常量缓冲区和只读结构化缓冲区有什么区别?

What is the difference between a constant buffer and a read only structured buffer?

我想知道哪种资源类型最适合用于保存尽可能多的静态数据元素,并且在绘制调用期间不会更改。我可以说出常量缓冲区和只读结构化缓冲区之间的唯一区别是常量缓冲区数据必须在其 ID3D12Resource 对象内部对齐 256 字节。

lights.hlsl

#define as_many_as_possible 1000

struct light
{
    float3 position;
    float falloff_start;
    float3 direction;
    float falloff_end;
    float3 color;
    float3 strenght;
};

struct light_data
{
    light lights [as_many_as_possible];
};
ConstantBuffer<light_data> cb_lights : register(b0);

// Versus

StructuredBuffer<light> sb_lights : register(s0);

如果我的目标是保存尽可能多的灯的数据,哪个更好?

常量缓冲区和结构化缓冲区之间存在更多差异。

在常量缓冲区中,只能同时显示 64k 的数据,因此您不能拥有 1mb 的数据并在着色器中同时显示它,而在结构化缓冲区上是可能的。

常量缓冲区比结构化缓冲区具有更复杂的对齐规则,您的示例实际上非常适合它:

如果是结构化缓冲区,您的光结构的大小为:

struct light
{
    float3 position; /12
    float falloff_start; /4 -> 16
    float3 direction; /12 -> 28
    float falloff_end; /4 -> 32
    float3 color; /12 -> 44
    float3 strenght; /12 -> 56
};

因此您的数据将被解释为 56 字节结构数组。

但是,常量缓冲区结构对齐需要 16 个字节,因此您的结构将被解释为:

struct light
{
    float3 position; /12
    float falloff_start; /4 -> 16
    float3 direction; /12 -> 28 (not 16 byte boundary crossing)
    float falloff_end; /4 -> 32
    float3 color; /12 -> 44 (no 16 byte boundary crossing)
    float pad; /4 -> 48 (float3 would cross 16 boundary)
    float3 strenght; /12 -> 60
    float pad2; /4 ->64 (next float3 would cross 16 boundary, which is the next position in the array, there is no end padding for the last element of the array however)

所以你的灯将是 64 字节(需要匹配你的 cpu 结构,否则你的数据将不匹配)。

在某些硬件上,由于这些限制,在常量缓冲区与结构化缓冲区的情况下,读取访问可以得到更优化。这取决于许多因素(例如,在着色器中读取频率),因此您需要分析以查看您的用例有何不同。

还有一些供应商(如 NVidia)建议出于性能原因(在结构化缓冲区的情况下)将结构与 16 字节边界对齐,因此在您的情况下,结构将是:

struct light
{
    float3 position; /12
    float falloff_start; /4 -> 16
    float3 direction; /12 -> 28
    float falloff_end; /4 -> 32
    float3 color; /12 -> 44
    float3 strenght; /12 -> 56
    float2 _pad;
};