Three.js Transform Feedback Particles (Raw WebGL2)

GPU particle physics with WebGL2 transform feedback alongside Three.js, where a vertex shader writes updated positions and velocities into a second buffer that is then drawn directly, for up to a million particles with no CPU readback.

Key topics: three.js transform feedback, webgl2, gpu particles, raw webgl, rasterizer discard, ping pong buffers

What this code does

- Transform Feedback: `transformFeedbackVaryings` tells the linker to capture vertex outputs (`vPos`, `vVel`) into a buffer.
- Simulation Pass: with RASTERIZER_DISCARD on, drawing N points runs the vertex shader N times and writes the results into the other buffer.
- Ping-Pong Buffers: two interleaved [pos, vel] buffers swap roles each frame, each with its own VAO for update and render.
- Same Context: three.js draws the grid first, the raw points are depth-tested against it, then `renderer.resetState()` resyncs three.
- Physics: gravity, ground bounce with friction, and respawn at a moving emitter using gl_VertexID-seeded hashes.
- Controls: particle count, gravity, bounce, point size and emitter motion.

Continue Learning

JavaScript Implementation

ES6+
// Transform feedback: capture vertex shader outputs into a buffer (WebGL2 core, not exposed by three)
const gl = renderer.getContext()
gl.transformFeedbackVaryings(updateProgram, ['vPos', 'vVel'], gl.INTERLEAVED_ATTRIBS) // before linkProgram
gl.linkProgram(updateProgram)

function step () {
  gl.useProgram(updateProgram)
  gl.bindVertexArray(vaoReading[src])
  gl.enable(gl.RASTERIZER_DISCARD)                         // simulate only, don't draw
  gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, tf)
  gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, buffers[1 - src])
  gl.beginTransformFeedback(gl.POINTS)
  gl.drawArrays(gl.POINTS, 0, count)
  gl.endTransformFeedback()
  gl.disable(gl.RASTERIZER_DISCARD)
  src = 1 - src
  renderer.resetState()                                     // let three.js resync its GL cache
}