Home > OS >  HLSL Array Indexing Returning Unexpected Values
HLSL Array Indexing Returning Unexpected Values

Time:02-26

I am executing some HLSL code on the GPU in Unity, but I am having issues with getting values out of an array. Here is my simplified code example.

C#

ComputeBuffer meshVerticesBuffer = new ComputeBuffer(
  15 * 1,
  sizeof(float) * 3
);
marchingCubesShader.SetBuffer(0, "MeshVertices", meshVerticesBuffer);
marchingCubesShader.Dispatch(0, 1, 1, 1);

Vector3[] meshVertices = new Vector3[15 * 1];
meshVerticesBuffer.GetData(meshVertices);
meshVerticesBuffer.Release();

HLSL

#pragma kernel ApplyMarchingCubes

int EDGE_TABLE[][15] = {
    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
    ...255 more irrelevant entries
};

RWStructuredBuffer<float3> MeshVertices;

[numthreads(4, 4, 4)]
void ApplyMarchingCubes(uint3 id : SV_DispatchThreadID)
{
    MeshVertices[0] = float3(0, 0, EDGE_TABLE[0][0]);
}

I am watching meshVertices on the C# side through the debugger, and the first item is always a Vector3(0, 0, 0). I am expecting a result of Vector3(0, 0, -1). What am I doing wrong?

CodePudding user response:

I figured out why the array was not putting out the right values. In HLSL, when declaring and initializing an array in the same line, you must include the static keyword.

My HLSL code should have been:

#pragma kernel ApplyMarchingCubes

static int EDGE_TABLE[][15] = {
    {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
    ...255 more irrelevant entries
};

RWStructuredBuffer<float3> MeshVertices;

[numthreads(4, 4, 4)]
void ApplyMarchingCubes(uint3 id : SV_DispatchThreadID)
{
    MeshVertices[0] = float3(0, 0, EDGE_TABLE[0][0]);
}

(Notice static on the third line, it was not there before).

  • Related