Cast变量用作索引(Metal Shading语言)

时间:2017-04-12 17:56:32

标签: ios metal

我试图使用浮点变量作为索引来访问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)

我试图完成的工作是否有任何解决方法? 我在这里做错了什么?

提前谢谢

1 个答案:

答案 0 :(得分:1)

as_type在功能上等同于C ++的reinterpret_cast:它实际上将源值的位视为提供的类型,在此上下文中是不正确的。您可能想要的是floor,或者根本没有演员(即您可以使用float初始化索引,并且(昂贵的)float - 来 - {{1转换将隐式发生)。在不访问颜色时您没有收到此错误的事实可能表示当结果值未使用时,阵列访问会消除死代码。

相关问题