Search code examples
directxhlsl

Using cbuffer without specifying a register


I generally use cbuffer with specifying 'b#' register in hlsl, but i recently found out it is fine that i don't have to specify it for some of cases. so it brings me a question. What exactly is the difference between

cbuffer
{
   float4x4 someMatrix = (float4x4)0;
}

And

cbuffer : register(b0)
{
   float4x4 someMatrix = (float4x4)0;
}

Is it automatically bound on b0 register when compiled?


Solution

  • The compiler assigns the unspecified buffers to a register in a 'first-fits' policy. You have to use shader reflection at runtime to determine exactly where it's bound. See D3DReflect and ID3D11ShaderReflection / ID3D12ShaderReflection.

    You would probably use cbuffer MyCB and then use the GetConstantBufferByName method to find it rather than the unnamed cbuffer for reflection.

    This was a feature of HLSL used for the legacy Effects system.

    For modern usage, you generally explicitly assign the binding so you can avoid switching the binding every time you change shaders.