Interactive Vision From Zero · Episode 26

Face Particles II — The GPGPU Studio

Face Particles II — The GPGPU Studio is Episode 26 of Interactive Vision From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

← Interactive Vision From Zero Bonus · Episode 26
Bonus · Episode 26 · Interactive Vision From Zero

Last episode the swarm lived on the CPU and topped out around ten thousand particles — fine for a face, hopeless for a storm of one. This episode moves the entire simulation onto the GPU. We keep every particle's position and velocity in textures, run the physics as a fragment shader that reads last frame's texture and writes this frame's, and ping-pong the two every tick. Suddenly tens of thousands of particles cost almost nothing, and they can do real physics: momentum, cohesion, a curl-noise wind, and a force that follows your hand.

This is the full rebuild of the VIVERSE FaceParticles piece. The demo is alive on load with a synthetic face and a procedural attractor. Switch mode between Face (the swarm springs into your face), Fluid (it sloshes with momentum and reforms), and Classic (a curl-noise flow field). Move your mouse over the demo to push the particles around; hold the button down to suck them into your cursor. Then hit use my camera and it's your face the storm keeps collapsing back into.

0 fps
move the mouse to push · hold to suck
🔒 runs on-device · nothing leaves your machine
GPGPU · 25,600 particles
Face mode: the swarm springs into the face and holds. Push it with the mouse.

🔒 The camera button runs MediaPipe's Face Landmarker entirely in your browser. No frame is ever uploaded; nothing leaves your machine. Until you press it, the demo uses a synthetic face and makes zero network requests.

What you're looking at

The same idea as Episode 25 — particles chasing a face — but nothing about a particle lives in JavaScript anymore. Each particle is one texel in a pair of floating-point textures: one holds its position (plus a life value), the other its velocity. Every frame, two tiny fragment shaders run once per texel: the velocity shader computes forces and updates the velocity; the position shader moves the particle by that velocity. The output textures become next frame's input. That read-last-write-this dance, on a buffer of numbers, is GPGPU — general-purpose computation on the GPU — and Three.js ships a helper for it, GPUComputationRenderer.

The face still arrives as a few hundred landmark points (synthetic, or your camera's 468), which we bake into a small target texture every frame. Each particle reads its assigned target out of that texture and is pulled toward it. What changes between the three modes is simply which forces the velocity shader adds.

┌─ positionTex (xyz + life) ─┐ ┌─ velocityTex (xyz + seed) ─┐ │ read │ write │ │ read │ write │ └────┬────┴─────▲─────────────┘ └────┬────┴─────▲─────────────┘ │ │ │ │ position shader: pos += vel·dt velocity shader: vel += forces·dt (+ respawn to face target (cohesion→face, curl wind, when life runs out) hand push/suck, damping, clamp) │ ▲ └──────────── faceTex (M target points, baked each frame) ──────┘ render: THREE.Points whose vertex shader SAMPLES positionTex → lit sphere

Mode — Face

The velocity shader applies one dominant force: a stiff spring from each particle to its target on the face, plus heavy damping. The swarm snaps into a crisp face and holds it, quivering slightly. Shove it with the mouse and it scatters, then springs right back — that elastic "reform" is the signature of the whole genre. With the camera on, the target is your real face, so it tracks you live.

Mode — Fluid

Loosen the spring to a gentle cohesion, add a curl-noise wind and full momentum, and the particles stop being a rigid face and start behaving like a fluid that remembers it's a face. Push them and they carry their velocity, swirl, collide, and slowly drift home. This is the mode that looks alive. The flow and cohesion sliders trade "smoke" against "snap."

Mode — Classic

Drop the cohesion near zero and let the curl-noise field dominate. Now the face is just a faint memory the particles keep washing through — a flowing, organic vector field, the classic generative-art look. The same wind that adds life to Fluid mode is the whole simulation here. Crank flow and watch it stream.

The attractor — your hand

One force is shared by every mode: a point that follows your pointer. Hover and it gently pushes particles away (an open palm); press and hold and it flips to suck them in (a fist), in slow motion. That single signed radial force, faded out by distance, is the entire "interaction." In the original it's driven by MediaPipe's hand landmarks — open vs. closed fist; here the mouse stands in, and the hand episodes show how to swap a real hand back in.

The studio look — trails, light, color

Two cheap touches turn the simulation into a piece. Trails: instead of clearing the screen each frame, we paint a nearly-transparent black rectangle over it, so moving particles smear into comet tails (the trails slider sets how long). Light: each particle is the same lit sphere-sprite as Episode 25, tinted by a vertical palette and brightened by its own speed, so fast particles glow. Recessed, darkened eyes and mouth keep the face readable underneath the storm.

How the code works

(a) Set up the ping-pong with GPUComputationRenderer

We make a square simulation of SIZE×SIZE texels (here 160² = 25,600 particles). Two variables — position and velocity — each get a fragment shader and a list of which textures they're allowed to read. The helper handles the double-buffering:

import { GPUComputationRenderer } from 'three/addons/misc/GPUComputationRenderer.js';

const SIZE = 160;                                   // 25,600 particles
const gpu  = new GPUComputationRenderer(SIZE, SIZE, renderer);

const pos0 = gpu.createTexture(), vel0 = gpu.createTexture();
seedTextures(pos0, vel0);                          // scatter into a ball; life + seed

const posVar = gpu.addVariable('texturePosition', positionFrag, pos0);
const velVar = gpu.addVariable('textureVelocity', velocityFrag, vel0);
gpu.setVariableDependencies(posVar, [posVar, velVar]); // each shader may read both
gpu.setVariableDependencies(velVar, [posVar, velVar]);
const err = gpu.init(); if (err) console.error(err);   // surfaces shader compile errors

(b) The velocity shader — all the physics lives here

For each texel it reads the particle's position and velocity, looks up its face target, and sums the forces for the current mode. resolution and gl_FragCoord are provided by the helper, so we can recover the particle's index and pick its target slot:

uniform float uMode, uCohesion, uFlow, uDamping, uMaxSpeed;
uniform vec3  uHandPos; uniform float uHandForce, uHandRadius, uDt;
uniform sampler2D uFaceTex; uniform float uFaceCount, uFaceTexSize;

void main() {
  vec2 uv  = gl_FragCoord.xy / resolution.xy;
  vec3 pos = texture2D(texturePosition, uv).xyz;
  vec3 vel = texture2D(textureVelocity, uv).xyz;

  // which face point is mine? (stable per particle) → sample the target texture
  float idx  = floor(gl_FragCoord.y) * resolution.x + floor(gl_FragCoord.x);
  float slot = mod(idx, uFaceCount);
  vec2  fuv  = (vec2(mod(slot, uFaceTexSize), floor(slot / uFaceTexSize)) + 0.5) / uFaceTexSize;
  vec3  home = texture2D(uFaceTex, fuv).xyz + (hash3(uv) - 0.5) * uJitter;

  vec3 force = vec3(0.0);
  if (uMode < 0.5)      force += curl(pos * uCurlSize) * uFlow * 1.4;        // Fluid: wind
  if (uMode > 1.5)      force += (home - pos) * 0.18;                         // Face: stiff spring
  else                  force += (home - pos) * uCohesion + curl(pos*uCurlSize)*uFlow; // Fluid/Classic

  vec3 toHand = uHandPos - pos; float d = length(toHand);                      // the attractor
  force += normalize(toHand + 1e-4) * uHandForce * smoothstep(uHandRadius, 0.0, d);

  vel = (vel + force * uDt) * uDamping;                                        // integrate + damp
  float sp = length(vel); if (sp > uMaxSpeed) vel *= uMaxSpeed / sp;           // clamp
  gl_FragColor = vec4(vel, texture2D(textureVelocity, uv).a);                  // keep the seed
}

(c) Bake the face into a texture every frame

The simulation can't read a JS array — it reads textures. So each frame we copy the M current face points (synthetic or live landmarks, mapped to world space) into a small DataTexture and flag it dirty. One onLandmarks path feeds it, exactly as in every episode this season:

// faceData: Float32Array(FT*FT*4); faceTex: THREE.DataTexture(faceData, FT, FT, RGBAFormat, FloatType)
function bakeFace(points) {                 // points: M × {x,y,z} normalized image space
  for (let m = 0; m < M; m++) {
    const w = toWorld(points[m]);          // mirror-X + flip-Y + depth, shared mapping
    faceData[m*4+0] = w.x; faceData[m*4+1] = w.y;
    faceData[m*4+2] = w.z; faceData[m*4+3] = points[m].feat;
  }
  faceTex.needsUpdate = true;                // re-upload to the GPU
}

(d) Render by sampling the position texture

The particles are a THREE.Points whose geometry carries no real positions — just a ref attribute (each vertex's texel UV). The vertex shader reads the live position straight out of the simulation texture; the fragment shader is the lit sphere from last episode, plus a speed-driven glow:

// VERTEX — fetch this particle's position from the GPGPU texture
uniform sampler2D uPosTex, uVelTex; attribute vec2 ref;
void main() {
  vec3 pos = texture2D(uPosTex, ref).xyz;
  vSpeed   = length(texture2D(uVelTex, ref).xyz);
  vec4 mv  = modelViewMatrix * vec4(pos, 1.0);
  gl_PointSize = uSize * uDpr * 90.0 / -mv.z;
  gl_Position  = projectionMatrix * mv;
}

Common pitfalls

  • Everything is black / NaN. Float textures that start as zeros give a divide-by-zero in normalize. Seed the initial textures with real values (a scatter ball, a non-zero life) and add + 1e-4 before normalizing directions.
  • The sim "explodes" to infinity. No speed clamp, or uDt times a stiff spring overshoots. Clamp velocity to uMaxSpeed and keep a damping factor below 1.0. GPGPU has no safety net — one frame of runaway force is permanent until respawn.
  • Particles read the wrong target. The index math from gl_FragCoord must match how you assigned the ref attribute on the CPU. Off-by-one here scrambles the whole face. Verify by dropping to Face mode with flow at zero — it should be a clean face.
  • Trails never fade (screen fills white) or never appear. You left autoClear on (no trails) or off without drawing the fade quad (smear forever). Draw a black quad at opacity = 1 − trails each frame and clear only depth.
  • Compile errors vanish silently. Always check the return value of gpu.init() and log it. A mistyped uniform makes the shader fail and the texture stays at its seed values — looking like "frozen," not "errored."
  • Camera works on localhost but not file://. Same as always: getUserMedia needs a secure context. The synthetic face keeps the demo alive regardless.

Exercises

  1. Real fists. Load HandLandmarker alongside the face (the gesture episode's open/closed test), and drive uHandPos + the suck/push sign from a real hand instead of the mouse. Now you conduct the storm in the air.
  2. Mouth-blast. Read the lip gap and, when you open your mouth, spike uFlow and zero the cohesion for a few frames so the face detonates outward, then reforms. The crowd-pleaser.
  3. Color from the camera. Sample the webcam video texture at each landmark and bake an RGB into the face texture's spare channels, so particles wear your actual skin tones — the original's "webcam colors" mode.

What's next

You've now built the whole thing twice — once on the CPU to understand it, once on the GPU to ship it. This is the end of the Face Particles bonus pair, and a natural capstone for the vision series: it folds the face mesh (Ep 12), GPU effects (Ep 20), and the particle-instrument idea (Ep 24) into one portfolio piece. Drop it on a page, wire in a real hand, and you have a living installation.