Skip to content

Playbook and Three.js code kit for detailed dioramas: classic pixel art, stroked toon or pixel + stroke; two intake gates for look and model sourcing; free orbit, palette snap and ink; animated toy-scale cast; per-entity frame QA.

Diorama: pixel-art Three.js diorama playbook, copy-in modules and QA harness

sloemodzna98a68677c4f
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f566d29
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+.DS_Store
+node_modules/
+dist/
+*.bak-*
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..0bfe5f1
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Nehal Kanak
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..12e7e34
--- /dev/null
+++ b/README.md
@@ -0,0 +1,63 @@
+# Diorama
+
+A playbook and code kit for building small pixel-art dioramas in Three.js.
+
+A diorama here means a tiny staged scene on a slab: a locked three-quarter camera,
+a flat cut-out against white paper, a 64-colour palette with ordered dither and an
+inked contour, and toy-scale people with real joint animation. The subject changes
+(pool, night market, bakery, harbour, bank job); the slab, the cast and the
+presentation stay.
+
+Everything is deterministic. The scene is a pure function of `t`, so any frame can
+be frozen, screenshotted and compared.
+
+## What is in here
+
+| Path | What it is |
+| --- | --- |
+| `SKILL.md` | The whole playbook: look contract, detail and animation bars, pipeline, recipes, QA and pitfalls. Start here. |
+| `templates/` | Copy-in modules: palette, post pass, camera, lighting, geometry, props, rig, poses, vehicle transfer, paths, combat, water, effects, build script. |
+| `templates/DESIGN.md` | The design sheet you fill before modelling. |
+| `templates/qa/` | Seven verification scripts that check a build against frozen frames and printed numbers. |
+| `verify/water/` | A worked scene that exercises the water modules, with the screenshots the QA loop produced. |
+| `verify/climb/` | A unit test for the vehicle transfer maths. |
+
+## Start a diorama
+
+1. Read `SKILL.md`: `One Prompt, One Build`, `The Look Contract`, `The Detail Bar`,
+ `The Animation Bar`, `Pipeline`.
+2. Copy `templates/DESIGN.md` into the project as `DESIGN.md` and fill it. Premise
+ as a verb, cast, systems, five beats with timestamps, detail budget.
+3. Copy the modules you need into `src/core/` and `src/scene/`, then a `config.js`
+ that holds the scene's numbers. `verify/water/src/` is the reference layout.
+4. Block out in grey at the locked camera before any production pass, then run the
+ pipeline: palette, materials, detail, animation, effects, post.
+5. Verify with `templates/qa/` before calling it done.
+
+The QA scripts drive Chromium through `playwright-core` and expect the page to
+expose a debug handle:
+
+```js
+window.__diorama = {
+ THREE, scene, camera, renderer, post,
+ freeze(t) { /* draw(t) synchronously */ },
+ view(pos, tgt) { /* optional debug camera */ }
+};
+window.__dioramaReady = true;
+```
+
+`freeze(t)` has to draw synchronously. Without it a screenshot is a race, and a
+screenshot that may show a different frame than you asked for is not evidence.
+
+`verify/water/` and `verify/climb/` show the full loop end to end.
+
+## Using it as a skill
+
+`SKILL.md` carries skill frontmatter (`name`, `description`, `version`), so a
+skill-capable coding agent can load it as-is. It is self-contained: no external
+reference documents, everything needed to build a diorama is in the file plus
+`templates/`.
+
+## Licence
+
+MIT. See `LICENSE`.
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..0799f18
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,2475 @@
+---
+name: diorama
+description: Use when building a pixel diorama in Three.js — one-prompt autonomous builds with staged systems, detailed props, real animation, and social/service choreography.
+version: 3.6.0
+author: Nehal Kanak (sloemo)
+license: MIT
+platforms: [linux, macos, windows]
+---
+
+# Diorama
+
+A diorama is a tiny staged scene on a slab: a locked three-quarter camera, a
+flat cut-out against white, a palette-snapped pixel grid with an ink contour, and
+toy-scale people with real joint animation. Any subject works (pool, market,
+kitchen, bank job, launch pad, aquarium). The slab and the cast stay; the props
+change.
+
+**This file is the whole guide.** It carries no external reference documents:
+everything needed to build a diorama is here, plus copy-in modules and a design
+sheet template in `templates/`.
+
+Read `One Prompt, One Build`, `The Look Contract`, `The Detail Bar`,
+`The Animation Bar` and `Pipeline` first. Then read the sections for the systems
+you are actually building; the rest is reference. Do not spend the first pass
+reading every vehicle or water note for a kitchen scene.
+
+### Fast path by scene
+
+| If the commission is... | Read next, in this order |
+| --- | --- |
+| market, food truck, bakery, cafe, shop, laundromat | Cast → Clothed Cast: Heads, Layers, Hands → Service And Queue → Machine Grammar → Carrying, Loading And Mounting → Verification |
+| heist, defence, combat | Detail Bar → Tool/Tower recipes → System And Combat Animation → Combat Readability → Verification |
+| aquarium, pool, harbour | Cast → base rig → Water templates → Vehicles (boat) → Effects → Verification |
+| station, airport, hotel, transit | Service And Queue → Vehicles → Crowd Variation → Verification |
+| stage, festival, parade | Cast → Secondary Motion → Crowd Variation → System Grammar → Verification |
+| farm, garden, nature | Creature Anatomy → Ambient Loops → Effects → Verification |
+
+The universal shape still applies: place + repeated ritual + interruption +
+consequence. The fast path only decides which reference notes to read first.
+
+## When to Use
+
+- "Make a small diorama / miniature scene / pixel scene of X"
+- A clip or still shows a flat cut-out scene with chunky pixels and little
+ people, and the ask is to match that look
+- An existing 3D scene needs the pixel-art presentation (palette, dither, ink,
+ locked angle) rather than a smooth render
+- The figures need believable motion: walking, climbing into a car, sitting,
+ swimming, diving, and it has to survive close inspection
+- The ask is for a *staged diorama*, not a model: several systems, a cast, a goal or boss,
+ and a loop that can be frozen at any second
+- The user gives only one line ("a bakery at closing", "a lighthouse under
+ siege"); this skill is designed to turn that into a complete commission
+ without an interview
+
+Don't use for full-resolution product renders, photoreal scenes, or anything
+that needs free orbit controls.
+
+## One Prompt, One Build
+
+When the user gives a subject in one line, treat it as a **commission**, not a
+questionnaire. Make the creative decisions, state them in one short assumption
+line, and build the whole diorama. Do not stop at a plan, a blockout or a design
+sheet and wait for approval.
+
+The only reasons to ask are credentials, a destructive action, or a path that
+would overwrite the user's work. Everything else is a default.
+
+### The default commission
+
+Use these unless the prompt explicitly says otherwise:
+
+| Knob | Default |
+| --- | --- |
+| Slab | 21 x 14 x 0.42 m; 16 x 12 for one room, 24 x 16 for a street, port or launch pad |
+| Loop | 46 s at 40 Hz; one readable cycle plus a quiet seam |
+| Palette | 64 entries |
+| Systems | 4 defences/machines/service stations/attractions; 3 is acceptable, 6 is the ceiling |
+| Cast | 4 to 6 roles total, including one disruption; 2 ambient loops |
+| Props / landmarks | 2 hero props, 1 landmark, 3 to 6 supporting props |
+| Hero detail | every hero object meets the Detail Bar |
+| Animation | every hero actor has all five layers |
+| Output | `index.html`, `<slug>.html`, `README.md`, `DESIGN.md`, `src/`, `dist/` |
+| Path | `<cwd>/<slug>/` unless the user named a folder |
+| Minimum viable | 3 systems, 3 roles + 1 disruption, 1 hero prop + 1 landmark, 30 s loop; still passes the bars |
+
+State the assumption in one line before coding:
+
+> Assumption: market archetype, 46 s loop, 4 service systems, 6 roles plus a
+> late customer, 21 x 14 slab, 64 colours. Say if you want a different scale or
+> genre.
+
+That line is the contract. State it, then continue in the same turn; do not wait
+for approval. It gives the user a chance to redirect after seeing the assumption,
+without blocking the build.
+
+### Reading the prompt
+
+| Prompt shape | What to do |
+| --- | --- |
+| one noun ("a bakery") | pick the closest router row; invent the verb, disruption and goal |
+| one sentence ("a lighthouse under siege") | take its nouns and verbs literally; fill the missing cast/systems from the router |
+| a reference image | match its composition, camera side and palette first; keep this skill's detail/animation bars |
+| "like X but Y" | reuse X's structure, replace the subject and the detail anchors; do not copy X's nouns |
+| "make it detailed" | use the full Detail Bar and five animation layers; do not add more systems |
+| "keep it simple" | cut systems and cast, not detail per hero; two rich objects beat six blockouts |
+
+A prompt that names only a place is still a commission. Decide what the place
+does, who arrives, and what goes wrong. State the assumption and build.
+
+### The scene router
+
+Pick the closest row. Do not invent a new genre from scratch unless none fit.
+
+| If the prompt is... | Systems (3–5) | Cast | Goal / disruption | Detail anchor |
+| --- | --- | --- | --- | --- |
+| defence, siege, castle, base, zombies | 4 towers + gate guns | defenders, 4 species, boss | boss reaches the gate | gatehouse |
+| heist, bank, museum, casino | drill, lasers, cameras, getaway | 3 crew, guards, manager | vault opens / escape | vault door |
+| market, kitchen, bakery, cafe, food truck, night market | stalls, ovens, prep, pass, dispatch | vendors, cooks, cashier, courier, customers, inspector | closing time / service rush / last bag | counter, hatch or oven |
+| laundromat, workshop, gym, repair shop, arcade | washers, dryers, benches, tools, machine slots, ticket rail | folder, attendant, customer, courier, cat | last load / closing / power cut | machine bank or workbench |
+| launch, factory, port, mine | gantry, press, crane, conveyor | crew, inspector, cargo | launch / ship / lift | gantry |
+| aquarium, pool, harbour, reef | filters, pumps, slides, lights | fish, swimmers, diver, lifeguard | feeding / party / storm | reef or tank |
+| station, airport, bus, hotel | signal, platform, desk, luggage | commuters, guard, porter | last departure | clock |
+| festival, temple, carnival, funeral | stage, rides, altar, procession | performers, crowd, official | climax / storm | big top or altar |
+| farm, garden, safari, nature | irrigation, harvester, weather vane | animals, farmer, crows | harvest / storm | barn |
+| home, shop, library, workshop | rooms, counter, shelves, tools | family, clerk, customer, pet | opening / closing | window |
+| arena, battle, mech, gladiator | traps, weapons, doors, lifts | fighters, champion, beast | champion enters | gate |
+
+If none fit, use the universal shape: **place + repeated ritual + interruption
++ consequence**. Give it 3 to 5 systems, 4 roles and one goal. A quiet subject
+still needs a verb: a library needs a closing, a bakery needs a service, a
+lighthouse needs a sweep that fails.
+
+### If the router misses
+
+Do not freeze. Answer four questions about the noun:
+
+1. **What does this place produce or repeat?** Bread, light, trains, fish, money,
+ quiet, laundry, coffees.
+2. **Who operates it?** Baker, keeper, guard, diver, clerk, mechanic.
+3. **What interrupts the output?** A critic, a storm, a thief, a shutdown, a
+ delivery, a leak, a closing-time crowd.
+4. **What is the visible consequence?** Burnt batch, dark lens, missed train,
+ flooded tank, empty till, closed sign.
+
+Those four answers give you the system, cast, goal and residue. Then use the
+five beats: **normal output → first interruption → escalation → goal contact →
+residue and seam**. No combat required. A deadline, an inspection, a storm or a
+closing bell is a valid boss.
+
+Worked one-prompt example:
+
+> "a tiny bakery at closing time"
+
+- Archetype: market/kitchen. Slab 16 x 12. Loop 42 s.
+- Systems: oven, proofing rack, counter, till. Cast: baker, apprentice, last
+ customer, food inspector (the disruption).
+- Goal: the inspector reaches the counter before the last loaf is sold.
+- Beats: 0 s oven glow and bread out; 8 s first customer; 16 s inspector at the
+ door; 26 s last loaf contested; 34 s sign turns, flour settles, cat sleeps.
+- Detail anchors: oven door (hinges, soot, peel), bread rack (trays, crumbs,
+ cloth), counter (ledger, bell, worn edge), inspector's clipboard.
+- No towers: use machine grammar for the oven and till; field audit for the
+ oven's heat; death/exit for the inspector's departure.
+
+### The autonomous pass
+
+1. **Interpret.** Pick the archetype; write the assumption line; fill
+ `DESIGN.md` yourself. Do not ask the user to fill it.
+2. **Blockout.** Grey slab, camera, five beats at 1:1. No palette, no post, no
+ materials. If the beats do not read, restage before adding detail.
+3. **Presentation.** Palette, light, post, ink, dither, camera solve.
+4. **Set and props.** Landmark, two hero props, supporting dressing. Clear the
+ 2 m threshold. No duplicate silhouettes.
+5. **Cast and detail.** Rig the cast; apply the Detail Bar to every hero object.
+ Cut a role before cutting detail per role.
+6. **Animation and systems.** Five layers per hero; tower acquire/fire/impact/
+ recovery; field ramp/area/affect/decay; machine input/motion/output/residue.
+7. **Effects and residue.** Contact shadows, species deaths, dropped gear,
+ stains, ambient loops, loop seam.
+8. **QA and package.** Detail/animation audit, numbers, 1:1 crops, standalone
+ `file://`, README and `DESIGN.md` agreeing.
+
+If time is tight, **cut the number of systems or actors, never the detail per
+hero or the animation layers**. Two detailed towers with five layers beat six
+blockout towers with one fire animation.
+
+### Efficiency rules
+
+- **One project, one build loop.** Scaffold once, then build, shoot and fix in
+ place. Do not rewrite the entry file for a detail that lives in a prop module.
+- **Build only what the locked camera sees.** Spend the polygon and part budget
+ on the +Z face and the top; simplify the back.
+- **Cut systems before detail.** A tight build with two rich towers and five
+ animation layers reads better than six thin towers with one recoil.
+- **Use the templates.** Camera, post, palette, lighting, the cast rig and the
+ detail helpers are already solved; do not re-derive them from prose.
+- **Shoot known timestamps.** Freeze at the five beat times and the five QA
+ frames; do not scrub for a good frame.
+- **Package last, once.** Build the standalone only after the QA frames pass;
+ rebuilding it after every tweak wastes the pass.
+
+### One-prompt acceptance
+
+Do not report "done" until all of these are true:
+
+- `DESIGN.md` exists and matches the build.
+- Five beats have timestamps and proof frames.
+- Every system has events; every actor has a death, exit or residue.
+- Each hero has three detail passes and at least one story detail.
+- Each hero actor has idle, locomotion, action, reaction and death/exit.
+- Every carry, handoff, load and mount has a contact timestamp and a nine-frame
+ strip; palms are on the prop and boots are on the vehicle.
+- A queue serves after arrival, never before; no standing gesture is blended
+ into a walking root.
+- No generic sphere burst, floating prop, clipped landmark or beam on a target
+ that has already expired.
+- No fixed deck prop, ammo store, tool or crew member moves with a turret,
+ flywheel or machine pivot.
+- Standalone opens over `file://` with zero console errors.
+- The final message gives the path, loop length, system/shot counts and the QA
+ frames, not a request for feedback.
+
+## Starting A New Diorama
+
+When the subject is new, the first deliverable is a design sheet, not a scene.
+With a one-line prompt, fill it from the defaults in `One Prompt, One Build` and
+do not ask the user to complete it.
+
+1. Copy `templates/DESIGN.md` into the project as `DESIGN.md`.
+2. Write the premise as a verb, not a noun. Name the place, the repeated action,
+ who interrupts it, and the payoff.
+3. Fill the cast and system sheets. If a role has no action, cut it. If a system
+ has no visible consequence, cut it.
+4. Pick five beats and five QA timestamps. A beat without a timestamp is not
+ staged.
+5. Block out in grey at the locked camera and shoot the five beats at 1:1.
+ This is a staging check, not a production pass: no palette, no post, no
+ materials. Redesign staging before committing to it.
+6. Once the blockout reads, run the production pipeline below. Palette is the
+ first production pass; the grey blockout does not count as one. Detail
+ multiplies a readable blockout; it cannot rescue an unreadable one.
+
+The rest of this file is the recipe for each pass.
+
+## The Look Contract
+
+Ten rules. Break one and it stops reading as a diorama.
+
+1. **Locked angle.** One three-quarter view, no drift, no orbit. Azimuth 45,
+ elevation 33, fov 20.5, target just under the slab centre. When the user says
+ "this angle", it means this one, for the whole loop.
+2. **Flat cut-out.** A slab with no plinth, no soil sides, background null, page
+ white. Everything below the deck plane hides in the overhang at 33 degrees.
+3. **Palette snap.** Every pixel resolves to one entry of a fixed palette. No
+ gradients survive; banding is the material.
+4. **Ink contour.** A luminance-neighbour edge mixes toward warm near-black at
+ about 0.62, suppressed on the outer rim so figures are not haloed.
+5. **Dither only where tones move.** Ordered Bayer gated by local edge contrast.
+ Flat decks stay flat; ramps stipple.
+6. **Contact shadows, not just cast shadows.** A soft radial patch under every
+ figure and prop is what anchors it to the ground at this scale.
+7. **People read at 30 to 45 px.** Faces need eyes, brows, nose, mouth, ears.
+ Bodies need joint fillers so a bend never opens a wedge.
+8. **Clipped edge.** The slab is a window, not a stage: four world-space clip
+ planes sit on its edges and anything driving in or out is cut at the
+ boundary. Nothing ever floats on the white page outside the block.
+9. **Everything is a pure function of `t`.** No integration that carries state
+ between frames, no `Math.random`, no drift across the loop.
+10. **Empty paper.** The white page carries no DOM title, caption, HUD or
+ instructions. Put copy on a modelled sign/screen or in the browser title; a
+ label floating on the paper breaks the cut-out.
+
+## The Detail Bar
+
+A blockout with a camera is not a diorama. The difference between a demo and a
+diorama is **three passes**, and every hero object has to survive all three.
+
+1. **Silhouette.** At 1:1 the object is recognisable from its outline in about
+ 0.2 seconds, before colour or detail.
+2. **Construction.** The silhouette is explained by visible assemblies: posts,
+ rails, bands, plates, wheels, hinges, ropes, fasteners. A single primitive is
+ a placeholder, not a prop.
+3. **Story.** One detail tells you who used it and what happened: a chipped edge,
+ a trophy skull, a repair strap, a spare bolt, a rag, a tally mark, a spent
+ shell. If the detail could be removed without changing the read, it is
+ greeble, not story.
+
+The numbers below are **reference density** from The Hollow Toll, a 21 x 14 m
+slab with four towers, two gate guns, five species, 42 units, one boss, 527
+events and 183 shots. Treat them as a calibration target, not a cap.
+
+| Element | Minimum visible assemblies | Hero target | Required story detail |
+| --- | --- | --- | --- |
+| Tower | 6 | 25 to 45 parts | crew, ammo, livery, wear |
+| Creature | 8 | 12 to 20 parts; boss 40 to 60 | gear, scar, trophy |
+| Prop | 5 | 8 to 15 parts | contents, tool, repair, rag |
+| Landmark | 8 | 30 to 60 parts | one unmistakable silhouette |
+| Death | 3 stages | 5 to 8 pieces + stain + soul | species-specific debris |
+| Environment | 3 scale cues, 3 story props | 2 ambient loops | a before/after trace |
+
+In a social diorama, read the Death row as **Exit**: a role-specific departure
+(turn, walk out, shutter down) with the prop and no debris. The five layers are
+unchanged; the residue is the changed place, not a stain.
+
+**An object can hold two roles.** A lighthouse that is also a beam tower gets
+the landmark budget for its structure **plus** the machine's moving parts; list
+both rows in the design sheet. A boss weapon is a separate group: budget 8 to 12
+parts for the weapon on top of the body, and say so, or the body will be blamed
+for a thin haft.
+
+**Primitive discipline.** No naked box, sphere or cylinder at hero scale. A box
+gets a chamfer, a frame, plank divisions or a band. A sphere becomes a skull,
+bale, sack or head with a snout, ties or a neck. A cylinder gets a foot, cap,
+taper or iron rings. If a shape is still a primitive after the detail pass, it
+will read as a rock, a blob or a placeholder at 30 to 45 px.
+
+**Two to four palette entries per object, plus one accent.** More entries
+turns into noise after the palette snap; fewer turns into a silhouette cut-out.
+Use value contrast for construction and hue for story.
+
+**Detail lives on the camera-facing surfaces.** At the locked angle, model the
+front and the top; simplify the back. A perfect back is wasted geometry. Do not
+add detail under about 1.5 screen pixels: it aliases into speckle, not craft.
+
+**Every prop must touch the ground.** Feet, wheels, a base, a contact shadow, a
+stain. A prop hovering by two centimetres is the single most common "it looks
+cheap" report. Check the shadow and the lowest vertex, not the group origin.
+
+**Every landmark must be the only one of its silhouette.** Two skull trees, two
+red tents or two identical towers read as duplication, not composition. Move,
+scale or redesign the second one. Check overlap by projecting both bounding
+boxes to screen: if they merge into one blob, one is invisible detail.
+
+**Clear thresholds.** Keep at least 2 m of empty ground in front of a gate,
+portal, spawn mouth or door. No crates, barrels, boulders, bones, vines or
+rising smoke in that pocket. A grey billboard above an arch reads as a rock
+flying out of the entrance even when it is transparent.
+
+## The Animation Bar
+
+An actor is animated when it has all five of these, not just a walk cycle:
+
+1. **Idle / ambient.** Breathing, sway, scan, flame, flag, wing settle. Two
+ loops minimum in the environment.
+2. **Locomotion.** Distance-driven walk, run, hop, flap or slither, with feet
+ planted and joints filled.
+3. **Action.** A readable wind-up, contact and recovery: fire, swing, slam,
+ dive, throw, open, build.
+4. **Reaction.** A directional flinch, hit flash, knockback, stagger or squash
+ that recovers to the same pose.
+5. **Exit / consequence.** In a combat diorama, a body-specific collapse plus
+ debris, dropped gear, a ground stain and a brief residue — never a generic
+ sphere burst. In a social diorama, the equivalent is a role-specific exit:
+ turn, walk out with the bag, close the shutter, or sit back down. The scene
+ must show that the actor changed the place.
+
+Background actors need 1, 2 and 5. Hero actors need all five. A tower is an
+actor too: idle hum, aim, fire, recoil, reload. A service actor's action is
+order/pay/receive, its reaction is a look-up or step-back, and its exit is the
+walk-out with the prop. A prop with a moving part (door, flag, wheel, pulley,
+cauldron) needs its own loop.
+
+**Motion is data.** Author beats as absolute times or travel distances, then
+read them at `t`. Do not hide a state machine inside render-frame conditionals;
+it will pop on a seek, drift on a loop, and be impossible to screenshot.
+
+**Nothing at hero scale is static.** A tower that spawns a projectile from its
+centre without recoil, a boss that stands at a door without touching it, a
+creature that slides without a step: all read as unfinished, even with good
+geometry.
+
+## Numbers That Make It Read
+
+| Knob | Value | Why |
+| --- | --- | --- |
+| Camera | fov 20.5, az 45, elev 33 | long lens, near-ortho miniature |
+| Framing | `fillX 0.84–0.94`, `fillY 0.86–0.94` | fit margin only: slab plus landmark tops |
+| Subject scale | `1.0`, or `0.70` for 30% smaller | post-fit camera multiplier; never geometry |
+| Camera distance | solved, 5 to 300 | bisection; actual distance = fit / subjectScale |
+| Post buffer | 1× CSS; 1.2–1.5× for a small subject; 2× faces | extra detail without resizing the diorama |
+| Palette | 64 entries (any N, but the shader array and loop must match) | skin, stone, asphalt, glass, livery, props |
+| Dither | `d*(0.0012 + 0.019*gate) + sparkle*0.0012` | stipple in ramps only; gate = edge |
+| Ink | `smoothstep(0.13,0.34,edge)`, mix 0.62 | outline without scribble |
+| Palette tie-break | `secondD-bestD < 0.0005` → lighter | flat surfaces come out flat |
+| Sun | `0xfff8ee` at 3.3, hemi 0.24, fill 0.46, env 0.18 | hard shadows, cool fill |
+| Shadow cam | ±13, near 4, far 70, 2048 map, bias -0.00022 | tight around the whole slab, no acne |
+| Figure | 1.69 m, hip 0.86, head 0.584 | toy proportions that read |
+| Car | L 4.4, W 1.86, belt 0.90, roof 1.44 | door 1.30, leaf sits between 0.34 and 0.90 |
+| Scooter | wheel r 0.26, board 0.30, seat 0.83, bars 1.06 | boots and hands land on built surfaces |
+| Loop | 41 to 47 s | one robbery beat plus police, and a quiet seam |
+
+The table mixes two different kinds of number, and treating them alike is how a
+new subject comes out wrong.
+
+**Invariants.** Come from the look itself and hold on every subject: azimuth 45,
+elevation 33, fov 20.5; one locked camera for the whole loop; palette discipline
+(every material samples a palette entry, the shader array length equals the
+palette length); gated dither, ink at 0.13/0.34 mixed 0.62, the palette tie-break;
+the rig's proportions and joint signs; 2048 shadow map with a frustum tight to
+the slab; everything a pure function of `t`.
+
+**Calibrated.** Measured against one subject and only evidence for it: palette
+count (64 for the bank job, 66 here), buffer size and renderScale (1×/1.25×/2×),
+`fillX`/`fillY`, `subjectScale` and the camera `size` divisor, slab dimensions
+and deck height,
+loop length, sun and hemisphere intensities, and every prop dimension in the
+vehicle and scooter rows. Re-derive these per build: start from the value, then
+look at a screenshot and change it.
+
+A scene may change any calibrated number if the subject needs it; change the
+template and `DESIGN.md` in the same edit and record the reason. A template that
+silently uses a 2x different sun is worse than no template, because the next
+reader trusts it.
+
+## Pipeline
+
+Each step ends in something you can look at.
+
+1. **Palette first.** The palette array in `palette.js` plus a named `C` map.
+ Every material samples a palette hex, nothing else. Done when a grep for
+ colour literals in `materials.js` finds only palette names.
+2. **Frame the slab.** Camera constants from `templates/camera.js`, slab sized so
+ its projected diamond leaves a margin. Done when a grey slab shot has roughly
+ 25 to 40 percent white around it at `subjectScale: 1.0`; for a smaller subject,
+ apply `subjectScale` after the fit and expect more paper, not a smaller set.
+3. **Light it.** Sun plus low hemisphere for daylight; the **Night, Practicals
+ And Headlights** rig for a night scene. Tighten the shadow camera to the slab
+ and call `updateProjectionMatrix()` after changing the frustum. Done when every
+ figure has a readable contact shadow (crisp by day, a soft pool by night).
+4. **Post pass.** `templates/post.js`: gamma, grade, ink, gated dither, palette
+ snap, rim dither. Done when a 1:1 crop shows square pixels and a dark contour,
+ and flat pavement shows no speckle.
+5. **Props.** Flat-colour boxes and lathes, no textures, coarse detail. Done when
+ the 1:1 crop reads the object's silhouette without colour.
+6. **Cast.** `templates/peopleModel.js` (base) or `templates/peopleModel-street.js`
+ (clothed) rig, one entry per figure with a base pose. Done when isolated portraits show no gaps, no floating parts, knees
+ bending the right way.
+7. **Detail pass.** Apply the Detail Bar to every hero object: construction
+ layers, attachment, story detail, contact shadow. Done when the object meets
+ its row's minimum (5 prop, 6 tower, 8 creature, 8 landmark), has one
+ asymmetry and one story detail. "Three assemblies" is a blockout; it is not
+ a pass. Do not animate a placeholder.
+8. **Animation and systems.** Locomotion, idle, tower/machine actions, reactions,
+ exits/deaths, goal contact, crowd variation. Done when each hero actor has all five
+ animation layers and each tower has acquire/fire/impact/recovery.
+9. **Effects.** Contact shadows, smoke, splash, spill light, debris. Done when the
+ effect is visible but never the subject.
+10. **QA.** Detail and animation audit, `qa/audit.mjs` for seams/glows/fades,
+ camera/render scale, exits and emitters, desktop/iPad/phone, `file://` standalone,
+ zero page errors, motion and camera proven from numbers and strips. See
+ Verification.
+
+## New Subject Intake
+
+A new subject is not a new pile of props. Before modelling, fill this sheet.
+Copy `templates/DESIGN.md` into the project and keep it in sync with the code.
+
+```
+PREMISE
+ [place] + [a repeated verb/ritual] + [who or what interrupts it] + [payoff].
+ One sentence. If it has no verb, it is a shelf model, not a diorama.
+
+CAMERA SIDE
+ Which face is +Z? Where is the threshold, the hero tower, the foreground prop?
+ Which silhouette must never be occluded from this angle?
+
+CAST SHEET
+ role | silhouette feature | locomotion | action | reaction | exit/death | signature
+ ...
+
+SYSTEM SHEET
+ loop length | three or four systems | crew | three or four visitor roles |
+ goal/disruption (optional) | economy/score (optional) | what changes
+
+BEAT SHEET (absolute seconds)
+ 0.0 establish / portal / doors
+ ... first signal, first system output, first consequence
+ ... disruption reaches the goal (or the last customer arrives)
+ ... contact / handoff / finale, residue, loop seam
+
+DETAIL BUDGET
+ systems n x parts | vehicles n | creatures/people n | props n | landmark n |
+ exits/deaths n | ambient loops n | triangle / draw-call ceiling
+```
+
+Rules that keep a new subject from becoming a blockout:
+
+- **Invent the conflict.** If the user says "a diorama of a lighthouse", decide
+ what the lighthouse does, who arrives, what goes wrong, and what the keeper
+ does about it. A subject plus a verb is a diorama.
+- **Give every machine an operator.** If a tower, loom or pump needs a crew,
+ model the crew and decide what happens when they die: the machine slows, stops,
+ or runs unmanned with a visible consequence. A gun that fires itself while its
+ crew lies dead is a ghost. If the machine is autonomous, say so in the sheet.
+- **Choose five signature moments before modelling.** Establish, first system
+ output, first consequence, goal/handoff contact, final residue. A social diorama
+ may use establish, ritual, disruption, handoff, residue. Every object earns its
+ place by serving one of those five.
+- **Stage for the locked camera.** Put the threshold and the hero action on the
+ +Z face; put tall landmarks at the back but offset in screen x so they do not
+ stack. Put one foreground prop at the near corner for depth and one mid-ground
+ prop to lead the eye.
+- **Blockout in grey first.** Boxes, cylinders and the camera, no palette, no
+ post. Shoot 1:1. If the five moments do not read in grey, detail will not save
+ them. Redesign the staging, not the textures.
+- **Name every hero object.** `totem`, `hayCart`, `gatehouse`, `troll`, not
+ `prop12`. Unnamed objects become clutter because nobody owns their silhouette.
+- **One boss goal, one tower verb.** The boss must visibly act on a place
+ (door, bridge, pump, nest); the tower must visibly act on a target (pierce,
+ blast, freeze, chain). Repeat the verbs with variation, not new nouns.
+- **Write the QA timestamps now.** Pick the five frames you will inspect before
+ you build them. If you cannot name a timestamp for a beat, it is not staged.
+
+### Reference Density
+
+The Hollow Toll shipped at this density. Use it to calibrate a new subject; a
+smaller subject should have fewer objects at the same detail per object, not
+fewer details per object.
+
+| Measure | Value |
+| --- | --- |
+| Slab | 21 x 14 x 0.42 m, 64-colour palette |
+| Towers | 4 + 2 gate cannons |
+| Species | 5 (goblin, orc, slime + split, bat/imp, troll) |
+| Units | 42, one boss |
+| Combat events | 527 |
+| Tower shots | 183 |
+| Scene meshes | ~3,100 |
+| Triangles | ~164,000 |
+| Scene draw calls | ~1,700 at 1440 x 900 |
+| Textures | 5 |
+| Loop / sim | 46.0 s at 40 Hz pre-sim |
+| Standalone | ~783 kB with three.js inlined |
+
+A 12 x 9 m scene with two towers and three species should land around
+1,000 to 1,600 meshes and 60 to 100k triangles. Raw count is not the goal;
+the detail per hero object and the number of readable beats are.
+
+### Worked Example: The Hollow Toll
+
+This is the reference build the numbers above come from. Read it as a calibration
+of **what "finished" looks like**, not as a scene to copy.
+
+- **Set.** A 21 x 14 m slab, purple portal at the back-left, winding road, goblin
+ camp, moat and drawbridge, gatehouse at the near-right. Four towers and two
+ gate swivels; keep gate faces +Z.
+- **Cast.** 14 goblins, 4 orcs, 7 slimes plus 10 split slimelets, 6 imps and one
+ Toll-Troll: 42 units, 5 death grammars, one boss goal.
+- **System.** 46 s loop at 40 Hz, 527 events, 183 shots. Ballista single target,
+ bombard splash, frost lance channel, tesla chain, gate swivels on the last
+ stretch. The troll reaches the gate at 38.6 s and hits it eight times.
+- **Detail.** The gatehouse has a plinth, two towers, crenellations, a gate arch,
+ door leaves with cracks, two swivel cannons, banners and torches. The skull
+ warning tree has a trunk, fork, trophy board, horned skull, rope collar, bone
+ chimes, rags, tally marks and roots. The hay cart has a bed, slats, two spoked
+ wheels with iron tyres, corner straps, three tied bales, loose straw, a
+ pitchfork, a sack, a rag and two shafts.
+- **Animation.** The frost spire pulses, flares at the crystal, holds a scrolling
+ band lance, ramps heat, and shuts off on the target's death. The troll stops
+ outside the threshold, turns three-quarter, swings an iron-banded maul, and
+ drives the door flash, shake and cracks from the same gate-hit timestamp.
+ Every species has its own collapse and debris.
+
+Fixes that became rules in this file:
+
+| Report | Root cause | Rule |
+| --- | --- | --- |
+| "rocks flying out of the entrance" | camp smoke billboards above the portal | clear the threshold of smoke, props and fireflies |
+| troll inside the gatehouse | stop at `length - 1.05`, body through wall | stop at body depth + weapon reach; keep the door visible |
+| club looked like a rock | end-on pose, haft hidden, no bands | yaw 0.35 rad, build haft + bands + studs, sync contact |
+| beam had a black segment | black backing plate in the additive beam texture | clear the canvas; transparent gaps, never black |
+| deaths were spheres/rocks | generic burst | species collapse + debris + dropped gear + residue |
+| skull tree looked like a monster | a second totem overlapped the tree | one landmark per silhouette; mount the skull on a board |
+| cart looked like a blob | pale spheres in an open box | five-part prop: bed, slats, wheels, load, tools, story |
+| standalone broke over `file://` | `String.replace` expanded `$&` in the bundle | function replacer; test the standalone |
+
+A new subject should copy the **density and audit discipline**, not these nouns.
+A lighthouse, market or launch pad needs the same number of readable systems,
+the same five animation layers and the same proof frames.
+
+### Worked Example: Night Market
+
+The social-scene calibration: no combat, no boss, no deaths. A food truck, a
+queue, a courier, one scooter and a cat. It proves the same discipline applies to
+a life scene.
+
+- **Set.** 21 x 14 x 0.42 slab; truck at (0.15, -3.35) with the hatch facing +Z;
+ counter at z 1.10; parked scooter at (5.55, -0.72) facing +Z; bench, rail,
+ lamps, bins, service block behind. Camera azimuth 45, elevation 33, fov 20.5,
+ fill 0.93.
+- **Cast.** Cook, cashier, customers A/B/C, courier, late customer D, cat. The cat
+ is an actor with its own idle, walk, sit and tail loop, not set dressing.
+- **Systems.** Grill flare, order rail, bag pass, scooter dispatch. Four readable
+ systems, no towers.
+- **Loop.** 46 s at 40 Hz. Queue forms 0–16 s; four paper bags + one insulated
+ bag; courier loads 21.2–22.5, mounts 22.7–23.5, departs 23.5–27.3; D arrives
+ 26.0–33.4, last bag 34.0, exits 34.8; quiet seam 40–46.
+- **Scale.** The user asked for 30% smaller. The fix was `subjectScale: 0.70`
+ after the fit (`distance = fit / 0.70`), not scaling the slab, cast or canvas;
+ geometry scaling breaks the world clip and shadow maps, and shrinking the
+ canvas breaks the 1:1 crops. Backing buffer 2x CSS for the faces, CSS
+ downscale.
+- **Proof.** Nine 1280x800 frames plus two close strips: courier mount, D walk.
+ The strip camera was a fixed side view, not the hero camera.
+
+Fixes that became rules in this file:
+
+| Report | Root cause | Rule |
+| --- | --- | --- |
+| "the building bottom/right is cut" | slab edge/backdrop closed too tight | close side walls and undersides; camera fit includes the slab corners |
+| "bike lights look unnatural" | large additive disc | emissive lens + small halo; cone only at night |
+| "doesn't put the box on the bike" | prop teleported from hands to crate | carry in world space from wrists; lower over the rim; release with a beat |
+| "doesn't sit on the bike naturally" | car seat/root constants reused | measure scooter seat; board for the left boot; abduction swing; bars to hands |
+| "the human/cat doesn't look human" | sphere head, cap at theta 1.85 | skull+jaw head, hair cap 1.22, ears/brow/lids, tapered limbs |
+| "carry the bags more human-like" | prop at root, hands nearby | two-hand hold at the prop's top, object origin at its bottom |
+| "no text outside the diorama" | DOM overlay on the paper | empty-paper rule; copy on modelled signs only |
+| "30% smaller" | scaling the scene | move the camera; keep world clipping and shadow scale |
+| "leg swings over the handlebar" | hip X flexion for a side mount | abduct with hip Z; knee tucked; root arc 0.1–0.2 m |
+| "single human slides near the shop" | standing gesture blended during walk | gate gestures on `!state.moving`; serve after arrival |
+
+A new subject should copy the **timing discipline and contact logs**, not the
+food truck. A pool, a station or a bakery needs the same queue/service,
+carry/load and close-up proof.
+
+## Palette And The Post Pass
+
+`templates/post.js` renders the scene to an offscreen target, then a full-screen
+shader turns it into pixel art. Order matters; each stage assumes the last.
+
+1. **Coverage gather.** ~12 taps in a small disc read alpha, so the silhouette can
+ be softened and stippled without blurring the interior. The target is
+ transparent outside the slab.
+2. **Composite onto paper.** `mix(vec3(1.0), c, smoothstep(0.26, 0.72, cov))`.
+3. **Gamma.** `c = pow(c, 1/2.2)`. The target is linear; skip this and the frame is
+ dark and muddy, which reads as a lighting bug.
+4. **Grade.** Saturation 1.07 and contrast 1.028 *before* quantising, or the snap
+ flattens everything to mid tones.
+5. **Ink.** Neighbour luma differences, `edge = max(abs(d))`, brought to display
+ scale with `pow(edge, 0.4545)`, then
+ `ink = smoothstep(0.13,0.34,edge) * smoothstep(0.20,0.55,cov) * (1 - smoothstep(0.86,0.985,cov))`
+ mixed 0.62 toward `vec3(0.085,0.082,0.076)`.
+6. **Dither, gated.** `d = bayer8(gl_FragCoord.xy) - 0.5`,
+ `gate = smoothstep(0.004,0.055,edge)`,
+ `c += (d*(0.0012 + 0.019*gate) + sparkle*0.0012) * uDither`. Keep `uDither` as a
+ uniform: it is the fastest way to prove whether a speckle is the dither.
+7. **Palette snap.** Nearest entry with channel weighting `(1.0, 1.12, 0.93)` so
+ greens do not beat skin. Keep the runner-up and break near-ties toward the
+ lighter entry, or a surface halfway between two entries flips entry per pixel
+ on the dither noise and stipples a whole pavement.
+8. **Rim dither.** Where coverage is 0.78 to 0.995, threshold against Bayer so the
+ cut-out edge is stippled, not anti-aliased.
+
+The palette length is a shader constant: `uniform vec3 uPalette[N]` in the
+fragment source and the JS array must be the same length. A mismatch loses the
+last colours or reads out of bounds, and the symptom is a colour that "does not
+exist in the palette" appearing on screen.
+
+### Tuning Table
+
+| Symptom | Cause | Fix |
+| --- | --- | --- |
+| Water looks like TV static | dither ungated | add the edge gate |
+| Frame dark and muddy | missing gamma | `pow(c, 1/2.2)` before grade |
+| Everything mid-grey | no grade before snap | saturate 1.07, contrast 1.028 |
+| Scribble outlines | ink threshold too low | 0.13 / 0.34 |
+| Missing outline on figures | rim suppression too wide | narrow to 0.86 / 0.985 |
+| White speckle on flat deck | material grain aliasing | cut grain, not resolution |
+| Bands with hard edges | palette hole | add 4 to 6 intermediate entries |
+| Speckle only where a tone sits between entries | palette tie | break near-ties toward lighter |
+| Speckle at zero dither | sub-pixel geometry | widen detail to ~1.5 px or delete it |
+| Beam goes flat or vanishes on paper | additive white over white | saturated palette core + dark halo; fade before the edge |
+| Glow disappears after the snap | sub-pixel or pure-white FX | widen to 2 px+, use a palette entry, add a contour |
+| Beam ends in a hard vertical cut | world clip plane on a read-through FX | taper intensity to zero before the slab edge |
+| Flame reads as a grey smudge | normal-alpha smoke over a bright source | lighten/remove smoke in the flame corridor, draw flame last |
+
+Isolate noise in this order and stop at the first that removes it: dither
+uniform to 0 → widen or delete sub-pixel geometry → disable `shadowMap`. Judge on
+a 1:1 crop; a downscaled preview softens all three into "texture".
+
+### Resolution
+
+Default: `setSize` renders one target pixel per CSS pixel, capped by `maxDim`
+(1600), and CSS `image-rendering: pixelated` handles the upscale. The chunky
+look comes from the palette snap and the ink, not from a low buffer.
+
+When the diorama is deliberately small on the page (`subjectScale` under ~0.8),
+raise the buffer **a little** instead of enlarging the subject:
+`new PixelPost(renderer, 2000, 1.25)` renders 1.25 target pixels per CSS pixel;
+at a 1312 × 760 CSS canvas that is a 1640 × 950 buffer, CSS still 1312 × 760.
+The post pass quantises at the finer grid and the browser downsamples; the page
+size, camera solve, slab and clip do not move. 1.2–1.5× is the useful range; 2×
+on a full arena is usually a frame-rate tax, not more art. Log `post.size` and
+`canvas.getBoundingClientRect()` and check a 1:1 crop for shimmer.
+
+For faces and close-up contact beats, use `renderScale: 2` and
+`image-rendering: auto` (not pixelated), with `maxDim` high enough (2400) to
+avoid the cap. The post pass still quantises at 2×; the CSS downscale is a clean
+box filter, not a change to the art. Keep the CSS size as the layout size so the
+camera solve and the 1:1 QA crops stay comparable. Re-run the portraits after
+any resolution change: raising the buffer exposes hats, stripes and noses that
+hid at the old grid.
+
+## Camera And Framing
+
+```js
+CAMERA = { fov: 20.5, azimuth: 45°, elevation: 33°, target: (0,-0.15,0),
+ fillX: 0.84, fillY: 0.86,
+ subjectScale: 1.0 } // 0.70 = 30% smaller, more paper
+```
+
+The distance is solved, not typed: build a direction vector from the angles,
+project each fit point (slab corners at deck and underside, plus the tallest
+building corners) into camera axes, and bisect the distance until every point's
+`|x|/(depth*tan*aspect)` and `|y|/(depth*tan)` fit inside `fillX` and
+`fillY`. 48 iterations is plenty. `fillX`/`fillY` are the **fit margin**, not the
+page-size control; tune them together, because raising one alone crops the other
+axis on a portrait phone.
+
+**Subject scale is a second, post-fit move.** Solve the fit first, then pull the
+camera back:
+
+```js
+const fit = solveDistance(aspect, points);
+const scale = CAMERA.subjectScale ?? 1;
+const distance = fit / Math.max(0.1, scale);
+camera.userData.fitDistance = fit;
+camera.userData.subjectScale = scale;
+camera.userData.distance = distance;
+```
+
+`subjectScale: 0.70` renders the diorama at 70% width/height — 30% smaller
+linearly and about 49% less screen area — so the paper margin grows. `1.0` is the
+fitted size. Keep the slab, cast, world clip, shadow camera, CSS canvas and
+frame at full size; raise the backing buffer only with `renderScale` (next
+section), never by scaling geometry. Shrinking the geometry also shrinks contact
+shadows and the clip volume; shrinking the frame/canvas changes the 1:1 crop
+and does not change the model's scale. **Move the camera.**
+
+A phone is already height-limited, so 0.70 can make the trucks unreadable. Try
+0.70, then 0.80–0.90 if needed; the scale is per scene, not a universal 30%.
+
+**Verification.** Log both distances and assert
+`actualDistance ≈ fitDistance / subjectScale` within 2%. Also project the slab
+and compare its width to the fitted width: the ratio must be the scale, not just
+the distance. On Dust Kings at 1.73 aspect: fit 67.93, scale 0.70, actual 97.05;
+projected slab width 872 → 611 px (0.70), with slab, clip and shadows unchanged.
+
+`updateCamera(camera, aspect)` on every resize and orientation change, with a
+debounced call after `orientationchange`. A canvas measured at under 2 px is a
+layout race: return early rather than dividing by zero.
+
+## Scene Furniture
+
+- **Slab** 21 x 14 x 0.42 with the street on the camera side (+Z) and the
+ building block at the back (-Z) for an exterior. For an interior cutaway, see
+ **Cutaways And Glass** before placing the street. Deck at y 0 is the street;
+ the pavement is a raised 0.16 slab with a kerb face.
+- **Pavement joints** 2.6 m apart, 0.085 m wide. Anything thinner rasterises to
+ dots that read as noise. `groundY(x,z)` returns street, pavement or step height
+ so every track and shadow samples the same function.
+- **Buildings** are boxes with a parapet, a sign band, recessed windows and a
+ door pivot. At 33 degrees you look down onto roofs: a 4.6 m wall in front of a
+ 5.2 m deep building hides none of its roof, so model the parapet, plant,
+ skylight or stair head, or keep it lower than it is tall.
+- **Doors** are pivots at the jamb with the leaf extending into the opening.
+ Recess them 0.15 so the opening shows a shadow gap, and light the interior so
+ an open door reads as a room, not a hole.
+- **Contact shadows** are one unlit radial-gradient plane per figure, opacity
+ 0.55 to 0.95, scaled to the footprint, 0.018 above the ground it belongs to.
+
+### Night, Practicals And Headlights
+
+Night is a new light ratio and a new palette, not the day rig dimmed. The sun
+table is a daylight default; a 2am scene needs its own numbers and its own test.
+
+| Key | Night default | Why |
+| --- | --- | --- |
+| moon / key | `0x93a7c4` at 0.45 to 0.65 | cool, low, soft shadows |
+| hemisphere | sky `0x1b2740`, ground `0x090b12`, 0.16 | blue ambient, never black |
+| fill | `0x6d7f9e` at 0.10 to 0.16 | keeps the shadow side readable |
+| practical | `0xffb066` at 1.0 to 1.4 | warm bulb/lamp, 2700 K |
+| pool | unlit radial plane, opacity 0.28 to 0.45 | light on the ground, cheap |
+| headlight | `0xfff0c8`, lens + cone + floor ellipse | source, throw and landing |
+
+- **A practical is an object, not a glow.** Bulb sphere, shade/guard, bracket,
+ emissive lens, small halo, and a pool on the surface below. A floating halo with
+ no fixture reads as a firefly.
+- **Use one real point light at the hero practical**, not one per bulb. The rest
+ are emissive + pool decals. Ten point lights flatten the darks and cost more
+ than they return.
+- **Keep three dark values.** Deep shadow, mid shadow and lit edge must be
+ different palette entries; if the night is one black silhouette, lift the
+ hemisphere or add a cool rim. `0x000000` is forbidden, as in daylight.
+- **Headlights are a moving pool, not a global spotlight.** Two lenses, two
+ tapered cones, one elongated floor ellipse that travels with the vehicle.
+ Do not let the cone light the whole facade: it will read as dawn.
+- **Windows are dark glass with a warm interior.** A blue-grey pane, two
+ reflection streaks, and a visible warm room behind it. A fully transparent
+ plane tints the whole interior and kills the cutaway.
+- **Grade for night after the snap:** lift black to about `0x0b1020`, keep warm
+ highlights from clipping. Test a 1:1 crop: three dark values, a visible source,
+ a readable pool, no white blob.
+
+A night scene passes when the unlit areas still have shape and the light sources
+are in the frame. "It is dark" is not a pass.
+
+### Cutaways And Glass
+
+The +Z street convention is for an **exterior**. If the hero action is inside a
+shop and the street is between the camera and the hero, the bus/traffic will
+occlude the beat. Choose one:
+
+- **Exterior scene:** street on +Z, facade behind it, action on the pavement.
+- **Interior cutaway:** omit the camera-side wall entirely (or keep a 0.25 m
+ header and sill), put the street **behind** the room at -Z behind glazing, and
+ keep the camera-side floor open. The room is the stage; the street is the
+ cyclorama.
+- **Foreground traffic:** allowed only if it crosses before or after the hero's
+ contact beat; check the occlusion frame, not just the still.
+
+For glazing, build the frame, mullions, sill and a few reflection streaks. Do not
+lay one transparent plane across the opening: it tints the interior, hides the
+practical lights and turns the cutaway into a fish tank. If the bus must read
+through the glass, give it lit windows and a dark body against the warm interior;
+do not brighten the whole room to compensate.
+
+## Detail Recipes
+
+Detail is a hierarchy, not a texture. Build in this order and stop adding when
+the silhouette is explained.
+
+### The Five-Part Prop
+
+Every readable prop answers five questions with geometry:
+
+1. **What touches the ground?** Feet, skids, wheels, a stone base, roots. Add a
+ contact shadow at 0.018 above the deck.
+2. **What holds it up?** Posts, frame, legs, axle, brace. This is the
+ construction layer and it must be visible from the camera.
+3. **What is its working surface?** Planks, slats, a lid, a blade, a trough, a
+ table. Divide it into pieces; a single slab reads as a box.
+4. **What attaches the parts?** Rope, iron straps, nails, hinges, lashings,
+ rivets. Two or three are enough; a row of identical studs is noise.
+5. **What is the story?** Contents, a tool, a repair, a trophy, a rag, wear on
+ the edge that is used. One or two, placed where the camera sees them.
+
+A hay cart from the reference build: bed, six side slats, two spoked wheels with
+iron tyres, four corner straps, three tied bales, loose straw, pitchfork, sack,
+red rag, two draft shafts. That is ten assemblies for a prop the user sees for
+two seconds. A crate with a pale sphere inside is none of them.
+
+### Tower Anatomy
+
+A defence tower is a small building, a machine and a crew in one silhouette.
+
+| Layer | What it adds | Failure if missing |
+| --- | --- | --- |
+| 1 foundation | plinth, steps, rubble, contact | tower floats or looks pasted on |
+| 2 shaft | taper, buttresses, bands, ladder | reads as a cylinder |
+| 3 platform | deck, rail, hatch, brackets | machine has nowhere to stand |
+| 4 machine | weapon, pivot, rail, recoil travel | attack has no origin |
+| 5 crew | gunner, cranks, spotter, ammo | tower feels automated/empty |
+| 6 livery | banner, number, pennant, paint | tower has no owner |
+| 7 wear | scorch, chips, rope, spent cases | tower looks unplaced |
+
+The animation pivot belongs to layer 4. The muzzle or launch point belongs to
+the weapon, never the tower centre. Recoil travel is 0.1 to 0.25 m for a ballista
+or cannon, 0.02 to 0.06 for a beam crystal. A tower with no recoil, no crew and
+no ammo is a monument.
+
+**A hollow object must show its opening.** A cannon with a solid brass cap is a
+baton, not a gun; the same failure turns a pipe into a rod, a chimney into a
+post, a lamp into a mushroom and a tunnel into a painted arch. Build the opening
+as geometry, not a dark decal:
+
+- replace the end cap with one or two **open-ended collars** (no front face);
+- add a recessed **dark bore tube**, open at the mouth, with its inner wall
+ visible (`DoubleSide` on a cloned material, never on the shared palette
+ material);
+- close the back with a **dark disc** so the barrel interior is not see-through;
+- add an **iron inner lip ring** and a **brass outer lip ring** so the edge
+ catches the light at 1:1;
+- put the muzzle/effect origin at the lip, not inside the bore.
+
+At 1:1 the opening needs a dark centre at least 5 to 6 px across and a lit lip.
+If the centre is brass, the hole failed.
+
+**A rotating assembly owns only its moving parts.** The yaw/turret group may
+contain the carriage, barrel, recoil slide and muzzle. Fixed stores — powder
+keg, shot pile, rammer, tools, ready rack, crew — belong to a static group on the
+tower root, never the yaw group. If they are children of the yaw group they sweep
+around the tower when it tracks a target, which reads as the whole gun deck
+rotating.
+
+Do not simply reparent the props at deck height: the barrel and carriage sweep
+through that volume at some yaw. Put them outside both the yaw sweep and the
+barrel's vertical arc. If the deck has no clear sector, bolt a ready locker to
+the outer wall below the deck: shelf, two iron brackets, powder chest with corner
+straps, shot tray, and a rammer hung on two hooks. It reads as part of the tower
+and never collides.
+
+Test two ways at minimum and maximum yaw: each fixed child's world position
+delta must be 0, and each fixed mesh's world bounding box must not intersect any
+mesh under the yaw group. Both checks pass, or the station is still in the arc.
+
+Worked example, Bombard Bastion: 17 fixed parts — shelf, two iron brackets,
+powder chest, lid, two corner straps, rope handle, shot tray, tray lip, three
+iron shot, rammer shaft, iron cap and two wall hooks. It sits at y 1.1 to 1.6 on
+the outer shaft, below the deck and outside the barrel arc. At both yaw extremes
+all 17 world positions are identical and the station has zero bounding-box hits
+against the yaw group.
+
+### Creature Anatomy
+
+A creature needs a silhouette feature before it needs a face.
+
+1. **Core mass.** One dominant volume: hunched torso, round slime, long bat.
+2. **Silhouette feature.** Horns, ears, hump, wings, tail, crest, antlers. This
+ is what the user recognises at 30 px.
+3. **Face.** Two eyes, brow, jaw or beak. Eye sockets must be dark and set in,
+ not painted on the surface.
+4. **Limbs.** Joint groups with fillers; hands and feet larger than anatomy
+ suggests, or they disappear at this scale.
+5. **Gear.** One weapon, one strap, one trophy. Not a full armour set.
+6. **Colour break.** One hue for skin, one for cloth, one metal accent.
+7. **Asymmetry.** A chipped horn, a single pauldron, a dragging club. Perfect
+ symmetry reads as a toy soldier.
+
+The boss gets 40 to 60 parts and one signature weapon. Build the weapon as a
+separate group with a haft, head, bands, studs or spikes, and a hand attachment.
+A stone head with no haft reads as a rock floating at the door.
+
+### Small Quadrupeds (Cats, Dogs)
+
+A cat is not a small human on all fours. Build a horizontal spine and four
+contact legs; the silhouette is the back line, ears and tail.
+
+- **Body:** chest sphere r 0.085 at y 0.24, belly capsule 0.24 long, hip sphere
+ r 0.080. Shoulder height 0.26, nose-to-tail base 0.46. A cat at human scale is
+ about 0.25 m at the shoulder; measure, do not scale a person by 0.2.
+- **Head:** skull r 0.075, muzzle 0.045 forward, jaw, nose, two triangular ears
+ (cones or three-vertex prisms) at the top corners. Eyes face forward with a
+ dark socket and a vertical pupil; at 30 px the ears and pupils carry the read.
+- **Legs:** four chains (upper 0.10, lower 0.11, paw 0.05). Front legs are
+ straighter; rear legs have a hock that bends backward. Paws land flat, toes
+ forward. Do not use the human knee sign for a hock.
+- **Tail:** four to six segments with a slow S-curve, root at the sacrum. It
+ counter-sways against the walk and curls when sitting; a rigid stick tail is
+ the fastest way to lose the animal.
+- **Walk:** lateral-sequence four-beat, phase offsets roughly LF 0, RH 0.25,
+ RF 0.5, LH 0.75. The spine dips and rises twice per cycle; the head stays
+ level. Drive phase from distance travelled, like the bipeds.
+- **Sit:** haunches down, rear hocks folded, front legs straight, chest up, tail
+ curled around the paws. A sitting cat is a triangle, not a crouched person.
+- **Jump:** crouch (hips down, spine compressed), extend (all four legs push),
+ airborne (legs tucked, tail up), land (front paws first, then rear). Two
+ seconds of anticipation and recovery, not a linear hop.
+- **Fur:** one base colour, a lighter chest/muzzle, darker ears/tail tip and two
+ or three stripe bands. Do not model individual hairs; the palette snap eats
+ them. Contact shadow is one stretched ellipse under the body, not four paw
+ blobs.
+
+Shoot the cat at 1:1 in profile, three-quarter and sitting. If it reads as a
+rabbit, the ears are too long; if it reads as a dog, the muzzle is too broad and
+the back line too straight. No gear, no trophy, no human jacket.
+
+### Environment Anatomy
+
+- **Three scale cues.** One small (grass, bones, cobbles), one human (cart,
+ barrel, spear), one tall (tower, tree, gate). Without all three the slab has
+ no scale.
+- **Three story props.** A camp, a repair, a warning, a toll, a shrine. Place
+ them off the main path but inside the camera cone.
+- **Two ambient loops.** Fire, flag, smoke, fireflies, grass, water, hanging
+ bones. Phase them differently; synchronized loops read as a screensaver.
+- **A path with a memory.** Ruts, footprints, dropped goods, a worn threshold.
+ A clean path is a diagram.
+- **A boundary treatment.** Trees, rocks, posts or a wall that explains why the
+ slab ends. Do not let props clutter the threshold.
+
+### Detail Audit At 1:1
+
+Before the animation pass, inspect each hero object at 1:1 and answer:
+
+- Can I name its three construction layers without guessing?
+- Does it cast a contact shadow and touch the ground?
+- Is there one asymmetry or story detail I can point to?
+- Does it overlap another object of the same silhouette?
+- Is any detail under 1.5 px, and therefore speckle?
+- Does every hollow object — cannon, pipe, chimney, lamp, tunnel — show a real
+ opening, or does it end in a cap?
+- Does it read in grey, without colour?
+
+If any answer is no, fix the object before animating it. Animation multiplies
+detail; it does not create it.
+
+## The Cast
+
+A 1.69 m figure built from primitives, with an anatomical group per joint so
+limbs overlap when they bend. Faces +Z.
+
+| Constant | Value | Notes |
+| --- | --- | --- |
+| hipY | 0.86 | pelvis group height above the root |
+| hipX | 0.10 | half stance width |
+| thigh | 0.42 | hip to knee |
+| shin | 0.40 | knee to ankle |
+| shoulderY | 0.415 | above the pelvis |
+| shoulderX | 0.182 | half shoulder width |
+| upperArm | 0.30 | shoulder to elbow |
+| foreArm | 0.27 | elbow to wrist |
+| headY | 0.584 | neck to head group |
+
+The base swimwear rig uses two spheres (cranium 0.115, jaw 0.089) plus a nose
+box. For a clothed cast, replace that with the skull/jaw/cheek head below. Torso
+and pelvis are lathes (0.135→0.198 and 0.105→0.180), flattened 0.72 in Z so the
+body is an oval, not a tube.
+
+Construction rules:
+
+1. Build joint groups at the pivot, hang geometry **down (-Y)** from them, so a
+ rotation is an anatomical rotation.
+2. Every joint gets a sphere filler just inside the limb radius. Without it a 90
+ degree bend shows a wedge-shaped hole.
+3. Limbs are capsules; torso and pelvis are lathes for a tapered silhouette.
+4. Clothing is layered over the body as its own lathe slightly larger than the
+ pelvis or torso, plus a band cylinder at the waist or chest.
+5. Never parent a part to a group that has not been created yet in the function
+ body: straps added before the torso exists throw on load.
+
+Pose API: `setPose(person, pose)`, `easePose(p, pose, 1-exp(-22*dt))`,
+`blendPose(a, b)` (component-wise add). Angles are `[x,y,z]` radians per joint:
+`torso, head, shoulderL/R, elbowL/R, wristL/R, hipL/R, kneeL/R, ankleL/R`,
+optional `pelvis`.
+
+**Sign conventions, get these right once:**
+
+- Facing +Z. Positive hip X swings the thigh **backward**; negative forward.
+- Positive knee X bends the heel **backward**. Negative hyperextends and reads as
+ a broken leg. This single sign error is the most common "the walk is broken".
+- Positive shoulder X swings the arm backward, negative forward.
+- Negative elbow X folds the forearm toward the face.
+- Positive shoulder Z abducts an arm away from the body; mirror the sign.
+
+Detail that pays, in order: the skull/jaw head in **Clothed Cast** (hair cap
+theta 1.22, eyes at ±0.037, 0.110, 0.101); cap as a crown cylinder, band and
+brim; brow and lid creases; a narrow nose bridge; a three-layer mouth; ears as
+flattened spheres; hands as a palm plus a finger block and thumb; feet with a toe
+box. Fingers, nostrils and micro-seams do not survive 30 px.
+
+Balaclava: one sphere shell over cranium and jaw (r 0.134, scale 1.0/1.10/0.99)
+plus a neck gaiter cylinder running into the collar. A cover cut at the equator
+leaves a band of skin under the hem that reads as a bare head, and eye openings
+tucked under the shell disappear: put pale lids a few millimetres proud of it. A
+darker skin material is `skin.clone()` with `color.multiplyScalar(0.86)`.
+
+### Clothed Cast: Heads, Layers, Hands
+
+The skeleton is shared; the person is made by the head, the garment silhouette
+and the hand contact. For a clothed cast, start from
+`templates/peopleModel-street.js`; `templates/peopleModel.js` remains the
+swimwear/aquatic variant.
+
+**Head.** A skull plus a jaw, not two stacked balls.
+
+- Cranium: sphere r 0.100 at y 0.118, scale [0.98, 1.16, 0.98]. Jaw: r 0.079
+ at y 0.054, scale [0.78, 0.80, 0.86]; chin r 0.029 at y 0.029, z 0.079.
+- Ears: flattened spheres at x ±0.098, y 0.101, with a darker inner bowl. They
+ are what makes the head read in profile.
+- Eyes: a shade socket, a dark iris r 0.0145 scaled flat, a pale catchlight.
+ Brow above, lid crease below, cheek plane under that. At 30 px the socket and
+ brow carry the expression; the iris just anchors the look.
+- Nose: a narrow bridge box plus a tip sphere, 0.022 wide. A single box reads as
+ a beak from three-quarter.
+- Mouth: upper lip in shade, dark seam, lower lip in skin. Three thin layers at
+ most; a wide box reads as a letterbox.
+- Hair: a sphere cap with `thetaLength` 1.22, positioned at y 0.132 and stopping
+ at the hairline. A 1.85 cap swallows the forehead and reads as a helmet. Add a
+ back mass, sideburns, and for a bun a high sphere at y 0.204. Under a hat show
+ a nape tuft; under a full helmet show none.
+- Hats are their own silhouette: beanie (dome + rolled torus + pom), cap (crown
+ + brim + band), bandana (cap + knot + tail), helmet (shell + visor + chin
+ strap + reflective bands). Never draw hair through a helmet or a cap.
+
+**Clothing is geometry, not paint.**
+
+- Base body: torso lathe 0.135→0.198, pelvis lathe 0.105→0.180, flattened 0.72
+ in Z.
+- Garment: a second lathe 4 to 12% larger (`topK` 1.0 tee, 1.05 jacket, 1.12
+ puffer), plus a hem/waistband cylinder. The garment must have a thickness step
+ at the cuff, collar and hem or it reads as body paint.
+- Sleeves: short sleeve ends above the elbow with a cuff ring; long sleeve is a
+ second lathe down the forearm with a ribbed cuff. Do not texture a bare arm and
+ call it a sleeve.
+- Trousers: tapered lathes over thigh and shin with a cuff at the ankle and a
+ break over the shoe. Loose trousers get a wider profile and a deeper cuff, not
+ a scaled leg.
+- Outerwear: jacket shell + zip/lapel/hem; puffer gets 3 horizontal quilt bands;
+ hoodie gets a kangaroo pocket and drawstrings; apron is a front panel with a
+ bib, waist ties and a towel, never a full cylinder around the body.
+- Backpack sits behind the torso with two shoulder straps that cross the front;
+ a bag floating at the spine reads as a growth.
+- High-vis, reflective bands and lanyards are thin boxes proud of the cloth,
+ following the body curve at 2 to 4 mm.
+
+**Hands are the contact proof.** Palm box 0.070 x 0.078 x 0.054, a finger block
+with two grooves and a thumb capsule. A glove is the same geometry in glove
+material, with a cuff. When a hand holds something, the palm and finger block
+must touch it; a wrist near a handle is not a hold.
+
+If the head or the clothing is wrong, fix it before the walk. A good gait cannot
+rescue a sphere head or a painted jacket.
+
+## Animation
+
+Every motion is a pure function of `t` or of a distance along a track.
+
+```js
+const swing = Math.sin(phase), cs = Math.cos(phase);
+const kneeL = 0.05 + 0.46*Math.max(0,-cs) + 0.22*Math.max(0, swing);
+const kneeR = 0.05 + 0.46*Math.max(0, cs) + 0.22*Math.max(0,-swing);
+pose = {
+ torso: [lean, swing*0.05, 0],
+ shoulderL: [-swing*arm, 0, -0.09], shoulderR: [swing*arm, 0, 0.09],
+ elbowL: [-0.16 - Math.max(0, swing)*0.28, 0, 0],
+ elbowR: [-0.16 - Math.max(0,-swing)*0.28, 0, 0],
+ hipL: [swing*amp, 0, 0.03], hipR: [-swing*amp, 0, -0.03],
+ kneeL: [kneeL,0,0], kneeR: [kneeR,0,0],
+ ankleL: [-kneeL*0.32,0,0], ankleR: [-kneeR*0.32,0,0],
+};
+```
+
+- Hips above ±0.35 read as a march; 0.30 to 0.34 is a walk, 0.5+ is a run with
+ lean 0.26 and elbows near -0.75.
+- Match travel to stride or feet skate: `footTravel = 2*legLength*sin(amp)`,
+ `speed = footTravel * phaseRate / PI`. A 0.86 leg at 0.34 rad and 5.2 rad/s is
+ about 0.9 m/s. Drive `phase` from distance travelled, not from time, and the
+ walk always matches the path.
+- A track is a Catmull-Rom sampled to an arc-length table with `groundY` heights
+ smoothed by three 1-2-1 passes, so steps read as ramps. `at(d)` returns
+ position and heading.
+- Sit: hip X around -1.35 to -1.50, knee +0.5 to +1.3 so the shin drops
+ vertically, torso back 0.05 to 0.1. Seat height is a measured constant.
+- Climb: hands start above the head, opposite hand and foot move together, hips
+ stay close to the ladder (0.12 to 0.2 m) and swing 0.06 to 0.10. Rung spacing
+ 0.30 m, climb 1.0 to 1.2 m/s, phase driven by height, not time. Feet land on
+ rungs, not between them; the shadow belongs on the ladder/deck, not the slab.
+- One-shot actions (jump, dive, kick) are phase tables with eased poses, never a
+ blend between two loops. Hoist shared easing factors above the branch: a
+ `const` declared in one branch and read in another throws every frame and
+ freezes the figure. Pose targets are full poses, not deltas.
+- Airborne arcs are solved backwards from the impact: for a fixed flight `T`,
+ `vy = (landY - launchY + 4.9*T*T)/T`. A guessed `vy` either lands late or
+ stops in mid-air.
+- The rig root is at the feet, so a rigid-body spin sweeps the model around its
+ toes: rotate about a pivot `C` with `p' = p + C - R*C`, C about 0.55 up.
+
+### Carrying, Loading And Mounting
+
+These are the beats closest to the camera and the ones users report first. A
+prop that teleports, a hand that misses it, or a leg that swings through the
+handlebars destroys the whole miniature.
+
+**Carry.** Keep the prop in world space and solve its transform from the hands
+every frame; do not parent a big prop to a wrist group (it inherits the wrist
+roll and swims).
+
+```js
+const hl = new THREE.Vector3(), hr = new THREE.Vector3();
+J.wristL.getWorldPosition(hl); J.wristR.getWorldPosition(hr);
+const mid = hl.clone().add(hr).multiplyScalar(0.5);
+bag.position.set(mid.x, Math.min(hl.y, hr.y) - 0.42, mid.z);
+```
+
+- Build the prop with its origin at the **bottom centre**. Then a hold offset is
+ a single subtraction, and the same object seats on the ground/crate floor
+ without a second pivot.
+- Two hands for anything heavier than a paper bag. The palms must be within
+ 0.08 m of the prop surface at every sampled frame; log the wrist positions and
+ the prop bounds.
+- Match the carry pose to the weight: heavy box at the belly, shoulders -1.2 to
+ -1.4, elbows -1.2 to -1.4, torso lean 0.2; a light bag hangs from one wrist
+ with the elbow nearly straight.
+- Reduce arm swing while carrying; the legs do the walking. A full arm swing
+ with a box in the hands reads as a puppet.
+- **Handoff:** at contact, set the prop to the receiver's hold for one frame, then
+ blend ownership over 0.2 to 0.3 s. A hard parent switch pops even when the
+ world positions match.
+
+**Loading into a crate or hatch.**
+
+1. Lift the prop above the rim in front of the chest, with both hands on it.
+2. Tuck the prop's x/z over the opening while the hands stay on it.
+3. Lower it until its base reaches the floor; keep the hands on it for a beat.
+4. Release, step back, and only then close the lid, clip the bungee or turn away.
+
+Never translate the prop from hands to slot in one frame, and never let it
+descend outside the crate wall. A bungee or lid that intersects the prop on the
+way in must animate open and closed; hiding it for the whole beat reads as a
+missing part.
+
+**Mounting a scooter, bike or horse.**
+
+Author the mount in the vehicle's local frame, from a measured seat/board, not
+by eye.
+
+- Place the left boot on an outboard running board or peg. If the vehicle has
+ none, add one; standing on the body or the seat reads as a doll being posed.
+- Swing the right leg **out to the side** with hip Z abduction (about +0.9 to
+ +1.25 rad), knee flexed 1.2 to 1.4. Hip X flexion swings the leg forward,
+ through the handlebars; that is the common error.
+- Raise the root in a small arc (0.10 to 0.20 m) so the boot clears the saddle,
+ then drop onto the seat. Do not hop a body-height above it.
+- Seat root = the pelvis mesh's contact point, not the rig origin. Sit with the
+ pelvis on the cushion, both boots on the boards, knees 0.9 to 1.1 rad, toes
+ forward; hands reach the grips with soft elbows. Move the bars to the hands
+ before hyperextending the arms.
+- A rider pose is not the standing pose rotated: torso upright 0.15 to 0.25,
+ hips flexed -0.9 to -1.1, hips abducted ±0.25 to ±0.35, knees 1.0 to 1.1,
+ ankles near -0.05.
+- Keep the vehicle and rider on the same mover after departure, with the rider
+ root attached to the seat anchor; a bob applied to one and not the other
+ separates them.
+
+**Proof.** A nine-frame side strip at 0.15 to 0.25 s spacing: approach, lift,
+over-rim, lower, release, step, leg-swing, seat contact, ride. Shoot it at 1:1
+and log wrists, ankles, prop base and seat. A still cannot prove a mount.
+
+## System And Combat Animation
+
+The character section above covers body mechanics. This section covers the
+systems that carry a diorama: towers, projectiles, reactions, deaths,
+bosses, crowds and secondary motion. Every one is a pure function of `t`, driven
+by a pre-simulated event list.
+
+### The Five Layers In Code
+
+| Layer | Driver | Typical period | Use |
+| --- | --- | --- | --- |
+| ambient | `sin(t*f + phase)` | 1.5 to 5 s | breath, flame, flag, scan |
+| locomotion | distance along a path | stride length | walk, fly, hop, slither |
+| action | absolute event time | 0.3 to 1.2 s | fire, swing, slam, dive |
+| reaction | event time + direction | 0.15 to 0.5 s | flinch, flash, knockback |
+| death | absolute death time | 0.6 to 1.4 s | collapse, debris, residue |
+
+If an action and a reaction share a clock, derive both from the **same event
+timestamp**. Two independent cycles will drift apart even if they match on the
+frame you happened to inspect.
+
+### Deterministic Timeline
+
+```js
+const DT = 1 / 40;
+const LOOP = 46.0;
+
+const pulse = (t, t0, tau) => (t < t0 ? 0 : Math.exp(-(t - t0) / tau));
+const win = (t, t0, dur) => clamp((t - t0) / dur, 0, 1);
+const easeOutCubic = (u) => 1 - Math.pow(1 - u, 3);
+const spring = (t, t0, freq = 9, damp = 6) => {
+ const a = t - t0;
+ return a < 0 ? 0 : Math.exp(-damp * a) * Math.cos(freq * a);
+};
+```
+
+Run the battle at `DT` from 0 to `LOOP` once at load. Store:
+
+```js
+events.push({ t, kind: 'shot', tower, target, from, to, flight, damage });
+events.push({ t, kind: 'impact', x, y, z, species, dir });
+events.push({ t, kind: 'death', id, type, x, y, z, t });
+events.push({ t, kind: 'gate', x, y, z, hit: n });
+```
+
+The render loop reads the events whose time has passed. It never re-simulates
+and never carries state between frames. `?t=12.4` freezes the whole system,
+including effects, so every QA shot is reproducible.
+
+### Tower Attack Grammar
+
+A tower attack needs five visible stages. Cut one and the tower reads as a
+spawner, not a weapon.
+
+| Stage | What the player sees | Time |
+| --- | --- | --- |
+| acquire | head/turret turns; crew leans; crystal brightens | 0.15 to 0.4 s |
+| wind-up | rail pulls back, arm cocks, coil charges, barrel vents | 0.1 to 0.35 s |
+| release | muzzle flash, string snap, beam origin flare, arc jump | 1 to 2 frames |
+| travel | bolt, ball, beam, chain, projectile with trail | 0.05 to 0.6 s |
+| impact | flash on target, dust/goo/ice/feathers, ring | 0.1 to 0.25 s |
+| recovery | recoil returns, crew resets, smoke clears | 0.2 to 0.5 s |
+
+Tower archetypes:
+
+- **Ballista / arrow.** Slow traverse, rail recoil 0.15 m, string snap, bolt
+ with a short trail, thunk and a small dust puff. Reload is a winch crank.
+- **Cannon / bombard.** Breech recoil 0.2 m, muzzle flash and a smoke ring,
+ arcing iron ball, impact dust and a ground ring. Never rock debris.
+- **Beam / lance.** Crystal pulses, origin flare, a sustained channel with a
+ scrolling texture, a target flash, a heat ramp. The beam dies on the frame its
+ target dies and respects line of sight. Never a static white cylinder.
+- **Tesla / chain.** Coil hum, charge glow, a jagged arc that hops to two or
+ three targets, capacitor fade. The arc must visibly leave the coil.
+- **Support / aura.** A ground ring with a clear radius, a pulse that travels
+ outward, a colour shift on affected units, and a caster animation that shows
+ the source. No invisible buff. Audit it as a field, not a shot: origin, area,
+ ramp, affected-target change, decay.
+- **Rotating emitter / lighthouse.** A continuous sweep is not a turret. Keep the
+ base sweep `theta(t)`, add a short dwell window when a target crosses the
+ beam, and ease in/out of the dwell so the housing never snaps. Fire inside the
+ dwell; return to the sweep with the same phase it would have had. If the beam
+ can point into the goal pocket, mask that sector physically (back-screen,
+ shroud) rather than breaking line of sight with a special case.
+
+If the tower has a crew, the crew reacts: brace, pull, cover ears, crank. A
+crew that stands in the same pose through a cannon shot is a mannequin.
+
+### Machine Grammar (non-combat)
+
+A loom, press, crane, oven, pump or lighthouse lens is not a tower, but it needs
+the same causality. Replace "attack" with **work**:
+
+| Stage | What the player sees | Time |
+| --- | --- | --- |
+| engage | clutch drops, belt tightens, valve opens, lamp housing turns | 0.15 to 0.4 s |
+| work | beam sweep, flywheel spin, ram stroke, dough stretch, water flow | 0.3 to 3 s |
+| output | light pool, pressed sheet, lifted crate, baked loaf, water rise | 0.1 to 0.5 s |
+| settle | flywheel coasts, valve closes, belt slackens, lamp returns | 0.2 to 1 s |
+
+Audit: **input** (what feeds it), **motion** (what turns/strokes), **output**
+(what changes in the world), **residue** (waste, heat, crumbs, steam). A machine
+with a beautiful motion and no output is a kinetic sculpture; give it a product
+and show the product.
+
+### Goal Response Vocabulary
+
+A boss or disaster must act on a **goal**, not just a door. Pick the response
+from the goal's material:
+
+| Goal | Contact response | Failure |
+| --- | --- | --- |
+| door / gate | flash, shake, crack, dust from the lintel | leaf hangs, ward closes |
+| valve / pipe | spray, gauge drop, pipe shudder, hiss | pressure falls, lamp starves |
+| rope / bridge | slack, sag, strands snap, deck drops | span falls, route closes |
+| wall / dam | chip, crack, water seep, block falls | breach, flood |
+| tree / mast | bark split, creak, tilt, leaves fall | trunk breaks, canopy drops |
+
+Put the contact point on the **silhouette edge** of the goal, not buried in its
+body, and keep it clear of the boss's shoulder/weapon. If the goal is tall, put
+the contact at chest height and turn the boss 0.3 to 0.4 rad so the weapon shaft
+crosses the frame. The response and the contact must share the same timestamp.
+
+### Projectile Grammar
+
+1. Spawn at the **muzzle, rail tip, hand or crystal**, not the tower centre.
+2. Give it a fixed flight time or a solved arc; do not integrate physics in the
+ render loop.
+3. Add one trail or one tumble. A bare sphere is a debug object.
+4. On impact, switch to a **species-specific** effect: dust and ring for iron,
+ splinters for wood, goo for slime, feathers for flyers, ice shards for frost.
+5. Remove it on the impact frame. No projectile survives its target.
+
+A projectile that is visible after the target is dead is a bug, not a flourish.
+
+### Creature Animation Grammar
+
+| Archetype | Locomotion | Action | Reaction | Death |
+| --- | --- | --- | --- | --- |
+| small scrapper | scamper, 2-beat | quick stab | flinch + skid | cloth, knife, stain |
+| brute | heavy walk, shoulder roll | overhead cleaver | stagger, shoulder dip | iron plates, sword, dust |
+| slime | squash-hop | lunge | wobble, split | goo splat, two lets |
+| flyer | flap, bank, hover | dive | spiral, feather burst | feathers, spiral fall |
+| boss | weight shift, slow stride | telegraph + slam | recoil, knee dip | collapse, gear, weapon, soul |
+
+Every creature gets a **hit flash** on the body material for 0.08 to 0.12 s and
+a **directional flinch** opposite the impact. Do not reset the whole pose on a
+hit; blend a flinch over the current pose and recover.
+
+Death is a sequence, not a switch:
+
+1. **Impact frame:** freeze or compress the body, flash, drop the weapon.
+2. **Collapse:** 0.25 to 0.5 s; knees buckle, torso folds, flyer spirals.
+3. **Species debris:** 5 to 8 pieces of cloth, iron, goo, feathers, bone.
+4. **Residue:** a stain, scorch, splat or dropped gear that stays for 1 to 3 s.
+5. **Soul:** a brief additive flicker or wisp, 0.2 to 0.4 s, then gone.
+
+A death that is a sphere burst, a grey puff or a rock shower fails the bar even
+if the particle count is high.
+
+### Boss Choreography
+
+A boss exists to **act on a place**, not to have more hit points.
+
+- Stop it outside the threshold by **body depth + weapon reach**. At the gate,
+ that was 2.0 m short of the path end, which left the troll on the drawbridge
+ with the door visible behind the club.
+- Turn it **three-quarter to the goal** (about 0.35 rad off the door axis) so
+ the weapon shaft reads across the frame instead of end-on. An end-on club
+ head is a grey rock at the door.
+- Build the weapon as a separate group: haft, head, two iron bands, six studs,
+ six spikes, and a visible hand attachment. A stone head with no haft is a
+ floating rock.
+- **Telegraph** 0.4 to 0.7 s, contact 0.1 s, recovery 0.3 to 0.5 s. The contact
+ pose is driven by the same gate-hit pulse as the door flash and crack.
+- Put the door response on the same timestamp: flash, shake, crack, dust. If
+ the club hits at 41.075, the door cracks at 41.075, not 41.2.
+- Lose the tower's line of sight to the gate pocket while the boss is there.
+ A beam arriving at the same pixels as the club steals the beat.
+- Prove it with two shots: contact frame and contact +0.2 s. The first shows
+ contact and flash; the second shows recoil. If the club is hidden at contact
+ and only appears on recoil, the pose is late.
+
+### Crowd Variation
+
+- Phase offset per actor: `phase = hash(i) * TAU`, never one global `sin(t)`.
+- Vary speed by 4 to 8 percent, scale by 2 to 4 percent, and idle by phase.
+- Stagger spawns and attack windows by at least 0.15 s. A shared window makes a
+ group move like a chorus line.
+- Give each actor a lane or offset on the path; two actors at the same waypoint
+ stack into one silhouette.
+- At a shared door or gate, one actor reaches the threshold; the rest hold back
+ at `0.9 + i * 0.8` along their own path.
+
+### Secondary Motion
+
+Flags, banners, cloth, chains, hanging bones, smoke and fire are the cheapest
+way to make a static scene feel alive. Rules:
+
+- Drive with `sin(t * f + phase)` and a phase offset per object.
+- Add a lag of 0.1 to 0.2 s behind the parent motion; cloth that moves exactly
+ with the body looks rigid.
+- Keep amplitude small: 0.03 to 0.12 rad for cloth, 0.02 to 0.06 for chains.
+- Cap the count. Six flags at different phases read as wind; twenty read as
+ noise.
+- Never let a secondary object enter the threshold pocket or cover a face.
+
+### Animation QA
+
+For every hero actor, capture:
+
+- a **6-frame strip** of locomotion at 0.1 s spacing;
+- the **action contact frame** and contact +0.2 s;
+- the **death** at impact, mid-collapse and residue;
+- the **boss contact** at the door plus recoil;
+- the **beam** at full channel and the frame after the target dies;
+- a **pivot parentage strip**: freeze at minimum and maximum yaw and log the world
+ positions of every fixed deck prop. They must not move; only the turret and its
+ carriage should. Also check world bounding-box overlap between the fixed
+ station and every mesh under the yaw group: zero hits.
+
+The strip passes when feet plant, knees bend backward, no joint opens a wedge,
+no part floats, and the silhouette changes between frames. A still cannot prove
+an animation; a strip can.
+
+## Service And Queue
+
+A market, hatch, ticket window or bakery is a **queue machine**: people arrive,
+advance one slot, order, pay, receive and leave. Build the queue before the
+props; it is the scene's clock.
+
+**Slots.** Lay four to six positions along the counter, 0.65 to 0.80 m apart,
+perpendicular to the hatch. Everyone in the queue shares one lane and one
+heading; a diagonal queue reads as a crowd, not a line.
+
+```js
+const SLOTS = [q0, q1, q2, q3]; // q0 is at the hatch, q3 is the tail
+const toSlot = (p, slot) => ({ x: slot.x, z: slot.z });
+```
+
+- A customer's mover is a sequence of `seg(t0, t1, track)` legs: **enter →
+ tail → advance one slot per serve → counter → exit**. Keep each leg on its own
+ track; re-pathing every serve makes feet slide.
+- Advance the whole queue on the serve timestamp, with a 0.06 to 0.12 s stagger
+ by slot. The person at the hatch does not advance; they receive and turn away.
+- When a customer leaves, the next walks **into** the vacated slot; do not teleport
+ the queue forward while the camera is on it.
+
+**Customer state machine.**
+
+| State | Visible action | Gate |
+| --- | --- | --- |
+| arrive | walk with distance-driven gait | until slot reached |
+| order | point at menu/board, head turns | only when speed = 0 |
+| pay | hand to counter / phone | after order, only when still |
+| wait | idle, weight shift, phone | until bag lands |
+| receive | both hands or one hand out | at bag contact |
+| exit | turn, walk out, carry bag | after receive + 0.3 s |
+
+**The gate is the whole fix.** Never blend a standing gesture (`PAY`,
+`POINT_MENU`, `RECEIVE`) into a walking pose. If the gesture has straight legs
+and the walk has bent knees, the mix straightens the legs while the root keeps
+translating: the figure glides. Compute `state.moving` from the mover and write:
+
+```js
+if (state.moving) pose = walkPose(phase, { amp, arm, carry });
+else if (t < orderEnd) pose = mixPose(idle, POINT_MENU, bell(t, order));
+else pose = idlePose(t, phase);
+```
+
+- Serve **after** the counter arrival, by at least 0.25 s. A bag that lands before
+ the customer reaches the hatch is the second-most-reported queue bug.
+- One action at a time: order, then pay, then receive. Overlapping windows make
+ the arms fight.
+- A late customer may arrive after the queue empties, but only once; reusing the
+ same slot for a second invisible customer reads as a spawn.
+
+**Machine slots.** A laundromat, workshop or gym uses the same clock with
+machines in the slots: washer drum → dryer drum → fold table. Advance the batch
+on the **end-of-cycle** timestamp, not on a fixed beat, and land the next action
+0.25 s after the lid/door closes. A drum that starts tumbling before the door
+shuts is the machine version of serving before arrival.
+
+**Staff side.** The cook works the grill; the cashier takes payment and hands the
+bag across the hatch. Their gestures are independent loops, but the bag's release
+comes from the cashier's hand position, not a fixed world point. Keep a stack of
+paper bags at the hatch and decrement it per serve; the last bag is the goal
+object.
+
+**Proof.** Freeze the approach every 0.25 s for two strides and log root speed,
+`moving`, hip/shoulder angles and slot. The strip passes when the feet alternate,
+the root advances smoothly, no standing gesture appears while `moving` is true,
+and the serve timestamp is after the arrival timestamp.
+
+## Vehicles
+
+A vehicle is the prop the user inspects the moment a door opens, so build it to
+be opened. Model facing +Z.
+
+| Part | Size and place | Note |
+| --- | --- | --- |
+| floor pan | 1.62 x 0.10 x 4.02 at y 0.35 | dark; its top is the cabin floor |
+| rockers | 0.12 x 0.16 x 3.92 at x ±0.87 | stay with the body |
+| front fender | 0.10 x 0.56 x 1.05 at z 1.62 | body side ahead of the front door |
+| rear quarter | 0.10 x 0.56 x 0.72 at z -1.84 | body side behind the rear door |
+| belt moulding | 0.10 x 0.08, one per fixed panel | never one rail across the apertures |
+| bulkheads | 1.84 x 0.56 x 0.16 at z ±2.12 | close the tub |
+| roof | 1.48 x 0.08 x 1.94 at y 1.44 | drip rails at x ±0.76 |
+| pillars | A raked -0.64, B upright, C raked +0.60, 0.075 thick | |
+| windscreen | 1.44 x 0.62 x 0.05, rotation.x -0.64 | glass between the A pillars |
+| side glass | none | windows down: open holes between the pillars |
+
+Cabin: dash 1.46 x 0.15 x 0.30 at y 1.00 z 0.80; wheel torus r 0.125 at
+(-0.40, 1.10, 0.68) rotated -0.42; front cushions 0.46 x 0.10 x 0.50 at y 0.57
+**z 0.30** with backs at z 0.04; rear bench 1.20 wide at z -0.50 with its back at
+z -0.74.
+
+The windscreen is not a plane at the front of the cabin: rotated -0.64 it sweeps
+back to about z 0.59 at its base. A front seat at z 0.72 therefore sits **inside
+the glass volume**, and every occupant's head prints on the windscreen from every
+angle. Keep the cushion's front edge at least 0.25 behind the glass base and move
+the dash, wheel and column back with it.
+
+**Doors.** Hinge at the shut line, leaf extends backward in -Z: front 1.15 to
+-0.15, rear -0.15 to -1.45, leaf 1.30 long and 0.55 high. Pivot at
+`(side*0.86, 0.62, hingeZ)`, children are outer skin, inner card, sill strip,
+handle, and any livery; `rotation.y = -side * open` swings it out. Swing 1.28 rad
+for a saloon, up to 1.52 for a cruiser. Split every full-length body moulding at
+the shut lines: a moulding left on the shell reads as the top of the door left
+behind when it opens.
+
+**Boot.** Pivot at (0, 0.90, -1.46), lid extends -Z, `rotation.x = +0.95` lifts
+the rear edge. Well floor y 0.44 against a lid underside at 0.89, so cargo must
+fit 0.45: bags r 0.165 at y 0.63 (tops 0.80) clear it. Close the boot off from
+the cabin with a parcel shelf (1.74 x 0.05 x 0.66 at y 0.86, z -1.10) and a
+bulkhead behind the rear seat back (1.74 x 0.46 x 0.06 at y 0.63, z -0.82);
+without them the boot is open to the cabin through the rear windows and the load
+reads as sitting on the closed lid.
+
+Cargo carries `visible = false` until it lands and `userData.noMerge = true`.
+A throw needs an object that travels: keep one world-space bag per thrower and arc
+it hand → slot with `p.y += sin(f*PI)*0.6`, switching the slot's bag on when the
+flight lands, not at release.
+
+### Scooters, Cargo Bikes And Mounts
+
+A scooter is not a car with two wheels. Build it around the contact points: two
+tyres on the ground, a floor pan for the boots, a seat the pelvis can sit on, bars
+the hands can reach, and a cargo crate whose opening is visible from the camera.
+
+Reference local frame, facing +Z, for a delivery scooter at 1.0 scale:
+
+| Part | Place | Note |
+| --- | --- | --- |
+| wheels | r 0.26 at z ±0.62 | tyre + hub + fender; both touch y 0 |
+| floor pan | 0.60 x 0.04 x 0.30 at y 0.30 | top is the boot surface |
+| running boards | 0.12 wide at x ±0.235 | outboard, full length; the left boot lands here |
+| body / shield | 0.46 wide, up to y 0.72 | front leg shield, not a box |
+| seat | top 0.83 at z -0.18 | measure the cushion top, not the body |
+| bars | y 1.06, grips x ±0.33, z 0.52 | raise bars to the rider's hands |
+| cargo crate | 0.52 x 0.44 x 0.46, base y 0.86, z -0.56 | open top, interior floor ~0.91 |
+| bungees | two cords across the opening | clip open during loading |
+
+- **Seat anchor.** `seat = local(0, 0.83, -0.18)`; set the root so the **pelvis
+ mesh** contacts the cushion, then prove it in a seated portrait. On the Night
+ Market scooter that is root y 0.09 against a 0.83 seat; do not copy a
+ `seatY - hipY` formula from a chair, because the pelvis mesh hangs below the
+ hip joint. A copied root puts the rider on the front edge or floating.
+- **Boots.** Add outboard running boards at y 0.30 if the floor pan is narrower
+ than the rider's stance. Ankles at 0.30, knees 1.0 to 1.1, toes forward; both
+ soles flat. Perching one boot on the body is the "doll on a toy" read.
+- **Hands.** Grips at the wrist height; a rider with hands 0.15 m above the bars
+ is not holding them. Move the bar/riser up or soften the elbow; do not
+ hyperextend the shoulder.
+- **Cargo.** A crate with an open top needs an interior floor and side walls;
+ a bag lowered to `baseY + 0.01` sits inside. Keep bungees as a separate group so
+ they can unclip during loading and close over the lid afterwards.
+- **Lights.** One emissive lens plus a small halo sprite; a headlight cone only
+ at night. A large additive disc reads as a floating balloon; a brake light is a
+ second, smaller lens, not a copy of the headlight.
+- **Clipping.** The whole vehicle + rider + cargo move as one mover after
+ departure; clip the group at the slab edge, and hide rider shadow at the same
+ time the vehicle shadow takes over.
+
+Mounting is authored with the sequence in **Carrying, Loading And Mounting**:
+left boot on the board, right leg abducted over the saddle, small root arc,
+pelvis on the seat, hands to the grips. Prove it with the nine-frame side strip.
+
+### Buses, Vans And Long Vehicles
+
+A bus is a moving room. Its job is a window band, a door, a route sign and a
+headlight sweep; the chassis is the least visible part.
+
+| Part | Size / place | Note |
+| --- | --- | --- |
+| body | 9 to 12 m long, 2.5 wide, 3.0 high | one box with a chamfered roof |
+| window band | y 1.35 to 2.45, full length | dark glass + warm interior, not a transparent plane |
+| door | 1.1 wide, front or centre | step well, grab rail, lit interior |
+| wheels | r 0.50, wheelbase 5.5 | two axles; arches cut into the skirt |
+| route sign | front above the windscreen | emissive text/colour blocks, readable at 1:1 |
+| livery | one band + one number | never a full advertising wrap at this scale |
+| headlights | two lenses at y 0.65 | plus cones and a floor ellipse |
+| interior | 4 to 6 lit windows + driver silhouette | a dark box with one warm strip reads as a bus |
+
+- **Speed and weight.** 5 to 8 m/s, no bounce; one brake dip at the stop. A bus
+ that bobs like a car reads as a toy. The body leans 0.01 to 0.02 rad on the
+ brake, no more.
+- **Headlight sweep.** Two cones and one long floor pool travel with the bus.
+ Do not light the facade with the cone; a 12 m vehicle with a global spotlight
+ turns night into noon.
+- **Occlusion.** A bus between the camera and an interior hero covers the beat.
+ Put its lane behind glazing at -Z, or time it before/after the contact. Check
+ the occlusion frame at the hero timestamp.
+- **Doors.** If the door opens, model the step well, a grab rail and an interior
+ light; a black rectangle reads as a hole. For a passing bus, keep the door shut.
+- **Clip.** The whole bus, lights, interior and driver move as one group; hide
+ its contact shadow at the slab edge, same frame as the vehicle.
+
+A bus that reads as a white box with black windows is not finished: the window
+band, route sign, wheel arches and one warm interior strip are the minimum.
+
+### Seats, Exits And Transfers
+
+Seat root = cushion top minus hipY, which is **-0.38** in car space on this rig:
+the hips settle into the cushion and a masked head clears the roof with 6 to 8 cm.
+At -0.18 a hooded head lands about a centimetre under the roof panel and any bob
+prints a dark pixel on the white roof. Measure against the head mesh, not the head
+joint, and lower the seat rather than raising the roof, which is pinned to the
+pillars.
+
+The stand spot is 2.00 m out from the car's centreline and 0.30 behind the hinge
+for a front seat, 0.55 for a rear:
+
+```js
+const exit = toWorld(car, side * 2.00, seatZ - 0.30);
+```
+
+An open leaf hangs in the plane of its hinge, so an exit level with the seat puts
+shoulders and head through the door skin. 0.30 still sits inside the aperture and
+leaves room for a torso plus a swinging arm. 2.00 out is about 1.07 of daylight
+from the flank, and that is not padding: at 45/33 a figure 0.7 off the flank sits
+wholly inside the car's silhouette with his feet on the rocker line and reads as
+welded to the body.
+
+The climb is authored in the **car's own frame**, so it works at any parking
+angle. It ships: `templates/transfer.js` is the whole move (`transfer`,
+`climbAt`, `CLIMB`, `stepPose`, `standSpot`), and `templates/poses.js` carries
+the four climb poses plus the walk and run cycles it blends between. Copy them,
+do not retype them. `k` runs 0 at the open door to 1 at the seat, `dy` is the root height
+above the seated root, and the pose is a real sequence: stand, reach, crouch in,
+sit on the edge, swing the legs in, settle.
+
+```js
+const CLIMB = [
+ { u: 0.00, k: 0.00, dy: 0.380, pose: STAND },
+ { u: 0.16, k: 0.03, dy: 0.330, pose: REACH }, // hand to the roof edge
+ { u: 0.36, k: 0.16, dy: 0.120, pose: CROUCH_IN }, // knees deep, hips dropping
+ { u: 0.56, k: 0.38, dy: 0.010, pose: SIT_EDGE }, // perched, feet still down
+ { u: 0.76, k: 0.66, dy: 0.000, pose: LEGS_IN }, // knees up, feet over the sill
+ { u: 0.90, k: 0.88, dy: 0.000, pose: mix(LEGS_IN, SEATED, 0.55) },
+ { u: 1.00, k: 1.00, dy: 0.000, pose: SEATED },
+];
+```
+
+The transfer wraps that climb: the first `STEP_SHARE` (0.26) of the window is one
+stride from the stand spot to the door, the rest is the climb, and on the way out
+the stride away comes last. The body only reaches cushion height once the hips are
+over the sill, so nobody sinks, floats or slides through the bodywork. `DOOR_STAND_X`
+1.34, `DOOR_STAND_DZ` -0.06, durations 1.05 to 1.20 s each way. Never derive the
+duration from the next beat's start: under about 0.9 s the whole move reads as a
+slide or a blur. Move the following beat later instead.
+
+Facing is the trap. The outward yaw points away from the car, so a figure entering
+with it climbs in backwards: body into the seat, face to the street. On the way in
+every key before the seated ones faces the car, including the standing key that
+gets forgotten. Resolve it from geometry, never from the approach path's tangent:
+a path's opening segment runs along the street, so `path.at(0).yaw + PI` points
+down the kerb and lands the figure a right angle off whichever way he arrived.
+
+```js
+const faceYaw = car.yaw - side * (PI / 2); // square to the open door
+const face = Math.atan2(seat.x - stand.x, seat.z - stand.z); // stand -> seat
+// turn to the windscreen only once the hips are on the cushion
+const turn = smooth(clamp((v - 0.62) / 0.30, 0, 1));
+yaw = lerpAngle(faceYaw, car.yaw, turn);
+```
+
+Staging rules that came out of real reports:
+
+- **One window per actor, staggered 0.2 s or more.** A shared window climbs two
+ men into a seat on the same frame, which reads as choreography, and at 0.1 s
+ they climb through each other.
+- **Separate a pair in screen space, not in world space.** At a locked 45/33
+ view, moving a figure further out along the camera axis barely changes where it
+ lands on screen: it stays stacked over the car's flank and still reads as one
+ blob, which is why pushing the stand spot from 1.6 m to 2.0 m did not cure a
+ "stuck" report. What separates them is offset along the car's axis, because that
+ is screen x: rear occupant 0.72 behind his hinge against 0.30 for the front
+ leaves 1.2 m of screen distance instead of 0.8, where two figures merge into one
+ silhouette. Project both actors with `v.project(camera)` and compare pixels
+ before concluding they are spaced.
+- **Doors are a timeline, not a state.** Open the leaf 0.15 s before a transfer,
+ shut it 0.5 s after the last man is clear, reopen just before the entry. A car
+ left open for the eight seconds its crew is away reads as the crew stuck in the
+ doorway, however clean the walk is.
+- **A run that ends at the car must not hand straight into the transfer.** End it
+ 0.4 to 0.6 s early, blend out to STAND over the last 12 percent, hold a beat at
+ the door, then climb.
+- **Seated figures stay visible.** Hiding them when the entry ends sends an empty
+ car down the street, which the user reads as a bug, not a cutaway.
+
+### Clear Spots, Shut Doors
+
+- **A shared doorway needs one lane per actor plus a hold-back on the approach.**
+ Actors on the same waypoints put the second in the first's back and stack at the
+ threshold. Offset the approach per actor, stop each one short of the door by
+ `0.9 + i*0.8` along his own path, stagger the walk-in windows by 0.25 s, and let
+ the lead actor alone reach the threshold: the kick, the first step through. Four
+ men then read as a queue filing in rather than a scrum.
+- **Diagnose "stuck" with numbers, not frames.** Freeze in 0.3 s steps across the
+ beat and print every actor's x/z with the pairs closer than 0.6 m. A pair that
+ holds that close for more than one sample is jammed; a single sample is two men
+ passing. At 12 px a figure a screenshot cannot tell those apart, and nudging
+ spacing by eye fixes the wrong thing: the real cause is usually a route that
+ ends where another actor already stands.
+- **Give every actor a route out of every beat.** Two officers left in a cover
+ crouch at the kerb while everyone else moves is a direction bug, and the report
+ is always "they are stuck" however correctly the two are separated.
+
+### Clipping At The Diorama Edge
+
+Vehicles enter and leave the block, and the slab is a window. Four world-space
+planes on the renderer for the scene pass, cleared before the post quad:
+
+```js
+const CLIP = [
+ new THREE.Plane(new THREE.Vector3( 1, 0, 0), hx + 0.05),
+ new THREE.Plane(new THREE.Vector3(-1, 0, 0), hx + 0.05),
+ new THREE.Plane(new THREE.Vector3( 0, 0, 1), hz + 0.05),
+ new THREE.Plane(new THREE.Vector3( 0, 0,-1), hz + 0.05),
+];
+r.clippingPlanes = clipPlanes; r.setRenderTarget(rt); r.render(scene, camera);
+r.clippingPlanes = []; // before the full-screen quad
+```
+
+A car entering nose-first shows its own front surfaces at the cut, so the cut
+reads clean; one leaving tail-first exposes the cut face, so keep the interior
+modelled and it reads as a cutaway. Route every vehicle one way, in at one end of
+the street and out at the other, no reversing and no angled parking: an angled
+park reads as a collision, and backing in reads as a bug. Two vehicles sharing a
+lane need a departure gap (`pLeaveGap` ~1.15 s) or the far one drives through the
+near one.
+
+## Effects
+
+- **Water**: `MeshPhysicalMaterial` with vertex colours, not a custom shader, so
+ it receives shadows. Ramp shallow to deep teal, never to navy: a near-black end
+ quantises into a hard band the user reads as a hole.
+- **Wake**: unlit additive foam streak plus 8 to 12 expanding ripple rings spawned
+ behind a moving body every 0.4 s, fading as `(1-k)^2`.
+- **Splash**: 60ish unlit additive droplets with gravity plus four rings and a
+ foam disc; normal-blended white over teal reads as a grey blob. Seed the burst
+ (`trigger(x, z, power, burstSeed)`), never `Math.random`: a frozen frame must
+ reproduce the same burst, and the same frame must reproduce it again after the
+ clock jumps.
+- **Effects that integrate dt need a `reset()`.** Wake and splash advance by
+ `dt`, so jumping the clock to freeze a frame does not jump their state, and the
+ frozen splash shows whatever the last played frame left behind. Both templates
+ expose `reset()`; the harness calls it and re-simulates in fixed steps from
+ zero, which took a two-frame diff from 334 differing pixels to 18.
+- **Smoke**: camera-derived billboards. The camera is locked, so copy its
+ quaternion once and every puff is a plane facing the lens.
+- **Debris with history**: loose notes or paper use a solved arc, a drag term, a
+ spin about a random-but-deterministic axis, then slerp to flat and lie there for
+ the rest of the loop. Deterministic hashing (`sin(n*127.1)*43758.5` fractional)
+ keeps every replay identical.
+
+### FX And The Edge
+
+The slab is a window, but not every effect is a solid. Split them:
+
+- **Cut FX** — debris, props, vehicles, bodies. Let the world clip plane cut
+ them; model the interior so the cut reads as a cutaway, and route them so they
+ enter and leave rather than parking across the edge.
+- **Read-through FX** — light beams, glow, wake, spray, horizon haze. Do **not**
+ let a hard clip plane slice them. End the effect at its target, fade intensity
+ to zero before the slab boundary, or mask it with a soft edge. A lighthouse
+ beam that stops in a straight vertical cut reads as a broken cone.
+- **Additive over white.** Additive white on a white page is invisible. Give a
+ beam a saturated core from the palette plus a darker under-edge or halo, and
+ test it at 1:1 against the page, not against a dark viewport. If the beam must
+ cross the whole frame, let it dim toward the edge; a bright hard-ended beam is
+ worse than a soft falloff.
+- **Clipped water.** A hull cut at the slab edge needs its interior and a foam
+ plane at the cut, or it reads as a hollow shell. A moored boat should sit fully
+ inside the frame for the beat where it unloads.
+
+### FX Under The Snap
+
+Every scene effect goes through the palette snap. That is the look, but it
+punishes sub-pixel tricks:
+
+- Author FX at **2 px or wider** at the target buffer. A 1 px additive wisp
+ disappears or becomes a single palette dot; enlarge it or delete it.
+- Use a **palette-legal saturated colour** and a dark contour, not pure white.
+ White clips to the page and the snap has nothing to quantise.
+- Do not rely on a smooth gradient to carry an effect. Build it from 2 to 4
+ palette steps, a scrolling band, or a shape with a hard edge.
+- Test with `?dither=0` and at 1:1. If the effect only reads in a downscaled
+ preview, it is not in the render.
+
+### Contact Contexts
+
+"Touching the ground" is not one rule:
+
+- **Ground prop:** contact shadow plane 0.018 above the slab; lowest vertex on
+ the deck, not floating.
+- **Deck / gallery / table:** the shadow belongs on that surface at its Y, not on
+ the slab below. Parent the figure and shadow to the deck, or project onto the
+ deck plane; a gallery figure with a slab shadow reads as a ghost.
+- **Water:** the hull sits below the waterline; use a foam ring at the waterline
+ and a wake, not a contact shadow. A floating boat with a hard shadow on the
+ water reads as a toy on a table.
+- **Vertical / wall:** a ladder, hook or rope needs a contact mark at the rung,
+ grille or rail it bites, plus a small recoil; a hook in mid-air is a prop.
+
+## Combat Readability (towers, bosses, deaths)
+
+A diorama is judged on whether the **cause and the consequence are both
+visible at the locked camera**. Geometry that is correct in world space can
+still read as a bug on screen. Run these gates before calling a combat beat
+finished.
+
+- **Clear the threshold.** Keep at least 2 m of empty ground in front of a
+ portal mouth, gate, or spawn arch. No crates, barrels, boulders, bones, or
+ hanging vines in that pocket. Remove fireflies over the mouth, and never put
+ rising smoke there: a grey billboard above an arch reads as a rock flying out
+ of the entrance, even when it is soft and transparent.
+- **Give every tower a legible grammar.** Origin flare, a readable travel or
+ channel, and an impact that lands on the target. A beam needs contrast against
+ both the tower body and the page (there is no sky), plus motion along its
+ length; a plain white
+ cylinder over a white tower reads as a waterfall or a static icicle. Use a
+ scrolling band texture, a darker halo, and a target flash. If the line of
+ sight is blocked by the keep, a foreground tower, or a ruin, pick another
+ target instead of drawing through the wall.
+- **A beam that fires at a dead target is a bug.** Store the target id on every
+ beam event and hide the beam on the frame its target dies.
+- **A boss with a goal must act on the goal.** Stop it outside the threshold by
+ at least its body depth plus weapon reach, face the door, and make the weapon
+ visibly contact the door. Position alone is not enough: sync the contact pose
+ to the door-hit timestamp (a decaying pulse from the simulation), so the
+ club/ram/fist is low on the same frame the door flashes, shakes, and cracks.
+ If the weapon is off-screen, through the wall, or on the ground at the hit
+ frame, the beat is not finished.
+- **Do not let an attack hide the story.** A boss at the gate and a tower beam
+ arriving at the same spot fight for the same pixels. Let the tower lose line
+ of sight to the gate pocket, or dim/shorten the beam there; the door beat
+ wins. The player can see the beam elsewhere in the loop.
+- **Deaths need a species, not an explosion.** No generic sphere, boulder, or
+ rock burst on death. Use a body-specific collapse plus two or three
+ type-coloured shards or cloth/armour/goo/feather pieces, a dropped weapon
+ where the species carries one, a ground stain or splat, and a brief soul
+ flicker. Cannon and mortar impacts land in dust and smoke with a ring, never
+ in stone chunks. If a death reads as "grey puff", it is not done.
+- **A stone weapon is not a floating rock.** A club, maul, or ram needs a
+ visible haft connecting it to the hand, iron bands, studs, or spikes, and a
+ colour that separates it from the wall it hits. Check the impact crop: if the
+ head looks detached, add the haft/band contrast, not more debris.
+- **Prove the beat with time, not a still.** Shoot the impact frame and the
+ frame 0.2 s later. The first must show contact and the flash; the second must
+ show recoil or follow-through. If the club is hidden at impact and only
+ appears on the recoil, the pose is late.
+- **Sync effects by timestamp.** Gate hits, door cracks, beam impacts, and
+ death pulses must derive from the same simulated event time. Two independent
+ cycles will drift apart on a long loop even if they match on the frame you
+ happened to inspect.
+
+### Attack Audit
+
+Run one row per tower, at the timestamp it fires. A tower that never fires in
+the loop is scenery, not a defence.
+
+| Check | Pass condition |
+| --- | --- |
+| origin | muzzle, rail, crystal or hand is visible and offset from the body |
+| wind-up | at least 0.1 s of visible anticipation |
+| travel | projectile or beam is traceable across at least 4 frames |
+| impact | lands on the target with a species-specific effect |
+| recovery | weapon returns; crew resets; no snap to rest |
+| count | `shots > 0` in the sim stats for this tower |
+| no stale | no projectile or beam outlives its target |
+
+If a tower fails "origin", move the spawn point; adding more impact particles
+will not fix it. If it fails "travel", slow the projectile or widen the trail;
+a 1-frame hit is a hitscan, which is fine only for a beam.
+
+### Field Audit
+
+A **support, aura or ground field** has no projectile and must not be failed for
+that. Audit it on five field stages instead:
+
+| Check | Pass condition |
+| --- | --- |
+| source | emitter, valve, horn mouth or caster hand is visible |
+| area | radius/cone is readable on the deck; no floating ring |
+| ramp | effect grows over at least 0.15 s; not an instant decal |
+| affect | affected units visibly change (speed, colour, stagger, burn) |
+| decay | effect fades/expires on the loop, leaving residue |
+| count | `events > 0` for this field in the sim stats |
+
+A field that never expires is a lighting change, not an attack.
+
+### Death Grammar
+
+| Species | Body collapse | Debris | Dropped | Residue |
+| --- | --- | --- | --- | --- |
+| goblin | fold forward, knees first | cloth scraps, 2 bone chips | knife or spear | dark stain |
+| orc | drop to one knee, then side | 3 iron plates, 2 tusk chips | cleaver or sword | dust + blood |
+| slime | flatten, then pop | 6 goo blobs, 1 core | none | glossy splat |
+| flyer | spiral, wings fold | 5 feathers, 1 bone | none | feather on ground |
+| human / crew | knees, then hat/coat fold | 3 cloth scraps, 1 tool | hat, keys or hook | oil or blood stain |
+| boss | knee dip, torso fall, weapon drop | 6 armour plates, 2 horns | club | scorch + rubble |
+
+Every death also gets a 0.2 to 0.4 s additive soul flicker. It is the punctuation
+that says "this was a creature", not "this was a particle system".
+
+### Beam And Impact Artifacts
+
+- **A black band along a beam is a texture backing, not a shadow.** A canvas
+ filled with black and then painted with white stripes still carries black RGB
+ with alpha 1; under a render target it can survive as a dark segment. Clear the
+ canvas and paint pale stripes with transparent gaps. Never use a black
+ background for an additive beam texture.
+- **A beam that looks like a waterfall** is a white cylinder against a white
+ tower. Add a darker halo, a scrolling band texture, an origin flare and a
+ target flash. The eye needs motion along the length and contrast at both ends.
+- **A beam through a wall** is a line-of-sight bug. Sample the keep/foreground
+ silhouette and drop the target if the segment crosses it; do not shorten the
+ beam after it has already drawn through the wall.
+- **A beam on a corpse** is a stale target. Store `targetId` on the beam event
+ and hide the beam on the frame that id dies.
+- **Dark smoke over a bright beam** reads as a black bite. Smoke is normal-alpha
+ grey; if it crosses a beam, lighten it, move it out of the beam corridor, or
+ draw the beam after the smoke. Do not assume additive blending saves it.
+- **A projectile that looks like a floating rock** has no trail and no muzzle.
+ Spawn it at the weapon, add a tumble or trail, and remove it on impact.
+- **A muzzle flash with no recoil** reads as a sticker. Move the weapon back
+ 0.1 to 0.25 m and return it over 0.2 to 0.5 s.
+
+### Prop And Landmark Failures
+
+- **Two landmarks with one silhouette.** A skull tree behind a skull totem
+ becomes one antlered monster; a cart beside a crate becomes a pile. Remove or
+ move one. Project both to screen and check the union.
+- **A trophy that floats.** Mount it on a board, plaque or branch with a visible
+ rope, strap or nails. A skull in mid-air is a rock with eye sockets.
+- **Loose skulls at the base read as white pebbles.** At diorama scale, a 0.1 m
+ sphere with two dots is not a skull. Remove it or make it a clear bone pile
+ with a jaw and horns.
+- **A cart load made of pale spheres reads as a blob.** Use tied rectangular
+ bales, straw tufts, a pitchfork and a sack. The load must have a construction
+ logic, not just a colour.
+- **Rising smoke over a threshold reads as rocks flying out.** Remove it from
+ the pocket. Fire can glow without a smoke column.
+- **A prop at the slab edge with its wheel or shaft over the void** breaks the
+ cut-out. Move it in until the lowest contact and the full silhouette are on
+ the deck.
+
+## Build And Ship
+
+`templates/build.mjs` bundles `src/main.js` to `dist/app.js` with esbuild (IIFE),
+writes `index.html` and a standalone HTML with the bundle inlined, escapes
+`</script` in the payload, and passes the replacement as a **function**, not a
+string. `String.replace` expands `$&`, `$'`, `` $` `` and `$1` inside a string
+replacement; a minified bundle routinely contains those sequences, which
+silently injects the `<script src=...>` tag into the middle of the app and
+breaks the standalone file. Always test the standalone over `file://`, not just
+the served page. `--minify` for shipping; expect roughly 780 kB with
+three.js inside.
+
+Freeze and seek come free if everything is a function of `t`:
+
+```js
+const params = new URLSearchParams(location.search);
+const frozen = params.has('t') ? parseFloat(params.get('t')) : null;
+const startAt = params.has('from') ? parseFloat(params.get('from')) : 0;
+window.__diorama = { THREE, scene, camera, renderer, post, director, cast,
+ robbers, cops, mats, TL, CLIP, freeze(t){ frozen = t; draw(t); }, play(){}, view(){} };
+```
+
+`?t=12.4` is the whole QA surface: every screenshot and every diagnosis is a
+frozen frame, so a screenshot never depends on timing luck.
+
+## Surface, Motion And Event FX
+
+These are the failures that survive a good first render: a finished-looking set
+with one raw seam, a clean loop with a vehicle that teleports out, or an effect
+that is technically present but reads as a grey rectangle. Audit them as a
+system, on every subject.
+
+- **Finish the edge, not just the field.** A heightfield, bank, road, water or
+ terrain piece that meets the slab must feather to the slab height over the last
+ 0.5–1.0 m. Never end a terrain in a lip, a vertical wall or a portal-shaped
+ hole. Prove it with a 1:1 crop of each visible slab edge at two nearby times,
+ not a wide shot where the seam is 2 px.
+- **A mover has not exited until its bounds clear the slab.** Keep the whole
+ group — body, lights, shadow, cargo — visible through the complete run-out.
+ Hide only after the world-space box is wholly outside the slab plus a 0.2–0.5 m
+ margin. No early `visible = false`, no parking at the gate, no portal. If the
+ scene uses a clip plane, the mover may be cut by it, but the cut body must
+ continue moving out; a cut that freezes is the same bug.
+- **Never fade a solid hero with material opacity.** Per-material opacity on a
+ multi-mesh vehicle or figure produces ghosting and sort artefacts: some parts
+ turn transparent before others, and the result is a see-through prop, not a
+ fade. Cut, clip, or hide only when the bounds have cleared. Transparent glass
+ and FX are exempt; whole-object fades are not.
+- **Effects are events, not weather.** Exhaust, steam, dust bursts and impact
+ puffs belong to explicit windows: start, rev, launch, hit, landing, open. If
+ the brief does not ask for idle smoke, do not emit while the source is parked.
+ A continuous plume erases the timing of the event it was meant to sell.
+ One-shot exhaust is roughly **0.7–1.2 s**, with a short fade tail under 1 s.
+ Check the event frame and event + 1.5 s: present then absent.
+- **Anchor an emitter at the physical nozzle.** For a vehicle, the source is the
+ exhaust-tip object (`(±0.66, 3.74, -0.74) * scale` on the truck recipe), not
+ the engine centre, cab roof or a point chosen by eye. Put the tip
+ in `userData` during construction and use that same object for the smoke. A
+ plume that starts above or behind the stack reads as a floating cloud. If a
+ canopy hides the tip, offset the birth point downstream in the open direction,
+ not the source anchor; the audit's `maxOffset` allows that.
+- **A halo is a sprite, not a quad.** A flat, untextured, low-opacity additive
+ `PlaneGeometry` is a light-grey rectangle at the palette snap, especially over
+ a dark board or wall. Use `haloPlane`/`softDiscTexture` from `detail.js`, a real
+ emissive lens, or no halo. This is the single most common "what is that
+ rectangle?" report.
+- **Event FX must not cover the thing you are pointing at.** A smoke cloud that
+ grows over a sign, jumbotron, face or gate has become the subject. Cap size,
+ cap life, and move the source to the open side of the prop; verify at the
+ event frame, not only at 60% of the burst.
+- **Every correction gets a regression check.** For these failures the checks
+ are: edge crop pair, mover bounds log, whole-group fade scan, emitter
+ active/quiet windows, source-to-puff distance, flat-glow scan, and margin
+ scan. `templates/qa/audit.mjs` runs the mechanical ones; the 1:1 crops remain
+ human evidence.
+
+## Verification
+
+- **Build first, then shoot, then prove the edit landed.** A failed bundle leaves
+ the previous `dist/` in place, and a refused or blocked edit leaves the source
+ untouched, so in both cases every screenshot shows the old app and the fix
+ looks like it did not land. Read the build's own output line, grep for a
+ sentinel string from the change, and only then judge the frame.
+- **Judge orientation from the transform, not the pixels.** At diorama scale a
+ back and a front read the same: a 4x-downscaled strip once made a
+ correctly-facing figure look like he was climbing in backwards, and the
+ "spin" it appeared to do was an artefact of re-reading the crop. Print
+ `group.rotation.y` and compare it with `atan2(dx, dz)` of the expected facing
+ vector before re-shooting a facing fix.
+- Screenshot 1280x800, 1388x950 (iPad landscape) and 390x844 (phone). Zero page
+ errors in all three, and the framing holds at each aspect.
+- Two shots 1.5 s apart differ (the loop is alive) and the camera position is
+ identical (the angle is locked).
+- A 1:1 crop shows square pixels, a dark contour, no speckle on flat deck.
+- **Pairwise distance sweep** across every multi-actor beat: freeze in 0.3 s
+ steps, log x/z and the pairs under 0.6 m. Held for two samples means jammed.
+- **Position logs across every one-shot boundary**: consecutive samples differ by
+ centimetres, never by a body length.
+- Isolated portraits per figure: no gaps, knees bend backward, nothing floats.
+- **Queue gate strip.** Sample a walking customer every 0.15 s across two
+ strides; log root speed, `state.moving`, hip/shoulder angles and slot. No
+ standing gesture may be non-zero while speed is non-zero; the leg angles must
+ alternate; serve must be at least 0.25 s after arrival.
+- **Carry contact log.** During every carry beat, print both wrist positions,
+ the prop's world bounds and the distance from each palm to the prop. The palms
+ stay within 0.08 m until release; the prop does not move more than 0.05 m in one
+ frame except during the authored handoff blend.
+- **Mount strip.** Nine side frames from load to seat; log wrists, ankles, prop
+ base and seat. No boot passes through the bars/seat/body, both soles reach the
+ boards, and the rider root follows the seat after departure.
+- **Scale check.** The 30%-smaller request is a camera move; assert
+ `actualDistance / fitDistance ≈ subjectScale`, the projected slab width fell
+ by the same factor, `post.size ≈ CSS size × renderScale` (capped), the
+ slab/world clip/shadow camera and CSS frame are unchanged, and the standalone
+ still frames on the page.
+- **Night 1:1.** Three distinct dark values, a visible practical with a pool, no
+ clipped white, no pure black. For an interior, the glass must not tint the
+ room; for a passing bus, the occlusion frame at the hero timestamp must still
+ show the hero.
+- **Quadruped strip.** Profile, three-quarter, sit and jump. Ears read as ears,
+ pupils are vertical, rear hocks bend backward, the tail curves; a rabbit or a
+ dog silhouette fails.
+- **Exit strip.** For a social actor: contact, turn, walk out, prop in hand. No
+ debris or stain unless the scene is a death; the residue is the changed place.
+- When a prop never appears, print its world position rather than trusting
+ `visible`. `getWorldPosition` on a merge-eaten object returns local coordinates
+ because the original was unparented; that is the signature of the merge pass.
+
+### Detail And Animation Audit
+
+Run this after the build and before shipping. It is deliberately visual; a
+number cannot prove that a club is touching a door.
+
+1. **Grey silhouette.** Hide the palette/post (or desaturate) and shoot the hero
+ frame at 1:1. Every tower, creature, landmark and prop must be nameable from
+ its outline. If two objects merge, restage.
+2. **Hero crops.** One 1:1 crop per tower, one per species, one per landmark, one
+ per large prop. Look for: floating parts, untextured primitives, duplicate
+ silhouettes, sub-pixel speckle, missing contact shadows.
+3. **Threshold crop.** The gate/portal/spawn mouth is empty for 2 m. No smoke,
+ crates, rocks, bones or vines. The boss's weapon is visible against the door.
+4. **Attack strip.** For each weapon tower: acquire, release, travel, impact,
+ recovery. The muzzle/rail/crystal must be visible at release. For a support,
+ aura or field: source, area, ramp, affected-target change, decay. A defence
+ with zero events is a bug in the sim or the data, not "atmosphere".
+5. **Death strip.** For each species: impact, mid-collapse, residue. Debris must
+ be species-specific. A grey puff, sphere burst or rock shower fails.
+6. **Boss contact.** Contact frame plus 0.2 s later. Contact must show the weapon
+ on the goal, the goal's response (flash/crack, spray/gauge drop, sag/snap) and
+ the first consequence; +0.2 s must show recoil or follow-through. The haft
+ and bands must be visible at contact.
+7. **Beam/field on/off.** Full channel, then the frame after the target dies or
+ the field expires. No black band, no beam through the keep, no beam on the
+ corpse, no field left glowing after its timer.
+8. **Crowd strip.** 6 frames at 0.1 s across a group. Actors must not share a
+ phase, stack at one waypoint, or walk through each other.
+9. **Numbers.** Print `events`, `shots` per tower, `deaths` per species, `maxD`
+ per species, loop length and console errors. A species with zero deaths did
+ not finish its route; a tower with zero shots never joined the fight.
+10. **Rectangle and seam test.** Look at every large translucent plane and every
+ slab edge in a 1:1 crop. A hard-edged grey rectangle near a sign is a flat
+ quad halo; a step/lip/black slot at the surface is an unfinished edge. Fix
+ both before the standalone pass.
+11. **Standalone.** Open the built HTML over `file://` once. `ready: true`, no
+ console errors, and a frame that matches the served page.
+
+Keep the proof pack: `shots/hero.png`, `shots/tower-*.png`, `shots/death-*.png`,
+`shots/boss-contact.png`, `shots/boss-recoil.png`, `shots/beam-off.png`. A future
+chat can compare its own pack to these crops.
+
+### New-Chat Handoff
+
+When a different diorama is requested in a fresh chat, the skill should produce
+the same level without re-deriving it:
+
+1. Read this file and `templates/DESIGN.md`.
+2. Fill the design sheet before coding: premise, camera side, cast, systems,
+ five beats, detail budget.
+3. Block out in grey and shoot the five beats at 1:1.
+4. Build the pipeline in the order in this file: palette, camera, light, post,
+ props, cast, detail pass, animation/systems, effects, QA.
+5. Apply the detail bar per hero object and the animation bar per actor.
+6. Run the detail and animation audit plus `qa/audit.mjs`, not just "does it
+ load".
+7. Ship the standalone and leave `DESIGN.md`, `README.md` and the code agreeing.
+
+If the new subject has no combat, replace tower grammar with **Machine Grammar**
+(loom, press, crane, oven, pump) and creature grammar with **character grammar**
+(customer, worker, animal, vehicle). Audit outputs as fields when there is no
+projectile. The five layers and the audit still apply: idle, locomotion, action,
+reaction, residue.
+
+### Comment Triage
+
+When the user marks a region, project the object instead of guessing pixels:
+`obj.getWorldPosition(v); v.project(camera); px = (v.x*0.5+0.5)*w`.
+If it is not obvious, raycast that pixel and read the first few hits' materials and
+heights: the first hit is the surface they see, the second is what is under it.
+Then fix the marked region and nothing else, and prove it with a zoomed crop at the
+same timestamp.
+
+## Pitfalls
+
+- **A building's roof is a large visible surface at 33 degrees.** Look down onto
+ it and dress it, or keep buildings lower than they are deep.
+- **A merge pass eats anything whose visibility is animated.** Batching
+ same-material siblings keeps one `visible` flag, so hidden cargo comes back as a
+ single invisible mesh that never appears, and the survivor's `getWorldPosition`
+ reports local coordinates. Tag runtime-toggled meshes `userData.noMerge = true`.
+- **Canvas size is presentation, resolution is the buffer.** Shrinking the display
+ keeps the buffer; moving the buffer changes the art. `renderScale` 1.2–1.5×
+ on a small subject sharpens it without making it larger; measure fps and inspect
+ a 1:1 crop before keeping it.
+- **Raising the buffer exposes geometry that hid at the old grid.** Re-run the
+ portraits after any resolution change: floating hats, detached stripes and
+ oversized noses show up there first.
+- **A prop swallows a figure placed inside it.** Sit the figure on the near rim
+ with the limbs outside; more detail inside will not read anyway.
+- **Lying bodies convert joint Z rotations into vertical lifts.** Flatten
+ shoulders to about ±0.15 and keep elbows near zero.
+- **A springboard must move and the rider must follow it**: pivot at the root,
+ integrate a spring on `rotation.z`, and put the feet on
+ `pivotY + h*cos(flex) - arm*sin(flex)`.
+- **A standing gesture blended into a walk straightens the legs and slides.**
+ Gate `PAY`, `ORDER` and `POINT` on `!state.moving`; a still at one timestamp
+ will not catch it, a 0.15 s strip will.
+- **A carried prop parented to the root leaves the hands at the first turn.**
+ Keep it in world space, solve from the wrists each frame, and log palm-to-prop
+ distance.
+- **A leg swung with hip X goes through the handlebars.** A side mount needs hip
+ Z abduction, knee flex and a small root arc; hip X is for walking and sitting.
+- **Shrinking the geometry or the canvas frame to satisfy "smaller"** shrinks
+ the world clip, contact shadows and slab, or changes the 1:1 crop. Move the
+ camera with `subjectScale` instead; the frame and backing buffer stay fixed.
+- **A DOM caption on the white paper** is outside the diorama. Model the sign or
+ use the browser title.
+- **A hat hovering above the skull** is a brim at 0.225 instead of 0.192.
+- **Oversized nose**: 0.044 at this camera is a snout, 0.038 is a nose.
+- **Two figures at 0.8 m read as one silhouette.** Judge spacing from numbers.
+- **A shared window synchronises a group.** Stagger every actor's window.
+- **A door left open beside idle actors reads as stuck in the doorway.**
+- **A pose switch is not a transition.** Cutting from a run into a transfer pops
+ the whole body: blend out over the last 10 to 15 percent and hold a beat.
+- **A cannon with a brass end cap is a baton.** Hollow collars, a recessed dark
+ bore, a back disc and a lip ring; the hole must survive the 1:1 crop.
+- **Fixed deck props parented to a yaw group sweep with the gun.** A powder keg,
+ shot pile, rammer or crew member under the turret turns with every aim. Put
+ them on a static wall locker outside the barrel arc, not just on the root at
+ deck height; test world positions and bounding-box overlap at both yaw extremes.
+
+## Project Layout
+
+```
+DESIGN.md filled design sheet: premise, cast, systems, beats, budget
+src/
+ config.js scene constants + clamp/lerp/smooth/pulse/hash
+ main.js renderer, scene, clip planes, resize, rAF, ?t= freeze
+ core/
+ palette.js N entries + named C map
+ post.js PixelPost: gamma, grade, ink, dither, snap, rim
+ materials.js every material, palette-validated
+ geometry.js roundedBox, addBox, lathe helpers
+ merge.js mergeSiblingMeshes: one draw per material per group
+ scene/
+ camera.js lighting.js street.js bank.js props.js
+ car.js shell, doors, boot, seats, cargo
+ peopleModel.js base rig (swimwear/aquatic)
+ peopleModel-street.js clothed rig: heads, layers, hats, hands
+ people.js the cast: poses, walk/run, tracks, buildCast
+ stage.js the beat sheet + every actor as a function of t
+ effects.js contact shadows, smoke, spill, siren
+build.mjs esbuild bundle, index.html, standalone HTML
+qa/
+ shoot.mjs viewports + console errors + named timestamps
+ audit.mjs scene lint: halos, fades, camera/render scale, exits, FX
+ portrait.mjs isolated figure/framing shots through a debug camera
+ strip.mjs N-frame motion strips (fails on a frozen loop)
+ probe.py colour runs across an edge
+ sweep.mjs pairwise distances + jam/teleport verdict
+ tile.py tile a motion strip
+ README.md audit contract, commands, failure table
+```
+
+Wire order in `main.js`: renderer → scene → camera → post → clip planes → lights →
+materials → street/bank/props → cars → cast → effects → merge → stage. Merge once,
+before the stage is created, so the timeline binds to the surviving meshes.
+
+A defence or arena subject replaces `street/bank/car` with `path/towers/keep`:
+
+```
+src/scene/
+ path.js route samples, arc length, at(d), ground height
+ towers.js foundations, machines, crew, recoil pivots
+ monsters.js rig, poses, walk/fly/hop, boss club
+ keep.js gate, walls, door leaves, cracks, goal response
+ roster.js species stats and wave table
+ battle.js deterministic 40 Hz sim, shots, impacts, deaths, gate hits
+ props.js camp, skull tree, cart, torches, trees, portal dressing
+ effects.js beams, projectiles, dust, smoke, shards, rings, souls
+```
+
+The same wire order applies: build the set, then the cast, then effects, then
+merge once before the battle timeline reads the survivors.
+
+When the beat sheet moves into its own module, delete the superseded director and
+update the README's beat table in the same pass. An unreferenced six-hundred-line
+timeline and a table that disagrees with the code are exactly what the next reader
+trusts.
+
+`templates/` carries runnable copies, not excerpts. Foundations: `post.js`,
+`palette.js`, `camera.js`, `lighting.js`, `geometry.js`, `build.mjs`. Cast and
+motion: `peopleModel.js`, `peopleModel-street.js`, `poses.js` (the pose library,
+including the four climb poses and the walk/run cycles), `transfer.js` (seating,
+the climb, stand spots, facing), `track.js` (arc-length paths with lane offsets
+and smoothed ground height), `stage.js` (beat table, `keysAt`, `place`, the
+actor loop, a car state machine). Props and systems: `detail.js` for prop
+assemblies (including `haloPlane`/`softDiscTexture` for soft light cards),
+`combat.js` for deterministic timing and death grammar. Effects:
+`water.js`, `wake.js`, `splash.js`. Sheets: `DESIGN.md`.
+
+`stage.js` ships as a **skeleton with one worked actor chain**: a figure leaves a
+car, walks a route, comes back and climbs in. It is deliberately not a story. The
+structure it does ship is the part that is tedious and easy to get wrong: beats
+ordered monotonically in `t`, one branch per actor per frame, the contact shadow
+following `place()`, and the door as a timeline rather than a state. Replace the
+cast, the routes and the beat table; keep the skeleton.
+
+`car.js` is still not in the kit. A vehicle is the most subject-specific prop in
+the scene, and the recipe (dimensions, door pivots, windscreen versus seat, boot
+well, livery split) is written above at the length it needs. Everything else you
+need is a file.
+
+`qa/` is the harness: `shoot.mjs` (viewports, named timestamps, console errors,
+the buffer/camera/draw-call line), `audit.mjs` (flat-glow, whole-object fade,
+camera/render-scale, early-hide, teleport, idle/orphan emitter and margin checks
+against the optional scene contract), `portrait.mjs` (isolated figures through the debug
+camera), `strip.mjs` plus `tile.py` (motion strips, which fail on a frozen
+loop), `probe.py` (colour runs across an edge, the tool for "why is there a band
+here"), and `sweep.mjs` (pairwise distances across a beat, with a two-sample jam
+verdict and a teleport limit). They need `playwright-core` and a page that
+exposes `window.__diorama` with `freeze(t)`; `verify/water/` is a worked example
+that exercises the three water modules and shows what the acceptance output
+looks like.
+
+## Skill Maintenance
+
+The skill is part of the deliverable. After every shipped diorama, do a ten-minute
+postmortem and write down what the user actually reported, not what you intended.
+
+1. **Add at most three rules per routine project.** A skill that grows by fifty
+ small rules becomes unreadable and the next reader skips it; a deliberate
+ major overhaul is a versioned release, not a stealth append.
+2. **Every rule needs evidence and a test.** "Clear the threshold" came from a
+ screenshot of smoke above a portal; the test is a 1:1 crop of the pocket.
+ "The club must touch the door" came from a still at 41.075; the test is the
+ contact frame plus 0.2 s.
+3. **Promote repeated fixes.** If the same bug appears twice, it is a missing
+ rule, not a one-off.
+4. **Retire stale rules.** If a template or pipeline change makes a rule
+ obsolete, remove it in the same edit.
+5. **Bump the version.** Patch for wording, minor for a new rule/section, major
+ for a new contract or a reorganisation. Keep `SKILL.md.bak-v<old>` beside it.
+6. **Update the templates and the project layout in the same pass.** A rule that
+ points at a file that does not exist is worse than no rule.
+7. **Test the skill on a new subject.** After a major edit, give a fresh model
+ only this file and ask it to fill `DESIGN.md` for a different diorama. Fix
+ every contradiction it finds; that is cheaper than discovering them after a
+ build.
+
+A useful postmortem entry has this shape:
+
+```
+BUG: the club read as a rock at the gate
+CAUSE: end-on pose; haft hidden; no bands
+RULE: turn the boss 0.35 rad to the goal; build haft + bands + studs
+TEST: contact crop at the gate-hit timestamp; haft visible, head on door
+```
+
+Two entries from the truck-diorama correction pass:
+
+```
+BUG: a light-grey rectangle floated beside the jumbotron
+CAUSE: a flat, untextured, additive PlaneGeometry used as a glow
+RULE: halos need a radial-alpha map, an emissive lens, or deletion
+TEST: qa/audit.mjs FLAT_GLOW plus a 1:1 crop of the board at the hero time
+```
+
+```
+BUG: both trucks vanished at the gate before the run-out finished
+CAUSE: visible=false keyed to a beat, not to world bounds clearing the slab
+RULE: hide only after the box is outside slab + 0.2–0.5 m; never fade solids
+TEST: qa/audit.mjs EARLY_HIDE over the full loop; exit strip at 0.2 s spacing
+```
+
+```
+BUG: the yellow truck smoked while parked, from a cloud above the cab
+CAUSE: continuous idle haze plus a guessed emitter point inside the body
+RULE: one start/rev event window, puffs born at the real stack tip; offset the
+ birth point downstream if a canopy hides it, never the source anchor
+TEST: qa/audit.mjs IDLE_EMITTER / ORPHAN_EMITTER; event frame present,
+ event + 1.5 s absent
+```
+
+## Changelog
+
+- **3.6.0** — Renamed to Diorama throughout: the playbook, templates and QA docs
+ now call the artifact a diorama. No code behaviour changed.
+- **3.5.1** — Camera-scale rule made explicit: `subjectScale` is a post-fit
+ multiplier (`0.70` = 30% smaller linearly), while `fillX`/`fillY` stay a fit
+ margin. The camera template now exposes `fitDistance` and `subjectScale`;
+ `qa/audit.mjs` now proves `distance ≈ fitDistance / subjectScale` when those
+ two fields are exposed, and `post.size ≈ CSS × renderScale` when the post
+ exposes it. Added the
+ Dust Kings calibration (fit 67.93 → actual 97.05, projected slab 872 → 611 px)
+ and a rule against shrinking the geometry or canvas frame to create margin.
+ `PixelPost` gains a `renderScale` argument; Dust Kings renders at 1.25× (buffer
+ 1640 × 950 on a 1312 × 760 CSS canvas) so the smaller diorama keeps its edge
+ detail without changing page size. The resolution section now separates buffer
+ from layout and warns about the frame-rate cost.
+- **3.5.0** — Surface/Motion/Event-FX correction release from a truck-diorama
+ postmortem: finish heightfield/slab edges flush (no lip or portal), keep every
+ exiting mover visible until its world bounds clear the slab, never fade a solid
+ hero with material opacity, gate exhaust/steam/dust by authored event windows
+ with the emitter at the physical nozzle, and replace flat untextured halo
+ quads with radial-alpha sprites. New `qa/audit.mjs` checks flat glows,
+ whole-group fades, early hides, teleports, idle/orphan emitters and paper-margin
+ leaks; `shoot`, `portrait`, `sweep` and `strip` now fail with a nonzero exit
+ code; QA README documents the optional audit contract. New DESIGN audit sheet;
+ `detail.js` gains `haloPlane`/`softDiscTexture` so a soft light card is the
+ default.
+- **3.4.0** — The fragile code is now shipped, not described: `poses.js`,
+ `transfer.js` (climb, stand spots, facing), `track.js` and a `stage.js`
+ skeleton with a worked actor chain; `qa/` as runnable scripts (shoot, portrait,
+ strip, probe, sweep) instead of a checklist; Numbers split into invariants and
+ calibrated values. Water, wake and splash re-verified in `verify/water/`, which
+ found two real defects: the splash used `Math.random` (now seeded) and neither
+ effect could be frozen (both now expose `reset()`; the harness re-simulates from
+ zero and a two-frame diff fell from 334 to 18 pixels). `build.mjs` writes a
+ favicon stub so the 404 stops polluting the console gate.
+- **3.3.0** — Social/life-scene release from the Night Market build: clothed-cast
+ craft (skull/jaw head, hairline, layered garments, hands), carry/handoff and
+ crate-loading rules, scooter/cargo-bike anatomy, two-wheeler mount with hip-Z
+ abduction, service/queue state machine with `moving` gates, Night Market worked
+ example and fix table, 2x backing/scale-by-camera guidance, empty-paper rule,
+ social verification logs, night/practical/headlight guidance, cutaway and
+ glazing rules, bus/van anatomy, cat/dog quadruped rig and gait, generalised
+ `DESIGN.md` with Life/Service and Contact/Choreography sheets, new
+ `peopleModel-street.js` template, scene fast path, and a laundromat/workshop
+ router row.
+- **3.2.3** — Hollow-object rule: cannon bores, pipe mouths, chimney flues, lamp
+ chimneys and tunnels need open collars, a recessed dark bore, a back disc and
+ a lip ring. Added 1:1 bore audit and the brass-end-cap pitfall; the Bombard
+ cannon now has an open muzzle instead of a cap.
+- **3.2.2** — Fixed cannon ammo station rebuilt as a wall-mounted locker below
+ the deck: shelf, brackets, powder chest, shot tray and hung rammer, outside
+ both yaw sweep and barrel arc. Added bounding-box overlap check to the pivot
+ audit and recorded the wall-locker pattern.
+- **3.2.1** — Rotating-assembly parentage rule: only the gun may live under yaw;
+ fixed deck stores go on a static group. Added pivot-parentage strip and
+ acceptance check; cannon keg, shot and rammer moved off the yaw group.
+- **3.2.0** — One-prompt commission mode: default commission table, assumption
+ line, ten-scene router, universal four-question generator, bakery worked
+ example, autonomous eight-pass build, cut-count-not-detail rule and
+ one-prompt acceptance; reading order trimmed to the sections needed.
+- **3.1.0** — Canonical numbers/camera/light/post/palette contract; field and
+ machine grammar; goal-response vocabulary; FX edge, snap and contact-context
+ rules; crew/defender rule; human death grammar; climb and rotating-emitter
+ rules; expanded `DESIGN.md`; new `detail.js` rope, trophy-board and
+ contact-shadow helpers.
+- **3.0.0** — Detail Bar, Animation Bar, new-subject intake, reference density,
+ detail recipes, system/combat animation, attack/death audits, beam/artifact
+ triage, detail-and-animation QA, `templates/DESIGN.md`, `templates/detail.js`,
+ `templates/combat.js`.
+- **2.1.0** — Combat Readability section; threshold clearing, tower grammar,
+ boss goal contact, death species, standalone `String.replace` guard.
+- **2.0.0** — Palette/post contract, camera solve, cast rig, vehicle/seat
+ transfers, clipping, verification.
diff --git a/templates/DESIGN.md b/templates/DESIGN.md
new file mode 100644
index 0000000..53ae96b
--- /dev/null
+++ b/templates/DESIGN.md
@@ -0,0 +1,210 @@
+# <TITLE> — design sheet
+
+> Fill this before modelling. Keep it in sync with `README.md` and the code.
+> A new subject with no verb is a shelf model; give it a conflict.
+> Delete rows that do not apply, but replace them with the equivalent
+> (a machine's goal, a field's area, an ambient loop's period).
+
+## Premise
+
+`[place]` + `[a repeated verb/ritual]` + `[who or what interrupts it]` + `[payoff]`.
+
+One sentence:
+
+- Archetype (router row):
+- Assumption line (scale, loop, systems, cast):
+
+## Camera Side
+
+- Locked angle: azimuth 45, elevation 33, fov 20.5; fillX/fillY 0.84–0.94
+ (fit margin only).
+- Subject scale: 1.0; 0.70 = 30% smaller linearly, more paper (camera only;
+ frame, slab, clip and shadows unchanged):
+- Exterior or interior cutaway:
+- Street lane (in front +Z / behind -Z; passing vehicle timing):
+- Night palette mix (moon/key / practical / pool):
+- Render buffer: 1× CSS default; 1.2–1.5× renderScale for a small subject;
+ 2× only for face close-ups; maxDim / CSS image-rendering:
+- Slab size / deck height:
+- +Z face / hero face (exterior); for an interior cutaway, camera-side wall
+ omitted and street behind at -Z:
+- Threshold / entrance (keep 2 m clear):
+- Tall landmark (back, offset in screen x; top height):
+- Foreground prop (near corner):
+- Mid-ground prop (leads the eye):
+- What must never be occluded:
+- Grey blockout frame (time):
+
+## Cast Sheet
+
+Three to eight rows; the default is four to six including any disruption. Every
+row needs an exit (or death) and a signature prop.
+
+| Role | Silhouette feature | Locomotion | Action | Reaction | Exit / death | Signature prop |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+
+## Life / Service Sheet
+
+Fill this for a market, hatch, ticket window, bakery, hotel desk or any social
+scene. A combat play can delete it.
+
+- Service point (counter / hatch / window):
+- Queue slots (positions, spacing, heading):
+- Staff positions (cook / cashier / runner):
+- Arrival order and serve order:
+- Machine slots (washer/dryer/table), cycle end and release beat:
+- When the queue is full / empty:
+- Late customer or disruption:
+
+| Role | Entry | Slot | Order | Pay | Receive | Exit |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+
+## System Sheet
+
+- Loop length / DT:
+- Three or four systems (defence / machine / service station / loop; name,
+ origin, output, contact, events):
+- Crew / staff (who operates, exit, machine behaviour when gone):
+- Three or four visitor / enemy / animal roles:
+- One goal or disruption, optional for a life scene (what place does it act on?
+ contact point + response):
+- Economy / score / progression (optional for a life scene):
+- What changes between first and last beat:
+
+### Shot / Event Count
+
+| System | Shots / events | First at | Last at | Proof frame |
+| --- | --- | --- | --- | --- |
+| | | | | |
+| | | | | |
+| | | | | |
+
+## Beat Sheet
+
+| Time | Beat | Camera proof |
+| --- | --- | --- |
+| 0.0 | establish | |
+| | first system output | |
+| | first consequence | |
+| | machine / field / service output | |
+| | disruption arrives | |
+| | goal / service contact | |
+| | finale / residue | |
+| | relight / recovery | |
+| | loop seam | |
+
+A social play may collapse this to five rows: establish, first ritual, disruption,
+handoff, residue. A combat play uses all nine.
+
+## Hero Objects
+
+Name every object that gets the Detail Bar. Type is tower / machine / service
+station / vehicle / creature / prop / landmark. "Parts" is the visible mesh count target.
+
+| Name | Type | Parts | Construction layers | Story detail | Contact |
+| --- | --- | --- | --- | --- | --- |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+
+## Contact / Choreography Sheet
+
+Every carry, handoff, load, mount and seat needs a contact timestamp.
+
+| Beat | Hands on | Prop / seat anchor | Start | Contact | Release | Proof |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+
+## Ambient Loops
+
+| Loop | Period | Motion | Phase offset | What it touches |
+| --- | --- | --- | --- | --- |
+| | | | | |
+| | | | | |
+| | | | | |
+
+## Surface / Motion / FX Audit
+
+- Slab edges finished (right / lower / all visible): heightfield or road
+ feathers to slab over:
+- Exit rule for every mover: visible until world bounds clear slab + margin:
+- Event FX windows (start / rev / launch / hit / landing), source object, tail:
+- Idle effects that are deliberately allowed (otherwise "none"):
+- Large translucent planes and why each is not a flat halo:
+- Whole-object fades: none / exempted with reason:
+- `qa/audit.mjs` contract exposed (`slab`, `movers`, `emitters`):
+- Edge crop pair, burst frame, burst + 1.5 s, margin scan:
+
+## Detail Budget
+
+| Element | Count | Parts each | Story detail |
+| --- | --- | --- | --- |
+| Towers / machines / service stations | | 25–45 | |
+| Vehicles | | 20–45 | |
+| Species / people | | 12–20 (hero 40–60) | |
+| Props | | 8–15 | |
+| Landmark | | 30–60 | |
+| Deaths / exits | | 5–8 pieces + residue, or exit-only with no debris | |
+| Ambient loops | | 2+ | |
+| Triangles / draw calls | | | |
+
+## Palette
+
+- Length (must equal `uPalette[N]` and the JS array):
+- Base entries:
+- Accent entries:
+- Forbidden: pure black, gradients, unlisted colours.
+
+## QA Frames
+
+| Frame | Time | What it proves |
+| --- | --- | --- |
+| Grey blockout | | staging before palette |
+| Hero | | staging + palette |
+| First system | | origin / travel / contact |
+| Queue approach | | slots, feet, serve order |
+| Carry / load | | palms on prop, over-rim, release |
+| Mount / seat | | boot, leg clearance, hands on grips |
+| Night / glass | | darks, practical, no tint, no occlusion |
+| Quadruped | | ears, pupils, hocks, tail |
+| Exit (social) | | turn, walk, prop, no debris |
+| Machine / field / service | | area, ramp, output |
+| Surface edge | | no lip, gap or portal; flush at 1:1 |
+| Event FX start | | burst at the source, not idle haze |
+| Event FX tail | | plume gone within the authored tail |
+| Mover clear | | whole bounds outside slab before hide |
+| Exit / death | | species or role grammar |
+| Goal contact | | contact + response |
+| Follow-through | | recoil / release |
+| Beam / field off | | no stale effect |
+| Threshold | | clear pocket |
+| Relight / aftermath | | residue and recovery |
+| Standalone | | `file://`, no errors |
+
+## Risks
+
+- What is most likely to read as a blob at 1:1?
+- Which object has the weakest silhouette?
+- Which beat has the least visible cause?
+- Which FX crosses the slab edge, and does it fade or cut?
+- Does any standing gesture overlap a walking root? (queue slide)
+- Are the palms on the carried prop at the contact frame?
+- Does a boot pass through the bars, seat or body during the mount?
+- At night, are there three dark values and a visible practical?
+- Does a passing vehicle cover the hero at the contact frame?
diff --git a/templates/build.mjs b/templates/build.mjs
new file mode 100644
index 0000000..e4bb9df
--- /dev/null
+++ b/templates/build.mjs
@@ -0,0 +1,94 @@
+import { build } from 'esbuild';
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+
+const minify = process.argv.includes('--minify');
+
+await mkdir('dist', { recursive: true });
+
+await build({
+ entryPoints: ['src/main.js'],
+ bundle: true,
+ format: 'iife',
+ target: ['es2020'],
+ outfile: 'dist/app.js',
+ minify,
+ sourcemap: minify ? false : 'inline',
+ legalComments: 'none',
+ logLevel: 'info',
+});
+
+const js = await readFile('dist/app.js', 'utf8');
+const safeJs = js.replace(/<\/script/gi, '<\\/script');
+
+const css = `
+ :root { color-scheme: light; }
+ * { box-sizing: border-box; }
+ html, body {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+ overflow: hidden;
+ background: #ffffff;
+ }
+ body { -webkit-tap-highlight-color: transparent; }
+ #frame {
+ position: fixed;
+ left: 50%;
+ top: 50%;
+ width: 64vw;
+ height: 64vh;
+ transform: translate(-50%, -50%);
+ background: #ffffff;
+ }
+ @media (max-width: 620px) {
+ #frame { width: 94vw; height: 94vh; }
+ }
+ #stage {
+ display: block;
+ width: 100%;
+ height: 100%;
+ background: #ffffff;
+ image-rendering: pixelated;
+ image-rendering: crisp-edges;
+ outline: none;
+ }
+ #fallback {
+ position: fixed;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ background: #ffffff;
+ color: #333a3d;
+ font: 14px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
+ letter-spacing: 0.02em;
+ text-align: center;
+ padding: 2rem;
+ }
+ #fallback[hidden] { display: none; }
+`;
+
+function page(scriptTag) {
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<link rel="icon" href="data:," />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<meta name="theme-color" content="#ffffff" />
+<title>Swimming Pool — a small diorama</title>
+<style>${css}</style>
+</head>
+<body>
+<div id="frame"><canvas id="stage" aria-label="A real-time rendered miniature swimming pool diorama" tabindex="-1"></canvas></div>
+<div id="fallback" hidden>This diorama needs a browser with WebGL2 enabled.</div>
+${scriptTag}
+</body>
+</html>
+`;
+}
+
+await writeFile('index.html', page('<script src="./dist/app.js"></script>'));
+await writeFile('pool-diorama.html', page(`<script>${safeJs}</script>`));
+
+console.log(`built dist/app.js (${(js.length / 1024).toFixed(0)} kB), index.html, pool-diorama.html`);
diff --git a/templates/camera.js b/templates/camera.js
new file mode 100644
index 0000000..33f77dd
--- /dev/null
+++ b/templates/camera.js
@@ -0,0 +1,95 @@
+import * as THREE from 'three';
+
+/**
+ * Locked three-quarter camera. Distance is solved against a set of fit points
+ * (slab corners plus the tops of tall props) so the play keeps its white
+ * margin at every aspect ratio. Nothing here orbits or drifts.
+ */
+export const CAMERA = {
+ fov: 20.5,
+ azimuth: (45.0 * Math.PI) / 180,
+ elevation: (33.0 * Math.PI) / 180,
+ target: new THREE.Vector3(0, -0.15, 0),
+ fillX: 0.84,
+ fillY: 0.86,
+ // Post-fit camera multiplier. Keep 1.0 for the fitted size; 0.70 makes the
+ // diorama 30% smaller linearly and leaves more paper margin. This is a camera
+ // move only: slab, world clip, shadows and canvas stay at full scale.
+ subjectScale: 1.0,
+};
+
+/** Override this list for a different slab / landmark height. */
+export const FIT_POINTS = [
+ new THREE.Vector3(-10.5, 0.0, -7.0),
+ new THREE.Vector3(10.5, 0.0, -7.0),
+ new THREE.Vector3(10.5, 0.0, 7.0),
+ new THREE.Vector3(-10.5, 0.0, 7.0),
+ new THREE.Vector3(-10.5, -0.42, -7.0),
+ new THREE.Vector3(10.5, -0.42, -7.0),
+ new THREE.Vector3(10.5, -0.42, 7.0),
+ new THREE.Vector3(-10.5, -0.42, 7.0),
+ new THREE.Vector3(0.0, 3.6, 0.0),
+];
+
+export function cameraDirection(out = new THREE.Vector3()) {
+ const ce = Math.cos(CAMERA.elevation);
+ return out.set(
+ ce * Math.cos(CAMERA.azimuth),
+ Math.sin(CAMERA.elevation),
+ ce * Math.sin(CAMERA.azimuth)
+ );
+}
+
+function fits(dir, right, up, aspect, distance, points) {
+ const tanHalf = Math.tan((CAMERA.fov * Math.PI) / 360);
+ const p = new THREE.Vector3();
+ for (const fit of points) {
+ p.subVectors(fit, CAMERA.target);
+ const depth = distance - p.dot(dir);
+ if (depth < 0.4) return false;
+ const x = p.dot(right) / (depth * tanHalf * aspect);
+ const y = p.dot(up) / (depth * tanHalf);
+ if (Math.abs(x) > CAMERA.fillX) return false;
+ if (Math.abs(y) > CAMERA.fillY) return false;
+ }
+ return true;
+}
+
+export function solveDistance(aspect, points = FIT_POINTS) {
+ const a = Math.max(0.3, aspect);
+ const dir = cameraDirection();
+ const right = new THREE.Vector3().crossVectors(new THREE.Vector3(0, 1, 0), dir).normalize();
+ const up = new THREE.Vector3().crossVectors(dir, right).normalize();
+
+ let lo = 5;
+ let hi = 300;
+ for (let i = 0; i < 48; i++) {
+ const mid = (lo + hi) * 0.5;
+ if (fits(dir, right, up, a, mid, points)) hi = mid;
+ else lo = mid;
+ }
+ return hi;
+}
+
+export function createCamera(aspect = 1.16, points = FIT_POINTS) {
+ const camera = new THREE.PerspectiveCamera(CAMERA.fov, aspect, 0.5, 400);
+ updateCamera(camera, aspect, points);
+ return camera;
+}
+
+export function updateCamera(camera, aspect, points = FIT_POINTS) {
+ const a = Math.max(0.3, aspect);
+ const fit = solveDistance(a, points);
+ const scale = CAMERA.subjectScale ?? 1;
+ const d = fit / Math.max(0.1, scale);
+ const dir = cameraDirection();
+ camera.position.copy(CAMERA.target).addScaledVector(dir, d);
+ camera.lookAt(CAMERA.target);
+ camera.aspect = a;
+ camera.near = Math.max(0.3, d * 0.01);
+ camera.far = d * 4 + 80;
+ camera.updateProjectionMatrix();
+ camera.userData.fitDistance = fit;
+ camera.userData.subjectScale = scale;
+ camera.userData.distance = d;
+}
diff --git a/templates/combat.js b/templates/combat.js
new file mode 100644
index 0000000..cc1837f
--- /dev/null
+++ b/templates/combat.js
@@ -0,0 +1,100 @@
+/**
+ * Deterministic combat helpers for a diorama.
+ *
+ * Everything here is pure: no Date, no Math.random, no state carried between
+ * frames. Feed the same t and seed and you get the same frame.
+ */
+
+export const DT = 1 / 40;
+
+export const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
+export const pulse = (t, t0, tau) => (t < t0 ? 0 : Math.exp(-(t - t0) / tau));
+export const win = (t, t0, dur) => clamp((t - t0) / dur, 0, 1);
+export const easeOutCubic = (u) => 1 - Math.pow(1 - u, 3);
+export const easeInOut = (u) => u * u * (3 - 2 * u);
+
+/** Decaying oscillation; +1 at t0, settles to 0. */
+export const spring = (t, t0, freq = 9, damp = 6) => {
+ const a = t - t0;
+ return a < 0 ? 0 : Math.exp(-damp * a) * Math.cos(freq * a);
+};
+
+/** Stable 0..1 hash for per-actor phase offsets. */
+export function hash(n) {
+ const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;
+ return x - Math.floor(x);
+}
+
+export const phase = (i, turns = 1) => hash(i) * Math.PI * 2 * turns;
+
+/** Stagger a group so they do not move like a chorus line. */
+export const stagger = (i, step = 0.18, base = 0) => base + i * step;
+
+/** Absolute event times, sorted once. */
+export function finalize(events) {
+ events.sort((a, b) => a.t - b.t);
+ return events;
+}
+
+/** The last event of a kind at or before t. */
+export function lastEvent(events, kind, t) {
+ let found = null;
+ for (const e of events) {
+ if (e.t > t) break;
+ if (e.kind === kind) found = e;
+ }
+ return found;
+}
+
+/** All events of a kind in [t0, t1). */
+export function eventsIn(events, kind, t0, t1) {
+ return events.filter((e) => e.kind === kind && e.t >= t0 && e.t < t1);
+}
+
+/**
+ * Species death grammar. Counts are the minimum; add one signature piece if
+ * the species carries a weapon or trophy.
+ */
+export function deathPieces(type, seed = 0) {
+ const n = 1 + Math.floor(hash(seed + 3) * 3);
+ switch (type) {
+ case 'goblin':
+ return { debris: 'cloth', count: 2 + n, dropped: 'knife', stain: 'blood' };
+ case 'orc':
+ return { debris: 'iron', count: 3 + n, dropped: 'sword', stain: 'blood' };
+ case 'slime':
+ return { debris: 'goo', count: 5 + n, dropped: null, stain: 'goo' };
+ case 'flyer':
+ return { debris: 'feather', count: 4 + n, dropped: null, stain: 'feather' };
+ case 'human':
+ return { debris: 'cloth', count: 3 + n, dropped: 'tool', stain: 'blood' };
+ case 'boss':
+ return { debris: 'iron', count: 6 + n, dropped: 'club', stain: 'scorch' };
+ default:
+ // Never default to a grey dust puff; cloth at least reads as a body.
+ return { debris: 'cloth', count: 3 + n, dropped: null, stain: 'dust' };
+ }
+}
+
+/**
+ * A fixed-flight projectile position. `u` is 0 at launch, 1 at impact.
+ * `arc` is the height gained at mid-flight, in metres.
+ */
+export function projectileAt(from, to, u, arc = 0) {
+ const k = clamp(u, 0, 1);
+ return {
+ x: from.x + (to.x - from.x) * k,
+ y: from.y + (to.y - from.y) * k + Math.sin(k * Math.PI) * arc,
+ z: from.z + (to.z - from.z) * k,
+ };
+}
+
+/** A boss contact pose weight: telegraph, snap, recover. */
+export function contactWeight(t, hitT, wind = 0.45, recover = 0.4) {
+ if (t < hitT - wind || t > hitT + recover) return 0;
+ if (t < hitT) {
+ const u = (t - (hitT - wind)) / wind;
+ return 1 - Math.pow(1 - u, 3); // accelerating wind-up
+ }
+ return 1 - (t - hitT) / recover; // follow-through then rest
+}
diff --git a/templates/detail.js b/templates/detail.js
new file mode 100644
index 0000000..4ee3bac
--- /dev/null
+++ b/templates/detail.js
@@ -0,0 +1,256 @@
+/**
+ * Reusable detail assemblies. All colours come from the caller's materials so
+ * the palette stays the single source of truth.
+ */
+import * as THREE from 'three';
+
+export function mesh(parent, geo, mat, x, y, z, opts = {}) {
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ if (opts.rotation) m.rotation.set(...opts.rotation);
+ if (opts.scale) m.scale.set(...opts.scale);
+ m.castShadow = opts.castShadow ?? true;
+ m.receiveShadow = opts.receiveShadow ?? true;
+ parent.add(m);
+ return m;
+}
+
+/** A straight bone/rope/bar between two points. */
+export function seg(parent, a, b, r0, r1, mat, opts = {}) {
+ const dir = new THREE.Vector3().subVectors(b, a);
+ const len = Math.max(0.001, dir.length());
+ const mid = new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5);
+ const m = mesh(
+ parent,
+ new THREE.CylinderGeometry(r1, r0, len, opts.segments ?? 5),
+ mat,
+ mid.x,
+ mid.y,
+ mid.z,
+ opts
+ );
+ m.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir.normalize());
+ return m;
+}
+
+/** Horizontal iron band around a shaft. */
+export function band(parent, radius, tube, mat, y, opts = {}) {
+ return mesh(
+ parent,
+ new THREE.TorusGeometry(radius, tube, 4, opts.segments ?? 10),
+ mat,
+ 0,
+ y,
+ 0,
+ { rotation: [Math.PI / 2, 0, 0], ...opts }
+ );
+}
+
+/** A ring of rivets/studs around a horizontal circle. */
+export function rivets(parent, mat, count, radius, y, size = 0.03, opts = {}) {
+ const g = new THREE.Group();
+ g.position.y = y;
+ parent.add(g);
+ for (let i = 0; i < count; i++) {
+ const a = (i / count) * Math.PI * 2;
+ mesh(g, new THREE.SphereGeometry(size, 4, 3), mat, Math.sin(a) * radius, 0, Math.cos(a) * radius, {
+ castShadow: false,
+ ...opts,
+ });
+ }
+ return g;
+}
+
+/** Simple spoked wheel in the YZ plane, axle along X. */
+export function wheel(parent, mat, rimMat, x, y, z, radius = 0.3, width = 0.06, spokes = 6) {
+ const g = new THREE.Group();
+ g.position.set(x, y, z);
+ parent.add(g);
+ mesh(g, new THREE.TorusGeometry(radius, width, 4, 12), mat, 0, 0, 0, {
+ rotation: [0, Math.PI / 2, 0],
+ });
+ mesh(g, new THREE.TorusGeometry(radius + 0.02, 0.018, 4, 12), rimMat, 0, 0, 0, {
+ rotation: [0, Math.PI / 2, 0],
+ castShadow: false,
+ });
+ for (let i = 0; i < spokes; i++) {
+ mesh(g, new THREE.BoxGeometry(0.035, radius * 1.9, 0.035), mat, 0, 0, 0, {
+ rotation: [(i / spokes) * Math.PI, 0, 0],
+ castShadow: false,
+ });
+ }
+ mesh(g, new THREE.CylinderGeometry(0.06, 0.06, width * 1.6, 6), rimMat, 0, 0, 0, {
+ rotation: [0, 0, Math.PI / 2],
+ castShadow: false,
+ });
+ return g;
+}
+
+/** A tied rectangular hay bale, with straw tufts. */
+export function bale(parent, mat, tieMat, x, y, z, opts = {}) {
+ const w = opts.w ?? 0.6;
+ const h = opts.h ?? 0.3;
+ const d = opts.d ?? 0.46;
+ const g = new THREE.Group();
+ g.position.set(x, y, z);
+ if (opts.rotation) g.rotation.y = opts.rotation;
+ parent.add(g);
+ mesh(g, new THREE.BoxGeometry(w, h, d), mat, 0, 0, 0);
+ for (const s of [-1, 1]) {
+ mesh(g, new THREE.BoxGeometry(0.032, h * 1.04, d * 1.04), tieMat, s * w * 0.25, 0, 0, {
+ castShadow: false,
+ });
+ }
+ for (let i = 0; i < 5; i++) {
+ mesh(g, new THREE.BoxGeometry(0.015, 0.11, 0.015), mat, -w * 0.35 + i * w * 0.17, h * 0.6, d * 0.3, {
+ rotation: [0.2, 0, 0.4 - i * 0.2],
+ castShadow: false,
+ });
+ }
+ return g;
+}
+
+/** A horned skull facing +Z. Mount it on trophyBoard(), never in mid-air. */
+export function skull(parent, boneMat, inkMat, x, y, z, s = 1) {
+ const g = new THREE.Group();
+ g.position.set(x, y, z);
+ parent.add(g);
+ mesh(g, new THREE.SphereGeometry(0.22 * s, 7, 6), boneMat, 0, 0, 0, { scale: [1, 0.92, 1.04] });
+ mesh(g, new THREE.BoxGeometry(0.34 * s, 0.09 * s, 0.16 * s), boneMat, 0, 0.09 * s, 0.12 * s);
+ mesh(g, new THREE.BoxGeometry(0.19 * s, 0.14 * s, 0.22 * s), boneMat, 0, -0.12 * s, 0.18 * s, {
+ rotation: [0.12, 0, 0],
+ });
+ mesh(g, new THREE.BoxGeometry(0.17 * s, 0.07 * s, 0.18 * s), boneMat, 0, -0.2 * s, 0.2 * s);
+ for (const side of [-1, 1]) {
+ mesh(g, new THREE.BoxGeometry(0.075 * s, 0.09 * s, 0.06 * s), inkMat, side * 0.085 * s, 0.03 * s, 0.2 * s, {
+ castShadow: false,
+ });
+ const a = new THREE.Vector3(side * 0.16 * s, 0.11 * s, 0.02 * s);
+ const b = new THREE.Vector3(side * 0.31 * s, 0.25 * s, 0);
+ const c = new THREE.Vector3(side * 0.41 * s, 0.43 * s, -0.02 * s);
+ const d = new THREE.Vector3(side * 0.35 * s, 0.56 * s, -0.01 * s);
+ seg(g, a, b, 0.06 * s, 0.048 * s, boneMat);
+ seg(g, b, c, 0.048 * s, 0.034 * s, boneMat);
+ seg(g, c, d, 0.034 * s, 0.02 * s, boneMat);
+ }
+ return g;
+}
+
+
+/** A rope/chain run through points. Returns the segment group. */
+export function rope(parent, points, radius, mat, opts = {}) {
+ const g = new THREE.Group();
+ parent.add(g);
+ for (let i = 1; i < points.length; i++) {
+ seg(g, points[i - 1], points[i], radius, radius * 0.92, mat, {
+ segments: opts.segments ?? 4,
+ castShadow: opts.castShadow ?? true,
+ });
+ if (i < points.length - 1) {
+ mesh(g, new THREE.SphereGeometry(radius * 1.05, 4, 3), mat, points[i].x, points[i].y, points[i].z, {
+ castShadow: false,
+ });
+ }
+ }
+ return g;
+}
+
+/** A trophy board with studs and a rope loop; place a skull on its face. */
+export function trophyBoard(parent, woodMat, ironMat, x, y, z, w = 0.62, h = 0.72) {
+ const g = new THREE.Group();
+ g.position.set(x, y, z);
+ parent.add(g);
+ mesh(g, new THREE.BoxGeometry(w, h, 0.07), woodMat, 0, 0, 0);
+ for (const sx of [-1, 1]) {
+ for (const sy of [-1, 1]) {
+ mesh(g, new THREE.SphereGeometry(0.028, 4, 3), ironMat, sx * w * 0.38, sy * h * 0.38, 0.045, {
+ castShadow: false,
+ });
+ }
+ }
+ mesh(g, new THREE.TorusGeometry(0.06, 0.012, 3, 6), ironMat, 0, h * 0.5, 0, {
+ rotation: [Math.PI / 2, 0, 0],
+ castShadow: false,
+ });
+ return g;
+}
+
+let _shadowTex = null;
+function shadowTexture() {
+ if (_shadowTex) return _shadowTex;
+ const c = document.createElement('canvas');
+ c.width = c.height = 64;
+ const ctx = c.getContext('2d');
+ const g = ctx.createRadialGradient(32, 32, 2, 32, 32, 31);
+ g.addColorStop(0, 'rgba(0,0,0,0.72)');
+ g.addColorStop(0.55, 'rgba(0,0,0,0.28)');
+ g.addColorStop(1, 'rgba(0,0,0,0)');
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, 64, 64);
+ _shadowTex = new THREE.CanvasTexture(c);
+ return _shadowTex;
+}
+
+/** Ground-projected contact shadow. Put it on the surface the object stands on. */
+export function contactShadow(parent, x, y, z, size = 1, opacity = 0.62) {
+ const mat = new THREE.MeshBasicMaterial({
+ map: shadowTexture(),
+ transparent: true,
+ opacity,
+ depthWrite: false,
+ color: 0x000000,
+ });
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(size, size), mat);
+ m.rotation.x = -Math.PI / 2;
+ m.position.set(x, y + 0.018, z);
+ m.renderOrder = 1;
+ parent.add(m);
+ return m;
+}
+
+const _radialTex = new Map();
+
+/**
+ * Soft radial-alpha texture for halos, light pools and glow cards.
+ * `rgb` is an "r,g,b" string so the texture bakes the palette colour.
+ */
+export function softDiscTexture(rgb = '255,255,255', size = 64) {
+ const key = `${rgb}|${size}`;
+ if (_radialTex.has(key)) return _radialTex.get(key);
+ const c = document.createElement('canvas');
+ c.width = c.height = size;
+ const ctx = c.getContext('2d');
+ const g = ctx.createRadialGradient(size / 2, size / 2, size * 0.03, size / 2, size / 2, size * 0.49);
+ g.addColorStop(0, `rgba(${rgb},1)`);
+ g.addColorStop(0.45, `rgba(${rgb},0.55)`);
+ g.addColorStop(1, `rgba(${rgb},0)`);
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, size, size);
+ const tex = new THREE.CanvasTexture(c);
+ tex.colorSpace = THREE.SRGBColorSpace;
+ _radialTex.set(key, tex);
+ return tex;
+}
+
+/**
+ * A glow card with a soft edge. Use this instead of an untextured additive
+ * PlaneGeometry: a flat quad reads as a light-grey rectangle at the palette snap.
+ * Add it to the prop so it moves with the lamp/board/sign.
+ */
+export function haloPlane(parent, width, height, rgb, opacity = 0.35, x = 0, y = 0, z = 0, opts = {}) {
+ const mat = new THREE.MeshBasicMaterial({
+ map: softDiscTexture(rgb),
+ transparent: true,
+ opacity,
+ blending: THREE.AdditiveBlending,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ color: 0xffffff,
+ });
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(width, height), mat);
+ m.position.set(x, y, z);
+ if (opts.rotation) m.rotation.set(...opts.rotation);
+ m.renderOrder = opts.renderOrder ?? 3;
+ parent.add(m);
+ return m;
+}
diff --git a/templates/geometry.js b/templates/geometry.js
new file mode 100644
index 0000000..3b47296
--- /dev/null
+++ b/templates/geometry.js
@@ -0,0 +1,292 @@
+import * as THREE from 'three';
+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
+
+/**
+ * A crisp, flat-shaded box with geometrically chamfered top / bottom edges.
+ * The chamfer lives in the geometry (not in a normal map), so it catches a real
+ * specular highlight and reads as thickness at small scale.
+ */
+export function chamferBoxGeometry(w, h, d, opts = {}) {
+ const top = opts.top ?? Math.min(w, d, h) * 0.06;
+ const bottom = opts.bottom ?? 0;
+ const hw = w * 0.5;
+ const hd = d * 0.5;
+ const hh = h * 0.5;
+ const t = Math.min(top, hw * 0.35, hd * 0.35, h * 0.35);
+ const b = Math.min(bottom, hw * 0.35, hd * 0.35, h * 0.35);
+ const yt = hh - t;
+ const yb = -hh + b;
+ const tx = hw - t;
+ const tz = hd - t;
+ const bx = hw - b;
+ const bz = hd - b;
+
+ const pos = [];
+ const nor = [];
+ const center = new THREE.Vector3();
+
+ const v = (x, y, z) => new THREE.Vector3(x, y, z);
+
+ function tri(a, b, c, n) {
+ pos.push(a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z);
+ for (let i = 0; i < 3; i++) nor.push(n.x, n.y, n.z);
+ }
+
+ function quad(a, b, c, d, hint) {
+ const n = new THREE.Vector3()
+ .subVectors(b, a)
+ .cross(new THREE.Vector3().subVectors(c, a))
+ .normalize();
+ if (n.dot(hint) < 0) {
+ const tmp = b;
+ b = d;
+ d = tmp;
+ n.negate();
+ }
+ tri(a, b, c, n);
+ tri(a, c, d, n);
+ }
+
+ // Bottom cap
+ if (b > 0.0001) {
+ quad(
+ v(-bx, -hh, -bz), v(bx, -hh, -bz), v(bx, -hh, bz), v(-bx, -hh, bz),
+ v(0, -1, 0)
+ );
+ } else {
+ quad(
+ v(-hw, -hh, -hd), v(hw, -hh, -hd), v(hw, -hh, hd), v(-hw, -hh, hd),
+ v(0, -1, 0)
+ );
+ }
+
+ // Four sides
+ quad(v(hw, yb, -hd), v(hw, yb, hd), v(hw, yt, hd), v(hw, yt, -hd), v(1, 0, 0));
+ quad(v(-hw, yb, hd), v(-hw, yb, -hd), v(-hw, yt, -hd), v(-hw, yt, hd), v(-1, 0, 0));
+ quad(v(-hw, yb, hd), v(hw, yb, hd), v(hw, yt, hd), v(-hw, yt, hd), v(0, 0, 1));
+ quad(v(hw, yb, -hd), v(-hw, yb, -hd), v(-hw, yt, -hd), v(hw, yt, -hd), v(0, 0, -1));
+
+ // Top chamfer band
+ quad(v(hw, yt, -hd), v(hw, yt, hd), v(tx, hh, tz), v(tx, hh, -tz), v(1, 1, 0));
+ quad(v(-hw, yt, hd), v(-hw, yt, -hd), v(-tx, hh, -tz), v(-tx, hh, tz), v(-1, 1, 0));
+ quad(v(-hw, yt, hd), v(hw, yt, hd), v(tx, hh, tz), v(-tx, hh, tz), v(0, 1, 1));
+ quad(v(hw, yt, -hd), v(-hw, yt, -hd), v(-tx, hh, -tz), v(tx, hh, -tz), v(0, 1, -1));
+
+ // Top cap
+ quad(v(-tx, hh, -tz), v(tx, hh, -tz), v(tx, hh, tz), v(-tx, hh, tz), v(0, 1, 0));
+
+ // Bottom chamfer band
+ if (b > 0.0001) {
+ quad(v(bx, -hh, -bz), v(hw, yb, -hd), v(hw, yb, hd), v(bx, -hh, bz), v(1, -1, 0));
+ quad(v(-bx, -hh, bz), v(-hw, yb, hd), v(-hw, yb, -hd), v(-bx, -hh, -bz), v(-1, -1, 0));
+ quad(v(-bx, -hh, bz), v(bx, -hh, bz), v(hw, yb, hd), v(-hw, yb, hd), v(0, -1, 1));
+ quad(v(bx, -hh, -bz), v(-bx, -hh, -bz), v(-hw, yb, -hd), v(hw, yb, -hd), v(0, -1, -1));
+ }
+
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ geo.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ geo.computeBoundingSphere();
+ return geo;
+}
+
+export function roundedBoxGeometry(w, h, d, radius = 0.02, segments = 2) {
+ return new RoundedBoxGeometry(w, h, d, segments, Math.min(radius, w * 0.45, h * 0.45, d * 0.45));
+}
+
+/** A chamfered rectangle path, used for the plan section of the concrete shell. */
+export function chamferedRectShape(w, d, chamfer = 0.12) {
+ const hw = w * 0.5;
+ const hd = d * 0.5;
+ const c = Math.min(chamfer, hw * 0.4, hd * 0.4);
+ const s = new THREE.Shape();
+ s.moveTo(-hw + c, -hd);
+ s.lineTo(hw - c, -hd);
+ s.lineTo(hw, -hd + c);
+ s.lineTo(hw, hd - c);
+ s.lineTo(hw - c, hd);
+ s.lineTo(-hw + c, hd);
+ s.lineTo(-hw, hd - c);
+ s.lineTo(-hw, -hd + c);
+ s.closePath();
+ return s;
+}
+
+/** Rectangular ring slab with an actual hole and chamfered edges. */
+export function ringSlabGeometry(outerW, outerD, innerW, innerD, thickness, bevel = 0.02) {
+ const shape = chamferedRectShape(outerW, outerD, bevel * 2.2);
+ const hole = new THREE.Path();
+ const hw = innerW * 0.5;
+ const hd = innerD * 0.5;
+ hole.moveTo(-hw, -hd);
+ hole.lineTo(hw, -hd);
+ hole.lineTo(hw, hd);
+ hole.lineTo(-hw, hd);
+ hole.closePath();
+ shape.holes.push(hole);
+ const geo = new THREE.ExtrudeGeometry(shape, {
+ depth: thickness,
+ bevelEnabled: bevel > 0,
+ bevelThickness: bevel,
+ bevelSize: bevel,
+ bevelSegments: 2,
+ curveSegments: 1,
+ steps: 1,
+ });
+ geo.rotateX(-Math.PI / 2);
+ // After rotateX(-90) the extrusion runs from y=0 to y=thickness.
+ geo.translate(0, -thickness, 0);
+ geo.computeVertexNormals();
+ return geo;
+}
+
+/** Extrude a plan ring vertically (concrete pool walls). */
+export function extrudedWallRing(outerW, outerD, innerW, innerD, height, opts = {}) {
+ const shape = chamferedRectShape(outerW, outerD, opts.chamfer ?? 0.14);
+ const hole = new THREE.Path();
+ const hw = innerW * 0.5;
+ const hd = innerD * 0.5;
+ hole.moveTo(-hw, -hd);
+ hole.lineTo(hw, -hd);
+ hole.lineTo(hw, hd);
+ hole.lineTo(-hw, hd);
+ hole.closePath();
+ shape.holes.push(hole);
+ const geo = new THREE.ExtrudeGeometry(shape, {
+ depth: height,
+ bevelEnabled: true,
+ bevelThickness: opts.bevel ?? 0.015,
+ bevelSize: opts.bevel ?? 0.015,
+ bevelSegments: 2,
+ curveSegments: 1,
+ steps: 1,
+ });
+ geo.rotateX(-Math.PI / 2);
+ geo.translate(0, -height, 0);
+ geo.computeVertexNormals();
+ return geo;
+}
+
+/** Plane whose height follows a function of x (used for the sloping pool floor). */
+export function heightFieldGeometry(width, depth, segX, segZ, heightFn) {
+ const geo = new THREE.PlaneGeometry(width, depth, segX, segZ);
+ geo.rotateX(-Math.PI / 2);
+ const p = geo.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i);
+ const z = p.getZ(i);
+ p.setY(i, heightFn(x, z));
+ }
+ geo.computeVertexNormals();
+ return geo;
+}
+
+export function quatFromBasis(u, normal) {
+ const x = u.clone().normalize();
+ const y = normal.clone().normalize();
+ const z = new THREE.Vector3().crossVectors(x, y).normalize();
+ const m = new THREE.Matrix4().makeBasis(x, y, z);
+ return new THREE.Quaternion().setFromRotationMatrix(m);
+}
+
+export function hash2(x, y) {
+ const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453123;
+ return s - Math.floor(s);
+}
+
+export function hash3(x, y, z) {
+ const s = Math.sin(x * 12.9898 + y * 78.233 + z * 37.719) * 43758.5453123;
+ return s - Math.floor(s);
+}
+
+export function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function () {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/**
+ * Build an InstancedMesh from a list of { position, quaternion, scale, color }.
+ * A tiny custom varying (vInstColor) is injected into the material so instance
+ * tint works reliably on MeshStandardMaterial / MeshPhysicalMaterial.
+ */
+export function instancedMesh(geometry, material, items, opts = {}) {
+ const mesh = new THREE.InstancedMesh(geometry, material, items.length);
+ const m = new THREE.Matrix4();
+ const q = new THREE.Quaternion();
+ const s = new THREE.Vector3(1, 1, 1);
+ for (let i = 0; i < items.length; i++) {
+ const it = items[i];
+ q.copy(it.quaternion);
+ s.copy(it.scale ?? { x: 1, y: 1, z: 1 });
+ m.compose(it.position, q, s);
+ mesh.setMatrixAt(i, m);
+ if (it.color) mesh.setColorAt(i, it.color);
+ }
+ mesh.instanceMatrix.needsUpdate = true;
+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ mesh.castShadow = opts.castShadow ?? false;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ mesh.frustumCulled = false;
+ return mesh;
+}
+
+export function colorVariation(base, rand, h = 0.01, s = 0.05, l = 0.03) {
+ const c = base.clone();
+ c.offsetHSL((rand() - 0.5) * h, (rand() - 0.5) * s, (rand() - 0.5) * l);
+ return c;
+}
+
+export function smoothstep(a, b, x) {
+ const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+}
+
+export function addBox(group, w, h, d, material, x, y, z, opts = {}) {
+ const geo = opts.chamfer
+ ? chamferBoxGeometry(w, h, d, { top: opts.chamfer, bottom: opts.chamferBottom ?? 0 })
+ : new THREE.BoxGeometry(w, h, d);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.position.set(x, y, z);
+ if (opts.rotation) mesh.rotation.set(opts.rotation[0], opts.rotation[1], opts.rotation[2]);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ group.add(mesh);
+ return mesh;
+}
+
+export function addCylinder(group, rTop, rBottom, h, material, x, y, z, opts = {}) {
+ const geo = new THREE.CylinderGeometry(rTop, rBottom, h, opts.segments ?? 16, opts.heightSegments ?? 1, opts.open ?? false);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.position.set(x, y, z);
+ if (opts.rotation) mesh.rotation.set(opts.rotation[0], opts.rotation[1], opts.rotation[2]);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ group.add(mesh);
+ return mesh;
+}
+
+export function addSphere(group, r, material, x, y, z, scale = [1, 1, 1], opts = {}) {
+ const geo = new THREE.SphereGeometry(r, opts.widthSegments ?? 20, opts.heightSegments ?? 14);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.position.set(x, y, z);
+ mesh.scale.set(scale[0], scale[1], scale[2]);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ group.add(mesh);
+ return mesh;
+}
+
+export function makeTube(points, radius, material, opts = {}) {
+ const curve = new THREE.CatmullRomCurve3(points, false, 'catmullrom', 0.35);
+ const geo = new THREE.TubeGeometry(curve, opts.segments ?? 48, radius, opts.radialSegments ?? 8, false);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ return mesh;
+}
diff --git a/templates/lighting.js b/templates/lighting.js
new file mode 100644
index 0000000..2118aac
--- /dev/null
+++ b/templates/lighting.js
@@ -0,0 +1,50 @@
+import * as THREE from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+
+export function createLighting(renderer, scene) {
+ const hemi = new THREE.HemisphereLight(0xd6ecf6, 0x6f6a60, 0.24);
+ scene.add(hemi);
+
+ const sun = new THREE.DirectionalLight(0xfff8ee, 3.3);
+ sun.position.set(-15, 19.5, 17);
+ sun.target.position.set(0, -0.4, 0);
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048);
+ sun.shadow.camera.left = -13;
+ sun.shadow.camera.right = 13;
+ sun.shadow.camera.top = 13;
+ sun.shadow.camera.bottom = -13;
+ sun.shadow.camera.near = 4;
+ sun.shadow.camera.far = 70;
+ sun.shadow.bias = -0.00022;
+ sun.shadow.normalBias = 0.025;
+ sun.shadow.radius = 1.0;
+ sun.shadow.camera.updateProjectionMatrix();
+ scene.add(sun);
+ scene.add(sun.target);
+
+ const fill = new THREE.DirectionalLight(0xa9cbe2, 0.46);
+ fill.position.set(19, 13, -15);
+ fill.target.position.set(0, -0.5, 0);
+ scene.add(fill);
+ scene.add(fill.target);
+
+ // Aquatic subjects set scene.userData.aquatic = true before lighting.
+ // A dry scene must not get a cyan bounce from below the deck.
+ let waterBounce = null;
+ if (scene.userData.aquatic) {
+ waterBounce = new THREE.PointLight(0x74cfd2, 1.7, 11, 2.0);
+ waterBounce.position.set(0.3, -0.9, 0.0);
+ scene.add(waterBounce);
+ }
+
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const envScene = new RoomEnvironment();
+ const env = pmrem.fromScene(envScene, 0.035).texture;
+ scene.environment = env;
+ scene.environmentIntensity = 0.18;
+ pmrem.dispose();
+ envScene.dispose?.();
+
+ return { sun, hemi, fill, waterBounce, env };
+}
diff --git a/templates/palette.js b/templates/palette.js
new file mode 100644
index 0000000..ce7de7c
--- /dev/null
+++ b/templates/palette.js
@@ -0,0 +1,35 @@
+/**
+ * 64-colour sRGB palette. The scene is quantised to these values after an
+ * 8x8 ordered dither, which is what gives the miniature its printed, pixel-art
+ * finish. Keep the length at exactly 64: the shader declares vec3[64].
+ */
+export const PALETTE_HEX = [
+ // paper, plaster, limestone, deck stone
+ '#ffffff', '#faf7ef', '#f3eddf', '#eae2d3', '#e1d7c5',
+ '#d6cbb8', '#c9bda9', '#baae9a', '#a89c88', '#908574',
+ // concrete, shadow, steel darks
+ '#8b9195', '#7b8287', '#6c7378', '#5e656a', '#51575c',
+ '#444a4f', '#383e43', '#2c3237',
+ // water and glazed tile ramps
+ '#d8f2ef', '#bce9e4', '#9ddddb', '#80cecf', '#67bfc4',
+ '#54aeb6', '#429da7', '#338b98', '#287888', '#206577',
+ '#1a5366', '#164456', '#9d988c', '#1f5f6f', '#2d7f8c',
+ '#4a9aa5',
+ // skin
+ '#f4d5b8', '#eac09d', '#dfab82', '#d0966b', '#b97d55',
+ '#9c6440', '#71452e',
+ // hair
+ '#2c231e', '#463128', '#62452f', '#a87b4a', '#d8b878',
+ // swimwear, inflatables, drink, accents
+ '#ef6a52', '#d9503c', '#918c80', '#857f74', '#3aa39a',
+ '#267e78', '#6d685f', '#6fa0c9', '#efe7d6', '#79746a',
+ '#615d55', '#c7d3d8',
+ // metals
+ '#b9c5c9', '#9ba7ab', '#7f8b90', '#606b70', '#3b4449',
+ '#20282c',
+];
+
+export const PALETTE_RGB = PALETTE_HEX.map((hex) => {
+ const n = parseInt(hex.slice(1), 16);
+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
+});
diff --git a/templates/peopleModel-street.js b/templates/peopleModel-street.js
new file mode 100644
index 0000000..34127cb
--- /dev/null
+++ b/templates/peopleModel-street.js
@@ -0,0 +1,664 @@
+import * as THREE from 'three';
+import { roundedBoxGeometry } from '../core/geometry.js';
+
+/**
+ * Diorama clothed rig: the 1.69 m skeleton with a skull/jaw head, layered
+ * street clothing (tee, jacket, puffer, hoodie, scrubs, apron, trousers, hats,
+ * packs, gloves) and tapered lathe limbs. Faces +Z. Positive hip/shoulder X
+ * swings a limb backward. Copy beside the base rig and pick per scene: this one
+ * for clothed social/street casts, the base one for swimwear/aquatic casts.
+ */
+export const RIG = {
+ hipY: 0.86,
+ hipX: 0.10,
+ thigh: 0.42,
+ shin: 0.40,
+ shoulderY: 0.415,
+ shoulderX: 0.182,
+ upperArm: 0.30,
+ foreArm: 0.27,
+ headY: 0.584,
+};
+
+function part(parent, geo, mat, x, y, z, opts = {}) {
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ if (opts.rotation) m.rotation.set(...opts.rotation);
+ if (opts.scale) m.scale.set(...opts.scale);
+ m.castShadow = opts.castShadow ?? true;
+ m.receiveShadow = true;
+ parent.add(m);
+ return m;
+}
+function capsule(parent, r, len, mat, x, y, z, opts = {}) {
+ return part(parent, new THREE.CapsuleGeometry(r, Math.max(0.01, len), 6, 14), mat, x, y, z, opts);
+}
+function sphere(parent, r, mat, x, y, z, scale = [1, 1, 1], opts = {}) {
+ return part(parent, new THREE.SphereGeometry(r, 20, 14), mat, x, y, z, { ...opts, scale });
+}
+function box(parent, w, h, d, r, mat, x, y, z, opts = {}) {
+ const geo = roundedBoxGeometry(w, h, d, Math.min(r, Math.min(w, h, d) * 0.48), 2);
+ return part(parent, geo, mat, x, y, z, opts);
+}
+function lathe(parent, profile, flatten, mat, y, x = 0, z = 0) {
+ const pts = profile.map(([r, h]) => new THREE.Vector2(r, h));
+ const geo = new THREE.LatheGeometry(pts, 22);
+ geo.scale(1, 1, flatten);
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ parent.add(m);
+ return m;
+}
+
+const TORSO = [
+ [0.135, -0.02],
+ [0.165, 0.09],
+ [0.190, 0.22],
+ [0.198, 0.33],
+ [0.196, 0.40],
+ [0.168, 0.47],
+ [0.090, 0.53],
+ [0.062, 0.56],
+];
+const PELVIS = [
+ [0.105, -0.24],
+ [0.150, -0.17],
+ [0.176, -0.07],
+ [0.180, 0.04],
+ [0.168, 0.12],
+];
+const wide = (profile, k) => profile.map(([r, h]) => [r * k, h]);
+
+export function buildPerson(mats, opts = {}) {
+ const cloth = mats.cloth ?? mats.suits ?? {};
+ const skin = opts.skin ?? mats.skinTones?.[2] ?? mats.skin;
+ const hairMat = opts.hair ?? mats.hair?.[0] ?? mats.hairColor ?? cloth.charcoal;
+ const top = opts.top ?? cloth.navy ?? cloth.coral;
+ const bottom = opts.bottom ?? cloth.charcoal ?? cloth.navy ?? top;
+ const shoe = opts.shoe ?? mats.leather ?? mats.eye ?? bottom;
+ const shade = skin.clone();
+ shade.color = skin.color.clone().multiplyScalar(0.84);
+ const trim = top.clone();
+ trim.color = top.color.clone().multiplyScalar(0.78);
+ // Every material below can be supplied by the scene; fall back to a cloth
+ // tone rather than throwing on a missing key in a new palette.
+ const leather = mats.leather ?? bottom;
+ const metal = mats.steelDark ?? mats.ink ?? bottom;
+ const pale = mats.chrome ?? mats.bone ?? mats.paper ?? top;
+ const bone = mats.bone ?? mats.paper ?? top;
+ const eye = mats.eye ?? mats.ink ?? mats.steelDark ?? bottom;
+ const mouth = mats.mouth ?? eye;
+ const glass = mats.glass ?? eye;
+ const rose = mats.roseDeep ?? cloth.rose ?? top;
+ const rustLight = mats.rustLight ?? mats.rust ?? top;
+
+ const root = new THREE.Group();
+ const J = {};
+ const sleeve = opts.sleeve ?? 'short'; // short | long | none
+ const puffer = opts.topStyle === 'puffer';
+ const jacket = opts.topStyle === 'jacket' || opts.topStyle === 'hoodie' || puffer;
+ const topK = puffer ? 1.12 : jacket ? 1.05 : 1.0;
+
+ const loose = opts.loose === true;
+ const pelvis = new THREE.Group();
+ pelvis.position.y = RIG.hipY;
+ root.add(pelvis);
+ J.pelvis = pelvis;
+ lathe(pelvis, PELVIS, 0.86, bottom, 0);
+
+ // Belt / waistband.
+ part(
+ pelvis,
+ new THREE.CylinderGeometry(0.171, 0.178, 0.045, 18),
+ leather,
+ 0,
+ 0.03,
+ 0,
+ { scale: [1, 1, 0.88] }
+ );
+
+ const torso = new THREE.Group();
+ torso.position.y = 0.02;
+ pelvis.add(torso);
+ J.torso = torso;
+ lathe(torso, wide(TORSO, topK), 0.72, top, 0);
+
+ // Jacket details: lapels, zip, hem band, chest pocket.
+ if (jacket) {
+ box(torso, 0.014, 0.35, 0.016, 0.005, metal, 0, 0.25, 0.150);
+ box(torso, 0.028, 0.022, 0.010, 0.005, pale, 0, 0.410, 0.152, { castShadow: false });
+ part(torso, new THREE.CylinderGeometry(0.202 * topK, 0.198 * topK, 0.05, 18), trim, 0, 0.02, 0, {
+ scale: [1, 1, 0.74],
+ });
+ box(torso, 0.10, 0.045, 0.012, 0.006, rustLight, -0.105, 0.30, 0.146);
+ }
+ if (jacket && !opts.hood) {
+ // Stand collar: open at the front so the throat stays visible.
+ part(
+ torso,
+ new THREE.CylinderGeometry(0.078 * topK, 0.088 * topK, 0.044, 16, 1, true, Math.PI / 2 + 0.36, Math.PI * 2 - 0.72),
+ top,
+ 0,
+ 0.538,
+ 0.004,
+ { scale: [1, 1, 0.94] }
+ );
+ }
+ if (puffer) {
+ for (let i = 0; i < 3; i++) {
+ part(
+ torso,
+ new THREE.CylinderGeometry(0.196 * topK, 0.198 * topK, 0.075, 18),
+ top,
+ 0,
+ 0.12 + i * 0.13,
+ 0,
+ { scale: [1, 1, 0.735] }
+ );
+ }
+ }
+ if (opts.topStyle === 'hoodie') {
+ // Kangaroo pocket and drawstrings.
+ box(torso, 0.22, 0.13, 0.02, 0.02, top, 0, 0.16, 0.145);
+ for (const s of [-1, 1]) {
+ part(torso, new THREE.CylinderGeometry(0.007, 0.007, 0.16, 5), bone, s * 0.045, 0.40, 0.15, {
+ castShadow: false,
+ });
+ sphere(torso, 0.014, bone, s * 0.045, 0.32, 0.15, [1, 1, 1], { castShadow: false });
+ }
+ }
+ if (opts.topStyle === 'scrubs') {
+ // V-neck binding: two narrow strips down to the sternum.
+ for (const s of [-1, 1]) {
+ box(torso, 0.022, 0.180, 0.012, 0.005, cloth.tealDeep, s * 0.035, 0.455, 0.142, {
+ rotation: [0.01, 0, -s * 0.30],
+ });
+ }
+ part(torso, new THREE.CylinderGeometry(0.072, 0.080, 0.030, 14), cloth.tealDeep, 0, 0.540, 0.004);
+ // Loose tunic hem over the hips.
+ part(torso, new THREE.CylinderGeometry(0.184, 0.204, 0.085, 18), top, 0, 0.012, 0, {
+ scale: [1, 1, 0.80],
+ });
+ part(torso, new THREE.CylinderGeometry(0.204, 0.206, 0.016, 18), cloth.tealDeep, 0, -0.030, 0, {
+ scale: [1, 1, 0.80],
+ });
+ box(torso, 0.095, 0.050, 0.012, 0.006, cloth.tealDeep, 0.09, 0.31, 0.145);
+ for (const s of [-1, 1]) {
+ box(torso, 0.070, 0.080, 0.014, 0.006, cloth.tealDeep, s * 0.115, 0.105, 0.142);
+ }
+ // Drawstring at the waist.
+ for (const s of [-1, 1]) {
+ part(torso, new THREE.CylinderGeometry(0.005, 0.005, 0.09, 5), bone, s * 0.022, 0.085, 0.150, {
+ rotation: [0.1, 0, s * 0.25],
+ castShadow: false,
+ });
+ }
+ }
+
+ // Apron: bib, skirt, waist ties, pocket, towel.
+ if (opts.apron) {
+ const ap = new THREE.Group();
+ ap.position.set(0, 0.20, 0.155);
+ torso.add(ap);
+ box(ap, 0.28, 0.38, 0.018, 0.01, opts.apron, 0, 0.22, 0.0);
+ box(ap, 0.36, 0.52, 0.018, 0.012, opts.apron, 0, -0.22, 0.0);
+ box(ap, 0.20, 0.13, 0.022, 0.01, opts.apron, 0, -0.16, 0.012);
+ for (const s of [-1, 1]) {
+ box(ap, 0.06, 0.30, 0.016, 0.006, opts.apron, s * 0.15, 0.36, -0.01, {
+ rotation: [0, 0, s * 0.22],
+ });
+ }
+ // Waist knot with two short tails, not rigid horizontal straps.
+ box(ap, 0.07, 0.06, 0.03, 0.012, bone, 0, -0.02, 0.012);
+ for (const s of [-1, 1]) {
+ box(ap, 0.034, 0.19, 0.014, 0.006, bone, s * 0.035, -0.12, 0.012, {
+ rotation: [0.12, 0, s * 0.18],
+ });
+ }
+ if (opts.towel) {
+ box(ap, 0.10, 0.22, 0.02, 0.006, opts.towel, 0.17, 0.03, 0.016, {
+ rotation: [0, 0, 0.08],
+ });
+ }
+ }
+
+ // Neck and head: a skull, jaw and cheeks rather than stacked spheres.
+ capsule(torso, 0.050, 0.080, skin, 0, 0.545, -0.004);
+ sphere(torso, 0.078, skin, 0, 0.512, 0, [1.18, 0.42, 0.92]);
+
+ const head = new THREE.Group();
+ head.position.y = RIG.headY;
+ torso.add(head);
+ J.head = head;
+ head.scale.setScalar(0.97);
+
+ sphere(head, 0.100, skin, 0, 0.118, -0.004, [0.98, 1.16, 0.98]);
+ sphere(head, 0.079, skin, 0, 0.054, 0.012, [0.78, 0.80, 0.86]);
+ sphere(head, 0.029, skin, 0, 0.029, 0.079, [1.15, 0.62, 0.68]);
+ for (const s of [-1, 1]) {
+ sphere(head, 0.030, shade, s * 0.064, 0.090, 0.078, [0.55, 0.34, 0.18], { castShadow: false });
+ // Ear with a shadowed bowl.
+ sphere(head, 0.028, skin, s * 0.098, 0.101, 0.018, [0.36, 1.0, 0.72]);
+ sphere(head, 0.014, shade, s * 0.102, 0.102, 0.030, [0.28, 0.9, 0.5], { castShadow: false });
+ }
+
+ // Eyes sit proud of the face plane, under a brow and a soft socket.
+ for (const s of [-1, 1]) {
+ box(head, 0.036, 0.010, 0.008, 0.003, shade, s * 0.038, 0.123, 0.100, { castShadow: false });
+sphere(head, 0.0145, eye, s * 0.037, 0.110, 0.101, [1.0, 0.84, 0.42], { castShadow: false });
+ sphere(head, 0.0045, bone, s * 0.033, 0.114, 0.105, [1, 1, 0.6], { castShadow: false });
+ box(head, 0.034, 0.007, 0.010, 0.003, hairMat, s * 0.037, 0.131, 0.097, {
+ rotation: [0, 0, s * 0.09],
+ castShadow: false,
+ });
+ box(head, 0.031, 0.005, 0.009, 0.002, shade, s * 0.037, 0.120, 0.101, {
+ rotation: [0, 0, -s * 0.08],
+ castShadow: false,
+ });
+ box(head, 0.033, 0.005, 0.008, 0.002, shade, s * 0.040, 0.098, 0.101, {
+ rotation: [0, 0, -s * 0.06],
+ castShadow: false,
+ });
+ }
+
+ // Nose: a small bridge and tip, no beak.
+ box(head, 0.022, 0.058, 0.020, 0.007, skin, 0, 0.099, 0.103, { rotation: [-0.04, 0, 0] });
+ sphere(head, 0.018, skin, 0, 0.084, 0.113, [1.0, 0.8, 0.9]);
+ for (const s of [-1, 1]) {
+ sphere(head, 0.005, shade, s * 0.009, 0.081, 0.117, [1, 0.7, 0.7], { castShadow: false });
+ }
+
+ // Mouth: two lips and a dark seam.
+ box(head, 0.036, 0.007, 0.010, 0.003, shade, 0, 0.060, 0.099);
+ box(head, 0.033, 0.008, 0.011, 0.004, mouth, 0, 0.052, 0.101, { castShadow: false });
+ box(head, 0.033, 0.003, 0.012, 0.001, eye, 0, 0.056, 0.104, { castShadow: false });
+ box(head, 0.010, 0.014, 0.008, 0.003, shade, 0, 0.073, 0.103, { castShadow: false });
+
+ if (opts.glasses) {
+ for (const s of [-1, 1]) {
+ box(head, 0.070, 0.045, 0.012, 0.008, metal, s * 0.042, 0.111, 0.107, {
+ castShadow: false,
+ });
+ box(head, 0.054, 0.030, 0.006, 0.004, (mats.glass ?? eye), s * 0.042, 0.111, 0.114, {
+ castShadow: false,
+ });
+ }
+ box(head, 0.028, 0.006, 0.006, 0.002, metal, 0, 0.116, 0.111, { castShadow: false });
+ }
+
+ // Hair: a cap that stops at the hairline, a back mass and sideburns.
+ const hairStyle = opts.hairStyle ?? 'short';
+ const hatType = opts.hatType ?? null;
+ if (hairStyle !== 'bald' && hairStyle !== 'buzz') {
+ const cap = new THREE.Mesh(
+ new THREE.SphereGeometry(0.108, 20, 14, 0, Math.PI * 2, 0, hairStyle === 'bun' ? 1.18 : 1.22),
+ hairMat
+ );
+ cap.position.set(0, hairStyle === 'bun' ? 0.136 : 0.132, -0.006);
+ cap.scale.set(1.03, 1.04, 1.02);
+ cap.castShadow = true;
+ head.add(cap);
+ sphere(head, 0.098, hairMat, 0, 0.098, -0.045, [1.0, 1.05, 0.75]);
+ for (const s of [-1, 1]) {
+ box(head, 0.020, 0.060, 0.034, 0.008, hairMat, s * 0.094, 0.108, 0.028, {
+ rotation: [0.05, 0, -s * 0.05],
+ });
+ }
+ if (hairStyle === 'long') {
+ box(head, 0.052, 0.024, 0.024, 0.008, hairMat, -0.032, 0.166, 0.080, {
+ rotation: [0.22, 0.02, -0.16],
+ });
+ box(head, 0.045, 0.022, 0.024, 0.008, hairMat, 0.031, 0.168, 0.079, {
+ rotation: [0.22, 0.02, 0.20],
+ });
+ } else if (hairStyle !== 'bun') {
+ box(head, 0.098, 0.026, 0.026, 0.009, hairMat, -0.006, 0.167, 0.079, {
+ rotation: [0.24, 0.04, 0.16],
+ });
+ }
+ if (hairStyle === 'long' || hairStyle === 'bun') {
+ sphere(head, 0.075, hairMat, 0, 0.070, -0.075, [1.0, 1.25, 0.7]);
+ if (hairStyle === 'long') {
+ for (const s of [-1, 1]) {
+ capsule(head, 0.018, 0.13, hairMat, s * 0.090, 0.055, -0.045, {
+ rotation: [0.1, 0, s * 0.04],
+ });
+ }
+ }
+ }
+ if (hairStyle === 'bun') {
+ sphere(head, 0.062, hairMat, 0, 0.204, -0.072, [1, 0.94, 0.92]);
+ // Hairline of hair pulled back, not a fringe.
+ box(head, 0.160, 0.014, 0.020, 0.006, hairMat, 0, 0.180, 0.084, {
+ rotation: [-0.16, 0, 0],
+ });
+ for (const s of [-1, 1]) {
+ capsule(head, 0.010, 0.050, hairMat, s * 0.092, 0.128, 0.048, {
+ rotation: [0.1, 0, s * 0.08],
+ });
+ }
+ }
+ }
+ if (hairStyle === 'buzz') {
+ const cap = new THREE.Mesh(
+ new THREE.SphereGeometry(0.105, 20, 14, 0, Math.PI * 2, 0, 1.08),
+ hairMat
+ );
+ cap.position.set(0, 0.130, -0.004);
+ cap.scale.set(1.01, 1.02, 1.01);
+ cap.castShadow = true;
+ head.add(cap);
+ }
+
+ // A little hair at the nape shows under every hat.
+ if (hatType && hairStyle !== 'bald') {
+ sphere(head, 0.090, hairMat, 0, 0.095, -0.055, [0.95, 0.9, 0.55]);
+ }
+
+ if (hatType === 'beanie') {
+ const mat = opts.hatMat ?? cloth.rust;
+ const cap = new THREE.Mesh(
+ new THREE.SphereGeometry(0.118, 20, 14, 0, Math.PI * 2, 0, 1.55),
+ mat
+ );
+ cap.position.set(0, 0.134, -0.018);
+ cap.scale.set(1.01, 1.05, 1.04);
+ cap.castShadow = true;
+ head.add(cap);
+ part(head, new THREE.TorusGeometry(0.112, 0.016, 6, 20), mat, 0, 0.156, -0.004, {
+ rotation: [Math.PI / 2, 0, 0],
+ scale: [1, 1, 0.98],
+ });
+ sphere(head, 0.024, mat, 0, 0.252, -0.024);
+ }
+ if (hatType === 'cap') {
+ const mat = opts.hatMat ?? cloth.navy;
+ part(head, new THREE.CylinderGeometry(0.108, 0.120, 0.075, 18), mat, 0, 0.198, 0);
+ box(head, 0.176, 0.016, 0.098, 0.022, mat, 0, 0.164, 0.122, {
+ rotation: [-0.12, 0, 0],
+ scale: [1, 1, 1.02],
+ });
+ box(head, 0.200, 0.022, 0.045, 0.006, opts.hatBand ?? metal, 0, 0.170, 0.040);
+ sphere(head, 0.012, mat, 0, 0.238, 0);
+ }
+ if (hatType === 'bandana') {
+ const mat = opts.hatMat ?? rose;
+ const cap = new THREE.Mesh(
+ new THREE.SphereGeometry(0.114, 18, 12, 0, Math.PI * 2, 0, 1.38),
+ mat
+ );
+ cap.position.set(0, 0.132, 0);
+ cap.scale.set(1.03, 1.0, 1.03);
+ head.add(cap);
+ part(head, new THREE.CylinderGeometry(0.118, 0.118, 0.032, 18), mat, 0, 0.152, 0);
+ box(head, 0.070, 0.050, 0.030, 0.010, mat, 0, 0.148, -0.125, { rotation: [0.2, 0, 0] });
+ box(head, 0.030, 0.100, 0.020, 0.006, mat, 0.060, 0.095, -0.110, {
+ rotation: [0, 0, -0.5],
+ });
+ }
+ if (hatType === 'helmet') {
+ const mat = opts.hatMat ?? cloth.tealDeep;
+ const shell = new THREE.Mesh(
+ new THREE.SphereGeometry(0.132, 20, 14, 0, Math.PI * 2, 0, 1.42),
+ mat
+ );
+ shell.position.set(0, 0.125, -0.004);
+ shell.scale.set(1.0, 0.98, 1.04);
+ shell.castShadow = true;
+ head.add(shell);
+ // Visor and brow bar sit above the eyes.
+ box(head, 0.205, 0.032, 0.060, 0.012, (mats.glass ?? eye), 0, 0.160, 0.150, {
+ rotation: [-0.10, 0, 0],
+ castShadow: false,
+ });
+ box(head, 0.245, 0.022, 0.024, 0.008, metal, 0, 0.150, 0.118);
+ box(head, 0.150, 0.018, 0.060, 0.012, mat, 0, 0.184, 0.118, { rotation: [-0.20, 0, 0] });
+ // Ear pads and chin strap.
+ for (const s of [-1, 1]) {
+ box(head, 0.022, 0.062, 0.062, 0.010, mat, s * 0.106, 0.098, 0.004);
+ box(head, 0.012, 0.100, 0.012, 0.004, metal, s * 0.078, 0.055, 0.020, {
+ rotation: [0, 0, s * 0.18],
+ });
+ }
+ // Open-face shell with cheek guards and a chin bar.
+ for (const s of [-1, 1]) {
+ box(head, 0.026, 0.058, 0.060, 0.011, mat, s * 0.080, 0.046, 0.058);
+ }
+ box(head, 0.138, 0.026, 0.036, 0.012, mat, 0, 0.012, 0.082);
+ }
+ if (opts.hoodDown) {
+ // Hood pushed back: a soft roll of fabric across the shoulders.
+ box(torso, 0.235, 0.095, 0.110, 0.035, opts.hoodMat ?? top, 0, 0.468, -0.135, {
+ rotation: [0.22, 0, 0],
+ });
+ for (const s of [-1, 1]) {
+ sphere(torso, 0.055, opts.hoodMat ?? top, s * 0.095, 0.505, -0.105, [1.25, 0.85, 0.95]);
+ }
+ }
+ if (opts.hood) {
+ const shell = new THREE.Mesh(
+ new THREE.SphereGeometry(0.155, 24, 18, Math.PI * 0.740, Math.PI * 1.34, 0, Math.PI * 0.72),
+ opts.hoodMat ?? top
+ );
+ shell.position.set(0, 0.098, -0.038);
+ shell.scale.set(1.06, 1.10, 1.06);
+ shell.castShadow = true;
+ head.add(shell);
+ // Cowl around the neck.
+ part(torso, new THREE.CylinderGeometry(0.148, 0.172, 0.14, 16), opts.hoodMat ?? top, 0, 0.548, -0.030, {
+ scale: [1, 1, 0.9],
+ });
+
+ }
+
+ if (opts.scarf) {
+ part(torso, new THREE.TorusGeometry(0.106, 0.026, 6, 18), opts.scarf, 0, 0.548, 0, {
+ rotation: [Math.PI / 2, 0, 0],
+ scale: [1.02, 1, 1.08],
+ });
+ box(torso, 0.060, 0.055, 0.055, 0.018, opts.scarf, 0.070, 0.512, 0.105, {
+ rotation: [0.1, 0.2, 0.1],
+ });
+ box(torso, 0.060, 0.21, 0.026, 0.010, opts.scarf, 0.058, 0.41, 0.135, {
+ rotation: [0.06, 0, 0.05],
+ });
+ box(torso, 0.055, 0.10, 0.026, 0.010, opts.scarf, 0.070, 0.29, 0.140, {
+ rotation: [0.1, 0, 0.08],
+ });
+ }
+
+ if (opts.lanyard) {
+ for (const s of [-1, 1]) {
+ box(torso, 0.014, 0.30, 0.012, 0.004, opts.lanyard, s * 0.055, 0.36, 0.145, {
+ rotation: [0, 0, s * 0.12],
+ castShadow: false,
+ });
+ }
+ box(torso, 0.085, 0.11, 0.014, 0.006, bone, 0.0, 0.19, 0.15, { castShadow: false });
+ box(torso, 0.06, 0.035, 0.016, 0.004, rose, 0.0, 0.21, 0.155, { castShadow: false });
+ }
+
+ if (opts.backpack) {
+ const pack = new THREE.Group();
+ pack.position.set(0, 0.30, -0.19);
+ torso.add(pack);
+ box(pack, 0.33, 0.42, 0.20, 0.035, opts.backpack, 0, 0, 0);
+ box(pack, 0.27, 0.12, 0.06, 0.02, opts.backpack, 0, -0.14, 0.08);
+ box(pack, 0.10, 0.03, 0.02, 0.006, metal, 0, -0.02, 0.105);
+ for (const s of [-1, 1]) {
+ box(torso, 0.045, 0.32, 0.022, 0.008, opts.backpack, s * 0.12, 0.33, -0.005, {
+ rotation: [0.1, 0, s * 0.06],
+ });
+ }
+ }
+
+ // Arms.
+ for (const s of [-1, 1]) {
+ const shoulder = new THREE.Group();
+ shoulder.position.set(s * RIG.shoulderX, RIG.shoulderY, 0);
+ torso.add(shoulder);
+ // The rounded top of the upper-arm capsule is the deltoid; no joint ball.
+ const upperMat = sleeve === 'none' ? skin : top;
+ lathe(
+ shoulder,
+ puffer
+ ? [[0.012, 0.044], [0.040, 0.034], [0.064, 0.010], [0.072, -0.03], [0.068, -0.12], [0.058, -0.26], [0.052, -0.30]]
+ : [[0.010, 0.040], [0.034, 0.030], [0.052, 0.010], [0.058, -0.03], [0.054, -0.12], [0.046, -0.26], [0.042, -0.30]],
+ 1,
+ upperMat,
+ 0
+ );
+ if (puffer) {
+ part(shoulder, new THREE.TorusGeometry(0.059, 0.018, 4, 10), top, 0, -0.09, 0, {
+ rotation: [Math.PI / 2, 0, 0],
+ });
+ part(shoulder, new THREE.TorusGeometry(0.057, 0.018, 4, 10), top, 0, -0.19, 0, {
+ rotation: [Math.PI / 2, 0, 0],
+ });
+ }
+
+ const elbow = new THREE.Group();
+ elbow.position.y = -RIG.upperArm;
+ shoulder.add(elbow);
+ sphere(elbow, puffer ? 0.055 : 0.046, sleeve === 'long' ? top : skin, 0, 0, 0, [1, 0.9, 1]);
+ lathe(
+ elbow,
+ puffer
+ ? [[0.030, -0.27], [0.036, -0.23], [0.048, -0.10], [0.054, -0.02], [0.052, 0.0]]
+ : [[0.028, -0.27], [0.033, -0.23], [0.042, -0.10], [0.047, -0.02], [0.045, 0.0]],
+ 1,
+ sleeve === 'long' ? top : skin,
+ 0
+ );
+ if (sleeve === 'long') {
+ part(elbow, new THREE.CylinderGeometry(0.056, 0.056, 0.040, 12), trim, 0, -0.247, 0);
+ } else {
+ part(shoulder, new THREE.CylinderGeometry(0.058, 0.059, 0.022, 12), trim, 0, -0.292, 0);
+ }
+
+ const wrist = new THREE.Group();
+ wrist.position.y = -RIG.foreArm + 0.01;
+ elbow.add(wrist);
+ const handMat = opts.glove ?? skin;
+ box(wrist, 0.070, 0.078, 0.054, 0.020, handMat, 0, -0.040, 0.002);
+ // Fingers as one soft block, with two grooves, and a thumb across the side.
+ box(wrist, 0.062, 0.048, 0.046, 0.016, handMat, 0, -0.088, 0.010);
+ for (let f = -1; f <= 1; f += 2) {
+ box(wrist, 0.004, 0.036, 0.006, 0.001, opts.glove ? metal : shade, f * 0.013, -0.092, 0.032, {
+ castShadow: false,
+ });
+ }
+ capsule(
+ wrist,
+ 0.014,
+ 0.030,
+ handMat,
+ s * 0.036,
+ -0.052,
+ 0.020,
+ { rotation: [0.5, 0, -s * 0.5] }
+ );
+
+ J[s < 0 ? 'shoulderL' : 'shoulderR'] = shoulder;
+ J[s < 0 ? 'elbowL' : 'elbowR'] = elbow;
+ J[s < 0 ? 'wristL' : 'wristR'] = wrist;
+ }
+
+ // Legs.
+ for (const s of [-1, 1]) {
+ const hip = new THREE.Group();
+ hip.position.set(s * RIG.hipX, -0.04, 0);
+ pelvis.add(hip);
+ sphere(hip, 0.068, bottom, 0, 0, 0, [0.95, 0.76, 0.95]);
+ lathe(
+ hip,
+ loose
+ ? [[0.066, -0.42], [0.074, -0.38], [0.090, -0.24], [0.104, -0.08], [0.100, 0.03]]
+ : [[0.060, -0.42], [0.067, -0.38], [0.082, -0.24], [0.094, -0.08], [0.090, 0.03]],
+ 1,
+ bottom,
+ 0
+ );
+
+ const knee = new THREE.Group();
+ knee.position.y = -RIG.thigh;
+ hip.add(knee);
+ sphere(knee, 0.062, bottom, 0, 0, 0, [0.95, 0.82, 0.95]);
+ lathe(
+ knee,
+ loose
+ ? [[0.044, -0.40], [0.052, -0.36], [0.078, -0.18], [0.073, -0.08], [0.068, 0.0]]
+ : [[0.040, -0.40], [0.046, -0.36], [0.068, -0.18], [0.064, -0.08], [0.060, 0.0]],
+ 1,
+ bottom,
+ 0
+ );
+ // Cuff.
+ part(knee, new THREE.CylinderGeometry(loose ? 0.082 : 0.073, loose ? 0.082 : 0.073, 0.04, 10), bottom, 0, -0.36, 0);
+
+ const ankle = new THREE.Group();
+ ankle.position.y = -RIG.shin;
+ knee.add(ankle);
+ box(ankle, 0.105, 0.07, 0.215, 0.03, shoe, 0, 0.017, 0.045);
+ box(ankle, 0.098, 0.04, 0.055, 0.016, shoe, 0, 0.006, 0.158);
+ // Sole.
+ box(ankle, 0.108, 0.018, 0.225, 0.006, eye, 0, -0.018, 0.045);
+
+ J[s < 0 ? 'hipL' : 'hipR'] = hip;
+ J[s < 0 ? 'kneeL' : 'kneeR'] = knee;
+ J[s < 0 ? 'ankleL' : 'ankleR'] = ankle;
+ }
+
+ if (opts.scale) root.scale.set(opts.scale[0], opts.scale[1], opts.scale[2]);
+ return { group: root, joints: J, opts };
+}
+
+export function setPose(p, pose = {}) {
+ const J = p.joints;
+ const r = (obj, v) => {
+ if (!obj) return;
+ obj.rotation.set(v?.[0] ?? 0, v?.[1] ?? 0, v?.[2] ?? 0);
+ };
+ r(J.torso, pose.torso);
+ r(J.head, pose.head);
+ r(J.shoulderL, pose.shoulderL);
+ r(J.shoulderR, pose.shoulderR);
+ r(J.elbowL, pose.elbowL);
+ r(J.elbowR, pose.elbowR);
+ r(J.wristL, pose.wristL);
+ r(J.wristR, pose.wristR);
+ r(J.hipL, pose.hipL);
+ r(J.hipR, pose.hipR);
+ r(J.kneeL, pose.kneeL);
+ r(J.kneeR, pose.kneeR);
+ r(J.ankleL, pose.ankleL);
+ r(J.ankleR, pose.ankleR);
+ if (pose.pelvis) r(J.pelvis, pose.pelvis);
+}
+
+export function blendPose(base, add) {
+ const out = {};
+ for (const k of new Set([...Object.keys(base), ...Object.keys(add)])) {
+ const a = base[k] ?? [0, 0, 0];
+ const b = add[k] ?? [0, 0, 0];
+ out[k] = [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
+ }
+ return out;
+}
+
+export function mixPose(a, b, k) {
+ const out = {};
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
+ for (const key of keys) {
+ const av = a[key] ?? [0, 0, 0];
+ const bv = b[key] ?? [0, 0, 0];
+ out[key] = [
+ av[0] + (bv[0] - av[0]) * k,
+ av[1] + (bv[1] - av[1]) * k,
+ av[2] + (bv[2] - av[2]) * k,
+ ];
+ }
+ return out;
+}
diff --git a/templates/peopleModel.js b/templates/peopleModel.js
new file mode 100644
index 0000000..8a897ba
--- /dev/null
+++ b/templates/peopleModel.js
@@ -0,0 +1,422 @@
+import * as THREE from 'three';
+import { roundedBoxGeometry } from '../core/geometry.js';
+
+/**
+ * Diorama proportions: a 1.69 m figure with a tapered lathe torso and
+ * pelvis, chunky limbs, and joint fillers so a bend never opens a gap.
+ * The figure faces +Z. Positive hip/shoulder X rotation swings a limb
+ * backwards; negative swings it forwards.
+ */
+export const RIG = {
+ hipY: 0.86,
+ hipX: 0.10,
+ thigh: 0.42,
+ shin: 0.40,
+ shoulderY: 0.415,
+ shoulderX: 0.182,
+ upperArm: 0.30,
+ foreArm: 0.27,
+ headY: 0.584,
+};
+
+function part(parent, geo, mat, x, y, z, opts = {}) {
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ if (opts.rotation) m.rotation.set(...opts.rotation);
+ if (opts.scale) m.scale.set(...opts.scale);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ parent.add(m);
+ return m;
+}
+
+function capsule(parent, r, len, mat, x, y, z, opts = {}) {
+ const geo = new THREE.CapsuleGeometry(r, Math.max(0.01, len), 8, 18);
+ return part(parent, geo, mat, x, y, z, opts);
+}
+
+function sphere(parent, r, mat, x, y, z, scale = [1, 1, 1], opts = {}) {
+ return part(parent, new THREE.SphereGeometry(r, 24, 18), mat, x, y, z, { ...opts, scale });
+}
+
+function box(parent, w, h, d, r, mat, x, y, z, opts = {}) {
+ const geo = roundedBoxGeometry(w, h, d, Math.min(r, Math.min(w, h, d) * 0.48), 3);
+ return part(parent, geo, mat, x, y, z, opts);
+}
+
+/** Lathe a side profile, then flatten it front-to-back. */
+function lathe(parent, profile, flatten, mat, y, x = 0, z = 0) {
+ const pts = profile.map(([r, h]) => new THREE.Vector2(r, h));
+ const geo = new THREE.LatheGeometry(pts, 26);
+ geo.scale(1, 1, flatten);
+ const m = new THREE.Mesh(geo, mat);
+ m.position.set(x, y, z);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ parent.add(m);
+ return m;
+}
+
+const TORSO = [
+ [0.135, -0.02],
+ [0.165, 0.09],
+ [0.190, 0.22],
+ [0.198, 0.33],
+ [0.196, 0.40],
+ [0.168, 0.47],
+ [0.090, 0.53],
+ [0.062, 0.56],
+];
+
+const PELVIS = [
+ [0.105, -0.24],
+ [0.150, -0.17],
+ [0.176, -0.07],
+ [0.180, 0.04],
+ [0.168, 0.12],
+];
+
+const SHORTS = [
+ [0.150, -0.30],
+ [0.182, -0.20],
+ [0.190, -0.08],
+ [0.188, 0.06],
+ [0.178, 0.12],
+];
+
+const BRIEFS = [
+ [0.100, -0.23],
+ [0.152, -0.18],
+ [0.184, -0.06],
+ [0.183, 0.07],
+ [0.172, 0.12],
+];
+
+export function buildPerson(mats, opts = {}) {
+ const skin = opts.skin ?? mats.skinTones[0];
+ const hairMat = opts.hair ?? mats.hair[0];
+ const suit = opts.suit ?? mats.suits.coral;
+ const suitStyle = opts.suitStyle ?? 'onepiece';
+ // A darker clone of the skin for creases, lids and seams.
+ const shade = skin.clone();
+ shade.color = skin.color.clone().multiplyScalar(0.86);
+ const root = new THREE.Group();
+ const J = {};
+
+ const pelvis = new THREE.Group();
+ pelvis.position.y = RIG.hipY;
+ root.add(pelvis);
+ J.pelvis = pelvis;
+
+ // Hips, always skin; swimwear is layered over them.
+ lathe(pelvis, PELVIS, 0.86, suitStyle === 'trunks' || suitStyle === 'briefs' ? suit : skin, 0);
+
+ const torso = new THREE.Group();
+ torso.position.y = 0.02;
+ pelvis.add(torso);
+ J.torso = torso;
+
+ const torsoMat = suitStyle === 'trunks' ? skin : suit;
+ lathe(torso, TORSO, 0.72, torsoMat, 0);
+
+ if (suitStyle === 'onepiece' || suitStyle === 'briefs') {
+ if (opts.suitAccent) {
+ const band = new THREE.Mesh(
+ new THREE.CylinderGeometry(0.201, 0.200, 0.06, 22),
+ opts.suitAccent
+ );
+ band.position.set(0, 0.315, 0);
+ band.scale.z = 0.735;
+ band.castShadow = true;
+ torso.add(band);
+ }
+ lathe(pelvis, BRIEFS, 0.88, suit, 0);
+
+ } else if (suitStyle === 'trunks') {
+ lathe(pelvis, SHORTS, 0.88, suit, 0);
+ const band = new THREE.Mesh(
+ new THREE.CylinderGeometry(0.187, 0.19, 0.045, 22),
+ opts.suitAccent ?? suit
+ );
+ band.position.set(0, 0.015, 0);
+ band.scale.z = 0.885;
+ band.castShadow = true;
+ pelvis.add(band);
+ for (const s of [-1, 1]) {
+ box(pelvis, 0.024, 0.20, 0.05, 0.01, opts.suitAccent ?? suit, s * 0.185, -0.12, 0.02);
+ }
+ box(pelvis, 0.07, 0.028, 0.02, 0.008, opts.suitAccent ?? suit, 0, 0.05, 0.155);
+ }
+
+ // Collarbones and chest planes on bare torsos.
+ if (suitStyle === 'trunks' || suitStyle === 'briefs') {
+ for (const s of [-1, 1]) {
+ capsule(torso, 0.011, 0.10, shade, s * 0.095, 0.455, 0.098, {
+ rotation: [0, 0, s * 1.32],
+ castShadow: false,
+ });
+ sphere(torso, 0.062, skin, s * 0.078, 0.352, 0.10, [0.95, 0.72, 0.42]);
+ }
+ box(torso, 0.012, 0.012, 0.006, 0.005, shade, 0, 0.075, 0.148, { castShadow: false });
+ }
+ if (opts.suitAccent && (suitStyle === 'onepiece' || suitStyle === 'briefs')) {
+ box(torso, 0.034, 0.030, 0.008, 0.008, opts.suitAccent, -0.085, 0.355, 0.132, {
+ castShadow: false,
+ });
+ }
+
+ // Neck and head.
+ capsule(torso, 0.057, 0.075, skin, 0, 0.545, 0);
+ const head = new THREE.Group();
+ head.position.y = RIG.headY;
+ torso.add(head);
+ J.head = head;
+
+ sphere(head, 0.115, skin, 0, 0.105, 0.004, [1.0, 1.1, 0.96]);
+ sphere(head, 0.089, skin, 0, 0.028, 0.018, [0.94, 0.78, 0.92]);
+
+ // Ears and a soft nose wedge keep the head from reading as a ball.
+ for (const s of [-1, 1]) {
+ sphere(head, 0.028, skin, s * 0.112, 0.10, 0.0, [0.55, 1.0, 0.85]);
+ }
+ box(head, 0.038, 0.054, 0.044, 0.018, skin, 0, 0.090, 0.106, {
+ rotation: [-0.12, 0, 0],
+ });
+
+ if (!opts.goggles) {
+ for (const s of [-1, 1]) {
+ sphere(head, 0.017, mats.eye, s * 0.044, 0.115, 0.104, [1.0, 1.15, 0.5], {
+ castShadow: false,
+ });
+ box(head, 0.05, 0.011, 0.012, 0.004, hairMat, s * 0.047, 0.146, 0.102, {
+ rotation: [0, 0, s * 0.12],
+ });
+ }
+ box(head, 0.052, 0.013, 0.012, 0.005, mats.mouth, 0, 0.045, 0.106);
+ // Fine face detail: lids, cheek planes, chin, nostrils, lower lip.
+ for (const s of [-1, 1]) {
+ box(head, 0.046, 0.007, 0.010, 0.003, shade, s * 0.044, 0.101, 0.104, {
+ rotation: [0, 0, s * 0.10],
+ castShadow: false,
+ });
+ sphere(head, 0.030, skin, s * 0.060, 0.078, 0.078, [0.95, 0.62, 0.55]);
+ }
+ box(head, 0.046, 0.026, 0.036, 0.012, skin, 0, 0.026, 0.094);
+ box(head, 0.038, 0.009, 0.012, 0.004, shade, 0, 0.034, 0.106, { castShadow: false });
+ for (const s of [-1, 1]) {
+ box(head, 0.008, 0.007, 0.008, 0.003, shade, s * 0.013, 0.060, 0.132, { castShadow: false });
+ }
+ }
+
+ // Swim cap sits over a bald head.
+ if (opts.cap) {
+ const capMesh = new THREE.Mesh(
+ new THREE.SphereGeometry(0.121, 24, 16, 0, Math.PI * 2, 0, 1.62),
+ opts.cap
+ );
+ capMesh.position.set(0, 0.105, 0);
+ capMesh.scale.set(1.02, 1.06, 1.0);
+ capMesh.castShadow = true;
+ head.add(capMesh);
+ }
+
+ // Hair: a rounded cap over the skull, with optional length at the back.
+ if (opts.hairStyle !== 'bald' && !opts.cap) {
+ const style = opts.hairStyle ?? 'short';
+ const capMat = opts.cap ?? hairMat;
+ const theta = style === 'buzz' ? 1.35 : 1.85;
+ const cap = new THREE.Mesh(
+ new THREE.SphereGeometry(0.121, 24, 16, 0, Math.PI * 2, 0, theta),
+ capMat
+ );
+ cap.position.set(0, 0.105, 0);
+ cap.scale.set(1.02, 1.06, 1.0);
+ cap.castShadow = true;
+ head.add(cap);
+ // Fringe across the forehead.
+ box(head, 0.20, 0.055, 0.05, 0.02, capMat, 0, 0.175, 0.093, {
+ rotation: [0.18, 0, 0],
+ });
+
+ if (style === 'long' || style === 'bun') {
+ sphere(head, 0.10, capMat, 0, 0.075, -0.055, [1.0, 1.15, 0.7]);
+ for (const s of [-1, 1]) {
+ sphere(head, 0.05, capMat, s * 0.098, 0.055, -0.02, [0.8, 1.5, 0.9]);
+ }
+ }
+ if (style === 'bun') {
+ sphere(head, 0.07, capMat, 0, 0.165, -0.10, [1, 0.95, 0.9]);
+ }
+ }
+
+ if (opts.sunglasses) {
+ box(head, 0.175, 0.05, 0.024, 0.011, mats.goggle, 0, 0.118, 0.098);
+ }
+ if (opts.goggles) {
+ for (const s of [-1, 1]) {
+ box(head, 0.072, 0.048, 0.026, 0.012, mats.goggle, s * 0.05, 0.118, 0.10);
+ }
+ box(head, 0.045, 0.02, 0.024, 0.008, mats.goggleStrap, 0, 0.118, 0.104);
+ box(head, 0.235, 0.03, 0.235, 0.012, mats.goggleStrap, 0, 0.135, -0.004);
+ }
+
+ if (opts.hat) {
+ const hat = new THREE.Group();
+ hat.position.y = 0.192;
+ hat.rotation.x = -0.05;
+ const brim = new THREE.Mesh(new THREE.CylinderGeometry(0.20, 0.212, 0.018, 24), opts.hat);
+ brim.castShadow = true;
+ hat.add(brim);
+ const crown = new THREE.Mesh(new THREE.CylinderGeometry(0.100, 0.120, 0.115, 20), opts.hat);
+ crown.position.y = 0.062;
+ crown.castShadow = true;
+ hat.add(crown);
+ const band = new THREE.Mesh(
+ new THREE.CylinderGeometry(0.112, 0.12, 0.026, 20),
+ opts.hatBand ?? mats.suits.navy
+ );
+ band.position.y = 0.016;
+ hat.add(band);
+ head.add(hat);
+ }
+
+ // Arms: joint spheres sit just inside the limb radius so bends stay sealed.
+ for (const s of [-1, 1]) {
+ const shoulder = new THREE.Group();
+ shoulder.position.set(s * RIG.shoulderX, RIG.shoulderY, 0);
+ torso.add(shoulder);
+ sphere(shoulder, 0.062, skin, 0, 0, 0, [1, 0.94, 1]);
+ capsule(shoulder, 0.057, 0.166, skin, 0, -RIG.upperArm / 2, 0);
+
+ const elbow = new THREE.Group();
+ elbow.position.y = -RIG.upperArm;
+ shoulder.add(elbow);
+ sphere(elbow, 0.049, skin, 0, 0, 0);
+ capsule(elbow, 0.05, 0.15, skin, 0, -RIG.foreArm / 2, 0);
+
+ const wrist = new THREE.Group();
+ wrist.position.y = -RIG.foreArm + 0.01;
+ elbow.add(wrist);
+ box(wrist, 0.072, 0.098, 0.058, 0.024, skin, 0, -0.045, 0.004);
+ box(wrist, 0.026, 0.058, 0.03, 0.012, skin, s * 0.042, -0.032, 0.014, {
+ rotation: [0, 0, -s * 0.55],
+ });
+
+ // Knuckle grooves and an optional band/watch at the wrist.
+ for (let f = 0; f < 3; f++) {
+ box(wrist, 0.006, 0.052, 0.012, 0.002, shade, -0.022 + f * 0.022, -0.062, 0.030, {
+ castShadow: false,
+ });
+ }
+ if (opts.band) {
+ const strap = new THREE.Mesh(new THREE.CylinderGeometry(0.060, 0.060, 0.024, 16), opts.band);
+ strap.position.set(0, 0.008, 0.0);
+ strap.castShadow = true;
+ wrist.add(strap);
+ }
+
+ if (suitStyle === 'onepiece' && opts.suitSleeve) {
+ capsule(shoulder, 0.066, 0.09, suit, 0, -0.065, 0);
+ }
+
+ J[s < 0 ? 'shoulderL' : 'shoulderR'] = shoulder;
+ J[s < 0 ? 'elbowL' : 'elbowR'] = elbow;
+ J[s < 0 ? 'wristL' : 'wristR'] = wrist;
+ }
+
+ // Legs.
+ for (const s of [-1, 1]) {
+ const hip = new THREE.Group();
+ hip.position.set(s * RIG.hipX, -0.04, 0);
+ pelvis.add(hip);
+ sphere(hip, 0.078, suitStyle === 'trunks' || suitStyle === 'briefs' ? suit : skin, 0, 0, 0);
+ capsule(hip, 0.086, 0.224, skin, 0, -RIG.thigh / 2, 0);
+
+ const knee = new THREE.Group();
+ knee.position.y = -RIG.thigh;
+ hip.add(knee);
+ sphere(knee, 0.069, skin, 0, 0, 0);
+ capsule(knee, 0.068, 0.244, skin, 0, -RIG.shin / 2, 0);
+
+ const ankle = new THREE.Group();
+ ankle.position.y = -RIG.shin;
+ knee.add(ankle);
+ box(ankle, 0.105, 0.07, 0.215, 0.03, opts.shoe ?? skin, 0, 0.017, 0.045);
+ box(ankle, 0.098, 0.04, 0.055, 0.016, opts.shoe ?? skin, 0, 0.006, 0.158);
+
+ sphere(knee, 0.048, skin, 0, -0.012, 0.040, [1.0, 1.05, 0.62]);
+ for (let f = 0; f < 2; f++) {
+ box(ankle, 0.007, 0.036, 0.05, 0.003, shade, -0.014 + f * 0.026, 0.010, 0.168, {
+ castShadow: false,
+ });
+ }
+ box(ankle, 0.030, 0.018, 0.026, 0.008, shade, -0.030, 0.020, 0.196, { castShadow: false });
+
+ J[s < 0 ? 'hipL' : 'hipR'] = hip;
+ J[s < 0 ? 'kneeL' : 'kneeR'] = knee;
+ J[s < 0 ? 'ankleL' : 'ankleR'] = ankle;
+ }
+
+ return { group: root, joints: J, opts };
+}
+
+export function setPose(p, pose = {}) {
+ const J = p.joints;
+ const r = (obj, v) => {
+ if (!obj) return;
+ obj.rotation.set(v?.[0] ?? 0, v?.[1] ?? 0, v?.[2] ?? 0);
+ };
+ r(J.torso, pose.torso);
+ r(J.head, pose.head);
+ r(J.shoulderL, pose.shoulderL);
+ r(J.shoulderR, pose.shoulderR);
+ r(J.elbowL, pose.elbowL);
+ r(J.elbowR, pose.elbowR);
+ r(J.wristL, pose.wristL);
+ r(J.wristR, pose.wristR);
+ r(J.hipL, pose.hipL);
+ r(J.hipR, pose.hipR);
+ r(J.kneeL, pose.kneeL);
+ r(J.kneeR, pose.kneeR);
+ r(J.ankleL, pose.ankleL);
+ r(J.ankleR, pose.ankleR);
+ if (pose.pelvis) r(J.pelvis, pose.pelvis);
+}
+
+export function easePose(p, pose, k) {
+ const J = p.joints;
+ const apply = (obj, v) => {
+ if (!obj) return;
+ const tx = v?.[0] ?? 0;
+ const ty = v?.[1] ?? 0;
+ const tz = v?.[2] ?? 0;
+ obj.rotation.x += (tx - obj.rotation.x) * k;
+ obj.rotation.y += (ty - obj.rotation.y) * k;
+ obj.rotation.z += (tz - obj.rotation.z) * k;
+ };
+ apply(J.torso, pose.torso);
+ apply(J.head, pose.head);
+ apply(J.shoulderL, pose.shoulderL);
+ apply(J.shoulderR, pose.shoulderR);
+ apply(J.elbowL, pose.elbowL);
+ apply(J.elbowR, pose.elbowR);
+ apply(J.wristL, pose.wristL);
+ apply(J.wristR, pose.wristR);
+ apply(J.hipL, pose.hipL);
+ apply(J.hipR, pose.hipR);
+ apply(J.kneeL, pose.kneeL);
+ apply(J.kneeR, pose.kneeR);
+ apply(J.ankleL, pose.ankleL);
+ apply(J.ankleR, pose.ankleR);
+ if (pose.pelvis) apply(J.pelvis, pose.pelvis);
+}
+
+export function blendPose(base, add) {
+ const out = {};
+ for (const k of new Set([...Object.keys(base), ...Object.keys(add)])) {
+ const a = base[k] ?? [0, 0, 0];
+ const b = add[k] ?? [0, 0, 0];
+ out[k] = [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
+ }
+ return out;
+}
diff --git a/templates/poses.js b/templates/poses.js
new file mode 100644
index 0000000..a6eeb06
--- /dev/null
+++ b/templates/poses.js
@@ -0,0 +1,313 @@
+import { lerp } from '../config.js';
+
+/**
+ * The pose library. Every entry is a full set of joint angles, in radians, for
+ * the rig in peopleModel.js. Poses are absolute, never deltas: a partial pose
+ * leaves the previous value on any joint it does not name, and the error
+ * accumulates the moment two poses are blended in a loop.
+ *
+ * Joint order in every entry is [x, y, z]:
+ * torso head shoulderL/R elbowL/R wristL/R hipL/R kneeL/R ankleL/R
+ *
+ * Signs, which are the whole game:
+ * +hip X swings the thigh backward, -hip X forward
+ * +knee X bends the heel backward, a negative knee hyperextends
+ * +shoulder X swings the arm backward, -shoulder X forward
+ * -elbow X folds the forearm toward the face
+ */
+
+export const STAND = {
+ torso: [0.03, 0, 0],
+ head: [0, 0, 0],
+ shoulderL: [0.02, 0, -0.1],
+ shoulderR: [0.02, 0, 0.1],
+ elbowL: [-0.17, 0, 0],
+ elbowR: [-0.17, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [0, 0, 0.02],
+ hipR: [0, 0, -0.02],
+ kneeL: [0.05, 0, 0],
+ kneeR: [0.05, 0, 0],
+ ankleL: [-0.03, 0, 0],
+ ankleR: [-0.03, 0, 0],
+};
+
+/** Seated: thighs forward and level, shins down, torso a touch back. */
+export const SEATED = {
+ torso: [0.05, 0, 0],
+ head: [0, 0, 0],
+ shoulderL: [-0.72, 0, -0.14],
+ shoulderR: [-0.72, 0, 0.14],
+ elbowL: [-0.52, 0, 0],
+ elbowR: [-0.52, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-1.5, 0, 0.05],
+ hipR: [-1.5, 0, -0.05],
+ kneeL: [0.52, 0, 0],
+ kneeR: [0.52, 0, 0],
+ ankleL: [0.18, 0, 0],
+ ankleR: [0.18, 0, 0],
+};
+
+/** Perched on the seat edge, legs swung out of the door aperture. */
+export const LEGS_OUT = {
+ torso: [0.2, 0, 0],
+ head: [-0.06, 0, 0],
+ shoulderL: [-0.62, 0, -0.3],
+ shoulderR: [-0.55, 0, 0.34],
+ elbowL: [-0.72, 0, 0],
+ elbowR: [-0.6, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.88, 0, 0.14],
+ hipR: [-0.72, 0, -0.1],
+ kneeL: [0.62, 0, 0],
+ kneeR: [0.48, 0, 0],
+ ankleL: [-0.16, 0, 0],
+ ankleR: [-0.12, 0, 0],
+};
+
+/**
+ * Climbing in, beat 1: standing square to the open door, near hand up to the
+ * roof edge, weight already moving onto the front foot.
+ */
+export const REACH = {
+ torso: [0.14, 0.04, 0.04],
+ head: [-0.1, 0.12, 0],
+ shoulderL: [-0.42, 0, -0.26],
+ shoulderR: [-1.52, 0, 0.24],
+ elbowL: [-0.62, 0, 0],
+ elbowR: [-0.48, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [-0.25, 0, 0],
+ hipL: [-0.22, 0, 0.06],
+ hipR: [-0.1, 0, -0.06],
+ kneeL: [0.4, 0, 0],
+ kneeR: [0.26, 0, 0],
+ ankleL: [-0.16, 0, 0],
+ ankleR: [-0.12, 0, 0],
+};
+
+/**
+ * Climbing in, beat 2: knees deep, hips dropping to cushion height just outside
+ * the sill, head still clear of the roof, one hand braced on the door.
+ */
+export const CROUCH_IN = {
+ torso: [0.52, 0.1, 0.02],
+ head: [-0.34, 0.1, 0],
+ shoulderL: [-0.92, 0, -0.26],
+ shoulderR: [-1.3, 0, 0.26],
+ elbowL: [-1.05, 0, 0],
+ elbowR: [-0.72, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.72, 0, 0.12],
+ hipR: [-0.66, 0, -0.1],
+ kneeL: [1.12, 0, 0],
+ kneeR: [1.04, 0, 0],
+ ankleL: [-0.34, 0, 0],
+ ankleR: [-0.3, 0, 0],
+};
+
+/**
+ * Climbing in, beat 3: perched on the seat edge, both feet still on the road,
+ * torso folded under the roof line.
+ */
+export const SIT_EDGE = {
+ torso: [0.46, 0.12, 0],
+ head: [-0.26, 0.1, 0],
+ shoulderL: [-0.55, 0, -0.3],
+ shoulderR: [-0.95, 0, 0.3],
+ elbowL: [-0.95, 0, 0],
+ elbowR: [-0.85, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-1.12, 0, 0.11],
+ hipR: [-1.04, 0, -0.09],
+ kneeL: [1.12, 0, 0],
+ kneeR: [1.06, 0, 0],
+ ankleL: [-0.02, 0, 0],
+ ankleR: [-0.04, 0, 0],
+};
+
+/**
+ * Climbing in, beat 4: hips on the cushion, knees up and feet swinging in over
+ * the sill.
+ */
+export const LEGS_IN = {
+ torso: [0.36, 0.16, 0],
+ head: [-0.16, 0.1, 0],
+ shoulderL: [-0.5, 0, -0.28],
+ shoulderR: [-0.62, 0, 0.28],
+ elbowL: [-1.1, 0, 0],
+ elbowR: [-1.05, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-1.46, 0, 0.1],
+ hipR: [-1.4, 0, -0.1],
+ kneeL: [1.58, 0, 0],
+ kneeR: [1.5, 0, 0],
+ ankleL: [0.16, 0, 0],
+ ankleR: [0.14, 0, 0],
+};
+
+/** Feet planted, knees deep, one hand on the door frame. */
+export const DUCK = {
+ torso: [0.46, 0, 0],
+ head: [-0.26, 0, 0],
+ shoulderL: [-0.8, 0, -0.26],
+ shoulderR: [-0.3, 0, 0.3],
+ elbowL: [-0.95, 0, 0],
+ elbowR: [-0.45, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.72, 0, 0.16],
+ hipR: [-0.58, 0, -0.12],
+ kneeL: [1.38, 0, 0],
+ kneeR: [1.2, 0, 0],
+ ankleL: [-0.42, 0, 0],
+ ankleR: [-0.34, 0, 0],
+};
+
+/** Feet planted, squatting, both hands free: the working crouch. */
+export const CROUCH = {
+ torso: [0.3, 0, 0],
+ head: [-0.16, 0, 0],
+ shoulderL: [-0.3, 0, -0.22],
+ shoulderR: [-0.26, 0, 0.24],
+ elbowL: [-0.7, 0, 0],
+ elbowR: [-0.62, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.98, 0, 0.14],
+ hipR: [-0.86, 0, -0.12],
+ kneeL: [1.52, 0, 0],
+ kneeR: [1.38, 0, 0],
+ ankleL: [-0.46, 0, 0],
+ ankleR: [-0.4, 0, 0],
+};
+
+/** Both arms out and level: aiming a weapon, a hose, a torch. */
+export const REACH_FWD = {
+ ...STAND,
+ torso: [0.08, 0, 0],
+ shoulderL: [-1.34, 0, -0.12],
+ shoulderR: [-1.3, 0, 0.1],
+ elbowL: [-0.3, 0, 0],
+ elbowR: [-0.22, 0, 0],
+ hipL: [-0.16, 0, 0.06],
+ hipR: [0.1, 0, -0.08],
+ kneeL: [0.34, 0, 0],
+ kneeR: [0.22, 0, 0],
+ ankleL: [-0.16, 0, 0],
+ ankleR: [-0.06, 0, 0],
+};
+
+/** Alias kept for scenes that read better with the old name. */
+export const AIM = REACH_FWD;
+
+/** Arms bent up, carrying something against the chest. */
+export const CARRY = {
+ shoulderR: [0.14, 0, 0.12],
+ elbowR: [-0.12, 0, 0],
+ shoulderL: [-0.1, 0, -0.12],
+ elbowL: [-0.3, 0, 0],
+};
+
+/** Wind-up and release for throwing a weight into a container. */
+export const THROW_BACK = {
+ ...STAND,
+ torso: [0.04, -0.26, 0],
+ head: [0, -0.2, 0],
+ shoulderR: [0.95, 0, 0.22],
+ elbowR: [-1.15, 0, 0],
+ shoulderL: [-0.45, 0, -0.2],
+ elbowL: [-0.55, 0, 0],
+ hipL: [-0.12, 0, 0.05],
+ hipR: [0.14, 0, -0.05],
+};
+
+export const THROW_FWD = {
+ ...STAND,
+ torso: [0.22, 0.2, 0],
+ head: [-0.05, 0.12, 0],
+ shoulderR: [-1.55, 0, 0.1],
+ elbowR: [-0.18, 0, 0],
+ shoulderL: [0.2, 0, -0.28],
+ elbowL: [-0.85, 0, 0],
+ hipL: [0.1, 0, 0.05],
+ hipR: [-0.16, 0, -0.05],
+ kneeL: [0.24, 0, 0],
+ kneeR: [0.18, 0, 0],
+};
+
+/**
+ * Component-wise blend. Missing joints fall back to zero, which is why every
+ * pose above names the full set.
+ */
+export function mixPose(a, b, k) {
+ const out = {};
+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
+ const av = a[key] ?? [0, 0, 0];
+ const bv = b[key] ?? [0, 0, 0];
+ out[key] = [
+ lerp(av[0] ?? 0, bv[0] ?? 0, k),
+ lerp(av[1] ?? 0, bv[1] ?? 0, k),
+ lerp(av[2] ?? 0, bv[2] ?? 0, k),
+ ];
+ }
+ return out;
+}
+
+/**
+ * Walk cycle. Phase is driven by distance travelled, not by time, so the feet
+ * never skate: speed = 2 * legLength * sin(amp) * phaseRate / PI.
+ *
+ * opts: amp (hip), armAmp, lean, kneeBase, carry (keeps the right arm occupied)
+ */
+export function walkPose(phase, opts = {}) {
+ const amp = opts.amp ?? 0.32;
+ const armAmp = opts.armAmp ?? 0.44;
+ const lean = opts.lean ?? 0.05;
+ const kneeBase = opts.kneeBase ?? 0.06;
+ const swing = Math.sin(phase);
+ const cs = Math.cos(phase);
+ const kneeL = kneeBase + 0.46 * Math.max(0, -cs) + 0.22 * Math.max(0, swing);
+ const kneeR = kneeBase + 0.46 * Math.max(0, cs) + 0.22 * Math.max(0, -swing);
+ const p = {
+ torso: [lean, swing * 0.05, 0],
+ head: [0, -swing * 0.04, 0],
+ shoulderL: [-swing * armAmp, 0, -0.09],
+ shoulderR: [swing * armAmp, 0, 0.09],
+ elbowL: [-0.16 - Math.max(0, swing) * 0.28, 0, 0],
+ elbowR: [-0.16 - Math.max(0, -swing) * 0.28, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [swing * amp, 0, 0.03],
+ hipR: [-swing * amp, 0, -0.03],
+ kneeL: [kneeL, 0, 0],
+ kneeR: [kneeR, 0, 0],
+ ankleL: [-kneeL * 0.32, 0, 0],
+ ankleR: [-kneeR * 0.32, 0, 0],
+ };
+ if (opts.carry) {
+ p.shoulderR = [0.1 + swing * 0.06, 0, 0.12];
+ p.elbowR = [-0.14, 0, 0];
+ p.shoulderL = [-swing * armAmp * 1.15, 0, -0.1];
+ }
+ return p;
+}
+
+/** Same cycle, driven harder: longer stride, forward lean, elbows tucked. */
+export function runPose(phase, opts = {}) {
+ const p = walkPose(phase, { amp: 0.52, armAmp: 0.72, lean: 0.26, kneeBase: 0.12, ...opts });
+ const bob = Math.abs(Math.cos(phase));
+ p.torso = [0.26 + bob * 0.03, p.torso[1], 0];
+ p.elbowL = [-0.75, 0, 0];
+ p.elbowR = opts.carry ? [-0.18, 0, 0] : [-0.75, 0, 0];
+ p.shoulderL = [-Math.sin(phase) * 0.8, 0, -0.14];
+ p.shoulderR = opts.carry ? [0.16, 0, 0.14] : [Math.sin(phase) * 0.8, 0, 0.14];
+ return p;
+}
diff --git a/templates/post.js b/templates/post.js
new file mode 100644
index 0000000..ad963c9
--- /dev/null
+++ b/templates/post.js
@@ -0,0 +1,193 @@
+import * as THREE from 'three';
+import { PALETTE_RGB } from './palette.js';
+
+const VERT = /* glsl */ `
+out vec2 vUv;
+void main() {
+ vUv = position.xy * 0.5 + 0.5;
+ gl_Position = vec4(position.xy, 0.0, 1.0);
+}
+`;
+
+const FRAG = /* glsl */ `
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D tScene;
+uniform vec2 uResolution;
+uniform vec3 uPalette[64];
+uniform float uDither;
+
+float bayer2(vec2 a) {
+ a = floor(a);
+ return fract(a.x * 0.5 + a.y * a.y * 0.75);
+}
+float bayer4(vec2 a) {
+ return bayer2(0.5 * a) * 0.25 + bayer2(a);
+}
+float bayer8(vec2 a) {
+ return bayer4(0.5 * a) * 0.25 + bayer4(a);
+}
+float luma(vec3 c) {
+ return dot(c, vec3(0.299, 0.587, 0.114));
+}
+vec3 fetch(vec2 uv) {
+ return texture(tScene, uv).rgb;
+}
+float fetchA(vec2 uv) {
+ return texture(tScene, uv).a;
+}
+
+void main() {
+ vec2 px = 1.0 / uResolution;
+ vec4 centre = texture(tScene, vUv);
+
+ // Gather a small disc of coverage for the cut-out rim. The alpha buffer is
+ // opaque everywhere inside the diorama, so this only bites at the silhouette.
+ float weights = 0.0;
+ float cov = 0.0;
+ vec3 acc = vec3(0.0);
+ for (int i = 0; i < 12; i++) {
+ float ang = float(i) * 2.399963 + 0.4;
+ float rad = 1.0 + float(i % 3) * 1.15;
+ vec2 off = vec2(cos(ang), sin(ang)) * rad * px;
+ vec2 uv = vUv + off;
+ float a = fetchA(uv);
+ float w = 1.0 - rad / 5.4;
+ cov += a * w;
+ acc += fetch(uv) * a * w;
+ weights += w;
+ }
+ cov /= weights;
+ vec3 gathered = acc / max(cov * weights, 0.00001);
+
+ float centreCov = centre.a;
+ cov = max(cov, centreCov);
+ vec3 c = mix(gathered, centre.rgb, smoothstep(0.62, 0.92, centreCov));
+
+ // Composite the model onto paper white before grading.
+ c = mix(vec3(1.0), c, smoothstep(0.26, 0.72, cov));
+
+ // Linear render target -> display sRGB.
+ c = pow(max(c, vec3(0.0)), vec3(1.0 / 2.2));
+
+ // Gentle grade, then the crisp ink contour.
+ float l = luma(c);
+ c = mix(vec3(l), c, 1.07);
+ c = clamp((c - 0.5) * 1.028 + 0.5, 0.0, 1.0);
+
+ float l0 = luma(texture(tScene, vUv).rgb);
+ float l1 = luma(texture(tScene, vUv + vec2(px.x, 0.0)).rgb);
+ float l2 = luma(texture(tScene, vUv - vec2(px.x, 0.0)).rgb);
+ float l3 = luma(texture(tScene, vUv + vec2(0.0, px.y)).rgb);
+ float l4 = luma(texture(tScene, vUv - vec2(0.0, px.y)).rgb);
+ float edge = max(max(abs(l0 - l1), abs(l0 - l2)), max(abs(l0 - l3), abs(l0 - l4)));
+ // Neighbour luminance is linear; bring it into the same scale.
+ edge = pow(edge, 0.4545);
+ float ink = smoothstep(0.13, 0.34, edge) * smoothstep(0.20, 0.55, cov) * (1.0 - smoothstep(0.86, 0.985, cov));
+ c = mix(c, vec3(0.085, 0.082, 0.076), ink * 0.62);
+
+ // 8x8 ordered dither, then nearest palette snap.
+ float d = bayer8(gl_FragCoord.xy) - 0.5;
+ float sparkle = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453) - 0.5;
+ // Dither hardest where tones are actually transitioning; flat areas stay calm.
+ float gate = smoothstep(0.004, 0.055, edge);
+ c += (d * (0.0012 + 0.019 * gate) + sparkle * 0.0012) * uDither;
+
+ vec3 best = uPalette[0];
+ float bestD = 1e9;
+ for (int i = 0; i < 64; i++) {
+ vec3 p = uPalette[i];
+ vec3 diff = (c - p) * vec3(1.0, 1.12, 0.93);
+ float dd = dot(diff, diff);
+ if (dd < bestD) {
+ bestD = dd;
+ best = p;
+ }
+ }
+ c = best;
+
+ // Fragment the outer silhouette with the same ordered matrix.
+ float rim = 1.0 - smoothstep(0.78, 0.995, cov);
+ float threshold = bayer4(gl_FragCoord.xy * 1.0) * 0.92 + 0.018;
+ if (rim > 0.002 && cov < threshold) {
+ c = vec3(1.0);
+ }
+ if (cov < 0.02) c = vec3(1.0);
+
+ fragColor = vec4(c, 1.0);
+}
+`;
+
+export class PixelPost {
+ constructor(renderer, maxDim = 1600, renderScale = 1) {
+ this.renderer = renderer;
+ this.maxDim = maxDim;
+ this.renderScale = renderScale;
+
+ this.rt = new THREE.WebGLRenderTarget(2, 2, {
+ minFilter: THREE.NearestFilter,
+ magFilter: THREE.NearestFilter,
+ depthBuffer: true,
+ stencilBuffer: false,
+ samples: 0,
+ type: THREE.HalfFloatType,
+ format: THREE.RGBAFormat,
+ colorSpace: THREE.LinearSRGBColorSpace,
+ });
+ this.rt.texture.generateMipmaps = false;
+
+ this.uniforms = {
+ tScene: { value: this.rt.texture },
+ uResolution: { value: new THREE.Vector2(2, 2) },
+ uPalette: { value: PALETTE_RGB.map((c) => new THREE.Vector3(c[0], c[1], c[2])) },
+ uDither: { value: 1.0 },
+ };
+
+ this.material = new THREE.ShaderMaterial({
+ glslVersion: THREE.GLSL3,
+ uniforms: this.uniforms,
+ vertexShader: VERT,
+ fragmentShader: FRAG,
+ depthTest: false,
+ depthWrite: false,
+ toneMapped: false,
+ });
+
+ this.scene = new THREE.Scene();
+ this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.material);
+ quad.frustumCulled = false;
+ this.scene.add(quad);
+
+ this.size = new THREE.Vector2(2, 2);
+ }
+
+ setSize(w, h) {
+ // Default one target pixel per CSS pixel. `renderScale` 1.2–1.5 supersamples
+ // a subject that is small on the page so the palette and dither keep detail
+ // after the CSS downscale; `maxDim` is a hard ceiling for 4K displays.
+ const scale = Math.min(this.renderScale, this.maxDim / Math.max(w, h));
+ const iw = Math.max(2, Math.round(w * scale));
+ const ih = Math.max(2, Math.round(h * scale));
+ if (iw === this.size.x && ih === this.size.y) return;
+ this.size.set(iw, ih);
+ this.rt.setSize(iw, ih);
+ this.uniforms.uResolution.value.set(iw, ih);
+ this.renderer.setSize(iw, ih, false);
+ }
+
+ render(scene, camera) {
+ const r = this.renderer;
+ r.setRenderTarget(this.rt);
+ r.setClearColor(0x000000, 0);
+ r.clear(true, true, true);
+ r.render(scene, camera);
+ r.setRenderTarget(null);
+ r.setClearColor(0x000000, 1);
+ r.clear(true, true, true);
+ r.render(this.scene, this.camera);
+ }
+}
diff --git a/templates/qa/README.md b/templates/qa/README.md
new file mode 100644
index 0000000..d604c8d
--- /dev/null
+++ b/templates/qa/README.md
@@ -0,0 +1,153 @@
+# QA harness
+
+Seven scripts and no framework. The point is that every claim about the build is
+checked against a frozen frame, a printed number or a scene-graph rule, never
+against a memory of what the code should do.
+
+## Setup
+
+The scripts drive a real Chromium through `playwright-core`, so they need it
+installed where Node can find it, plus a page that exposes the debug handle:
+
+```js
+window.__diorama = {
+ THREE, scene, camera, renderer, post,
+ freeze(t) { /* draw(t) synchronously */ },
+ view(pos, tgt) { /* optional debug camera */ }
+};
+window.__dioramaReady = true; // after the first frame
+```
+
+`freeze(t)` must draw synchronously. Without it every screenshot is a race, and
+a screenshot that might be showing a different frame than you think is not
+evidence. The harness also accepts the older `window.__ready` + `draw(t)` pair.
+
+```bash
+npm i -D playwright-core
+python3 -m http.server 4180 & # serve the project root
+```
+
+## The seven checks
+
+| Script | Answers | Fails when |
+| --- | --- | --- |
+| `shoot.mjs` | does it load and frame at three viewports? | any console/page error, or a viewport that writes no frame |
+| `audit.mjs` | are the seams, scale, halos, exits and emitters honest? | flat glow quad, whole-object fade, camera/render-scale mismatch, early hide, teleport, idle/orphan emitter, paper-margin leak |
+| `portrait.mjs` | is the rig sound up close? | joint gap, floating part, knee bending forward, oversized head |
+| `strip.mjs` + `tile.py` | does the motion read over six frames? | a phase pop, a skate, a body through a door, or every frame identical |
+| `probe.py` | what colour is on screen, and how thick is that band? | a stray palette entry, a band that should not exist |
+| `sweep.mjs` | are two actors jammed, or did one teleport? | the same pair under 0.6 m for two consecutive samples, or a jump over `MAX_STEP` |
+| `verify/` | does an effect reproduce after a clock jump? | two identical freezes differ because the effect integrates `dt` |
+
+```bash
+BASE_URL=http://127.0.0.1:4180/index.html \
+SHOTS="3.2:exit,9.0:mid,24.4:getin" \
+node qa/shoot.mjs
+
+BASE_URL=http://127.0.0.1:4180/index.html LOOP=46 \
+node qa/audit.mjs
+
+FROM=15.4 TO=16.6 N=8 OUT=qa/strip-exit.png node qa/strip.mjs
+python3 qa/tile.py qa/strip-exit.png --crop 420,300,640,450 --zoom 3 qa/frames/f*.png
+
+python3 qa/probe.py qa/wide-edge.png 520 425 560 # colour runs down a column
+
+FROM=20 TO=26 STEP=0.3 node qa/sweep.mjs
+```
+
+Every script that can fail sets a nonzero exit code. A green screenshot tour is
+not a QA pass if `audit.mjs` or `sweep.mjs` printed a failure.
+
+## The audit contract
+
+`audit.mjs` always runs the graph checks. The paper-margin scan needs the
+`slab` rectangle; add the optional contract when the scene has movers, particles
+or a visible slab edge. The mechanical checks then cover exits, FX timing and
+edge leaks too.
+
+```js
+window.__diorama.audit = {
+ loop: 46,
+ // World-space slab, plus how far outside it counts as clear.
+ slab: { x0: -12, x1: 12, z0: -8, z1: 8, margin: 0.35 },
+
+ // Every vehicle, animal or walker that leaves. Bounds are measured from the
+ // group, so the whole body/lights/shadow must clear the slab before hiding.
+ movers: [
+ { name: 'hero', group: hero.group, required: true, allowSpawn: false },
+ { name: 'rival', group: rival.group }
+ ],
+
+ // One entry per event-driven cloud. `source` is the actual nozzle/tip object,
+ // not the engine centre. `active(t)` is the authored event window.
+ emitters: [
+ {
+ name: 'hero-exhaust',
+ points: smoke.points, // or count(t) / centroid(t)
+ source: () => exhaustTip.getWorldPosition(new THREE.Vector3()),
+ active: (t) => t > 12.9 && t < 13.8,
+ maxOffset: 2.2, // puff centroid to source, metres
+ tail: 0.8 // allowed fade-out after the window
+ }
+ ]
+};
+```
+
+If the camera exposes `userData.fitDistance` and `userData.subjectScale`,
+`audit.mjs` also proves `distance ≈ fitDistance / subjectScale` without a
+contract key. That is the 30%-smaller camera move: the set and clip stay full
+size, only the camera pulls back. If `post.renderScale` is exposed, it checks
+`post.size ≈ CSS size × renderScale` (capped by `maxDim`) too.
+
+`allowSpawn: true` is for a mover that legitimately appears inside the frame
+(an actor already seated, a prop revealed by a cutaway). `qaAllowGlow = true`
+on a mesh and `qaAllowFade = true` on a group are explicit exemptions; use them
+only with a written reason in `DESIGN.md`.
+
+## What "passing" looks like
+
+- `no console errors` at 1280×800, 1388×950 and 390×844, and the camera position
+ identical across all three samples of the same viewport (the angle is locked).
+- `audit passed` with no `ERROR` lines. Warnings are allowed at the default
+ strictness; `STRICT=1` makes them fail too. The margin limit is
+ `MARGIN_RATIO=0.0002` (0.02% of the sampled margin).
+- Two screenshots 1.5 s apart differ (the loop is alive).
+- A 1:1 crop shows square pixels, a dark contour, no speckle on flat deck, no
+ flat grey rectangle beside a sign, no step at a slab edge.
+- A strip reads as one continuous motion; consecutive positions differ by
+ centimetres, never by a body length.
+- The sweep prints no jammed pair and no jump over `MAX_STEP`.
+
+## Effects and the frozen clock
+
+Anything that integrates `dt` (wake, splash, smoke) is not a function of `t`
+until it is reset and re-simulated. Both effect templates expose `reset()`; the
+pattern is:
+
+```js
+function simulateTo(t) {
+ wake.reset(); splash.reset();
+ const dt = 1 / 30;
+ for (let s = 0; s < t; s += dt) { /* fire triggers, then step updates */ }
+}
+```
+
+`verify/water/` is a working example. Two identical freezes there differ by 18
+pixels, against 334 before the reset was added.
+
+## Common audit failures and what they mean
+
+| Finding | Usual cause | Fix |
+| --- | --- | --- |
+| `FLAT_GLOW` | untextured additive plane behind a board/lamp | radial-alpha texture, real lens, or delete |
+| `GROUP_FADE` | material opacity applied to a whole vehicle/figure | cut/clip/hide after bounds clear; never fade solids |
+| `CAMERA_SCALE` | actual distance is not `fitDistance / subjectScale` | apply `subjectScale` after the fit; do not scale geometry |
+| `RENDER_SCALE` | post buffer is not CSS × `renderScale` | pass `renderScale` to `PixelPost`; check `maxDim` and CSS size |
+| `EARLY_HIDE` | `visible=false` at the gate or before the bounds clear | carry the full run-out; hide after slab + margin |
+| `TELEPORT` | a keyed position jumps between samples | add the missing key or move the cut outside frame |
+| `POP_IN` | a mover appears inside the slab | spawn outside, or set `allowSpawn` with a reason |
+| `MOVER_MISSING` | the contract names a group that does not exist | fix the name/group reference |
+| `MISSING_EMITTER` | the event window is open but the cloud is empty | fix the bake window or the count/points hook |
+| `IDLE_EMITTER` | continuous smoke while parked | gate emission by an event window; add a fade tail |
+| `ORPHAN_EMITTER` | plume starts at engine centre/cab roof | source at the real exhaust tip/nozzle |
+| `MARGIN_LEAK` | read-through FX or geometry past the slab | taper/fade before the edge, or clip the solid |
diff --git a/templates/qa/audit.mjs b/templates/qa/audit.mjs
new file mode 100644
index 0000000..af2b28a
--- /dev/null
+++ b/templates/qa/audit.mjs
@@ -0,0 +1,476 @@
+import { chromium } from 'playwright-core';
+
+/**
+ * Mechanical scene audit. Run this in addition to shoot.mjs.
+ *
+ * It catches the post-build failures that screenshots alone miss:
+ * FLAT_GLOW a flat, untextured, low-opacity plane (the grey rectangle)
+ * GROUP_FADE a whole object made translucent by material opacity
+ * EARLY_HIDE a mover hidden while its world bounds still touch the slab
+ * TELEPORT a mover jumping more than MAX_SPEED between samples
+ * IDLE_EMITTER particles alive while the effect's event window is closed
+ * ORPHAN_EMITTER particle cloud far from its declared nozzle/source
+ * CAMERA_SCALE actual camera distance does not match fit / subjectScale
+ * RENDER_SCALE post buffer does not match CSS size * renderScale
+ * MARGIN_LEAK geometry/FX pixels in the paper margin
+ *
+ * BASE_URL and CHROME_PATH as in shoot.mjs.
+ * LOOP=20 STEP=0.1 MAX_SPEED=12 MARGIN_RATIO=0.0002 STRICT=0
+ *
+ * Optional audit contract in main.js (strongly recommended):
+ *
+ * window.__diorama.audit = {
+ * loop: 46,
+ * slab: { x0: -12, x1: 12, z0: -8, z1: 8, margin: 0.35 },
+ * movers: [
+ * { name: 'hero', group: hero.group, required: true, allowSpawn: false }
+ * ],
+ * emitters: [
+ * { name: 'hero-exhaust', points: smoke.points,
+ * source: () => exhaustTip.getWorldPosition(new THREE.Vector3()),
+ * active: (t) => t > 12.9 && t < 13.8,
+ * maxOffset: 2.2, tail: 0.8 }
+ * ]
+ * };
+ *
+ * `source` may be a Vector3, an Object3D, or a function returning either.
+ * `points` may be omitted when `count(t)` / `centroid(t)` are supplied.
+ * With no contract, the flat-glow and fade checks still run; the margin scan
+ * needs the slab rectangle.
+ */
+
+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:4180/index.html';
+const CHROME =
+ process.env.CHROME_PATH ||
+ `${process.env.HOME}/Library/Caches/ms-playwright/chromium-1243/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing`;
+const LOOP = Number(process.env.LOOP || 20);
+const STEP = Number(process.env.STEP || 0.1);
+const MAX_SPEED = Number(process.env.MAX_SPEED || 12);
+const STRICT = process.env.STRICT === '1';
+const FLAT_AREA = Number(process.env.FLAT_AREA || 0.75);
+const MARGIN_RATIO = Number(process.env.MARGIN_RATIO || 0.0002);
+
+const browser = await chromium.launch({
+ executablePath: CHROME,
+ headless: true,
+ args: ['--ignore-gpu-blocklist', '--enable-webgl', '--use-angle=metal'],
+});
+const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
+const consoleErrors = [];
+page.on('pageerror', (e) => consoleErrors.push(e.message));
+page.on('console', (m) => {
+ if (m.type() === 'error') consoleErrors.push(m.text());
+});
+
+await page.goto(BASE_URL, { waitUntil: 'load' });
+await page.waitForFunction(
+ () => window.__dioramaReady === true || window.__ready === true,
+ null,
+ { timeout: 30000 }
+);
+
+const report = await page.evaluate(
+ ({ step, flatArea, loopDefault, maxSpeed }) => {
+ const d = window.__diorama;
+ const THREE = d && d.THREE;
+ if (!d || !d.scene || !THREE) {
+ return { fatal: 'window.__diorama.scene/THREE is missing', errors: [], warnings: [] };
+ }
+ const freeze = d.freeze || d.draw;
+ if (typeof freeze !== 'function') {
+ return { fatal: 'window.__diorama.freeze(t) (or draw(t)) is missing', errors: [], warnings: [] };
+ }
+
+ const audit = d.audit || {};
+ const loop = Number(audit.loop ?? d.loop ?? d.WORLD?.loop ?? loopDefault);
+ const slab = audit.slab || null;
+ const errors = [];
+ const warnings = [];
+ const seen = new Set();
+ const add = (bucket, kind, message, data = {}) => {
+ const key = `${kind}:${message}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ bucket.push({ kind, message, ...data });
+ };
+ const shown = (o) => {
+ for (let p = o; p; p = p.parent) if (p.visible === false) return false;
+ return true;
+ };
+ const vec = (value) => {
+ if (!value) return null;
+ if (value.isVector3) return value.clone();
+ if (Array.isArray(value)) return new THREE.Vector3(value[0], value[1], value[2]);
+ if (value.isObject3D) {
+ value.updateWorldMatrix(true, false);
+ return new THREE.Vector3().setFromMatrixPosition(value.matrixWorld);
+ }
+ return null;
+ };
+ const resolve = (ref) => {
+ if (!ref) return null;
+ if (typeof ref === 'string') return d.scene.getObjectByName(ref);
+ return ref;
+ };
+ const boxOf = (g) => {
+ g.updateWorldMatrix(true, true);
+ const b = new THREE.Box3().setFromObject(g);
+ return b.isEmpty() ? null : b;
+ };
+ const cleared = (box, s, margin) =>
+ box.max.x < s.x0 - margin ||
+ box.min.x > s.x1 + margin ||
+ box.max.z < s.z0 - margin ||
+ box.min.z > s.z1 + margin;
+ const touchesSlab = (box, s, margin) =>
+ box.max.x > s.x0 - margin &&
+ box.min.x < s.x1 + margin &&
+ box.max.z > s.z0 - margin &&
+ box.min.z < s.z1 + margin;
+
+ // 0. Camera scale. A post-fit subjectScale must be the only size change:
+ // actual distance is fitDistance / subjectScale. No metadata, no check.
+ const cam = d.camera;
+ const fit = Number(cam?.userData?.fitDistance);
+ const scale = Number(cam?.userData?.subjectScale);
+ if (Number.isFinite(fit) && fit > 0 && Number.isFinite(scale) && scale > 0) {
+ const actual = Number(cam.userData.distance);
+ const expected = fit / scale;
+ if (!Number.isFinite(actual) || Math.abs(actual / expected - 1) > 0.02) {
+ add(errors, 'CAMERA_SCALE',
+ `camera scale ${scale.toFixed(2)}: actual distance ${Number.isFinite(actual) ? actual.toFixed(2) : '?'} vs fit/scale ${expected.toFixed(2)} — apply subjectScale after solveDistance`,
+ { scale, fit, actual });
+ }
+ }
+
+ // 0b. Render buffer. A 1.25x post has to report 1.25x the CSS canvas; if it
+ // silently stayed at 1x, the screenshot looks soft but nothing else fails.
+ const post = d.post;
+ const rect = d.renderer?.domElement?.getBoundingClientRect?.();
+ const renderScale = Number(post?.renderScale);
+ let renderChecked = false;
+ if (post?.size && Number.isFinite(renderScale) && renderScale > 0 && rect?.width > 0) {
+ renderChecked = true;
+ const expected = Math.min(renderScale, (post.maxDim || Infinity) / Math.max(rect.width, rect.height));
+ const actual = post.size.x / rect.width;
+ if (Math.abs(actual / expected - 1) > 0.02) {
+ add(errors, 'RENDER_SCALE',
+ `post buffer ${post.size.x}x${post.size.y} is ${actual.toFixed(2)}x CSS ${rect.width.toFixed(0)}x${rect.height.toFixed(0)}; expected ${expected.toFixed(2)}x — check renderScale / maxDim`,
+ { renderScale, actual });
+ }
+ }
+
+ // 1. Flat untextured halo quads. This is the light-grey rectangle bug.
+ d.scene.traverse((o) => {
+ if (!o.isMesh || !shown(o)) return;
+ const mats = Array.isArray(o.material) ? o.material : [o.material];
+ for (const m of mats) {
+ if (!m || !m.transparent || (m.opacity ?? 1) < 0.01) continue;
+ if (m.map || m.alphaMap) continue;
+ if ((m.transmission || 0) > 0.01) continue;
+ if (o.userData.qaAllowGlow === true) continue;
+ const flatTypes = new Set(['PlaneGeometry', 'ShapeGeometry', 'CircleGeometry']);
+ if (!flatTypes.has(o.geometry?.type)) continue;
+ o.updateWorldMatrix(true, true);
+ const bb = new THREE.Box3().setFromObject(o);
+ if (bb.isEmpty()) continue;
+ const dims = bb.getSize(new THREE.Vector3()).toArray().sort((a, b) => b - a);
+ // A glow card is large in two axes and effectively zero in the third.
+ if (dims[2] >= 0.08 || dims[0] * dims[1] < flatArea) continue;
+ const additive = m.blending === THREE.AdditiveBlending;
+ const lowAlpha = (m.opacity ?? 1) <= 0.28;
+ if (!additive && !lowAlpha) continue;
+ const wp = new THREE.Vector3();
+ o.getWorldPosition(wp);
+ add(errors, 'FLAT_GLOW',
+ `flat untextured ${additive ? 'additive' : 'translucent'} ${o.geometry.type} ${dims[0].toFixed(1)}x${dims[1].toFixed(1)} at ${wp.x.toFixed(2)},${wp.y.toFixed(2)},${wp.z.toFixed(2)} — use a radial-alpha map or remove`,
+ { name: o.name || '(unnamed)' });
+ }
+ });
+
+ // 2. Whole-group material fades. A hero turning see-through is not a fade.
+ const groups = [];
+ d.scene.traverse((o) => {
+ if (o.isGroup) groups.push(o);
+ });
+ const flagged = new Set();
+ for (const g of groups) {
+ if (!shown(g) || g.userData.qaAllowFade === true) continue;
+ let meshes = 0;
+ let faded = 0;
+ g.traverse((o) => {
+ if (!o.isMesh || o === g || o.visible === false) return;
+ meshes++;
+ const mats = Array.isArray(o.material) ? o.material : [o.material];
+ const f = mats.some((m) => m && m.transparent && (m.opacity ?? 1) < 0.95 &&
+ !m.map && !m.alphaMap && (m.transmission || 0) <= 0.01 &&
+ (m.isMeshStandardMaterial === true || m.isMeshLambertMaterial === true || m.isMeshPhongMaterial === true));
+ if (f) faded++;
+ });
+ if (meshes < 6 || faded < 4 || faded / meshes < 0.45) continue;
+ let parent = g.parent;
+ let covered = false;
+ while (parent) { if (flagged.has(parent)) { covered = true; break; } parent = parent.parent; }
+ if (covered) continue;
+ flagged.add(g);
+ add(errors, 'GROUP_FADE',
+ `${g.name || '(unnamed group)'}: ${faded}/${meshes} meshes use transparent opacity<0.95 without a texture — whole-object ghosting`,
+ { name: g.name || '(unnamed group)' });
+ }
+
+ // 3. Mover bounds: no early hide, no teleport.
+ for (const spec of audit.movers || []) {
+ const g = resolve(spec.group || spec.name);
+ if (!g) { add(errors, 'MOVER_MISSING', `mover ${spec.name || '?'} has no group`); continue; }
+ const samples = Math.max(2, Math.ceil(loop / step));
+ let prevVisible = false;
+ let prevCenter = null;
+ let everVisible = false;
+ for (let i = 0; i <= samples; i++) {
+ const t = (i / samples) * loop;
+ freeze(t);
+ const vis = shown(g);
+ // Box3 still measures an invisible group; that is what lets us prove a
+ // hide happened inside the slab instead of after the bounds cleared.
+ const box = boxOf(g);
+ const center = box ? box.getCenter(new THREE.Vector3()) : null;
+ everVisible ||= vis;
+ if (prevVisible && !vis && t > 0.3 && t < loop - 0.05 && box && slab) {
+ if (!cleared(box, slab, slab.margin ?? 0.35)) {
+ add(errors, 'EARLY_HIDE',
+ `${spec.name || g.name} disappears at t=${t.toFixed(2)} while its bounds still touch the slab — carry the full run-out`,
+ { name: spec.name || g.name, t: +t.toFixed(2) });
+ }
+ }
+ if (!prevVisible && vis && t > 0.1 && t < loop - 0.1 && !spec.allowSpawn && box && slab) {
+ if (touchesSlab(box, slab, slab.margin ?? 0.35)) {
+ add(errors, 'POP_IN',
+ `${spec.name || g.name} appears inside the slab at t=${t.toFixed(2)} — spawn outside or set allowSpawn`,
+ { name: spec.name || g.name, t: +t.toFixed(2) });
+ }
+ }
+ if (vis && prevVisible && prevCenter && center && t > step && t < loop - step) {
+ const dist = center.distanceTo(prevCenter);
+ const limit = (spec.maxSpeed ?? maxSpeed) * step * 1.8;
+ if (dist > limit) {
+ add(errors, 'TELEPORT',
+ `${spec.name || g.name} jumps ${dist.toFixed(2)} m in ${step.toFixed(2)} s at t=${t.toFixed(2)} (limit ${limit.toFixed(2)} m)`,
+ { name: spec.name || g.name, t: +t.toFixed(2) });
+ }
+ }
+ prevVisible = vis;
+ prevCenter = center || prevCenter;
+ }
+ if (!everVisible && spec.required !== false) {
+ add(warnings, 'NEVER_VISIBLE', `mover ${spec.name || g.name} is never visible in the loop`);
+ }
+ }
+
+ // 4. Emitter windows and anchor distance.
+ for (const spec of audit.emitters || []) {
+ if (typeof spec.active !== 'function') continue;
+ const samples = Math.max(2, Math.ceil(loop / step));
+ const points = resolve(spec.points);
+ let lastActive = -Infinity;
+ let idleReported = false;
+ let missingRun = 0;
+ let orphanReported = false;
+ for (let i = 0; i <= samples; i++) {
+ const t = (i / samples) * loop;
+ freeze(t);
+ const active = !!spec.active(t);
+ if (active) lastActive = t;
+ else missingRun = 0;
+ let n = 0;
+ let centroid = null;
+ if (typeof spec.count === 'function') {
+ n = spec.count(t) || 0;
+ } else if (points && !shown(points)) {
+ n = 0;
+ } else if (points?.geometry?.attributes?.aAlpha) {
+ const al = points.geometry.attributes.aAlpha;
+ const pos = points.geometry.attributes.position;
+ let sx = 0, sy = 0, sz = 0, sw = 0;
+ for (let k = 0; k < al.count; k++) {
+ const a = al.getX(k);
+ if (a <= 0.02) continue;
+ n++;
+ sx += pos.getX(k) * a;
+ sy += pos.getY(k) * a;
+ sz += pos.getZ(k) * a;
+ sw += a;
+ }
+ if (sw > 0) centroid = new THREE.Vector3(sx / sw, sy / sw, sz / sw);
+ } else if (typeof spec.count !== 'function') {
+ continue;
+ }
+ if (typeof spec.centroid === 'function') {
+ const c = vec(spec.centroid(t));
+ if (c) centroid = c;
+ }
+ if (active && n === 0) {
+ missingRun++;
+ if (missingRun === 2) {
+ add(errors, 'MISSING_EMITTER',
+ `${spec.name || 'emitter'} is active at t=${t.toFixed(2)} but has no live particles — check the bake window`);
+ }
+ } else if (n > 0) {
+ missingRun = 0;
+ }
+ if (!active && n > 0 && !idleReported && t - lastActive > (spec.tail ?? 1.2)) {
+ idleReported = true;
+ add(errors, 'IDLE_EMITTER',
+ `${spec.name || 'emitter'} has ${n} live puffs at t=${t.toFixed(2)} while its event window is closed — make FX event-driven`,
+ { name: spec.name || 'emitter', t: +t.toFixed(2) });
+ }
+ if (centroid && typeof spec.source !== 'undefined') {
+ const raw = typeof spec.source === 'function' ? spec.source(t) : spec.source;
+ const src = vec(raw);
+ if (src) {
+ const dist = centroid.distanceTo(src);
+ if (dist > (spec.maxOffset ?? 2.5) && !orphanReported) {
+ orphanReported = true;
+ add(errors, 'ORPHAN_EMITTER',
+ `${spec.name || 'emitter'} puffs are ${dist.toFixed(2)} m from their source at t=${t.toFixed(2)} — anchor at the real nozzle`,
+ { name: spec.name || 'emitter', t: +t.toFixed(2) });
+ }
+ }
+ }
+ }
+ }
+
+ return { loop, errors, warnings, camera: Number.isFinite(fit) && fit > 0 && Number.isFinite(scale) && scale > 0, render: renderChecked, contract: {
+ slab,
+ movers: (audit.movers || []).length,
+ emitters: (audit.emitters || []).length,
+ camera: Number.isFinite(fit) && fit > 0 && Number.isFinite(scale) && scale > 0,
+ render: renderChecked,
+ } };
+ },
+ { step: STEP, flatArea: FLAT_AREA, loopDefault: LOOP, maxSpeed: MAX_SPEED }
+);
+
+if (report.fatal) {
+ console.error(`AUDIT FATAL: ${report.fatal}`);
+ await browser.close();
+ process.exit(1);
+}
+
+// 5. Paper-margin scan. A border pixel that is not paper means a read-through
+// FX or geometry leaked past the slab window.
+const times = report.loop ? [0, report.loop * 0.5, report.loop - 0.15] : [0];
+const margin = await page.evaluate(
+ ({ loop, ratio, times, slab }) => {
+ if (!slab) return { skipped: 'no audit.slab contract' };
+ const d = window.__diorama;
+ const freeze = d.freeze || d.draw;
+ const canvas = d.renderer?.domElement || document.querySelector('canvas');
+ if (!canvas || !d.camera) return { skipped: 'no canvas/camera' };
+ const camera = d.camera;
+ camera.updateMatrixWorld();
+ const corners = [];
+ for (const x of [slab.x0, slab.x1]) {
+ for (const y of [-0.6, 0.6]) {
+ for (const z of [slab.z0, slab.z1]) {
+ const p = new d.THREE.Vector3(x, y, z).project(camera);
+ corners.push({ x: (p.x * 0.5 + 0.5) * canvas.width, y: (-p.y * 0.5 + 0.5) * canvas.height });
+ }
+ }
+ }
+ const pad = 6;
+ const minX = Math.min(...corners.map((c) => c.x)) - pad;
+ const maxX = Math.max(...corners.map((c) => c.x)) + pad;
+ const minY = Math.min(...corners.map((c) => c.y)) - pad;
+ const maxY = Math.max(...corners.map((c) => c.y)) + pad;
+
+ const out = [];
+ for (const t of times) {
+ freeze(t);
+ const w = canvas.width, h = canvas.height;
+ const gl = d.renderer.getContext();
+ const pixels = new Uint8Array(w * h * 4);
+ // Read in the same task as the render, so it does not depend on
+ // preserveDrawingBuffer. Origin is bottom-left.
+ gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
+ let nonPaper = 0, total = 0, lit = 0;
+ const at = (x, y) => ((h - 1 - y) * w + x) * 4;
+ // Read the paper colour from the frame, not a hard-coded white: the
+ // palette paper may be warm, and a hard 245 test would flag all of it.
+ const cornerIdx = [at(0, 0), at(w - 1, 0), at(0, h - 1), at(w - 1, h - 1)];
+ let pi = cornerIdx[0];
+ for (const i of cornerIdx) {
+ if (pixels[i] + pixels[i + 1] + pixels[i + 2] > pixels[pi] + pixels[pi + 1] + pixels[pi + 2]) pi = i;
+ }
+ const paper = [pixels[pi], pixels[pi + 1], pixels[pi + 2]];
+ const isPaper = (i) =>
+ Math.abs(pixels[i] - paper[0]) <= 6 &&
+ Math.abs(pixels[i + 1] - paper[1]) <= 6 &&
+ Math.abs(pixels[i + 2] - paper[2]) <= 6;
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ // Only the paper between the projected slab and the frame edge.
+ if (x >= minX && x <= maxX && y >= minY && y <= maxY) continue;
+ total++;
+ const i = at(x, y);
+ if (pixels[i] + pixels[i + 1] + pixels[i + 2] > 12) lit++;
+ if (!isPaper(i)) nonPaper++;
+ }
+ }
+ out.push({ t: +t.toFixed(2), nonPaper, total, lit, ratio: total ? nonPaper / total : 0 });
+ }
+ return { samples: out };
+ },
+ { loop: report.loop, ratio: MARGIN_RATIO, times, slab: report.contract.slab }
+);
+
+if (process.env.DEBUG === '1') console.log('margin', JSON.stringify(margin));
+const marginChecked = !!margin.samples?.some((s) => s.total > 0);
+const errors = [...report.errors];
+const warnings = [...report.warnings];
+if (margin.skipped) {
+ if (report.contract.slab) warnings.push({ kind: 'MARGIN_UNVERIFIED', message: margin.skipped });
+ else console.log('note: margin scan skipped (add audit.slab to enable)');
+} else {
+ for (const s of margin.samples || []) {
+ if (s.total === 0) continue; // slab fills the frame; no paper margin to inspect
+ if (s.lit === 0) {
+ warnings.push({ kind: 'MARGIN_UNVERIFIED', message: `readback black at t=${s.t}` });
+ continue;
+ }
+ if (s.ratio > MARGIN_RATIO) {
+ errors.push({
+ kind: 'MARGIN_LEAK',
+ message: `${s.nonPaper}/${s.total} border pixels are non-paper at t=${s.t} (${(s.ratio * 100).toFixed(2)}%, limit ${(MARGIN_RATIO * 100).toFixed(2)}%)`,
+ t: s.t,
+ });
+ }
+ }
+}
+for (const e of consoleErrors) errors.push({ kind: 'CONSOLE', message: e });
+
+console.log(`audit loop=${report.loop} contract=${JSON.stringify({
+ slab: !!report.contract.slab,
+ camera: !!report.contract.camera,
+ render: !!report.contract.render,
+ movers: report.contract.movers,
+ emitters: report.contract.emitters,
+})}`);
+for (const e of errors) console.log(`ERROR ${e.kind} ${e.message}`);
+for (const w of warnings) console.log(`WARN ${w.kind} ${w.message}`);
+if (!errors.length && !warnings.length) {
+ const checks = ['flat halos', 'whole-object fades'];
+ if (report.contract.movers) checks.push('early hides/teleports');
+ if (report.contract.emitters) checks.push('idle emitters/orphan puffs');
+ if (report.contract.camera) checks.push('camera scale');
+ if (report.contract.render) checks.push('render scale');
+ if (marginChecked) checks.push('margin leaks');
+ let suffix = '';
+ if (!report.contract.slab) suffix = ' (margin scan skipped: add audit.slab)';
+ else if (!marginChecked) suffix = ' (slab fills frame: no margin to scan)';
+ console.log(`audit passed: no ${checks.join(', ')}${suffix}`);
+}
+if (errors.length) console.log(`audit failed: ${errors.length} error(s), ${warnings.length} warning(s)`);
+else if (STRICT && warnings.length) console.log(`audit failed (STRICT): ${warnings.length} warning(s)`);
+if (errors.length || (STRICT && warnings.length)) process.exitCode = 1;
+
+await browser.close();
diff --git a/templates/qa/portrait.mjs b/templates/qa/portrait.mjs
new file mode 100644
index 0000000..c7c65cd
--- /dev/null
+++ b/templates/qa/portrait.mjs
@@ -0,0 +1,67 @@
+import { chromium } from 'playwright-core';
+import { mkdirSync } from 'node:fs';
+
+/**
+ * Isolated portraits: pull the debug camera close and shoot one subject, so
+ * joint gaps, floating parts, a reversed knee or an oversized nose can be seen.
+ * At 30 to 45 px on the diorama a figure hides all four.
+ *
+ * BASE_URL QA_DIR CHROME_PATH as in shoot.mjs
+ * SHOTS '[{"name":"car","t":4.2,"pos":[1.4,2.2,7.4],"tgt":[-2.2,0.95,2.9]}]'
+ *
+ * pos/tgt are world coordinates for window.__diorama.view(pos, tgt). Call
+ * view() with no arguments to restore the locked three-quarter camera.
+ * Accepts either window.__dioramaReady/freeze(t) or __ready/draw(t).
+ */
+
+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:4180/index.html';
+const QA_DIR = process.env.QA_DIR || 'qa';
+const SHOTS = JSON.parse(process.env.SHOTS || '[]');
+const W = Number(process.env.W || 900);
+const H = Number(process.env.H || 700);
+
+const CHROME =
+ process.env.CHROME_PATH ||
+ `${process.env.HOME}/Library/Caches/ms-playwright/chromium-1243/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing`;
+
+if (!SHOTS.length) {
+ console.error('SHOTS is empty: pass a JSON array of {name, t, pos, tgt}');
+ process.exit(1);
+}
+
+mkdirSync(QA_DIR, { recursive: true });
+
+const browser = await chromium.launch({
+ executablePath: CHROME,
+ headless: true,
+ args: ['--ignore-gpu-blocklist', '--enable-webgl', '--use-angle=metal'],
+});
+const page = await browser.newPage({ viewport: { width: W, height: H } });
+const errors = [];
+page.on('pageerror', (e) => errors.push(e.message));
+await page.goto(BASE_URL, { waitUntil: 'load' });
+await page.waitForFunction(
+ () => window.__dioramaReady === true || window.__ready === true,
+ null,
+ { timeout: 30000 }
+);
+
+for (const s of SHOTS) {
+ await page.evaluate(
+ ({ t, pos, tgt }) => {
+ const d = window.__diorama;
+ (d.freeze || d.draw)(t);
+ d.view(pos, tgt);
+ d.post.render(d.scene, d.camera, d.CLIP || []);
+ },
+ { t: s.t, pos: s.pos, tgt: s.tgt }
+ );
+ await page.waitForTimeout(140);
+ await page.screenshot({ path: `${QA_DIR}/p-${s.name}.png` });
+ console.log('shot', s.name);
+}
+
+await page.evaluate(() => window.__diorama.view());
+console.log(errors.length ? `ERRORS: ${errors.join(' | ')}` : 'no console errors');
+if (errors.length) process.exitCode = 1;
+await browser.close();
diff --git a/templates/qa/probe.py b/templates/qa/probe.py
new file mode 100644
index 0000000..48b1bbd
--- /dev/null
+++ b/templates/qa/probe.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python3
+"""Sample a strip of pixels across an edge and print the colour runs.
+
+ probe.py frame.png 520 425 560 # column 520, rows 425..560
+
+The first tool to reach for when something "looks wrong" at an edge. It answers
+which palette entry is on screen, how thick a band is, and whether a ramp steps
+or fades, none of which a screenshot can be trusted for after it has been
+downscaled once.
+"""
+import sys
+from PIL import Image
+
+def run(pixels):
+ out = []
+ prev = None
+ start = 0
+ for i, p in enumerate(pixels):
+ if p != prev:
+ if prev is not None:
+ out.append((start, i - 1, prev))
+ prev = p
+ start = i
+ out.append((start, len(pixels) - 1, prev))
+ return out
+
+def main(argv):
+ path, x, y0, y1 = argv[1], int(argv[2]), int(argv[3]), int(argv[4])
+ im = Image.open(path).convert('RGB')
+ col = [im.getpixel((x, y)) for y in range(y0, y1)]
+ for a, b, c in run(col):
+ print(f'y {y0 + a}..{y0 + b} {c} #{c[0]:02x}{c[1]:02x}{c[2]:02x} ({b - a + 1}px)')
+ return 0
+
+if __name__ == '__main__':
+ if len(sys.argv) < 5:
+ print(__doc__)
+ sys.exit(1)
+ sys.exit(main(sys.argv))
diff --git a/templates/qa/shoot.mjs b/templates/qa/shoot.mjs
new file mode 100644
index 0000000..c15d9e7
--- /dev/null
+++ b/templates/qa/shoot.mjs
@@ -0,0 +1,96 @@
+import { chromium } from 'playwright-core';
+import { mkdirSync } from 'node:fs';
+
+/**
+ * Screenshot the play at named timestamps across the viewports that matter.
+ *
+ * BASE_URL default http://127.0.0.1:4180/index.html
+ * QA_DIR default ./qa
+ * SHOTS "3.2:exit,9.0:mid,24.4:getin" (t:name pairs, comma separated)
+ * VIEWPORTS '[{"w":1280,"h":800,"tag":"wide"}, ...]'
+ *
+ * Requires the page to expose window.__diorama with freeze(t), and to set
+ * window.__dioramaReady = true (or the older window.__ready) once the first
+ * frame has drawn. Without the freeze hook every screenshot is a race and a
+ * screenshot stops being evidence.
+ *
+ * Prints one line per viewport: buffer size, css size, camera position, draw
+ * calls, triangles, and any page errors. "no console errors" is the only
+ * acceptable result, and this line is the proof of it.
+ */
+
+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:4180/index.html';
+const QA_DIR = process.env.QA_DIR || 'qa';
+const SHOTS = process.env.SHOTS || '2.0:frame';
+const VIEWPORTS = JSON.parse(
+ process.env.VIEWPORTS ||
+ '[{"w":1280,"h":800,"tag":"wide"},{"w":1388,"h":950,"tag":"ipad"},{"w":390,"h":844,"tag":"phone"}]'
+);
+
+const CHROME =
+ process.env.CHROME_PATH ||
+ `${process.env.HOME}/Library/Caches/ms-playwright/chromium-1243/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing`;
+
+const shots = SHOTS.split(',')
+ .map((s) => s.split(':'))
+ .map(([t, name]) => ({ t: parseFloat(t), name: name || `t${t}` }))
+ .filter((s) => Number.isFinite(s.t));
+
+mkdirSync(QA_DIR, { recursive: true });
+
+const browser = await chromium.launch({
+ executablePath: CHROME,
+ headless: true,
+ args: ['--ignore-gpu-blocklist', '--enable-webgl', '--use-angle=metal'],
+});
+
+let failed = false;
+for (const vp of VIEWPORTS) {
+ const page = await browser.newPage({ viewport: { width: vp.w, height: vp.h } });
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ page.on('console', (m) => {
+ if (m.type() === 'error') errors.push(m.text());
+ });
+
+ await page.goto(BASE_URL, { waitUntil: 'load' });
+ await page.waitForFunction(
+ () => window.__dioramaReady === true || window.__ready === true,
+ null,
+ { timeout: 30000 }
+ );
+
+ for (const s of shots) {
+ await page.evaluate((t) => {
+ const d = window.__diorama;
+ (d.freeze || d.draw)(t);
+ }, s.t);
+ await page.waitForTimeout(140);
+ await page.screenshot({ path: `${QA_DIR}/${vp.tag}-${s.name}.png` });
+ }
+
+ const info = await page.evaluate(() => {
+ const d = window.__diorama;
+ const canvas = d.renderer.domElement;
+ const size = d.post?.size || { x: canvas.width, y: canvas.height };
+ const rect = canvas.getBoundingClientRect();
+ const c = d.camera.position;
+ return {
+ buffer: `${size.x},${size.y}`,
+ css: `${Math.round(rect.width)},${Math.round(rect.height)}`,
+ cam: [c.x, c.y, c.z].map((n) => n.toFixed(2)).join(','),
+ calls: d.renderer.info.render.calls,
+ tris: d.renderer.info.render.triangles,
+ };
+ });
+
+ console.log(
+ `[${vp.tag}] buffer=${info.buffer} css=${info.css} cam=${info.cam} calls=${info.calls} tris=${info.tris} ` +
+ (errors.length ? `ERRORS: ${errors.join(' | ')}` : 'no console errors')
+ );
+ if (errors.length) failed = true;
+ await page.close();
+}
+
+await browser.close();
+if (failed) process.exitCode = 1;
diff --git a/templates/qa/strip.mjs b/templates/qa/strip.mjs
new file mode 100644
index 0000000..c29a59d
--- /dev/null
+++ b/templates/qa/strip.mjs
@@ -0,0 +1,74 @@
+import { chromium } from 'playwright-core';
+import { mkdirSync, readFileSync } from 'node:fs';
+
+/**
+ * Motion strip: N evenly spaced frames across a window, cropped to the subject
+ * and laid out left to right in one PNG. A still cannot show a bad knee, a foot
+ * skating, a figure climbing through a door, or a phase pop at a boundary; six
+ * frames in a row usually can.
+ *
+ * FROM / TO window in seconds
+ * N frame count (default 6)
+ * CROP "x,y,w,h" in page pixels (default: whole frame)
+ * OUT output path (default qa/strip.png)
+ * QA_DIR frame directory (default qa)
+ *
+ * Then read the strip, not the individual frames.
+ */
+
+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:4180/index.html';
+const FROM = Number(process.env.FROM || 0);
+const TO = Number(process.env.TO || 2);
+const N = Number(process.env.N || 6);
+const OUT = process.env.OUT || 'qa/strip.png';
+const QA_DIR = process.env.QA_DIR || 'qa';
+const W = Number(process.env.W || 900);
+const H = Number(process.env.H || 700);
+
+const CHROME =
+ process.env.CHROME_PATH ||
+ `${process.env.HOME}/Library/Caches/ms-playwright/chromium-1243/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing`;
+
+mkdirSync(`${QA_DIR}/frames`, { recursive: true });
+
+const browser = await chromium.launch({
+ executablePath: CHROME,
+ headless: true,
+ args: ['--ignore-gpu-blocklist', '--enable-webgl', '--use-angle=metal'],
+});
+const page = await browser.newPage({ viewport: { width: W, height: H } });
+await page.goto(BASE_URL, { waitUntil: 'load' });
+await page.waitForFunction(
+ () => window.__dioramaReady === true || window.__ready === true,
+ null,
+ { timeout: 30000 }
+);
+
+const paths = [];
+const frames = [];
+for (let i = 0; i < N; i++) {
+ const t = FROM + ((TO - FROM) * i) / Math.max(1, N - 1);
+ await page.evaluate((tt) => {
+ const d = window.__diorama;
+ (d.freeze || d.draw)(tt);
+ }, t);
+ await page.waitForTimeout(120);
+ const p = `${QA_DIR}/frames/f${String(i).padStart(2, '0')}.png`;
+ await page.screenshot({ path: p });
+ paths.push(p);
+ frames.push(readFileSync(p));
+}
+await browser.close();
+
+let identical = false;
+if (frames.length > 1) {
+ const first = frames[0];
+ identical = frames.every((b) => b.equals(first));
+ if (identical) {
+ console.error('strip failed: every frame is byte-identical; the clock or the animation is frozen');
+ process.exitCode = 1;
+ }
+}
+console.log(paths.join('\n'));
+console.log(`\nmotion: ${frames.length} frame(s), ${identical ? 'IDENTICAL' : 'varying'}`);
+console.log(`\nNow tile them:\n python3 templates/qa/tile.py ${OUT} ${paths.join(' ')}`);
diff --git a/templates/qa/sweep.mjs b/templates/qa/sweep.mjs
new file mode 100644
index 0000000..28c28ad
--- /dev/null
+++ b/templates/qa/sweep.mjs
@@ -0,0 +1,117 @@
+import { chromium } from 'playwright-core';
+
+/**
+ * Pairwise distance sweep. Freezes the clock in steps across a multi-actor beat
+ * and prints every pair closer than THRESH (0.6 m by default).
+ *
+ * A pair that holds that close for more than one sample is genuinely jammed; a
+ * single sample is two actors passing each other. At 12 px a figure, a
+ * screenshot cannot tell those apart, and nudging spacing by eye fixes the wrong
+ * thing: the usual cause is a route that ends where another actor already stands.
+ *
+ * FROM / TO / STEP window and sampling interval (default 0.3 s)
+ * THRESH metres
+ * MAX_STEP metres between samples before a jump is reported
+ * (default 3.0; a real teleport, not a fast walk)
+ * CAST JS expression returning the actor list, default
+ * `window.__diorama.cast`, each entry `{ group }`
+ */
+
+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:4180/index.html';
+const FROM = Number(process.env.FROM || 0);
+const TO = Number(process.env.TO || 20);
+const STEP = Number(process.env.STEP || 0.3);
+const THRESH = Number(process.env.THRESH || 0.6);
+const MAX_STEP = Number(process.env.MAX_STEP || 3.0);
+const CAST = process.env.CAST || 'window.__diorama.cast';
+
+const CHROME =
+ process.env.CHROME_PATH ||
+ `${process.env.HOME}/Library/Caches/ms-playwright/chromium-1243/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing`;
+
+const browser = await chromium.launch({
+ executablePath: CHROME,
+ headless: true,
+ args: ['--ignore-gpu-blocklist', '--enable-webgl', '--use-angle=metal'],
+});
+const page = await browser.newPage({ viewport: { width: 640, height: 480 } });
+await page.goto(BASE_URL, { waitUntil: 'load' });
+await page.waitForFunction(
+ () => window.__dioramaReady === true || window.__ready === true,
+ null,
+ { timeout: 30000 }
+);
+
+const rows = await page.evaluate(
+ ({ from, to, step, thresh, maxStep, castExpr }) => {
+ const d = window.__diorama;
+ const freeze = d.freeze || d.draw;
+ const actors = eval(castExpr);
+ const out = [];
+ let prev = null;
+ for (let t = from; t <= to; t += step) {
+ freeze(t);
+ const p = actors.map((a, i) => {
+ const g = a.group ?? a;
+ const name = a.name || g.name || `actor${i}`;
+ return { i, name, vis: g.visible, x: g.position.x, z: g.position.z };
+ });
+ const close = [];
+ for (let i = 0; i < p.length; i++) {
+ for (let j = i + 1; j < p.length; j++) {
+ if (!p[i].vis || !p[j].vis) continue;
+ const d2 = Math.hypot(p[i].x - p[j].x, p[i].z - p[j].z);
+ if (d2 < thresh) close.push(`${p[i].i}-${p[j].i}:${d2.toFixed(2)}`);
+ }
+ }
+ const jumps = [];
+ if (prev) {
+ for (const a of p) {
+ const b = prev.find((q) => q.i === a.i);
+ if (!b || !a.vis || !b.vis) continue;
+ const dist = Math.hypot(a.x - b.x, a.z - b.z);
+ if (dist > maxStep) jumps.push(`${a.name}:${dist.toFixed(2)}m`);
+ }
+ }
+ out.push({ t: +t.toFixed(2), close, jumps });
+ prev = p;
+ }
+ return out;
+ },
+ { from: FROM, to: TO, step: STEP, thresh: THRESH, maxStep: MAX_STEP, castExpr: CAST }
+);
+
+let strikes = 0;
+let jammed = false;
+let jumped = false;
+for (let idx = 0; idx < rows.length; idx++) {
+ const r = rows[idx];
+ if (r.close.length) {
+ strikes++;
+ console.log(r.t.toFixed(2), r.close.join(' '));
+ const now = new Set(r.close.map((s) => s.split(':')[0]));
+ const prev = rows[idx - 1];
+ if (prev) {
+ const prevPairs = new Set(prev.close.map((s) => s.split(':')[0]));
+ for (const pair of now) {
+ if (prevPairs.has(pair)) {
+ console.log(` JAMMED pair ${pair} held under ${THRESH} m at ${prev.t} and ${r.t}`);
+ jammed = true;
+ }
+ }
+ }
+ }
+ if (r.jumps.length) {
+ jumped = true;
+ console.log(`${r.t.toFixed(2)} JUMP ${r.jumps.join(' ')}`);
+ }
+}
+console.log(
+ strikes
+ ? `\n${strikes} sample(s) under ${THRESH} m. A pair repeating for two or more consecutive samples is jammed.`
+ : `no pair under ${THRESH} m across the window`
+);
+if (jammed) console.log('sweep failed: jammed pair(s)');
+if (jumped) console.log(`sweep failed: mover jumped more than ${MAX_STEP} m between samples`);
+if (jammed || jumped) process.exitCode = 1;
+await browser.close();
diff --git a/templates/qa/tile.py b/templates/qa/tile.py
new file mode 100644
index 0000000..ff2b5fb
--- /dev/null
+++ b/templates/qa/tile.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Tile frames into a strip, optionally cropping and zooming.
+
+ tile.py OUT.png f0.png f1.png ... # side by side, 1x
+ tile.py OUT.png --crop 420,300,640,450 --zoom 3 f0.png f1.png
+
+Cropping first, then zooming, is not the same as the other way round: the crop
+takes pixels from the original render, so a 3x zoom of a 200 px box shows real
+pixels and real dither instead of a resampled blur. Judge speckle, contours and
+pixel grid on this, never on the full frame.
+"""
+import sys
+from PIL import Image
+
+def main(argv):
+ out = argv[1]
+ args = argv[2:]
+ crop = None
+ zoom = 1
+ files = []
+ i = 0
+ while i < len(args):
+ if args[i] == '--crop':
+ crop = tuple(int(n) for n in args[i + 1].split(','))
+ i += 2
+ elif args[i] == '--zoom':
+ zoom = int(args[i + 1])
+ i += 2
+ else:
+ files.append(args[i])
+ i += 1
+
+ if not files:
+ print('no frames given')
+ return 1
+
+ ims = []
+ for f in files:
+ im = Image.open(f).convert('RGB')
+ if crop:
+ im = im.crop(crop)
+ if zoom > 1:
+ im = im.resize((im.width * zoom, im.height * zoom), Image.NEAREST)
+ ims.append(im)
+
+ w, h = ims[0].size
+ strip = Image.new('RGB', (w * len(ims), h), 'white')
+ for n, im in enumerate(ims):
+ strip.paste(im, (n * w, 0))
+ strip.save(out)
+ print(out, strip.size)
+ return 0
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv))
diff --git a/templates/splash.js b/templates/splash.js
new file mode 100644
index 0000000..fefc954
--- /dev/null
+++ b/templates/splash.js
@@ -0,0 +1,159 @@
+import * as THREE from 'three';
+import { POOL } from '../config.js';
+
+/**
+ * Chunky pixel-friendly splash: a burst of white droplets, a foam disc and
+ * three expanding rings on the water surface. Everything is unlit so it stays
+ * bright after the palette snap.
+ */
+export function createSplash() {
+ const group = new THREE.Group();
+ const dropMat = new THREE.MeshBasicMaterial({ color: 0xf2fbf7 });
+ const foamMat = () =>
+ new THREE.MeshBasicMaterial({
+ color: 0xdff6ee,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+
+ const drops = [];
+ for (let i = 0; i < 64; i++) {
+ const r = 0.024 + (i % 7) * 0.007;
+ const mesh = new THREE.Mesh(new THREE.IcosahedronGeometry(r, 0), dropMat);
+ mesh.visible = false;
+ mesh.frustumCulled = false;
+ group.add(mesh);
+ drops.push({
+ mesh,
+ pos: new THREE.Vector3(),
+ vel: new THREE.Vector3(),
+ live: false,
+ spin: new THREE.Vector3(),
+ });
+ }
+
+ const rings = [];
+ for (let i = 0; i < 4; i++) {
+ const geo = new THREE.RingGeometry(0.30, 0.375, 30);
+ geo.rotateX(-Math.PI / 2);
+ const mat = foamMat();
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.y = POOL.waterY + 0.008 + i * 0.0015;
+ mesh.visible = false;
+ mesh.renderOrder = 8;
+ group.add(mesh);
+ rings.push({ mesh, mat, age: 0, delay: i * 0.14, live: false });
+ }
+
+ const foamGeo = new THREE.CircleGeometry(0.62, 24);
+ foamGeo.rotateX(-Math.PI / 2);
+ const foam = new THREE.Mesh(foamGeo, foamMat());
+ foam.position.y = POOL.waterY + 0.012;
+ foam.renderOrder = 9;
+ foam.visible = false;
+ group.add(foam);
+
+ let foamAge = 0;
+ let foamLive = false;
+
+ /**
+ * Deterministic stand-in for Math.random. The whole play is a function of t,
+ * so a burst must look identical every time it fires, and identical again when
+ * the QA harness re-simulates the effects from zero to freeze a frame.
+ */
+ let seed = 1;
+ function rnd() {
+ seed = (seed * 16807) % 2147483647;
+ return (seed - 1) / 2147483646;
+ }
+
+ function trigger(x, z, power = 1, burstSeed = 1) {
+ seed = burstSeed * 7919 || 1;
+ drops.forEach((d, i) => {
+ const a = rnd() * Math.PI * 2;
+ const chunky = i % 5 === 0;
+ const speed = (chunky ? 0.3 : 0.55 + rnd() * 1.65) * power;
+ const up = (chunky ? 1.0 + rnd() * 0.7 : 1.7 + rnd() * 2.1) * power;
+ d.pos.set(x + (rnd() - 0.5) * 0.22, POOL.waterY + 0.04, z + (rnd() - 0.5) * 0.22);
+ d.vel.set(Math.cos(a) * speed, up, Math.sin(a) * speed);
+ d.spin.set(rnd() * 6, rnd() * 6, rnd() * 6);
+ d.live = true;
+ d.mesh.visible = true;
+ d.mesh.position.copy(d.pos);
+ });
+ for (const r of rings) {
+ r.age = 0;
+ r.live = true;
+ r.mesh.visible = true;
+ r.mesh.scale.setScalar(0.22);
+ r.mat.opacity = 0.0;
+ }
+ foamAge = 0;
+ foamLive = true;
+ foam.visible = true;
+ foam.position.set(x, POOL.waterY + 0.012, z);
+ foam.scale.setScalar(0.35);
+ foam.material.opacity = 0.40;
+ }
+
+ function update(dt) {
+ for (const d of drops) {
+ if (!d.live) continue;
+ d.vel.y -= 9.6 * dt;
+ d.pos.addScaledVector(d.vel, dt);
+ d.mesh.position.copy(d.pos);
+ d.mesh.rotation.x += d.spin.x * dt;
+ d.mesh.rotation.y += d.spin.y * dt;
+ if (d.pos.y < POOL.waterY - 0.02) {
+ d.live = false;
+ d.mesh.visible = false;
+ }
+ }
+
+ for (const r of rings) {
+ if (!r.live) continue;
+ r.age += dt;
+ const a = r.age - r.delay;
+ if (a < 0) continue;
+ const k = a / 1.5;
+ if (k >= 1) {
+ r.live = false;
+ r.mesh.visible = false;
+ continue;
+ }
+ r.mesh.scale.setScalar(0.3 + k * 3.4);
+ r.mat.opacity = 0.75 * (1 - k) * (1 - k);
+ }
+
+ if (foamLive) {
+ foamAge += dt;
+ const k = foamAge / 0.9;
+ if (k >= 1) {
+ foamLive = false;
+ foam.visible = false;
+ } else {
+ foam.scale.setScalar(0.35 + k * 1.3);
+ foam.material.opacity = 0.40 * (1 - k) * (1 - k);
+ }
+ }
+ }
+
+ /** See wake.js reset(): effects that integrate dt must start clean on a jump. */
+ function reset() {
+ for (const d of drops) {
+ d.live = false;
+ d.mesh.visible = false;
+ }
+ for (const r of rings) {
+ r.live = false;
+ r.mesh.visible = false;
+ r.mat.opacity = 0;
+ }
+ foamLive = false;
+ foam.visible = false;
+ }
+
+ return { group, trigger, update, reset };
+}
diff --git a/templates/stage.js b/templates/stage.js
new file mode 100644
index 0000000..f4aee48
--- /dev/null
+++ b/templates/stage.js
@@ -0,0 +1,197 @@
+import * as THREE from 'three';
+import { clamp, lerp, smooth, groundY } from '../config.js';
+import { STAND } from './poses.js';
+import { transfer, standSpot, SEAT_ROOT_Y, toWorld } from './transfer.js';
+
+/**
+ * The beat sheet, and the actor loop that reads it.
+ *
+ * Everything here is a pure function of `t`. No state is carried between frames,
+ * nothing integrates, nothing calls Math.random: any frame can be frozen with
+ * ?t= and the loop restarts without drift. That property is what makes the QA
+ * harness possible, so keep it.
+ *
+ * This file is scaffolding, not a scene. It ships the one structure that is easy
+ * to get wrong and tedious to rewrite: a table of beats, a keyed scalar curve, a
+ * place() that keeps the contact shadow glued to the actor, and an actor loop
+ * whose branches are ordered by time so exactly one of them runs per frame.
+ * Replace the cast, the tracks and the beats; keep the skeleton.
+ */
+
+export const TL = {
+ loop: 20.0,
+ driveIn: [0.4, 3.0],
+ doorsOpen: [3.1, 3.5],
+ out: [3.4, 3.65, 3.9], // one start per actor
+ outDur: 1.15,
+ walk: [4.9, 5.2, 5.5],
+ walkDur: 4.0,
+ back: [11.0, 11.2, 11.4],
+ backDur: 2.4,
+ in: [15.0, 15.25, 15.5],
+ inDur: 1.05,
+ doorsClose: [16.6, 17.0],
+ pull: [17.1, 19.6],
+};
+
+const PI = Math.PI;
+
+const CAR_PARK = { x: -2.0, z: 2.4, yaw: PI / 2 };
+const CAR_IN = { x: -12.0, z: CAR_PARK.z, yaw: PI / 2 };
+const CAR_OUT_X = 14.0;
+
+/** Keyed scalar: [[t, value, ease], ...]. Ease applies to the segment. */
+export function keysAt(t, keys) {
+ if (t <= keys[0][0]) return keys[0][1];
+ for (let i = 1; i < keys.length; i++) {
+ const [t1, v1, ease = 'smooth'] = keys[i];
+ if (t <= t1) {
+ const [t0, v0] = keys[i - 1];
+ const u = clamp((t - t0) / Math.max(0.0001, t1 - t0), 0, 1);
+ const e = ease === 'out' ? 1 - (1 - u) ** 3 : ease === 'in' ? u ** 3 : smooth(u);
+ return lerp(v0, v1, e);
+ }
+ }
+ return keys[keys.length - 1][1];
+}
+
+/**
+ * Put an actor somewhere with a pose, and keep its contact shadow on the ground
+ * underneath it. `ground` overrides the sampled height for a figure standing on
+ * something (a car roof, a table).
+ */
+export function place(actor, pos, yaw, pose, opts = {}) {
+ const visible = opts.visible !== false;
+ actor.group.visible = visible;
+ actor.group.position.set(pos.x, pos.y, pos.z);
+ actor.group.rotation.set(0, yaw, 0);
+ const p = { ...pose };
+ if (opts.headTurn) {
+ p.head = [p.head?.[0] ?? 0, (p.head?.[1] ?? 0) + opts.headTurn, p.head?.[2] ?? 0];
+ }
+ actor.setPose(p);
+ if (!actor.shadow) return;
+ actor.shadow.visible = visible && opts.shadow !== false;
+ if (!actor.shadow.visible) return;
+ const gy = opts.ground ?? groundY(pos.x, pos.z);
+ actor.shadow.position.set(pos.x, gy + 0.018, pos.z);
+ const s = opts.shadowScale ?? 1;
+ actor.shadow.scale.set(s, s * 0.82, 1);
+ actor.shadow.material.opacity = opts.shadowOpacity ?? 0.62;
+}
+
+/** Car position as a function of time: in, parked, out. Never reversing. */
+export function carState(t) {
+ if (t < TL.driveIn[0]) return { ...CAR_IN, present: false };
+ if (t < TL.driveIn[1]) {
+ const u = clamp((t - TL.driveIn[0]) / (TL.driveIn[1] - TL.driveIn[0]), 0, 1);
+ const e = 1 - (1 - u) ** 2.3;
+ return { x: lerp(CAR_IN.x, CAR_PARK.x, e), z: CAR_PARK.z, yaw: CAR_PARK.yaw, present: true };
+ }
+ if (t < TL.pull[0]) return { ...CAR_PARK, present: true };
+ if (t < TL.pull[1]) {
+ const u = clamp((t - TL.pull[0]) / (TL.pull[1] - TL.pull[0]), 0, 1);
+ const e = 0.32 * u + 0.68 * u * u;
+ return { x: lerp(CAR_PARK.x, CAR_OUT_X, e), z: CAR_PARK.z, yaw: CAR_PARK.yaw, present: true };
+ }
+ return { x: CAR_OUT_X, z: CAR_PARK.z, yaw: CAR_PARK.yaw, present: false };
+}
+
+/**
+ * @param world { scene, car, cast, doorPivot, doorSwing, makeTrack }
+ */
+export function createStage(world) {
+ const { car, cast, makeTrack, setDoor } = world;
+
+ // Seats, one per actor. Left flank (side -1) because that is the camera side.
+ const side = -1;
+ const seats = [
+ { x: side * 0.4, z: 0.3, y: SEAT_ROOT_Y },
+ { x: side * 0.4, z: -0.5, y: SEAT_ROOT_Y },
+ ];
+ const stands = seats.map((s) => standSpot(CAR_PARK, side, s.z));
+
+ // Routes: pavement -> place -> back.
+ const outTracks = stands.map((s, i) =>
+ makeTrack([
+ [s.x, s.z, 0],
+ [s.x + 1.2, s.z + 0.5, 1],
+ [1.0 + i * 0.9, 4.6, 0.6],
+ ])
+ );
+
+ function seatPos(state, seat) {
+ const p = toWorld(state, seat.x, seat.z);
+ p.y = seat.y + (state.y ?? 0);
+ return p;
+ }
+
+ function update(T) {
+ const t = ((T % TL.loop) + TL.loop) % TL.loop;
+ const state = carState(t);
+
+ car.group.visible = state.present !== false;
+ car.group.position.set(state.x, 0, state.z);
+ car.group.rotation.y = state.yaw;
+
+ // Doors are a timeline, not a state: open before a transfer, shut after.
+ const open = keysAt(t, [
+ [0, 0],
+ [TL.doorsOpen[0], 0, 'out'],
+ [TL.doorsOpen[1], 1],
+ [TL.doorsClose[0], 1, 'in'],
+ [TL.doorsClose[1], 0],
+ ]);
+ setDoor(world.doorPivot, open * world.doorSwing);
+
+ for (let i = 0; i < cast.length; i++) {
+ const a = cast[i];
+ const seat = seats[i];
+ const sp = seatPos(state, seat);
+ const stand = stands[i];
+ const track = outTracks[i];
+ const out = TL.out[i];
+ const walk = TL.walk[i];
+ const back = TL.back[i];
+ const into = TL.in[i];
+
+ // Exactly one branch runs. Order matters: keep them monotonic in t.
+ if (t < out) {
+ place(a, sp, state.yaw, STAND, { shadow: false });
+ } else if (t < out + TL.outDur) {
+ const face = Math.atan2(sp.x - stand.x, sp.z - stand.z);
+ const r = transfer(t, out, TL.outDur, state, side, seat, stand, face, false);
+ place(a, r.pos, r.yaw, r.pose);
+ } else if (t < walk) {
+ const at = track.at(0);
+ place(a, at.pos, at.yaw, STAND, { headTurn: Math.sin(t * 1.2 + i) * 0.18 });
+ } else if (t < walk + TL.walkDur) {
+ const u = clamp((t - walk) / TL.walkDur, 0, 1);
+ const d = smooth(u) * track.length;
+ const at = track.at(d);
+ place(a, at.pos, at.yaw, world.walkPose(d * 5.2), { headTurn: Math.sin(t * 0.9) * 0.1 });
+ } else if (t < back) {
+ const at = track.at(track.length);
+ place(a, at.pos, at.yaw + PI, STAND);
+ } else if (t < back + TL.backDur) {
+ const u = clamp((t - back) / TL.backDur, 0, 1);
+ const d = track.length * (1 - smooth(u));
+ const at = track.at(d);
+ place(a, at.pos, at.yaw + PI, world.runPose(d * 5.6));
+ } else if (t < into) {
+ // A standing beat at the door. Never hand a run straight into a climb.
+ const face = Math.atan2(sp.x - stand.x, sp.z - stand.z);
+ place(a, stand, face, STAND, { headTurn: Math.sin(t * 0.9 + i) * 0.05 });
+ } else if (t < into + TL.inDur) {
+ const face = Math.atan2(sp.x - stand.x, sp.z - stand.z);
+ const r = transfer(t, into, TL.inDur, state, side, seat, stand, face, true);
+ place(a, r.pos, r.yaw, r.pose);
+ } else {
+ // Seated figures stay visible: an empty car driving off reads as a bug.
+ place(a, sp, state.yaw, world.seatedPose ?? STAND, { shadow: false });
+ }
+ }
+ }
+
+ return { update, TL, carState };
+}
diff --git a/templates/track.js b/templates/track.js
new file mode 100644
index 0000000..8933309
--- /dev/null
+++ b/templates/track.js
@@ -0,0 +1,60 @@
+import * as THREE from 'three';
+import { clamp, lerp, groundY } from '../config.js';
+
+/**
+ * Arc-length path through waypoints, sampled to a lookup table.
+ *
+ * Each waypoint is [x, z, weight]. `weight` scales the lane offset so a crowd
+ * can walk the same route but queue up in the street and pass a doorway one at a
+ * time, which is the difference between "four people filing in" and a scrum.
+ *
+ * Ground height comes from the scene's own `groundY(x, z)` and is then smoothed,
+ * so steps read as a ramp instead of a teleport.
+ */
+export class Track {
+ constructor(points, lane = 0) {
+ const ctrl = points.map(([x, z, w = 1], i) => {
+ const prev = points[Math.max(0, i - 1)];
+ const next = points[Math.min(points.length - 1, i + 1)];
+ let dx = next[0] - prev[0];
+ let dz = next[1] - prev[1];
+ const len = Math.hypot(dx, dz) || 1;
+ dx /= len;
+ dz /= len;
+ return new THREE.Vector3(x + dz * lane * w, 0, z - dx * lane * w);
+ });
+
+ const curve = new THREE.CatmullRomCurve3(ctrl, false, 'catmullrom', 0.28);
+ const N = 320;
+ this.pts = [];
+ let total = 0;
+ for (let i = 0; i <= N; i++) {
+ const p = curve.getPoint(i / N);
+ if (i > 0) total += Math.hypot(p.x - this.pts[i - 1].x, p.z - this.pts[i - 1].z);
+ this.pts.push(new THREE.Vector3(p.x, groundY(p.x, p.z), p.z));
+ this.pts[i].dist = total;
+ }
+ // Three 1-2-1 passes: steps become a ramp.
+ for (let pass = 0; pass < 3; pass++) {
+ const ys = this.pts.map((p) => p.y);
+ for (let i = 1; i < this.pts.length - 1; i++) {
+ this.pts[i].y = (ys[i - 1] + ys[i] * 2 + ys[i + 1]) / 4;
+ }
+ }
+ this.length = total;
+ }
+
+ /** Position and heading at arc length `d`. */
+ at(d) {
+ const dd = clamp(d, 0, this.length);
+ let i = 1;
+ while (i < this.pts.length - 1 && this.pts[i].dist < dd) i++;
+ const a = this.pts[i - 1];
+ const b = this.pts[i];
+ const span = b.dist - a.dist || 1;
+ const u = clamp((dd - a.dist) / span, 0, 1);
+ const pos = new THREE.Vector3(lerp(a.x, b.x, u), lerp(a.y, b.y, u), lerp(a.z, b.z, u));
+ const yaw = Math.atan2(b.x - a.x, b.z - a.z);
+ return { pos, yaw };
+ }
+}
diff --git a/templates/transfer.js b/templates/transfer.js
new file mode 100644
index 0000000..fec940d
--- /dev/null
+++ b/templates/transfer.js
@@ -0,0 +1,184 @@
+import * as THREE from 'three';
+import { clamp, lerp, smooth } from '../config.js';
+import {
+ STAND,
+ SEATED,
+ REACH,
+ CROUCH_IN,
+ SIT_EDGE,
+ LEGS_IN,
+ mixPose,
+} from './poses.js';
+
+/**
+ * Getting in and out of a seat: the whole move, authored in the CAR's own frame
+ * so it works at any parking angle.
+ *
+ * Why this ships as code rather than as advice: it is the single most fragile
+ * thing in a vehicle play. Every previous attempt failed the same three ways,
+ * and none of them are visible in a still:
+ *
+ * 1. A straight lerp from the pavement to the seat drags the body through the
+ * door skin. The climb has to be keyed: knees drop, hips land on the sill,
+ * then the legs swing in.
+ * 2. The outbound yaw points away from the car. Reused on the way in, it makes
+ * the figure climb in backwards, face to the street, and turn a half circle
+ * during the first frames. On the way in, every key before the seated ones
+ * faces the car.
+ * 3. Taking that facing from the approach path's tangent is wrong: the path's
+ * opening segment runs along the street, so `path.at(0).yaw + PI` points
+ * down the kerb. Resolve it from the seat and stand positions.
+ *
+ * Usage, per figure:
+ *
+ * const seat = { x: side * 0.40, z: 0.30, y: SEAT_ROOT_Y };
+ * const stand = toWorld(car, side * 2.00, seat.z - 0.30);
+ * const r = transfer(t, t0, 1.15, car, side, seat, stand, face, false);
+ * place(actor, r.pos, r.yaw, r.pose);
+ *
+ * where `face = Math.atan2(seatWorld.x - stand.x, seatWorld.z - stand.z)`.
+ */
+
+const PI = Math.PI;
+
+/** Seat root: cushion top minus hipY, so the hips settle into the cushion. */
+export const SEAT_ROOT_Y = -0.38;
+/** How far out from the car's centreline the stand spot sits. */
+export const DOOR_STAND_X = 2.0;
+/** Stand this far behind the hinge, so the open leaf clears the shoulders. */
+export const DOOR_STAND_DZ = -0.06;
+/** The stand spot used by the climb itself, inside the outer stand spot. */
+export const DOOR_NEAR_X = 1.34;
+/** Share of the transfer window spent taking the stride to the door. */
+export const STEP_SHARE = 0.26;
+
+export function toWorld(base, x, z) {
+ const c = Math.cos(base.yaw);
+ const s = Math.sin(base.yaw);
+ return new THREE.Vector3(base.x + x * c + z * s, 0, base.z - x * s + z * c);
+}
+
+export function clampAngle(a) {
+ let x = a;
+ while (x > PI) x -= PI * 2;
+ while (x < -PI) x += PI * 2;
+ return x;
+}
+
+export const lerpAngle = (a, b, k) => a + clampAngle(b - a) * k;
+
+/**
+ * The climb. k runs 0 at the open door to 1 at the seat; dy is the root height
+ * above the seated root. The body only reaches cushion height once the hips are
+ * over the sill, which is what stops it sinking, floating or sliding through the
+ * bodywork.
+ */
+export const CLIMB = [
+ { u: 0.0, k: 0.0, dy: 0.38, pose: STAND },
+ { u: 0.16, k: 0.03, dy: 0.33, pose: REACH }, // hand to the roof edge
+ { u: 0.36, k: 0.16, dy: 0.12, pose: CROUCH_IN }, // knees deep, hips dropping
+ { u: 0.56, k: 0.38, dy: 0.01, pose: SIT_EDGE }, // perched, feet still down
+ { u: 0.76, k: 0.66, dy: 0.0, pose: LEGS_IN }, // knees up, feet over the sill
+ { u: 0.9, k: 0.88, dy: 0.0, pose: mixPose(LEGS_IN, SEATED, 0.55) },
+ { u: 1.0, k: 1.0, dy: 0.0, pose: SEATED },
+];
+
+export function climbAt(u) {
+ let a = CLIMB[0];
+ let b = CLIMB[CLIMB.length - 1];
+ for (let i = 1; i < CLIMB.length; i++) {
+ if (u <= CLIMB[i].u) {
+ a = CLIMB[i - 1];
+ b = CLIMB[i];
+ break;
+ }
+ }
+ const f = smooth(clamp((u - a.u) / Math.max(0.0001, b.u - a.u), 0, 1));
+ return { k: lerp(a.k, b.k, f), dy: lerp(a.dy, b.dy, f), pose: mixPose(a.pose, b.pose, f) };
+}
+
+/** One stride on the pavement, used at both ends of the climb. */
+export function stepPose(f) {
+ const lift = Math.sin(PI * clamp(f, 0, 1));
+ return {
+ ...STAND,
+ torso: [0.06 + 0.08 * f, 0, 0],
+ head: [-0.02, 0, 0],
+ hipL: [-0.36 * lift, 0, 0.04],
+ hipR: [0.22 * lift, 0, -0.04],
+ kneeL: [0.1 + 0.55 * lift, 0, 0],
+ kneeR: [0.16, 0, 0],
+ ankleL: [-0.1 - 0.16 * lift, 0, 0],
+ ankleR: [-0.1, 0, 0],
+ };
+}
+
+/**
+ * The whole move between the pavement and a seat.
+ *
+ * t timeline seconds
+ * t0 window start
+ * dur window length; 1.05 to 1.20 s each way, never under 0.9
+ * state the car: { x, z, yaw } (plus optional y offset)
+ * side -1 or +1: which flank the door is on, in car space
+ * seat { x, z, y } seat root in car space
+ * standPos pavement spot, world Vector3 ({x,y,z})
+ * standYaw heading to hold when standing (only used on the way out)
+ * inward true to climb in, false to climb out
+ *
+ * Returns { pos, yaw, pose }. Assign it to the actor's group and call setPose.
+ */
+export function transfer(t, t0, dur, state, side, seat, standPos, standYaw, inward) {
+ const u = clamp((t - t0) / Math.max(0.1, dur), 0, 1);
+ const A = STEP_SHARE;
+ const faceYaw = state.yaw - side * (PI / 2); // square to the open door
+ const door = toWorld(state, side * DOOR_NEAR_X, seat.z + DOOR_STAND_DZ);
+ door.y = 0;
+
+ const climbPos = (v) => {
+ const c = climbAt(clamp(v, 0, 1));
+ const p = toWorld(
+ state,
+ lerp(side * DOOR_NEAR_X, seat.x, c.k),
+ lerp(seat.z + DOOR_STAND_DZ, seat.z, c.k)
+ );
+ p.y = seat.y + c.dy + (state.y ?? 0);
+ return { c, p };
+ };
+
+ if (inward) {
+ // One stride up to the door, facing the car the whole way.
+ if (u < A) {
+ const f = smooth(u / A);
+ const pos = new THREE.Vector3().lerpVectors(standPos, door, f);
+ return { pos, yaw: lerpAngle(standYaw, faceYaw, f), pose: stepPose(f) };
+ }
+ const v = (u - A) / (1 - A);
+ const { c, p } = climbPos(v);
+ // Turn to face the windscreen only once the hips are on the cushion, so the
+ // shoulders never sweep through the door frame or the roof.
+ const turn = smooth(clamp((v - 0.62) / 0.3, 0, 1));
+ return { pos: p, yaw: lerpAngle(faceYaw, state.yaw, turn), pose: c.pose };
+ }
+
+ if (u < 1 - A) {
+ const v = u / (1 - A);
+ const { c, p } = climbPos(1 - v);
+ const turn = smooth(clamp(v / 0.34, 0, 1));
+ return { pos: p, yaw: lerpAngle(state.yaw, faceYaw, turn), pose: c.pose };
+ }
+ const f = smooth((u - (1 - A)) / A);
+ const pos = new THREE.Vector3().lerpVectors(door, standPos, f);
+ return { pos, yaw: lerpAngle(faceYaw, standYaw, f), pose: stepPose(f) };
+}
+
+/**
+ * Where to stand. 2.00 m out and 0.30 behind the hinge for a front seat, 0.55
+ * for a rear: an open leaf hangs in its hinge's plane, so an exit level with the
+ * seat puts shoulders and head through the door skin, and 0.72 behind the front
+ * leaves the two occupants 1.2 m apart instead of 0.8, where two figures merge
+ * into one silhouette at this scale.
+ */
+export function standSpot(state, side, seatZ) {
+ return toWorld(state, side * DOOR_STAND_X, seatZ + DOOR_STAND_DZ - (seatZ > 0 ? 0.24 : 0.49));
+}
diff --git a/templates/wake.js b/templates/wake.js
new file mode 100644
index 0000000..383dd04
--- /dev/null
+++ b/templates/wake.js
@@ -0,0 +1,163 @@
+import * as THREE from 'three';
+import { POOL } from '../config.js';
+
+/**
+ * Surface wake: a soft foam streak trailing each swimmer plus pooled ripple
+ * rings. Unlit and additive so it stays bright after the palette pass.
+ */
+function makeWakeTexture() {
+ const c = document.createElement('canvas');
+ c.width = 256;
+ c.height = 128;
+ const ctx = c.getContext('2d');
+ ctx.clearRect(0, 0, 256, 128);
+
+ const head = ctx.createRadialGradient(214, 64, 3, 214, 64, 48);
+ head.addColorStop(0, 'rgba(244, 253, 249, 0.9)');
+ head.addColorStop(0.55, 'rgba(232, 250, 244, 0.35)');
+ head.addColorStop(1, 'rgba(232, 250, 244, 0)');
+ ctx.fillStyle = head;
+ ctx.fillRect(150, 8, 106, 112);
+
+ for (const sign of [-1, 1]) {
+ const g = ctx.createLinearGradient(222, 64, 6, 64 + sign * 40);
+ g.addColorStop(0, 'rgba(238, 252, 247, 0.5)');
+ g.addColorStop(0.6, 'rgba(238, 252, 247, 0.16)');
+ g.addColorStop(1, 'rgba(238, 252, 247, 0)');
+ ctx.strokeStyle = g;
+ ctx.lineWidth = 11;
+ ctx.lineCap = 'round';
+ ctx.beginPath();
+ ctx.moveTo(214, 64);
+ ctx.quadraticCurveTo(120, 64 + sign * 22, 6, 64 + sign * 42);
+ ctx.stroke();
+ }
+
+ for (let i = 0; i < 26; i++) {
+ const x = 40 + Math.random() * 190;
+ const y = 64 + (Math.random() - 0.5) * 70;
+ const r = 1 + Math.random() * 3;
+ ctx.fillStyle = `rgba(245, 253, 250, ${0.12 + Math.random() * 0.28})`;
+ ctx.beginPath();
+ ctx.arc(x, y, r, 0, Math.PI * 2);
+ ctx.fill();
+ }
+
+ const tex = new THREE.CanvasTexture(c);
+ tex.colorSpace = THREE.SRGBColorSpace;
+ return tex;
+}
+
+export function createWake(count = 2) {
+ const group = new THREE.Group();
+ const tex = makeWakeTexture();
+
+ const trails = [];
+ for (let i = 0; i < count; i++) {
+ const mat = new THREE.MeshBasicMaterial({
+ map: tex,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+ const geo = new THREE.PlaneGeometry(2.5, 1.25);
+ geo.rotateX(-Math.PI / 2);
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.y = POOL.waterY + 0.008;
+ mesh.renderOrder = 7;
+ mesh.visible = false;
+ group.add(mesh);
+ trails.push({ mesh, mat, phase: i * 1.7 });
+ }
+
+ const rings = [];
+ const ringGeo = new THREE.RingGeometry(0.3, 0.36, 26);
+ ringGeo.rotateX(-Math.PI / 2);
+ for (let i = 0; i < 12; i++) {
+ const mat = new THREE.MeshBasicMaterial({
+ color: 0xe9f9f3,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+ const mesh = new THREE.Mesh(ringGeo, mat);
+ mesh.position.y = POOL.waterY + 0.0105;
+ mesh.renderOrder = 8;
+ mesh.visible = false;
+ group.add(mesh);
+ rings.push({ mesh, mat, age: 0, live: false });
+ }
+ let ringCursor = 0;
+ let spawnClock = 0;
+
+ /**
+ * entries: [{ x, z, yaw, active }] — body centre, heading, on/off.
+ */
+ function update(dt, t, entries) {
+ spawnClock += dt;
+ const spawn = spawnClock > 0.42;
+ if (spawn) spawnClock = 0;
+
+ entries.forEach((e, i) => {
+ const trail = trails[i];
+ if (!trail) return;
+ trail.mesh.visible = !!e.active;
+ if (!e.active) return;
+ const hx = Math.cos(e.yaw);
+ const hz = -Math.sin(e.yaw);
+ trail.mesh.position.set(e.x - hx * 0.95, POOL.waterY + 0.008, e.z - hz * 0.95);
+ trail.mesh.rotation.y = e.yaw;
+ const pulse = 0.30 + Math.sin(t * 3.1 + trail.phase) * 0.05;
+ trail.mat.opacity = pulse;
+ trail.mesh.scale.set(1 + Math.sin(t * 2.2 + trail.phase) * 0.05, 1, 1);
+
+ if (spawn) {
+ const ring = rings[ringCursor % rings.length];
+ ringCursor++;
+ ring.age = 0;
+ ring.live = true;
+ ring.mesh.visible = true;
+ ring.mesh.position.set(e.x - hx * 1.1, POOL.waterY + 0.0105, e.z - hz * 1.1);
+ ring.mesh.scale.setScalar(0.35);
+ ring.mat.opacity = 0.45;
+ }
+ });
+
+ for (const r of rings) {
+ if (!r.live) continue;
+ r.age += dt;
+ const k = r.age / 1.5;
+ if (k >= 1) {
+ r.live = false;
+ r.mesh.visible = false;
+ continue;
+ }
+ r.mesh.scale.setScalar(0.3 + k * 1.15);
+ r.mat.opacity = 0.38 * (1 - k) * (1 - k);
+ }
+ }
+
+ /**
+ * Drop every trail and ring. Call this before re-simulating the effects from
+ * zero, which is how a frozen frame (?t=) stays identical to the played one:
+ * these effects integrate dt, so a jump in the clock is not a jump in state.
+ */
+ function reset() {
+ ringCursor = 0;
+ spawnClock = 0;
+ for (const t of trails) {
+ t.mesh.visible = false;
+ t.mat.opacity = 0;
+ }
+ for (const r of rings) {
+ r.age = 0;
+ r.live = false;
+ r.mesh.visible = false;
+ r.mat.opacity = 0;
+ }
+ }
+
+ return { group, update, reset };
+}
diff --git a/templates/water.js b/templates/water.js
new file mode 100644
index 0000000..70b8f19
--- /dev/null
+++ b/templates/water.js
@@ -0,0 +1,50 @@
+import * as THREE from 'three';
+import { POOL } from '../config.js';
+import { timeUniform } from '../core/materials.js';
+
+/**
+ * Flat, glassy water. A standard physical material keeps shadows, environment
+ * reflection and tone mapping consistent with the rest of the diorama, which a
+ * hand-written shader would otherwise have to reimplement per light.
+ */
+export function createWater() {
+ const geo = new THREE.PlaneGeometry(12.94, 6.94, 10, 6);
+ geo.rotateX(-Math.PI / 2);
+
+ // Shallow end reads pale teal, the deep end nearly navy. Interpolated in
+ // vertex colours so the surface itself carries the pool's depth.
+ const pos = geo.attributes.position;
+ const shallow = new THREE.Color(0x3f9397);
+ const deep = new THREE.Color(0x2a707a);
+ const colors = new Float32Array(pos.count * 3);
+ const c = new THREE.Color();
+ for (let i = 0; i < pos.count; i++) {
+ const t = Math.min(1, Math.max(0, (pos.getX(i) + 6.3) / 11.6));
+ c.copy(shallow).lerp(deep, t * t * 0.85);
+ colors[i * 3] = c.r;
+ colors[i * 3 + 1] = c.g;
+ colors[i * 3 + 2] = c.b;
+ }
+ geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
+
+ const mat = new THREE.MeshPhysicalMaterial({
+ color: 0xffffff,
+ vertexColors: true,
+ roughness: 0.16,
+ metalness: 0.0,
+ clearcoat: 0.7,
+ clearcoatRoughness: 0.1,
+ envMapIntensity: 0.4,
+ transparent: true,
+ opacity: 0.62,
+ depthWrite: false,
+ side: THREE.FrontSide,
+ });
+
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.y = POOL.waterY;
+ mesh.renderOrder = 5;
+ mesh.receiveShadow = true;
+ mesh.userData.uniforms = { uTime: timeUniform };
+ return mesh;
+}
diff --git a/verify/climb/README.md b/verify/climb/README.md
new file mode 100644
index 0000000..50c0296
--- /dev/null
+++ b/verify/climb/README.md
@@ -0,0 +1,19 @@
+# Climb harness
+
+A unit test for `transfer.js`, the one piece of the kit that is tedious to get
+right and easy to break: no browser, no render, just the maths.
+
+```bash
+npm i three # transfer.js imports THREE for Vector3
+npm test
+```
+
+Checks, in order: the move is continuous (no frame jumps a body length, which is
+what reads as "not human"), the root never climbs above a step, the exit finishes
+on the stand spot and the entry on the seat, and the entry faces the car at the
+door rather than the street. Current result: 5.8 cm per frame at 60 fps both ways,
+root -0.38 to 0.00, all landing assertions inside 2 mm.
+
+If you retune `CLIMB` or `STEP_SHARE`, re-run this before looking at a single
+screenshot: a pop of 15 cm per frame is invisible in a still and obvious in
+motion.
diff --git a/verify/climb/package.json b/verify/climb/package.json
new file mode 100644
index 0000000..46af422
--- /dev/null
+++ b/verify/climb/package.json
@@ -0,0 +1,5 @@
+{
+ "type": "module",
+ "private": true,
+ "scripts": { "test": "node test.mjs" }
+}
diff --git a/verify/climb/src/config.js b/verify/climb/src/config.js
new file mode 100644
index 0000000..a3090ba
--- /dev/null
+++ b/verify/climb/src/config.js
@@ -0,0 +1,26 @@
+/**
+ * Scene constants. Every template that draws water or walks a track reads these.
+ * Values are metres.
+ */
+export const POOL = {
+ waterY: 0.06,
+ hx: 6.5,
+ hz: 3.5,
+ bottomY: -1.4,
+};
+
+export const SCENE = {
+ slab: { hx: 7.4, hz: 4.4, thick: 0.42 },
+};
+
+export const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
+export const lerp = (a, b, t) => a + (b - a) * t;
+export const smooth = (t) => {
+ const u = clamp(t, 0, 1);
+ return u * u * (3 - 2 * u);
+};
+
+/** Deck height at a point. Flat here; a play with steps overrides it. */
+export function groundY() {
+ return 0;
+}
diff --git a/verify/climb/src/scene/poses.js b/verify/climb/src/scene/poses.js
new file mode 100644
index 0000000..a6eeb06
--- /dev/null
+++ b/verify/climb/src/scene/poses.js
@@ -0,0 +1,313 @@
+import { lerp } from '../config.js';
+
+/**
+ * The pose library. Every entry is a full set of joint angles, in radians, for
+ * the rig in peopleModel.js. Poses are absolute, never deltas: a partial pose
+ * leaves the previous value on any joint it does not name, and the error
+ * accumulates the moment two poses are blended in a loop.
+ *
+ * Joint order in every entry is [x, y, z]:
+ * torso head shoulderL/R elbowL/R wristL/R hipL/R kneeL/R ankleL/R
+ *
+ * Signs, which are the whole game:
+ * +hip X swings the thigh backward, -hip X forward
+ * +knee X bends the heel backward, a negative knee hyperextends
+ * +shoulder X swings the arm backward, -shoulder X forward
+ * -elbow X folds the forearm toward the face
+ */
+
+export const STAND = {
+ torso: [0.03, 0, 0],
+ head: [0, 0, 0],
+ shoulderL: [0.02, 0, -0.1],
+ shoulderR: [0.02, 0, 0.1],
+ elbowL: [-0.17, 0, 0],
+ elbowR: [-0.17, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [0, 0, 0.02],
+ hipR: [0, 0, -0.02],
+ kneeL: [0.05, 0, 0],
+ kneeR: [0.05, 0, 0],
+ ankleL: [-0.03, 0, 0],
+ ankleR: [-0.03, 0, 0],
+};
+
+/** Seated: thighs forward and level, shins down, torso a touch back. */
+export const SEATED = {
+ torso: [0.05, 0, 0],
+ head: [0, 0, 0],
+ shoulderL: [-0.72, 0, -0.14],
+ shoulderR: [-0.72, 0, 0.14],
+ elbowL: [-0.52, 0, 0],
+ elbowR: [-0.52, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-1.5, 0, 0.05],
+ hipR: [-1.5, 0, -0.05],
+ kneeL: [0.52, 0, 0],
+ kneeR: [0.52, 0, 0],
+ ankleL: [0.18, 0, 0],
+ ankleR: [0.18, 0, 0],
+};
+
+/** Perched on the seat edge, legs swung out of the door aperture. */
+export const LEGS_OUT = {
+ torso: [0.2, 0, 0],
+ head: [-0.06, 0, 0],
+ shoulderL: [-0.62, 0, -0.3],
+ shoulderR: [-0.55, 0, 0.34],
+ elbowL: [-0.72, 0, 0],
+ elbowR: [-0.6, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.88, 0, 0.14],
+ hipR: [-0.72, 0, -0.1],
+ kneeL: [0.62, 0, 0],
+ kneeR: [0.48, 0, 0],
+ ankleL: [-0.16, 0, 0],
+ ankleR: [-0.12, 0, 0],
+};
+
+/**
+ * Climbing in, beat 1: standing square to the open door, near hand up to the
+ * roof edge, weight already moving onto the front foot.
+ */
+export const REACH = {
+ torso: [0.14, 0.04, 0.04],
+ head: [-0.1, 0.12, 0],
+ shoulderL: [-0.42, 0, -0.26],
+ shoulderR: [-1.52, 0, 0.24],
+ elbowL: [-0.62, 0, 0],
+ elbowR: [-0.48, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [-0.25, 0, 0],
+ hipL: [-0.22, 0, 0.06],
+ hipR: [-0.1, 0, -0.06],
+ kneeL: [0.4, 0, 0],
+ kneeR: [0.26, 0, 0],
+ ankleL: [-0.16, 0, 0],
+ ankleR: [-0.12, 0, 0],
+};
+
+/**
+ * Climbing in, beat 2: knees deep, hips dropping to cushion height just outside
+ * the sill, head still clear of the roof, one hand braced on the door.
+ */
+export const CROUCH_IN = {
+ torso: [0.52, 0.1, 0.02],
+ head: [-0.34, 0.1, 0],
+ shoulderL: [-0.92, 0, -0.26],
+ shoulderR: [-1.3, 0, 0.26],
+ elbowL: [-1.05, 0, 0],
+ elbowR: [-0.72, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.72, 0, 0.12],
+ hipR: [-0.66, 0, -0.1],
+ kneeL: [1.12, 0, 0],
+ kneeR: [1.04, 0, 0],
+ ankleL: [-0.34, 0, 0],
+ ankleR: [-0.3, 0, 0],
+};
+
+/**
+ * Climbing in, beat 3: perched on the seat edge, both feet still on the road,
+ * torso folded under the roof line.
+ */
+export const SIT_EDGE = {
+ torso: [0.46, 0.12, 0],
+ head: [-0.26, 0.1, 0],
+ shoulderL: [-0.55, 0, -0.3],
+ shoulderR: [-0.95, 0, 0.3],
+ elbowL: [-0.95, 0, 0],
+ elbowR: [-0.85, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-1.12, 0, 0.11],
+ hipR: [-1.04, 0, -0.09],
+ kneeL: [1.12, 0, 0],
+ kneeR: [1.06, 0, 0],
+ ankleL: [-0.02, 0, 0],
+ ankleR: [-0.04, 0, 0],
+};
+
+/**
+ * Climbing in, beat 4: hips on the cushion, knees up and feet swinging in over
+ * the sill.
+ */
+export const LEGS_IN = {
+ torso: [0.36, 0.16, 0],
+ head: [-0.16, 0.1, 0],
+ shoulderL: [-0.5, 0, -0.28],
+ shoulderR: [-0.62, 0, 0.28],
+ elbowL: [-1.1, 0, 0],
+ elbowR: [-1.05, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-1.46, 0, 0.1],
+ hipR: [-1.4, 0, -0.1],
+ kneeL: [1.58, 0, 0],
+ kneeR: [1.5, 0, 0],
+ ankleL: [0.16, 0, 0],
+ ankleR: [0.14, 0, 0],
+};
+
+/** Feet planted, knees deep, one hand on the door frame. */
+export const DUCK = {
+ torso: [0.46, 0, 0],
+ head: [-0.26, 0, 0],
+ shoulderL: [-0.8, 0, -0.26],
+ shoulderR: [-0.3, 0, 0.3],
+ elbowL: [-0.95, 0, 0],
+ elbowR: [-0.45, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.72, 0, 0.16],
+ hipR: [-0.58, 0, -0.12],
+ kneeL: [1.38, 0, 0],
+ kneeR: [1.2, 0, 0],
+ ankleL: [-0.42, 0, 0],
+ ankleR: [-0.34, 0, 0],
+};
+
+/** Feet planted, squatting, both hands free: the working crouch. */
+export const CROUCH = {
+ torso: [0.3, 0, 0],
+ head: [-0.16, 0, 0],
+ shoulderL: [-0.3, 0, -0.22],
+ shoulderR: [-0.26, 0, 0.24],
+ elbowL: [-0.7, 0, 0],
+ elbowR: [-0.62, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [-0.98, 0, 0.14],
+ hipR: [-0.86, 0, -0.12],
+ kneeL: [1.52, 0, 0],
+ kneeR: [1.38, 0, 0],
+ ankleL: [-0.46, 0, 0],
+ ankleR: [-0.4, 0, 0],
+};
+
+/** Both arms out and level: aiming a weapon, a hose, a torch. */
+export const REACH_FWD = {
+ ...STAND,
+ torso: [0.08, 0, 0],
+ shoulderL: [-1.34, 0, -0.12],
+ shoulderR: [-1.3, 0, 0.1],
+ elbowL: [-0.3, 0, 0],
+ elbowR: [-0.22, 0, 0],
+ hipL: [-0.16, 0, 0.06],
+ hipR: [0.1, 0, -0.08],
+ kneeL: [0.34, 0, 0],
+ kneeR: [0.22, 0, 0],
+ ankleL: [-0.16, 0, 0],
+ ankleR: [-0.06, 0, 0],
+};
+
+/** Alias kept for scenes that read better with the old name. */
+export const AIM = REACH_FWD;
+
+/** Arms bent up, carrying something against the chest. */
+export const CARRY = {
+ shoulderR: [0.14, 0, 0.12],
+ elbowR: [-0.12, 0, 0],
+ shoulderL: [-0.1, 0, -0.12],
+ elbowL: [-0.3, 0, 0],
+};
+
+/** Wind-up and release for throwing a weight into a container. */
+export const THROW_BACK = {
+ ...STAND,
+ torso: [0.04, -0.26, 0],
+ head: [0, -0.2, 0],
+ shoulderR: [0.95, 0, 0.22],
+ elbowR: [-1.15, 0, 0],
+ shoulderL: [-0.45, 0, -0.2],
+ elbowL: [-0.55, 0, 0],
+ hipL: [-0.12, 0, 0.05],
+ hipR: [0.14, 0, -0.05],
+};
+
+export const THROW_FWD = {
+ ...STAND,
+ torso: [0.22, 0.2, 0],
+ head: [-0.05, 0.12, 0],
+ shoulderR: [-1.55, 0, 0.1],
+ elbowR: [-0.18, 0, 0],
+ shoulderL: [0.2, 0, -0.28],
+ elbowL: [-0.85, 0, 0],
+ hipL: [0.1, 0, 0.05],
+ hipR: [-0.16, 0, -0.05],
+ kneeL: [0.24, 0, 0],
+ kneeR: [0.18, 0, 0],
+};
+
+/**
+ * Component-wise blend. Missing joints fall back to zero, which is why every
+ * pose above names the full set.
+ */
+export function mixPose(a, b, k) {
+ const out = {};
+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
+ const av = a[key] ?? [0, 0, 0];
+ const bv = b[key] ?? [0, 0, 0];
+ out[key] = [
+ lerp(av[0] ?? 0, bv[0] ?? 0, k),
+ lerp(av[1] ?? 0, bv[1] ?? 0, k),
+ lerp(av[2] ?? 0, bv[2] ?? 0, k),
+ ];
+ }
+ return out;
+}
+
+/**
+ * Walk cycle. Phase is driven by distance travelled, not by time, so the feet
+ * never skate: speed = 2 * legLength * sin(amp) * phaseRate / PI.
+ *
+ * opts: amp (hip), armAmp, lean, kneeBase, carry (keeps the right arm occupied)
+ */
+export function walkPose(phase, opts = {}) {
+ const amp = opts.amp ?? 0.32;
+ const armAmp = opts.armAmp ?? 0.44;
+ const lean = opts.lean ?? 0.05;
+ const kneeBase = opts.kneeBase ?? 0.06;
+ const swing = Math.sin(phase);
+ const cs = Math.cos(phase);
+ const kneeL = kneeBase + 0.46 * Math.max(0, -cs) + 0.22 * Math.max(0, swing);
+ const kneeR = kneeBase + 0.46 * Math.max(0, cs) + 0.22 * Math.max(0, -swing);
+ const p = {
+ torso: [lean, swing * 0.05, 0],
+ head: [0, -swing * 0.04, 0],
+ shoulderL: [-swing * armAmp, 0, -0.09],
+ shoulderR: [swing * armAmp, 0, 0.09],
+ elbowL: [-0.16 - Math.max(0, swing) * 0.28, 0, 0],
+ elbowR: [-0.16 - Math.max(0, -swing) * 0.28, 0, 0],
+ wristL: [0, 0, 0],
+ wristR: [0, 0, 0],
+ hipL: [swing * amp, 0, 0.03],
+ hipR: [-swing * amp, 0, -0.03],
+ kneeL: [kneeL, 0, 0],
+ kneeR: [kneeR, 0, 0],
+ ankleL: [-kneeL * 0.32, 0, 0],
+ ankleR: [-kneeR * 0.32, 0, 0],
+ };
+ if (opts.carry) {
+ p.shoulderR = [0.1 + swing * 0.06, 0, 0.12];
+ p.elbowR = [-0.14, 0, 0];
+ p.shoulderL = [-swing * armAmp * 1.15, 0, -0.1];
+ }
+ return p;
+}
+
+/** Same cycle, driven harder: longer stride, forward lean, elbows tucked. */
+export function runPose(phase, opts = {}) {
+ const p = walkPose(phase, { amp: 0.52, armAmp: 0.72, lean: 0.26, kneeBase: 0.12, ...opts });
+ const bob = Math.abs(Math.cos(phase));
+ p.torso = [0.26 + bob * 0.03, p.torso[1], 0];
+ p.elbowL = [-0.75, 0, 0];
+ p.elbowR = opts.carry ? [-0.18, 0, 0] : [-0.75, 0, 0];
+ p.shoulderL = [-Math.sin(phase) * 0.8, 0, -0.14];
+ p.shoulderR = opts.carry ? [0.16, 0, 0.14] : [Math.sin(phase) * 0.8, 0, 0.14];
+ return p;
+}
diff --git a/verify/climb/src/scene/transfer.js b/verify/climb/src/scene/transfer.js
new file mode 100644
index 0000000..fec940d
--- /dev/null
+++ b/verify/climb/src/scene/transfer.js
@@ -0,0 +1,184 @@
+import * as THREE from 'three';
+import { clamp, lerp, smooth } from '../config.js';
+import {
+ STAND,
+ SEATED,
+ REACH,
+ CROUCH_IN,
+ SIT_EDGE,
+ LEGS_IN,
+ mixPose,
+} from './poses.js';
+
+/**
+ * Getting in and out of a seat: the whole move, authored in the CAR's own frame
+ * so it works at any parking angle.
+ *
+ * Why this ships as code rather than as advice: it is the single most fragile
+ * thing in a vehicle play. Every previous attempt failed the same three ways,
+ * and none of them are visible in a still:
+ *
+ * 1. A straight lerp from the pavement to the seat drags the body through the
+ * door skin. The climb has to be keyed: knees drop, hips land on the sill,
+ * then the legs swing in.
+ * 2. The outbound yaw points away from the car. Reused on the way in, it makes
+ * the figure climb in backwards, face to the street, and turn a half circle
+ * during the first frames. On the way in, every key before the seated ones
+ * faces the car.
+ * 3. Taking that facing from the approach path's tangent is wrong: the path's
+ * opening segment runs along the street, so `path.at(0).yaw + PI` points
+ * down the kerb. Resolve it from the seat and stand positions.
+ *
+ * Usage, per figure:
+ *
+ * const seat = { x: side * 0.40, z: 0.30, y: SEAT_ROOT_Y };
+ * const stand = toWorld(car, side * 2.00, seat.z - 0.30);
+ * const r = transfer(t, t0, 1.15, car, side, seat, stand, face, false);
+ * place(actor, r.pos, r.yaw, r.pose);
+ *
+ * where `face = Math.atan2(seatWorld.x - stand.x, seatWorld.z - stand.z)`.
+ */
+
+const PI = Math.PI;
+
+/** Seat root: cushion top minus hipY, so the hips settle into the cushion. */
+export const SEAT_ROOT_Y = -0.38;
+/** How far out from the car's centreline the stand spot sits. */
+export const DOOR_STAND_X = 2.0;
+/** Stand this far behind the hinge, so the open leaf clears the shoulders. */
+export const DOOR_STAND_DZ = -0.06;
+/** The stand spot used by the climb itself, inside the outer stand spot. */
+export const DOOR_NEAR_X = 1.34;
+/** Share of the transfer window spent taking the stride to the door. */
+export const STEP_SHARE = 0.26;
+
+export function toWorld(base, x, z) {
+ const c = Math.cos(base.yaw);
+ const s = Math.sin(base.yaw);
+ return new THREE.Vector3(base.x + x * c + z * s, 0, base.z - x * s + z * c);
+}
+
+export function clampAngle(a) {
+ let x = a;
+ while (x > PI) x -= PI * 2;
+ while (x < -PI) x += PI * 2;
+ return x;
+}
+
+export const lerpAngle = (a, b, k) => a + clampAngle(b - a) * k;
+
+/**
+ * The climb. k runs 0 at the open door to 1 at the seat; dy is the root height
+ * above the seated root. The body only reaches cushion height once the hips are
+ * over the sill, which is what stops it sinking, floating or sliding through the
+ * bodywork.
+ */
+export const CLIMB = [
+ { u: 0.0, k: 0.0, dy: 0.38, pose: STAND },
+ { u: 0.16, k: 0.03, dy: 0.33, pose: REACH }, // hand to the roof edge
+ { u: 0.36, k: 0.16, dy: 0.12, pose: CROUCH_IN }, // knees deep, hips dropping
+ { u: 0.56, k: 0.38, dy: 0.01, pose: SIT_EDGE }, // perched, feet still down
+ { u: 0.76, k: 0.66, dy: 0.0, pose: LEGS_IN }, // knees up, feet over the sill
+ { u: 0.9, k: 0.88, dy: 0.0, pose: mixPose(LEGS_IN, SEATED, 0.55) },
+ { u: 1.0, k: 1.0, dy: 0.0, pose: SEATED },
+];
+
+export function climbAt(u) {
+ let a = CLIMB[0];
+ let b = CLIMB[CLIMB.length - 1];
+ for (let i = 1; i < CLIMB.length; i++) {
+ if (u <= CLIMB[i].u) {
+ a = CLIMB[i - 1];
+ b = CLIMB[i];
+ break;
+ }
+ }
+ const f = smooth(clamp((u - a.u) / Math.max(0.0001, b.u - a.u), 0, 1));
+ return { k: lerp(a.k, b.k, f), dy: lerp(a.dy, b.dy, f), pose: mixPose(a.pose, b.pose, f) };
+}
+
+/** One stride on the pavement, used at both ends of the climb. */
+export function stepPose(f) {
+ const lift = Math.sin(PI * clamp(f, 0, 1));
+ return {
+ ...STAND,
+ torso: [0.06 + 0.08 * f, 0, 0],
+ head: [-0.02, 0, 0],
+ hipL: [-0.36 * lift, 0, 0.04],
+ hipR: [0.22 * lift, 0, -0.04],
+ kneeL: [0.1 + 0.55 * lift, 0, 0],
+ kneeR: [0.16, 0, 0],
+ ankleL: [-0.1 - 0.16 * lift, 0, 0],
+ ankleR: [-0.1, 0, 0],
+ };
+}
+
+/**
+ * The whole move between the pavement and a seat.
+ *
+ * t timeline seconds
+ * t0 window start
+ * dur window length; 1.05 to 1.20 s each way, never under 0.9
+ * state the car: { x, z, yaw } (plus optional y offset)
+ * side -1 or +1: which flank the door is on, in car space
+ * seat { x, z, y } seat root in car space
+ * standPos pavement spot, world Vector3 ({x,y,z})
+ * standYaw heading to hold when standing (only used on the way out)
+ * inward true to climb in, false to climb out
+ *
+ * Returns { pos, yaw, pose }. Assign it to the actor's group and call setPose.
+ */
+export function transfer(t, t0, dur, state, side, seat, standPos, standYaw, inward) {
+ const u = clamp((t - t0) / Math.max(0.1, dur), 0, 1);
+ const A = STEP_SHARE;
+ const faceYaw = state.yaw - side * (PI / 2); // square to the open door
+ const door = toWorld(state, side * DOOR_NEAR_X, seat.z + DOOR_STAND_DZ);
+ door.y = 0;
+
+ const climbPos = (v) => {
+ const c = climbAt(clamp(v, 0, 1));
+ const p = toWorld(
+ state,
+ lerp(side * DOOR_NEAR_X, seat.x, c.k),
+ lerp(seat.z + DOOR_STAND_DZ, seat.z, c.k)
+ );
+ p.y = seat.y + c.dy + (state.y ?? 0);
+ return { c, p };
+ };
+
+ if (inward) {
+ // One stride up to the door, facing the car the whole way.
+ if (u < A) {
+ const f = smooth(u / A);
+ const pos = new THREE.Vector3().lerpVectors(standPos, door, f);
+ return { pos, yaw: lerpAngle(standYaw, faceYaw, f), pose: stepPose(f) };
+ }
+ const v = (u - A) / (1 - A);
+ const { c, p } = climbPos(v);
+ // Turn to face the windscreen only once the hips are on the cushion, so the
+ // shoulders never sweep through the door frame or the roof.
+ const turn = smooth(clamp((v - 0.62) / 0.3, 0, 1));
+ return { pos: p, yaw: lerpAngle(faceYaw, state.yaw, turn), pose: c.pose };
+ }
+
+ if (u < 1 - A) {
+ const v = u / (1 - A);
+ const { c, p } = climbPos(1 - v);
+ const turn = smooth(clamp(v / 0.34, 0, 1));
+ return { pos: p, yaw: lerpAngle(state.yaw, faceYaw, turn), pose: c.pose };
+ }
+ const f = smooth((u - (1 - A)) / A);
+ const pos = new THREE.Vector3().lerpVectors(door, standPos, f);
+ return { pos, yaw: lerpAngle(faceYaw, standYaw, f), pose: stepPose(f) };
+}
+
+/**
+ * Where to stand. 2.00 m out and 0.30 behind the hinge for a front seat, 0.55
+ * for a rear: an open leaf hangs in its hinge's plane, so an exit level with the
+ * seat puts shoulders and head through the door skin, and 0.72 behind the front
+ * leaves the two occupants 1.2 m apart instead of 0.8, where two figures merge
+ * into one silhouette at this scale.
+ */
+export function standSpot(state, side, seatZ) {
+ return toWorld(state, side * DOOR_STAND_X, seatZ + DOOR_STAND_DZ - (seatZ > 0 ? 0.24 : 0.49));
+}
diff --git a/verify/climb/test.mjs b/verify/climb/test.mjs
new file mode 100644
index 0000000..88295d3
--- /dev/null
+++ b/verify/climb/test.mjs
@@ -0,0 +1,58 @@
+import assert from 'node:assert';
+import { transfer, standSpot, toWorld, SEAT_ROOT_Y } from './src/scene/transfer.js';
+import { SEATED, STAND } from './src/scene/poses.js';
+
+// A car parked square, left flank toward the camera.
+const car = { x: -3.0, z: 2.55, yaw: Math.PI / 2 };
+const side = -1;
+const seatZ = 0.3;
+const seat = { x: side * 0.4, z: seatZ, y: SEAT_ROOT_Y };
+const seatWorld = toWorld(car, seat.x, seat.z);
+seatWorld.y = seat.y;
+const stand = standSpot(car, side, seatZ);
+const face = Math.atan2(seatWorld.x - stand.x, seatWorld.z - stand.z);
+
+/**
+ * A transfer must be continuous: consecutive samples move by centimetres, never
+ * by a body length. A pop here is what the user calls "not human" and no still
+ * frame shows it.
+ */
+function sweep(inward) {
+ const DUR = 1.15;
+ let prev = null;
+ let maxStep = 0;
+ let minY = 1e9;
+ let maxY = -1e9;
+ for (let t = 0; t <= DUR + 1e-6; t += 1 / 60) {
+ const r = transfer(t, 0, DUR, car, side, seat, stand, face, inward);
+ minY = Math.min(minY, r.pos.y);
+ maxY = Math.max(maxY, r.pos.y);
+ if (prev) maxStep = Math.max(maxStep, prev.distanceTo(r.pos));
+ prev = r.pos.clone();
+ }
+ return { maxStep, minY, maxY };
+}
+
+for (const inward of [false, true]) {
+ const { maxStep, minY, maxY } = sweep(inward);
+ console.log(
+ `${inward ? 'entry' : 'exit '} max step ${(maxStep * 100).toFixed(1)} cm/frame ` +
+ `y ${minY.toFixed(2)}..${maxY.toFixed(2)}`
+ );
+ assert(maxStep < 0.12, `${inward ? 'entry' : 'exit'} pops: ${maxStep.toFixed(3)} m in one frame`);
+ assert(maxY < 0.6, 'the root climbed above the seat by more than a step');
+}
+
+// Ends where it says it ends.
+const exitEnd = transfer(1.15, 0, 1.15, car, side, seat, stand, face, false);
+assert(exitEnd.pos.distanceTo(stand) < 0.02, 'exit did not finish on the stand spot');
+const entryEnd = transfer(1.15, 0, 1.15, car, side, seat, stand, face, true);
+assert(entryEnd.pos.distanceTo(seatWorld) < 0.02, 'entry did not finish on the seat');
+
+// The entry faces the car at the door, and the exit faces the pavement.
+const entryMid = transfer(0.3, 0, 1.15, car, side, seat, stand, face, true);
+const toCar = Math.atan2(seatWorld.x - entryMid.pos.x, seatWorld.z - entryMid.pos.z);
+let dy = Math.abs(((entryMid.yaw - toCar + Math.PI * 3) % (Math.PI * 2)) - Math.PI);
+assert(dy < 0.35, `entry is ${(dy * 57.3).toFixed(0)} deg off facing the car`);
+
+console.log('transfer: continuous, lands on the seat, faces the car on the way in');
diff --git a/verify/water/README.md b/verify/water/README.md
new file mode 100644
index 0000000..959de38
--- /dev/null
+++ b/verify/water/README.md
@@ -0,0 +1,27 @@
+# Water harness
+
+A working scene for `water.js`, `wake.js` and `splash.js`, and a worked example
+of the QA loop. No story, no cast: two swimmers crossing a pool on a sine, a
+timed splash, and the post pass.
+
+```bash
+npm i three esbuild playwright-core # or link a project that already has them
+node build.mjs # dist/app.js + index.html
+python3 -m http.server 4181 &
+BASE_URL=http://127.0.0.1:4181/index.html QA_DIR=shots SHOTS="1.75:splash" \
+ node ../../templates/qa/shoot.mjs # copy the qa folder into the root first
+```
+
+## What the verification found
+
+- `water.js` is sound: the vertex ramp reads as depth provided the pool's shallow
+ to deep axis matches the plane's local X, and the basin under it is dark. A deck
+ box spanning the whole slab puts beige under the water and the surface reads as
+ a stain, which is a scene bug, not an effect bug.
+- `wake.js` works; rings are pooled and one `spawn` tick is shared by every
+ swimmer, so more than four bodies will exhaust the ring pool.
+- `splash.js` used `Math.random` in `trigger`, so two identical frames never
+ matched. It now takes a `burstSeed`. Both effects also gained `reset()`: they
+ integrate `dt`, so freezing the clock does not reset them, and a frozen frame
+ showed the last played state. Re-simulating from zero in fixed steps took a
+ two-frame diff from 334 differing pixels to 18.
diff --git a/verify/water/build.mjs b/verify/water/build.mjs
new file mode 100644
index 0000000..e4bb9df
--- /dev/null
+++ b/verify/water/build.mjs
@@ -0,0 +1,94 @@
+import { build } from 'esbuild';
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+
+const minify = process.argv.includes('--minify');
+
+await mkdir('dist', { recursive: true });
+
+await build({
+ entryPoints: ['src/main.js'],
+ bundle: true,
+ format: 'iife',
+ target: ['es2020'],
+ outfile: 'dist/app.js',
+ minify,
+ sourcemap: minify ? false : 'inline',
+ legalComments: 'none',
+ logLevel: 'info',
+});
+
+const js = await readFile('dist/app.js', 'utf8');
+const safeJs = js.replace(/<\/script/gi, '<\\/script');
+
+const css = `
+ :root { color-scheme: light; }
+ * { box-sizing: border-box; }
+ html, body {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+ overflow: hidden;
+ background: #ffffff;
+ }
+ body { -webkit-tap-highlight-color: transparent; }
+ #frame {
+ position: fixed;
+ left: 50%;
+ top: 50%;
+ width: 64vw;
+ height: 64vh;
+ transform: translate(-50%, -50%);
+ background: #ffffff;
+ }
+ @media (max-width: 620px) {
+ #frame { width: 94vw; height: 94vh; }
+ }
+ #stage {
+ display: block;
+ width: 100%;
+ height: 100%;
+ background: #ffffff;
+ image-rendering: pixelated;
+ image-rendering: crisp-edges;
+ outline: none;
+ }
+ #fallback {
+ position: fixed;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ background: #ffffff;
+ color: #333a3d;
+ font: 14px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
+ letter-spacing: 0.02em;
+ text-align: center;
+ padding: 2rem;
+ }
+ #fallback[hidden] { display: none; }
+`;
+
+function page(scriptTag) {
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<link rel="icon" href="data:," />
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+<meta name="theme-color" content="#ffffff" />
+<title>Swimming Pool — a small diorama</title>
+<style>${css}</style>
+</head>
+<body>
+<div id="frame"><canvas id="stage" aria-label="A real-time rendered miniature swimming pool diorama" tabindex="-1"></canvas></div>
+<div id="fallback" hidden>This diorama needs a browser with WebGL2 enabled.</div>
+${scriptTag}
+</body>
+</html>
+`;
+}
+
+await writeFile('index.html', page('<script src="./dist/app.js"></script>'));
+await writeFile('pool-diorama.html', page(`<script>${safeJs}</script>`));
+
+console.log(`built dist/app.js (${(js.length / 1024).toFixed(0)} kB), index.html, pool-diorama.html`);
diff --git a/verify/water/shots/crop.png b/verify/water/shots/crop.png
new file mode 100644
index 0000000..43760eb
Binary files /dev/null and b/verify/water/shots/crop.png differ
diff --git a/verify/water/shots/ipad-a.png b/verify/water/shots/ipad-a.png
new file mode 100644
index 0000000..7aeac96
Binary files /dev/null and b/verify/water/shots/ipad-a.png differ
diff --git a/verify/water/shots/ipad-bsp.png b/verify/water/shots/ipad-bsp.png
new file mode 100644
index 0000000..cd4e143
Binary files /dev/null and b/verify/water/shots/ipad-bsp.png differ
diff --git a/verify/water/shots/ipad-c.png b/verify/water/shots/ipad-c.png
new file mode 100644
index 0000000..daaf0f6
Binary files /dev/null and b/verify/water/shots/ipad-c.png differ
diff --git a/verify/water/shots/ipad-dsp.png b/verify/water/shots/ipad-dsp.png
new file mode 100644
index 0000000..fe72113
Binary files /dev/null and b/verify/water/shots/ipad-dsp.png differ
diff --git a/verify/water/shots/ipad-s1.png b/verify/water/shots/ipad-s1.png
new file mode 100644
index 0000000..74efd94
Binary files /dev/null and b/verify/water/shots/ipad-s1.png differ
diff --git a/verify/water/shots/ipad-s2.png b/verify/water/shots/ipad-s2.png
new file mode 100644
index 0000000..798df4c
Binary files /dev/null and b/verify/water/shots/ipad-s2.png differ
diff --git a/verify/water/shots/ipad-s3.png b/verify/water/shots/ipad-s3.png
new file mode 100644
index 0000000..6b66554
Binary files /dev/null and b/verify/water/shots/ipad-s3.png differ
diff --git a/verify/water/shots/phone-a.png b/verify/water/shots/phone-a.png
new file mode 100644
index 0000000..57273d2
Binary files /dev/null and b/verify/water/shots/phone-a.png differ
diff --git a/verify/water/shots/phone-bsp.png b/verify/water/shots/phone-bsp.png
new file mode 100644
index 0000000..9633c45
Binary files /dev/null and b/verify/water/shots/phone-bsp.png differ
diff --git a/verify/water/shots/phone-c.png b/verify/water/shots/phone-c.png
new file mode 100644
index 0000000..d782710
Binary files /dev/null and b/verify/water/shots/phone-c.png differ
diff --git a/verify/water/shots/phone-dsp.png b/verify/water/shots/phone-dsp.png
new file mode 100644
index 0000000..157475f
Binary files /dev/null and b/verify/water/shots/phone-dsp.png differ
diff --git a/verify/water/shots/phone-s1.png b/verify/water/shots/phone-s1.png
new file mode 100644
index 0000000..5a681ad
Binary files /dev/null and b/verify/water/shots/phone-s1.png differ
diff --git a/verify/water/shots/phone-s2.png b/verify/water/shots/phone-s2.png
new file mode 100644
index 0000000..19160db
Binary files /dev/null and b/verify/water/shots/phone-s2.png differ
diff --git a/verify/water/shots/phone-s3.png b/verify/water/shots/phone-s3.png
new file mode 100644
index 0000000..c2280b7
Binary files /dev/null and b/verify/water/shots/phone-s3.png differ
diff --git a/verify/water/shots/wide-a.png b/verify/water/shots/wide-a.png
new file mode 100644
index 0000000..7dd46e8
Binary files /dev/null and b/verify/water/shots/wide-a.png differ
diff --git a/verify/water/shots/wide-bsp.png b/verify/water/shots/wide-bsp.png
new file mode 100644
index 0000000..b98f06b
Binary files /dev/null and b/verify/water/shots/wide-bsp.png differ
diff --git a/verify/water/shots/wide-c.png b/verify/water/shots/wide-c.png
new file mode 100644
index 0000000..407edbd
Binary files /dev/null and b/verify/water/shots/wide-c.png differ
diff --git a/verify/water/shots/wide-dsp.png b/verify/water/shots/wide-dsp.png
new file mode 100644
index 0000000..92098ee
Binary files /dev/null and b/verify/water/shots/wide-dsp.png differ
diff --git a/verify/water/shots/wide-s1.png b/verify/water/shots/wide-s1.png
new file mode 100644
index 0000000..fab230f
Binary files /dev/null and b/verify/water/shots/wide-s1.png differ
diff --git a/verify/water/shots/wide-s2.png b/verify/water/shots/wide-s2.png
new file mode 100644
index 0000000..079770a
Binary files /dev/null and b/verify/water/shots/wide-s2.png differ
diff --git a/verify/water/shots/wide-s3.png b/verify/water/shots/wide-s3.png
new file mode 100644
index 0000000..604dd18
Binary files /dev/null and b/verify/water/shots/wide-s3.png differ
diff --git a/verify/water/src/config.js b/verify/water/src/config.js
new file mode 100644
index 0000000..a3090ba
--- /dev/null
+++ b/verify/water/src/config.js
@@ -0,0 +1,26 @@
+/**
+ * Scene constants. Every template that draws water or walks a track reads these.
+ * Values are metres.
+ */
+export const POOL = {
+ waterY: 0.06,
+ hx: 6.5,
+ hz: 3.5,
+ bottomY: -1.4,
+};
+
+export const SCENE = {
+ slab: { hx: 7.4, hz: 4.4, thick: 0.42 },
+};
+
+export const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
+export const lerp = (a, b, t) => a + (b - a) * t;
+export const smooth = (t) => {
+ const u = clamp(t, 0, 1);
+ return u * u * (3 - 2 * u);
+};
+
+/** Deck height at a point. Flat here; a play with steps overrides it. */
+export function groundY() {
+ return 0;
+}
diff --git a/verify/water/src/core/geometry.js b/verify/water/src/core/geometry.js
new file mode 100644
index 0000000..3b47296
--- /dev/null
+++ b/verify/water/src/core/geometry.js
@@ -0,0 +1,292 @@
+import * as THREE from 'three';
+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
+
+/**
+ * A crisp, flat-shaded box with geometrically chamfered top / bottom edges.
+ * The chamfer lives in the geometry (not in a normal map), so it catches a real
+ * specular highlight and reads as thickness at small scale.
+ */
+export function chamferBoxGeometry(w, h, d, opts = {}) {
+ const top = opts.top ?? Math.min(w, d, h) * 0.06;
+ const bottom = opts.bottom ?? 0;
+ const hw = w * 0.5;
+ const hd = d * 0.5;
+ const hh = h * 0.5;
+ const t = Math.min(top, hw * 0.35, hd * 0.35, h * 0.35);
+ const b = Math.min(bottom, hw * 0.35, hd * 0.35, h * 0.35);
+ const yt = hh - t;
+ const yb = -hh + b;
+ const tx = hw - t;
+ const tz = hd - t;
+ const bx = hw - b;
+ const bz = hd - b;
+
+ const pos = [];
+ const nor = [];
+ const center = new THREE.Vector3();
+
+ const v = (x, y, z) => new THREE.Vector3(x, y, z);
+
+ function tri(a, b, c, n) {
+ pos.push(a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z);
+ for (let i = 0; i < 3; i++) nor.push(n.x, n.y, n.z);
+ }
+
+ function quad(a, b, c, d, hint) {
+ const n = new THREE.Vector3()
+ .subVectors(b, a)
+ .cross(new THREE.Vector3().subVectors(c, a))
+ .normalize();
+ if (n.dot(hint) < 0) {
+ const tmp = b;
+ b = d;
+ d = tmp;
+ n.negate();
+ }
+ tri(a, b, c, n);
+ tri(a, c, d, n);
+ }
+
+ // Bottom cap
+ if (b > 0.0001) {
+ quad(
+ v(-bx, -hh, -bz), v(bx, -hh, -bz), v(bx, -hh, bz), v(-bx, -hh, bz),
+ v(0, -1, 0)
+ );
+ } else {
+ quad(
+ v(-hw, -hh, -hd), v(hw, -hh, -hd), v(hw, -hh, hd), v(-hw, -hh, hd),
+ v(0, -1, 0)
+ );
+ }
+
+ // Four sides
+ quad(v(hw, yb, -hd), v(hw, yb, hd), v(hw, yt, hd), v(hw, yt, -hd), v(1, 0, 0));
+ quad(v(-hw, yb, hd), v(-hw, yb, -hd), v(-hw, yt, -hd), v(-hw, yt, hd), v(-1, 0, 0));
+ quad(v(-hw, yb, hd), v(hw, yb, hd), v(hw, yt, hd), v(-hw, yt, hd), v(0, 0, 1));
+ quad(v(hw, yb, -hd), v(-hw, yb, -hd), v(-hw, yt, -hd), v(hw, yt, -hd), v(0, 0, -1));
+
+ // Top chamfer band
+ quad(v(hw, yt, -hd), v(hw, yt, hd), v(tx, hh, tz), v(tx, hh, -tz), v(1, 1, 0));
+ quad(v(-hw, yt, hd), v(-hw, yt, -hd), v(-tx, hh, -tz), v(-tx, hh, tz), v(-1, 1, 0));
+ quad(v(-hw, yt, hd), v(hw, yt, hd), v(tx, hh, tz), v(-tx, hh, tz), v(0, 1, 1));
+ quad(v(hw, yt, -hd), v(-hw, yt, -hd), v(-tx, hh, -tz), v(tx, hh, -tz), v(0, 1, -1));
+
+ // Top cap
+ quad(v(-tx, hh, -tz), v(tx, hh, -tz), v(tx, hh, tz), v(-tx, hh, tz), v(0, 1, 0));
+
+ // Bottom chamfer band
+ if (b > 0.0001) {
+ quad(v(bx, -hh, -bz), v(hw, yb, -hd), v(hw, yb, hd), v(bx, -hh, bz), v(1, -1, 0));
+ quad(v(-bx, -hh, bz), v(-hw, yb, hd), v(-hw, yb, -hd), v(-bx, -hh, -bz), v(-1, -1, 0));
+ quad(v(-bx, -hh, bz), v(bx, -hh, bz), v(hw, yb, hd), v(-hw, yb, hd), v(0, -1, 1));
+ quad(v(bx, -hh, -bz), v(-bx, -hh, -bz), v(-hw, yb, -hd), v(hw, yb, -hd), v(0, -1, -1));
+ }
+
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ geo.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ geo.computeBoundingSphere();
+ return geo;
+}
+
+export function roundedBoxGeometry(w, h, d, radius = 0.02, segments = 2) {
+ return new RoundedBoxGeometry(w, h, d, segments, Math.min(radius, w * 0.45, h * 0.45, d * 0.45));
+}
+
+/** A chamfered rectangle path, used for the plan section of the concrete shell. */
+export function chamferedRectShape(w, d, chamfer = 0.12) {
+ const hw = w * 0.5;
+ const hd = d * 0.5;
+ const c = Math.min(chamfer, hw * 0.4, hd * 0.4);
+ const s = new THREE.Shape();
+ s.moveTo(-hw + c, -hd);
+ s.lineTo(hw - c, -hd);
+ s.lineTo(hw, -hd + c);
+ s.lineTo(hw, hd - c);
+ s.lineTo(hw - c, hd);
+ s.lineTo(-hw + c, hd);
+ s.lineTo(-hw, hd - c);
+ s.lineTo(-hw, -hd + c);
+ s.closePath();
+ return s;
+}
+
+/** Rectangular ring slab with an actual hole and chamfered edges. */
+export function ringSlabGeometry(outerW, outerD, innerW, innerD, thickness, bevel = 0.02) {
+ const shape = chamferedRectShape(outerW, outerD, bevel * 2.2);
+ const hole = new THREE.Path();
+ const hw = innerW * 0.5;
+ const hd = innerD * 0.5;
+ hole.moveTo(-hw, -hd);
+ hole.lineTo(hw, -hd);
+ hole.lineTo(hw, hd);
+ hole.lineTo(-hw, hd);
+ hole.closePath();
+ shape.holes.push(hole);
+ const geo = new THREE.ExtrudeGeometry(shape, {
+ depth: thickness,
+ bevelEnabled: bevel > 0,
+ bevelThickness: bevel,
+ bevelSize: bevel,
+ bevelSegments: 2,
+ curveSegments: 1,
+ steps: 1,
+ });
+ geo.rotateX(-Math.PI / 2);
+ // After rotateX(-90) the extrusion runs from y=0 to y=thickness.
+ geo.translate(0, -thickness, 0);
+ geo.computeVertexNormals();
+ return geo;
+}
+
+/** Extrude a plan ring vertically (concrete pool walls). */
+export function extrudedWallRing(outerW, outerD, innerW, innerD, height, opts = {}) {
+ const shape = chamferedRectShape(outerW, outerD, opts.chamfer ?? 0.14);
+ const hole = new THREE.Path();
+ const hw = innerW * 0.5;
+ const hd = innerD * 0.5;
+ hole.moveTo(-hw, -hd);
+ hole.lineTo(hw, -hd);
+ hole.lineTo(hw, hd);
+ hole.lineTo(-hw, hd);
+ hole.closePath();
+ shape.holes.push(hole);
+ const geo = new THREE.ExtrudeGeometry(shape, {
+ depth: height,
+ bevelEnabled: true,
+ bevelThickness: opts.bevel ?? 0.015,
+ bevelSize: opts.bevel ?? 0.015,
+ bevelSegments: 2,
+ curveSegments: 1,
+ steps: 1,
+ });
+ geo.rotateX(-Math.PI / 2);
+ geo.translate(0, -height, 0);
+ geo.computeVertexNormals();
+ return geo;
+}
+
+/** Plane whose height follows a function of x (used for the sloping pool floor). */
+export function heightFieldGeometry(width, depth, segX, segZ, heightFn) {
+ const geo = new THREE.PlaneGeometry(width, depth, segX, segZ);
+ geo.rotateX(-Math.PI / 2);
+ const p = geo.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i);
+ const z = p.getZ(i);
+ p.setY(i, heightFn(x, z));
+ }
+ geo.computeVertexNormals();
+ return geo;
+}
+
+export function quatFromBasis(u, normal) {
+ const x = u.clone().normalize();
+ const y = normal.clone().normalize();
+ const z = new THREE.Vector3().crossVectors(x, y).normalize();
+ const m = new THREE.Matrix4().makeBasis(x, y, z);
+ return new THREE.Quaternion().setFromRotationMatrix(m);
+}
+
+export function hash2(x, y) {
+ const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453123;
+ return s - Math.floor(s);
+}
+
+export function hash3(x, y, z) {
+ const s = Math.sin(x * 12.9898 + y * 78.233 + z * 37.719) * 43758.5453123;
+ return s - Math.floor(s);
+}
+
+export function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function () {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/**
+ * Build an InstancedMesh from a list of { position, quaternion, scale, color }.
+ * A tiny custom varying (vInstColor) is injected into the material so instance
+ * tint works reliably on MeshStandardMaterial / MeshPhysicalMaterial.
+ */
+export function instancedMesh(geometry, material, items, opts = {}) {
+ const mesh = new THREE.InstancedMesh(geometry, material, items.length);
+ const m = new THREE.Matrix4();
+ const q = new THREE.Quaternion();
+ const s = new THREE.Vector3(1, 1, 1);
+ for (let i = 0; i < items.length; i++) {
+ const it = items[i];
+ q.copy(it.quaternion);
+ s.copy(it.scale ?? { x: 1, y: 1, z: 1 });
+ m.compose(it.position, q, s);
+ mesh.setMatrixAt(i, m);
+ if (it.color) mesh.setColorAt(i, it.color);
+ }
+ mesh.instanceMatrix.needsUpdate = true;
+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ mesh.castShadow = opts.castShadow ?? false;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ mesh.frustumCulled = false;
+ return mesh;
+}
+
+export function colorVariation(base, rand, h = 0.01, s = 0.05, l = 0.03) {
+ const c = base.clone();
+ c.offsetHSL((rand() - 0.5) * h, (rand() - 0.5) * s, (rand() - 0.5) * l);
+ return c;
+}
+
+export function smoothstep(a, b, x) {
+ const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+}
+
+export function addBox(group, w, h, d, material, x, y, z, opts = {}) {
+ const geo = opts.chamfer
+ ? chamferBoxGeometry(w, h, d, { top: opts.chamfer, bottom: opts.chamferBottom ?? 0 })
+ : new THREE.BoxGeometry(w, h, d);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.position.set(x, y, z);
+ if (opts.rotation) mesh.rotation.set(opts.rotation[0], opts.rotation[1], opts.rotation[2]);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ group.add(mesh);
+ return mesh;
+}
+
+export function addCylinder(group, rTop, rBottom, h, material, x, y, z, opts = {}) {
+ const geo = new THREE.CylinderGeometry(rTop, rBottom, h, opts.segments ?? 16, opts.heightSegments ?? 1, opts.open ?? false);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.position.set(x, y, z);
+ if (opts.rotation) mesh.rotation.set(opts.rotation[0], opts.rotation[1], opts.rotation[2]);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ group.add(mesh);
+ return mesh;
+}
+
+export function addSphere(group, r, material, x, y, z, scale = [1, 1, 1], opts = {}) {
+ const geo = new THREE.SphereGeometry(r, opts.widthSegments ?? 20, opts.heightSegments ?? 14);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.position.set(x, y, z);
+ mesh.scale.set(scale[0], scale[1], scale[2]);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ group.add(mesh);
+ return mesh;
+}
+
+export function makeTube(points, radius, material, opts = {}) {
+ const curve = new THREE.CatmullRomCurve3(points, false, 'catmullrom', 0.35);
+ const geo = new THREE.TubeGeometry(curve, opts.segments ?? 48, radius, opts.radialSegments ?? 8, false);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.castShadow = opts.castShadow ?? true;
+ mesh.receiveShadow = opts.receiveShadow ?? true;
+ return mesh;
+}
diff --git a/verify/water/src/core/materials.js b/verify/water/src/core/materials.js
new file mode 100644
index 0000000..c05b832
--- /dev/null
+++ b/verify/water/src/core/materials.js
@@ -0,0 +1,26 @@
+import * as SVG from 'three';
+
+/**
+ * Minimal materials module for the water harness: the templates import
+ * `timeUniform` from here, and the harness needs one deck and one tile colour.
+ */
+export const timeUniform = { value: 0 };
+
+const std = (hex, opts = {}) =>
+ new SVG.MeshStandardMaterial({
+ color: new SVG.Color(hex),
+ roughness: opts.roughness ?? 0.92,
+ metalness: 0,
+ });
+
+export function createMaterials() {
+ return {
+ deck: std(0xb9b2a4),
+ coping: std(0xe8e2d4),
+ tile: std(0x7fb3b5, { roughness: 0.6 }),
+ tileDeep: std(0x2f5f66),
+ skin: std(0xe8bd98),
+ suit: std(0x2f7f8f),
+ slabEdge: std(0x8b8b86),
+ };
+}
diff --git a/verify/water/src/core/palette.js b/verify/water/src/core/palette.js
new file mode 100644
index 0000000..ce7de7c
--- /dev/null
+++ b/verify/water/src/core/palette.js
@@ -0,0 +1,35 @@
+/**
+ * 64-colour sRGB palette. The scene is quantised to these values after an
+ * 8x8 ordered dither, which is what gives the miniature its printed, pixel-art
+ * finish. Keep the length at exactly 64: the shader declares vec3[64].
+ */
+export const PALETTE_HEX = [
+ // paper, plaster, limestone, deck stone
+ '#ffffff', '#faf7ef', '#f3eddf', '#eae2d3', '#e1d7c5',
+ '#d6cbb8', '#c9bda9', '#baae9a', '#a89c88', '#908574',
+ // concrete, shadow, steel darks
+ '#8b9195', '#7b8287', '#6c7378', '#5e656a', '#51575c',
+ '#444a4f', '#383e43', '#2c3237',
+ // water and glazed tile ramps
+ '#d8f2ef', '#bce9e4', '#9ddddb', '#80cecf', '#67bfc4',
+ '#54aeb6', '#429da7', '#338b98', '#287888', '#206577',
+ '#1a5366', '#164456', '#9d988c', '#1f5f6f', '#2d7f8c',
+ '#4a9aa5',
+ // skin
+ '#f4d5b8', '#eac09d', '#dfab82', '#d0966b', '#b97d55',
+ '#9c6440', '#71452e',
+ // hair
+ '#2c231e', '#463128', '#62452f', '#a87b4a', '#d8b878',
+ // swimwear, inflatables, drink, accents
+ '#ef6a52', '#d9503c', '#918c80', '#857f74', '#3aa39a',
+ '#267e78', '#6d685f', '#6fa0c9', '#efe7d6', '#79746a',
+ '#615d55', '#c7d3d8',
+ // metals
+ '#b9c5c9', '#9ba7ab', '#7f8b90', '#606b70', '#3b4449',
+ '#20282c',
+];
+
+export const PALETTE_RGB = PALETTE_HEX.map((hex) => {
+ const n = parseInt(hex.slice(1), 16);
+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
+});
diff --git a/verify/water/src/core/post.js b/verify/water/src/core/post.js
new file mode 100644
index 0000000..238cf24
--- /dev/null
+++ b/verify/water/src/core/post.js
@@ -0,0 +1,191 @@
+import * as THREE from 'three';
+import { PALETTE_RGB } from './palette.js';
+
+const VERT = /* glsl */ `
+out vec2 vUv;
+void main() {
+ vUv = position.xy * 0.5 + 0.5;
+ gl_Position = vec4(position.xy, 0.0, 1.0);
+}
+`;
+
+const FRAG = /* glsl */ `
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D tScene;
+uniform vec2 uResolution;
+uniform vec3 uPalette[64];
+uniform float uDither;
+
+float bayer2(vec2 a) {
+ a = floor(a);
+ return fract(a.x * 0.5 + a.y * a.y * 0.75);
+}
+float bayer4(vec2 a) {
+ return bayer2(0.5 * a) * 0.25 + bayer2(a);
+}
+float bayer8(vec2 a) {
+ return bayer4(0.5 * a) * 0.25 + bayer4(a);
+}
+float luma(vec3 c) {
+ return dot(c, vec3(0.299, 0.587, 0.114));
+}
+vec3 fetch(vec2 uv) {
+ return texture(tScene, uv).rgb;
+}
+float fetchA(vec2 uv) {
+ return texture(tScene, uv).a;
+}
+
+void main() {
+ vec2 px = 1.0 / uResolution;
+ vec4 centre = texture(tScene, vUv);
+
+ // Gather a small disc of coverage for the cut-out rim. The alpha buffer is
+ // opaque everywhere inside the diorama, so this only bites at the silhouette.
+ float weights = 0.0;
+ float cov = 0.0;
+ vec3 acc = vec3(0.0);
+ for (int i = 0; i < 12; i++) {
+ float ang = float(i) * 2.399963 + 0.4;
+ float rad = 1.0 + float(i % 3) * 1.15;
+ vec2 off = vec2(cos(ang), sin(ang)) * rad * px;
+ vec2 uv = vUv + off;
+ float a = fetchA(uv);
+ float w = 1.0 - rad / 5.4;
+ cov += a * w;
+ acc += fetch(uv) * a * w;
+ weights += w;
+ }
+ cov /= weights;
+ vec3 gathered = acc / max(cov * weights, 0.00001);
+
+ float centreCov = centre.a;
+ cov = max(cov, centreCov);
+ vec3 c = mix(gathered, centre.rgb, smoothstep(0.62, 0.92, centreCov));
+
+ // Composite the model onto paper white before grading.
+ c = mix(vec3(1.0), c, smoothstep(0.26, 0.72, cov));
+
+ // Linear render target -> display sRGB.
+ c = pow(max(c, vec3(0.0)), vec3(1.0 / 2.2));
+
+ // Gentle grade, then the crisp ink contour.
+ float l = luma(c);
+ c = mix(vec3(l), c, 1.07);
+ c = clamp((c - 0.5) * 1.028 + 0.5, 0.0, 1.0);
+
+ float l0 = luma(texture(tScene, vUv).rgb);
+ float l1 = luma(texture(tScene, vUv + vec2(px.x, 0.0)).rgb);
+ float l2 = luma(texture(tScene, vUv - vec2(px.x, 0.0)).rgb);
+ float l3 = luma(texture(tScene, vUv + vec2(0.0, px.y)).rgb);
+ float l4 = luma(texture(tScene, vUv - vec2(0.0, px.y)).rgb);
+ float edge = max(max(abs(l0 - l1), abs(l0 - l2)), max(abs(l0 - l3), abs(l0 - l4)));
+ // Neighbour luminance is linear; bring it into the same scale.
+ edge = pow(edge, 0.4545);
+ float ink = smoothstep(0.13, 0.34, edge) * smoothstep(0.20, 0.55, cov) * (1.0 - smoothstep(0.86, 0.985, cov));
+ c = mix(c, vec3(0.085, 0.082, 0.076), ink * 0.62);
+
+ // 8x8 ordered dither, then nearest palette snap.
+ float d = bayer8(gl_FragCoord.xy) - 0.5;
+ float sparkle = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453) - 0.5;
+ // Dither hardest where tones are actually transitioning; flat areas stay calm.
+ float gate = smoothstep(0.004, 0.055, edge);
+ c += (d * (0.0012 + 0.019 * gate) + sparkle * 0.0012) * uDither;
+
+ vec3 best = uPalette[0];
+ float bestD = 1e9;
+ for (int i = 0; i < 64; i++) {
+ vec3 p = uPalette[i];
+ vec3 diff = (c - p) * vec3(1.0, 1.12, 0.93);
+ float dd = dot(diff, diff);
+ if (dd < bestD) {
+ bestD = dd;
+ best = p;
+ }
+ }
+ c = best;
+
+ // Fragment the outer silhouette with the same ordered matrix.
+ float rim = 1.0 - smoothstep(0.78, 0.995, cov);
+ float threshold = bayer4(gl_FragCoord.xy * 1.0) * 0.92 + 0.018;
+ if (rim > 0.002 && cov < threshold) {
+ c = vec3(1.0);
+ }
+ if (cov < 0.02) c = vec3(1.0);
+
+ fragColor = vec4(c, 1.0);
+}
+`;
+
+export class PixelPost {
+ constructor(renderer, maxDim = 1600) {
+ this.renderer = renderer;
+ this.maxDim = maxDim;
+
+ this.rt = new THREE.WebGLRenderTarget(2, 2, {
+ minFilter: THREE.NearestFilter,
+ magFilter: THREE.NearestFilter,
+ depthBuffer: true,
+ stencilBuffer: false,
+ samples: 0,
+ type: THREE.HalfFloatType,
+ format: THREE.RGBAFormat,
+ colorSpace: THREE.LinearSRGBColorSpace,
+ });
+ this.rt.texture.generateMipmaps = false;
+
+ this.uniforms = {
+ tScene: { value: this.rt.texture },
+ uResolution: { value: new THREE.Vector2(2, 2) },
+ uPalette: { value: PALETTE_RGB.map((c) => new THREE.Vector3(c[0], c[1], c[2])) },
+ uDither: { value: 1.0 },
+ };
+
+ this.material = new THREE.ShaderMaterial({
+ glslVersion: THREE.GLSL3,
+ uniforms: this.uniforms,
+ vertexShader: VERT,
+ fragmentShader: FRAG,
+ depthTest: false,
+ depthWrite: false,
+ toneMapped: false,
+ });
+
+ this.scene = new THREE.Scene();
+ this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.material);
+ quad.frustumCulled = false;
+ this.scene.add(quad);
+
+ this.size = new THREE.Vector2(2, 2);
+ }
+
+ setSize(w, h) {
+ // One target pixel per CSS pixel: the cap is a ceiling for huge displays,
+ // never a supersample (which the browser would blur back down).
+ const scale = Math.min(1, this.maxDim / Math.max(w, h));
+ const iw = Math.max(2, Math.round(w * scale));
+ const ih = Math.max(2, Math.round(h * scale));
+ if (iw === this.size.x && ih === this.size.y) return;
+ this.size.set(iw, ih);
+ this.rt.setSize(iw, ih);
+ this.uniforms.uResolution.value.set(iw, ih);
+ this.renderer.setSize(iw, ih, false);
+ }
+
+ render(scene, camera) {
+ const r = this.renderer;
+ r.setRenderTarget(this.rt);
+ r.setClearColor(0x000000, 0);
+ r.clear(true, true, true);
+ r.render(scene, camera);
+ r.setRenderTarget(null);
+ r.setClearColor(0x000000, 1);
+ r.clear(true, true, true);
+ r.render(this.scene, this.camera);
+ }
+}
diff --git a/verify/water/src/main.js b/verify/water/src/main.js
new file mode 100644
index 0000000..4b60ac3
--- /dev/null
+++ b/verify/water/src/main.js
@@ -0,0 +1,223 @@
+import * as THREE from 'three';
+import { PixelPost } from './core/post.js';
+import { createMaterials, timeUniform } from './core/materials.js';
+import { createCamera, updateCamera } from './scene/camera.js';
+import { createLighting } from './scene/lighting.js';
+import { createWater } from './scene/water.js';
+import { createWake } from './scene/wake.js';
+import { createSplash } from './scene/splash.js';
+import { POOL, SCENE } from './config.js';
+
+/**
+ * Water harness: a slab with a pool, two swimmers crossing on a deterministic
+ * path, a wake behind each and two timed splash bursts. Its only job is to put
+ * templates/water.js, wake.js and splash.js in front of a camera so they can be
+ * looked at, frozen and judged. It is not a play; there is no story.
+ *
+ * Run:
+ * npm i three esbuild playwright-core
+ * node build.mjs
+ * python3 -m http.server 4180 &
+ * node ../templates/qa/shoot.mjs (BASE_URL=http://127.0.0.1:4180/index.html)
+ */
+
+const canvas = document.getElementById('stage');
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: true });
+renderer.setPixelRatio(1);
+renderer.shadowMap.enabled = true;
+renderer.shadowMap.type = THREE.PCFShadowMap;
+renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
+renderer.toneMapping = THREE.NoToneMapping;
+
+const scene = new THREE.Scene();
+scene.background = null;
+const camera = createCamera();
+const post = new PixelPost(renderer, 1600);
+const { hx, hz, thick } = SCENE.slab;
+
+const CLIP = [
+ new THREE.Plane(new THREE.Vector3(1, 0, 0), hx + 0.05),
+ new THREE.Plane(new THREE.Vector3(-1, 0, 0), hx + 0.05),
+ new THREE.Plane(new THREE.Vector3(0, 0, 1), hz + 0.05),
+ new THREE.Plane(new THREE.Vector3(0, 0, -1), hz + 0.05),
+];
+
+createLighting(renderer, scene);
+const mats = createMaterials();
+
+// ---- slab, basin, coping ---------------------------------------------------
+const slab = new THREE.Mesh(new THREE.BoxGeometry(hx * 2, thick, hz * 2), mats.slabEdge);
+slab.position.y = -thick / 2;
+slab.receiveShadow = true;
+scene.add(slab);
+
+// Deck as a frame around the pool opening, so the water sits over the dark
+// basin and not over beige. A deck covering the whole slab is the fastest way
+// to make transparent water look like a stain.
+const deckStrips = [
+ [hx * 2, POOL.hz + (hz - POOL.hz), 0, (POOL.hz + hz) / 2],
+ [hx * 2, hz - POOL.hz, 0, -(POOL.hz + hz) / 2],
+ [hx - POOL.hx, POOL.hz * 2, (POOL.hx + hx) / 2, 0],
+ [hx - POOL.hx, POOL.hz * 2, -(POOL.hx + hx) / 2, 0],
+];
+for (const [w, d, x, z] of deckStrips) {
+ const strip = new THREE.Mesh(new THREE.BoxGeometry(w, 0.02, d), mats.deck);
+ strip.position.set(x, 0.01, z);
+ strip.receiveShadow = true;
+ scene.add(strip);
+}
+
+const floor = new THREE.Mesh(new THREE.BoxGeometry(POOL.hx * 2, 0.1, POOL.hz * 2), mats.tile);
+floor.position.y = POOL.bottomY;
+scene.add(floor);
+
+for (const [sx, sz] of [
+ [1, 0],
+ [-1, 0],
+ [0, 1],
+ [0, -1],
+]) {
+ const w = sz === 0 ? 0.12 : POOL.hx * 2;
+ const d = sz === 0 ? POOL.hz * 2 : 0.12;
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(w, -POOL.bottomY, d), mats.tile);
+ wall.position.set(sx * POOL.hx, POOL.bottomY / 2, sz * POOL.hz);
+ scene.add(wall);
+}
+
+for (const [w, d, x, z] of [
+ [POOL.hx * 2 + 0.5, 0.25, 0, POOL.hz + 0.12],
+ [POOL.hx * 2 + 0.5, 0.25, 0, -(POOL.hz + 0.12)],
+ [0.25, POOL.hz * 2, POOL.hx + 0.12, 0],
+ [0.25, POOL.hz * 2, -(POOL.hx + 0.12), 0],
+]) {
+ const c = new THREE.Mesh(new THREE.BoxGeometry(w, 0.08, d), mats.coping);
+ c.position.set(x, 0.03, z);
+ c.receiveShadow = true;
+ scene.add(c);
+}
+
+// ---- water, wake, splash ---------------------------------------------------
+const water = createWater();
+scene.add(water);
+
+const wake = createWake(2);
+scene.add(wake.group);
+
+const splash = createSplash();
+scene.add(splash.group);
+
+// Two swimmers on a pure function of t: back and forth across the pool.
+const SWIM = { y0: 0.42, spanX: 4.2, period: 6.0 };
+function swimmerAt(i, t) {
+ const phase = (t / SWIM.period) * Math.PI * 2 + i * 1.9;
+ const x = Math.sin(phase) * SWIM.spanX;
+ const z = i === 0 ? -1.1 : 1.0;
+ const vx = Math.cos(phase) * SWIM.spanX * (Math.PI * 2) / SWIM.period;
+ const yaw = Math.atan2(vx, 0);
+ return { x, z, yaw, vx };
+}
+
+const bodies = [];
+for (let i = 0; i < 2; i++) {
+ const g = new THREE.Group();
+ const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.16, 0.5, 6, 10), mats.suit);
+ body.rotation.x = Math.PI / 2;
+ body.position.y = 0.02;
+ body.castShadow = true;
+ g.add(body);
+ const head = new THREE.Mesh(new THREE.SphereGeometry(0.11, 12, 10), mats.skin);
+ head.position.set(0, 0.03, 0.34);
+ head.castShadow = true;
+ g.add(head);
+ scene.add(g);
+ bodies.push(g);
+}
+
+// Two splashes, at fixed times and places, so a frozen frame is reproducible.
+const BURSTS = [
+ { t: 1.6, x: 2.1, z: -1.1, power: 1.0 },
+ { t: 4.3, x: -2.6, z: 1.0, power: 1.3 },
+];
+
+const LOOP = 9.0;
+
+/** Re-simulate the dt-driven effects from zero whenever the clock jumps. */
+function simulateTo(t) {
+ wake.reset();
+ splash.reset();
+ const dt = 1 / 30;
+ for (let s = 0; s < t; s += dt) {
+ const tt = Math.min(s, t);
+ const entries = [0, 1].map((i) => {
+ const p = swimmerAt(i, tt);
+ return { x: p.x, z: p.z, yaw: p.yaw, active: true };
+ });
+ wake.update(dt, tt, entries);
+ for (const b of BURSTS) {
+ if (s <= b.t && b.t < s + dt) splash.trigger(b.x, b.z, b.power, Math.round(b.t * 100));
+ }
+ splash.update(dt);
+ }
+}
+
+function draw(T) {
+ const t = ((T % LOOP) + LOOP) % LOOP;
+ timeUniform.value = t;
+
+ for (let i = 0; i < 2; i++) {
+ const p = swimmerAt(i, t);
+ bodies[i].position.set(p.x, POOL.waterY + SWIM.y0 - 0.42, p.z);
+ bodies[i].rotation.y = p.yaw;
+ }
+
+ simulateTo(t);
+ post.render(scene, camera, CLIP);
+}
+
+function resize() {
+ const rect = canvas.getBoundingClientRect();
+ if (rect.width < 2 || rect.height < 2) return;
+ updateCamera(camera, Math.max(0.3, rect.width / rect.height));
+ post.setSize(rect.width, rect.height);
+}
+resize();
+window.addEventListener('resize', resize);
+
+let frozen = null;
+let origin = performance.now();
+function tick(now) {
+ if (frozen == null) draw((now - origin) / 1000);
+ requestAnimationFrame(tick);
+}
+
+draw(0);
+resize();
+requestAnimationFrame(tick);
+
+window.__diorama = {
+ THREE,
+ scene,
+ camera,
+ renderer,
+ post,
+ CLIP,
+ water: { wake, splash },
+ freeze(t) {
+ frozen = t;
+ draw(t);
+ },
+ play() {
+ origin = performance.now() - (frozen ?? 0) * 1000;
+ frozen = null;
+ },
+ view(pos, target) {
+ if (!pos) {
+ resize();
+ return;
+ }
+ camera.position.set(pos[0], pos[1], pos[2]);
+ camera.lookAt(target[0], target[1], target[2]);
+ camera.updateProjectionMatrix();
+ },
+};
+window.__dioramaReady = true;
diff --git a/verify/water/src/scene/camera.js b/verify/water/src/scene/camera.js
new file mode 100644
index 0000000..49634c6
--- /dev/null
+++ b/verify/water/src/scene/camera.js
@@ -0,0 +1,87 @@
+import * as THREE from 'three';
+
+/**
+ * Locked three-quarter camera. Distance is solved against a set of fit points
+ * (slab corners plus the tops of tall props) so the play keeps its white
+ * margin at every aspect ratio. Nothing here orbits or drifts.
+ */
+export const CAMERA = {
+ fov: 20.5,
+ azimuth: (45.0 * Math.PI) / 180,
+ elevation: (33.0 * Math.PI) / 180,
+ target: new THREE.Vector3(0, -0.15, 0),
+ fillX: 0.84,
+ fillY: 0.86,
+};
+
+/** Override this list for a different slab / landmark height. */
+export const FIT_POINTS = [
+ new THREE.Vector3(-10.5, 0.0, -7.0),
+ new THREE.Vector3(10.5, 0.0, -7.0),
+ new THREE.Vector3(10.5, 0.0, 7.0),
+ new THREE.Vector3(-10.5, 0.0, 7.0),
+ new THREE.Vector3(-10.5, -0.42, -7.0),
+ new THREE.Vector3(10.5, -0.42, -7.0),
+ new THREE.Vector3(10.5, -0.42, 7.0),
+ new THREE.Vector3(-10.5, -0.42, 7.0),
+ new THREE.Vector3(0.0, 3.6, 0.0),
+];
+
+export function cameraDirection(out = new THREE.Vector3()) {
+ const ce = Math.cos(CAMERA.elevation);
+ return out.set(
+ ce * Math.cos(CAMERA.azimuth),
+ Math.sin(CAMERA.elevation),
+ ce * Math.sin(CAMERA.azimuth)
+ );
+}
+
+function fits(dir, right, up, aspect, distance, points) {
+ const tanHalf = Math.tan((CAMERA.fov * Math.PI) / 360);
+ const p = new THREE.Vector3();
+ for (const fit of points) {
+ p.subVectors(fit, CAMERA.target);
+ const depth = distance - p.dot(dir);
+ if (depth < 0.4) return false;
+ const x = p.dot(right) / (depth * tanHalf * aspect);
+ const y = p.dot(up) / (depth * tanHalf);
+ if (Math.abs(x) > CAMERA.fillX) return false;
+ if (Math.abs(y) > CAMERA.fillY) return false;
+ }
+ return true;
+}
+
+export function solveDistance(aspect, points = FIT_POINTS) {
+ const a = Math.max(0.3, aspect);
+ const dir = cameraDirection();
+ const right = new THREE.Vector3().crossVectors(new THREE.Vector3(0, 1, 0), dir).normalize();
+ const up = new THREE.Vector3().crossVectors(dir, right).normalize();
+
+ let lo = 5;
+ let hi = 300;
+ for (let i = 0; i < 48; i++) {
+ const mid = (lo + hi) * 0.5;
+ if (fits(dir, right, up, a, mid, points)) hi = mid;
+ else lo = mid;
+ }
+ return hi;
+}
+
+export function createCamera(aspect = 1.16, points = FIT_POINTS) {
+ const camera = new THREE.PerspectiveCamera(CAMERA.fov, aspect, 0.5, 400);
+ updateCamera(camera, aspect, points);
+ return camera;
+}
+
+export function updateCamera(camera, aspect, points = FIT_POINTS) {
+ const a = Math.max(0.3, aspect);
+ const d = solveDistance(a, points);
+ const dir = cameraDirection();
+ camera.position.copy(CAMERA.target).addScaledVector(dir, d);
+ camera.lookAt(CAMERA.target);
+ camera.aspect = a;
+ camera.near = Math.max(0.3, d * 0.01);
+ camera.far = d * 4 + 80;
+ camera.updateProjectionMatrix();
+ camera.userData.distance = d;
+}
diff --git a/verify/water/src/scene/lighting.js b/verify/water/src/scene/lighting.js
new file mode 100644
index 0000000..2118aac
--- /dev/null
+++ b/verify/water/src/scene/lighting.js
@@ -0,0 +1,50 @@
+import * as THREE from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+
+export function createLighting(renderer, scene) {
+ const hemi = new THREE.HemisphereLight(0xd6ecf6, 0x6f6a60, 0.24);
+ scene.add(hemi);
+
+ const sun = new THREE.DirectionalLight(0xfff8ee, 3.3);
+ sun.position.set(-15, 19.5, 17);
+ sun.target.position.set(0, -0.4, 0);
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048);
+ sun.shadow.camera.left = -13;
+ sun.shadow.camera.right = 13;
+ sun.shadow.camera.top = 13;
+ sun.shadow.camera.bottom = -13;
+ sun.shadow.camera.near = 4;
+ sun.shadow.camera.far = 70;
+ sun.shadow.bias = -0.00022;
+ sun.shadow.normalBias = 0.025;
+ sun.shadow.radius = 1.0;
+ sun.shadow.camera.updateProjectionMatrix();
+ scene.add(sun);
+ scene.add(sun.target);
+
+ const fill = new THREE.DirectionalLight(0xa9cbe2, 0.46);
+ fill.position.set(19, 13, -15);
+ fill.target.position.set(0, -0.5, 0);
+ scene.add(fill);
+ scene.add(fill.target);
+
+ // Aquatic subjects set scene.userData.aquatic = true before lighting.
+ // A dry scene must not get a cyan bounce from below the deck.
+ let waterBounce = null;
+ if (scene.userData.aquatic) {
+ waterBounce = new THREE.PointLight(0x74cfd2, 1.7, 11, 2.0);
+ waterBounce.position.set(0.3, -0.9, 0.0);
+ scene.add(waterBounce);
+ }
+
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const envScene = new RoomEnvironment();
+ const env = pmrem.fromScene(envScene, 0.035).texture;
+ scene.environment = env;
+ scene.environmentIntensity = 0.18;
+ pmrem.dispose();
+ envScene.dispose?.();
+
+ return { sun, hemi, fill, waterBounce, env };
+}
diff --git a/verify/water/src/scene/splash.js b/verify/water/src/scene/splash.js
new file mode 100644
index 0000000..fefc954
--- /dev/null
+++ b/verify/water/src/scene/splash.js
@@ -0,0 +1,159 @@
+import * as THREE from 'three';
+import { POOL } from '../config.js';
+
+/**
+ * Chunky pixel-friendly splash: a burst of white droplets, a foam disc and
+ * three expanding rings on the water surface. Everything is unlit so it stays
+ * bright after the palette snap.
+ */
+export function createSplash() {
+ const group = new THREE.Group();
+ const dropMat = new THREE.MeshBasicMaterial({ color: 0xf2fbf7 });
+ const foamMat = () =>
+ new THREE.MeshBasicMaterial({
+ color: 0xdff6ee,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+
+ const drops = [];
+ for (let i = 0; i < 64; i++) {
+ const r = 0.024 + (i % 7) * 0.007;
+ const mesh = new THREE.Mesh(new THREE.IcosahedronGeometry(r, 0), dropMat);
+ mesh.visible = false;
+ mesh.frustumCulled = false;
+ group.add(mesh);
+ drops.push({
+ mesh,
+ pos: new THREE.Vector3(),
+ vel: new THREE.Vector3(),
+ live: false,
+ spin: new THREE.Vector3(),
+ });
+ }
+
+ const rings = [];
+ for (let i = 0; i < 4; i++) {
+ const geo = new THREE.RingGeometry(0.30, 0.375, 30);
+ geo.rotateX(-Math.PI / 2);
+ const mat = foamMat();
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.y = POOL.waterY + 0.008 + i * 0.0015;
+ mesh.visible = false;
+ mesh.renderOrder = 8;
+ group.add(mesh);
+ rings.push({ mesh, mat, age: 0, delay: i * 0.14, live: false });
+ }
+
+ const foamGeo = new THREE.CircleGeometry(0.62, 24);
+ foamGeo.rotateX(-Math.PI / 2);
+ const foam = new THREE.Mesh(foamGeo, foamMat());
+ foam.position.y = POOL.waterY + 0.012;
+ foam.renderOrder = 9;
+ foam.visible = false;
+ group.add(foam);
+
+ let foamAge = 0;
+ let foamLive = false;
+
+ /**
+ * Deterministic stand-in for Math.random. The whole play is a function of t,
+ * so a burst must look identical every time it fires, and identical again when
+ * the QA harness re-simulates the effects from zero to freeze a frame.
+ */
+ let seed = 1;
+ function rnd() {
+ seed = (seed * 16807) % 2147483647;
+ return (seed - 1) / 2147483646;
+ }
+
+ function trigger(x, z, power = 1, burstSeed = 1) {
+ seed = burstSeed * 7919 || 1;
+ drops.forEach((d, i) => {
+ const a = rnd() * Math.PI * 2;
+ const chunky = i % 5 === 0;
+ const speed = (chunky ? 0.3 : 0.55 + rnd() * 1.65) * power;
+ const up = (chunky ? 1.0 + rnd() * 0.7 : 1.7 + rnd() * 2.1) * power;
+ d.pos.set(x + (rnd() - 0.5) * 0.22, POOL.waterY + 0.04, z + (rnd() - 0.5) * 0.22);
+ d.vel.set(Math.cos(a) * speed, up, Math.sin(a) * speed);
+ d.spin.set(rnd() * 6, rnd() * 6, rnd() * 6);
+ d.live = true;
+ d.mesh.visible = true;
+ d.mesh.position.copy(d.pos);
+ });
+ for (const r of rings) {
+ r.age = 0;
+ r.live = true;
+ r.mesh.visible = true;
+ r.mesh.scale.setScalar(0.22);
+ r.mat.opacity = 0.0;
+ }
+ foamAge = 0;
+ foamLive = true;
+ foam.visible = true;
+ foam.position.set(x, POOL.waterY + 0.012, z);
+ foam.scale.setScalar(0.35);
+ foam.material.opacity = 0.40;
+ }
+
+ function update(dt) {
+ for (const d of drops) {
+ if (!d.live) continue;
+ d.vel.y -= 9.6 * dt;
+ d.pos.addScaledVector(d.vel, dt);
+ d.mesh.position.copy(d.pos);
+ d.mesh.rotation.x += d.spin.x * dt;
+ d.mesh.rotation.y += d.spin.y * dt;
+ if (d.pos.y < POOL.waterY - 0.02) {
+ d.live = false;
+ d.mesh.visible = false;
+ }
+ }
+
+ for (const r of rings) {
+ if (!r.live) continue;
+ r.age += dt;
+ const a = r.age - r.delay;
+ if (a < 0) continue;
+ const k = a / 1.5;
+ if (k >= 1) {
+ r.live = false;
+ r.mesh.visible = false;
+ continue;
+ }
+ r.mesh.scale.setScalar(0.3 + k * 3.4);
+ r.mat.opacity = 0.75 * (1 - k) * (1 - k);
+ }
+
+ if (foamLive) {
+ foamAge += dt;
+ const k = foamAge / 0.9;
+ if (k >= 1) {
+ foamLive = false;
+ foam.visible = false;
+ } else {
+ foam.scale.setScalar(0.35 + k * 1.3);
+ foam.material.opacity = 0.40 * (1 - k) * (1 - k);
+ }
+ }
+ }
+
+ /** See wake.js reset(): effects that integrate dt must start clean on a jump. */
+ function reset() {
+ for (const d of drops) {
+ d.live = false;
+ d.mesh.visible = false;
+ }
+ for (const r of rings) {
+ r.live = false;
+ r.mesh.visible = false;
+ r.mat.opacity = 0;
+ }
+ foamLive = false;
+ foam.visible = false;
+ }
+
+ return { group, trigger, update, reset };
+}
diff --git a/verify/water/src/scene/wake.js b/verify/water/src/scene/wake.js
new file mode 100644
index 0000000..383dd04
--- /dev/null
+++ b/verify/water/src/scene/wake.js
@@ -0,0 +1,163 @@
+import * as THREE from 'three';
+import { POOL } from '../config.js';
+
+/**
+ * Surface wake: a soft foam streak trailing each swimmer plus pooled ripple
+ * rings. Unlit and additive so it stays bright after the palette pass.
+ */
+function makeWakeTexture() {
+ const c = document.createElement('canvas');
+ c.width = 256;
+ c.height = 128;
+ const ctx = c.getContext('2d');
+ ctx.clearRect(0, 0, 256, 128);
+
+ const head = ctx.createRadialGradient(214, 64, 3, 214, 64, 48);
+ head.addColorStop(0, 'rgba(244, 253, 249, 0.9)');
+ head.addColorStop(0.55, 'rgba(232, 250, 244, 0.35)');
+ head.addColorStop(1, 'rgba(232, 250, 244, 0)');
+ ctx.fillStyle = head;
+ ctx.fillRect(150, 8, 106, 112);
+
+ for (const sign of [-1, 1]) {
+ const g = ctx.createLinearGradient(222, 64, 6, 64 + sign * 40);
+ g.addColorStop(0, 'rgba(238, 252, 247, 0.5)');
+ g.addColorStop(0.6, 'rgba(238, 252, 247, 0.16)');
+ g.addColorStop(1, 'rgba(238, 252, 247, 0)');
+ ctx.strokeStyle = g;
+ ctx.lineWidth = 11;
+ ctx.lineCap = 'round';
+ ctx.beginPath();
+ ctx.moveTo(214, 64);
+ ctx.quadraticCurveTo(120, 64 + sign * 22, 6, 64 + sign * 42);
+ ctx.stroke();
+ }
+
+ for (let i = 0; i < 26; i++) {
+ const x = 40 + Math.random() * 190;
+ const y = 64 + (Math.random() - 0.5) * 70;
+ const r = 1 + Math.random() * 3;
+ ctx.fillStyle = `rgba(245, 253, 250, ${0.12 + Math.random() * 0.28})`;
+ ctx.beginPath();
+ ctx.arc(x, y, r, 0, Math.PI * 2);
+ ctx.fill();
+ }
+
+ const tex = new THREE.CanvasTexture(c);
+ tex.colorSpace = THREE.SRGBColorSpace;
+ return tex;
+}
+
+export function createWake(count = 2) {
+ const group = new THREE.Group();
+ const tex = makeWakeTexture();
+
+ const trails = [];
+ for (let i = 0; i < count; i++) {
+ const mat = new THREE.MeshBasicMaterial({
+ map: tex,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+ const geo = new THREE.PlaneGeometry(2.5, 1.25);
+ geo.rotateX(-Math.PI / 2);
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.y = POOL.waterY + 0.008;
+ mesh.renderOrder = 7;
+ mesh.visible = false;
+ group.add(mesh);
+ trails.push({ mesh, mat, phase: i * 1.7 });
+ }
+
+ const rings = [];
+ const ringGeo = new THREE.RingGeometry(0.3, 0.36, 26);
+ ringGeo.rotateX(-Math.PI / 2);
+ for (let i = 0; i < 12; i++) {
+ const mat = new THREE.MeshBasicMaterial({
+ color: 0xe9f9f3,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ });
+ const mesh = new THREE.Mesh(ringGeo, mat);
+ mesh.position.y = POOL.waterY + 0.0105;
+ mesh.renderOrder = 8;
+ mesh.visible = false;
+ group.add(mesh);
+ rings.push({ mesh, mat, age: 0, live: false });
+ }
+ let ringCursor = 0;
+ let spawnClock = 0;
+
+ /**
+ * entries: [{ x, z, yaw, active }] — body centre, heading, on/off.
+ */
+ function update(dt, t, entries) {
+ spawnClock += dt;
+ const spawn = spawnClock > 0.42;
+ if (spawn) spawnClock = 0;
+
+ entries.forEach((e, i) => {
+ const trail = trails[i];
+ if (!trail) return;
+ trail.mesh.visible = !!e.active;
+ if (!e.active) return;
+ const hx = Math.cos(e.yaw);
+ const hz = -Math.sin(e.yaw);
+ trail.mesh.position.set(e.x - hx * 0.95, POOL.waterY + 0.008, e.z - hz * 0.95);
+ trail.mesh.rotation.y = e.yaw;
+ const pulse = 0.30 + Math.sin(t * 3.1 + trail.phase) * 0.05;
+ trail.mat.opacity = pulse;
+ trail.mesh.scale.set(1 + Math.sin(t * 2.2 + trail.phase) * 0.05, 1, 1);
+
+ if (spawn) {
+ const ring = rings[ringCursor % rings.length];
+ ringCursor++;
+ ring.age = 0;
+ ring.live = true;
+ ring.mesh.visible = true;
+ ring.mesh.position.set(e.x - hx * 1.1, POOL.waterY + 0.0105, e.z - hz * 1.1);
+ ring.mesh.scale.setScalar(0.35);
+ ring.mat.opacity = 0.45;
+ }
+ });
+
+ for (const r of rings) {
+ if (!r.live) continue;
+ r.age += dt;
+ const k = r.age / 1.5;
+ if (k >= 1) {
+ r.live = false;
+ r.mesh.visible = false;
+ continue;
+ }
+ r.mesh.scale.setScalar(0.3 + k * 1.15);
+ r.mat.opacity = 0.38 * (1 - k) * (1 - k);
+ }
+ }
+
+ /**
+ * Drop every trail and ring. Call this before re-simulating the effects from
+ * zero, which is how a frozen frame (?t=) stays identical to the played one:
+ * these effects integrate dt, so a jump in the clock is not a jump in state.
+ */
+ function reset() {
+ ringCursor = 0;
+ spawnClock = 0;
+ for (const t of trails) {
+ t.mesh.visible = false;
+ t.mat.opacity = 0;
+ }
+ for (const r of rings) {
+ r.age = 0;
+ r.live = false;
+ r.mesh.visible = false;
+ r.mat.opacity = 0;
+ }
+ }
+
+ return { group, update, reset };
+}
diff --git a/verify/water/src/scene/water.js b/verify/water/src/scene/water.js
new file mode 100644
index 0000000..70b8f19
--- /dev/null
+++ b/verify/water/src/scene/water.js
@@ -0,0 +1,50 @@
+import * as THREE from 'three';
+import { POOL } from '../config.js';
+import { timeUniform } from '../core/materials.js';
+
+/**
+ * Flat, glassy water. A standard physical material keeps shadows, environment
+ * reflection and tone mapping consistent with the rest of the diorama, which a
+ * hand-written shader would otherwise have to reimplement per light.
+ */
+export function createWater() {
+ const geo = new THREE.PlaneGeometry(12.94, 6.94, 10, 6);
+ geo.rotateX(-Math.PI / 2);
+
+ // Shallow end reads pale teal, the deep end nearly navy. Interpolated in
+ // vertex colours so the surface itself carries the pool's depth.
+ const pos = geo.attributes.position;
+ const shallow = new THREE.Color(0x3f9397);
+ const deep = new THREE.Color(0x2a707a);
+ const colors = new Float32Array(pos.count * 3);
+ const c = new THREE.Color();
+ for (let i = 0; i < pos.count; i++) {
+ const t = Math.min(1, Math.max(0, (pos.getX(i) + 6.3) / 11.6));
+ c.copy(shallow).lerp(deep, t * t * 0.85);
+ colors[i * 3] = c.r;
+ colors[i * 3 + 1] = c.g;
+ colors[i * 3 + 2] = c.b;
+ }
+ geo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
+
+ const mat = new THREE.MeshPhysicalMaterial({
+ color: 0xffffff,
+ vertexColors: true,
+ roughness: 0.16,
+ metalness: 0.0,
+ clearcoat: 0.7,
+ clearcoatRoughness: 0.1,
+ envMapIntensity: 0.4,
+ transparent: true,
+ opacity: 0.62,
+ depthWrite: false,
+ side: THREE.FrontSide,
+ });
+
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.position.y = POOL.waterY;
+ mesh.renderOrder = 5;
+ mesh.receiveShadow = true;
+ mesh.userData.uniforms = { uTime: timeUniform };
+ return mesh;
+}