I am passing in a constant buffer with the following layout:
struct
{
float spread;
D2D1_POINT_2F dimension;
D2D1_POINT_2F dimension2;
} m_constants;
for debugging sake, dimension and dimension2 have the same values.
In the shader i have:
cbuffer constants
{
float spread;
float2 dimension;
float2 dimension2;
};
float4 main(
float4 pos : SV_POSITION,
float4 posScene : SCENE_POSITION,
float4 uv0 : TEXCOORD0
) : SV_Target
{
float width = dimension.x;
float height = dimension.y;
float2 uv2 = float2(posScene.x / width, posScene.y / height);
color.rgb = float3(uv2.xy, 0);
return color;
}
this, in theory, should output a gradient with green on the bottom left and red at the top right. And it does.
But if, in the shader i have the width and height to use dimension2 instead. i get a horizontal gradient from green on the left to yellow on the right.
Why is that? both dimensions have the same value when i passed the m_constants to the shader
Constant buffers data is aligned by 16 bytes by default, so this means:
will be
here is a link that describes this.
So a better way to arrange your structure would be:
and modify the hlsl counterpart accordingly:
Another way, without modifying initial layout, in c++ side, either declare your structure like:
That will force structure to be 16 bytes aligned.
You can also use /Zp16 compiler flag , but that will then apply to every structure in your program (which is not always desirable). In visual studio go to project properties -> c/c++ -> Code Generation, then you have option “Struct Member Alignment”, where you can set it from.
You can also use packoffset on hlsl side, but then it means that the c++ layout needs to match the packed hlsl one (which means you keep same order in hlsl constant buffer, but still have to modify the c++ version).