Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Step 1a's acceptance, measured: tools/tokyo/accept-1a.ts (fly-past and drive, 5 poses x 4 times, in place against a fresh load) and tools/tokyo/clip.ts; the results in the ROADMAP

Evan (Yifeng) Wang6c90fe566a86
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index bf1ca4f..bab8fd0 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -440,8 +440,43 @@ Earlier direction (2026-11-05, kept for the history below): finish the three.js
result, a few frames later.
- The fly-past's frame interval p95 went from 29.7 / 28.5 to 17.20 / 17.17 ms, and its commits over 5 ms from
91 to 0.
- - Next for step 1a: the acceptance runs (the fly-past and a Shinjuku drive, 5 poses × 4 times, in place against a
- fresh load, a clip).
+ - Acceptance (2026-11-11, branch `tokyo-1a-acceptance`; `node tools/tokyo/accept-1a.ts`, clips by
+ `node tools/tokyo/clip.ts tower|drive`), on main + ThreeRT#6 (light sampling set up for the lights switched off at
+ load, found by these runs):
+ - The Shiba fly-past (15:30 → 17:45 in 10.5 s, 540–760 km/h) and a Shinjuku drive (Yasukuni-dōri eastbound from
+ `roads.json` at 60 km/h, 16:00 → 18:00 over 67 s), real time at the dynamic resolution:
+
+ | run | frames | scale | frame start p95 / p99 | interval p95 / max | over 50 ms | rebuilds | GPU p50 / p95 |
+ |---|---|---|---|---|---|---|---|
+ | fly-past | 648 in 10.5 s | 0.70 | 16.67 / 23.73 | 17.5 / 27.1 | 0 | 0 | 14.24 / 16.55 |
+ | drive | 4,086 in 67.1 s | 0.625 | 16.67 / 16.95 | 16.83 / 20.0 | 0 | 0 | 14.40 / 16.25 |
+
+ Both pass. Before #6 neither did: frame start p95 19.92 and 17.21 ms at the 0.5 floor.
+ - Live (the 0.5 floor, 64 frames after a reset) against our offline render (4096 spp, no denoiser, clamps off): ΔE
+ / SSIM / luminance (the truth's own noise, its 1024 spp render against it, ΔE / SSIM; SSIM with both halved, at
+ the resolution live renders):
+
+ | pose | 15:30 | sunset (16:40) | civil dusk (17:07) | night (19:30) |
+ |---|---|---|---|---|
+ | Kabukichō's gate | 0.50 / 0.983 / 0.976 (0.19 / 0.996; 0.990) | 0.60 / 0.984 / 1.004 (0.23 / 0.998; 0.992) | 0.62 / 0.966 / 0.989 (0.29 / 0.980; 0.979) | 1.73 / 0.877 / 0.994 (1.20 / 0.884; 0.936) |
+ | west exit | 0.98 / 0.942 / 0.945 (0.29 / 0.975; 0.968) | 0.91 / 0.965 / 1.011 (0.27 / 0.997; 0.980) | 0.75 / 0.954 / 0.989 (0.26 / 0.982; 0.970) | 2.01 / **0.869** / 0.993 (1.14 / 0.900; 0.916) |
+ | skyscraper canyon | 1.09 / 0.960 / 0.961 (0.28 / 0.987; 0.982) | 0.88 / 0.965 / 1.011 (0.26 / 0.996; 0.985) | 0.60 / 0.958 / 0.973 (0.22 / 0.978; 0.975) | 1.88 / **0.835** / 0.994 (1.19 / 0.878; 0.905) |
+ | aerial east | 1.56 / 0.933 / 0.993 (0.29 / 0.991; 0.976) | 1.83 / 0.916 / 0.963 (0.25 / 0.998; 0.964) | 1.75 / 0.931 / 0.898 (0.13 / 0.998; 0.981) | 2.89 / **0.896** / 1.037 (0.28 / 0.993; 0.962) |
+ | aerial west | 2.26 / 0.938 / 0.985 (0.34 / 0.993; 0.976) | 2.07 / **0.880** / 0.975 (0.29 / 0.998; 0.939) | 1.17 / 0.930 / 0.879 (0.12 / 0.997; 0.977) | 2.52 / **0.884** / 1.030 (0.30 / 0.989; 0.951) |
+
+ - ΔE ≤ 3 at all 20. SSIM ≥ 0.9, or within 0.02 of the truth's own, at 15 (bold: the misses).
+ - The night's numbers are step 1's static night rooms' (gate 1.70 / 0.878, west exit 2.02 / 0.868, canyon
+ 1.87 / 0.836, aerials 2.95 / 0.894 and 2.57 / 0.882): the time-of-day room at 19:30 renders as they do. Their
+ misses are step 1's, left to step 3.
+ - Sunset's west aerial misses on the far city's detail at the 0.5 floor: halved, 0.939.
+ - At civil dusk the aerials read 10–12 % dark (0.898, 0.879): the far lamps and windows the live view does not
+ sample (`LT_FAR`, 120 m) and finds only by BSDF rays. Step 3.
+ - In place against a fresh load (Shinjuku's east aerial; the clock run in lockstep to the time, held 200 frames,
+ reset, 128 frames): ΔE 0.03 at 15:30, 0.08 at sunset, 0.01 at civil dusk, 0 at night (bit for bit). All pass.
+ Before #6: 0.29 / 0.49 / 0.15 / 0.34.
+ - Clips, posted in the session (animated WebP: the real-time run's frames, the lockstep snapshots of each):
+ - the fly-past, 637 frames in 10.5 s at scale 0.70;
+ - the drive, 4,078 frames in 67.1 s at scale 0.625.
1b. **Weather on Tokyo.** States, and transitions between them, all in place (no rebuild):
- rain: wet streets and puddles reflecting the city, and the rain curtain (Bistro's), measured on Tokyo;
- fog and mist: height fog over the city, thickening and clearing;
diff --git a/tools/tokyo/accept-1a.ts b/tools/tokyo/accept-1a.ts
new file mode 100644
index 0000000..1e88643
--- /dev/null
+++ b/tools/tokyo/accept-1a.ts
@@ -0,0 +1,183 @@
+// Step 1a's acceptance (docs/ROADMAP.md § 0): Tokyo's time of day in the live view, measured.
+// node tools/tokyo/accept-1a.ts [--only flight,drive,poses,inplace] [--times 15:30,sunset,civil-dusk,night]
+// [--spp 4096] [--json out.json] [--settle 200] [--after 128]
+// (The 20 truths of `poses` take ~2 h at 4096 spp: --times runs some of the times; each result is kept in the JSON.)
+//
+// 1. flight: Shiba past Tokyo Tower at 540–760 km/h while the clock runs 15:30 -> 17:45 (the supervisor's clip: its
+// keyframes, Hermite), in real time at the dynamic resolution (auto). Pass: frame start p95 ≤ 16.7 ms, no frame
+// over 50 ms, no rebuild.
+// 2. drive: Shinjuku along Yasukuni-dōri eastbound (the road graph's own nodes, 1.6 m above them, 60 km/h, ~67 s), the
+// clock running 16:00 -> 18:00 over it. Same pass.
+// 3. poses: live (the 0.5 floor, 64 frames after a reset) against our offline render (tools/tokyo/truth.ts: no
+// denoiser, clamps off) at Shinjuku's 5 poses x 4 times (15:30, sunset, civil dusk, night). Pass: ΔE ≤ 3 and SSIM ≥
+// 0.9, where the truth's own noise allows (its spp / 4 render against it, per pose and time).
+// 4. inplace: the clock run in place (lockstep, the sun, sky, exposure, lamps, windows and moon changed frame by frame)
+// to each time, held 200 frames, the history reset, 128 frames (--after); against the room that loads that time. Pass:
+// ΔE ≤ 0.1.
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { join } from "node:path";
+import { bundleGame } from "../bundle-game.ts";
+import { rendererBin, repoRoot, requireQuietGpu } from "../lib/bench.ts";
+import { startLive, type Build } from "../lib/live.ts";
+import { POSES } from "../../games/tokyo/tokyo.game.ts";
+import { sunAt } from "../../games/tokyo/tokyo-tod.game.ts";
+import { driver, towerCam, yasukuni, type Cam } from "./paths.ts";
+import { compare, truth } from "./truth.ts";
+
+const sharp = createRequire(join(repoRoot, "package.json"))("sharp");
+
+const args = process.argv.slice(2);
+const opt = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);
+const only = new Set(opt("--only", "flight,drive,poses,inplace").split(","));
+const spp = Number(opt("--spp", "4096"));
+const out = join(repoRoot, "out/bench/tokyo-1a");
+mkdirSync(out, { recursive: true });
+const bundle = join(repoRoot, "out/bundles/tokyo-tod.js");
+await bundleGame(join(repoRoot, "games/tokyo/tokyo-tod.game.ts"), bundle);
+const b = { bin: rendererBin, assets: repoRoot, presets: join(repoRoot, "presets"), bundles: join(repoRoot, "out/bundles"), label: "tokyo-1a" } as Build;
+requireQuietGpu();
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+const pick = (v: number[], p: number) => v[Math.min(v.length - 1, Math.floor(p * v.length))];
+const result: Record<string, unknown> = {};
+
+// ---------------------------------------------------------------- 1, 2: real time
+async function realtime(name: string, room: string, cam: (t: number) => Cam, secs: number) {
+ const log = join(out, `${name}.jsonl`);
+ rmSync(log, { force: true });
+ const live = startLive(b, bundle, { scale: "auto", frameLog: log, room });
+ await live.firstFrame;
+ live.send({ cmd: "camera", ...cam(0) });
+ await sleep(4000);
+ live.send({ cmd: "time", t: 0 });
+ const before = readFileSync(log, "utf8").trim().split("\n").length;
+ const t0 = performance.now();
+ for (let k = 0; ; k++) {
+ const t = (performance.now() - t0) / 1000;
+ if (t > secs) break;
+ live.send({ cmd: "camera", ...cam(t) });
+ await sleep(Math.max(0, t0 + ((k + 1) * 1000) / 60 - performance.now()));
+ }
+ await sleep(200);
+ await live.quit();
+ const f = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l)).slice(before);
+ const st = f.map((x) => x.start).filter((v) => typeof v === "number").sort((p, q) => p - q);
+ const iv = f.slice(1).map((x) => x.interval as number).sort((p, q) => p - q);
+ const g = f.map((x) => x.gpu).filter((v) => typeof v === "number" && v > 0).sort((p, q) => p - q);
+ const sc = f.map((x) => x.scale).sort((p, q) => p - q);
+ const r = {
+ room, secs: +secs.toFixed(1), frames: f.length, scale_p50: pick(sc, 0.5),
+ rebuilds: f.filter((x) => (x.rebuild ?? 0) > 0).length,
+ start_p95_ms: +pick(st, 0.95).toFixed(2), start_p99_ms: +pick(st, 0.99).toFixed(2),
+ interval_p95_ms: +pick(iv, 0.95).toFixed(2), interval_max_ms: +iv[iv.length - 1].toFixed(1),
+ over_50ms: iv.filter((x) => x > 50).length,
+ gpu_p50_ms: +pick(g, 0.5).toFixed(2), gpu_p95_ms: +pick(g, 0.95).toFixed(2),
+ };
+ const pass = r.start_p95_ms <= 16.7 && r.over_50ms === 0 && r.rebuilds === 0;
+ console.log(`${name}: ${r.frames} frames in ${r.secs} s at scale ${r.scale_p50}; frame start p95 / p99 ${r.start_p95_ms} / ${r.start_p99_ms} ms, interval p95 ${r.interval_p95_ms} max ${r.interval_max_ms}, ${r.over_50ms} over 50 ms, ${r.rebuilds} rebuilds; GPU p50 / p95 ${r.gpu_p50_ms} / ${r.gpu_p95_ms} ms: ${pass ? "PASS" : "FAIL"}`);
+ result[name] = { ...r, pass };
+}
+if (only.has("flight")) await realtime("flight", "shiba-15.5-17.75-10-r1300", towerCam, 10.5);
+if (only.has("drive")) {
+ const d = driver(yasukuni(), 60 / 3.6);
+ await realtime("drive", `shinjuku-16-18-${Math.round(d.secs)}`, d.cam, d.secs);
+}
+
+// ---------------------------------------------------------------- 3, 4: the four times
+/** The clock (JST hour) where the sun stands at `elevation` degrees on its way down (bisection over the afternoon). */
+function sunDown(elevation: number): number {
+ let lo = 14, hi = 20;
+ for (let k = 0; k < 40; k++) {
+ const mid = (lo + hi) / 2;
+ if (sunAt(mid).elevation > elevation) lo = mid;
+ else hi = mid;
+ }
+ return lo;
+}
+const ALL_TIMES: Record<string, number> = { "15:30": 15.5, sunset: sunDown(-0.833), "civil-dusk": sunDown(-6), night: 19.5 };
+const wanted = new Set(opt("--times", Object.keys(ALL_TIMES).join(",")).split(","));
+// (Also any clock as h<hours>, e.g. h18.25.)
+const TIMES = { ...Object.fromEntries(Object.entries(ALL_TIMES).filter(([t]) => wanted.has(t))), ...Object.fromEntries([...wanted].filter((t) => /^h[0-9.]+$/.test(t)).map((t) => [t, Number(t.slice(1))])) };
+const fixed = (h: number) => `shinjuku-${h.toFixed(4)}-${h.toFixed(4)}-1`;
+
+async function liveShot(room: string, pose: { position: number[]; target: number[]; fov: number }, png: string) {
+ const live = startLive(b, bundle, { scale: "0.5", room });
+ await live.firstFrame;
+ live.send({ cmd: "camera", pos: pose.position, target: pose.target, tan: Math.tan((pose.fov * Math.PI) / 360) });
+ await sleep(3000);
+ live.send({ cmd: "reset" });
+ const done = live.wait((l: string) => l.includes(png), 600000);
+ live.send({ cmd: "snapshot", path: png, after: 64 });
+ await done;
+ await live.quit();
+}
+
+if (only.has("poses")) {
+ const rows: Record<string, unknown>[] = [];
+ for (const [time, h] of Object.entries(TIMES)) {
+ const room = fixed(h);
+ for (const [name, pose] of Object.entries(POSES)) {
+ const ref = truth(bundle, room, name, pose, spp);
+ const noise = compare(ref, truth(bundle, room, name, pose, spp / 4));
+ const png = join(out, `live-${time}-${name}.png`);
+ await liveShot(room, pose, png);
+ const m = compare(ref, png);
+ const pass = (m.mean_delta_e <= 3 || m.mean_delta_e <= noise.mean_delta_e * 1.25) && (m.ssim >= 0.9 || m.ssim >= noise.ssim - 0.02);
+ // (Also at the resolution the live view renders, the 0.5 floor: what the upscale loses is not in it.)
+ const halved = await Promise.all([ref, png].map(async (f, k) => {
+ const h = join(out, `half-${k}.png`);
+ await sharp(f).resize(Math.round((await sharp(f).metadata()).width! / 2)).png().toFile(h);
+ return h;
+ }));
+ const atRender = compare(halved[0], halved[1]);
+ rows.push({ time, pose: name, live: m, noise, atRender, pass });
+ console.log(`${time.padEnd(10)} ${name.padEnd(18)} live ΔE ${m.mean_delta_e.toFixed(2)} SSIM ${m.ssim.toFixed(3)} lum ${m.luminance_ratio.toFixed(3)} | truth's noise ΔE ${noise.mean_delta_e.toFixed(2)} SSIM ${noise.ssim.toFixed(3)} | at the render's 0.5 SSIM ${atRender.ssim.toFixed(3)}: ${pass ? "PASS" : "FAIL"}`);
+ }
+ }
+ result.poses = rows;
+}
+
+if (only.has("inplace")) {
+ const SETTLE = Number(opt("--settle", "200")), AFTER = Number(opt("--after", "128")), from = 15.5, to = 20, secs = 9;
+ const pose = POSES["aerial-east"];
+ const shot = async (room: string, steps: number, png: string) => {
+ const live = startLive(b, bundle, { scale: "0.5", room });
+ await live.firstFrame;
+ live.send({ cmd: "camera", pos: pose.position, target: pose.target, tan: Math.tan((pose.fov * Math.PI) / 360) });
+ live.send({ cmd: "lockstep", dt: 1 / 60 });
+ live.send({ cmd: "time", t: 0 });
+ const moved = live.wait((l: string) => l.includes("sync moved"), 600000);
+ live.send({ cmd: "frames", n: steps, sync: "moved" });
+ await moved;
+ live.send({ cmd: "lockstep", dt: 0 });
+ const settled = live.wait((l: string) => l.includes("sync settled"), 600000);
+ live.send({ cmd: "frames", n: SETTLE, sync: "settled" });
+ await settled;
+ live.send({ cmd: "reset" });
+ const done = live.wait((l: string) => l.includes(`snapshot ${png}`), 600000);
+ live.send({ cmd: "frames", n: AFTER, snapshot: png });
+ await done;
+ await live.quit();
+ };
+ const eq: Record<string, unknown> = {};
+ for (const [time, h] of Object.entries(TIMES)) {
+ // the sweep's frame at that clock (at least one: the shot always moves a frame), and the clock it then shows (what
+ // the loaded room is set to)
+ const steps = Math.max(1, Math.round(((h - from) / (to - from)) * secs * 60)), clock = from + ((to - from) * steps) / 60 / secs;
+ const moved = join(out, `inplace-${time}.png`), loaded = join(out, `loaded-${time}.png`);
+ await shot(`shinjuku-${from}-${to}-${secs}`, steps, moved);
+ await shot(fixed(clock), steps, loaded);
+ const m = JSON.parse(execFileSync(rendererBin, ["compare", loaded, moved]).toString().trim().split("\n").pop()!);
+ eq[time] = { clock, delta_e: m.mean_delta_e, ssim: m.ssim, luminance: m.luminance_ratio, pass: m.mean_delta_e <= 0.1 };
+ console.log(`in place vs loaded at ${time} (${clock.toFixed(3)} h): ΔE ${m.mean_delta_e} SSIM ${m.ssim} luminance ${m.luminance_ratio}: ${m.mean_delta_e <= 0.1 ? "PASS" : "FAIL"}`);
+ }
+ result.inplace = eq;
+}
+// Merged with earlier runs (--times runs some of the times): this run's times replace theirs, the rest are kept.
+const file = opt("--json", join(out, "accept-1a.json"));
+const before: Record<string, any> = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
+const merged: Record<string, unknown> = { ...before, ...result };
+if (result.poses && before.poses) merged.poses = [...before.poses.filter((r: { time: string }) => !(r.time in TIMES)), ...(result.poses as unknown[])];
+if (result.inplace && before.inplace) merged.inplace = { ...before.inplace, ...(result.inplace as object) };
+writeFileSync(file, JSON.stringify(merged, null, 1));
diff --git a/tools/tokyo/clip.ts b/tools/tokyo/clip.ts
new file mode 100644
index 0000000..531247b
--- /dev/null
+++ b/tools/tokyo/clip.ts
@@ -0,0 +1,114 @@
+// A clip of Tokyo in the live view, as a player sees it: an animated WebP.
+// node tools/tokyo/clip.ts [tower|drive] [--fps 30] [--width 800] [--quality 45] -> out/clips/tokyo-<path>.webp
+//
+// tower: past Tokyo Tower at 540–760 km/h while the clock runs 15:30 -> 17:45 (tools/tokyo/paths.ts).
+// drive: Shinjuku along Yasukuni-dōri at 60 km/h while the clock runs 16:00 -> 18:00.
+//
+// The clip is made in three passes:
+// 1. Real time, at the dynamic resolution, with the frame log: which frames the viewport actually produced, and when.
+// 2. Lockstep at 1/60 s along the same path at that run's median scale: a snapshot of every frame.
+// 3. At each display tick, the last frame the real-time run had produced by then, drawn from the snapshots. The overlay
+// shows the clock, the measured frame rate and the speed, with the data's credits. Stalls show as held frames.
+// The scene clock restarts at 0 as each pass starts, so the sun, the exposure and the lamps follow the same time.
+import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { join } from "node:path";
+import { bundleGame } from "../bundle-game.ts";
+import { rendererBin, repoRoot, requireGpuLock } from "../lib/bench.ts";
+import { startLive, type Build } from "../lib/live.ts";
+import { driver, towerCam, yasukuni, type Cam } from "./paths.ts";
+
+const sharp = createRequire(join(repoRoot, "package.json"))("sharp");
+const args = process.argv.slice(2);
+const opt = (k: string, d: number) => (args.includes(k) ? Number(args[args.indexOf(k) + 1]) : d);
+const which = args.find((a) => a === "tower" || a === "drive") ?? "tower";
+const FPS = opt("--fps", 30), W = opt("--width", 800), Q = opt("--quality", 45), H = Math.round((W * 9) / 16);
+const d = which === "drive" ? driver(yasukuni(), 60 / 3.6) : null;
+const route = which === "drive"
+ ? { cam: d!.cam, secs: d!.secs, room: `shinjuku-16-18-${Math.round(d!.secs)}`, from: 16, to: 18, label: "Shinjuku · Yasukuni-dōri" }
+ : { cam: towerCam, secs: 10.5, room: "shiba-15.5-17.75-10-r1300", from: 15.5, to: 17.75, label: "Tokyo Tower" };
+const clockSecs = which === "drive" ? Math.round(d!.secs) : 10;
+const out = join(repoRoot, "out/clips", which);
+rmSync(out, { recursive: true, force: true });
+mkdirSync(join(out, "shots"), { recursive: true });
+const bundle = join(repoRoot, "out/bundles/tokyo-tod.js");
+await bundleGame(join(repoRoot, "games/tokyo/tokyo-tod.game.ts"), bundle);
+const b = { bin: rendererBin, assets: repoRoot, presets: join(repoRoot, "presets"), bundles: join(repoRoot, "out/bundles"), label: "clip" } as Build;
+requireGpuLock("tokyo clip");
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+const N = Math.round(route.secs * 60);
+
+// 1. Real time.
+const log = join(out, "frames.jsonl");
+let live = startLive(b, bundle, { scale: "auto", frameLog: log, room: route.room });
+await live.firstFrame;
+live.send({ cmd: "camera", ...route.cam(0) });
+await sleep(4000);
+live.send({ cmd: "time", t: 0 });
+const before = readFileSync(log, "utf8").trim().split("\n").length;
+const t0 = performance.now();
+for (let k = 0; k <= N; k++) {
+ live.send({ cmd: "camera", ...route.cam(Math.min(route.secs, (performance.now() - t0) / 1000)) });
+ await sleep(Math.max(0, t0 + ((k + 1) * 1000) / 60 - performance.now()));
+}
+await sleep(200);
+await live.quit();
+const run = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l)).slice(before);
+const shown = run.map((f) => ({ t: f.t - run[0].t, scale: f.scale as number })).filter((f) => f.t <= route.secs * 1000);
+const scales = shown.map((s) => s.scale).sort((p, q) => p - q);
+const scale = scales[Math.floor(scales.length / 2)];
+console.log(`real time: ${shown.length} frames in ${route.secs.toFixed(1)} s, median scale ${scale}`);
+
+// 2. Lockstep snapshots.
+live = startLive(b, bundle, { scale: String(scale), room: route.room });
+await live.firstFrame;
+live.send({ cmd: "lockstep", dt: 0 });
+const hold = live.wait((l: string) => l.includes("sync hold"));
+live.send({ cmd: "camera", ...route.cam(0), frames: 120, sync: "hold" });
+await hold;
+live.send({ cmd: "time", t: 0 });
+live.send({ cmd: "lockstep", dt: 1 / 60 });
+for (let k = 0; k <= N; k++) {
+ const p = join(out, "shots", `${String(k).padStart(4, "0")}.png`);
+ const done = live.wait((l: string) => l.includes(`snapshot ${p}`));
+ live.send({ cmd: "camera", ...route.cam(k / 60), frames: 1, snapshot: p });
+ await done;
+}
+await live.quit();
+
+// 3. Compose.
+const FRAME = 1000 / 60;
+const at = (k: number): Cam => route.cam(Math.min(route.secs, k / 60));
+const kmh = (k: number) => {
+ const a = at(Math.max(0, k - 1)).pos, c = at(k).pos;
+ return Math.round(Math.hypot(c[0] - a[0], c[1] - a[1], c[2] - a[2]) * 60 * 3.6);
+};
+const clock = (s: number) => {
+ const m = Math.round((route.from + (route.to - route.from) * Math.min(1, s / clockSecs)) * 60);
+ return `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
+};
+const last = (T: number) => {
+ let j = 0;
+ while (j + 1 < shown.length && shown[j + 1].t <= T) j++;
+ return j;
+};
+const fpsAt = (T: number) => shown.filter((x) => x.t > T - 1000 && x.t <= T).length * (T >= 1000 ? 1 : 1000 / Math.max(T, FRAME));
+const svg = (w: number, h: number, body: string) => Buffer.from(`<svg width="${w}" height="${h}" xmlns="http://www.w3.org/2000/svg">${body}</svg>`);
+const tag = (t: string) => svg(W, 34, `<rect x="6" y="6" width="${14 + t.length * 7.9}" height="24" rx="3" fill="rgba(0,0,0,0.65)"/><text x="13" y="23" font-family="Helvetica" font-weight="bold" font-size="14.5" fill="#fff">${t}</text>`);
+const credit = svg(W, 18, `<rect width="100%" height="100%" fill="rgba(0,0,0,0.55)"/><text x="6" y="13" font-family="Helvetica" font-size="10.5" fill="#ccc">3D city model: Project PLATEAU (MLIT) · elevation and aerial photos: GSI · roads: © OpenStreetMap contributors · city pipeline: jeantimex/tokyo (MIT)</text>`);
+const frames: Buffer[] = [];
+const cache = new Map<string, Buffer>();
+for (let i = 0; i < Math.floor(route.secs * FPS); i++) {
+ const T = (i * 1000) / FPS;
+ const k = Math.min(N, Math.floor(shown[last(T)].t / FRAME));
+ const f = join(out, "shots", `${String(k).padStart(4, "0")}.png`);
+ if (!cache.has(f)) cache.set(f, await sharp(f).resize(W, H).toBuffer());
+ frames.push(await sharp(cache.get(f)).composite([
+ { input: tag(`ThreeRT live · ${route.label} · ${clock(T / 1000)} JST · ${Math.round(fpsAt(T))} fps · ${kmh(k)} km/h`), left: 0, top: 0 },
+ { input: credit, left: 0, top: H - 18 },
+ ]).png().toBuffer());
+}
+const webp = join(repoRoot, "out/clips", `tokyo-${which}.webp`);
+await sharp(frames, { join: { animated: true } }).webp({ delay: frames.map(() => Math.round(1000 / FPS)), loop: 0, quality: Q, effort: 5 }).toFile(webp);
+writeFileSync(join(out, "realtime.json"), JSON.stringify({ room: route.room, secs: route.secs, scale, shown }, null, 1));
+console.log(`${webp}: ${frames.length} frames, ${(statSync(webp).size / 1048576).toFixed(2)} MB`);
diff --git a/tools/tokyo/paths.ts b/tools/tokyo/paths.ts
new file mode 100644
index 0000000..7ed8084
--- /dev/null
+++ b/tools/tokyo/paths.ts
@@ -0,0 +1,76 @@
+// Camera paths through Tokyo for the live view (camera commands at 60 Hz): past Tokyo Tower at 540-760 km/h, and along
+// Yasukuni-dori in Shinjuku at street level. Used by tools/tokyo/accept-1a.ts and tools/tokyo/clip.ts.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { repoRoot } from "../lib/bench.ts";
+
+export type Cam = { pos: number[]; target: number[]; tan: number };
+const tan = Math.tan((60 * Math.PI) / 360);
+
+/** Past Tokyo Tower (Shiba's origin; ground 18.5 m, top ~351 m): keyframes (t s, position, target), Hermite. */
+const TOWER = [
+ { t: 0.0, p: [600, 270, -275], q: [0, 175, 0] },
+ { t: 1.6, p: [360, 225, -165], q: [0, 175, 0] },
+ { t: 3.0, p: [130, 185, -70], q: [0, 175, 0] },
+ { t: 3.9, p: [28, 172, -52], q: [-120, 172, 30] },
+ { t: 5.0, p: [-140, 182, 25], q: [-900, 160, 360] },
+ { t: 6.1, p: [-260, 230, 170], q: [-700, 190, 900] },
+ { t: 7.2, p: [-280, 300, 330], q: [0, 210, 0] },
+ { t: 8.5, p: [-70, 340, 450], q: [0, 225, 0] },
+ { t: 10.0, p: [190, 355, 420], q: [0, 225, 0] },
+ { t: 10.6, p: [270, 360, 380], q: [0, 225, 0] },
+];
+export function towerCam(t: number): Cam {
+ const K = TOWER;
+ let i = 0;
+ while (i < K.length - 2 && K[i + 1].t <= t) i++;
+ const k0 = K[i], k1 = K[i + 1], kp = K[Math.max(0, i - 1)], kn = K[Math.min(K.length - 1, i + 2)];
+ const h = k1.t - k0.t, u = Math.min(1, Math.max(0, (t - k0.t) / h));
+ const f = (key: "p" | "q") => [0, 1, 2].map((c) => {
+ const m0 = ((k1[key][c] - kp[key][c]) / (k1.t - kp.t)) * h, m1 = ((kn[key][c] - k0[key][c]) / (kn.t - k0.t)) * h;
+ return (2 * u ** 3 - 3 * u ** 2 + 1) * k0[key][c] + (u ** 3 - 2 * u ** 2 + u) * m0 + (-2 * u ** 3 + 3 * u ** 2) * k1[key][c] + (u ** 3 - u ** 2) * m1;
+ });
+ return { pos: f("p"), target: f("q"), tan };
+}
+
+/** Yasukuni-dōri eastbound in Shinjuku: its road-graph nodes (x, road height, z), chained east from the westmost. */
+export function yasukuni(): number[][] {
+ const r = JSON.parse(readFileSync(join(repoRoot, "assets/city/tiles/shinjuku/roads.json"), "utf8"));
+ const N: number[][] = r.nodes;
+ const E = (r.edges as { a: number; b: number; oneway: number; nameEn?: string }[]).filter((e) => e.nameEn === "Yasukuni Street");
+ const next = new Map<number, number[]>();
+ for (const e of E) {
+ next.set(e.a, [...(next.get(e.a) ?? []), e.b]);
+ if (!e.oneway) next.set(e.b, [...(next.get(e.b) ?? []), e.a]);
+ }
+ const ends = [...new Set(E.flatMap((e) => [e.a, e.b]))].sort((p, q) => N[p][0] - N[q][0]);
+ let best: number[] = [];
+ for (const s of ends.slice(0, 6)) {
+ const path = [s], seen = new Set([s]);
+ for (;;) {
+ const cur = path[path.length - 1];
+ const cand = (next.get(cur) ?? []).filter((n) => !seen.has(n));
+ if (!cand.length) break;
+ const n = cand.reduce((p, q) => (N[q][0] > N[p][0] ? q : p));
+ if (N[n][0] < N[cur][0] - 30) break;
+ path.push(n);
+ seen.add(n);
+ }
+ if (path.length > best.length) best = path;
+ }
+ return best.map((i) => N[i]);
+}
+/** A camera driving `pts` at `speed` m/s, 1.6 m above the road, looking 30 m ahead; and the drive's length (s). */
+export function driver(pts: number[][], speed: number): { cam: (t: number) => Cam; secs: number } {
+ const cum = [0];
+ for (let i = 1; i < pts.length; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][2] - pts[i - 1][2]));
+ const at = (s: number) => {
+ s = Math.min(Math.max(s, 0), cum[cum.length - 1]);
+ let i = 1;
+ while (i < cum.length - 1 && cum[i] < s) i++;
+ const u = (s - cum[i - 1]) / Math.max(1e-6, cum[i] - cum[i - 1]);
+ return [0, 1, 2].map((c) => pts[i - 1][c] + (pts[i][c] - pts[i - 1][c]) * u + (c === 1 ? 1.6 : 0));
+ };
+ return { cam: (t) => ({ pos: at(t * speed), target: at(t * speed + 30), tan }), secs: cum[cum.length - 1] / speed };
+}
+