Interactive Vision From Zero · Episode 24
Capstone: Conduct a Cloud of Light
Capstone: Conduct a Cloud of Light is Episode 24 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 .
This is the last episode, so it isn't a lesson — it's a performance. Everything the series taught, fused into one shippable piece: a living cloud of forty thousand glowing particles that you sculpt and play with your bare hands. Pinch to grab a fistful and fling it; open your palm to push a shockwave through the swarm; make a fist to freeze the whole galaxy mid-air. A note sounds when you do. It's the kind of clip you screen-record and people ask "wait, that's just a webcam?"
It is alive the instant the page loads — a synthetic hand walks through a
short routine on its own, conducting the cloud so you can watch the finished instrument
before you lift a finger. Then press use my camera and you take over: your hand
flows into the exact same onLandmarks path the synthetic one uses, so nothing
downstream knows or cares whether the 21 landmarks came from a webcam or from JavaScript.
Step through the six stages to watch the showpiece get assembled, one capability at a time,
then conduct it yourself.
What you're looking at
One THREE.Points cloud of forty thousand particles, blended
additively so where they pile up they glow white-hot, drifting in a slow
3D orbit. A single invisible attractor sits where your index fingertip is —
un-projected from the 2D landmark into the 3D scene — and every particle feels it. Your
gesture decides what that attractor does: pull, push, or freeze.
Each stage below is the same machine with one more system switched on, mapped one-to-one to
a heading. The synthetic hand puppets it on a gentle loop so the piece performs with no
camera; drag your mouse to take the wheel of the synthetic hand, or hit the camera button
for the real thing.
Stage 1 — The particle field
The canvas we'll conduct. Forty thousand particles, each a soft additive sprite, seeded into a fuzzy sphere and given a lazy curl of drift. No hand yet — just a gorgeous, self-animating cloud of light. The trick that makes it shippable rather than a toy is hiding in plain sight: the particles live in pooled, pre-allocated typed arrays. We never create an object inside the render loop, which is the difference between a steady 120fps and a stuttery garbage-collected mess.
Stage 2 — + Hand attractor
Now your fingertip enters the scene as a force. The 2D index-tip landmark is mirrored and un-projected onto a fixed z-plane to become a 3D point, then smoothed with the One-Euro filter from Episode 23 — so the cloud responds instantly when you move fast but stops jittering when you hold still. Every particle is pulled gently toward that point. Move your hand (or mouse) and the whole swarm leans after it like iron filings drawn to a magnet you're holding.
Stage 3 — + Gestures
The attractor learns to read your hand. Using the geometry from across the series — thumb-to-index distance for pinch, per-finger curl for open palm and fist — your gesture flips the force's sign and character. Pinch turns the gentle pull into a hard grab that scoops particles into your hand and flings them on release. Open palm fires a push-wave that blasts the cloud outward. Fist freezes every particle where it sits. One hand, three verbs.
Stage 4 — + Trails & color
The look. Instead of clearing the frame to black each tick, we fade it — a translucent black rectangle drawn over the last frame — so moving particles smear into trails of light. And each particle is colored by its age: born hot and white near the attractor, cooling through a palette toward deep blue as it drifts away. Together these turn a swarm of dots into long ribbons of color that read as motion, energy, and life. This is the stage that makes it framable.
Stage 5 — + Sound
The piece gains a voice. Using the Web Audio gesture-instrument idea from the Season 1 finale, each gesture plays a soft synthesized note: a bright pluck on pinch, a low swell on the push-wave, a muted thunk on freeze, pitched by where your hand is on screen. Crucially, audio never autoplays — browsers forbid it, and it would be rude. You tap enable sound once (a real user gesture) to unlock the audio context; after that the notes are gesture-gated, firing only on the rising edge of a gesture, never per frame.
Stage 6 — The full showpiece
Everything live at once: the additive field, the One-Euro-smoothed attractor, all three gestures, trails, color-over-life, and gesture-gated sound, with the intensity slider scaling the whole performance. On first paint the synthetic hand runs a short routine — drift, pinch-and-fling, push-wave, freeze, release — so the instrument performs itself like a music box. Turn on your camera, enable sound, and conduct. This is the clip. This is the whole series, in your hands.
How the code works
Four parts carry the entire showpiece: the pooled additive particle field; the smoothed hand-to-3D-attractor with gesture detection; the gesture-to-effect mapping; and the compose loop that ties them together with gesture-gated audio. Because every input arrives as the same 21-landmark array, none of it cares whether you're driving with a webcam or with the synthetic performer.
(a) The 3D particle field — pooled and additive
The single most important performance rule in any particle system: allocate
once, reuse forever. We pre-fill flat Float32Arrays for position,
velocity, color, and per-particle age, and from then on the render loop only ever
writes into those arrays — never news anything. The geometry's
position and color attributes alias the same buffers, so updating
a particle is just three array writes. Additive blending plus depth-write-off makes the
overlaps glow:
const N = 40000;
// One allocation each — the render loop only ever WRITES into these.
const pos = new Float32Array(N * 3); // xyz per particle
const vel = new Float32Array(N * 3); // velocity (pooled — never re-created)
const col = new Float32Array(N * 3); // rgb, driven by age
const age = new Float32Array(N); // seconds alive → color & respawn
for (let i = 0; i < N; i++) seedParticle(i); // fuzzy sphere + slow curl
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
const material = new THREE.ShaderMaterial({
uniforms: { uSize: { value: 2.6 }, uDpr: { value: dpr } },
vertexShader, fragmentShader, // round soft sprite, size ∝ 1/depth
transparent: true,
blending: THREE.AdditiveBlending, // overlaps add up → glowing core
depthWrite: false, // don't occlude — it's light, not solid
});
scene.add(new THREE.Points(geo, material));
Each frame we integrate velocity into position, apply a little drag, and respawn
particles that have drifted too far or aged out — all by mutating the arrays in place, then
flagging geo.attributes.position.needsUpdate = true. Forty thousand particles
with zero per-frame allocation holds 120fps comfortably.
(b) The smoothed hand → 3D attractor (One-Euro) + gesture detection
The bridge from landmarks to the scene. We take the index tip, mirror it
(1 - x, the selfie flip that's bitten everyone in this series at least once),
run each axis through a One-Euro filter so the attractor is smooth at rest
but snappy in motion, and un-project the 2D point onto a fixed z-plane to get a real 3D
position. In the same pass we read the gesture from finger geometry:
// One-Euro filter (Ep23): low lag when moving fast, low jitter when still.
class OneEuro {
constructor(minCut = 1.2, beta = 0.020, dCut = 1.0) {
Object.assign(this, { minCut, beta, dCut, x: 0, dx: 0, init: false });
}
alpha(cut, dt) { const r = 2 * Math.PI * cut * dt; return r / (r + 1); }
filter(v, dt) {
if (!this.init) { this.x = v; this.init = true; return v; }
const dv = (v - this.x) / dt;
this.dx += this.alpha(this.dCut, dt) * (dv - this.dx);
const cut = this.minCut + this.beta * Math.abs(this.dx); // faster move → higher cutoff
this.x += this.alpha(cut, dt) * (v - this.x);
return this.x;
}
}
const fx = new OneEuro(), fy = new OneEuro();
function onLandmarks(hand, dt) {
const tip = hand[8]; // INDEX_TIP
const mx = fx.filter(1 - tip.x, dt); // MIRROR + smooth
const my = fy.filter(tip.y, dt);
// un-project the 0→1 point onto a fixed z-plane → 3D attractor
attractor.set((mx * 2 - 1) * SPAN, (1 - my * 2) * SPAN * 0.62, 0);
gesture = readGesture(hand); // 'pinch' | 'palm' | 'fist' | 'idle'
}
The gesture reader is pure geometry — the same toolkit the series built. Pinch is the thumb-tip-to-index-tip distance normalized by hand size (with hysteresis so it doesn't chatter at the threshold); open-palm and fist come from counting how many fingertips are extended past their knuckles:
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
let pinched = false; // hysteresis latch
function readGesture(h) {
const span = dist(h[5], h[17]) || 1e-4; // hand width = scale ref
const pinch = dist(h[4], h[8]) / span; // thumb tip ↔ index tip
if (pinch < 0.45) pinched = true; // on/off thresholds differ
if (pinch > 0.75) pinched = false; // = hysteresis, no flicker
if (pinched) return 'pinch';
// count extended fingers: tip farther from wrist than its PIP joint
const tips = [8, 12, 16, 20], pips = [6, 10, 14, 18];
let ext = 0;
for (let i = 0; i < 4; i++)
if (dist(h[tips[i]], h[0]) > dist(h[pips[i]], h[0])) ext++;
if (ext >= 4) return 'palm'; // all four out → open palm
if (ext <= 1) return 'fist'; // all curled → fist
return 'idle';
}
(c) Gesture → effect: emit / push / freeze
The gesture sets how the per-particle force is computed, and we apply it to the whole pool in one tight loop. Pinch is a strong inward pull that captures particles; on the frame you release a pinch we kick the captured ones outward with a burst (grab-and-throw, scaled across a swarm). Palm pushes radially outward — once, on the rising edge, as a shockwave. Fist multiplies all velocity by zero: a hard freeze. Everything else is the gentle idle pull from Stage 2:
function applyForces(dt, intensity) {
const ax = attractor.x, ay = attractor.y, az = attractor.z;
const freeze = gesture === 'fist';
const grab = gesture === 'pinch' ? 1 : 0;
for (let i = 0; i < N; i++) {
const p = i * 3;
if (freeze) { vel[p] = vel[p+1] = vel[p+2] = 0; continue; } // FREEZE
const dx = ax - pos[p], dy = ay - pos[p+1], dz = az - pos[p+2];
const d2 = dx*dx + dy*dy + dz*dz + 0.4; // soften the singularity
const inv = 1 / Math.sqrt(d2);
// pinch = hard inward GRAB; idle = gentle pull; both scale with 1/dist
const pull = (0.6 + grab * 5.0) * intensity / d2;
vel[p] += dx * inv * pull * dt;
vel[p+1] += dy * inv * pull * dt;
vel[p+2] += dz * inv * pull * dt;
}
}
// On the rising edge of a gesture (debounced), inject a one-shot impulse:
function onGestureEnter(g, intensity) {
if (g === 'palm') pushWave(attractor, 9.0 * intensity); // PUSH shockwave
if (g === 'release-pinch') pushWave(attractor, 5.0 * intensity); // fling on release
}
(d) The compose loop + gesture-gated audio
The loop ties it together: read a hand (camera or synthetic — one path), apply forces,
integrate the pool, color by age, fade the frame for trails, render. Gesture changes are
debounced against the last gesture so a one-shot impulse (and its note)
fires only on a real transition, not every frame the gesture is held. And audio is
gesture-gated: the context starts null and is only created by a user tap, so a
fresh load never tries — and is never allowed — to autoplay:
let audio = null; // stays null until the user taps
soundBtn.addEventListener('click', () => { // a real user gesture
audio = new (window.AudioContext || window.webkitAudioContext)();
});
function playNote(freq, type, gain) {
if (!audio) return; // gated: silent until unlocked
const o = audio.createOscillator(), g = audio.createGain();
o.type = type; o.frequency.value = freq;
g.gain.setValueAtTime(gain, audio.currentTime);
g.gain.exponentialRampToValueAtTime(0.0001, audio.currentTime + 0.5);
o.connect(g).connect(audio.destination); o.start(); o.stop(audio.currentTime + 0.5);
}
let lastGesture = 'idle';
renderer.setAnimationLoop((t) => {
const dt = Math.min(0.05, (t - prev) / 1000); prev = t;
const hand = usingCamera ? detect() : syntheticHand(t * 0.001, drivePos(t), routine(t));
if (hand) onLandmarks(hand, dt); // ONE path, synthetic or real
if (gesture !== lastGesture) { // DEBOUNCE: only on a real change
if (lastGesture === 'pinch') { onGestureEnter('release-pinch', I); playNote(523, 'triangle', 0.18); }
onGestureEnter(gesture, I);
if (gesture === 'palm') playNote(196, 'sine', 0.22);
if (gesture === 'fist') playNote(110, 'sawtooth', 0.10);
lastGesture = gesture;
}
applyForces(dt, I); integrate(dt); colorByAge();
fadeFrame(); // translucent black over last frame → trails
renderer.render(scene, camera);
});
Common pitfalls
- Scope creep kills the capstone. The temptation is to cram all 23 episodes in. Don't. One tight loop, one cloud, three gestures, one optional voice. A finished small thing beats an unfinished big thing — and the constraint is what makes it feel designed rather than dumped.
- Allocating inside the loop. The fastest way to turn 120fps into a
stutter is to
newa vector or push to an array sixty times a second. Pre-allocate every buffer once (the typed arrays in part a) and only ever write into them. If the fps counter sawtooths, the garbage collector is the prime suspect. - Audio needs a user gesture — never autoplay. Browsers suspend the
AudioContextuntil a real click/tap. Don't create it at load (it starts suspended and silent, and some browsers warn); create it inside the button handler. After that, gate every note behind a gesture so it never drones. - Gesture chatter without debounce. If you fire the impulse (and the note) every frame the gesture is held, an open palm spawns sixty shockwaves a second and the audio turns to mush. Fire only on the rising edge — compare to last frame's gesture — and put hysteresis on the pinch threshold so it doesn't flicker on the boundary.
- The synthetic hand has to actually perform. "Alive on first paint"
isn't a still frame. Drive the synthetic hand through a real routine — drift, pinch,
release, push, freeze — on a loop, feeding the same
onLandmarksas the camera. If the demo looks dead before you touch it, the whole promise falls apart. - Perf with particles. Forty thousand is a sweet spot on a laptop, but
it isn't free: keep the per-particle loop branch-light, do the color math only when trails
are on, and cap
devicePixelRatioat 2. Watch the counter as you scale N — and remember additive blending is fill-rate-bound, so big sprites cost more than more points.
Exercises
- Record the performance. Grab the canvas stream with
canvas.captureStream(60), feed it to aMediaRecorder, and add a record button that downloads a.webm. Now your hand-conducted clip is a file you can post. (Bonus: mix in the Web Audio output withaudioCtx.createMediaStreamDestination()so the notes are in the recording.) - A second gesture instrument. Add a fourth verb — a "point" (index
extended, others curled) that spins the whole cloud around the attractor like a vortex,
with a rising arpeggio. You already have the finger-extension count from part b; one more
branch in
readGestureand one more force mode inapplyForces. - Save a preset seed. The cloud is seeded from a single integer RNG seed. Expose it, let the user type one (or randomize), and put it in the URL hash so a link reproduces the exact same starting galaxy. Two people, same seed, same instrument — a shareable patch.
What's next — there is no next, and that's the point
This is the finale. Interactive Vision From Zero is complete — all 24 episodes. You started with a webcam frame as a flat array of pixels and ended conducting a living cloud of light with your bare hands. In between you learned the 21-landmark hand, the pinch, grab-and-throw, gesture classification, DOM control, the 33-point body and the 468-point face, AR filters, multi-person tracking, two-hand 3D manipulation, WebXR, training your own gestures, GPU effects, splats, multiplayer landmarks, and the One-Euro filter that smooths it all. You can now take any hand, body, or face motion and wire it to any response, from zero — which is the whole promise, delivered.
And it doesn't end here, it connects here. The exact skills behind this showpiece power the rest of the Visual Coding Universe: the Three.js series is the engine under this scene, the Shaders series is the language that made the particles glow, the Gaussian Splatting series is the photoreal cloud you reached into back in Episode 21, and the streaming and WebGPU work is how you'd take any of this multiplayer or scale it to millions of points. Pick a sibling, bring your hands, and keep building. You have, genuinely, everything you need.
You learned to see with code. Now go make something nobody's seen.