我正在努力通过计算着色器存储uint数组的方式。我有以下着色器代码(一个简单的极简示例来重现该问题):
cbuffer TCstParams : register(b0)
{
int IntValue1;
uint UIntArray[10]; // <== PROBLEM IS HERE
int IntValue2;
}
RWTexture2D<float4> Output : register(u0);
[numthreads(1, 1, 1)]
void CSMain()
{
if (IntValue1 == 0)
Output[uint2(0, 0)] = float4(1, 1, 1, 1);
}
一旦编译,我将检查编译器的输出,以了解常量缓冲区项目的数量和大小。项目“ uint UIntArray [10];”令人惊讶地具有148个字节的大小。考虑到uint为4个字节,这很奇怪。因此,我希望数组大小为40个字节。
这是编译器输出:
Microsoft (R) Direct3D Shader Compiler 6.3.9600.16384
Copyright (C) 2013 Microsoft. All rights reserved.
//
// Generated by Microsoft (R) HLSL Shader Compiler 6.3.9600.16384
//
//
// Buffer Definitions:
//
// cbuffer TCstParams
// {
//
// int IntValue1; // Offset: 0 Size: 4
// uint UIntArray[10]; // Offset: 16 Size: 148 [unused] // <== PROBLEM IS HERE
// int IntValue2; // Offset: 164 Size: 4 [unused]
//
// }
//
//
// Resource Bindings:
//
// Name Type Format Dim Slot Elements
// ------------------------------ ---------- ------- ----------- ---- --------
// Output UAV float4 2d 0 1
// TCstParams cbuffer NA NA 0 1
//
//
//
// Input signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// no Input
//
// Output signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// no Output
cs_5_0
dcl_globalFlags refactoringAllowed | skipOptimization
dcl_constantbuffer cb0[1], immediateIndexed
dcl_uav_typed_texture2d (float,float,float,float) u0
dcl_temps 2
dcl_thread_group 1, 1, 1
#line 13 "E:\Development\Projects\Test Projects\DirectCompute\TestShader1.hlsl"
if_z cb0[0].x
mov r0.xyzw, l(0,0,0,0)
itof r1.xyzw, l(1, 1, 1, 1)
store_uav_typed u0.xyzw, r0.xyzw, r1.xyzw
endif
ret
// Approximately 6 instruction slots used
我检查了各种数组大小,结果很奇怪:当元素数量改变时,每个元素的大小都不一样!
我在做什么错或我想念什么?谢谢。
从Microsoft Docs报价:
默认情况下,数组不打包在HLSL中。为避免强制着色器承担ALU开销以进行偏移量计算,将数组中的每个元素存储在四分量向量中。
因此uint UIntArray[10];
实际上存储为uint4 UIntArray[10];
,除了最后三个填充uint不包括在大小计算中(即使它们仍计入偏移量计算中)。
如果需要更紧密的包装,则可以将数组声明为uint4 UInt4Array[4];
,然后将其强制转换为:static uint UInt1Array[16] = (uint[16])TCstParams.UInt4Array;
(不必检查该代码是否正确,但是应该类似)。强制转换本身不会造成任何开销-但是,UInt1Array
中的accassing元素将引入其他指令来计算实际偏移量。