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 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 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 on other sites
MJP    19755
No those are just names I picked, I just meant that you should split up your constants into multiple buffers rather than grouping them all together into one giant constant buffer.

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 on other sites
MJP    19755
Are you talking about the register (slot) that a constant buffer is bound to using *SetConstantBuffers, or the offset into a constant buffer into which an actual variable is placed?

Share on other sites
elurahu    258
Talking about the slots you bind them to.

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 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 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 on other sites
elurahu    258

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 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 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 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 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 on other sites
Tordin    625
Well thanks MJP! this solves alot of questions and troubel for me!

Create an account

Register a new account

• Similar Content

• 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?

• 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.
• 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.

• 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!

• 11
• 14
• 26
• 16
• 19