Hi,
I’ve written a fairly simple compute shader that iterates through a some mesh data to build a distance field around it. It works pretty well, but I’m having an issue with my vertex compute buffer, that I don’t quite understand.
To my understanding when you’re creating a ComputeBuffer you have to tell it how many elements it’ll contain; in my case, the number of vertices in my mesh. And then the size of each element; in my case I’m only using the position data, which consists of Vector3, so sizeof(float) * 3.
So I created and filled my buffers like this:
indicesBuffer = new ComputeBuffer(mesh.triangles.Length, sizeof(int));
indicesBuffer.SetData(mesh.triangles);
vertexBuffer = new ComputeBuffer(mesh.vertexCount, sizeof(float) * 3);
vertexBuffer.SetData(mesh.vertices);
shader.SetBuffer(kernel, "_IndicesBuffer", indicesBuffer);
shader.SetBuffer(kernel, "_VertexBuffer", vertexBuffer);
And then I’m reconstructing the triangles from the buffers like this in the shader:
RWStructuredBuffer<float3> _VertexBuffer;
RWStructuredBuffer<int> _IndicesBuffer;
void MyFunction()
{
uint triangles;
uint stride;
_VertexBuffer.GetDimensions(triangles, stride);
for (uint i = 0; i < triangles; i += 3)
{
float3 a = _VertexBuffer[_IndicesBuffer[i + 0]];
float3 b = _VertexBuffer[_IndicesBuffer[i + 1]];
float3 c = _VertexBuffer[_IndicesBuffer[i + 2]];
// Stuff that's not relevant to my question.
}
}
The indices buffer works exactly like I’m expecting it to, but the vertex buffer seems to be missing data. Like some of the vertices didn’t get copied to the buffer.
By monkeying around with it a bit, I found that by multiplying the size of the vertex buffer by 5 got it to work as I wanted. But I don’t understand how or why this solves anything. As far as I know, all this does is waste a bunch of extra memory for no real reason, which I could see becoming problematic when working with more complicated geometry.
I could understand it if the count was actually a byte count; i.e vertices.vertexCount * sizeof(float) * 3; but this doesn’t seem to be the case when looking at my indices buffer. In that case the indices buffer count should be mesh.triangles.Length * sizeof(int), but it’s not.
vertexBuffer = new ComputeBuffer(mesh.vertexCount * 5, sizeof(float) * 3); // size multiplied by 5???
vertexBuffer.SetData(mesh.vertices);
To demonstate what I mean when I’m saying missing vertices, I’ve attached an image displaying the results of my compute shader. Only thing that’s changed between the 3 different images, is the element count of the vertex buffer.
Does anyone know why this is happening, or what I’m doing wrong here?
