say hi
A build log · the physics is the easy part

The flock is trivial.
The fourth axis
is not.

Reynolds' three rules are twelve lines of arithmetic and they are already written in ℝⁿ — nothing in them knows how many dimensions it is in. Everything that makes 4D flocking hard sits somewhere else: in the density law that fixes the neighbourhood radius, in a domain with no walls, in two perspective divides, in six planes of rotation, and in finding the neighbours at all once N stops being small.

2D · 3D · 4D one core TD and SD−1 r ∝ n−1/D, measured 6 bivector planes spatial hash → 106

00 · Orientation

Why boids, and why in four dimensions

A boids page is usually a pretty demo with three sliders. This one is a vehicle for a different question: which parts of a simulation actually depend on the number of dimensions? Flocking is the ideal test case, because the answer is surprising — the dynamics are dimension-free, and almost everything around them is not.

Craig Reynolds published the model in 1987 as three steering rules applied to local neighbours. Written as vector arithmetic, none of the three mentions a coordinate:

◈The three rules, in ℝⁿ

separation  as = Σj∈N(i) (xi − xj) / ‖xi − xj‖²
alignment   aa = ⟨vj⟩j∈N(i) − vi
cohesion    ac = ⟨xj⟩j∈N(i) − xi

with N(i) = { j : ‖xi − xj‖ < r }. Sums, differences, means, a norm. Every one of those operations is defined in any inner-product space. Change vec2 to vec4 and the code compiles and runs — and produces something subtly wrong, for reasons that take the next two parts to unpack.

The interesting failure is not a crash. It is that the flock dissolves: with the radius you used in 2D, a boid in 4D has almost no neighbours, so there is nothing to align with. Fixing that properly is a question about the geometry of high-dimensional space, not about boids. It is also exactly the question that governs the cost of every neighbour search in this page's last part.

PartWhat it coversWhy it is here
01Three rules, one metricThe core, written once, with D as a parameter. Live in 2D.
02The density lawr ∝ n−1/D. Measured from the simulation, not asserted.
03Torus or sphereTwo compact domains with no walls, and the degrees of freedom they cost.
04Two perspective divides4D → 3D → 2D, and four honest ways to encode w.
05Six planes of rotationBivectors, simple vs isoclinic, rotors in Cl(4,0).
06Glyphs and trailsOrientation after a non-linear projection is a Jacobian, not a vector.
07The instrumentEverything above, in one canvas, with the knobs exposed.
08Finding the kGrids, spatial hashing, Morton order, Verlet lists — and why not a kd-tree.
09SetupThe Metal toolchain — only needed if you're building part 10 yourself.
10Toward a millionThe Metal path, and the point where individuals stop being visible.
11Where intuition endsD = 5, 6, and what is left to look at.
⌥What runs here, and what is only listed

Every figure on this page is canvas 2D on the CPU, single-threaded JavaScript. That is a deliberate ceiling: it runs in every browser, it degrades honestly, and at N ≈ 104 it is already fast enough to make every point the text makes. That JS is what actually moves when you drag a slider — it is not shown as a listing, because reading it teaches you nothing the figure itself doesn't.

The code blocks are a separate, parallel thing: a C++ description of the same algorithms, close enough to each figure's live JS that the two are easy to cross-check. Parts 09 and 10 go one step further and describe an actual native, GPU-resident program — a Metal compute kernel, a real window, a render pass drawing straight to the screen — which, like every C++ listing on this page, is not wired into it. If a benchmark number is not printed live by a figure you can drag, treat it as an estimate and say so.

01 · The core

Three rules, one metric

Write the simulation once, with the dimension as a variable, and never write it again. The only place D appears is the length of the loop over components — and, later, in the radius.

Positions and velocities live in a flat array of stride 4, regardless of D. Components D…3 are held at exactly zero and excluded from every reduction. That costs nothing (the arithmetic is on components you were loading anyway) and it means the 2D case is a genuine 2D simulation that happens to sit in a four-wide buffer — not a 4D simulation squashed onto a plane. The distinction matters: a flattened axis that is still part of the metric makes every boid a neighbour of every other along that axis, and the density measurements in part 02 would be measuring the wrong thing.

cpp core.cpp — the whole model
// pos, vel: float arrays of stride 4 * N; components D..3 pinned to 0.
// Only `D` and the neighbour predicate know about dimension.
constexpr float TAU  = 0.25f;   // steering timescale, seconds
constexpr float AMAX = 2.0f;    // clamp on the dimensionless steering vector
const float RS = 0.5f * r;      // separation acts on its own, shorter radius

void step(float dt) {
    for (int i = 0; i < N; i++) {
        int bi = 4 * i;
        float s[4] = {0,0,0,0}, a[4] = {0,0,0,0}, c[4] = {0,0,0,0};
        int count = 0, sCount = 0;

        forEachNeighbour(i, r, [&](int j, const float* d, float d2){
            if (d2 < RS*RS) {                                // short-range only
                float g = std::min(8.0f, RS*RS/d2) / std::sqrt(d2);  // capped 1/d^2
                for (int k = 0; k < 4; k++) s[k] += d[k] * g;
                sCount++;
            }
            for (int k = 0; k < 4; k++) { a[k] += vel[4*j+k]; c[k] -= d[k]; }
            count++;
        });

        if (count > 0) {
            // Each term divided by its own natural scale first: separation
            // is already dimensionless, alignment by the cruise speed,
            // cohesion by r. Skip this and the three are orders of
            // magnitude apart.
            float inv = 1.0f/count, sInv = sCount ? 1.0f/sCount : 0.0f;
            float rd[4]; randomUnitDir(rd);
            float g[4];
            for (int k = 0; k < 4; k++)
                g[k] = Ws * s[k] * sInv
                     + Wa * (a[k] * inv - vel[bi+k]) / speed
                     + Wc * c[k] * inv / r
                     + noise * rd[k];                          // Vicsek eta

            // Clamp the steering vector, then apply it over TAU.
            float m = std::sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]+g[3]*g[3]);
            float f = dt * (speed / TAU) * (m > AMAX ? AMAX/m : 1.0f);
            for (int k = 0; k < 4; k++) vel[bi+k] += f * g[k];
        }
        clampSpeed(bi);       // fixed cruise speed keeps the flock legible
    }
    integrate(dt);             // domain-dependent: wrap, or project onto the sphere
}

Clamping the speed instead of integrating a real acceleration is not physics — it is a legibility decision. Boids with variable speed spend most of their time nearly stationary or streaking off-screen, and the flocking structure becomes hard to see. Everything else in that listing that looks like fussiness is load-bearing, and the reason is worth a box of its own.

!The three rules have incompatible units

Written as the equations at the top of this page, the three terms have different physical dimensions. Separation goes as 1/d, so its scale is 1/r. Alignment is a velocity difference, so its scale is the cruise speed. Cohesion is a displacement, so its scale is r. Put the three in one weighted sum with weights near 1 and you have not balanced anything.

Measured on this page's first draft — r = 0.075, speed = 0.16, weights 1.5 / 1.15 / 0.7 — the mean magnitudes came out as sep : ali : coh = 1 : 0.0094 : 0.0006. Alignment and cohesion were not weak; they were numerically absent. Worse, the separation impulse per frame was 2.2× the entire velocity, so each boid's heading was re-decided from scratch every step. The mean turn was 110° per frame and the polarisation φ was 0.022. It looked like a swarm of vibrating dots, which is exactly what it was: a repulsive gas.

The fix is three lines: divide each term by its own scale before weighting, clamp the resulting dimensionless steering vector, and apply it over a turn timescale τ rather than instantly. After that the weights mean what they look like they mean.

Two further details are not decoration either. Separation runs on a shorter radius than alignment and cohesion — half, here. With a single radius it acts out to r and quietly enforces a uniform lattice: the flock churns pleasantly and never forms groups. Measured as the variance-to-mean ratio of the neighbour count, one radius gives 0.3 (more regular than random) and a halved separation radius gives 2.5 (genuinely clustered). This is also the first appearance of the short-range/mean-field split that part 08 turns into an optimisation.

And there is a noise term, Vicsek's η. Without it the torus has an absorbing state: alignment drives the flock to complete consensus, φ = 1.000, mean turn 0.01° per frame, and it stays there forever. The sphere's answer depends on parity. At D = 3, S² is the textbook hairy-ball surface — no continuous, nowhere-zero tangent field exists on it — so total consensus there is not just unlikely, it is topologically forbidden. S1 and S3, D = 2 and D = 4, carry no such obstruction: both are parallelizable, and S3's combing is exactly the Hopf field the isoclinic rotations in part 05 trace out. D = 3 is the one dimension on this page where the domain overrules the dynamics outright, rather than merely discouraging them.

2D · the three weights
—
show

One boid is highlighted; the disc is its simulation radius, the exact set it averages over. Turn alignment to zero and the flock becomes a gas that still avoids itself. Turn separation to zero and it collapses to a point — cohesion has no opposing force. The band where it looks alive is narrow, and that is the whole reason these three numbers are famous.

!Two radii, and they must be labelled

Later figures draw a boid's visual influence larger than the radius the simulation actually uses, with alpha and scale falling off, so that individuals stay trackable at high N. That is a rendering decision and it lies about the model unless it is stated. Wherever the two differ on this page, the readout says which one you are looking at. In this figure they are the same.

02 · The density law

What D actually changes

The rules do not change with dimension. The neighbourhood does, and it changes fast enough to break a naive port. This is the one piece of real high-dimensional geometry the page needs, so it is worth doing properly: derived in two lines, then measured.

Put n boids in a unit domain of dimension D. The expected number of neighbours inside radius r is the density times the volume of a D-ball:

◈Expected neighbour count

k  =  n · VD(r)  =  n · πD/2 rD / Γ(D/2 + 1)

Hold k fixed — you want each boid to average over roughly a dozen neighbours regardless of dimension — and solve for r:

r*  =  [ k · Γ(D/2 + 1) / (n · πD/2) ]1/D   ∝   n−1/D

Two consequences, one obvious and one not. The obvious one: the exponent flattens with D, so in 4D you must raise the radius far more than intuition suggests to keep the same crowd. Doubling n in 2D lets you shrink r by 1.41; in 4D only by 1.19.

The non-obvious one is the constant. Γ(D/2+1)/πD/2 is the reciprocal of the unit ball's volume, and that volume peaks at D = 5 and collapses afterwards — 3.14 in 2D, 4.19 in 3D, 4.93 in 4D, 5.26 in 5D, then down through 2.55 by D = 10 and 0.0258 by D = 20. A ball of radius 1 inscribed in a cube of side 2 fills 78% of it in 2D and 0.0000025% in D = 20. Almost all of the cube is in its corners. Flocking never reaches that regime, but the neighbour search in part 08 feels the beginning of it at D = 4 already.

None of that is worth believing on the strength of an argument. The figure below measures it: for each D it samples n points on the periodic domain, computes each sample point's distance to its 12th nearest neighbour, and averages. That mean is the radius giving k = 12. Fitting a line through the log–log points gives the exponent back.

measured: r*(n) for k = 12 neighbours
measuring…

Log–log. Straight lines mean a power law; the printed slopes are least-squares fits over the measured points, and the bracketed values are the predicted −1/D. The measurement uses the periodic (minimum-image) metric, which is why it converges to the prediction rather than drifting — a bounded box would show boundary depletion at every n.

✓Gate

Fitted slopes should land within a few percent of −0.500, −0.333 and −0.250. If a slope is systematically shallow, the metric is not periodic somewhere — the usual cause is a minimum-image wrap applied to D components but the distance summed over all four.

Practically this collapses to one rule the rest of the page uses: never set a radius, set a neighbour count. Every figure below takes k as the knob and solves for r at the current n and D. Switching dimension then keeps the flock's local structure intact, and the differences you see are the ones the geometry actually causes.

03 · The domain

Torus or sphere — pick your compromise

A flock needs somewhere to live that has no edges. Walls produce boundary artefacts that dominate every statistic you would like to measure, and reflecting boundaries produce a flock that spends its life bouncing. There are exactly two convenient edgeless choices, and they trade against each other.

The flat torus TD

Coordinates in [0,1)D, distances by minimum image: for each component take the shortest of the wrapped alternatives. Flat, homogeneous, isotropic, D genuine degrees of freedom, and the metric is what everyone's intuition expects. The cost is the seam. Nothing is wrong with the physics at the wrap, but every drawn object that spans it is wrong: a trail segment across the seam is a line across the entire viewport, and a cohesion arrow points the wrong way. You handle it by discarding segments longer than half the domain, which is a rendering hack that you have to remember in six places.

The sphere SD−1

Positions constrained to ‖x‖ = 1 in ℝD, velocities in the tangent space, integration by x ← normalise(x + v Δt) with v re-projected afterwards. Compact, edgeless, homogeneous, isotropic — and with no seam at all, because there is no seam to have. Trails are continuous everywhere. Every geodesic is a great circle, so a flock that commits to a direction eventually comes back, which produces the pleasant behaviour of bands forming along great circles.

!The sphere costs you a dimension

SD−1 embedded in ℝD is a manifold of dimension D−1. "4D boids on S³" means positions in ℝ⁴ with three degrees of freedom, not four. The projection problem is still genuinely four-dimensional — the points have four coordinates and need two perspective divides — but the dynamics are those of a curved 3-manifold.

This propagates into part 02's law. On the torus the intrinsic dimension is D, so r ∝ n−1/D. On the sphere it is D−1, so r ∝ n−1/(D−1), and S³ scales like a 3-dimensional space, not a 4-dimensional one. If you want four true degrees of freedom, the torus is the only one of the two that gives them.

Dimension switching, done twice

Both families nest, which is what makes a single dimension switch honest rather than a re-initialisation. On the torus, dropping to D means pinning components D…3 to zero and removing them from the metric. On the sphere the nesting is prettier: S³ ∩ {w = 0} = S², and S² ∩ {z = 0} = S¹. Because every force is projected into the tangent space and the constraint surface is invariant, a flock started on the subsphere stays on it exactly, by symmetry — no clamping, no drift correction.

◈Why "collapse the axis" is not enough

The tempting shortcut for a 2D mode is to keep four components and give the unused ones a tiny extent — say w ∈ [0, 1) with everything else scaled down. Do not. If the extent is smaller than the interaction radius, the domain wraps completely along that axis and every boid becomes a neighbour of every other in w. The metric degenerates, the measured neighbour count stops matching a true 2D run, and part 02's figure quietly measures nothing.

Components excluded from the metric cost nothing anyway: they are already in the register you loaded. Pin them to zero and mask the reduction.

Torus TDSphere SD−1
Degrees of freedomDD − 1
Curvatureflatconstant positive
Density exponent−1/D−1/(D−1)
Distanceminimum image, per componentambient chord, or arccos of the dot product
Integrationx ← frac(x + vΔt)x ← normalise(x + vΔt), then re-project v
Trailsneed seam cullingcontinuous, no special case
Spatial griddense, every cell occupieda shell in ℝD — most cells empty

That last row is not a drawback, it is the reason the sphere is pedagogically useful in part 08. A uniform grid over the bounding box of S³ is almost entirely empty; only a thin shell holds anything. Storing it densely is absurd, and the hash table that fixes it is the same hash table you need on the torus at D = 4 for a different reason. One structure, two motivations.

04 · Projection

Two perspective divides

Getting a point from ℝ⁴ to a screen is the same operation applied twice. Nothing about it is exotic; what is easy to get wrong is believing that the second divide is optional, or that the result behaves like a linear map.

Place a 4D eye on the negative w axis at distance d₄ and project onto the hyperplane w = 0. That is one divide and it hands you a point in ℝ³. Then do the familiar thing: 3D eye at distance d₃ down z, divide, get pixels.

cpp project.cpp
// p is already in view space (world rotation applied).
// Returns screen x, y and the accumulated scale factor — which is
// exactly the right depth cue: it is how much the point shrank.
struct Projected { float x, y, s, w; };

Projected project(const float* p) {
    float x = p[0], y = p[1], z = p[2], w = p[3], s = 1.0f;
    if (D >= 4) { float k = f4 / (w + d4); x *= k; y *= k; z *= k; s *= k; }
    if (D >= 3) { float k = f3 / (z + d3); x *= k; y *= k;          s *= k; }
    return { cx + x * S, cy - y * S, s, w };
}

The w + d4 denominator is the entire fourth-dimensional effect, and it is worth being clear about what it does: a boid nearer in w is magnified in all three remaining coordinates, including z, so it also appears nearer in the 3D sense. Movement purely along w shows up as an object growing while staying still. That is the sensation to aim for, and it is genuinely the same sensation a 2D creature would get from a 3D object passing through its plane.

!The composition is not linear

Two projective divides compose into a map whose Jacobian varies across the frame. Two consequences the rest of the page depends on: the projection of a velocity vector is not the on-screen direction of motion (part 06), and equal 4D distances do not map to equal screen distances, so any on-screen distance readout is decorative.

Four ways to encode w

Perspective alone is not enough to read a fourth axis, because the eye has no prior for it. The four modes below are the ones worth having; the figure runs the same flock through all four simultaneously so they can be compared rather than argued about.

ModeWhat it doesGood for
sliceDraw only |w − w₀| < ε, no divide in w. A hyperplane cut.Reading actual structure. Unambiguous, and empty most of the time.
weightedFull divide; size and alpha follow the accumulated scale.Motion. Approach along w reads immediately.
colourNo divide in w; hue maps w. Geometry stays undistorted.Comparing w across the whole flock at once.
hybridDivide, plus hue, plus alpha falloff away from w₀.Default. Redundant cues survive a still frame.
the same 4D cloud, four encodings
—

600 points on S³, rotating isoclinically in the xy and zw planes at equal rate. Top-left slice, top-right weighted, bottom-left colour, bottom-right hybrid. Watch one thing: in the slice panel the population changes as w₀ moves — that is honest, and it is also why slice alone is a poor default. Drop d₄ toward 1.6 and the weighted panel distorts violently; the eye is approaching the sphere.

05 · Rotation

Six planes, and two of them at once

Rotation is the part where 3D intuition actively misleads. In 3D we say "rotate about an axis" and get away with it. That phrasing is an accident of three dimensions, and it does not survive the trip to four.

A rotation is not defined by an axis; it is defined by the plane it rotates in. The number of independent planes is C(D,2): one in 2D, three in 3D, six in 4D — xy, xz, xw, yz, yw, zw. In 3D each plane happens to have a unique normal direction, so naming the normal instead of the plane loses nothing. In 4D the orthogonal complement of a plane is another plane, so "the axis of rotation" does not refer to anything.

◈Bivectors, briefly

The object that names a plane is the bivector ei ∧ ej, and in 4D the six of them span the space of rotations — which is the Lie algebra so(4), of dimension 6. A rotor R = exp(−θ B / 2) in the Clifford algebra Cl(4,0) acts by the sandwich product x ↦ R x R̃, exactly as quaternions do in 3D. That is the elegant construction, and it is genuinely useful when you need to compose or interpolate rotations.

For this page it would be overkill. Applying a plane rotation is a Givens rotation touching two components, six of them compose into a 4×4 matrix, and the matrix is what the vertex maths wants anyway. The bivector language is the right way to think; the matrix is the right thing to ship. Where rotors earn their place is stable interpolation — 4×4 matrices drift out of SO(4) under repeated multiplication and need periodic re-orthonormalisation, which the instrument in part 07 does every few hundred frames.

cpp rot4.cpp — a Givens rotation in the (a,b) plane
// Right-multiply the 4x4 view matrix M by a rotation in plane (a,b).
// Two columns change; the other two are untouched. This is the whole
// of 4D rotation — six such planes generate SO(4).
void rotatePlane(float* M, int a, int b, float theta) {
    float c = std::cos(theta), s = std::sin(theta);
    for (int row = 0; row < 4; row++) {
        int ia = 4*row + a, ib = 4*row + b;
        float va = M[ia], vb = M[ib];
        M[ia] = va * c - vb * s;
        M[ib] = va * s + vb * c;
    }
}

Simple, double, isoclinic

Any rotation in SO(4) decomposes into rotations in two orthogonal planes, by angles θ₁ and θ₂. The three cases are qualitatively different objects:

  • Simple (θ₂ = 0): one plane turns, the orthogonal plane is fixed pointwise. A whole plane of fixed points — the closest 4D thing to a 3D axis, and it is a plane, not a line.
  • Double (θ₁ ≠ θ₂ ≠ 0): both planes turn at different rates. Only the origin is fixed. Trajectories wind around a torus and are generically non-closing.
  • Isoclinic (θ₁ = ±θ₂): both planes turn at the same rate. Every point moves through the same angle; every direction is displaced equally. There is no analogue in 3D at all, and its orbits are the fibres of the Hopf fibration.

The isoclinic case is the one to spend attention on. Because every point rotates by the same angle, the transformation has no visual "preferred plane", and a rigid 4D object under isoclinic rotation looks like it is turning inside out in a way that is completely regular but has no 3D counterpart. It is also the rotation that makes S³ legible: the orbits are Hopf fibres, they are pairwise linked great circles, and a flock rotating isoclinically traces them.

tesseract · 16 vertices, 32 edges
—
rotation

A tesseract is the right test object because you know what it should be: two cubes joined at corresponding vertices. Under simple xy nothing changes size — the zw plane is fixed and w never varies. Under simple xw you get the familiar inside-out turn. Under isoclinic, every vertex moves at the same angular rate and the figure never has a still part; compare it against double, where the two rates beat against each other and the motion visibly has structure.

⌥Left and right isoclinic

θ₁ = +θ₂ and θ₁ = −θ₂ are different rotations, and the distinction is not cosmetic: it is the double cover SU(2) × SU(2) → SO(4), the reason unit quaternions come in a left and a right action, and the reason the Hopf fibration has a handedness. Every rotation in SO(4) factors uniquely into a left-isoclinic and a right-isoclinic part.

06 · Glyphs and trails

Orientation is a Jacobian, not a vector

A dot has no heading, and a flock drawn as dots loses the one thing worth looking at. So: arrowheads. Which immediately raises a question that looks like a detail and is not — which way does the arrowhead point?

The tempting answer is to project the velocity the same way you projected the position and use the result. That is wrong, and part 04 already said why: the composition of two perspective divides is not linear, so it does not commute with taking differences. The correct screen direction is the image of v under the Jacobian of the projection at p, and the cheapest way to get that is to not derive it at all:

cpp heading.cpp
// Screen-space heading by forward difference through the same non-linear
// map the position went through. Two extra multiplies and one projection.
constexpr float eps = 1e-3f;
Projected a = project(p);
float pEps[4] = { p[0]+eps*v[0], p[1]+eps*v[1], p[2]+eps*v[2], p[3]+eps*v[3] };
Projected b = project(pEps);
float hx = b.x - a.x, hy = b.y - a.y;
float L = std::hypot(hx, hy); if (L == 0.0f) L = 1.0f;
hx /= L; hy /= L;                     // unit screen heading

The difference is largest where the projection is most curved: near the frame centre for the 3D divide, and anywhere w is small for the 4D one. A boid moving almost straight along w has a projected velocity of nearly zero but a Jacobian heading that is well defined and points outward, because the thing it is actually doing on screen is growing. The naive version renders that boid with a random flickering heading. The instrument below has a toggle; the effect is small in calm frames and obvious near the centre.

◈The rest of the frame is free

A heading fixes one direction. In 2D that is the whole orientation. In 3D it leaves the roll about the heading free, and in 4D it leaves an entire 3-dimensional space of rotations free — which is why you cannot orient a 4D glyph in 4D and expect it to be stable: any basis you pick for the complement flickers frame to frame.

Orient the glyph after projection instead. In screen space the heading determines everything and there is nothing left to choose. If you do need a 3D-oriented body (before the last divide), build the frame branchlessly — Frisvad's construction gives an orthonormal basis from a unit vector with no square root and one sign branch, and it is stable everywhere except the pole it is documented to be unstable at.

Two kinds of trail, and you need both

Trails do a real job: they turn instantaneous velocity into visible history, which is what makes a flock's structure readable in a still frame. There are two implementations and their failure modes are complementary.

Feedback bufferGeometric ring buffer
MethodBlend the previous frame in at α < 1 instead of clearingKeep the last k world positions per boid; draw a tapered strip
CostO(pixels), independent of NO(N·k) memory and a second pass
Camera motionBreaks. Old pixels are stale in world terms; the whole image smearsCorrect — positions are re-projected every frame
High NFine, it is per-pixel106 × 16 × 4 floats is 256 MB. Not fine
Use for2D, and any static-camera shot3D and 4D, where the camera moves

The hero at the top of this page is a feedback buffer — static camera, so there is no reason to pay for anything else. The instrument below uses ring buffers, because it has an orbit camera and a rotating 4D view, and a feedback trail under either of those turns the canvas into fog within a second.

!The seam again

On the torus, a trail segment that crosses the wrap draws a line across the entire viewport. Cull any segment whose screen length exceeds a threshold — a fraction of the viewport works and is robust, because a legitimate segment is one frame of motion and is therefore short by construction. On the sphere this case does not exist, which is the third time in this page that the sphere has quietly removed a special case.

07 · The instrument

Everything, with the knobs out

One simulation core, two domains, three dimensions, four projection modes, two render modes. Drag inside the canvas to orbit. The readout is measured, not configured — the radius is servo-controlled to hit the neighbour count you ask for, so switching dimension keeps the local structure intact instead of dissolving the flock.

nD boids · live
—
dim domain
4D view 4D spin
render options
fps — mean neighbours — radius — pair tests / frame — vs brute force — step — turn —

Things worth doing: switch to 4D with the spin off and note that the flock looks like a bad 3D flock — the fourth axis is invisible without motion. Turn on isoclinic spin and it resolves. Switch domain to torus at D = 4 and watch the mean-neighbour servo settle to a different radius for the same k, because the intrinsic dimension changed from 3 to 4. Turn the noise to zero on the torus and watch the turn-rate readout fall to nothing — that is the absorbing consensus state, and on the sphere it is topologically forbidden only at D = 3. Turn the hash grid off and watch the pair-test counter and the frame time; at N = 1200 the difference is uncomfortable, at N = 6000 it is decisive. The N slider caps at 4000 in 4D and 9000 below it: 81 probes per query instead of 27 moves the single-thread ceiling down by roughly a factor of three, and a widget running at five frames per second teaches nothing.

!A flock is not a uniform point set

Part 02 measured k(r) on random points, and got a clean rD. A settled flock does not obey that law, because separation gives the pair-correlation function a shell: neighbours pile up at a preferred spacing. Measured on a frozen 4D torus run at N = 1200, k goes from 3.5 to 25 as r moves from 0.20 to 0.24 — roughly an order of magnitude steeper than r4 predicts.

That is why the servo below is slow and low-passed rather than solving the formula: a proportional controller with a sensible-looking gain lands in a period-2 limit cycle across the shell, alternating k ≈ 9 and k ≈ 15 forever. The fix is a gain of well under one percent per frame and an exponential average on the measurement. It also means the readout will sometimes settle a little off target — that is the shell, not a bug.

⌥What the servo does

Rather than solving part 02's formula for r — which would need the domain's intrinsic dimension, its volume, and a boundary correction — the instrument measures the mean neighbour count each frame and nudges r by at most 2% toward the target. It converges in well under a second, it is domain-agnostic, and it is honest: the number in the readout is counted, not computed. The formula's job was to tell you the scaling; the servo's job is to hit it.

08 · Neighbour search

The work is O(N·k). The problem is finding the k.

Here is the frame that makes this part cohere with part 02 rather than sitting next to it. If you hold the neighbour count k fixed as n grows — which part 02 says you should, and which the servo does — then the useful work is exactly O(N·k), linear in N, for every dimension. Not one operation of it is avoidable and none of it gets harder with D.

All of the difficulty is in the lookup: producing, for each boid, the k that matter, without touching the N−k that do not. Brute force does the useful work plus O(N²) of pure rejection. Everything below is a way to shrink the rejection term, and the reason D matters is that the rejection term is where the geometry lives.

Uniform grid — and what D does to it

Bin positions into cells of side r; a boid's neighbours can only be in its own cell and the adjacent ones. In 2D that is 9 cells, in 3D 27, in 4D 81. The 3D growth is the first cost, and it is the mild one. The severe one is occupancy: a grid over the bounding box of the domain has (1/r)D cells, and with r ∝ n−1/D that is proportional to n — fine on a torus, where every cell holds about the same handful of boids. It is not fine on a sphere, where the points occupy a thin shell of a D-dimensional box, and the overwhelming majority of cells are empty and still allocated.

cells touched per query, and how many hold anything
—

Measured, for D = 2…6, at the radius that yields k neighbours. Bars: cells visited per query (3D, the dark bar) against cells that actually contain a point (bright). The gap is wasted probes. On the torus it stays modest; on the sphere the occupied fraction falls off a cliff, because a (D−1)-dimensional shell in a D-dimensional grid is a set of measure zero being approximated by boxes.

◈Hashing fixes the sparse case, not the 3D case

Replace the dense array with a hash of the integer cell coordinate into a table of size O(n). Empty cells cost nothing because they are never inserted. Collisions are harmless: two unrelated cells sharing a bucket means a few extra distance tests, and you were going to test distances anyway. This is Teschner's spatial hashing, it is four lines, and it is the right default for any domain that is not a filled box.

What it does not fix is the 81 probes. Nothing fixes that except reducing D, or accepting a coarser grid with more candidates per cell — the trade is between probe count and candidate count, and at D = 4 the optimum sits at a cell size somewhat larger than r.

cpp hashgrid.cpp — counting sort, no per-frame allocation
// Table size M = next power of two above 2N. Three passes, all linear,
// all cache-friendly, and identical in structure to the GPU version:
// count -> prefix sum -> scatter.
constexpr uint32_t P[4] = { 73856093u, 19349663u, 83492791u, 39916801u };  // one per axis

uint32_t cellHash(int32_t ix, int32_t iy, int32_t iz, int32_t iw) {
    uint32_t h = (uint32_t)ix*P[0] ^ (uint32_t)iy*P[1] ^ (uint32_t)iz*P[2] ^ (uint32_t)iw*P[3];
    return h & (M - 1);
}

void build() {
    std::fill(count, count + M, 0);
    for (int i = 0; i < N; i++) { key[i] = hashOf(i); count[key[i]]++; }
    uint32_t acc = 0;
    for (uint32_t c = 0; c < M; c++) { start[c] = acc; acc += count[c]; cursor[c] = start[c]; }
    start[M] = acc;
    for (int i = 0; i < N; i++) items[cursor[key[i]]++] = i;
}

The three-pass structure is not an accident of JavaScript. It is exactly the shape a GPU wants: the count is an atomic increment per particle, the prefix sum is a standard scan, and the scatter is another atomic. Writing it this way on the CPU first means the Metal version in part 10 is a transcription rather than a redesign.

Morton order — the free 20%

Sorting by hash scatters memory access. Sorting by Morton code — the integer formed by interleaving the bits of the cell coordinates — keeps spatially adjacent cells adjacent in memory, so the 3D probes mostly hit cache lines you already have. In 4D the interleave is four-way, taking bits in the order w z y x, w z y x, …; with 8 bits per axis that is a 32-bit key, which is convenient because a 32-bit radix sort is a solved problem on the CPU and, on platforms that ship one, on the GPU too — Metal doesn't ship a general sort primitive (part 10 covers what that means for the grid build itself), so a Morton reorder there means writing the radix passes yourself. The gain is not asymptotic and it is real: locality, not complexity.

Verlet lists — amortise the build

From molecular dynamics, and it applies here for the same reason it applies there: speeds are bounded. Build the neighbour list at radius r + skin, then reuse it for as many frames as it takes any boid to travel skin/2. With a cruise speed of v and a skin of 0.5 r, that is 0.25 r / v seconds — typically 5 to 15 frames. The build cost drops by that factor; the per-frame cost rises by the extra candidates inside the skin, which in D dimensions is a factor (1 + skin/r)D. In 4D a 50% skin costs 5× the candidates, which is why the optimal skin shrinks with dimension — another instance of the same volume law.

!Not a kd-tree

kd-trees are the reflex answer for nearest-neighbour queries and they are the wrong tool here, for three reasons that have nothing to do with dimension.

The point set is fully dynamic — every point moves every frame, so the tree is rebuilt every frame, at O(n log n) against the grid's O(n). Traversal is irregular and branch-heavy, which is acceptable on a CPU and hostile to a GPU, where a warp diverging into 32 different subtrees serialises. And their actual advantage — adapting to strongly non-uniform density — is an advantage a flock partly has (flocks clump) but not enough to pay for the other two.

The honest statement is narrower than "kd-trees are bad in high dimensions". At D = 4 they are not yet degenerate; the classic result that they lose to brute force needs D of roughly 10 or more. They lose here for engineering reasons, not geometric ones.

The idea that actually scales: split the forces

This is the one worth taking away from the page, because it is not about data structures at all. The three rules do not have the same accuracy requirement.

  • Separation is 1/d²-weighted and short-range. It is dominated by the nearest two or three neighbours, and getting it wrong produces visible interpenetration. It needs exact neighbours.
  • Alignment and cohesion are unweighted means over the neighbourhood. A mean does not care which samples produced it. It needs an estimate of the local mean, and it converges as 1/√k.

So compute separation exactly from the grid, and take alignment and cohesion from a coarse cell average — sum positions and velocities per cell during the build, then read the aggregate of your cell and its neighbours. That is one Barnes–Hut level, no tree, and it turns two of the three rules into O(N) with a small constant. The cheaper variant: sample k random members of your cell rather than all of them. At k = 12 the mean has about 29% relative error per boid, which is invisible in the aggregate because neighbouring boids draw different samples and the errors do not correlate.

✓Gate

Any approximation here must be checked against a statistic, not against a screenshot — two flocks with identical statistics look different because the dynamics are chaotic. Use the mean nearest-neighbour distance and the polarisation order parameter φ = ‖⟨v̂i⟩‖, both averaged over a few hundred frames after transients. If exact and approximate agree on those to a few percent, the approximation is fine.

09 · Setup

The toolchain, if you build part 10 yourself

Everything above this line runs in any browser with no setup at all — single threaded canvas 2D, on purpose. What follows in part 10 is native: a C++/Metal program that actually dispatches the kernel below on a GPU. You only need this if you want to run it, not to read it.

macOS — Apple Silicon

Metal 4 shipped at WWDC 2025 and lives in macOS 26 ("Tahoe"). You need a matching Xcode and the metal-cpp headers, which Apple distributes as a single zip pinned to each OS/Xcode pair.

zsh macOS setup
# Command-line tools (clang, metal, metallib, xcrun)
xcode-select --install

# Verify the Metal compiler is present
xcrun -sdk macosx metal --version

# metal-cpp: download the zip matching your macOS from
#   https://developer.apple.com/metal/cpp/
# then unzip into your project, e.g. third_party/metal-cpp/
# It is header-only — there is nothing to build.

# Live GPU monitor, useful for confirming the kernel actually ran on
# the GPU rather than silently falling back to a CPU path
pip install asitop            # graphical; needs sudo to read powermetrics
# or use the built-in:
sudo powermetrics --samplers gpu_power -i 500
!Gotcha — you may not have the metal compiler

The offline xcrun metal/metallib tools ship with the full Xcode, not the Command Line Tools. If xcrun -sdk macosx metal --version errors with "unable to find utility metal", don't fight it — compile the shader from source at runtime instead: read the .metal file as a string and hand it to MTL::Device::newLibrary(source, …). No .metallib, no full Xcode, and the .metal file stays the single source of truth.

10 · Scale

Toward a million, and what you lose getting there

Everything above runs on one CPU thread and tops out around 104. Getting to 106 is not conceptually different — it is the same three passes, executed by a machine with a different shape. What genuinely changes is what a million boids look like, and that is the part usually left out.

The compute pass

One invocation per boid, state in two storage buffers ping-ponged each frame so no invocation reads a buffer another is writing. The dimension enters as a function constant — Metal's equivalent of a C++ template parameter, resolved once when the pipeline is built rather than tested on every invocation — which lets the same source compile to three pipelines (2D/3D/4D) with the masking folded away before the kernel ever runs.

Metal boids.metal — the force pass
#include <metal_stdlib>
using namespace metal;

// Resolved once per pipeline at build time (see the metal-cpp snippet
// below) — dead code for the unused components folds away at compile
// time exactly like WGSL's `override` or a CUDA template parameter would.
constant uint DIM [[function_constant(0)]];

struct Params {
  float r, rs, ws, wa, wc;
  float noise, tau, amax;
  float dt, speed;
  uint  n, tableMask, frame;
};

// Components >= DIM are zero in the buffers, so masking the metric is a
// multiply by a constant vector the compiler folds away.
inline float4 dimMask() {
  return float4(1.0f,
                DIM > 1u ? 1.0f : 0.0f,
                DIM > 2u ? 1.0f : 0.0f,
                DIM > 3u ? 1.0f : 0.0f);
}

kernel void forces(device const float4* posIn      [[buffer(0)]],
                    device const float4* velIn      [[buffer(1)]],
                    device       float4* posOut     [[buffer(2)]],
                    device       float4* velOut     [[buffer(3)]],
                    device const uint*   cellStart  [[buffer(4)]],
                    device const uint*   cellItems  [[buffer(5)]],
                    constant     Params& P          [[buffer(6)]],
                    uint i [[thread_position_in_grid]])
{
    if (i >= P.n) return;

    const float4 m  = dimMask();
    const float4 xi = posIn[i] * m;
    const float4 vi = velIn[i] * m;

    float4 sep = 0, ali = 0, coh = 0;
    float  cnt = 0, sCnt = 0;

    const auto base = cellCoord(xi, P.r);
    // 3^DIM neighbour cells; the loop bound comes from the same function
    // constant, so the compiler sees a fixed-length loop and unrolls it.
    for (uint o = 0; o < nOffsets(); ++o) {
        uint h = cellHash(base + offset(o)) & P.tableMask;
        uint s = cellStart[h], e = cellStart[h + 1];
        for (uint t = s; t < e; ++t) {
            uint j = cellItems[t];
            if (j == i) continue;
            float4 d  = minImage(xi - posIn[j] * m);   // identity on the sphere
            float  d2 = dot(d, d);
            if (d2 >= P.r * P.r) continue;              // hash collisions land here
            if (d2 < P.rs * P.rs) {                      // separation: shorter radius
                sep += d * min(8.0f, P.rs * P.rs / d2) / sqrt(d2);
                sCnt += 1.0f;
            }
            ali += velIn[j] * m;
            coh -= d;
            cnt += 1.0f;
        }
    }

    float4 v = vi;
    if (cnt > 0.0f) {
        // Non-dimensionalise each term before weighting — separation is
        // already scaled by its own radius, alignment by the cruise speed,
        // cohesion by r.
        float  inv  = 1.0f / cnt;
        float  sInv = sCnt > 0.0f ? 1.0f / sCnt : 0.0f;
        float4 g = P.ws * sep * sInv
                 + P.wa * (ali * inv - vi) / P.speed
                 + P.wc * coh * inv / P.r
                 + P.noise * noiseDir(i, P.frame);
        float gm = length(g);
        if (gm > P.amax) g *= P.amax / gm;
        v += P.dt * (P.speed / P.tau) * g;
    }
    v = normalize(v) * P.speed;

    float4 x = xi + v * P.dt;
    x = wrapOrProject(x);                                // frac(), or normalize()
    v = tangent(v, x);                                    // no-op on the torus

    posOut[i] = x;
    velOut[i] = v;
}

The function constant is what makes the same source compile to three specialised pipelines. The host side sets it once, at pipeline-creation time, not per dispatch:

metal-cpp specialising DIM at pipeline build time
// Build three pipelines up front and pick one at dispatch time — the
// alternative, branching on DIM inside the kernel, would pay the branch
// on every one of a million invocations instead of once at load time.
MTL::FunctionConstantValues* fc = MTL::FunctionConstantValues::alloc()->init();
uint32_t dim = 4;
fc->setConstantValue(&dim, MTL::DataTypeUInt, NS::UInteger(0));   // index 0 = DIM

NS::Error* err = nullptr;
MTL::Function* fn = lib->newFunction(
    NS::String::string("forces", NS::UTF8StringEncoding), fc, &err);
MTL::ComputePipelineState* forces4D = dev->newComputePipelineState(fn, &err);

The sort

The grid build is the part people underestimate, and on Metal it is worth being precise about what the platform actually gives you: no general-purpose GPU sort, nothing like CUDA's CUB. So the table isn't built by sorting the boid array at all — it's the same three-pass counting sort part 08 already worked out on the CPU (hashCount → scanCells → scatter), running entirely on the GPU in one command buffer instead. A kernel hashes each boid's cell and atomically bumps a per-cell counter; a one-thread kernel turns those counts into an exclusive prefix sum; a scatter kernel atomically claims each boid's slot in the cell-ordered array. Three dispatches, no auxiliary buffer wider than the boid count itself, and — because the table size is O(n) rather than the full 32-bit key range — no radix passes to write at all for this part. (The Morton reorder from part 08 is the one place in this page that genuinely does need a real sort, and on Metal that one really is on you to write.)

The alternative for a first version is a fixed-capacity grid: an atomic counter per cell and a hard cap of, say, 32 boids per cell, dropping the overflow. It is one pass, it needs no sort, and it is wrong in a specific way — dense regions silently lose neighbours, which is precisely where the flocking behaviour lives. Acceptable to get something on screen; not acceptable in anything you measure.

Windowing, and drawing to the screen

The kernel above has nowhere to put its output until something owns a window. The least-friction way to get a Metal surface from C++ is GLFW with GLFW_NO_API: create the window, fetch its NSWindow via glfwGetCocoaWindow, and attach a CAMetalLayer whose drawables you render into. Ask glfwGetVideoMode for the monitor's native resolution and create the window at that size with the decorations off, rather than the usual fixed-size box, if you want the flock filling the screen instead of sitting in a corner of it. Each frame you fetch the layer's nextDrawable and use its texture as the render target. Attaching the layer is the one place that must touch Objective-C, so it lives in a tiny .mm bridge; everything else stays pure C++/metal-cpp.

Metal draw.metal — boids as point sprites
#include <metal_stdlib>
using namespace metal;

struct ViewParams { float f3, f4, d3, d4; float2 centre, scale; };
struct VSOut { float4 pos [[position]]; float psize [[point_size]]; float4 col; };

// The same two-divide projection as project() in part 04, run once per
// vertex on the GPU instead of once per boid on the CPU. Unlike the force
// kernel, this pass does not need to branch on DIM: components above D are
// pinned to zero, so the "extra" divide is just a constant common factor
// (f4/d4, the same for every boid) rather than something data-dependent —
// the identical shader runs unmodified in 2D, 3D and 4D.
vertex VSOut vmain(uint vid [[vertex_id]],
                   device const float4* pos [[buffer(0)]],
                   constant ViewParams& V    [[buffer(1)]])
{
    float4 p = pos[vid];
    float  s = 1.0;
    { float k = V.f4 / (p.w + V.d4); p.xyz *= k; s *= k; }
    { float k = V.f3 / (p.z + V.d3); p.xy  *= k; s *= k; }

    VSOut o;
    o.pos   = float4(V.centre + p.xy * V.scale, 0, 1);
    o.psize = clamp(6.0 * s, 1.0, 24.0);           // depth cue: shrink with s
    o.col   = float4(0.5 + 0.5*p.w, 0.85, 0.9 - 0.4*p.w, 1.0);   // hue by w
    return o;
}

// Round the square point sprite into a soft disc, same trick as every
// other point renderer on this site.
fragment float4 fmain(VSOut in [[stage_in]], float2 pc [[point_coord]]) {
    float d = length(pc - float2(0.5));
    if (d > 0.5) discard_fragment();
    return float4(in.col.rgb, smoothstep(0.5, 0.3, d));
}
metal-cpp one frame: compute then render, no copy
// per frame:
MTL::CommandBuffer* cb = queue->commandBuffer();

// (1) physics — the pipeline built with DIM baked in at load time
auto* ce = cb->computeCommandEncoder();
ce->setComputePipelineState(forces4D);
ce->setBuffer(curPos,0,0);  ce->setBuffer(curVel,0,1);
ce->setBuffer(nextPos,0,2); ce->setBuffer(nextVel,0,3);
ce->setBuffer(cellStart,0,4); ce->setBuffer(cellItems,0,5);
ce->setBytes(&params,sizeof(params),6);
ce->dispatchThreads(MTL::Size(N,1,1), MTL::Size(256,1,1));
ce->endEncoding();

// (2) render — reads nextPos, the buffer the compute pass just wrote
auto* rpd = MTL::RenderPassDescriptor::renderPassDescriptor();
rpd->colorAttachments()->object(0)->setTexture(drawable->texture());
rpd->colorAttachments()->object(0)->setLoadAction(MTL::LoadActionClear);
rpd->colorAttachments()->object(0)->setClearColor(MTL::ClearColor(0.08,0.08,0.1,1));
auto* re = cb->renderCommandEncoder(rpd);
re->setRenderPipelineState(drawPSO);
re->setVertexBuffer(nextPos,0,0);
re->setVertexBytes(&view,sizeof(view),1);
re->drawPrimitives(MTL::PrimitiveTypePoint, 0, N);
re->endEncoding();

cb->presentDrawable(drawable);
cb->commit();
std::swap(curPos,nextPos); std::swap(curVel,nextVel);     // ping-pong
⌥Why the render pass needs no copy

Same reasoning as every other zero-copy Metal pass on this site: nextPos lives in a StorageModeShared buffer, so the vertex stage reads the very bytes the compute pass just wrote, and Metal serialises the two encoders inside one command buffer correctly with no manual fence. On a discrete GPU you would round-trip through a staging buffer; on Apple Silicon's unified memory the compute output is the vertex input.

!A million boids are a fluid

The honest limit is not computational. At 106 on a 4K display there are more boids than pixels worth giving them, individuals are one pixel each, and every glyph, heading and trail you spent parts 05 and 06 on is invisible. A 4D projection of 106 points is fog with structure you cannot resolve.

So the render mode has to change with N, and it should change to something honest: rasterise density and mean velocity into a coarse buffer and colour by them. That is a genuinely different instrument — it shows you the flock as a continuum, order parameters and vortices and shear layers, which is the correct thing to look at at that scale. The instrument in part 07 switches at N ≈ 3000 for the same reason, several orders of magnitude earlier because it is drawing on a CPU.

Which produces the page's one firm recommendation about scale: do the large-N work on the torus in 2D or 3D, where a density field is readable, and keep S³ and the four-dimensional projections at a few thousand, where individuals are still trackable. They are answering different questions and there is no configuration that answers both.

11 · Limits

Where intuition ends

The simulation core does not care about D and would happily run at D = 12. Nothing else on this page survives past about five, and it is worth being precise about which piece breaks first, because they break for different reasons.

DState
2, 3Everything works. Projection is standard, one divide at most, glyphs and trails behave.
4The interesting case. Two divides, six rotation planes, 81 probes per query. Perceptible with motion and an isoclinic spin; borderline without.
5Three divides. 243 probes. The projection is still defined, and it is no longer readable — three nested foreshortenings cannot be disentangled by eye. Rotation has 10 planes. A generic element of SO(5) still fixes a line — five is odd, the same reason every 3D rotation has an axis — but no plane; the axis intuition outlives the plane intuition by exactly one dimension.
6729 probes per query, and the unit ball's volume is past its peak and falling. The grid is mostly empty even on a torus. Neighbourhoods are still fine; nothing about them is visualisable.
≳ 10Distance concentration: the ratio of nearest to farthest neighbour distance approaches 1, so "nearest neighbour" stops carrying information and the flocking rules lose their meaning along with their visualisation.

The pattern is that rendering fails first, at D = 5, well before the physics or the data structures do. That is a slightly humbling result for a page whose thesis is that the interesting difficulty is not in the compute: it means the difficulty is not merely front-loaded into projection, it is bounded by projection.

What is left undone

  • Hopf-fibration rendering. S³ under isoclinic rotation moves along Hopf fibres, and drawing the fibres themselves — as linked circles, coloured by their base point on S² — would show the structure the flock is moving through rather than only the flock. This is the obvious next figure and it did not fit here.
  • Obstacles and predators on a curved domain. A predator on S³ is a moving repulsive point whose influence spreads along geodesics; the flock's escape manoeuvres would reveal curvature directly.
  • The measured optimum for cell size against probe count at D = 4, which the text above asserts is above r without measuring it. That is a small experiment and it should be done before the claim is repeated.
  • A GPU version of all of it, which is part 10 as code and nothing more.
⌥Provenance

Reynolds' 1987 SIGGRAPH paper for the model; Teschner et al. (2003) for the spatial hash and the prime multipliers used above; Frisvad (2012) for the branchless orthonormal basis; Verlet (1967) for the skin-radius list. The distance-concentration result is Beyer et al. (1999). The left/right isoclinic decomposition of SO(4) is standard and is stated in any treatment of quaternions as rotations of ℝ⁴.