Skip to content
Back to search

diorama

SkillWorks with Claude CodeGitHub

"Full long-form guide for detailed rotatable Three.js dioramas. Narrative scenes are scene-first with no educational UI unless requested. Classic pixel, stroked-toon and pixel+stroke are rendering choices, not educational modes. Explanatory commissions use the separate educational contract. Includes composition, cast, animation, craft, sourcing and construction."

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/sloemo01/diorama with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/sloemo01/diorama'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/sloemo01--diorama/badge.svg)](/listings/sloemo01--diorama)

HTML

<a href="/listings/sloemo01--diorama"><img src="/api/listings/sloemo01--diorama/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

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 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.

Install the Diorama playbook here, then use it to build scenes.

Repo: https://github.com/sloemo01/diorama

1. Ask me where the folder should go before downloading anything,
   and wait for my answer. Propose ~/skills/diorama as the default.
   Do not pick a path silently.
2. Download the whole repository, not just SKILL.md:
     git clone https://github.com/sloemo01/diorama.git "<target>"
   Without git:
     curl -L -o diorama.tar.gz \
       https://github.com/sloemo01/diorama/archive/main.tar.gz
     tar xzf diorama.tar.gz && mv diorama-main "<target>"
3. Prove the install before describing it: SKILL.md, README.md,
   references/, templates/, verify/ and LICENSE at the root, and print the
   commit hash (git -C "<target>" rev-parse --short HEAD) or the
   archive date. If you have no shell or no network, say so and
   stop. If the download failed or a file is missing, say so and
   stop. Never describe this playbook from memory.
4. If you have a skills directory or plugin folder, install it
   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, references/INDEX.md, then
   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, 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.

Update it

One prompt, for a copy that is already installed. It saves your local patch, pulls the newest `main`, and reports what changed before any project is touched.

Update my Diorama install, then report what changed.

Repo: https://github.com/sloemo01/diorama

1. Ask me for the folder before touching anything, and wait.
   Propose ~/skills/diorama as the default.
2. Print the current commit, then make the update reversible:
     git -C "<target>" rev-parse --short HEAD
     git -C "<target>" diff > my-changes.patch
     cp -R "<target>" "<target>.bak"
   The copy works without git. Keep both until I say the update is good.
3. Pull the latest main:
     git -C "<target>" fetch origin
     git -C "<target>" reset --hard origin/main
   Without git: download main.tar.gz, unpack it, and copy the
   contents over the old folder.
4. Prove it before describing it: print the old and new commit, the
   version line from SKILL.md frontmatter, and confirm SKILL.md,
   README.md, references/, templates/, verify/ and LICENSE are
   present. If the pull failed, say so and stop.
5. Report the difference in this order: version jump, new or removed
   folders and templates, rules that changed, and whether my saved
   patch still applies. Re-apply it only when it does, and say so when
   it does not.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 2,975 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ---
  2. name: diorama
  3. description: "Full long-form guide for detailed rotatable Three.js dioramas. Narrative scenes are scene-first with no educational UI unless requested. Classic pixel, stroked-toon and pixel+stroke are rendering choices, not educational modes. Explanatory commissions use the separate educational contract. Includes composition, cast, animation, craft, sourcing and construction."
  4. version: 5.7.0
  5. author: Nehal Kanak (sloemo)
  6. license: MIT
  7. platforms: [linux, macos, windows]
  8. ---
  9. # Diorama
  10. ## Current intake contract (5.7.0 — authoritative)
  11. For a new commission, ask **look first, model sourcing second**, using the two gates below. These gates override older three-preset lists, automatic internet-first instructions and one-prompt assumptions elsewhere in this long guide and its references. Do not ask setup questions when merely editing the skill. Explicit answers in the brief skip the corresponding question; existing-project repairs retain recorded choices. An unanswered question is pending, not consent. Rendering and sourcing are independent of narrative/educational purpose.
  12. Three looks are available: `pixel` (Classic Pixel Art; recommended), `stroked-toon`, `pixel-stroke`. Generic “pixel art”, “classic”, “old pixel style” and explicit delegation (“you choose”) resolve to `pixel`. All looks preserve free orbit. An unanswered style gate waits.
  13. Three sourcing modes are available: `internet-full`, `hybrid` (recommended), `authored-only`. Generic “use internet models” resolves to `hybrid` unless the user requests downloaded models throughout. Older `internet-first` records map to `hybrid` on repairs. Sourcing requirements below apply only to modes that acquire external assets; authored-only skips model acquisition, not subject research, quality or geometry/contact checks.
  14. ## Profile boundary and retained additions (5.0 — read first)
  15. This is the **restored full-length guide**, not the compact 4.x replacement. Keep its detailed composition, subject recipes, scene furniture, cast, animation, service/queue, vehicle, effects, framing and craft guidance. The following profile/sourcing updates override older wording only where explicitly stated.
  16. ### Scene purpose is independent of rendering
  17. **Default `sceneProfile: narrative`.** A place, landscape, amusement park, town, fantasy scene or interactive scene is not an educational mechanism. Pixel, stroked-toon and pixel+stroke choose the renderer, NOT the profile. Asset choice, a working ride or click interactions do not make a scene educational. Choose `educational` when the user asks to explain/teach how something works, its anatomy or causal sequence. If intent is genuinely mixed, ask once; otherwise infer and record it without another forced setup question.
  18. **Narrative has no educational UI by default.** Do not import or instantiate `education-v8.css`, `education-dock.mjs`, an Explore/How it works panel, lesson steps, part picker, explanatory dashboard, floating callout labels or scattered teaching text for an ordinary diorama. This exclusion applies in ALL three render presets. Leave the scene/page visually clean. Free orbit and discreet functional pause/reset/accessibility controls remain permitted; diegetic park signs and shop names are scene geometry, not a teaching overlay. Optional title/readout furniture mentioned later is opt-in, not a toon/hybrid default. No debug panel in delivery.
  19. **Educational only:** canonical V8 right card/mobile dock, causal lessons, part inspection and connected explanatory callouts apply to explanatory commissions, not to all scenes. Explicit UI-free requests still override the panel default: explanation can be delivered through the requested scene behavior and accompanying prose. Narrative scenes with explicitly requested ride/part inspection get the requested scoped interaction, not an automatic lesson dashboard. Explicit requested informational labels are allowed, but do not add unrelated teaching surfaces. Record `uiMode: none | minimal-controls | requested-inspection | educational` and why; never satisfy a UI test by adding unwanted UI.
  20. Regression examples: “amusement park in pixel + stroked toon” → narrative + pixel-stroke + no education UI. “Interactive amusement park” → narrative; interaction alone adds no lessons. “Explain a roller coaster's operation” → educational, chosen style independently. “Amusement park with inspectable rides” → narrative + requested inspection only. A scene with no educational intent must not fail QA for lacking V8, lessons, labels or a card column.
  21. ### Default occupied-space pass: actions, seating and scenery
  22. Prevent intersections before adding detail or spawning copies, for people, animals, imported rigs, buildings, props and rides in BOTH profiles/all presets. Use `references/action-clearance.md`, `templates/action-clearance.mjs` and `templates/pose-bounds.mjs` with the actual production evaluator; this adds no educational UI.
  23. 1. **Reserve full space, not origins:** building/awning/door parcels, open access paths, actor swept widths and reach, tails/wings/horns, carried items and neighbouring actors. Reuse fitted rigs/clips from internet assets, but reject an asset/clip that cannot fit the required seat/action without distortion. Split accessible structures into actual wall/door/roof pieces; an enclosing hollow-building AABB is only a broad-phase candidate, not solid occupancy. Use deterministic lanes, queue slots, crossing priorities and seat reservations, not random nudges after overlap.
  24. 2. **Solve real contact/action frames:** approach → align → bend/lower → supported sit → stand/exit; pelvis, knees, feet and hands follow real seat/ground/handle frames. Don't sit by dropping a standing model through the chair. Ride occupants inherit the seat's moving frame once. Permit only exact named intended body↔support/joint contacts, with action window and bounded depth; never exempt an entire actor, chair, species or same-owner subtree. Check support gaps separately—an allowed collision contact does not prove the person isn't floating.
  25. 3. **Check the live pose across the whole action:** refresh skeleton/morph vertices and world frames, then use measured conservative body-region capsules/boxes plus structural pieces. Bind-pose bounds/root-point distances miss moving limbs; undersized colliders and omitted tails/carry props are failures. Broad-screen nearby pairs; refine loose bounds instead of deleting objects to lower candidate counts. Production audits supply independently specified `requiredIds`; missing actors/proxies or unverified coverage cannot pass. Test nonadjacent self-parts too, while explicitly declaring valid anatomical/structural joints. Proxy overlap is not automatically actual mesh penetration.
  26. 4. **Test critical times and fixes:** sample full cycles, loop seam, approach/contact/departure, largest reach, sitting/standing, crossings and door swing. Include exact events and refine using relative tip motion/clearance, not only endpoints or an attractive frame. `sampledOnly:true` is bounded sampled evidence, not continuous collision freedom. Move a real wrist/tail/knee into an obstacle, overlap building parcels and synchronize a crossing; the SAME production predicate must flag the fault and pass after repair. Review worst-contact side/back/top crops plus an action strip. Never hide bodies, shrink proxies, fade through walls or freeze the requested action to claim a pass. One source-driven QA runner, cached static obstacles, nearby-pair broad phase and worst-few reporting keep this practical.
  27. ### Default asset workflow: search, acquire and USE fitting models
  28. Ask the Model Sourcing Gate after the look is resolved, for BOTH profiles. Follow the recorded `internet-full`, `hybrid` or `authored-only` choice; do not silently impose internet-first. In the first two modes, reuse valid local assets but still search for missing major roles. The acquisition requirements in this section apply to those two modes; authored-only intentionally builds geometry and does not need a failed model search to justify it.
  29. **A search is not the deliverable.** Before detailed hand-modelling, find candidates for the hero and major supporting roles, review the actual per-asset terms and appearance, download the chosen permitted model/dependencies, inspect an actual import, and USE it in the scene when it fits. A fitting, licensed asset must not be ignored in favour of primitive-only reconstruction merely because hand-building is familiar. Nor does importing one token tree satisfy sourcing a park's otherwise hand-built rides/buildings/cast. Record decisions for the main roles in the existing SOURCES/CREDITS/design ledger.
  30. **Fit means diorama-quality, not merely downloadable:** correct subject/representation and silhouette, coherent kit/palette/proportions, adequate construction detail, usable parts/rig/clips for the requested motion or inspection, viable triangle/draw-call/texture budget, and compatibility with the chosen pixel/toon/hybrid rendering. Judge the real model from more than a thumbnail. Normalize scale/axes/origin, adapt colours/materials without losing important markings, preserve rigs/part identity, fit to the scene and review a rendered close-up. A realistic/PBR asset is not automatically disallowed if it can be adapted well; an unrelated low-poly substitute is not automatically suitable. Follow the original long-form craft, composition and motion standards after importing.
  31. **Rights remain mandatory:** prefer FREE assets whose explicit terms permit commercial use, modifications and redistribution/embedding in the delivered scene. Read original asset/license evidence; retain credits/license/change notices where required. NC, ND, editorial, personal/educational-only and missing rights do not pass. Custom/ShareAlike/other terms require compatibility review, not a fake CC0 label. No purchases, subscriptions or paid downloads without explicit user approval. Check separately licensed dependencies. Commercial permission is not scientific accuracy or trademark/other-rights clearance.
  32. **Source order:** use the user's Polyfork-first sweep for narrative kits/props, then the relevant original-author/model-library sources in this guide; if Polyfork misses, continue to appropriate alternatives rather than declare that the internet has none. Educational subjects use their bounded exact-subject search and extra accuracy/structure gate. Reuse a compatible kit for coherence. Do not crawl every provider indiscriminately or repeatedly search the same noun. Actual search/download/import evidence stays on disk; never fabricate searches, licenses or successful loads.
  33. **Hand-model only the justified gap:** necessary missing/custom geometry, unsuitable candidates after source/fit checks, or interfaces/animation adaptations not supplied by an imported model. Selection or movement alone is NOT a reason to reject an asset: use real part/pivot wrappers where feasible. Retain an all-authored approach when the user explicitly asks for it. If browsing/downloads are unavailable, disclose the limitation and fallback; never say the search found nothing when it never ran. A quality mismatch, unclear license or lack of useful motion is a documented reason to reject, not a reason to force a bad download.
  34. **Proof before completion:** for each major role record search/source, chosen asset or rejection/fallback reason, license evidence, actual downloaded file/path/hash and import/style/motion result. A compliant matching candidate found → acquired and used; no suitable candidate → honest specific fallback. Verify the chosen asset actually exists in the final scene, not just in assets/. Offline/standalone delivery packages every permitted dependency and is tested without network; a warm cache or CDN loader is not self-contained. Sourcing adds NO education panels, callouts or other UI to narrative scenes.
  35. ### Preserve the approved 4.x additions without shortening this guide
  36. - **Representation:** actual subject by default, not a classroom surrogate. Follow `references/representation.md`: Earth means a planet, not a globe on a stand. Ask real subject / physical teaching model / explanatory abstraction / you choose only if materially ambiguous; preserve explicit choices. Keep representation, render preset, purpose, scene/object context and Inside independent. Natural subjects do not acquire invented platforms, frames or machinery merely because this guide contains mechanical examples.
  37. - **Narrative sourcing:** preserve the user's Polyfork-first catalogue sweep, kits/matching, source decisions and scale/palette integration in `references/external-models.md`. This extends the older model-library section; do not fall back to primitive-only scenery without checking suitable assets.
  38. - **Educational sourcing:** the named teaching object/parts may be verified external geometry. Use the bounded candidate search and accuracy/import wrapper in `references/educational-models.md`, not a narrative full-catalogue crawl. Add authored semantic IDs, interfaces, pivots and explanation where needed.
  39. - **Rights:** all downloaded assets must permit commercial use, modification and redistribution in the delivered scene. Free download is not permission. Use `templates/educational-asset-gate.mjs` with reviewed evidence/credits and actual file hashes; CC0/CC-BY can pass, unknown/custom terms require review, NC/ND/editorial/incompatible terms do not pass. Verify dependencies and offline bundling; a remote CDN load is not an offline standalone artifact. This rights gate overrides older library summaries, including casually accepted restrictive licenses.
  40. - **Construction:** retain `templates/construction-kit.js` and `templates/interface-checks.js`; reserve working pockets, derive contact stacks from shared datums, check actual geometry and repeats. Keep the original detailed construction/selection chapters. Material/selection/annotation checks apply only to implemented/requested features; no forced annotation system to satisfy QA. AABB overlap is a candidate, not certified penetration. Use scoped real mutations, not bespoke injected-object detectors. Available helpers are supplemental, not proof of a whole scene.
  41. - **Maintenance:** do not mutate the installed skill after each scene automatically. An explicit maintenance request and filesystem approval are required. Preserve original/current backups. Historical changelogs document prior versions; they do not override this release.
  42. A diorama is a tiny staged scene with a resettable three-quarter hero camera and
  43. free user orbit. The default pixel preset uses a white cut-out, palette-snapped
  44. pixel grid and ink contour; the other presets follow their own presentation
  45. contracts. Narrative scenes retain the slab and toy-scale animated cast;
  46. educational scenes use the exception below.
  47. Classic Pixel Art is the recommended new-project look. **Stroked toon / illustrated miniature**
  48. (`stroked-toon`) and the **pixel + stroke hybrid** (`pixel-stroke`) are optional
  49. rendering presets for any subject, not a coffee-machine genre. **Ask which of the
  50. three to build in at the start of every project** — see `Render Preset Gate` —
  51. because the look changes presentation only, never the subject, story, research
  52. requirements, choreography or construction standard, and nobody should have it
  53. chosen silently on their behalf.
  54. **Profile precedence (read first):** For an educational explanation, read
  55. `Educational Mechanism Profile` before the narrative defaults. One mechanism and
  56. one causal sequence replace ALL mandatory cast/ritual/multiple-system/story-prop
  57. quotas throughout this guide. Clean off-white and the single V8 right card/mobile dock replace empty
  58. paper or decorative figure UI (explicit placement requests remain supported). Construction and mechanical correctness are never
  59. waived. For EVERY preset, free user orbit is mandatory; fixed/hero views below
  60. refer to deterministic QA/reset poses, not a locked interaction camera.
  61. **This file restores the full guide.** The supplemental references named in the 5.0 additions carry later approved sourcing/representation rules; copy-in modules and the detailed design sheet remain in `templates/`.
  62. **Execution index — do not read every genre recipe first.** Resolve the preset
  63. and profile, then use the fast-path table. Read `Research Before You Model` and
  64. `The Detail Bar` (including whole-object completeness) for every build. Narrative
  65. builds additionally use `One Prompt, One Build`, `The Animation Bar` and their
  66. chosen rendering recipe; educational builds go directly to the canonical UI/
  67. inspection and construction contracts. `The Look Contract` is pixel-only.
  68. | Before advancing | One source of truth / required evidence |
  69. | --- | --- |
  70. | First mesh | Filled `templates/DESIGN.md`: complete object, essential parts, source provenance and shared mating frames |
  71. | Repeated assembly | `Construction regression gates`: every instance, actual axes/bores and end-plane separation; not one good sample |
  72. | Requested selection | `Canonical educational UI and inspection contract`: reuse selection behavior only as requested; no narrative education card/lessons/labels. Verify visible emphasis, keyboard equivalent and exact restoration |
  73. | Claimed pass | `Verification`: nonempty actual geometry, expected counts, negative injections and fresh build hash tied to the report |
  74. This table indexes existing acceptance rules; detailed tests live only in the
  75. sections named here. Read other subject recipes only when the build uses them.
  76. ## Render Preset Gate (ask once, every project)
  77. Before the first mesh or presentation work, ask using the structured-choice tool when available. Keep labels and one-sentence consequences visible:
  78. > **Which look should I build this in?**
  79. >
  80. > 1. **Classic Pixel Art (Recommended)** — The original finer palette-snapped miniature look with ink contours and ordered dither.
  81. > 2. **Stroked Toon / Illustrated Miniature** — Smooth bevelled parts, stepped shading and fine charcoal outlines.
  82. > 3. **Pixel + Stroke** — Toon shading and outlines on a low-resolution pixel grid.
  83. Map answers respectively to `pixel`, `stroked-toon`, `pixel-stroke`. Generic “pixel art”, explicit classic and explicit delegation select `pixel`; silence waits. A reference image alone does not settle a materially ambiguous request. Do not repeat the question per material or repair. Record the answer verbatim in DESIGN, including the preset ID and renderer implementation. Every preset supports free orbit and deterministic hero reset; no second orbit question. After the look answer, ask the sourcing question next unless already answered. While either is pending, inspect local files and research the subject, but do not start detailed geometry, model downloads or a presentation implementation that commits the unanswered choice.
  84. ## Model Sourcing Gate (ask next, once per project)
  85. > **How should I create the models?**
  86. >
  87. > 1. **Hybrid — source + custom-build (Recommended)** — Search for commercially usable models, download and use the ones that fit, then model missing or scene-specific pieces myself.
  88. > 2. **Internet models throughout** — Search for and use commercially usable downloaded models for all major roles; focus my work on assembly, styling, rigging and animation.
  89. > 3. **Fully agent-modeled** — Build all scene geometry myself for a unified custom look, without downloading third-party models.
  90. This is a separate question after style, not a hidden assumption or a confused “pixel hybrid” choice. Use stable question ID `asset-strategy`, single-select, and map answers to `hybrid`, `internet-full`, `authored-only`. Record exact user wording. Explicit delegation selects hybrid; silence waits. Explicit requests for original/procedural geometry answer authored-only; an offline deliverable alone does NOT mean authored-only (permitted assets can be packaged locally).
  91. - **Hybrid:** actually search for every missing major role and use fitting licensed candidates; fill documented gaps with authored geometry. A token imported prop does not satisfy sourcing the hero/cast/buildings. Do not search and then hand-build suitable assets out of habit.
  92. - **Internet models throughout:** source the hero and all major supporting roles. Scale/material changes, pivots, adapters, collision proxies and simple joining/support geometry are allowed; quietly hand-building a missing hero is not. If no fitting licensed major asset exists, report the specific gap and offer a subject substitute or permission to switch that role to hybrid. Do not guarantee a full matching library before searching, and do not force an unsuitable model just to fill a quota.
  93. - **Fully agent-modeled:** author all visible model geometry, including hero and supporting roles. Subject/photo/motion references and coding/rendering libraries remain allowed; this choice does not mean “no internet research”. Do not download model packs, use an imported model as a hidden starting point, or downgrade the detail/animation/contact bar. User-provided models require an explicit exception if this mode is selected.
  94. - **Commercially usable, not merely commercially available:** in BOTH internet modes verify the actual per-asset license permits commercial use, modification and redistribution/embedding in the delivered scene. Prefer free CC0/compatible CC-BY; preserve required credits, modifications and license notices, check dependencies and package offline. Unknown rights, NC, ND, editorial/personal-only and incompatible licenses fail. Availability for sale is not a rights check. No purchases or subscriptions without separate explicit approval. Explain this briefly with the question; do not overwhelm it with legal boilerplate.
  95. - **Honest exceptions:** unavailable search/download access is not “nothing suitable found”. Disclose the limitation and ask before changing a selected sourcing mode. New choices do not waive subject accuracy or mandatory verification and add no educational UI.
  96. **Pre-build decision receipt:** after both answers, state one short line such as “Classic Pixel Art · hybrid sourcing · narrative · minimal controls”, then record the choices in DESIGN. Before delivery reconcile each major role against its chosen source mode and record native render dimensions, scaling and style crops. Missing answers, unsupported render-preset claims or unapproved sourcing switches cannot pass QA.
  97. ### Fast path by scene
  98. | If the commission is... | Read next, in this order |
  99. | --- | --- |
  100. | explicit explanation / guided how-it-works (not a machine or cutaway view alone) | Educational Mechanism Profile → Universal Inspection Controls → chosen render preset → Machine Grammar → Verification (profile-aware) |
  101. | market, food truck, bakery, cafe, shop, laundromat | Cast → Clothed Cast: Heads, Layers, Hands → Service And Queue → Machine Grammar → Carrying, Loading And Mounting → Verification |
  102. | heist, defence, combat | Detail Bar → Tool/Tower recipes → System And Combat Animation → Combat Readability → Verification |
  103. | 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 |
  104. | aquarium, pool, harbour | Cast → base rig → Water templates → Vehicles (boat) → Effects → Verification |
  105. | station, airport, hotel, transit | Service And Queue → Vehicles → Crowd Variation → Verification |
  106. | stage, festival, parade | Cast → Secondary Motion → Crowd Variation → System Grammar → Verification |
  107. | farm, garden, nature | Creature Anatomy → Ambient Loops → Effects → Verification |
  108. The narrative shape is place + repeated ritual + interruption + consequence.
  109. Educational scenes instead use mechanism + causal sequence + observable result;
  110. do not add a fictional interruption or cast. The fast path selects the relevant
  111. reference notes, not extra narrative requirements.
  112. ## When to Use
  113. - Educational "how does this work?" mechanisms, cutaways and step-through
  114. causal explanations; use the Educational Mechanism Profile, not cast quotas.
  115. - "Make a small diorama / miniature scene / pixel scene of X"
  116. - A clip or still shows a flat cut-out scene with chunky pixels and little
  117. people, and the ask is to match that look
  118. - An existing 3D scene needs the pixel-art presentation (palette, dither, ink,
  119. reset hero angle plus orbit) rather than a smooth render
  120. - The figures need believable motion: walking, climbing into a car, sitting,
  121. swimming, diving, and it has to survive close inspection
  122. - The ask is for a *staged diorama*, not a model: several systems, a cast, a goal or boss,
  123. and a loop that can be frozen at any second
  124. - The user gives only one line ("a bakery at closing", "a lighthouse under
  125. siege"); this skill is designed to turn that into a complete commission
  126. without an interview
  127. Don't use for photoreal scenes or full-resolution photographic product renders.
  128. Every scene MUST support free user orbit by default, including pixel, stroked-toon and pixel-stroke. No separate orbit consent exists. Keep a deterministic hero angle for QA/reset, never auto-spin.
  129. ## Research Before You Model
  130. Four lookups come before the first mesh: the subject by frames, the asset
  131. libraries, the motion itself, and the capture loop. Skipping them is how a build
  132. ends up with a plausible silhouette that matches nothing and animation that reads
  133. as generic. Budget for them, they are usually faster than the modelling they save.
  134. | Question the research answers | Where it lands |
  135. | --- | --- |
  136. | what does it look like, exactly | `refs/<subject>/*.png` contact sheets |
  137. | what does it do, in what order, how fast | `refs/SOURCES.md` + the beat table |
  138. | does a rig or clip already exist | `CREDITS.md` + `assets/` |
  139. | is it actually right on screen | `qa/` captures, compared to the sheets |
  140. ### 1. The subject, by frames
  141. Find the real thing moving, not stills. For games, anime, sport or machinery the
  142. footage *is* the specification: it settles what the shape is, where the motion
  143. starts, how long each stage lasts and what colour it is at each step.
  144. ```bash
  145. yt-dlp --flat-playlist --print "%(id)s | %(title)s | %(duration)s" "ytsearch6:<subject> animation"
  146. yt-dlp --extractor-args "youtube:player_client=ios,android" -f 18 -o "refs/clip.%(ext)s" <id>
  147. ffmpeg -i refs/clip.mp4 -vf "fps=8,scale=300:-1,tile=6x4" refs/sheet-%02d.png
  148. ```
  149. Read the contact sheets with vision, then write the grammar down in words before
  150. touching geometry: *ball leaves the hand on an arc, opens with a white burst, the
  151. creature springs out at full size, the ball snaps shut and returns*. A paragraph
  152. like that is the acceptance test for the effect you are about to build.
  153. Rules that come out of doing this repeatedly:
  154. - Prefer **game footage** over fan animation for game subjects; the game is the
  155. canonical grammar, and fan cuts are already an interpretation.
  156. - Prefer **one clean clip sampled densely** over ten clips sampled sparsely.
  157. Twelve frames a second on a 4 second send-out shows the whole sequence.
  158. - Keep the sheets in `refs/<subject>/` next to the build so the next person can
  159. see what you were matching, and so QA has an image to compare against.
  160. ### 2. Model sourcing: check the libraries before you build
  161. Internet-first sourcing applies to ALL major scene roles, not only creatures. Acquire and use fitting commercially licensed models by default; hand-build only a documented gap or explicit original-geometry request. Hand-building a creature from primitives is the *last* option, not the first. A
  162. rigged download with real deformation and usable clips beats four hundred lines
  163. of spheres the moment the camera comes within a metre. Search first, and keep a
  164. record of what you searched.
  165. **The ladder. Every hero asset walks down it in order.**
  166. 1. **Already on disk.** The user's folder often ships a `tools/`, `assets/` or
  167. `model/` directory with GLBs in it. List it before anything else.
  168. 2. **A CC0 pack covers it.** Import it. No attribution, no negotiation.
  169. 3. **A CC-BY model covers it** and the page can carry a credit line. Import it,
  170. credit it, done.
  171. 4. **Nothing fits the silhouette** and the shape has to be exact. Hand-build it
  172. against the reference frames, and say in the log that you searched.
  173. 5. **Never:** ripped game assets, Models Resource / Spriters Resource downloads
  174. used as geometry, "editorial use only", NC, ND, or anything with no stated
  175. licence. Those are hard stops; ask the user instead of guessing.
  176. **Creatures, characters and rigs**
  177. | Source | Licence | What is actually there | How to search |
  178. | --- | --- | --- | --- |
  179. | [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 |
  180. | [KayKit / Kay Lousberg](https://kaylousberg.itch.io) | CC0 | adventurers, skeletons, dungeon and RPG packs, rigged and animated | itch page, per-pack zip |
  181. | [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 |
  182. | [Kenney](https://kenney.nl/assets) | CC0 | kits for props, vehicles, characters, UI, audio | category browse |
  183. | [Sketchfab](https://sketchfab.com/3d-models) | per model | the long tail: specific machines, animals, buildings | filter **Downloadable** + **CC0**/**CC-BY** before looking at anything |
  184. | [Smithsonian 3D](https://3d.si.edu) | CC0 | scanned real objects, fossils, artefacts, vehicles | search, check the licence note under the download |
  185. | [NASA 3D Resources](https://nasa3d.arc.nasa.gov) | public domain | spacecraft, rovers, terrain, helmets | browse by category |
  186. | [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 |
  187. | [Objaverse](https://objaverse.allenai.org) | mixed, per object | 800k research objects, good for odd props | verify the per-object licence, most are not clean |
  188. | [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` |
  189. **Animation clips** (motion is usually harder to hand-key than shape is to model)
  190. | Source | Licence | Notes |
  191. | --- | --- | --- |
  192. | Quaternius Universal Animation Library | CC0 | 120+ humanoid clips, retargetable, best first stop |
  193. | [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 |
  194. | [Rokoko Motion Library](https://rokoko.com/products/motion-library) | 150 free clips, paid beyond | mocap quality, good for weight and follow-through |
  195. | CMU Graphics Lab Motion Capture | free for research and commercial use with credit | raw BVH, huge, needs cleanup |
  196. | Sketchfab animated models | per model | often ships with an idle/walk/attack set |
  197. | [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 |
  198. **Props, environments, textures, light**
  199. | Source | Licence | Notes |
  200. | --- | --- | --- |
  201. | [Poly Haven](https://polyhaven.com) | CC0 | HDRIs, textures, models; the HDRI set is the fastest way to fix flat lighting |
  202. | [ambientCG](https://ambientcg.com) | CC0 | tiling PBR materials, HDRIs, some models |
  203. | [OpenGameArt](https://opengameart.org) | mixed | filter to CC0 / CC-BY; 3D section is thin but has good odd props |
  204. | [madjin/awesome-cc0](https://github.com/madjin/awesome-cc0) | index | a maintained list of CC0 sources when the usual four fail |
  205. **Searching them without a browser.** Three of the libraries have open APIs, so a
  206. build can check them in a single command and read the licence back:
  207. ```bash
  208. # Sketchfab: downloadable + CC0 only, name and page printed for each hit
  209. curl -s "https://api.sketchfab.com/v3/search?type=models&downloadable=true&license=cc0&q=dragon&count=24" \
  210. | python3 -c "import json,sys;[print(r['name'],'|','https://sketchfab.com/models/'+r['uid']) for r in json.load(sys.stdin)['results']]"
  211. # Poly Haven: models, HDRIs, textures (filter by category)
  212. curl -s "https://api.polyhaven.com/assets?t=models"
  213. curl -s "https://api.polyhaven.com/assets?t=hdris&c=studio"
  214. # ambientCG: materials and HDRIs by keyword
  215. curl -s "https://ambientcg.com/api/v2/full_json?type=Material&limit=20&q=concrete" \
  216. | python3 -c "import json,sys;print([a['assetId'] for a in json.load(sys.stdin)['foundAssets']])"
  217. ```
  218. Poly Pizza, Quaternius, KayKit and Kenney are browsed by search on their own
  219. pages; query them with the noun plus the style (`low poly dragon`, `kaykit
  220. skeleton`), not with a sentence.
  221. **Reference only, never geometry:** The Spriters Resource, The Models Resource,
  222. sakugabooru, game rip archives, Pinterest. Use them to learn the shape and the
  223. timing, then build or buy the actual asset.
  224. ### 3. Animation research: how the thing moves
  225. Shape is half the job; the other half is the motion, and it is researched the same
  226. way. Search the *verb*, not the noun.
  227. ```bash
  228. # the motion itself, canonical first
  229. web_search: "<subject> <move> animation" # a game doing it
  230. web_search: "<subject> <move> slow motion" # real footage, for weight
  231. web_search: "<subject> sprite sheet" # frame-by-frame timing
  232. yt-dlp "ytsearch6:<subject> <move> animation"
  233. ffmpeg -i clip.mp4 -vf "fps=12,scale=320:-1,tile=6x4" refs/move-%02d.png
  234. ```
  235. Read the sheet, then **count frames and convert**: `seconds = frames / fps`, and
  236. scale to the loop length you are building. That is how a 0.42 s anticipation and a
  237. 0.18 s contact become the beat table instead of a guess.
  238. Write four lines per action before animating it:
  239. ```
  240. wind-up 0.00 -> 0.42 weight back, head down, tail still
  241. contact 0.42 -> 0.55 fastest frames, one pose held for two frames
  242. follow 0.55 -> 0.90 overshoot, then settle
  243. recover 0.90 -> 1.30 back to idle
  244. ```
  245. Every attack in the beat sheet needs all four. Missing anticipation is why an
  246. effect reads as "it just happens", and missing follow-through is why it reads as
  247. "it snaps back".
  248. For rigs, cross-check the reference against a real clip: if the library has a
  249. punch, a swipe or a jump that is close, retarget it and offset the acting, rather
  250. than keying a pose from scratch.
  251. ### 4. The research log
  252. Every build writes `refs/SOURCES.md`. It is the proof the searches happened and
  253. the reason the next person does not repeat them.
  254. ```md
  255. | Question | Searched | Found | Decision |
  256. | --- | --- | --- | --- |
  257. | what does the send-out look like | yt: "sword shield send out slow motion" | RoUJ_TWvB3g, orb + white burst | matched, timings below |
  258. | hero creature rig | poly.pizza "dragon", quaternius characters | nothing matching the silhouette | hand-built from refs/sendout |
  259. | hit reaction weight | yt: "pokemon take damage animation" | 0.9 s flinch, 1.7 s stagger | HURTS table |
  260. ```
  261. A build with no `SOURCES.md` has not finished its research step, even if the
  262. scene looks right.
  263. ### 5. Prove it with shots
  264. Every beat gets frozen, captured and compared against the reference sheet before
  265. the next beat is built. The contact sheet of those captures is the review
  266. artifact, not a paragraph describing them.
  267. - Freeze the loop at the beats the reference showed: `?t=<second>` in the page,
  268. `freeze(t)` through the debug hook, screenshot the frame element.
  269. - Put the captures in a grid next to the reference frames and read them with
  270. vision. Anything that needs a caption to explain is not finished.
  271. - Keep numerical checks alongside the pictures: facing dot products, NaN scans
  272. over every geometry, console errors, effect bounding boxes. They catch the
  273. failures the eye forgives at 300 px.
  274. ## One Prompt, One Build
  275. When the user gives a subject in one line, treat it as a **commission**, not a
  276. questionnaire. Make the creative decisions, state them in one short assumption
  277. line, and build the whole diorama. Do not stop at a plan, a blockout or a design
  278. sheet and wait for approval.
  279. The only reasons to ask are credentials, a destructive action, a path that
  280. would overwrite the user's work, **or the `Render Preset Gate`**. That gate is a
  281. deliberate exception to autonomous assumptions: one question, once per project,
  282. before the first mesh. Everything else is a default.
  283. ### Step 0, before the assumption line
  284. Ask the `Render Preset Gate` question first, then run the three lookups in
  285. `Research Before You Model`:
  286. 1. Step the real subject into frames and write down its motion grammar.
  287. 2. Walk the sourcing ladder for every hero asset (disk, CC0, CC-BY, hand-build),
  288. with a `CREDITS.md` line per import and the search in `refs/SOURCES.md`.
  289. 3. Stand up the capture loop (`qa/shoot.mjs`, a frozen `?t=` frame, a contact
  290. sheet) so every beat can be reviewed as a picture.
  291. For an invented subject, spend the same time on reference density instead: find
  292. three images that agree on what the place looks like, list the props they share,
  293. and build those before any invented detail.
  294. ### The default commission
  295. Use these unless the prompt explicitly says otherwise:
  296. | Knob | Default |
  297. | --- | --- |
  298. | Slab | 21 x 14 x 0.42 m; 16 x 12 for one room, 24 x 16 for a street, port or launch pad |
  299. | Loop | 46 s at 40 Hz; one readable cycle plus a quiet seam |
  300. | Palette | 64 entries |
  301. | Systems | 4 defences/machines/service stations/attractions; 3 is acceptable, 6 is the ceiling |
  302. | Cast | 4 to 6 roles total, including one disruption; 2 ambient loops |
  303. | Props / landmarks | 2 hero props, 1 landmark, 3 to 6 supporting props |
  304. | Hero detail | every hero object meets the Detail Bar |
  305. | Animation | every hero actor has all five layers |
  306. | Output | `index.html`, `<slug>.html`, `README.md`, `DESIGN.md`, `src/`, `dist/` |
  307. | Path | `<cwd>/<slug>/` unless the user named a folder |
  308. | Minimum viable | 3 systems, 3 roles + 1 disruption, 1 hero prop + 1 landmark, 30 s loop; still passes the bars |
  309. State the assumption in one line before coding:
  310. > Assumption: market archetype, 46 s loop, 4 service systems, 6 roles plus a
  311. > late customer, 21 x 14 slab, 64 colours. Say if you want a different scale or
  312. > genre.
  313. That line is the contract. State it, then continue in the same turn; do not wait
  314. for approval. It gives the user a chance to redirect after seeing the assumption,
  315. without blocking the build.
  316. ### Long builds and context
  317. A scene like this runs for hours of agent time and thousands of messages: render
  318. loops, one screenshot per beat, one probe per bug. The session will need to
  319. compress its context, more than once, and compaction is lossy. Build so that a
  320. compact does not cost you the work:
  321. - **State lives in files, not in the chat.** `DESIGN.md`, `refs/SOURCES.md`,
  322. `CREDITS.md`, `qa/report.json` and the beat table in `stage.js` must carry every
  323. decision. If a fact only exists in a message, it is already gone.
  324. - **Write the rule down when you learn it.** A fix found at 3 a.m. is worthless if
  325. it only exists in the transcript; put it in the skill or a comment next to the
  326. code, with the reason.
  327. - **Name the shots.** `qa/frames/<entity>/sheet.png` and `shots/t-12.40.png` are
  328. stable handles a post-compact agent can re-read without rerunning anything.
  329. - **Re-derive, do not remember.** After a compact, re-run `frames.mjs` and
  330. `shoot.mjs` rather than trusting your summary of what the last frame looked
  331. like: the numbers are cheap, and a confident memory of an old build is the
  332. most expensive thing in the session.
  333. - **Keep one open task list** in the repo (a `TODO.md` or an issue) so the thread
  334. that survives compaction is the plan, not the chat.
  335. ### Reading the prompt
  336. | Prompt shape | What to do |
  337. | --- | --- |
  338. | one noun ("a bakery") | pick the closest router row; invent the verb, disruption and goal |
  339. | one sentence ("a lighthouse under siege") | take its nouns and verbs literally; fill the missing cast/systems from the router |
  340. | a reference image | match its composition, camera side and palette first; keep this skill's detail/animation bars |
  341. | "like X but Y" | reuse X's structure, replace the subject and the detail anchors; do not copy X's nouns |
  342. | "make it detailed" | use the full Detail Bar and five animation layers; do not add more systems |
  343. | "keep it simple" | cut systems and cast, not detail per hero; two rich objects beat six blockouts |
  344. A prompt that names only a place is still a commission. Decide what the place
  345. does, who arrives, and what goes wrong. State the assumption and build.
  346. ### The scene router
  347. Pick the closest row. Do not invent a new genre from scratch unless none fit.
  348. | If the prompt is... | Systems (3–5) | Cast | Goal / disruption | Detail anchor |
  349. | --- | --- | --- | --- | --- |
  350. | defence, siege, castle, base, zombies | 4 towers + gate guns | defenders, 4 species, boss | boss reaches the gate | gatehouse |
  351. | heist, bank, museum, casino | drill, lasers, cameras, getaway | 3 crew, guards, manager | vault opens / escape | vault door |
  352. | 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 |
  353. | 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 |
  354. | launch, factory, port, mine | gantry, press, crane, conveyor | crew, inspector, cargo | launch / ship / lift | gantry |
  355. | aquarium, pool, harbour, reef | filters, pumps, slides, lights | fish, swimmers, diver, lifeguard | feeding / party / storm | reef or tank |
  356. | station, airport, bus, hotel | signal, platform, desk, luggage | commuters, guard, porter | last departure | clock |
  357. | festival, temple, carnival, funeral | stage, rides, altar, procession | performers, crowd, official | climax / storm | big top or altar |
  358. | farm, garden, safari, nature | irrigation, harvester, weather vane | animals, farmer, crows | harvest / storm | barn |
  359. | home, shop, library, workshop | rooms, counter, shelves, tools | family, clerk, customer, pet | opening / closing | window |
  360. | arena, battle, mech, gladiator | traps, weapons, doors, lifts | fighters, champion, beast | champion enters | gate |
  361. If none fit, use the universal shape: **place + repeated ritual + interruption
  362. + consequence**. Give it 3 to 5 systems, 4 roles and one goal. A quiet subject
  363. still needs a verb: a library needs a closing, a bakery needs a service, a
  364. lighthouse needs a sweep that fails.
  365. ### If the router misses
  366. Do not freeze. Answer four questions about the noun:
  367. 1. **What does this place produce or repeat?** Bread, light, trains, fish, money,
  368. quiet, laundry, coffees.
  369. 2. **Who operates it?** Baker, keeper, guard, diver, clerk, mechanic.
  370. 3. **What interrupts the output?** A critic, a storm, a thief, a shutdown, a
  371. delivery, a leak, a closing-time crowd.
  372. 4. **What is the visible consequence?** Burnt batch, dark lens, missed train,
  373. flooded tank, empty till, closed sign.
  374. Those four answers give you the system, cast, goal and residue. Then use the
  375. five beats: **normal output → first interruption → escalation → goal contact →
  376. residue and seam**. No combat required. A deadline, an inspection, a storm or a
  377. closing bell is a valid boss.
  378. Worked one-prompt example:
  379. > "a tiny bakery at closing time"
  380. - Archetype: market/kitchen. Slab 16 x 12. Loop 42 s.
  381. - Systems: oven, proofing rack, counter, till. Cast: baker, apprentice, last
  382. customer, food inspector (the disruption).
  383. - Goal: the inspector reaches the counter before the last loaf is sold.
  384. - Beats: 0 s oven glow and bread out; 8 s first customer; 16 s inspector at the
  385. door; 26 s last loaf contested; 34 s sign turns, flour settles, cat sleeps.
  386. - Detail anchors: oven door (hinges, soot, peel), bread rack (trays, crumbs,
  387. cloth), counter (ledger, bell, worn edge), inspector's clipboard.
  388. - No towers: use machine grammar for the oven and till; field audit for the
  389. oven's heat; death/exit for the inspector's departure.
  390. ### The autonomous pass
  391. 1. **Interpret.** Pick the archetype; write the assumption line; fill
  392. `DESIGN.md` yourself. Do not ask the user to fill it.
  393. 2. **Blockout.** Grey slab, camera, five beats at 1:1. No palette, no post, no
  394. materials. If the beats do not read, restage before adding detail.
  395. 3. **Presentation.** Palette, light, post, ink, dither, camera solve.
  396. 4. **Set and props.** Landmark, two hero props, supporting dressing. Clear the
  397. 2 m threshold. No duplicate silhouettes.
  398. 5. **Cast and detail.** Rig the cast; apply the Detail Bar to every hero object.
  399. Cut a role before cutting detail per role.
  400. 6. **Animation and systems.** Five layers per hero; tower acquire/fire/impact/
  401. recovery; field ramp/area/affect/decay; machine input/motion/output/residue.
  402. 7. **Effects and residue.** Contact shadows, species deaths, dropped gear,
  403. stains, ambient loops, loop seam.
  404. 8. **QA and package.** Detail/animation audit, numbers, 1:1 crops, standalone
  405. `file://`, README and `DESIGN.md` agreeing.
  406. If time is tight, **cut the number of systems or actors, never the detail per
  407. hero or the animation layers**. Two detailed towers with five layers beat six
  408. blockout towers with one fire animation.
  409. ### Efficiency rules
  410. - **One project, one build loop.** Scaffold once, then build, shoot and fix in
  411. place. Do not rewrite the entry file for a detail that lives in a prop module.
  412. - **Build for orbit inspection.** Prioritise the hero view, but construct every exposed back, support, cavity and joint coherently.
  413. - **Cut systems before detail.** A tight build with two rich towers and five
  414. animation layers reads better than six thin towers with one recoil.
  415. - **Use the templates.** Camera, post, palette, lighting, the cast rig and the
  416. detail helpers are already solved; do not re-derive them from prose.
  417. - **Shoot known timestamps.** Freeze at the five beat times and the five QA
  418. frames; do not scrub for a good frame.
  419. - **Package last, once.** Build the standalone only after the QA frames pass;
  420. rebuilding it after every tweak wastes the pass.
  421. ### One-prompt acceptance
  422. Do not report "done" until all of these are true:
  423. - `DESIGN.md` exists and matches the build.
  424. - Five beats have timestamps and proof frames.
  425. - Every system has events; every actor has a death, exit or residue.
  426. - Each hero has three detail passes and at least one story detail.
  427. - Each hero actor has idle, locomotion, action, reaction and death/exit.
  428. - Every carry, handoff, load and mount has a contact timestamp and a nine-frame
  429. strip; palms are on the prop and boots are on the vehicle.
  430. - A queue serves after arrival, never before; no standing gesture is blended
  431. into a walking root.
  432. - No generic sphere burst, floating prop, clipped landmark or beam on a target
  433. that has already expired.
  434. - No fixed deck prop, ammo store, tool or crew member moves with a turret,
  435. flywheel or machine pivot.
  436. - Standalone opens over `file://` with zero console errors.
  437. - The final message gives the path, loop length, system/shot counts and the QA
  438. frames, not a request for feedback.
  439. ## Starting A New Diorama
  440. When the subject is new, the first deliverable is a design sheet, not a scene.
  441. With a one-line prompt, fill it from the defaults in `One Prompt, One Build` and
  442. do not ask the user to complete it.
  443. 1. Copy `templates/DESIGN.md` into the project as `DESIGN.md`.
  444. 2. Write the premise as a verb, not a noun. Name the place, the repeated action,
  445. who interrupts it, and the payoff.
  446. 3. Fill the cast and system sheets. If a role has no action, cut it. If a system
  447. has no visible consequence, cut it.
  448. 4. Pick five beats and five QA timestamps. A beat without a timestamp is not
  449. staged.
  450. 5. Block out in grey at the reset hero camera and shoot the five beats at 1:1.
  451. This is a staging check, not a production pass: no palette, no post, no
  452. materials. Redesign staging before committing to it.
  453. 6. Once the blockout reads, run the production pipeline below. Palette is the
  454. first production pass; the grey blockout does not count as one. Detail
  455. multiplies a readable blockout; it cannot rescue an unreadable one.
  456. The rest of this file is the recipe for each pass.
  457. ## Educational Mechanism Profile (first-class exception)
  458. **UI and inspection authority:** `Canonical educational UI and inspection contract`
  459. below owns placement, controls, lessons, selection, focus and restoration. Follow
  460. it rather than inferring defaults from older screenshots. The render preset gate
  461. and free orbit apply unchanged.
  462. Choose `sceneProfile: educational` for explicit explanations, guided technical cutaways and how-it-works teaching requests—not a machine subject, rotation or a cutaway view alone. This profile takes precedence over ALL narrative quotas below: no mandatory cast, disruption, ritual, landmark, three systems, ambient loops, five actor layers or decorative story props. One accurately constructed mechanism and one clear causal sequence is sufficient. Do not invent a crowd or combat to satisfy the router. Research and construction accuracy remain mandatory; simple UI never means missing mechanical parts.
  463. - **UI, selection and lessons:** when enabled/requested, use the canonical contract below; explicit UI-free briefs omit panels/lesson controls. No second toolbar, competing material cache or explanatory clock.
  464. - **Component manifest is a hard delivery artifact:** record each essential part's ID, assembly/parent, function, supporting joint/bearing/fastener, input/output connection, motion law, units, source and tolerance, mesh/group mapping, selectable anchor and proof frame. Include otherwise obscured shafts, cams, rods, links, valve gear, ports, supports and housings when functionally relevant. Explicitly state omissions and symbolic simplifications before acceptance; never substitute a label for missing construction.
  465. - **Mechanics are coupled, not independently looped:** derive all driven transforms from a shared phase/driver. Write and test actual ratios, directions, phase offsets, link lengths, kinematic equations, contact/clearance and event timing. For an engine, for example, verify crank:cam 2:1 over a 720° four-stroke cycle, connecting-rod length and piston stroke, valve lift/seat contact and opening order; do not copy these ratios into unrelated mechanisms. Check contacts across motion, not only at the hero frame.
  466. - **Nothing passes through another solid:** this is a hard acceptance rule for EVERY profile and preset, including educational scenes. Test non-contact pairs over the complete motion range and at contact transitions, not just one still. Declare intended joints/contact surfaces and numeric tolerances; all other swept bodies must keep positive clearance. Include complete geometry (tips, tails, bevels, fasteners and attachment arms), not only centres/anchors. In an engine, test actual piston-crown/valve-head/spark-plug bounds and actual cam/follower surfaces at dense phase samples. Do not move independent parts with unrelated sine waves, hide a collision with a cutaway, turn off depth testing, or use transparency/labels to pretend it is fixed. First solve the constraint or alter the geometry. Every shaft, piston, rod or sliding member that crosses a fixed wall/flange needs a REAL bored hole, slot or cutaway opening with measured swept clearance; a solid shelf with a dark circle painted on it is a failure. Test the moving body against the actual structural mesh at the crossing plane, including the lowest/full-travel pose. Ignition flames, gas arrows and pressure indicators must also stay in the moving free volume: their full tips/tails/width must not cross the piston, liner, valves or plug. Keep depth testing on; an explicit x-ray teaching mode must be separately selected and clearly identified, never the default. Capture before/contact/after frames from at least two useful orbit angles. A failed or unrun penetration check blocks acceptance.
  467. - **Hard acceptance, not promises about agents:** reject delivery until the manifest has no unexplained missing essentials; numeric invariant tests pass at boundaries and dense cycle samples; repeated `freeze(t)` yields identical state; desktop/phone hero frames and front/back/high orbit crops are reviewed; a motion strip proves causal order, contact and no interpenetration; controls, pointer-drag vs click, keyboard selection/focus and reset are tested. Store actual commands/results and tolerances in `qa/report.json`. An unrun check is UNVERIFIED, never a pass. These gates make omissions detectable; no skill can guarantee every future agent complies.
  468. - **Profile-aware QA:** retain finite geometry, console, deterministic time, contact and motion checks for every preset. Pixel uses palette/dither checks; toon uses native contour/material checks; hybrid checks low-res target + nearest upscale + only one outline pipeline. Educational off-white (and the canonical single UI surface only when enabled) replace white-empty-paper/cast/ritual quotas explicitly; do not silence unrelated failures. Fixed-camera assertions apply only after `orbit.reset()`, never during user inspection.
  469. ## Canonical educational UI and inspection contract
  470. This is the single authority for educational UI, selection and lesson behavior. **EDUCATIONAL / EXPLICITLY REQUESTED FEATURES ONLY: ordinary narrative scenes skip this chapter and its UI tests. Requested narrative inspection may reuse only its selection behavior; do not add the card, lessons or teaching labels.**
  471. The exact V8 tokens/hierarchy below remain the 3.16 visual contract.
  472. **Use code, not an interpretation of “shadcn-style”.** For new educational scenes WITH the educational UI enabled (not an explicit UI-free brief), copy `templates/education-v8.css` and build the DOM hierarchy below. UI-free educational scenes skip this chapter's DOM and UI tests; narrative scenes do not inherit it.
  473. This is the canonical visual contract extracted from the V8 explorer, independent
  474. of the chosen 3D render preset. Default to its ONE right card / mobile bottom dock;
  475. do not substitute the older bottom/center examples as new-build defaults.
  476. An explicitly requested bottom/center dock may change placement only, retaining
  477. these tokens, controls and hierarchy. Existing repairs preserve requested placement.
  478. The older `education-dock.css` is a minimal helper, NOT the V8 visual reference;
  479. do not use it as the visual starting point for new educational builds.
  480. Evidence: the grandfather-clock drift used beige/brass UI, a separate top-left
  481. title, translucent blurred panel and fixed top-to-bottom height. None follows
  482. from a clock subject. Brass belongs on the clock, not on its application chrome.
  483. ### Exact visual values (copy the CSS; do not restyle per subject)
  484. - Page `#f7f7f5`, opaque card `#fff`, ink `#18181b`, muted `#71717a`,
  485. border `#e4e4e7`, secondary `#f4f4f5`, focus/accent `#2563eb`.
  486. - System sans, base 14px/1.5. Desktop heading 21px/1.35, weight 650,
  487. letter spacing -0.6px; mobile 19px. Supporting copy and buttons 12px.
  488. - Desktop `.viewer`: grid `minmax(0,1fr) 360px`, right padding 24px,
  489. height 100dvh, vertically centered card. Stage is the first grid cell, NOT
  490. a fullscreen canvas underneath an overlay. Card is content-height, max
  491. `calc(100dvh - 48px)`, 22px padding, 18px gap, 14px radius, 1px border,
  492. shadow `0 1px 3px #18181b08, 0 8px 32px #18181b03`.
  493. - Below/equal 880px: one column, rows `minmax(0,1fr) auto`; dock max-height
  494. 48dvh, full width, top corners 14px, padding 16px 18px plus safe-area bottom.
  495. Measure the actual remaining stage for camera fit and renderer sizing.
  496. - Two segmented tabs: secondary background, 4px inset, 9px outer radius;
  497. selected tab white with subtle shadow. Primary playback is dark ink/white,
  498. not subject-coloured. Controls 36px desktop / 40px mobile; maintain adequate
  499. touch targets (44px hit regions where needed without crowding the row).
  500. - No beige/brown UI substitutions, serif/display fonts, uppercase eyebrow,
  501. translucent glass, backdrop blur, heavy shadow, detached title, always-open
  502. technical sections, extra dashboards or full-height panel. Do not grow a short
  503. card to fill its max-height. Subject geometry/materials remain subject-specific.
  504. ### DOM skeleton and state adapter
  505. ```html
  506. <main class="viewer">
  507. <div class="stage-wrap">
  508. <canvas id="stage" tabindex="0" aria-label="Interactive mechanism; drag to orbit"></canvas>
  509. <p class="gesture">Drag to orbit · scroll to zoom · click a part</p>
  510. </div>
  511. <aside class="panel" aria-label="Mechanism controls and explanation">
  512. <div class="panel-top">
  513. <header class="panel-head">
  514. <div class="title-row"><h1>Subject name</h1><span class="badge">Interactive</span></div>
  515. <p class="lede">Short input → change → output summary.</p>
  516. </header>
  517. <div class="tabs" role="tablist" aria-label="Mode">
  518. <button id="tab-explore" role="tab" aria-selected="true" aria-controls="explore-panel">Explore</button>
  519. <button id="tab-learn" role="tab" aria-selected="false" aria-controls="learn-panel" tabindex="-1">How it works</button>
  520. </div>
  521. <div class="controls" role="group" aria-label="Playback">
  522. <button class="btn primary" id="play">Pause</button>
  523. <button class="btn icon" id="prev" aria-label="Previous step">‹</button>
  524. <button class="btn icon" id="next" aria-label="Next step">›</button>
  525. <button class="btn icon" id="home" aria-label="Reset view">↺</button>
  526. <button class="btn toggle" id="xray" aria-pressed="false">Inside</button>
  527. </div>
  528. </div>
  529. <section id="learn-panel" role="tabpanel" aria-labelledby="tab-learn" hidden>
  530. <p class="section-note">One short instruction.</p>
  531. <div class="lesson-steps" role="group" aria-label="Causal steps"><!-- subject steps --></div>
  532. </section>
  533. <div class="readout">
  534. <p class="phase-title" id="phaseTitle"></p>
  535. <p class="phase-meta" id="phaseMeta"></p>
  536. <p class="explain" id="explainText"></p>
  537. </div>
  538. <button class="link" id="clearPart" hidden>← Back to cycle</button>
  539. <section id="explore-panel" role="tabpanel" aria-labelledby="tab-explore">
  540. <label class="label" for="parts">Inspect a part</label>
  541. <select id="parts"><option value="">Choose a part…</option></select>
  542. </section>
  543. <details class="disclosure help"><summary>About this model</summary>
  544. <p class="section-note">Simplifications and keyboard help.</p>
  545. </details>
  546. <p class="sr-only" role="status" aria-live="polite" id="announcer"></p>
  547. </aside>
  548. </main>
  549. ```
  550. Adapt subject names, number of lesson steps, part IDs, explanatory text and
  551. physical units only. Omit Inside for a mechanism with no enclosing shell; never
  552. add a fake x-ray toggle. Optional scrubber/Back lives in this same surface, not a
  553. second toolbar. Use line SVG icons matching the supplied CSS in production.
  554. Implement tab click plus ArrowLeft/Right/Home/End roving tabindex, hidden panel
  555. state, and semantic buttons/select/range. Bind controls to the actual evaluator:
  556. `play/pause`, `freeze(step.phase)`, `orbit.reset`, reversible `inside`,
  557. `selectPart(id)` and `clearSelection`. A lesson change freezes synchronously and
  558. updates explanation from that state; it must not trigger automatic camera motion.
  559. The skeleton/CSS is not a functioning controller; do not ship inert controls.
  560. ### Three regression gates
  561. 1. **Computed-style/structure:** at 1280×800 assert one card, one h1 INSIDE it,
  562. 360px card column, opaque white card, exact neutral tokens, no backdrop filter,
  563. content-height card, closed About and Explore selected initially. At 390×844
  564. and 320×640 assert one bottom dock, no horizontal overflow and an uncovered
  565. nonzero stage. Inject beige tokens, detached title and full-height panel; each
  566. must fail the check. Record measured values, not just “V8-like”.
  567. 2. **Rendered evidence:** review desktop, phone and 200% zoom screenshots plus
  568. selected/restored states. Check actual background pixels against the authored
  569. paper (not merely body CSS), tiny-part readability, stage/card separation and
  570. front/back/high camera fits. For V8 matching use `#f7f7f5` consistently in CSS,
  571. renderer clear/scene and ground composition; user-requested white overrides all
  572. those together. A screenshot is not mechanical clearance proof.
  573. 3. **Interaction:** keyboard-only tabs/steps/picker/reset, paused orbit, drag vs
  574. selection, Inside lifecycle and shared-material restoration must pass existing
  575. per-scene gates. Store commands, values and proof paths in `qa/report.json`;
  576. missing browser/computed-style/visual checks remain UNVERIFIED.
  577. ### Selection, focus and lesson adapter
  578. Raycast actual visible geometry: nearest eligible hit wins, respecting nearer
  579. opaque occluders. Map the hit mesh to both its assembly ID and its actual piece
  580. ID; assembly selection and clicked-mesh selection are distinct scopes. The
  581. single labelled keyboard piece picker must expose the same pieces/actions,
  582. including hidden pieces; never silently broaden a click to an entire assembly.
  583. Show one short explanation in the card. An optional single label uses a live
  584. geometry-local anchor and hides behind camera, offscreen or when occluded.
  585. A deliberate canvas/picker Inspect selection may make one short useful camera
  586. AND OrbitControls-target transition to live selected bounds. Avoid end-on shafts
  587. and blocking housings; use an authored reveal/cutaway for hidden pieces and
  588. report remaining occlusion honestly. Save the prior view for Back; Reset restores
  589. the hero. User orbit/pointer/keyboard navigation cancels the tween immediately.
  590. Reduced motion uses an immediate useful view. Never auto-spin, chase moving parts
  591. or restart focus per frame. Lesson step selection instead pauses and synchronously
  592. freezes the real evaluator, highlights its part and updates phase/text/readout
  593. without moving the camera; only an explicit Inspect action focuses. Scrubbing
  594. updates the lesson from evaluated state, not an independent clock. Announce
  595. intentional changes politely, not each frame.
  596. Use semantic buttons/select/range, visible focus and non-colour part-name cues;
  597. canvas arrows orbit and R resets. Tabs implement roving focus and keyboard
  598. navigation; no focus trap. Drag/multitouch is orbit, not click (use the movement
  599. threshold/cancel handling in `templates/orbit.js`); UI gestures never bubble into
  600. the stage. Paused and reduced-motion modes retain inspection.
  601. ### Soft glow and holographic inspection — implementation recipe
  602. This is an **inspection overlay**, not a new render preset, bloom pass or a way to hide modelling errors. Use the same mechanism for a selected gear, valve, pump impeller, drawer slide or anatomical structure. The V8 selection implementation is the calibration evidence: restrained warm material lift, dimmed context, transparent outer castings and selective gold feature edges. Do not interpret “glow” as a white emissive blob.
  603. **1. Preserve and derive, never mutate the shared originals.** Build a registry once from the actual selectable meshes, BEFORE adding overlays. Store each exact original material reference, including arrays of material slots; a mesh's slot array itself must also be restored by identity. Derive cached variants from each source UUID plus mode. Clone `userData` and `outlineParameters` before changing outline alpha, since nested objects may otherwise be shared. Keep toon ramps, texture maps, roughness and existing supported preset properties. Restore the originals before applying each new selection/X-ray state, not by attempting to reverse colour arithmetic.
  604. Use `templates/inspection.js` rather than duplicating a second material controller.
  605. Its API is `createInspection(THREE, {parts, contextMeshes, resolveVisibility,
  606. onChange, style})`, with `select({partId, mesh})`, `clear()`, `refresh()`,
  607. `dispose()` and `piecePickerEntries(partId, {visibleOnly:false})` (includes hidden
  608. pieces for keyboard inspection). Validate actual mesh membership before selection.
  609. The helper supports rigid meshes only; reject skinned/instanced/morph assumptions.
  610. `resolveVisibility` returns named `hiddenPartIds`/`hiddenMeshes` plus `description`
  611. for an authored cover removal. Hiding requires `shell:true`, or an explicit
  612. `inspectionOccluder:true` part plus an active selection and nonempty cutaway
  613. description; that latter exception may remove an upper gear/bridge to expose a
  614. lower part, never hide construction failures. Optional `ghostPartIds`/`ghostMeshes`
  615. are accepted only for `shell:true`. Selected assemblies/pieces remain visible;
  616. context meshes (floor/stand/UI) cannot hide, ghost or dim.
  617. Unknown parts, duplicate ownership, empty geometry and unsupported material or
  618. deformation paths fail explicitly. Never request a whole-mechanism ghost. The host owns
  619. camera focus, picking and V8 DOM; the helper owns emphasis/restoration, not UI or
  620. mechanical certification. Cached variants derive per original material and mode; never
  621. from the currently displayed variant. Lift colour gently; write emissive values
  622. only where the original material supports them. Dim context as opaque solids.
  623. Only the explicit housing reveal below may change transparency/depth-write.
  624. **2. Reveal only manifest-authorized occluders; ghosting is shell-only. Never defeat depth on the selected part.** Declare `internalPartIds` and `occludingShellIds` per subject in the component manifest. For an internal selection, remove authored covers or optionally ghost only declared outer housings that obscure it; keep the selected part solid, retain non-selected internals as dim solids, and leave floor/stand/UI alone. A global Inside toggle applies that same named reveal plan without dimming all internals. A selected housing stays highlighted rather than ghosting itself. Unlisted opaque solids must still occlude correctly: `renderOrder` does not override the depth buffer. For an internal blocker, author an explained selection-only `inspectionOccluder:true` removal plan; the independent Inside toggle still affects shells only. Hidden siblings need a piece-level plan and cannot remove the selected scope. Do not set `depthTest=false`, use additive whole-body overlays, or fade all solids to pretend a mechanism is correctly constructed. Picker rays ignore generated edges and ghost-shell hits, but respect remaining opaque foreground objects; click and picker share the same selection action.
  625. **3. Make the hologram from feature edges, attached to the live part.** Do not use `wireframe:true`: that exposes triangle diagonals. Use `EdgesGeometry(source.geometry, 32)` and a restrained `LineBasicMaterial` (`color:0xffc35c`, `opacity:0.5`, `transparent:true`, `depthTest:true`, `depthWrite:false`, `toneMapped:false`). Normal blending, no bloom. Exclude slivers, ring grooves, gaskets and tiny bolts when edges become noise; the V8 thresholds were minimum dimension 0.018 units and, for cast housings, volume 0.006 units³. Those are **model-scale-dependent starting values**, not universal dimensions. Use one physical edge overlay on the selected component only, not a second full-scene OutlineEffect/Sobel pipeline. Its surface outline may need suppression to avoid doubled contours. WebGL line width is generally one device pixel: do not promise a controllable CSS-pixel width through `linewidth`.
  626. Attach each owned edge overlay as an identity-transform child of its live source
  627. mesh; mark it as an inspection overlay and exclude it from raycasting. On change,
  628. remove and dispose owned overlays, never source geometry or shared maps.
  629. This child pattern follows moving rigid geometry without copying a stale pose. If an overlay must be a sibling/world-space object, synchronise its transform from the source every evaluation; copying position/quaternion once is insufficient when the source mesh moves. `EdgesGeometry` does **not** automatically follow vertex deformation or per-instance transforms: skinned/morphed/instanced subjects need a deformation-aware shader/overlay or a clearly declared unsupported path. Never claim those supported because a rigid V8 example works. Do not dispose the source geometry, shared source maps, shared toon ramps or original materials; dispose only owned variants/edge geometries and owned overlay materials. Keep overlay generation bounded to selection changes, never create/dispose hundreds of edge objects every frame.
  630. **State and restoration contract.** One selection controller owns this effect. Resolve in order: restore exact originals → remove previous edges → compute selected/internal/Inside state → ghost selected occluding housings → highlight selected meshes → dim remaining mechanism meshes → attach selected edges. Re-apply from originals when Inside changes. Leaving How it works restores its earlier Inside state and removes its tutorial tint; clearing selection retains an independently enabled Inside toggle. Picker, canvas, keyboard and lesson adapters must not compete by writing materials from separate uncoordinated caches. Clear/reset/teardown restores material references, opacity/depth/blending/outline state, selection/readout and authored camera state; only teardown disposes long-lived caches. Respect reduced motion; avoid automatic pulsing, scanlines or flashing. Keep the part name and keyboard focus as non-colour cues.
  631. **Historical evidence (not project dependencies):** `quartz-watch/shots/highlights/dialPost1.png`,
  632. `quartz-watch/shots/highlights/dialPost2.png`, `quartz-watch/shots/highlights/dialPost3.png`,
  633. `quartz-watch/shots/highlights/dialPost4.png`, `quartz-watch/shots/highlights/individual-piece.png`,
  634. `quartz-watch/shots/highlights/rotor.png`, `quartz-watch/shots/highlights/reduction.png`,
  635. `quartz-watch/qa/highlights-report.json` and `quartz-watch/qa/construction-report.json`.
  636. These record this repair, not files future users must have. Twenty-six assembly
  637. glow states had numerical tests/captures; only a subset received visual review.
  638. Do not present that as universal contrast certification.
  639. **Evidence and test — selection contract (3.18).** Quartz-watch selection was
  640. almost invisible, posts were end-on/occluded, and adding emitter properties to
  641. MeshBasicMaterial caused a `shader.value` error. Use `templates/inspection.js`,
  642. with `templates/qa/inspection.test.mjs` and
  643. `templates/qa/inspection-browser.mjs`; use the API above. Assert assembly versus actual clicked-piece identity,
  644. keyboard equivalence, nearest opaque occlusion, and obvious visible glow with
  645. retained shape/colour (never a white blob) in desktop/phone crops. Test shared
  646. and array materials, Basic/toon, two frozen phases, moving/orbiting, rapid changes,
  647. Inside/clear/Back/Reset/lesson exit, interrupted focus and reduced motion. Restore
  648. exact original material AND slot-array identities, shadow flags and `visible`
  649. state, plus original material properties; test source immutability and owned-only
  650. disposal with stable overlay/material counts. Basic materials must never gain
  651. `emissive` or `emissiveIntensity`, even temporarily; feature-test capability before
  652. writing, and assert absent properties remain absent. Verify shader compilation
  653. and no console errors in the fresh browser build. Scalar/material tests alone do
  654. not establish visible contrast, depth correctness or useful focus.
  655. ## Repair acceptance: enclosure, fit and reference UI (3.15)
  656. Use this short checklist for existing educational scenes before re-reading narrative
  657. recipes. Evidence: the LEAP-1B repair was requested because its permanent section
  658. exposed the core, its fit cropped the model, its beige background and crowded panel
  659. did not match the requested V8 reference. These checks supplement mechanical QA;
  660. passing enclosure rays or a screenshot does not certify a complete mechanism.
  661. 1. **Closed first, explicit Inside.** Unless a permanent section is commissioned,
  662. cold load and hero Reset show the complete opaque housing, no tutorial tint,
  663. Inside off. Build the missing casing as real connected wall geometry while
  664. preserving inlet/outlet openings; a toggle cannot repair absent geometry.
  665. Inside is a named semantic button in the single surface. Internal picker or
  666. lesson selection may explicitly activate it, but must update its pressed state;
  667. leaving the lesson restores the preceding Inside state. Clearing selection
  668. preserves an independently enabled Inside state. **Test:** load → Inside on/off
  669. → internal selection → clear → lesson exit → Reset; check visible ancestors,
  670. nearest opaque ray hits, exact material restoration and open-mouth rays.
  671. 2. **Fit the assembly in the space actually available.** Measure canvas layout
  672. after the dock/panel; use actual complete assembly bounds including covers,
  673. supports and swept extrema, not a default slab. Fit the safe rectangle with
  674. padding; if UI overlays the canvas, solve its offset as well as distance.
  675. With direction target→camera, depth is `distance - along`, so each fit bound
  676. contributes `abs(transverse)/tanHalf + along` (not minus along). Do not clamp
  677. distance below the solved fit or distort portrait aspect. Re-measure on layout,
  678. disclosure, resize/orientation and zoom changes without hijacking user orbit.
  679. **Test:** project covered/exposed swept bounds at desktop, tablet, 390×844,
  680. 320×640 and 200% zoom, with lesson/disclosure open; front/back/high captures;
  681. fail an injected protrusion and verify near-plane/focus fits separately.
  682. 3. **UI repair:** compare the supplied reference before changing placement;
  683. apply `Canonical educational UI and inspection contract`, including rendered
  684. background, accessible lesson state and desktop/phone/200% zoom gates. Do not
  685. copy the reference subject or introduce a second surface.
  686. ## Construction regression gates
  687. These construction rules apply across subjects and all render presets; they supplement, not replace, the style gate and profile-aware verification above. They make known failures testable, not impossible.
  688. 1. **Specify the mating interface before decorating the part.** Extend the component manifest with units, parent-local frame, shaft/bore/slide axes, shared joint/port anchor IDs, mating surfaces, nominal dimensions and radial/axial tolerances. Derive both mating meshes and their motion from those anchors, not repeated guessed offsets. A bearing eye needs a real through-bore; its beam, cap, bolt and bevel must stop outside that bore. Budget bevel/fillet intrusion in the actual construction method (inward bevels reduce usable bore), axial lane widths, spacers, end float and end stops. Check coaxial alignment and anchor residual after parent transforms. Model the load path through real bearings, brackets, fasteners and a base; route each functional port through an actual connected opening to its destination, not a hose ending inside a solid. Document symbolic/omitted internals. **Evidence:** V8 running-gear repair found a centred rod beam cutting its crankpin despite an annular eye, bank stagger applied to only one mating member, and fillets facing the wrong local axis. **Test:** local-axis/anchor tests, measured bore plus bevel allowance and axial stack tests, section crops from two orbit directions, and traced port/support connections. Record geometry revision and proof frames in the manifest. Copy `templates/mechanism-contract.mjs` and fill the interface and connection sheets in `templates/DESIGN.md`; the helper validates scalar budgets, not arbitrary mesh bores or load strength.
  689. 2. **Audit the complete swept assembly, with narrowly scoped intended contact.** Derive every driven pose from one driver and test the actual transformed meshes or documented conservative collision proxies, including beams, caps, fasteners, webs, fillets and supports. Broad-phase boxes alone neither detect holes correctly nor prove clearance. Enumerate potentially interacting pairs and coverage; whitelist only a named pair of mating surfaces with phase window, normal-gap/penetration tolerance and rationale (bearing/journal, meshing teeth, valve/seat), never an entire assembly or all pairs of a part type. All other pairs need the declared positive clearance. Check full travel, extrema, cycle seam, contact transitions and close-approach intervals with refinement; include ports/FX containment. Report method, sample spacing, tolerance, worst phase/pair, exclusions and unresolved regions. Dense sampled vertex/triangle tests are bounded evidence, not continuous exact collision proof: use analytic bounds or conservative continuous checks where available, otherwise retain that limitation explicitly and block unsupported clearance claims. **Evidence:** the V8 12/12 invariant report omitted rod/crank interference; the later rod probe added bore triangle samples, axial lanes, journal vertices, anchor residual and fillet axes. **Test:** intentionally inject a beam-through-bore, wrong-axis fillet, too-wide lane, out-of-window contact and a non-whitelisted overlap; each must fail. Run full-cycle probes plus before/contact/after crops from two angles. `templates/qa/mechanism-contract.test.mjs` tests budget/contact-policy failure detection only; per-scene geometry/sweep checks remain mandatory and UNVERIFIED until run.
  690. 3. **Repeated interfaces share anchors and axes (3.18 evidence + test).**
  691. Generate ALL repeated mating members from one anchor/axis table, not just the
  692. first working example. Quartz-watch pads at radius 12.6 missed posts at 13;
  693. rotating a native CylinderGeometry about Y did not redirect its native Y axis.
  694. The seconds shaft opposed its hand and the model lacked a physical 60:1 stage.
  695. Coplanar shaft-cap fans z-fought. Use transformed local axes (quaternion maps
  696. native Y to the declared axis), common anchors, real through-bores and a single
  697. end surface or measured axial separation; never hide coplanar caps with depth
  698. overrides. Derive ratio/direction from the actual connected transmission, not
  699. only a display hand formula. **Test:** with `templates/mechanism-contract.mjs`
  700. shared anchors/checkRepeatedInterfaces/checkEndPlanes, enumerate every pad,
  701. post, bore, cap and shaft; assert count, transformed axis/anchor residual,
  702. radial/axial clearance and physical ratio/direction across the full cycle.
  703. The repaired watch measured zero residual at all four pad anchors and 0.08
  704. board-bore radial clearance; those are historical measurements, not defaults.
  705. Inject one displaced repeat, wrong native axis, sealed bore, reversed shaft,
  706. missing reduction and coplanar cap; each relevant check must fail. Review
  707. section/end-on and oblique crops; scalars cannot prove real mesh openings.
  708. Evidence: the historical construction report and highlight shots above.
  709. Lesson/UI behavior and its tests are defined once in `Canonical educational UI
  710. and inspection contract`. `templates/education-dock.mjs` remains a dependency-free
  711. state helper with `templates/qa/education-dock.test.mjs`; its older CSS is not the
  712. V8 visual authority.
  713. ## Universal Inspection Controls
  714. Copy `templates/orbit.js` for EVERY scene and preset. Create it after camera fit with the fitted target; keep animation evaluation independent of camera interaction. Render on control change even when paused. Expose `orbit.reset()` and have the QA freeze wrapper reset it before capture (`freeze(t)` evaluates time synchronously). User pause/freeze UI need not reset their chosen inspection angle. Fit zoom/polar limits to real subject bounds without preventing back/high inspection. No auto-rotation, no camera motion driven by the animation clock. Keep reset + a brief drag/keyboard hint accessible; educational controls and selection follow `Canonical educational UI and inspection contract`.
  715. ## Optional Pixel + Stroke Hybrid
  716. `pixel-stroke` is a third style, not the pixel default, and it is selected through the single `Render Preset Gate` question — never inferred, never switched to later without a new answer. Record the answer and do not offer it again during the build. Rotation is mandatory regardless of the answer.
  717. Copy `templates/pixel-stroke.js` plus `templates/stroked-toon.js`. Create WebGLRenderer with antialias false, alpha true. Use `createPixelStroke(renderer, {width:320,height:200})`, its `toon`/`flat` material factories and `render(scene,camera)`. Resize the low-resolution target explicitly with `look.setSize(bufferW,bufferH)` while sizing the renderer to the display aspect; keep target aspect aligned to viewport/camera. Toon lighting/materials plus selective geometry OutlineEffect render into that target, then ONE nearest-neighbour fullscreen upscale. Do not run PixelPost, Sobel ink, a second outline pass or CSS blur over it. Native-resolution DOM UI is outside the target and must remain crisp.
  718. OutlineEffect thickness is a projected effect parameter, NOT a CSS-pixel width. Rasterisation happens at the low-resolution target: a one-target-pixel contour becomes approximately `displayWidth / targetWidth` CSS pixels after upscale (analogous vertically). A thinner subpixel outline can disappear or flicker; measure target and screen crops at desktop/phone, adjust target resolution and selective material stroke together. Disable outlines for inward cavity surfaces, liquids, films, transparent glass, vapour and contact patches; do not double edges. For native toon, measure the native-DPR render instead. Free orbit, construction, manifest and QA requirements are unchanged.
  719. ## Optional Stroked-Toon Preset
  720. ### 1. Chosen through the gate; preserve the default
  721. Use **stroked toon / illustrated miniature** (`stroked-toon`) only as resolved by
  722. `Render Preset Gate`; retain its recorded answer during repairs. The gate owns
  723. consent/default/recording rules—do not ask a second style question here. This
  724. preset changes presentation, not the subject or choreography; never import
  725. coffee props or workshop colours into an unrelated scene. Record paper/frame
  726. and camera choices alongside the preset in `DESIGN.md`.
  727. **Precedence when approved:** the recipe below replaces the pixel-only camera,
  728. white/no-plinth, palette-snap, edge-shader, Bayer, empty-paper and buffer rules
  729. where they conflict. Do not combine both post pipelines by default. A thin
  730. bevelled slab edge and a restrained optional figure frame/title/hint/readout are
  731. allowed. Locked animation framing, deterministic time, clipping/containment,
  732. contacts, silhouette readability, detail and animation QA still apply. Orbit is mandatory for all presets; it needs no separate approval. Character
  733. proportions remain subject-appropriate; don't force toy people into every scene.
  734. ### 2. Render solid illustrated parts, not a pixel filter
  735. Copy `templates/stroked-toon.js` into the project. It exports an opt-in Three.js
  736. helper; it has no dependency on Anatomy CSS, SVG, fonts or the coffee rig.
  737. - **Native crisp rendering:** antialias on; device pixel ratio capped at 2;
  738. sRGB output, `NoToneMapping`. Disable PixelPost, palette quantisation, dither,
  739. Sobel ink and CSS `image-rendering: pixelated`. Keep a small authored colour
  740. family, not a requirement that every final shaded pixel equal a palette entry.
  741. - **Four-step surface shading:** `MeshToonMaterial` with a 4×1 RedFormat ramp,
  742. bytes `[68, 122, 184, 246]`, nearest filters, no mipmaps. These are starting
  743. values, not physical light calibration. Give materials distinct local colours:
  744. warm/cool off-white, desaturated object hues, dark structure, metal or timber,
  745. one restrained accent. Adapt to the setting; warm cream is optional.
  746. - **Selective fine contours:** Three.js `OutlineEffect`, warm charcoal rather
  747. than pure black. Start thickness 0.0024–0.0038 (effect units, not world units
  748. or pixels). At the final viewport, aim for a roughly 1–2 CSS-pixel hero contour
  749. with finer subordinate edges; tune by screenshots at desktop and phone sizes.
  750. Broad silhouettes can be heavier, tiny fasteners lighter. Do not add wireframe
  751. or stroke every triangulation. Flat decals, liquid films, transparent glass,
  752. steam, contact patches and inward cavity surfaces normally have no outline.
  753. - **Light for volume:** one warm upper-side key with shadows, a broad hemisphere
  754. and weaker cool fill. The helper starts key 2.55, hemi 1.55, fill 0.72; measure
  755. and tune for the scene, especially night/water. Tight shadow bounds, 2048 map,
  756. PCFSoft shadows, low bias, no acne. Combine cast shadows with small radial-alpha
  757. contact patches only where needed; no overlapping dark discs or false rings.
  758. - **Model the edge:** modest bevels on casing, slab, rails and props; profile
  759. lathes for vessels; cylinders with enough segments to read round. Avoid a
  760. melted soft-plastic scene or polygonal mugs. Separate outer silhouette from
  761. cavity shading: real wall thickness and a bottom, one-sided inward surface,
  762. no expanded backface stroke through the interior. Glass must reveal contents;
  763. liquid stays inside the wall through the whole fill range. Paper/grain and
  764. lighting gradients are allowed; they must not obscure part boundaries.
  765. - **Compose and inspect:** a long-lens three-quarter view (start fov 26,
  766. azimuth 38°, elevation 27.5°), fit to full animated bounds, room for the tallest
  767. object and controls. These are a starting point, not a mandatory angle for all
  768. subjects. Free user orbit is mandatory in every preset: use OrbitControls,
  769. bounded zoom/polar angles, reset view and no pan; detail all exposed sides. No auto-spin.
  770. Keep explicitly requested UI outside the subject, subtle, readable and keyboard-accessible. Narrative builds have no title/readout/card/teaching overlays by default; only discreet necessary controls. A title, hint or live state is opt-in figure furniture, not a requirement of toon rendering and not an excuse to import educational or Anatomy CSS.
  771. Minimal integration after user confirmation:
  772. ```js
  773. import * as THREE from 'three';
  774. import { createStrokedToon } from './core/stroked-toon.js';
  775. const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
  776. const look = createStrokedToon(renderer);
  777. renderer.setSize(width, height, false);
  778. const shell = look.toon(0xc4cbb4);
  779. const inner = look.toon(0xb8bfaa, { outline: false });
  780. // Add subject-specific lighting and objects; do not also call PixelPost.render.
  781. look.render(scene, camera);
  782. // On resize: renderer.setSize(width, height, false); update camera projection.
  783. ```
  784. ### 3. Match the craft and detail, not just the shader
  785. Use the Detail Bar's silhouette → construction → story passes, plus this close-up
  786. acceptance bar. Detail is structural, not a quota of randomly scattered meshes.
  787. Visual calibration references are `media/stroked-toon-reference.jpg` (overall
  788. framing/material hierarchy) and `media/stroked-toon-service-reference.jpg`
  789. (assembly detail). Read them when reproducing this look, but translate their
  790. craft to the requested subject rather than copying their props or palette.
  791. The coffee-rig repair is the evidence: a floating lever needed a pedestal;
  792. interior parts needed supports and connected runs; a ring under the scale read
  793. as a detached base; outlined cavities and oversized liquid surfaces looked broken.
  794. | Pass | Any-scene requirement | Translate to the subject |
  795. | --- | --- | --- |
  796. | Structure | Primary mass, supporting assembly, secondary panels/members | trunk/roots/branches; hull/ribs/deck; torso/joints/gear; wall/roof/trim |
  797. | Attachments | Every small part has a visible or explainable seat, joint or support | leaf stem, rope knot, hinge pin, bracket, cuff, axle, strap, fastener |
  798. | Functional detail | Inputs, outputs and working parts connect; contents fit containers | rooted irrigation, connected hoses, docked lines, harness to buckle, wheels to hubs |
  799. | Surface hierarchy | Large readable forms, medium assemblies, sparse microdetails | seams, fittings, latches, bark scars, stitches, labels, scales; not uniform noise |
  800. | Nearby life | 3–6 supporting props in purposeful clusters when space/brief permits | campsite kit; cargo/lifebuoys; books/blanket; tools/materials; tracks/nests |
  801. | Story | At least one specific used/changed detail per hero | wear at contact, repair, folded cloth, spilled contents, missing tile, footprint |
  802. Start with 8–15 meaningful pieces for a small supporting prop and 30–60 for a
  803. hero; a complex cutaway may need 100–250+ small pieces across its subsystems.
  804. These are planning ranges, not mesh-count acceptance tests. Reuse geometry and
  805. materials, merge static siblings only after visibility/animation ownership is
  806. settled, measure draw calls/fps and reduce invisible detail before construction.
  807. Preserve clear working paths and negative space. "Feels empty" calls for a few
  808. related clusters at varied heights, not filling every inch of deck.
  809. **Proof before delivery:** one whole-scene desktop and phone frame; a 1:1 hero
  810. crop; a cavity/contact crop if relevant; an action strip at known times. Always inspect front, service/back and high angles. Check outline
  811. width and tiny-part legibility; no floating supports, disconnected endpoints,
  812. false residue hoops, filled-in hollows, liquid clipping, or outlines on vapour.
  813. Scan finite vertices, contacts/clearances and moving bounds; check the actual
  814. readout against the frozen time. Keep `freeze(t)` and reduced-motion support.
  815. Do not call a symbolic cutaway a verified engineering design. Use the existing
  816. QA harness for shared checks, but disable or replace its pixel-palette/dither,
  817. empty-white-paper and fixed-angle assertions for this preset explicitly; do not
  818. silence unrelated failures. Record the preset and which checks apply.
  819. ## The Look Contract
  820. The ten rules below define the **default pixel preset**, not the optional
  821. stroked-toon preset. Approved stroked-toon builds use the explicit overrides
  822. above; the remaining scene/animation requirements still hold.
  823. 1. **Resettable hero angle + free orbit.** Start azimuth 45, elevation 33, fov
  824. 20.5, target just under slab centre. User orbit is enabled in EVERY preset.
  825. No auto-spin or timeline camera drift. Reset to this pose before frozen QA.
  826. 2. **Flat cut-out.** A slab with no plinth, no soil sides, background null, page
  827. white. Everything below the deck plane hides in the overhang at 33 degrees.
  828. 3. **Palette snap.** Every pixel resolves to one entry of a fixed palette. No
  829. gradients survive; banding is the material.
  830. 4. **Ink contour.** A luminance-neighbour edge mixes toward warm near-black at
  831. about 0.62, suppressed on the outer rim so figures are not haloed.
  832. 5. **Dither only where tones move.** Ordered Bayer gated by local edge contrast.
  833. Flat decks stay flat; ramps stipple.
  834. 6. **Contact shadows, not just cast shadows.** A soft radial patch under every
  835. figure and prop is what anchors it to the ground at this scale.
  836. 7. **People read at 30 to 45 px.** Faces need eyes, brows, nose, mouth, ears.
  837. Bodies need joint fillers so a bend never opens a wedge.
  838. 8. **Clipped edge.** The slab is a window, not a stage: four world-space clip
  839. planes sit on its edges and anything driving in or out is cut at the
  840. boundary. Nothing ever floats on the white page outside the block.
  841. 9. **Everything is a pure function of `t`.** No integration that carries state
  842. between frames, no `Math.random`, no drift across the loop.
  843. 10. **Empty paper (narrative profile only; educational dock and universal orbit controls are exceptions).** The white page carries no DOM title, caption, HUD or
  844. instructions. Put copy on a modelled sign/screen or in the browser title; a
  845. label floating on the paper breaks the cut-out.
  846. ## The Detail Bar
  847. A blockout with a camera is not a diorama. The difference between a demo and a
  848. diorama is **three passes**, and every hero object has to survive all three.
  849. 1. **Silhouette.** At 1:1 the object is recognisable from its outline in about
  850. 0.2 seconds, before colour or detail.
  851. 2. **Construction.** The silhouette is explained by visible assemblies: posts,
  852. rails, bands, plates, wheels, hinges, ropes, fasteners. A single primitive is
  853. a placeholder, not a prop.
  854. 3. **Story.** One detail tells you who used it and what happened: a chipped edge,
  855. a trophy skull, a repair strap, a spare bolt, a rag, a tally mark, a spent
  856. shell. If the detail could be removed without changing the read, it is
  857. greeble, not story.
  858. ### Whole-object completeness gates (3.17)
  859. Apply these three gates to every hero object in every profile and render preset,
  860. including educational cutaways. They extend the existing Detail Bar and component
  861. manifest; they do not add cast, story-prop or mesh-count quotas to educational scenes.
  862. Evidence is the user's report of a quartz watch missing its straps and back; no
  863. independent inspection or root-cause diagnosis of that model is claimed here.
  864. 1. **Approve the whole-object silhouette, not only the teaching core.** Before
  865. detail, record whether the commissioned subject is a complete object, a detached
  866. mechanism or an explicit permanent section; default to the complete named object.
  867. Reference the entire object and its proportions, not just its most interesting
  868. subsystem. A complete wristwatch needs its case and both strap/bracelet sides,
  869. not merely a dial or quartz movement. Simplify small surface detail before
  870. deleting identity-defining masses. **Evidence:** the reported watch lacked
  871. straps despite its watch subject. **Test:** compare grey whole-object front,
  872. side and rear views against recorded references, then review desktop/phone
  873. delivery frames with the entire silhouette uncropped. Temporarily hide an
  874. essential silhouette assembly (for the watch, either strap side); the review
  875. must reject it. A close crop of the core cannot pass this gate.
  876. 2. **Construct exterior, rear and attachment chains as real assemblies.** An
  877. educational explanation of internals does not waive the casing, rear closure,
  878. mounting or wearable attachments. Inventory every orbit-exposed side and trace
  879. attachments into their seats/joints. For a strapped watch this includes caseback,
  880. lugs/spring-bar connections, both strap halves and the reference-appropriate
  881. buckle/keeper or clasp; do not impose those exact fittings on a different design.
  882. Keep required construction in the model when an explicit Inside mode reveals
  883. internals; a label, dark disc or transparency is not a replacement for absent
  884. geometry. Honour a commissioned permanent section and document its boundaries.
  885. **Evidence:** the same report named the missing back as well as straps.
  886. **Test:** review opaque front/rear/side/high orbit crops and attachment-seat
  887. close-ups; inspect mesh/group mappings and actual contact/clearance at joints.
  888. Exercise cold load → Inside on/off (if present) → Reset to check restoration.
  889. Hide the rear closure or disconnect an attachment in a test copy; the matching
  890. presence/connection check and visual review must reject it. Existing motion and
  891. non-penetration tests still apply; presence alone does not prove sound mechanics.
  892. 3. **Close an explicit completeness matrix before claiming completion.** Fill
  893. the matching DESIGN sheet before modelling and reconcile it against the built
  894. scene before delivery. Give each expected silhouette, exterior/rear, attachment
  895. and functional/internal assembly a stable ID, reference or stated assumption,
  896. required/simplified/omitted status with scope rationale, mesh/group mapping,
  897. connection and proof view plus actual test result. An omission note alone cannot
  898. waive an essential part of the commissioned whole object; build it or obtain an
  899. explicit scope change. **Evidence:** the reported missing straps/back show why
  900. subsystem detail cannot stand in for whole-object coverage. **Test:** reconcile
  901. every expected row with nonempty live geometry and reviewed proof; check that
  902. the inventory itself covers the whole reference, not just existing meshes.
  903. Deliberately remove a required row's mesh, leave its proof blank, and add an
  904. unexplained omission in test copies; each must fail the audit. Store commands,
  905. results and proof paths in `qa/report.json`. Missing evidence is UNVERIFIED,
  906. a missing required assembly is FAIL, and either blocks a completeness pass.
  907. This matrix makes omissions reviewable; it is not automatic certification or
  908. a guarantee that future agents will comply.
  909. The numbers below are **reference density** from The Hollow Toll, a 21 x 14 m
  910. slab with four towers, two gate guns, five species, 42 units, one boss, 527
  911. events and 183 shots. Treat them as a calibration target, not a cap.
  912. | Element | Minimum visible assemblies | Hero target | Required story detail |
  913. | --- | --- | --- | --- |
  914. | Tower | 6 | 25 to 45 parts | crew, ammo, livery, wear |
  915. | Creature | 8 | 12 to 20 parts; boss 40 to 60 | gear, scar, trophy |
  916. | Prop | 5 | 8 to 15 parts | contents, tool, repair, rag |
  917. | Landmark | 8 | 30 to 60 parts | one unmistakable silhouette |
  918. | Death | 3 stages | 5 to 8 pieces + stain + soul | species-specific debris |
  919. | Environment | 3 scale cues, 3 story props | 2 ambient loops | a before/after trace |
  920. In a social diorama, read the Death row as **Exit**: a role-specific departure
  921. (turn, walk out, shutter down) with the prop and no debris. The five layers are
  922. unchanged; the residue is the changed place, not a stain.
  923. **An object can hold two roles.** A lighthouse that is also a beam tower gets
  924. the landmark budget for its structure **plus** the machine's moving parts; list
  925. both rows in the design sheet. A boss weapon is a separate group: budget 8 to 12
  926. parts for the weapon on top of the body, and say so, or the body will be blamed
  927. for a thin haft.
  928. **Primitive discipline.** No naked box, sphere or cylinder at hero scale. A box
  929. gets a chamfer, a frame, plank divisions or a band. A sphere becomes a skull,
  930. bale, sack or head with a snout, ties or a neck. A cylinder gets a foot, cap,
  931. taper or iron rings. If a shape is still a primitive after the detail pass, it
  932. will read as a rock, a blob or a placeholder at 30 to 45 px.
  933. **Two to four palette entries per object, plus one accent.** More entries
  934. turns into noise after the palette snap; fewer turns into a silhouette cut-out.
  935. Use value contrast for construction and hue for story.
  936. **Detail lives on every orbit-exposed surface.** All presets need coherent backs,
  937. construction, attachments and cavities; a fixed hero shot is not permission to
  938. omit parts. Hidden internals may be simplified only if outside the mechanism manifest. Do not add detail
  939. under about 1.5 screen pixels at the delivery view: it aliases into speckle, not craft.
  940. **Every prop must touch the ground.** Feet, wheels, a base, a contact shadow, a
  941. stain. A prop hovering by two centimetres is the single most common "it looks
  942. cheap" report. Check the shadow and the lowest vertex, not the group origin.
  943. **Every landmark must be the only one of its silhouette.** Two skull trees, two
  944. red tents or two identical towers read as duplication, not composition. Move,
  945. scale or redesign the second one. Check overlap by projecting both bounding
  946. boxes to screen: if they merge into one blob, one is invisible detail.
  947. **Clear thresholds.** Keep at least 2 m of empty ground in front of a gate,
  948. portal, spawn mouth or door. No crates, barrels, boulders, bones, vines or
  949. rising smoke in that pocket. A grey billboard above an arch reads as a rock
  950. flying out of the entrance even when it is transparent.
  951. ## The Animation Bar
  952. An actor is animated when it has all five of these, not just a walk cycle:
  953. 1. **Idle / ambient.** Breathing, sway, scan, flame, flag, wing settle. Two
  954. loops minimum in the environment.
  955. 2. **Locomotion.** Distance-driven walk, run, hop, flap or slither, with feet
  956. planted and joints filled.
  957. 3. **Action.** A readable wind-up, contact and recovery: fire, swing, slam,
  958. dive, throw, open, build.
  959. 4. **Reaction.** A directional flinch, hit flash, knockback, stagger or squash
  960. that recovers to the same pose.
  961. 5. **Exit / consequence.** In a combat diorama, a body-specific collapse plus
  962. debris, dropped gear, a ground stain and a brief residue — never a generic
  963. sphere burst. In a social diorama, the equivalent is a role-specific exit:
  964. turn, walk out with the bag, close the shutter, or sit back down. The scene
  965. must show that the actor changed the place.
  966. Background actors need 1, 2 and 5. Hero actors need all five. A tower is an
  967. actor too: idle hum, aim, fire, recoil, reload. A service actor's action is
  968. order/pay/receive, its reaction is a look-up or step-back, and its exit is the
  969. walk-out with the prop. A prop with a moving part (door, flag, wheel, pulley,
  970. cauldron) needs its own loop.
  971. **Motion is data.** Author beats as absolute times or travel distances, then
  972. read them at `t`. Do not hide a state machine inside render-frame conditionals;
  973. it will pop on a seek, drift on a loop, and be impossible to screenshot.
  974. **Nothing at hero scale is static.** A tower that spawns a projectile from its
  975. centre without recoil, a boss that stands at a door without touching it, a
  976. creature that slides without a step: all read as unfinished, even with good
  977. geometry.
  978. ## Numbers That Make It Read
  979. | Knob | Value | Why |
  980. | --- | --- | --- |
  981. | Camera | fov 20.5, az 45, elev 33 | long lens, near-ortho miniature |
  982. | Framing | `fillX 0.84–0.94`, `fillY 0.86–0.94` | fit margin only: slab plus landmark tops |
  983. | Subject scale | `1.0`, or `0.70` for 30% smaller | post-fit camera multiplier; never geometry |
  984. | Camera distance | solved, 5 to 300 | bisection; actual distance = fit / subjectScale |
  985. | Post buffer | 1× CSS; 1.2–1.5× for a small subject; 2× faces | extra detail without resizing the diorama |
  986. | Palette | 64 entries (any N, but the shader array and loop must match) | skin, stone, asphalt, glass, livery, props |
  987. | Dither | `d*(0.0012 + 0.019*gate) + sparkle*0.0012` | stipple in ramps only; gate = edge |
  988. | Ink | `smoothstep(0.13,0.34,edge)`, mix 0.62 | outline without scribble |
  989. | Palette tie-break | `secondD-bestD < 0.0005` → lighter | flat surfaces come out flat |
  990. | Sun | `0xfff8ee` at 3.3, hemi 0.24, fill 0.46, env 0.18 | hard shadows, cool fill |
  991. | Shadow cam | ±13, near 4, far 70, 2048 map, bias -0.00022 | tight around the whole slab, no acne |
  992. | Figure | 1.69 m, hip 0.86, head 0.584 | toy proportions that read |
  993. | Car | L 4.4, W 1.86, belt 0.90, roof 1.44 | door 1.30, leaf sits between 0.34 and 0.90 |
  994. | Scooter | wheel r 0.26, board 0.30, seat 0.83, bars 1.06 | boots and hands land on built surfaces |
  995. | Loop | 41 to 47 s | one robbery beat plus police, and a quiet seam |
  996. The table mixes two different kinds of number, and treating them alike is how a
  997. new subject comes out wrong.
  998. **Pixel-preset invariants.** The camera/palette/post values here belong to the
  999. pixel look, not approved stroked-toon builds. They hold on every pixel subject: azimuth 45,
  1000. elevation 33, fov 20.5; one deterministic reset hero pose for QA plus user orbit; palette discipline
  1001. (every material samples a palette entry, the shader array length equals the
  1002. palette length); gated dither, ink at 0.13/0.34 mixed 0.62, the palette tie-break;
  1003. the rig's proportions and joint signs; 2048 shadow map with a frustum tight to
  1004. the slab; everything a pure function of `t`.
  1005. **Calibrated.** Measured against one subject and only evidence for it: palette
  1006. count (64 for the bank job, 66 here), buffer size and renderScale (1×/1.25×/2×),
  1007. `fillX`/`fillY`, `subjectScale` and the camera `size` divisor, slab dimensions
  1008. and deck height,
  1009. loop length, sun and hemisphere intensities, and every prop dimension in the
  1010. vehicle and scooter rows. Re-derive these per build: start from the value, then
  1011. look at a screenshot and change it.
  1012. A scene may change any calibrated number if the subject needs it; change the
  1013. template and `DESIGN.md` in the same edit and record the reason. A template that
  1014. silently uses a 2x different sun is worse than no template, because the next
  1015. reader trusts it.
  1016. ## Pipeline
  1017. Each step ends in something you can look at. Settle the render preset through the
  1018. `Render Preset Gate` before step 1 — one question at project start, not a mid-build
  1019. decision. In a confirmed `stroked-toon` or `pixel-stroke` build, steps 1–4 use the
  1020. authored colour family, fitted long-lens camera, toon lighting and
  1021. `templates/stroked-toon.js` recipe instead of pixel snap/dither/Sobel post. Steps
  1022. 5–10 still apply; use preset-aware QA.
  1023. 1. **Palette first.** The palette array in `palette.js` plus a named `C` map.
  1024. Every material samples a palette hex, nothing else. Done when a grep for
  1025. colour literals in `materials.js` finds only palette names.
  1026. 2. **Frame the slab.** Camera constants from `templates/camera.js`, slab sized so
  1027. its projected diamond leaves a margin. Done when a grey slab shot has roughly
  1028. 25 to 40 percent white around it at `subjectScale: 1.0`; for a smaller subject,
  1029. apply `subjectScale` after the fit and expect more paper, not a smaller set.
  1030. 3. **Light it.** Sun plus low hemisphere for daylight; the **Night, Practicals
  1031. And Headlights** rig for a night scene. Tighten the shadow camera to the slab
  1032. and call `updateProjectionMatrix()` after changing the frustum. Done when every
  1033. figure has a readable contact shadow (crisp by day, a soft pool by night).
  1034. 4. **Post pass.** `templates/post.js`: gamma, grade, ink, gated dither, palette
  1035. snap, rim dither. Done when a 1:1 crop shows square pixels and a dark contour,
  1036. and flat pavement shows no speckle.
  1037. 5. **Props.** Start with flat-colour boxes and lathes, coarse detail and no
  1038. textures hiding weak geometry. This is the initial silhouette pass, not the
  1039. finished detail target. Done when the 1:1 crop reads the object without colour;
  1040. step 7 adds construction and story. Approved toon may then add restrained
  1041. decals or grain as described in its recipe.
  1042. 6. **Cast.** `templates/peopleModel.js` (base) or `templates/peopleModel-street.js`
  1043. (clothed) rig, one entry per figure with a base pose. Done when isolated portraits show no gaps, no floating parts, knees
  1044. bending the right way.
  1045. 7. **Detail pass.** Apply the Detail Bar to every hero object: construction
  1046. layers, attachment, story detail, contact shadow. Done when the object meets
  1047. its row's minimum (5 prop, 6 tower, 8 creature, 8 landmark), has one
  1048. asymmetry and one story detail. "Three assemblies" is a blockout; it is not
  1049. a pass. Do not animate a placeholder.
  1050. 8. **Animation and systems.** Locomotion, idle, tower/machine actions, reactions,
  1051. exits/deaths, goal contact, crowd variation. Done when each hero actor has all five
  1052. animation layers and each tower has acquire/fire/impact/recovery.
  1053. 9. **Effects.** Contact shadows, smoke, splash, spill light, debris. Done when the
  1054. effect is visible but never the subject.
  1055. 10. **QA.** Detail and animation audit, `qa/audit.mjs` for seams/glows/fades,
  1056. camera/render scale, exits and emitters, desktop/iPad/phone, `file://` standalone,
  1057. zero page errors, motion and camera proven from numbers and strips. See
  1058. Verification.
  1059. ## New Subject Intake
  1060. A new subject is not a new pile of props. Before modelling, fill this sheet.
  1061. Copy `templates/DESIGN.md` into the project and keep it in sync with the code.
  1062. ```
  1063. PREMISE
  1064. [place] + [a repeated verb/ritual] + [who or what interrupts it] + [payoff].
  1065. One sentence. If it has no verb, it is a shelf model, not a diorama.
  1066. CAMERA SIDE
  1067. Which face is +Z? Where is the threshold, the hero tower, the foreground prop?
  1068. Which silhouette must never be occluded from this angle?
  1069. CAST SHEET
  1070. role | silhouette feature | locomotion | action | reaction | exit/death | signature
  1071. ...
  1072. SYSTEM SHEET
  1073. loop length | three or four systems | crew | three or four visitor roles |
  1074. goal/disruption (optional) | economy/score (optional) | what changes
  1075. BEAT SHEET (absolute seconds)
  1076. 0.0 establish / portal / doors
  1077. ... first signal, first system output, first consequence
  1078. ... disruption reaches the goal (or the last customer arrives)
  1079. ... contact / handoff / finale, residue, loop seam
  1080. DETAIL BUDGET
  1081. systems n x parts | vehicles n | creatures/people n | props n | landmark n |
  1082. exits/deaths n | ambient loops n | triangle / draw-call ceiling
  1083. ```
  1084. Rules that keep a new subject from becoming a blockout:
  1085. - **Invent the conflict.** If the user says "a diorama of a lighthouse", decide
  1086. what the lighthouse does, who arrives, what goes wrong, and what the keeper
  1087. does about it. A subject plus a verb is a diorama.
  1088. - **Give every machine an operator.** If a tower, loom or pump needs a crew,
  1089. model the crew and decide what happens when they die: the machine slows, stops,
  1090. or runs unmanned with a visible consequence. A gun that fires itself while its
  1091. crew lies dead is a ghost. If the machine is autonomous, say so in the sheet.
  1092. - **Choose five signature moments before modelling.** Establish, first system
  1093. output, first consequence, goal/handoff contact, final residue. A social diorama
  1094. may use establish, ritual, disruption, handoff, residue. Every object earns its
  1095. place by serving one of those five.
  1096. - **Stage for the hero camera.** Put the threshold and the hero action on the
  1097. +Z face; put tall landmarks at the back but offset in screen x so they do not
  1098. stack. Put one foreground prop at the near corner for depth and one mid-ground
  1099. prop to lead the eye.
  1100. - **Blockout in grey first.** Boxes, cylinders and the camera, no palette, no
  1101. post. Shoot 1:1. If the five moments do not read in grey, detail will not save
  1102. them. Redesign the staging, not the textures.
  1103. - **Name every hero object.** `totem`, `hayCart`, `gatehouse`, `troll`, not
  1104. `prop12`. Unnamed objects become clutter because nobody owns their silhouette.
  1105. - **One boss goal, one tower verb.** The boss must visibly act on a place
  1106. (door, bridge, pump, nest); the tower must visibly act on a target (pierce,
  1107. blast, freeze, chain). Repeat the verbs with variation, not new nouns.
  1108. - **Write the QA timestamps now.** Pick the five frames you will inspect before
  1109. you build them. If you cannot name a timestamp for a beat, it is not staged.
  1110. ### Reference Density
  1111. The Hollow Toll shipped at this density. Use it to calibrate a new subject; a
  1112. smaller subject should have fewer objects at the same detail per object, not
  1113. fewer details per object.
  1114. | Measure | Value |
  1115. | --- | --- |
  1116. | Slab | 21 x 14 x 0.42 m, 64-colour palette |
  1117. | Towers | 4 + 2 gate cannons |
  1118. | Species | 5 (goblin, orc, slime + split, bat/imp, troll) |
  1119. | Units | 42, one boss |
  1120. | Combat events | 527 |
  1121. | Tower shots | 183 |
  1122. | Scene meshes | ~3,100 |
  1123. | Triangles | ~164,000 |
  1124. | Scene draw calls | ~1,700 at 1440 x 900 |
  1125. | Textures | 5 |
  1126. | Loop / sim | 46.0 s at 40 Hz pre-sim |
  1127. | Standalone | ~783 kB with three.js inlined |
  1128. A 12 x 9 m scene with two towers and three species should land around
  1129. 1,000 to 1,600 meshes and 60 to 100k triangles. Raw count is not the goal;
  1130. the detail per hero object and the number of readable beats are.
  1131. ### Worked Example: The Hollow Toll
  1132. This is the reference build the numbers above come from. Read it as a calibration
  1133. of **what "finished" looks like**, not as a scene to copy.
  1134. - **Set.** A 21 x 14 m slab, purple portal at the back-left, winding road, goblin
  1135. camp, moat and drawbridge, gatehouse at the near-right. Four towers and two
  1136. gate swivels; keep gate faces +Z.
  1137. - **Cast.** 14 goblins, 4 orcs, 7 slimes plus 10 split slimelets, 6 imps and one
  1138. Toll-Troll: 42 units, 5 death grammars, one boss goal.
  1139. - **System.** 46 s loop at 40 Hz, 527 events, 183 shots. Ballista single target,
  1140. bombard splash, frost lance channel, tesla chain, gate swivels on the last
  1141. stretch. The troll reaches the gate at 38.6 s and hits it eight times.
  1142. - **Detail.** The gatehouse has a plinth, two towers, crenellations, a gate arch,
  1143. door leaves with cracks, two swivel cannons, banners and torches. The skull
  1144. warning tree has a trunk, fork, trophy board, horned skull, rope collar, bone
  1145. chimes, rags, tally marks and roots. The hay cart has a bed, slats, two spoked
  1146. wheels with iron tyres, corner straps, three tied bales, loose straw, a
  1147. pitchfork, a sack, a rag and two shafts.
  1148. - **Animation.** The frost spire pulses, flares at the crystal, holds a scrolling
  1149. band lance, ramps heat, and shuts off on the target's death. The troll stops
  1150. outside the threshold, turns three-quarter, swings an iron-banded maul, and
  1151. drives the door flash, shake and cracks from the same gate-hit timestamp.
  1152. Every species has its own collapse and debris.
  1153. Fixes that became rules in this file:
  1154. | Report | Root cause | Rule |
  1155. | --- | --- | --- |
  1156. | "rocks flying out of the entrance" | camp smoke billboards above the portal | clear the threshold of smoke, props and fireflies |
  1157. | troll inside the gatehouse | stop at `length - 1.05`, body through wall | stop at body depth + weapon reach; keep the door visible |
  1158. | club looked like a rock | end-on pose, haft hidden, no bands | yaw 0.35 rad, build haft + bands + studs, sync contact |
  1159. | beam had a black segment | black backing plate in the additive beam texture | clear the canvas; transparent gaps, never black |
  1160. | deaths were spheres/rocks | generic burst | species collapse + debris + dropped gear + residue |
  1161. | skull tree looked like a monster | a second totem overlapped the tree | one landmark per silhouette; mount the skull on a board |
  1162. | cart looked like a blob | pale spheres in an open box | five-part prop: bed, slats, wheels, load, tools, story |
  1163. | standalone broke over `file://` | `String.replace` expanded `$&` in the bundle | function replacer; test the standalone |
  1164. A new subject should copy the **density and audit discipline**, not these nouns.
  1165. A lighthouse, market or launch pad needs the same number of readable systems,
  1166. the same five animation layers and the same proof frames.
  1167. ### Worked Example: Night Market
  1168. The social-scene calibration: no combat, no boss, no deaths. A food truck, a
  1169. queue, a courier, one scooter and a cat. It proves the same discipline applies to
  1170. a life scene.
  1171. - **Set.** 21 x 14 x 0.42 slab; truck at (0.15, -3.35) with the hatch facing +Z;
  1172. counter at z 1.10; parked scooter at (5.55, -0.72) facing +Z; bench, rail,
  1173. lamps, bins, service block behind. Camera azimuth 45, elevation 33, fov 20.5,
  1174. fill 0.93.
  1175. - **Cast.** Cook, cashier, customers A/B/C, courier, late customer D, cat. The cat
  1176. is an actor with its own idle, walk, sit and tail loop, not set dressing.
  1177. - **Systems.** Grill flare, order rail, bag pass, scooter dispatch. Four readable
  1178. systems, no towers.
  1179. - **Loop.** 46 s at 40 Hz. Queue forms 0–16 s; four paper bags + one insulated
  1180. bag; courier loads 21.2–22.5, mounts 22.7–23.5, departs 23.5–27.3; D arrives
  1181. 26.0–33.4, last bag 34.0, exits 34.8; quiet seam 40–46.
  1182. - **Scale.** The user asked for 30% smaller. The fix was `subjectScale: 0.70`
  1183. after the fit (`distance = fit / 0.70`), not scaling the slab, cast or canvas;
  1184. geometry scaling breaks the world clip and shadow maps, and shrinking the
  1185. canvas breaks the 1:1 crops. Backing buffer 2x CSS for the faces, CSS
  1186. downscale.
  1187. - **Proof.** Nine 1280x800 frames plus two close strips: courier mount, D walk.
  1188. The strip camera was a fixed side view, not the hero camera.
  1189. Fixes that became rules in this file:
  1190. | Report | Root cause | Rule |
  1191. | --- | --- | --- |
  1192. | "the building bottom/right is cut" | slab edge/backdrop closed too tight | close side walls and undersides; camera fit includes the slab corners |
  1193. | "bike lights look unnatural" | large additive disc | emissive lens + small halo; cone only at night |
  1194. | "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 |
  1195. | "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 |
  1196. | "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 |
  1197. | "carry the bags more human-like" | prop at root, hands nearby | two-hand hold at the prop's top, object origin at its bottom |
  1198. | "no text outside the diorama" | DOM overlay on the paper | empty-paper rule; copy on modelled signs only |
  1199. | "30% smaller" | scaling the scene | move the camera; keep world clipping and shadow scale |
  1200. | "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 |
  1201. | "single human slides near the shop" | standing gesture blended during walk | gate gestures on `!state.moving`; serve after arrival |
  1202. A new subject should copy the **timing discipline and contact logs**, not the
  1203. food truck. A pool, a station or a bakery needs the same queue/service,
  1204. carry/load and close-up proof.
  1205. ## Palette And The Post Pass
  1206. `templates/post.js` renders the scene to an offscreen target, then a full-screen
  1207. shader turns it into pixel art. Order matters; each stage assumes the last.
  1208. 1. **Coverage gather.** ~12 taps in a small disc read alpha, so the silhouette can
  1209. be softened and stippled without blurring the interior. The target is
  1210. transparent outside the slab.
  1211. 2. **Composite onto paper.** `mix(vec3(1.0), c, smoothstep(0.26, 0.72, cov))`.
  1212. 3. **Gamma.** `c = pow(c, 1/2.2)`. The target is linear; skip this and the frame is
  1213. dark and muddy, which reads as a lighting bug.
  1214. 4. **Grade.** Saturation 1.07 and contrast 1.028 *before* quantising, or the snap
  1215. flattens everything to mid tones.
  1216. 5. **Ink.** Neighbour luma differences, `edge = max(abs(d))`, brought to display
  1217. scale with `pow(edge, 0.4545)`, then
  1218. `ink = smoothstep(0.13,0.34,edge) * smoothstep(0.20,0.55,cov) * (1 - smoothstep(0.86,0.985,cov))`
  1219. mixed 0.62 toward `vec3(0.085,0.082,0.076)`.
  1220. 6. **Dither, gated.** `d = bayer8(gl_FragCoord.xy) - 0.5`,
  1221. `gate = smoothstep(0.004,0.055,edge)`,
  1222. `c += (d*(0.0012 + 0.019*gate) + sparkle*0.0012) * uDither`. Keep `uDither` as a
  1223. uniform: it is the fastest way to prove whether a speckle is the dither.
  1224. 7. **Palette snap.** Nearest entry with channel weighting `(1.0, 1.12, 0.93)` so
  1225. greens do not beat skin. Keep the runner-up and break near-ties toward the
  1226. lighter entry, or a surface halfway between two entries flips entry per pixel
  1227. on the dither noise and stipples a whole pavement.
  1228. 8. **Rim dither.** Where coverage is 0.78 to 0.995, threshold against Bayer so the
  1229. cut-out edge is stippled, not anti-aliased.
  1230. The palette length is a shader constant: `uniform vec3 uPalette[N]` in the
  1231. fragment source and the JS array must be the same length. A mismatch loses the
  1232. last colours or reads out of bounds, and the symptom is a colour that "does not
  1233. exist in the palette" appearing on screen.
  1234. ### Tuning Table
  1235. | Symptom | Cause | Fix |
  1236. | --- | --- | --- |
  1237. | Water looks like TV static | dither ungated | add the edge gate |
  1238. | Frame dark and muddy | missing gamma | `pow(c, 1/2.2)` before grade |
  1239. | Everything mid-grey | no grade before snap | saturate 1.07, contrast 1.028 |
  1240. | Scribble outlines | ink threshold too low | 0.13 / 0.34 |
  1241. | Missing outline on figures | rim suppression too wide | narrow to 0.86 / 0.985 |
  1242. | White speckle on flat deck | material grain aliasing | cut grain, not resolution |
  1243. | Bands with hard edges | palette hole | add 4 to 6 intermediate entries |
  1244. | Speckle only where a tone sits between entries | palette tie | break near-ties toward lighter |
  1245. | Speckle at zero dither | sub-pixel geometry | widen detail to ~1.5 px or delete it |
  1246. | Beam goes flat or vanishes on paper | additive white over white | saturated palette core + dark halo; fade before the edge |
  1247. | Glow disappears after the snap | sub-pixel or pure-white FX | widen to 2 px+, use a palette entry, add a contour |
  1248. | Beam ends in a hard vertical cut | world clip plane on a read-through FX | taper intensity to zero before the slab edge |
  1249. | Flame reads as a grey smudge | normal-alpha smoke over a bright source | lighten/remove smoke in the flame corridor, draw flame last |
  1250. Isolate noise in this order and stop at the first that removes it: dither
  1251. uniform to 0 → widen or delete sub-pixel geometry → disable `shadowMap`. Judge on
  1252. a 1:1 crop; a downscaled preview softens all three into "texture".
  1253. ### Resolution
  1254. Default: `setSize` renders one target pixel per CSS pixel, capped by `maxDim`
  1255. (1600), and CSS `image-rendering: pixelated` handles the upscale. The chunky
  1256. look comes from the palette snap and the ink, not from a low buffer.
  1257. When the diorama is deliberately small on the page (`subjectScale` under ~0.8),
  1258. raise the buffer **a little** instead of enlarging the subject:
  1259. `new PixelPost(renderer, 2000, 1.25)` renders 1.25 target pixels per CSS pixel;
  1260. at a 1312 × 760 CSS canvas that is a 1640 × 950 buffer, CSS still 1312 × 760.
  1261. The post pass quantises at the finer grid and the browser downsamples; the page
  1262. size, camera solve, slab and clip do not move. 1.2–1.5× is the useful range; 2×
  1263. on a full arena is usually a frame-rate tax, not more art. Log `post.size` and
  1264. `canvas.getBoundingClientRect()` and check a 1:1 crop for shimmer.
  1265. For faces and close-up contact beats, use `renderScale: 2` and
  1266. `image-rendering: auto` (not pixelated), with `maxDim` high enough (2400) to
  1267. avoid the cap. The post pass still quantises at 2×; the CSS downscale is a clean
  1268. box filter, not a change to the art. Keep the CSS size as the layout size so the
  1269. camera solve and the 1:1 QA crops stay comparable. Re-run the portraits after
  1270. any resolution change: raising the buffer exposes hats, stripes and noses that
  1271. hid at the old grid.
  1272. ## Camera And Framing
  1273. ```js
  1274. CAMERA = { fov: 20.5, azimuth: 45°, elevation: 33°, target: (0,-0.15,0),
  1275. fillX: 0.84, fillY: 0.86,
  1276. subjectScale: 1.0 } // 0.70 = 30% smaller, more paper
  1277. ```
  1278. The distance is solved, not typed: build a direction vector from the angles,
  1279. project each fit point (slab corners at deck and underside, plus the tallest
  1280. building corners) into camera axes, and bisect the distance until every point's
  1281. `|x|/(depth*tan*aspect)` and `|y|/(depth*tan)` fit inside `fillX` and
  1282. `fillY`. 48 iterations is plenty. `fillX`/`fillY` are the **fit margin**, not the
  1283. page-size control; tune them together, because raising one alone crops the other
  1284. axis on a portrait phone.
  1285. **Subject scale is a second, post-fit move.** Solve the fit first, then pull the
  1286. camera back:
  1287. ```js
  1288. const fit = solveDistance(aspect, points);
  1289. const scale = CAMERA.subjectScale ?? 1;
  1290. const distance = fit / Math.max(0.1, scale);
  1291. camera.userData.fitDistance = fit;
  1292. camera.userData.subjectScale = scale;
  1293. camera.userData.distance = distance;
  1294. ```
  1295. `subjectScale: 0.70` renders the diorama at 70% width/height — 30% smaller
  1296. linearly and about 49% less screen area — so the paper margin grows. `1.0` is the
  1297. fitted size. Keep the slab, cast, world clip, shadow camera, CSS canvas and
  1298. frame at full size; raise the backing buffer only with `renderScale` (next
  1299. section), never by scaling geometry. Shrinking the geometry also shrinks contact
  1300. shadows and the clip volume; shrinking the frame/canvas changes the 1:1 crop
  1301. and does not change the model's scale. **Move the camera.**
  1302. A phone is already height-limited, so 0.70 can make the trucks unreadable. Try
  1303. 0.70, then 0.80–0.90 if needed; the scale is per scene, not a universal 30%.
  1304. **Verification.** Log both distances and assert
  1305. `actualDistance ≈ fitDistance / subjectScale` within 2%. Also project the slab
  1306. and compare its width to the fitted width: the ratio must be the scale, not just
  1307. the distance. On Dust Kings at 1.73 aspect: fit 67.93, scale 0.70, actual 97.05;
  1308. projected slab width 872 → 611 px (0.70), with slab, clip and shadows unchanged.
  1309. `updateCamera(camera, aspect)` on every resize and orientation change, with a
  1310. debounced call after `orientationchange`. A canvas measured at under 2 px is a
  1311. layout race: return early rather than dividing by zero.
  1312. ## Scene Furniture
  1313. - **Slab** 21 x 14 x 0.42 with the street on the camera side (+Z) and the
  1314. building block at the back (-Z) for an exterior. For an interior cutaway, see
  1315. **Cutaways And Glass** before placing the street. Deck at y 0 is the street;
  1316. the pavement is a raised 0.16 slab with a kerb face.
  1317. - **Pavement joints** 2.6 m apart, 0.085 m wide. Anything thinner rasterises to
  1318. dots that read as noise. `groundY(x,z)` returns street, pavement or step height
  1319. so every track and shadow samples the same function.
  1320. - **Buildings** are boxes with a parapet, a sign band, recessed windows and a
  1321. door pivot. At 33 degrees you look down onto roofs: a 4.6 m wall in front of a
  1322. 5.2 m deep building hides none of its roof, so model the parapet, plant,
  1323. skylight or stair head, or keep it lower than it is tall.
  1324. - **Doors** are pivots at the jamb with the leaf extending into the opening.
  1325. Recess them 0.15 so the opening shows a shadow gap, and light the interior so
  1326. an open door reads as a room, not a hole.
  1327. - **Contact shadows** are one unlit radial-gradient plane per figure, opacity
  1328. 0.55 to 0.95, scaled to the footprint, 0.018 above the ground it belongs to.
  1329. ### Night, Practicals And Headlights
  1330. Night is a new light ratio and a new palette, not the day rig dimmed. The sun
  1331. table is a daylight default; a 2am scene needs its own numbers and its own test.
  1332. | Key | Night default | Why |
  1333. | --- | --- | --- |
  1334. | moon / key | `0x93a7c4` at 0.45 to 0.65 | cool, low, soft shadows |
  1335. | hemisphere | sky `0x1b2740`, ground `0x090b12`, 0.16 | blue ambient, never black |
  1336. | fill | `0x6d7f9e` at 0.10 to 0.16 | keeps the shadow side readable |
  1337. | practical | `0xffb066` at 1.0 to 1.4 | warm bulb/lamp, 2700 K |
  1338. | pool | unlit radial plane, opacity 0.28 to 0.45 | light on the ground, cheap |
  1339. | headlight | `0xfff0c8`, lens + cone + floor ellipse | source, throw and landing |
  1340. - **A practical is an object, not a glow.** Bulb sphere, shade/guard, bracket,
  1341. emissive lens, small halo, and a pool on the surface below. A floating halo with
  1342. no fixture reads as a firefly.
  1343. - **Use one real point light at the hero practical**, not one per bulb. The rest
  1344. are emissive + pool decals. Ten point lights flatten the darks and cost more
  1345. than they return.
  1346. - **Keep three dark values.** Deep shadow, mid shadow and lit edge must be
  1347. different palette entries; if the night is one black silhouette, lift the
  1348. hemisphere or add a cool rim. `0x000000` is forbidden, as in daylight.
  1349. - **Headlights are a moving pool, not a global spotlight.** Two lenses, two
  1350. tapered cones, one elongated floor ellipse that travels with the vehicle.
  1351. Do not let the cone light the whole facade: it will read as dawn.
  1352. - **Windows are dark glass with a warm interior.** A blue-grey pane, two
  1353. reflection streaks, and a visible warm room behind it. A fully transparent
  1354. plane tints the whole interior and kills the cutaway.
  1355. - **Grade for night after the snap:** lift black to about `0x0b1020`, keep warm
  1356. highlights from clipping. Test a 1:1 crop: three dark values, a visible source,
  1357. a readable pool, no white blob.
  1358. A night scene passes when the unlit areas still have shape and the light sources
  1359. are in the frame. "It is dark" is not a pass.
  1360. ### Cutaways And Glass
  1361. The +Z street convention is for an **exterior**. If the hero action is inside a
  1362. shop and the street is between the camera and the hero, the bus/traffic will
  1363. occlude the beat. Choose one:
  1364. - **Exterior scene:** street on +Z, facade behind it, action on the pavement.
  1365. - **Interior cutaway:** omit the camera-side wall entirely (or keep a 0.25 m
  1366. header and sill), put the street **behind** the room at -Z behind glazing, and
  1367. keep the camera-side floor open. The room is the stage; the street is the
  1368. cyclorama.
  1369. - **Foreground traffic:** allowed only if it crosses before or after the hero's
  1370. contact beat; check the occlusion frame, not just the still.
  1371. For glazing, build the frame, mullions, sill and a few reflection streaks. Do not
  1372. lay one transparent plane across the opening: it tints the interior, hides the
  1373. practical lights and turns the cutaway into a fish tank. If the bus must read
  1374. through the glass, give it lit windows and a dark body against the warm interior;
  1375. do not brighten the whole room to compensate.
  1376. ## Detail Recipes
  1377. Detail is a hierarchy, not a texture. Build in this order and stop adding when
  1378. the silhouette is explained.
  1379. ### The Five-Part Prop
  1380. Every readable prop answers five questions with geometry:
  1381. 1. **What touches the ground?** Feet, skids, wheels, a stone base, roots. Add a
  1382. contact shadow at 0.018 above the deck.
  1383. 2. **What holds it up?** Posts, frame, legs, axle, brace. This is the
  1384. construction layer and it must be visible from the camera.
  1385. 3. **What is its working surface?** Planks, slats, a lid, a blade, a trough, a
  1386. table. Divide it into pieces; a single slab reads as a box.
  1387. 4. **What attaches the parts?** Rope, iron straps, nails, hinges, lashings,
  1388. rivets. Two or three are enough; a row of identical studs is noise.
  1389. 5. **What is the story?** Contents, a tool, a repair, a trophy, a rag, wear on
  1390. the edge that is used. One or two, placed where the camera sees them.
  1391. A hay cart from the reference build: bed, six side slats, two spoked wheels with
  1392. iron tyres, four corner straps, three tied bales, loose straw, pitchfork, sack,
  1393. red rag, two draft shafts. That is ten assemblies for a prop the user sees for
  1394. two seconds. A crate with a pale sphere inside is none of them.
  1395. ### Tower Anatomy
  1396. A defence tower is a small building, a machine and a crew in one silhouette.
  1397. | Layer | What it adds | Failure if missing |
  1398. | --- | --- | --- |
  1399. | 1 foundation | plinth, steps, rubble, contact | tower floats or looks pasted on |
  1400. | 2 shaft | taper, buttresses, bands, ladder | reads as a cylinder |
  1401. | 3 platform | deck, rail, hatch, brackets | machine has nowhere to stand |
  1402. | 4 machine | weapon, pivot, rail, recoil travel | attack has no origin |
  1403. | 5 crew | gunner, cranks, spotter, ammo | tower feels automated/empty |
  1404. | 6 livery | banner, number, pennant, paint | tower has no owner |
  1405. | 7 wear | scorch, chips, rope, spent cases | tower looks unplaced |
  1406. The animation pivot belongs to layer 4. The muzzle or launch point belongs to
  1407. the weapon, never the tower centre. Recoil travel is 0.1 to 0.25 m for a ballista
  1408. or cannon, 0.02 to 0.06 for a beam crystal. A tower with no recoil, no crew and
  1409. no ammo is a monument.
  1410. **A hollow object must show its opening.** A cannon with a solid brass cap is a
  1411. baton, not a gun; the same failure turns a pipe into a rod, a chimney into a
  1412. post, a lamp into a mushroom and a tunnel into a painted arch. Build the opening
  1413. as geometry, not a dark decal:
  1414. - replace the end cap with one or two **open-ended collars** (no front face);
  1415. - add a recessed **dark bore tube**, open at the mouth, with its inner wall
  1416. visible (`DoubleSide` on a cloned material, never on the shared palette
  1417. material);
  1418. - close the back with a **dark disc** so the barrel interior is not see-through;
  1419. - add an **iron inner lip ring** and a **brass outer lip ring** so the edge
  1420. catches the light at 1:1;
  1421. - put the muzzle/effect origin at the lip, not inside the bore.
  1422. At 1:1 the opening needs a dark centre at least 5 to 6 px across and a lit lip.
  1423. If the centre is brass, the hole failed.
  1424. **A rotating assembly owns only its moving parts.** The yaw/turret group may
  1425. contain the carriage, barrel, recoil slide and muzzle. Fixed stores — powder
  1426. keg, shot pile, rammer, tools, ready rack, crew — belong to a static group on the
  1427. tower root, never the yaw group. If they are children of the yaw group they sweep
  1428. around the tower when it tracks a target, which reads as the whole gun deck
  1429. rotating.
  1430. Do not simply reparent the props at deck height: the barrel and carriage sweep
  1431. through that volume at some yaw. Put them outside both the yaw sweep and the
  1432. barrel's vertical arc. If the deck has no clear sector, bolt a ready locker to
  1433. the outer wall below the deck: shelf, two iron brackets, powder chest with corner
  1434. straps, shot tray, and a rammer hung on two hooks. It reads as part of the tower
  1435. and never collides.
  1436. Test two ways at minimum and maximum yaw: each fixed child's world position
  1437. delta must be 0, and each fixed mesh's world bounding box must not intersect any
  1438. mesh under the yaw group. Both checks pass, or the station is still in the arc.
  1439. Worked example, Bombard Bastion: 17 fixed parts — shelf, two iron brackets,
  1440. powder chest, lid, two corner straps, rope handle, shot tray, tray lip, three
  1441. iron shot, rammer shaft, iron cap and two wall hooks. It sits at y 1.1 to 1.6 on
  1442. the outer shaft, below the deck and outside the barrel arc. At both yaw extremes
  1443. all 17 world positions are identical and the station has zero bounding-box hits
  1444. against the yaw group.
  1445. ### Creature Anatomy
  1446. A creature needs a silhouette feature before it needs a face.
  1447. 1. **Core mass.** One dominant volume: hunched torso, round slime, long bat.
  1448. 2. **Silhouette feature.** Horns, ears, hump, wings, tail, crest, antlers. This
  1449. is what the user recognises at 30 px.
  1450. 3. **Face.** Two eyes, brow, jaw or beak. Eye sockets must be dark and set in,
  1451. not painted on the surface.
  1452. 4. **Limbs.** Joint groups with fillers; hands and feet larger than anatomy
  1453. suggests, or they disappear at this scale.
  1454. 5. **Gear.** One weapon, one strap, one trophy. Not a full armour set.
  1455. 6. **Colour break.** One hue for skin, one for cloth, one metal accent.
  1456. 7. **Asymmetry.** A chipped horn, a single pauldron, a dragging club. Perfect
  1457. symmetry reads as a toy soldier.
  1458. The boss gets 40 to 60 parts and one signature weapon. Build the weapon as a
  1459. separate group with a haft, head, bands, studs or spikes, and a hand attachment.
  1460. A stone head with no haft reads as a rock floating at the door.
  1461. ### Small Quadrupeds (Cats, Dogs)
  1462. A cat is not a small human on all fours. Build a horizontal spine and four
  1463. contact legs; the silhouette is the back line, ears and tail.
  1464. - **Body:** chest sphere r 0.085 at y 0.24, belly capsule 0.24 long, hip sphere
  1465. r 0.080. Shoulder height 0.26, nose-to-tail base 0.46. A cat at human scale is
  1466. about 0.25 m at the shoulder; measure, do not scale a person by 0.2.
  1467. - **Head:** skull r 0.075, muzzle 0.045 forward, jaw, nose, two triangular ears
  1468. (cones or three-vertex prisms) at the top corners. Eyes face forward with a
  1469. dark socket and a vertical pupil; at 30 px the ears and pupils carry the read.
  1470. - **Legs:** four chains (upper 0.10, lower 0.11, paw 0.05). Front legs are
  1471. straighter; rear legs have a hock that bends backward. Paws land flat, toes
  1472. forward. Do not use the human knee sign for a hock.
  1473. - **Tail:** four to six segments with a slow S-curve, root at the sacrum. It
  1474. counter-sways against the walk and curls when sitting; a rigid stick tail is
  1475. the fastest way to lose the animal.
  1476. - **Walk:** lateral-sequence four-beat, phase offsets roughly LF 0, RH 0.25,
  1477. RF 0.5, LH 0.75. The spine dips and rises twice per cycle; the head stays
  1478. level. Drive phase from distance travelled, like the bipeds.
  1479. - **Sit:** haunches down, rear hocks folded, front legs straight, chest up, tail
  1480. curled around the paws. A sitting cat is a triangle, not a crouched person.
  1481. - **Jump:** crouch (hips down, spine compressed), extend (all four legs push),
  1482. airborne (legs tucked, tail up), land (front paws first, then rear). Two
  1483. seconds of anticipation and recovery, not a linear hop.
  1484. - **Fur:** one base colour, a lighter chest/muzzle, darker ears/tail tip and two
  1485. or three stripe bands. Do not model individual hairs; the palette snap eats
  1486. them. Contact shadow is one stretched ellipse under the body, not four paw
  1487. blobs.
  1488. Shoot the cat at 1:1 in profile, three-quarter and sitting. If it reads as a
  1489. rabbit, the ears are too long; if it reads as a dog, the muzzle is too broad and
  1490. the back line too straight. No gear, no trophy, no human jacket.
  1491. ### Environment Anatomy
  1492. - **Three scale cues.** One small (grass, bones, cobbles), one human (cart,
  1493. barrel, spear), one tall (tower, tree, gate). Without all three the slab has
  1494. no scale.
  1495. - **Three story props.** A camp, a repair, a warning, a toll, a shrine. Place
  1496. them off the main path but inside the camera cone.
  1497. - **Two ambient loops.** Fire, flag, smoke, fireflies, grass, water, hanging
  1498. bones. Phase them differently; synchronized loops read as a screensaver.
  1499. - **A path with a memory.** Ruts, footprints, dropped goods, a worn threshold.
  1500. A clean path is a diagram.
  1501. - **A boundary treatment.** Trees, rocks, posts or a wall that explains why the
  1502. slab ends. Do not let props clutter the threshold.
  1503. ### Detail Audit At 1:1
  1504. Before the animation pass, inspect each hero object at 1:1 and answer:
  1505. - Can I name its three construction layers without guessing?
  1506. - Does it cast a contact shadow and touch the ground?
  1507. - Is there one asymmetry or story detail I can point to?
  1508. - Does it overlap another object of the same silhouette?
  1509. - Is any detail under 1.5 px, and therefore speckle?
  1510. - Does every hollow object — cannon, pipe, chimney, lamp, tunnel — show a real
  1511. opening, or does it end in a cap?
  1512. - Does it read in grey, without colour?
  1513. If any answer is no, fix the object before animating it. Animation multiplies
  1514. detail; it does not create it.
  1515. ## The Cast
  1516. A 1.69 m figure built from primitives, with an anatomical group per joint so
  1517. limbs overlap when they bend. Faces +Z.
  1518. | Constant | Value | Notes |
  1519. | --- | --- | --- |
  1520. | hipY | 0.86 | pelvis group height above the root |
  1521. | hipX | 0.10 | half stance width |
  1522. | thigh | 0.42 | hip to knee |
  1523. | shin | 0.40 | knee to ankle |
  1524. | shoulderY | 0.415 | above the pelvis |
  1525. | shoulderX | 0.182 | half shoulder width |
  1526. | upperArm | 0.30 | shoulder to elbow |
  1527. | foreArm | 0.27 | elbow to wrist |
  1528. | headY | 0.584 | neck to head group |
  1529. The base swimwear rig uses two spheres (cranium 0.115, jaw 0.089) plus a nose
  1530. box. For a clothed cast, replace that with the skull/jaw/cheek head below. Torso
  1531. and pelvis are lathes (0.135→0.198 and 0.105→0.180), flattened 0.72 in Z so the
  1532. body is an oval, not a tube.
  1533. Construction rules:
  1534. 1. Build joint groups at the pivot, hang geometry **down (-Y)** from them, so a
  1535. rotation is an anatomical rotation.
  1536. 2. Every joint gets a sphere filler just inside the limb radius. Without it a 90
  1537. degree bend shows a wedge-shaped hole.
  1538. 3. Limbs are capsules; torso and pelvis are lathes for a tapered silhouette.
  1539. 4. Clothing is layered over the body as its own lathe slightly larger than the
  1540. pelvis or torso, plus a band cylinder at the waist or chest.
  1541. 5. Never parent a part to a group that has not been created yet in the function
  1542. body: straps added before the torso exists throw on load.
  1543. Pose API: `setPose(person, pose)`, `easePose(p, pose, 1-exp(-22*dt))`,
  1544. `blendPose(a, b)` (component-wise add). Angles are `[x,y,z]` radians per joint:
  1545. `torso, head, shoulderL/R, elbowL/R, wristL/R, hipL/R, kneeL/R, ankleL/R`,
  1546. optional `pelvis`.
  1547. **Sign conventions, get these right once:**
  1548. - Facing +Z. Positive hip X swings the thigh **backward**; negative forward.
  1549. - Positive knee X bends the heel **backward**. Negative hyperextends and reads as
  1550. a broken leg. This single sign error is the most common "the walk is broken".
  1551. - Positive shoulder X swings the arm backward, negative forward.
  1552. - Negative elbow X folds the forearm toward the face.
  1553. - Positive shoulder Z abducts an arm away from the body; mirror the sign.
  1554. Detail that pays, in order: the skull/jaw head in **Clothed Cast** (hair cap
  1555. theta 1.22, eyes at ±0.037, 0.110, 0.101); cap as a crown cylinder, band and
  1556. brim; brow and lid creases; a narrow nose bridge; a three-layer mouth; ears as
  1557. flattened spheres; hands as a palm plus a finger block and thumb; feet with a toe
  1558. box. Fingers, nostrils and micro-seams do not survive 30 px.
  1559. Balaclava: one sphere shell over cranium and jaw (r 0.134, scale 1.0/1.10/0.99)
  1560. plus a neck gaiter cylinder running into the collar. A cover cut at the equator
  1561. leaves a band of skin under the hem that reads as a bare head, and eye openings
  1562. tucked under the shell disappear: put pale lids a few millimetres proud of it. A
  1563. darker skin material is `skin.clone()` with `color.multiplyScalar(0.86)`.
  1564. ### Clothed Cast: Heads, Layers, Hands
  1565. The skeleton is shared; the person is made by the head, the garment silhouette
  1566. and the hand contact. For a clothed cast, start from
  1567. `templates/peopleModel-street.js`; `templates/peopleModel.js` remains the
  1568. swimwear/aquatic variant.
  1569. **Head.** A skull plus a jaw, not two stacked balls.
  1570. - Cranium: sphere r 0.100 at y 0.118, scale [0.98, 1.16, 0.98]. Jaw: r 0.079
  1571. at y 0.054, scale [0.78, 0.80, 0.86]; chin r 0.029 at y 0.029, z 0.079.
  1572. - Ears: flattened spheres at x ±0.098, y 0.101, with a darker inner bowl. They
  1573. are what makes the head read in profile.
  1574. - Eyes: a shade socket, a dark iris r 0.0145 scaled flat, a pale catchlight.
  1575. Brow above, lid crease below, cheek plane under that. At 30 px the socket and
  1576. brow carry the expression; the iris just anchors the look.
  1577. - Nose: a narrow bridge box plus a tip sphere, 0.022 wide. A single box reads as
  1578. a beak from three-quarter.
  1579. - Mouth: upper lip in shade, dark seam, lower lip in skin. Three thin layers at
  1580. most; a wide box reads as a letterbox.
  1581. - Hair: a sphere cap with `thetaLength` 1.22, positioned at y 0.132 and stopping
  1582. at the hairline. A 1.85 cap swallows the forehead and reads as a helmet. Add a
  1583. back mass, sideburns, and for a bun a high sphere at y 0.204. Under a hat show
  1584. a nape tuft; under a full helmet show none.
  1585. - Hats are their own silhouette: beanie (dome + rolled torus + pom), cap (crown
  1586. + brim + band), bandana (cap + knot + tail), helmet (shell + visor + chin
  1587. strap + reflective bands). Never draw hair through a helmet or a cap.
  1588. **Clothing is geometry, not paint.**
  1589. - Base body: torso lathe 0.135→0.198, pelvis lathe 0.105→0.180, flattened 0.72
  1590. in Z.
  1591. - Garment: a second lathe 4 to 12% larger (`topK` 1.0 tee, 1.05 jacket, 1.12
  1592. puffer), plus a hem/waistband cylinder. The garment must have a thickness step
  1593. at the cuff, collar and hem or it reads as body paint.
  1594. - Sleeves: short sleeve ends above the elbow with a cuff ring; long sleeve is a
  1595. second lathe down the forearm with a ribbed cuff. Do not texture a bare arm and
  1596. call it a sleeve.
  1597. - Trousers: tapered lathes over thigh and shin with a cuff at the ankle and a
  1598. break over the shoe. Loose trousers get a wider profile and a deeper cuff, not
  1599. a scaled leg.
  1600. - Outerwear: jacket shell + zip/lapel/hem; puffer gets 3 horizontal quilt bands;
  1601. hoodie gets a kangaroo pocket and drawstrings; apron is a front panel with a
  1602. bib, waist ties and a towel, never a full cylinder around the body.
  1603. - Backpack sits behind the torso with two shoulder straps that cross the front;
  1604. a bag floating at the spine reads as a growth.
  1605. - High-vis, reflective bands and lanyards are thin boxes proud of the cloth,
  1606. following the body curve at 2 to 4 mm.
  1607. **Hands are the contact proof.** Palm box 0.070 x 0.078 x 0.054, a finger block
  1608. with two grooves and a thumb capsule. A glove is the same geometry in glove
  1609. material, with a cuff. When a hand holds something, the palm and finger block
  1610. must touch it; a wrist near a handle is not a hold.
  1611. If the head or the clothing is wrong, fix it before the walk. A good gait cannot
  1612. rescue a sphere head or a painted jacket.
  1613. ## Animation
  1614. Every motion is a pure function of `t` or of a distance along a track.
  1615. ```js
  1616. const swing = Math.sin(phase), cs = Math.cos(phase);
  1617. const kneeL = 0.05 + 0.46*Math.max(0,-cs) + 0.22*Math.max(0, swing);
  1618. const kneeR = 0.05 + 0.46*Math.max(0, cs) + 0.22*Math.max(0,-swing);
  1619. pose = {
  1620. torso: [lean, swing*0.05, 0],
  1621. shoulderL: [-swing*arm, 0, -0.09], shoulderR: [swing*arm, 0, 0.09],
  1622. elbowL: [-0.16 - Math.max(0, swing)*0.28, 0, 0],
  1623. elbowR: [-0.16 - Math.max(0,-swing)*0.28, 0, 0],
  1624. hipL: [swing*amp, 0, 0.03], hipR: [-swing*amp, 0, -0.03],
  1625. kneeL: [kneeL,0,0], kneeR: [kneeR,0,0],
  1626. ankleL: [-kneeL*0.32,0,0], ankleR: [-kneeR*0.32,0,0],
  1627. };
  1628. ```
  1629. - Hips above ±0.35 read as a march; 0.30 to 0.34 is a walk, 0.5+ is a run with
  1630. lean 0.26 and elbows near -0.75.
  1631. - Match travel to stride or feet skate: `footTravel = 2*legLength*sin(amp)`,
  1632. `speed = footTravel * phaseRate / PI`. A 0.86 leg at 0.34 rad and 5.2 rad/s is
  1633. about 0.9 m/s. Drive `phase` from distance travelled, not from time, and the
  1634. walk always matches the path.
  1635. - A track is a Catmull-Rom sampled to an arc-length table with `groundY` heights
  1636. smoothed by three 1-2-1 passes, so steps read as ramps. `at(d)` returns
  1637. position and heading.
  1638. - Sit: hip X around -1.35 to -1.50, knee +0.5 to +1.3 so the shin drops
  1639. vertically, torso back 0.05 to 0.1. Seat height is a measured constant.
  1640. - Climb: hands start above the head, opposite hand and foot move together, hips
  1641. stay close to the ladder (0.12 to 0.2 m) and swing 0.06 to 0.10. Rung spacing
  1642. 0.30 m, climb 1.0 to 1.2 m/s, phase driven by height, not time. Feet land on
  1643. rungs, not between them; the shadow belongs on the ladder/deck, not the slab.
  1644. - One-shot actions (jump, dive, kick) are phase tables with eased poses, never a
  1645. blend between two loops. Hoist shared easing factors above the branch: a
  1646. `const` declared in one branch and read in another throws every frame and
  1647. freezes the figure. Pose targets are full poses, not deltas.
  1648. - Airborne arcs are solved backwards from the impact: for a fixed flight `T`,
  1649. `vy = (landY - launchY + 4.9*T*T)/T`. A guessed `vy` either lands late or
  1650. stops in mid-air.
  1651. - The rig root is at the feet, so a rigid-body spin sweeps the model around its
  1652. toes: rotate about a pivot `C` with `p' = p + C - R*C`, C about 0.55 up.
  1653. ### Carrying, Loading And Mounting
  1654. These are the beats closest to the camera and the ones users report first. A
  1655. prop that teleports, a hand that misses it, or a leg that swings through the
  1656. handlebars destroys the whole miniature.
  1657. **Carry.** Keep the prop in world space and solve its transform from the hands
  1658. every frame; do not parent a big prop to a wrist group (it inherits the wrist
  1659. roll and swims).
  1660. ```js

Lines 2,001–2,975 are not shown. The link to the file on GitHub has every line.

README.md · README · 356 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div align="center">
  2. # Diorama
  3. **A playbook and code kit for detailed Three.js dioramas. It asks two questions before the first mesh: which of three looks to build in, and whether the models come from libraries or from your own geometry.**
  4. [![Stars](https://img.shields.io/github/stars/sloemo01/diorama?style=flat-square&color=1d1d1f&logo=github&label=stars)](https://github.com/sloemo01/diorama/stargazers)
  5. [![Forks](https://img.shields.io/github/forks/sloemo01/diorama?style=flat-square&color=1d1d1f&label=forks)](https://github.com/sloemo01/diorama/forks)
  6. [![Watchers](https://img.shields.io/github/watchers/sloemo01/diorama?style=flat-square&color=1d1d1f&label=watchers)](https://github.com/sloemo01/diorama/watchers)
  7. [![License](https://img.shields.io/github/license/sloemo01/diorama?style=flat-square&color=1d1d1f)](LICENSE)
  8. [![npm](https://img.shields.io/npm/v/@sloemo/diorama?style=flat-square&color=1d1d1f&logo=npm&logoColor=white)](https://www.npmjs.com/package/@sloemo/diorama)
  9. [![Skill](https://img.shields.io/badge/skill-v5.7.0-1d1d1f?style=flat-square)](SKILL.md)
  10. [![three.js](https://img.shields.io/badge/three.js-r170-1d1d1f?style=flat-square&logo=three.js&logoColor=white)](https://threejs.org)
  11. <p>
  12. <a href="https://raw.githubusercontent.com/sloemo01/diorama/main/media/pikachu-vs-charizard.mp4"><img src="https://raw.githubusercontent.com/sloemo01/diorama/main/media/pikachu-vs-charizard.gif" width="24%" alt="Pikachu vs Charizard battle diorama, looping"></a>
  13. <a href="https://raw.githubusercontent.com/sloemo01/diorama/main/media/dust-kings.mp4"><img src="https://raw.githubusercontent.com/sloemo01/diorama/main/media/dust-kings.gif" width="24%" alt="Dust Kings arena show diorama, looping"></a>
  14. <a href="https://raw.githubusercontent.com/sloemo01/diorama/main/media/pool.mp4"><img src="https://raw.githubusercontent.com/sloemo01/diorama/main/media/pool.gif" width="24%" alt="Swimming pool diorama, looping"></a>
  15. <a href="https://raw.githubusercontent.com/sloemo01/diorama/main/media/bank-job.mp4"><img src="https://raw.githubusercontent.com/sloemo01/diorama/main/media/bank-job.gif" width="24%" alt="Bank job diorama, looping"></a>
  16. </p>
  17. <sub><b>Pikachu vs Charizard</b>, 45 s &nbsp;·&nbsp; <b>Dust Kings</b>, 38 s &nbsp;·&nbsp; <b>Pool</b>, 26 s &nbsp;·&nbsp; <b>Bank job</b>, 48 s</sub>
  18. <sub>Four scenes built with this playbook. Click any tile for the full capture.</sub>
  19. [**Install it in one prompt**](#install-it) &nbsp;·&nbsp; [**Update it in one prompt**](#update-it) &nbsp;·&nbsp; [What is in here](#what-is-in-here) &nbsp;·&nbsp; [Start a diorama](#start-a-diorama) &nbsp;·&nbsp; [Verification](#verification)
  20. </div>
  21. A diorama here is a tiny staged scene on a slab: a resettable three-quarter hero camera with free user orbit, a
  22. flat cut-out against white paper, a 64 colour palette with ordered dither and an
  23. inked contour, and toy-scale people with real joint animation. The subject changes
  24. (pool, night market, bank job, arena battle); the slab, the cast and the
  25. presentation stay for the default pixel preset.
  26. **Looks:** pixel (default), stroked toon, or pixel + stroke. The agent asks once and
  27. builds in the answer; silence means pixel.
  28. **Sourcing:** hybrid is the default: licensed assets, hand-built gaps. Also internet
  29. throughout or agent-modelled. Assets must allow commercial use and redistribution,
  30. with evidence in `refs/SOURCES.md` and `CREDITS.md`.
  31. Everything is deterministic. The scene is a pure function of `t`, so any frame can
  32. be frozen, screenshotted and compared. A screenshot is evidence, not a lucky
  33. capture.
  34. `SKILL.md` is the playbook: research-first workflow, the look and animation bars,
  35. the pipeline, the recipes, the QA harness and the pitfalls. It stays the source of
  36. truth. `references/` holds the same material split into on-demand topic files for
  37. long sessions, and everything else here is copy-in code that supports it.
  38. ## Install it
  39. Paste this into an agent that can run shell commands. It asks where the folder should
  40. go, installs the published package with `npm i @sloemo/diorama` and `npx diorama`,
  41. reads it, and reports what it learned before it builds anything. That is about 155
  42. files and 1.6 MB — `SKILL.md`, `references/`, `templates/`, `verify/`, the licence and
  43. the two educational screenshots. Nothing is installed globally and nothing runs after
  44. the copy.
  45. For a one-off without adding a dependency, `npx @sloemo/diorama <target>` does the same
  46. thing; `--list` previews the copy, `--force` writes over an existing install,
  47. `--no-verify` skips the worked examples.
  48. `--media` adds the four demo scenes as GIF and MP4 — 20 MB, from
  49. [`@sloemo/diorama-media`](https://www.npmjs.com/package/@sloemo/diorama-media) — for when
  50. you are rebuilding one of them and want the reference footage in hand.
  51. ```text
  52. Install the Diorama playbook here, then use it to build scenes.
  53. Package: https://www.npmjs.com/package/@sloemo/diorama
  54. 1. Ask me where the folder should go before installing anything,
  55. and wait for my answer. Propose ~/skills/diorama as the default.
  56. Do not pick a path silently.
  57. 2. Install the published package. Run it from a scratch directory or
  58. from the parent of <target>, not inside an unrelated project:
  59. npm i @sloemo/diorama && npx diorama "<target>"
  60. Without touching package.json:
  61. npx --yes @sloemo/diorama "<target>"
  62. Add --media only if I want the four demo clips as reference footage
  63. (20 MB, from @sloemo/diorama-media). The playbook does not need it.
  64. --list previews the copy, --force overwrites an existing install,
  65. --no-verify skips the worked examples. If <target> already has files,
  66. ask me before using --force.
  67. Install from the registry only. Do not clone the GitHub repository or
  68. unpack an archive instead: the npm download count is how this project
  69. tells whether anyone uses it. If npm or node 18+ is missing, say so
  70. and stop.
  71. 3. Prove the install before describing it, and print what you ran:
  72. npx diorama --version # package and playbook version
  73. ls "<target>" # SKILL.md README.md LICENSE references templates verify
  74. find "<target>" -type f | wc -l
  75. The count must match what the installer printed. If a check fails, say
  76. so and stop. Never describe this playbook from memory.
  77. 4. If you have a skills directory or plugin folder, install it
  78. there so you can load it by name in later sessions; otherwise
  79. treat "<target>" as the folder.
  80. 5. Read before you build: all of SKILL.md, references/INDEX.md, then
  81. templates/DESIGN.md, templates/SOURCES.md, templates/CREDITS.md,
  82. templates/qa/README.md, the header comment of every template you
  83. intend to copy, and the worked examples under verify/. SKILL.md is
  84. the source of truth; the README is only a summary.
  85. 6. Report back in this order: install path and version, the Look
  86. Contract in one paragraph, the Pipeline as ordered steps, the
  87. QA scripts and what each one checks, and three rules from
  88. SKILL.md with the section each came from.
  89. 7. Then ask me what the first diorama should be. Do not ask me to
  90. fill the design sheet. When I give you a subject, research it
  91. first (frames, assets, motion), fill DESIGN.md from the
  92. defaults, copy the modules you need into my project instead of
  93. editing the installed copy, build through the Pipeline, and run
  94. the QA scripts before you show me anything. Give me the paths
  95. of the frames you kept and what each one proves.
  96. If two parts of SKILL.md contradict each other, list them before
  97. you build. A successful npx is not an install: 5 and 6 are it.
  98. ```
  99. ## Update it
  100. Paste this into an agent for a copy that is already installed. It backs the folder up,
  101. updates the command with `npm i @sloemo/diorama@latest`, refreshes the folder with
  102. `npx diorama <target> --force`, and reports what changed before any project is touched.
  103. ```text
  104. Update my Diorama install, then report what changed.
  105. Package: https://www.npmjs.com/package/@sloemo/diorama
  106. 1. Ask me for the folder before touching anything, and wait.
  107. Propose ~/skills/diorama as the default.
  108. 2. Print the current version and make the update reversible:
  109. npx diorama --version
  110. cp -R "<target>" "<target>.bak"
  111. Keep the copy until I say the update is good.
  112. 3. Refresh in place from the registry:
  113. npm i @sloemo/diorama@latest && npx diorama "<target>" --force
  114. Without touching package.json:
  115. npx --yes @sloemo/diorama@latest "<target>" --force
  116. No git pull, no archive: the npm download count is how this project
  117. tracks real installs. Add --media if <target>/media already holds the
  118. demo clips, so the reference footage moves with the playbook.
  119. If node 18+ or npm is missing, say so and stop.
  120. 4. Prove it before describing it: print the old and new version from
  121. SKILL.md frontmatter, confirm the same six paths still exist, and
  122. confirm the file count matches what the installer printed. If the
  123. refresh failed, say so and stop.
  124. 5. Report the difference in this order: version jump, new or removed
  125. folders and templates, rules that changed, and which of my own files
  126. inside <target> differ from the new ones. Re-apply my edits only when
  127. the difference is clean, and say so when it is not.
  128. 6. If one of my dioramas is mid-build, read SKILL.md and
  129. references/INDEX.md again and list the rules that now affect that
  130. project. Do not rewrite the scene without asking me.
  131. ```
  132. ## Educational scenes and inspection (5.7)
  133. Educational mode is a first-class exception to narrative cast/ritual/system quotas:
  134. one accurately built mechanism, one causal sequence and clean off-white (`#f7f7f5`).
  135. The default surface is one opaque white card in a reserved 360px right column, which
  136. becomes a bottom dock below 880px; an explicitly requested placement keeps those tokens
  137. and controls. Narrative scenes get none of it: no card, lesson steps, part picker,
  138. dashboard or floating labels unless an explanation was asked for. Click a real part for
  139. one short explanation, and the same labelled picker supports keyboard selection,
  140. including pieces hidden inside the housing. Selection lifts the chosen material while
  141. the rest dims, from reversible overrides that restore the exact original materials, and
  142. feature edges are built from `EdgesGeometry` on the live meshes rather than a wireframe
  143. pass. Selecting a part triggers one short camera and target transition, cancelled
  144. immediately by user orbit or keyboard navigation; Back restores the previous view and
  145. Reset keeps the hero pose. Component manifests, real through-bores and
  146. ratio/kinematic/contact tests stop simplification from quietly deleting working parts.
  147. Delivery needs frozen-frame, motion, orbit, mobile and accessibility evidence, not a
  148. promise that an agent complied.
  149. All presets rotate by default, with no separate orbit consent. `templates/orbit.js` supplies reset, keyboard orbit and drag-versus-click handling. `pixel-stroke` is chosen through that same one-question gate; `templates/pixel-stroke.js` renders toon materials and selective geometry contours into an explicit low-res target then nearest upscales once. No PixelPost/Sobel double edges; DOM UI stays native resolution. Stroke thickness must be checked in target pixels and after screen upscale.
  150. ## Motion graphics
  151. Arrows, flames and flow are geometry, not texture. The v3.12.0 four-stroke work hardened them with a
  152. full-cycle, frame-by-frame pass: a spline through the
  153. cutaway speared the valve disc, only the arrow *centre* was clamped so heads
  154. poked through the crown, two stacked rows read as double-headed chevrons, scales
  155. ran past 1.0 and defeated the legibility gate, the force arrow outlived its
  156. flame, and the ignition flash blew the head to white. The rules are: derive each
  157. effect from the current free volume (never a port centreline), fit the
  158. direction-dependent cone extent, anchor to the real valve/crown surface, use one
  159. arrow per stroke, normalize the authored length, couple the effect to its source,
  160. declare every Y constant in one local space, cap the flash, and accept only after
  161. a 15°-step contact sheet plus a 720° vertex containment sweep. Earlier findings
  162. still apply: tested +Z axis, no `depthTest:false`, no sub-pixel specks,
  163. free-band sizing, compact flames, un-outlined FX and phase-bound lifetimes.
  164. `templates/flow-primitives.js` is the copy-in helper: tested +Z arrows, a
  165. free-band fitter and a legibility gate. See "Motion Graphics Primitives" in
  166. `SKILL.md` and the effects block in `templates/DESIGN.md`.
  167. <p align="center">
  168. <img src="https://raw.githubusercontent.com/sloemo01/diorama/main/media/education-ui-right.png" width="62%" alt="Educational mechanism with one right-side dock">
  169. <img src="https://raw.githubusercontent.com/sloemo01/diorama/main/media/education-selection-focus.png" width="34%" alt="Selected part glowing while the rest dims">
  170. </p>
  171. ## The scenes
  172. **Pikachu vs Charizard** is the fight at the top of this page: Leon throws a ball,
  173. Charizard bursts out of it and the ball comes back to his hand, four attacks trade
  174. across the arena with their own wind-up and hit reactions, Pikachu takes a
  175. knockdown, and the red recall beam only appears once Charizard is beaten.
  176. **Dust Kings** follows one night's billing: cars on the arena floor, the billboard
  177. running through LIVE, NEW RECORD and THANK YOU, and a fire that gets away from
  178. them.
  179. **Pool** is a slow afternoon: one swimmer working laps with a wake trailing behind,
  180. one standing waist-deep by the ladder, one folding into a dive beside the board, a
  181. lifebuoy and a ball left floating, a lifeguard pacing the far edge, and a
  182. sunbather who does not move from the towel.
  183. **Bank job** runs in daylight: a sedan noses into the curb, a group in dark clothes
  184. climbs the bank steps and the windows go red behind them, the sedan pulls away, two
  185. cruisers arrive and officers fan out across the street, then the street empties
  186. again.
  187. ## What is in here
  188. | Path | What it is |
  189. | --- | --- |
  190. | `SKILL.md` | The whole playbook: research gate, look contract, detail and animation bars, pipeline, recipes, QA, pitfalls. Start here. |
  191. | `templates/` | Copy-in modules: palette, post pass, camera, lighting, geometry, props, rig, poses, vehicle transfer, paths, combat, creature, water, effects, build script. |
  192. | `templates/flow-primitives.js` | Tested +Z arrow primitive, free-band fitter and legibility gate for motion graphics. |
  193. | `templates/DESIGN.md` | The design sheet you fill before modelling. |
  194. | `templates/SOURCES.md` | The research log you fill before modelling: query, what was found, decision. |
  195. | `templates/CREDITS.md` | The licence ledger for every imported model, clip or texture. |
  196. | `templates/creature.js` | Rigged-actor combat: stage-local aiming, bone-space effect anchors, upright billboards, hit severities, send-out geometry. |
  197. | `references/` | The playbook split by topic, indexed in `references/INDEX.md`: sourcing, representation, inspection, construction gates, service, vehicles, effects, verification. |
  198. | `templates/qa/` | Eight verification scripts that check a build against frozen frames and printed numbers, including a per-entity frame recorder, plus unit and browser regressions for the inspection and mechanism helpers. |
  199. | `archive/` | Retired material kept for reference: the removed Pixel Art V2 renderer and its supporting parts. |
  200. | `verify/water/` | A worked scene that exercises the water modules, with the screenshots the QA loop produced. |
  201. | `verify/climb/` | A unit test for the vehicle transfer maths. |
  202. | `verify/creature-battle/` | What a two-actor fight build proved: aiming, effect anchoring, send-out and hit numbers. |
  203. | `media/` | The preview GIFs and source captures shown above. The two `education-ui-*.png` screenshots ship with the npm package; the four demo clips live in [`@sloemo/diorama-media`](https://www.npmjs.com/package/@sloemo/diorama-media) and arrive with `--media`. |
  204. ## Start a diorama
  205. 1. Read `SKILL.md`: `Research Before You Model`, `One Prompt, One Build`, `The Look
  206. Contract`, `The Detail Bar`, `The Animation Bar`, `Pipeline`.
  207. 2. Research first. Step the real subject into frames and write its motion grammar
  208. down. Walk the sourcing ladder for every hero asset (already on disk, CC0,
  209. CC-BY, then hand-build) and record each search in `refs/SOURCES.md`. Imported
  210. assets get a row in `CREDITS.md`.
  211. 3. Copy `templates/DESIGN.md` into the project as `DESIGN.md` and fill it. Premise
  212. as a verb, cast, systems, five beats with timestamps, detail budget.
  213. 4. Copy the modules you need into `src/core/` and `src/scene/`, then a `config.js`
  214. that holds the scene's numbers. `verify/water/src/` is the reference layout.
  215. 5. Block out in grey at the reset hero camera before any production pass, then run the
  216. pipeline: palette, materials, detail, animation, effects, post.
  217. 6. Verify with `templates/qa/` before calling it done, and check the research gate
  218. in `Build And Ship` (reference sheets, `SOURCES.md`, `CREDITS.md`, per-beat
  219. captures).
  220. ## Research before you model
  221. The playbook opens with four lookups, because a plausible silhouette that matches
  222. nothing is the most common way a commission fails:
  223. - **Shape.** Pull the real thing on video, step it into contact sheets at 8 to 12
  224. fps, read them, and write the grammar down before touching geometry.
  225. - **Assets.** Check the user's disk, then the Polyfork catalogue, then the CC0 and CC-BY libraries (Quaternius,
  226. KayKit, Poly Pizza, Kenney, Sketchfab with the downloadable plus CC0 filter,
  227. Smithsonian, Poly Haven, ambientCG, Mixamo and the Quaternius animation
  228. library). A rigged download beats four hundred lines of primitives at close
  229. range. Licences that are NC, ND, ripped or unstated are a hard stop.
  230. - **Motion.** Search the verb, not the noun. Count frames at a known fps, convert
  231. to seconds, and write wind-up / contact / follow-through / recover before
  232. animating.
  233. - **Proof.** Freeze every beat and compare the capture against the reference
  234. frame for that beat.
  235. `templates/SOURCES.md` and `templates/CREDITS.md` are the two artifacts that make
  236. that research visible in a project, and `Build And Ship` will not pass without
  237. them.
  238. ## How it works
  239. - **One camera solve.** The camera is fitted to the slab's bounding box once, at a
  240. fixed three-quarter azimuth, with a `subjectScale` margin. Free orbit controls and reset in every preset; no auto-spin.
  241. - **Two passes, one look.** The render is drawn into a small buffer, then gamma,
  242. grade, a 64 entry palette snap, ordered dither, an ink contour and a nearest
  243. neighbour upscale happen in that fixed order.
  244. - **Detail is a bar, not a mood.** Every hero prop carries a real silhouette,
  245. chamfers, seams, hardware and a contact shadow; if it reads at a glance and
  246. still holds at 1:1, it passes.
  247. - **Animation is five layers.** Idle, locomotion, secondary motion (clothes, hair,
  248. tails, capes), glance and weight shifts, then the scripted acting on top.
  249. - **Everything is a function of `t`.** Actors, props, effects and camera are
  250. evaluated from the beat sheet each frame, so `?t=12.4` is exactly the same
  251. picture every time.
  252. ## Verification
  253. The `templates/qa/` scripts drive Chromium through `playwright-core` against a
  254. page that exposes a debug handle:
  255. ```js
  256. window.__diorama = {
  257. THREE, scene, camera, renderer, post,
  258. freeze(t) { /* draw(t) synchronously */ },
  259. view(pos, tgt) { /* optional debug camera */ }
  260. };
  261. window.__dioramaReady = true;
  262. ```
  263. | Script | What it checks |
  264. | --- | --- |
  265. | `shoot.mjs` | console errors, layout at each viewport, named frozen timestamps |
  266. | `audit.mjs` | flat glows, whole-group fades, early hides, teleports, margin leaks |
  267. | `portrait.mjs` | isolated figures through a debug camera |
  268. | `strip.mjs` | N-frame motion strips, fails on a frozen loop |
  269. | `frames.mjs` | per-entity frame series with a verdict each: FROZEN, TELEPORT, EMPTY, OFFSCREEN |
  270. | `sweep.mjs` | pairwise distances, jam and teleport verdicts |
  271. | `probe.py` | colour runs across an edge |
  272. | `tile.py` | tiles a motion strip into a contact sheet |
  273. `freeze(t)` has to draw synchronously. Without it a screenshot is a race, and a
  274. screenshot that may show a different frame than you asked for is not evidence.
  275. `frames.mjs` is the one that pays for itself on a scene with more than two actors.
  276. It records one dense series per entity, isolates it, fits a camera to its swept
  277. bounds, and scores it: a flat energy line means the actor is not animating, an NDC
  278. jump means a state boundary is snapping instead of blending, and empty frames mean
  279. the window is wrong. Each entity gets a contact sheet and a verdict, so a dead
  280. actor cannot hide behind a moving neighbour.
  281. The worked examples under `verify/` show the loop end to end, including the
  282. defects the harness found and the numbers after the fix.
  283. ## Using it as a skill
  284. `SKILL.md` carries skill frontmatter (`name`, `description`, `version`), so a
  285. skill-capable coding agent can load it as-is. It reads on its own; `references/`
  286. carries the same guidance split by topic for long sessions, and `templates/` carries
  287. the copy-in code.
  288. If you just want to read it, start at `Research Before You Model`, then
  289. `One Prompt, One Build` and `The Look Contract`.
  290. Long builds will eventually compact the agent's context, and compaction is lossy.
  291. `SKILL.md` has a `Long builds and context` section for that: state lives in
  292. `DESIGN.md`, `SOURCES.md`, `CREDITS.md`, `report.json` and the beat table rather
  293. than in the chat, and after a compact the agent re-runs `frames.mjs` and
  294. `shoot.mjs` instead of trusting its own summary of the last frame.
  295. ## Licence
  296. MIT. See `LICENSE`. three.js is MIT as well.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.