Search code examples
webglwebgl2

Drawing instances with WebGL2 - vertexAttribDivisor


I'm learning webgl2 from https://webgl2fundamentals.org. I'm learning about instancing right now. I can get the demo to work, where it draws many crosses, and I can get it to work with 500 instances.

But I cannot add anything else to the scene. I have a simple triangle that renders fine without the instancing, but with the crosses added the triangle disappears. I believe it has to do with gl.vertexAttribDivisor. I'm not sure when I need to call it, or if I need to undo it somehow.

If I omit calls to vertexAttribDivisor, the crosses don't render correctly, but the triangle is fine. If I replace the call to vertexAttribDivisor, the triangle disappears.

When do I call gl.vertexAttribDivisor? Do I have to undo the call to resume normal, non-instanced rendering? What does it really do?


Solution

  • The vertex attribute functions change a single global state. vertexAttribDivisor sets the divisor for a specified generic vertex attribute (one of the globally available ones), for every draw* call you want to setup the attributes using vertexAttribPointer and vertexAttribDivisor, if you changed the divisor for an attribute for one draw call but don't want to use the same divisor for your following draw call you need to reset it.