018: Skimming Stones

2026-10-18

So far everything has been made of separate pieces. First atoms: even the blast wave was a wave of atoms shoving one another. Then darts, walkers and the needles of a magnet, all pushed about by chance. This post has no atoms and no dice.

Drop a stone in a pond and a ring spreads out. Nothing travels with the ring: the water only moves up and down a little and the shape of that moving goes on across the pond. A wave is that shape. It is a thing in its own right and it does things that no single particle does. It passes straight through other waves and where two meet it can cancel.

The tank below is a sheet of water seen from above. Red is a crest, blue is a trough and dark is flat. Click anywhere to drop a stone or drag to skim one across the water.

Try these:

Show code
{
  // Shared WebGPU boilerplate: setup, buffers and the animation loop (lib/gpu.js)
  const gpu = await import(new URL("../lib/gpu.js", document.baseURI).href);
  const ui = await import(new URL("../lib/ui.js", document.baseURI).href);
  // The wave-tank kernels and bookkeeping shared by the wave posts (lib/wave.js)
  const wave = await import(new URL("../lib/wave.js", document.baseURI).href);

  // Controls are read live from their elements, so moving them does not restart
  // this cell.
  const sizeInput = viewof stoneSize;

  const { canvas, device, context, format } = await gpu.setup({
    width: 640,
    height: 360,
    resolution: "auto",
  });
  canvas.style.touchAction = "none";

  // The tank, in cells, and where things sit in it
  const W = 640;
  const H = 360;
  const cells = W * H;
  const beachWidth = 24; // cells of damping at each edge
  const C = 0.5; // the Courant number: cells a ripple travels in one step
  const speed = 100; // wave speed, in cells a second
  const maxSplashes = wave.maxSplashes;

  // --------------------------------------------------------------- the shaders
  // Step, splash and drawing kernels, the same ones the other wave-tank posts use
  const stepPipeline = wave.computePipeline(device, wave.stepWGSL(), "step");
  const splashPipeline = wave.computePipeline(device, wave.splashWGSL(), "splash");
  const showPipeline = wave.showPipeline(device, wave.showWGSL(), format, gpu.squareLayout);

  // --------------------------------------------------------------------- buffers
  // Three height arrays that take turns: one step ago, now, and the one being made
  const heights = wave.heightBuffers(gpu, device, cells);
  const snapshot = gpu.storageBuffer(device, new Float32Array(cells));
  const params = wave.paramBlock(device);

  // Bind groups for each way the three arrays can be taking turns
  const fixed = [{ binding: 0, resource: { buffer: params.buffer } }];
  const stepGroups = wave.turnGroups(device, stepPipeline, heights, fixed, wave.stepSlots);
  const splashGroups = wave.turnGroups(device, splashPipeline, heights, fixed, wave.splashSlots);
  const showGroups = wave.turnGroups(device, showPipeline, heights, fixed, wave.showSlots);
  const cornerBuffer = gpu.unitSquare(device);

  // ------------------------------------------------------------------- the state
  let turn = 0; // which of the three arrays is "one step ago"
  let stepCount = 0;
  const stones = []; // [x, y, height, radius] waiting to be dropped

  // A small stone is given a little more height so that its rings stay visible
  const drop = (x, y, height = 2) => {
    const radius = sizeInput.value;
    stones.push([x, y, height * Math.sqrt(6 / radius), radius]);
    if (stones.length > maxSplashes) stones.shift();
  };

  // Stones and skims
  let lastDrag = null;
  const place = (event) => {
    const box = canvas.getBoundingClientRect();
    return [((event.clientX - box.left) / box.width) * W, ((event.clientY - box.top) / box.height) * H];
  };
  canvas.addEventListener("pointerdown", (event) => {
    canvas.setPointerCapture(event.pointerId);
    lastDrag = place(event);
    drop(...lastDrag);
  });
  canvas.addEventListener("pointermove", (event) => {
    if (!lastDrag) return;
    const here = place(event);
    if (Math.hypot(here[0] - lastDrag[0], here[1] - lastDrag[1]) > 10) {
      lastDrag = here;
      drop(...here, 1.4);
    }
  });
  const release = () => (lastDrag = null);
  canvas.addEventListener("pointerup", release);
  canvas.addEventListener("pointercancel", release);

  // What the chart is built from
  const readback = gpu.readback(device, [{ buffer: snapshot, bytes: cells * 4 }]);
  const sampleEvery = 10; // frames between readbacks
  const keep = 400; // samples kept for the chart
  let frameCount = 0;
  let epoch = 0; // bumped when the tank is cleared, so a read in flight is dropped
  let peak = 0;
  let startStep = 0; // step at which the latest stone dropped
  const heightHistory = []; // {r, peak}: largest wave height against distance travelled

  const [heightHost] = charts.children;
  const draw = ui.plotter(Plot);

  function drawChart() {
    // A ring spreads over a circle that grows with its radius, so its height should
    // fall as 1/sqrt(r). The dashed line is that, matched to the first point past 40
    const first = heightHistory.find((d) => d.r >= 40);
    const spreading = first
      ? [40, 400].map((r) => ({ r, peak: first.peak * Math.sqrt(first.r / r) }))
      : [];
    draw(heightHost, {
      height: 200,
      x: { label: "distance the wave has travelled (cells)", grid: true, type: "log", domain: [10, 400] },
      y: { label: "largest wave height", grid: true, type: "log", domain: [0.01, 3] },
      marks: [
        Plot.line(spreading, {
          x: "r",
          y: "peak",
          stroke: "currentColor",
          strokeOpacity: 0.7,
          strokeDasharray: "4 3",
        }),
        Plot.line(heightHistory, { x: "r", y: "peak", stroke: "#FF4834", clip: true }),
      ],
    });
  }

  function onData(buffer) {
    const u = new Float32Array(buffer);
    let top = 0;
    for (let i = 0; i < cells; i++) top = Math.max(top, Math.abs(u[i]));
    peak = top;
    const r = (stepCount - startStep) * C;
    if (r > 10) heightHistory.push({ r, peak: Math.max(top, 1e-4) });
    if (heightHistory.length > keep) heightHistory.shift();
    drawChart();
  }

  // Empty the tank
  function clear() {
    epoch++;
    const zeros = new Float32Array(cells);
    for (const buffer of heights) device.queue.writeBuffer(buffer, 0, zeros);
    stones.length = 0;
    heightHistory.length = 0;
    peak = 0;
  }

  drop(W / 2, H / 2);

  const clearButton = ui.button({ label: "Clear", onClick: clear });
  const readout = ui.readout();
  drawChart();

  let owed = 0; // steps due but not yet done
  let lastTime = null;
  const groups = wave.groups(W, H);

  function frame(ms) {
    const dt = lastTime === null ? 0 : Math.min((ms - lastTime) / 1000, 0.1);
    lastTime = ms;

    owed += (speed / C) * dt;
    const count = Math.min(Math.floor(owed), 40);
    owed = Math.min(owed - count, 1);

    const splashes = stones.splice(0, maxSplashes);
    if (splashes.length) {
      startStep = stepCount;
      heightHistory.length = 0;
    }

    params.write({
      width: W,
      height: H,
      ...wave.beach({ C, width: beachWidth }),
      gain: wave.heightGain,
      splashes,
    });

    const encoder = device.createCommandEncoder();
    const compute = encoder.beginComputePass();
    if (splashes.length) {
      compute.setPipeline(splashPipeline);
      compute.setBindGroup(0, splashGroups[turn]);
      compute.dispatchWorkgroups(groups.x, groups.y);
    }
    compute.setPipeline(stepPipeline);
    for (let s = 0; s < count; s++) {
      compute.setBindGroup(0, stepGroups[turn]);
      compute.dispatchWorkgroups(groups.x, groups.y);
      turn = (turn + 1) % 3;
    }
    compute.end();
    stepCount += count;

    const sample = !readback.pending && ++frameCount % sampleEvery === 0;
    if (sample) {
      encoder.copyBufferToBuffer(heights[(turn + 1) % 3], 0, snapshot, 0, cells * 4);
      readback.copy(encoder);
    }

    const pass = gpu.beginRenderPass(encoder, context);
    pass.setPipeline(showPipeline);
    pass.setBindGroup(0, showGroups[turn]);
    pass.setVertexBuffer(0, cornerBuffer);
    pass.draw(6);
    pass.end();
    device.queue.submit([encoder.finish()]);

    if (sample) {
      const mine = epoch;
      readback.read((buffer) => {
        if (mine === epoch) onData(buffer);
      });
    }

    if (frameCount % 6 === 0) {
      readout.textContent = `largest wave ${peak.toFixed(2)}`;
    }
  }

  gpu.run(invalidation, device, frame);

  // The canvas with the controls laid over its corner
  yield ui.stage(canvas, [sizeInput, clearButton, readout]);
}

Analysis

The largest wave height in the tank against how far the wave has gone, both on a logarithmic scale. After a stone the line falls along the dashed one, which is the height of a ring that gets weaker as 1/\sqrt{r} because the same wave has to cover a circle whose length grows with r. The height squared is what a wave carries and it is shared out round that circle. On a log scale a power is a straight line, here with a slope of -1/2. Near the end the line drops faster where the ring reaches the beach.

How the computer makes ripples

The tank is a grid of 640 by 360 cells and each cell holds one number: the height of the water there. The rule is the same one a ball on a spring follows. A cell is pulled towards the average of its four neighbours and it carries on moving the way it was already going. That is all a wave is in the end: each cell is pulled by its neighbours and they are pulled by it.

To step forward in time the rule needs three things for every cell: its height now, its height one step ago and the heights of its four neighbours now. The GPU takes one thread per cell (all 230,400 at once) and each writes its cell’s new height into a third array. Then the three arrays swap roles with no copying: “the one before” becomes “the one before that”, “now” becomes “the one before” and the new heights become “now”.

At the edges the tank has beaches. Close to the border the rule gets a little damping that grows towards the edge so a wave that reaches it slowly dies instead of bouncing back. Without them the surface soon becomes a mess. Real ripple tanks often have sloping edges or sponge for the same reason.

The wave equation

Jean le Rond d’Alembert wrote down the wave equation in 1747 for a vibrating string. For a sheet of water with the height written u(x, y, t) and the wave speed c it is

\frac{\partial^2 u}{\partial t^2} = c^2 \, \nabla^2 u.

On a grid with spacing \Delta x and time step \Delta t, each cell is updated with

u^{n+1}_{ij} = 2 u^n_{ij} - u^{n-1}_{ij} + C^2 \sum_{\text{4 neighbours}} \left( u^n_{\text{nb}} - u^n_{ij} \right),

where C = c \, \Delta t / \Delta x is the Courant number: the distance a ripple travels in one step in cells. Here it is 0.5 and it cannot be much bigger. We’ll find out why later.

Sources

  • d’Alembert, J. le R. (1747), “Recherches sur la courbe que forme une corde tenduë mise en vibration”, Histoire de l’Académie royale des sciences et belles lettres de Berlin 3, 214 to 219 (published 1750).
  • Feynman, R. P., Leighton, R. B. and Sands, M. (1963), The Feynman Lectures on Physics, volume I, chapter 47, Sound. The wave equation.