Skip to content

A motion design toolkit for coding agents.

JavaScript

Add web sims: one HTML page per piece, captured frame by frame to 60 fps

whaleyb2a30afc5483
diff --git a/.claude/skills/web-sims/SKILL.md b/.claude/skills/web-sims/SKILL.md
new file mode 100644
index 0000000..a4a6d21
--- /dev/null
+++ b/.claude/skills/web-sims/SKILL.md
@@ -0,0 +1,50 @@
+---
+name: web-sims
+description: Build a simulation-style video (agents, particles, 3D machines, fly-throughs) as one HTML page whose render(t) is a pure function of time, then capture it frame by frame to a 60 fps mp4 with sims/capture.mjs. Use when the idea is a simulation or a 3D object rather than motion graphics with text and UI.
+---
+
+# Web sims
+
+Read `sims/README.md` first; it has the contract and every command.
+
+## When to use this instead of Remotion
+
+- Hundreds of moving things with their own rules (agents, particles, crawlers).
+- A 3D object or machine the camera moves around or flies through.
+- Anything that is easier to write as a three.js or canvas page than as React.
+
+Motion graphics with type, UI and timed reveals stay in Remotion (`src/`).
+
+## Workflow
+
+1. Agree on the idea, the hero moment and the length with the user. Default
+ format: 1080×1350 layout (4:5), 60 fps, 20–24 s.
+2. Put every beat in a `timeline.json` next to the sim (chapters, the hero
+ moment, camera keys). Sound scripts read the same file.
+3. Start from the closest example: `crawlers` (agents on DOM text),
+ `dossier` (the same plus screen-space overlays), `engine` (three.js object
+ with cutaway, chapters, fly-through, exploded view, generated sound).
+4. Simulate anything stateful once at load; `render(t)` only reads it.
+5. Build: `node sims/build.mjs <name>`.
+6. Review with stills at every beat:
+ `node sims/capture.mjs <name> --stills 0,2,5,8,12,16,20 --cols 4 --out out/sims/<name>-review.png`.
+ Open the sheet and check it like the review loop says: frame 0 strong,
+ one focal point per frame, nothing blown out by bloom, text readable on a
+ phone, labels never cover the subject. Fix and repeat.
+7. Sound: a music track (`--music`, the sim gets `cfg.beats` and should hit
+ the drop), a generated bed (`python3 sims/<name>/sound.py` like
+ `sims/engine/sound.py`), or both mixed with ffmpeg first.
+8. Capture: `node sims/capture.mjs <name> --size 1080x1350 --out out/sims/<name>.mp4`
+ and look at a sheet of the final file before calling it done.
+
+## Lessons from the examples
+
+- Bloom eats detail: keep emissive and additive layers under ~1.0 and raise
+ them only for the one hero moment.
+- Glossy metal plus a low sun gives white streaks. Use roughness ≥ 0.45 and
+ envMapIntensity ≈ 0.5 on big surfaces.
+- One hero object beats a crowd. If parts hide the subject, move them out of
+ the way or fade them.
+- Chapters + a one-line caption per step + labels with real numbers make a
+ simulation read as an explanation, not just eye candy.
+- A camera that flies *through* the object is worth more than ten orbits.
diff --git a/.gitignore b/.gitignore
index e4953e3..d5cbbe3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ __pycache__/
.mcp.json
.env
drafts/
+sims/dist/
diff --git a/AGENTS.md b/AGENTS.md
index 3f3a0bd..c806dd5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,6 +9,7 @@ The skills in `.claude/skills/` are the core of this repo. Claude Code and Curso
- `motion-design/SKILL.md`: easing, springs, timing, type, color, texture, transitions, with numbers.
- `review-loop/SKILL.md`: how to look at your own renders and what to check. Mandatory before saying a video is done.
- `sound-design/SKILL.md`: writing a cue sheet for the `sfx` engine, levels, mastering, adding generators.
+- `web-sims/SKILL.md`: simulations and 3D pieces built as one HTML page and captured frame by frame to 60 fps (`sims/`).
## Making a video
@@ -21,6 +22,10 @@ The skills in `.claude/skills/` are the core of this repo. Claude Code and Curso
7. Render, mux, and check loudness on the final file.
8. Add the piece to `examples/` with the prompt you were given.
+## Simulations and 3D
+
+When the idea is a simulation (agents, particles, a machine the camera flies through) rather than motion graphics, use the `sims/` pipeline instead of Remotion: one HTML page per piece, `render(t)` pure in time, `node sims/capture.mjs` steps it frame by frame into an mp4. Guide and commands: `sims/README.md`; workflow: `web-sims/SKILL.md`. Capture needs a Chromium: `npx playwright install chromium` once, or set `$CHROMIUM`.
+
## Tools
| Command | What it does |
@@ -56,6 +61,8 @@ src/components/ reusable pieces: primitives (Mask, Roll, Spark, Grain,
src/EffortVideo.tsx example piece; its scenes in src/scenes/, its timeline in timeline.json
src/ArticleCover.tsx example still: a 2000×800 cover drawn from the same timeline
examples/ gallery: prompt, process and result for each piece
+sims/ web sims → video: kit/, build.mjs, capture.mjs, beats.py, examples crawlers/ dossier/ engine/
+sfx/dsp.py filters, oscillators, reverb for longer sound scripts (used by sims/engine/sound.py)
```
## Conventions
diff --git a/README.md b/README.md
index 188ebba..20b27da 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# claude-motion
-**A motion design toolkit for coding agents.** Remotion skills teach your agent the API. This teaches it taste, makes it check its own frames, and gives it a sound engine.
+**A motion design toolkit for coding agents.** Remotion skills teach your agent the API. This teaches it taste, makes it check its own frames, and gives it a sound engine. And when the idea is a simulation, not a motion graphic, it renders web sims frame by frame to 60 fps video.
Works with Claude Code and Cursor out of the box (skills in `.claude/skills/`), and with Codex, OpenCode or anything else that reads `AGENTS.md`.
@@ -12,6 +12,38 @@ Works with Claude Code and Cursor out of the box (skills in `.claude/skills/`),
<!-- For the version with sound: open this README in the GitHub editor, drag out/effort.mp4 in, and GitHub will turn it into an inline player. -->
+## New: web sims → 60 fps video
+
+<p align="center">
+ <img src="media/sims/crawlers.gif" width="250" alt="256 spider agents crawling a wall of websites" />
+ <img src="media/sims/dossier.gif" width="250" alt="Agents turning one username into a dossier with red threads" />
+ <img src="media/sims/engine.gif" width="250" alt="Camera flying through a running rocket engine's chamber" />
+</p>
+
+<p align="center"><sub>Made by Claude with this toolkit. Left: <a href="https://x.com/whaleyxbt/status/2106099822088331481">the crawler swarm</a> (340K+ views on X). Middle: <a href="https://x.com/whaleyxbt/status/2106420024286031963">one username → a dossier</a>. Right: a rocket engine explorer with a fly-through and an exploded view.</sub></p>
+
+Some videos are simulations: 256 agents doubling on the beat, a rocket engine the camera flies through. Those are easier to write as a web page than as React, so [`sims/`](sims/) is a second pipeline:
+
+- **One HTML page per piece**, three.js and fonts inlined, works offline. Open it and it plays live.
+- **`render(t)` is a pure function of time.** Agents and physics are simulated once at load, so any frame can be drawn on demand.
+- **Frame-exact capture.** Headless Chromium steps the page frame by frame into ffmpeg: 60 fps at 1440×1800 (or any size), no matter how slow a frame is.
+- **Cuts on the beat.** `beats.py` finds the tempo, bars and drop of a track and hands them to the sim.
+- **Three examples to take apart:** [`crawlers`](sims/crawlers/), [`dossier`](sims/dossier/), [`engine`](sims/engine/) (with its sound generated in Python).
+
+```bash
+npm install && npx playwright install chromium
+npm run sims # → sims/dist/<name>.html
+npm run capture -- engine --size 1080x1350 --out out/engine.mp4 # 1440×1800, 60 fps
+```
+
+Ask your agent:
+
+```text
+Read sims/README.md and the web-sims skill. Build a 20-second sim of <your idea>
+as one HTML page at 1080×1350. Review it with --stills before you render,
+then capture it to a 60 fps mp4.
+```
+
## What your agent gets
**Motion rules with numbers.** Easing curves, spring presets, stagger, reading holds, type scale, one-accent color, texture, motivated transitions. Not "make it smooth": `bezier(0.16, 1, 0.3, 1)` for entrances, exits at half the duration, 0.09 s between words. → [`motion-design`](.claude/skills/motion-design/SKILL.md)
@@ -33,6 +65,7 @@ Clone https://github.com/whaleyxbt/claude-motion and cd into it.
Check that Node 20+, Python 3 and ffmpeg are installed; install whatever is missing.
Run `npm install` and `npm run build`, then show me out/effort.mp4.
Then read AGENTS.md and the skills in .claude/skills/, and ask me what video I want to make next.
+(For simulations and 3D, also run `npx playwright install chromium` and read sims/README.md.)
```
**Or by hand:**
diff --git a/media/sims/crawlers.gif b/media/sims/crawlers.gif
new file mode 100644
index 0000000..45df86c
Binary files /dev/null and b/media/sims/crawlers.gif differ
diff --git a/media/sims/dossier.gif b/media/sims/dossier.gif
new file mode 100644
index 0000000..df39a28
Binary files /dev/null and b/media/sims/dossier.gif differ
diff --git a/media/sims/engine.gif b/media/sims/engine.gif
new file mode 100644
index 0000000..b5e127d
Binary files /dev/null and b/media/sims/engine.gif differ
diff --git a/package-lock.json b/package-lock.json
index 20fab6e..a42bad4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -18,6 +18,9 @@
},
"devDependencies": {
"@types/react": "19.2.2",
+ "esbuild": "0.28.1",
+ "playwright": "1.63.0",
+ "three": "0.186.1",
"typescript": "5.9.3"
}
},
@@ -3189,6 +3192,35 @@
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
+ "node_modules/playwright": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
+ "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.63.0"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
@@ -3684,6 +3716,13 @@
}
}
},
+ "node_modules/three": {
+ "version": "0.186.1",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",
+ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/tiny-invariant": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
diff --git a/package.json b/package.json
index ee93d85..eda8879 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "effort-video",
"version": "1.0.0",
"private": true,
- "description": "Motion design pipeline for coding agents: taste rules, timeline-synced sound, and a visual self-review loop. Built with Remotion.",
+ "description": "Motion design pipeline for coding agents: taste rules, timeline-synced sound, a visual self-review loop (Remotion), and web sims captured frame by frame to 60 fps video.",
"scripts": {
"studio": "remotion studio",
"still": "remotion still EffortVideo",
@@ -15,7 +15,9 @@
"wave": "node scripts/wave.mjs",
"cover": "remotion still ArticleCover out/article-cover.png",
"gif": "ffmpeg -loglevel error -y -i out/effort.mp4 -vf \"fps=12,scale=420:-1:flags=lanczos,hqdn3d=4:4:6:6,split[a][b];[a]palettegen=max_colors=64:stats_mode=diff[p];[b][p]paletteuse=dither=none:diff_mode=rectangle\" media/preview.gif",
- "typecheck": "tsc"
+ "typecheck": "tsc",
+ "sims": "node sims/build.mjs",
+ "capture": "node sims/capture.mjs"
},
"dependencies": {
"@fontsource-variable/inter": "5.3.0",
@@ -28,6 +30,9 @@
},
"devDependencies": {
"@types/react": "19.2.2",
+ "esbuild": "0.28.1",
+ "playwright": "1.63.0",
+ "three": "0.186.1",
"typescript": "5.9.3"
}
}
diff --git a/sfx/dsp.py b/sfx/dsp.py
new file mode 100644
index 0000000..6363160
--- /dev/null
+++ b/sfx/dsp.py
@@ -0,0 +1,453 @@
+"""DSP building blocks (oscillators, filters, delays, reverb), pure Python stdlib at 48 kHz.
+
+Used by sound scripts that need more than the one-shot generators in synth.py,
+e.g. sims/engine/sound.py.
+
+Signals are plain lists of floats. Speed comes from two tricks:
+
+- A Python per-sample loop costs about 0.3 µs/sample and a list comprehension
+ about 0.05 µs. So constant-pitch oscillators are one comprehension (the naive
+ ramp) plus a sparse PolyBLEP fix-up at each wrap. Feedback delays and the
+ reverb combs/allpasses run one block at a time, where the block is no longer
+ than the delay, so every block depends only on earlier blocks and is a single
+ comprehension.
+- Filters whose state really is sequential (SVF, biquad, ladder) are tight
+ loops, run only on short one-shots or on the few full-length buses that need
+ them.
+"""
+
+import math
+
+from .synth import SR
+
+TAU = 2.0 * math.pi
+_tanh = math.tanh
+
+
+# ---------------------------------------------------------------- buffers
+
+
+def zeros(n):
+ return [0.0] * n
+
+
+def add(dst, src, at=0, gain=1.0):
+ """dst[at:] += gain * src, in place, clipped to dst."""
+ if at < 0:
+ src = src[-at:]
+ at = 0
+ end = min(len(dst), at + len(src))
+ if end <= at:
+ return
+ seg = dst[at:end]
+ if gain == 1.0:
+ dst[at:end] = [a + b for a, b in zip(seg, src)]
+ else:
+ dst[at:end] = [a + b * gain for a, b in zip(seg, src)]
+
+
+def scaled(x, g):
+ return [v * g for v in x]
+
+
+def mul(x, y):
+ return [a * b for a, b in zip(x, y)]
+
+
+def summed(a, b):
+ return [p + q for p, q in zip(a, b)]
+
+
+def rms(x):
+ return math.sqrt(sum(v * v for v in x) / len(x)) if x else 0.0
+
+
+def peak(x):
+ return max(max(x), -min(x)) if x else 0.0
+
+
+def pan_gains(pan):
+ """Equal-power pan, -1 left .. +1 right."""
+ ang = (pan + 1.0) * math.pi / 4.0
+ return math.cos(ang), math.sin(ang)
+
+
+def fade(x, fin=0, fout=0):
+ """Linear fade in/out over fin/fout samples, in place."""
+ n = len(x)
+ fin, fout = min(fin, n), min(fout, n)
+ for i in range(fin):
+ x[i] *= i / fin
+ for i in range(fout):
+ x[n - 1 - i] *= i / fout
+ return x
+
+
+# ------------------------------------------------------------ oscillators
+
+
+def _blep(out, phase, dt, n, h=1.0):
+ """Subtract the PolyBLEP residual at every wrap of the ramp phase + i*dt (downward jump 2h)."""
+ k = 1
+ while True:
+ j = math.ceil((k - phase) / dt)
+ # float guard: make j the first sample whose wrapped phase is small
+ if j < n and (phase + j * dt) % 1.0 > 0.5:
+ j += 1
+ if j >= 1 and (phase + (j - 1) * dt) % 1.0 < 0.5:
+ j -= 1
+ if j - 1 >= n:
+ break
+ if 0 <= j < n:
+ u = ((phase + j * dt) % 1.0) / dt
+ if u < 1.0:
+ out[j] -= h * (u + u - u * u - 1.0)
+ if 1 <= j <= n:
+ u = (((phase + (j - 1) * dt) % 1.0) - 1.0) / dt
+ if u > -1.0:
+ out[j - 1] -= h * (u * u + u + u + 1.0)
+ k += 1
+
+
+def saw(freq, n, phase=0.0):
+ """Band-limited sawtooth (PolyBLEP) at constant freq, -1..1."""
+ dt = freq / SR
+ phase %= 1.0
+ out = [2.0 * ((phase + i * dt) % 1.0) - 1.0 for i in range(n)]
+ if 0.0 < dt < 0.5:
+ _blep(out, phase, dt, n)
+ return out
+
+
+def pulse(freq, n, width=0.5, phase=0.0):
+ """Band-limited pulse as the difference of two PolyBLEP saws; zero mean."""
+ a = saw(freq, n, phase)
+ b = saw(freq, n, phase + width)
+ return [p - q for p, q in zip(a, b)]
+
+
+def sine(freq, n, phase=0.0):
+ w = TAU * freq / SR
+ ph = TAU * phase
+ sin = math.sin
+ return [sin(ph + w * i) for i in range(n)]
+
+
+def noise(rng, n):
+ r = rng.random
+ return [2.0 * r() - 1.0 for _ in range(n)]
+
+
+# ---------------------------------------------------------------- filters
+
+
+def _norm(b0, b1, b2, a0, a1, a2):
+ return (b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0)
+
+
+def lp(fc, q=0.7071):
+ w = TAU * min(fc, 0.45 * SR) / SR
+ c, al = math.cos(w), math.sin(w) / (2 * q)
+ return _norm((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + al, -2 * c, 1 - al)
+
+
+def hp(fc, q=0.7071):
+ w = TAU * min(fc, 0.45 * SR) / SR
+ c, al = math.cos(w), math.sin(w) / (2 * q)
+ return _norm((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + al, -2 * c, 1 - al)
+
+
+def bp(fc, q=1.0):
+ w = TAU * min(fc, 0.45 * SR) / SR
+ c, al = math.cos(w), math.sin(w) / (2 * q)
+ return _norm(al, 0.0, -al, 1 + al, -2 * c, 1 - al)
+
+
+def peaking(fc, q, db):
+ a = 10 ** (db / 40)
+ w = TAU * min(fc, 0.45 * SR) / SR
+ c, al = math.cos(w), math.sin(w) / (2 * q)
+ return _norm(1 + al * a, -2 * c, 1 - al * a, 1 + al / a, -2 * c, 1 - al / a)
+
+
+def shelf(fc, db, high=True):
+ a = 10 ** (db / 40)
+ w = TAU * min(fc, 0.45 * SR) / SR
+ c, s = math.cos(w), math.sin(w)
+ al = s / 2 * math.sqrt(2)
+ sa = 2 * math.sqrt(a) * al
+ if high:
+ return _norm(
+ a * ((a + 1) + (a - 1) * c + sa), -2 * a * ((a - 1) + (a + 1) * c), a * ((a + 1) + (a - 1) * c - sa),
+ (a + 1) - (a - 1) * c + sa, 2 * ((a - 1) - (a + 1) * c), (a + 1) - (a - 1) * c - sa,
+ )
+ return _norm(
+ a * ((a + 1) - (a - 1) * c + sa), 2 * a * ((a - 1) - (a + 1) * c), a * ((a + 1) - (a - 1) * c - sa),
+ (a + 1) + (a - 1) * c + sa, -2 * ((a - 1) + (a + 1) * c), (a + 1) + (a - 1) * c - sa,
+ )
+
+
+def biquad(x, c):
+ """Static biquad (transposed direct form II); c from lp/hp/bp/peaking/shelf."""
+ b0, b1, b2, a1, a2 = c
+ z1 = z2 = 0.0
+ out = [0.0] * len(x)
+ i = 0
+ for v in x:
+ y = b0 * v + z1
+ z1 = b1 * v - a1 * y + z2
+ z2 = b2 * v - a2 * y
+ out[i] = y
+ i += 1
+ return out
+
+
+def svf(x, fc, q=0.7071, mode="lp", ctrl=32):
+ """Zero-delay-feedback state-variable filter (Cytomic/Simper), stable under fast modulation.
+
+ fc: Hz, or a function of the sample index evaluated every `ctrl` samples.
+ mode: 'lp', 'bp' or 'hp'.
+ """
+ n = len(x)
+ out = [0.0] * n
+ k = 1.0 / q
+ ic1 = ic2 = 0.0
+ const = not callable(fc)
+ if const:
+ ctrl = max(n, 1)
+ tan = math.tan
+ pis = math.pi / SR
+ for s in range(0, n, ctrl):
+ f = fc if const else fc(s)
+ f = 10.0 if f < 10.0 else 20000.0 if f > 20000.0 else f
+ g = tan(pis * f)
+ a1 = 1.0 / (1.0 + g * (g + k))
+ a2 = g * a1
+ a3 = g * a2
+ e = s + ctrl if s + ctrl < n else n
+ if mode == "lp":
+ for i in range(s, e):
+ v3 = x[i] - ic2
+ v1 = a1 * ic1 + a2 * v3
+ v2 = ic2 + a2 * ic1 + a3 * v3
+ ic1 = v1 + v1 - ic1
+ ic2 = v2 + v2 - ic2
+ out[i] = v2
+ elif mode == "bp":
+ for i in range(s, e):
+ v3 = x[i] - ic2
+ v1 = a1 * ic1 + a2 * v3
+ v2 = ic2 + a2 * ic1 + a3 * v3
+ ic1 = v1 + v1 - ic1
+ ic2 = v2 + v2 - ic2
+ out[i] = v1
+ else:
+ for i in range(s, e):
+ xi = x[i]
+ v3 = xi - ic2
+ v1 = a1 * ic1 + a2 * v3
+ v2 = ic2 + a2 * ic1 + a3 * v3
+ ic1 = v1 + v1 - ic1
+ ic2 = v2 + v2 - ic2
+ out[i] = xi - k * v1 - v2
+ return out
+
+
+def onepole_hp(x, fc):
+ """Gentle 6 dB/oct high-pass; used as a DC blocker."""
+ a = math.exp(-TAU * fc / SR)
+ out = [0.0] * len(x)
+ px = py = 0.0
+ i = 0
+ for v in x:
+ py = a * (py + v - px)
+ px = v
+ out[i] = py
+ i += 1
+ return out
+
+
+def sweep(x, start, end, f0, f1, mode="lp", q=0.9, wet_in=0.0, wet_out=0.0):
+ """Filter x[start:end] in place, cutoff gliding exponentially f0 -> f1.
+
+ wet_in / wet_out (fractions of the region) crossfade from / back to the
+ dry signal, so the region's edges are seamless.
+ """
+ start, end = max(0, start), min(len(x), end)
+ n = end - start
+ if n <= 0:
+ return
+ seg = x[start:end]
+ r = f1 / f0
+ y = svf(seg, lambda i: f0 * r ** (i / n), q, mode, 32)
+ a = max(1, int(wet_in * n))
+ b = max(1, int(wet_out * n))
+ out = []
+ for i in range(n):
+ w = 1.0
+ if wet_in and i < a:
+ w = i / a
+ if wet_out and i > n - b:
+ w = min(w, (n - i) / b)
+ out.append(seg[i] + (y[i] - seg[i]) * w)
+ x[start:end] = out
+
+
+# ------------------------------------------------------- delay and reverb
+
+_COMBS = (1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617)
+_ALLPASSES = (556, 441, 341, 225)
+
+
+def _comb(x, m, fb, damp):
+ """Freeverb comb, block-vectorized; the in-loop damping is a 2-tap low-pass."""
+ n = len(x)
+ a = fb * (1.0 - damp)
+ b = fb * damp
+ w = [0.0] * (n + m + 1) # w[i + m + 1] = W(i)
+ for s in range(0, n, m):
+ e = min(s + m, n)
+ w[s + m + 1:e + m + 1] = [xi + a * p + b * q for xi, p, q in zip(x[s:e], w[s + 1:e + 1], w[s:e])]
+ return w[1:n + 1]
+
+
+def _allpass(x, m, g=0.5):
+ n = len(x)
+ v = [0.0] * (n + m) # v[i + m] = V(i)
+ for s in range(0, n, m):
+ e = min(s + m, n)
+ v[s + m:e + m] = [xi + g * p for xi, p in zip(x[s:e], v[s:e])]
+ return [p - xi for xi, p in zip(x, v)]
+
+
+def reverb(x, size=0.7, damp=0.45, scale=1.0, spread=23):
+ """Freeverb (8 combs + 4 allpasses per side): mono in, (left, right) wet out.
+
+ size 0..1 maps to comb feedback 0.7..0.98; scale stretches every delay
+ (0.3 = small room, 1.5 = hall). Output is roughly level-matched to input.
+ """
+ fb = 0.7 + 0.28 * size
+ r = SR / 44100 * scale
+ outs = []
+ for off in (0, spread):
+ acc = None
+ for m in _COMBS:
+ c = _comb(x, max(8, int((m + off) * r)), fb, damp)
+ acc = c if acc is None else [p + q for p, q in zip(acc, c)]
+ for m in _ALLPASSES:
+ acc = _allpass(acc, max(8, int((m + off) * r)))
+ outs.append(acc)
+ g = math.sqrt((1 - fb * fb) / 8.0) * 1.4
+ return [v * g for v in outs[0]], [v * g for v in outs[1]]
+
+
+def pingpong(x, d, fb=0.5, damp=0.35):
+ """Ping-pong delay, mono in -> (left, right) wet; first echo left at d samples, then alternating."""
+ n = len(x)
+ xp = [0.0] * d + x
+ a = [0.0] * (n + d + 1) # a[i + d + 1] = A(i)
+ b = [0.0] * (n + d + 1)
+ c0 = fb * (1.0 - damp)
+ c1 = fb * damp
+ for s in range(0, n, d):
+ e = min(s + d, n)
+ av = [xi + c0 * p + c1 * q for xi, p, q in zip(xp[s:e], b[s + 1:e + 1], b[s:e])]
+ bv = [c0 * p + c1 * q for p, q in zip(a[s + 1:e + 1], a[s:e])]
+ a[s + d + 1:e + d + 1] = av
+ b[s + d + 1:e + d + 1] = bv
+ return a[d + 1:], b[d + 1:]
+
+
+# --------------------------------------------------------------- dynamics
+
+
+def softclip(x, drive=1.5):
+ norm = 1.0 / _tanh(drive)
+ return [_tanh(drive * v) * norm for v in x]
+
+
+def compress(left, right, thresh_db=-12.0, ratio=2.0, attack=0.01, release=0.15, knee_db=6.0, block=64):
+ """Stereo-linked RMS bus compressor at control rate (one gain per block, interpolated)."""
+ n = len(left)
+ pw = [a * a + b * b for a, b in zip(left, right)]
+ ca = math.exp(-block / (attack * SR))
+ cr = math.exp(-block / (release * SR))
+ slope = 1.0 / ratio - 1.0
+ half = knee_db / 2
+ gr = 0.0
+ gains = []
+ # warm the detector on the first second so the start isn't uncompressed
+ for warm in (True, False):
+ for s in range(0, n if not warm else min(n, SR), block):
+ p = sum(pw[s:s + block]) / (2 * block)
+ db = 10 * math.log10(p + 1e-12)
+ over = db - thresh_db
+ if over <= -half:
+ want = 0.0
+ elif over < half:
+ want = slope * (over + half) ** 2 / (2 * knee_db)
+ else:
+ want = slope * over
+ c = ca if want < gr else cr
+ gr = c * gr + (1 - c) * want
+ if not warm:
+ gains.append(10 ** (gr / 20))
+ ramp = [k / block for k in range(block)]
+ g = []
+ prev = gains[0]
+ for cur in gains:
+ d = cur - prev
+ g.extend([prev + d * r for r in ramp])
+ prev = cur
+ return [a * b for a, b in zip(left, g)], [a * b for a, b in zip(right, g)]
+
+
+def mono_below(left, right, fc=120.0):
+ """Collapse the side signal below fc (24 dB/oct), so the low end is mono."""
+ mid = [(a + b) * 0.5 for a, b in zip(left, right)]
+ side = [(a - b) * 0.5 for a, b in zip(left, right)]
+ c = hp(fc)
+ side = biquad(biquad(side, c), c)
+ return [m + s for m, s in zip(mid, side)], [m - s for m, s in zip(mid, side)]
+
+
+# --------------------------------------------------------- glitch effects
+
+
+def crush(x, bits=8, hold=2):
+ """Bit and sample-rate reduction (intentionally aliasing)."""
+ q = float(2 ** (bits - 1))
+ return [round(x[i - i % hold] * q) / q for i in range(len(x))]
+
+
+def stutter(x, start, slice_n, repeats, decay=0.9, edge=48):
+ """Beat-repeat in place: x[start:start+slice_n] repeated `repeats` times."""
+ sl = x[start:start + slice_n]
+ if len(sl) < slice_n:
+ return
+ sl = fade(sl[:], edge, edge)
+ for r in range(repeats):
+ a = start + r * slice_n
+ if a + slice_n > len(x):
+ break
+ x[a:a + slice_n] = [v * decay ** r for v in sl]
+
+
+def tapestop(x, start, n, curve=1.6):
+ """Tape stop in place over x[start:start+n]: playback slows to zero."""
+ seg = x[start:start + n]
+ n = len(seg)
+ if n < 2:
+ return
+ out = []
+ pos = 0.0
+ for i in range(n):
+ j = int(pos)
+ if j + 1 >= n:
+ out.append(0.0)
+ else:
+ f = pos - j
+ out.append(seg[j] + (seg[j + 1] - seg[j]) * f)
+ pos += (1 - i / n) ** curve
+ fade(out, 0, min(n, 480))
+ x[start:start + n] = out
diff --git a/sims/README.md b/sims/README.md
new file mode 100644
index 0000000..0975ee2
--- /dev/null
+++ b/sims/README.md
@@ -0,0 +1,100 @@
+# Web sims → 60 fps video
+
+Some videos aren't motion graphics, they're simulations: 256 agents crawling
+a wall of websites, a rocket engine you can fly through. Those are easier to
+build as a web page than as a Remotion composition, so this folder is a second
+pipeline for them:
+
+1. A sim is **one HTML page** (`sims/<name>/main.js`, bundled to
+ `sims/dist/<name>.html` with three.js and fonts inlined, works offline).
+2. Its `render(t)` is a **pure function of time**. Heavy work (agents, paths,
+ collisions) is simulated once at 60 Hz when the page loads, so any frame can
+ be drawn on demand.
+3. `capture.mjs` opens it in headless Chromium, **steps `render(t)` frame by
+ frame** and pipes screenshots to ffmpeg: frame-exact 60 fps at any size,
+ however slow a frame is to draw.
+
+Open the HTML file in a browser and it plays live and loops (space pauses,
+←/→ seek, r restarts, f fullscreen).
+
+## Examples
+
+| | What it shows | Tricks worth stealing |
+|---|---|---|
+| [`crawlers`](crawlers/) | One spider agent doubles every 2 beats (1 → 256) across 16 made-up websites; every word a foot lands on lights up; the camera pulls back to the whole wall. [On X](https://x.com/whaleyxbt/status/2106099822088331481) | Real DOM text as terrain: every word is wrapped and measured, feet hit-test it. Procedural legs (2-bone IK, alternating gait). Doublings snap to the music's beat grid. |
+| [`dossier`](dossier/) | The same swarm aimed at one fictional person: each public page leaks one detail, the nearest agent walks to it, a red thread carries it into a dossier. [On X](https://x.com/whaleyxbt/status/2106420024286031963) | "Hunter" agents steered to a target by a set time; screen-space threads from world-space words; facts land on the beat. |
+| [`engine`](engine/) | A methane rocket engine running above a sunset cloud deck: the skirt opens, chapters light the flows, the camera flies through the chamber and throat into the plume, then the engine comes apart and back together. | three.js with sky + environment lighting, clipping-plane cutaway, glowing flow tubes, a plume volume with shock diamonds, a Python sound script on the same `timeline.json`. |
+
+Everything in the examples is invented: no real people, brands or domains
+(`.example`). Caption figures in `engine` are rounded textbook values.
+
+## Commands
+
+```bash
+npm install
+npx playwright install chromium # once; or set $CHROMIUM to your own build
+
+node sims/build.mjs # all sims → sims/dist/<name>.html
+node sims/build.mjs engine # one sim
+
+# review sheet: one frame per listed second, tiled
+node sims/capture.mjs engine --stills 0,4,8,12,16,20 --cols 3 --out out/sims/engine-review.png
+
+# video: 1080x1350 layout → 1440x1800 at 60 fps (default dpr 4/3, crf 16)
+node sims/capture.mjs engine --size 1080x1350 --out out/sims/engine.mp4
+
+# with a music track: beats.py finds tempo, bars and the drop, places the
+# window so the drop lands ~40 % in, and passes the beat map to the sim
+node sims/capture.mjs crawlers --music path/to/track.mp3 --to 20 --out out/sims/crawlers.mp4
+
+# with a generated sound bed (engine)
+python3 sims/engine/sound.py
+node sims/capture.mjs engine --music out/sims/engine/ambient.wav --music-start 0 --no-sync --lufs -24 --out out/sims/engine.mp4
+```
+
+Other flags: `--config post.json` (merged over the sim's `DEFAULTS`),
+`--still 12.5` (one PNG), `--fps`, `--dpr`, `--crf`, `--from`/`--to`,
+`--lufs` (loudness of the muxed audio, default −21).
+
+Every example has `watermark` in its `DEFAULTS`. Set it to your own handle,
+or to `''`, in the sim or in a `--config` file.
+
+## Making a new sim
+
+Copy the example closest to what you want and change it. The contract:
+
+```js
+import {runSim} from '../kit/runtime.js';
+
+const DEFAULTS = {duration: 20, fps: 60, hud: {enabled: false}, director: {enabled: false}, /* your params */};
+
+runSim(DEFAULTS, async ({cfg, canvas, capture}) => {
+ // build the scene, precompute anything stateful
+ return {
+ render(t) { /* draw frame t from scratch */ return {}; },
+ resize() {},
+ };
+});
+```
+
+- `render(t)` must be pure: no `Math.random` (use `rng(seed)` from
+ `kit/util.js` at setup), no `Date`, no state carried between frames.
+ Capture calls it at arbitrary times.
+- Anything that moves by its own rules (agents, particles that collide,
+ steering) is simulated once at load into typed arrays, then `render` reads
+ them.
+- Frame 0 is the thumbnail on X. It must already be busy and beautiful.
+- Lay out for 1080 px wide (CSS px); `--dpr` sets the output resolution.
+- One NaN pixel blacks out the whole frame through bloom: clamp `pow()` bases
+ in shaders.
+- `cfg.beats` (with `--music`) holds `beats`, `downbeats`, `kicks` and `drop`
+ in seconds from the clip start. Snap your big moments to them.
+
+Kit: `kit/runtime.js` (boot, config merge, live loop, `window.SIM` for
+capture), `kit/stage3d.js` (three.js renderer, bloom, camera),
+`kit/util.js` (easing, keyframes, seeded rng), `kit/hud.js` and
+`kit/director.js` (an optional instrument HUD and auto camera cuts; the
+examples turn both off).
+
+Review before you render the full clip: make a `--stills` sheet at the key
+moments, look at every tile (see `.claude/skills/review-loop`), fix, repeat.
diff --git a/sims/beats.py b/sims/beats.py
new file mode 100644
index 0000000..1b2716b
--- /dev/null
+++ b/sims/beats.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Beat map for a music track, so a sim can cut and hit on the music.
+
+ python3 sims/beats.py music/track.mp3 [--duration 30] [--start auto|SECONDS] [-o out.json]
+
+Decodes with ffmpeg, then in pure Python:
+- tempo from the autocorrelation of the onset envelope (prefers 100-160 BPM),
+- the beat grid, aligned to the onsets,
+- downbeats (the beat phase with the most low-band attack),
+- kicks (low-band onset peaks, with strength 0..1),
+- energy per bar, and the drop (the biggest sustained jump in energy).
+
+With --start auto the 30 s window is placed so the drop lands at ~40 % of the
+clip, snapped to a bar. All times in the output are relative to the window start.
+"""
+import argparse
+import json
+import math
+import os
+import subprocess
+import sys
+from array import array
+
+SR = 11025
+HOP = 256
+FPS = SR / HOP # envelope frames per second (~43)
+
+
+def decode(path, filt=None):
+ cmd = ['ffmpeg', '-v', 'error', '-i', path, '-ac', '1', '-ar', str(SR)]
+ if filt:
+ cmd += ['-af', filt]
+ cmd += ['-f', 's16le', '-']
+ raw = subprocess.run(cmd, check=True, capture_output=True).stdout
+ a = array('h')
+ a.frombytes(raw[: len(raw) // 2 * 2])
+ return a
+
+
+def frame_energy(samples):
+ n = len(samples) // HOP
+ out = array('d', bytes(8 * n))
+ for i in range(n):
+ s = 0
+ for x in samples[i * HOP:(i + 1) * HOP]:
+ s += x * x
+ out[i] = s / HOP
+ return out
+
+
+def onset(env):
+ """Positive change of log energy, lightly smoothed."""
+ lg = [math.log(1e-3 + e) for e in env]
+ d = [0.0] + [max(0.0, lg[i] - lg[i - 1]) for i in range(1, len(lg))]
+ return [0.5 * d[i] + 0.25 * (d[i - 1] if i else 0) + 0.25 * (d[i + 1] if i + 1 < len(d) else 0)
+ for i in range(len(d))]
+
+
+def tempo(nov):
+ """Best period in frames from the autocorrelation, weighted toward ~126 BPM."""
+ n = len(nov)
+ mean = sum(nov) / n
+ x = [v - mean for v in nov]
+ best, best_lag = -1e18, None
+ scores = {}
+ lo = int(FPS * 60 / 190)
+ hi = int(FPS * 60 / 70) + 1
+ for lag in range(lo, hi):
+ s = 0.0
+ for i in range(n - lag):
+ s += x[i] * x[i + lag]
+ bpm = 60 * FPS / lag
+ w = math.exp(-0.5 * (math.log2(bpm / 126) / 0.6) ** 2)
+ scores[lag] = s
+ if s * w > best:
+ best, best_lag = s * w, lag
+ # parabolic refinement
+ l = best_lag
+ if l - 1 in scores and l + 1 in scores:
+ a, b, c = scores[l - 1], scores[l], scores[l + 1]
+ den = a - 2 * b + c
+ if den:
+ l = l + 0.5 * (a - c) / den
+ return l
+
+
+def beat_grid(nov, period):
+ """Phase of the grid that sits on the most onset energy, then local snapping."""
+ n = len(nov)
+ best, best_off = -1, 0
+ for off in range(int(period) + 1):
+ s, k = 0.0, 0
+ while True:
+ i = int(round(off + k * period))
+ if i >= n:
+ break
+ s += nov[i]
+ k += 1
+ if s > best:
+ best, best_off = s, off
+ beats = []
+ while best_off - period >= 0: # grid back to the very start
+ best_off -= period
+ k = 0
+ while True:
+ c = best_off + k * period
+ if c >= n:
+ break
+ i = int(round(c))
+ lo, hi = max(0, i - 2), min(n - 1, i + 2)
+ j = max(range(lo, hi + 1), key=lambda q: nov[q])
+ # only snap if the peak is clearly there, else keep the grid
+ beats.append(j if nov[j] > 1.5 * nov[i] + 1e-9 else i)
+ k += 1
+ return beats
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument('track')
+ ap.add_argument('--duration', type=float, default=30)
+ ap.add_argument('--start', default='auto')
+ ap.add_argument('-o', '--out')
+ args = ap.parse_args()
+
+ full = decode(args.track)
+ low = decode(args.track, 'lowpass=f=140,lowpass=f=140')
+ total = len(full) / SR
+ env = frame_energy(full)
+ envl = frame_energy(low)
+ nov = onset(env)
+ novl = onset(envl)
+ comb = [a + 1.5 * b for a, b in zip(nov, novl)]
+
+ period = tempo(comb)
+ bpm = 60 * FPS / period
+ beats = beat_grid(comb, period)
+ # downbeat phase: most low-band attack
+ phase = max(range(4), key=lambda p: sum(novl[b] for b in beats[p::4]))
+ downs = beats[phase::4]
+
+ # kicks: low-band onset peaks above an adaptive threshold
+ srt = sorted(novl)
+ thr = srt[int(len(srt) * 0.9)]
+ peak = max(novl) or 1
+ kicks = []
+ for i in range(1, len(novl) - 1):
+ if novl[i] > thr and novl[i] >= novl[i - 1] and novl[i] > novl[i + 1]:
+ if not kicks or i - kicks[-1][0] > FPS * 0.18:
+ kicks.append((i, novl[i] / peak))
+
+ # energy per bar
+ bar_e = []
+ for b in range(len(downs) - 1):
+ seg = env[downs[b]:downs[b + 1]]
+ bar_e.append(math.sqrt(sum(seg) / max(1, len(seg))))
+ mx = max(bar_e) or 1
+ bar_e = [e / mx for e in bar_e]
+
+ # drop: biggest jump vs the previous 4 bars that holds for the next 2
+ drop_bar, best = None, 0
+ for b in range(4, len(bar_e) - 2):
+ before = sum(bar_e[b - 4:b]) / 4
+ after = min(bar_e[b:b + 2])
+ j = after - before
+ if j > best:
+ best, drop_bar = j, b
+ drop_t = downs[drop_bar] / FPS if drop_bar is not None else None
+
+ D = args.duration
+ if args.start == 'auto':
+ if drop_t is not None and best > 0.12:
+ want = drop_t - 0.4 * D
+ else:
+ # loudest window
+ nb = max(1, int(D / (240 / bpm)))
+ want_bar = max(range(max(1, len(bar_e) - nb)), key=lambda b: sum(bar_e[b:b + nb]))
+ want = downs[want_bar] / FPS
+ want = min(max(0.0, want), max(0.0, total - D))
+ start = min((d / FPS for d in downs), key=lambda d: abs(d - want))
+ if start + D > total:
+ start = max(0.0, total - D)
+ else:
+ start = float(args.start)
+ end = start + D
+
+ rel = lambda f: round(f / FPS - start, 3)
+ inwin = lambda f: start - 1e-6 <= f / FPS < end
+ bar_starts = [d for d in downs if inwin(d)]
+ out = {
+ 'track': os.path.abspath(args.track),
+ 'start': round(start, 3),
+ 'duration': D,
+ 'bpm': round(bpm, 2),
+ 'beats': [rel(b) for b in beats if inwin(b)],
+ 'downbeats': [rel(d) for d in bar_starts],
+ 'kicks': [[rel(i), round(s, 3)] for i, s in kicks if inwin(i)],
+ 'barEnergy': [round(bar_e[downs.index(d)], 3) for d in bar_starts if downs.index(d) < len(bar_e)],
+ 'drop': round(drop_t - start, 3) if drop_t is not None and start <= drop_t < end else None,
+ }
+ path = args.out or os.path.splitext(args.track)[0] + f'.beats-{int(round(start))}.json'
+ with open(path, 'w') as f:
+ json.dump(out, f)
+ print(f'{os.path.basename(args.track)}: {out["bpm"]} bpm, window {start:.2f}-{end:.2f} s, '
+ f'drop {"%.2f" % out["drop"] if out["drop"] is not None else "none"} (clip time), '
+ f'{len(out["beats"])} beats, {len(out["kicks"])} kicks -> {path}')
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/sims/build.mjs b/sims/build.mjs
new file mode 100644
index 0000000..8317655
--- /dev/null
+++ b/sims/build.mjs
@@ -0,0 +1,74 @@
+#!/usr/bin/env node
+// Bundles every sims/<name>/main.js into one self-contained HTML file:
+// sims/dist/<name>.html (three.js, fonts, CSS inlined). Opens from file://,
+// works offline, can be published as-is.
+//
+// node sims/build.mjs all sims
+// node sims/build.mjs topology one sim
+import * as esbuild from 'esbuild';
+import fs from 'node:fs';
+import path from 'node:path';
+
+const HERE = path.dirname(new URL(import.meta.url).pathname);
+const ROOT = path.resolve(HERE, '..');
+const DIST = path.join(HERE, 'dist');
+fs.mkdirSync(DIST, {recursive: true});
+
+const font = (weight) => {
+ const file = path.join(
+ ROOT,
+ `node_modules/@fontsource/jetbrains-mono/files/jetbrains-mono-latin-${weight}-normal.woff2`,
+ );
+ const b64 = fs.readFileSync(file).toString('base64');
+ return `@font-face{font-family:'JetBrains Mono';font-weight:${weight};font-style:normal;font-display:block;src:url(data:font/woff2;base64,${b64}) format('woff2');}`;
+};
+const inter = fs.readFileSync(path.join(ROOT, 'node_modules/@fontsource-variable/inter/files/inter-latin-wght-normal.woff2')).toString('base64');
+const FONTS = [400, 600, 700].map(font).join('\n') +
+ `\n@font-face{font-family:'Inter';font-weight:100 900;font-style:normal;font-display:block;src:url(data:font/woff2;base64,${inter}) format('woff2');}`;
+const KIT_CSS = fs.readFileSync(path.join(HERE, 'kit/style.css'), 'utf8');
+
+const names = process.argv.slice(2).length
+ ? process.argv.slice(2)
+ : fs
+ .readdirSync(HERE)
+ .filter((d) => fs.existsSync(path.join(HERE, d, 'main.js')));
+
+for (const name of names) {
+ const dir = path.join(HERE, name);
+ const t0 = Date.now();
+ const res = await esbuild.build({
+ entryPoints: [path.join(dir, 'main.js')],
+ bundle: true,
+ format: 'esm',
+ minify: true,
+ write: false,
+ target: 'es2022',
+ legalComments: 'none',
+ logLevel: 'warning',
+ });
+ const js = res.outputFiles[0].text.replace(/<\/script/g, '<\\/script');
+ const css = fs.existsSync(path.join(dir, 'style.css')) ? fs.readFileSync(path.join(dir, 'style.css'), 'utf8') : '';
+ const html = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
+<title>${name}</title>
+<style>
+${FONTS}
+${KIT_CSS}
+${css}
+</style>
+</head>
+<body>
+<div id="app"></div>
+<script type="module">
+${js}
+</script>
+</body>
+</html>
+`;
+ const out = path.join(DIST, `${name}.html`);
+ fs.writeFileSync(out, html);
+ console.log(`${path.relative(ROOT, out)} ${(html.length / 1024).toFixed(0)} KB ${Date.now() - t0} ms`);
+}
diff --git a/sims/capture.mjs b/sims/capture.mjs
new file mode 100644
index 0000000..3b77d0d
--- /dev/null
+++ b/sims/capture.mjs
@@ -0,0 +1,153 @@
+#!/usr/bin/env node
+// Frame-accurate capture of a sim page to mp4: steps window.SIM.render(t) for
+// every frame in headless Chromium, screenshots, pipes to ffmpeg, then muxes
+// a music track if given.
+//
+// node sims/capture.mjs <name> [--config post.json] [--out out/sims/x.mp4]
+// [--size 1080x1350] [--dpr 1.3333] [--fps 60] [--from 0] [--to <duration>]
+// (--size is the layout in CSS px; --dpr multiplies the output: 1080x1350
+// at the default 4/3 gives a 1440x1800 video. Default 60 fps, crf 16.)
+// [--music music/track.mp3 [--music-start auto|SEC] [--no-sync] [--lufs -21]] [--crf 21]
+// [--still 12.5] (--still: one PNG, no video)
+// [--stills 0,4,9,14 --cols 3] (tiled review sheet)
+import {spawn} from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import {chromium} from 'playwright';
+
+const HERE = path.dirname(new URL(import.meta.url).pathname);
+const ROOT = path.resolve(HERE, '..');
+const argv = process.argv.slice(2);
+const name = argv[0];
+const opt = (k, d) => {
+ const i = argv.indexOf(`--${k}`);
+ return i === -1 ? d : argv[i + 1];
+};
+if (!name) {
+ console.error('usage: node sims/capture.mjs <name> [--config f.json] [--out f.mp4] [--music f.wav]');
+ process.exit(1);
+}
+const html = path.join(HERE, 'dist', `${name}.html`);
+if (!fs.existsSync(html)) {
+ console.error(`missing ${html}; run node sims/build.mjs ${name}`);
+ process.exit(1);
+}
+const [W, H] = opt('size', '1080x1350').split('x').map(Number);
+const config = opt('config') ? JSON.parse(fs.readFileSync(opt('config'), 'utf8')) : {};
+// --music <file> [--music-start auto|SECONDS]: analyse the track (sims/beats.py),
+// cut the window so the drop lands ~40% in, and give the beat map to the director.
+const music = opt('music');
+let beats = null;
+if (music) {
+ const dur = Number(opt('to', config.duration ?? 30)) - Number(opt('from', 0));
+ const ms = opt('music-start', 'auto');
+ const cache = path.join(ROOT, 'out/beats', `${path.basename(music).replace(/\.[^.]+$/, '')}-${ms}-${dur}.json`);
+ fs.mkdirSync(path.dirname(cache), {recursive: true});
+ const {execFileSync} = await import('node:child_process');
+ if (!fs.existsSync(cache) || fs.statSync(cache).mtimeMs < fs.statSync(music).mtimeMs) {
+ execFileSync('python3', [path.join(HERE, 'beats.py'), music, '--duration', String(dur), '--start', ms, '-o', cache], {stdio: 'inherit'});
+ }
+ beats = JSON.parse(fs.readFileSync(cache, 'utf8'));
+ if (!opt('no-sync')) config.beats = beats;
+}
+const still = opt('still');
+const stamp = new Date().toISOString().slice(5, 16).replace(/[-:T]/g, '');
+const out = path.resolve(opt('out', path.join(ROOT, 'out/sims', still ? `${name}-${still}.png` : `${name}-${stamp}.mp4`)));
+fs.mkdirSync(path.dirname(out), {recursive: true});
+
+// Browser: $CHROMIUM if set, else /usr/bin/chromium if present, else the one
+// Playwright installs (`npx playwright install chromium`).
+const exe = process.env.CHROMIUM || (fs.existsSync('/usr/bin/chromium') ? '/usr/bin/chromium' : undefined);
+const browser = await chromium.launch({
+ executablePath: exe,
+ args: ['--ignore-gpu-blocklist', '--enable-gpu-rasterization', ...(process.platform === 'linux' ? ['--use-angle=gl'] : []), '--enable-webgl', '--hide-scrollbars'],
+});
+const dpr = Number(opt('dpr', 4 / 3));
+const page = await browser.newPage({viewport: {width: W, height: H}, deviceScaleFactor: dpr});
+page.on('console', (m) => m.type() === 'error' && console.error('[page]', m.text()));
+page.on('pageerror', (e) => console.error('[page error]', e.message));
+await page.addInitScript((cfg) => {
+ window.__CAPTURE = true;
+ window.__SIM_CONFIG = cfg;
+}, config);
+await page.goto('file://' + html);
+await page.waitForFunction(() => window.SIM && window.SIM.ready, null, {timeout: 60000});
+const info = await page.evaluate(() => {
+ const gl = document.createElement('canvas').getContext('webgl2');
+ const ext = gl && gl.getExtension('WEBGL_debug_renderer_info');
+ return {
+ duration: window.SIM.duration,
+ fps: window.SIM.fps,
+ gpu: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : 'unknown',
+ };
+});
+console.log(`gpu: ${info.gpu}`);
+
+const stills = opt('stills');
+if (stills) {
+ const ts = stills.split(',').map(Number);
+ const dir = out.replace(/\.(png|mp4)$/, '') + '-frames';
+ fs.mkdirSync(dir, {recursive: true});
+ for (const [i, t] of ts.entries()) {
+ await page.evaluate((x) => window.SIM.render(x), t);
+ await page.screenshot({path: path.join(dir, `${String(i).padStart(2, '0')}.png`)});
+ }
+ await browser.close();
+ const cols = Math.min(ts.length, Number(opt('cols', 3)));
+ const sheet = out.endsWith('.png') ? out : out.replace(/\.mp4$/, '') + '-sheet.png';
+ const tw = Math.round(W * 0.4);
+ const th = Math.round(H * 0.4);
+ await new Promise((r) =>
+ spawn('ffmpeg', ['-loglevel', 'error', '-y', '-framerate', '1', '-i', path.join(dir, '%02d.png'),
+ '-vf', `scale=${tw}:${th},tile=${cols}x${Math.ceil(ts.length / cols)}:padding=4:color=0x333333`, '-frames:v', '1', sheet],
+ {stdio: 'inherit'}).on('close', r),
+ );
+ console.log(`→ ${path.relative(ROOT, sheet)} (full frames in ${path.relative(ROOT, dir)})`);
+ process.exit(0);
+}
+
+if (still !== undefined) {
+ await page.evaluate((t) => window.SIM.render(t), Number(still));
+ await page.screenshot({path: out});
+ await browser.close();
+ console.log(`→ ${path.relative(ROOT, out)}`);
+ process.exit(0);
+}
+
+const fps = Number(opt('fps', 60));
+const from = Number(opt('from', 0));
+const to = Number(opt('to', info.duration));
+const frames = Math.round((to - from) * fps);
+const silent = music ? out.replace(/\.mp4$/, '-silent.mp4') : out;
+
+const ff = spawn(
+ 'ffmpeg',
+ ['-loglevel', 'error', '-y', '-f', 'image2pipe', '-framerate', String(fps), '-i', '-',
+ '-c:v', 'libx264', '-preset', 'slow', '-crf', String(opt('crf', 16)), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', silent],
+ {stdio: ['pipe', 'inherit', 'inherit']},
+);
+const t0 = Date.now();
+for (let i = 0; i < frames; i++) {
+ await page.evaluate((t) => window.SIM.render(t), from + i / fps);
+ const buf = await page.screenshot({type: 'jpeg', quality: 97});
+ if (!ff.stdin.write(buf)) await new Promise((r) => ff.stdin.once('drain', r));
+ if (i % fps === 0) process.stdout.write(`\r${i}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);
+}
+ff.stdin.end();
+await new Promise((r) => ff.on('close', r));
+await browser.close();
+console.log(`\r${frames}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);
+
+if (music) {
+ await new Promise((r, j) =>
+ spawn(
+ 'ffmpeg',
+ ['-loglevel', 'error', '-y', '-i', silent, '-ss', String(beats.start), '-i', music, '-map', '0:v', '-map', '1:a',
+ '-c:v', 'copy', '-c:a', 'aac', '-b:a', '256k', '-af', `loudnorm=I=${opt('lufs', -21)}:TP=-3,afade=t=in:d=0.04,afade=t=out:st=${(to - from - 0.6).toFixed(2)}:d=0.6`,
+ '-shortest', '-movflags', '+faststart', out],
+ {stdio: 'inherit'},
+ ).on('close', (c) => (c === 0 ? r() : j(new Error('mux failed')))),
+ );
+ fs.rmSync(silent);
+}
+console.log(`→ ${path.relative(ROOT, out)}`);
diff --git a/sims/crawlers/main.js b/sims/crawlers/main.js
new file mode 100644
index 0000000..8fb6e77
--- /dev/null
+++ b/sims/crawlers/main.js
@@ -0,0 +1,559 @@
+import {runSim} from '../kit/runtime.js';
+import {clamp01, easeInOutCubic, lerp, rng} from '../kit/util.js';
+import SITES from './sites.js';
+
+// "Crawlers": one spider agent on a web page spawns subagents, every
+// generation doubles (1 → 256), children fly out on threads to other pages,
+// and the camera pulls back from one page to the whole wall. Every word a foot
+// lands on lights up in that agent's colour; agents close to each other are
+// joined by silk. Text on screen: three counters, nothing else.
+//
+// The whole run is simulated once at 60 Hz when the page loads (births,
+// flights, gait, landings), so render(t) is a pure lookup: frame-exact in
+// capture, seekable live. With --music, the doublings snap to the beat grid.
+//
+// Pages: sites.js, sixteen made-up websites (no real brands, .example domains).
+
+const DEFAULTS = {
+ duration: 20,
+ fps: 60,
+ theme: 'dark',
+ hud: {enabled: false, title: 'crawlers', subtitle: ''},
+ director: {enabled: false},
+ watermark: 'X: @whaleyxbt',
+ seed: 5,
+ pages: SITES,
+ swarm: {
+ cols: 4,
+ rows: 4,
+ first: [1, 1], // page (col, row) where agent #1 starts
+ pageH: 1500,
+ gap: 90,
+ gens: 8, // 2^gens agents at the end
+ genStart: 2.4, // first doubling; with music it snaps to the next beat
+ genEvery: 1.25, // seconds between doublings without music
+ genBeats: 2, // beats between doublings with music (cfg.beats)
+ spread: 0.18, // children of one generation are born within this many seconds
+ stayGens: 3, // generations that land on their parent's page
+ blockGens: 6, // ...then on the 2x2 block around page 1, then anywhere
+ endPage: [3, 2], // the camera ends close on this page
+ web: 230, // world px: agents closer than this share a thread
+ counters: true,
+ },
+};
+
+const W = 1080;
+const DT = 1 / 60;
+const PALETTE = ['#ff3db4', '#4dff9a', '#3d7bff', '#ffd23d', '#ff6a3d', '#19c3ff', '#a98bff'];
+const RGB = PALETTE.map((h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)));
+
+const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+
+function wrapWords(root) {
+ const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ const texts = [];
+ while (walk.nextNode()) texts.push(walk.currentNode);
+ for (const tn of texts) {
+ if (!tn.textContent.trim() || tn.parentElement.closest('.ln')) continue;
+ const frag = document.createDocumentFragment();
+ for (const part of tn.textContent.split(/(\s+)/)) {
+ if (!part) continue;
+ if (/^\s+$/.test(part)) frag.appendChild(document.createTextNode(part));
+ else {
+ const s = document.createElement('span');
+ s.className = 'w';
+ s.textContent = part;
+ frag.appendChild(s);
+ }
+ }
+ tn.replaceWith(frag);
+ }
+ return [...root.querySelectorAll('.w')];
+}
+
+const angWrap = (a) => Math.atan2(Math.sin(a), Math.cos(a));
+
+/** Doubling times: every genEvery s, or every genBeats beats of the music. */
+function genTimes(cfg) {
+ const S = cfg.swarm;
+ const b = cfg.beats && cfg.beats.beats;
+ if (b && b.length) {
+ const i = Math.max(0, b.findIndex((x) => x >= S.genStart));
+ return [...Array(S.gens)].map((_, g) => b[Math.min(b.length - 1, i + g * S.genBeats)]);
+ }
+ return [...Array(S.gens)].map((_, g) => S.genStart + g * S.genEvery);
+}
+
+function simulate(cfg, words, pages) {
+ const S = cfg.swarm;
+ const R = rng(cfg.seed);
+ const N = Math.ceil((cfg.duration + 0.2) / DT) + 1;
+ const n = 2 ** S.gens;
+ const firstPage = S.first[1] * S.cols + S.first[0];
+
+ // births: generation g doubles the swarm
+ const G = genTimes(cfg);
+ const ag = [{born: -1, parent: -1, size: 1.35, color: 0, gen: -1}];
+ for (let g = 0; g < S.gens; g++) {
+ const cur = ag.length;
+ for (let i = 0; i < cur; i++)
+ ag.push({born: G[g] + R() * S.spread, parent: i, gen: g, size: 0.8 + R() * 0.45, color: 1 + Math.floor(R() * (PALETTE.length - 1))});
+ }
+ // reveal order: page 1, its 2x2 block, then the rest by distance
+ const [fc, fr] = S.first;
+ const block = [[fc, fr], [fc + 1, fr], [fc, fr - 1], [fc + 1, fr - 1]].map(([c, r]) => r * S.cols + c);
+ const rest = pages.map((_, i) => i).filter((i) => !block.includes(i));
+ rest.sort((a, b) => Math.hypot(a % S.cols - fc - 0.5, Math.floor(a / S.cols) - fr + 0.5) - Math.hypot(b % S.cols - fc - 0.5, Math.floor(b / S.cols) - fr + 0.5));
+ const reveal = [...block, ...rest];
+ const count = new Array(pages.length).fill(0);
+ const pageWords = pages.map(() => []);
+ words.forEach((w, i) => pageWords[w.page].push(i));
+
+ const GS = 80;
+ const grid = new Map();
+ words.forEach((w, i) => {
+ for (let gx = Math.floor(w.x / GS); gx <= Math.floor((w.x + w.w) / GS); gx++)
+ for (let gy = Math.floor(w.y / GS); gy <= Math.floor((w.y + w.h) / GS); gy++) {
+ const k = gx * 100000 + gy;
+ if (!grid.has(k)) grid.set(k, []);
+ grid.get(k).push(i);
+ }
+ });
+ const hit = (x, y) => {
+ for (const i of grid.get(Math.floor(x / GS) * 100000 + Math.floor(y / GS)) || []) {
+ const w = words[i];
+ if (x >= w.x - 4 && x <= w.x + w.w + 4 && y >= w.y - 5 && y <= w.y + w.h + 5) return i;
+ }
+ return -1;
+ };
+ const wc = (i) => [words[i].x + words[i].w / 2, words[i].y + words[i].h / 2];
+
+ const pos = new Float32Array(N * n * 3).fill(NaN); // x, y, angle per frame per agent
+ const feet = new Float32Array(N * n * 16);
+ const lift = new Uint8Array(N * n * 8);
+ const hits = []; // [t, word, colour]
+ const flights = []; // {a, t0, t1, x0, y0}
+
+ const TH = [38, 78, 112, 148].map((d) => (d * Math.PI) / 180);
+ const RR = [112, 118, 112, 104];
+ const st = ag.map(() => null);
+ const pickTarget = (s, near) => {
+ const list = pageWords[s.page];
+ for (let tries = 0; tries < 12; tries++) {
+ const i = list[Math.floor(R() * list.length)];
+ const [x, y] = wc(i);
+ if (!near || Math.hypot(x - s.x, y - s.y) < 430) return [x, y];
+ }
+ return wc(list[Math.floor(R() * list.length)]);
+ };
+ const local = (s, lx, ly) => [s.x + Math.cos(s.ang) * lx - Math.sin(s.ang) * ly, s.y + Math.sin(s.ang) * lx + Math.cos(s.ang) * ly];
+ const restOf = (s, L) => local(s, Math.cos(TH[L.j]) * RR[L.j] * s.size, L.side * Math.sin(TH[L.j]) * RR[L.j] * s.size);
+
+ for (let f = 0; f < N; f++) {
+ const t = f * DT;
+ // births
+ for (let a = 0; a < n; a++) {
+ if (st[a] || ag[a].born > t) continue;
+ const A = ag[a];
+ const s = {x: 0, y: 0, ang: R() * Math.PI * 2, speed: 0, size: A.size, vmax: 230 + R() * 170, mode: 'walk', until: 0, idle: 0, tx: 0, ty: 0, page: firstPage, fly: null};
+ if (A.parent < 0) {
+ // start in the middle of the first view
+ const pw = pageWords[firstPage];
+ const top = Math.min(...pw.map((i) => words[i].y)), cx = Math.min(...pw.map((i) => words[i].x)) + 420;
+ const dm = (i) => Math.hypot(words[i].y - top - 560, words[i].x - cx);
+ const mid = pw.reduce((b, i) => (dm(i) < dm(b) ? i : b), pw[0]);
+ [s.x, s.y] = wc(mid);
+ s.ang = -0.4;
+ } else {
+ const p = st[A.parent];
+ let page = p.page;
+ if (A.gen >= S.stayGens) {
+ const open = reveal.slice(0, A.gen < S.blockGens ? 4 : pages.length);
+ page = open.reduce((b, i) => (count[i] < count[b] ? i : b), open[0]);
+ }
+ s.page = page;
+ const [x1, y1] = page === p.page ? [p.x + (R() - 0.5) * 260, p.y + (R() - 0.5) * 260] : pickTarget(s, false);
+ const d = Math.hypot(x1 - p.x, y1 - p.y);
+ s.fly = {t0: t, t1: t + Math.min(0.95, 0.3 + d / 2600), x0: p.x, y0: p.y, x1, y1};
+ flights.push({a, t0: t, t1: s.fly.t1, x0: p.x, y0: p.y});
+ s.x = p.x;
+ s.y = p.y;
+ }
+ count[s.page]++;
+ [s.tx, s.ty] = pickTarget(s, true);
+ s.legs = [...Array(8)].map((_, i) => {
+ const L = {side: i < 4 ? -1 : 1, j: i % 4, step: false};
+ L.group = (L.j + (L.side > 0 ? 1 : 0)) % 2;
+ return L;
+ });
+ for (const L of s.legs) L.f = restOf(s, L);
+ st[a] = s;
+ }
+
+ for (let a = 0; a < n; a++) {
+ const s = st[a];
+ if (!s) continue;
+ if (s.fly) {
+ const q = easeInOutCubic((t - s.fly.t0) / (s.fly.t1 - s.fly.t0));
+ s.x = lerp(s.fly.x0, s.fly.x1, q);
+ s.y = lerp(s.fly.y0, s.fly.y1, q);
+ s.ang += 4 * DT;
+ for (const L of s.legs) {
+ L.f = restOf(s, L);
+ L.step = false;
+ }
+ if (t >= s.fly.t1) {
+ s.fly = null;
+ [s.tx, s.ty] = pickTarget(s, true);
+ }
+ } else {
+ const dx = s.tx - s.x, dy = s.ty - s.y;
+ const dist = Math.hypot(dx, dy);
+ if (s.mode === 'walk') {
+ const wander = 0.4 * Math.sin(t * 2.1 + a * 1.3) * clamp01(dist / 260);
+ const da = angWrap(Math.atan2(dy, dx) + wander - s.ang);
+ s.ang += Math.max(-8 * DT, Math.min(8 * DT, da));
+ const vt = Math.max(60, s.vmax * clamp01(dist / 130)) * Math.max(0.3, Math.cos(da));
+ s.speed = lerp(s.speed, vt, 1 - Math.exp(-DT * 9));
+ if (dist < 22) {
+ s.mode = 'dwell';
+ s.until = t + 0.12 + R() * 0.45;
+ }
+ } else {
+ s.speed = lerp(s.speed, 0, 1 - Math.exp(-DT * 14));
+ if (t >= s.until) {
+ s.mode = 'walk';
+ [s.tx, s.ty] = pickTarget(s, true);
+ }
+ }
+ s.x += Math.cos(s.ang) * s.speed * DT;
+ s.y += Math.sin(s.ang) * s.speed * DT;
+ s.idle = s.speed < 30 ? s.idle + DT : 0;
+ const busy = [false, false];
+ for (const L of s.legs) if (L.step) busy[L.group] = true;
+ for (const L of s.legs) {
+ if (L.step) {
+ const q = (t - L.t0) / L.dur;
+ if (q >= 1) {
+ L.step = false;
+ L.f = L.to;
+ const wi = hit(L.f[0], L.f[1]);
+ if (wi >= 0) hits.push([t, wi, ag[a].color]);
+ } else {
+ const e = easeInOutCubic(q);
+ L.f = [lerp(L.from[0], L.to[0], e), lerp(L.from[1], L.to[1], e)];
+ }
+ continue;
+ }
+ const r = restOf(s, L);
+ const d = Math.hypot(L.f[0] - r[0], L.f[1] - r[1]);
+ const thr = s.idle > 0.12 ? 14 : 56 * s.size;
+ if (d > thr && (!busy[1 - L.group] || d > thr * 2.4)) {
+ const lead = 0.07 * s.speed;
+ L.from = L.f;
+ L.to = [r[0] + Math.cos(s.ang) * lead + (R() - 0.5) * 10, r[1] + Math.sin(s.ang) * lead + (R() - 0.5) * 10];
+ L.t0 = t;
+ L.dur = s.idle > 0.12 ? 0.1 : 0.075;
+ L.step = true;
+ busy[L.group] = true;
+ }
+ }
+ }
+ const o = (f * n + a) * 3;
+ pos[o] = s.x;
+ pos[o + 1] = s.y;
+ const prev = f ? pos[o - n * 3 + 2] : NaN;
+ pos[o + 2] = Number.isNaN(prev) ? s.ang : prev + angWrap(s.ang - prev);
+ s.legs.forEach((L, i) => {
+ feet[(f * n + a) * 16 + i * 2] = L.f[0];
+ feet[(f * n + a) * 16 + i * 2 + 1] = L.f[1];
+ lift[(f * n + a) * 8 + i] = L.step ? Math.round(255 * Math.sin(Math.PI * clamp01((t - L.t0) / L.dur))) : 0;
+ });
+ }
+ }
+ return {N, n, ag, pos, feet, lift, hits, flights};
+}
+
+runSim(DEFAULTS, async ({cfg, canvas}) => {
+ await Promise.all([
+ document.fonts.load('400 20px "JetBrains Mono"'),
+ document.fonts.load('600 20px "JetBrains Mono"'),
+ document.fonts.load('700 20px "JetBrains Mono"'),
+ document.fonts.load('400 20px Inter'),
+ document.fonts.load('700 20px Inter'),
+ ]).catch(() => {});
+ document.title = 'crawlers';
+ const S = cfg.swarm;
+ const pagesCfg = cfg.pages.slice(0, S.cols * S.rows);
+
+ const app = document.getElementById('app');
+ const stage = document.createElement('div');
+ stage.id = 'stage';
+ app.appendChild(stage);
+ const world = document.createElement('div');
+ world.className = 'world';
+ stage.appendChild(world);
+ stage.appendChild(canvas);
+
+ const pageEls = pagesCfg.map((p, i) => {
+ const el = document.createElement('div');
+ el.className = `page site ${p.theme}`;
+ const c = i % S.cols, r = Math.floor(i / S.cols);
+ el.style.left = `${c * (W + S.gap)}px`;
+ el.style.top = `${r * (S.pageH + S.gap)}px`;
+ el.style.height = `${S.pageH}px`;
+ el.innerHTML = `<div class="chrome"><span class="dots"><b></b><b></b><b></b></span><span class="nav">‹ › ↻</span><span class="url">${esc(p.url)}</span></div><div class="content">${p.html}</div>`;
+ world.appendChild(el);
+ return el;
+ });
+
+ const hud = document.createElement('div');
+ hud.className = 'counters';
+ hud.innerHTML = `<div class="c big"><span>agents</span><b id="cA">1</b></div><div class="c"><span>pages</span><b id="cP">1</b></div><div class="c"><span>words read</span><b id="cW">0</b></div>`;
+ if (S.counters) stage.appendChild(hud);
+ if (cfg.watermark) {
+ const wm = document.createElement('div');
+ wm.className = 'wm';
+ wm.textContent = cfg.watermark;
+ stage.appendChild(wm);
+ }
+
+ let s = 1, VH = 1350;
+ const layout = () => {
+ const iw = innerWidth, ih = innerHeight;
+ s = iw / ih <= 1 ? iw / W : ih / 1350;
+ VH = ih / s;
+ stage.style.left = `${(iw - W * s) / 2}px`;
+ stage.style.height = `${VH}px`;
+ stage.style.transform = `scale(${s})`;
+ const dpr = devicePixelRatio || 1;
+ canvas.width = Math.round(W * s * dpr);
+ canvas.height = Math.round(VH * s * dpr);
+ };
+ layout();
+
+ // words in world coordinates (world is untransformed while measuring)
+ const wr = world.getBoundingClientRect();
+ const words = [];
+ pageEls.forEach((pe, pi) => {
+ const pr = pe.getBoundingClientRect();
+ for (const el of wrapWords(pe.querySelector('.content'))) {
+ const r = el.getBoundingClientRect();
+ if (r.bottom > pr.bottom - 10 || r.width === 0) continue; // clipped by the page
+ words.push({el, page: pi, x: (r.left - wr.left) / s, y: (r.top - wr.top) / s, w: r.width / s, h: r.height / s});
+ }
+ });
+
+ const sim = simulate(cfg, words, pagesCfg);
+ const {n, ag, pos, feet, lift, flights} = sim;
+ // per-word hit lists (time-sorted), first-hit times for the counter
+ const wh = words.map(() => []);
+ for (const h of sim.hits) wh[h[1]].push(h);
+ const firsts = wh.filter((l) => l.length).map((l) => l[0][0]).sort((a, b) => a - b);
+ const pageOpen = new Array(pagesCfg.length).fill(1e9);
+ for (let a = 0; a < n; a++) {
+ // which page each agent lives on = the page under it 1.2 s after birth
+ const f = Math.min(sim.N - 1, Math.ceil((ag[a].born + 1.2) / DT));
+ const x = pos[(f * n + a) * 3], y = pos[(f * n + a) * 3 + 1];
+ const c = Math.floor(x / (W + S.gap)), r = Math.floor(y / (S.pageH + S.gap));
+ const pi = r * S.cols + c;
+ if (pi >= 0 && pi < pageOpen.length) pageOpen[pi] = Math.min(pageOpen[pi], ag[a].born);
+ }
+ const opens = pageOpen.filter((x) => x < 1e9).sort((a, b) => a - b);
+ window.__SWARM = {agents: n, words: words.length, hits: sim.hits.length, wordsRead: firsts.length};
+
+ // camera keyframes
+ const P = (c, r) => ({x: c * (W + S.gap), y: r * (S.pageH + S.gap)});
+ const [fc, fr] = S.first;
+ const p0 = P(fc, fr);
+ const gridW = S.cols * W + (S.cols - 1) * S.gap, gridH = S.rows * S.pageH + (S.rows - 1) * S.gap;
+ const blockZ = () => Math.min((W * 0.94) / (2 * W + S.gap), (VH * 0.9) / (2 * S.pageH + S.gap));
+ const wallZ = () => Math.min((W * 0.96) / gridW, (VH * 0.86) / gridH);
+ // page 1 → its 2x2 block → the whole wall → back in on one page
+ const GT = genTimes(cfg);
+ const keys = () => {
+ const pe = P(S.endPage[0], S.endPage[1]);
+ const tWall = GT[S.gens - 1] + 1.0;
+ const tHold = Math.max(tWall + 3, cfg.duration - 5.5);
+ return [
+ {t: 0, x: p0.x + W / 2, y: p0.y + VH / 2, z: 1},
+ {t: GT[2], x: p0.x + W / 2, y: p0.y + VH / 2 + 220, z: 1},
+ {t: GT[3] + 0.6, x: p0.x + W + S.gap / 2, y: p0.y - S.gap / 2, z: blockZ()},
+ {t: GT[5] + 0.3, x: p0.x + W + S.gap / 2 + 20, y: p0.y - S.gap / 2 + 30, z: blockZ() * 0.97},
+ {t: tWall, x: gridW / 2, y: gridH / 2 + 40, z: wallZ()},
+ {t: tHold, x: gridW / 2 + 40, y: gridH / 2 + 30, z: wallZ() * 1.05},
+ {t: cfg.duration, x: pe.x + W / 2, y: pe.y + S.pageH * 0.42, z: 0.62},
+ ];
+ };
+ let K = keys();
+ const camAt = (t) => {
+ let i = 0;
+ while (i < K.length - 2 && t > K[i + 1].t) i++;
+ const a = K[i], b = K[i + 1];
+ const q = easeInOutCubic((t - a.t) / (b.t - a.t));
+ const z = Math.exp(lerp(Math.log(a.z), Math.log(b.z), q));
+ return {x: lerp(a.x, b.x, q), y: lerp(a.y, b.y, q), z};
+ };
+
+ const ctx = canvas.getContext('2d');
+ const shown = new Array(words.length).fill('');
+ const cA = hud.querySelector('#cA'), cP = hud.querySelector('#cP'), cW = hud.querySelector('#cW');
+ const countLE = (arr, t) => {
+ let lo = 0, hi = arr.length;
+ while (lo < hi) {
+ const m = (lo + hi) >> 1;
+ if (arr[m] <= t) lo = m + 1;
+ else hi = m;
+ }
+ return lo;
+ };
+ const fmt = (x) => x.toLocaleString('en-US');
+
+ return {
+ resize() {
+ layout();
+ K = keys();
+ },
+ render(t) {
+ const cam = camAt(t);
+ world.style.transform = `translate(${W / 2 - cam.x * cam.z}px, ${VH / 2 - cam.y * cam.z}px) scale(${cam.z})`;
+
+ // highlights: the latest hit on each word, bright when fresh
+ for (let i = 0; i < words.length; i++) {
+ const l = wh[i];
+ let v = '';
+ if (l.length && l[0][0] <= t) {
+ let lo = 0, hi = l.length - 1;
+ while (lo < hi) {
+ const m = (lo + hi + 1) >> 1;
+ if (l[m][0] <= t) lo = m;
+ else hi = m - 1;
+ }
+ const [ht, , c] = l[lo];
+ const al = Math.round((0.26 + 0.6 * Math.exp(-(t - ht) / 0.25)) * 20) / 20;
+ v = `rgba(${RGB[c][0]},${RGB[c][1]},${RGB[c][2]},${al})`;
+ }
+ if (v !== shown[i]) {
+ shown[i] = v;
+ words[i].el.style.background = v;
+ }
+ }
+
+ // canvas
+ const fi = Math.max(0, Math.min(sim.N - 1.001, t / DT));
+ const f = Math.floor(fi), a = fi - f;
+ const dpr = canvas.width / (W * s);
+ ctx.setTransform(s * dpr, 0, 0, s * dpr, 0, 0);
+ ctx.clearRect(0, 0, W, VH);
+ ctx.translate(W / 2 - cam.x * cam.z, VH / 2 - cam.y * cam.z);
+ ctx.scale(cam.z, cam.z);
+ const px = (i) => lerp(pos[(f * n + i) * 3], pos[((f + 1) * n + i) * 3], a);
+ const py = (i) => lerp(pos[(f * n + i) * 3 + 1], pos[((f + 1) * n + i) * 3 + 1], a);
+ const alive = [];
+ for (let i = 0; i < n; i++) if (!Number.isNaN(pos[(f * n + i) * 3]) && !Number.isNaN(pos[((f + 1) * n + i) * 3])) alive.push(i);
+ const X = new Float32Array(n), Y = new Float32Array(n);
+ for (const i of alive) {
+ X[i] = px(i);
+ Y[i] = py(i);
+ }
+ const lw = (w) => Math.max(w, w * 0.45 / cam.z);
+
+ // web between neighbours
+ ctx.lineWidth = lw(1.2);
+ for (let u = 0; u < alive.length; u++)
+ for (let v = u + 1; v < alive.length; v++) {
+ const i = alive[u], j = alive[v];
+ const d = Math.hypot(X[i] - X[j], Y[i] - Y[j]);
+ if (d > S.web) continue;
+ ctx.strokeStyle = `rgba(255,61,180,${(0.5 * (1 - d / S.web)).toFixed(3)})`;
+ ctx.beginPath();
+ ctx.moveTo(X[i], Y[i]);
+ ctx.lineTo(X[j], Y[j]);
+ ctx.stroke();
+ }
+ // spawn threads
+ for (const fl of flights) {
+ if (t < fl.t0 || t > fl.t1 + 0.35) continue;
+ const fade = t > fl.t1 ? 1 - (t - fl.t1) / 0.35 : 1;
+ ctx.strokeStyle = `rgba(255,255,255,${(0.85 * fade).toFixed(3)})`;
+ ctx.lineWidth = lw(2);
+ ctx.beginPath();
+ ctx.moveTo(fl.x0, fl.y0);
+ ctx.lineTo(X[fl.a], Y[fl.a]);
+ ctx.stroke();
+ }
+ // spiders
+ ctx.lineCap = 'round';
+ for (const i of alive) {
+ const A = ag[i];
+ const ang = lerp(pos[(f * n + i) * 3 + 2], pos[((f + 1) * n + i) * 3 + 2], a);
+ const x = X[i], y = Y[i], sz = A.size;
+ const born = clamp01((t - A.born) / 0.25);
+ const col = PALETTE[A.color], joint = PALETTE[(A.color + 3) % PALETTE.length];
+ const ca = Math.cos(ang), sa = Math.sin(ang);
+ const L1 = 66 * sz, L2 = 74 * sz;
+ ctx.globalAlpha = born;
+ ctx.strokeStyle = col;
+ ctx.fillStyle = joint;
+ for (let l = 0; l < 8; l++) {
+ const side = l < 4 ? -1 : 1, j = l % 4;
+ const HX = [16, 6, -4, -14][j] * sz;
+ const hx = x + ca * HX - sa * side * 6 * sz, hy = y + sa * HX + ca * side * 6 * sz;
+ const o = (f * n + i) * 16 + l * 2, o2 = ((f + 1) * n + i) * 16 + l * 2;
+ const fX = lerp(feet[o], feet[o2], a), fY = lerp(feet[o + 1], feet[o2 + 1], a);
+ const lf = lerp(lift[(f * n + i) * 8 + l], lift[((f + 1) * n + i) * 8 + l], a) / 255;
+ const dx = fX - hx, dy = fY - hy;
+ const d = Math.max(Math.abs(L1 - L2) + 1, Math.min(L1 + L2 - 1, Math.hypot(dx, dy)));
+ const base = Math.atan2(dy, dx);
+ const k = Math.acos(Math.max(-1, Math.min(1, (L1 * L1 + d * d - L2 * L2) / (2 * L1 * d))));
+ let kx = hx + Math.cos(base + k) * L1, ky = hy + Math.sin(base + k) * L1;
+ const kx2 = hx + Math.cos(base - k) * L1, ky2 = hy + Math.sin(base - k) * L1;
+ if (Math.hypot(kx2 - x, ky2 - y) > Math.hypot(kx - x, ky - y)) {
+ kx = kx2;
+ ky = ky2;
+ }
+ const kd = Math.hypot(kx - x, ky - y) || 1;
+ kx += ((kx - x) / kd) * lf * 12;
+ ky += ((ky - y) / kd) * lf * 12;
+ ctx.lineWidth = lw(3.1);
+ ctx.beginPath();
+ ctx.moveTo(hx, hy);
+ ctx.lineTo(kx, ky);
+ ctx.lineTo(fX, fY);
+ ctx.stroke();
+ const r = lw(4.2);
+ ctx.beginPath();
+ ctx.arc(kx, ky, r, 0, Math.PI * 2);
+ ctx.moveTo(fX + r * 1.1, fY);
+ ctx.arc(fX, fY, r * 1.1 + lf * 2.5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.save();
+ ctx.translate(x, y);
+ ctx.rotate(ang);
+ ctx.fillStyle = 'rgba(8,9,13,0.92)';
+ ctx.strokeStyle = col;
+ ctx.lineWidth = lw(2.6);
+ const bl = 48 * sz, bw = 17 * sz;
+ ctx.beginPath();
+ ctx.rect(-bl / 2, -bw / 2, bl, bw);
+ ctx.fill();
+ ctx.stroke();
+ ctx.fillStyle = '#ff3db4';
+ ctx.beginPath();
+ ctx.arc(bl * 0.22, 0, Math.max(5.5 * sz, 2 / cam.z), 0, Math.PI * 2);
+ ctx.fill();
+ ctx.restore();
+ ctx.globalAlpha = 1;
+ }
+
+ // counters
+ let agents = 0;
+ for (const A of ag) if (A.born <= t) agents++;
+ cA.textContent = fmt(agents);
+ cP.textContent = `${countLE(opens, t)}/${pagesCfg.length}`;
+ cW.textContent = fmt(countLE(firsts, t));
+ return {};
+ },
+ };
+});
diff --git a/sims/crawlers/sites.js b/sims/crawlers/sites.js
new file mode 100644
index 0000000..c9d334c
--- /dev/null
+++ b/sims/crawlers/sites.js
@@ -0,0 +1,248 @@
+// Sixteen generic web pages for the swarm to crawl: encyclopedia, search,
+// news, forum, social feed, code host, shop, inbox, Q&A, docs, video, sheet.
+// No real brands, logos or people: names and domains are made up (.example).
+// Each entry: {url, theme: 'light' | 'dark', html}. Styles: style.css (.s-*).
+
+const P = (s) => `<p>${s}</p>`;
+const img = (h, a, b, extra = '') => `<div class="s-img" style="height:${h}px;background:linear-gradient(135deg,${a},${b})${extra}"></div>`;
+
+const wiki = (title, lead, infobox, sections, refs) => `
+<div class="s-wiki">
+ <div class="wk-top"><span class="wk-logo">◎ Encyclopedia</span><div class="wk-search">Search Encyclopedia</div></div>
+ <div class="wk-tabs"><b>Article</b><span>Talk</span><i></i><b>Read</b><span>Edit</span><span>View history</span></div>
+ <h1>${title}</h1>
+ <div class="wk-from">From Encyclopedia, the free encyclopedia</div>
+ ${infobox}
+ ${lead.map(P).join('')}
+ ${sections.map(([h, ps]) => `<h2>${h}</h2>${ps.map(P).join('')}`).join('')}
+ <h2>References</h2>
+ <ol class="wk-refs">${refs.map((r) => `<li>^ ${r}</li>`).join('')}</ol>
+</div>`;
+
+const search = (q, results) => `
+<div class="s-search">
+ <div class="sr-top"><span class="sr-logo">seek</span><div class="sr-box">${q}<span>⌕</span></div></div>
+ <div class="sr-tabs"><b>All</b><span>Images</span><span>News</span><span>Videos</span><span>Maps</span><span>More</span></div>
+ <div class="sr-count">About 2,140,000 results (0.31 seconds)</div>
+ ${results.map(([site, title, snip]) => `<div class="sr-r"><div class="sr-site"><i></i>${site}</div><a>${title}</a><p>${snip}</p></div>`).join('')}
+</div>`;
+
+const news = (mast, kicker, head, dek, by, paras, side) => `
+<div class="s-news">
+ <div class="nw-mast">${mast}</div>
+ <div class="nw-nav"><span>World</span><span>Tech</span><span>Business</span><span>Science</span><span>Opinion</span><span>Culture</span></div>
+ <div class="nw-grid">
+ <div class="nw-main">
+ <div class="nw-kick">${kicker}</div>
+ <h1>${head}</h1>
+ <div class="nw-dek">${dek}</div>
+ <div class="nw-by">${by}</div>
+ ${img(330, '#c9d6e2', '#7d93a8')}
+ <div class="nw-cap">Illustration</div>
+ ${paras.map(P).join('')}
+ </div>
+ <div class="nw-side"><h3>Most read</h3>${side.map((s, i) => `<div class="nw-mr"><b>${i + 1}</b><span>${s}</span></div>`).join('')}</div>
+ </div>
+</div>`;
+
+const forum = (items) => `
+<div class="s-forum">
+ <div class="fm-top"><b>▲ newsdesk</b><span>new | past | comments | ask | show | jobs | submit</span><span class="fm-login">login</span></div>
+ ${items.map(([t, site, pts, by, ago, c], i) => `<div class="fm-it"><span class="fm-n">${i + 1}.</span><div><div class="fm-t">▲ ${t} <i>(${site})</i></div><div class="fm-m">${pts} points by ${by} ${ago} | hide | ${c} comments</div></div></div>`).join('')}
+</div>`;
+
+const social = (posts) => `
+<div class="s-social">
+ <div class="so-top"><b>Home</b><span>For you</span><span class="on">Following</span></div>
+ ${posts.map(([name, handle, ago, text, stats, media]) => `
+ <div class="so-post"><div class="so-av" style="background:${media ? '#3d7bff' : '#a98bff'}"></div><div class="so-b">
+ <div class="so-h"><b>${name}</b><span>${handle} · ${ago}</span></div>
+ <div class="so-t">${text}</div>
+ ${media ? img(220, '#1b2a44', '#5a3d8a', ';border-radius:16px;margin:12px 0 4px') : ''}
+ <div class="so-s"><span>↩ ${stats[0]}</span><span>⟲ ${stats[1]}</span><span>♡ ${stats[2]}</span><span>▥ ${stats[3]}</span></div>
+ </div></div>`).join('')}
+</div>`;
+
+const PAGES = [
+ // row 0
+ {url: 'seek.example/search?q=how+do+ai+agents+browse+the+web', theme: 'light', html: search('how do ai agents browse the web', [
+ ['agents-handbook.example', 'How AI agents browse the web: a practical guide', 'An agent opens a real browser, reads the page as text or pixels, decides what to click, and repeats until the task is done or it gives up.'],
+ ['devnotes.example › blog', 'Browser agents explained in 5 minutes', 'Most browser agents run a loop: observe the page, pick an action, act, observe again. The hard part is knowing when to stop.'],
+ ['forum.newsdesk.example', 'Ask: how do you keep an agent from looping on a page?', 'Give it a step budget, log every action, and make "I am stuck" a valid answer. Agents loop when every option looks equally good.'],
+ ['research-digest.example', 'Agents that read the web for you', 'Instead of ten tabs you send one agent. It reads the pages, keeps the quotes, and comes back with sources you can check.'],
+ ['buildlog.example › posts', 'I gave an agent 50 tabs and a deadline', 'It read every page, wrote a summary per tab, and flagged three that contradicted each other. Then it asked which one to trust.'],
+ ['robots-guide.example', 'robots.txt for the agent era', 'Crawlers used to index pages. Agents act on them. Site owners are starting to write separate rules for each.'],
+ ['qa.example › questions', 'Can two agents share one browser session?', 'Yes, but give each its own tab and a lock on the cart. Otherwise they will both buy the same thing.'],
+ ])},
+ {url: 'morningledger.example/tech/agents-on-the-web', theme: 'light', html: news('The Morning Ledger', 'Technology', 'Your next visitor might not be a person', 'Agents now read, compare and click on behalf of people. Site owners are redesigning for readers that never scroll.', 'By the Ledger tech desk · 6 min read', [
+ 'For twenty years the web was built for eyes. Pages were long, images were big, and buttons were placed where a thumb could find them. That assumption is breaking.',
+ 'A growing share of page views now comes from software agents: programs that open a page, read it in a fraction of a second, and move on to the next one. They do not see the hero image. They read the text, the prices and the fine print.',
+ 'Some publishers block them. Others are building a second version of every page, plain and structured, for agents only. A few are doing both.',
+ 'The change is visible in small places. Checkout forms that used to hide the total until the last step now show it first, because agents compare totals before anything else.',
+ ], ['Agents now book more trips than travel desks', 'What happens when two agents negotiate', 'The case for boring, readable websites', 'Inside a newsroom that writes for bots', 'Why your inbox is full of agent receipts'])},
+ {url: 'chirp.example/home', theme: 'dark', html: social([
+ ['build log', '@buildlog', '2m', 'gave one agent a wiki page. it spawned subagents. 9 seconds later there were 256 of them reading the whole site', ['48', '310', '2.1K', '84K'], true],
+ ['agent 017', '@agent_017', '14m', 'status: read 1,204 pages today. found 3 broken links, 1 typo in a price, 0 reasons to stop', ['12', '40', '391', '9K'], false],
+ ['night shift', '@nightshift_ops', '31m', 'the agents never log off. we just check the morning summary and approve the drafts', ['7', '22', '180', '6K'], false],
+ ['web weekly', '@webweekly', '1h', 'thread: what changes when half your readers are software', ['33', '95', '640', '21K'], true],
+ ])},
+ {url: 'vidtube.example/feed', theme: 'dark', html: `
+<div class="s-video">
+ <div class="vd-top"><b>▶ vidtube</b><div class="vd-search">Search</div></div>
+ <div class="vd-chips"><span class="on">All</span><span>AI agents</span><span>Coding</span><span>Live</span><span>Science</span><span>Spiders</span></div>
+ <div class="vd-grid">${[
+ ['I let 100 agents run my website for a week', 'build log', '412K views · 3 days ago', '#3d1d5a', '#ff3db4'],
+ ['Spider silk is stronger than you think', 'nature lab', '1.2M views · 2 weeks ago', '#1d3a2a', '#4dff9a'],
+ ['How web crawlers actually work', 'cs explained', '880K views · 1 month ago', '#14304d', '#19c3ff'],
+ ['One prompt, 256 subagents', 'agent diaries', '96K views · 5 hours ago', '#4d2a14', '#ff6a3d'],
+ ['Watching a jumping spider hunt in slow motion', 'macro world', '3.4M views · 1 year ago', '#3a3a14', '#ffd23d'],
+ ['Agents vs captchas: who wins in 2026', 'web weekly', '201K views · 6 days ago', '#2a1d4d', '#a98bff'],
+ ].map(([t, ch, m, a, b]) => `<div class="vd-c">${img(190, a, b, ';border-radius:14px')}<div class="vd-t">${t}</div><div class="vd-m">${ch}<br>${m}</div></div>`).join('')}</div>
+</div>`},
+
+ // row 1
+ {url: 'newsdesk.example/news', theme: 'light', html: forum([
+ ['Show: a swarm of crawler agents that reads a site in seconds', 'github.example', 412, 'pmc', '3 hours ago', 188],
+ ['Spider silk proteins made in yeast at industrial scale', 'nature-digest.example', 290, 'arachne', '5 hours ago', 97],
+ ['Robots.txt was never meant for agents', 'blog.example', 254, 'kv', '6 hours ago', 141],
+ ['Ask: how do you budget tokens for long-running agents?', 'newsdesk.example', 198, 'tm', '7 hours ago', 203],
+ ['The web is quietly becoming an API', 'essays.example', 176, 'jb', '8 hours ago', 64],
+ ['Why my agent kept buying the same book', 'postmortem.example', 161, 'lw', '9 hours ago', 88],
+ ['A minimal browser for agents, in 600 lines', 'code.example', 143, 'dn', '10 hours ago', 52],
+ ['Jumping spiders can see in colour, and plan routes', 'science.example', 131, 'ro', '11 hours ago', 39],
+ ['We replaced our nightly cron jobs with agents', 'eng.example', 120, 'sh', '12 hours ago', 77],
+ ['Ballooning: how spiderlings travel hundreds of km', 'wildlife.example', 111, 'mf', '13 hours ago', 26],
+ ['Agents that ask before they click', 'ux.example', 98, 'ae', '14 hours ago', 31],
+ ['Crawling 1B pages on a single machine', 'infra.example', 92, 'zz', '15 hours ago', 45],
+ ['The case for plain HTML in 2026', 'web.example', 87, 'cb', '16 hours ago', 58],
+ ['Show: watch your agents as spiders on a map of your site', 'demo.example', 80, 'qq', '17 hours ago', 22],
+ ['Silk, steel and Kevlar: a fair comparison', 'materials.example', 74, 'ps', '18 hours ago', 19],
+ ])},
+ {url: 'en.encyclopedia.example/wiki/Spider', theme: 'light', html: wiki('Spider', [
+ 'Spiders are eight-legged arachnids of the order Araneae. Almost all of them make <a>silk</a>, and most use <a>venom</a> to subdue their prey. More than 50,000 species have been described, and they live on every continent except <a>Antarctica</a>.',
+ 'A spider\'s body has two main parts, the <a>cephalothorax</a> and the <a>abdomen</a>, joined by a narrow waist. The legs, the fangs and most of the eyes sit on the front part; the silk glands and <a>spinnerets</a> sit at the back.',
+ ], `<div class="wk-box"><div class="wk-bt">Spider</div>${img(230, '#d8cdb8', '#8a7a5c')}<div class="wk-bc">Temporal range: Carboniferous – present</div><div class="wk-bt2">Scientific classification</div><table>${[['Kingdom', 'Animalia'], ['Phylum', 'Arthropoda'], ['Subphylum', 'Chelicerata'], ['Class', 'Arachnida'], ['Order', 'Araneae']].map(([a, b]) => `<tr><td>${a}:</td><td><a>${b}</a></td></tr>`).join('')}</table></div>`, [
+ ['Silk', ['Silk comes out of the spinnerets as a liquid and hardens as it is pulled. One spider can make several kinds: dragline silk for safety lines, sticky threads for capture, and soft silk for wrapping eggs.', 'Weight for weight, dragline silk is comparable to high-grade steel in strength and far more elastic.']],
+ ['Webs and hunting', ['Many spiders build webs and wait. Others hunt on foot, ambush prey from burrows, or <a>jump</a> on it from a distance. Some spin no web at all and use silk only for travel and shelter.']],
+ ['Ballooning', ['Young spiders of many species travel by <a>ballooning</a>: they climb to a high point, release a few threads, and let the wind and electric fields lift them. Spiderlings have been caught far out at sea and kilometres above the ground.']],
+ ], ['Field guide to spiders of the world, 2nd ed., p. 12.', 'Silk: structure, proteins and mechanical properties. Review, vol. 41.', 'Hunting strategies in non-web-building spiders. Notes, p. 88.', 'Aerial dispersal of spiderlings. Proceedings, vol. 7.', 'Arachnid anatomy for beginners, ch. 3.', 'Venom and digestion in Araneae. Review, vol. 19.'])},
+ {url: 'codehost.example/acme/crawler', theme: 'dark', html: `
+<div class="s-repo">
+ <div class="rp-top"><b>⌂</b><span>acme / <b>crawler</b></span><em>Public</em></div>
+ <div class="rp-tabs"><b>Code</b><span>Issues 42</span><span>Pull requests 7</span><span>Actions</span><span>Wiki</span><span>Insights</span></div>
+ <div class="rp-bar"><span class="rp-br">⑂ main</span><span>3 branches · 28 tags</span><span class="rp-go">Code ▾</span></div>
+ <div class="rp-files">
+ <div class="rp-h"><b>agent-17</b> spawn: cap children per page at 16 <i>· 4m ago · 1,284 commits</i></div>
+ ${[['src', 'spawn subagents on a beat grid', '4m'], ['src/agent', 'agent: read, decide, move', '1h'], ['src/pages', 'snapshot real pages for the wall', '3h'], ['tests', 'add 256-agent soak test', '1d'], ['docs', 'how the swarm splits work', '2d'], ['.github/workflows', 'nightly crawl on 16 pages', '5d'], ['README.md', 'swarm: one agent becomes 256', '4m'], ['package.json', 'bump playwright', '6d'], ['LICENSE', 'MIT', '1y']].map(([f, m, t]) => `<div class="rp-f"><span class="rp-fn">${f.includes('.') ? '▤' : '▸'} ${f}</span><span class="rp-fm">${m}</span><span class="rp-ft">${t}</span></div>`).join('')}
+ </div>
+ <div class="rp-readme"><div class="rp-rh">README.md</div><h2>crawler</h2><p>One agent reads a page. When the page is big, it spawns a subagent and gives it half. Every two beats the swarm doubles, until every page has its own reader.</p><pre>npx crawler --start https://example.com --max-agents 256
+✓ 1 → 2 → 4 → 8 → 16 → 32 → 64 → 128 → 256
+✓ 16 pages · 3,412 words read · 0 pages twice</pre><p>Agents share one queue and never read the same page twice. Each one writes what it found to a single log you can read in the morning.</p></div>
+</div>`},
+ {url: 'shop.example/p/silk-thread-500m', theme: 'light', html: `
+<div class="s-shop">
+ <div class="sh-top"><b>shop</b><div class="sh-search">Search products</div><span>Account</span><span>Cart (2)</span></div>
+ <div class="sh-crumbs">Home › Craft › Thread › Natural fibres</div>
+ <div class="sh-grid">
+ <div>${img(470, '#f3e9d8', '#cdb48a', ';border-radius:12px')}<div class="sh-th">${[0, 1, 2, 3].map(() => img(88, '#efe4d0', '#d8c3a0', ';border-radius:8px')).join('')}</div></div>
+ <div class="sh-info"><h1>Natural Silk Thread, 500 m Spool</h1><div class="sh-st">★★★★☆ <a>4.6 · 1,284 ratings</a></div><div class="sh-pr">$12.99</div><div class="sh-ship">Free delivery Thursday. In stock.</div><div class="sh-btn">Add to cart</div><div class="sh-btn2">Buy now</div>
+ <ul><li>Fine, strong and slightly elastic</li><li>Hand-wound, 500 metres per spool</li><li>Good for embroidery, repairs and fishing flies</li><li>Ships in a recyclable box</li></ul></div>
+ </div>
+ <h2>Customer reviews</h2>
+ <div class="sh-rev"><b>★★★★★ Stronger than it looks</b><p>Used it to repair a net. Thin, but it holds. Will buy again.</p></div>
+ <div class="sh-rev"><b>★★★★☆ My agent ordered three</b><p>I asked for one spool. The agent compared prices across nine shops and decided three was the better deal. It was right.</p></div>
+ <div class="sh-rev"><b>★★★☆☆ Tangles easily</b><p>Great thread, but unwind it slowly. It has a mind of its own.</p></div>
+</div>`},
+
+ // row 2
+ {url: 'mail.example/inbox', theme: 'light', html: `
+<div class="s-mail">
+ <div class="ml-top"><b>✉ mail</b><div class="ml-search">Search mail</div></div>
+ <div class="ml-grid"><div class="ml-side"><div class="ml-compose">✎ Compose</div>${['Inbox 24', 'Starred', 'Snoozed', 'Sent', 'Drafts 3', 'Agents', 'Receipts', 'Spam'].map((s, i) => `<div class="${i ? '' : 'on'}">${s}</div>`).join('')}</div>
+ <div class="ml-list">${[
+ ['Agent #17', 'Morning summary: 1,204 pages read', 'Nothing urgent. Three prices changed overnight, one link is broken.', '07:02'],
+ ['Crawler bot', 'Your crawl finished', '16 pages, 256 agents, 0 errors. Full log attached.', '06:48'],
+ ['Billing', 'Invoice for September', 'Your usage this month is attached. Most of it came from one night.', 'Oct 1'],
+ ['Agent #4', 'I need a decision', 'Two suppliers, same price. One ships faster, the other has better reviews.', 'Oct 1'],
+ ['Newsdesk digest', 'Top stories this week', 'A swarm of crawler agents, silk made in yeast, and the case for plain HTML.', 'Sep 30'],
+ ['Agent #91', 'Draft ready for review', 'I rewrote the landing page copy. I did not publish it.', 'Sep 30'],
+ ['Calendar', 'Reminder: review agent logs', 'Every Friday at 10:00. Bring coffee.', 'Sep 29'],
+ ['Shop', 'Your order has shipped', 'Natural Silk Thread, 500 m Spool (×3). Arrives Thursday.', 'Sep 29'],
+ ['Agent #203', 'Stuck on a captcha', 'I stopped and saved my place. Can you take a look?', 'Sep 28'],
+ ['Security', 'New sign-in from an agent', 'If this was you, no action is needed.', 'Sep 28'],
+ ['Agent #12', 'Found a cheaper flight', 'Same route, two hours later, 40% less. Want me to hold it?', 'Sep 27'],
+ ['Team', 'Swarm demo on Friday', 'Bring your weirdest page. We will see how long it lasts.', 'Sep 27'],
+ ].map(([f, s, sn, t], i) => `<div class="ml-r ${i < 4 ? 'un' : ''}"><span class="ml-f">${f}</span><span class="ml-s"><b>${s}</b> – ${sn}</span><span class="ml-t">${t}</span></div>`).join('')}</div></div>
+</div>`},
+ {url: 'qa.example/questions/stop-agent-loop', theme: 'light', html: `
+<div class="s-qa">
+ <div class="qa-top"><b>▤ qa</b><div class="qa-search">Search…</div></div>
+ <h1>How do I stop my agent from clicking the same button forever?</h1>
+ <div class="qa-meta">Asked 2 days ago · Modified today · Viewed 12k times</div>
+ <div class="qa-q"><div class="qa-v">▲<b>214</b>▼</div><div>${P('My browser agent gets stuck on a page with a "Load more" button. It clicks it, the page changes a little, and it clicks again. After an hour it has clicked 3,000 times and read nothing new.')}<pre>while not done:
+ page = observe()
+ action = decide(page) # always "click load more"
+ act(action)</pre>${P('How do I make it notice that it is not making progress?')}<div class="qa-tags"><span>agents</span><span>browser-automation</span><span>loops</span></div></div></div>
+ <h2>3 Answers</h2>
+ <div class="qa-q qa-a"><div class="qa-v">▲<b>389</b>▼<i>✓</i></div><div>${P('Give the loop a memory and a budget. Keep a hash of the last few page states and stop when the new state is the same as an old one. Also cap the number of steps per page.')}<pre>seen = set()
+for step in range(50):
+ page = observe()
+ if hash(page) in seen: break
+ seen.add(hash(page))
+ act(decide(page))</pre>${P('And make "stop and report" one of the actions the agent can choose. Agents loop when every option looks equally good.')}</div></div>
+</div>`},
+ {url: 'docs.agents.example/api/spawn', theme: 'dark', html: `
+<div class="s-docs">
+ <div class="dc-top"><b>agents</b><span>Docs</span><span>API</span><span>Guides</span><span>Changelog</span><div class="dc-search">Search docs ⌘K</div></div>
+ <div class="dc-grid"><div class="dc-side">${['Getting started', 'Agents', ' create', ' spawn', ' join', ' stop', 'Pages', ' read', ' click', ' fill', 'Logs', 'Limits', 'Pricing'].map((s) => `<div class="${s.trim() === 'spawn' ? 'on' : ''}">${s.trim()}</div>`).join('')}</div>
+ <div class="dc-main"><div class="dc-crumb">API › Agents › spawn</div><h1>spawn</h1>${P('Creates a subagent that inherits the parent\'s task, tools and budget share. The parent keeps running. Children report back to the parent, never to each other.')}<pre><span class="k">const</span> child = <span class="k">await</span> agent.<span class="f">spawn</span>({
+ task: <span class="s">'read the second half of this page'</span>,
+ budget: parent.budget / <span class="n">2</span>,
+ page: <span class="s">'https://example.com/docs'</span>,
+});</pre><h2>Parameters</h2><table>${[['task', 'string', 'What the child should do, in plain words.'], ['budget', 'number', 'Max steps. Defaults to half of the parent.'], ['page', 'string', 'Where the child starts. Defaults to the parent page.'], ['onDone', 'function', 'Called with the child\'s report.']].map((r) => `<tr><td><code>${r[0]}</code></td><td>${r[1]}</td><td>${r[2]}</td></tr>`).join('')}</table><h2>Limits</h2>${P('A swarm can double at most 8 times: one agent becomes 256. Each page gets at most 16 agents, the rest move on to the next page in the queue.')}</div></div>
+</div>`},
+ {url: 'en.encyclopedia.example/wiki/Web_crawler', theme: 'light', html: wiki('Web crawler', [
+ 'A <b>web crawler</b>, also called a <a>spider</a> or <a>bot</a>, is a program that browses the <a>World Wide Web</a> automatically, usually to build an index for a <a>search engine</a>.',
+ 'A crawler starts from a list of seed addresses, downloads each page, extracts its links and adds them to a queue. It repeats this until the queue is empty or a limit is reached.',
+ ], `<div class="wk-box"><div class="wk-bt">Web crawler</div>${img(170, '#dfe7ef', '#8aa0b8')}<div class="wk-bc">A crawler follows links from page to page</div></div>`, [
+ ['Politeness', ['A polite crawler reads a site\'s <a>robots.txt</a> file first and follows its rules. It also limits how often it requests pages, so the site does not slow down for human visitors.']],
+ ['Agents', ['A newer kind of crawler does more than read. <a>AI agents</a> open pages in a real browser, click buttons, fill in forms and make decisions for the person who sent them. Many sites now write separate rules for crawlers that index and agents that act.']],
+ ['Scale', ['Large crawlers fetch billions of pages. They run many workers in parallel, share one queue, and keep a record of every address they have seen so that no page is read twice.']],
+ ], ['Crawling the web: an introduction. Lecture notes, part 2.', 'Politeness policies for automated agents. Workshop paper.', 'The robots exclusion standard, explained. Guide, p. 4.', 'Parallel crawlers and shared queues. Systems review, vol. 12.'])},
+
+ // row 3
+ {url: 'sheets.example/d/agent-log', theme: 'light', html: `
+<div class="s-sheet">
+ <div class="st-top"><b>▦ agent-log</b><span>File Edit View Insert Format Data Tools</span></div>
+ <div class="st-fx"><b>fx</b> =SUM(D2:D21)</div>
+ <table><tr><th></th>${['A', 'B', 'C', 'D', 'E', 'F'].map((c) => `<th>${c}</th>`).join('')}</tr>
+ <tr><td>1</td><td><b>agent</b></td><td><b>page</b></td><td><b>gen</b></td><td><b>words</b></td><td><b>status</b></td><td><b>parent</b></td></tr>
+ ${Array.from({length: 26}, (_, i) => {
+ const pages = ['wiki/Spider', 'search', 'news', 'forum', 'feed', 'repo', 'shop', 'inbox', 'qa', 'docs', 'wiki/Web_crawler', 'video'];
+ const st = ['reading', 'done', 'done', 'reading', 'waiting', 'done'][i % 6];
+ return `<tr><td>${i + 2}</td><td>#${String(i * 9 + 1).padStart(3, '0')}</td><td>${pages[i % pages.length]}</td><td>${Math.min(8, Math.floor(Math.log2(i * 9 + 2)))}</td><td>${(i * 137 + 41) % 900 + 60}</td><td class="${st}">${st}</td><td>#${String(Math.floor((i * 9 + 1) / 2)).padStart(3, '0')}</td></tr>`;
+ }).join('')}</table>
+</div>`},
+ {url: 'morningledger.example/business/night-shift', theme: 'light', html: news('The Morning Ledger', 'Business', 'The night shift that never logs off', 'Small teams now leave agents running overnight. In the morning there is a summary, a list of drafts, and a bill.', 'By the Ledger business desk · 4 min read', [
+ 'At six in the morning the office is empty, but the work log is not. Overnight, a group of agents read supplier pages, compared prices, answered routine emails and drafted three proposals.',
+ 'Nobody approved anything yet. That is the rule: agents can read and draft, people decide and send. The morning starts with a short summary and a queue of things to sign off.',
+ 'The appeal is obvious for a team of four. The risk is quieter. An agent that misreads a page can repeat the mistake a thousand times before anyone wakes up, which is why every action goes into a log.',
+ ], ['Your next visitor might not be a person', 'Agents that ask before they click', 'What a 256-agent crawl costs', 'Plain HTML is back', 'The receipts your agents keep'])},
+ {url: 'chirp.example/explore', theme: 'dark', html: social([
+ ['web weekly', '@webweekly', '3m', 'the internet in 2026: you open one tab, your agents open the other 255', ['21', '140', '1.4K', '40K'], false],
+ ['macro world', '@macroworld', '22m', 'reminder that real spiders also send out tiny scouts. it is called ballooning and it is wild', ['9', '61', '820', '15K'], true],
+ ['agent 203', '@agent_203', '40m', 'stuck on a captcha. saved my place. waiting for a human. this is fine', ['30', '75', '2.2K', '31K'], false],
+ ['cs explained', '@csexplained', '1h', 'a crawler with a queue is a spider. a crawler with a goal is an agent. same web, different job', ['14', '88', '960', '19K'], false],
+ ])},
+ {url: 'seek.example/search?q=spider+silk+vs+steel', theme: 'light', html: search('spider silk vs steel', [
+ ['materials.example', 'Spider silk vs steel: a fair comparison', 'Weight for weight, dragline silk is comparable to high-grade steel in strength, and it can stretch far more before it breaks.'],
+ ['nature-digest.example', 'Why spider silk is so tough', 'The secret is structure: stiff crystal regions held together by flexible chains. Strength from one, stretch from the other.'],
+ ['science.example › news', 'Silk proteins made in yeast at scale', 'Researchers produce silk-like fibres without spiders. The fibres are close, but not yet as good as the real thing.'],
+ ['qa.example', 'Is spider silk really stronger than Kevlar?', 'Depends on the measure. Kevlar is stiffer; silk absorbs more energy before breaking. Both beat steel by weight.'],
+ ['wildlife.example', 'How spiders use silk for travel', 'Spiderlings release threads and let the wind carry them. The behaviour is called ballooning.'],
+ ['en.encyclopedia.example', 'Spider silk – Encyclopedia', 'Spider silk is a protein fibre spun by spiders. Spiders use it to build webs, wrap prey, protect eggs and travel.'],
+ ['vidtube.example', 'Spider silk is stronger than you think (video)', 'A slow-motion look at silk under load, and why it rarely snaps all at once.'],
+ ])},
+];
+
+export default PAGES;
diff --git a/sims/crawlers/style.css b/sims/crawlers/style.css
new file mode 100644
index 0000000..d22f19c
--- /dev/null
+++ b/sims/crawlers/style.css
@@ -0,0 +1,164 @@
+:root { --bg: #060709; }
+#stage { position: absolute; top: 0; width: 1080px; overflow: hidden; transform-origin: 0 0; background: #060709; }
+#stage #gl { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 5; }
+.world { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
+.page { position: absolute; width: 1080px; overflow: hidden; background: #0d0e12; border: 1px solid #22242c; border-radius: 16px; color: #d6d8df; font-family: Inter, sans-serif; }
+.page .bar { height: 64px; display: flex; align-items: center; gap: 22px; padding: 0 28px; border-bottom: 1px solid #22242c; background: #111218; font: 400 20px 'JetBrains Mono', monospace; color: #8d909c; }
+.page .dots { display: flex; gap: 9px; }
+.page .dots b { width: 13px; height: 13px; border-radius: 50%; background: #2a2c35; }
+.page .crumbs i { font-style: normal; color: #4a4d58; margin: 0 8px; }
+.page .crumbs { white-space: nowrap; }
+.page .content { padding: 26px 40px 0; }
+.page pre.code { margin: 0; font: 400 21px/1.62 'JetBrains Mono', monospace; color: #c9cbd4; white-space: pre; }
+.page pre.code .ln { display: inline-block; width: 46px; color: #3d404b; text-align: right; margin-right: 22px; }
+.page .kw { color: #b79cff; } .page .str { color: #8fe3b0; } .page .com { color: #5f6372; font-style: italic; }
+.page .md h1 { font: 800 46px/1.15 Inter; color: #fff; margin: 10px 0 18px; letter-spacing: -0.02em; }
+.page .md h2 { font: 700 32px/1.2 Inter; color: #fff; margin: 22px 0 12px; padding-bottom: 8px; border-bottom: 1px solid #22242c; }
+.page .md p { font-size: 24px; line-height: 1.55; margin: 0 0 6px; }
+.page .md li { font-size: 24px; line-height: 1.55; margin: 0 0 4px 26px; list-style: disc; display: list-item; }
+.page .md b { color: #fff; }
+.page .md code { font-family: 'JetBrains Mono', monospace; font-size: 0.86em; color: #c9cbd4; background: #171820; padding: 1px 6px; border-radius: 5px; }
+.page .md pre.mdc { font: 400 20px/1.55 'JetBrains Mono', monospace; background: #13141a; border: 1px solid #22242c; border-radius: 10px; padding: 12px 18px; margin: 6px 0 12px; white-space: pre; color: #c9cbd4; overflow: hidden; }
+.page .md .gapl { height: 12px; }
+.w { border-radius: 4px; }
+
+.counters { position: absolute; left: 28px; top: 28px; z-index: 6; display: flex; align-items: flex-end; gap: 34px; padding: 20px 28px 22px; font-family: 'JetBrains Mono', monospace; background: #0b0c10; border: 1px solid #2a2c35; border-radius: 18px; box-shadow: 0 12px 40px rgba(0,0,0,0.45); }
+.counters .c { display: flex; flex-direction: column; gap: 4px; }
+.counters span { font: 600 19px 'JetBrains Mono', monospace; letter-spacing: 0.14em; text-transform: uppercase; color: #8d909c; }
+.counters b { font: 700 40px 'JetBrains Mono', monospace; color: #fff; font-variant-numeric: tabular-nums; }
+.counters .big b { font-size: 76px; line-height: 0.95; color: #ff3db4; }
+.wm { position: absolute; right: 26px; bottom: 22px; z-index: 7; font: 400 20px 'JetBrains Mono', monospace; color: rgba(255,255,255,0.45); }
+
+/* generic web pages (sites.js) */
+.page.site { border-color: #2a2c35; }
+.page.site.light { background: #fff; color: #202124; }
+.page.site.dark { background: #0f1014; color: #e3e4e8; }
+.page.site .content { padding: 0; }
+.chrome { height: 60px; display: flex; align-items: center; gap: 20px; padding: 0 22px; background: #1b1c22; border-bottom: 1px solid #2a2c35; font: 400 19px Inter, sans-serif; color: #9a9da8; }
+.chrome .dots { display: flex; gap: 9px; }
+.chrome .dots b { width: 13px; height: 13px; border-radius: 50%; background: #3a3c46; }
+.chrome .url { flex: 1; background: #26272f; border-radius: 18px; padding: 8px 18px; white-space: nowrap; overflow: hidden; color: #c9cbd4; }
+.chrome .url::before { content: '🔒 '; filter: grayscale(1); opacity: 0.6; }
+.s-img { width: 100%; border-radius: 4px; }
+.site a { color: #1a5fd0; }
+.site.dark a { color: #7aa2ff; }
+.site p { margin: 0 0 14px; }
+
+.s-wiki { padding: 0 44px; font: 400 23px/1.55 'FreeSerif', 'C059', serif; }
+.s-wiki .wk-top { display: flex; align-items: center; justify-content: space-between; height: 76px; border-bottom: 1px solid #c8ccd1; font-family: Inter; }
+.s-wiki .wk-logo { font: 700 26px 'C059', serif; }
+.s-wiki .wk-search { border: 1px solid #a2a9b1; padding: 8px 14px; width: 360px; font: 400 18px Inter; color: #72777d; border-radius: 2px; }
+.s-wiki .wk-tabs { display: flex; gap: 20px; font: 400 18px Inter; padding: 14px 0 8px; color: #1a5fd0; border-bottom: 1px solid #a2a9b1; }
+.s-wiki .wk-tabs b { color: #202122; font-weight: 400; border-bottom: 3px solid #202122; } .s-wiki .wk-tabs i { flex: 1; }
+.s-wiki h1 { font: 400 46px/1.2 'C059', serif; margin: 22px 0 4px; border-bottom: 1px solid #a2a9b1; padding-bottom: 6px; }
+.s-wiki .wk-from { font: 400 17px Inter; color: #54595d; margin-bottom: 16px; }
+.s-wiki h2 { font: 400 32px 'C059', serif; margin: 22px 0 10px; border-bottom: 1px solid #a2a9b1; padding-bottom: 4px; }
+.s-wiki .wk-box { float: right; width: 330px; margin: 0 0 16px 22px; border: 1px solid #a2a9b1; background: #f8f9fa; padding: 8px; font: 400 17px/1.4 Inter; }
+.s-wiki .wk-bt { text-align: center; font-weight: 700; font-size: 20px; padding: 4px 0 8px; background: #e2d8c2; margin: -8px -8px 8px; padding-top: 8px; }
+.s-wiki .wk-bt2 { text-align: center; font-weight: 700; background: #e2d8c2; margin: 8px -8px; padding: 4px; }
+.s-wiki .wk-bc { text-align: center; color: #54595d; font-size: 15px; padding: 6px 0; }
+.s-wiki table { width: 100%; font-size: 17px; } .s-wiki td { padding: 2px 4px; }
+.s-wiki .wk-refs { font: 400 18px/1.5 Inter; color: #202122; padding-left: 30px; }
+
+.s-search { padding: 0 52px; font-family: Inter, sans-serif; }
+.s-search .sr-top { display: flex; align-items: center; gap: 28px; height: 104px; }
+.s-search .sr-logo { font: 700 38px Inter; color: #3d7bff; letter-spacing: -0.03em; }
+.s-search .sr-box { flex: 1; border: 1px solid #dfe1e5; border-radius: 28px; padding: 14px 24px; font-size: 21px; box-shadow: 0 1px 6px rgba(32,33,36,0.18); display: flex; justify-content: space-between; }
+.s-search .sr-tabs { display: flex; gap: 26px; font-size: 18px; color: #5f6368; border-bottom: 1px solid #ebebeb; padding-bottom: 10px; margin-left: 4px; }
+.s-search .sr-tabs b { color: #1a5fd0; border-bottom: 3px solid #1a5fd0; padding-bottom: 8px; font-weight: 500; }
+.s-search .sr-count { font-size: 16px; color: #70757a; margin: 14px 0 10px; }
+.s-search .sr-r { margin: 0 0 30px; max-width: 900px; }
+.s-search .sr-site { font-size: 17px; color: #202124; display: flex; align-items: center; gap: 10px; } .s-search .sr-site i { width: 26px; height: 26px; border-radius: 50%; background: #e8eaed; }
+.s-search .sr-r a { display: block; font-size: 25px; color: #1a0dab; margin: 6px 0 4px; }
+.s-search .sr-r p { font-size: 19px; line-height: 1.55; color: #4d5156; margin: 0; }
+
+.s-news { padding: 0 44px; font-family: 'C059', serif; }
+.s-news .nw-mast { text-align: center; font: 700 64px 'C059', serif; padding: 26px 0 10px; border-bottom: 1px solid #222; }
+.s-news .nw-nav { display: flex; justify-content: center; gap: 28px; font: 600 17px Inter; padding: 12px 0; border-bottom: 3px double #222; text-transform: uppercase; letter-spacing: 0.06em; }
+.s-news .nw-grid { display: grid; grid-template-columns: 1fr 270px; gap: 36px; padding-top: 22px; }
+.s-news .nw-kick { font: 700 16px Inter; color: #c0392b; text-transform: uppercase; letter-spacing: 0.1em; }
+.s-news h1 { font: 700 50px/1.08 'C059', serif; margin: 8px 0 12px; }
+.s-news .nw-dek { font: 400 23px/1.4 'C059', serif; color: #444; margin-bottom: 10px; }
+.s-news .nw-by { font: 600 16px Inter; color: #666; margin-bottom: 14px; }
+.s-news .nw-cap { font: 400 14px Inter; color: #777; margin: 6px 0 16px; }
+.s-news p { font: 400 21px/1.6 'C059', serif; }
+.s-news .nw-side h3 { font: 700 18px Inter; text-transform: uppercase; letter-spacing: 0.08em; border-top: 3px solid #222; padding-top: 10px; }
+.s-news .nw-mr { display: flex; gap: 12px; padding: 12px 0; border-bottom: 1px solid #ddd; font: 600 19px/1.3 'C059', serif; } .s-news .nw-mr b { font: 700 28px Inter; color: #c0392b; }
+
+.s-forum { font: 400 20px Verdana, 'DejaVu Sans', sans-serif; background: #f6f6ef; min-height: 100%; }
+.s-forum .fm-top { background: #2a8c82; color: #fff; display: flex; gap: 16px; align-items: center; padding: 8px 14px; font-size: 18px; }
+.s-forum .fm-top b { font-size: 20px; } .s-forum .fm-login { margin-left: auto; }
+.s-forum .fm-it { display: flex; gap: 10px; padding: 9px 14px 3px; }
+.s-forum .fm-n { color: #828282; width: 34px; text-align: right; }
+.s-forum .fm-t { color: #000; } .s-forum .fm-t i { color: #828282; font-size: 16px; font-style: normal; }
+.s-forum .fm-m { font-size: 15px; color: #828282; margin-top: 3px; }
+
+.s-social { font-family: Inter, sans-serif; }
+.s-social .so-top { display: flex; gap: 40px; padding: 18px 30px 0; border-bottom: 1px solid #2f3336; font-size: 20px; color: #71767b; }
+.s-social .so-top b { color: #e7e9ea; font-size: 26px; margin-right: auto; } .s-social .so-top span { padding-bottom: 14px; } .s-social .so-top .on { color: #e7e9ea; border-bottom: 4px solid #1d9bf0; }
+.s-social .so-post { display: flex; gap: 16px; padding: 22px 30px; border-bottom: 1px solid #2f3336; }
+.s-social .so-av { width: 58px; height: 58px; border-radius: 50%; flex: none; }
+.s-social .so-b { flex: 1; }
+.s-social .so-h { font-size: 20px; } .s-social .so-h span { color: #71767b; margin-left: 8px; }
+.s-social .so-t { font-size: 23px; line-height: 1.45; margin: 6px 0; }
+.s-social .so-s { display: flex; justify-content: space-between; color: #71767b; font-size: 18px; max-width: 640px; margin-top: 8px; }
+
+.s-video { font-family: Inter, sans-serif; padding: 0 28px; }
+.s-video .vd-top { display: flex; align-items: center; gap: 30px; height: 84px; } .s-video .vd-top b { font-size: 28px; }
+.s-video .vd-search { flex: 1; border: 1px solid #303030; border-radius: 24px; padding: 10px 20px; color: #888; font-size: 19px; }
+.s-video .vd-chips { display: flex; gap: 12px; margin-bottom: 22px; } .s-video .vd-chips span { background: #272727; padding: 8px 16px; border-radius: 10px; font-size: 18px; } .s-video .vd-chips .on { background: #f1f1f1; color: #0f0f0f; }
+.s-video .vd-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 26px 22px; }
+.s-video .vd-t { font: 600 21px/1.3 Inter; margin: 12px 0 6px; } .s-video .vd-m { font-size: 17px; color: #aaa; line-height: 1.4; }
+
+.s-repo { font-family: Inter, sans-serif; padding: 0 34px; font-size: 19px; }
+.s-repo .rp-top { display: flex; gap: 16px; align-items: center; height: 74px; font-size: 24px; } .s-repo .rp-top em { font-style: normal; font-size: 15px; border: 1px solid #3d444d; border-radius: 12px; padding: 2px 10px; color: #9198a1; }
+.s-repo .rp-tabs { display: flex; gap: 26px; border-bottom: 1px solid #3d444d; padding-bottom: 12px; color: #9198a1; } .s-repo .rp-tabs b { color: #f0f6fc; border-bottom: 2px solid #f78166; padding-bottom: 10px; }
+.s-repo .rp-bar { display: flex; gap: 18px; align-items: center; margin: 20px 0 14px; color: #9198a1; } .s-repo .rp-br { background: #212830; border: 1px solid #3d444d; padding: 6px 12px; border-radius: 6px; color: #f0f6fc; } .s-repo .rp-go { margin-left: auto; background: #238636; color: #fff; padding: 7px 14px; border-radius: 6px; font-weight: 600; }
+.s-repo .rp-files { border: 1px solid #3d444d; border-radius: 8px; overflow: hidden; }
+.s-repo .rp-h { background: #151b23; padding: 12px 16px; border-bottom: 1px solid #3d444d; } .s-repo .rp-h i { color: #9198a1; font-style: normal; }
+.s-repo .rp-f { display: grid; grid-template-columns: 280px 1fr 70px; padding: 10px 16px; border-bottom: 1px solid #262c36; } .s-repo .rp-fm, .s-repo .rp-ft { color: #9198a1; } .s-repo .rp-ft { text-align: right; }
+.s-repo .rp-readme { border: 1px solid #3d444d; border-radius: 8px; margin-top: 20px; padding: 0 20px 10px; } .s-repo .rp-rh { margin: 0 -20px; padding: 12px 20px; border-bottom: 1px solid #3d444d; font-weight: 600; }
+.s-repo h2 { font-size: 32px; border-bottom: 1px solid #3d444d; padding-bottom: 8px; } .s-repo p { line-height: 1.55; }
+.s-repo pre { background: #151b23; border-radius: 6px; padding: 14px; font: 400 17px/1.6 'JetBrains Mono'; white-space: pre; overflow: hidden; }
+
+.s-shop { font-family: Inter, sans-serif; padding: 0 34px; font-size: 19px; }
+.s-shop .sh-top { display: flex; align-items: center; gap: 24px; height: 78px; margin: 0 -34px; padding: 0 34px; background: #131921; color: #fff; } .s-shop .sh-top b { font-size: 28px; }
+.s-shop .sh-search { flex: 1; background: #fff; color: #888; border-radius: 6px; padding: 10px 16px; }
+.s-shop .sh-crumbs { font-size: 16px; color: #565959; margin: 16px 0; }
+.s-shop .sh-grid { display: grid; grid-template-columns: 470px 1fr; gap: 30px; } .s-shop .sh-th { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-top: 10px; }
+.s-shop h1 { font: 500 32px/1.25 Inter; margin: 0 0 10px; } .s-shop .sh-st { color: #de7921; } .s-shop .sh-pr { font: 500 44px Inter; margin: 14px 0 6px; }
+.s-shop .sh-ship { color: #067d62; margin-bottom: 16px; } .s-shop .sh-btn, .s-shop .sh-btn2 { background: #ffd814; border-radius: 22px; text-align: center; padding: 12px; margin-bottom: 10px; } .s-shop .sh-btn2 { background: #ffa41c; }
+.s-shop ul { padding-left: 22px; line-height: 1.6; } .s-shop h2 { font-size: 28px; margin: 24px 0 10px; } .s-shop .sh-rev { border-top: 1px solid #ddd; padding: 12px 0 0; } .s-shop .sh-rev b { color: #c45500; }
+
+.s-mail { font-family: Inter, sans-serif; font-size: 18px; }
+.s-mail .ml-top { display: flex; align-items: center; gap: 40px; height: 78px; padding: 0 26px; } .s-mail .ml-top b { font-size: 26px; color: #c5221f; }
+.s-mail .ml-search { flex: 1; background: #eaf1fb; border-radius: 24px; padding: 12px 22px; color: #5f6368; }
+.s-mail .ml-grid { display: grid; grid-template-columns: 200px 1fr; }
+.s-mail .ml-side div { padding: 9px 20px; border-radius: 0 18px 18px 0; color: #202124; } .s-mail .ml-side .on { background: #d3e3fd; font-weight: 700; }
+.s-mail .ml-compose { background: #c2e7ff; border-radius: 16px !important; margin: 0 10px 14px; padding: 16px 20px !important; font-weight: 600; }
+.s-mail .ml-r { display: grid; grid-template-columns: 170px 1fr 70px; gap: 12px; padding: 13px 18px; border-bottom: 1px solid #eceff1; color: #5f6368; white-space: nowrap; overflow: hidden; }
+.s-mail .ml-r.un { background: #fff; color: #202124; } .s-mail .ml-r:not(.un) { background: #f2f6fc; } .s-mail .ml-s { overflow: hidden; text-overflow: ellipsis; } .s-mail .ml-r.un .ml-f { font-weight: 700; }
+
+.s-qa { font-family: Inter, sans-serif; padding: 0 40px; font-size: 20px; }
+.s-qa .qa-top { display: flex; align-items: center; gap: 30px; height: 70px; border-top: 4px solid #f48024; margin: 0 -40px; padding: 0 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.12); } .s-qa .qa-top b { font-size: 24px; }
+.s-qa .qa-search { flex: 1; border: 1px solid #babfc4; border-radius: 6px; padding: 8px 14px; color: #888; }
+.s-qa h1 { font: 400 32px/1.3 Inter; margin: 22px 0 8px; } .s-qa .qa-meta { font-size: 16px; color: #6a737c; border-bottom: 1px solid #e3e6e8; padding-bottom: 14px; }
+.s-qa .qa-q { display: flex; gap: 22px; padding: 18px 0; line-height: 1.55; } .s-qa .qa-v { display: flex; flex-direction: column; align-items: center; color: #babfc4; font-size: 26px; min-width: 50px; } .s-qa .qa-v b { color: #232629; font-size: 24px; } .s-qa .qa-v i { color: #2f6f44; font-style: normal; font-size: 30px; }
+.s-qa pre { background: #f6f6f6; border-radius: 6px; padding: 14px; font: 400 17px/1.55 'JetBrains Mono'; white-space: pre; }
+.s-qa .qa-tags span { background: #e1ecf4; color: #39739d; padding: 4px 10px; border-radius: 4px; margin-right: 8px; font-size: 16px; } .s-qa h2 { font: 400 26px Inter; }
+
+.s-docs { font-family: Inter, sans-serif; font-size: 19px; }
+.s-docs .dc-top { display: flex; align-items: center; gap: 28px; height: 72px; padding: 0 28px; border-bottom: 1px solid #2a2c35; color: #9a9da8; } .s-docs .dc-top b { color: #fff; font-size: 24px; } .s-docs .dc-search { margin-left: auto; border: 1px solid #2a2c35; border-radius: 8px; padding: 8px 14px; }
+.s-docs .dc-grid { display: grid; grid-template-columns: 230px 1fr; }
+.s-docs .dc-side { border-right: 1px solid #2a2c35; padding: 18px 0; } .s-docs .dc-side div { padding: 7px 26px; color: #9a9da8; } .s-docs .dc-side .on { color: #fff; background: #1d1f27; border-left: 3px solid #4dff9a; }
+.s-docs .dc-main { padding: 22px 34px; line-height: 1.6; } .s-docs .dc-crumb { color: #6b6e7a; font-size: 16px; } .s-docs h1 { font: 700 44px Inter; margin: 8px 0 12px; } .s-docs h2 { font: 700 28px Inter; margin: 26px 0 10px; }
+.s-docs pre { background: #15161c; border: 1px solid #2a2c35; border-radius: 10px; padding: 16px 18px; font: 400 18px/1.6 'JetBrains Mono'; white-space: pre; color: #c9cbd4; }
+.s-docs .k { color: #b79cff; } .s-docs .s { color: #8fe3b0; } .s-docs .n { color: #ffd23d; } .s-docs .f { color: #7aa2ff; }
+.s-docs table { width: 100%; border-collapse: collapse; } .s-docs td { border-bottom: 1px solid #2a2c35; padding: 10px 8px; vertical-align: top; } .s-docs code { font-family: 'JetBrains Mono'; color: #4dff9a; }
+
+.s-sheet { font-family: Inter, sans-serif; font-size: 18px; }
+.s-sheet .st-top { display: flex; gap: 26px; align-items: center; height: 70px; padding: 0 22px; } .s-sheet .st-top b { color: #188038; font-size: 24px; } .s-sheet .st-top span { color: #444; }
+.s-sheet .st-fx { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; padding: 8px 22px; color: #333; font-family: 'JetBrains Mono'; } .s-sheet .st-fx b { color: #888; margin-right: 18px; }
+.s-sheet table { border-collapse: collapse; width: 100%; } .s-sheet th { background: #f8f9fa; color: #5f6368; font-weight: 500; border: 1px solid #e2e3e3; height: 30px; }
+.s-sheet td { border: 1px solid #e2e3e3; padding: 7px 10px; white-space: nowrap; } .s-sheet td:first-child { background: #f8f9fa; color: #5f6368; text-align: center; width: 44px; }
+.s-sheet .done { color: #188038; } .s-sheet .reading { color: #1a5fd0; } .s-sheet .waiting { color: #b06000; }
diff --git a/sims/dossier/main.js b/sims/dossier/main.js
new file mode 100644
index 0000000..2f98d49
--- /dev/null
+++ b/sims/dossier/main.js
@@ -0,0 +1,737 @@
+import {runSim} from '../kit/runtime.js';
+import {clamp01, easeInOutCubic, lerp, rng} from '../kit/util.js';
+import SITES from './sites.js';
+
+// "Dossier": the crawlers sim (sims/crawlers) pointed at one made-up person. One
+// agent starts on @nightwren_88's profile and doubles every 2 beats (1 → 256)
+// across twelve public pages about them. Each page leaks one detail; an agent
+// walks to it, the phrase gets a red box and a numbered tag, and a red thread
+// carries it into the dossier docked at the bottom. When all twelve are in,
+// the wall dims and the threads stay: "0 hacks · all public".
+//
+// Same engine as crawlers: the whole run is simulated once at 60 Hz on load, so
+// render(t) is a pure lookup. Pages: sites.js (all invented, .example).
+
+const DEFAULTS = {
+ duration: 20,
+ fps: 60,
+ theme: 'dark',
+ hud: {enabled: false, title: 'dossier', subtitle: ''},
+ director: {enabled: false},
+ watermark: 'X: @whaleyxbt',
+ seed: 5,
+ pages: SITES,
+ target: '@nightwren_88',
+ // one per page, in the order they are found; f = data-f of the .ev phrase
+ // in sites.js, t = when it is found (snapped to the nearest beat with music)
+ facts: [
+ {f: 'pet', label: 'PET', value: 'Biscuit, a beagle', t: 1.67},
+ {f: 'bday', label: 'BIRTHDAY', value: '14 March', t: 6.8},
+ {f: 'alias', label: 'ALIASES', value: 'wren.h · n_wren', t: 7.71},
+ {f: 'email', label: 'EMAIL', value: 'w.h███@mail.example', t: 8.47},
+ {f: 'city', label: 'CITY', value: 'Portvale', t: 9.78},
+ {f: 'name', label: 'NAME', value: 'Wren H███████', t: 10.63},
+ {f: 'work', label: 'WORK', value: 'Kestrel Cargo', t: 11.49},
+ {f: 'home', label: 'HOME', value: 'Alder St', t: 12.35},
+ {f: 'gym', label: 'ROUTINE', value: 'gym Tue/Thu 6:40', t: 13.19},
+ {f: 'phone', label: 'PHONE', value: '••• ••• 41 07', t: 14.05},
+ {f: 'car', label: 'CAR', value: 'grey hatch ··4K7', t: 14.91},
+ {f: 'leaks', label: 'LEAKS', value: '3 data breaches', t: 15.7},
+ ],
+ endLine: '0 hacks · all public',
+ swarm: {
+ cols: 4,
+ rows: 3,
+ first: [1, 1], // page (col, row) where agent #1 starts
+ pageH: 1400,
+ gap: 90,
+ gens: 8, // 2^gens agents at the end
+ genStart: 2.4, // first doubling; with music it snaps to the next beat
+ genEvery: 1.25, // seconds between doublings without music
+ genBeats: 2, // beats between doublings with music (cfg.beats)
+ spread: 0.18, // children of one generation are born within this many seconds
+ stayGens: 3, // generations that land on their parent's page
+ blockGens: 6, // ...then on the 2x2 block around page 1, then anywhere
+ web: 230, // world px: agents closer than this share a thread
+ counters: true,
+ },
+};
+
+const W = 1080;
+const DT = 1 / 60;
+// no reds or pinks: red is reserved for findings
+const PALETTE = ['#19c3ff', '#4dff9a', '#3d7bff', '#ffd23d', '#a98bff', '#e8ecf2', '#7ff0d0'];
+const RED = '#ff2d3d';
+const RGB = PALETTE.map((h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)));
+
+const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+function wrapWords(root) {
+ const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ const texts = [];
+ while (walk.nextNode()) texts.push(walk.currentNode);
+ for (const tn of texts) {
+ if (!tn.textContent.trim() || tn.parentElement.closest('.ln')) continue;
+ const frag = document.createDocumentFragment();
+ for (const part of tn.textContent.split(/(\s+)/)) {
+ if (!part) continue;
+ if (/^\s+$/.test(part)) frag.appendChild(document.createTextNode(part));
+ else {
+ const s = document.createElement('span');
+ s.className = 'w';
+ s.textContent = part;
+ frag.appendChild(s);
+ }
+ }
+ tn.replaceWith(frag);
+ }
+ return [...root.querySelectorAll('.w')];
+}
+
+const angWrap = (a) => Math.atan2(Math.sin(a), Math.cos(a));
+
+/** Doubling times: every genEvery s, or every genBeats beats of the music. */
+function genTimes(cfg) {
+ const S = cfg.swarm;
+ const b = cfg.beats && cfg.beats.beats;
+ if (b && b.length) {
+ const i = Math.max(0, b.findIndex((x) => x >= S.genStart));
+ return [...Array(S.gens)].map((_, g) => b[Math.min(b.length - 1, i + g * S.genBeats)]);
+ }
+ return [...Array(S.gens)].map((_, g) => S.genStart + g * S.genEvery);
+}
+
+
+/** Fact times, snapped to the nearest beat when there is music. */
+function factTimes(cfg) {
+ const b = cfg.beats && cfg.beats.beats;
+ return cfg.facts.map(({t}) => (b && b.length ? b.reduce((best, x) => (Math.abs(x - t) < Math.abs(best - t) ? x : best), b[0]) : t));
+}
+
+const HUNT_LEAD = 1.6; // seconds before a fact's time the nearest agent heads for it
+
+function simulate(cfg, words, pages, facts) {
+ const S = cfg.swarm;
+ const R = rng(cfg.seed);
+ const N = Math.ceil((cfg.duration + 0.2) / DT) + 1;
+ const n = 2 ** S.gens;
+ const firstPage = S.first[1] * S.cols + S.first[0];
+
+ // births: generation g doubles the swarm
+ const G = genTimes(cfg);
+ const ag = [{born: -1, parent: -1, size: 1.35, color: 0, gen: -1}];
+ for (let g = 0; g < S.gens; g++) {
+ const cur = ag.length;
+ for (let i = 0; i < cur; i++)
+ ag.push({born: G[g] + R() * S.spread, parent: i, gen: g, size: 0.8 + R() * 0.45, color: Math.floor(R() * PALETTE.length)});
+ }
+ // reveal order: page 1, its 2x2 block, then the rest by distance
+ const [fc, fr] = S.first;
+ const block = [[fc, fr], [fc + 1, fr], [fc, fr - 1], [fc + 1, fr - 1]].map(([c, r]) => r * S.cols + c);
+ const rest = pages.map((_, i) => i).filter((i) => !block.includes(i));
+ rest.sort((a, b) => Math.hypot(a % S.cols - fc - 0.5, Math.floor(a / S.cols) - fr + 0.5) - Math.hypot(b % S.cols - fc - 0.5, Math.floor(b / S.cols) - fr + 0.5));
+ const reveal = [...block, ...rest];
+ const count = new Array(pages.length).fill(0);
+ const pageWords = pages.map(() => []);
+ words.forEach((w, i) => pageWords[w.page].push(i));
+
+ const GS = 80;
+ const grid = new Map();
+ words.forEach((w, i) => {
+ for (let gx = Math.floor(w.x / GS); gx <= Math.floor((w.x + w.w) / GS); gx++)
+ for (let gy = Math.floor(w.y / GS); gy <= Math.floor((w.y + w.h) / GS); gy++) {
+ const k = gx * 100000 + gy;
+ if (!grid.has(k)) grid.set(k, []);
+ grid.get(k).push(i);
+ }
+ });
+ const hit = (x, y) => {
+ for (const i of grid.get(Math.floor(x / GS) * 100000 + Math.floor(y / GS)) || []) {
+ const w = words[i];
+ if (x >= w.x - 4 && x <= w.x + w.w + 4 && y >= w.y - 5 && y <= w.y + w.h + 5) return i;
+ }
+ return -1;
+ };
+ const wc = (i) => [words[i].x + words[i].w / 2, words[i].y + words[i].h / 2];
+
+ const pos = new Float32Array(N * n * 3).fill(NaN); // x, y, angle per frame per agent
+ const feet = new Float32Array(N * n * 16);
+ const lift = new Uint8Array(N * n * 8);
+ const hits = []; // [t, word, colour]
+ const flights = []; // {a, t0, t1, x0, y0}
+
+ const TH = [38, 78, 112, 148].map((d) => (d * Math.PI) / 180);
+ const RR = [112, 118, 112, 104];
+ const st = ag.map(() => null);
+ const pickTarget = (s, near) => {
+ const list = pageWords[s.page];
+ for (let tries = 0; tries < 12; tries++) {
+ const i = list[Math.floor(R() * list.length)];
+ const [x, y] = wc(i);
+ if (!near || Math.hypot(x - s.x, y - s.y) < 430) return [x, y];
+ }
+ return wc(list[Math.floor(R() * list.length)]);
+ };
+ const local = (s, lx, ly) => [s.x + Math.cos(s.ang) * lx - Math.sin(s.ang) * ly, s.y + Math.sin(s.ang) * lx + Math.cos(s.ang) * ly];
+ const restOf = (s, L) => local(s, Math.cos(TH[L.j]) * RR[L.j] * s.size, L.side * Math.sin(TH[L.j]) * RR[L.j] * s.size);
+
+ for (let f = 0; f < N; f++) {
+ const t = f * DT;
+ // births
+ for (let a = 0; a < n; a++) {
+ if (st[a] || ag[a].born > t) continue;
+ const A = ag[a];
+ const s = {x: 0, y: 0, ang: R() * Math.PI * 2, speed: 0, size: A.size, vmax: 230 + R() * 170, mode: 'walk', until: 0, idle: 0, tx: 0, ty: 0, page: firstPage, fly: null, hunt: null};
+ if (A.parent < 0) {
+ // start below-left of the first fact, so its walk to it is on screen
+ const F0 = facts[0];
+ const dm = (i) => Math.hypot(words[i].x - (F0.cx - 330), words[i].y - (F0.cy + 210));
+ const pw = pageWords[firstPage];
+ [s.x, s.y] = wc(pw.reduce((b, i) => (dm(i) < dm(b) ? i : b), pw[0]));
+ s.ang = -0.5;
+ } else {
+ const p = st[A.parent];
+ let page = p.page;
+ if (A.gen >= S.stayGens) {
+ const open = reveal.slice(0, A.gen < S.blockGens ? 4 : pages.length);
+ page = open.reduce((b, i) => (count[i] < count[b] ? i : b), open[0]);
+ }
+ s.page = page;
+ const [x1, y1] = page === p.page ? [p.x + (R() - 0.5) * 260, p.y + (R() - 0.5) * 260] : pickTarget(s, false);
+ const d = Math.hypot(x1 - p.x, y1 - p.y);
+ s.fly = {t0: t, t1: t + Math.min(0.95, 0.3 + d / 2600), x0: p.x, y0: p.y, x1, y1};
+ flights.push({a, t0: t, t1: s.fly.t1, x0: p.x, y0: p.y});
+ s.x = p.x;
+ s.y = p.y;
+ }
+ count[s.page]++;
+ [s.tx, s.ty] = pickTarget(s, true);
+ s.legs = [...Array(8)].map((_, i) => {
+ const L = {side: i < 4 ? -1 : 1, j: i % 4, step: false};
+ L.group = (L.j + (L.side > 0 ? 1 : 0)) % 2;
+ return L;
+ });
+ for (const L of s.legs) L.f = restOf(s, L);
+ st[a] = s;
+ }
+
+ // hunters: the nearest free agent on a fact's page walks to the phrase
+ for (const F of facts) {
+ if (F.agent >= 0 || t < F.t - HUNT_LEAD) continue;
+ let best = -1, bd = Infinity;
+ for (let a = 0; a < n; a++) {
+ const s = st[a];
+ if (!s || s.fly || s.hunt || s.page !== F.page) continue;
+ const d = Math.hypot(s.x - F.cx, s.y - F.cy);
+ if (d < bd) {
+ bd = d;
+ best = a;
+ }
+ }
+ if (best < 0) continue;
+ const s = st[best];
+ s.hunt = F;
+ s.mode = 'walk';
+ s.tx = F.cx;
+ s.ty = F.cy;
+ F.agent = best;
+ }
+
+ for (let a = 0; a < n; a++) {
+ const s = st[a];
+ if (!s) continue;
+ if (s.fly) {
+ const q = easeInOutCubic((t - s.fly.t0) / (s.fly.t1 - s.fly.t0));
+ s.x = lerp(s.fly.x0, s.fly.x1, q);
+ s.y = lerp(s.fly.y0, s.fly.y1, q);
+ s.ang += 4 * DT;
+ for (const L of s.legs) {
+ L.f = restOf(s, L);
+ L.step = false;
+ }
+ if (t >= s.fly.t1) {
+ s.fly = null;
+ [s.tx, s.ty] = pickTarget(s, true);
+ }
+ } else {
+ const dx = s.tx - s.x, dy = s.ty - s.y;
+ const dist = Math.hypot(dx, dy);
+ if (s.mode === 'walk') {
+ const wander = s.hunt ? 0 : 0.4 * Math.sin(t * 2.1 + a * 1.3) * clamp01(dist / 260);
+ const da = angWrap(Math.atan2(dy, dx) + wander - s.ang);
+ s.ang += Math.max(-8 * DT, Math.min(8 * DT, da));
+ const vt = Math.max(60, (s.hunt ? 440 : s.vmax) * clamp01(dist / 130)) * Math.max(0.3, Math.cos(da));
+ s.speed = lerp(s.speed, vt, 1 - Math.exp(-DT * 9));
+ if (dist < (s.hunt ? 16 : 22)) {
+ s.mode = 'dwell';
+ if (s.hunt) {
+ if (s.hunt.found == null) s.hunt.found = Math.max(s.hunt.t, t);
+ s.until = s.hunt.found + 0.8;
+ } else s.until = t + 0.12 + R() * 0.45;
+ }
+ } else {
+ s.speed = lerp(s.speed, 0, 1 - Math.exp(-DT * 14));
+ if (t >= s.until) {
+ s.hunt = null;
+ s.mode = 'walk';
+ [s.tx, s.ty] = pickTarget(s, true);
+ }
+ }
+ s.x += Math.cos(s.ang) * s.speed * DT;
+ s.y += Math.sin(s.ang) * s.speed * DT;
+ s.idle = s.speed < 30 ? s.idle + DT : 0;
+ const busy = [false, false];
+ for (const L of s.legs) if (L.step) busy[L.group] = true;
+ for (const L of s.legs) {
+ if (L.step) {
+ const q = (t - L.t0) / L.dur;
+ if (q >= 1) {
+ L.step = false;
+ L.f = L.to;
+ const wi = hit(L.f[0], L.f[1]);
+ if (wi >= 0) hits.push([t, wi, ag[a].color]);
+ } else {
+ const e = easeInOutCubic(q);
+ L.f = [lerp(L.from[0], L.to[0], e), lerp(L.from[1], L.to[1], e)];
+ }
+ continue;
+ }
+ const r = restOf(s, L);
+ const d = Math.hypot(L.f[0] - r[0], L.f[1] - r[1]);
+ const thr = s.idle > 0.12 ? 14 : 56 * s.size;
+ if (d > thr && (!busy[1 - L.group] || d > thr * 2.4)) {
+ const lead = 0.07 * s.speed;
+ L.from = L.f;
+ L.to = [r[0] + Math.cos(s.ang) * lead + (R() - 0.5) * 10, r[1] + Math.sin(s.ang) * lead + (R() - 0.5) * 10];
+ L.t0 = t;
+ L.dur = s.idle > 0.12 ? 0.1 : 0.075;
+ L.step = true;
+ busy[L.group] = true;
+ }
+ }
+ }
+ const o = (f * n + a) * 3;
+ pos[o] = s.x;
+ pos[o + 1] = s.y;
+ const prev = f ? pos[o - n * 3 + 2] : NaN;
+ pos[o + 2] = Number.isNaN(prev) ? s.ang : prev + angWrap(s.ang - prev);
+ s.legs.forEach((L, i) => {
+ feet[(f * n + a) * 16 + i * 2] = L.f[0];
+ feet[(f * n + a) * 16 + i * 2 + 1] = L.f[1];
+ lift[(f * n + a) * 8 + i] = L.step ? Math.round(255 * Math.sin(Math.PI * clamp01((t - L.t0) / L.dur))) : 0;
+ });
+ }
+ }
+ return {N, n, ag, pos, feet, lift, hits, flights};
+}
+
+const easeOutCubic = (x) => 1 - (1 - clamp01(x)) ** 3;
+
+runSim(DEFAULTS, async ({cfg, canvas}) => {
+ await Promise.all([
+ document.fonts.load('400 20px "JetBrains Mono"'),
+ document.fonts.load('600 20px "JetBrains Mono"'),
+ document.fonts.load('700 20px "JetBrains Mono"'),
+ document.fonts.load('400 20px Inter'),
+ document.fonts.load('700 20px Inter'),
+ ]).catch(() => {});
+ document.title = 'dossier';
+ const S = cfg.swarm;
+ const pagesCfg = cfg.pages.slice(0, S.cols * S.rows);
+
+ const app = document.getElementById('app');
+ const stage = document.createElement('div');
+ stage.id = 'stage';
+ app.appendChild(stage);
+ const world = document.createElement('div');
+ world.className = 'world';
+ stage.appendChild(world);
+ stage.appendChild(canvas);
+
+ const pageEls = pagesCfg.map((p, i) => {
+ const el = document.createElement('div');
+ el.className = `page site ${p.theme}`;
+ const c = i % S.cols, r = Math.floor(i / S.cols);
+ el.style.left = `${c * (W + S.gap)}px`;
+ el.style.top = `${r * (S.pageH + S.gap)}px`;
+ el.style.height = `${S.pageH}px`;
+ el.innerHTML = `<div class="chrome"><span class="dots"><b></b><b></b><b></b></span><span class="nav">‹ › ↻</span><span class="url">${esc(p.url)}</span></div><div class="content">${p.html}</div>`;
+ world.appendChild(el);
+ return el;
+ });
+
+ // the dossier: fixed layout from frame 0, rows fill as facts come in
+ const nF = cfg.facts.length;
+ const dos = document.createElement('div');
+ dos.className = 'dossier';
+ dos.innerHTML = `<div class="d-av"><div class="d-ring"></div><div class="d-face"><b></b><i></i></div></div>
+ <div class="d-head"><div class="d-t"><span>TARGET</span><b>${esc(cfg.target)}</b></div><div class="d-st"></div></div>
+ <div class="d-grid" style="grid-template-rows:repeat(${Math.ceil(nF / 2)},52px)">${cfg.facts.map((F, i) => `<div class="d-r"><span class="d-n">${String(i + 1).padStart(2, '0')}</span><span class="d-l">${esc(F.label)}</span><span class="d-v"></span></div>`).join('')}</div>
+ <div class="d-foot"><span>AGENTS<b>1</b></span><span>PAGES<b>1/${pagesCfg.length}</b></span><span>WORDS READ<b>0</b></span><span class="d-wm">${esc(cfg.watermark || '')}</span></div>`;
+ stage.appendChild(dos);
+ const [endA, endB] = cfg.endLine.split(' · ');
+ const endEl = document.createElement('div');
+ endEl.className = 'endline';
+ endEl.innerHTML = `<b>${esc(endA)}.</b> <span>${esc(endB || '')}.</span>`;
+ stage.appendChild(endEl);
+
+ let s = 1, VH = 1350, cardTop = 864, VC = 432;
+ const layout = () => {
+ const iw = innerWidth, ih = innerHeight;
+ s = iw / ih <= 1 ? iw / W : ih / 1350;
+ VH = ih / s;
+ stage.style.left = `${(iw - W * s) / 2}px`;
+ stage.style.height = `${VH}px`;
+ stage.style.transform = `scale(${s})`;
+ const dpr = devicePixelRatio || 1;
+ canvas.width = Math.round(W * s * dpr);
+ canvas.height = Math.round(VH * s * dpr);
+ cardTop = (dos.getBoundingClientRect().top - stage.getBoundingClientRect().top) / s;
+ VC = cardTop / 2;
+ };
+ layout();
+
+ // words in world coordinates (world is untransformed while measuring)
+ const wr = world.getBoundingClientRect();
+ const words = [];
+ pageEls.forEach((pe, pi) => {
+ const pr = pe.getBoundingClientRect();
+ for (const el of wrapWords(pe.querySelector('.content'))) {
+ const r = el.getBoundingClientRect();
+ if (r.bottom > pr.bottom - 10 || r.width === 0) continue; // clipped by the page
+ words.push({el, page: pi, x: (r.left - wr.left) / s, y: (r.top - wr.top) / s, w: r.width / s, h: r.height / s});
+ }
+ });
+
+ // facts: the phrase's words, its box and page
+ const FT = factTimes(cfg);
+ const facts = cfg.facts.map((F, i) => {
+ const ev = world.querySelector(`.ev[data-f="${F.f}"]`);
+ const ws = [];
+ words.forEach((w, wi) => {
+ if (ev && ev.contains(w.el)) ws.push(wi);
+ });
+ if (!ws.length) throw new Error(`dossier: no visible phrase for fact "${F.f}"`);
+ const x0 = Math.min(...ws.map((k) => words[k].x)), y0 = Math.min(...ws.map((k) => words[k].y));
+ const x1 = Math.max(...ws.map((k) => words[k].x + words[k].w)), y1 = Math.max(...ws.map((k) => words[k].y + words[k].h));
+ return {...F, i, words: ws, page: words[ws[0]].page, x0, y0, x1, y1, cx: (x0 + x1) / 2, cy: (y0 + y1) / 2, t: FT[i], agent: -1, found: null};
+ });
+
+ const sim = simulate(cfg, words, pagesCfg, facts);
+ const {n, ag, pos, feet, lift, flights} = sim;
+ for (const F of facts) {
+ if (F.found == null) {
+ console.warn(`dossier: fact "${F.f}" never reached, forcing it`);
+ F.found = F.t + 0.6;
+ }
+ F.on = F.found + 0.42; // the thread reaches the dossier
+ }
+ const tDone = Math.max(...facts.map((F) => F.on)) + 0.5;
+ const redOf = new Array(words.length).fill(0);
+ for (const F of facts) for (const k of F.words) redOf[k] = F.found;
+
+ // per-word hit lists (time-sorted), first-hit times for the counter
+ const wh = words.map(() => []);
+ for (const h of sim.hits) wh[h[1]].push(h);
+ const firsts = wh.filter((l) => l.length).map((l) => l[0][0]).sort((a, b) => a - b);
+ const pageOpen = new Array(pagesCfg.length).fill(1e9);
+ for (let a = 0; a < n; a++) {
+ const f = Math.min(sim.N - 1, Math.ceil((ag[a].born + 1.2) / DT));
+ const x = pos[(f * n + a) * 3], y = pos[(f * n + a) * 3 + 1];
+ const c = Math.floor(x / (W + S.gap)), r = Math.floor(y / (S.pageH + S.gap));
+ const pi = r * S.cols + c;
+ if (pi >= 0 && pi < pageOpen.length) pageOpen[pi] = Math.min(pageOpen[pi], ag[a].born);
+ }
+ const opens = pageOpen.filter((x) => x < 1e9).sort((a, b) => a - b);
+ window.__OSINT = {agents: n, words: words.length, wordsRead: firsts.length, tDone, facts: facts.map((F) => ({f: F.f, page: F.page, t: +F.t.toFixed(2), found: +F.found.toFixed(2), late: +(F.found - F.t).toFixed(2)}))};
+
+ // camera: page 1 → its 2x2 block → the whole wall, a slow push while the board holds
+ const P = (c, r) => ({x: c * (W + S.gap), y: r * (S.pageH + S.gap)});
+ const [fc, fr] = S.first;
+ const p0 = P(fc, fr);
+ const gridW = S.cols * W + (S.cols - 1) * S.gap, gridH = S.rows * S.pageH + (S.rows - 1) * S.gap;
+ const GT = genTimes(cfg);
+ const keys = () => {
+ const AH = cardTop - 70; // the avatar pokes up out of the card
+ const blockZ = Math.min((W * 0.94) / (2 * W + S.gap), (AH * 0.94) / (2 * S.pageH + S.gap));
+ const wallZ = Math.min((W * 0.95) / gridW, (AH * 0.95) / gridH);
+ const tWall = GT[S.gens - 1] + 0.9;
+ return [
+ {t: 0, x: p0.x + W / 2, y: p0.y + VC, z: 1},
+ {t: GT[2], x: p0.x + W / 2, y: p0.y + VC + 110, z: 1},
+ {t: GT[3] + 0.6, x: p0.x + W + S.gap / 2, y: p0.y - S.gap / 2, z: blockZ},
+ {t: GT[5] + 0.3, x: p0.x + W + S.gap / 2 + 20, y: p0.y - S.gap / 2 + 30, z: blockZ * 0.97},
+ {t: tWall, x: gridW / 2, y: gridH / 2, z: wallZ},
+ {t: Math.max(tWall + 1, tDone), x: gridW / 2 + 30, y: gridH / 2 + 20, z: wallZ * 1.03},
+ // pull back and down a little so the end line sits above the wall
+ {t: cfg.duration, x: gridW / 2, y: gridH / 2 - 230, z: wallZ * 0.9},
+ ];
+ };
+ let K = keys();
+ const camAt = (t) => {
+ let i = 0;
+ while (i < K.length - 2 && t > K[i + 1].t) i++;
+ const a = K[i], b = K[i + 1];
+ const q = easeInOutCubic((t - a.t) / (b.t - a.t));
+ const z = Math.exp(lerp(Math.log(a.z), Math.log(b.z), q));
+ return {x: lerp(a.x, b.x, q), y: lerp(a.y, b.y, q), z};
+ };
+
+ const ctx = canvas.getContext('2d');
+ const shown = new Array(words.length).fill('');
+ const rows = [...dos.querySelectorAll('.d-r')];
+ const rowShown = rows.map(() => '');
+ const [cA, cP, cW] = dos.querySelectorAll('.d-foot b');
+ const stEl = dos.querySelector('.d-st'), ring = dos.querySelector('.d-ring');
+ const countLE = (arr, t) => {
+ let lo = 0, hi = arr.length;
+ while (lo < hi) {
+ const m = (lo + hi) >> 1;
+ if (arr[m] <= t) lo = m + 1;
+ else hi = m;
+ }
+ return lo;
+ };
+ const fmt = (x) => x.toLocaleString('en-US');
+ // a value types in one character at a time; █ is drawn as a redaction bar
+ const valueHTML = (v, k) =>
+ [...v]
+ .slice(0, k)
+ .join('')
+ .split(/(█+)/)
+ .map((p) => (p[0] === '█' ? `<u style="width:${(p.length * 0.56).toFixed(2)}em"></u>` : esc(p)))
+ .join('');
+
+ return {
+ resize() {
+ layout();
+ K = keys();
+ },
+ render(t) {
+ const cam = camAt(t);
+ world.style.transform = `translate(${W / 2 - cam.x * cam.z}px, ${VC - cam.y * cam.z}px) scale(${cam.z})`;
+ const SX = (x) => W / 2 + (x - cam.x) * cam.z, SY = (y) => VC + (y - cam.y) * cam.z;
+
+ // highlights: the latest hit on each word; found phrases turn red
+ for (let i = 0; i < words.length; i++) {
+ let v = '';
+ if (redOf[i] && t >= redOf[i]) {
+ const al = Math.round((0.4 + 0.5 * Math.exp(-(t - redOf[i]) / 0.35)) * 20) / 20;
+ v = `rgba(255,45,61,${al})`;
+ } else {
+ const l = wh[i];
+ if (l.length && l[0][0] <= t) {
+ let lo = 0, hi = l.length - 1;
+ while (lo < hi) {
+ const m = (lo + hi + 1) >> 1;
+ if (l[m][0] <= t) lo = m;
+ else hi = m - 1;
+ }
+ const [ht, , c] = l[lo];
+ const al = Math.round((0.2 + 0.55 * Math.exp(-(t - ht) / 0.25)) * 20) / 20;
+ v = `rgba(${RGB[c][0]},${RGB[c][1]},${RGB[c][2]},${al})`;
+ }
+ }
+ if (v !== shown[i]) {
+ shown[i] = v;
+ words[i].el.style.background = v;
+ }
+ }
+
+ // canvas, world space: web, spawn threads, spiders
+ const fi = Math.max(0, Math.min(sim.N - 1.001, t / DT));
+ const f = Math.floor(fi), a = fi - f;
+ const dpr = canvas.width / (W * s);
+ ctx.setTransform(s * dpr, 0, 0, s * dpr, 0, 0);
+ ctx.clearRect(0, 0, W, VH);
+ ctx.save();
+ ctx.translate(W / 2 - cam.x * cam.z, VC - cam.y * cam.z);
+ ctx.scale(cam.z, cam.z);
+ const alive = [];
+ for (let i = 0; i < n; i++) if (!Number.isNaN(pos[(f * n + i) * 3]) && !Number.isNaN(pos[((f + 1) * n + i) * 3])) alive.push(i);
+ const X = new Float32Array(n), Y = new Float32Array(n);
+ for (const i of alive) {
+ X[i] = lerp(pos[(f * n + i) * 3], pos[((f + 1) * n + i) * 3], a);
+ Y[i] = lerp(pos[(f * n + i) * 3 + 1], pos[((f + 1) * n + i) * 3 + 1], a);
+ }
+ const lw = (w) => Math.max(w, (w * 0.45) / cam.z);
+
+ ctx.lineWidth = lw(1.2);
+ for (let u = 0; u < alive.length; u++)
+ for (let v = u + 1; v < alive.length; v++) {
+ const i = alive[u], j = alive[v];
+ const d = Math.hypot(X[i] - X[j], Y[i] - Y[j]);
+ if (d > S.web) continue;
+ ctx.strokeStyle = `rgba(25,195,255,${(0.45 * (1 - d / S.web)).toFixed(3)})`;
+ ctx.beginPath();
+ ctx.moveTo(X[i], Y[i]);
+ ctx.lineTo(X[j], Y[j]);
+ ctx.stroke();
+ }
+ for (const fl of flights) {
+ if (t < fl.t0 || t > fl.t1 + 0.35) continue;
+ const fade = t > fl.t1 ? 1 - (t - fl.t1) / 0.35 : 1;
+ ctx.strokeStyle = `rgba(255,255,255,${(0.85 * fade).toFixed(3)})`;
+ ctx.lineWidth = lw(2);
+ ctx.beginPath();
+ ctx.moveTo(fl.x0, fl.y0);
+ ctx.lineTo(X[fl.a], Y[fl.a]);
+ ctx.stroke();
+ }
+ ctx.lineCap = 'round';
+ for (const i of alive) {
+ const A = ag[i];
+ const ang = lerp(pos[(f * n + i) * 3 + 2], pos[((f + 1) * n + i) * 3 + 2], a);
+ const x = X[i], y = Y[i], sz = A.size;
+ const col = PALETTE[A.color], joint = PALETTE[(A.color + 3) % PALETTE.length];
+ const ca = Math.cos(ang), sa = Math.sin(ang);
+ const L1 = 66 * sz, L2 = 74 * sz;
+ ctx.globalAlpha = clamp01((t - A.born) / 0.25);
+ ctx.strokeStyle = col;
+ ctx.fillStyle = joint;
+ for (let l = 0; l < 8; l++) {
+ const side = l < 4 ? -1 : 1, j = l % 4;
+ const HX = [16, 6, -4, -14][j] * sz;
+ const hx = x + ca * HX - sa * side * 6 * sz, hy = y + sa * HX + ca * side * 6 * sz;
+ const o = (f * n + i) * 16 + l * 2, o2 = ((f + 1) * n + i) * 16 + l * 2;
+ const fX = lerp(feet[o], feet[o2], a), fY = lerp(feet[o + 1], feet[o2 + 1], a);
+ const lf = lerp(lift[(f * n + i) * 8 + l], lift[((f + 1) * n + i) * 8 + l], a) / 255;
+ const dx = fX - hx, dy = fY - hy;
+ const d = Math.max(Math.abs(L1 - L2) + 1, Math.min(L1 + L2 - 1, Math.hypot(dx, dy)));
+ const base = Math.atan2(dy, dx);
+ const k = Math.acos(Math.max(-1, Math.min(1, (L1 * L1 + d * d - L2 * L2) / (2 * L1 * d))));
+ let kx = hx + Math.cos(base + k) * L1, ky = hy + Math.sin(base + k) * L1;
+ const kx2 = hx + Math.cos(base - k) * L1, ky2 = hy + Math.sin(base - k) * L1;
+ if (Math.hypot(kx2 - x, ky2 - y) > Math.hypot(kx - x, ky - y)) {
+ kx = kx2;
+ ky = ky2;
+ }
+ const kd = Math.hypot(kx - x, ky - y) || 1;
+ kx += ((kx - x) / kd) * lf * 12;
+ ky += ((ky - y) / kd) * lf * 12;
+ ctx.lineWidth = lw(3.1);
+ ctx.beginPath();
+ ctx.moveTo(hx, hy);
+ ctx.lineTo(kx, ky);
+ ctx.lineTo(fX, fY);
+ ctx.stroke();
+ const r = lw(4.2);
+ ctx.beginPath();
+ ctx.arc(kx, ky, r, 0, Math.PI * 2);
+ ctx.moveTo(fX + r * 1.1, fY);
+ ctx.arc(fX, fY, r * 1.1 + lf * 2.5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.save();
+ ctx.translate(x, y);
+ ctx.rotate(ang);
+ ctx.fillStyle = 'rgba(8,9,13,0.92)';
+ ctx.strokeStyle = col;
+ ctx.lineWidth = lw(2.6);
+ const bl = 48 * sz, bw = 17 * sz;
+ ctx.beginPath();
+ ctx.rect(-bl / 2, -bw / 2, bl, bw);
+ ctx.fill();
+ ctx.stroke();
+ ctx.fillStyle = A.parent < 0 || facts.some((F) => F.agent === i && t >= F.t - HUNT_LEAD && t < F.found + 0.8) ? RED : '#19c3ff';
+ ctx.beginPath();
+ ctx.arc(bl * 0.22, 0, Math.max(5.5 * sz, 2 / cam.z), 0, Math.PI * 2);
+ ctx.fill();
+ ctx.restore();
+ ctx.globalAlpha = 1;
+ }
+ ctx.restore();
+
+ // screen space: dim the wall once the profile is complete, then the board
+ const dim = easeInOutCubic(clamp01((t - tDone) / 1.0));
+ if (dim > 0) {
+ ctx.fillStyle = `rgba(4,5,8,${(0.62 * dim).toFixed(3)})`;
+ ctx.fillRect(0, 0, W, VH);
+ }
+ const ax = W / 2, ay = cardTop;
+ ctx.font = `700 17px 'JetBrains Mono', monospace`;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ for (const F of facts) {
+ if (t < F.found) continue;
+ const q = clamp01((t - F.found) / 0.3);
+ let x0 = SX(F.x0) - 6, y0 = SY(F.y0) - 5, x1 = SX(F.x1) + 6, y1 = SY(F.y1) + 5;
+ const mw = Math.max(0, 34 - (x1 - x0)) / 2, mh = Math.max(0, 24 - (y1 - y0)) / 2;
+ x0 -= mw; x1 += mw; y0 -= mh; y1 += mh;
+ const pop = 22 * (1 - easeOutCubic(q));
+ // thread from the box into the avatar, sagging a little
+ const bx = (x0 + x1) / 2, by = y1;
+ const mx = (bx + ax) / 2, my = (by + ay) / 2 + Math.hypot(ax - bx, ay - by) * 0.12;
+ const p = easeOutCubic((t - F.found) / 0.42);
+ const old = t > F.on + 0.9 && t < tDone;
+ ctx.strokeStyle = old ? 'rgba(255,45,61,0.5)' : RED;
+ ctx.lineWidth = old ? 2 : 2.8;
+ ctx.beginPath();
+ const SEG = 28;
+ for (let k = 0; k <= SEG * p; k++) {
+ const u = k / SEG;
+ const px = (1 - u) * (1 - u) * bx + 2 * u * (1 - u) * mx + u * u * ax;
+ const py = (1 - u) * (1 - u) * by + 2 * u * (1 - u) * my + u * u * ay;
+ if (k) ctx.lineTo(px, py);
+ else ctx.moveTo(px, py);
+ }
+ ctx.stroke();
+ if (p < 1) {
+ const hx = (1 - p) * (1 - p) * bx + 2 * p * (1 - p) * mx + p * p * ax;
+ const hy = (1 - p) * (1 - p) * by + 2 * p * (1 - p) * my + p * p * ay;
+ ctx.fillStyle = '#fff';
+ ctx.beginPath();
+ ctx.arc(hx, hy, 5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ // box and numbered tag
+ ctx.globalAlpha = q;
+ ctx.strokeStyle = RED;
+ ctx.lineWidth = 3;
+ ctx.strokeRect(x0 - pop, y0 - pop, x1 - x0 + 2 * pop, y1 - y0 + 2 * pop);
+ ctx.fillStyle = RED;
+ ctx.beginPath();
+ ctx.roundRect(x0 - 2, y0 - 31, 44, 27, 6);
+ ctx.fill();
+ ctx.fillStyle = '#fff';
+ ctx.fillText(String(F.i + 1).padStart(2, '0'), x0 + 20, y0 - 17);
+ ctx.globalAlpha = 1;
+ }
+
+ // dossier rows
+ let done = 0;
+ facts.forEach((F, i) => {
+ let h;
+ if (t < F.on) h = '<i class="ph"></i>';
+ else {
+ done++;
+ const k = Math.ceil(clamp01((t - F.on) / 0.32) * [...F.value].length);
+ h = valueHTML(F.value, k);
+ }
+ const fl = t >= F.on ? Math.exp(-(t - F.on) / 0.45) : 0;
+ const key = h + Math.round(fl * 20);
+ if (key !== rowShown[i]) {
+ rowShown[i] = key;
+ rows[i].classList.toggle('on', t >= F.on);
+ rows[i].querySelector('.d-v').innerHTML = h;
+ rows[i].style.background = fl > 0.03 ? `rgba(255,45,61,${(0.4 * fl).toFixed(2)})` : '';
+ }
+ });
+ const fin = t >= tDone;
+ const stTxt = fin ? 'PROFILE COMPLETE' : `${Math.floor(t * 2.5) % 2 ? '○' : '●'} SEARCHING · ${done}/${nF}`;
+ if (stEl.textContent !== stTxt) stEl.textContent = stTxt;
+ stEl.classList.toggle('done', fin);
+ dos.classList.toggle('done', fin);
+ ring.style.setProperty('--p', (done / nF).toFixed(3));
+ const eo = easeOutCubic((t - tDone - 0.35) / 0.5);
+ endEl.style.opacity = eo.toFixed(3);
+ endEl.style.transform = `translateY(${((1 - eo) * 24).toFixed(1)}px)`;
+
+ let agents = 0;
+ for (const A of ag) if (A.born <= t) agents++;
+ cA.textContent = fmt(agents);
+ cP.textContent = `${countLE(opens, t)}/${pagesCfg.length}`;
+ cW.textContent = fmt(countLE(firsts, t));
+ return {};
+ },
+ };
+});
diff --git a/sims/dossier/sites.js b/sims/dossier/sites.js
new file mode 100644
index 0000000..dbe88cc
--- /dev/null
+++ b/sims/dossier/sites.js
@@ -0,0 +1,178 @@
+// Twelve public pages about one made-up person (@nightwren_88), for the
+// osint sim. Every page leaks one detail; the phrase is wrapped in
+// <span class="ev" data-f="KEY"> and KEY matches a field in main.js.
+// No real people, brands or places: names, towns and domains are invented
+// (.example), and phone/email are partly masked like a demo with PII hidden.
+// Grid order is row-major on a 4x3 wall; the swarm starts on index 5.
+
+const P = (s) => `<p>${s}</p>`;
+const img = (h, a, b, extra = '') => `<div class="s-img" style="height:${h}px;background:linear-gradient(135deg,${a},${b})${extra}"></div>`;
+const ev = (k, s) => `<span class="ev" data-f="${k}">${s}</span>`;
+
+const PAGES = [
+ // row 0
+ {url: 'portvalecourier.example/local/harbour-10k-results', theme: 'light', html: `
+<div class="s-news">
+ <div class="nw-mast">The Portvale Courier</div>
+ <div class="nw-nav"><span>Local</span><span>Sport</span><span>Business</span><span>Weather</span><span>Events</span><span>Opinion</span></div>
+ <div class="nw-grid">
+ <div class="nw-main">
+ <div class="nw-kick">Local sport</div>
+ <h1>Record turnout at the Harbour 10K</h1>
+ <div class="nw-dek">More than 900 runners lined up on Sunday morning. Full results for every finisher are below.</div>
+ <div class="nw-by">By the Courier sport desk · 3 min read</div>
+ ${img(250, '#c9d6e2', '#7d93a8')}
+ <div class="nw-cap">Runners pass the harbour wall at the 6 km mark.</div>
+ ${P('The course ran along the harbour, up through the old town and back down to the finish by the ferry terminal. Conditions were cool and dry.')}
+ <table class="nw-res"><tr><th>#</th><th>Name</th><th>Club</th><th>Time</th></tr>
+ ${[['212', 'T. Okafor', 'Harbour Harriers', '46:58'], ['213', ev('name', 'Wren Halloway'), 'unattached', '47:12'], ['214', 'M. Lindqvist', 'Old Town RC', '47:15'], ['215', 'S. Petrova', 'unattached', '47:19'], ['216', 'D. Achebe', 'Harbour Harriers', '47:22'], ['217', 'K. Moreau', 'Portvale Tri', '47:30'], ['218', 'J. Brandt', 'unattached', '47:41'], ['219', 'A. Novak', 'Old Town RC', '47:44']].map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join('')}</tr>`).join('')}</table>
+ ${P('Organisers thanked the volunteers who handed out water at three stations. Next year the race moves to the first Sunday of the month.')}
+ </div>
+ <div class="nw-side"><h3>Most read</h3>${['Ferry timetable changes from Monday', 'New bakery opens on the harbour', 'Old town parking: what changes', 'Dog park gets new lights', 'Weekend weather: cool and dry'].map((s, i) => `<div class="nw-mr"><b>${i + 1}</b><span>${s}</span></div>`).join('')}</div>
+ </div>
+</div>`},
+ {url: 'snapshots.example/nightwren_88', theme: 'light', html: `
+<div class="s-pics">
+ <div class="pc-top"><b>snapshots</b><span>Explore</span><span>Upload</span><span class="pc-me">nightwren_88</span></div>
+ <div class="pc-head"><div class="pc-av"></div><div><div class="pc-name">nightwren_88</div><div class="pc-meta">214 photos · 388 followers · 401 following</div><div class="pc-bio">little moments. mostly the dog</div></div></div>
+ <div class="pc-grid">${[
+ ['#f2c6a0', '#c0703a', 'sunday at the harbour'],
+ ['#d7e3c4', '#6f8f4a', 'new running shoes, same old route'],
+ ['#f0d8e0', '#b06080', `birthday dinner, ${ev('bday', '14 March')}. another year older`],
+ ['#cfe0f0', '#4a78a8', 'ferry back from work'],
+ ['#efe1c2', '#a8823a', 'the loudest beagle on the block'],
+ ['#e2d6f0', '#7a5aa8', 'gym selfie, 6:40 am, regret'],
+ ['#d0ece8', '#3a8f86', 'parcel mountain at the depot'],
+ ['#f5d5c5', '#c4583a', 'race day, 47:12, new best'],
+ ['#dde3ea', '#6a7a8c', 'first night in the new flat'],
+ ].map(([a, b, c]) => `<div class="pc-c">${img(270, a, b, ';border-radius:10px')}<div class="pc-cap">${c}</div></div>`).join('')}</div>
+</div>`},
+ {url: 'codehost.example/nightwren', theme: 'dark', html: `
+<div class="s-repo">
+ <div class="rp-top"><b>⌂</b><span><b>nightwren</b></span><em>Profile</em></div>
+ <div class="rp-tabs"><b>Overview</b><span>Repositories 6</span><span>Projects</span><span>Stars 41</span></div>
+ <div class="rp-prof"><div class="rp-av"></div><div><div class="rp-pn">nightwren</div><div class="rp-pb">ships parcels by day, scripts by night</div><div class="rp-pl">Portvale · joined 2019</div></div></div>
+ <div class="rp-files">
+ <div class="rp-h"><b>parcel-route-helper</b> <i>· last commit 2 days ago</i></div>
+ ${[['a91f2c0', 'fix: depot opens at 5:30 not 6'], ['7c03e1d', 'add tue/thu gym reminder lol'], ['e55b9a4', 'route: skip harbour bridge on sundays'], ['0b6d2f8', 'readme: how to run']].map(([h, m]) => `<div class="rp-f"><span class="rp-fn">● ${h}</span><span class="rp-fm">${m}</span><span class="rp-ft">2d</span></div>`).join('')}
+ </div>
+ <div class="rp-readme"><div class="rp-rh">commit a91f2c0</div><pre>commit a91f2c0e7d
+Author: nightwren &lt;${ev('email', '[email protected]')}&gt;
+Date: Thu Oct 1 06:12:44
+
+ fix: depot opens at 5:30 not 6</pre>${P('A tiny helper that plans the morning parcel route around the harbour and the old town. Nothing fancy, it just saves me ten minutes a day.')}</div>
+</div>`},
+ {url: 'board.portvale.example/t/new-here-running-group', theme: 'light', html: `
+<div class="s-forum">
+ <div class="fm-top"><b>▲ portvale board</b><span>local | events | for sale | jobs | ask</span><span class="fm-login">login</span></div>
+ <div class="fm-thread">
+ <div class="fm-title">new here, looking for a running group</div>
+ <div class="fm-m">posted by nightwren_88 · 3 weeks ago · 14 replies</div>
+ <div class="fm-body">${P(`hi all, ${ev('city', 'just moved to Portvale')} for work. I run most mornings before my shift and I'd love some company on weekends. 5k to 10k, not fast. also, any vets you'd recommend for a beagle?`)}</div>
+ ${[['harbour_harriers', 'Saturdays 8am from the ferry terminal. All paces, coffee after.'], ['oldtown_jo', 'Welcome! The vet on Mill Lane is great with loud dogs.'], ['nightwren_88', 'perfect, see you saturday. the dog will judge everyone'], ['k_moreau', 'Tri club does Tuesday track sessions if you want speed work.'], ['pv_dad', 'Watch the cobbles in the old town when it rains.']].map(([u, c]) => `<div class="fm-c"><div class="fm-m">${u} · 3 weeks ago</div>${P(c)}</div>`).join('')}
+ </div>
+</div>`},
+
+ // row 1
+ {url: 'worknet.example/in/wren-h', theme: 'light', html: `
+<div class="s-work">
+ <div class="wk2-top"><b>worknet</b><div class="wk2-search">Search</div><span>Jobs</span><span>Messages</span></div>
+ <div class="wk2-card">${img(150, '#b8c9dc', '#5d7896')}<div class="wk2-av"></div>
+ <div class="wk2-name">Wren H.</div>
+ <div class="wk2-head">${ev('work', 'Dispatcher at Kestrel Cargo')}</div>
+ <div class="wk2-loc">Portvale area · 312 connections</div>
+ <div class="wk2-btns"><span class="on">Connect</span><span>Message</span></div>
+ </div>
+ <div class="wk2-sec"><h2>About</h2>${P('I keep parcels moving. Morning shifts, route planning, and too many spreadsheets. Previously in warehouse operations.')}</div>
+ <div class="wk2-sec"><h2>Experience</h2>${[['Dispatcher', 'Kestrel Cargo · Full-time', '2024 – present · Portvale'], ['Warehouse lead', 'a regional logistics firm', '2020 – 2024'], ['Picker', 'a regional logistics firm', '2018 – 2020']].map(([a, b, c]) => `<div class="wk2-x"><div class="wk2-xl"></div><div><b>${a}</b><div>${b}</div><div class="wk2-d">${c}</div></div></div>`).join('')}</div>
+ <div class="wk2-sec"><h2>Skills</h2>${P('Route planning · Scheduling · Spreadsheets · Forklift licence')}</div>
+</div>`},
+ {url: 'chirp.example/nightwren_88', theme: 'dark', html: `
+<div class="s-social s-prof">
+ ${img(190, '#1b2a44', '#2d5a6a', ';border-radius:0')}
+ <div class="pf-av"></div>
+ <div class="pf-name">wren</div>
+ <div class="pf-handle">@nightwren_88</div>
+ <div class="pf-bio">6am gym club. ships parcels for a living. dog parent to ${ev('pet', 'Biscuit, the loudest beagle')} on the block</div>
+ <div class="pf-meta">Joined March 2019 · <b>412</b> Following · <b>530</b> Followers</div>
+ <div class="so-top"><span class="on">Posts</span><span>Replies</span><span>Media</span><span>Likes</span></div>
+ ${[
+ ['2h', 'biscuit stole my sandwich again. he shows no remorse', ['4', '1', '38', '610']],
+ ['1d', 'leg day. tue/thu or nothing', ['2', '0', '21', '402']],
+ ['2d', 'another 5k before the shift. the harbour at 6am is unreal', ['6', '3', '57', '1.1K']],
+ ['4d', 'new flat, old problem: the dog has opinions about the neighbours', ['9', '2', '74', '1.4K']],
+ ['1w', 'selling my old road bike if anyone local wants it', ['3', '1', '12', '380']],
+ ].map(([ago, text, s]) => `<div class="so-post"><div class="so-av" style="background:#3d7bff"></div><div class="so-b"><div class="so-h"><b>wren</b><span>@nightwren_88 · ${ago}</span></div><div class="so-t">${text}</div><div class="so-s"><span>↩ ${s[0]}</span><span>⟲ ${s[1]}</span><span>♡ ${s[2]}</span><span>▥ ${s[3]}</span></div></div></div>`).join('')}
+</div>`},
+ {url: 'seek.example/search?q=nightwren_88', theme: 'light', html: `
+<div class="s-search">
+ <div class="sr-top"><span class="sr-logo">seek</span><div class="sr-box">nightwren_88<span>⌕</span></div></div>
+ <div class="sr-tabs"><b>All</b><span>Images</span><span>News</span><span>Videos</span><span>Maps</span><span>More</span></div>
+ <div class="sr-count">About 1,240 results (0.27 seconds)</div>
+ ${[
+ ['chirp.example › nightwren_88', 'wren (@nightwren_88) on chirp', '6am gym club. ships parcels for a living. dog parent to Biscuit, the loudest beagle on the block.'],
+ ['namecheck.example', 'nightwren_88: username found on 7 sites', `Same avatar and bio on 7 sites. Also active as ${ev('alias', 'wren.h and n_wren')}.`],
+ ['snapshots.example › nightwren_88', 'nightwren_88 · 214 photos', 'little moments. mostly the dog. sunday at the harbour, race day, new flat.'],
+ ['board.portvale.example', 'new here, looking for a running group', 'posted by nightwren_88: hi all, just moved to Portvale for work. I run most mornings before my shift…'],
+ ['codehost.example › nightwren', 'nightwren · 6 repositories', 'ships parcels by day, scripts by night. parcel-route-helper, gym-timer, dog-feeder.'],
+ ['runloop.example › athlete › n_wren', 'n_wren · 212 runs', 'Morning Run · 5.2 km · 26:40. Most runs between 05:50 and 06:20.'],
+ ].map(([site, title, snip]) => `<div class="sr-r"><div class="sr-site"><i></i>${site}</div><a>${title}</a><p>${snip}</p></div>`).join('')}
+</div>`},
+ {url: 'localrate.example/biz/ironyard-gym-portvale', theme: 'light', html: `
+<div class="s-rev">
+ <div class="rv-top"><b>★ localrate</b><div class="rv-search">gyms near Portvale</div></div>
+ ${img(200, '#3a3f4a', '#8a919c')}
+ <h1>IronYard Gym</h1>
+ <div class="rv-st"><span class="rv-stars">★★★★☆</span> 4.4 · 186 reviews · Gym · Open 05:30–22:00</div>
+ <div class="rv-tags"><span>Free weights</span><span>Early opening</span><span>Showers</span><span>Parking</span></div>
+ ${[
+ ['nightwren_88', '★★★★★', `${ev('gym', 'Tue/Thu at 6:40')} for two years now. Never crowded at that hour, the staff know my name and my water bottle.`],
+ ['harbour_jo', '★★★★☆', 'Good equipment, small changing rooms. Busy after 17:00.'],
+ ['k_moreau', '★★★★★', 'Best early opening in town. Squat racks are always free before 7.'],
+ ['pv_dad', '★★★☆☆', 'Fine gym, but the music is loud and the parking is tight.'],
+ ['m_lindqvist', '★★★★☆', 'Friendly, clean, fair price for a monthly pass.'],
+ ].map(([u, s, t]) => `<div class="rv-r"><div class="rv-u"><i></i><b>${u}</b><span>${s}</span></div>${P(t)}</div>`).join('')}
+</div>`},
+
+ // row 2
+ {url: 'runloop.example/athlete/n_wren', theme: 'dark', html: `
+<div class="s-run">
+ <div class="rn-top"><b>runloop</b><span>Dashboard</span><span>Explore</span><span class="rn-me">n_wren</span></div>
+ <div class="rn-head"><div class="rn-av"></div><div><div class="rn-n">n_wren</div><div class="rn-m">212 runs · 1,064 km this year</div></div></div>
+ <div class="rn-map"><svg viewBox="0 0 1000 420" preserveAspectRatio="none">${Array.from({length: 11}, (_, i) => `<line x1="${i * 100}" y1="0" x2="${i * 100 - 60}" y2="420" stroke="#1f2630" stroke-width="10"/>`).join('')}${Array.from({length: 6}, (_, i) => `<line x1="0" y1="${i * 84}" x2="1000" y2="${i * 84 + 30}" stroke="#1f2630" stroke-width="8"/>`).join('')}<path d="M 220 300 C 300 180, 430 120, 560 150 S 800 260, 760 330 S 520 380, 400 340 S 240 330, 220 300" fill="none" stroke="#ff6a3d" stroke-width="9" stroke-linejoin="round"/><circle cx="220" cy="300" r="15" fill="#4dff9a" stroke="#0f1014" stroke-width="5"/></svg></div>
+ <div class="rn-act"><b>Morning Run</b><div class="rn-when">Today at 05:58 · 5.2 km · 26:40 · 5:08 /km</div>${P(`Same loop as always: ${ev('home', 'starts and ends on Alder St')}, out along the harbour and back before the shift.`)}</div>
+ ${[['Morning Run', 'Yesterday at 06:04 · 5.1 km'], ['Morning Run', 'Tue at 05:52 · 5.2 km'], ['Long Run', 'Sun at 08:01 · 10.4 km'], ['Morning Run', 'Fri at 05:55 · 5.2 km']].map(([a, b]) => `<div class="rn-row"><b>${a}</b><span>${b}</span></div>`).join('')}
+</div>`},
+ {url: 'swapsy.example/item/road-bike-54cm', theme: 'light', html: `
+<div class="s-shop">
+ <div class="sh-top"><b>swapsy</b><div class="sh-search">Search Portvale</div><span>Sell</span><span>Messages</span></div>
+ <div class="sh-crumbs">Portvale › Sports › Bikes</div>
+ <div class="sh-grid">
+ <div>${img(420, '#e3e8ee', '#8b9bb0', ';border-radius:12px')}<div class="sh-th">${[0, 1, 2, 3].map(() => img(80, '#e8ecf0', '#b0bccb', ';border-radius:8px')).join('')}</div></div>
+ <div class="sh-info"><h1>Road bike, 54 cm, barely used</h1><div class="sh-pr">$240</div><div class="sh-ship">Pickup only · listed 6 days ago</div><div class="sh-btn">Message seller</div>
+ ${P('Bought it for the commute, ended up running instead. New tyres, serviced in spring. Pickup near Alder St, evenings only.')}
+ ${P(`Call or text: ${ev('phone', '••• ••• 41 07')}`)}
+ <div class="sh-seller"><b>wren h.</b> · on swapsy since 2021 · 9 sales · replies within an hour</div></div>
+ </div>
+ <h2>More from this seller</h2>
+ <div class="sh-th">${['#efe1c2', '#d0ece8', '#f0d8e0', '#dde3ea'].map((c) => img(110, c, '#9aa4b0', ';border-radius:8px')).join('')}</div>
+</div>`},
+ {url: 'vidtube.example/watch/car-tour', theme: 'dark', html: `
+<div class="s-video">
+ <div class="vd-top"><b>▶ vidtube</b><div class="vd-search">Search</div></div>
+ ${img(470, '#2a2f38', '#6a7480', ';border-radius:16px')}
+ <div class="vd-title">first car tour!! (it's not fancy)</div>
+ <div class="vd-ch"><i></i><b>n_wren</b><span>48 subscribers</span><em>Subscribe</em></div>
+ <div class="vd-desc"><b>1,204 views · 5 months ago</b>${P(`a quick tour of my ${ev('car', 'grey hatchback, plate ends 4K7')}. it smells like dog. it has never been washed. I love it`)}</div>
+ <div class="vd-com"><b>23 comments</b>${[['harbour_jo', 'saw this parked by the harbour lol'], ['pv_dad', 'the dog in the back seat is the real star'], ['k_moreau', 'honest review, 10/10']].map(([u, c]) => `<div class="vd-cm"><i></i><div><b>@${u}</b>${P(c)}</div></div>`).join('')}</div>
+</div>`},
+ {url: 'leakcheck.example/?q=w.halloway%40mail.example', theme: 'dark', html: `
+<div class="s-leak">
+ <div class="lk-top"><b>leakcheck</b><span>Check</span><span>Notify me</span><span>About</span></div>
+ <div class="lk-hero"><div class="lk-q">[email protected]</div><div class="lk-big">Oh no: ${ev('leaks', 'found in 3 data breaches')}</div>${P('This address appeared in data leaked from the sites below. Passwords from these leaks may be reused elsewhere.')}</div>
+ ${[['a fitness app', '2023', 'email, name, date of birth, workout history'], ['an online shop', '2024', 'email, phone, delivery address'], ['a local forum', '2021', 'email, username, password hash']].map(([a, y, d]) => `<div class="lk-r"><div class="lk-ic"></div><div><b>${a} · ${y}</b>${P(`Compromised data: ${d}`)}</div></div>`).join('')}
+ ${P('Change these passwords, turn on two-factor sign-in, and use a password manager so one leak does not unlock the rest.')}
+</div>`},
+];
+
+export default PAGES;
diff --git a/sims/dossier/style.css b/sims/dossier/style.css
new file mode 100644
index 0000000..a00ef85
--- /dev/null
+++ b/sims/dossier/style.css
@@ -0,0 +1,269 @@
+:root { --bg: #060709; }
+#stage { position: absolute; top: 0; width: 1080px; overflow: hidden; transform-origin: 0 0; background: #060709; }
+#stage #gl { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 5; }
+.world { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
+.page { position: absolute; width: 1080px; overflow: hidden; background: #0d0e12; border: 1px solid #22242c; border-radius: 16px; color: #d6d8df; font-family: Inter, sans-serif; }
+.page .bar { height: 64px; display: flex; align-items: center; gap: 22px; padding: 0 28px; border-bottom: 1px solid #22242c; background: #111218; font: 400 20px 'JetBrains Mono', monospace; color: #8d909c; }
+.page .dots { display: flex; gap: 9px; }
+.page .dots b { width: 13px; height: 13px; border-radius: 50%; background: #2a2c35; }
+.page .crumbs i { font-style: normal; color: #4a4d58; margin: 0 8px; }
+.page .crumbs { white-space: nowrap; }
+.page .content { padding: 26px 40px 0; }
+.page pre.code { margin: 0; font: 400 21px/1.62 'JetBrains Mono', monospace; color: #c9cbd4; white-space: pre; }
+.page pre.code .ln { display: inline-block; width: 46px; color: #3d404b; text-align: right; margin-right: 22px; }
+.page .kw { color: #b79cff; } .page .str { color: #8fe3b0; } .page .com { color: #5f6372; font-style: italic; }
+.page .md h1 { font: 800 46px/1.15 Inter; color: #fff; margin: 10px 0 18px; letter-spacing: -0.02em; }
+.page .md h2 { font: 700 32px/1.2 Inter; color: #fff; margin: 22px 0 12px; padding-bottom: 8px; border-bottom: 1px solid #22242c; }
+.page .md p { font-size: 24px; line-height: 1.55; margin: 0 0 6px; }
+.page .md li { font-size: 24px; line-height: 1.55; margin: 0 0 4px 26px; list-style: disc; display: list-item; }
+.page .md b { color: #fff; }
+.page .md code { font-family: 'JetBrains Mono', monospace; font-size: 0.86em; color: #c9cbd4; background: #171820; padding: 1px 6px; border-radius: 5px; }
+.page .md pre.mdc { font: 400 20px/1.55 'JetBrains Mono', monospace; background: #13141a; border: 1px solid #22242c; border-radius: 10px; padding: 12px 18px; margin: 6px 0 12px; white-space: pre; color: #c9cbd4; overflow: hidden; }
+.page .md .gapl { height: 12px; }
+.w { border-radius: 4px; }
+
+.counters { position: absolute; left: 28px; top: 28px; z-index: 6; display: flex; align-items: flex-end; gap: 34px; padding: 20px 28px 22px; font-family: 'JetBrains Mono', monospace; background: #0b0c10; border: 1px solid #2a2c35; border-radius: 18px; box-shadow: 0 12px 40px rgba(0,0,0,0.45); }
+.counters .c { display: flex; flex-direction: column; gap: 4px; }
+.counters span { font: 600 19px 'JetBrains Mono', monospace; letter-spacing: 0.14em; text-transform: uppercase; color: #8d909c; }
+.counters b { font: 700 40px 'JetBrains Mono', monospace; color: #fff; font-variant-numeric: tabular-nums; }
+.counters .big b { font-size: 76px; line-height: 0.95; color: #ff3db4; }
+.wm { position: absolute; right: 26px; bottom: 22px; z-index: 7; font: 400 20px 'JetBrains Mono', monospace; color: rgba(255,255,255,0.45); }
+
+/* generic web pages (sites.js) */
+.page.site { border-color: #2a2c35; }
+.page.site.light { background: #fff; color: #202124; }
+.page.site.dark { background: #0f1014; color: #e3e4e8; }
+.page.site .content { padding: 0; }
+.chrome { height: 60px; display: flex; align-items: center; gap: 20px; padding: 0 22px; background: #1b1c22; border-bottom: 1px solid #2a2c35; font: 400 19px Inter, sans-serif; color: #9a9da8; }
+.chrome .dots { display: flex; gap: 9px; }
+.chrome .dots b { width: 13px; height: 13px; border-radius: 50%; background: #3a3c46; }
+.chrome .url { flex: 1; background: #26272f; border-radius: 18px; padding: 8px 18px; white-space: nowrap; overflow: hidden; color: #c9cbd4; }
+.chrome .url::before { content: '🔒 '; filter: grayscale(1); opacity: 0.6; }
+.s-img { width: 100%; border-radius: 4px; }
+.site a { color: #1a5fd0; }
+.site.dark a { color: #7aa2ff; }
+.site p { margin: 0 0 14px; }
+
+.s-wiki { padding: 0 44px; font: 400 23px/1.55 'FreeSerif', 'C059', serif; }
+.s-wiki .wk-top { display: flex; align-items: center; justify-content: space-between; height: 76px; border-bottom: 1px solid #c8ccd1; font-family: Inter; }
+.s-wiki .wk-logo { font: 700 26px 'C059', serif; }
+.s-wiki .wk-search { border: 1px solid #a2a9b1; padding: 8px 14px; width: 360px; font: 400 18px Inter; color: #72777d; border-radius: 2px; }
+.s-wiki .wk-tabs { display: flex; gap: 20px; font: 400 18px Inter; padding: 14px 0 8px; color: #1a5fd0; border-bottom: 1px solid #a2a9b1; }
+.s-wiki .wk-tabs b { color: #202122; font-weight: 400; border-bottom: 3px solid #202122; } .s-wiki .wk-tabs i { flex: 1; }
+.s-wiki h1 { font: 400 46px/1.2 'C059', serif; margin: 22px 0 4px; border-bottom: 1px solid #a2a9b1; padding-bottom: 6px; }
+.s-wiki .wk-from { font: 400 17px Inter; color: #54595d; margin-bottom: 16px; }
+.s-wiki h2 { font: 400 32px 'C059', serif; margin: 22px 0 10px; border-bottom: 1px solid #a2a9b1; padding-bottom: 4px; }
+.s-wiki .wk-box { float: right; width: 330px; margin: 0 0 16px 22px; border: 1px solid #a2a9b1; background: #f8f9fa; padding: 8px; font: 400 17px/1.4 Inter; }
+.s-wiki .wk-bt { text-align: center; font-weight: 700; font-size: 20px; padding: 4px 0 8px; background: #e2d8c2; margin: -8px -8px 8px; padding-top: 8px; }
+.s-wiki .wk-bt2 { text-align: center; font-weight: 700; background: #e2d8c2; margin: 8px -8px; padding: 4px; }
+.s-wiki .wk-bc { text-align: center; color: #54595d; font-size: 15px; padding: 6px 0; }
+.s-wiki table { width: 100%; font-size: 17px; } .s-wiki td { padding: 2px 4px; }
+.s-wiki .wk-refs { font: 400 18px/1.5 Inter; color: #202122; padding-left: 30px; }
+
+.s-search { padding: 0 52px; font-family: Inter, sans-serif; }
+.s-search .sr-top { display: flex; align-items: center; gap: 28px; height: 104px; }
+.s-search .sr-logo { font: 700 38px Inter; color: #3d7bff; letter-spacing: -0.03em; }
+.s-search .sr-box { flex: 1; border: 1px solid #dfe1e5; border-radius: 28px; padding: 14px 24px; font-size: 21px; box-shadow: 0 1px 6px rgba(32,33,36,0.18); display: flex; justify-content: space-between; }
+.s-search .sr-tabs { display: flex; gap: 26px; font-size: 18px; color: #5f6368; border-bottom: 1px solid #ebebeb; padding-bottom: 10px; margin-left: 4px; }
+.s-search .sr-tabs b { color: #1a5fd0; border-bottom: 3px solid #1a5fd0; padding-bottom: 8px; font-weight: 500; }
+.s-search .sr-count { font-size: 16px; color: #70757a; margin: 14px 0 10px; }
+.s-search .sr-r { margin: 0 0 30px; max-width: 900px; }
+.s-search .sr-site { font-size: 17px; color: #202124; display: flex; align-items: center; gap: 10px; } .s-search .sr-site i { width: 26px; height: 26px; border-radius: 50%; background: #e8eaed; }
+.s-search .sr-r a { display: block; font-size: 25px; color: #1a0dab; margin: 6px 0 4px; }
+.s-search .sr-r p { font-size: 19px; line-height: 1.55; color: #4d5156; margin: 0; }
+
+.s-news { padding: 0 44px; font-family: 'C059', serif; }
+.s-news .nw-mast { text-align: center; font: 700 64px 'C059', serif; padding: 26px 0 10px; border-bottom: 1px solid #222; }
+.s-news .nw-nav { display: flex; justify-content: center; gap: 28px; font: 600 17px Inter; padding: 12px 0; border-bottom: 3px double #222; text-transform: uppercase; letter-spacing: 0.06em; }
+.s-news .nw-grid { display: grid; grid-template-columns: 1fr 270px; gap: 36px; padding-top: 22px; }
+.s-news .nw-kick { font: 700 16px Inter; color: #c0392b; text-transform: uppercase; letter-spacing: 0.1em; }
+.s-news h1 { font: 700 50px/1.08 'C059', serif; margin: 8px 0 12px; }
+.s-news .nw-dek { font: 400 23px/1.4 'C059', serif; color: #444; margin-bottom: 10px; }
+.s-news .nw-by { font: 600 16px Inter; color: #666; margin-bottom: 14px; }
+.s-news .nw-cap { font: 400 14px Inter; color: #777; margin: 6px 0 16px; }
+.s-news p { font: 400 21px/1.6 'C059', serif; }
+.s-news .nw-side h3 { font: 700 18px Inter; text-transform: uppercase; letter-spacing: 0.08em; border-top: 3px solid #222; padding-top: 10px; }
+.s-news .nw-mr { display: flex; gap: 12px; padding: 12px 0; border-bottom: 1px solid #ddd; font: 600 19px/1.3 'C059', serif; } .s-news .nw-mr b { font: 700 28px Inter; color: #c0392b; }
+
+.s-forum { font: 400 20px Verdana, 'DejaVu Sans', sans-serif; background: #f6f6ef; min-height: 100%; }
+.s-forum .fm-top { background: #2a8c82; color: #fff; display: flex; gap: 16px; align-items: center; padding: 8px 14px; font-size: 18px; }
+.s-forum .fm-top b { font-size: 20px; } .s-forum .fm-login { margin-left: auto; }
+.s-forum .fm-it { display: flex; gap: 10px; padding: 9px 14px 3px; }
+.s-forum .fm-n { color: #828282; width: 34px; text-align: right; }
+.s-forum .fm-t { color: #000; } .s-forum .fm-t i { color: #828282; font-size: 16px; font-style: normal; }
+.s-forum .fm-m { font-size: 15px; color: #828282; margin-top: 3px; }
+
+.s-social { font-family: Inter, sans-serif; }
+.s-social .so-top { display: flex; gap: 40px; padding: 18px 30px 0; border-bottom: 1px solid #2f3336; font-size: 20px; color: #71767b; }
+.s-social .so-top b { color: #e7e9ea; font-size: 26px; margin-right: auto; } .s-social .so-top span { padding-bottom: 14px; } .s-social .so-top .on { color: #e7e9ea; border-bottom: 4px solid #1d9bf0; }
+.s-social .so-post { display: flex; gap: 16px; padding: 22px 30px; border-bottom: 1px solid #2f3336; }
+.s-social .so-av { width: 58px; height: 58px; border-radius: 50%; flex: none; }
+.s-social .so-b { flex: 1; }
+.s-social .so-h { font-size: 20px; } .s-social .so-h span { color: #71767b; margin-left: 8px; }
+.s-social .so-t { font-size: 23px; line-height: 1.45; margin: 6px 0; }
+.s-social .so-s { display: flex; justify-content: space-between; color: #71767b; font-size: 18px; max-width: 640px; margin-top: 8px; }
+
+.s-video { font-family: Inter, sans-serif; padding: 0 28px; }
+.s-video .vd-top { display: flex; align-items: center; gap: 30px; height: 84px; } .s-video .vd-top b { font-size: 28px; }
+.s-video .vd-search { flex: 1; border: 1px solid #303030; border-radius: 24px; padding: 10px 20px; color: #888; font-size: 19px; }
+.s-video .vd-chips { display: flex; gap: 12px; margin-bottom: 22px; } .s-video .vd-chips span { background: #272727; padding: 8px 16px; border-radius: 10px; font-size: 18px; } .s-video .vd-chips .on { background: #f1f1f1; color: #0f0f0f; }
+.s-video .vd-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 26px 22px; }
+.s-video .vd-t { font: 600 21px/1.3 Inter; margin: 12px 0 6px; } .s-video .vd-m { font-size: 17px; color: #aaa; line-height: 1.4; }
+
+.s-repo { font-family: Inter, sans-serif; padding: 0 34px; font-size: 19px; }
+.s-repo .rp-top { display: flex; gap: 16px; align-items: center; height: 74px; font-size: 24px; } .s-repo .rp-top em { font-style: normal; font-size: 15px; border: 1px solid #3d444d; border-radius: 12px; padding: 2px 10px; color: #9198a1; }
+.s-repo .rp-tabs { display: flex; gap: 26px; border-bottom: 1px solid #3d444d; padding-bottom: 12px; color: #9198a1; } .s-repo .rp-tabs b { color: #f0f6fc; border-bottom: 2px solid #f78166; padding-bottom: 10px; }
+.s-repo .rp-bar { display: flex; gap: 18px; align-items: center; margin: 20px 0 14px; color: #9198a1; } .s-repo .rp-br { background: #212830; border: 1px solid #3d444d; padding: 6px 12px; border-radius: 6px; color: #f0f6fc; } .s-repo .rp-go { margin-left: auto; background: #238636; color: #fff; padding: 7px 14px; border-radius: 6px; font-weight: 600; }
+.s-repo .rp-files { border: 1px solid #3d444d; border-radius: 8px; overflow: hidden; }
+.s-repo .rp-h { background: #151b23; padding: 12px 16px; border-bottom: 1px solid #3d444d; } .s-repo .rp-h i { color: #9198a1; font-style: normal; }
+.s-repo .rp-f { display: grid; grid-template-columns: 280px 1fr 70px; padding: 10px 16px; border-bottom: 1px solid #262c36; } .s-repo .rp-fm, .s-repo .rp-ft { color: #9198a1; } .s-repo .rp-ft { text-align: right; }
+.s-repo .rp-readme { border: 1px solid #3d444d; border-radius: 8px; margin-top: 20px; padding: 0 20px 10px; } .s-repo .rp-rh { margin: 0 -20px; padding: 12px 20px; border-bottom: 1px solid #3d444d; font-weight: 600; }
+.s-repo h2 { font-size: 32px; border-bottom: 1px solid #3d444d; padding-bottom: 8px; } .s-repo p { line-height: 1.55; }
+.s-repo pre { background: #151b23; border-radius: 6px; padding: 14px; font: 400 17px/1.6 'JetBrains Mono'; white-space: pre; overflow: hidden; }
+
+.s-shop { font-family: Inter, sans-serif; padding: 0 34px; font-size: 19px; }
+.s-shop .sh-top { display: flex; align-items: center; gap: 24px; height: 78px; margin: 0 -34px; padding: 0 34px; background: #131921; color: #fff; } .s-shop .sh-top b { font-size: 28px; }
+.s-shop .sh-search { flex: 1; background: #fff; color: #888; border-radius: 6px; padding: 10px 16px; }
+.s-shop .sh-crumbs { font-size: 16px; color: #565959; margin: 16px 0; }
+.s-shop .sh-grid { display: grid; grid-template-columns: 470px 1fr; gap: 30px; } .s-shop .sh-th { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-top: 10px; }
+.s-shop h1 { font: 500 32px/1.25 Inter; margin: 0 0 10px; } .s-shop .sh-st { color: #de7921; } .s-shop .sh-pr { font: 500 44px Inter; margin: 14px 0 6px; }
+.s-shop .sh-ship { color: #067d62; margin-bottom: 16px; } .s-shop .sh-btn, .s-shop .sh-btn2 { background: #ffd814; border-radius: 22px; text-align: center; padding: 12px; margin-bottom: 10px; } .s-shop .sh-btn2 { background: #ffa41c; }
+.s-shop ul { padding-left: 22px; line-height: 1.6; } .s-shop h2 { font-size: 28px; margin: 24px 0 10px; } .s-shop .sh-rev { border-top: 1px solid #ddd; padding: 12px 0 0; } .s-shop .sh-rev b { color: #c45500; }
+
+.s-mail { font-family: Inter, sans-serif; font-size: 18px; }
+.s-mail .ml-top { display: flex; align-items: center; gap: 40px; height: 78px; padding: 0 26px; } .s-mail .ml-top b { font-size: 26px; color: #c5221f; }
+.s-mail .ml-search { flex: 1; background: #eaf1fb; border-radius: 24px; padding: 12px 22px; color: #5f6368; }
+.s-mail .ml-grid { display: grid; grid-template-columns: 200px 1fr; }
+.s-mail .ml-side div { padding: 9px 20px; border-radius: 0 18px 18px 0; color: #202124; } .s-mail .ml-side .on { background: #d3e3fd; font-weight: 700; }
+.s-mail .ml-compose { background: #c2e7ff; border-radius: 16px !important; margin: 0 10px 14px; padding: 16px 20px !important; font-weight: 600; }
+.s-mail .ml-r { display: grid; grid-template-columns: 170px 1fr 70px; gap: 12px; padding: 13px 18px; border-bottom: 1px solid #eceff1; color: #5f6368; white-space: nowrap; overflow: hidden; }
+.s-mail .ml-r.un { background: #fff; color: #202124; } .s-mail .ml-r:not(.un) { background: #f2f6fc; } .s-mail .ml-s { overflow: hidden; text-overflow: ellipsis; } .s-mail .ml-r.un .ml-f { font-weight: 700; }
+
+.s-qa { font-family: Inter, sans-serif; padding: 0 40px; font-size: 20px; }
+.s-qa .qa-top { display: flex; align-items: center; gap: 30px; height: 70px; border-top: 4px solid #f48024; margin: 0 -40px; padding: 0 40px; box-shadow: 0 1px 3px rgba(0,0,0,0.12); } .s-qa .qa-top b { font-size: 24px; }
+.s-qa .qa-search { flex: 1; border: 1px solid #babfc4; border-radius: 6px; padding: 8px 14px; color: #888; }
+.s-qa h1 { font: 400 32px/1.3 Inter; margin: 22px 0 8px; } .s-qa .qa-meta { font-size: 16px; color: #6a737c; border-bottom: 1px solid #e3e6e8; padding-bottom: 14px; }
+.s-qa .qa-q { display: flex; gap: 22px; padding: 18px 0; line-height: 1.55; } .s-qa .qa-v { display: flex; flex-direction: column; align-items: center; color: #babfc4; font-size: 26px; min-width: 50px; } .s-qa .qa-v b { color: #232629; font-size: 24px; } .s-qa .qa-v i { color: #2f6f44; font-style: normal; font-size: 30px; }
+.s-qa pre { background: #f6f6f6; border-radius: 6px; padding: 14px; font: 400 17px/1.55 'JetBrains Mono'; white-space: pre; }
+.s-qa .qa-tags span { background: #e1ecf4; color: #39739d; padding: 4px 10px; border-radius: 4px; margin-right: 8px; font-size: 16px; } .s-qa h2 { font: 400 26px Inter; }
+
+.s-docs { font-family: Inter, sans-serif; font-size: 19px; }
+.s-docs .dc-top { display: flex; align-items: center; gap: 28px; height: 72px; padding: 0 28px; border-bottom: 1px solid #2a2c35; color: #9a9da8; } .s-docs .dc-top b { color: #fff; font-size: 24px; } .s-docs .dc-search { margin-left: auto; border: 1px solid #2a2c35; border-radius: 8px; padding: 8px 14px; }
+.s-docs .dc-grid { display: grid; grid-template-columns: 230px 1fr; }
+.s-docs .dc-side { border-right: 1px solid #2a2c35; padding: 18px 0; } .s-docs .dc-side div { padding: 7px 26px; color: #9a9da8; } .s-docs .dc-side .on { color: #fff; background: #1d1f27; border-left: 3px solid #4dff9a; }
+.s-docs .dc-main { padding: 22px 34px; line-height: 1.6; } .s-docs .dc-crumb { color: #6b6e7a; font-size: 16px; } .s-docs h1 { font: 700 44px Inter; margin: 8px 0 12px; } .s-docs h2 { font: 700 28px Inter; margin: 26px 0 10px; }
+.s-docs pre { background: #15161c; border: 1px solid #2a2c35; border-radius: 10px; padding: 16px 18px; font: 400 18px/1.6 'JetBrains Mono'; white-space: pre; color: #c9cbd4; }
+.s-docs .k { color: #b79cff; } .s-docs .s { color: #8fe3b0; } .s-docs .n { color: #ffd23d; } .s-docs .f { color: #7aa2ff; }
+.s-docs table { width: 100%; border-collapse: collapse; } .s-docs td { border-bottom: 1px solid #2a2c35; padding: 10px 8px; vertical-align: top; } .s-docs code { font-family: 'JetBrains Mono'; color: #4dff9a; }
+
+.s-sheet { font-family: Inter, sans-serif; font-size: 18px; }
+.s-sheet .st-top { display: flex; gap: 26px; align-items: center; height: 70px; padding: 0 22px; } .s-sheet .st-top b { color: #188038; font-size: 24px; } .s-sheet .st-top span { color: #444; }
+.s-sheet .st-fx { border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; padding: 8px 22px; color: #333; font-family: 'JetBrains Mono'; } .s-sheet .st-fx b { color: #888; margin-right: 18px; }
+.s-sheet table { border-collapse: collapse; width: 100%; } .s-sheet th { background: #f8f9fa; color: #5f6368; font-weight: 500; border: 1px solid #e2e3e3; height: 30px; }
+.s-sheet td { border: 1px solid #e2e3e3; padding: 7px 10px; white-space: nowrap; } .s-sheet td:first-child { background: #f8f9fa; color: #5f6368; text-align: center; width: 44px; }
+.s-sheet .done { color: #188038; } .s-sheet .reading { color: #1a5fd0; } .s-sheet .waiting { color: #b06000; }
+
+/* osint: extra page types (sites.js) */
+.ev { border-radius: 4px; }
+.s-news .nw-res { width: 100%; border-collapse: collapse; font: 400 19px Inter; margin: 4px 0 18px; }
+.s-news .nw-res th { text-align: left; border-bottom: 2px solid #222; padding: 6px 8px; font-weight: 700; }
+.s-news .nw-res td { border-bottom: 1px solid #ddd; padding: 7px 8px; }
+
+.s-pics { font-family: Inter, sans-serif; padding: 0 30px; }
+.s-pics .pc-top { display: flex; gap: 26px; align-items: center; height: 74px; font-size: 19px; color: #555; border-bottom: 1px solid #e6e6e6; margin: 0 -30px; padding: 0 30px; }
+.s-pics .pc-top b { font: 700 28px Inter; color: #111; margin-right: auto; } .s-pics .pc-me { font-weight: 600; color: #111; }
+.s-pics .pc-head { display: flex; gap: 30px; align-items: center; padding: 28px 10px; }
+.s-pics .pc-av { width: 130px; height: 130px; border-radius: 50%; background: linear-gradient(135deg, #efe1c2, #a8823a); flex: none; }
+.s-pics .pc-name { font: 600 30px Inter; } .s-pics .pc-meta { font-size: 19px; color: #555; margin: 6px 0; } .s-pics .pc-bio { font-size: 20px; }
+.s-pics .pc-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
+.s-pics .pc-cap { font-size: 18px; line-height: 1.35; color: #333; margin: 8px 2px 4px; }
+
+.s-repo .rp-prof { display: flex; gap: 26px; align-items: center; margin: 24px 0; }
+.s-repo .rp-av { width: 120px; height: 120px; border-radius: 50%; background: linear-gradient(135deg, #2d5a6a, #19c3ff); flex: none; }
+.s-repo .rp-pn { font: 700 30px Inter; color: #f0f6fc; } .s-repo .rp-pb { font-size: 21px; margin: 6px 0; } .s-repo .rp-pl { color: #9198a1; }
+.s-repo .rp-f { grid-template-columns: 170px 1fr 50px; }
+
+.s-forum .fm-thread { padding: 16px 22px; }
+.s-forum .fm-title { font-size: 28px; color: #000; }
+.s-forum .fm-body { font-size: 21px; line-height: 1.55; padding: 12px 0; border-bottom: 1px solid #ddd; }
+.s-forum .fm-c { padding: 12px 0 0 34px; font-size: 20px; line-height: 1.5; }
+.s-forum .fm-c p { margin: 4px 0 6px; }
+
+.s-work { font-family: Inter, sans-serif; background: #f4f2ee; min-height: 100%; padding: 0 30px 30px; font-size: 19px; }
+.s-work .wk2-top { display: flex; align-items: center; gap: 26px; height: 74px; margin: 0 -30px; padding: 0 30px; background: #fff; border-bottom: 1px solid #ddd; color: #555; }
+.s-work .wk2-top b { font: 700 28px Inter; color: #0a66c2; } .s-work .wk2-search { flex: 1; background: #edf3f8; border-radius: 6px; padding: 9px 16px; }
+.s-work .wk2-card, .s-work .wk2-sec { background: #fff; border-radius: 12px; border: 1px solid #ddd; margin-top: 20px; overflow: hidden; }
+.s-work .wk2-card { padding-bottom: 22px; } .s-work .wk2-card > * { margin-left: 28px; } .s-work .wk2-card > .s-img { margin-left: 0; border-radius: 0; }
+.s-work .wk2-av { width: 150px; height: 150px; border-radius: 50%; border: 5px solid #fff; background: linear-gradient(135deg, #b8c9dc, #3d5a7a); margin-top: -80px; }
+.s-work .wk2-name { font: 700 34px Inter; margin-top: 8px; } .s-work .wk2-head { font-size: 23px; margin: 6px 0; } .s-work .wk2-loc { color: #666; }
+.s-work .wk2-btns { display: flex; gap: 12px; margin-top: 16px; } .s-work .wk2-btns span { border: 1px solid #0a66c2; color: #0a66c2; border-radius: 20px; padding: 8px 22px; font-weight: 600; } .s-work .wk2-btns .on { background: #0a66c2; color: #fff; }
+.s-work .wk2-sec { padding: 4px 28px 14px; line-height: 1.5; } .s-work h2 { font: 700 26px Inter; margin: 18px 0 10px; }
+.s-work .wk2-x { display: flex; gap: 18px; margin-bottom: 16px; } .s-work .wk2-xl { width: 54px; height: 54px; border-radius: 8px; background: #dfe5ec; flex: none; } .s-work .wk2-d { color: #777; font-size: 17px; }
+
+.s-prof .pf-av { width: 150px; height: 150px; border-radius: 50%; border: 6px solid #0f1014; background: linear-gradient(135deg, #3d7bff, #19c3ff); margin: -76px 0 0 30px; }
+.s-prof .pf-name { font: 800 32px Inter; margin: 14px 30px 0; } .s-prof .pf-handle { color: #71767b; font-size: 21px; margin: 2px 30px 14px; }
+.s-prof .pf-bio { font-size: 24px; line-height: 1.45; margin: 0 30px 14px; } .s-prof .pf-meta { color: #71767b; font-size: 19px; margin: 0 30px 18px; } .s-prof .pf-meta b { color: #e7e9ea; }
+.s-prof .so-top { justify-content: space-around; padding-top: 6px; } .s-prof .so-top span { padding: 0 10px 14px; }
+
+.s-rev { font-family: Inter, sans-serif; padding: 0 34px; font-size: 20px; }
+.s-rev .rv-top { display: flex; align-items: center; gap: 24px; height: 76px; margin: 0 -34px 0; padding: 0 34px; background: #d32323; color: #fff; } .s-rev .rv-top b { font-size: 28px; }
+.s-rev .rv-search { flex: 1; background: #fff; color: #888; border-radius: 6px; padding: 10px 16px; }
+.s-rev > .s-img { margin: 0 -34px; width: auto; border-radius: 0; }
+.s-rev h1 { font: 800 40px Inter; margin: 18px 0 6px; } .s-rev .rv-st { color: #555; } .s-rev .rv-stars { color: #d32323; font-size: 24px; }
+.s-rev .rv-tags { display: flex; gap: 10px; margin: 14px 0 6px; } .s-rev .rv-tags span { border: 1px solid #ccc; border-radius: 16px; padding: 4px 14px; font-size: 17px; }
+.s-rev .rv-r { border-top: 1px solid #e6e6e6; padding: 16px 0 4px; line-height: 1.5; } .s-rev .rv-u { display: flex; gap: 12px; align-items: center; } .s-rev .rv-u i { width: 40px; height: 40px; border-radius: 50%; background: #ccd3dc; } .s-rev .rv-u span { color: #d32323; margin-left: auto; }
+.s-rev .rv-r p { margin: 8px 0; }
+
+.s-run { font-family: Inter, sans-serif; font-size: 19px; padding: 0 30px; }
+.s-run .rn-top { display: flex; gap: 26px; align-items: center; height: 72px; margin: 0 -30px; padding: 0 30px; border-bottom: 1px solid #2a2c35; color: #9a9da8; } .s-run .rn-top b { font: 800 28px Inter; color: #ff6a3d; margin-right: auto; } .s-run .rn-me { color: #fff; }
+.s-run .rn-head { display: flex; gap: 22px; align-items: center; padding: 22px 0; } .s-run .rn-av { width: 90px; height: 90px; border-radius: 50%; background: linear-gradient(135deg, #3d7bff, #19c3ff); }
+.s-run .rn-n { font: 700 28px Inter; } .s-run .rn-m { color: #9a9da8; }
+.s-run .rn-map { height: 420px; background: #12161c; border-radius: 14px; overflow: hidden; } .s-run .rn-map svg { width: 100%; height: 100%; }
+.s-run .rn-act { padding: 18px 0 8px; font-size: 21px; line-height: 1.5; } .s-run .rn-act b { font-size: 26px; } .s-run .rn-when { color: #9a9da8; margin: 4px 0 8px; }
+.s-run .rn-row { display: flex; justify-content: space-between; border-top: 1px solid #2a2c35; padding: 14px 0; } .s-run .rn-row span { color: #9a9da8; }
+
+.s-shop .sh-seller { color: #565959; font-size: 17px; border-top: 1px solid #ddd; padding-top: 12px; }
+.s-video > .s-img { margin-bottom: 4px; }
+.s-video .vd-title { font: 700 30px Inter; margin: 16px 0 12px; }
+.s-video .vd-ch { display: flex; align-items: center; gap: 14px; font-size: 19px; } .s-video .vd-ch i { width: 50px; height: 50px; border-radius: 50%; background: #3d7bff; } .s-video .vd-ch span { color: #aaa; } .s-video .vd-ch em { font-style: normal; background: #f1f1f1; color: #0f0f0f; border-radius: 20px; padding: 8px 18px; font-weight: 600; margin-left: 10px; }
+.s-video .vd-desc { background: #272727; border-radius: 12px; padding: 14px 18px; margin: 16px 0; font-size: 20px; line-height: 1.5; } .s-video .vd-desc p { margin: 6px 0 0; }
+.s-video .vd-com { font-size: 19px; } .s-video .vd-cm { display: flex; gap: 14px; margin: 16px 0; } .s-video .vd-cm i { width: 42px; height: 42px; border-radius: 50%; background: #555; flex: none; } .s-video .vd-cm p { margin: 4px 0; }
+
+.s-leak { font-family: Inter, sans-serif; padding: 0 40px; font-size: 20px; line-height: 1.5; }
+.s-leak .lk-top { display: flex; gap: 26px; align-items: center; height: 74px; color: #9a9da8; } .s-leak .lk-top b { font: 800 28px Inter; color: #fff; margin-right: auto; }
+.s-leak .lk-hero { text-align: center; padding: 40px 30px; margin: 10px -40px 26px; background: linear-gradient(180deg, #3a1218, #1a0c10); }
+.s-leak .lk-q { font: 400 24px 'JetBrains Mono'; color: #c9cbd4; background: #0f1014; border: 1px solid #3a3c46; border-radius: 10px; padding: 12px 18px; display: inline-block; }
+.s-leak .lk-big { font: 800 44px Inter; color: #fff; margin: 22px 0 10px; }
+.s-leak .lk-r { display: flex; gap: 20px; border: 1px solid #2a2c35; border-radius: 12px; padding: 16px 20px; margin-bottom: 14px; } .s-leak .lk-ic { width: 50px; height: 50px; border-radius: 10px; background: #2a2c35; flex: none; } .s-leak .lk-r p { margin: 4px 0 0; color: #9a9da8; }
+
+/* dossier card (screen space, docked at the bottom) */
+.dossier { position: absolute; left: 24px; right: 24px; bottom: 24px; z-index: 6; background: #0b0c10; border: 1px solid #2a2c35; border-radius: 20px; box-shadow: 0 -10px 50px rgba(0,0,0,0.5); font-family: Inter, sans-serif; color: #fff; }
+.dossier .d-head { display: flex; align-items: center; justify-content: space-between; height: 72px; padding: 0 26px; border-bottom: 1px solid #22242c; }
+.dossier .d-t span, .dossier .d-foot span { font: 600 17px 'JetBrains Mono', monospace; letter-spacing: 0.14em; color: #8d909c; }
+.dossier .d-t b { font: 700 30px 'JetBrains Mono', monospace; margin-left: 12px; }
+.dossier .d-st { font: 700 19px 'JetBrains Mono', monospace; letter-spacing: 0.1em; color: #19c3ff; text-align: right; width: 330px; }
+.dossier .d-st.done { color: #ff2d3d; }
+.dossier .d-av { position: absolute; left: 50%; top: -52px; width: 104px; height: 104px; margin-left: -52px; border-radius: 50%; background: #14161c; border: 1px solid #2a2c35; overflow: hidden; }
+.dossier .d-av canvas { width: 100%; height: 100%; }
+.dossier .d-grid { display: grid; grid-template-columns: 1fr 1fr; column-gap: 26px; padding: 10px 26px 8px; }
+.dossier .d-r { display: flex; align-items: center; height: 52px; border-radius: 10px; padding: 0 8px; }
+.dossier .d-n { font: 700 16px 'JetBrains Mono', monospace; width: 38px; height: 28px; line-height: 26px; text-align: center; border: 1px solid #3a3c46; border-radius: 7px; color: #6b6e7a; flex: none; }
+.dossier .d-r.on .d-n { background: #ff2d3d; border-color: #ff2d3d; color: #fff; }
+.dossier .d-l { font: 600 16px 'JetBrains Mono', monospace; letter-spacing: 0.1em; color: #8d909c; width: 112px; margin-left: 14px; flex: none; }
+.dossier .d-v { font: 600 25px Inter; white-space: nowrap; overflow: hidden; }
+.dossier .d-v i { font-style: normal; color: #2a2c35; letter-spacing: -0.05em; }
+.dossier .d-foot { display: flex; align-items: center; gap: 30px; height: 58px; padding: 0 26px; border-top: 1px solid #22242c; }
+.dossier .d-foot b { font: 700 24px 'JetBrains Mono', monospace; margin-left: 8px; font-variant-numeric: tabular-nums; }
+.dossier .d-end { margin-left: auto; font: 800 26px Inter; color: #ff2d3d; }
+.dossier .d-grid { grid-auto-flow: column; grid-template-columns: 1fr 1fr; }
+.dossier .d-av { overflow: visible; background: none; border: 0; }
+.dossier .d-ring { position: absolute; inset: 0; border-radius: 50%; background: conic-gradient(#ff2d3d calc(var(--p, 0) * 360deg), #2a2c35 0); }
+.dossier .d-face { position: absolute; inset: 6px; border-radius: 50%; background: #14161c; overflow: hidden; }
+.dossier .d-face b { position: absolute; left: 50%; top: 18%; width: 36%; height: 36%; margin-left: -18%; border-radius: 50%; background: #3a3c46; }
+.dossier .d-face i { position: absolute; left: 50%; top: 60%; width: 74%; height: 60%; margin-left: -37%; border-radius: 50% 50% 0 0; background: #3a3c46; }
+.dossier.done .d-face b, .dossier.done .d-face i { background: #ff2d3d; }
+.dossier .d-v u { display: inline-block; height: 0.8em; background: #c9cbd4; vertical-align: -0.08em; }
+.dossier .d-v .ph { display: inline-block; width: 190px; height: 14px; border-radius: 4px; background: #1b1d24; vertical-align: middle; }
+.dossier .d-wm { margin-left: auto; font: 400 18px 'JetBrains Mono', monospace !important; letter-spacing: 0 !important; color: rgba(255,255,255,0.4) !important; }
+.endline { position: absolute; left: 0; right: 0; top: 46px; z-index: 7; text-align: center; font: 800 66px/1 Inter, sans-serif; letter-spacing: -0.02em; color: #fff; opacity: 0; text-shadow: 0 4px 30px rgba(0,0,0,0.6); }
+.endline span { color: #ff2d3d; }
diff --git a/sims/engine/main.js b/sims/engine/main.js
new file mode 100644
index 0000000..1596f1e
--- /dev/null
+++ b/sims/engine/main.js
@@ -0,0 +1,715 @@
+import * as THREE from 'three';
+import {Sky} from 'three/addons/objects/Sky.js';
+import {runSim} from '../kit/runtime.js';
+import {createStage} from '../kit/stage3d.js';
+import {clamp01, easeInOutCubic, easeOutCubic, lerp, rng, smooth} from '../kit/util.js';
+import TL from './timeline.json';
+
+// "Engine": explorer-style film of one methane rocket engine running under its
+// stage, high above a sunset cloud deck (format after the turbofan explorer
+// videos). The cowling splits open, chapters FEED / SPIN / BURN / BLAST light
+// up the flows they talk about, the camera flies down through the injector,
+// the chamber and the throat into the plume, then the engine throttles down,
+// comes apart into labelled parts, goes back together, relights, and the
+// cowling closes on the opening shot (loops).
+//
+// Generic engine, no names or logos. Caption figures are textbook values for
+// methane/LOX full-flow engines, rounded. Sound: sims/engine/sound.py on the
+// same timeline.json.
+
+const DEFAULTS = {
+ duration: TL.duration,
+ fps: 60,
+ theme: 'dark',
+ hud: {enabled: false, title: 'engine', subtitle: ''},
+ director: {enabled: false},
+ watermark: 'X: @whaleyxbt',
+ seed: 21,
+ title: 'ROCKET ENGINE · EXPLORER',
+ chapters: [['FEED', TL.feed], ['SPIN', TL.spin], ['BURN', TL.burn], ['BLAST', TL.blast]],
+ captions: [
+ [0.3, 'A methane rocket engine at full thrust. Cold liquid in, a 3 km/s jet out.'],
+ [TL.feed, 'Feed: liquid oxygen at −183 °C and methane at −162 °C pour in from the tanks.'],
+ [TL.spin, 'Spin: two turbopumps, each driven by its own preburner. All the propellant goes through them.'],
+ [TL.burn, 'Burn: the two hot gas streams meet in the chamber at about 3,500 K and 300 bar.'],
+ [TL.flyIn + 0.9, 'The walls survive because cold methane runs through them first.'],
+ [TL.blast, 'Blast: the bell turns heat into speed. The exhaust leaves at over 3 km/s.'],
+ [TL.blast + 1.6, 'Shock diamonds: the jet overshoots, recompresses, and does it again.'],
+ [TL.explode + 0.2, 'Taken apart: inlets, turbopumps, preburners, injector, chamber, nozzle.'],
+ [TL.relight - 0.1, 'Feed, spin, burn, blast: all at once, the whole way up.'],
+ ],
+};
+
+const C = {
+ lox: new THREE.Color('#3fd0ff'),
+ ch4: new THREE.Color('#ff9a3d'),
+ oxg: new THREE.Color('#ff63d8'),
+ fug: new THREE.Color('#ffc94d'),
+ hot: new THREE.Color('#d8deff'),
+};
+
+// chamber + nozzle profile (y = 0 at the throat)
+const R_CH = 0.36, R_TH = 0.17, R_EX = 0.84, Y_TOP = 1.0, Y_CV = 0.36, Y_EX = -2.1, Y_JOINT = -0.25;
+const wallR = (y) => {
+ if (y >= Y_CV) return R_CH;
+ if (y >= 0) return R_TH + (R_CH - R_TH) * (0.5 - 0.5 * Math.cos(Math.PI * (y / Y_CV)));
+ const s = clamp01(y / Y_EX);
+ return R_TH + (R_EX - R_TH) * (1 - Math.pow(1 - s, 2.1));
+};
+const STAGE_Y = 4.6;
+const PX = 1.3; // turbopump offset from the axis
+
+// cutaway wedge around the axis facing +z, below yTop
+const CLIP = [new THREE.Plane(), new THREE.Plane(), new THREE.Plane()];
+const setCut = (h, yTop) => {
+ CLIP[0].set(new THREE.Vector3(-Math.cos(h), 0, -Math.sin(h)), 0);
+ CLIP[1].set(new THREE.Vector3(Math.cos(h), 0, -Math.sin(h)), 0);
+ CLIP[2].set(new THREE.Vector3(0, 1, 0), -yTop);
+};
+setCut(0, 0);
+const std = (color, metal = 0.6, rough = 0.5, o = {}) =>
+ new THREE.MeshStandardMaterial({
+ color,
+ metalness: metal,
+ roughness: rough,
+ side: THREE.DoubleSide,
+ clippingPlanes: o.clip ? CLIP : null,
+ clipIntersection: true,
+ transparent: (o.opacity ?? 1) < 1,
+ opacity: o.opacity ?? 1,
+ depthWrite: (o.opacity ?? 1) >= 1,
+ envMapIntensity: o.env ?? 0.6,
+ ...(o.extra || {}),
+ });
+
+const VERT = /* glsl */ `
+varying vec3 vN; varying vec3 vV; varying vec3 vP; varying vec2 vUv; varying vec3 vW;
+void main(){
+ vec4 w = modelMatrix * vec4(position, 1.0);
+ vec4 mv = viewMatrix * w;
+ vV = -mv.xyz; vN = normalize(normalMatrix * normal); vP = position; vUv = uv; vW = w.xyz;
+ gl_Position = projectionMatrix * mv;
+}`;
+const NOISE = /* glsl */ `
+float h2(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+float vnoise(vec2 p){
+ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(h2(i), h2(i + vec2(1, 0)), f.x), mix(h2(i + vec2(0, 1)), h2(i + vec2(1, 1)), f.x), f.y);
+}
+float fbm(vec2 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 5; i++) { s += a * vnoise(p); p = p * 2.03 + 7.1; a *= 0.5; } return s; }
+`;
+// flowing stream inside a pipe: pulses travel along the tube
+const STREAM_FRAG = /* glsl */ `
+uniform vec3 uCol; uniform float uT; uniform float uSpeed; uniform float uLen; uniform float uI;
+varying vec3 vN; varying vec3 vV; varying vec3 vP; varying vec2 vUv; varying vec3 vW;
+void main(){
+ float p = fract(vUv.x * uLen * 2.4 - uT * uSpeed);
+ float pulse = smoothstep(0.0, 0.12, p) * smoothstep(1.0, 0.35, p);
+ float face = pow(abs(dot(normalize(vN), normalize(vV))), 0.7);
+ vec3 c = uCol * (0.3 + 1.2 * pulse) * (0.35 + 0.65 * face) * uI;
+ gl_FragColor = vec4(c, 1.0);
+}`;
+const FLAME_FRAG = /* glsl */ `
+uniform float uI; uniform float uT;
+varying vec3 vN; varying vec3 vV; varying vec3 vP; varying vec2 vUv; varying vec3 vW;
+${NOISE}
+void main(){
+ vec3 n = normalize(vN); vec3 v = normalize(vV);
+ float face = pow(abs(dot(n, v)), 1.3);
+ float y = vP.y;
+ float core = y > 0.0 ? 1.0 : exp(y * 0.8);
+ float fl = 0.75 + 0.5 * fbm(vec2(vUv.x * 18.0, y * 5.0 + uT * 14.0));
+ vec3 c = mix(vec3(0.45, 0.38, 1.0), vec3(1.0, 0.94, 1.0), face * core);
+ gl_FragColor = vec4(c * uI * (0.2 + 1.4 * face) * core * fl, 1.0);
+}`;
+// plume as a volume shell (reads from any angle, including from inside)
+const PLUME_FRAG = /* glsl */ `
+uniform float uI; uniform float uT; uniform float uLen;
+varying vec3 vN; varying vec3 vV; varying vec3 vP; varying vec2 vUv; varying vec3 vW;
+${NOISE}
+void main(){
+ float s = clamp((${Y_EX.toFixed(2)} - vP.y) / uLen, 0.0, 1.0);
+ vec3 n = normalize(vN); vec3 v = normalize(vV);
+ float face = pow(abs(dot(n, v)), 1.6);
+ float tur = fbm(vec2(vUv.x * 10.0, s * 14.0 - uT * 6.0));
+ float fall = pow(1.0 - s, 1.3) * smoothstep(0.0, 0.03, s + 0.01);
+ vec3 body = mix(vec3(0.42, 0.3, 1.0), vec3(0.95, 0.55, 0.9), smoothstep(0.35, 1.0, s));
+ vec3 c = body * (0.12 + 1.1 * face) * (0.6 + 0.8 * tur) * fall;
+ c += vec3(1.0, 0.95, 1.0) * pow(face, 6.0) * exp(-s * 9.0) * 0.6;
+ gl_FragColor = vec4(c * uI, 1.0);
+}`;
+const DIAMOND_FRAG = /* glsl */ `
+uniform float uI;
+varying vec3 vN; varying vec3 vV; varying vec3 vP; varying vec2 vUv; varying vec3 vW;
+void main(){
+ float face = pow(abs(dot(normalize(vN), normalize(vV))), 2.0);
+ gl_FragColor = vec4(vec3(1.0, 0.86, 0.97) * face * uI, 1.0);
+}`;
+const CLOUD_FRAG = /* glsl */ `
+uniform float uT; uniform vec3 uHaze; uniform vec3 uLit; uniform vec3 uShade; uniform vec3 uBase; uniform vec3 uCam;
+varying vec3 vN; varying vec3 vV; varying vec3 vP; varying vec2 vUv; varying vec3 vW;
+${NOISE}
+void main(){
+ vec2 p = vW.xz * 0.0045 + vec2(0.0, uT * 0.035);
+ float n = fbm(p) * 0.75 + fbm(p * 3.1 + 4.0) * 0.25;
+ float cov = smoothstep(0.38, 0.6, n);
+ float lit = smoothstep(0.45, 0.78, n);
+ vec3 c = mix(uBase, mix(uShade, uLit, lit), cov);
+ float d = length(vW.xz - uCam.xz);
+ c = mix(c, uHaze, smoothstep(300.0, 2600.0, d));
+ gl_FragColor = vec4(c, 1.0);
+}`;
+const POINT_VERT = /* glsl */ `
+attribute float aSize; attribute vec3 aColor; varying vec3 vC; uniform float uScale;
+void main(){
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
+ vC = aColor;
+ gl_PointSize = min(aSize * uScale / max(0.05, -mv.z), 120.0);
+ gl_Position = projectionMatrix * mv;
+}`;
+const POINT_FRAG = /* glsl */ `
+varying vec3 vC;
+void main(){
+ vec2 p = gl_PointCoord - 0.5; float d = dot(p, p) * 4.0;
+ if (d > 1.0) discard;
+ gl_FragColor = vec4(vC * pow(1.0 - d, 1.6), 1.0);
+}`;
+
+function path(points, n = 160) {
+ const curve = new THREE.CatmullRomCurve3(points.map((p) => new THREE.Vector3(...p)), false, 'centripetal');
+ const pts = curve.getSpacedPoints(n);
+ let len = 0;
+ for (let i = 1; i < pts.length; i++) len += pts[i].distanceTo(pts[i - 1]);
+ return {curve, pts, len};
+}
+const at = (P, u, out) => {
+ const f = clamp01(u) * (P.pts.length - 1);
+ const i = Math.min(P.pts.length - 2, Math.floor(f));
+ return out.lerpVectors(P.pts[i], P.pts[i + 1], f - i);
+};
+const lathePts = (pts) => pts.map(([r, y]) => new THREE.Vector2(r, y));
+
+runSim(DEFAULTS, async ({cfg, canvas, hud, capture}) => {
+ await Promise.all([document.fonts.load('600 20px "JetBrains Mono"'), document.fonts.load('700 20px "JetBrains Mono"'), document.fonts.load('500 20px Inter'), document.fonts.load('600 20px Inter')]).catch(() => {});
+ const st = createStage(canvas, hud, {bg: '#7a6a8a', capture, fov: 38, exposure: 0.55, bloom: {strength: 0.34, radius: 0.5, threshold: 0.92}});
+ const {scene, camera, renderer} = st;
+ renderer.localClippingEnabled = true;
+ camera.near = 0.02;
+ camera.far = 12000;
+ camera.updateProjectionMatrix();
+ const R = rng(cfg.seed);
+
+ // ---- sky above a cloud deck at sunset
+ const sky = new Sky();
+ sky.scale.setScalar(6000);
+ const su = sky.material.uniforms;
+ su.turbidity.value = 6;
+ su.rayleigh.value = 2.2;
+ su.mieCoefficient.value = 0.006;
+ su.mieDirectionalG.value = 0.85;
+ const sunDir = new THREE.Vector3().setFromSphericalCoords(1, THREE.MathUtils.degToRad(85.5), Math.PI / 2 + 0.55);
+ su.sunPosition.value.copy(sunDir);
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const envScene = new THREE.Scene();
+ envScene.add(sky);
+ scene.environment = pmrem.fromScene(envScene, 0.03).texture;
+ scene.add(sky);
+ const sun = new THREE.DirectionalLight('#ffbb88', 2.0);
+ sun.position.copy(sunDir).multiplyScalar(100);
+ scene.add(sun);
+ scene.add(new THREE.HemisphereLight('#a9b8e8', '#4a3a48', 0.6));
+ const cloudMat = new THREE.ShaderMaterial({
+ vertexShader: VERT,
+ fragmentShader: CLOUD_FRAG,
+ uniforms: {uT: {value: 0}, uHaze: {value: new THREE.Color('#e3a891')}, uLit: {value: new THREE.Color('#ffc9a6')}, uShade: {value: new THREE.Color('#8a77a6')}, uBase: {value: new THREE.Color('#4a4366')}, uCam: {value: new THREE.Vector3()}},
+ });
+ const deck = new THREE.Mesh(new THREE.PlaneGeometry(9000, 9000, 1, 1), cloudMat);
+ deck.rotation.x = -Math.PI / 2;
+ deck.position.y = -160;
+ scene.add(deck);
+
+ // ---- the stage above the engine
+ const stageG = new THREE.Group();
+ scene.add(stageG);
+ const paint = std('#e9e6e0', 0.15, 0.55, {env: 0.5});
+ const stageBody = new THREE.Mesh(new THREE.CylinderGeometry(2.5, 2.5, 60, 128, 1, true), paint);
+ stageBody.position.y = STAGE_Y + 30;
+ stageG.add(stageBody);
+ const band = new THREE.Mesh(new THREE.CylinderGeometry(2.52, 2.52, 1.2, 128, 1, true), std('#23252b', 0.3, 0.6));
+ band.position.y = STAGE_Y + 2.2;
+ stageG.add(band);
+ const shield = new THREE.Mesh(new THREE.CircleGeometry(2.5, 96), std('#2b2d33', 0.3, 0.8));
+ shield.rotation.x = Math.PI / 2;
+ shield.position.y = STAGE_Y;
+ stageG.add(shield);
+
+ // ---- engine parts (each group can move in the exploded view)
+ const engine = new THREE.Group();
+ scene.add(engine);
+ const parts = {};
+ for (const k of ['inlets', 'pre', 'pumpL', 'pumpR', 'inj', 'chamber', 'nozzle', 'ducts']) {
+ parts[k] = new THREE.Group();
+ engine.add(parts[k]);
+ }
+ // chamber and nozzle: copper with coolant-tube ridges, cut open by the wedge
+ const ridged = (y0, y1, seg = 420) => {
+ const pts = [];
+ for (let k = 0; k <= 60; k++) {
+ const y = lerp(y0, y1, k / 60);
+ pts.push(new THREE.Vector2(wallR(y), y));
+ }
+ const g = new THREE.LatheGeometry(pts, seg);
+ const pa = g.attributes.position;
+ for (let i = 0; i < pa.count; i++) {
+ const x = pa.getX(i), y = pa.getY(i), z = pa.getZ(i);
+ if (Math.hypot(x, z) < 1e-4) continue;
+ const k = 1 + 0.02 * Math.pow(0.5 + 0.5 * Math.cos(Math.atan2(x, z) * 84), 0.6) * smooth((Y_TOP - 0.04 - y) / 0.08);
+ pa.setX(i, x * k);
+ pa.setZ(i, z * k);
+ }
+ g.computeVertexNormals();
+ return g;
+ };
+ const heatTex = (() => {
+ const c = document.createElement('canvas');
+ c.width = 4;
+ c.height = 256;
+ const g = c.getContext('2d');
+ const gr = g.createLinearGradient(0, 0, 0, 256);
+ gr.addColorStop(0, '#000000');
+ gr.addColorStop(0.55, '#3a0c00');
+ gr.addColorStop(1, '#ff6a1c');
+ g.fillStyle = gr;
+ g.fillRect(0, 0, 4, 256);
+ const t = new THREE.CanvasTexture(c);
+ t.colorSpace = THREE.SRGBColorSpace;
+ return t;
+ })();
+ const copper = std('#a8714f', 0.7, 0.42, {clip: true, env: 0.7});
+ const copperHot = std('#a8714f', 0.7, 0.42, {clip: true, env: 0.7, extra: {emissive: new THREE.Color('#ffffff'), emissiveMap: heatTex, emissiveIntensity: 0.9}});
+ parts.chamber.add(new THREE.Mesh(ridged(Y_TOP, Y_JOINT), copperHot));
+ parts.nozzle.add(new THREE.Mesh(ridged(Y_JOINT, Y_EX), copper));
+ const steelRing = std('#c4c9d0', 0.85, 0.3, {clip: true});
+ const ring = (grp, r, y, tube) => {
+ const g = new THREE.TorusGeometry(r, tube, 10, 128);
+ g.rotateX(Math.PI / 2);
+ const m = new THREE.Mesh(g, steelRing);
+ m.position.y = y;
+ grp.add(m);
+ };
+ ring(parts.chamber, R_CH + 0.035, Y_TOP, 0.045);
+ ring(parts.chamber, R_CH + 0.035, Y_CV, 0.035);
+ ring(parts.chamber, wallR(Y_JOINT) + 0.04, Y_JOINT, 0.04);
+ ring(parts.nozzle, wallR(Y_JOINT) + 0.04, Y_JOINT - 0.03, 0.035);
+ ring(parts.nozzle, wallR(-0.9) + 0.03, -0.9, 0.022);
+ ring(parts.nozzle, wallR(-1.5) + 0.035, -1.5, 0.045); // regen manifold
+ ring(parts.nozzle, R_EX + 0.02, Y_EX, 0.04);
+ // injector dome + gimbal block
+ const domeMat = std('#b9bfc7', 0.85, 0.32, {clip: true});
+ parts.inj.add(new THREE.Mesh(new THREE.LatheGeometry(lathePts([[0.001, 1.5], [0.14, 1.48], [0.27, 1.4], [0.36, 1.24], [0.39, 1.1], [0.4, 1.02]]), 96), domeMat));
+ const puck = new THREE.Mesh(new THREE.CylinderGeometry(0.13, 0.22, 0.42, 32), std('#444a53', 0.7, 0.5));
+ puck.position.y = 1.71;
+ parts.inj.add(puck);
+ const bolts = [];
+ for (let i = 0; i < 52; i++) {
+ const a = (i / 52) * Math.PI * 2;
+ bolts.push([0.44 * Math.sin(a), Y_TOP + 0.05, 0.44 * Math.cos(a)]);
+ }
+ const boltMesh = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.012, 0.012, 0.026, 6), std('#dfe3e8', 0.9, 0.25, {clip: true}), bolts.length);
+ const mtx = new THREE.Matrix4();
+ bolts.forEach((b, i) => boltMesh.setMatrixAt(i, mtx.makeTranslation(...b)));
+ parts.chamber.add(boltMesh);
+
+ // turbopumps: big housings with an open window toward the camera, impeller + turbine inside
+ const graphite = std('#3c424b', 0.65, 0.48);
+ const pumps = [-1, 1].map((side) => {
+ const g = side < 0 ? parts.pumpL : parts.pumpR;
+ const P = new THREE.Group();
+ P.position.set(side * PX, 0, 0);
+ g.add(P);
+ const win = 1.9;
+ P.add(new THREE.Mesh(new THREE.LatheGeometry(lathePts([[0.001, 1.25], [0.22, 1.25], [0.36, 1.36], [0.42, 1.55], [0.42, 2.25], [0.47, 2.36], [0.47, 2.62], [0.3, 2.72], [0.12, 2.76]]), 96, win / 2, Math.PI * 2 - win), graphite));
+ for (const y of [1.55, 2.25, 2.62]) {
+ const tg = new THREE.TorusGeometry(y > 2.3 ? 0.48 : 0.43, 0.025, 8, 96, Math.PI * 2 - win);
+ tg.rotateX(Math.PI / 2);
+ tg.rotateY(-Math.PI / 2 - win / 2);
+ const m = new THREE.Mesh(tg, std('#9ea6b0', 0.85, 0.3));
+ m.position.y = y;
+ P.add(m);
+ }
+ const rotor = new THREE.Group();
+ rotor.add(new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.05, 1.45, 16), std('#d7dce2', 0.9, 0.22)));
+ const bladeMat = std('#e2c48a', 0.85, 0.3);
+ const turbMat = std('#c9cfd6', 0.9, 0.25);
+ // inducer spiral + impeller (pump end, low) and a turbine disk (top)
+ for (let i = 0; i < 3; i++) {
+ for (let k = 0; k < 10; k++) {
+ const b = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.012, 0.09), bladeMat);
+ const a = (k / 10) * Math.PI * 2 + i * 0.4;
+ b.position.set(Math.cos(a) * 0.19, -0.42 + i * 0.12 + k * 0.004, Math.sin(a) * 0.19);
+ b.rotation.set(0.0, -a, 0.55);
+ rotor.add(b);
+ }
+ }
+ const impeller = new THREE.Mesh(new THREE.CylinderGeometry(0.36, 0.36, 0.04, 48), bladeMat);
+ impeller.position.y = -0.06;
+ rotor.add(impeller);
+ for (let k = 0; k < 14; k++) {
+ const b = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.13, 0.016), bladeMat);
+ const a = (k / 14) * Math.PI * 2;
+ b.position.set(Math.cos(a) * 0.2, 0.02, Math.sin(a) * 0.2);
+ b.rotation.y = -a - 0.45;
+ rotor.add(b);
+ }
+ const disk = new THREE.Mesh(new THREE.CylinderGeometry(0.4, 0.4, 0.05, 48), turbMat);
+ disk.position.y = 0.62;
+ rotor.add(disk);
+ for (let k = 0; k < 36; k++) {
+ const b = new THREE.Mesh(new THREE.BoxGeometry(0.045, 0.12, 0.014), turbMat);
+ const a = (k / 36) * Math.PI * 2;
+ b.position.set(Math.cos(a) * 0.42, 0.62, Math.sin(a) * 0.42);
+ b.rotation.set(0, -a, 0.5);
+ rotor.add(b);
+ }
+ rotor.position.y = 1.85;
+ P.add(rotor);
+ // preburner above the turbine
+ const preG = new THREE.Group();
+ preG.position.set(side * PX, 0, 0);
+ parts.pre.add(preG);
+ preG.add(new THREE.Mesh(new THREE.LatheGeometry(lathePts([[0.001, 3.62], [0.1, 3.6], [0.18, 3.52], [0.2, 3.38], [0.2, 2.92], [0.15, 2.8]]), 64, 0.8, Math.PI * 2 - 1.6), std('#59606a', 0.75, 0.42)));
+ const glow = new THREE.Mesh(new THREE.SphereGeometry(0.15, 24, 16), new THREE.MeshBasicMaterial({color: side < 0 ? C.oxg : C.fug, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false}));
+ glow.position.y = 3.2;
+ glow.scale.set(1, 1.9, 1);
+ preG.add(glow);
+ return {rotor, glow};
+ });
+
+ // pipes (faint glass) with glowing streams inside
+ const glass = std('#c8d3e0', 0.0, 0.35, {opacity: 0.1, env: 0.4});
+ const streams = [];
+ const pipe = (grp, pts, r, col, speed, chapter) => {
+ const P = path(pts);
+ grp.add(new THREE.Mesh(new THREE.TubeGeometry(P.curve, 140, r, 16, false), glass));
+ const mat = new THREE.ShaderMaterial({vertexShader: VERT, fragmentShader: STREAM_FRAG, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, uniforms: {uCol: {value: col}, uT: {value: 0}, uSpeed: {value: speed}, uLen: {value: P.len}, uI: {value: 1}}});
+ grp.add(new THREE.Mesh(new THREE.TubeGeometry(P.curve, 140, r * 0.62, 12, false), mat));
+ streams.push({mat, chapter});
+ return P;
+ };
+ const mir = (pts) => pts.map(([x, y, z]) => [-x, y, z]);
+ const loxIn = [[-0.8, STAGE_Y + 0.4, 0.2], [-0.9, 3.9, 0.5], [-1.55, 2.5, 0.55], [-1.6, 1.4, 0.3], [-PX, 1.2, 0.05]];
+ pipe(parts.inlets, loxIn, 0.13, C.lox, 1.6, 'feed');
+ pipe(parts.inlets, mir(loxIn), 0.13, C.ch4, 1.6, 'feed');
+ // pump discharge: LOX to the injector, methane down to the regen manifold
+ pipe(parts.ducts, [[-PX + 0.3, 1.36, 0.3], [-0.95, 1.05, 0.6], [-0.45, 1.25, 0.55], [-0.22, 1.42, 0.3]], 0.08, C.lox, 1.9, 'spin');
+ pipe(parts.ducts, [[PX - 0.3, 1.36, 0.3], [1.2, 0.4, 0.62], [1.05, -0.8, 0.75], [0.62, -1.5, 0.62]], 0.075, C.ch4, 1.9, 'spin');
+ // hot gas: turbine exhaust to the injector
+ pipe(parts.ducts, [[-PX, 2.75, 0.0], [-PX + 0.15, 2.95, 0.4], [-0.6, 2.2, 0.5], [-0.25, 1.6, 0.35]], 0.1, C.oxg, 2.2, 'burn');
+ pipe(parts.ducts, mir([[-PX, 2.75, 0.0], [-PX + 0.15, 2.95, 0.4], [-0.6, 2.2, 0.5], [-0.25, 1.6, 0.35]]), 0.1, C.fug, 2.2, 'burn');
+ // preburner feeds
+ pipe(parts.ducts, [[-PX - 0.35, 1.5, 0.15], [-PX - 0.5, 2.4, 0.25], [-PX - 0.2, 3.3, 0.18]], 0.045, C.lox, 1.6, 'spin');
+ pipe(parts.ducts, [[0.42, 1.02, 0.25], [0.95, 1.9, 0.62], [PX + 0.45, 2.6, 0.3], [PX + 0.2, 3.3, 0.18]], 0.05, C.ch4, 1.6, 'spin');
+ // regen: streams on the outside of the bell and chamber
+ const regenMat = new THREE.ShaderMaterial({vertexShader: VERT, fragmentShader: STREAM_FRAG, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, uniforms: {uCol: {value: C.ch4}, uT: {value: 0}, uSpeed: {value: 1.3}, uLen: {value: 3}, uI: {value: 1}}});
+ streams.push({mat: regenMat, chapter: 'burn'});
+ for (const phi of [1.05, 1.5, 1.95, 2.5, -1.05, -1.5, -1.95, -2.5]) {
+ const pts = [];
+ for (let k = 0; k <= 14; k++) {
+ const y = lerp(-1.5, 0.95, k / 14);
+ const r = wallR(y) + 0.04;
+ pts.push([r * Math.sin(phi), y, r * Math.cos(phi)]);
+ }
+ parts.nozzle.add(new THREE.Mesh(new THREE.TubeGeometry(path(pts).curve, 80, 0.018, 8, false), regenMat));
+ }
+
+ // flame in the chamber, plume shell, shock diamonds
+ const flameMat = new THREE.ShaderMaterial({vertexShader: VERT, fragmentShader: FLAME_FRAG, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide, uniforms: {uI: {value: 1}, uT: {value: 0}}});
+ const fpts = [];
+ for (let k = 0; k <= 50; k++) {
+ const y = lerp(Y_TOP - 0.02, Y_EX, k / 50);
+ fpts.push(new THREE.Vector2(wallR(y) * 0.9, y));
+ }
+ parts.chamber.add(new THREE.Mesh(new THREE.LatheGeometry(fpts, 64), flameMat));
+ const PL = 16;
+ const plumeMat = new THREE.ShaderMaterial({vertexShader: VERT, fragmentShader: PLUME_FRAG, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide, uniforms: {uI: {value: 1}, uT: {value: 0}, uLen: {value: PL}}});
+ const ppts = [];
+ for (let k = 0; k <= 60; k++) {
+ const s = k / 60;
+ ppts.push(new THREE.Vector2(R_EX * 0.92 * (1 + 1.4 * s) * (1 - 0.07 * Math.sin(s * 40) ** 2 * (1 - s)), Y_EX - s * PL));
+ }
+ const plume = new THREE.Mesh(new THREE.LatheGeometry(ppts, 64), plumeMat);
+ parts.nozzle.add(plume);
+ const diaMat = new THREE.ShaderMaterial({vertexShader: VERT, fragmentShader: DIAMOND_FRAG, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, uniforms: {uI: {value: 1}}});
+ for (let k = 0; k < 9; k++) {
+ const d = new THREE.Mesh(new THREE.LatheGeometry(lathePts([[0.001, 0.5], [0.5, 0.0], [0.001, -0.5]]), 32), diaMat);
+ d.position.y = Y_EX - 0.75 - k * 1.05;
+ d.scale.set(0.62 - k * 0.03, 0.42, 0.62 - k * 0.03);
+ parts.nozzle.add(d);
+ }
+ const plumeLight = new THREE.PointLight('#c8b6ff', 0, 0, 2);
+ plumeLight.position.set(0, Y_EX - 2.5, 0);
+ parts.nozzle.add(plumeLight);
+
+ // hot streaks through the chamber and throat
+ const comb = [];
+ for (let i = 0; i < 90; i++) {
+ const phi = R() * Math.PI * 2, q = Math.sqrt(R()) * 0.82;
+ comb.push(path([0.98, 0.6, 0.25, 0.0, -0.7, -1.4, -2.1, -3.2].map((y) => [(y > Y_EX ? wallR(y) : R_EX * (1 + 0.3 * (Y_EX - y))) * q * Math.sin(phi), y, (y > Y_EX ? wallR(y) : R_EX * (1 + 0.3 * (Y_EX - y))) * q * Math.cos(phi)]), 60));
+ }
+ const PER = 7;
+ const nP = comb.length * PER;
+ const pPos = new Float32Array(nP * 3), pCol = new Float32Array(nP * 3), pSize = new Float32Array(nP);
+ const ph = Array.from({length: nP}, () => R());
+ const pg = new THREE.BufferGeometry();
+ pg.setAttribute('position', new THREE.BufferAttribute(pPos, 3));
+ pg.setAttribute('aColor', new THREE.BufferAttribute(pCol, 3));
+ pg.setAttribute('aSize', new THREE.BufferAttribute(pSize, 1));
+ const pMat = new THREE.ShaderMaterial({vertexShader: POINT_VERT, fragmentShader: POINT_FRAG, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, uniforms: {uScale: {value: 30}}});
+ const pts = new THREE.Points(pg, pMat);
+ pts.frustumCulled = false;
+ parts.chamber.add(pts);
+
+ // aft skirt of the stage: two white half-cylinders with the heat-shield floor; they slide apart
+ const SK0 = 0.85;
+ const cowl = [];
+ for (const side of [-1, 1]) {
+ const grp = new THREE.Group();
+ const shellMat = std('#ebe8e2', 0.12, 0.5, {env: 0.5, extra: {transparent: true}});
+ const shell = new THREE.Mesh(new THREE.CylinderGeometry(2.5, 2.5, STAGE_Y - SK0, 128, 1, true, side < 0 ? Math.PI : 0, Math.PI), shellMat);
+ shell.position.y = (STAGE_Y + SK0) / 2;
+ grp.add(shell);
+ const fg = new THREE.RingGeometry(0.62, 2.5, 96, 1, side < 0 ? Math.PI / 2 : -Math.PI / 2, Math.PI);
+ fg.rotateX(-Math.PI / 2);
+ const floor = new THREE.Mesh(fg, std('#2a2c31', 0.35, 0.75));
+ floor.position.y = SK0;
+ grp.add(floor);
+ for (const y of [SK0 + 0.04, (STAGE_Y + SK0) / 2]) {
+ const tg = new THREE.TorusGeometry(2.515, 0.03, 6, 96, Math.PI);
+ tg.rotateX(Math.PI / 2);
+ tg.rotateY(side < 0 ? 0 : Math.PI);
+ const r = new THREE.Mesh(tg, std('#9ea3aa', 0.6, 0.4));
+ r.position.y = y;
+ grp.add(r);
+ }
+ scene.add(grp);
+ cowl.push({grp, side, mat: shellMat});
+ }
+
+ // ---- overlay
+ const ov = document.createElement('div');
+ ov.className = 'e-ov';
+ ov.innerHTML = `<div class="e-top"><div class="e-title">${cfg.title}</div><div class="e-ch">${cfg.chapters.map(([c]) => `<span>${c}</span>`).join('')}</div></div>
+ <div class="e-cap"><span></span></div>
+ <div class="e-bar"><i></i>${cfg.chapters.map(([, t]) => `<em style="left:${((t / cfg.duration) * 100).toFixed(2)}%"></em>`).join('')}</div>
+ <div class="e-time"></div><div class="e-wm">${cfg.watermark}</div><canvas class="e-lines"></canvas>`;
+ document.getElementById('app').appendChild(ov);
+ const lineCv = ov.querySelector('.e-lines');
+ const lctx = lineCv.getContext('2d');
+ const chEls = [...ov.querySelectorAll('.e-ch span')];
+ const capEl = ov.querySelector('.e-cap'), capSpan = ov.querySelector('.e-cap span');
+ const barFill = ov.querySelector('.e-bar i'), timeEl = ov.querySelector('.e-time');
+ const X0 = TL.explode + 1.3, X1 = TL.assemble - 0.2;
+ const LABELS = [
+ {text: 'LOX INLET', sub: '−183 °C', part: 'inlets', a: [-1.58, 2.3, 0.56], side: -1, t0: TL.feed + 0.3, t1: TL.spin - 0.1, c: C.lox},
+ {text: 'METHANE INLET', sub: '−162 °C', part: 'inlets', a: [1.58, 2.3, 0.56], side: 1, t0: TL.feed + 0.5, t1: TL.spin - 0.1, c: C.ch4},
+ {text: 'LOX TURBOPUMP', sub: 'driven by the ox-rich preburner', part: 'pumpL', a: [-PX, 1.85, 0.3], side: -1, t0: TL.spin + 0.2, t1: TL.burn - 0.1, c: C.lox},
+ {text: 'OX-RICH PREBURNER', sub: 'burns a little methane in all the oxygen', part: 'pre', a: [-PX, 3.25, 0.2], side: -1, t0: TL.spin + 0.9, t1: TL.burn - 0.1, c: C.oxg},
+ {text: 'METHANE TURBOPUMP', sub: 'driven by the fuel-rich preburner', part: 'pumpR', a: [PX, 1.85, 0.3], side: 1, t0: TL.spin + 0.6, t1: TL.burn - 0.1, c: C.ch4},
+ {text: 'FUEL-RICH PREBURNER', sub: 'burns a little oxygen in all the methane', part: 'pre', a: [PX, 3.25, 0.2], side: 1, t0: TL.spin + 1.2, t1: TL.burn - 0.1, c: C.fug},
+ {text: 'MAIN INJECTOR', sub: 'the two hot gas streams meet', part: 'inj', a: [0.0, 1.35, 0.4], side: -1, t0: TL.burn + 0.2, t1: TL.flyIn + 0.3, c: C.hot},
+ {text: 'COMBUSTION CHAMBER', sub: '~300 bar · ~3,500 K', part: 'chamber', a: [0.3, 0.65, 0.2], side: 1, t0: TL.burn + 0.4, t1: TL.flyIn + 0.3, c: C.hot},
+ {text: 'NOZZLE', sub: 'regen-cooled by methane', part: 'nozzle', a: [0.72, -1.4, 0.35], side: 1, t0: TL.blast + 0.3, t1: TL.throttle, c: C.ch4},
+ {text: 'SHOCK DIAMONDS', sub: '', part: 'nozzle', a: [0, Y_EX - 1.8, 0], side: -1, t0: TL.blast + 1.6, t1: TL.throttle, c: C.hot},
+ {text: 'INLETS', sub: '', part: 'inlets', a: [-1.58, 2.6, 0.56], side: -1, t0: X0, t1: X1, c: C.lox},
+ {text: 'PREBURNERS', sub: '', part: 'pre', a: [PX, 3.4, 0.2], side: 1, t0: X0 + 0.1, t1: X1, c: C.oxg},
+ {text: 'TURBOPUMPS', sub: '', part: 'pumpL', a: [-PX - 0.4, 1.9, 0], side: -1, t0: X0 + 0.2, t1: X1, c: C.lox},
+ {text: 'INJECTOR', sub: '', part: 'inj', a: [0.38, 1.25, 0.1], side: 1, t0: X0 + 0.3, t1: X1, c: C.hot},
+ {text: 'CHAMBER', sub: '', part: 'chamber', a: [0.36, 0.5, 0.1], side: 1, t0: X0 + 0.4, t1: X1, c: C.hot},
+ {text: 'NOZZLE', sub: '', part: 'nozzle', a: [-0.7, -1.3, 0.3], side: -1, t0: X0 + 0.5, t1: X1, c: C.ch4},
+ ].map((L) => {
+ const el = document.createElement('div');
+ el.className = `e-lab ${L.side < 0 ? 'l' : 'r'}`;
+ el.innerHTML = `<b><i style="background:#${L.c.getHexString()}"></i>${L.text}</b>${L.sub ? `<span>${L.sub}</span>` : ''}`;
+ ov.appendChild(el);
+ return {...L, el};
+ });
+ let s = 1, OW = 1080, OH = 1350;
+ const layoutOv = () => {
+ const iw = innerWidth, ih = innerHeight;
+ s = iw / ih <= 1080 / 1350 ? iw / 1080 : ih / 1350;
+ OW = iw / s;
+ OH = ih / s;
+ ov.style.width = `${OW}px`;
+ ov.style.height = `${OH}px`;
+ ov.style.transform = `scale(${s})`;
+ const dpr = devicePixelRatio || 1;
+ lineCv.width = Math.round(iw * dpr);
+ lineCv.height = Math.round(ih * dpr);
+ lineCv.style.width = `${OW}px`;
+ lineCv.style.height = `${OH}px`;
+ };
+ layoutOv();
+ st.resize();
+
+ // ---- state over time
+ const openAt = (t) => smooth((t - TL.open) / 1.3) * (1 - smooth((t - TL.close) / 1.4));
+ const explAt = (t) => easeInOutCubic((t - TL.explode) / 1.4) * (1 - easeInOutCubic((t - TL.assemble) / 1.3));
+ const powerAt = (t) => 1 - smooth((t - TL.throttle) / 0.6) + smooth((t - TL.relight) / 0.25);
+ const OFF = {inlets: [0, 1.2, 0], pre: [0, 1.6, 0], pumpL: [-1.0, 0.25, 0], pumpR: [1.0, 0.25, 0], inj: [0, 0.75, 0], chamber: [0, 0, 0], nozzle: [0, -1.4, 0], ducts: [0, 0.45, 0]};
+ const omega = (t) => 40 * (0.15 + 0.85 * clamp01(powerAt(t)));
+ const rotorAngle = (t) => {
+ let a = 0;
+ for (let x = 0; x < t; x += 1 / 120) a += omega(x) / 120;
+ return a;
+ };
+ const K = [
+ {t: 0, c: [5.2, -4.6, 13.5], l: [0, 0.3, 0]},
+ {t: TL.open - 0.1, c: [4.4, 1.0, 9.2], l: [0, 1.7, 0]},
+ {t: TL.feed + 1.3, c: [2.4, 2.6, 6.4], l: [0, 2.1, 0]},
+ {t: TL.spin + 0.5, c: [-4.4, 2.4, 4.8], l: [-PX, 2.1, 0]},
+ {t: TL.burn - 0.3, c: [4.4, 2.9, 4.8], l: [PX * 0.6, 2.3, 0]},
+ {t: TL.flyIn, c: [0.35, 3.3, 1.5], l: [0, 1.0, 0]},
+ {t: TL.flyIn + 0.9, c: [0.02, 1.25, 0.06], l: [0, -0.75, -0.08], ease: 'in'},
+ {t: TL.flyIn + 1.7, c: [0.0, -0.2, 0.04], l: [0, -2.2, -0.06], ease: 'lin'},
+ {t: TL.flyOut, c: [0.0, -3.4, 0.05], l: [0, -5.4, -0.06], ease: 'lin'},
+ {t: TL.blast + 1.4, c: [5.2, -6.8, 10.5], l: [0, -3.8, 0], ease: 'out'},
+ {t: TL.throttle, c: [6.2, -2.6, 11.5], l: [0, -0.8, 0]},
+ {t: TL.explode + 1.8, c: [5.0, 1.5, 11.2], l: [0, 1.0, 0]},
+ {t: TL.assemble, c: [-5.2, 1.4, 10.8], l: [0, 0.9, 0]},
+ {t: TL.close + 0.3, c: [-4.4, -1.6, 11], l: [0, 0.3, 0]},
+ {t: TL.duration, c: [5.2, -4.6, 13.5], l: [0, 0.3, 0]},
+ ];
+ const camAt = (t) => {
+ let i = 0;
+ while (i < K.length - 2 && t > K[i + 1].t) i++;
+ const a = K[i], b = K[i + 1];
+ const k = clamp01((t - a.t) / (b.t - a.t));
+ const q = b.ease === 'out' ? easeOutCubic(k) : b.ease === 'in' ? k ** 2 : b.ease === 'lin' ? k : easeInOutCubic(k);
+ return {c: a.c.map((v, j) => lerp(v, b.c[j], q)), l: a.l.map((v, j) => lerp(v, b.l[j], q))};
+ };
+ const chapterOf = (t) => (t >= TL.blast ? 'blast' : t >= TL.burn ? 'burn' : t >= TL.spin ? 'spin' : t >= TL.feed ? 'feed' : '');
+ const v3 = new THREE.Vector3();
+
+ return {
+ resize() {
+ st.resize();
+ layoutOv();
+ },
+ render(t) {
+ const open = openAt(t), ex = explAt(t), pw = clamp01(powerAt(t));
+ const relit = t > TL.relight ? Math.exp(-(t - TL.relight) / 0.3) : 0;
+
+ // parts and cowling
+ for (const [k, g] of Object.entries(parts)) g.position.set(OFF[k][0] * ex, OFF[k][1] * ex, OFF[k][2] * ex);
+ stageG.position.y = 2.0 * ex;
+ for (const c of cowl) {
+ c.grp.position.set(c.side * 4.6 * open, 2.0 * ex + 0.8 * open, -1.2 * open);
+ c.grp.rotation.y = -c.side * 0.55 * open;
+ const vis = 1 - smooth((open - 0.3) / 0.45);
+ c.grp.visible = vis > 0.01;
+ c.grp.traverse((m) => m.material && ((m.material.transparent = true), (m.material.opacity = vis), (m.material.depthWrite = vis > 0.98)));
+ }
+ setCut(0.95 * open, 1.75 + 0.75 * ex);
+
+ // camera (+ light vibration from the engine)
+ const cam = camAt(t);
+ const buzz = 0.006 * pw + 0.05 * relit;
+ camera.position.set(cam.c[0] + buzz * Math.sin(t * 91), cam.c[1] + buzz * Math.sin(t * 127 + 1), cam.c[2] + buzz * Math.sin(t * 73 + 2));
+ camera.lookAt(cam.l[0], cam.l[1], cam.l[2]);
+ camera.updateMatrixWorld();
+
+ // running engine
+ pumps.forEach((p, k) => {
+ p.rotor.rotation.y = (k ? -1 : 1) * rotorAngle(t);
+ p.glow.material.opacity = pw * (0.85 + 0.15 * Math.sin(t * 47 + k * 2));
+ });
+ const chap = chapterOf(t);
+ for (const S of streams) {
+ S.mat.uniforms.uT.value = t;
+ const focus = !chap || chap === 'blast' ? 0.7 : S.chapter === chap ? 1.2 : 0.3;
+ S.mat.uniforms.uI.value = focus * (0.25 + 0.75 * pw) * (1 - 0.85 * ex);
+ }
+ flameMat.uniforms.uI.value = (0.85 + 0.6 * relit) * pw;
+ flameMat.uniforms.uT.value = t;
+ plumeMat.uniforms.uI.value = (0.5 + 0.8 * relit) * pw;
+ plumeMat.uniforms.uT.value = t;
+ diaMat.uniforms.uI.value = (1.15 + 0.15 * Math.sin(t * 37)) * pw;
+ plumeLight.intensity = 110 * pw * (0.9 + 0.1 * Math.sin(t * 57));
+ copperHot.emissiveIntensity = 0.9 * pw;
+ cloudMat.uniforms.uT.value = t;
+ cloudMat.uniforms.uCam.value.copy(camera.position);
+ // hot streaks
+ let o = 0;
+ for (const P of comb) {
+ for (let k = 0; k < PER; k++, o++) {
+ const u = Math.pow((ph[o] + t * 0.9) % 1, 1.4);
+ at(P, u, v3);
+ pPos[o * 3] = v3.x;
+ pPos[o * 3 + 1] = v3.y;
+ pPos[o * 3 + 2] = v3.z;
+ const b = 0.55 * pw * (1 - ex);
+ pCol[o * 3] = C.hot.r * b;
+ pCol[o * 3 + 1] = C.hot.g * b;
+ pCol[o * 3 + 2] = C.hot.b * b;
+ pSize[o] = 0.6 + 0.9 * u;
+ }
+ }
+ pg.attributes.position.needsUpdate = true;
+ pg.attributes.aColor.needsUpdate = true;
+ pg.attributes.aSize.needsUpdate = true;
+ pMat.uniforms.uScale.value = 30 * (st.size.h / 1350) * (window.devicePixelRatio || 1);
+
+ st.render();
+
+ // overlay
+ chEls.forEach((el, i) => el.classList.toggle('on', chap === ['feed', 'spin', 'burn', 'blast'][i]));
+ let ci = -1;
+ cfg.captions.forEach(([ct], i) => (t >= ct ? (ci = i) : 0));
+ if (ci >= 0) {
+ const [ct, text] = cfg.captions[ci];
+ const next = cfg.captions[ci + 1]?.[0] ?? cfg.duration + 1;
+ if (capSpan.textContent !== text) capSpan.textContent = text;
+ capEl.style.opacity = (smooth((t - ct) / 0.25) * (1 - smooth((t - next + 0.2) / 0.2))).toFixed(3);
+ } else capEl.style.opacity = '0';
+ barFill.style.width = `${((t / cfg.duration) * 100).toFixed(2)}%`;
+ timeEl.textContent = `${t.toFixed(1)} / ${cfg.duration.toFixed(1)} s`;
+
+ const dpr = lineCv.width / (OW * s);
+ lctx.setTransform(s * dpr, 0, 0, s * dpr, 0, 0);
+ lctx.clearRect(0, 0, OW, OH);
+ const used = {'-1': [], 1: []};
+ for (const L of LABELS) {
+ const a = smooth((t - L.t0) / 0.3) * (1 - smooth((t - L.t1) / 0.3));
+ const off = OFF[L.part];
+ const p = st.project([L.a[0] + off[0] * ex, L.a[1] + off[1] * ex, L.a[2] + off[2] * ex]);
+ const onScreen = p.visible && p.x > 20 && p.x < st.size.w - 20 && p.y > 20 && p.y < st.size.h - 20;
+ if (a <= 0.001 || !onScreen) {
+ L.el.style.opacity = '0';
+ continue;
+ }
+ L.el.style.opacity = a.toFixed(3);
+ const ax = p.x / s, ay = p.y / s;
+ let ly = Math.min(OH - 340, Math.max(190, ay));
+ for (const u of used[L.side]) if (Math.abs(u - ly) < 70) ly = u + 70 * Math.sign(ly - u || 1);
+ used[L.side].push(ly);
+ L.el.style.top = `${ly - (L.sub ? 26 : 18)}px`;
+ const w = L.el.offsetWidth;
+ const ex2 = L.side < 0 ? 40 + w + 10 : OW - 40 - w - 10;
+ lctx.globalAlpha = a;
+ lctx.strokeStyle = 'rgba(255,255,255,0.85)';
+ lctx.lineWidth = 1.6;
+ lctx.beginPath();
+ lctx.moveTo(ex2, ly);
+ lctx.lineTo(lerp(ex2, ax, 0.35), ly);
+ lctx.lineTo(ax, ay);
+ lctx.stroke();
+ lctx.fillStyle = '#fff';
+ lctx.beginPath();
+ lctx.arc(ax, ay, 4.5, 0, Math.PI * 2);
+ lctx.fill();
+ lctx.globalAlpha = 1;
+ }
+ return {};
+ },
+ };
+});
diff --git a/sims/engine/sound.py b/sims/engine/sound.py
new file mode 100644
index 0000000..13e7785
--- /dev/null
+++ b/sims/engine/sound.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Ambient soundtrack for the engine explorer, built on the same timeline.json.
+
+No music: air rush and a steady muffled roar, louder and brighter on the
+fly-through, turbopump whine in the SPIN chapter, servo + clunk when the
+skirt opens and closes, whooshes for the exploded view, a relight boom.
+
+ python3 sims/engine/sound.py [-o out/sims/engine/ambient.wav]
+
+Mux it with capture.mjs: --music <wav> --music-start 0 --no-sync --lufs -24
+"""
+
+import argparse
+import json
+import math
+import os
+import random
+import sys
+import wave
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, "..", ".."))
+from sfx.dsp import SR, biquad, hp, lp, svf # noqa: E402
+
+TL = json.load(open(os.path.join(HERE, "timeline.json")))
+DUR = TL["duration"]
+N = int(DUR * SR)
+T_OPEN, T_SPIN, T_BURN, T_FIN, T_FOUT = TL["open"], TL["spin"], TL["burn"], TL["flyIn"], TL["flyOut"]
+T_THR, T_EXP, T_ASM, T_REL, T_CLOSE = TL["throttle"], TL["explode"], TL["assemble"], TL["relight"], TL["close"]
+
+
+def smooth(x):
+ x = 0.0 if x < 0 else 1.0 if x > 1 else x
+ return x * x * (3 - 2 * x)
+
+
+def env(fn):
+ """Per-sample envelope from a function of time, evaluated every 64 samples."""
+ out = [0.0] * N
+ for s in range(0, N, 64):
+ v = fn(s / SR)
+ e = min(N, s + 64)
+ out[s:e] = [v] * (e - s)
+ return out
+
+
+def mul(a, b):
+ return [x * y for x, y in zip(a, b)]
+
+
+def white(seed):
+ r = random.Random(seed).random
+ return [2.0 * r() - 1.0 for _ in range(N)]
+
+
+def brown(seed, leak=0.997):
+ x = white(seed)
+ out = [0.0] * N
+ y = 0.0
+ for i, v in enumerate(x):
+ y = leak * y + 0.06 * v
+ out[i] = y
+ return out
+
+
+def norm(x, peak=1.0):
+ m = max(1e-9, max(abs(v) for v in x))
+ return [v * peak / m for v in x]
+
+
+def stereo(fn):
+ """Same layer from two seeds: decorrelated left/right."""
+ return fn(1), fn(2)
+
+
+L = [0.0] * N
+Rch = [0.0] * N
+
+
+def add(pair_or_mono, gain=1.0, pan=0.0):
+ if isinstance(pair_or_mono, tuple):
+ l, r = pair_or_mono
+ else:
+ l = r = pair_or_mono
+ gl, gr = gain * math.sqrt(0.5 * (1 - pan)), gain * math.sqrt(0.5 * (1 + pan))
+ for i in range(N):
+ L[i] += l[i] * gl
+ Rch[i] += r[i] * gr
+
+
+def power(t):
+ p = 1 - smooth((t - T_THR) / 0.6) + smooth((t - T_REL) / 0.25)
+ return max(0.0, min(1.0, p))
+
+
+def fly(t):
+ return smooth((t - T_FIN + 0.3) / 0.8) * (1 - smooth((t - T_FOUT) / 0.8))
+
+
+def thump(at, f0=75, f1=38, dur=0.45):
+ out = [0.0] * N
+ s0 = int(at * SR)
+ ph = 0.0
+ for i in range(int(dur * SR)):
+ if s0 + i >= N:
+ break
+ k = i / (dur * SR)
+ ph += 2 * math.pi * (f0 + (f1 - f0) * k) / SR
+ out[s0 + i] = math.sin(ph) * math.exp(-k * 4.5)
+ return out
+
+
+def clicks(at, n=3, gap=0.05, seed=1):
+ out = [0.0] * N
+ rr = random.Random(seed)
+ for c in range(n):
+ s0 = int((at + c * gap) * SR)
+ for i in range(int(0.012 * SR)):
+ if s0 + i < N:
+ out[s0 + i] += (2 * rr.random() - 1) * math.exp(-i / (0.002 * SR))
+ return biquad(out, hp(1800))
+
+
+def burst_env(at, dur):
+ return env(lambda t: math.sin(math.pi * min(1.0, max(0.0, (t - at) / dur))) ** 2 if at <= t <= at + dur else 0.0)
+
+
+# 1. air rush, always
+add(stereo(lambda k: mul(norm(svf(white(10 + k), 900, 0.5)), env(lambda t: 0.8 + 0.2 * math.sin(t * 0.9)))), 0.16)
+
+# 2. the roar: steady, swells and brightens on the fly-through
+def roar_fc(s):
+ t = s / SR
+ return 700 + 2000 * fly(t)
+roar_env = env(lambda t: power(t) * (0.75 + 0.55 * fly(t)) * (1 + 0.6 * (math.exp(-(t - T_REL) / 0.5) if t > T_REL else 0)))
+add(stereo(lambda k: mul(norm(svf(brown(60 + k, 0.995), roar_fc, 0.6)), roar_env)), 0.4)
+sub = [math.sin(2 * math.pi * 36 * i / SR) + 0.5 * math.sin(2 * math.pi * 51 * i / SR + 1.1) for i in range(N)]
+add(mul(sub, env(lambda t: power(t) * (0.8 + 0.2 * math.sin(t * 2.7)))), 0.14)
+
+# 3. turbopump whine, loud while we look at the pumps
+whine = [0.0] * N
+ph = 0.0
+for i in range(N):
+ t = i / SR
+ f = 1500 * (0.2 + 0.8 * power(t))
+ ph += 2 * math.pi * f / SR
+ whine[i] = math.sin(ph) + 0.35 * math.sin(2.01 * ph) + 0.12 * math.sin(3.03 * ph)
+add(mul(norm(whine), env(lambda t: power(t) * (0.25 + 0.75 * smooth((t - T_SPIN + 0.4) / 0.6) * (1 - smooth((t - T_BURN) / 0.8))))), 0.06)
+
+# 4. skirt opens / closes: servo whir + clunks
+for at in (T_OPEN, T_CLOSE):
+ add(mul(norm(svf(white(70), 950, 2.0, "bp")), burst_env(at, 1.3)), 0.12)
+ add(thump(at + 1.25, 140, 70, 0.25), 0.35)
+ add(clicks(at + 1.22, 2, 0.06, int(at * 10)), 0.25)
+
+# 5. fly-through: rising air sweep
+def sweep_fc(s):
+ t = s / SR
+ return 300 + 3200 * smooth((t - T_FIN) / (T_FOUT - T_FIN))
+add(stereo(lambda k: mul(norm(svf(white(80 + k), sweep_fc, 1.4, "bp")), env(fly))), 0.16)
+
+# 6. exploded view: whoosh out, whoosh back, parts lock
+for at in (T_EXP, T_ASM):
+ def wfc(s, at=at):
+ t = s / SR
+ return 400 + 2200 * smooth((t - at) / 1.4)
+ add(stereo(lambda k, at=at: mul(norm(svf(white(90 + k + int(at)), wfc, 1.1, "bp")), burst_env(at, 1.5))), 0.14)
+add(clicks(T_ASM + 1.25, 4, 0.07, 4), 0.3)
+add(thump(T_ASM + 1.3, 120, 60, 0.2), 0.3)
+
+# 7. relight
+add(thump(T_REL, 95, 30, 1.4), 0.8)
+
+# 8. crackle while running
+crk_l, crk_r = [0.0] * N, [0.0] * N
+rr = random.Random(9)
+t = 0.0
+while t < DUR:
+ t += -math.log(1 - rr.random()) / 22.0
+ if power(t) < 0.2:
+ continue
+ s0 = int(t * SR)
+ amp = (0.3 + 0.7 * rr.random()) * power(t) * (1 + fly(t))
+ pan = rr.random()
+ for i in range(int(0.005 * SR)):
+ if s0 + i >= N:
+ break
+ v = amp * (2 * rr.random() - 1) * math.exp(-i / (0.001 * SR))
+ crk_l[s0 + i] += v * (1 - pan)
+ crk_r[s0 + i] += v * pan
+add((biquad(crk_l, hp(1400)), biquad(crk_r, hp(1400))), 0.12)
+# master: gentle soft clip, normalise, write 16-bit stereo
+peak = max(max(abs(v) for v in L), max(abs(v) for v in Rch))
+g = 0.92 / peak
+def sc(v):
+ return math.tanh(1.2 * v) / math.tanh(1.2)
+ap = argparse.ArgumentParser()
+ap.add_argument("-o", "--out", default=os.path.join(HERE, "..", "..", "out", "sims", "engine", "ambient.wav"))
+out = os.path.abspath(ap.parse_args().out)
+os.makedirs(os.path.dirname(out), exist_ok=True)
+frames = bytearray()
+for l, r in zip(L, Rch):
+ for v in (sc(l * g), sc(r * g)):
+ frames += int(max(-1.0, min(1.0, v)) * 32767).to_bytes(2, "little", signed=True)
+with wave.open(out, "wb") as wf:
+ wf.setnchannels(2)
+ wf.setsampwidth(2)
+ wf.setframerate(SR)
+ wf.writeframes(bytes(frames))
+print(f"→ {os.path.relpath(out)} ({DUR} s)")
diff --git a/sims/engine/style.css b/sims/engine/style.css
new file mode 100644
index 0000000..32f8eeb
--- /dev/null
+++ b/sims/engine/style.css
@@ -0,0 +1,21 @@
+.e-ov { position: absolute; left: 0; top: 0; transform-origin: 0 0; pointer-events: none; z-index: 6; color: #fff; font-family: Inter, sans-serif; }
+.e-lines { position: absolute; left: 0; top: 0; }
+.e-top { position: absolute; left: 40px; top: 36px; display: flex; flex-direction: column; gap: 14px; }
+.e-title { font: 700 22px 'JetBrains Mono', monospace; letter-spacing: 0.14em; text-shadow: 0 2px 14px rgba(0,0,0,0.45); }
+.e-ch { display: flex; gap: 10px; }
+.e-ch span { font: 700 18px 'JetBrains Mono', monospace; letter-spacing: 0.14em; padding: 7px 14px; border-radius: 8px; background: rgba(10,10,16,0.42); border: 1px solid rgba(255,255,255,0.16); color: rgba(255,255,255,0.55); }
+.e-ch span.on { background: rgba(255,255,255,0.94); color: #111; border-color: #fff; }
+.e-clock { position: absolute; right: 40px; top: 30px; }
+.e-clock b { font: 700 52px 'JetBrains Mono', monospace; font-variant-numeric: tabular-nums; letter-spacing: -0.02em; text-shadow: 0 2px 18px rgba(0,0,0,0.5); }
+.e-cap { position: absolute; left: 40px; right: 40px; bottom: 118px; display: flex; justify-content: center; opacity: 0; }
+.e-cap span { font: 600 31px/1.32 Inter, sans-serif; text-align: center; padding: 16px 24px; border-radius: 16px; background: rgba(10,10,16,0.62); border: 1px solid rgba(255,255,255,0.12); max-width: 940px; }
+.e-bar { position: absolute; left: 40px; right: 40px; bottom: 70px; height: 5px; border-radius: 3px; background: rgba(255,255,255,0.22); }
+.e-bar i { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 3px; background: #fff; }
+.e-bar em { position: absolute; top: -5px; width: 3px; height: 15px; margin-left: -1px; border-radius: 2px; background: rgba(255,255,255,0.75); }
+.e-wm { position: absolute; right: 40px; bottom: 26px; font: 400 19px 'JetBrains Mono', monospace; color: rgba(255,255,255,0.6); }
+.e-lab { position: absolute; display: flex; flex-direction: column; gap: 3px; padding: 9px 14px; border-radius: 10px; background: rgba(10,10,16,0.66); border: 1px solid rgba(255,255,255,0.18); white-space: nowrap; opacity: 0; }
+.e-lab.l { left: 40px; } .e-lab.r { right: 40px; align-items: flex-end; }
+.e-lab b { display: flex; align-items: center; gap: 9px; font: 700 20px 'JetBrains Mono', monospace; letter-spacing: 0.06em; }
+.e-lab b i { width: 10px; height: 10px; border-radius: 50%; }
+.e-lab span { font: 500 18px Inter, sans-serif; color: rgba(255,255,255,0.72); }
+.e-time { position: absolute; left: 40px; bottom: 26px; font: 600 19px 'JetBrains Mono', monospace; color: rgba(255,255,255,0.6); font-variant-numeric: tabular-nums; }
diff --git a/sims/engine/timeline.json b/sims/engine/timeline.json
new file mode 100644
index 0000000..3688b79
--- /dev/null
+++ b/sims/engine/timeline.json
@@ -0,0 +1,15 @@
+{
+ "duration": 24,
+ "open": 2.4,
+ "feed": 3.0,
+ "spin": 5.6,
+ "burn": 7.8,
+ "flyIn": 9.0,
+ "flyOut": 11.6,
+ "blast": 12.0,
+ "throttle": 14.4,
+ "explode": 15.0,
+ "assemble": 19.0,
+ "relight": 20.5,
+ "close": 21.0
+}
diff --git a/sims/kit/director.js b/sims/kit/director.js
new file mode 100644
index 0000000..aacf2d9
--- /dev/null
+++ b/sims/kit/director.js
@@ -0,0 +1,300 @@
+import {clamp01, easeOutExpo, fmt, hash, smooth} from './util.js';
+
+/**
+ * The director edits a sim to the music: hard cuts between wide and tight
+ * shots on bar lines, punch-ins on kicks, a shake and flash on the drop,
+ * glitches on stage changes, and big readable story captions on the beat.
+ *
+ * Beats come from cfg.beats (sims/beats.py output, injected by capture.mjs).
+ * Without music it runs on a synthetic grid (cfg.director.bpm) so live pages
+ * still feel edited.
+ *
+ * Shots crop the 3D render (crisp re-render of a sub-rectangle) when the sim
+ * uses kit/stage3d; otherwise they scale the target element with CSS.
+ * Sims can return `foci: [{x, y}]` (screen px) in their render info: tight
+ * shots frame those points.
+ *
+ * Story: cfg.story = [{at | bar | drop, text, sub, kind: 'hero'|'num', hold,
+ * from, to, prefix, suffix, tag}]. `drop` is in bars relative to the drop,
+ * `bar` counts bars from the clip start, `hold` is in beats. *word* gets the
+ * accent box.
+ */
+export const DIRECTOR = {
+ enabled: true,
+ bpm: 128,
+ drop: null,
+ hero: null,
+ // cut every N beats before / after the drop
+ cutBeats: [4, 2],
+ shots: [
+ {z: 1},
+ {z: 1.75, f: 0},
+ {z: 1.3, f: 1},
+ {z: 2.2, f: 2},
+ {z: 1.12, f: 0},
+ {z: 1.6, f: 1},
+ ],
+ punch: [0.03, 0.07],
+ shake: 1,
+ flash: 1,
+ glitch: 1,
+ target: '#gl',
+};
+
+const before = (arr, t) => {
+ let lo = 0;
+ let hi = arr.length;
+ while (lo < hi) {
+ const m = (lo + hi) >> 1;
+ if (arr[m] <= t) lo = m + 1;
+ else hi = m;
+ }
+ return lo - 1;
+};
+
+export function createDirector(app, cfg) {
+ const d = {...DIRECTOR, ...(cfg.director || {})};
+ const D = cfg.duration;
+ const music = cfg.beats && cfg.beats.beats && cfg.beats.beats.length > 4;
+ const spb = music ? 60 / cfg.beats.bpm : 60 / d.bpm;
+ const beats = music ? cfg.beats.beats : Array.from({length: Math.ceil(D / spb) + 8}, (_, i) => i * spb);
+ // pad the grid past both ends so lookups never fall off
+ while (beats[0] > 0) beats.unshift(beats[0] - spb);
+ while (beats[beats.length - 1] < D + 4 * spb) beats.push(beats[beats.length - 1] + spb);
+ let downs = music && cfg.beats.downbeats.length ? cfg.beats.downbeats.slice() : beats.filter((_, i) => i % 4 === 0);
+ while (downs[0] > 0) downs.unshift(downs[0] - 4 * spb);
+ while (downs[downs.length - 1] < D + 8 * spb) downs.push(downs[downs.length - 1] + 4 * spb);
+ const kicks = music ? cfg.beats.kicks : beats.map((b) => [b, 0.8]);
+ const kickT = kicks.map((k) => k[0]);
+ const energy = music ? cfg.beats.barEnergy : null;
+ const drop = (music && cfg.beats.drop) ?? d.drop ?? Math.round((0.4 * D) / (4 * spb)) * 4 * spb;
+ const dropBar = before(downs, drop + 0.01);
+
+ const barTime = (b) => downs[Math.max(0, Math.min(downs.length - 1, b))];
+
+ // ---- time warp: the sim's hero moment lands on the drop
+ const warp = (t) => {
+ if (d.hero == null || !d.enabled) return t;
+ const h = d.hero;
+ if (t <= drop) return (t / drop) * h;
+ return h + ((t - drop) / (D - drop)) * (D - h);
+ };
+
+ const beat = (t) => {
+ const sh = shotAt(t);
+ const bi = before(beats, t);
+ const b0 = beats[Math.max(0, bi)];
+ const b1 = beats[bi + 1] ?? b0 + spb;
+ const ri = before(downs, t);
+ const r0 = downs[Math.max(0, ri)];
+ const r1 = downs[ri + 1] ?? r0 + 4 * spb;
+ const ki = before(kickT, t);
+ const kick = ki >= 0 ? kicks[ki][1] * Math.exp(-(t - kicks[ki][0]) / 0.11) : 0;
+ const down = Math.exp(-(t - r0) / 0.18);
+ return {
+ music,
+ bpm: 60 / spb,
+ beat: bi,
+ beatPhase: clamp01((t - b0) / (b1 - b0)),
+ bar: ri,
+ barPhase: clamp01((t - r0) / (r1 - r0)),
+ kick,
+ down,
+ energy: energy ? energy[Math.max(0, Math.min(energy.length - 1, ri))] ?? 1 : 1,
+ drop,
+ sinceDrop: t - drop,
+ isDrop: t >= drop,
+ // current shot: sims may change camera angle per shot index
+ shot: sh.k,
+ shotZ: sh.shot.z || 1,
+ };
+ };
+
+ // ---- story timing
+ const story = (cfg.story || []).map((s, i) => {
+ const start = s.at ?? (s.bar != null ? barTime(s.bar) : s.drop != null ? barTime(dropBar + s.drop) : 0);
+ const b0 = before(beats, start + 0.02);
+ const hold = s.hold ?? 8;
+ const end = s.end ?? beats[Math.min(beats.length - 1, b0 + hold)] ?? start + hold * spb;
+ return {...s, i, start, end, b0};
+ });
+
+ // ---- DOM layers
+ app.insertAdjacentHTML(
+ 'beforeend',
+ `<canvas class="dir-glitch"></canvas><div class="dir-flash"></div><div class="dir-story"></div>`,
+ );
+ const gcv = app.querySelector('.dir-glitch');
+ const gctx = gcv.getContext('2d');
+ const flash = app.querySelector('.dir-flash');
+ const storyEl = app.querySelector('.dir-story');
+
+ let foci = [];
+ let crop = {z: 1, x0: 0, y0: 0};
+ let built = -1;
+ let parts = null;
+
+ const stageCuts = (cfg.stages || []).map((s) => s.at).filter((a) => a > 0.2);
+
+ const dropBeat = before(beats, drop + 0.01);
+ function shotAt(t) {
+ const bi = before(beats, t);
+ const isDrop = t >= drop;
+ const every = isDrop ? d.cutBeats[1] : d.cutBeats[0];
+ // the first beats of the drop always open wide
+ if (isDrop && bi - dropBeat < every) return {shot: d.shots[0], k: 0};
+ const rel = isDrop ? bi - dropBeat : bi - before(beats, 0.01);
+ const k = Math.floor(rel / every) + (isDrop ? 1000 : 0);
+ return {shot: d.shots[((k % d.shots.length) + d.shots.length) % d.shots.length], k};
+ }
+
+ const target = () => document.querySelector(d.target);
+
+ return {
+ warp,
+ beat,
+ /** Before the sim renders: set this frame's crop. */
+ pre(t) {
+ if (!d.enabled) return;
+ const {shot} = shotAt(t);
+ const b = beat(t);
+ const punch = 1 + (b.isDrop ? d.punch[1] : d.punch[0]) * b.kick;
+ const drift = 1 + 0.035 * b.barPhase;
+ let z = (shot.z || 1) * punch * (shot.z > 1 ? drift : 1);
+ const vw = innerWidth;
+ const vh = innerHeight;
+ let f = {x: vw / 2, y: vh / 2};
+ if (shot.z > 1 && foci.length) f = foci[(shot.f ?? 0) % foci.length];
+ else if (window.__STAGE) {
+ const vp = window.__STAGE.hudViewport();
+ f = {x: vw / 2, y: (vp.top + vh - vp.bottom) / 2};
+ }
+ // drop shake (decays over ~0.6 s)
+ const sk = d.shake * (b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.25) : 0);
+ const sx = sk * (hash(t * 91.7) - 0.5) * 26;
+ const sy = sk * (hash(t * 53.3 + 7) - 0.5) * 26;
+ const st = window.__STAGE;
+ if (st) {
+ crop = st.setCrop(z, f.x + sx, f.y + sy);
+ } else {
+ const el = target();
+ if (el) {
+ el.style.transformOrigin = `${f.x}px ${f.y}px`;
+ el.style.transform = `translate(${sx}px, ${sy}px) scale(${z})`;
+ }
+ crop = {z: 1, x0: 0, y0: 0};
+ }
+ },
+ /** After the sim renders: remember its foci, draw overlays and the story. */
+ post(t, info = {}) {
+ if (!d.enabled) return;
+ if (info.foci && info.foci.length) {
+ // convert from this frame's cropped screen back to base screen coords
+ foci = info.foci.map((p) => ({x: crop.x0 + p.x / crop.z, y: crop.y0 + p.y / crop.z}));
+ }
+ const b = beat(t);
+ const vw = innerWidth;
+ const vh = innerHeight;
+
+ // flash: accent bloom on downbeats after the drop, white hit on the drop
+ const dropHit = b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.22) : 0;
+ const onBar = b.isDrop ? 0.16 * b.down * b.energy : 0;
+ flash.style.opacity = String(d.flash * Math.min(0.85, dropHit * 0.7 + onBar));
+
+ // glitch: 3 frames around each stage change and the drop
+ const gl = [...stageCuts, b.drop].some((c) => t >= c - 0.03 && t < c + 0.1);
+ if (gcv.width !== vw || gcv.height !== vh) {
+ gcv.width = vw;
+ gcv.height = vh;
+ }
+ gctx.clearRect(0, 0, vw, vh);
+ const src = document.getElementById('gl');
+ if (gl && d.glitch && src && src.width) {
+ const n = 7;
+ for (let i = 0; i < n; i++) {
+ const y = Math.floor(hash(t * 13 + i) * vh);
+ const h = 6 + Math.floor(hash(t * 7 + i * 3) * 60);
+ const dx = (hash(t * 31 + i * 5) - 0.5) * 120;
+ const sx = src.width / vw;
+ gctx.globalAlpha = 0.9;
+ gctx.drawImage(src, 0, y * sx, src.width, h * sx, dx, y, vw, h);
+ }
+ gctx.globalAlpha = 0.25;
+ gctx.fillStyle = cfg.accent;
+ gctx.fillRect(0, Math.floor(hash(t * 3.3) * vh), vw, 3 + hash(t) * 10);
+ gctx.globalAlpha = 1;
+ }
+
+ // ---- story
+ const cur = story.find((s) => t >= s.start && t < s.end);
+ if (!cur) {
+ storyEl.style.opacity = '0';
+ return;
+ }
+ if (built !== cur.i) {
+ built = cur.i;
+ const words = (cur.text || '').split(/\s+/).filter(Boolean);
+ storyEl.innerHTML = `<div class="cap ${cur.kind || 'hero'}">
+ ${cur.tag ? `<div class="cap-tag">${cur.tag}</div>` : ''}
+ <div class="cap-main">${
+ cur.kind === 'num'
+ ? `<span class="w"><span class="n"></span></span>`
+ : (() => {
+ // *several words* → each word gets the accent box
+ let on = false;
+ return words
+ .map((w) => {
+ const open = w.startsWith('*');
+ const close = w.endsWith('*') && (w.length > 1 || on);
+ if (open) on = true;
+ const hl = on;
+ if (close) on = false;
+ return `<span class="w${hl ? ' hl' : ''}">${w.replace(/^\*|\*$/g, '')}</span>`;
+ })
+ .join(' ');
+ })()
+ }</div>
+ ${cur.sub ? `<div class="cap-sub"></div>` : ''}
+ </div>`;
+ parts = {
+ words: [...storyEl.querySelectorAll('.w')],
+ num: storyEl.querySelector('.n'),
+ sub: storyEl.querySelector('.cap-sub'),
+ main: storyEl.querySelector('.cap-main'),
+ };
+ }
+ const vp = window.__HUDVP ? window.__HUDVP() : {top: 0, bottom: 0};
+ storyEl.style.top = `${vp.top}px`;
+ storyEl.style.bottom = `${vp.bottom}px`;
+ storyEl.style.opacity = '1';
+ const ex = clamp01((t - (cur.end - 0.18)) / 0.18);
+ // words slam in on successive beats (half-beats if the text is long)
+ const step = parts.words.length > 4 ? 0.5 : 1;
+ let lastIn = cur.start;
+ parts.words.forEach((w, i) => {
+ const bi = cur.b0 + i * step;
+ const wt = Math.floor(bi) === bi ? beats[bi] : (beats[Math.floor(bi)] + beats[Math.ceil(bi)]) / 2;
+ const k = cur.start <= 0.001 ? 1 : clamp01((t - wt) / 0.12);
+ lastIn = Math.max(lastIn, wt);
+ const s = 1 + 0.35 * (1 - easeOutExpo(k)) + 0.03 * b.kick;
+ w.style.opacity = String(k > 0 ? 1 : 0);
+ w.style.transform = `scale(${s}) translateY(${ex * -0.25}em)`;
+ w.style.filter = k < 1 ? `blur(${(1 - k) * 8}px)` : 'none';
+ });
+ if (cur.kind === 'num' && parts.num) {
+ const roll = cur.roll ?? 6;
+ const k = easeOutExpo(clamp01((t - cur.start) / (roll * spb)));
+ const v = cur.from + (cur.to - cur.from) * k;
+ parts.num.textContent = `${cur.prefix ?? ''}${fmt(v, cur.decimals ?? 0)}${cur.suffix ?? ''}`;
+ lastIn = cur.start + roll * spb * 0.6;
+ }
+ if (parts.sub) {
+ const n = Math.floor(Math.max(0, t - lastIn - 0.15) / 0.022);
+ parts.sub.textContent = cur.sub.slice(0, n);
+ }
+ parts.main.style.opacity = String(1 - ex);
+ if (parts.sub) parts.sub.style.opacity = String(1 - ex);
+ storyEl.firstElementChild.style.transform = `translateX(${ex * (hash(t * 41) - 0.5) * 40}px)`;
+ },
+ };
+}
diff --git a/sims/kit/hud.js b/sims/kit/hud.js
new file mode 100644
index 0000000..289f0f5
--- /dev/null
+++ b/sims/kit/hud.js
@@ -0,0 +1,194 @@
+import {clamp01, pad} from './util.js';
+
+/**
+ * Instrument-style HUD: header with stage/command/clock, annotations over the
+ * viewport, a terminal log and a side panel (minimap + stats) at the bottom.
+ * Everything is derived from `t` and the config's stages, so it's deterministic.
+ *
+ * cfg.stages: [{at, name, cmd, logs: [string]}]. A log line starting with "!"
+ * is highlighted in the accent. {key} tokens are replaced from `facts`.
+ */
+export function createHud(root, cfg) {
+ const h = cfg.hud;
+ root.insertAdjacentHTML(
+ 'beforeend',
+ `<div class="hud">
+ <div class="ann"></div>
+ <div class="wm"></div>
+ <div class="hdr">
+ <div class="row row1">
+ <div class="title"><i class="bar"></i><span class="t"></span></div>
+ <div class="sub"></div>
+ <div class="right"></div>
+ </div>
+ <div class="row row2">
+ <div class="stage accent"></div>
+ <div class="cmd"></div>
+ <div class="time accent"></div>
+ </div>
+ <div class="prog"><i></i></div>
+ </div>
+ <div class="bot">
+ <div class="term">
+ <div class="thead">
+ <span class="host accent"></span><span class="path"></span>
+ <span class="status accent"><i></i><span></span></span>
+ </div>
+ <div class="prompt"></div>
+ <div class="logs"></div>
+ <div class="tfoot"></div>
+ </div>
+ <div class="side">
+ <div class="shead accent"></div>
+ <canvas class="mini"></canvas>
+ <div class="stats"></div>
+ <div class="sfoot"></div>
+ </div>
+ <div class="baseline"><i></i></div>
+ </div>
+ </div>`,
+ );
+ const $ = (s) => root.querySelector(s);
+ const el = {
+ hud: $('.hud'),
+ ann: $('.ann'),
+ stage: $('.row2 .stage'),
+ cmd: $('.row2 .cmd'),
+ time: $('.row2 .time'),
+ prog: $('.prog i'),
+ prompt: $('.prompt'),
+ logs: $('.logs'),
+ tfoot: $('.tfoot'),
+ status: $('.thead .status span'),
+ stats: $('.stats'),
+ sfoot: $('.sfoot'),
+ base: $('.baseline i'),
+ mini: $('.mini'),
+ };
+ $('.title .t').textContent = h.title;
+ $('.sub').textContent = h.subtitle;
+ $('.right').textContent = h.right;
+ $('.wm').textContent = cfg.watermark;
+ $('.thead .host').textContent = h.host;
+ $('.thead .path').textContent = h.path;
+ $('.shead').textContent = h.sideTitle;
+
+ const stages = cfg.stages;
+ const D = cfg.duration;
+ const TYPE_CMD = 0.028;
+ const TYPE_LOG = 0.011;
+
+ // Log line schedule: each stage types its command, then its lines spread
+ // over the stage.
+ const lines = [];
+ stages.forEach((s, i) => {
+ const end = i + 1 < stages.length ? stages[i + 1].at : D;
+ const t0 = s.at + 0.25 + s.cmd.length * TYPE_CMD + 0.2;
+ const n = s.logs.length;
+ const gap = Math.min(0.8, Math.max(0.22, (end - t0 - 0.4) / Math.max(1, n)));
+ s.logs.forEach((text, j) => lines.push({at: t0 + j * gap, text, stage: i}));
+ });
+
+ const stageAt = (t) => {
+ let i = 0;
+ while (i + 1 < stages.length && stages[i + 1].at <= t) i++;
+ return i;
+ };
+ const fill = (text, facts) => text.replace(/\{(\w+)\}/g, (m, k) => (k in facts ? facts[k] : m));
+ const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+
+ let lastStats = '';
+ let lastLogs = '';
+ const annPool = [];
+
+ return {
+ minimap: el.mini,
+ stageAt,
+ setVisible(v) {
+ el.hud.classList.toggle('hidden', !v);
+ },
+ /** Viewport between header and bottom panel, in CSS px. */
+ viewport() {
+ const fs = parseFloat(getComputedStyle(document.documentElement).fontSize);
+ return {top: 13.4 * fs, bottom: 30.5 * fs};
+ },
+ render(t, frame, info = {}) {
+ const facts = {...cfg.facts, ...(info.facts || {})};
+ const si = stageAt(t);
+ const s = stages[si];
+ const dt = t - s.at;
+ const typed = Math.floor(Math.max(0, dt - 0.15) / TYPE_CMD);
+ const cmd = fill(s.cmd, facts);
+ const typing = typed < cmd.length;
+ const caretOn = typing || Math.floor(t * 2.4) % 2 === 0;
+
+ el.stage.textContent = `${pad(si + 1, 2)} / ${s.name}`;
+ el.cmd.textContent = cmd.slice(0, typed);
+ el.time.textContent = `${t.toFixed(2).padStart(5, '0')} / ${D}`;
+ el.prog.style.width = `${(clamp01(t / D) * 100).toFixed(2)}%`;
+ el.base.style.width = `${(clamp01(dt / ((stages[si + 1]?.at ?? D) - s.at)) * 100).toFixed(2)}%`;
+ el.prompt.innerHTML = `<span class="accent">&gt;</span> ${esc(cmd.slice(0, typed))}${
+ caretOn ? '<i class="caret"></i>' : ''
+ }`;
+
+ const shown = lines.filter((l) => l.at <= t);
+ const rows = shown.slice(-h.logRows);
+ const offset = shown.length - rows.length;
+ const html = rows
+ .map((l, j) => {
+ const full = fill(l.text, facts);
+ const hl = full.startsWith('!');
+ const text = hl ? full.slice(1) : full;
+ const n = Math.floor((t - l.at) / TYPE_LOG);
+ const isLast = j === rows.length - 1 && n < text.length;
+ return `<div><span class="ln">${pad(offset + j, 3)}</span><span class="${hl ? 'hl' : ''}">${esc(
+ text.slice(0, n),
+ )}</span>${isLast ? '<i class="caret"></i>' : ''}</div>`;
+ })
+ .join('');
+ if (html !== lastLogs) {
+ el.logs.innerHTML = html;
+ lastLogs = html;
+ }
+
+ el.tfoot.textContent = `frame ${pad(frame, 4)} delta ${pad((dt * 7.3) % 100, 2)} / ${s.name.toLowerCase()}`;
+ el.status.textContent = info.status ?? (t >= D - 0.05 ? 'DONE' : 'RUNNING');
+ el.sfoot.textContent = `view ${pad(si + 1, 2)} / ${pad(h.views, 2)} seed ${cfg.seed} · t+${dt.toFixed(2)}s`;
+
+ const stats = (info.stats || []).map((x) => `<div>${esc(x.label)}<b>${esc(String(x.value))}</b></div>`).join('');
+ if (stats !== lastStats) {
+ el.stats.innerHTML = stats;
+ lastStats = stats;
+ }
+
+ const anns = info.annotations || [];
+ while (annPool.length < anns.length) {
+ const d = document.createElement('div');
+ el.ann.appendChild(d);
+ annPool.push(d);
+ }
+ annPool.forEach((d, i) => {
+ const a = anns[i];
+ if (!a) {
+ d.style.display = 'none';
+ return;
+ }
+ d.style.display = '';
+ d.className = a.cls || '';
+ d.style.left = `${a.x}px`;
+ d.style.top = `${a.y}px`;
+ d.style.opacity = a.opacity ?? 1;
+ if (a.html !== undefined) d.innerHTML = a.html;
+ else d.textContent = a.text;
+ // keep labels inside the viewport (between header and bottom panel)
+ const vp = this.viewport();
+ const w = d.offsetWidth;
+ const hh = d.offsetHeight;
+ const x = Math.min(Math.max(a.x, 8), innerWidth - w - 40);
+ const y = Math.min(Math.max(a.y, vp.top + hh / 2 + 8), innerHeight - vp.bottom - hh / 2 - 8);
+ d.style.left = `${x}px`;
+ d.style.top = `${y}px`;
+ });
+ },
+ };
+}
diff --git a/sims/kit/runtime.js b/sims/kit/runtime.js
new file mode 100644
index 0000000..82b6044
--- /dev/null
+++ b/sims/kit/runtime.js
@@ -0,0 +1,162 @@
+import {createDirector, DIRECTOR} from './director.js';
+import {createHud} from './hud.js';
+import {merge} from './util.js';
+
+/** Config every sim starts from; a sim's defaults and the post config merge over it. */
+export const BASE = {
+ duration: 30,
+ fps: 30,
+ seed: 746337560,
+ theme: 'dark',
+ accent: '#f2b632',
+ watermark: 'X: @whaleyxbt',
+ hud: {
+ title: 'AGENT MESH',
+ subtitle: '/ SIMULATION',
+ right: 'VISUAL SIMULATION',
+ host: 'agent@local',
+ path: '~/session-01',
+ sideTitle: 'LOCAL VIEW',
+ logRows: 5,
+ views: 10,
+ },
+ stages: [{at: 0, name: 'RUN', cmd: 'run', logs: []}],
+ facts: {},
+ director: DIRECTOR,
+ story: [],
+ beats: null,
+};
+
+const fromBase64 = (s) => decodeURIComponent(escape(atob(s.replace(/-/g, '+').replace(/_/g, '/'))));
+
+/**
+ * Config sources, later wins: BASE, the sim's defaults, window.__SIM_CONFIG
+ * (injected by the capture script), ?config=<base64 json>, and a few plain
+ * query params (?title= ?accent= ?seed= ?theme= ?duration=).
+ */
+export function loadConfig(defaults) {
+ let cfg = merge(BASE, defaults);
+ if (window.__SIM_CONFIG) cfg = merge(cfg, window.__SIM_CONFIG);
+ const q = new URLSearchParams(location.search);
+ if (q.get('config')) {
+ try {
+ cfg = merge(cfg, JSON.parse(fromBase64(q.get('config'))));
+ } catch (e) {
+ console.warn('bad ?config', e);
+ }
+ }
+ if (q.get('title')) cfg = merge(cfg, {hud: {title: q.get('title')}});
+ if (q.get('accent')) cfg.accent = '#' + q.get('accent').replace('#', '');
+ if (q.get('seed')) cfg.seed = Number(q.get('seed'));
+ if (q.get('theme')) cfg.theme = q.get('theme');
+ if (q.get('duration')) cfg.duration = Number(q.get('duration'));
+ if (q.has('nodirector')) cfg.director = {...cfg.director, enabled: false};
+ return cfg;
+}
+
+/**
+ * Boots a sim. `setup({cfg, canvas, hud, capture})` returns (or resolves to)
+ * `{render(t) -> hudInfo, resize()}`. render must be a pure function of t.
+ *
+ * Live mode loops in real time. Keys: space pause, h hide HUD, f fullscreen,
+ * r restart, ←/→ seek 2 s, 1–9 jump to a stage.
+ * Capture mode (?capture or window.__CAPTURE) exposes window.SIM.render(t).
+ */
+export async function runSim(defaults, setup) {
+ const cfg = loadConfig(defaults);
+ const q = new URLSearchParams(location.search);
+ const capture = !!window.__CAPTURE || q.has('capture');
+ const root = document.documentElement;
+ root.dataset.theme = cfg.theme;
+ root.style.setProperty('--accent', cfg.accent);
+ document.title = `${cfg.hud.title} ${cfg.hud.subtitle}`.trim();
+
+ const scale = () => {
+ root.style.fontSize = `${10 * Math.min(innerWidth / 1080, innerHeight / 1350)}px`;
+ };
+ scale();
+
+ const app = document.getElementById('app');
+ const canvas = document.createElement('canvas');
+ canvas.id = 'gl';
+ app.appendChild(canvas);
+ // cfg.hud.enabled === false: no instrument chrome (UI demos, infographics).
+ const hud =
+ cfg.hud.enabled === false
+ ? {minimap: null, stageAt: () => 0, setVisible() {}, viewport: () => ({top: 0, bottom: 0}), render() {}}
+ : createHud(app, cfg);
+
+ await Promise.all([
+ document.fonts.load('400 20px "JetBrains Mono"'),
+ document.fonts.load('600 20px "JetBrains Mono"'),
+ document.fonts.load('800 20px "Inter"'),
+ ]).catch(() => {});
+
+ window.__HUDVP = () => hud.viewport();
+ const sim = await setup({cfg, canvas, hud, capture});
+ const dir = createDirector(app, cfg);
+ // The sim and HUD run on warped time (hero lands on the drop); the
+ // director's cuts, punches and story run on real (music) time.
+ const draw = (t) => {
+ const tw = dir.warp(t);
+ dir.pre(t);
+ const info = sim.render(tw, dir.beat(t)) || {};
+ hud.render(tw, Math.round(t * cfg.fps), info);
+ dir.post(t, info);
+ };
+
+ let cur = 0;
+ let paused = false;
+ const resize = () => {
+ scale();
+ sim.resize?.();
+ if (paused || capture) draw(cur);
+ };
+ addEventListener('resize', resize);
+ resize();
+
+ window.SIM = {
+ cfg,
+ duration: cfg.duration,
+ fps: cfg.fps,
+ ready: true,
+ render: (t) => {
+ cur = t;
+ draw(t);
+ },
+ };
+ if (capture) {
+ draw(0);
+ return;
+ }
+
+ let start = performance.now();
+ const seek = (t) => {
+ cur = ((t % cfg.duration) + cfg.duration) % cfg.duration;
+ start = performance.now() - cur * 1000;
+ };
+ let hudOn = true;
+ addEventListener('keydown', (e) => {
+ if (e.key === ' ') {
+ paused = !paused;
+ if (!paused) seek(cur);
+ } else if (e.key === 'h') {
+ hudOn = !hudOn;
+ hud.setVisible(hudOn);
+ } else if (e.key === 'f') {
+ if (document.fullscreenElement) document.exitFullscreen();
+ else document.documentElement.requestFullscreen();
+ } else if (e.key === 'r') seek(0);
+ else if (e.key === 'ArrowRight') seek(cur + 2);
+ else if (e.key === 'ArrowLeft') seek(cur - 2);
+ else if (/^[1-9]$/.test(e.key) && cfg.stages[+e.key - 1]) seek(Math.max(0, cfg.stages[+e.key - 1].at));
+ else return;
+ e.preventDefault();
+ });
+ const loop = (now) => {
+ if (!paused) cur = Math.max(0, (now - start) / 1000) % cfg.duration;
+ draw(cur);
+ requestAnimationFrame(loop);
+ };
+ requestAnimationFrame(loop);
+}
diff --git a/sims/kit/stage3d.js b/sims/kit/stage3d.js
new file mode 100644
index 0000000..c69fffe
--- /dev/null
+++ b/sims/kit/stage3d.js
@@ -0,0 +1,108 @@
+import * as THREE from 'three';
+import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';
+import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';
+import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';
+import {UnrealBloomPass} from 'three/addons/postprocessing/UnrealBloomPass.js';
+
+/**
+ * Renderer + scene + camera + bloom. The camera's projection centre is shifted
+ * to the middle of the HUD viewport (between header and bottom panel), so the
+ * subject is centred in the visible area, not behind the terminal.
+ */
+export function createStage(canvas, hud, opts = {}) {
+ const {
+ bg = '#09090a',
+ fov = 38,
+ bloom = {strength: 0.85, radius: 0.55, threshold: 0.62},
+ capture = false,
+ exposure = 1,
+ } = opts;
+ const renderer = new THREE.WebGLRenderer({
+ canvas,
+ antialias: false,
+ preserveDrawingBuffer: true,
+ powerPreference: 'high-performance',
+ });
+ renderer.setClearColor(new THREE.Color(bg), 1);
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = exposure;
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(bg);
+ const camera = new THREE.PerspectiveCamera(fov, 1, 0.5, 6000);
+
+ const target = new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 4});
+ const composer = new EffectComposer(renderer, target);
+ composer.addPass(new RenderPass(scene, camera));
+ const bloomPass = new UnrealBloomPass(new THREE.Vector2(4, 4), bloom.strength, bloom.radius, bloom.threshold);
+ composer.addPass(bloomPass);
+ composer.addPass(new OutputPass());
+
+ const size = {w: 1, h: 1, centre: 0.5};
+ // Director crop: render a sub-rectangle of the base view (crisp punch-ins).
+ const crop = {z: 1, fx: 0, fy: 0, x0: 0, y0: 0};
+ const applyView = () => {
+ const {w, h, centre} = size;
+ const offY = h / 2 - centre;
+ if (crop.z <= 1.0001) {
+ crop.x0 = 0;
+ crop.y0 = 0;
+ camera.setViewOffset(w, h, 0, offY, w, h);
+ } else {
+ const cw = w / crop.z;
+ const ch = h / crop.z;
+ crop.x0 = Math.min(Math.max(crop.fx - cw / 2, 0), w - cw);
+ crop.y0 = Math.min(Math.max(crop.fy - ch / 2, 0), h - ch);
+ camera.setViewOffset(w, h, crop.x0, offY + crop.y0, cw, ch);
+ }
+ camera.updateProjectionMatrix();
+ };
+ const resize = () => {
+ const w = canvas.clientWidth || innerWidth;
+ const h = canvas.clientHeight || innerHeight;
+ const pr = capture ? 1 : Math.min(devicePixelRatio || 1, 2);
+ size.w = w;
+ size.h = h;
+ renderer.setPixelRatio(pr);
+ renderer.setSize(w, h, false);
+ composer.setPixelRatio(pr);
+ composer.setSize(w, h);
+ const vp = hud.viewport();
+ size.centre = (vp.top + (h - vp.bottom)) / 2;
+ camera.aspect = w / h;
+ applyView();
+ };
+ /** Zoom z around base-screen point (fx, fy); returns {z, x0, y0} for mapping back. */
+ const setCrop = (z, fx, fy) => {
+ crop.z = Math.max(1, z);
+ crop.fx = fx;
+ crop.fy = fy;
+ applyView();
+ return {z: crop.z, x0: crop.x0, y0: crop.y0};
+ };
+
+ const v = new THREE.Vector3();
+ /** World point → CSS px on screen, plus whether it's in front of the camera. */
+ const project = (p) => {
+ v.set(p[0] ?? p.x, p[1] ?? p.y, p[2] ?? p.z).project(camera);
+ return {x: (v.x * 0.5 + 0.5) * size.w, y: (-v.y * 0.5 + 0.5) * size.h, visible: v.z < 1};
+ };
+
+ const st = {
+ THREE,
+ renderer,
+ scene,
+ camera,
+ composer,
+ bloomPass,
+ size,
+ resize,
+ project,
+ render: () => composer.render(),
+ setCrop,
+ hudViewport: () => hud.viewport(),
+ };
+ window.__STAGE = st;
+ return st;
+}
diff --git a/sims/kit/style.css b/sims/kit/style.css
new file mode 100644
index 0000000..7bf7ca8
--- /dev/null
+++ b/sims/kit/style.css
@@ -0,0 +1,137 @@
+/* HUD chrome shared by every sim. 1rem = 10px at the 1080x1350 reference
+ size; runtime sets html font-size from the viewport so it scales. */
+
+:root {
+ --bg: #09090a;
+ --fg: #ece6d6;
+ --dim: rgba(236, 230, 214, 0.64);
+ --mute: rgba(236, 230, 214, 0.38);
+ --faint: rgba(236, 230, 214, 0.16);
+ --line: rgba(236, 230, 214, 0.14);
+ --panel: rgba(9, 9, 10, 0.9);
+ --accent: #f2b632;
+ --top: 13.4rem;
+ --bot: 30.5rem;
+}
+:root[data-theme='light'] {
+ --bg: #f3f2ee;
+ --fg: #151515;
+ --dim: rgba(21, 21, 21, 0.66);
+ --mute: rgba(21, 21, 21, 0.42);
+ --faint: rgba(21, 21, 21, 0.16);
+ --line: rgba(21, 21, 21, 0.16);
+ --panel: rgba(243, 242, 238, 0.93);
+}
+
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; background: var(--bg); overflow: hidden; }
+#app {
+ position: fixed; inset: 0; color: var(--fg);
+ font-family: 'JetBrains Mono', ui-monospace, monospace;
+ font-variant-ligatures: none; -webkit-font-smoothing: antialiased;
+}
+#gl { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.hud { position: absolute; inset: 0; pointer-events: none; }
+.hud.hidden { display: none; }
+.accent { color: var(--accent); }
+
+/* header */
+.hdr {
+ position: absolute; left: 0; right: 0; top: 0; height: var(--top);
+ padding: 2.4rem 2.8rem 0;
+ background: linear-gradient(var(--bg) 0%, var(--bg) 78%, transparent 100%);
+}
+.row { display: flex; align-items: baseline; white-space: nowrap; }
+.row1 { gap: 5.6rem; }
+.title { display: flex; align-items: center; gap: 1.3rem; font-size: 3.6rem; font-weight: 600; letter-spacing: 0.04em; }
+.title .bar { display: inline-block; width: 0.75rem; height: 3.6rem; background: var(--accent); }
+.sub { font-size: 1.75rem; color: var(--dim); letter-spacing: 0.08em; }
+.right { margin-left: auto; font-size: 1.6rem; color: var(--dim); letter-spacing: 0.1em; }
+.row2 { margin-top: 2rem; font-size: 1.95rem; }
+.row2 .stage { width: 21rem; letter-spacing: 0.05em; }
+.row2 .cmd { color: var(--fg); }
+.row2 .time { margin-left: auto; letter-spacing: 0.05em; }
+.prog { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 1.2rem; height: 0.35rem; }
+.prog i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
+
+/* viewport overlays */
+.ann { position: absolute; inset: 0; overflow: hidden; }
+.ann div {
+ position: absolute; transform: translate(1.4rem, -50%); white-space: nowrap;
+ font-size: 1.7rem; letter-spacing: 0.04em; color: var(--fg);
+ text-shadow: 0 0 0.6rem var(--bg), 0 0 1.2rem var(--bg);
+}
+.ann div.a { color: var(--accent); }
+.ann div.box {
+ padding: 0.8rem 1.1rem; border: 1px solid var(--line); background: var(--panel);
+ text-shadow: none; line-height: 1.45; font-size: 1.55rem;
+}
+.ann div.box b { color: var(--accent); font-weight: 600; }
+.wm {
+ position: absolute; right: 3rem; bottom: calc(var(--bot) + 1.6rem);
+ font-size: 2.3rem; letter-spacing: 0.06em; color: var(--fg); opacity: 0.3;
+}
+
+/* bottom panel */
+.bot {
+ position: absolute; left: 0; right: 0; bottom: 0; height: var(--bot);
+ display: flex; border-top: 1px solid var(--line); background: var(--panel);
+ padding: 2rem 2.8rem 1.6rem;
+}
+.term { flex: 1; min-width: 0; display: flex; flex-direction: column; padding-right: 2.6rem; }
+.thead { display: flex; align-items: baseline; gap: 2.4rem; font-size: 1.75rem; white-space: nowrap; }
+.thead .host { font-size: 2.1rem; }
+.thead .path { color: var(--dim); }
+.thead .status { margin-left: auto; font-size: 1.5rem; letter-spacing: 0.1em; display: flex; align-items: center; gap: 0.9rem; }
+.thead .status i { width: 1rem; height: 1rem; border-radius: 50%; background: var(--accent); display: inline-block; }
+.prompt { margin-top: 1.9rem; font-size: 2.2rem; white-space: nowrap; overflow: hidden; }
+.logs { margin-top: 1.1rem; font-size: 1.85rem; line-height: 1.52; flex: 1; overflow: hidden; }
+.logs div { white-space: nowrap; overflow: hidden; text-overflow: clip; }
+.logs .ln { color: var(--mute); display: inline-block; width: 6.4rem; }
+.logs .hl { color: var(--accent); }
+.caret { display: inline-block; width: 0.95em; height: 1.05em; vertical-align: -0.15em; background: var(--accent); margin-left: 0.15em; }
+.tfoot { font-size: 1.35rem; color: var(--mute); white-space: nowrap; letter-spacing: 0.04em; }
+.side {
+ width: 31%; border-left: 1px solid var(--line); padding-left: 2.2rem;
+ display: flex; flex-direction: column;
+}
+.shead { font-size: 1.45rem; letter-spacing: 0.12em; }
+.mini { width: 100%; flex: 1; min-height: 0; display: block; margin: 0.8rem 0; }
+.stats { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem 1.4rem; font-size: 1.35rem; color: var(--mute); }
+.stats b { display: block; font-size: 2rem; color: var(--fg); font-weight: 600; letter-spacing: 0.02em; }
+.sfoot { margin-top: 0.8rem; font-size: 1.3rem; color: var(--mute); letter-spacing: 0.05em; }
+.baseline { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 0.9rem; height: 0.25rem; background: var(--line); }
+.baseline i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
+
+/* director layers */
+.dir-glitch { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
+.dir-flash {
+ position: absolute; inset: 0; pointer-events: none; opacity: 0; mix-blend-mode: screen;
+ background: radial-gradient(ellipse 75% 55% at 50% 45%, var(--accent) 0%, transparent 70%), rgba(255,255,255,0.18);
+}
+.dir-story {
+ position: absolute; left: 0; right: 0; top: 0; bottom: 0; pointer-events: none;
+ display: flex; align-items: flex-end; justify-content: center; padding: 0 4.5rem 6rem; opacity: 0;
+}
+.cap { text-align: center; max-width: 96rem; position: relative; }
+.cap::before {
+ content: ''; position: absolute; inset: -6rem -10rem; z-index: -1;
+ background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(0,0,0,0.62) 0%, rgba(0,0,0,0) 100%);
+}
+:root[data-theme='light'] .cap::before { background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(243,242,238,0.8) 0%, rgba(243,242,238,0) 100%); }
+.cap-main {
+ font-family: 'Inter', 'Inter Variable', system-ui, sans-serif; font-weight: 800;
+ font-size: 11.5rem; line-height: 0.98; letter-spacing: -0.035em; color: var(--fg);
+ text-shadow: 0 0.4rem 2.4rem rgba(0,0,0,0.55);
+}
+.cap.num .cap-main { font-size: 15rem; font-variant-numeric: tabular-nums; letter-spacing: -0.045em; }
+.cap-main .w { display: inline-block; transform-origin: 50% 70%; }
+.cap-main .w.hl { background: var(--accent); color: #0a0a0a; padding: 0 0.14em; text-shadow: none; border-radius: 0.06em; }
+.cap-sub {
+ margin-top: 2rem; font-size: 2.7rem; letter-spacing: 0.08em; text-transform: uppercase;
+ color: var(--fg); opacity: 0.85; min-height: 1.3em;
+}
+.cap-tag {
+ display: inline-block; margin-bottom: 1.8rem; padding: 0.5rem 1.2rem; font-size: 2.2rem; letter-spacing: 0.12em;
+ border: 1px solid var(--accent); color: var(--accent); background: rgba(0,0,0,0.5);
+}
diff --git a/sims/kit/util.js b/sims/kit/util.js
new file mode 100644
index 0000000..1dbf9d0
--- /dev/null
+++ b/sims/kit/util.js
@@ -0,0 +1,79 @@
+// Small pure helpers shared by every sim. Everything animated must be a pure
+// function of `t` (seconds) so live playback and frame capture match.
+
+export const clamp01 = (x) => Math.min(1, Math.max(0, x));
+export const lerp = (a, b, k) => a + (b - a) * k;
+export const smooth = (x) => {
+ const k = clamp01(x);
+ return k * k * (3 - 2 * k);
+};
+export const easeOutCubic = (x) => 1 - Math.pow(1 - clamp01(x), 3);
+export const easeInOutCubic = (x) => {
+ const k = clamp01(x);
+ return k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;
+};
+export const easeOutExpo = (x) => (x >= 1 ? 1 : 1 - Math.pow(2, -10 * clamp01(x)));
+export const easeOutBack = (x, s = 1.7) => {
+ const k = clamp01(x) - 1;
+ return 1 + (s + 1) * k * k * k + s * k * k;
+};
+/** 0..1 progress of t between t0 and t1, eased. */
+export const prog = (t, t0, t1, ease = easeInOutCubic) => ease((t - t0) / (t1 - t0));
+
+/** Seeded PRNG (mulberry32). Same seed → same sequence. */
+export const rng = (seed) => {
+ let s = seed >>> 0;
+ return () => {
+ s = (s + 0x6d2b79f5) >>> 0;
+ let x = s;
+ x = Math.imul(x ^ (x >>> 15), x | 1);
+ x ^= x + Math.imul(x ^ (x >>> 7), x | 61);
+ return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
+ };
+};
+
+/** Stateless hash noise in [0,1). */
+export const hash = (n) => {
+ const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;
+ return x - Math.floor(x);
+};
+
+/** Random unit vector from a PRNG. */
+export const randDir = (r) => {
+ const u = r() * 2 - 1;
+ const a = r() * Math.PI * 2;
+ const s = Math.sqrt(1 - u * u);
+ return [s * Math.cos(a), u, s * Math.sin(a)];
+};
+
+/**
+ * Keyframed value: keys = [[t, value], ...] with numbers or arrays of numbers.
+ * Eased between keys, held outside.
+ */
+export const keyed = (keys, t, ease = easeInOutCubic) => {
+ if (t <= keys[0][0]) return keys[0][1];
+ for (let i = 0; i < keys.length - 1; i++) {
+ const [t0, v0] = keys[i];
+ const [t1, v1] = keys[i + 1];
+ if (t <= t1) {
+ const k = ease((t - t0) / (t1 - t0));
+ return Array.isArray(v0) ? v0.map((v, j) => lerp(v, v1[j], k)) : lerp(v0, v1, k);
+ }
+ }
+ return keys[keys.length - 1][1];
+};
+
+export const fmt = (n, d = 0) =>
+ Number(n).toLocaleString('en-US', {minimumFractionDigits: d, maximumFractionDigits: d});
+export const pad = (n, w) => String(Math.max(0, Math.floor(n))).padStart(w, '0');
+
+/** Deep merge plain objects; arrays and scalars from `b` replace `a`. */
+export const merge = (a, b) => {
+ if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b;
+ const out = {...a};
+ for (const k of Object.keys(b)) {
+ out[k] =
+ a && typeof a[k] === 'object' && !Array.isArray(a[k]) && a[k] !== null ? merge(a[k], b[k]) : b[k];
+ }
+ return out;
+};