Interactive Vision From Zero · Episode 20

GPU-Accelerated Vision Effects

GPU-Accelerated Vision Effects is Episode 20 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 .

Episode 20 · Interactive Vision From Zero

Bend pixels with your bare hand. In this episode your fingertip stops being a dot drawn on top of the picture and becomes a force inside the picture: ripples chase it across the screen, a glow pools where it goes, the surface warps away from your palm, and when you pinch you punch a shockwave into a flowing field. No drawing API does this — every pixel is computed in parallel on the GPU, and the only thing the GPU knows about your hand is two numbers we hand it every frame.

This is where the two halves of the universe meet: the vision toolkit (21 hand landmarks from a webcam) plugs straight into the shader toolkit (a fullscreen ShaderMaterial with GLSL running per-pixel). We take the index fingertip, normalize it, mirror it, and shove it into a uHand uniform. The fragment shader does the rest — for a million pixels at once, at well over a hundred frames a second. It's alive the instant the page loads on a synthetic hand, so flip through all six stages first, then point your webcam at it.

0 fps
move your mouse · or use your camera ↗
synthetic hand · click to use your camera
🔒 runs on-device · nothing leaves your machine
ShaderMaterial · GLSL · uHand uniform
A fullscreen shader: every pixel is computed in parallel on the GPU.

What you're looking at

A single quad fills the frame, painted by one fragment shader. There is no scene, no lights, no geometry to speak of — just a program that runs once per pixel and decides its color from a handful of uniforms: the time, the resolution, the chosen palette, and — the star of the show — uHand (your fingertip, in 0→1 screen space) and uPinch (how closed your thumb-and-index are, 0→1). Every stage is the same machine with more of the shader switched on. Drag your mouse to puppet the synthetic hand; the pinch animates on its own so you can see the ripples without a camera.

Stage 1 — A fullscreen shader

The baseline: a slow animated gradient with a little flowing noise, ignoring your hand entirely. This is the canvas we'll deform. Notice it's already moving on first paint — that motion is just uTime feeding a couple of sine waves. If you've done the shaders series, this is home turf; if not, the mental model is simply "for each pixel, given its position and the clock, return an RGB."

Stage 2 — Fingertip → uniform

Now the shader reads uHand. We compute the distance from each pixel to your fingertip and turn it into a soft glow — bright at the tip, fading with an exp() falloff. Move the mouse (or your hand): a pool of light follows the index tip. This is the entire trick of the episode in one line of GLSL — distance(uv, uHand) — and everything else is a variation on it.

Stage 3 — Ripple on pinch

Pinch your thumb and index together (the synthetic hand does this for you on a timer) and a ring expands outward from your hand like a stone dropped in a pond. Each pinch injects a ripple: we store its origin and birth-time on the JS side, pass the active ripples to the shader, and draw an animated sin() ring whose radius grows with age and whose brightness fades out. A few ripples can be alive at once — watch them overlap and interfere.

Stage 4 — Displacement

So far we've only changed color. Now we change where the pixel samples from. We push the lookup coordinate away from your hand — a radial shove that falls off with distance — so the underlying pattern bulges outward around your fingertip like a lens, or a finger pressed into a sheet of rubber. This is the seed of every heat-haze, glass, and shockwave effect: don't repaint the image, bend the coordinates you read it with.

Stage 5 — Fluid field

The hand stops poking and starts stirring. We build a flowing field from layered, time-advected noise and let your fingertip drag it — a cheap, single-pass nod to reaction-diffusion and fluid sims (no ping-pong buffers, just clever noise). Move slowly to comb the field; pinch to dump energy into it. It's not a physically accurate solver, but it reads as fluid, and it stays cheap enough to never drop a frame.

Stage 6 — Full effect

Everything at once, plus a palette: the flowing field underneath, the displacement lens around your hand, ripples on every pinch, and the fingertip glow on top, all tinted by the palette selector. This is the shareable look — the "bend pixels with your bare hand" clip. Switch the palette dropdown between aurora, ember, and ice and find your favorite, then turn on your camera and record yourself conducting it.

How the code works

Four moving parts: the ShaderMaterial with its hand uniforms; the per-frame uniform update (with the all-important mirror); the fragment GLSL that turns distance-to-hand into glow and ripples; and the shared synthetic→camera path that means none of the above cares where the landmarks came from.

(a) The ShaderMaterial with a uHand + uPinch uniform

A fullscreen shader in Three.js is a plane that fills clip space, drawn with an orthographic camera (or any camera — we just bypass projection in the vertex shader). The interesting state lives entirely in uniforms. We declare uHand as a vec2 (the fingertip in 0→1 screen space), uPinch as a float, and a small fixed-size array of uRipples (each vec3 = x, y, age):

// A quad that fills the screen, painted by one fragment shader.
const uniforms = {
  uTime:    { value: 0 },
  uRes:     { value: new THREE.Vector2(1, 1) },
  uHand:    { value: new THREE.Vector2(0.5, 0.5) }, // fingertip, 0→1 screen space
  uPinch:   { value: 0 },                              // 0 = open, 1 = closed
  uStage:   { value: 0 },
  uPalette: { value: 0 },
  uRipples: { value: Array.from({ length: 6 }, () => new THREE.Vector3()) },
  uRippleN: { value: 0 },
};

const material = new THREE.ShaderMaterial({
  uniforms,
  vertexShader:   /* pass uv straight through, no projection */ vert,
  fragmentShader: frag,
});
// A 2×2 plane in clip space; the vertex shader sets gl_Position = vec4(position, 1).
scene.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material));

(b) Updating the uniforms each frame from the landmark — with the mirror

This is the bridge. Each frame, onLandmarks(hand) receives the 21-point array (synthetic or real — same shape) and copies two derived numbers into the uniforms. The index tip is landmark 8; the pinch is the thumb-tip-to-index-tip distance, normalized by hand size. The mirror is the single most important line: we flip X with 1 - x so moving your hand right warps the right side of the screen. We also smooth the hand toward its target so raw landmark jitter doesn't make the glow buzz:

const INDEX_TIP = 8, THUMB_TIP = 4, INDEX_MCP = 5, PINKY_MCP = 17;

function onLandmarks(hand) {
  const tip = hand[INDEX_TIP];
  // MIRROR: selfie view — flip X so the field reacts on the correct side.
  const hx = 1 - tip.x;        // ← without this, everything is backwards
  const hy = tip.y;             // y already points down in both shader and image

  // smooth toward the target (lerp) so the glow doesn't jitter
  const u = uniforms.uHand.value;
  u.x += (hx - u.x) * 0.35;
  u.y += (hy - u.y) * 0.35;

  // pinch = thumb→index distance, scaled by hand size, with hysteresis
  const span = dist(hand[INDEX_MCP], hand[PINKY_MCP]) || 0.0001;
  const d    = dist(hand[THUMB_TIP], hand[INDEX_TIP]) / span;
  const pinch = THREE.MathUtils.clamp(1 - (d - 0.25) / 0.85, 0, 1);
  uniforms.uPinch.value = pinch;

  // rising edge → inject a ripple at the hand (see part c)
  if (pinch > 0.7 && !pinching) { spawnRipple(u.x, u.y); pinching = true; }
  if (pinch < 0.4) pinching = false;   // separate on/off = hysteresis
}

(c) The fragment GLSL: distance-to-hand glow + ripple

Here's the heart of it. vUv is the pixel's 0→1 coordinate; we correct it by aspect ratio so distances are circular, not oval. The glow is an exp() of the distance to uHand. The ripple loop walks the active ripples, and for each draws a thin animated ring whose radius is its age and whose brightness decays — classic sin(distance·k − age·speed) with a falloff:

uniform vec2  uHand;
uniform float uPinch;
uniform vec3  uRipples[6];   // each: xy = origin, z = age in seconds
uniform int   uRippleN;
varying vec2  vUv;

void main() {
  vec2 uv  = vUv;
  float aspect = uRes.x / uRes.y;
  vec2 p   = vec2(uv.x * aspect, uv.y);     // aspect-correct so circles are round
  vec2 h   = vec2(uHand.x * aspect, uHand.y);

  // fingertip glow: bright at the tip, soft exponential falloff
  float d    = distance(p, h);
  float glow = exp(-d * 9.0) * (0.6 + 0.8 * uPinch);

  // ripples: sum a thin expanding ring per active ripple
  float ring = 0.0;
  for (int i = 0; i < 6; i++) {
    if (i >= uRippleN) break;            // only the live ones
    vec2  o   = vec2(uRipples[i].x * aspect, uRipples[i].y);
    float age = uRipples[i].z;
    float rd  = distance(p, o);
    float wave = sin(rd * 40.0 - age * 9.0);
    float band = smoothstep(0.06, 0.0, abs(rd - age * 0.6)); // follow the front
    ring += wave * band * exp(-age * 1.6);    // fade with age
  }

  vec3 col = palette(uPalette, glow + ring * 0.5 + flow(p, uTime));
  gl_FragColor = vec4(col, 1.0);
}

Displacement (Stage 4) is the same idea applied to the lookup: before sampling the flow field, push p away from h by normalize(p - h) * exp(-d·k) * strength. You're not adding light, you're moving the coordinate you read — which is why the whole pattern bulges instead of brightening.

(d) The synthetic → camera shared path

The shader never knows whether the hand is real. A synthetic generator emits the exact 21-landmark structure MediaPipe does, so the same onLandmarks runs in both modes. The camera is lazy-loaded — MediaPipe is only fetched when you click the button, wrapped in try/catch so a camera-less load stays alive on the synthetic hand with zero network calls and zero errors:

let usingCamera = false, landmarker = null, video = null;

async function enableCamera() {
  try {
    // dynamic import — NEVER at top level, or a webcam-less load errors
    const { HandLandmarker, FilesetResolver } = await import(MP_URL);
    const fileset = await FilesetResolver.forVisionTasks(MP_WASM);
    landmarker = await HandLandmarker.createFromOptions(fileset, {
      baseOptions: { modelAssetPath: HAND_TASK, delegate: 'GPU' },
      runningMode: 'VIDEO', numHands: 1,
    });
    const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
    video = document.createElement('video');
    video.srcObject = stream; video.playsInline = true; await video.play();
    usingCamera = true;
    setStatus('camera live · on-device, nothing uploaded');
  } catch (err) {
    setStatus('camera unavailable — staying on synthetic (' + err.name + ')');
    usingCamera = false;          // fall back gracefully; the demo keeps running
  }
}

function tick(t) {
  let hand;
  if (usingCamera && landmarker && video.readyState >= 2) {
    hand = landmarker.detectForVideo(video, performance.now()).landmarks?.[0] || null;
  } else {
    hand = syntheticHand(t * 0.001, mouseActive ? mousePos : autoPos(t * 0.001), poseOpts(t));
  }
  if (hand) onLandmarks(hand);        // ONE downstream path for synthetic + real
}

Common pitfalls

  • The field reacts on the wrong side. The #1 bug. Landmark X is in image space (origin top-left, x→right); your screen is a selfie mirror. Flip it with 1 - x once, where you read the landmark — not in the shader, or you'll double-flip. Get this wrong and your hand goes left while the glow goes right.
  • Forgetting to update uniforms each frame. A ShaderMaterial reads its uniforms every draw, but you have to write them. If the glow is frozen at the center, you set uHand once at setup and never again. Update it inside the loop, every frame.
  • Distances come out oval. UVs are 0→1 on both axes, but the canvas is 16:10, so a circle in UV space is a squashed ellipse on screen. Multiply the X of both the pixel and the hand by the aspect ratio before distance().
  • Shader gets expensive fast. Every pixel runs your whole main(). Loops over ripples, stacked noise octaves, and per-pixel pow() add up. Keep the ripple array small (≤6), cap noise octaves, and prefer exp()/smoothstep() over big loops. Watch the fps counter as you add lines.
  • Ripple bookkeeping leaks. Spawn a ripple on the rising edge of the pinch (with hysteresis), not every frame the pinch is held — otherwise you spawn sixty a second. Age them on the CPU, drop the dead ones, and only upload the live count via uRippleN so the shader's for loop exits early.
  • GLSL-in-Three.js gotchas. Uniform names must match between JS and GLSL exactly; arrays need a fixed compile-time length (uRipples[6]); a vec2 uniform wants a THREE.Vector2, not a plain object; and a varying must be declared in both the vertex and fragment shaders or it's a silent black screen.

Exercises

  1. Multiple fingertips, multiple sources. Pass all five tips (4, 8, 12, 16, 20) as a uTips[5] array and sum a glow per tip. Now every finger is a light. Spread your hand and watch five pools bloom — then curl them into one.
  2. Color by hand speed. Track the fingertip's velocity on the JS side (the delta of uHand between frames), pass it as uSpeed, and drive the palette hue or the glow intensity with it. Slow hand → cool and calm; fast flick → a hot streak.
  3. A metaball field from all five tips. Instead of summing separate glows, sum 1.0 / distance² from each tip and threshold the total with smoothstep. The blobs merge as your fingers come together — a classic metaball field, driven by your hand. Cross-link this with the splats in the next episode for a gooey 3D version.

What's next

Episode 21 — Hands Meet Splats. We swap the flat fullscreen shader for a cloud of Gaussian splats in real 3D (the procedural splat cloud from the Gaussian Splatting series), and let your pinch push and scoop the blobs around in space. The distance-to-hand force you built today becomes a 3D force field; the ripple becomes a shockwave through a point cloud. Same idea — hand drives GPU — one dimension up. (See also the Shaders From Zero series for the GLSL foundations under today's effects.)