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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Landing page: the hero is a clip (Bistro night, three.js | ThreeRT, 60 fps, recorded on an M3 Max)
Yifeng "Evan" Wang418a4efefbc7
diff --git a/site/README.md b/site/README.mdindex 5b86a79..0cd79e6 100644--- a/site/README.md+++ b/site/README.md@@ -49,7 +49,10 @@ the same footer links. The markup is repeated in each page; change it in all fou### The landing page-1. **Hero:** Bistro night, three.js | ThreeRT under one draggable divider. "Path tracing at 60 fps."+1. **Hero:** Bistro night along its own camera move, three.js | ThreeRT under one draggable divider, as a clip+ (60 fps, a 12 s loop; `media/bistro/hero.mp4`, `hero-720.mp4`, both sides in one file so they cannot drift). Its first frame is+ what shows until it plays, and where it does not: reduced motion, a data saver, autoplay refused. A button pauses+ it. "Path tracing at 60 fps."2. **ThreeRT = Three + RT:** Ray Tracing, Real Time, Runtime.3. **Hello world looks right:** an auto-advancing reel of three starter scenes, the ThreeRT source next to its output(three.js as written | ThreeRT with every setting at its default).@@ -110,11 +113,11 @@ links from where they are served (`js/site.js` `packageLinks`):|---|---|| `index.html`, `showcase/`, `download/`, `docs/` | The pages (sections, their styles and their script) || `css/threert.css` | The visual system: ink, bone and tungsten tokens, type, the nav and footer, the comparison and player components, the cards, steps and QR tiles of the inner pages |-| `js/threert.js` | The wipe comparison, the synced camera-move player, the code highlighter |+| `js/threert.js` | The wipe comparison (and the clip that can play over its two stills), the synced camera-move player, the code highlighter || `js/site.js` | What the pages share: the visitor's platform, the release and the packages on this host, their links, QR codes || `js/devices.js` | The 3D device rows (three.js), with a still fallback when WebGL is off || `brand/` | The mark ("Three bounces": the three.js triangle, tilted as three.js draws it, and the closed light path inside it, which is three.js's own inner triangle) and its variants. `js/mark.js` draws it live in the lockup and on the landing page, and turns the path on hover |-| `media/` | The renders, WebP. Generated; never retouched |+| `media/` | The renders, WebP, and the hero clip, H.264. Generated; never retouched || `serve.ts`, `tools/` | Local server, static build, deploy, media and device-still generators; `tools/vendor.ts` names the npm files the pages import (three.js, qrcode-generator) || `worker.ts`, `wrangler.jsonc` | The Cloudflare Worker (www redirect, disk images from R2, static assets) and its config (threert.dev) || `releases/`, `play/` | Generated, not committed (above) |@@ -129,5 +132,21 @@ bun site/tools/media.ts # out/ -> site/media (stills, camera-move frabun site/tools/device-stills.ts # the 3D device rows -> site/media/devices (headless Chrome, software WebGL)```-The numbers behind the page (Apple M5, 1280 × 720, 2026-11-08) are in [`docs/COMPARE.md`](../docs/COMPARE.md).+The hero clip is recorded apart, on the machine at hand (it needs Bistro in the asset store: `bun scripts/orca.ts+bistro`, and ffmpeg):++```bash+node tools/site-hero.ts --probe --width 1600 --height 900 --reach 2.2 --scale auto # the scale 60 fps holds here+node tools/site-hero.ts --width 1600 --height 900 --reach 2.2 --scale 0.5 # record at that scale, fixed+node tools/site-hero.ts --probe --width 1600 --height 900 --reach 2.2 --scale 0.5 # its GPU times, back to back+bun site/tools/hero.ts # out/site-hero -> site/media/bistro/hero*.mp4, hero-*.webp, hero.json+```++Every frame of the clip is one frame the live renderer drew, in lockstep at 60 fps; the probe draws the same move+back to back, as on screen, with nothing else on the GPU, and `media/bistro/hero.json` keeps what it measured. The+landing page's footnote quotes that file (machine, size, scale, GPU ms): change the footnote when the clip changes.+The one committed was recorded on an Apple M3 Max: 1600 × 900 at render scale 0.5 (1920 × 1080 does not hold 60 fps+there: 22 ms a frame at the lowest scale), a slow 2.2 s stretch of the scene's camera move taken in 6 s.++The numbers behind the rest of the page (Apple M5, 1280 × 720, 2026-11-08) are in [`docs/COMPARE.md`](../docs/COMPARE.md).Amazon Lumberyard Bistro and Zero-Day are from NVIDIA's ORCA (CC BY 4.0); the credits are in the page's footer.diff --git a/site/css/threert.css b/site/css/threert.cssindex 3c1b313..52e662d 100644--- a/site/css/threert.css+++ b/site/css/threert.css@@ -100,6 +100,12 @@ a:focus-visible, button:focus-visible, summary:focus-visible { outline: 2px soli.cmp .pa, .cmp .pb { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }.cmp .pb { clip-path: inset(0 0 0 var(--x, 50%)); }.cmp img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; pointer-events: none; }+/* A clip over the stills (js/threert.js, clip): a canvas a pane, shown once it plays; its pause button. */+.cmp canvas { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; pointer-events: none; opacity: 0; transition: opacity 0.5s; }+.cmp.playing canvas { opacity: 1; }+.cmp .pp { position: absolute; z-index: 6; right: 14px; bottom: 14px; width: 34px; height: 34px; border-radius: 50%; border: 1px solid rgba(236, 232, 225, 0.25); background: rgba(8, 9, 11, 0.6); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); color: #ece8e1; display: grid; place-items: center; cursor: pointer; padding: 0; opacity: 0.7; transition: opacity 0.2s; }+.cmp .pp:hover, .cmp .pp:focus-visible { opacity: 1; }+.cmp .pp[hidden] { display: none; }.cmp.zoom img { transform: scale(var(--z, 2)); transform-origin: var(--o, 50% 50%); }.cmp .bar, .seqp .bar { position: absolute; top: 0; bottom: 0; left: var(--x, 50%); width: 2px; margin-left: -1px; background: var(--filament); box-shadow: 0 0 18px 2px color-mix(in srgb, var(--tungsten) 65%, transparent); z-index: 3; pointer-events: none; }.cmp .knob { position: absolute; top: 50%; left: var(--x, 50%); width: 42px; height: 42px; margin: -21px 0 0 -21px; border-radius: 50%; background: rgba(10, 11, 14, 0.66); border: 1.5px solid var(--filament); z-index: 4; display: grid; place-items: center; color: var(--filament); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); pointer-events: none; }diff --git a/site/index.html b/site/index.htmlindex daee66b..66c4e49 100644--- a/site/index.html+++ b/site/index.html@@ -16,6 +16,7 @@.hero .cmp .lab.a { left: 32px; } .hero .cmp .lab.b { right: 32px; }.hero .cmp::after { content: ""; position: absolute; inset: 0; z-index: 2; pointer-events: none; background: linear-gradient(90deg, rgba(6,7,9,.86) 0%, rgba(6,7,9,.55) 34%, rgba(6,7,9,0) 62%), linear-gradient(180deg, rgba(6,7,9,.7) 0%, rgba(6,7,9,0) 16%), linear-gradient(0deg, rgba(6,7,9,.6) 0%, rgba(6,7,9,0) 16%); }.hero .cmp .knob { top: 74%; }+ .hero .cmp .pp { right: auto; left: 50%; bottom: 30px; margin-left: -17px; }.hero .copy { position: absolute; z-index: 7; left: 0; right: 0; top: 132px; pointer-events: none; }.hero .copy .wrap { display: grid; gap: 24px; }.hero .copy a { pointer-events: auto; }@@ -137,7 +138,7 @@</nav><header class="hero">- <div class="cmp" id="hero" data-a="media/bistro/tuned.webp" data-b="media/bistro/live.webp" data-la="three.js" data-lb="ThreeRT" data-x="44" data-intro></div>+ <div class="cmp" id="hero" data-a="media/bistro/hero-three.webp" data-b="media/bistro/hero-rt.webp" data-video="media/bistro/hero.mp4" data-video-sm="media/bistro/hero-720.mp4" data-la="three.js" data-lb="ThreeRT" data-x="44" data-intro></div><div class="copy"><div class="wrap"><h1 class="h-display">Path tracing<span class="l2 ray-text">at 60 fps.</span></h1>@@ -305,7 +306,7 @@<div class="site"><a href="showcase/">Showcase</a><a href="download/">Download</a><a href="docs/">Docs</a><a href="https://github.com/taichi-dev/ThreeRT" rel="noopener">GitHub</a></div></div><div class="note">- <p><sup>1</sup> To our knowledge. 60 fps measured on an Apple M5 MacBook at 1280 × 720 output with dynamic resolution, along each scene’s own camera path; three.js r187 in Chrome on the same machine.</p>+ <p><sup>1</sup> To our knowledge. 60 fps measured on an Apple M5 MacBook at 1280 × 720 output with dynamic resolution, along each scene’s own camera path; three.js r187 in Chrome on the same machine. The clip at the top of this page is ThreeRT live on an Apple M3 Max at 1600 × 900 (render scale 0.5), every frame as it drew it: 12.8 ms of GPU time a frame at the median, 14.8 ms at the 95th percentile, none over 16.7 ms.</p><p>Amazon Lumberyard Bistro: Amazon Lumberyard (2017). Zero-Day: Mike Winkelmann (Beeple) and Kate Anderson (2019). Both from NVIDIA’s Open Research Content Archive (ORCA), CC BY 4.0, converted from FBX to glTF. Damaged Helmet: Khronos glTF sample models. three.js is an independent open-source project; ThreeRT is not affiliated with it.</p></div></div>diff --git a/site/js/threert.js b/site/js/threert.jsindex 774a0c7..a3eef5d 100644--- a/site/js/threert.js+++ b/site/js/threert.js@@ -61,10 +61,67 @@ export function compare(el) {}, { threshold: 0.5 });io.observe(el);}+ if (d.video) clip(el, [$(".pa", el), $(".pb", el)]);el.cmp = { set, setX, get x() { return x; }, imgs: [ia, ib] };return el.cmp;}+/**+ * A clip over a comparison's two stills (`data-video`, and `data-video-sm` for a small screen): one file with both+ * sides in it, the left one on top of the right one, so the two cannot drift apart. Each half is drawn onto its own+ * pane, under the same divider. The stills stay until the clip plays, and for good where it does not (reduced motion,+ * a data saver, autoplay refused); it plays only while it is on screen. A button pauses it.+ */+function clip(el, panes) {+ const d = el.dataset;+ if (matchMedia("(prefers-reduced-motion: reduce)").matches || navigator.connection?.saveData) return;+ const small = Math.min(screen.width, screen.height) < 700;+ const v = Object.assign(document.createElement("video"), { muted: true, loop: true, playsInline: true, preload: "auto" });+ v.setAttribute("muted", "");+ v.setAttribute("playsinline", "");+ const cvs = panes.map((p) => p.appendChild(document.createElement("canvas")));+ const cxs = cvs.map((c) => c.getContext("2d", { alpha: false }));+ const pp = el.appendChild(Object.assign(document.createElement("button"), { className: "pp", type: "button", hidden: true }));+ const ICON = { pause: `<svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true"><rect x="2" y="1.5" width="3" height="9" fill="currentColor"/><rect x="7" y="1.5" width="3" height="9" fill="currentColor"/></svg>`, play: `<svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true"><path d="M3 1.5v9l7.5-4.5z" fill="currentColor"/></svg>` };+ let w = 0, h = 0, shown = false, visible = false, paused = false;+ const draw = () => {+ if (!v.videoWidth) return;+ if (!w) {+ w = v.videoWidth; h = v.videoHeight / 2;+ for (const c of cvs) { c.width = w; c.height = h; }+ }+ cxs[0].drawImage(v, 0, 0, w, h, 0, 0, w, h);+ cxs[1].drawImage(v, 0, h, w, h, 0, 0, w, h);+ if (!shown) {+ shown = true;+ el.classList.add("playing");+ pp.hidden = false;+ }+ };+ // A frame of the canvas for every frame of the clip, where the browser says when one is up; else every repaint.+ const tick = () => {+ draw();+ if (v.requestVideoFrameCallback) v.requestVideoFrameCallback(tick);+ else if (visible && !paused) requestAnimationFrame(tick);+ };+ const state = () => {+ pp.innerHTML = paused ? ICON.play : ICON.pause;+ pp.setAttribute("aria-label", paused ? "Play the clip" : "Pause the clip");+ if (visible && !paused) v.play().then(() => { if (!v.requestVideoFrameCallback) requestAnimationFrame(tick); }, () => {});+ else v.pause();+ };+ pp.addEventListener("pointerdown", (e) => e.stopPropagation()); // not a drag of the divider+ pp.addEventListener("click", () => { paused = !paused; state(); });+ new IntersectionObserver(([en]) => {+ visible = en.isIntersecting;+ if (visible && !v.src) {+ v.src = (small && d.videoSm) || d.video;+ if (v.requestVideoFrameCallback) v.requestVideoFrameCallback(tick);+ }+ state();+ }, { threshold: 0.05 }).observe(el);+}+/** Plays the 60-pose camera move of both engines in lockstep, wiped like a comparison. */export function sequence(el) {const d = el.dataset, n = +(d.n ?? 60), fps = +(d.fps ?? 10);diff --git a/site/media/bistro/hero-720.mp4 b/site/media/bistro/hero-720.mp4new file mode 100644index 0000000..5c9d057Binary files /dev/null and b/site/media/bistro/hero-720.mp4 differdiff --git a/site/media/bistro/hero-rt.webp b/site/media/bistro/hero-rt.webpnew file mode 100644index 0000000..c66a596Binary files /dev/null and b/site/media/bistro/hero-rt.webp differdiff --git a/site/media/bistro/hero-three.webp b/site/media/bistro/hero-three.webpnew file mode 100644index 0000000..0eaa340Binary files /dev/null and b/site/media/bistro/hero-three.webp differdiff --git a/site/media/bistro/hero.json b/site/media/bistro/hero.jsonnew file mode 100644index 0000000..4046d62--- /dev/null+++ b/site/media/bistro/hero.json@@ -0,0 +1,31 @@+{+ "at": "2026-11-11T18:21:38.264Z",+ "machine": "Apple M3 Max",+ "cores": 16,+ "commit": "81f5da7",+ "width": 1600,+ "height": 900,+ "fps": 60,+ "seconds": 6,+ "reach": 2.2,+ "poses": 360,+ "loop": 718,+ "option_scale": "0.5",+ "bounces": 4,+ "seconds_loop": 11.97,+ "realtime": {+ "at": "2026-11-11T18:28:42.312Z",+ "frames": 724,+ "gpu_ms": {+ "p50": 12.78,+ "p95": 14.75,+ "max": 16.01+ },+ "over_budget": 0,+ "scale": {+ "min": 0.5,+ "p50": 0.5,+ "max": 0.5+ }+ }+}diff --git a/site/media/bistro/hero.mp4 b/site/media/bistro/hero.mp4new file mode 100644index 0000000..1b5e2a2Binary files /dev/null and b/site/media/bistro/hero.mp4 differdiff --git a/site/serve.ts b/site/serve.tsindex 6be1f74..3cd1870 100644--- a/site/serve.ts+++ b/site/serve.ts@@ -22,7 +22,7 @@ const TYPES: Record<string, string> = {".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",".json": "application/json", ".ts": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",".glb": "model/gltf-binary", ".gltf": "model/gltf+json", ".bin": "application/octet-stream", ".hdr": "application/octet-stream", ".exr": "application/octet-stream", ".ktx2": "image/ktx2",- ".dmg": "application/x-apple-diskimage", ".zip": "application/zip",+ ".mp4": "video/mp4", ".dmg": "application/x-apple-diskimage", ".zip": "application/zip",};for (const f of Object.values(VENDOR)) if (!existsSync(f)) console.warn(`missing ${f}: run npm install at the repo root`);diff --git a/site/tools/hero.ts b/site/tools/hero.tsnew file mode 100644index 0000000..c537a0c--- /dev/null+++ b/site/tools/hero.ts@@ -0,0 +1,54 @@+// Encodes the landing page's hero clip from the frames tools/site-hero.ts recorded (out/site-hero/bistro):+// node tools/site-hero.ts ... (ThreeRT live + three.js along Bistro's camera move; site/README.md has the run)+// bun site/tools/hero.ts [--crf 27] [--crf-sm 28]+// -> site/media/bistro/hero.mp4, hero-720.mp4 both sides in one file, three.js on top of ThreeRT, 60 fps, a+// loop (there and back); H.264 so every browser plays it.+// hero.mp4 is the size it was recorded at, hero-720.mp4 for phones+// site/media/bistro/hero-three.webp, hero-rt.webp the clip's first frame: what the page shows until it plays+// site/media/bistro/hero.json how it was recorded (machine, size, scale) and, from the probe+// at the same settings, the GPU time a frame: the footnote's source+// One file for both sides, because two videos drift: js/threert.js draws each half onto its side of the divider.+// Needs ffmpeg on PATH. Sources can be moved with THREERT_OUT (default <repo>/out).+import { $ } from "bun";+import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";+import { join, resolve } from "node:path";+import sharp from "sharp";++const site = resolve(import.meta.dir, "..");+const OUT = process.env.THREERT_OUT ?? join(site, "../out");+const src = join(OUT, "site-hero/bistro");+const media = join(site, "media/bistro");+const args = process.argv.slice(2);+const opt = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);++const meta = JSON.parse(readFileSync(join(src, "meta.json"), "utf8"));+const frames = (d: string, ext: string) => readdirSync(join(src, d)).filter((f) => new RegExp(`^\\d{4}\\.${ext}$`).test(f)).sort();+const rt = frames("threert", "png"), three = frames("three", "jpg");+const n = meta.poses as number;+if (three.length !== n) throw new Error(`three.js: ${three.length} frames, the recording has ${n} poses`);+if (rt.length !== 2 * n - 2) throw new Error(`ThreeRT: ${rt.length} frames, expected ${2 * n - 2} (there and back)`);++// three.js has no history: its way back is its way out, reversed (the same order ThreeRT was recorded in).+const order = [...three.keys(), ...Array.from({ length: n - 2 }, (_, k) => n - 2 - k)];+const list = join(src, "three.ffconcat");+writeFileSync(list, "ffconcat version 1.0\n" + order.map((k) => `file 'three/${three[k]}'\nduration ${1 / meta.fps}`).join("\n") + "\n");++mkdirSync(media, { recursive: true });+const encode = async (name: string, height: number, crf: string) => {+ const out = join(media, name);+ const scale = height === meta.height ? "" : `,scale=-2:${2 * height}:flags=lanczos`;+ // yuv420p + High profile + faststart: plays everywhere and starts before it has all arrived. A key frame a second.+ await $`ffmpeg -hide_banner -loglevel error -y -f concat -safe 0 -i ${list} -framerate ${meta.fps} -i ${join(src, "threert/%04d.png")} -filter_complex ${`[0:v][1:v]vstack=inputs=2${scale},format=yuv420p`} -r ${meta.fps} -c:v libx264 -preset slower -crf ${crf} -profile:v high -g ${meta.fps} -color_primaries bt709 -color_trc bt709 -colorspace bt709 -movflags +faststart -an ${out}`;+ return `${name} ${(statSync(out).size / 1048576).toFixed(1)} MiB`;+};+const sizes = [await encode("hero.mp4", meta.height, opt("--crf", "27")), await encode("hero-720.mp4", 720, opt("--crf-sm", "28"))];++await sharp(join(src, "three", three[0])).webp({ quality: 88, effort: 6 }).toFile(join(media, "hero-three.webp"));+await sharp(join(src, "threert", rt[0])).webp({ quality: 88, effort: 6 }).toFile(join(media, "hero-rt.webp"));+// The times to quote are the probe's (frames back to back, as on screen), when it ran at the recorded settings.+const probe = existsSync(join(src, "probe.json")) ? JSON.parse(readFileSync(join(src, "probe.json"), "utf8")) : null;+const same = probe && probe.width === meta.width && probe.height === meta.height && String(probe.option_scale) === String(meta.option_scale) && probe.bounces === meta.bounces;+if (!same) console.warn("warning: no probe at the recorded settings (node tools/site-hero.ts --probe ...): hero.json has no back-to-back GPU times");+const { threert, ...how } = meta;+writeFileSync(join(media, "hero.json"), JSON.stringify({ ...how, seconds_loop: +(rt.length / meta.fps).toFixed(2), realtime: same ? { at: probe.at, ...probe.threert } : null }, null, 1) + "\n");+console.log(`${sizes.join(", ")} -> ${media}`);diff --git a/tools/lib/live.ts b/tools/lib/live.tsindex a4714fc..b5aeebf 100644--- a/tools/lib/live.ts+++ b/tools/lib/live.ts@@ -80,8 +80,9 @@ export interface Live {quit(): Promise<void>;}-export function startLive(b: Build, bundle: string, o: { scale?: string; env?: Record<string, string>; frameLog?: string; profile?: boolean; room?: string } = {}): Live {- const args = ["live", bundle, "--assets", b.assets, "--presets", b.presets, "--width", "1280", "--height", "720", "--scale", o.scale ?? "0.5"];+export function startLive(b: Build, bundle: string, o: { scale?: string; env?: Record<string, string>; frameLog?: string; profile?: boolean; room?: string; width?: number; height?: number; bounces?: number } = {}): Live {+ const args = ["live", bundle, "--assets", b.assets, "--presets", b.presets, "--width", String(o.width ?? 1280), "--height", String(o.height ?? 720), "--scale", o.scale ?? "0.5"];+ if (o.bounces) args.push("--bounces", String(o.bounces));if (o.room) args.push("--room", o.room);if (o.frameLog) {rmSync(o.frameLog, { force: true });diff --git a/tools/orca/fbx2gltf.py b/tools/orca/fbx2gltf.pyindex eda493d..5f397d0 100644--- a/tools/orca/fbx2gltf.py+++ b/tools/orca/fbx2gltf.py@@ -44,6 +44,12 @@ texdir = os.path.join(out, "textures")os.makedirs(texdir, exist_ok=True)bpy.ops.wm.read_factory_settings(use_empty=True)+# Blender 5.1's FBX importer sets lamp.cycles.cast_shadow when Cycles is loaded, and Cycles' light settings no longer+# have it: the import of any FBX with a light stops there. Nothing here renders with Cycles, so it is unloaded first+# (the importer checks for lamp.cycles); the lights themselves are removed below.+import addon_utils+if addon_utils.check("cycles")[1]:+ addon_utils.disable("cycles")bpy.ops.import_scene.fbx(filepath=os.path.abspath(args.fbx), use_image_search=False, use_anim=not args.no_animations)print(f"orca: imported {args.fbx} in {time.time() - t0:.1f} s", flush=True)diff --git a/tools/site-hero.ts b/tools/site-hero.tsnew file mode 100644index 0000000..e4bd544--- /dev/null+++ b/tools/site-hero.ts@@ -0,0 +1,138 @@+// The landing page's hero clip: Bistro night along the scene's own camera move, three.js and ThreeRT on the same poses,+// 60 poses a second, there and back so it loops.+//+// node tools/site-hero.ts [--width 1920] [--height 1080] [--seconds 6] [--reach 6] [--scale auto|0.25..1]+// [--bounces 4] [--only threert|three] [--probe] [--force]+//+// ThreeRT is the live renderer in lockstep at 60 fps: one frame a pose, every frame of the clip is one frame it drew+// (its history carried from the frame before, as on screen), and frames.jsonl has the GPU time of each. --probe runs+// the move without writing frames, back to back as on screen, and writes those times to probe.json. Pick the size and+// scale with it: `--probe --scale auto` shows the scale dynamic resolution holds at 60 fps on this machine; record at+// that scale, fixed (a recording pauses for a PNG after every frame, and dynamic resolution reads that as headroom),+// then `--probe` once more at the recorded settings: those are the times the page quotes.+// three.js is the tuned WebGL scene (tools/three/page.ts), a JPEG a pose; it has no history, so the way back reuses+// the way out.+// The move is the scene's FBX camera clip from 0 s to --reach s, taken in --seconds and eased at both ends (it turns+// round there).+// -> out/site-hero/bistro/threert/NNNN.png (2n - 2 frames), three/NNNN.jpg (n), frames.jsonl, meta.json+// site/tools/hero.ts encodes them into site/media.+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { cpus } from "node:os";+import { join } from "node:path";+import { BISTRO } from "../scenes/bistro.ts";+import { bundleGame } from "./bundle-game.ts";+import { frameStats, requireQuietGpu, rendererBin } from "./lib/bench.ts";+import { gltfCameraPath } from "./lib/gltf-camera.ts";+import { startLive } from "./lib/live.ts";+import { bundlePage, launch, root, serve } from "./three/browser.ts";++const args = process.argv.slice(2);+const opt = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);+const width = Number(opt("--width", "1920")), height = Number(opt("--height", "1080"));+const seconds = Number(opt("--seconds", "6")), scale = opt("--scale", "auto"), bounces = opt("--bounces", "4");+const only = opt("--only", ""), probe = args.includes("--probe");+/** How much of the camera clip the move covers (s of the clip, from 0), in --seconds of time: under --seconds, slower+ * than the clip plays. A slow move is what a temporal renderer resolves best, and what sits best behind a headline. */+const reach = Number(opt("--reach", String(seconds)));+const FPS = 60;++const dir = join(root, "out/site-hero/bistro");+mkdirSync(dir, { recursive: true });+const path = gltfCameraPath(join(root, BISTRO), "Camera");+const n = Math.round(seconds * FPS);+// Eased: no speed at either end, where the move turns round.+const out = Array.from({ length: n }, (_, k) => path.at((reach * (1 - Math.cos((Math.PI * k) / (n - 1)))) / 2));+// There and back without repeating an end pose: 0 .. n-1, n-2 .. 1.+const loop = [...out.keys(), ...Array.from({ length: n - 2 }, (_, k) => n - 2 - k)];+const pad = (k: number) => String(k).padStart(4, "0");+const fresh = (name: string) => {+ const d = join(dir, name);+ rmSync(d, { recursive: true, force: true });+ mkdirSync(d, { recursive: true });+ return d;+};++if (only !== "three") {+ const bundle = join(root, "out/bundles/bistro.js");+ await bundleGame(join(root, "scenes/bistro.ts"), bundle);+ const frames = probe ? join(dir, "probe") : fresh("threert");+ mkdirSync(frames, { recursive: true });+ const frameLog = join(dir, probe ? "probe.jsonl" : "frames.jsonl");+ requireQuietGpu();+ const b = { bin: rendererBin, assets: root, presets: join(root, "presets"), bundles: join(root, "out/bundles"), label: "site-hero" };+ const live = startLive(b, bundle, { scale, frameLog, width, height, bounces: Number(bounces) });+ await live.firstFrame;+ live.send({ cmd: "camera", ...out[0] });+ await new Promise((ok) => setTimeout(ok, 5000));+ live.send({ cmd: "lockstep", dt: 1 / FPS });+ // One loop unrecorded, so the recorded one starts with the history a loop leaves (the clip's seam).+ const lap = async (record: boolean) => {+ for (const [i, k] of loop.entries()) {+ if (record && !probe) {+ const f = join(frames, `${pad(i)}.png`);+ live.send({ cmd: "camera", ...out[k], frames: 1, snapshot: f });+ await live.wait((l) => l.includes(f), 60_000);+ } else {+ const id = `${record ? "r" : "w"}${i}`;+ live.send({ cmd: "camera", ...out[k], frames: 1, sync: id });+ await live.wait((l) => l.endsWith(`sync ${id}`), 60_000);+ }+ }+ };+ await lap(false);+ const mark = readFileSync(frameLog, "utf8").trim().split("\n").length;+ await lap(true);+ await live.quit();+ type F = { gpu: number; scale?: number };+ const logged = readFileSync(frameLog, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as F).slice(mark);+ const gpu = frameStats(logged.map((f) => f.gpu));+ const scales = logged.map((f) => f.scale).filter((s): s is number => typeof s === "number").sort((a, b) => a - b);+ const over = logged.filter((f) => f.gpu > 1000 / FPS).length;+ const report = {+ frames: logged.length, gpu_ms: { p50: +gpu.p50.toFixed(2), p95: +gpu.p95.toFixed(2), max: +Math.max(...logged.map((f) => f.gpu)).toFixed(2) },+ over_budget: over, scale: scales.length ? { min: scales[0], p50: scales[scales.length >> 1], max: scales.at(-1) } : scale,+ };+ console.log(`ThreeRT ${width} x ${height}, --scale ${scale}, ${bounces} bounces: ${JSON.stringify(report)}`);+ // The probe draws its frames back to back, as on screen; a recording waits for a PNG after each. So the probe's+ // times are the ones to quote, and the recording should use the scale the probe holds.+ if (probe) writeFileSync(join(dir, "probe.json"), JSON.stringify({ at: new Date().toISOString(), width, height, reach, option_scale: scale, bounces: Number(bounces), threert: report }, null, 1) + "\n");+ if (!probe) {+ const chip = execFileSync("sysctl", ["-n", "machdep.cpu.brand_string"], { encoding: "utf8" }).trim();+ const commit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: root, encoding: "utf8" }).trim();+ writeFileSync(join(dir, "meta.json"), JSON.stringify({ at: new Date().toISOString(), machine: chip, cores: cpus().length, commit, width, height, fps: FPS, seconds, reach, poses: n, loop: loop.length, option_scale: scale, bounces: Number(bounces), threert: report }, null, 1) + "\n");+ }+}++if (only !== "threert" && !probe) {+ const three = fresh("three");+ const { server, origin } = await serve();+ const browser = await launch(args.includes("--verbose") ? (l) => console.log(l) : undefined);+ try {+ const page = await bundlePage("bistro-hero", join(root, "scenes/bistro.ts"));+ // A batch of poses a page. The page keeps its frames; they are read one a message (a run's whole result, with+ // 1080p frames in it, is more than a DevTools message carries: the tab never answers).+ const BATCH = 60;+ for (let k0 = 0; k0 < n; k0 += BATCH) {+ const poses = out.slice(k0, k0 + BATCH);+ const pq = new URLSearchParams({ probe: "0", frames: "4", width: String(width), height: String(height), path: JSON.stringify(poses.map((p) => ({ position: p.pos, target: p.target, fov: (2 * Math.atan(p.tan) * 180) / Math.PI }))) });+ const tab = await browser.open(`${origin}${page.html}?${pq}`);+ try {+ const done = await tab.evaluate<string>(`new Promise((ok) => { const k = setInterval(() => { if (window.__result) { clearInterval(k); ok(JSON.stringify({ ok: window.__result.ok, error: window.__result.error })); } }, 200); })`, 1_800_000);+ const res = JSON.parse(done) as { ok: boolean; error?: string };+ if (!res.ok) throw new Error(`three.js (${k0}): ${res.error}`);+ for (let i = 0; i < poses.length; i++) {+ const u = await tab.evaluate<string>(`(window.__frames ??= JSON.parse(window.__result.images.path))[${i}]`);+ writeFileSync(join(three, `${pad(k0 + i)}.jpg`), Buffer.from(u.split(",")[1], "base64"));+ }+ } finally {+ await tab.close();+ }+ console.log(`three.js ${Math.min(n, k0 + BATCH)} / ${n}`);+ }+ } finally {+ browser.close();+ server.close();+ }+}+console.log(`-> ${dir}`);