是否可以使用HLSL计算着色器写入非4字节对齐的地址



我正在尝试将现有的OpenCL内核转换为HLSL计算着色器。

OpenCL内核对RGBA纹理中的每个像素进行采样,并将每个颜色通道写入一个三次压缩的阵列。

因此,基本上,我需要以如下模式写入一个紧密封装的uchar数组:

r r r ... r g g g ... g b b b ... b a a a ... a

其中每个字母代表源自像素通道的单个字节(红/绿/蓝/阿尔法)。

通过RWByteAddressBuffer存储方法的文档,它清楚地指出:

void Store(
in uint address,
in uint value
);

地址[in]

类型:uint

以字节为单位的输入地址,必须是4的倍数

为了将正确的模式写入缓冲区,我必须能够将单个字节写入未对齐的地址。在OpenCL/CUDA中,这是非常琐碎的。

  • 使用HLSL在技术上可以实现这一点吗
  • 这是已知的限制吗?可能的解决方案

据我所知,在这种情况下,不可能直接写入不对齐的地址。然而,你可以使用一个小技巧来实现你想要的。在下面,您可以看到整个计算着色器的代码,它完全可以执行您想要的操作。函数StoreValueAtByte尤其是您要查找的。

Texture2D<float4> Input;
RWByteAddressBuffer Output;
void StoreValueAtByte(in uint index_of_byte, in uint value) {
// Calculate the address of the 4-byte-slot in which index_of_byte resides
uint addr_align4 = floor(float(index_of_byte) / 4.0f) * 4;
// Calculate which byte within the 4-byte-slot it is
uint location = index_of_byte % 4;
// Shift bits to their proper location within its 4-byte-slot
value = value << ((3 - location) * 8);
// Write value to buffer
Output.InterlockedOr(addr_align4, value);
}
[numthreads(20, 20, 1)]
void CSMAIN(uint3 ID : SV_DispatchThreadID) {
// Get width and height of texture
uint tex_width, tex_height;
Input.GetDimensions(tex_width, tex_height);
// Make sure thread does not operate outside the texture
if(tex_width > ID.x && tex_height > ID.y) {
uint num_pixels = tex_width * tex_height;
// Calculate address of where to write color channel data of pixel
uint addr_red = 0 * num_pixels + ID.y * tex_width + ID.x;
uint addr_green = 1 * num_pixels + ID.y * tex_width + ID.x;
uint addr_blue = 2 * num_pixels + ID.y * tex_width + ID.x;
uint addr_alpha = 3 * num_pixels + ID.y * tex_width + ID.x;
// Get color of pixel and convert from [0,1] to [0,255]
float4 color = Input[ID.xy];
uint4 color_final = uint4(round(color.x * 255), round(color.y * 255), round(color.z * 255), round(color.w * 255));      
// Store color channel values in output buffer
StoreValueAtByte(addr_red, color_final.x);
StoreValueAtByte(addr_green, color_final.y);
StoreValueAtByte(addr_blue, color_final.z);
StoreValueAtByte(addr_alpha, color_final.w);
}
}

我希望代码是不言自明的,因为它很难解释,但无论如何我都会尝试
函数StoreValueAtByte所做的第一件事是计算包含要写入的字节的4字节插槽的地址。然后计算4字节插槽内字节的位置(是插槽中的第一个、第二个、第三个还是第四个字节)。由于要写入的字节已经在一个4字节的变量(即value)中,并且占据了最右边的字节,因此您只需将字节移动到4字节变量中的适当位置即可。之后,您只需要将变量value写入4字节对齐地址的缓冲区。这是使用bitwise OR完成的,因为多个线程向同一地址写入会相互干扰,从而导致一次又一次写入的危险。当然,只有在发出调度调用之前用零初始化整个输出缓冲区时,这才有效。

最新更新