Sign in to follow this  
Tordin

DX11 Directx11 - Shader Constantbuffers vs the world.

Recommended Posts

Tordin    625
Hey!

i working on some dx11 stuff and are at the point where i need to be able to set shader variables easy and fast, since it gonna happen in runtime i am looking for the fastest way to do this.

At the moment i am struggeling with Constant buffers and i havent realy found another way to set shader input variabels, so my big question is :

How do i in the fastest CPU SPEED way set shadervariables? i need them to change on the fly for each frame.

Is CBuffers the way to do it?
Is there any other way to do it?
Is that otherway faster than remapping the cbuffer?

Would be glad for articels, information, tutorials and more!

cheers !

Share this post


Link to post
Share on other sites
MJP    19755
If you want performance, than constant buffers are absolutely the way to go. No question. You obviously want to limit the amount of data that you map and update, and the way to do that is to group your constants based on how often they change. So for example if your view * projection matrix never changes the entire frame, put in a PerFrames cb and only set them once a frame. If you set a world matrix for each draw call, put that in a PerDraws cb.

Share this post


Link to post
Share on other sites
Tordin    625
is PreFrame cb a different constant buffer than a regular Cbuffer?
is PreDraw cb a different constant buffer than a regular Cbuffer?

How do they work? (if they exsist?)

or do you just mean to have different cb in the shader with less data than a full global one?

Share this post


Link to post
Share on other sites
elurahu    258
That does actually touch on something I've been wanting to ask about MJP. Say you want to set a VP matrix on a per frame basis. How would you go about that in detail.

In my framework I'm working without the DX effects as I wanted to learn the nitty gritty details. And when I reflect my shaders to find the bind information a given CB containing the VP matrix (for the sake of this example let it contain only that) it might give me different bind points for different shaders.

How exactly would I avoid having to bind the information for each shader. Even when specifying the CB register that doesn't change the bind points, and I just haven't been able to find any information regarding them.

Share this post


Link to post
Share on other sites
MJP    19755
If you manually bind a constant buffer to a register using "register : (cb0)", then you can use that index to bind the D3D11 constant buffer at runtime. If you want you can keep your commonly-used constant buffers in a header file and #include that in all of your shaders, which makes it easier to manage.

Share this post


Link to post
Share on other sites
Jason Z    6434
Another way to improve performance for CPU related configuration of the pipeline is to use the multithreading capabilities of D3D11. If you are using 2 or 4 cores to submit the requested changes into command lists, and then submit the command lists to the immediate context then you will almost surely be faster than doing it in a single thread on a single core.

Share this post


Link to post
Share on other sites
Tordin    625
Ah, i see.
Than this brings me to another question.

Say i have 3 sets of CBs,
When i set thees and do the call "SetVSConstantBuffer" for the second one for example, should i set the "numBuff" to 1? or 2?

or is this where the register thing come into play?

Can some one give me a example & explenation of the cb & registery system?

i have understood it like this :

ConstantBuffer WorldViewProjection {
matrix World : World <--- in my c++ buffer i have to have a variable named that name?
};

Or is this wrong?

Cheers!

Share this post


Link to post
Share on other sites
elurahu    258
Hey Tordin - Sorry for hijacking your thread like that.

As far as I can tell what you're doing is wrong. A constant buffer is a buffer like any other. It's a structure containing some data you would like your shader instance to use. In DX9-era shaders you would have a shader just declare the variables it would need - But in DX10/11 they switched to batching variables to the GPU to avoid the driver overhead caused by repeated updating of variables. Enter the constant buffer. It's a way to group up variables (be it matricies, floats, arrays whatever) based on usage.

An excample of a constant buffer declaration in a shader could be:

cbuffer CBObject : register(cb0) <-- The register here would be the slot you need to set.
{
float4x4 m_kWorldView;
float4x4 m_kWorldViewIT;
float4x4 m_kWorldViewProjection;
}

Hope this helped.

Share this post


Link to post
Share on other sites
Tordin    625
So if i have three buffers

i would define them like this : ?

cbuffer CBObject : register(cb0)
{
float4x4 m_kWorldView;
float4x4 m_kWorldViewIT;
float4x4 m_kWorldViewProjection;
}

cbuffer CBObject : register(cb1)
{
float4x4 m_kWorldView;
float4x4 m_kWorldViewIT;
float4x4 m_kWorldViewProjection;
}

cbuffer CBObject : register(cb2)
{
float4x4 m_kWorldView;
float4x4 m_kWorldViewIT;
float4x4 m_kWorldViewProjection;
}


if i call the SetVsConstantbuffer(1,....);

i would assign stuff to the second buffer? not the first or the third one?
just because i sat the registery(cb1) there? is this correct?

Share this post


Link to post
Share on other sites
MJP    19755
The VSSetConstantBuffers works like this: you specify which slot you want to start at, and how many constant buffers you want to set contiguously starting from the slot you specified. So if you pass 1 as StartSlot and then pass an array of 3 constant buffers, you will set those three constant buffers to slots 1, 2, and 3 respectively. If you want to just set one constant buffer, then you pass the slot you want to set it to and pass 1 for NumBuffers.

That said, that example you just outlined with three identical constant buffers declared will not compile. This is because you can't have multiple buffers with the same name declared in the same file, and you can't have the same parameter name declared in multiple constant buffers.

Share this post


Link to post
Share on other sites
Tordin    625
Yes of corse that wont compile, that wasent the point eiter, the point was that i had understood it and hadent the time to write a correct shader!

Anyhow, to bring the subject up again, I have this shader :

cbuffer perFrame : register(cb0)
{
float3 floatP1;
float3 floatP2;
float3 floatP3;
float3 floatP4;
};

struct VSOUT
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};


Texture2D diffuse;
SamplerState samLin;


float4 mainPS(VSOUT inPS) : SV_Target
{
float4 color = diffuse.Sample(samLin,inPS.uv);
return color*floatP2.x;
}



And i try to set a row of 4 3d vectors, the first vector floatP1 gets it information, but the rest dosent!

and this is how i set the buffer! if you see ways to improve this, please tell me!


bool D3D11Device::SetPixelShaderVariableConstantBuffer(MORN_VARIABLE_BUFFER_PERFRAME data)
{
HRESULT hr;
D3D11_BUFFER_DESC cbDesc;
D3D11_SUBRESOURCE_DATA cbSubData;
D3D11_MAPPED_SUBRESOURCE cbMapped;
MORN_VARIABLE_BUFFER_PERFRAME* Buffer;

if(m_pPixelShaderCBuffer == NULL)
{
Buffer = &data;

ZeroMemory(&cbDesc,sizeof(cbDesc));
ZeroMemory(&cbSubData,sizeof(cbSubData));

cbDesc.ByteWidth = sizeof(MORN_VARIABLE_BUFFER_PERFRAME);
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;

cbSubData.pSysMem = Buffer;
cbSubData.SysMemPitch = 0;
cbSubData.SysMemSlicePitch = 0;

int size = sizeof(MORN_VARIABLE_BUFFER_PERFRAME);

hr = m_pD3DDevice->CreateBuffer( &cbDesc, &cbSubData,
&m_pPixelShaderCBuffer );
if(ChekReturnError(hr))
return false;

m_pD3DContex->PSSetConstantBuffers( 0, 1, &m_pPixelShaderCBuffer );
return true;
}
else if(m_pPixelShaderCBuffer != NULL)
{
hr = m_pD3DContex->Map(m_pPixelShaderCBuffer,0,D3D11_MAP_WRITE_DISCARD,0,&cbMapped);
if(ChekReturnError(hr))
return false;

Buffer = (MORN_VARIABLE_BUFFER_PERFRAME*)cbMapped.pData;
for(int i = 0; i<4; ++i)
Buffer->fff[i] = data.fff[i];

m_pD3DContex->Unmap(m_pPixelShaderCBuffer,0);
m_pD3DContex->PSSetConstantBuffers( 0, 1, &m_pPixelShaderCBuffer );

return true;
}
}



So when i try to get information from the second 3d vector in the array, it´s pichblack!

Share this post


Link to post
Share on other sites
MJP    19755
In constant buffers, float3's will be aligned to 16-byte boundaries due to the fact that registers are 16 bytes in size. So on the CPU side you need to either mirror that alignment using pragmas, or put in appropriate padding. See this for a full set of packing rules.

[Edited by - MJP on November 25, 2010 1:34:25 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By KaiserJohan
      Just a really quick question - is there any overhead to using DrawIndexedInstanced even for geometry you just render once vs using DrawIndexed? Or is the details obfuscated by the graphics driver?
      I would assume no but you never know  
    • By isu diss
       I'm trying to code Rayleigh part of Nishita's model (Display Method of the Sky Color Taking into Account Multiple Scattering). I get black screen no colors. Can anyone find the issue for me?
       
      #define InnerRadius 6320000 #define OutterRadius 6420000 #define PI 3.141592653 #define Isteps 20 #define Ksteps 10 static float3 RayleighCoeffs = float3(6.55e-6, 1.73e-5, 2.30e-5); RWTexture2D<float4> SkyColors : register (u0); cbuffer CSCONSTANTBUF : register( b0 ) { float fHeight; float3 vSunDir; } float Density(float Height) { return exp(-Height/8340); } float RaySphereIntersection(float3 RayOrigin, float3 RayDirection, float3 SphereOrigin, float Radius) { float t1, t0; float3 L = SphereOrigin - RayOrigin; float tCA = dot(L, RayDirection); if (tCA < 0) return -1; float lenL = length(L); float D2 = (lenL*lenL) - (tCA*tCA); float Radius2 = (Radius*Radius); if (D2<=Radius2) { float tHC = sqrt(Radius2 - D2); t0 = tCA-tHC; t1 = tCA+tHC; } else return -1; return t1; } float RayleighPhaseFunction(float cosTheta) { return ((3/(16*PI))*(1+cosTheta*cosTheta)); } float OpticalDepth(float3 StartPosition, float3 EndPosition) { float3 Direction = normalize(EndPosition - StartPosition); float RayLength = RaySphereIntersection(StartPosition, Direction, float3(0, 0, 0), OutterRadius); float SampleLength = RayLength / Isteps; float3 tmpPos = StartPosition + 0.5 * SampleLength * Direction; float tmp; for (int i=0; i<Isteps; i++) { tmp += Density(length(tmpPos)-InnerRadius); tmpPos += SampleLength * Direction; } return tmp*SampleLength; } static float fExposure = -2; float3 HDR( float3 LDR) { return 1.0f - exp( fExposure * LDR ); } [numthreads(32, 32, 1)] //disptach 8, 8, 1 it's 256 by 256 image void ComputeSky(uint3 DTID : SV_DispatchThreadID) { float X = ((2 * DTID.x) / 255) - 1; float Y = 1 - ((2 * DTID.y) / 255); float r = sqrt(((X*X)+(Y*Y))); float Theta = r * (PI); float Phi = atan2(Y, X); static float3 Eye = float3(0, 10, 0); float ViewOD = 0, SunOD = 0, tmpDensity = 0; float3 Attenuation = 0, tmp = 0, Irgb = 0; //if (r<=1) { float3 ViewDir = normalize(float3(sin(Theta)*cos(Phi), cos(Theta),sin(Theta)*sin(Phi) )); float ViewRayLength = RaySphereIntersection(Eye, ViewDir, float3(0, 0, 0), OutterRadius); float SampleLength = ViewRayLength / Ksteps; //vSunDir = normalize(vSunDir); float cosTheta = dot(normalize(vSunDir), ViewDir); float3 tmpPos = Eye + 0.5 * SampleLength * ViewDir; for(int k=0; k<Ksteps; k++) { float SunRayLength = RaySphereIntersection(tmpPos, vSunDir, float3(0, 0, 0), OutterRadius); float3 TopAtmosphere = tmpPos + SunRayLength*vSunDir; ViewOD = OpticalDepth(Eye, tmpPos); SunOD = OpticalDepth(tmpPos, TopAtmosphere); tmpDensity = Density(length(tmpPos)-InnerRadius); Attenuation = exp(-RayleighCoeffs*(ViewOD+SunOD)); tmp += tmpDensity*Attenuation; tmpPos += SampleLength * ViewDir; } Irgb = RayleighCoeffs*RayleighPhaseFunction(cosTheta)*tmp*SampleLength; SkyColors[DTID.xy] = float4(Irgb, 1); } }  
    • By Endurion
      I have a gaming framework with an renderer interface. Those support DX8, DX9 and latest, DX11. Both DX8 and DX9 use fixed function pipeline, while DX11 obviously uses shaders. I've got most of the parts working fine, as in I can switch renderers and notice almost no difference. The most advanced features are 2 directional lights with a single texture  
      My last problem is lighting; albeit there's documentation on the D3D lighting model I still can't get the behaviour right. My mistake shows most prominently in the dark side opposite the lights. I'm pretty sure the ambient calculation is off, but that one's supposed to be the most simple one and should be hard to get wrong.
      Interestingly I've been searching high and low, and have yet to find a resource that shows how to build a HLSL shader where diffuse, ambient and specular are used together with material properties. I've got various shaders for all the variations I'm supporting. I stepped through the shader with the graphics debugger, but the calculation seems to do what I want. I'm just not sure the formula is correct.
      This one should suffice though, it's doing two directional lights, texture modulated with vertex color and a normal. Maybe someone can spot one (or more mistakes). And yes, this is in the vertex shader and I'm aware lighting will be as "bad" as in fixed function; that's my goal currently.
      // A constant buffer that stores the three basic column-major matrices for composing geometry. cbuffer ModelViewProjectionConstantBuffer : register(b0) { matrix model; matrix view; matrix projection; matrix ortho2d; }; struct DirectionLight { float3 Direction; float PaddingL1; float4 Ambient; float4 Diffuse; float4 Specular; }; cbuffer LightsConstantBuffer : register( b1 ) { float4 Ambient; float3 EyePos; float PaddingLC1; DirectionLight Light[8]; }; struct Material { float4 MaterialEmissive; float4 MaterialAmbient; float4 MaterialDiffuse; float4 MaterialSpecular; float MaterialSpecularPower; float3 MaterialPadding; }; cbuffer MaterialConstantBuffer : register( b2 ) { Material _Material; }; // Per-vertex data used as input to the vertex shader. struct VertexShaderInput { float3 pos : POSITION; float3 normal : NORMAL; float4 color : COLOR0; float2 tex : TEXCOORD0; }; // Per-pixel color data passed through the pixel shader. struct PixelShaderInput { float4 pos : SV_POSITION; float2 tex : TEXCOORD0; float4 color : COLOR0; }; // Simple shader to do vertex processing on the GPU. PixelShaderInput main(VertexShaderInput input) { PixelShaderInput output; float4 pos = float4( input.pos, 1.0f ); // Transform the vertex position into projected space. pos = mul(pos, model); pos = mul(pos, view); pos = mul(pos, projection); output.pos = pos; // pass texture coords output.tex = input.tex; // Calculate the normal vector against the world matrix only. //set required lighting vectors for interpolation float3 normal = mul( input.normal, ( float3x3 )model ); normal = normalize( normal ); float4 ambientEffect = Ambient; float4 diffuseEffect = float4( 0, 0, 0, 0 ); float4 specularEffect = float4( 0, 0, 0, 0 ); for ( int i = 0; i < 2; ++i ) { // Invert the light direction for calculations. float3 lightDir = -Light[i].Direction; float lightFactor = max( dot( lightDir, input.normal ), 0 ); ambientEffect += Light[i].Ambient * _Material.MaterialAmbient; diffuseEffect += saturate( Light[i].Diffuse * dot( normal, lightDir ) );// * _Material.MaterialDiffuse; //specularEffect += Light[i].Specular * dot( normal, halfangletolight ) * _Material.MaterialSpecularPower; } specularEffect *= _Material.MaterialSpecular; //ambientEffect.w = 1.0; ambientEffect = normalize( ambientEffect ); /* Ambient effect: (L1.ambient + L2.ambient) * object ambient color Diffuse effect: (L1.diffuse * Dot(VertexNormal, Light1.Direction) + L2.diffuse * Dot(VertexNormal, Light2.Direction)) * object diffuse color Specular effect: (L1.specular * Dot(VertexNormal, HalfAngleToLight1) * Object specular reflection power + L2.specular * Dot(VertexNormal, HalfAngleToLight2) * Object specular reflection power ) * object specular color Resulting color = Ambient effect + diffuse effect + specular effect*/ float4 totalFactor = ambientEffect + diffuseEffect + specularEffect; totalFactor.w = 1.0; output.color = input.color * totalFactor; return output; }   Edit: This message editor is driving me nuts (Arrrr!) - I don't write code in Word.
    • By Mercesa
      Hey folks. So I'm having this problem in which if my camera is close to a surface, the SSAO pass suddenly spikes up to around taking 16 milliseconds.
      When still looking towards the same surface, but less close. The framerate resolves itself and becomes regular again.
      This happens with ANY surface of my model, I am a bit clueless in regards to what could cause this. Any ideas?
      In attached image: y axis is time in ms, x axis is current frame. The dips in SSAO milliseconds are when I moved away from the surface, the peaks happen when I am very close to the surface.

       
      Edit: So I've done some more in-depth profiling with Nvidia nsight. So these are the facts from my results
      Count of command buffers goes from 4 (far away from surface) to ~20(close to surface).
      The command buffer duration in % goes from around ~30% to ~99%
      Sometimes the CPU duration takes up to 0.03 to 0.016 milliseconds per frame while comparatively usually it takes around 0.002 milliseconds.
      I am using a vertex shader which generates my full-screen quad and afterwards I do my SSAO calculations in my pixel shader, could this be a GPU driver bug? I'm a bit lost myself. It seems there could be a CPU/GPU resource stall. But why would the amount of command buffers be variable depending on distance from a surface?
       
       
      Edit n2: Any resolution above 720p starts to have this issue, and I am fairly certain my SSAO is not that performance heavy it would crap itself at a bit higher resolutions.
       
    • By turanszkij
      In DirectX 11 we have a 24 bit integer depth + 8bit stencil format for depth-stencil resources ( DXGI_FORMAT_D24_UNORM_S8_UINT ). However, in an AMD GPU documentation for consoles I have seen they mentioned, that internally this format is implemented as a 64 bit resource with 32 bits for depth (but just truncated for 24 bits) and 32 bits for stencil (truncated to 8 bits). AMD recommends using a 32 bit floating point depth buffer instead with 8 bit stencil which is this format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT.
      Does anyone know why this is? What is the usual way of doing this, just follow the recommendation and use a 64 bit depthstencil? Are there performance considerations or is it just recommended to not waste memory? What about Nvidia and Intel, is using a 24 bit depthbuffer relevant on their hardware?
      Cheers!
       
  • Popular Now