0

I'm using a compute shader in unity to generate density values for the marching cube algorithm and for some it skips the calculation for every 17th value in the buffer and leaves it as 0.

The code to set up the compute buffer is:

public ComputeBuffer Generate(float radius,int width,float resolution,float[] planetCentre,float[] pos)
{
    int threadGroups = (int)Mathf.Ceil(((width) + 1) / 8);
    densityDebug = new float[((width) + 1) * ((width) + 1) * ((width) + 1)];
    ComputeBuffer densityBuffer = new ComputeBuffer(((width) + 1) * ((width) + 1) * ((width) + 1), sizeof(float));
    int kernelHandle = shader.FindKernel("CSMain");
    shader.SetBuffer(kernelHandle, "densityBuffer", densityBuffer);
    shader.SetFloat("resolution", resolution);
    shader.SetInt("densityWidth", (width) + 1);
    shader.SetFloat("radius", radius);
    shader.SetFloats("planetCentre", planetCentre);
    shader.SetFloats("pos", pos);
    shader.Dispatch(kernelHandle, threadGroups, threadGroups, threadGroups);

    densityBuffer.GetData(densityDebug);
    return densityBuffer;
}

and the shader code is:

RWStructuredBuffer<float> densityBuffer;
int densityWidth;
float radius;
float3 planetCentre;
float3 pos;
float resolution;

int flattenedIndex(int x, int y, int z)
{
    return (x * (densityWidth) * (densityWidth)) + (y * (densityWidth)) + z;
}

[numthreads(8,8,8)]
void CSMain (int3 id : SV_DispatchThreadID)
{
    if (id.x >= densityWidth || id.y >= densityWidth || id.z >= densityWidth)
    {
        return;
    }

    float dSphere = pow(pos.x + (id.x * resolution) - planetCentre.x, 2) + pow(pos.y + (id.y * resolution) - planetCentre.y, 2) + pow(pos.z + (id.z * resolution) - planetCentre.z, 2) - pow(radius, 2);

    densityBuffer[flattenedIndex(id.x, id.y, id.z)] = dSphere;
}

It happens no matter the values but for instance, the width is normally set to 16. Therefore, 3 thread groups are used. I am quite new to compute shaders so it could be something very simple.

Image

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • 1
    I'm pretty sure this `[![enter image description here][1]][1]` does not make part of your shader right? ;) – derHugo Apr 02 '20 at 05:24
  • 1
    I think it would help to know all your input parameters and the objects positions ... – derHugo Apr 02 '20 at 05:43
  • The objects' positions are (0,0,0), radius = 20, planetcentre = (10,10,10), resolution = 1. I think it might be something to do with the indexing as it works fine on the CPU just not in the compute shader. – user1971189 Apr 02 '20 at 14:45

0 Answers0