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.

Add the creature battle capture, per-entity frame recorder, and research-first playbook

sloemof87c88f1f562
diff --git a/README.md b/README.md
index 1277eee..9c64358 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,39 @@
+<div align="center">
+
# Diorama
-A playbook and code kit for building small pixel-art dioramas in Three.js.
+**A playbook and code kit for building small pixel-art dioramas in Three.js.**
+
+<a href="media/pikachu-vs-charizard.mp4"><img src="media/pikachu-vs-charizard.gif" width="620" alt="Pikachu vs Charizard, a 45 second battle diorama, looping"></a>
+
+<sub><b>Pikachu vs Charizard</b>, 45 s &nbsp;·&nbsp; a send-out, a full exchange of attacks, a knockout and a recall</sub>
+
+[![Stars](https://img.shields.io/github/stars/sloemo01/diorama?style=flat-square&color=1d1d1f&logo=github&label=stars)](https://github.com/sloemo01/diorama/stargazers)
+[![Forks](https://img.shields.io/github/forks/sloemo01/diorama?style=flat-square&color=1d1d1f&label=forks)](https://github.com/sloemo01/diorama/forks)
+[![Watchers](https://img.shields.io/github/watchers/sloemo01/diorama?style=flat-square&color=1d1d1f&label=watchers)](https://github.com/sloemo01/diorama/watchers)
+[![License](https://img.shields.io/github/license/sloemo01/diorama?style=flat-square&color=1d1d1f)](LICENSE)
+[![Skill](https://img.shields.io/badge/skill-v3.7.0-1d1d1f?style=flat-square)](SKILL.md)
+[![three.js](https://img.shields.io/badge/three.js-r170-1d1d1f?style=flat-square&logo=three.js&logoColor=white)](https://threejs.org)
-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
+</div>
+
+A diorama here is 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
+(pool, night market, bank job, arena battle); 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.
+be frozen, screenshotted and compared. A screenshot is evidence, not a lucky
+capture.
+
+`SKILL.md` is the whole playbook: it carries a research-first workflow, the look
+and animation bars, the pipeline, the recipes, the QA harness and the pitfalls,
+in one self-contained file. Everything else here is copy-in code that supports it.
## Preview
-Three scenes built with this playbook. Each tile loops in place; click one to open
+Four scenes built with this playbook. Each tile loops in place; click one to open
the full capture.
<p>
@@ -22,39 +42,48 @@ the full capture.
<a href="media/bank-job.mp4"><img src="media/bank-job.gif" width="31%" alt="Bank job diorama, police cars arriving on the street, looping"></a>
</p>
-<sub><b>Dust Kings</b>, 38 s &nbsp;·&nbsp; <b>Pool</b>, 26 s &nbsp;·&nbsp; <b>Bank job</b>, 48 s</sub>
+<sub><b>Dust Kings</b>, 38 s &nbsp;·&nbsp; <b>Pool</b>, 26 s &nbsp;·&nbsp; <b>Bank job</b>, 48 s &nbsp;·&nbsp; <b>Pikachu vs Charizard</b>, 45 s</sub>
+
+**Pikachu vs Charizard** is the fight scene at the top of this page: Leon throws a
+ball, Charizard bursts out of it and the ball comes back to his hand, four attacks
+trade across the arena with their own wind-up and hit reactions, Pikachu takes a
+knockdown, and the red recall beam only appears once Charizard is beaten.
-The Dust Kings loop follows one night's billing: cars on the arena floor, the
-billboard running through LIVE, NEW RECORD and THANK YOU, and a fire that gets
-away from them.
+**Dust Kings** follows one night's billing: cars on the arena floor, the billboard
+running through LIVE, NEW RECORD and THANK YOU, and a fire that gets away from
+them.
-The pool loop is a slow afternoon: one swimmer working laps with a wake trailing
-behind, one standing waist-deep by the ladder, one folding into a dive beside the
-board, a lifebuoy and a ball left floating, a lifeguard pacing the far edge, and a
+**Pool** is a slow afternoon: one swimmer working laps with a wake trailing behind,
+one standing waist-deep by the ladder, one folding into a dive beside the board, a
+lifebuoy and a ball left floating, a lifeguard pacing the far edge, and a
sunbather who does not move from the towel.
-The bank job loop runs in daylight: a sedan noses into the curb, a group in dark
-clothes climbs the bank steps and the windows go red behind them, the sedan pulls
-away, two cruisers arrive and officers fan out across the street, and then the
-street empties again.
+**Bank job** runs in daylight: a sedan noses into the curb, a group in dark clothes
+climbs the bank steps and the windows go red behind them, the sedan pulls away, two
+cruisers arrive and officers fan out across the street, then the street empties
+again.
## 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. |
+| `SKILL.md` | The whole playbook: research gate, look contract, detail and animation bars, pipeline, recipes, QA, pitfalls. Start here. |
+| `templates/` | Copy-in modules: palette, post pass, camera, lighting, geometry, props, rig, poses, vehicle transfer, paths, combat, creature, 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. |
+| `templates/SOURCES.md` | The research log you fill before modelling: query, what was found, decision. |
+| `templates/CREDITS.md` | The licence ledger for every imported model, clip or texture. |
+| `templates/creature.js` | Rigged-actor combat: stage-local aiming, bone-space effect anchors, upright billboards, hit severities, send-out geometry. |
+| `templates/qa/` | Eight verification scripts that check a build against frozen frames and printed numbers, including a per-entity frame recorder. |
| `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. |
+| `verify/creature-battle/` | What a two-actor fight build proved: aiming, effect anchoring, send-out and hit numbers. |
| `media/` | The preview GIFs and source captures shown above. |
## Install it
Paste this into an agent that can run shell commands. It asks where to put the
-folder, downloads the whole repository (playbook, templates, QA harness and both
-worked examples), reads them, and reports what it learned before it builds
+folder, downloads the whole repository (playbook, templates, QA harness and every
+worked example), reads them, and reports what it learned before it builds
anything. `SKILL.md` carries skill frontmatter (`name`, `description`, `version`),
so an agent with a skills directory can load it by name later.
@@ -82,44 +111,90 @@ Repo: https://github.com/sloemo01/diorama
there so you can load it by name in later sessions; otherwise
treat "<target>" as the folder.
5. Read before you build: all of SKILL.md, then
- templates/DESIGN.md, templates/qa/README.md, the header comment
- of every file in templates/, and both worked examples under
- verify/. SKILL.md is the source of truth; the README is only a
- summary.
+ templates/DESIGN.md, templates/SOURCES.md, templates/CREDITS.md,
+ templates/qa/README.md, the header comment of every file in
+ templates/, and the worked examples under verify/. SKILL.md is
+ the source of truth; the README is only a summary.
6. Report back in this order: install path and commit, the Look
Contract in one paragraph, the Pipeline as ordered steps, the
QA scripts and what each one checks, and three rules from
SKILL.md with the section each came from.
7. Then ask me what the first diorama should be. Do not ask me to
- fill the design sheet. When I give you a subject, fill
- DESIGN.md from the defaults, copy the modules you need into my
- project instead of editing the installed copy, build through
- the Pipeline, and run the QA scripts before you show me
- anything. Give me the paths of the frames you kept and what
- each one proves.
+ fill the design sheet. When I give you a subject, research it
+ first (frames, assets, motion), fill DESIGN.md from the
+ defaults, copy the modules you need into my project instead of
+ editing the installed copy, build through the Pipeline, and run
+ the QA scripts before you show me anything. Give me the paths
+ of the frames you kept and what each one proves.
If two parts of SKILL.md contradict each other, list them before
you build. A successful clone is not an install: 5 and 6 are it.
```
Needs `git`, or `curl` and `tar` for the fallback. The QA scripts need Node with
-`three`, `esbuild` and `playwright-core`. The `media/` previews are about 18 MB
+`three`, `esbuild` and `playwright-core`. The `media/` previews are about 20 MB
and can be deleted after the clone.
## 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
+1. Read `SKILL.md`: `Research Before You Model`, `One Prompt, One Build`, `The Look
+ Contract`, `The Detail Bar`, `The Animation Bar`, `Pipeline`.
+2. Research first. Step the real subject into frames and write its motion grammar
+ down. Walk the sourcing ladder for every hero asset (already on disk, CC0,
+ CC-BY, then hand-build) and record each search in `refs/SOURCES.md`. Imported
+ assets get a row in `CREDITS.md`.
+3. 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`
+4. 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
+5. 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:
+6. Verify with `templates/qa/` before calling it done, and check the research gate
+ in `Build And Ship` (reference sheets, `SOURCES.md`, `CREDITS.md`, per-beat
+ captures).
+
+## Research before you model
+
+The playbook opens with four lookups, because a plausible silhouette that matches
+nothing is the most common way a commission fails:
+
+- **Shape.** Pull the real thing on video, step it into contact sheets at 8 to 12
+ fps, read them, and write the grammar down before touching geometry.
+- **Assets.** Check the user's disk, then the CC0 and CC-BY libraries (Quaternius,
+ KayKit, Poly Pizza, Kenney, Sketchfab with the downloadable plus CC0 filter,
+ Smithsonian, Poly Haven, ambientCG, Mixamo and the Quaternius animation
+ library). A rigged download beats four hundred lines of primitives at close
+ range. Licences that are NC, ND, ripped or unstated are a hard stop.
+- **Motion.** Search the verb, not the noun. Count frames at a known fps, convert
+ to seconds, and write wind-up / contact / follow-through / recover before
+ animating.
+- **Proof.** Freeze every beat and compare the capture against the reference
+ frame for that beat.
+
+`templates/SOURCES.md` and `templates/CREDITS.md` are the two artifacts that make
+that research visible in a project, and `Build And Ship` will not pass without
+them.
+
+## How it works
+
+- **One camera solve.** The camera is fitted to the slab's bounding box once, at a
+ fixed three-quarter azimuth, with a `subjectScale` margin. No orbit controls.
+- **Two passes, one look.** The render is drawn into a small buffer, then gamma,
+ grade, a 64 entry palette snap, ordered dither, an ink contour and a nearest
+ neighbour upscale happen in that fixed order.
+- **Detail is a bar, not a mood.** Every hero prop carries a real silhouette,
+ chamfers, seams, hardware and a contact shadow; if it reads at a glance and
+ still holds at 1:1, it passes.
+- **Animation is five layers.** Idle, locomotion, secondary motion (clothes, hair,
+ tails, capes), glance and weight shifts, then the scripted acting on top.
+- **Everything is a function of `t`.** Actors, props, effects and camera are
+ evaluated from the beat sheet each frame, so `?t=12.4` is exactly the same
+ picture every time.
+
+## Verification
+
+The `templates/qa/` scripts drive Chromium through `playwright-core` against a
+page that exposes a debug handle:
```js
window.__diorama = {
@@ -130,11 +205,40 @@ window.__diorama = {
window.__dioramaReady = true;
```
+| Script | What it checks |
+| --- | --- |
+| `shoot.mjs` | console errors, layout at each viewport, named frozen timestamps |
+| `audit.mjs` | flat glows, whole-group fades, early hides, teleports, margin leaks |
+| `portrait.mjs` | isolated figures through a debug camera |
+| `strip.mjs` | N-frame motion strips, fails on a frozen loop |
+| `frames.mjs` | per-entity frame series with a verdict each: FROZEN, TELEPORT, EMPTY, OFFSCREEN |
+| `sweep.mjs` | pairwise distances, jam and teleport verdicts |
+| `probe.py` | colour runs across an edge |
+| `tile.py` | tiles a motion strip into a contact sheet |
+
`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.
+`frames.mjs` is the one that pays for itself on a scene with more than two actors.
+It records one dense series per entity, isolates it, fits a camera to its swept
+bounds, and scores it: a flat energy line means the actor is not animating, an NDC
+jump means a state boundary is snapping instead of blending, and empty frames mean
+the window is wrong. Each entity gets a contact sheet and a verdict, so a dead
+actor cannot hide behind a moving neighbour.
+
+The worked examples under `verify/` show the loop end to end, including the
+defects the harness found and the numbers after the fix.
+
+## 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/`.
+
+If you just want to read it, start at `Research Before You Model`, then
+`One Prompt, One Build` and `The Look Contract`.
## Licence
-MIT. See `LICENSE`.
+MIT. See `LICENSE`. three.js is MIT as well.
diff --git a/SKILL.md b/SKILL.md
index 0799f18..bb7ff84 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,7 +1,7 @@
---
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
+version: 3.8.0
author: Nehal Kanak (sloemo)
license: MIT
platforms: [linux, macos, windows]
@@ -19,8 +19,8 @@ change.
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
+Read `Research Before You Model`, `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.
@@ -30,6 +30,7 @@ reading every vehicle or water note for a kitchen scene.
| --- | --- |
| 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 |
+| creature battle, game scene, anime/movie fight | Research Before You Model → Field Notes: Two-Creature Combat → Creature Anatomy → 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 |
@@ -56,6 +57,191 @@ consequence. The fast path only decides which reference notes to read first.
Don't use for full-resolution product renders, photoreal scenes, or anything
that needs free orbit controls.
+## Research Before You Model
+
+Four lookups come before the first mesh: the subject by frames, the asset
+libraries, the motion itself, and the capture loop. Skipping them is how a build
+ends up with a plausible silhouette that matches nothing and animation that reads
+as generic. Budget for them, they are usually faster than the modelling they save.
+
+| Question the research answers | Where it lands |
+| --- | --- |
+| what does it look like, exactly | `refs/<subject>/*.png` contact sheets |
+| what does it do, in what order, how fast | `refs/SOURCES.md` + the beat table |
+| does a rig or clip already exist | `CREDITS.md` + `assets/` |
+| is it actually right on screen | `qa/` captures, compared to the sheets |
+
+### 1. The subject, by frames
+
+Find the real thing moving, not stills. For games, anime, sport or machinery the
+footage *is* the specification: it settles what the shape is, where the motion
+starts, how long each stage lasts and what colour it is at each step.
+
+```bash
+yt-dlp --flat-playlist --print "%(id)s | %(title)s | %(duration)s" "ytsearch6:<subject> animation"
+yt-dlp --extractor-args "youtube:player_client=ios,android" -f 18 -o "refs/clip.%(ext)s" <id>
+ffmpeg -i refs/clip.mp4 -vf "fps=8,scale=300:-1,tile=6x4" refs/sheet-%02d.png
+```
+
+Read the contact sheets with vision, then write the grammar down in words before
+touching geometry: *ball leaves the hand on an arc, opens with a white burst, the
+creature springs out at full size, the ball snaps shut and returns*. A paragraph
+like that is the acceptance test for the effect you are about to build.
+
+Rules that come out of doing this repeatedly:
+
+- Prefer **game footage** over fan animation for game subjects; the game is the
+ canonical grammar, and fan cuts are already an interpretation.
+- Prefer **one clean clip sampled densely** over ten clips sampled sparsely.
+ Twelve frames a second on a 4 second send-out shows the whole sequence.
+- Keep the sheets in `refs/<subject>/` next to the build so the next person can
+ see what you were matching, and so QA has an image to compare against.
+
+### 2. Model sourcing: check the libraries before you build
+
+Hand-building a creature from primitives is the *last* option, not the first. A
+rigged download with real deformation and usable clips beats four hundred lines
+of spheres the moment the camera comes within a metre. Search first, and keep a
+record of what you searched.
+
+**The ladder. Every hero asset walks down it in order.**
+
+1. **Already on disk.** The user's folder often ships a `tools/`, `assets/` or
+ `model/` directory with GLBs in it. List it before anything else.
+2. **A CC0 pack covers it.** Import it. No attribution, no negotiation.
+3. **A CC-BY model covers it** and the page can carry a credit line. Import it,
+ credit it, done.
+4. **Nothing fits the silhouette** and the shape has to be exact. Hand-build it
+ against the reference frames, and say in the log that you searched.
+5. **Never:** ripped game assets, Models Resource / Spriters Resource downloads
+ used as geometry, "editorial use only", NC, ND, or anything with no stated
+ licence. Those are hard stops; ask the user instead of guessing.
+
+**Creatures, characters and rigs**
+
+| Source | Licence | What is actually there | How to search |
+| --- | --- | --- | --- |
+| [Quaternius](https://quaternius.com) | CC0 | hundreds of low-poly creatures, characters, nature, buildings; the Universal Animation Library is 120+ clips | browse `quaternius.com/packs`, grab the pack GLB |
+| [KayKit / Kay Lousberg](https://kaylousberg.itch.io) | CC0 | adventurers, skeletons, dungeon and RPG packs, rigged and animated | itch page, per-pack zip |
+| [Poly Pizza](https://poly.pizza) | CC0 or CC-BY | 10,000+ low-poly props, creatures, vehicles; GLB/OBJ, no login | search by noun, read the badge on each card |
+| [Kenney](https://kenney.nl/assets) | CC0 | kits for props, vehicles, characters, UI, audio | category browse |
+| [Sketchfab](https://sketchfab.com/3d-models) | per model | the long tail: specific machines, animals, buildings | filter **Downloadable** + **CC0**/**CC-BY** before looking at anything |
+| [Smithsonian 3D](https://3d.si.edu) | CC0 | scanned real objects, fossils, artefacts, vehicles | search, check the licence note under the download |
+| [NASA 3D Resources](https://nasa3d.arc.nasa.gov) | public domain | spacecraft, rovers, terrain, helmets | browse by category |
+| [glTF Sample Assets](https://github.com/KhronosGroup/glTF-Sample-Assets) | per model, mostly CC-BY 4.0 | canonical rigged test models (CesiumMan, Fox, BrainStem) | read `LICENSES/` before use |
+| [Objaverse](https://objaverse.allenai.org) | mixed, per object | 800k research objects, good for odd props | verify the per-object licence, most are not clean |
+| [Meshy](https://meshy.ai), [Tripo](https://www.tripo3d.ai), user-supplied | user owns the output | anything the pack libraries do not have, generated from the reference | export GLB, keep the prompt in `CREDITS.md` |
+
+**Animation clips** (motion is usually harder to hand-key than shape is to model)
+
+| Source | Licence | Notes |
+| --- | --- | --- |
+| Quaternius Universal Animation Library | CC0 | 120+ humanoid clips, retargetable, best first stop |
+| [Mixamo](https://www.mixamo.com) | free with an Adobe account | thousands of humanoid clips + characters; check current Adobe terms, retarget in Blender or three.js |
+| [Rokoko Motion Library](https://rokoko.com/products/motion-library) | 150 free clips, paid beyond | mocap quality, good for weight and follow-through |
+| CMU Graphics Lab Motion Capture | free for research and commercial use with credit | raw BVH, huge, needs cleanup |
+| Sketchfab animated models | per model | often ships with an idle/walk/attack set |
+| [Godot4 Open Animation Libraries](https://github.com/catprisbrey/Godot4-OpenAnimationLibraries) | CC0 | Mixamo clips rebaked as Godot `.bin`/GLB banks, already retargeted; `jwelchgames/Godot4-MixamoLibraries` is the other mirror |
+
+**Props, environments, textures, light**
+
+| Source | Licence | Notes |
+| --- | --- | --- |
+| [Poly Haven](https://polyhaven.com) | CC0 | HDRIs, textures, models; the HDRI set is the fastest way to fix flat lighting |
+| [ambientCG](https://ambientcg.com) | CC0 | tiling PBR materials, HDRIs, some models |
+| [OpenGameArt](https://opengameart.org) | mixed | filter to CC0 / CC-BY; 3D section is thin but has good odd props |
+| [madjin/awesome-cc0](https://github.com/madjin/awesome-cc0) | index | a maintained list of CC0 sources when the usual four fail |
+
+**Searching them without a browser.** Three of the libraries have open APIs, so a
+build can check them in a single command and read the licence back:
+
+```bash
+# Sketchfab: downloadable + CC0 only, name and page printed for each hit
+curl -s "https://api.sketchfab.com/v3/search?type=models&downloadable=true&license=cc0&q=dragon&count=24" \
+ | python3 -c "import json,sys;[print(r['name'],'|','https://sketchfab.com/models/'+r['uid']) for r in json.load(sys.stdin)['results']]"
+
+# Poly Haven: models, HDRIs, textures (filter by category)
+curl -s "https://api.polyhaven.com/assets?t=models"
+curl -s "https://api.polyhaven.com/assets?t=hdris&c=studio"
+
+# ambientCG: materials and HDRIs by keyword
+curl -s "https://ambientcg.com/api/v2/full_json?type=Material&limit=20&q=concrete" \
+ | python3 -c "import json,sys;print([a['assetId'] for a in json.load(sys.stdin)['foundAssets']])"
+```
+
+Poly Pizza, Quaternius, KayKit and Kenney are browsed by search on their own
+pages; query them with the noun plus the style (`low poly dragon`, `kaykit
+skeleton`), not with a sentence.
+
+**Reference only, never geometry:** The Spriters Resource, The Models Resource,
+sakugabooru, game rip archives, Pinterest. Use them to learn the shape and the
+timing, then build or buy the actual asset.
+
+### 3. Animation research: how the thing moves
+
+Shape is half the job; the other half is the motion, and it is researched the same
+way. Search the *verb*, not the noun.
+
+```bash
+# the motion itself, canonical first
+web_search: "<subject> <move> animation" # a game doing it
+web_search: "<subject> <move> slow motion" # real footage, for weight
+web_search: "<subject> sprite sheet" # frame-by-frame timing
+yt-dlp "ytsearch6:<subject> <move> animation"
+ffmpeg -i clip.mp4 -vf "fps=12,scale=320:-1,tile=6x4" refs/move-%02d.png
+```
+
+Read the sheet, then **count frames and convert**: `seconds = frames / fps`, and
+scale to the loop length you are building. That is how a 0.42 s anticipation and a
+0.18 s contact become the beat table instead of a guess.
+
+Write four lines per action before animating it:
+
+```
+wind-up 0.00 -> 0.42 weight back, head down, tail still
+contact 0.42 -> 0.55 fastest frames, one pose held for two frames
+follow 0.55 -> 0.90 overshoot, then settle
+recover 0.90 -> 1.30 back to idle
+```
+
+Every attack in the beat sheet needs all four. Missing anticipation is why an
+effect reads as "it just happens", and missing follow-through is why it reads as
+"it snaps back".
+
+For rigs, cross-check the reference against a real clip: if the library has a
+punch, a swipe or a jump that is close, retarget it and offset the acting, rather
+than keying a pose from scratch.
+
+### 4. The research log
+
+Every build writes `refs/SOURCES.md`. It is the proof the searches happened and
+the reason the next person does not repeat them.
+
+```md
+| Question | Searched | Found | Decision |
+| --- | --- | --- | --- |
+| what does the send-out look like | yt: "sword shield send out slow motion" | RoUJ_TWvB3g, orb + white burst | matched, timings below |
+| hero creature rig | poly.pizza "dragon", quaternius characters | nothing matching the silhouette | hand-built from refs/sendout |
+| hit reaction weight | yt: "pokemon take damage animation" | 0.9 s flinch, 1.7 s stagger | HURTS table |
+```
+
+A build with no `SOURCES.md` has not finished its research step, even if the
+scene looks right.
+
+### 5. Prove it with shots
+
+Every beat gets frozen, captured and compared against the reference sheet before
+the next beat is built. The contact sheet of those captures is the review
+artifact, not a paragraph describing them.
+
+- Freeze the loop at the beats the reference showed: `?t=<second>` in the page,
+ `freeze(t)` through the debug hook, screenshot the frame element.
+- Put the captures in a grid next to the reference frames and read them with
+ vision. Anything that needs a caption to explain is not finished.
+- Keep numerical checks alongside the pictures: facing dot products, NaN scans
+ over every geometry, console errors, effect bounding boxes. They catch the
+ failures the eye forgives at 300 px.
+
## One Prompt, One Build
When the user gives a subject in one line, treat it as a **commission**, not a
@@ -66,6 +252,20 @@ 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.
+### Step 0, before the assumption line
+
+Run the three lookups in `Research Before You Model` first:
+
+1. Step the real subject into frames and write down its motion grammar.
+2. Walk the sourcing ladder for every hero asset (disk, CC0, CC-BY, hand-build),
+ with a `CREDITS.md` line per import and the search in `refs/SOURCES.md`.
+3. Stand up the capture loop (`qa/shoot.mjs`, a frozen `?t=` frame, a contact
+ sheet) so every beat can be reviewed as a picture.
+
+For an invented subject, spend the same time on reference density instead: find
+three images that agree on what the place looks like, list the props they share,
+and build those before any invented detail.
+
### The default commission
Use these unless the prompt explicitly says otherwise:
@@ -94,6 +294,28 @@ 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.
+### Long builds and context
+
+A scene like this runs for hours of agent time and thousands of messages: render
+loops, one screenshot per beat, one probe per bug. The session will need to
+compress its context, more than once, and compaction is lossy. Build so that a
+compact does not cost you the work:
+
+- **State lives in files, not in the chat.** `DESIGN.md`, `refs/SOURCES.md`,
+ `CREDITS.md`, `qa/report.json` and the beat table in `stage.js` must carry every
+ decision. If a fact only exists in a message, it is already gone.
+- **Write the rule down when you learn it.** A fix found at 3 a.m. is worthless if
+ it only exists in the transcript; put it in the skill or a comment next to the
+ code, with the reason.
+- **Name the shots.** `qa/frames/<entity>/sheet.png` and `shots/t-12.40.png` are
+ stable handles a post-compact agent can re-read without rerunning anything.
+- **Re-derive, do not remember.** After a compact, re-run `frames.mjs` and
+ `shoot.mjs` rather than trusting your summary of what the last frame looked
+ like: the numbers are cheap, and a confident memory of an old build is the
+ most expensive thing in the session.
+- **Keep one open task list** in the repo (a `TODO.md` or an issue) so the thread
+ that survives compaction is the plan, not the chat.
+
### Reading the prompt
| Prompt shape | What to do |
@@ -2021,6 +2243,24 @@ window.__diorama = { THREE, scene, camera, renderer, post, director, cast,
`?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.
+### The research gate, at ship time
+
+A build is not finished until these exist. Check them before the summary:
+
+- [ ] `refs/<subject>/` has at least one contact sheet stepped from real footage.
+- [ ] `refs/SOURCES.md` answers the four questions (shape, motion, asset, proof)
+ with the queries actually run. "Nothing found" is a valid answer only with
+ the query written down next to it.
+- [ ] `CREDITS.md` has a row per imported asset, and every licence is CC0, CC-BY,
+ public domain, or owned by the user.
+- [ ] Every hero asset walked the ladder: disk, CC0, CC-BY, then hand-built. If it
+ was hand-built, the row says so.
+- [ ] The captures for each beat exist, and each one was compared against the
+ reference frame for that beat.
+
+A missing `SOURCES.md` means the research step was skipped, and the scene is
+probably wearing the generic version of its genre.
+
## Surface, Motion And Event FX
These are the failures that survive a good first render: a finished-looking set
@@ -2124,6 +2364,57 @@ system, on every subject.
`visible`. `getWorldPosition` on a merge-eaten object returns local coordinates
because the original was unparented; that is the signature of the merge pass.
+### Per-entity frame recording
+
+A still cannot prove a jump. A six-frame strip cannot prove that the third
+character in the scene is animating, because the other two are moving in the
+same picture. `qa/frames.mjs` records **one dense series per entity**, and prints
+a verdict for each, so a dead actor cannot hide behind a live neighbour.
+
+```bash
+BASE_URL=http://127.0.0.1:4180/index.html \
+ENTITIES='({ hero: d.cast[0].model, guard: d.cast[1].model })' \
+FROM=4 TO=9 FPS=12 OUT=qa/frames STATIC=guard \
+ node templates/qa/frames.mjs
+```
+
+What it does per entity:
+
+- **Isolates it.** `ISOLATE=scene` (default) hides every mesh not on that
+ entity's branch, so the signature is really about this actor; `siblings` hides
+ the other registry entries only. Restored afterwards.
+- **Fits one camera to the swept bounds** and keeps it for the whole window, so
+ travel stays visible. A camera that follows the actor hides exactly the drift
+ you are looking for.
+- **Samples at `FPS`** (12 by default) across `FROM..TO`, and for each frame logs
+ the world bounds centre in NDC, plus a 32x32 luminance signature.
+- **Scores four ways.** `empty` counts frames where the entity is not on screen,
+ `energy` is the largest mean luminance delta between consecutive on-screen
+ frames (a flat line means the actor is not animating), `step` is the largest
+ NDC jump (a teleport), and `OFFSCREEN` counts frames outside the frustum.
+- **Writes a contact sheet** per entity, `qa/frames/<name>/sheet.png`, and the
+ numbers to `report.json`. Exit code 1 when anything is flagged, so CI can gate.
+
+Reading it:
+
+| Verdict | Means | What to do |
+| --- | --- | --- |
+| `ok` | moved, stayed inside, no jump | still read the sheet for pose quality |
+| `FROZEN` | energy under `MIN_ENERGY` | the pose blend is not reaching this actor |
+| `TELEPORT` | an NDC jump over `MAX_STEP` | a state boundary is snapping, not blending |
+| `EMPTY n/N` | not rendered for over half the window | wrong window, or it spawns later than you think |
+| `NOT-IN-WINDOW` | never rendered in the window | the entity name is wrong, or it is invisible |
+| `OFFSCREEN` | left the frustum | staging, camera fit, or a run that goes too far |
+
+Two rules for the numbers. A blank frame beside a full one must never be allowed
+to supply the energy for a window, so only consecutive on-screen pairs are
+compared. And an entity that is meant to hold still (a seated figure, a guard at
+a post) goes in `STATIC=`, or you will get a `FROZEN` that means nothing.
+
+Run it for every hero actor, and for each scripted beat that involves them:
+send-out, attack, hit, death, exit. The sheet is the evidence; the verdict only
+tells you which sheet to open first.
+
### Detail And Animation Audit
Run this after the build and before shipping. It is deliberately visual; a
@@ -2250,6 +2541,9 @@ same timestamp.
```
DESIGN.md filled design sheet: premise, cast, systems, beats, budget
+CREDITS.md every imported model: URL, author, licence (CC0/CC-BY/owned)
+refs/ reference frames: contact sheets stepped from the source clip
+refs/SOURCES.md research log: query -> found -> decision, per question
src/
config.js scene constants + clamp/lerp/smooth/pulse/hash
main.js renderer, scene, clip planes, resize, rAF, ?t= freeze
@@ -2270,6 +2564,7 @@ src/
build.mjs esbuild bundle, index.html, standalone HTML
qa/
shoot.mjs viewports + console errors + named timestamps
+ probe-*.mjs one-off numeric probes (facing, anchors, NaN, spawn pose)
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)
@@ -2313,8 +2608,11 @@ 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`.
+`combat.js` for deterministic timing and death grammar, `creature.js` for a
+fight between two rigged actors (stage-local `aimYaw`, bone-space `headAnchor`,
+`uprightQuat`, the `makeHurtModel` severity table and `sendOut` throw-and-return
+geometry). Effects: `water.js`, `wake.js`, `splash.js`. Sheets: `DESIGN.md`,
+`CREDITS.md`, `SOURCES.md` (the research log, filled before the first mesh).
`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
@@ -2399,8 +2697,130 @@ TEST: qa/audit.mjs IDLE_EMITTER / ORPHAN_EMITTER; event frame present,
event + 1.5 s absent
```
+## Field Notes: Two-Creature Combat
+
+From a Pikachu vs Charizard battle diorama built against Sword/Shield and anime
+footage. The rig, the effects and the send-out all broke in the same three ways,
+and the fixes generalise to any fight between two rigged actors.
+
+### Aiming is a local-space problem
+
+Both rigs look down their own `+Z`, and both sit under a stage root that is
+rotated (here 90°). Reading a world-space bearing to the opponent and writing it
+to a local `rotation.y` aims the two *past* each other, toward the lens. Compute
+the yaw inside the stage's own frame:
+
+```js
+const camLocal = cameraDirection.clone().applyAxisAngle(UP, -STAGE_ROT);
+const aimYaw = (a, b, cheat) => {
+ const dx = b.x - a.x, dz = b.z - a.z;
+ return Math.atan2(dx, dz) + camLocal.x * cheat; // local, not world
+};
+```
+
+Then prove it numerically, every half second, through the whole loop: forward
+vector versus vector-to-opponent should sit at 0.97+, and it may only dip during
+a deliberate spin. Eyeballing this at 300 px hides a 20° miss.
+
+### Effects belong in bone space, not world space
+
+Flames leaving a mouth must be anchored to the head joint, or they slide off the
+jaw whenever the head turns. Convert the parent's forward and up into the target
+bone's local space once at build time and keep the emitted point there:
+
+```js
+const localFwd = bone.worldToLocal(pivotPoint.clone().add(forward)).normalize();
+```
+
+Same idea for the aim of a projectile: take the muzzle from the bone matrix, not
+from a hardcoded offset.
+
+### Flat effects need an upright basis
+
+`quaternion.setFromUnitVectors(+Z, viewDir)` picks an arbitrary roll, which is
+why a kanji-shaped blast can arrive upside down or rotated 40°. Build the basis
+from the lens explicitly:
+
+```js
+const right = new THREE.Vector3().crossVectors(worldUp, viewDir).normalize();
+const up = new THREE.Vector3().crossVectors(viewDir, right).normalize();
+mesh.quaternion.setFromRotationMatrix(new THREE.Matrix4().makeBasis(right, up, viewDir));
+```
+
+### Explosion vocabulary
+
+A hit burst is a hot core with ten short sparks radiating out of it, plus a ring
+on the ground. That is the whole recipe; it reads at any size.
+
+- No cone petals, no triangle fans, no straight bars, no scaffolding around the
+ blast. Every one of those reads as geometry, not energy.
+- Layered silhouettes beat layered spheres: a body colour, a hot mid, a core,
+ each scaled *individually* (`m.scale.set(k,1,1)` per layer) — sharing one
+ geometry between layers makes the layers invisible.
+- A continuous stream is **one** mesh with overlapping segments. Separate quads
+ with per-segment jitter make a ladder with seams.
+- Nested cones hide their own core: nudge the inner layers toward the lens and
+ lift them so the hot tip clears the outer silhouette.
+
+### Pin the effect to where the hit landed
+
+An eruption anchored to `actor.position` every frame crawls across the slab while
+the actor slides out of it, which is exactly the "something feels off, it moves a
+bit" report. Latch the anchor once, at the moment of impact, and animate from
+that fixed point. Same for the projectile's target: aim at the latched point, not
+at the live chest position.
+
+### Send-out and recall are different verbs
+
+- Send-out: the trainer throws. The ball leaves the hand on an arc, spins, lands
+ on the mark, the lid opens with a white burst — flash, smoke puff, sparks, a
+ ground ring — and the creature springs out *at full size*, covered by the flash.
+ The ball then snaps shut and returns to the trainer's hand.
+- Do **not** replace that with a slow orb the creature materialises inside; that
+ is the legendary-encounter variant, and it reads as a bubble.
+- The red beam belongs to a recall or a knockout, never a send-out. If the ball
+ glows red before release, it reads as a second, wrong beam — keep the release
+ white.
+- If the trainer holds a second ball while the thrown one is in the air, hide the
+ held prop for the duration or the throw doubles.
+
+`templates/creature.js` ships these five as runnable functions: `aimYaw`,
+`headAnchor`, `uprightQuat`, `makeHurtModel`, `sendOut`.
+
+### Hit reactions scale with the attack
+
+One hit model, four severities: a light flinch (0.9 s, a tip back), a knocked-back
+stagger (1.7 s, air time), a spin-out (1.3 s), and a full collapse (3.5 s, falls,
+lies down, gets up). Rotate about the axis of the blow (`[dz, 0, -dx]`), pivot at
+mid-body so the actor rocks rather than hinging at the feet, and add a small
+vertical arc so the feet leave the ground.
+
## Changelog
+- **3.8.0** — `qa/frames.mjs`: a per-entity frame recorder. Samples one dense
+ series per entity across a window, isolates it (branch, siblings or full
+ scene), fits one camera to its swept bounds so travel stays visible, and scores
+ every entity: `energy` (flat means frozen), `step` (NDC jump means teleport),
+ `empty` frames, `OFFSCREEN`, with `STATIC=` for actors meant to hold still. Each
+ entity gets a contact sheet plus a row in `report.json`, and the script exits
+ non-zero on any flag. New `Per-entity frame recording` section in Verification.
+ New `Long builds and context` section: compaction is lossy, so state lives in
+ `DESIGN.md`, `SOURCES.md`, `CREDITS.md`, `report.json` and the beat table, and a
+ post-compact agent re-runs the harness instead of trusting its summary.
+- **3.7.0** — Research-first release, from the Pikachu vs Charizard battle
+ diorama. New `Research Before You Model` section: step the source footage into
+ contact sheets and write the motion grammar down before modelling, prefer
+ game footage over fan cuts, and check free commercial-use libraries (Poly
+ Pizza, Sketchfab CC0/CC-BY, Quaternius, Kenney, user-supplied AI meshes) before
+ hand-modelling a creature; `CREDITS.md` + licence gate + `fitModel` pipeline +
+ forward-axis probing; shots-as-acceptance-test. New `Field Notes: Two-Creature
+ Combat` section: stage-local aiming with a numeric facing sweep, bone-space
+ effect anchors, upright billboard basis, explosion vocabulary (no cones/bars/
+ scaffolding, per-layer scaling, one continuous stream), latching effect anchors
+ to the impact point, send-out vs recall grammar (throw → arc → open → burst →
+ full-size exit → ball returns; red beam only on recall), and severity-scaled
+ hit reactions about the blow axis. Project layout gains `refs/` and
+ `CREDITS.md`.
- **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
diff --git a/media/pikachu-vs-charizard.gif b/media/pikachu-vs-charizard.gif
new file mode 100644
index 0000000..c73cc40
Binary files /dev/null and b/media/pikachu-vs-charizard.gif differ
diff --git a/media/pikachu-vs-charizard.mp4 b/media/pikachu-vs-charizard.mp4
new file mode 100644
index 0000000..ad706c4
Binary files /dev/null and b/media/pikachu-vs-charizard.mp4 differ
diff --git a/templates/CREDITS.md b/templates/CREDITS.md
new file mode 100644
index 0000000..babc7b2
--- /dev/null
+++ b/templates/CREDITS.md
@@ -0,0 +1,22 @@
+# Credits
+
+Every imported asset gets a line here: what it is, where it came from, who made
+it, and the licence. Delete the examples once real rows are in.
+
+| Asset | File | Source | Author | Licence |
+| --- | --- | --- | --- | --- |
+| hero fighter rig (skinned) | `assets/knight.glb` | https://poly.pizza/m/xxxx | @author | CC0 |
+| stall awning texture | `assets/awning.glb` | https://sketchfab.com/3d-models/xxxx | @author | CC-BY 4.0 |
+| crow animation clips | `assets/crow.anim.glb` | user-supplied | — | owned by client |
+
+## Rules
+
+- **Allowed:** CC0, public domain, CC-BY with attribution, assets the user owns
+ or supplied, and AI-generated meshes the user commissioned (Meshy, Tripo, etc).
+- **Not allowed without asking:** anything NC, ND, "editorial use only", ripped
+ from a game, or with no stated licence. Ask the user; do not guess.
+- CC-BY needs visible attribution in the page footer or an `About` line, not just
+ this file.
+- Record the URL you actually downloaded from, and the date, because listings
+ move.
+- Note the edits you made: retopology, reskin, rescaled, root motion stripped.
diff --git a/templates/SOURCES.md b/templates/SOURCES.md
new file mode 100644
index 0000000..bf57183
--- /dev/null
+++ b/templates/SOURCES.md
@@ -0,0 +1,41 @@
+# Sources
+
+The research log for this build. One row per question, with the query actually
+run and the decision. Written before the first mesh and updated as the build
+finds out it was wrong.
+
+## Shape
+
+| Question | Searched | Found | Decision |
+| --- | --- | --- | --- |
+| what does a send-out look like, in order | yt: `sword shield send out slow motion` | `RoUJ_TWvB3g`, orb forms inside a white burst | matched; frames in `refs/sendout/` |
+
+## Motion
+
+| Question | Searched | Found | Decision |
+| --- | --- | --- | --- |
+| how long is the wind-up | yt: `<move> animation` stepped at 12 fps | 5 frames at 12 fps = 0.42 s | beat table: wind-up 0.42, contact 0.13, follow 0.35 |
+| what does the hit reaction look like | yt: `pokemon take damage animation` | 0.9 s flinch, 1.7 s stagger for the big one | HURTS table |
+
+## Assets
+
+| Asset | Ladder step | Source / query | Licence | Decision |
+| --- | --- | --- | --- | --- |
+| hero creature rig | 2 (CC0) | poly.pizza `dragon`, quaternius.com characters | CC0 | nothing matched the silhouette, hand-built from `refs/sendout/` |
+| backdrop HDRI | 3 (CC-BY) | polyhaven.com `studio` | CC0 | imported, credited |
+| attack clips | 2 (CC0) | Quaternius Universal Animation Library | CC0 | retargeted, root motion stripped |
+
+## Proof
+
+| Beat | Capture | Compared against | Result |
+| --- | --- | --- | --- |
+| send-out | `shots/sendout/sheet.png` | `refs/sendout/sheet-01.png` | ball arcs, opens, creature exits at full size, ball returns |
+
+## Rules
+
+- Write the query, not just the result, so the next person can tell a dead end
+ from an untried one.
+- "Nothing found" is a real answer, but only with the search written next to it.
+- Keep the reference sheets in `refs/<subject>/`; do not delete them after the
+ build, because the next fix will need them.
+- Anything imported gets a matching row in `CREDITS.md`.
diff --git a/templates/creature.js b/templates/creature.js
new file mode 100644
index 0000000..a30be8a
--- /dev/null
+++ b/templates/creature.js
@@ -0,0 +1,173 @@
+// Creature-combat module for the diorama kit.
+//
+// The four things that break in a two-actor fight, fixed once:
+// aimYaw stage-local aiming (world bearings into local rotations is a bug)
+// headAnchor effect anchors in bone space, so flames stay on the mouth
+// uprightQuat flat effects facing the lens without an arbitrary roll
+// hurtAt one severity model instead of four ad-hoc hit blocks
+// sendOut throw, arc, open, burst, exit, ball returns
+//
+// Import what you need. Nothing here touches the scene graph directly.
+
+import * as THREE from 'three';
+
+const TAU = Math.PI * 2;
+export const clamp = (v, lo = 0, hi = 1) => (v < lo ? lo : v > hi ? hi : v);
+export const smoothstep = (a, b, x) => {
+ const t = clamp((x - a) / (b - a));
+ return t * t * (3 - 2 * t);
+};
+export const outCubic = (t) => 1 - Math.pow(1 - clamp(t), 3);
+export const inOut = (t) => 0.5 - 0.5 * Math.cos(clamp(t) * Math.PI);
+export const shortAngle = (a) => Math.atan2(Math.sin(a), Math.cos(a));
+
+const UP = new THREE.Vector3(0, 1, 0);
+const _v = new THREE.Vector3();
+const _f = new THREE.Vector3();
+const _r = new THREE.Vector3();
+const _u = new THREE.Vector3();
+const _m = new THREE.Matrix4();
+
+/**
+ * Yaw for an actor that must look at a target, computed inside the stage frame.
+ *
+ * Both rigs look down their own +Z and sit under a stage root that may be
+ * rotated. Reading a world bearing and writing it to a local rotation aims the
+ * pair past each other, toward the lens. Pass the camera direction converted
+ * into stage-local space as camLocalX, plus a small cheat so they favour the
+ * camera by a few degrees.
+ *
+ * @param {{x:number,z:number}} from actor position, stage-local
+ * @param {{x:number,z:number}} to target position, stage-local
+ * @param {number} camLocalX stage-local camera bearing
+ * @param {number} [cheat=0] radians to lean toward camera
+ * @returns {number} rotation.y for the actor's pivot
+ */
+export function aimYaw(from, to, camLocalX, cheat = 0) {
+ const want = Math.atan2(to.x - from.x, to.z - from.z);
+ const d = shortAngle(camLocalX - want);
+ return want + Math.sign(d) * Math.min(Math.abs(d), cheat);
+}
+
+/**
+ * A point in a bone's local space, offset by the pivot's forward/up/side.
+ * Bake it once at build time; use the result every frame.
+ *
+ * @param {THREE.Object3D} bone
+ * @param {THREE.Object3D} pivot the actor root that defines forward
+ * @param {number} forward metres forward of the pivot
+ * @param {number} up metres above the pivot
+ * @param {number} [side=0] metres to the pivot's left
+ * @returns {THREE.Vector3} point in bone-local space
+ */
+export function headAnchor(bone, pivot, forward, up, side = 0) {
+ pivot.updateMatrixWorld(true);
+ bone.updateMatrixWorld(true);
+ pivot.getWorldDirection(_f).setY(0).normalize();
+ _r.crossVectors(UP, _f).normalize().negate(); // pivot's left
+ _v.copy(pivot.localToWorld(new THREE.Vector3(0, up, 0))).addScaledVector(_f, forward).addScaledVector(_r, side);
+ return bone.worldToLocal(_v);
+}
+
+/**
+ * Orient a flat effect (kanji blast, rune, splash card) to face the lens with a
+ * guaranteed upright roll. setFromUnitVectors picks an arbitrary roll and is the
+ * reason blasts arrive upside down.
+ *
+ * @param {THREE.Object3D} mesh
+ * @param {THREE.Vector3} viewDir unit vector from effect toward camera
+ */
+export function uprightQuat(mesh, viewDir) {
+ _r.crossVectors(UP, viewDir).normalize();
+ _u.crossVectors(viewDir, _r).normalize();
+ _m.makeBasis(_r, _u, viewDir);
+ mesh.quaternion.setFromRotationMatrix(_m);
+}
+
+/**
+ * Build a severity table for hits. Feed it every blow in the beat sheet, sorted
+ * by time, and it returns the pose weight for the current frame.
+ *
+ * @param {Array<{t0:number,dur:number,tip:number,air:number,settle:[number,number]}>} hits
+ * @returns {(t:number) => {h:object,a:number,k:number}|null}
+ */
+export function makeHurtModel(hits) {
+ return function hurtAt(t) {
+ let best = null;
+ for (const h of hits) {
+ const a = (t - h.t0) / h.dur;
+ if (a < 0 || a > 1) continue;
+ const rise = outCubic(clamp(a / 0.16));
+ const settle = smoothstep(h.settle[0], h.settle[1], a);
+ const k = rise * (1 - settle);
+ if (!best || k > best.k) best = { h, a, k };
+ }
+ return best && best.k > 0.002 ? best : null;
+ };
+}
+
+/**
+ * Mix a flinch pose into an existing pose and add the physical arc.
+ *
+ * @param {object} pose the actor's current pose object
+ * @param {object} flinch pose fragment for a hurt reaction
+ * @param {{h:object,a:number,k:number}} hurt from hurtAt()
+ * @param {(a:object,b:object,w:number)=>object} mixP the rig's pose mixer
+ * @param {{t:number, heavyRef?:number}} ctx
+ * @returns {object} pose
+ */
+export function applyHurt(pose, flinch, hurt, mixP, ctx) {
+ const { h, a, k } = hurt;
+ const heavy = k * clamp(h.tip / (ctx.heavyRef ?? 1.25), 0.45, 1);
+ const out = mixP(pose, flinch, heavy);
+ // a small vertical arc so the feet leave the ground on the big ones
+ out.rootY = (out.rootY ?? 0) + Math.sin(clamp(a / 0.55) * Math.PI) * h.air;
+ // and a shudder while he is still stunned
+ if (a > 0.30 && a < 0.85) out.rootTilt = (out.rootTilt ?? 0) + Math.sin(ctx.t * 24) * 0.035 * k;
+ return out;
+}
+
+/**
+ * Send-out geometry: the trainer throws the ball, it arcs to the mark, opens
+ * with a burst, and the ball comes back to the hand. Pure function of time.
+ *
+ * @param {number} t
+ * @param {{release:number,land:number,open:number,retStart:number,retEnd:number}} at
+ * @param {THREE.Vector3} hand release point (the trainer's wrist, world or stage-local)
+ * @param {THREE.Vector3} mark where the creature will stand
+ * @param {number} [arc=1.2] apex of the throw, metres above the straight line
+ * @returns {{visible:boolean,pos:THREE.Vector3,open:number,held:boolean,emerge:number,roll?:number}}
+ */
+export function sendOut(t, at, hand, mark, arc = 1.2) {
+ const out = { visible: false, pos: new THREE.Vector3(), open: 0, held: true, emerge: 0 };
+ const land = mark.clone().setY(mark.y + 0.10);
+ if (t < at.release - 0.02) return out;
+
+ out.visible = true;
+ out.held = false;
+
+ if (t < at.land) {
+ const u = clamp((t - at.release) / (at.land - at.release));
+ out.pos.copy(hand).lerp(land, outCubic(u));
+ out.pos.y += Math.sin(u * Math.PI) * arc * (0.55 + 0.45 * (1 - u));
+ out.roll = u * 14;
+ return out;
+ }
+
+ if (t < at.retStart) {
+ out.pos.copy(land);
+ out.pos.y += Math.sin((t - at.land) * 9) * 0.012;
+ // wide open to let it out, shut again before the return
+ out.open = smoothstep(at.open - 0.04, at.open + 0.06, t) * (1 - smoothstep(at.retStart - 0.16, at.retStart - 0.02, t));
+ out.emerge = smoothstep(at.open, at.open + 0.34, t);
+ return out;
+ }
+
+ const u = clamp((t - at.retStart) / (at.retEnd - at.retStart));
+ out.pos.copy(land).lerp(hand, inOut(u));
+ out.pos.y += Math.sin(u * Math.PI) * 0.55;
+ out.open = 1 - smoothstep(0, 0.25, u);
+ out.roll = u * 10;
+ if (u >= 1) out.held = true;
+ return out;
+}
diff --git a/templates/qa/README.md b/templates/qa/README.md
index d604c8d..6bbf3d8 100644
--- a/templates/qa/README.md
+++ b/templates/qa/README.md
@@ -1,6 +1,6 @@
# QA harness
-Seven scripts and no framework. The point is that every claim about the build is
+Eight 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.
@@ -27,7 +27,7 @@ npm i -D playwright-core
python3 -m http.server 4180 & # serve the project root
```
-## The seven checks
+## The eight checks
| Script | Answers | Fails when |
| --- | --- | --- |
@@ -35,6 +35,7 @@ python3 -m http.server 4180 & # serve the project root
| `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 |
+| `frames.mjs` | does *each* entity animate, stay in frame, and avoid snapping? | `FROZEN`, `TELEPORT`, `EMPTY`, `NOT-IN-WINDOW` or `OFFSCREEN` on any entity |
| `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` |
@@ -151,3 +152,32 @@ pixels, against 334 before the reset was added.
| `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 |
+
+## Per-entity frames
+
+`strip.mjs` samples the *scene*. `frames.mjs` samples one *entity* at a time, which
+is the only way to catch the third character in a shot whose neighbours are
+moving, or a prop that drifts while the camera follows an actor.
+
+```bash
+ENTITIES='({ hero: d.cast[0].model, guard: d.cast[1].model })' \
+FROM=4 TO=9 FPS=12 OUT=qa/frames STATIC=guard \
+ node templates/qa/frames.mjs
+```
+
+- `ENTITIES` is a JS expression evaluated in the page, returning `{name: Object3D}`.
+ The build should expose `window.__diorama.entities` so the default works.
+- `VIEW=portrait` (default) fits one camera to the entity's swept bounds, so the
+ whole move stays in frame and fills it. `VIEW=scene` keeps the locked camera and
+ crops to the entity instead.
+- `ISOLATE=scene` hides every mesh that is not on the entity's branch, so the
+ motion signature is about that actor alone. `siblings` hides only the other
+ registry entries.
+- `STATIC=name,name` exempts actors that are supposed to hold still from `FROZEN`
+ (they still get the teleport and offscreen checks).
+
+Each entity gets `qa/frames/<name>/f###.png`, a contact sheet, and a row in
+`report.json` with `empty`, `energy`, `maxStep` and a verdict. The script exits 1
+on any flag, so a build can gate on it. Read the sheets; the numbers only say
+which sheet to open first.
+
diff --git a/templates/qa/frames.mjs b/templates/qa/frames.mjs
new file mode 100644
index 0000000..2468535
--- /dev/null
+++ b/templates/qa/frames.mjs
@@ -0,0 +1,348 @@
+import { chromium } from 'playwright-core';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+
+/**
+ * Per-entity frame recorder.
+ *
+ * Records one dense frame series per entity across a window and prints a numeric
+ * verdict for each. This is the harness that catches what a single still never
+ * shows: an actor that never moves, one that teleports, a prop that drifts out of
+ * frame, an ear that pops, a foot that skates, a hand that phases through a body.
+ *
+ * BASE_URL default http://127.0.0.1:4180/index.html
+ * ENTITIES JS expression evaluated in the page, returning {name: Object3D}.
+ * Falls back to window.__diorama.entities, then window.__diorama.cast.
+ * FROM / TO window in seconds (default 0 .. 4)
+ * FPS frames per second to sample (default 12)
+ * OUT output dir (default qa/frames)
+ * VIEW "portrait" (default) fits a camera to the entity's swept bounds so
+ * it fills the frame for the whole move; "scene" keeps the locked
+ * camera and crops to the entity instead
+ * ISOLATE "scene" (default) hides every mesh that is not on the entity's
+ * branch; "siblings" hides only the other registered entities;
+ * "none" keeps the whole scene
+ * PAD padding in px for VIEW=scene (default 24)
+ * MIN_ENERGY mean luminance delta per frame under which an entity counts as
+ * frozen (default 0.35)
+ * MAX_STEP NDC jump between frames that counts as a teleport (default 0.22)
+ * STATIC comma separated names allowed to hold still (a guard, a seated
+ * figure); they still get teleport and offscreen checks
+ * COLS columns in the contact sheet (default 6)
+ *
+ * Output per entity: OUT/<name>/f###.png, OUT/<name>/sheet.png, and a line in
+ * OUT/report.json. Exit code 1 when any entity is flagged, so CI can gate on it.
+ * Read the sheets; the numbers only say where to look.
+ */
+
+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:4180/index.html';
+const ENTITIES = process.env.ENTITIES || '';
+const FROM = Number(process.env.FROM || 0);
+const TO = Number(process.env.TO || 4);
+const FPS = Number(process.env.FPS || 12);
+const OUT = process.env.OUT || 'qa/frames';
+const VIEW = process.env.VIEW || 'portrait';
+const ISOLATE = process.env.ISOLATE || 'scene';
+const PAD = Number(process.env.PAD || 24);
+const MIN_ENERGY = Number(process.env.MIN_ENERGY || 0.35);
+const MAX_STEP = Number(process.env.MAX_STEP || 0.22);
+const COLS = Number(process.env.COLS || 6);
+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`;
+
+const STATIC = new Set(
+ (process.env.STATIC || '')
+ .split(',')
+ .map((v) => v.trim())
+ .filter(Boolean)
+);
+const N = Math.max(2, Math.round((TO - FROM) * FPS));
+
+mkdirSync(OUT, { 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('console', (m) => {
+ if (m.type() !== 'error') return;
+ const url = m.location()?.url || '';
+ if (/favicon/i.test(url)) return; // a stub favicon 404 is not a scene error
+ errors.push(url ? `${m.text()} (${url})` : m.text());
+});
+page.on('pageerror', (e) => errors.push(String(e)));
+await page.goto(BASE_URL, { waitUntil: 'load' });
+await page.waitForFunction(() => window.__dioramaReady === true || window.__ready === true, null, {
+ timeout: 30000,
+});
+
+const names = await page.evaluate((expr) => {
+ const d = window.__diorama;
+ let reg = null;
+ if (expr) reg = new Function('d', `return (${expr});`)(d);
+ else if (d.entities) reg = d.entities;
+ else if (Array.isArray(d.cast)) {
+ reg = {};
+ for (const c of d.cast) reg[c.name || `cast${Object.keys(reg).length}`] = c.model || c.group || c;
+ }
+ if (!reg) throw new Error('no entity registry: set ENTITIES or expose window.__diorama.entities');
+ window.__entityRegistry = reg;
+ return Object.keys(reg).filter((k) => reg[k] && reg[k].isObject3D);
+}, ENTITIES);
+
+if (!names.length) {
+ console.error('frames failed: the registry has no Object3D entries');
+ process.exit(1);
+}
+
+// Isolation is installed once so the fit, the signature and the captures all
+// agree on what is on screen.
+await page.evaluate(
+ ({ isolateMode }) => {
+ const d = window.__diorama;
+ window.__iso = {
+ apply(name) {
+ const reg = window.__entityRegistry;
+ const target = reg[name];
+ const out = { others: [], meshes: [] };
+ if (isolateMode === 'siblings' || isolateMode === 'scene') {
+ for (const [k, o] of Object.entries(reg)) {
+ if (k === name) continue;
+ out.others.push([o, o.visible]);
+ o.visible = false;
+ }
+ }
+ if (isolateMode === 'scene') {
+ const keep = new Set();
+ target.traverseAncestors((o) => keep.add(o));
+ target.traverse((o) => keep.add(o));
+ d.scene.traverse((o) => {
+ if (o.isMesh && !keep.has(o)) {
+ out.meshes.push([o, o.visible]);
+ o.visible = false;
+ }
+ });
+ }
+ return out;
+ },
+ restore(saved) {
+ for (const [o, v] of saved.others) o.visible = v;
+ for (const [o, v] of saved.meshes) o.visible = v;
+ },
+ };
+ },
+ { isolateMode: ISOLATE }
+);
+
+const report = [];
+
+for (const name of names) {
+ const dir = `${OUT}/${name}`;
+ mkdirSync(dir, { recursive: true });
+
+ // Swept bounds over the window, then one camera fitted to them: the framing is
+ // stable while the entity moves, because a per-frame follow hides travel.
+ const fit = await page.evaluate(
+ ({ name, from, to, n, view }) => {
+ const d = window.__diorama;
+ const T = d.THREE;
+ const saved = window.__iso.apply(name);
+ const box = new T.Box3();
+ const tmp = new T.Box3();
+ for (let i = 0; i < n; i++) {
+ const t = from + ((to - from) * i) / Math.max(1, n - 1);
+ (d.freeze || d.draw)(t);
+ tmp.setFromObject(window.__entityRegistry[name]);
+ if (isFinite(tmp.min.x)) box.union(tmp);
+ }
+ const cam = d.camera;
+ const prev = { pos: cam.position.clone(), quat: cam.quaternion.clone(), zoom: cam.zoom, fov: cam.fov };
+ let rect = null;
+ if (view === 'portrait') {
+ const c = box.getCenter(new T.Vector3());
+ const size = box.getSize(new T.Vector3());
+ const dir = new T.Vector3(0.62, 0.52, 0.86).normalize();
+ cam.position.copy(c).addScaledVector(dir, 6);
+ cam.lookAt(c);
+ if (cam.isPerspectiveCamera) {
+ cam.fov = 32;
+ // Fit the subject, not its diagonal: height and width each get their
+ // own distance, take the larger, then 15% of paper. Fitting the
+ // diagonal is what leaves a character at a third of the frame.
+ const aspect = Math.max(0.2, window.innerWidth / window.innerHeight);
+ const tan = Math.tan((cam.fov * Math.PI) / 360);
+ const dv = (size.y * 0.5) / tan;
+ const dh = (size.x * 0.5) / (tan * aspect);
+ const dist = Math.max(0.6, Math.max(dv, dh) * 1.15);
+ cam.position.copy(c).addScaledVector(dir, dist);
+ cam.lookAt(c);
+ } else {
+ const span = Math.max(size.y, size.x / Math.max(0.2, window.innerWidth / window.innerHeight));
+ cam.zoom = (H * 0.5) / (Math.max(0.08, span * 0.58));
+ }
+ cam.updateProjectionMatrix();
+ cam.updateMatrixWorld(true);
+ } else {
+ cam.updateMatrixWorld(true);
+ const v = new T.Vector3();
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (let c = 0; c < 8; c++) {
+ v.set(c & 1 ? box.max.x : box.min.x, c & 2 ? box.max.y : box.min.y, c & 4 ? box.max.z : box.min.z);
+ v.project(cam);
+ const px = (v.x * 0.5 + 0.5) * innerWidth;
+ const py = (-v.y * 0.5 + 0.5) * innerHeight;
+ x0 = Math.min(x0, px); x1 = Math.max(x1, px);
+ y0 = Math.min(y0, py); y1 = Math.max(y1, py);
+ }
+ rect = { x0, y0, x1, y1 };
+ }
+ window.__iso.restore(saved);
+ return {
+ cam: { pos: prev.pos.toArray(), quat: prev.quat.toArray(), zoom: prev.zoom, fov: prev.fov },
+ size: box.getSize(new T.Vector3()).toArray().map((v) => +v.toFixed(2)),
+ center: box.getCenter(new T.Vector3()).toArray().map((v) => +v.toFixed(2)),
+ rect,
+ };
+ },
+ { name, from: FROM, to: TO, n: Math.min(N, 16), view: VIEW }
+ );
+
+ let clip = { x: 0, y: 0, width: W, height: H };
+ if (VIEW !== 'portrait' && fit.rect) {
+ const { x0, y0, x1, y1 } = fit.rect;
+ const cw = Math.max(48, Math.min(W, x1 - x0 + PAD * 2));
+ const ch = Math.max(48, Math.min(H, y1 - y0 + PAD * 2));
+ clip = {
+ x: Math.round(Math.max(0, Math.min(W - cw, x0 - PAD))),
+ y: Math.round(Math.max(0, Math.min(H - ch, y0 - PAD))),
+ width: Math.round(cw),
+ height: Math.round(ch),
+ };
+ }
+
+ const frames = [];
+ for (let i = 0; i < N; i++) {
+ const t = FROM + ((TO - FROM) * i) / Math.max(1, N - 1);
+ const sig = await page.evaluate(
+ ({ name, t }) => {
+ const d = window.__diorama;
+ const saved = window.__iso.apply(name);
+ (d.freeze || d.draw)(t);
+ const gl = d.renderer.getContext();
+ const w = gl.drawingBufferWidth, h = gl.drawingBufferHeight;
+ const buf = new Uint8Array(w * h * 4);
+ gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, buf);
+ // A 32x32 luminance signature is enough to feel motion, and cheap to send
+ // back. It is a detector, not a proof, so read the sheet too.
+ const G = 32, grid = new Array(G * G).fill(0), counts = new Array(G * G).fill(0);
+ for (let y = 0; y < h; y += 2) {
+ for (let x = 0; x < w; x += 2) {
+ const i2 = (y * w + x) * 4;
+ const l = 0.2126 * buf[i2] + 0.7152 * buf[i2 + 1] + 0.0722 * buf[i2 + 2];
+ const gx = Math.min(G - 1, Math.floor((x / w) * G));
+ const gy = Math.min(G - 1, Math.floor((y / h) * G));
+ grid[gy * G + gx] += l;
+ counts[gy * G + gx]++;
+ }
+ }
+ for (let k = 0; k < grid.length; k++) grid[k] = counts[k] ? grid[k] / counts[k] : 0;
+ let inkPx = 0, allPx = 0;
+ for (let y = 0; y < h; y += 4) {
+ for (let x = 0; x < w; x += 4) {
+ const i2 = (y * w + x) * 4;
+ const l = 0.2126 * buf[i2] + 0.7152 * buf[i2 + 1] + 0.0722 * buf[i2 + 2];
+ allPx++;
+ if (l < 232) inkPx++;
+ }
+ }
+ const box = new d.THREE.Box3().setFromObject(window.__entityRegistry[name]);
+ const c = box.getCenter(new d.THREE.Vector3()).project(d.camera);
+ window.__iso.restore(saved);
+ return { l: grid, ndc: [c.x, c.y], ink: +(inkPx / Math.max(1, allPx)).toFixed(4) };
+ },
+ { name, t }
+ );
+ const file = `${dir}/f${String(i).padStart(3, '0')}.png`;
+ await page.screenshot({ path: file, clip });
+ frames.push({ t, file, ...sig });
+ }
+
+ // Put the locked camera back before the next entity.
+ await page.evaluate((cam) => {
+ const d = window.__diorama;
+ d.camera.position.fromArray(cam.pos);
+ d.camera.quaternion.fromArray(cam.quat);
+ if (cam.fov) d.camera.fov = cam.fov;
+ if (cam.zoom) d.camera.zoom = cam.zoom;
+ d.camera.updateProjectionMatrix();
+ d.camera.updateMatrixWorld(true);
+ }, fit.cam);
+
+ let energy = 0, step = 0, offscreen = 0;
+ for (let i = 1; i < frames.length; i++) {
+ const prev = frames[i - 1], cur = frames[i];
+ // Only compare frames where the entity is actually on screen: a blank frame
+ // next to a full one would otherwise supply all the "motion" for the window.
+ if (prev.ink > 0.002 && cur.ink > 0.002) {
+ let sum = 0;
+ for (let k = 0; k < prev.l.length; k++) sum += Math.abs(prev.l[k] - cur.l[k]);
+ energy = Math.max(energy, sum / prev.l.length);
+ }
+ const dx = cur.ndc[0] - prev.ndc[0], dy = cur.ndc[1] - prev.ndc[1];
+ step = Math.max(step, Math.hypot(dx, dy));
+ }
+ const empty = frames.filter((f) => f.ink <= 0.002).length;
+ for (const f of frames) if (f.ink > 0.002 && (Math.abs(f.ndc[0]) > 1 || Math.abs(f.ndc[1]) > 1)) offscreen++;
+
+ const verdict = [];
+ if (empty === frames.length) verdict.push('NOT-IN-WINDOW');
+ else if (empty > frames.length / 2) verdict.push(`EMPTY ${empty}/${frames.length}`);
+ if (energy < MIN_ENERGY && !STATIC.has(name) && empty < frames.length) verdict.push('FROZEN');
+ if (step > MAX_STEP) verdict.push('TELEPORT');
+ if (offscreen) verdict.push(`OFFSCREEN ${offscreen}/${frames.length}`);
+
+ const sheet = `${dir}/sheet.png`;
+ const rows = Math.ceil(frames.length / COLS);
+ const tiled = spawnSync(
+ 'ffmpeg',
+ ['-y', '-v', 'error', '-i', `${dir}/f%03d.png`, '-vf', `tile=${COLS}x${rows}:padding=4:color=white`, '-frames:v', '1', sheet],
+ { encoding: 'utf8' }
+ );
+
+ report.push({
+ entity: name,
+ frames: frames.length,
+ size: fit.size,
+ center: fit.center,
+ clip,
+ energy: +energy.toFixed(3),
+ maxStep: +step.toFixed(3),
+ empty,
+ verdict: verdict.length ? verdict.join(' ') : 'ok',
+ sheet: tiled.status === 0 ? sheet : null,
+ });
+}
+
+await browser.close();
+
+writeFileSync(`${OUT}/report.json`, JSON.stringify({ base: BASE_URL, from: FROM, to: TO, fps: FPS, view: VIEW, report }, null, 1));
+
+const pad = (s, n) => String(s).padEnd(n);
+console.log(pad('entity', 16), pad('frames', 7), pad('empty', 6), pad('energy', 8), pad('step', 7), pad('bounds', 18), 'verdict');
+for (const r of report) {
+ console.log(pad(r.entity, 16), pad(r.frames, 7), pad(r.empty, 6), pad(r.energy, 8), pad(r.maxStep, 7), pad(r.size.join(' '), 18), r.verdict);
+}
+if (errors.length) {
+ console.log(`\nconsole errors (${errors.length}):`);
+ for (const e of errors.slice(0, 6)) console.log(' ', e);
+}
+const failed = report.filter((r) => r.verdict !== 'ok');
+console.log(`\n${report.length} entities, ${failed.length} flagged. Sheets in ${OUT}/<entity>/sheet.png`);
+if (failed.length || errors.length) process.exitCode = 1;
diff --git a/verify/creature-battle/README.md b/verify/creature-battle/README.md
new file mode 100644
index 0000000..f7f42d1
--- /dev/null
+++ b/verify/creature-battle/README.md
@@ -0,0 +1,46 @@
+# Creature battle harness
+
+A finished scene that exercises `templates/creature.js` end to end: two rigged
+creatures, a trainer throwing a ball, four attacks, a knockout and a recall. The
+source lives in the project it was commissioned for (`Desktop/pokemon`); this
+note records what the build proved, so the next battle commission starts from
+these numbers instead of rediscovering them.
+
+## What the verification found
+
+- **Aiming.** Forward-vs-opponent dot sat at 0.99 for the whole loop once the yaw
+ was computed in stage-local space. The earlier world-bearing version read 0.6
+ to 0.8 and looked like both creatures were facing the lens. It only drops to
+ 0.87 during the deliberate Iron Tail spin. Sweep it every half second; a 20°
+ miss is invisible at 300 px.
+- **Effect anchors.** Flames and bolts left the mouth correctly only after the
+ anchor was baked into head-bone space. A world-space muzzle slides off the jaw
+ as soon as the head turns, and a `+0.6 forward` guess is wrong for both rigs.
+- **Flat effects.** The kanji-shaped blast rendered upside down until the basis
+ came from `worldUp × viewDir`. `setFromUnitVectors` was the whole bug.
+- **Explosion vocabulary.** Cone petals, triangle fans and straight bars all read
+ as geometry. A hot core plus ten short sparks plus a ground ring reads as an
+ impact at any size. Layered silhouettes need per-mesh scale: sharing one
+ geometry between layers makes the layers invisible.
+- **Effect anchoring over time.** An eruption pinned to the actor's live position
+ crawls across the slab while he is knocked out of it. Latch the anchor at the
+ impact frame. That drift was reported as "it moves a bit, something feels off".
+- **Send-out.** Thrown ball, arc, landing, opening burst, full-size exit, ball
+ returns to the hand: all seven beats need their own time, and the held ball has
+ to be hidden while the thrown one is in the air or the throw reads as two balls.
+ A slow orb the creature materialises inside is the legendary-encounter variant
+ and reads as a bubble.
+- **Hits.** Four ad-hoc hit blocks were replaced by one severity table; the pose
+ weight and air arc scale with the blow, so a flamethrower staggers and a Fire
+ Blast folds the target in half. Rotate about the blow axis, pivot at mid-body.
+
+## Numbers that carried over
+
+| Quantity | Value |
+| --- | --- |
+| Loop | 46 s, 40 Hz |
+| Facing dot | 0.97+ except during a scripted spin |
+| Hit durations | 0.95 / 1.75 / 1.30 / 3.55 s |
+| Send-out | release 6.18, land 7.28, open 7.48, exit +0.34, return by 8.44 |
+| Internal render scale | 0.75 of CSS, buffer ceiling 2400 px |
+| Camera | `subjectScale 0.70` (30% smaller than the fitted slab) |