转换变量以用作索引(金属着色语言)

Cast variable to use as index (Metal Shading language)

我正在尝试使用浮点变量作为索引来访问 MTLBuffer 的位置,但我必须将其转换为 unsigned int。嗯,这是我的第一个想法。

实际上这似乎行不通,但我不太明白为什么。

我基本上有这样的东西:

vertex VertexOut basic_vertex(const device float3 *vertex_array   [[ buffer(0) ]],
                              const device float3 *color_array    [[ buffer(1) ]], 
(...))
{

   // get the current vertex
   float3 position = vertex_array[vid];
   // get the color index
   uint color_index = as_type<uint>(position.z);
   // get the color
   float3 color = color_array[color_index];

   VertexOut vertexOut;
   vertexOut.position = proj_Matrix * mv_Matrix * float4(position.x, position.y, 0, 1);
   vertexOut.color = float4(color, 1);
   return vertexOut;
}

我试图通过使用 Z 坐标索引颜色缓冲区来减少发送到 GPU 的数据量,而不是对大量顶点重复相同的颜色。这样,我只需要传递 3 个加上颜色,而不是传递 6 个浮点数 (x,y,z,r,g,b)。

我得到的错误不是当我使用 color_index 变量来获取颜色时。问题是当我尝试访问颜色时,例如:

vertexOut.color = float4(color, 1);

如果我这样做,我会得到这个错误:

Execution of the command buffer was aborted due to an error during execution. Caused GPU Hang Error (IOAF code 3)

对于我想要完成的事情,是否有任何变通办法? 我在这里做错了什么?

提前致谢

as_type 在功能上等同于 C++ 的 reinterpret_cast:它从字面上将源值的位视为提供的类型,这在这种情况下是不正确的。您可能想要的是 floor 之类的东西,或者根本没有强制转换(即您可以使用 float 和(昂贵的)float-to-[=15 初始化索引=] 转换将隐式发生)。在不访问颜色时没有出现此错误的事实可能表明,当结果值未被使用时,数组访问正在消除死代码。