# GPU Particle Simulation in Float Textures (Ping-Pong) with Divergence-Free Flow Noise and Analytic Colliders in Three.js

> 65,536 particles simulated entirely on the GPU: positions and velocities live in float render targets updated by two full-screen passes per fixed step, then drawn as one points object whose vertex shader reads the texture. Divergence-free flow noise, a vortex, and sphere and floor colliders; it runs on the kit's own render loop.

- **Canonical page:** https://gamecrew.ai/techniques/three/gpu-particle-simulation-textures
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** vfx
- **Tags:** `particles`, `gpgpu`, `ping-pong`, `flow-noise`, `render-target`, `vfx`, `fountain`, `sparks`
- **Author:** @maddmann (https://gamecrew.ai/makers/maddmann), reviewed before it was shared
- **Revision:** 3 (2026-11-29)
- **Demo:** Demo passed on r3: [play it](https://play.gamecrew.ai/t/P2Axnx6dri0UWtEENzmsB-n9jIj_TG4a/) ([picture](https://gamecrew.ai/techniques/three/gpu-particle-simulation-textures/demo.png))

## When to use it

Sparks, embers, snow spray, rain, dust, magic swirls, fountains: anything where you want tens of thousands of particles and a CPU pool (a few thousand at most in JavaScript) is not enough. The CPU never touches a particle after load, so 65,536 cost the CPU nothing per frame.

What it cannot do cheaply: particles that affect gameplay (the CPU does not know where they are), particles that collide with arbitrary meshes (only shapes you can write as a formula), and particles that interact with each other.

## The idea

Each particle is one texel. Two float textures hold its state:

- **positions**: `xyz` and, in `w`, the life it has left in seconds (`<= 0` means respawn this step);
- **velocities**: `xyz` and, in `w`, a fixed random seed in [0, 1).

A texture cannot be read and written in the same pass, so there are two of each (A and B). Each fixed step:

1. **Velocity pass** draws a full-screen quad into velocity B. Its fragment shader reads position A and velocity A at its own texel and writes the new velocity: forces in, colliders out.
2. **Position pass** draws into position B, reading position A and the new velocity B: integrate, keep out of colliders, count down life, respawn the dead.
3. Swap: B is now current.

Drawing is one `THREE.Points` with one vertex per particle whose only attribute is the texel to read. The vertex shader looks up the position there.

**Flow without clumping.** Random forces make particles bunch up and leave holes. The rotation (nabla cross) of any smooth vector field has zero divergence: it moves things around without compressing them, the way a fluid does. Build a smooth potential from a few sines and cosines, take nabla cross of it with central differences (six evaluations of the potential), and you have swirling, space-filling motion.

```glsl
vec3 potential(vec3 p, float t) {
  vec3 a = vec3(sin(p.y * 0.9 + t * 0.31) * cos(p.z * 0.7 - t * 0.17),
                sin(p.z * 0.8 + t * 0.23) * cos(p.x * 0.9 + t * 0.29),
                sin(p.x * 0.7 - t * 0.19) * cos(p.y * 0.8 + t * 0.37));
  vec3 q = p * 2.3 + 11.0;
  vec3 b = vec3(sin(q.y + t * 0.5) * cos(q.z), sin(q.z - t * 0.4) * cos(q.x), sin(q.x + t * 0.45) * cos(q.y));
  return a + 0.35 * b;
}
vec3 flow(vec3 p, float t) {
  const float e = 0.05;
  vec3 dx = (potential(p + vec3(e, 0.0, 0.0), t) - potential(p - vec3(e, 0.0, 0.0), t)) / (2.0 * e);
  vec3 dy = (potential(p + vec3(0.0, e, 0.0), t) - potential(p - vec3(0.0, e, 0.0), t)) / (2.0 * e);
  vec3 dz = (potential(p + vec3(0.0, 0.0, e), t) - potential(p - vec3(0.0, 0.0, e), t)) / (2.0 * e);
  return vec3(dy.z - dz.y, dz.x - dx.z, dx.y - dy.x); // nabla cross potential
}
```

**Colliders as formulas.** A sphere is a centre and a radius in a uniform. The velocity pass predicts `p + v * dt`; if that is inside, it removes the inward part of the velocity and adds it back reversed times `bounce`. The position pass then projects anything still inside onto the surface, so nothing tunnels. The floor is `y = 0` the same way. Boxes, capsules and height fields work the same; anything with a signed distance function does.

## Implementation

The simulation passes (a shared header holds the uniforms, the flow, a hash and the spawn functions):

```glsl
// velocity pass
void main() {
  vec4 p = texture2D(positions, vUv);
  vec4 v = texture2D(velocities, vUv);
  if (p.w <= 0.0) { gl_FragColor = vec4(spawnVelocity(v.w), v.w); return; }
  vec3 vel = v.xyz;
  vec3 wind = flow(p.xyz / flowScale, time) * flowStrength;
  vec3 around = vec3(-p.z, 0.0, p.x) * swirl / max(length(p.xz), 0.5); // a vortex round y
  vel += (gravity + wind + around - vel * drag) * dt;
  vec3 next = p.xyz + vel * dt;
  vec3 out_ = next - sphere.xyz;
  float d = length(out_);
  if (d < sphere.w) {
    vec3 n = out_ / max(d, 1e-4);
    float vn = dot(vel, n);
    if (vn < 0.0) vel -= (1.0 + bounce) * vn * n;
    vel *= 0.98;
  }
  if (next.y < 0.0 && vel.y < 0.0) { vel.y = -vel.y * bounce; vel.xz *= 0.8; }
  gl_FragColor = vec4(vel, v.w);
}

// position pass
void main() {
  vec4 p = texture2D(positions, vUv);
  vec4 v = texture2D(nextVelocities, vUv);
  if (p.w <= 0.0) {
    gl_FragColor = vec4(spawnPosition(v.w), lifetime * (0.35 + 0.65 * hash(vec2(v.w, time + 3.1))));
    return;
  }
  vec3 pos = p.xyz + v.xyz * dt;
  vec3 out_ = pos - sphere.xyz;
  float d = length(out_);
  if (d < sphere.w) pos = sphere.xyz + out_ / max(d, 1e-4) * sphere.w;
  pos.y = max(pos.y, 0.0);
  gl_FragColor = vec4(pos, p.w - dt);
}
```

Drawing: additive, no depth writes, soft round points sized by distance, coloured by speed, faded at the end of life.

```glsl
// vertex
attribute vec2 texel;
void main() {
  vec4 p = texture2D(positions, texel);
  vec4 v = texture2D(velocities, texel);
  vSpeed = length(v.xyz);
  vFade = clamp(p.w / (0.25 * lifetime), 0.0, 1.0) * step(0.0, p.w);
  vec4 view = modelViewMatrix * vec4(p.xyz, 1.0);
  gl_Position = projectionMatrix * view;
  gl_PointSize = pointSize / max(-view.z, 0.1);
}
```

The TypeScript side, condensed:

```ts
const canFloat = renderer.extensions.has('EXT_color_buffer_float');
const type = canFloat ? THREE.FloatType : THREE.HalfFloatType;
const opts = { type, format: THREE.RGBAFormat, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, depthBuffer: false, stencilBuffer: false };
const targets = [0, 1, 2, 3].map(() => new THREE.WebGLRenderTarget(side, side, opts)); // posA, velA, posB, velB

// the first state is a pair of DataTextures: everything dead, seeds spread low-discrepancy
for (let i = 0; i < n; i++) vel[i * 4 + 3] = (i * 0.7548776662 + 0.1) % 1;

function simulate(renderer: THREE.WebGLRenderer, steps: number, dt = 1 / 60): void {
  const before = renderer.getRenderTarget();
  for (let i = 0; i < steps; i++) {
    simTime += dt;
    const next = flip === 0 ? 2 : 0;
    velocityMaterial.uniforms.positions.value = current.positions;
    velocityMaterial.uniforms.velocities.value = current.velocities;
    velocityMaterial.uniforms.time.value = simTime;
    renderer.setRenderTarget(targets[next + 1]);
    renderer.render(velocityScene, simCamera);
    positionMaterial.uniforms.positions.value = current.positions;
    positionMaterial.uniforms.nextVelocities.value = targets[next + 1].texture;
    positionMaterial.uniforms.time.value = simTime;
    renderer.setRenderTarget(targets[next]);
    renderer.render(positionScene, simCamera);
    current = { positions: targets[next].texture, velocities: targets[next + 1].texture };
    flip = next;
  }
  renderer.setRenderTarget(before);
}

// one vertex per particle; its only data is which texel to read
const texel = new Float32Array(n * 2);
for (let i = 0; i < n; i++) {
  texel[i * 2] = ((i % side) + 0.5) / side;
  texel[i * 2 + 1] = (Math.floor(i / side) + 0.5) / side;
}
points.frustumCulled = false;
points.onBeforeRender = (r) => catchUp(r);
```

### Stepping on the kit's clock

The kit owns the render loop, there is no hook between steps and drawing for GPU work, and tests never draw. So the simulation is advanced from the points' `onBeforeRender`: it takes `game.frame - lastFrame` steps (at most 4, so a hitch does not snowball), and on the very first draw it prewarms 240 steps so the first picture shows a running effect, not a burst from one point. Nothing moves while paused (the frame count stops) or in headless tests, and nested `renderer.render` calls inside `onBeforeRender` are safe as long as the render target is restored.

## Knobs

`side` (256 gives 65,536; 512 gives 262,144 on desktop), `lifetime`, emitter position, radius, velocity and spread, `gravity`, `flowStrength` and `flowScale` (the size of the eddies), `swirl`, `drag`, `bounce`, and on the drawing side `pointSize` and `brightness`. In the demo, three presets set these: a fountain splashing off a sphere, a vortex, and wind-blown rain.

The kit's `tuning.json` is a list of knobs (`{"knobs": [{"name", "label", "group", "value", "min", "max"}]}`). A flat `{"brightness": 0.2}` file is ignored without a warning and every `tuning.value` returns its fallback.

## Traps

- **Float render targets need `EXT_color_buffer_float`.** Most WebGL 2 browsers have it; check, and fall back to half float. Half-float positions lose precision fast (about 1 cm at 10 m) and particles visibly jitter: keep the effect small or centred near the origin in that case.
- **Linear filtering on the state textures** blends neighbouring particles together. Use `NearestFilter` and sample texel centres.
- **Additive brightness explodes with count.** 65,536 additive points over one spot saturate to white. Scale brightness down by roughly the overlap (the demo uses 0.22 with 34-pixel points at 10 m), not by taste at 1,000 particles.
- **Everything respawning at once** gives pulsing waves. Randomise each life's length at respawn, as here.
- **`frustumCulled = false`**, or three culls the points by their unused position attribute.
- **Tone mapping and colour space**: the simulation materials set `toneMapped: false` (they write data, not colour); the points material includes the tone mapping and colour space chunks so sparks match the scene.
- **Sorting**: the points are one object. Over other transparent objects, order them with `renderOrder`.
- **VR** draws twice per frame from the headset's cameras; the step counter keeps the simulation at the game's rate, but check the cost of double fill.

## How to check it

- Unit test the flow field on the CPU (a TypeScript copy of the potential): central-difference divergence at a few points must be under 2% of the field's strength.
- Play test on the GPU: call `simulate(renderer, 45)`, read the position target back with `readRenderTargetPixels`, and count: most particles alive, most more than a metre from the emitter, none inside the sphere, none under the floor. Assert the target is `FloatType` so the test cannot pass vacuously.
- In a capture, the fountain should splash off the underside of the sphere and fall around it; no particle should be visible inside it.

## Official references

- Bridson, Hourihan and Nordenstam, divergence-free noise for procedural fluid flow (SIGGRAPH 2007)
- three.js manual: WebGLRenderTarget and readRenderTargetPixels
- Khronos: EXT_color_buffer_float for WebGL 2

## Who made it

This guide is by @maddmann.

- @maddmann (https://gamecrew.ai/makers/maddmann): owner, 3 revisions
