Three.js From Zero · Article s16-09

Wave Interference — A Ripple Tank Made of Pixels

The actual wave equation on the GPU: leapfrog time-stepping with (h, hPrev) packed into texture channels, tap-to-splash, rain mode, and a lit heightfield that reads as water. Part of the MasterAllArts Creative 3D Roadmap.

Part of the MasterAllArts Creative 3D Roadmap .

← Three.js From Zero S16-09 · Beautiful Math

Season 16 · Article 09 · Beautiful Math

Before computers, physics classrooms had a glass tray of water, a lamp, and a motor that tapped the surface. The ripple tank taught a century of students the deepest fact about waves: they pass through each other, and where they meet, they simply add. This is that tray, rebuilt as a GPU simulation of the actual wave equation — tap to splash, drag to draw, turn on the rain, and watch interference paint its nodal cathedrals.

— fps · — steps/frame · 512×320

Tap anywhere for a splash; drag to drag a wake across the surface. Drop two taps near each other and look between them: alternating lanes of motion and dead-calm — those still lanes are nodal lines, places where one wave's crest always meets the other's trough. Nothing cancels the water; the waves cancel each other. Then enable rain, lower the damping, and let the whole tank become a shimmering superposition of forgotten splashes.

The wave equation is "acceleration = curvature"

Everything a ripple tank does comes from one line of physics. Each point of the surface accelerates toward the average of its neighbors:

∂²h/∂t² = c² · ∇²h        // height accelerates proportional to local curvature

If a point sits below its neighbors (positive curvature), it gets pulled up; overshoot, and it gets pulled back down. That overshoot is why water rings instead of just leveling — and why the same equation describes drumheads, sound, light, and earthquake waves. You already met the Laplacian ∇² in reaction–diffusion; there it fed velocity (diffusion smooths), here it feeds acceleration (waves ring). One operator, two universes.

Step 1 — Leapfrog: the time-stepper in one line

Discretize acceleration with three time samples — next, current, previous — and solve for next:

next = 2.0 * curr - prev + c2 * laplacian(curr);   // leapfrog / Verlet
next *= damping;                                    // the tray's friction

You've seen this skeleton before: it's the same Verlet idea behind every cloth and rope sim. No velocity is stored anywhere — velocity lives implicitly in the difference between current and previous. Which raises the rendering question: the reaction–diffusion rig ping-pongs two textures, but a second-order equation needs two past states. Do we need three buffers?

Step 2 — Pack time into the channels

No. A texel has four channels and we're using one. Store the field's present in R and its past in G, and the two-buffer ping-pong rig carries a second-order PDE unchanged:

vec2 s = texture2D(uTex, vUv).rg;        // s.r = h(now), s.g = h(one step ago)
float lap = /* 4-neighbor stencil on .r */;
float next = (2.0 * s.r - s.g + uC2 * lap) * uDamp;
gl_FragColor = vec4(next, s.r, 0.0, 1.0);  // today becomes yesterday

That last line is the trick worth remembering: vec4(next, s.r, …) — each pass writes the new value and archives the old one, shifting the timeline one slot per step. GPGPU state design is mostly deciding what lives in which channel.

Step 3 — The stability cliff

Pitfall: the Courant condition is a hard law. The speed slider is c², and it stops at 0.45 because an explicit 2D wave step is only stable while c² ≤ 0.5 (information must not cross more than one cell per step). Push past it and the sim doesn't get faster — it explodes into checkerboard noise within a second. Every grid simulation has a cliff like this; learn to recognize the checkerboard, because it always means "your timestep outran your grid," and the fix is always the same: smaller dt, more substeps, or a bigger grid cell.

Step 4 — Lighting a heightfield

Raw height mapped to color looks like a weather map. Water reads as water because of how it shades — so the display pass derives a surface normal from the height gradient and fakes a sun:

float hx = h(vUv + texelX) - h(vUv - texelX);     // gradient by central difference
float hy = h(vUv + texelY) - h(vUv - texelY);
vec3 n = normalize(vec3(-hx * 14.0, -hy * 14.0, 1.0));
float diff = max(dot(n, normalize(vec3(-0.4, 0.6, 0.8))), 0.0);
float spec = pow(max(dot(reflect(-lightDir, n), vec3(0,0,1)), 0.0), 40.0);

Gradient → normal → diffuse + specular glint: this is the universal recipe for making any scalar field look physical — water, terrain, embossed paper, brushed metal. It's also exactly what normal maps do; you've just computed one live instead of loading it from a file.

Step 5 — Splashes are Gaussians

The brush adds a smooth dimple, not a single-texel spike — a hard spike contains every frequency the grid can carry and instantly rings with gridding artifacts. A Gaussian splash is band-limited and round:

float d2 = dot((vUv - uBrush.xy) * vec2(uAspect, 1.0), …);
next -= uBrush.w * exp(-d2 / (uBrush.z * uBrush.z));   // press the surface down

Rain mode is six lines of JavaScript: every few hundred milliseconds, write a random position and strength into the brush uniform for one frame. The GPU neither knows nor cares whether a human or a timer is painting.

What to try

  • Two taps, close together — the classic two-source interference pattern; count the nodal lines fanning out between them.
  • Drag slowly vs. flick fast — a slow drag makes a V-shaped wake (you're a boat); a fast flick outruns the waves entirely (you're supersonic, and that cone is a Mach cone).
  • Damping at 0.999 + rain — the tank fills with standing chaos; pause the rain and watch the box modes emerge as everything else dies.
  • Watch a reflection — waves bounce off the edges because the boundary texels clamp; an edge that can't move is a mirror.

The skeleton

<script type="importmap">
{ "imports": {
    "three": "https://unpkg.com/three@0.170.0/build/three.module.js",
    "three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/" } }
</script>
<script type="module">
import * as THREE from 'three';

// two HalfFloat targets, (h, hPrev) packed in RG        (Step 2)
// per frame: N× { leapfrog pass → swap }                 (Step 1)
//            display pass: gradient → normal → light     (Step 4)
// pointer/rain → Gaussian brush uniform                  (Step 5)
</script>