axiom-ai

Birds

Starling murmurations from three simple rules (boids), with hawks that scatter the flock.

Build log

Status

Not started. This log is written by Claude Code during the cloud session that builds the demo, then lightly edited.

The brief

The prompt the session received, verbatim, and a link to the cloud session and PR.

Approach

What was chosen and why. Alternatives considered. Anything reused from open source, with license and link.

Timeline

Short dated entries as the work progressed: what was tried, what broke, what fixed it.

Numbers

Rough wall-clock time, number of turns, tokens or cost if known, bundle size, frames per second on a laptop and a phone.

What I would do next

Known gaps, stretch goals, ideas.

Original spec

Birds

Build a flocking demo (Craig Reynolds’ boids) in projects/birds/demo/, following the demo contract in CLAUDE.md.

The build is a faithful port of cubedhuang/boids (MIT, © 2023 Daniel Huang) to TypeScript and Canvas 2D, plus a short, explicit list of changes and additions.

The rule: wherever this spec does not say otherwise, do exactly what the base does, with its maths, its order of operations and its defaults. When in doubt, read the base, not your memory of boids. Record any place where you had to deviate, and why, in BUILD-LOG.md.

Goal

A full-bleed canvas of thousands of birds flocking like a starling murmuration at dusk. It must look good on first load with no interaction. Visitors can tune the rules live, release hawks that tear holes in the flock, and push, pull or scatter the flock with a finger or mouse. It must work in portrait on a phone.

Branching

Branch from main after the design PR containing this spec has merged. That PR renames projects/boids/ to projects/birds/. Your PR then changes only projects/birds/.

Licensing

  • Clone the base at commit 25253edb0b6fa80008c5d07a8bdc0ae9aed68d55, the commit this spec was checked against. Record it in BUILD-LOG.md.
  • Every file containing ported code starts with a comment naming the source and carries the full MIT notice from the base’s LICENSE.
  • BUILD-LOG.md credits the base with a link, and says roughly what fraction of the final code is ported.
  • beneater/boids (MIT, stated in its README) may be consulted for explanation only. No other code sources.
  • No new npm dependencies. PixiJS is removed, not added.

What to port unchanged

These come from the base’s js/boid.js, js/flock.js, js/main.js and js/opt.js.

Units and timestep

  • Speeds are in CSS px per frame at 60 fps, and forces in px per frame².
  • Each animation frame computes delta = min(elapsedMs / (1000/60), 2). This replaces PixiJS’s ticker delta, which means the same thing.
  • There is no fixed timestep.

Frame order (Flock.update)

  1. Apply any pending count change.
  2. Run update() for every bird, integrating last frame’s acceleration.
  3. Rebuild the grid.
  4. Run flock() then interact() for every bird.
  5. In particle mode, or when vision is 0, skip the flock() half of step 4. Only interact() runs, and it first sets acceleration to 0, as the base does (boid.js, start of interact). Without that reset, the last frame’s acceleration and the pointer force accumulate and birds never stop accelerating.
  6. Hawks update after step 4, using this frame’s grid (see Hawks).

The grid is rebuilt every frame whenever flocking runs, hawks > 0, or the grid overlay is on.

Timing cases:

  • The Step key and button use delta = 1.
  • The frame rendered at mount uses delta = 1.
  • The base decays explode in the loop even while paused. Keep that: an explode made while paused fades without moving birds.

Neighbours (Boid.neighbors)

  • Candidates come from the 3×3 cells around the bird. Grid cell size is at least the vision radius; see “Grid that wraps”.
  • The bird itself is skipped when sampling, but counted in candidateCount, exactly as the base does (if (this === c[i]) continue;). This also applies in nearest-k mode.
    • Getting this wrong adds each bird’s own velocity, with weight up to 1.5^16, to its alignment.
    • It also guarantees at least one neighbour, so a lone bird is always driven to max speed.
  • Accuracy sampling: visit candidates with step = accuracy === 0 ? 1 : ceil(candidateCount / accuracy) from a random start offset, carried across cells exactly as the base does. This caps the work per bird and is the main reason the base stays fast. Do not drop it.
  • A neighbour is any sampled candidate with squared distance < vision².

Rules (Boid.flock)

  • Alignment: sum of other.vel × bias^(other.vel · this.vel).
  • Cohesion: mean neighbour position.
  • Separation: sum of (self − other) / (d² || 0.00001).
  • If there is at least one neighbour, each sum becomes setMag(maxSpeed) − vel, limited to maxForce. Cohesion first subtracts the bird’s own position.
  • acc = aln × alignment + csn × cohesion + sep × separation.
  • setMag of a zero vector stays zero, as in the base’s V2D. Keep that behaviour; it is the zero-length guard.

Integration (Boid.update)

  1. vel += acc × delta
  2. vel ×= (1 − drag)
  3. Rotate vel by a random angle in ±noiseRange, where noiseRange = π/80 × noise. Recompute this when the noise slider changes.
  4. Apply the minimum speed. If the speed is 0, use a random direction at minSpeed.
  5. Limit to maxSpeed.
  6. pos += vel × delta
  7. Apply the edges:
    • Wrap (default): ((x % W) + W) % W, and likewise for y.
    • Bounce: reflect the velocity component and constrain the position, as in the base.

Pointer force (Boid.interact)

  • While the pointer is down, every bird gets a force toward the pointer of magnitude 10000 / (d² || 1), limited to mouseForce. It is added to attract and subtracted to repel.
  • mouseForce = max(maxSpeed × maxForce × (alignment + cohesion + separation + 1) / 16, 0), recomputed each frame.

Explode

A double-click or double-tap at a point triggers it. A double-tap is two pointerdown events that are each primary (isPrimary) and button 0, within 500 ms and 40 px of each other. Two-finger touches and right-clicks never trigger it. The explode:

  • sets explode = 1
  • pushes every bird away from the point with magnitude explode × 100000 / (d² || 1), limited to 3 × mouseForce
  • decays with explode ×= 0.9 each frame and stops below 0.001

The visual: draw a circle of radius 100 × √explode at the point, filled rgba(255,255,255,0.15 × √explode). The base draws a black disc, which would vanish on our sky.

Defaults and ranges

These are the base’s values, except bird count:

Option Range Step Default
Birds 100 – 20,000 100 3,000 desktop / 800 phone
Accuracy (power) 2.25 – 10 0.25 5; accuracy = 2^p, and 10 means unlimited (0)
Vision 0 – 150 5 25
Alignment 0 – 4 0.1 1.1
Bias 0.25 – 4 0.05 1.5
Cohesion 0 – 4 0.1 1
Separation 0 – 4 0.1 1.1
Max force 0 – 1 0.05 0.2
Min speed 0 – max speed 0.05 1
Max speed 0 – 12 0.25 4
Drag 0 – 0.05 0.001 0.005
Noise 0 – 10 0.5 1

When max speed drops below min speed, lower min speed to match, as the base does.

Toggles from the base:

Toggle Base option Default
Colour by speed hues off; on in the base, but our default look is Natural
Show vision areas areas off
Show desired direction desired off
Show spatial grid buckets off
Particle mode particle off
Bounce edges bounce off
Pause paused off

Step one frame while paused: the “.” key, plus a Step button.

What changes from the base

  1. Data layout. Use structure-of-arrays typed arrays instead of V2D objects:

    • Float32Array for x, y, vx, vy, ax, ay, preallocated for 20,000 birds.
    • The grid is a counting sort (cellCount, cellStart, sortedIdx) instead of nested arrays.
    • The maths stays identical, including the setMag and limit semantics.
    • Changing the count never reallocates. Growing it spawns birds the way the base constructor does (random position, random direction at a speed between min and max). Shrinking it truncates.
    • The base draws random numbers from a 65,535-entry lookup table in util.js. Replace it with Math.random(); the two are equivalent.
  2. Grid that wraps. This fixes a base bug: the base never looks across the world edge, so flocks split at the seam.

    • Let S = max(vision, 25). The floor of 25 keeps the grid finite at vision 0 and bounded at low vision.
    • Use nx = max(1, floor(W / S)) and cellW = W / nx, and likewise ny and cellH. Every cell is then at least vision wide, with no partial cell at the seam. Do not use the base’s ceil.
    • This changes cell boundaries slightly, and with them the candidate counts that accuracy sampling sees. Accept that, and note it in the log.
    • In wrap mode, neighbouring cell coordinates wrap modulo nx/ny. Distance and separation use the shortest toroidal delta: if |dx| > W/2, add or subtract W, and likewise for dy.
    • Cohesion averages the neighbours’ positions as self + toroidal delta.
    • In bounce mode, nothing wraps and cells off the edge are skipped.
    • If an axis has fewer than 3 cells, visit each of its cells exactly once. Never visit a cell twice.
    • Clamp every computed cell coordinate to [0, n−1], because the bounce constraint can leave x == W.
  3. Renderer. Canvas 2D instead of PixiJS (see Rendering).

  4. Input.

    • Pointer Events on the canvas instead of mouse and touch listeners on document.
    • A tool selector replaces the right mouse button, because phones have none (see Additions).
  5. Mount contract.

    • No globals.
    • No listeners on window or document. Use a ResizeObserver on the stage instead of window.resize.
    • Everything is torn down in cleanup.
  6. fps readout. It is always visible. In the base it appears only with debug on.

Dropped from the base:

  • the “hide boids”, “outlines” and “half areas” toggles
  • the menu toggle shortcuts
  • URL-encoded settings

Additions

Murmuration look

  • Sky: vertical gradient, top #141a33 → 60% #3a2f4f → bottom #c0705a. Cache it and rebuild it on resize only.
  • Birds: the base’s dart shape, points (6,0), (−6,−4), (−4,0), (−6,4), rotated to the velocity. Fill #0b0d12 at alpha 0.8, the base’s alpha.
  • Colour by speed uses the base’s mapping:
    • The fill is hsv(h, 1, 1), where h = clamp(|vel| / (2 × maxSpeed), 0, 1), quantised into 12 buckets over h in 0–1.
    • Speed never exceeds maxSpeed, so h ≤ 0.5 and only the red-to-cyan half is used. That is the base’s behaviour; keep it.

Hawks

Hawks are set with a slider from 0 to 5, default 0. Each hawk:

  • Is stored separately from the birds, with its own position, velocity, target index and timers.
  • Updates once per frame after the birds’ interact() (frame step 6):
    1. Steers in the base’s style: (target − pos).setMag(1.3 × maxSpeed) − vel, limited to maxForce, using toroidal deltas in wrap mode.
    2. Integrates the velocity with delta.
    3. Applies the same drag as birds, and no noise.
    4. Limits speed to the range [0.65 × maxSpeed, 1.3 × maxSpeed]. Hawks must be faster than birds or they can never catch one.
    5. Moves, then wraps or bounces like the birds.
  • Targets the nearest bird within 150 px, re-evaluated every 30 frames:
    • Search the grid cells covering that radius, but only if the cell size is ≥ 30.
    • Otherwise, brute-force over 64 random birds.
  • If no bird is within 150 px, steers toward the centroid of 64 random birds, re-sampled every 120 frames. Compute the centroid with toroidal deltas relative to the first sample.
  • Within 12 px of its target, it keeps its current velocity with no steering for 60 frames, then retargets. Birds are never removed.
  • After any count change, clears any target index ≥ count.
  • Is drawn as a filled 14 px triangle, #ff5a4e, with a 1 px light outline, after the birds.

Flee: birds within 90 px of any hawk add (self − hawk).setMag(maxSpeed) − vel, limited to maxForce, then × 3.

  • Use toroidal deltas in wrap mode.
  • This is added in interact(), after the particle-mode reset.
  • Find hawks by brute force; there are at most 5.

Nearest-7 mode

Real starlings track about 7 nearest neighbours rather than everyone within a distance (Ballerini et al., PNAS 2008).

  • When the toggle is on, a bird’s neighbours are the k nearest sampled candidates in its 3×3 block, excluding itself, regardless of the vision distance.
  • k is a slider from 3 to 15, default 7, and is enabled only in this mode.
  • The rules are otherwise unchanged.
  • Keep the best k in a fixed-size insertion array.
  • Measure the cost and record it.

Trails

  • Off: repaint the sky each frame.
  • On: paint the sky at globalAlpha 0.25 instead, and repaint it fully every 10 s to clear 8-bit ghosting.

Dot mode

  • At 6,000 birds or more, draw each bird as a 2×2 px rect() instead of a dart.
  • Show “dot mode” in the readout.

Tool selector

A segmented control: Attract | Repel.

  • The selected tool sets the pointer direction.
  • On desktop, right-click or Shift held while dragging inverts it, preserving the base’s right-click repel.
  • Double-tap or double-click explodes with either tool.

Rendering

  • Batching: for each colour bucket:

    1. Call ctx.beginPath().
    2. Append every bird with moveTo/lineTo/closePath, or rect in dot mode.
    3. Call fill() once.

    Never draw birds one call at a time, and do not allocate a Path2D per frame.

  • Rotation: compute the heading from vel / |vel| directly, with no atan2, sin or cos per bird. If |vel| == 0, point the bird right.

  • Debug overlays draw only when enabled:

    • Vision areas: circles of radius vision, filled white at alpha 0.03.
      • Batch them into one path, with moveTo(x + r, y) before each arc so no connecting lines are drawn.
      • Overlapping circles then share one alpha instead of stacking as in the base. Accept that and note it.
    • Desired direction: a 24 px line along acc, shown when |acc|² > 0.01. Stroke #fb0301, width 2, alpha 0.5.
    • Overlays and the explode circle are drawn after the trails fade, so they do not smear.
    • Spatial grid: cell lines at alpha 0.3.
  • Pointer feedback: while the pointer is down, draw a faint ring at the pointer.

Layout and sizing

  • mount(container) creates a root with tabindex="0" and these styles: display:flex; flex-direction:column; height:max(70vh, 480px); outline:none.

  • The root holds:

    • a .demo-controls bar, styled with the classes from src/styles/global.css
    • a stage div: flex:1; position:relative; min-height:0
  • The canvas fills the stage absolutely, with touch-action:none.

  • The canvas follows the stage, never the reverse. The container only has min-height, so this prevents a ResizeObserver feedback loop.

  • The readout is an overlay at the top-left of the stage, not in the controls bar: pointer-events:none, font-variant-numeric: tabular-nums.

    • It shows fps (smoothed over 0.5 s, updated at most 4 times a second), bird count, and “dot mode” when active.
    • Changing text inside the controls bar would re-wrap it, resize the stage and loop the observer.
  • HiDPI:

    • Set the backing size to round(css × dpr), where dpr = min(devicePixelRatio, 2).
    • Draw with setTransform(dpr,0,0,dpr,0,0).
    • Ignore observed sizes under 1 px.
  • On resize:

    • Wrap birds into the new world in wrap mode, or clamp them in bounce mode.
    • Rebuild the grid and the sky gradient.
    • Repaint the sky.

    Do not reset the flock.

Controls bar

The bar is always visible:

  • Pause/Play
  • Step
  • Reset (respawns birds and hawks, and keeps settings)
  • Tool selector
  • Hawks (0 to 5)
  • Settings

Settings panel

Every slider and base toggle above, plus nearest-7, k and trails.

  • On wide screens it is an overlay on the right of the stage, open by default.
  • On phones it is a bottom sheet, at most 55% of the stage height, scrollable, and closed by default.
  • Sliders apply on input and show their values.

Phone detection

matchMedia('(pointer: coarse)').matches || container.clientWidth < 600, evaluated once at mount. Touch targets are at least 36 px high on phones.

Keyboard

Handle keydown on the root only. Ignore events whose target is an input, select, textarea or button, and call preventDefault on handled keys.

Key Action
Space Pause, from the base
. Step a frame while paused, from the base
R Reset
H Cycle hawks
T Toggle trails

A canvas pointerdown calls root.focus({ preventScroll: true }).

Pointer handling

  • Track one pointerId with setPointerCapture.
  • End the gesture on pointerup, pointercancel and lostpointercapture. iOS sends pointercancel; without it, Attract sticks on.
  • Clamp pointer coordinates to the world.
  • Prevent the context menu on the canvas, as the base does.

Lifecycle

  • Render one frame synchronously at the end of mount.
  • Pause the loop while the stage is off-screen, using an IntersectionObserver.
  • On any resume, reset the last-frame timestamp so the first delta is not huge. delta is capped at 2 anyway, as in the base.
  • If prefers-reduced-motion: reduce is set, start paused with Play visible.
  • Cleanup does all of the following:
    • cancels requestAnimationFrame
    • disconnects both observers
    • removes every listener
    • empties the container

Files

projects/birds/demo/
  index.ts     mount(): DOM, loop, wiring, cleanup
  flock.ts     ported Flock + Boid maths on typed arrays; hawks; nearest-7. No DOM access.
  grid.ts      counting-sort grid, wrap-aware 3x3 and 5x5 iteration. No DOM access.
  render.ts    sky, birds, hawks, overlays, trails, dot mode
  controls.ts  controls bar, settings panel, options object

project.json

The rename is already applied: title “Birds”, with the new tagline and description. Set status to building when you start and to live when done. Leave the other fields alone.

Build order

Commit after each step. Each step has a checkpoint.

  1. Skeleton. Mount, layout, HiDPI canvas, sky, loop, cleanup. Check: the canvas fills the container at any size, with no growth loop.
  2. Port the core. Port Flock, Boid and the options with the base’s defaults, including accuracy sampling, straight onto the new counting-sort grid. Render darts. Check: compare the port with the base numerically, in bounce mode, where the two grids agree on neighbours.
    1. Serve the base locally. Its lib/pixi.min.js is vendored, so npx serve on the clone works.
    2. Load both in headless Chromium at 1,000×700, with 1,500 birds and default settings.
    3. After 600 frames, compute in each:
      • polarisation: the length of the mean unit velocity
      • mean neighbour count per bird
    4. They must agree within 15%. Record both pairs in BUILD-LOG.md.
    • For the base, read its global flock from the page.
  3. Wrap. Turn on wrap-aware lookups and toroidal deltas. Check: a flock crosses the wrap edge without splitting; turning on “show spatial grid” confirms the cells.
  4. Controls and settings panel, with every base option. Check: the phone layout works at 375×667.
  5. Pointer, tool selector and explode, with touch. Check: works with a mouse and in DevTools touch emulation.
  6. Hawks. Check: the flock visibly splits and reforms.
  7. Dot mode, trails, nearest-7.
  8. Build log and screenshot.
    • Run npm run check and npm run build, then set status to live.
    • Screenshot with a throwaway headless Chromium script. Do not add Playwright to package.json.

Cut list, in this order:

  1. nearest-7
  2. trails
  3. dot mode (then cap the slider at 10,000)
  4. desired-direction overlay

Record any cuts under “What I would do next”.

Out of scope: obstacles, presets, a benchmark, WebGPU, 3D, sound, workers, saving settings.

Acceptance checklist

  • npm run check and npm run build pass. No new dependencies. Only projects/birds/ changed.
  • With the same settings, the behaviour matches the base (step 2 check). Any deviation is recorded in BUILD-LOG.md.
  • First load shows 3,000 birds on desktop or 800 on a phone, flocking on the dusk sky without interaction.
  • The canvas is sharp at dpr 2. Resizing or rotating keeps the flock and never grows the container.
  • In wrap mode, a flock crosses the edge without splitting.
  • Every base option in the tables exists with the stated range and default, and applies live.
  • Attract, Repel and explode work with a mouse and with touch. A second finger does not break tracking. pointercancel ends Attract.
  • 1–5 hawks chase, and the flock flees and reforms. 0 removes them.
  • Dot mode engages at 6,000 or more birds and shows in the readout.
  • Keyboard shortcuts work after clicking the canvas. Space on a focused button does not also pause. The page does not scroll.
  • Target: 5,000 birds with 2 hawks at 55 fps or more on a mid-range laptop. Drew verifies this with the readout. Record any numbers you measured in BUILD-LOG.md, labelled “headless” if taken in the container.
  • Phone, portrait: 800 birds run smoothly, the settings sheet scrolls, and touch tools work.
    • The builder checks layout, sharpness and touch in headless Chromium at 375×667 with --force-device-scale-factor=2 and touch emulation, and records the results.
    • Drew verifies smoothness on a real phone.
  • Leaving the page stops all animation frames and observers. No console errors.
  • The MIT notice is in the ported files. BUILD-LOG.md credits the base with a link and the commit hash, and covers everything CLAUDE.md requires.
  • media/ has a screenshot, referenced from BUILD-LOG.md.