Annex · quick maths 🧮
Annex

The square root & the Quake trick

Why the square root was long the bane of game engines, the legend of the code 0x5f3759df, and how Tower Duel simply avoids the calculation thanks to Pythagoras.

?The problem: measuring a distance

Constantly, a game asks itself “how far apart are these two points?”. Is the cannonball close to my tower? Which shell whistles the nearest?

The answer is the Pythagorean theorem. Between two points, we compute the horizontal gap dx and the vertical gap dy, and the distance is:

distance, the Pythagorean way
distance = Math.sqrt(dx*dx + dy*dy);   // √(dx² + dy²)

It works perfectly… but that little Math.sqrt (the square root) is, historically, one of the most expensive operations a processor can do. Multiplying and adding is almost free; extracting a root, far less so. And in a game we ask for it thousands of times per second.

For the curious. An addition or a multiplication takes a clock cycle or two. On 1990s machines, a square root cost dozens of them. Hence an obsession among the programmers of the era: how do we avoid, or cheat with, the square root?

1The legend: 0x5f3759df

The anecdote you may remember is famous: the “fast inverse square root”, popularised by the source code of Quake III Arena (id Software, 1999 — the studio behind Doom, hence the frequent confusion!). To light a 3D scene, the engine had to normalise millions of vectors, which means computing a lot of 1 / √x.

Someone wrote this — a piece of code that became mythical for its colourful comment:

Quake III — q_math.c (excerpt, in C)
float Q_rsqrt(float number) {
  long i;
  float x2, y;
  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;            // read the float's bits as an integer
  i  = 0x5f3759df - ( i >> 1 );   // what the f***?
  y  = * ( float * ) &i;
  y  = y * ( 1.5F - ( x2 * y * y ) ); // one Newton iteration to refine
  return y;
}

The idea: a floating-point number is, in its bits, already a kind of logarithm. By shifting those bits (i >> 1) and subtracting a magic constant, you get an excellent first approximation of 1/√x — with no square root at all. A single pass of Newton's method refines the result. The whole thing is about 4× faster than the classic method of the time.

What it means today. This trick is obsolete! Modern processors have a dedicated hardware instruction (rsqrtss, vsqrt…) that's both faster and more accurate. In JavaScript, Math.sqrt calls that instruction directly: you won't beat it with bit tricks. The lesson isn't the recipe — it's the mindset: know the cost of what you compute.

2The trick that still works: don't compute the root

The best optimisation is the operation you never do. And very often, we don't want the exact distance: we just want to compare it. “Is the ball less than 460 px away?” “Which of these shells is the closest?”

Key insight: the square root is a monotonically increasing function. If a² < b² (for positive distances), then a < b. So, to compare, we can compare the squares of the distances and skip the root entirely.

Slow: a √ every time d = √(dx²+dy²) if d < threshold … one root per test 🐢 Fast: we compare the squares d² = dx²+dy² if d² < threshold² … zero roots 🚀
Comparing comes out the same with the squares — and a square costs just one multiplication.

This is exactly what Tower Duel does for the proximity feedback on the phone. In turbo mode, several shells fly at once: we look for the one closest to your tower every frame. Instead of one root per shell, we compare the squares and extract only one root, right at the end, and only if a shell is within range:

src/scenes/ControllerScene.js — shell proximity
let bestSq = Infinity;
for (const p of s.projectiles) {
  const dx = p.x - ox, dy = p.y - oy;
  const d2 = dx*dx + dy*dy;       // a square: just * and +
  if (d2 < bestSq) bestSq = d2;    // we compare squares
}
// a single root, and only if something is in range
const intensity = bestSq < threshold*threshold ? 1 - Math.sqrt(bestSq)/threshold : 0;
Remember. Before optimising how you compute, ask whether you need to compute at all. Comparing squares is the poor man's “fast inverse square root”… and unlike the real one, it never goes obsolete.

3Even better: skip Pythagoras too

To know whether a ball has hit a tower, we don't use distance at all. The tower is a rectangular box, so we just test whether the point is inside the box (AABB, axis-aligned bounding box): four comparisons, no multiplication, no root.

src/sim/geometry.js — ball ↔ tower collision
export function rectContains(rect, x, y) {
  return x >= rect.x && x <= rect.x + rect.w &&
         y >= rect.y && y <= rect.y + rect.h;   // 4 comparisons, done.
}

And for the destructible terrain? A crater is a disc. “Is this point inside the crater of radius r?” amounts to “is its distance to the centre < r?”. We reuse the trick: we compare against the squared radius.

src/sim/terrain.js — is a point inside a crater?
for (const c of craters) {
  const dx = x - c.x, dy = y - c.y;
  if (dx*dx + dy*dy <= c.r*c.r) return true;  // no Math.sqrt
}
For the curious. The whole authoritative simulation (on the server) is thus square-root-free: trajectories in tiny additive steps, collisions in boxes, craters in squares. The only Math.sqrt left serves the feel (the intensity of the buzz/whizz), not the game logic.

4Your turn: square vs root

Try it! Move the mouse (or your finger) over the area. We show the squared distance and the true distance to the centre. Notice: to know whether you're inside the circle, comparing the squares is enough — no root needed.

Distance to the centre

The circle lights up green as soon as dx²+dy² ≤ r² — the same comparison as for a crater.

5Bonus: the “smoothstep” easing

Same spirit on the turbo-mode wind: to glide smoothly from one value to another, we don't need expensive trigonometry. The smoothstep function gives a natural acceleration/deceleration with a simple polynomial:

src/sim/Simulation.js — easing the continuous wind
const t = clock / WIND_KEY_SECONDS;     // 0 → 1 between two keypoints
const s = t * t * (3 - 2*t);          // smoothstep: gentle at the start and the end
const wind = from + (to - from) * s;     // eased interpolation

Three multiplications and a subtraction, versus a sine, to get an S-curve. Cheap, readable, sufficient. That's the game's philosophy: each time, pick the simplest calculation that gives the desired effect.

The moral. Today's real optimisations are rarely bit-twiddling magic tricks. They're choices: don't compute what's useless, compare squares rather than roots, prefer a box to a circle, a polynomial to a transcendental function.

↩ Back to home