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
Live: moving objects leave no copies of themselves (uncovered history, locks, reflections); bench-object-ghosting (#155)
Evan (Yifeng) Wangc946cc96bdb0
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex d769323..26e644b 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1600,6 +1600,32 @@ none of them it traces its light there. Two limits are known and held by tests ssunlit mirror wall 5 % bright), and a surface seen in a reflection takes the sky's light from it, unshadowedbelow a voxel's size.+## Moving objects in the live view++The live view's histories (the irradiance and specular ones on the traced grid, the upscaler's colour on the output+grid) follow a moving object by its motion vectors (`motion_in`), and three rules keep it from leaving copies of+itself where it was (`live.wgsl`; measured by `node tools/bench-object-ghosting.ts`: a dragged device, a light thrown+over a polished floor, the camera still):++- **What it uncovers starts again.** The g-buffer says whether a surface is a moving object's (`GB.moves`). A sample+ whose own surface stands still and lies behind the moving surface that was nearest there a frame ago is uncovered,+ and its history goes (`judge`; in every output pixel its verdict reaches, `upscale`, where what went was moving: a+ still scene's jitter finds a gone edge now and then, and dropping it whole there flickered). Before, the band behind a+ moving edge kept a line of the object's colour a frame (the nearest of the nine samples there is still the object,+ so the band reprojected with it, and the clamp in motion kept its colour).+- **Locks go with it.** A thin feature's lock on a moving surface is not carried by the two cameras (`lock_carry`),+ and a carried lock that lands on a moving surface is dropped (`track`): a moving screen's text left copies of+ itself for a jitter sequence.+- **Reflections follow what moves past them.** While the lighting is live (a moving object sets it), a still+ surface's specular history is clipped to this frame's neighbourhood (`SPEC_CLIP` deviations plus `SPEC_CLIP_REL`+ of its luminance): a light carried past a polished floor left its reflection along its path.++++Not covered: a fast light's effect on diffuse lighting (a shadow it casts) still lags by a few frames (the diffuse+history and its anti-lag), and the band just uncovered starts from this frame's samples (more aliased for a frame or+two, as any disocclusion).+## GlassA transmissive material (`transmission`, `ior`, `roughness`) is a rough dielectric interface, Walter et al. 2007diff --git a/docs/WORKFLOW.md b/docs/WORKFLOW.mdindex dbb2bf6..693ace5 100644--- a/docs/WORKFLOW.md+++ b/docs/WORKFLOW.md@@ -67,7 +67,7 @@ highest tier any of its changes needs.| **D** docs | only `docs/`, READMEs, comments | CI || **T** tools / TypeScript | `tools/`, `tests/` harness, `ue5/` scripts, `packages/*` without effect on what the renderer draws | `npm run typecheck`, `npm test`; `npm run test:render` if `packages/scene`, `packages/gameplay` or `tests/render` changed || **R1** renderer, existing scenes unchanged | new kernel / live code behind a feature bit, new DSL features, new passes that only run when a scene uses them | T, plus `cargo test --release`, `test:render` (no new failures against main), byte-identity of the catalog scenes (offline, software traversal) and of every `test:render` output (`node tools/render-identity.ts --a <main> --b <branch>`: live tests included), **perf smoke**, crops of the new feature |-| **R2** renderer, existing scenes change | anything that changes what existing scenes render, or the live passes they run (denoising, temporal, reflections, post) | R1 without byte-identity, plus `node tools/bench-ghosting.ts --quick --check` (Bistro) and `--scene kabukicho` (wet signs: the reflection stress case), `test:layer-b`, crops before / after; a change to the live passes also `node tools/bench-window.ts` on main and the branch (the play window against offline: still, the Bistro slice, Tokyo at dusk and in motion) |+| **R2** renderer, existing scenes change | anything that changes what existing scenes render, or the live passes they run (denoising, temporal, reflections, post) | R1 without byte-identity, plus `node tools/bench-ghosting.ts --quick --check` (Bistro) and `--scene kabukicho` (wet signs: the reflection stress case), `test:layer-b`, crops before / after; a change to the live passes also `node tools/bench-window.ts` on main and the branch (the play window against offline: still, the Bistro slice, Tokyo at dusk and in motion), and a change to the temporal passes `node tools/bench-object-ghosting.ts --repeat 3` on both (the camera still, an object moving: a dragged device, a thrown light over a polished floor) || **R3** hot path or perf claim | the PR claims a speed-up, or changes the cost of work existing scenes do every frame (trace loop, light sampling, filter passes, resolution control) | R2, plus **full A/B timing** (Bistro night still and moving and the 3 × 3 Bistro district along its camera path at the 0.5 floor, main and branch alternated: `node tools/bench-district.ts`) |- **render-identity** (R1, and any change that says it changes no picture): test-render whole, twice on each build,diff --git a/docs/images/object-ghosting.jpg b/docs/images/object-ghosting.jpgnew file mode 100644index 0000000..fa94093Binary files /dev/null and b/docs/images/object-ghosting.jpg differdiff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgslindex f69bcb3..7aad7b7 100644--- a/renderer/shaders/live.wgsl+++ b/renderer/shaders/live.wgsl@@ -222,16 +222,24 @@ fn oct_enc(n: vec3<f32>) -> vec2<f32> {// The g-buffer (`gbuffer`), 8 bytes: octahedral normal (snorm16 x 2), view depth// (0 = sky) and roughness (f16). The surface tests compare depths relatively (2-4 %), far coarser than f16. One fetch// per tap for the specular filter and the history tests (it was 16 bytes, and roughness a second 16-byte fetch from the-// albedo / emission history): those passes are bandwidth-bound.-struct GB { n: vec3<f32>, depth: f32, rough: f32 };+// albedo / emission history): those passes are bandwidth-bound. `moves`: the surface is a moving object's (the trace's+// motion, `motion_in` w), kept in the roughness's sign (-1 - roughness), so the next frame knows what was in front of+// what it uncovers was moving (`judge`) and that a lock on it moved with it (`lock_carry`).+struct GB { n: vec3<f32>, depth: f32, rough: f32, moves: bool };-fn gb_pack(n: vec3<f32>, depth: f32, rough: f32) -> vec2<u32> {- return vec2<u32>(pack2x16snorm(oct_enc(n)), pack2x16float(vec2<f32>(min(depth, 6.0e4), rough)));+// The second word: view depth, roughness and `moves`.+fn gb_dr(depth: f32, rough: f32, moves: bool) -> u32 {+ return pack2x16float(vec2<f32>(min(depth, 6.0e4), select(rough, -1.0 - rough, moves)));+}++fn gb_pack(n: vec3<f32>, depth: f32, rough: f32, moves: bool) -> vec2<u32> {+ return vec2<u32>(pack2x16snorm(oct_enc(n)), gb_dr(depth, rough, moves));}fn gb_unpack(g: vec2<u32>) -> GB {let dr = unpack2x16float(g.y);- return GB(oct_dec(g.x), dr.x, dr.y);+ let moves = dr.y < -0.5;+ return GB(oct_dec(g.x), dr.x, select(dr.y, -1.0 - dr.y, moves), moves);}const RESOLVE_N: u32 = 8u;@@ -792,6 +800,10 @@ fn spec_history(pp: vec3<f32>, n: vec3<f32>, t: f32, rough: f32, virt: bool) ->// The most a specular history may trail behind its reflection, output pixels (`stemporal`).const SPEC_TRAIL: f32 = 2.0;+// How far from this frame's neighbourhood mean a specular history may lie, in deviations of the neighbourhood+// (`stemporal`'s variance clipping).+const SPEC_CLIP: f32 = 2.0;+const SPEC_CLIP_REL: f32 = 0.5;// Specular temporal accumulation on the traced grid (UE 5.8 Lumen reflections, LumenReflectionDenoiserTemporal.usf): the// surface history and the reflection-hit one (reprojected through the mirror image of what it shows); the one closer to@@ -819,8 +831,9 @@ fn stemporal(@builtin(global_invocation_id) gid: vec3<u32>) {depth = dot(p - L.cur.pos.xyz, L.cur.fwd.xyz);}let cur = sample_specular(q);- // This frame's neighbourhood mean (same surface), in YCoCg.+ // This frame's neighbourhood mean and spread (same surface), in YCoCg.var m1 = vec3<f32>(0.0);+ var m2 = vec3<f32>(0.0);var mn = 0.0;for (var k = 0; k < 9; k++) {let qx = i32(gid.x) + k % 3 - 1;@@ -835,10 +848,13 @@ fn stemporal(@builtin(global_invocation_id) gid: vec3<u32>) {ok = s.color.w == 0.0;}if (!ok) { continue; }- m1 += ycocg(sample_specular(j));+ let yq = ycocg(sample_specular(j));+ m1 += yq;+ m2 += yq * yq;mn += 1.0;}let smean = m1 / max(mn, 1.0);+ let ssd = sqrt(max(m2 / max(mn, 1.0) - smean * smean, vec3<f32>(0.0)));// Reflection hit distance for the mirror-image reprojection: on near mirrors the resolved one (pass `refl`).let st = select(px.spec.w, refl_res[q].w, refl_res[q].w > 0.0 && rough < NEAR_MIRROR);let mv = motion_in[q];@@ -874,7 +890,18 @@ fn stemporal(@builtin(global_invocation_id) gid: vec3<u32>) {var surf = select(0.0, 0.8, length(smean - yv) > length(smean - ys) + 0.01 / exposure_scale());surf = select(surf, 1.0, hv.w <= 0.0);surf = select(surf, 0.0, hs.w <= 0.0 && hv.w > 0.0);- let hy = mix(yv, ys, surf);+ // The history held within SPEC_CLIP deviations of this frame's neighbourhood (variance clipping, as Lumen's+ // reflection temporal clamps its history): what a still surface reflects can move while the surface and the camera+ // hold still (a light carried past a polished floor), and nothing else tells its history so. Unclipped, the+ // reflection of a thrown orb stayed on the floor along its whole path for the length of the history.+ // While the scene's lighting changes (`mode.z`: something moved, a light switched), as the diffuse anti-lag: a+ // settled scene has nothing to find, and clipping it cuts what the history averaged out of one sample a pixel.+ // (Plus SPEC_CLIP_REL of the neighbourhood's luminance: one sample a pixel is heavy-tailed, most of the nine are+ // dark next to a rare bright one, and a deviation's box alone pulled a right history down and let the next bright+ // sample flash, a square at a time. What moved past is many times brighter than what is left.)+ let slack = SPEC_CLIP * ssd + vec3<f32>(SPEC_CLIP_REL * abs(smean.x) + 0.002 / exposure_scale(), 0.0, 0.0);+ var hy = mix(yv, ys, surf);+ if (L.mode.z != 0u && mn >= 3.0) { hy = clamp(hy, smean - slack, smean + slack); }// The history's length is the pixel's own (until 2026-11-13 every pixel's was held to 2 .. 12 frames by roughness// while the camera moved or turned at all, and to 4 for 8 frames after it translated): HIST_MOVING at a pixel a// frame, as the diffuse; and no longer than keeps its trail behind the reflection (frames x parallax) within@@ -892,7 +919,7 @@ fn stemporal(@builtin(global_invocation_id) gid: vec3<u32>) {s_out = select(max(s_out, vec3<f32>(0.0)), vec3<f32>(0.0), non_finite(s_out));spec_hist[this_half(q)] = vec4<f32>(s_out, count_s);spec_store(0u, q, vec4<f32>(s_out, count_s));- gbuffer[this_half(q)] = gb_pack(n, depth, rough);+ gbuffer[this_half(q)] = gb_pack(n, depth, rough, mv.w > 0.5 && t > 0.0);}// The specular filter (`spec_filter`'s kernel) on the traced grid: three passes over `spec_pp`, slot 0 -> 1 -> 0 -> 1.@@ -1043,7 +1070,9 @@ fn track(@builtin(global_invocation_id) gid: vec3<u32>) {let fw = atomicLoad(&lock_fwd[q]);atomicStore(&lock_fwd[q], 0u);var was = Carried(0.0, 0.0, 0.0, vec2<f32>(0.0), false);- if (fw != 0u && L.size.w == 0u && ps.x > 0) { was = carry((fw & 0x1ffffffu) - 1u); }+ // (Not onto a moving object's surface: the thing locked there a frame ago has moved, likely with the object that+ // started moving under it.)+ if (fw != 0u && L.size.w == 0u && ps.x > 0 && motion_in[q].w <= 0.5) { was = carry((fw & 0x1ffffffu) - 1u); }var life = max(was.life - 1.0 / jitter_phases(), 0.0);var lz = was.depth;var at = clamp(was.at - vec2<f32>(f32(gid.x), f32(gid.y)), vec2<f32>(0.0), vec2<f32>(0.999));@@ -1198,8 +1227,12 @@ fn lock_carry(@builtin(global_invocation_id) gid: vec3<u32>) {let p = gid.y * L.isz.z + gid.x;let c = carry(p);let g = gb_unpack(gbuffer[last_half(p)]);+ // (A lock on a moving object's surface went with it: the two cameras cannot take it there, and left where it was+ // it kept the object's light in the history over whatever it uncovered, a copy of its screen's text a frame. It+ // is found again where a sample next shows the thing.)+ if (g.moves) { return; }if (c.life > 0.0 && c.was > 0.0 && (g.depth <= 0.0 || c.was < g.depth)) {- gbuffer[last_half(p)].y = pack2x16float(vec2<f32>(min(c.was, 6.0e4), g.rough));+ gbuffer[last_half(p)].y = gb_dr(c.was, g.rough, g.moves);}if (c.life * jitter_phases() <= 1.0 || !c.ahead) { return; }let q = vec2<i32>(floor(c.at));@@ -1229,11 +1262,11 @@ fn flicker_at(q: u32) -> Flicker {// history there), the motion its output pixels reproject by: the surface nearest the camera among the nine samples// around (the sky the farthest), since an edge moves with what is in front of it; and whether its history is of// something that is gone.-struct Judged { d: vec3<f32>, lum: f32, vel: vec2<f32>, gone: bool };+struct Judged { d: vec3<f32>, lum: f32, vel: vec2<f32>, gone: bool, moved: bool };fn judged_at(q: u32) -> Judged {let v = up_state[judged_slot(q)];let b = unpack2x16float(v.y);- return Judged(vec3<f32>(unpack2x16float(v.x), b.x), b.y, unpack2x16float(v.z), v.w != 0u);+ return Judged(vec3<f32>(unpack2x16float(v.x), b.x), b.y, unpack2x16float(v.z), v.w != 0u, v.w == 2u);}@compute @workgroup_size(8, 8, 1)@@ -1269,6 +1302,7 @@ fn judge(@builtin(global_invocation_id) gid: vec3<u32>) {var d = vec3<f32>(0.0);var l = -1.0;var gone = false;+ var gone_moving = false;if (L.size.w == 0u) {let up = vec2<f32>(f32(L.size.x), f32(L.size.y)) / vec2<f32>(f32(iw), f32(ih));// Where this sample's point was a frame ago (output pixels; a pixel's centre at + 0.5).@@ -1311,15 +1345,27 @@ fn judge(@builtin(global_invocation_id) gid: vec3<u32>) {}let pc = vec2<i32>(floor(was * vec2<f32>(ps) / vec2<f32>(f32(L.size.x), f32(L.size.y))));var was_near = 1.0e30;+ var was_moving = false;for (var k = 0; k < 9; k++) {let x = pc.x + k % 3 - 1;let y = pc.y + k / 3 - 1;if (x < 0 || y < 0 || x >= ps.x || y >= ps.y) { continue; }- let zq = gb_unpack(gbuffer[last_half(u32(y * ps.x + x))]).depth;- was_near = min(was_near, select(1.0e29, zq, zq > 0.0));+ let gq = gb_unpack(gbuffer[last_half(u32(y * ps.x + x))]);+ let zq = select(1.0e29, gq.depth, gq.depth > 0.0);+ if (zq < was_near) {+ was_near = zq;+ was_moving = gq.moves;+ }}let now_near = select(near * zr, 1.0e29, near >= 1.0e29);- if (was_near < 1.0e29 && now_near > was_near * (1.0 + UP_GONE) + 0.01) {+ // Uncovered by something moving: this sample's own surface (not the nearest of the nine) stands still+ // and lies behind the moving object's surface that was nearest here. The band behind a moving edge+ // takes the edge's motion (the nearest of the nine is still the object), so its history is the+ // object's, and the clamp in motion keeps it (the object's colour is among the nine): each frame+ // left a line of it where the edge had been.+ let own = select(1.0e29, sample_vel[q].z * zr, sample_vel[q].z > 0.0);+ let uncovered = was_moving && motion_in[q].w <= 0.5 && was_near < 1.0e29 && own > was_near * (1.0 + UP_GONE) + 0.01;+ if (was_near < 1.0e29 && (uncovered || now_near > was_near * (1.0 + UP_GONE) + 0.01)) {var clo = vec3<f32>(1.0e30);var chi = vec3<f32>(-1.0e30);// (And no thin feature's lock alive among the nine: a lamp the samples miss this frame is not gone.@@ -1336,7 +1382,12 @@ fn judge(@builtin(global_invocation_id) gid: vec3<u32>) {alive = max(alive, unpack2x16float(up_state[this_half(j)].z).x);}let hm = hsum / hn;- gone = alive <= 0.0 && lum(abs(hm - clamp(hm, clo, chi))) > UP_STALE * lum(hm) + 0.01 / exposure_scale();+ // (What was in front and is gone was a moving object's surface: it went, the jitter did not take it+ // out of the nine. No colour asked: a rim half the object's light, half what it uncovers, lies+ // within the noisy range of the samples of what it uncovers, and stayed a line where the object's+ // edge was, one a frame, fading over UP_SAMPLES frames.)+ gone = alive <= 0.0 && (was_moving || lum(abs(hm - clamp(hm, clo, chi))) > UP_STALE * lum(hm) + 0.01 / exposure_scale());+ gone_moving = was_moving;}}}@@ -1344,7 +1395,8 @@ fn judge(@builtin(global_invocation_id) gid: vec3<u32>) {// A locked sample's distance from the history's range is no finding (a lamp finer than a pixel lies above it// whenever a sample hits it).d *= 1.0 - locked(q);- up_state[judged_slot(q)] = vec4<u32>(pack2x16float(d.xy), pack2x16float(vec2<f32>(d.z, l)), pack2x16float(vel), u32(gone));+ // (w: 1 gone, 2 gone with what was in front moving.)+ up_state[judged_slot(q)] = vec4<u32>(pack2x16float(d.xy), pack2x16float(vec2<f32>(d.z, l)), pack2x16float(vel), select(u32(gone), 2u, gone && gone_moving));}// `reject`: per traced pixel, into `spec_pp`'s slot 0 (free once the specular filter is done; f16): the correction@@ -1396,10 +1448,14 @@ fn reject(@builtin(global_invocation_id) gid: vec3<u32>) {let found = wsum / wall;drop = clamp(abs(mean) * keep / (UP_REJECT * level / wsum + 0.01 / e), 0.0, 1.0) * found + (1.0 - found);}- // (Its history is of something that is gone from in front of this: all of it goes.)- if (judged_at(q).gone) {+ // (Its history is of something that is gone from in front of this: all of it goes; and where what went was moving,+ // in every output pixel this sample's verdict reaches, `upscale`: drop 2 says so. Not for a still scene's gone: the+ // jitter alone finds one at an edge now and then, and dropped whole every time, a held Bistro flickered half as+ // much again, Kabukichō twice.)+ let jq = judged_at(q);+ if (jq.gone) {delta = vec3<f32>(0.0);- drop = 1.0;+ drop = select(1.0, 2.0, jq.moved);}spec_store(0u, q, vec4<f32>(clamp(delta, vec3<f32>(-6.0e4), vec3<f32>(6.0e4)), drop));}@@ -1480,15 +1536,21 @@ fn upscale(@builtin(global_invocation_id) gid: vec3<u32>) {let ft = rc - floor(rc);var verdict = vec4<f32>(0.0);var vsum = 0.0;+ var gone_near = false;for (var k = 0; k < 4; k++) {let qx = f0.x + (k & 1);let qy = f0.y + (k >> 1u);if (qx < 0 || qy < 0 || qx >= iw || qy >= ih) { continue; }let bw = select(1.0 - ft.x, ft.x, (k & 1) == 1) * select(1.0 - ft.y, ft.y, (k >> 1u) == 1);- verdict += spec_load(0u, u32(qy * iw + qx)) * bw;+ let v = spec_load(0u, u32(qy * iw + qx));+ // (A history of something gone, `reject`'s drop 2, goes wherever its verdict reaches: blended with its+ // neighbours' it left part of a moving object's edge where the edge had been, a dashed line a frame.)+ gone_near = gone_near || (v.w > 1.5 && bw > 0.0);+ verdict += vec4<f32>(v.xyz, min(v.w, 1.0)) * bw;vsum += bw;}verdict = select(vec4<f32>(0.0, 0.0, 0.0, 1.0), verdict / vsum, vsum > 1e-4);+ if (gone_near) { verdict = vec4<f32>(0.0, 0.0, 0.0, 1.0); }let vel = judged_at(u32(bc.y * iw + bc.x)).vel;var hist = vec4<f32>(0.0);if (L.size.w == 0u) {diff --git a/tools/bench-object-ghosting.ts b/tools/bench-object-ghosting.tsnew file mode 100644index 0000000..d6b2a3a--- /dev/null+++ b/tools/bench-object-ghosting.ts@@ -0,0 +1,140 @@+// Ghosting of moving objects in the live viewport. bench-ghosting moves the camera; here the camera holds still and one+// object moves, the way an app's drag or a physics body moves it: a pose a frame, by host message. Two scenes:+// device: a device dragged over a workbench (object-ghosting/device.game.ts, Pocket Bench's Tab5 made of boxes);+// orb: a glowing orb thrown across a dark room with a polished floor (object-ghosting/orb.game.ts, the Atrium of+// threert/native-app-template at night): a moving light, seen directly and in the floor's reflection. What the moving object leaves behind (copies+// of its edges where it was, its screen smeared over the wall) is measured against a converged frame of the same pose+// (history reset, then accumulated), as bench-ghosting does.+//+// node tools/bench-object-ghosting.ts [--scene device|orb|all] [--scale 0.5|1] [--bin path] [--tag name] [--repeat n]+//+// Moves (one pose a frame at 60 fps):+// device slide: x -0.18 -> +0.18 m in 0.5 s (about 13 px a frame at 1280 x 720), then held;+// device lift: y 0.2 -> 0.34 m and a quarter turn of yaw in 0.4 s, then held;+// orb throw: x -0.6 -> +0.6 m, 0.12 m over the floor, in 0.5 s (2.4 m/s), then held.+// Shots: the move's midpoint, and 0 / 0.1 / 0.3 s after it ends. Per shot, over the band the device sweeps: mean dE,+// p95, and trail_px (p95 over rows of the longest horizontal run of pixels off by dE > 10).+import { spawn, execFileSync } from "node:child_process";+import { createInterface } from "node:readline";+import { existsSync, mkdirSync } from "node:fs";+import { join, resolve } from "node:path";+import { bundleGame } from "./bundle-game.ts";++const root = resolve(import.meta.dirname, "..");+const args = process.argv.slice(2);+const flag = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);+const bin = resolve(flag("--bin", process.env.THREERT_BIN ?? join(root, "renderer/target/release/threert-render")));+const scale = flag("--scale", "0.5");+const repeats = Number(flag("--repeat", "1"));+const tag = flag("--tag", "run");+const refFrames = Number(flag("--ref-frames", "256"));+const out = join(root, "out/bench-object-ghosting", tag);+const refs = join(root, "out/bench-object-ghosting/refs", scale);+mkdirSync(out, { recursive: true });+mkdirSync(refs, { recursive: true });+const env = { ...process.env, THREERT_FREEZE_TIME: "1", THREERT_EXPOSURE_SNAP: "1", THREERT_MOTION_BLUR: "0" };++type Pose = { x: number; y: number; z: number; ry: number };+const lerp = (a: Pose, b: Pose, f: number): Pose => ({ x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f, z: a.z + (b.z - a.z) * f, ry: a.ry + (b.ry - a.ry) * f });+type Move = { from: Pose; to: Pose; frames: number; band: string };+const SCENES: Record<string, Record<string, Move>> = {+ device: {+ slide: { from: { x: -0.18, y: 0.2, z: 0, ry: 0 }, to: { x: 0.18, y: 0.2, z: 0, ry: 0 }, frames: 30, band: "0.05,0.3,0.95,0.7" },+ lift: { from: { x: 0, y: 0.2, z: 0, ry: 0 }, to: { x: 0, y: 0.34, z: 0, ry: Math.PI / 2 }, frames: 24, band: "0.25,0.05,0.75,0.7" },+ },+ orb: {+ throw: { from: { x: -0.6, y: 0.12, z: -0.1, ry: 0 }, to: { x: 0.6, y: 0.12, z: -0.1, ry: 0 }, frames: 30, band: "0,0.3,1,1" },+ },+};+const sceneArg = flag("--scene", "all");+const sceneNames = sceneArg === "all" ? Object.keys(SCENES) : [sceneArg];+const SHOTS = [["mid", -1], ["end", 0], ["end+0.1s", 6], ["end+0.3s", 18]] as const;++class Live {+ private p;+ private waiters: ((l: string) => boolean)[] = [];+ private syncs = 0;+ constructor(bundle: string) {+ this.p = spawn(bin, ["live", bundle, "--assets", root, "--width", "1280", "--height", "720", "--scale", scale], { stdio: ["pipe", "ignore", "pipe"], env });+ createInterface({ input: this.p.stderr! }).on("line", (l) => {+ if (process.env.VERBOSE) console.error(l);+ this.waiters = this.waiters.filter((w) => !w(l));+ });+ }+ send(o: object) { this.p.stdin!.write(JSON.stringify(o) + "\n"); }+ wait(pred: (l: string) => boolean) { return new Promise<string>((r) => this.waiters.push((l) => (pred(l) ? (r(l), true) : false))); }+ /** `n` frames; resolves when rendered (with a snapshot: saved). */+ step(n: number, snapshot?: string) {+ const id = `s${++this.syncs}`;+ const done = snapshot ? this.wait((l) => l.includes(`snapshot ${snapshot}`)) : this.wait((l) => l === `live: sync ${id}`);+ this.send({ cmd: "frames", n, ...(snapshot ? { snapshot } : { sync: id }) });+ return done;+ }+ pose(p: Pose) { this.send({ cmd: "host", messages: [{ t: "pose", ...p }] }); }+ quit() { this.send({ cmd: "quit" }); }+}++async function start(bundle: string) {+ const live = new Live(bundle);+ await live.wait((l) => l.includes("fps on"));+ live.send({ cmd: "lockstep", dt: 1 / 60 });+ await live.step(60);+ return live;+}++const refFile = (move: string, shot: string) => join(refs, `${move}-${shot}.png`);+const rows: { move: string; shot: string; mean: number; p95: number; trail: number }[] = [];+const allMoves: Record<string, Move> = {};+for (const sceneName of sceneNames) {+ const MOVES = Object.fromEntries(Object.entries(SCENES[sceneName]).map(([k, v]) => [`${sceneName}-${k}`, v]));+ Object.assign(allMoves, MOVES);+ const bundle = join(root, `out/bundles/object-ghosting-${sceneName}.js`);+ await bundleGame(join(root, `tools/object-ghosting/${sceneName}.game.ts`), bundle);+ const shotPose = (m: Move, at: number) => (at < 0 ? lerp(m.from, m.to, 0.5) : m.to);+ if (!Object.keys(MOVES).every((mv) => SHOTS.every(([s]) => existsSync(refFile(mv, s))))) {+ console.log(`references: ${refFrames} frames each at scale ${scale}…`);+ const live = await start(bundle);+ for (const [mv, m] of Object.entries(MOVES)) for (const [s, at] of SHOTS) {+ live.pose(shotPose(m, at));+ live.send({ cmd: "reset" });+ await live.step(refFrames, refFile(mv, s));+ }+ live.quit();+ }++ const live = await start(bundle);+ for (let rep = 0; rep < repeats; rep++) {+ for (const [mv, m] of Object.entries(MOVES)) {+ live.pose(m.from);+ await live.step(90); // settled at the start pose+ for (let k = 1; k <= m.frames; k++) {+ live.pose(lerp(m.from, m.to, k / m.frames));+ const mid = k === m.frames / 2, end = k === m.frames;+ const file = (s: string) => join(out, `${mv}-${s}${rep ? `@${rep}` : ""}.png`);+ if (mid) await live.step(1, file("mid"));+ else if (end) await live.step(1, file("end"));+ else await live.step(1);+ }+ let held = 0;+ for (const [s, at] of SHOTS) {+ if (at <= 0) continue;+ await live.step(at - held, join(out, `${mv}-${s}${rep ? `@${rep}` : ""}.png`));+ held = at;+ }+ for (const [s] of SHOTS) {+ const img = join(out, `${mv}-${s}${rep ? `@${rep}` : ""}.png`);+ const r = JSON.parse(execFileSync(bin, ["compare", refFile(mv, s), img, "--region", m.band]).toString().trim().split("\n").pop()!);+ rows.push({ move: mv, shot: s, mean: r.mean_delta_e, p95: r.p95_delta_e, trail: r.trail_px });+ }+ }+ }+ live.quit();+}++const median = (v: number[]) => [...v].sort((a, b) => a - b)[Math.floor(v.length / 2)];+console.log(`object ghosting (${tag}, scale ${scale}, ${repeats} run${repeats > 1 ? "s" : ""}): mean dE / p95 / trail px over the swept band`);+for (const mv of Object.keys(allMoves)) for (const [s] of SHOTS) {+ const r = rows.filter((x) => x.move === mv && x.shot === s);+ console.log(` ${`${mv} ${s}`.padEnd(20)} ${median(r.map((x) => x.mean)).toFixed(2).padStart(6)} ${median(r.map((x) => x.p95)).toFixed(2).padStart(7)} ${String(median(r.map((x) => x.trail))).padStart(5)}`);+}+console.log(`shots in ${out}`);diff --git a/tools/object-ghosting/device.game.ts b/tools/object-ghosting/device.game.tsnew file mode 100644index 0000000..cfdd6ae--- /dev/null+++ b/tools/object-ghosting/device.game.ts@@ -0,0 +1,75 @@+// A hand-held device dragged over a workbench (Pocket Bench's Tab5, made of boxes): a white case with an emissive+// screen in front of a wall, over a green cutting mat with a white grid. The driver (bench-object-ghosting.ts) moves+// it with `{t: "pose", x, y, z, ry}` host messages, one per frame, as an app's drag would.+import {+ BoxGeometry, DataTexture, Mesh, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry, RectAreaLight, Scene, SkyGradient,+} from "@threert/scene";+import { defineGame, host } from "@threert/gameplay";++export const CAMERA = { position: [0, 0.34, 0.78] as const, target: [0, 0.2, 0] as const, fov: 40 };++function matTexture(): DataTexture {+ const n = 512, px = new Uint8Array(n * n * 4);+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {+ const line = x % 64 < 2 || y % 64 < 2, fine = x % 16 === 0 || y % 16 === 0;+ const c = line ? [210, 230, 215] : fine ? [40, 120, 80] : [24, 104, 66];+ px.set([...c, 255], (y * n + x) * 4);+ }+ const t = new DataTexture(n, n, px);+ t.repeat = [2, 2];+ return t;+}++function screenTexture(): DataTexture {+ const w = 320, h = 180, px = new Uint8Array(w * h * 4);+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ const frame = x > 120 && x < 200 && y > 50 && y < 110 && !(x > 126 && x < 194 && y > 56 && y < 104);+ const text = y > 128 && y < 140 && x > 90 && x < 230 && (x % 9 < 6);+ const c = frame ? [60, 220, 140] : text ? [230, 235, 240] : [16, 26, 38];+ px.set([...c, 255], (y * w + x) * 4);+ }+ return new DataTexture(w, h, px);+}++let device: Mesh;++host.on("pose", (m) => {+ device.position.set(Number(m.x ?? 0), Number(m.y ?? 0.2), Number(m.z ?? 0));+ device.rotation.y = Number(m.ry ?? 0);+});++export default defineGame({+ state: {},+ handlers: {},+ setup: () => {+ const scene = new Scene();+ scene.environment = new SkyGradient({ zenith: 0x9aa6b0, horizon: 0x6c7076, ground: 0x303030, intensity: 0.4 });+ const panel = new RectAreaLight(0xfff4e6, 9000, 1.2, 0.6);+ panel.position.set(0, 1.4, 0.3);+ panel.lookAt(0, 0, 0);+ scene.add(panel);++ const mat = new Mesh(new PlaneGeometry(2.4, 2.4), new MeshStandardMaterial({ map: matTexture(), roughness: 0.55 }));+ mat.rotation.x = -Math.PI / 2;+ scene.add(mat);+ const wall = new Mesh(new BoxGeometry(2.4, 1.6, 0.05), new MeshStandardMaterial({ color: 0x7a7f72, roughness: 0.92 }));+ wall.position.set(0, 0.8, -0.5);+ scene.add(wall);++ device = new Mesh(new BoxGeometry(0.25, 0.155, 0.022), new MeshStandardMaterial({ color: 0xf2f2ee, roughness: 0.45 }));+ device.position.set(0, 0.2, 0);+ const screen = new Mesh(new PlaneGeometry(0.21, 0.118), new MeshStandardMaterial({+ color: 0x000000, roughness: 0.08, emissive: 0xffffff, emissiveMap: screenTexture(), emissiveIntensity: 80,+ }));+ screen.position.z = 0.0115;+ device.add(screen);+ scene.add(device);++ const camera = new PerspectiveCamera(CAMERA.fov, 16 / 9, 0.02, 20);+ camera.position.set(...CAMERA.position);+ camera.lookAt(...CAMERA.target);+ camera.setManualExposure(8);+ scene.add(camera);+ return { scene, camera, options: { name: "object-ghosting-device", width: 1280, height: 720 } };+ },+});diff --git a/tools/object-ghosting/orb.game.ts b/tools/object-ghosting/orb.game.tsnew file mode 100644index 0000000..fa5e5fb--- /dev/null+++ b/tools/object-ghosting/orb.game.ts@@ -0,0 +1,39 @@+// A glowing orb thrown across a dark room with a polished floor (the Atrium of threert/native-app-template, at+// night): a moving light, seen directly and in the floor's reflection, lighting the floor and wall as it goes. The+// driver (bench-object-ghosting.ts) moves it with `{t: "pose", x, y, z}` host messages, one per frame.+import { BoxGeometry, Mesh, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry, Scene, SkyGradient, SphereGeometry } from "@threert/scene";+import { defineGame, host } from "@threert/gameplay";++let orb: Mesh;++host.on("pose", (m) => {+ orb.position.set(Number(m.x ?? 0), Number(m.y ?? 0.2), Number(m.z ?? 0));+});++export default defineGame({+ state: {},+ handlers: {},+ setup: () => {+ const scene = new Scene();+ scene.environment = new SkyGradient({ zenith: 0x0a0d14, horizon: 0x0c0d10, ground: 0x050505, intensity: 0.05 });+ const floor = new Mesh(new PlaneGeometry(4, 4), new MeshStandardMaterial({ color: 0x1c1c1e, roughness: 0.08 }));+ floor.rotation.x = -Math.PI / 2;+ scene.add(floor);+ const wall = new Mesh(new BoxGeometry(4, 2, 0.05), new MeshStandardMaterial({ color: 0x8a857c, roughness: 0.9 }));+ wall.position.set(0, 1, -1.2);+ scene.add(wall);+ // A still object for the orb to pass behind and light.+ const block = new Mesh(new BoxGeometry(0.18, 0.3, 0.18), new MeshStandardMaterial({ color: 0x9c6a3c, roughness: 0.5 }));+ block.position.set(0.05, 0.15, -0.45);+ scene.add(block);+ orb = new Mesh(new SphereGeometry(0.035, 24, 16), new MeshStandardMaterial({ color: 0x000000, emissive: 0xffc27a, emissiveIntensity: 40000 }));+ orb.position.set(0, 0.2, 0);+ scene.add(orb);+ const camera = new PerspectiveCamera(45, 16 / 9, 0.02, 30);+ camera.position.set(0, 0.45, 1.25);+ camera.lookAt(0, 0.18, -0.2);+ camera.setManualExposure(3);+ scene.add(camera);+ return { scene, camera, options: { name: "object-ghosting-orb", width: 1280, height: 720 } };+ },+});