Two dimensional array in compute shader

I want to use a compute shader to calculate movements of cloth particles.

Cloth particle is a struct that contains three Vector3s its current position, previous position and acceleration to add. On CPU side I keep those particles in a 2D array, this way I know the place of each particle in the structure. Each frame I calculate new position for each particle in the structure. I want to do the same with a compute shader.

The question is, can I pass the 2D array of structures to compute shader via the ComputeBuffer.SetData() and access each particle by its position in the structure? Or do I have to pass it as a 1D array and restructure my code to process data this way?

I’m now to compute shaders and I need to understand some fundamental things to get everything right.

Hi, I’m doing something like this with independents particles (not in a 2D organization) so the high level concept you describe works :slight_smile: For 2D arrays, I don’t think it’s possible to declare such thing for Structured Buffers but you can emulate a 2D array with a 1D array anyway (table[ x + y * size_x], It also saves a bounds check in C# so it’s always good to do that when CPU is important). There are also some variant of SetData() and ComputeBuffers related API that works with NativeArrays, I would also recommend to use that to reduce Garbage creation and maybe some memcopy :slight_smile:

I think you could also work with 1 (or more) Texture that you can read and write to in a Compute Shader like a 2D array. I’m not sure of the performance though, and it could be difficult to organize/store all Vectors in different textures RGBA floats. I guess Structured Buffers were designed to not have to deal with that :slight_smile: