# GPGPU Particle System

[Live demo](https://matinmonshizadeh.github.io/animation-handbook/animations/06-3d-advanced/gpgpu-particle-system/)

## What it is
A GPU particle system moves tens of thousands of particles on the graphics chip instead of in JavaScript. Every particle's position and speed is stored as one pixel of a texture, and a shader reads last frame's texture and writes the next one, all at once. A second step draws each particle as a tiny point.

## When to use it
- Large-scale particle effects: galaxy simulations, fluid flow, fire systems, crowd simulations
- Any particle system where JavaScript particle count is the performance bottleneck
- Creative coding contexts where particle count itself is the aesthetic (100k points forming a shape)
- Technical demonstrations of GPGPU principles in the browser

## How it works
**Data layout**: a 256×256 texture of RGBA32F pixels stores 65,536 particles. Each pixel = one particle's `(x, y, vx, vy)`.

**Physics shader** (WebGL2 fragment shader, renders to offscreen texture):

```glsl
#version 300 es
precision highp float;
uniform sampler2D uPos;   // read previous frame's positions
uniform float uTime, uSpeed;
uniform int uBehavior;
uniform float uStep;     // one 60 Hz step per pass: 1, or 1/3 in slow motion
out vec4 outColor;        // write new positions

float hash(float n) { return fract(sin(n) * 43758.5); }

void main() {
  ivec2 coord = ivec2(gl_FragCoord.xy);
  vec4 p = texelFetch(uPos, coord, 0);
  float x = p.x, y = p.y, vx = p.z, vy = p.w;

  // Apply behavior (flow field, vortex, attractor, etc.)
  if (uBehavior == 1) {  // vortex
    float len = length(vec2(x, y)) + 0.01;
    vx += (-y / len) * uSpeed * 0.0004 * uStep;
    vy += ( x / len) * uSpeed * 0.0004 * uStep;
    vx -= x * 0.0005 * uStep;  // inward pull to prevent escape
    vy -= y * 0.0005 * uStep;
  }
  vx *= pow(0.985, uStep); vy *= pow(0.985, uStep);  // damping
  x += vx * uStep; y += vy * uStep;
  // Respawn anything that leaves clip space
  if (abs(x) > 1.0 || abs(y) > 1.0) {
    float n = float(coord.x) * 0.0713 + float(coord.y) * 0.1319 + uTime * 0.977;
    float a = hash(n) * 6.2832, r = hash(n + 3.71) * 0.9 + 0.05;
    x = cos(a) * r; y = sin(a) * r; vx = 0.0; vy = 0.0;
  }
  outColor = vec4(x, y, vx, vy);
}
```

**Time step** — every physics pass moves the particles by exactly one 60 Hz step: `uStep` is 1 (a third of that in slow motion), on every screen. The page looks at every frame the screen offers and measures the time since the last drawn one in steps of 1/60 s (a gap counts for at most 50 ms, and a value within 0.05 of a whole number of steps counts as that number, so a screen a little off 60 Hz, such as 59.94 or 119.88 Hz, still runs exactly one pass a frame). It runs one pass for every whole step it has added up (allowing 1 ms of slack, and at most three passes a frame) and carries the rest over: one pass a frame on a 60 Hz screen, two on a 30 Hz one, and none on a frame that comes too soon, which changes nothing and draws nothing, so the drawing stays near 60 pictures a second on a faster screen. The particles move at the same speed on every screen, and the attractor, which pulls hard near the middle and settles differently for a longer or a shorter step, looks the same too. A drawn frame lays the trail fade over the picture once for every pass it ran, after the passes, each time 12% of the old picture; slow motion still runs 60 passes a second, so it slows the particles but not the fade. One smaller fade would fade the same amount, but an 8-bit canvas rounds it differently, and the faint leftovers of a trail would end up another color.

**Texture ping-pong** — alternate which texture is the read source each pass:

```js
// Physics pass: read tex0, write to fbo1 (which wraps tex1)
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo1);
gl.bindTexture(gl.TEXTURE_2D, tex0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

// Swap
[tex0, tex1] = [tex1, tex0];
[fbo0, fbo1] = [fbo1, fbo0];
```

**Render pass** — vertex shader reads position texture to set `gl_Position`:

```glsl
#version 300 es
in float aIndex;
uniform sampler2D uPos;
uniform vec2 uTexSize;
uniform float uPointSize;   // 1.5 CSS px x devicePixelRatio

void main() {
  int idx = int(aIndex);
  ivec2 co = ivec2(int(mod(aIndex, uTexSize.x)), idx / int(uTexSize.x));
  vec4 p = texelFetch(uPos, co, 0);
  gl_Position = vec4(p.xy, 0.0, 1.0);
  gl_PointSize = uPointSize;
}
```

## Key parameters
| Parameter | Default | Effect |
|-----------|---------|--------|
| Movement | Flow | Flow follows a shifting field of currents; Swirl circles the middle; Attract pulls everything toward the middle; Orbit sweeps the particles round in rings |
| Number of particles | 65,000 | 16,000, 65,000 or 100,000 particles, one pixel each of a texture 128, 256 or 320 pixels square; phones start with 16,000 |
| Speed | Normal | How hard the rule pushes for every sixtieth of a second: slow pushes 0.35 times as hard as fast and normal 0.6 times; under Flow a typical particle then crosses about 11%, 16% or 22% of the stage a second |
| Color | One color | One blue, a color from each particle's speed, or colors that slowly shift |
| Trails | off | Fades the last picture instead of clearing it, so each particle leaves a streak |

## Production notes
- **WebGL2 required**: `RGBA32F` float framebuffer targets require WebGL2 (or the `WEBGL_color_buffer_float` extension in WebGL1, which is less reliably available). WebGL2 is supported in all modern browsers (Chrome 56+, Firefox 51+, Safari 15+).
- **Time, not frames**: a fixed step per frame would move the particles twice as fast on a 120 Hz screen and half as fast on a 30 Hz phone, and fade the trails at the same wrong rate. Step by a fixed 1/60 s from an accumulator, as above, and cap the time of one frame (this demo uses 50 ms) and the passes per frame, so a strong pull near a point settles the same on every screen. Fade once per physics pass, always by the same amount.
- **Three.js `GPUComputationRenderer`**: Three.js includes `GPUComputationRenderer` (in the `three/examples/jsm` path) which encapsulates the entire ping-pong texture pattern. It's the idiomatic production approach.
- **WebGPU compute shaders**: WebGPU provides proper `@compute` shader stages for GPGPU, eliminating the "fragment shader as compute" workaround. As of 2024, WebGPU is available in Chrome 113+ but not yet in Firefox stable or Safari.
- **Wrap only survives a divergence-free field**: this demo's flow field pushes particles away from the x-axis, so it has a net outward drift. An earlier version wrapped at ±1.2 while only ±1.0 is visible; particles drifted into that invisible ring faster than they came back and the canvas faded to black after about ten seconds. Tightening the wrap to ±1.0 only moved the symptom — a divergent field teleports the escapee straight back to the edge it just left, so the particles crust along the top and bottom instead. Respawning escapees at a random point near the middle is the fix, and it is what keeps the population steady here. Nothing throws in either failure, and the first second looks correct in all three versions, so this class of bug is only visible if you leave the demo running.
- **Point size is in device pixels**: the canvas backing store is sized `clientWidth * devicePixelRatio` (capped at 2 here) and `gl.viewport` uses those same numbers. `gl_PointSize` is measured in device pixels too, so it has to be multiplied by the same ratio or the points shrink on a retina screen.
- **Context loss**: a GPU reset, a tab restore, or too many live WebGL contexts will fire `webglcontextlost`. Without a listener that calls `preventDefault()`, the context never comes back and the demo stays black forever. On `webglcontextrestored` every program, buffer, texture and framebuffer has to be recreated — GPU objects do not survive the loss.
- **Mobile budget**: 65k additively blended points cover a phone screen several times over and are both slow and visually mushy. This demo drops to a 128x128 texture (16k particles) on phones (screens 600px wide or less, or 500px tall or less); a production system should scale the texture size to the pixel count it actually has to fill.
- **Memory**: 256×256 × 4 channels × 4 bytes (float32) = 1MB per texture. Two textures = 2MB — trivial. At 512×512 (262k particles): 4MB × 2 = 8MB.

## See also
- [Canvas Particle Effect](../canvas-particle-effect/) — hundreds of particles moved in JavaScript
- [Fluid / Liquid Simulation](../fluid-simulation/) — a shader that melts blobs together
- [WebGL Shader Animation](../webgl-shader-animation/) — shaders that paint every pixel
