Three.js From Zero · Article s17-03

The Double Pendulum — Watching One Become Five Hundred

500 pendulums released a ten-millionth of a radian apart: RK4 integration in doubles, a manual afterimage feedback loop for long-exposure trails, and an empirical Lyapunov horizon in the stats bar. Part of the MasterAllArts Creative 3D Roadmap.

Part of the MasterAllArts Creative 3D Roadmap .

← Three.js From Zero S17-03 · Order & Chaos

Season 17 · Article 03 · Order & Chaos

Hang a pendulum from a pendulum. That's the entire apparatus — two rods, two weights, gravity. Now release five hundred of them at once, every one identical except for a tilt of one ten-millionth of a radian, and watch: for several swings they move as a single bright blade, then a blur, then a storm of ribbons painting the whole reachable sky. Chaos is usually told; this is the demo where you get to watch the telling.

— fps · 500 pendulums · spread —

The white armature is pendulum #0; the colored swarm is the tips of all 500, joined into a ribbon so you can see the ensemble as one object. Hit release and time the show: the spread readout in the corner counts how far the family has drifted apart. Drop the offset to 10⁻⁹ — a difference a thousand times smaller — and they buy themselves only a few extra seconds of agreement. That's the signature of chaos: error grows exponentially, so heroic precision buys linear time.

Why this is THE chaos machine

The Lorenz attractor needed a weather model; the double pendulum needs a hardware store. Two degrees of freedom (the two angles), no randomness, no driving force, energy perfectly conserved — and still unpredictable beyond a horizon of seconds, because the equations couple the angles through trigonometric terms that fold trajectories back on themselves. It's the cheapest certified-chaotic system in physics, which is why every science museum has one bolted to a wall.

For art purposes the key property is the ensemble: one pendulum is a fidgety line; five hundred near-identical ones are a fluid — a curve that stretches and folds like taffy. Stretching + folding is literally what chaos is, and the ribbon makes it visible.

Step 1 — RK4: when Euler isn't good enough anymore

Season 16 integrated everything with Euler and I told you it was fine for art. Here it isn't. The double pendulum conserves energy exactly, and Euler's overshoot injects energy every step — within a minute your gentle swing becomes a propeller. Runge–Kutta 4 samples the derivative four times per step and blends them, canceling the leading error terms:

function rk4(state, dt) {
  const a = deriv(state);
  const b = deriv(add(state, scale(a, dt / 2)));
  const c = deriv(add(state, scale(b, dt / 2)));
  const d = deriv(add(state, scale(c, dt)));
  return add(state, scale(sum(a, 2,b, 2,c, d), dt / 6));   // (a + 2b + 2c + d)/6
}

Same shape as Euler — state in, state out — just four derivative calls instead of one. The derivative itself is the textbook double-pendulum formula (equal masses, equal arms); it's twelve lines in the demo source and the only part you'd ever need to swap for a different mechanism. Rule of thumb the series now owns: Euler when it just has to look right, RK4 when energy has to stay honest.

Step 2 — The ensemble is three Float64Arrays

const t1 = new Float64Array(N).fill(angle0);
const t2 = new Float64Array(N);
for (let i = 0; i < N; i++) t2[i] = angle0 + i * 1e-7;   // the whole experiment
const w1 = new Float64Array(N), w2 = new Float64Array(N); // start at rest

Note Float64Array, not 32 — the initial offsets are 10⁻⁷ and we intend to watch them grow from there, so we need precision below the perturbation. (The same reasoning, in the other direction, as the Mandelbrot precision wall: know where your epsilon lives.) Visualization stays float32; only the physics runs in doubles.

Step 3 — Feedback trails: the manual afterimage

The long-exposure look is a render-to-texture feedback loop — the video-feedback effect, tamed. Two render targets ping-pong; each frame you draw last frame, slightly dimmed and then the fresh geometry on top:

// 1. dim the past:    accumWrite ← accumRead × fade
quad.material = fadeMaterial;            // gl_FragColor = texture2D(uTex,vUv) * uFade
renderer.setRenderTarget(accumWrite);
renderer.render(quadScene, clipCamera);

// 2. stamp the present on top (no clear!)
renderer.render(pendulumScene, worldCamera);

// 3. swap, then show accumRead on screen

The fade factor is the exposure knob: 0.90 keeps a half-second of history, 0.99 keeps ten seconds and the canvas fills with phosphor. This is the third member of the ping-pong family you now own — reaction–diffusion evolved a field, the wave tank carried two time-slices, and this one accumulates pictures. Post-processing libraries call it AfterimagePass; now you know it's eight lines.

Pitfall: autoClear will eat your trails. Step 2 only works because the renderer doesn't wipe the target between the fade pass and the geometry pass — renderer.autoClear = false, clear manually when you decide. If your feedback loop shows only the current frame, autoClear is almost always the thief. (Same flag, same reason, as the Physarum deposit pass.)

Step 4 — Reading the picture

  • The blade (first seconds): all 500 tips agree; the ribbon is a point pretending to be a curve.
  • The smear: differences reach visible scale — the ribbon stretches into an arc. Stretching = positive Lyapunov exponent, live.
  • The fold: the arc wraps over the flip-over threshold — some pendulums go over the top, neighbors don't — and the ribbon tears into branches. This is the decision boundary of chaos.
  • The storm: spread saturates near π; the family has fully forgotten it was ever one pendulum. The stats bar freezes the time when spread first passes 3 rad — that's your empirical Lyapunov horizon, and you can watch the offset slider move it logarithmically.

What the controls teach

  • angle — below ~110° the system is mostly orderly (the ribbon breathes but doesn't tear); past 140° flip-overs dominate and decorrelation is brutal. Order and chaos share one slider.
  • offset — each notch is 10× more precision and buys roughly the same few extra seconds. Exponential divergence, felt in the hands.
  • exposure — pure aesthetics: streak length. Notice it changes nothing about the physics, only the memory of it.

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';

// ensemble state in Float64Arrays                   (Step 2)
// per frame: RK4 ×2 substeps for all 500            (Step 1)
//            fade pass → geometry pass → swap        (Step 3)
// tips as Points + one ribbon Line, color by index
</script>