Search code examples
hlslcompute-shader

How to make sure AppendStructuredBuffer is going higher than 32?


So I'm quite new to using compute shaders and starting to learn a bit about it. Right now I'm trying to create a procedurally generated terrain. Since it's procedurally generated it's quite slow if I would only do it on cpu, that's why I started learning about compute shaders. Now, all I am trying to do is get the id of the thread and append it to a buffer and read it from a normal c# script. Just to see if it works. All the code I am running once. I'm working with the unity engine if that is necessary knowledge to know to solve this problem.

So my question is that how can I make sure that all the values get appended? Since it will only print till 32 while it should print 512 if I am correct.

Compute shader:

AppendStructuredBuffer<float3> result;

[numthreads(8, 8, 8)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    result.Append(float3(id.x, id.y, id.z));
}

C# script:

    int threads = 1;
    //doing another * 2 to make sure i have a large enough array.
    int testResults = threads * 8 * 8 * 8 * 2;
    ComputeBuffer results = new ComputeBuffer(testResults, sizeof(float) * 3);

    noiseShader.SetBuffer(0, "result", results);

    noiseShader.Dispatch(0, threads, threads, threads);

    Vector3[] test = new Vector3[testResults];
    results.GetData(test);
    results.Release();

    Debug.Log("Test results amount : " + test.Length);

    for(int i = 0; i < test.Length; i++)
    {
        Debug.Log("Test result at " + i + " : " + test[i] );
    }

Solution

  • So i have found the problem, and of course its a very silly/easy solution. When creating a new buffer, I didn't specify which kind of buffer, which was needed. So instead of doing this:

    ComputeBuffer results = new ComputeBuffer(testResults, sizeof(float) * 3);
    

    I needed to do this:

    ComputeBuffer results = new ComputeBuffer(testResults, sizeof(float) * 3, ComputeBufferType.Append);
    

    Also don't forget to do reset the counter value of the buffer, else it will append where it left off previous run!