Search code examples
graphics3ddirectxdirectx-12

Does Structured Buffers has special alignment constraints?


I am implementing instancing in my renderer. To do so i need to use a StructuredBuffer of mesh data. Here what I first tried:

struct MeshData
{
    float4x4 transform;
    uint meshId;
};  

StructuredBuffer<MeshData> meshDatas : register(t0);

And CPP side:

__declspec(align(16)) struct MeshData
{
    DirectX::XMFLOAT4X4 transform;
    UINT meshId;
};

Unfortunatly this doesnt work. I get gliches in my rendering:
enter image description here

Instead of:
enter image description here

Since now I just needed to align CPP structures to 16 bytes to be able to properly send them to the GPU. But to solve this one I had to add padding on both the CPP code and HLSL. This one worked:

HLSL:

struct MeshData
{
    float4x4 transform;
    uint groupId;
    float pad1;
    float pad2;
    float pad3;
}; 

StructuredBuffer<MeshData> meshDatas : register(t0);  

CPP

struct MeshData
{
    DirectX::XMFLOAT4X4 transform;
    UINT groupId;
    FLOAT pad1;
    FLOAT pad2;
    FLOAT pad3;
};

Does Structured Buffers has special alignment constraints?


Solution

  • Unlike constant buffers, structured buffers in D3D12 have no special alignment constraints.

    On earlier hardware, however, some vendors did promote 16-byte alignment for performance, but I don't think this has a noticeable impact on modern generations of GPU.

    Therefore it's not necessary to byte align C++ struct declarations with __declspec(align(x)).

    If you do include a declspec directive, then this may only force you to add unnecessary padding in both the C++ and HLSL struct declarations to keep them aligned.