Use 32 bits indices with Mesh.setIndexBuffer()

I am simulating a cloth using a large particle system with WebGPU and its compute shaders.

How can I use 32 bits indices with Mesh.setIndexBuffer() instead of 16 bits ?

Relevant parts of the code:

const indices = new BABYLON.StorageBuffer(this.engine, indicesArray.length * 2, BABYLON.Constants.BUFFER_CREATIONFLAG_INDEX | BABYLON.Constants.BUFFER_CREATIONFLAG_WRITE);
indices.update(new Uint16Array(indicesArray));

mesh.setIndexBuffer(indices.getBuffer(), vertexCount, indicesArray.length); // mesh is broken if there is more than 65kB vertices.

You can use Engine.createIndexBuffer:

The value of Babylon.js docs is set depending on the source of createIndexBuffer : Uint32Array or Uint16Array

I don’t know if the buffer will benefit from the flags you need with compute shaders.

ping @Evgeni_Popov

Fixed it.
It seems (though I could not find any documentation about this) that setIndexBuffer expects 16 bits buffer if indicesArray.length<= 65535, 32 bits else.
So the solution is simple:

        if (indicesArray.length> 65535) {
            // 32 bits buffer
            this.indices.update(new Uint32Array(indicesArray));
        else {
            // 16 bits buffer
            this.indices.update(new Uint16Array(indicesArray));

It seems the SorageBuffer must be have a size set to 4*indicesArray.length to make sure it will fit in both cases.

Can someone confirm my findings, and explain the underlying reason?
ping @Evgeni_Popov

This is correct!!!

1 Like