I have a question about constant buffers in directX 11. They really confuse me and after searching on google most sites simply supply sample code without explaining how it works. I am probably overlooking something but, as of now, they appear to me to work by sheer magic. Say I have two constant buffers in an hlsl file:
struct Light
{
float3 dir;
float4 ambient;
float4 diffuse;
};
cbuffer cbPerFram
{
Light light;
};
cbuffer cbPerObject
{
float4x4 WVP;
float4x4 World;
};
And I create an equivalent buffer in my C++ program like so:
//Create the buffer to send to the cbuffer in effect file
D3D11_BUFFER_DESC cbbd;
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
cbbd.Usage = D3D11_USAGE_DEFAULT;
//cbPerObject is a struct with same layout as cbPerObject in HLSL file
cbbd.ByteWidth = sizeof(cbPerObject);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;
hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerObjectBuffer);
//Create the buffer to send to the cbuffer per frame in effect file
ZeroMemory(&cbbd, sizeof(D3D11_BUFFER_DESC));
cbbd.Usage = D3D11_USAGE_DEFAULT;
//cbPerFrame is struct with same layout as in cbPerFrame in effect file
cbbd.ByteWidth = sizeof(cbPerFrame);
cbbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbbd.CPUAccessFlags = 0;
cbbd.MiscFlags = 0;
And then I update one like this:
d3d11DevCon->UpdateSubresource( cbPerObjectBuffer, 0, NULL, &cbPerObj, 0, 0 );
d3d11DevCon->VSSetConstantBuffers( 0, 1, &cbPerObjectBuffer );
hr = d3d11Device->CreateBuffer(&cbbd, NULL, &cbPerFrameBuffer);
How does directX know which constant buffers in my shader are going to be used for VS and which for PS and which buffers in my codes correspond to which buffers in my hlsl? For example I call VSSetConstantBuffers above and pass the arguments and it automatically knows to throw that stuff in the per object buffer as opposed to trying to put it in the perFrame buffer. As far as I can tell when creating cbPerObjectBuffer, I never explicitly bound it to the cbPerObject buffer in my hlsl. Is slot number dependent on the order the buffers appear in hlsl? The only way I can figure is that the data structures simply define an interface to the buffer memory on the card and it is up to the programmer to use the correct one. For example, I COULD attempt to use cbPerFrame in my vertex shader and indeed the same data can be accessed that way but in order to get correct results you would have to access it using offsets into the light object. Does what I am asking make any sense? lol