I built Spin Lab, an interactive web app for learning table-tennis spin - Magnus effect in flight, bounce kick, why holding a still racket gets punished, sidespin, corkscrew spin, serves, and return strokes.
The thing that made building it actually work was turning the lesson claims into unit tests. Whenever a chapter says something like “at this pace topspin lands mid-table with room to spare, the flat ball barely scrapes the end line, and backspin floats off”, there is a test in tools/check.mjs that runs the exact same physics code in Node and checks if the sentence holds:
report("ch2 default: topspin lands mid-table with margin",
top.outcome === "lands" && top.bounce.x < 1.0);
report("ch2 default: flat ball lands but only just",
flat.outcome === "lands" && flat.bounce.x > 1.0);
report("ch2 default: backspin floats long", back.outcome === "long");
There are 228 assertions like this. If I change air drag and some line in Chapter 2 stops being true, the test fails and points straight at the broken claim.
The codebase is split like this:
physics.js pure math. no DOM, no THREE, no rendering
|
scenarios.js simulate -> precomputed frame timelines
|
player.js plays a timeline back
|
world.js three.js scene. only draws what it is handed
|
chapters/* copy, controls, per-frame dressing
tools/*.mjs run scenarios.js headless in node, assert the numbers
I kept physics.js with zero imports - no Three.js, no browser globals, nothing. That way Node runs the exact same file as the browser and gets bit-identical numbers without needing jsdom or headless Chrome.
I also avoided running the simulation live inside requestAnimationFrame. When you move a slider, the app computes the whole shot upfront into an array of frames and the player just scrubs through that array:
export function simulateFrames(initial, { dt = SIM_DT, maxTime = 4, until = null } = {}) {
const state = cloneState(initial);
const frames = [makeFrame(state, 0)];
for (let i = 1; i <= Math.ceil(maxTime / dt); i++) {
const { prev, events } = stepWithEvents(state, dt, options);
frames.push(makeFrame(state, i * dt, events[0]?.type ?? null));
if (until?.(frames.at(-1), { prev, events, index: i })) break;
}
return { frames, events, final: cloneState(state) };
}
Having the whole trajectory sitting in memory before frame 1 renders makes slow-mo, scrubbing backwards, and drawing the landing spot straightforward.
For collisions, a table-tennis ball hits five surfaces: your side of the table, the net, the far side, the server’s bat, and the receiver’s bat. I ran all five through one impulse solver so table bounce and racket contact could never disagree on spin:
export function resolvePlaneImpact(state, normal, surfaceVelocity, restitution, friction) {
const n = normalizeVec(normal, { x: 0, y: 1, z: 0 });
const radiusVector = scaleVec(n, -BALL_R);
const angularVelocity = vec(state.spinX || 0, state.spinY || 0, state.spin);
const contactVelocity = addVec(vec(state.vx, state.vy, state.vz),
crossVec(angularVelocity, radiusVector));
const relativeVelocity = subVec(contactVelocity, surfaceVelocity);
const normalSpeed = dotVec(relativeVelocity, n);
if (normalSpeed >= 0) return;
const normalImpulseMag = -(1 + restitution) * normalSpeed * BALL_M;
// Coulomb friction cap, with the effective inverse mass of a sphere that
// can both translate and spin up.
const effectiveInvMass = (1 / BALL_M) + (BALL_R * BALL_R / BALL_I);
const tangentialImpulseMag = Math.min(tangentialSpeed / effectiveInvMass,
friction * normalImpulseMag);
// ... apply, then derive the spin change from the torque
const deltaAngularVelocity = scaleVec(crossVec(radiusVector, totalImpulse), 1 / BALL_I);
}
Math.min(tangentialSpeed / effectiveInvMass, friction * normalImpulseMag) handles grip vs slip. Below the friction cap the rubber grips the ball; above it the ball slips. Table bounce and racket hit use the exact same function with different restitution, friction, and surfaceVelocity.
Four places the simulator caught my own mistakes
First was corkscrew spin. Magnus force in flight is crossVec(omega, velocity). When I wrote Chapter 6 (corkscrew spin, axis pointing forward along x like a rifle bullet), I wrote that the ball “flies dead straight” in the air since omega x velocity is zero when the two vectors are parallel, and only kicks sideways after hitting the table. Then I wrote a test for it:
report("ch6 spin axis along the flight path produces zero Magnus force",
Math.hypot(corkMagnus.x, corkMagnus.y, corkMagnus.z) < 1e-9);
The test failed - the ball actually curved 8.2 cm sideways in the air. A served ping-pong ball drops and rises at around 22 degrees off horizontal, so a horizontal spinX axis is 22 degrees off the velocity vector v, leaving sin(22°) ≈ 38% of the sideways Magnus force alive in flight. I had to rewrite that chapter to explain why corkscrew spin still drifts about a third as much as pure sidespin in the air.
Second was the serve presets. In the serve chapter I built a “contact clock” UI where you drag a dot around the ball (12 o’clock for topspin, 6 o’clock for backspin, 3/9 for sidespin), and I coupled the bat angle and brush angle together from that one clock position:
faceDeg: -26 * edge * Math.cos(rad),
brushDeg: 62 * edge * Math.cos(rad),
swingSideDeg: 52 * edge * Math.sin(rad)
Four of my eight serves (pendulum, ghost, kicker, fast long) kept hitting the net or flying long. I got tired of tweaking numbers by hand and wrote a script to grid-search 19,152 combinations of clock angle, swing speed, toss height, and rubber grip for a landing backspin serve:
outcomes: { net: 15498, inplay: 408, short: 321, long: 2895, over: 30 }
landed: 408
landed with ANY backspin: 0
Not a single one landed with backspin. Coupling faceDeg and brushDeg locked their ratio at -26/62 = -0.42, so brushing down at 6 o’clock kept the bat face too vertical instead of opening underneath the ball, launching it downward at vy = -0.8 m/s straight into the net. Once I decoupled bat angle from the brush clock (which is how real table tennis works anyway) and re-ran the search, all eight serves landed:
| serve | clock | bat | speed | result |
|---|---|---|---|---|
| Pendulum | 135 deg | open 50 | 12 | half-long, 37 rps back + side |
| Tomahawk | 80 deg | closed 18 | 8 | half-long, side + light top |
| Kicker | 350 deg | closed 18 | 8 | long, 46 rps topspin |
| Ghost | 170 deg | open 43 | 10 | short, 38 rps back |
| Float | 180 deg | open 28 | 5 | short, 2 rps |
Funny result from that search: Ghost and Float ended up with almost identical swing mechanics, differing mainly in rubber grip (0.95 vs 0.12), which is how players actually disguise a no-spin float serve.
Third was the fast long serve. I had written “no brush, no spin, all speed”. When I tried to find a zero-spin fast serve in the simulator that clears the net after bouncing on your side and still lands before the far baseline, none existed. Gravity alone cannot curve the arc down fast enough at high speed; you need roughly 15-30 rps (1000-2000 rpm) of topspin to pull it onto the far side. I rewrote that copy too.
Fourth was the serve-return advisor. At first I just had hardcoded coaching strings checked with regex tests (/decision/i.test(advice.movement)). I ripped that out and simulated 10 return stroke types (touch, push, chop, block, flick, loop, drive, etc.) across contact timings and face yaw angles against the incoming serve, then graded each return in judgeReturn:
if ((netClearance !== null && netClearance > 0.25) || apex > 0.5) {
tier = "smashable";
reason = `floats ${floatCm} cm over the net at ${speed} km/h - a real opponent ends the point`;
}
Landing on the table is useless if you pop it 30 cm over the net and get smashed.
Small implementation notes
- Forward vs inverse simulation: in the sandbox you set bat angle and swing, and physics decides where the ball goes (usually into the net at first). In the 18-cell coaching matrix I pick where the ball should land, bisection-solve the velocity, and work backwards to show the bat angle. I put a disclosure banner (
MATRIX_DISCLOSURE) on that chapter so nobody assumes those 18 presets were hand-tuned, and added a test for the disclosure string too. - To animate the ball arriving at the feeder’s racket before contact, I just run
stepFlight(rewound, -SIM_DT)backwards for a few frames. - For the trail fade on GPU, rather than re-uploading 110 trail vertices from CPU every frame to update alpha, I store each point’s birth timestamp in the alpha attribute and let the vertex shader compute
vColor.a = pow(0.988, max(0.0, uTrailNow - vColor.a)). - Three.js r170 gotcha:
BufferGeometry.setFromPointsreuses the old vertex count ifpositionalready exists on the geometry, so if your new trajectory has fewer points it reads past the end of the array. You have to callthis.geo.deleteAttribute("position")beforesetFromPoints.
The offline bundle is up on Gumroad if you want to try it.