Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.
TypeScript agent-skillsanimationcanvasclaude-codeclaude-pluginclaude-skillscodex-plugincreative-codecreative-codingcreative-toolsdeterministicgenerative-arthand-drawnillustrationlaunch-videomotion-designmotion-graphicspluginprocedural-generationskill
0.10.0: launch films that pass ship, brandable looks, the Becoming 10x lessons as checks
Alex Greenshpun987b1379d953
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex c424b5d..a2fb576 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -13,7 +13,7 @@"name": "anidoodle","source": "./","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.9.6",+ "version": "0.10.0","author": {"name": "Alex Greenshpun","url": "https://linkedin.com/in/alexgreensh"diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 97f371c..2f9601c 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"name": "anidoodle","displayName": "anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.9.6",+ "version": "0.10.0","icon": "./assets/icon.png","author": {"name": "Alex Greenshpun",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex e17cc11..4fd7a56 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "anidoodle",- "version": "0.9.6",+ "version": "0.10.0","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.","skills": "./skills/","interface": {diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.jsonindex 86c7218..5cdf99d 100644--- a/.grok-plugin/marketplace.json+++ b/.grok-plugin/marketplace.json@@ -10,7 +10,7 @@"name": "anidoodle","source": "./plugins/anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.9.6",+ "version": "0.10.0","author": {"name": "Alex Greenshpun","url": "https://linkedin.com/in/alexgreensh"diff --git a/skills/anidoodle/SKILL.md b/skills/anidoodle/SKILL.mdindex 971dd34..a0037a5 100644--- a/skills/anidoodle/SKILL.md+++ b/skills/anidoodle/SKILL.md@@ -36,16 +36,17 @@ or in 3D (one medium per film), what **shape** (1x1, 9x16, 16x9, 4x5 or any W x| A story film, any length | Film workflow below, `references/workflows/long-film.md` || A 3D film or 3D motion graphics: extruded type, objects, puppets, a camera through space | `references/workflows/three-d.md` || An explainer or infographic; a machine that comes apart to explain an idea, in any style | `references/workflows/explainer.md`, `references/workflows/machines.md` |-| A launch or product video (their screenshots welcome) | `references/workflows/launch-video.md`; build it on `references/workflows/launch-video-kit.md`; its claims: `references/workflows/facts.md` |+| A launch or product video, or 2D motion graphics (their screenshots welcome) | `references/workflows/launch-video.md`; one world, one camera: `references/workflows/motion-film.md`; the kit: `references/workflows/launch-video-kit.md`; claims: `references/workflows/facts.md` |+| A film in someone else's brand: their exact elements, logos, fonts, sponsors, an event program | `references/workflows/brand-film.md` (imported and signed off before the first board) || Art for a site (hero by a headline, tiles, spots, share card) on its page colour and brand; or a web animation that reacts to the UI | `references/workflows/site-art.md`; `references/workflows/interactive.md` || A drawing lesson, or "how do I draw this?" | `references/workflows/teach-drawing.md` || A character kept identical in any style (woodcut to toy brick) | `references/workflows/character-consistency.md`, `references/anatomy.md` || A style matched from their image | `references/workflows/adapt-a-style.md` |-| A score or soundtrack | `references/music/README.md` |+| A score or soundtrack; or a generated or licensed track cut to the film | `references/music/README.md`; `references/music/generated-tracks.md` || Narration, a voice-over, word timing or subtitles | `references/workflows/narration.md` |- Music: pick a style vocabulary (`references/music/styles/vocabularies.md`; deep dives `references/music/styles/music-box.md`, `references/music/styles/lofi-electronic.md`) and mood, sketch the tension arc and motif, compose your own harmony, motif and form (references/music/compose.md, craft in references/music/theory/), revise until node tools/music.mjs craft shows only findings you chose, then check must PASS before a human listens. Styles give sound, never notes.-- Sound effects: references/music/sound-design.md. 14 layered, seeded effects cued by film frame (filmSfx); the score ducks, and every cue must be within 6 dB of it. Effects only on real direction changes, one riser + one impact per film.+- Sound effects: references/music/sound-design.md. 14 layered, seeded effects cued by film frame (filmSfx); the score ducks, and every cue must be within 6 dB of it. Effects only on real direction changes, one riser + one impact per film. Under someone else's music, unpitched `tap` effects only.- Launch films: `launchTemplate.ts` renders a product's launch from data (prompts, plates or its own UI, a score composed for it, words, install lines) in every shape from one timeline; `launch.mjs new|ship`. Habits that save tokens: `references/working-method.md`.## The seven laws@@ -80,11 +81,11 @@ size and shape asked for from the same source, and say `reproducible` was printesomething moves every second. Check the seam (last frame against frame 0). ✋ **One approval, on the moving file.****Film.** (1) **The story in three sentences** (setup, transformation, payoff) and the token; for-longer films, a spine plus one line per chapter. If you cannot write it, stop. (2) **The grid**:+longer films, a spine plus one line per chapter; a launch or brand film adds a `board.json` that `board.mjs` passes. If you cannot write it, stop. (2) **The grid**:a beat is 60 x fps / bpm frames, the bpm from the brief's score; one cue table holds every frame number and a checkerruns at load. (3) **Real reference** for anything that exists. (4) **ONE look still**, the hardestframe, critiqued in writing. ✋ **Approval.** (5) **ONE 8-second music sample.** ✋ **Approval.**-(6) **Build the whole film**; mechanical checks run continuously. (7) **A fresh critic reviews, never you**+(6) **Build the whole film**; mechanical checks run continuously, and `ship.mjs` passes on the exact file before anyone sees a version. (7) **A fresh critic reviews, never you**(`references/workflows/review.md`): after the storyboard, each scene and the full render, a new subagent that saw none of the building returns ranked, timestamped problems and a verdict. Fix the biggest, a NEW critic rechecks; 3 rounds at most, logged in `ledger.md`.(8) ✋ **Final approval.** Say what you verified and what you cannot. Three approval gates at most. Approval is a budget; spend it where being wrong is expensive.@@ -101,7 +102,7 @@ draws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze## The engine`engine/` is the portable art core plus the tooling. `engine/src/canvas-core` knows nothing-about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`.+about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`. Four backends, one art core → `references/backends-and-adapters.md`.3D: `engine/src/three-core` renders three.js onto the same frame, so every tool below works on 3D films (vendored and hash-pinned, `engine/vendor/three/PROVENANCE.md`; type face `engine/assets/fonts/PROVENANCE.md`).Camera moves (pans, dollies, lens and dolly zooms, parallax, shake) and slow motion or freeze frames: `engine/src/canvas-core/camera.ts`, `engine/src/canvas-core/timeRemap.ts`, `references/camera.md`.Seams between scenes: `references/motion-grammar.md` (cuts that carry motion: `seams.ts`; `tools/deck.mjs deal` deals each film different moves; `deck.mjs find "<name>"` turns a move's everyday name into its card). `render.mjs --blur auto` renders with motion blur (subframes per frame@@ -123,24 +124,21 @@ node <skill>/engine/tools/soundfetch.mjs get piano rooms # on their yes (piano| `scaffold.mjs` | a project with a still and/or film; `--duration`, `--format` or `--size`, `--fps`, `--bpm` || `still.mjs` / `render.mjs` | frames drawn twice with hashes (`--frames a,b,c --sheet <file>` in one browser) / the piece in any format (`--from/--to`, `--poster-frame`, `--hashes`) || `gate.mjs` | determinism, contract, dead air, artifact, 3D checks; `--self-test` proves it can fail |-| `registry.mjs` / `gallery.mjs` | the style list from the plates themselves / the gallery sheet |-| `docs-check.mjs` | fails when any doc's style count, length or path disagrees with the code |+| `registry.mjs` / `gallery.mjs` / `docs-check.mjs` | the style list from the plates / the gallery sheet / fails when a doc's style count, length or path disagrees with the code || `verify-export.mjs` | QA on the rendered file: frames, duration, score, A/V sync, true peak after the encode; opt-in first frame, loop seam, `--delivery` |-| `launch.mjs` | a launch film: `new <name>` scaffolds the spec; `ship <name> --shapes 16x9,9x16` renders, posters, captions, verifies and framechecks each (`framecheck.mjs`: text whole, up long enough to read, clear of the 9:16 phone zones) and checks `facts.json` (`facts.mjs`) |+| `launch.mjs` | a launch film: `new <name>` scaffolds the spec (its `look` wears the product's own fonts, palette, shapes and logo: launch-video-kit.md, Looks); `ship <name> --shapes 16x9,9x16` renders, posters, captions, verifies and framechecks each (`framecheck.mjs`: text whole, up long enough to read, clear of the 9:16 phone zones) and checks `facts.json` (`facts.mjs`) || `test.mjs` (`npm test`) | unit suites in `engine/test/`, no browser || `music.mjs` | `vocab` prints a style's vocabulary; `check` gates your composed score (key, master, guards, stems, novelty, which parts played recordings) and prints its shape (ARC); `render`, `meter` || `narrate.mjs` | narration: `say` (takes, cached), `time`, `check` (hears every word back; exit 1 on a dropped word), `bake`, `all`, `providers` |-| `soundfetch.mjs` | the sound pack: `list`, `get <id...\|all>`, `where`, `verify`, `remove <id>` |-| `sfx.mjs` | the sound-effects kit: `list`, `one`, `kit <dir>`, `test` |--Four backends, one art core: `playwright`, `html-player`, `remotion`, `hyperframes` → `references/backends-and-adapters.md`.+| `soundfetch.mjs` / `sfx.mjs` | the sound pack: `list`, `get <id...\|all>`, `where`, `verify`, `remove <id>` / the effects kit: `list`, `one`, `kit <dir>`, `test` |+| `ship.mjs` | every check on the exact delivered file (framecheck on all drawn text, verify-export, gate, motion and layer scans, locks, sound, cues, facts, review ledger, length), one table and a critic sheet; a check that cannot look FAILS |+| `board.mjs` / `brand.mjs` | the brief and storyboard checked before drawing / a brand imported exactly: `import --sheet`, `inventory`, `find`, `check`, `logos`, `logo` |+| `motionscan.mjs` / `layerscan.mjs` / `lock.mjs` / `worldfilm.mjs` | slide cuts, carousels, dissolves, temperament on the MP4 / text residue, fast type, shapes over faces, translucent brand colour / approved shots frozen / a film started as one world |+| `track.mjs` / `cues.mjs` | an outside track: `analyze`, `cut` by bars, `mix`, `master`, `check`, `listen`, `prompt` (never sent) / the film's own event times for sound and sync |## Worked examples-- **The style plates** in `engine/src/canvas-core/`: every hand has a still and a film of it being- drawn, with the recipe in the header and `references/styles/<id>.md`.-- **MECHANICAL LEPIDOPTERA** in `example/`: a 47 s scored film. `scaffold.mjs ~/study --example`.-**Study them. Do not copy them.** The craft bar is not satisfied by inheritance.+The style plates in `engine/src/canvas-core/` (a still and a film of each being drawn, recipe in the header and `references/styles/<id>.md`) and **MECHANICAL LEPIDOPTERA** in `example/`, a 47 s scored film (`scaffold.mjs ~/study --example`). **Study them. Do not copy them.** The craft bar is not satisfied by inheritance.## Honest limitsdiff --git a/skills/anidoodle/engine/assets/brand/lantern/brand.json b/skills/anidoodle/engine/assets/brand/lantern/brand.jsonnew file mode 100644index 0000000..808c816--- /dev/null+++ b/skills/anidoodle/engine/assets/brand/lantern/brand.json@@ -0,0 +1,114 @@+{+ "version": 1,+ "elements": {+ "lanternMark": {+ "w": 120,+ "h": 120,+ "parts": [+ {+ "d": "M60 2 A13 13 0 1 1 59.99 2 Z M60 9 A6 6 0 1 0 60.01 9 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "evenodd",+ "op": 1,+ "bb": [+ 47,+ 2,+ 26,+ 26+ ]+ },+ {+ "d": "M40 24 H80 L92 38 H28 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "nonzero",+ "op": 1,+ "bb": [+ 28,+ 24,+ 64,+ 14+ ]+ },+ {+ "d": "M32 40 H88 V98 H32 Z M42 48 V90 H78 V48 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "evenodd",+ "op": 1,+ "bb": [+ 32,+ 40,+ 56,+ 58+ ]+ },+ {+ "d": "M60 52 C70 64 73 74 68 82 C65 87 55 87 52 82 C47 74 50 64 60 52 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "nonzero",+ "op": 1,+ "bb": [+ 49.63,+ 52,+ 20.75,+ 33.75+ ]+ },+ {+ "d": "M24 100 H96 Q100 100 100 104 V108 Q100 112 96 112 H24 Q20 112 20 108 V104 Q20 100 24 100 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "nonzero",+ "op": 1,+ "bb": [+ 20,+ 100,+ 80,+ 12+ ]+ }+ ]+ }+ },+ "report": {+ "lanternMark": {+ "parts": 5,+ "size": "120x120",+ "symmetry": {+ "rotational": 1,+ "mirrorX": true,+ "mirrorY": false+ },+ "repeats": [],+ "warnings": [],+ "fonts": []+ }+ },+ "sources": {+ "lanternMark": {+ "file": "lanternMark.svg",+ "sha256": "7b0f3e4589478e0e437abf992684e26cae3b77a1e624e7ed4ebc83543efe5eaa"+ }+ },+ "fonts": [],+ "palette": [+ {+ "hex": "#f2b544",+ "share": 1+ }+ ],+ "motion": {}+}\ No newline at end of filediff --git a/skills/anidoodle/engine/assets/brand/lantern/brand.ts b/skills/anidoodle/engine/assets/brand/lantern/brand.tsnew file mode 100644index 0000000..1a54543--- /dev/null+++ b/skills/anidoodle/engine/assets/brand/lantern/brand.ts@@ -0,0 +1,10 @@+// Written by tools/brand.mjs import from 1 source file(s); never edit by hand, re-import instead.+// These are the brand's exact paths: move, rotate, scale evenly, clip and layer them (brandKit.ts), never redraw them.+import type { BrandElement } from "../../../src/canvas-core/brandKit";++export const BRAND: { elements: Record<string, BrandElement>; palette: { hex: string; share: number }[]; fonts: string[]; motion: Record<string, any> } = {"elements":{"lanternMark":{"w":120,"h":120,"parts":[{"d":"M60 2 A13 13 0 1 1 59.99 2 Z M60 9 A6 6 0 1 0 60.01 9 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"evenodd","op":1,"bb":[47,2,26,26]},{"d":"M40 24 H80 L92 38 H28 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"nonzero","op":1,"bb":[28,24,64,14]},{"d":"M32 40 H88 V98 H32 Z M42 48 V90 H78 V48 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"evenodd","op":1,"bb":[32,40,56,58]},{"d":"M60 52 C70 64 73 74 68 82 C65 87 55 87 52 82 C47 74 50 64 60 52 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"nonzero","op":1,"bb":[49.63,52,20.75,33.75]},{"d":"M24 100 H96 Q100 100 100 104 V108 Q100 112 96 112 H24 Q20 112 20 108 V104 Q20 100 24 100 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"nonzero","op":1,"bb":[20,100,80,12]}]}},"palette":[{"hex":"#f2b544","share":1}],"fonts":[],"motion":{}};++/** For the film's meta.brand: the brand's colours (never drawn translucent outside a declared exception) and its element names. */+export const brandMeta = {"colors":["#f2b544"],"elements":["lanternMark"]};+/** For the film's meta.motion: layerscan fails a brand colour filled half-transparent. Spread it: meta.motion = { ...brandMotion, temperament: "calm" }. */+export const brandMotion = {"brandColors":["#f2b544"]};diff --git a/skills/anidoodle/engine/assets/brand/lantern/lanternMark.svg b/skills/anidoodle/engine/assets/brand/lantern/lanternMark.svgnew file mode 100644index 0000000..6896f14--- /dev/null+++ b/skills/anidoodle/engine/assets/brand/lantern/lanternMark.svg@@ -0,0 +1,8 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" width="120" height="120">+ <!-- Lantern, an invented brand for anidoodle's worked example of a custom launch look. Drawn for it; no one else's mark. -->+ <path fill-rule="evenodd" d="M60 2 A13 13 0 1 1 59.99 2 Z M60 9 A6 6 0 1 0 60.01 9 Z" fill="#f2b544"/>+ <path d="M40 24 H80 L92 38 H28 Z" fill="#f2b544"/>+ <path fill-rule="evenodd" d="M32 40 H88 V98 H32 Z M42 48 V90 H78 V48 Z" fill="#f2b544"/>+ <path d="M60 52 C70 64 73 74 68 82 C65 87 55 87 52 82 C47 74 50 64 60 52 Z" fill="#f2b544"/>+ <path d="M24 100 H96 Q100 100 100 104 V108 Q100 112 96 112 H24 Q20 112 20 108 V104 Q20 100 24 100 Z" fill="#f2b544"/>+</svg>diff --git a/skills/anidoodle/engine/assets/fonts/InstrumentSans-Bold.ttf b/skills/anidoodle/engine/assets/fonts/InstrumentSans-Bold.ttfnew file mode 100644index 0000000..f602dceBinary files /dev/null and b/skills/anidoodle/engine/assets/fonts/InstrumentSans-Bold.ttf differdiff --git a/skills/anidoodle/engine/assets/fonts/InstrumentSans-OFL.txt b/skills/anidoodle/engine/assets/fonts/InstrumentSans-OFL.txtnew file mode 100644index 0000000..4bb9914--- /dev/null+++ b/skills/anidoodle/engine/assets/fonts/InstrumentSans-OFL.txt@@ -0,0 +1,93 @@+Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/skills/anidoodle/engine/assets/fonts/InstrumentSans-Regular.ttf b/skills/anidoodle/engine/assets/fonts/InstrumentSans-Regular.ttfnew file mode 100644index 0000000..14c6113Binary files /dev/null and b/skills/anidoodle/engine/assets/fonts/InstrumentSans-Regular.ttf differdiff --git a/skills/anidoodle/engine/assets/fonts/Lora-Bold.ttf b/skills/anidoodle/engine/assets/fonts/Lora-Bold.ttfnew file mode 100644index 0000000..edae21eBinary files /dev/null and b/skills/anidoodle/engine/assets/fonts/Lora-Bold.ttf differdiff --git a/skills/anidoodle/engine/assets/fonts/Lora-OFL.txt b/skills/anidoodle/engine/assets/fonts/Lora-OFL.txtnew file mode 100644index 0000000..4cf1b95--- /dev/null+++ b/skills/anidoodle/engine/assets/fonts/Lora-OFL.txt@@ -0,0 +1,93 @@+Copyright 2011 The Lora Project Authors (https://github.com/cyrealtype/Lora-Cyrillic), with Reserved Font Name "Lora".++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/skills/anidoodle/engine/assets/fonts/PROVENANCE.md b/skills/anidoodle/engine/assets/fonts/PROVENANCE.mdindex bdd105e..c0bcad5 100644--- a/skills/anidoodle/engine/assets/fonts/PROVENANCE.md+++ b/skills/anidoodle/engine/assets/fonts/PROVENANCE.md@@ -19,3 +19,19 @@ node -e 'const fs=require("fs"),b=fs.readFileSync("assets/fonts/Poppins-Bold.ttfThe OFL allows bundling and redistribution with software; the font may not be sold on its own, anda modified version may not use the reserved name. We ship it unmodified.++## Lora Bold and Instrument Sans Regular and Bold (the launch template's look example, launchExampleBrand)++- `Lora-Bold.ttf`, 133828 bytes, sha256 `7d74015e950c2fb66519c7295b8155621d22200ae2ca2a4c6b43ce3c490cac87`.+ Copyright 2011 The Lora Project Authors, SIL Open Font License 1.1, full text in `Lora-OFL.txt`+ (sha256 `62e37a82d3f1ef2a70712885fa8b3144b65fd144d8e748d6196b690a354d792c`). Reserved Font Name "Lora".+- `InstrumentSans-Regular.ttf`, 68028 bytes, sha256 `a22cb26e48fd79bcb01bf2fc92d36785474dce36d9c544ab0a8868c2657c4a87`.+ Copyright 2022 The Instrument Sans Project Authors, SIL Open Font License 1.1, full text in+ `InstrumentSans-OFL.txt` (sha256 `bf4dc6d13a8cccd4807133c77a1ee9619a16b92cb23322258725ab6731c2f6e5`).+- `InstrumentSans-Bold.ttf`, 68084 bytes, sha256 `444f85bf1c4b0e1ce1ca624f6be54bcd832207714ccaf4ea99ee531341683bdf`.+ Same family, copyright and licence as the Regular above.+- Source: copied unmodified from a local copy of Anthropic's canvas-design skill font folder (the same+ Google Fonts releases), 2026-10-29; nothing fetched.+- Why: a serif display face and a plain text face for the worked example of a custom look, so the template+ is proven on fonts that are not ours. A film imports them by path (`import f from ".../Lora-Bold.ttf"`);+ tools/overlay.mjs inlines the bytes, so the page carries them and nothing is read or fetched at draw time.diff --git a/skills/anidoodle/engine/facts/launchClip.json b/skills/anidoodle/engine/facts/launchClip.jsonnew file mode 100644index 0000000..fe3dcbb--- /dev/null+++ b/skills/anidoodle/engine/facts/launchClip.json@@ -0,0 +1,8 @@+{+ "version": 1,+ "about": "The ledger of launchClip, anidoodle's own 4 second motion test (the Generate press, the ink drop and the bloom) cut from the launch film. Its prompt is a user's request and the rest of its text is the chat's own interface; the two lines below are the ones that claim something.",+ "claims": [+ { "claim": "drawn in code", "where": "on-screen", "source": { "sentence": "Pictures, films and interactive pieces drawn entirely in code, in 2D or in 3D.", "file": "skills/anidoodle/SKILL.md" } },+ { "claim": "marker comic", "where": "on-screen", "source": { "sentence": "| 2 | Marker comic | `koi.ts` | flat cel fills with a hard shadow edge, one heavy contour that thickens away from the light |", "file": "skills/anidoodle/references/styles.md" } }+ ]+}diff --git a/skills/anidoodle/engine/facts/launchExampleBrand.json b/skills/anidoodle/engine/facts/launchExampleBrand.jsonnew file mode 100644index 0000000..ba97e7a--- /dev/null+++ b/skills/anidoodle/engine/facts/launchExampleBrand.json@@ -0,0 +1,11 @@+{+ "version": 1,+ "about": "The ledger of launchExampleBrand, a demo launch film for an invented product ('Lantern', no real company) in a custom look: anidoodle's worked example of the look layer. Its words describe the mock product shown on screen, written for the template, labelled generated. The source map and the library rows are made-up sample data in mock screens, not claims.",+ "claims": [+ { "claim": "READ LESS.", "where": "on-screen", "generated": true, "note": "demo slogan for an invented product, states no fact" },+ { "claim": "KNOW MORE.", "where": "on-screen", "generated": true, "note": "demo slogan for an invented product, states no fact" },+ { "claim": "Then it cites", "where": "on-screen", "generated": true, "note": "describes the mock library screen beside it; the product is invented" },+ { "claim": "every page.", "where": "on-screen", "generated": true, "note": "second line of 'Then it cites every page.', describes the mock library screen beside it; the product is invented" },+ { "claim": "A reading desk that keeps your sources straight", "where": "on-screen", "generated": true, "note": "demo tagline for an invented product, states no fact" }+ ]+}diff --git a/skills/anidoodle/engine/facts/launchExampleClean.json b/skills/anidoodle/engine/facts/launchExampleClean.jsonindex 75b6d29..ca08799 100644--- a/skills/anidoodle/engine/facts/launchExampleClean.json+++ b/skills/anidoodle/engine/facts/launchExampleClean.json@@ -4,8 +4,8 @@"claims": [{ "claim": "ASK ONCE.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product, states no fact" },{ "claim": "DONE.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product, states no fact" },- { "claim": "Books close", "where": "on-screen", "generated": true, "note": "describes the mock UI on screen beside it (its rows reaching their after state); the product is made up" },- { "claim": "themselves.", "where": "on-screen", "generated": true, "note": "second line of 'Books close themselves.', describes the mock UI beside it; the product is made up" },+ { "claim": "Month end,", "where": "on-screen", "generated": true, "note": "describes the mock month-close screen beside it; the product is made up" },+ { "claim": "one click.", "where": "on-screen", "generated": true, "note": "second line of 'Month end, one click.', describes the one press on the mock screen beside it; the product is made up" },{ "claim": "And it shows", "where": "on-screen", "generated": true, "note": "describes the mock reports screen beside it; the product is made up" },{ "claim": "you where.", "where": "on-screen", "generated": true, "note": "second line of 'And it shows you where.', describes the mock reports screen beside it; the product is made up" },{ "claim": "Bookkeeping that does itself", "where": "on-screen", "generated": true, "note": "demo tagline for a made-up product, states no fact" }diff --git a/skills/anidoodle/engine/facts/launchExampleCleanChat.json b/skills/anidoodle/engine/facts/launchExampleCleanChat.jsonnew file mode 100644index 0000000..9d2300d--- /dev/null+++ b/skills/anidoodle/engine/facts/launchExampleCleanChat.json@@ -0,0 +1,11 @@+{+ "version": 1,+ "about": "The ledger of launchExampleCleanChat, a demo launch film for a made-up product ('Tally') in the clean look with a chat ask. Its words describe the mock product shown on screen, written for the template, labelled generated. The chart and the UI's figures are made-up sample data in mock screens, not claims.",+ "claims": [+ { "claim": "ASK IT.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product, states no fact" },+ { "claim": "SEE WHY.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product: the chart answering the chat ask is mock data" },+ { "claim": "Then it fixes", "where": "on-screen", "generated": true, "note": "describes the mock inbox screen beside it; the product is made up" },+ { "claim": "the books.", "where": "on-screen", "generated": true, "note": "second line of 'Then it fixes the books.', describes the mock inbox screen beside it; the product is made up" },+ { "claim": "Bookkeeping that does itself", "where": "on-screen", "generated": true, "note": "demo tagline for a made-up product, states no fact" }+ ]+}diff --git a/skills/anidoodle/engine/package-lock.json b/skills/anidoodle/engine/package-lock.jsonindex 91f2ea3..e48c997 100644--- a/skills/anidoodle/engine/package-lock.json+++ b/skills/anidoodle/engine/package-lock.json@@ -1,12 +1,12 @@{"name": "anidoodle-engine",- "version": "0.9.6",+ "version": "0.10.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "anidoodle-engine",- "version": "0.9.6",+ "version": "0.10.0","dependencies": {"esbuild": "0.25.12"},diff --git a/skills/anidoodle/engine/package.json b/skills/anidoodle/engine/package.jsonindex 046ca43..1c6353a 100644--- a/skills/anidoodle/engine/package.json+++ b/skills/anidoodle/engine/package.json@@ -1,6 +1,6 @@{"name": "anidoodle-engine",- "version": "0.9.6",+ "version": "0.10.0","private": true,"type": "module","description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",diff --git a/skills/anidoodle/engine/reviews/launchClip.json b/skills/anidoodle/engine/reviews/launchClip.jsonnew file mode 100644index 0000000..ef64e47--- /dev/null+++ b/skills/anidoodle/engine/reviews/launchClip.json@@ -0,0 +1,61 @@+{+ "about": "anidoodle's own review record for launchClip, written by a fresh critic (an agent), not a person's review. launchClip is a frozen cut of the published launch film: every finding is kept here so it is seen, and closed as wontfix because the film is not re-cut.",+ "findings": [+ {+ "id": "c1-1",+ "p": "P1",+ "status": "wontfix",+ "note": "0.00-1.10 s (f1-33): the first second does nothing. The text is already typed and the cursor is already on Generate, and only the caret blinks. That is 27% of a 4 s test spent idle, so the hook arrives late. Fix: start about 0.3 s before the press, or hold the full sentence no longer than 0.3 s before the click.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-2",+ "p": "P1",+ "status": "wontfix",+ "note": "~1.03-1.10 s (f31-35): the press itself barely reads. The Generate button never visibly moves down (no scale or shade change), and the drop is already sitting on top of the button before the click, so it reads as a dot that was there, not ink the click squeezes out. Fix: a 2-3 frame press-down on the button (scale ~0.94, darker), with the drop swelling out of it only after the click.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-3",+ "p": "P1",+ "status": "wontfix",+ "note": "1.6-2.2 s (f49-66): the bloom is a heavy, solid black wobbly ring (donut) about 25 px thick at 1080p. It is the darkest, biggest shape in a pale UI and reads as a hole or stain more than ink blooming open. While the card squares off (f57-66) the ring gets clipped by the card's rectangle, leaving four black triangles in the corners that shrink away. That reads as a mask artifact, not ink. Fix: bloom as a soft spreading wash that thins as it grows and fades into the card edge, or round the clip to match the ring so no hard black corners show.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-4",+ "p": "P1",+ "status": "wontfix",+ "note": "2.2-4.0 s (f66-120, last frame): the style promised is 'marker comic' but the koi is thin, pale blue pencil construction lines. The last frame shows a faint sketch with two flat orange blobs and a half-laid cream fill: no bold marker outline, no comic ink. The test ends on what looks like a draft that is still loading, so it does not pay off the request it ends beside. Fix: bring in a bold dark marker outline pass by about 3.0 s so the final frame holds a recognisable marker-comic koi (outline plus the main orange patches) for the last ~0.4 s.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-5",+ "p": "P2",+ "status": "wontfix",+ "note": "1.30-1.60 s (f40-48): the drop's trail is a soft grey gradient smear, like a CSS motion blur, not ink. It also flies down-left to empty space, away from the thread bubble at top right. Fix: draw the trail as tapering ink droplets or a brush flick, and arc it so it reads as landing in the reply slot below the user bubble.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-6",+ "p": "P2",+ "status": "wontfix",+ "note": "2.70-2.95 s (f81-88): the header, the 'marker comic' label, the input, the button and the cursor all fade out together, while the window grows slightly (a camera push). The brief says the small print fades IN, but on screen it fades OUT. That leaves an empty top band, and the input disappears mid-fade, so the window reads as unfinished. Fix: decide the direction on purpose. If the goal is to end on card plus request, keep the push and crop the frame to them, so no empty chrome band remains.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-7",+ "p": "P2",+ "status": "wontfix",+ "note": "Whole clip: the 'turning' in the request never happens. The koi stays still, so nothing in the drawing moves except strokes and fills arriving. Fix: a slight body curve or tail flick in the last 0.5 s would make the answer match the request.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ }+ ]+}diff --git a/skills/anidoodle/engine/reviews/launchExample.json b/skills/anidoodle/engine/reviews/launchExample.jsonnew file mode 100644index 0000000..5ffca3c--- /dev/null+++ b/skills/anidoodle/engine/reviews/launchExample.json@@ -0,0 +1,76 @@+{+ "about": "anidoodle's own review record for launchExample, the drawn worked example of the launch template. Written by fresh critics (agents), not a person's review. A film made from the template gets its own record, written for that film (references/workflows/review.md).",+ "verdict": "ship (critic r4, an agent): no open P0 or P1; 1 open optional P2",+ "findings": [+ {+ "id": "d1-1",+ "p": "P1",+ "status": "fixed",+ "note": "Frames 120 to 140 (9:16): the answer card's byline words vanished under the thread's top while its dot stayed behind. The dot now goes with its words (inkCard), and a byline nearing the window's top fades out whole.",+ "by": "fresh critic r1, an agent; r2 (an agent) found d1-1 still open on 9:16 (the zone fade withheld the words, not the dot); fixed again and confirmed by fresh critic r3, an agent"+ },+ {+ "id": "d1-2",+ "p": "P1",+ "status": "fixed",+ "note": "The corner mark touched the chat window's bottom right corner (16:9 frames 0 and 345, 9:16 frames 0 and 270). It now sits clear of the window: beside it on 16:9 (the room creeps about that corner), under it on 9:16 with room for the hook's creep.",+ "by": "fresh critic r1, an agent; confirmed fixed by fresh critics r2 and r3 (agents)"+ },+ {+ "id": "d1-3",+ "p": "P1",+ "status": "fixed",+ "note": "The end card's install lines were each centred, so they started at different places. Every line now starts at the panel's left padding, as a terminal sets them.",+ "by": "fresh critic r1, an agent; confirmed fixed by fresh critics r2 and r3 (agents)"+ },+ {+ "id": "d2-1",+ "p": "P2",+ "status": "fixed",+ "note": "9:16 frames 110 to 120: the corner mark hid behind the leaned card, then popped back on top at 120. It now fades back over the travel's second half (r3: frames 142 to 148).",+ "by": "fresh critic r2, an agent; confirmed fixed by r3"+ },+ {+ "id": "d2-2",+ "p": "P2",+ "status": "fixed",+ "note": "9:16 frames 128 to 132: the cursor vanished in one frame during the lean. It now fades with the lean (r3: 106 to 114).",+ "by": "fresh critic r2, an agent; confirmed fixed by r3"+ },+ {+ "id": "d2-3",+ "p": "P2",+ "status": "fixed",+ "note": "9:16: the corner mark's right end sat on the right-hand zone's edge. It now sits 20 px inside the window's right edge, about 29 px clear of the zone.",+ "by": "fresh critic r2, an agent; confirmed fixed by r3"+ },+ {+ "id": "d3-1",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (round 2): a carried string fades over the band before a zone (9:16) or the frame's top and bottom edges (16:9, drawn look), measured from where it rests; the byline's dot fades with its words (critic r4 saw the dot pop on 9:16; fixed after, checked on the re-render: 16:9 fades over frames 126 to 129, 9:16 dot and words fade together 130 to 133).",+ "by": "fresh critic r3, an agent; checked by fresh critic r4, an agent"+ },+ {+ "id": "d3-2",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (round 2): the chat header recedes with the lean, fully faded before the travel carries it off (critic r4: fades from 108, gone by 116).",+ "by": "fresh critic r3, an agent; checked by fresh critic r4, an agent"+ },+ {+ "id": "d3-3",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (round 2): the 9:16 end card centres on the frame, x 540, inside the right-hand zone's edge (critic r4 measured centres 528 to 532, rightmost text at 889 of 929).",+ "by": "fresh critic r3, an agent; checked by fresh critic r4, an agent"+ },+ {+ "id": "d4-1",+ "p": "P2",+ "status": "fixed",+ "note": "End card sits 8 to 20 px left of centre on both shapes, consistent across lines: likely the headline glyphs' side bearing. Optional polish; centring by ink bounds instead of advance width would fix it. Fixed (template round 3): the cause was the end card's settle, a 3 % lean about the dot at the name's right end, which carried every line left by 3 % of the dot's distance from the axis. The settle now zooms about the card's axis, and the name with its dot is centred by its ink (kinetic.inkSpan). Measured on the render: every line within 1.5 px of the centre on 16:9 and 9:16 (test endCardCentre).",+ "by": "fresh critic r4, an agent"+ }+ ]+}diff --git a/skills/anidoodle/engine/reviews/launchExampleBrand.json b/skills/anidoodle/engine/reviews/launchExampleBrand.jsonnew file mode 100644index 0000000..cc723f5--- /dev/null+++ b/skills/anidoodle/engine/reviews/launchExampleBrand.json@@ -0,0 +1,97 @@+{+ "about": "anidoodle's own review record for launchExampleBrand, the worked example of a brand's own look. Written by a fresh critic (an agent), not a person's review.",+ "verdict": "fix: no P0, but six P1 open. The type, palette and end card read as Lantern's own, but the declared shapes are not honoured (pill composer and pill button), the 9:16 cut is off centre and top heavy, both transitions out of the answer have dead or colliding frames, the logo is a 20 px glyph that never reaches the end card, and the answer map says nothing a viewer can read (fresh critic r1, an agent). What works: Lora and Instrument Sans read crisply on the dark ground, the amber is used sparingly, the answer iris reads at speed, and the end card is centred and readable on both shapes",+ "findings": [+ {+ "id": "br1-1",+ "p": "P1",+ "status": "open",+ "note": "The brand's declared shapes are not what renders, so it reads as the clean template with a dark palette. The source declares shape { bubble: square, composer: bar, button: square }. Bubbles are square (good), but the composer is a fully rounded pill with a thin outline on both shapes (16:9 full frames 1.6 s and 4.4 s, 9:16 1.0 s and 3.6 s), and the library's 'Check all' button is a full pill (16:9 and 9:16, 11 to 16 s), while the composer's Ask button is a near square. Three corner languages in one film. Fix: make the composer a flat bar (square or the 14 px radius) and 'Check all' the same square button as Ask.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-2",+ "p": "P1",+ "status": "open",+ "note": "9:16 layout is off centre and top heavy through the chat and library beats. Full frame 1.0 s and 3.6 s (540 px wide sample): the window runs from x 9 to 15 on the left to x 466 to 471, so the left margin is about 2 to 3 percent of width and the right about 13 percent; everything sits in the top 72 percent with the bottom 28 percent empty dark ground. Library beat (12.5 s): card from x 36 to 444, right margin more than double the left, bottom third empty. On a phone this reads as a 16:9 layout squeezed into a corner. Fix: centre the window and library horizontally and use the full height (or centre the block vertically).",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-3",+ "p": "P1",+ "status": "open",+ "note": "The exit from the answer to the word page has dead frames on both shapes. 16:9, 4.8 to 6.4 s (10 fps strip): the composer fades, then the whole window slides slowly up off frame for about 1.3 s; from 5.8 to 6.3 s the screen is mostly an empty grey slab (the bottom of the window) with nothing to read before READ rises in. 9:16, 4.4 to 6.4 s: the window zooms in slowly for about 1.5 s (header and bubble fade), then is pushed right; the full frame at 6.0 s is the left 40 percent bare ground and a grey slab with the map card cut by the right edge, and at 6.1 to 6.3 s 'AD LESS.' is clipped against the slab's edge. The two shapes also use different transitions (vertical lift vs horizontal push). Fix: one quick, matched push (about 0.5 s) that carries the map card out as the words come in, with no empty slab frames.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-4",+ "p": "P1",+ "status": "open",+ "note": "The iris from the library to the end card collides on 9:16. 15.9 to 16.6 s (15 fps strip, full frame 16.1 s): the iris opens from the drop at the upper right, so the end card is revealed lopsided: for about 0.5 s the wordmark reads 'ern.', 'tern.', 'antern.' while the tagline and the npm pill are drawn over the still visible library card (the 'Field notes' and 'Interview' rows sit under 'npm install lantern' at 16.3 to 16.5 s, and a tagline fragment 'es' pokes out of the ring at 16.1 s). 16:9 is cleaner but shows a faint dark ring edge over the end card at about 16.2 s and the wordmark settles about 20 px sideways after the reveal (16.4 to 16.5 s). Fix: hide or fade the library inside the iris, centre the iris on the frame (or the wordmark), and land the end card without the post reveal drift.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-5",+ "p": "P1",+ "status": "open",+ "note": "The logo is not doing a logo's job. The brand has its own lantern mark (assets/brand/lantern/lanternMark.svg), but in the film it appears only as a roughly 20 by 30 px glyph in the window header (16:9 crop at 1.6 s), where it reads as a battery or jar, with a large gap before the 'Lantern' title so it looks detached. It never appears on the end card (19 s, both shapes), which uses the type wordmark plus an amber dot. A brand film should close on its mark. Fix: put the lantern mark on the end card beside or above the wordmark at a size where the lantern shape reads, and tighten the header gap.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-6",+ "p": "P1",+ "status": "open",+ "note": "The answer does not answer the question. 'which sources disagree?' is answered by six unlabelled dots, two ringed in amber (16:9 4.4 s, 9:16 6.0 s). A viewer cannot tell which sources these are or that the rings mean 'these two disagree'; the label is only 'Your sources, mapped'. On 16:9 the card is about 410 px wide on the left of a 1380 px window and the right 60 percent of the window is empty, so the payoff is small as well as mute. On 9:16 it is about a quarter of the frame width. Fix: label the two ringed nodes (for example 'Field notes, 2019' and 'Survey, spring', which the library beat then reuses), a short 'these two disagree' line, and a bigger card.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-7",+ "p": "P2",+ "status": "open",+ "note": "The corner 'Lantern' stamp is small grey type and on 9:16 it is not in a corner. 16:9: bottom right, about 18 px tall, grey, 0 to 16 s. 9:16: it hangs at about two thirds height just under the window and the library card (full frames 1.0, 3.6, 12.5, 16.1 s), so it reads as a stray caption. The header subtitle 'your reading desk' and the 'Ask Lantern...' placeholder are also grey. The person has rejected grey and tiny text before. Fix: drop the stamp (the header already says Lantern) or put it in the real corner at a readable size.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-8",+ "p": "P2",+ "status": "open",+ "note": "The second drop is born on top of the library nav. 15.3 to 15.6 s on both shapes: the amber dot appears over the 'Map' tab (covering its label) and next to 'Check all' before lifting. It reads as a glitch on the tab, not a drop leaving the product. Fix: emit it from the highlighted 'Field notes' row or from 'Check all' itself.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-9",+ "p": "P2",+ "status": "open",+ "note": "The cursor idles above the library. After 'Check all' is pressed (cue 11.27 s) the cursor sits in empty ground above the card, outside the UI, until about 16 s on both shapes (16:9 full frame 12.5 s at x 1680, y 295). Fix: let it rest on the button or leave the frame after the click.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-10",+ "p": "P2",+ "status": "open",+ "note": "Copy mismatch in the library beat: the headline says 'Then it cites every page.' but the button pressed is 'Check all' and the tags say 'cited' while the values are page counts (12 p., 40 p., 8 p.). 'every page' plus a page count suggests the whole document was cited. Minor, but a launch film's one claim should match its UI word for word. Fix: a button like 'Cite all', or show a page reference such as 'p. 4' in the tag.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-11",+ "p": "P2",+ "status": "open",+ "note": "The word page holds still for about 2.5 s. 16:9 and 9:16, about 6.9 to 9.4 s: READ LESS. / KNOW MORE. lands and nothing moves (6 fps strip shows identical frames). For a 'lively' temperament that is a freeze. On 16:9 the block also sits left (x 160 to 1310) with the right third empty, which is fine as editorial type but makes the hold feel emptier. Fix: shorten the hold to about 1.5 s or give it a small live move (the amber line drawing under, a slow drift).",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-12",+ "p": "P2",+ "status": "open",+ "note": "9:16 hook: the question breaks into three short lines ('which / sources / disagree?') inside a narrow composer, with the Ask button vertically off the text block (full frame 1.0 s). It reads cramped next to the one line 16:9 hook. Fix: a wider composer (see br1-2) so it fits on two lines, Ask aligned to the text's last line or centre.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-13",+ "p": "P2",+ "status": "open",+ "note": "Sound, measured only (not listened to): integrated about -14.1 LUFS, true peak -1.4 dBTP, LRA 4.8 LU, which is fine for social. The first 2 s average about -30 dB (key ticks only), so the hook is near silent on a phone. The film also reuses the clean example's score (tallyScore), so the brand example does not have its own sound. Fix: a soft bed under the typing, and a short Lantern cue rather than the Tally score.",+ "by": "fresh critic r1, an agent"+ }+ ]+}\ No newline at end of filediff --git a/skills/anidoodle/engine/reviews/launchExampleClean.json b/skills/anidoodle/engine/reviews/launchExampleClean.jsonnew file mode 100644index 0000000..a208be1--- /dev/null+++ b/skills/anidoodle/engine/reviews/launchExampleClean.json@@ -0,0 +1,90 @@+{+ "about": "anidoodle's own review record for launchExampleClean, the worked example of the launch template. Written by fresh critics (agents) over two rounds, not a person's review. A film made from the template gets its own record, written for that film (references/workflows/review.md).",+ "verdict": "ship (builder agent, template r3): no open P0 or P1; every P2 from critics r1 and r2 fixed and the film re-shipped PASS on 16:9 and 9:16",+ "findings": [+ {+ "id": "c1-1",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): the end card no longer holds still. As its last part lands the page settles in 3 % about the dot on an out-cubic, and the install line is fully on for more than 3 s of it.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-2",+ "p": "P1",+ "status": "fixed",+ "note": "Words sink at frames 910 to 935, and the headline is fully gone before the dot travels and the bloom opens at 960 to 984. Nothing is cut mid-word.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c1-3",+ "p": "P1",+ "status": "fixed",+ "note": "Copy now reads 'Month end, one click.' (frames 560 to 700), and the cursor click on Close month at 596 agrees with the words.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c1-4",+ "p": "P1",+ "status": "fixed",+ "note": "The bloom is now the loudest moment: momentary -10.5 LUFS at 16.3 s against a body of about -12.5, true peak -1.4 dBFS. Slim margin; a short dip before the drop would sell it. Measured only: a person must listen.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c1-5",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): the grid card's footer stamp is set inline, one gap after the text block (endCard stamp: \"inline\"), and a lockup with a descender declares it (descent 0.3), so the line under 'Tally' keeps its air.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-6",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): on 16:9 the travels alternate, down then up then down; no two in a row arrive from the same side.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-7",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): on 9:16 the corner mark sits flush with the content's right edge, at the bottom of the safe rectangle (the platforms' bottom 25 % holds no text, so that is the frame's usable corner), clear of the window.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-8",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): in a tall frame the product's rows are tall touch rows, so the panel fills the safe rectangle above the corner mark. The bottom 25 % stays empty by design: it is the platforms' caption zone.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-9",+ "p": "P2",+ "status": "fixed",+ "note": "Counter steps 14 to 3 to 0 across frames 110 to 140, and rows flip to 'matched' one by one.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c2-1",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): the drop swells left of Explain and clear of its word on both shapes (launchGrammar checks it at any push).",+ "by": "fresh critic r2, an agent; fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c2-2",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): frame 0 shows the prompt typed to a whole word ('match every').",+ "by": "fresh critic r2, an agent; fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c2-3",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): after each click the pointer rests just above the product window, never on a row's figure (on 9:16 it had settled on '$1,208' at frame 935).",+ "by": "fresh critic r2, an agent; fixed in template r3, checked by the builder agent"+ }+ ]+}diff --git a/skills/anidoodle/engine/reviews/launchExampleCleanChat.json b/skills/anidoodle/engine/reviews/launchExampleCleanChat.jsonnew file mode 100644index 0000000..e182a48--- /dev/null+++ b/skills/anidoodle/engine/reviews/launchExampleCleanChat.json@@ -0,0 +1,97 @@+{+ "about": "anidoodle's own review record for launchExampleCleanChat, the worked example of the clean look with a chat ask. Written by a fresh critic (an agent), not a person's review. A film made from the template gets its own record (references/workflows/review.md).",+ "verdict": "fix: no P0 or P1 open (cc1-3 iris and cc2-1 16:9 thread are fixed); after round 3 these P2s remain: grey tiny type (cc1-4), orphan end card pill on 16:9 (cc1-5), handover frames (cc1-6), near silent hook, measured only (cc1-7), 9:16 layout and small answer card (cc2-2, cc2-3), new small 16:9 answer card (cc3-1) and iris ring corner fragments (cc3-2) (fresh critic r3, an agent)",+ "findings": [+ {+ "id": "cc1-1",+ "p": "P1",+ "status": "fixed",+ "note": "The composer does not travel as one object. 16:9, 1.1 to 2.2 s (10 fps strip): it slides down at full size (it even grows a little from 1.3 to 1.7 s). Its vertical travel is almost done by 1.8 s (about 20 px left of 1080), and then it shrinks to about 55 % width from 1.8 to 2.1 s, nearly in place. That reads as a second move after the landing. 9:16 does the same at 1.8 to 2.4 s, ending as a narrow box with the question broken over three small lines. Scale should run on the same curve as the travel and finish with it. Checked r2: 16:9 at 0.8 to 2.6 s (10 fps strip) and 9:16 at the same span: the composer slides from mid window to the bottom between about 1.3 and 1.9 s at one constant size and stays that size after it lands; no shrink while moving or after. The question keeps two or three large lines on 9:16. Fixed on both shapes.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r2, an agent"+ },+ {+ "id": "cc1-2",+ "p": "P1",+ "status": "fixed",+ "note": "The inbox reorder glitches instead of sliding. 16:9, 11.5 to 11.8 s (8 fps strip): at 11.5 s the 'Team lunch' row is half see-through on top of the slot below it. At 11.6 s only 'Cloud hosting' is left, with one empty ghost row and a blank lower half in the panel. At 11.75 s a faded 'Design tool' row overlaps 'Team lunch'. That breaks the opaque rule, and on a normal viewing the rows look like they vanish and collide. Same beat on 9:16 at about 11.5 s. Rows should keep full opacity and visibly swap places. Checked r2: 16:9 and 9:16 at 10.4 to 12.8 s (8 fps strips) and a full frame at 12.5 s: there is no reorder any more; the three rows stay fully opaque in place, no ghost row, no overlap, and they tick to matched in turn at about 11.6 to 11.8 s. Fixed on both shapes.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r2, an agent"+ },+ {+ "id": "cc1-3",+ "p": "P1",+ "status": "fixed",+ "note": "The answer's iris does not read, and it is the payoff. 16:9, 2.6 to 3.6 s: the blue drop flying from Ask to the chart spot reads well, but it vanishes and the iris that follows is a cream disc opening on a cream card on a white window (at 3.1 s it is a faint 40 px circle you can barely see). At speed it looks like the chart fading in, not an iris opening. Same on 9:16 at 3.0 to 3.5 s. Give the iris edge contrast (an ink or blue rim, or open it onto the canvas colour) so the circle shape is seen. Still stands r2, half fixed: the iris is now a pale blue disc instead of cream. On 16:9 (full frame 3.55 s, strip 3.3 to 4.0 s) it is a 245 px disc and the circle shape reads in a still, though it has no rim and is low contrast (pale blue on a pale pink card on white). On 9:16 (full frame 3.5 s) the whole chart card is only about 265 px wide, the disc is about 85 px and very faint on a near white card, so at speed it still reads as a fade, not an iris. Needs an edge (ink or accent rim) and, on 9:16, a bigger answer card (see cc2-3). Checked r3: 16:9 strip 3.0 to 4.1 s (10 fps) and 9:16 the same span: the drop lands at about 3.4 s, then a thin solid accent blue ring opens from about 40 px to past the card edge by 3.9 s, with the chart showing inside it. The circle is clearly an iris at speed on both shapes, not a fade. Small leftover logged as cc3-2.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r3, an agent"+ },+ {+ "id": "cc1-4",+ "p": "P2",+ "status": "open",+ "note": "Tiny grey text that does not earn its place. A corner 'Tally' stamp, about 10 px tall on 1080, sits bottom right in every shot from 0 to about 15 s on both shapes. You cannot read it at a phone glance, and it repeats the wordmark. The window header subtitle 'your books, answered' (0 to 5 s) and the grey 'matched' chips on the secondary rows (11.7 to 15 s) are also small grey type. The person has rejected grey and tiny text before. Still stands r2: the corner 'Tally' stamp (grey, about 18 px on 1080) is still bottom right from 0 to about 16 s on both shapes; the grey 'your books, answered' subtitle (0 to 5 s) and grey 'matched' chips on the two secondary rows (11.7 to 16 s, full frame 12.5 s) are unchanged. Still stands r3: full frames 0.5 s and 2.8 s: grey corner \"Tally\" stamp (about 20 px) still bottom right on both shapes, grey \"your books, answered\" subtitle unchanged; grey \"matched\" chips on the two lower inbox rows from about 11.7 s unchanged.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-5",+ "p": "P2",+ "status": "open",+ "note": "End card hierarchy, 16:9 from 15.5 s: the 'tally.example' pill floats on its own at x 1193 to 1591, 190 px past the end of the tagline, and lines up with no edge of the block above. It reads as an orphan, and the solid blue pill is the second-loudest thing on the card, louder than the tagline. The tagline also sits tight on the npm line (about 40 px) but far from the wordmark (about 90 px), so the two lower lines read as one clump. On 9:16 the pill stacks under the block and sits better. Still stands r2: 16:9 end card at 17 s, the 'tally.example' pill still floats alone at x 1185 to 1575, 70 px past the tagline, aligned to nothing, and stays the second loudest object; tagline still sits tight on the npm line and far from the wordmark. 9:16 stacks it and is fine. Still stands r3: 16:9 full frame 17 s: the \"tally.example\" pill still floats alone at x 1185 to 1575, about 70 px past the tagline, aligned to nothing, the second loudest thing on the card. 9:16 stacks it under the block and is fine.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-6",+ "p": "P2",+ "status": "open",+ "note": "The handover from the chart to the word page leaves poster-bad frames. 16:9, 5.4 to 6.2 s: the window is zoomed and cropped, with two white slabs (window, then a second copy of the chart card's foot) sliding up off the frame while 'ASK' rises from the bottom edge. 9:16, 5.9 to 6.4 s: a vertical wipe cuts through the words, so 'SK IT.' shows with the A still hidden behind the white window. Start the words after the wipe has passed their left edge. Still stands r2: 16:9 at 5.4 to 5.8 s still shows two or three stacked copies of the window and chart card sliding up while 'ASK' rises from the bottom edge. 9:16 at 6.0 to 6.4 s the vertical wipe still cuts the words ('K IT.', 'SK IT.') beside a half hidden chart card. Still stands r3: 16:9 strip 5.3 to 6.4 s: at 5.3 s two copies of the chart card show in two stacked white slabs, then the slabs slide up while \"ASK\" rises cut by the bottom edge (5.5 to 5.7 s). 9:16 strip same span: the vertical wipe still slices the words (\"IT\", \"K IT.\", \"SK IT.\") beside a half hidden chart card at 5.9 to 6.3 s.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-7",+ "p": "P2",+ "status": "open",+ "note": "Sound, measured only, so a person must listen: integrated -14.1 LUFS, true peak -1.4 dBFS, the same on both shapes. The loudest momentary is -11.6 LUFS at 7.5 s on the 'ASK IT. SEE WHY.' page. The answer opening (3 s, -16.5) and the end card's arrival (15.5 s, -12.4) are not the loudest moments. The first 2 s sit at -25 to -30 LUFS momentary, so the hook is nearly silent while the question types. Still stands r2: measured again, integrated -14.1 LUFS on both shapes; momentary is -25 to -28.5 LUFS from 0.5 to 2.1 s (the hook is near silent) and the loudest moments (-11.5) are at 7.6 s and 16.1 s, not the answer opening at 3 s (-15.6). A person must listen. Still stands r3: measured again (cannot hear): integrated -14.1 LUFS, true peak -1.2 (16:9) and -1.4 dBFS (9:16); momentary -24 to -30 LUFS from 0.5 to 2.1 s; loudest moments -11.7 at 7.5 s and -12.2 at 9.0 s, while the answer opening is -13.3 at 3.4 s. A person must listen.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-8",+ "p": "P2",+ "status": "fixed",+ "note": "The thread bubble 'why did hosting go up?' and the chart label 'Cloud hosting, by month' are about 14 px type on 16:9 (2.5 to 5.5 s). A phone viewing a landscape film shows them at roughly 5 px. They are context the viewer already saw typed large, so it is not fatal, but the answer's label is the only words that say what the chart shows. Checked r2: on 16:9 the chart label 'Cloud hosting, by month' is now about 22 px (full frame 4.5 s) and the chart card is about 490 px wide, readable. The thread bubble no longer shows long enough to matter on 16:9 (see cc2-1). On 9:16 the bubble and label are about 30 px, readable. The legibility point is fixed; the thread problem is new and logged as cc2-1.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r2, an agent"+ },+ {+ "id": "cc2-1",+ "p": "P1",+ "status": "fixed",+ "note": "New since the composer now stays big: on 16:9 the thread has no room for the question. The user bubble 'why did hosting go up?' appears at the top of the thread at about 2.5 s and scrolls straight up under the header rule: at 2.8 s (full frame) it is cut in half by the header line, and by 3.3 s it is gone, so the answer chart opens with no question above it. The chart card's bottom is also cut flat by the thread's clip just above the composer (3.55 s and 4.5 s, square bottom corners, shadow cut). 9:16 keeps the bubble and is fine. Give the thread the height it needs (shorter composer after the send, or a taller window) so question and answer are seen together. Checked r3: 16:9 full frames 2.8 s and 4.5 s and strip 3.0 to 4.1 s: the question bubble sits right under the header rule, whole, from about 2.6 s through 5 s, and the chart card below it has round bottom corners and its full shadow, about 200 px clear of the composer. Question and answer are seen together. The cost is a smaller card, logged as cc3-1.",+ "by": "fresh critic r2, an agent; checked fixed by fresh critic r3, an agent"+ },+ {+ "id": "cc2-2",+ "p": "P2",+ "status": "open",+ "note": "9:16 composition: from 0 to about 5 s the app window sits in the top 72 % of the frame and off centre (about 18 px margin left, 137 px right at 1080 wide; full frames 0.5 s and 3.5 s), leaving a 540 px empty band of canvas at the bottom. Reads as a misplaced layout, not as intent. Centre it and use the height. Still stands r3: 9:16 full frame 0.5 s: window still x 33 to 928 (33 px margin left, 152 right) and y 268 to 1364, with about 556 px of empty canvas below it, up to about 5 s.",+ "by": "fresh critic r2, an agent"+ },+ {+ "id": "cc2-3",+ "p": "P2",+ "status": "open",+ "note": "9:16 answer card is too small for the payoff: the chart card is about 265 px wide on a 1080 frame (full frames 3.5 s and 4.5 s), with the label, the bubble and a lot of empty white window below it. The film's key image is a thumbnail until the zoom at about 5 s. Still stands r3: 9:16 full frame 4.5 s (zoom already starting): chart card about 280 px wide on 1080, the rest of the window empty white below it; the key image is still a thumbnail until the zoom.",+ "by": "fresh critic r2, an agent"+ },+ {+ "id": "cc3-1",+ "p": "P2",+ "status": "fixed",+ "note": "16:9: the cc2-1 fix shrank the answer card. Full frame 4.5 s: the chart card is about 280 px wide (x 402 to 684) on a 1920 frame, under 15 % of the width, with the right two thirds of the thread empty between the bubble and the composer. The payoff image now reads as a thumbnail on 16:9 too (same as cc2-3 on 9:16). The room is there: a wider card, or a slightly shorter composer after the send, would let it be about twice the size. Fixed after r3 (builder agent): the clean hook, which is also the dock, is now set at the hook's smallest size (56 px on 16:9, 64 px on 9:16), so the docked composer is 171 px tall on 16:9 instead of 296 and the answer card is 393 px instead of 280 (checked on the render at 3.8 to 4.5 s). Not rechecked by a fourth critic: review.md stops at round 3.",+ "by": "fresh critic r3, an agent; fixed by the builder agent after r3"+ },+ {+ "id": "cc3-2",+ "p": "P2",+ "status": "fixed",+ "note": "Iris end, 16:9 strip 3.8 to 3.9 s and 9:16 the same: the accent ring grows past the card, so for two or three frames it shows only as four blue arc fragments at the card corners before it vanishes. Seen only on pause; fading the ring as it reaches the card edge would close it cleanly. Fixed after r3 (builder agent): the rim is drawn only while the whole ring is inside the card (test irisRim), so no arcs are left in the corners (checked at 3.77 to 3.97 s on both shapes). Not rechecked by a fourth critic.",+ "by": "fresh critic r3, an agent; fixed by the builder agent after r3"+ }+ ]+}diff --git a/skills/anidoodle/engine/src/canvas-core/brandKit.ts b/skills/anidoodle/engine/src/canvas-core/brandKit.tsnew file mode 100644index 0000000..e31f4e7--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/brandKit.ts@@ -0,0 +1,144 @@+// BRAND KIT. Draws a brand's own elements exactly as `tools/brand.mjs import` exported them, and only+// ever moves them. A brand mark redrawn by eye, morphed through a blur or squashed into an ellipse is a+// different mark to its owner: a launch film lost four rounds of notes to a goo "mitosis" of a logo and+// to brand dots squashed out of round. So the rule lives in the code, not only in the docs:+// - parts are filled from their exported paths, never rebuilt;+// - an element may be translated, rotated, uniformly scaled, clipped and layered;+// - drawEl throws on a non-uniform scale or a skew in the current transform, unless the caller names the+// gag the squash serves ({ allowSquash: "the dot is crushed by the falling chat window" });+// - the caller's globalAlpha and transform are kept (a helper that resets alpha breaks every fade);+// - each drawn element reports its on-screen box to the frame probe ("brand:<name>"), so the shape scans see it.+//+// import { BRAND } from "./myBrand"; // written by brand.mjs import+// ctx.save(); ctx.translate(x, y); ctx.rotate(a); ctx.scale(s, s);+// drawEl(ctx, BRAND.elements.mark); ctx.restore();+// riseIn(ctx, BRAND.elements.lockup.parts[3], k); // one letter rises from behind its own baseline+import { probeRect, type Ctx, type Env, type ProbeRec } from "./core";++export type BrandStop = [offset: number, colour: string, alpha: number];+export type BrandPaint =+ | { type: "solid"; c: string }+ | { type: "lin"; x1: number; y1: number; x2: number; y2: number; stops: BrandStop[]; m?: number[] }+ | { type: "rad"; cx: number; cy: number; r: number; fx: number; fy: number; stops: BrandStop[]; m?: number[] }+ | { type: "none" };+export type BrandPart = {+ d: string; fill: BrandPaint; rule: string; op: number; bb: number[]; m?: number[];+ stroke?: { paint: BrandPaint; w: number; cap: string; join: string; op: number };+ clip?: { paths: { d: string; m: number[] }[] };+};+export type BrandElement = { w: number; h: number; parts: BrandPart[] };++const P2 = new Map<string, Path2D>();+/** One Path2D per path string, built once (it never changes, so caching it keeps the draw pure). */+const path = (d: string) => { let p = P2.get(d); if (!p) { p = new Path2D(d); P2.set(d, p); } return p; };+const hexA = (h: string, a: number) => { if (a >= 1 || !/^#[0-9a-f]{6}$/i.test(h)) return h; const n = parseInt(h.slice(1), 16); return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`; };++const gradient = (ctx: Ctx, f: BrandPaint): CanvasGradient | string => {+ if (f.type === "solid") return f.c;+ if (f.type === "none") return "rgba(0,0,0,0)";+ const g = f.type === "lin" ? ctx.createLinearGradient(f.x1, f.y1, f.x2, f.y2) : ctx.createRadialGradient(f.fx, f.fy, 0, f.cx, f.cy, f.r);+ for (const [o, c, a] of f.stops) g.addColorStop(Math.max(0, Math.min(1, o)), hexA(c, a));+ return g;+};+/** Fill a path with a paint. A gradient with its own matrix is drawn in gradient space under a clip, which is exact for any affine. */+const fillWith = (ctx: Ctx, p: Path2D, rule: CanvasFillRule, f: BrandPaint, bb: number[]) => {+ if (f.type === "none") return;+ const m = f.type !== "solid" ? f.m : undefined;+ if (!m) { ctx.fillStyle = gradient(ctx, f); ctx.fill(p, rule); return; }+ ctx.save(); ctx.clip(p, rule); ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]); ctx.fillStyle = gradient(ctx, f);+ const det = m[0] * m[3] - m[1] * m[2] || 1, inv = [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det];+ const pad = 2, corners = [[bb[0] - pad, bb[1] - pad], [bb[0] + bb[2] + pad, bb[1] - pad], [bb[0] - pad, bb[1] + bb[3] + pad], [bb[0] + bb[2] + pad, bb[1] + bb[3] + pad]].map(([x, y]) => [inv[0] * x + inv[2] * y + inv[4], inv[1] * x + inv[3] * y + inv[5]]);+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);+ ctx.fillRect(Math.min(...xs), Math.min(...ys), Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));+ ctx.restore();+};++/** Draw one exported part as it is, times the caller's alpha. */+export function drawPart(ctx: Ctx, p: BrandPart, alpha = 1) {+ const g = ctx.globalAlpha;+ ctx.save();+ if (p.clip) clipIn(ctx, p);+ if (p.m) ctx.transform(p.m[0], p.m[1], p.m[2], p.m[3], p.m[4], p.m[5]);+ ctx.globalAlpha = g * alpha * (p.op ?? 1);+ // bb is in element space; the gradient fill wants it in the part's own space, so map it back through m+ fillWith(ctx, path(p.d), (p.rule === "evenodd" ? "evenodd" : "nonzero") as CanvasFillRule, p.fill, p.m ? localBox(p) : p.bb);+ if (p.stroke) {+ ctx.globalAlpha = g * alpha * (p.stroke.op ?? 1); ctx.lineWidth = p.stroke.w; ctx.lineCap = p.stroke.cap as CanvasLineCap; ctx.lineJoin = p.stroke.join as CanvasLineJoin;+ ctx.strokeStyle = gradient(ctx, p.stroke.paint); ctx.stroke(path(p.d));+ }+ ctx.restore();+ ctx.globalAlpha = g; // keeps any fade the caller set+}+/** Clip to the part's clip-path: its shapes (a union) carry their own matrices in element space. */+function clipIn(ctx: Ctx, p: BrandPart) {+ const c = new Path2D();+ for (const q of p.clip!.paths) c.addPath(path(q.d), { a: q.m[0], b: q.m[1], c: q.m[2], d: q.m[3], e: q.m[4], f: q.m[5] });+ ctx.clip(c);+}+const localBox = (p: BrandPart) => {+ const m = p.m!, det = m[0] * m[3] - m[1] * m[2] || 1, inv = [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det];+ const [x, y, w, h] = p.bb, pts = [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].map(([a, b]) => [inv[0] * a + inv[2] * b + inv[4], inv[1] * a + inv[3] * b + inv[5]]);+ const xs = pts.map((q) => q[0]), ys = pts.map((q) => q[1]);+ return [Math.min(...xs), Math.min(...ys), Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)];+};++/**+ * How the current transform distorts a shape: the x and y scales and the skew (cosine of the angle between the axes).+ * A uniform scale with a rotation has sx = sy and skew 0.+ */+export const distortion = (m: { a: number; b: number; c: number; d: number }) => {+ const sx = Math.hypot(m.a, m.b), sy = Math.hypot(m.c, m.d), skew = sx && sy ? (m.a * m.c + m.b * m.d) / (sx * sy) : 0;+ return { sx, sy, skew, squash: Math.max(sx, sy) ? Math.abs(sx - sy) / Math.max(sx, sy) : 0 };+};+export type DrawElOpts = { alpha?: number; name?: string; allowSquash?: string; env?: Env; probe?: boolean };+/** The element's ink box in element space: the union of its parts' boxes. */+export const inkBox = (el: BrandElement) => {+ if (!el.parts.length) return [0, 0, el.w, el.h];+ const x0 = Math.min(...el.parts.map((p) => p.bb[0])), y0 = Math.min(...el.parts.map((p) => p.bb[1]));+ return [x0, y0, Math.max(...el.parts.map((p) => p.bb[0] + p.bb[2])) - x0, Math.max(...el.parts.map((p) => p.bb[1] + p.bb[3])) - y0];+};+/**+ * Tell the frame probe where a brand element landed (device pixels, kind "box", label "brand:<name>"), so the+ * scans that look for shapes (layerscan's shape-over-a-face check, framecheck's edge cuts) see brand marks too.+ * With the film's env it goes through probeRect (which reports only on the frame's own canvas); without one it+ * reports straight to the probe, which suits the usual case of a mark drawn on the frame. Off when no probe is installed.+ */+const reportBox = (ctx: Ctx, el: BrandElement, opts: DrawElOpts) => {+ if (opts.probe === false || (opts.alpha ?? 1) * ctx.globalAlpha < 0.1) return;+ const [x, y, w, h] = inkBox(el), label = `brand:${opts.name ?? "element"}`;+ if (opts.env) { probeRect(ctx, opts.env, x, y, w, h, label, "box"); return; }+ const p = (globalThis as { __ANIDOODLE_PROBE__?: (r: ProbeRec) => void }).__ANIDOODLE_PROBE__;+ if (!p || typeof ctx.getTransform !== "function") return;+ const m = ctx.getTransform(), pts = [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].map(([a, b]) => [m.a * a + m.c * b + m.e, m.b * a + m.d * b + m.f]);+ p({ kind: "box", label, x0: Math.min(...pts.map((q) => q[0])), y0: Math.min(...pts.map((q) => q[1])), x1: Math.max(...pts.map((q) => q[0])), y1: Math.max(...pts.map((q) => q[1])) });+};+/** Draw a whole brand element. Throws on a squash or skew of more than 1% unless `allowSquash` names the gag. */+export function drawEl(ctx: Ctx, el: BrandElement, opts: DrawElOpts = {}) {+ if (!opts.allowSquash && typeof ctx.getTransform === "function") {+ const t = distortion(ctx.getTransform());+ if (t.squash > 0.01 || Math.abs(t.skew) > 0.01) throw new Error(`brand: element ${opts.name ? `'${opts.name}' ` : ""}drawn with a non-uniform scale or skew (x ${t.sx.toFixed(3)}, y ${t.sy.toFixed(3)}, skew ${t.skew.toFixed(3)}). A brand mark is only moved, rotated, scaled evenly, clipped or layered; an ellipse of a brand circle is a redraw. If the squash IS the joke, pass { allowSquash: "<the gag it serves>" }.`);+ }+ for (const p of el.parts) drawPart(ctx, p, opts.alpha ?? 1);+ reportBox(ctx, el, opts);+}+/** Place an element by its box: centre at (x, y), height h (or width w), rotated by `rot` radians. Uniform by construction. */+export function placeEl(ctx: Ctx, el: BrandElement, at: { x: number; y: number; h?: number; w?: number; rot?: number; alpha?: number; name?: string; env?: Env }) {+ const s = at.h != null ? at.h / el.h : at.w != null ? at.w / el.w : 1;+ ctx.save(); ctx.translate(at.x, at.y); if (at.rot) ctx.rotate(at.rot); ctx.scale(s, s); ctx.translate(-el.w / 2, -el.h / 2);+ try { drawEl(ctx, el, { alpha: at.alpha, name: at.name, env: at.env }); } finally { ctx.restore(); }+}+/** A part rises into place from behind its own baseline (the clip is the line it sits on); k 0..1. */+export function riseIn(ctx: Ctx, p: BrandPart, k: number) {+ if (k <= 0) return; if (k >= 1) { drawPart(ctx, p); return; }+ const [x, y, w, h] = p.bb;+ ctx.save(); ctx.beginPath(); ctx.rect(x - w, y - h * 4, w * 3, h * 4 + h + 1.5); ctx.clip();+ ctx.translate(0, (1 - k) * h * 1.08); drawPart(ctx, p); ctx.restore();+}+/** Centre of a part's box, in element space. */+export const centreOf = (p: BrandPart): [number, number] => [p.bb[0] + p.bb[2] / 2, p.bb[1] + p.bb[3] / 2];+/** Tile an element along x every `period` units (a frieze whose repeat brand.mjs measured), across [0, span]. */+export function tileX(ctx: Ctx, el: BrandElement, period: number, offset: number, span: number) {+ if (period <= 0) throw new Error("brand: tileX needs the element's measured period (brand.mjs import prints it)");+ const start = Math.floor(-offset / period) - 1;+ for (let i = start; i * period + offset < span + period; i++) { ctx.save(); ctx.translate(i * period + offset, 0); drawEl(ctx, el, { name: "tile" }); ctx.restore(); }+}diff --git a/skills/anidoodle/engine/src/canvas-core/cues.ts b/skills/anidoodle/engine/src/canvas-core/cues.tsnew file mode 100644index 0000000..cc8e5b7--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/cues.ts@@ -0,0 +1,108 @@+// CUE SHEET. The film says when its events happen, once, in its own source, and every tool reads+// that: the sound mix, the sync check, the duration budget. A brand launch film kept a second copy of+// its timing in a Python file (a hand-kept timing script) that re-implemented the film's time maps by hand; it drifted+// twice (one section left at real time after a 25 % slowdown, logo keys set in the wrong units), and+// its effects landed at chance level (49 % of 97 visual events had a sound, 71 % by chance alone).+//+// export const myFilm = withCues(film, [+// { name: "x-lock", at: { scene: 22.0, through: [master] } }, // a scene time, through the film's time maps+// { name: "fall", at: { scene: 11.94, through: [slowMo, master] } }, // innermost map first, as they are applied+// { name: "card", at: { film: 84.2 }, sync: true }, // a film time, also a verify-export sync marker+// { name: "tap", at: { frame: 512 }, sound: "tap:tock -4" }, // a whole frame, with its sound+// ]);+// node tools/cues.mjs myFilm -> out/myFilm.cues.json, which tools/track.mjs mix reads+//+// Times say their units: a bare number throws, because "4.4" in scene seconds and "4.4" in film seconds+// are different frames once a time map runs (the logo-keys bug). Pure: arithmetic over the maps.+import type { Film } from "./film";+import type { TimeRemap } from "./timeRemap";++export type CueAt = { frame: number } | { film: number } | { scene: number; through?: TimeRemap[] };+export type CueDef = { name: string; at: CueAt; sound?: string; sync?: boolean; note?: string };+export type FilmCue = { name: string; frame: number; t: number; sound?: string; sync?: boolean; note?: string };+export type CuedFilm = Film & { cues: FilmCue[] };++/** The film frame (fractional) that shows scene frame `t` under one map: the inverse of map.at, by bisection. */+export const invertRemap = (map: TimeRemap, t: number) => {+ const whole = map.filmFrameOf(t); // the first whole frame at or past t+ let lo = whole - 1, hi = whole;+ if (map.at(lo) >= t) return lo;+ for (let k = 0; k < 40; k++) { const mid = (lo + hi) / 2; if (map.at(mid) >= t) hi = mid; else lo = mid; }+ return hi;+};++/** One cue's film frame, fractional: a scene time is carried out through each map in turn. */+export const cueFrame = (at: CueAt, fps: number): number => {+ if (typeof at !== "object" || at === null) throw new Error(`cue time ${String(at)} has no units: write { scene: s }, { film: s } or { frame: n }`);+ if ("frame" in at) { if (!Number.isFinite(at.frame)) throw new Error(`cue frame must be a number, got ${String(at.frame)}`); return at.frame; }+ if ("film" in at) { if (!Number.isFinite(at.film)) throw new Error(`cue film time must be a number of seconds, got ${String(at.film)}`); return at.film * fps; }+ if ("scene" in at) {+ if (!Number.isFinite(at.scene)) throw new Error(`cue scene time must be a number of seconds, got ${String(at.scene)}`);+ let f = at.scene * fps; for (const m of at.through ?? []) f = invertRemap(m, f); return f;+ }+ throw new Error(`cue time ${JSON.stringify(at)} has no units: write { scene: s }, { film: s } or { frame: n }`);+};++/**+ * The film's cue sheet: each cue on the first whole frame that shows it (a sound cued a frame early+ * reads as a lead, a frame late as a lag), with its exact time in seconds. Names are unique, cues sit+ * inside the film, and the list is sorted by frame.+ */+export const cueSheet = (meta: Pick<Film["meta"], "fps" | "durationFrames">, defs: CueDef[]): FilmCue[] => {+ const seen = new Set<string>();+ const out = defs.map((d, i) => {+ if (!d || typeof d.name !== "string" || !d.name.trim()) throw new Error(`cue #${i} needs a name (what happens: "x-lock", "card-lands")`);+ if (seen.has(d.name)) throw new Error(`cue "${d.name}" is declared twice; give each event its own name ("land-1", "land-2")`);+ seen.add(d.name);+ const f = cueFrame(d.at, meta.fps), frame = Math.ceil(f - 1e-6);+ if (frame < 0 || frame >= meta.durationFrames) throw new Error(`cue "${d.name}" lands on frame ${frame}, outside the film (0..${meta.durationFrames - 1})`);+ return { name: d.name, frame, t: +(f / meta.fps).toFixed(4), ...(d.sound ? { sound: d.sound } : {}), ...(d.sync ? { sync: true } : {}), ...(d.note ? { note: d.note } : {}) };+ });+ return out.sort((a, b) => a.frame - b.frame || a.name.localeCompare(b.name));+};++/** The film with its cue sheet attached, and the cues marked sync added to meta.sync (verify-export's markers). */+export const withCues = (film: Film, defs: CueDef[]): CuedFilm => {+ const cues = cueSheet(film.meta, defs), sync = cues.filter((c) => c.sync).map((c) => ({ frame: c.frame, label: c.name }));+ const meta = sync.length ? { ...film.meta, sync: [...(film.meta.sync ?? []), ...sync] } : film.meta;+ return { ...film, meta, cues };+};++/** What changed between two cue sheets (a mix built from an old sheet is out of date): moved, added, removed. */+export const diffCues = (was: FilmCue[], now: FilmCue[], tolFrames = 0) => {+ const a = new Map(was.map((c) => [c.name, c])), b = new Map(now.map((c) => [c.name, c])), out: string[] = [];+ for (const [n, c] of b) {+ const o = a.get(n); if (!o) { out.push(`added "${n}" at frame ${c.frame}`); continue; }+ if (Math.abs(o.frame - c.frame) > tolFrames) out.push(`moved "${n}" from frame ${o.frame} to ${c.frame} (${((c.frame - o.frame) / 1).toFixed(0)} frames)`);+ // the mix plays the cue's sound, and verify-export reads its sync mark: a change to either is a stale mix too+ if ((o.sound ?? "") !== (c.sound ?? "")) out.push(`"${n}" changed its sound from ${o.sound ?? "none"} to ${c.sound ?? "none"}`);+ if (!!o.sync !== !!c.sync) out.push(`"${n}" ${c.sync ? "gained" : "lost"} its sync mark`);+ }+ for (const n of a.keys()) if (!b.has(n)) out.push(`removed "${n}"`);+ return out;+};++/**+ * Any film's cues as sheet cues: { name, frame, t } each. A withCues sheet passes through unchanged. A+ * launch template film carries its sound cues as film.cues ({ frame, kind, variant, label }, no name and+ * no time): each gets t = frame / fps, its label (or its kind) as the name, numbered in frame order when+ * the label repeats (every key of a typed prompt), and kind:variant as its sound, so --check can tell+ * one moved cue from another.+ */+export const sheetCues = (cues: readonly ({ frame: number; name?: string; t?: number; label?: string; kind?: string; variant?: string; sound?: string; sync?: boolean; note?: string })[], fps: number): FilmCue[] => {+ const seen = new Map<string, number>();+ return [...cues].sort((a, b) => a.frame - b.frame).map((c) => {+ if (typeof c.name === "string" && c.name && typeof c.t === "number") return c as FilmCue;+ const base = c.name || c.label || c.kind || "cue", k = (seen.get(base) ?? 0) + 1; seen.set(base, k);+ const sound = c.sound ?? (c.kind ? (c.variant ? `${c.kind}:${c.variant}` : c.kind) : undefined);+ return { name: k === 1 ? base : `${base} #${k}`, frame: c.frame, t: c.frame / fps, ...(sound ? { sound } : {}), ...(c.sync ? { sync: true } : {}), ...(c.note ? { note: c.note } : {}) };+ });+};++/** What changed between a written cue sheet and the film's sheet now: frame rate, length, then every cue. */+export const diffSheets = (was: { fps?: number; durationFrames?: number; cues?: FilmCue[] }, now: { fps: number; durationFrames: number; cues: FilmCue[] }) => {+ const out: string[] = [];+ if (was.fps !== now.fps) out.push(`the film runs at ${now.fps} fps now, ${was.fps ?? "no"} fps when the sheet was written`);+ if (was.durationFrames !== now.durationFrames) out.push(`the film is ${now.durationFrames} frames now, ${was.durationFrames ?? "no"} when the sheet was written`);+ return [...out, ...diffCues(was.cues ?? [], now.cues)];+};diff --git a/skills/anidoodle/engine/src/canvas-core/endCard.ts b/skills/anidoodle/engine/src/canvas-core/endCard.tsnew file mode 100644index 0000000..6c64474--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/endCard.ts@@ -0,0 +1,90 @@+// END CARD. One card, one frame, an asymmetric grid: the layout the director approved on a brand launch film+// after rejecting a centred stack ("who is gonna read this overload of info?"), a shrunken card under a+// stinger and a split into extra frames ("too many slides now"). Built from the approved v12 card:+// lockup top-left at the margin; the event lines (date, venue) under it; the call to action as a+// stamp on the right, sitting on the venue's baseline; a hairline; a sponsor band along the foot,+// its label large enough not to be swallowed (38 px, weight 800 at 1080) and each sponsor switchable.+// Variants for 16x9, 1x1, 4x5 and 9x16 come from the frame's own shape (on 9:16 everything stays out of+// the platforms' bands and the right button column). The card reports itself to the frame probe as+// "end card", so framecheck fails a film whose card lands twice (card, stinger, card).+// endCardLayout(W, H, spec, measure) pure: every rectangle and size, for tests and for the draw+// drawEndCard(ctx, env, spec, p) draws it; p 0..1 is the arrival (staggered rise, no fade)+import { probeRect, type Ctx, type Env } from "./core";++export type Rect = { x: number; y: number; w: number; h: number };+export type Sponsor = { name: string; aspect: number; on?: boolean; draw: (ctx: Ctx, box: Rect) => void };+export type EndCardSpec = {+ // the exact brand lockup (brand import), drawn into its box; descent: how far its drawing hangs below+ // the box, as a share of the box's height (a name set on the box's foot as its baseline: its descenders)+ lockup: { aspect: number; draw: (ctx: Ctx, box: Rect) => void; descent?: number };+ date: string; venue: string;+ cta: string;+ sponsors?: { label?: string; list: Sponsor[] };+ colors: { ink: string; accent: string; ctaInk: string; hair?: string };+ font?: (weight: number, px: number) => string;+ // where a wide card's stamp sits on the venue's baseline: "edge", at the right margin (the approved card,+ // over its sponsor band), or "inline", one gap after the text block (a card with no band, where a stamp+ // at the edge floats far from everything it belongs to)+ stamp?: "edge" | "inline";+};+const FONT = (w: number, px: number) => `${w} ${px}px "Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;+export type Measure = (text: string, font: string) => number;+export type EndCardLayout = { margin: number; lockup: Rect; date: Rect & { px: number }; venue: Rect & { px: number }; cta: Rect & { px: number }; hairY: number; label: Rect & { px: number } | null; logos: (Rect & { name: string })[]; shape: "wide" | "square" | "tall" };++/** Every rectangle of the card for a W x H frame. `measure` gives a text's width in a font (ctx.measureText in the draw). */+export const endCardLayout = (W: number, H: number, spec: EndCardSpec, measure: Measure): EndCardLayout => {+ const font = spec.font ?? FONT, u = Math.min(W, H) / 1080, shape = W / H > 1.2 ? "wide" : W / H < 0.7 ? "tall" : "square";+ const air = Math.ceil(0.035 * H); // the smallest gap between two parts: over framecheck's 3 % of the height+ const margin = shape === "wide" ? Math.round(W * 0.078) : Math.round(W * 0.09);+ const fit = (text: string, w: number, maxPx: number, minPx: number, weight: number) => { let px = maxPx; while (px > minPx && measure(text, font(weight, px)) > w) px -= 1; return px; };+ const top = shape === "tall" ? Math.round(H * 0.17) : margin; // 9:16: under the platforms' top band+ const textW = shape === "tall" ? Math.floor(W * 0.86) - margin - 8 : W - 2 * margin; // 9:16: lines end left of the platforms' right button column (14 %)+ const lockW = shape === "wide" ? W * 0.36 : W * (shape === "tall" ? 0.7 : 0.55), lockup = { x: margin, y: top, w: lockW, h: lockW / spec.lockup.aspect };+ const datePx = fit(spec.date, textW, Math.round(64 * u), Math.round(40 * u), 800), venuePx = fit(spec.venue, shape === "wide" ? W * 0.5 : textW, Math.round(44 * u), Math.round(32 * u), 600);+ const date = { x: margin, y: lockup.y + lockup.h * (1 + (spec.lockup.descent ?? 0)) + Math.max(Math.round(56 * u), air), w: measure(spec.date, font(800, datePx)), h: datePx, px: datePx };+ const venue = { x: margin, y: date.y + date.h + Math.round(18 * u), w: measure(spec.venue, font(600, venuePx)), h: venuePx, px: venuePx };+ const ctaPx = fit(spec.cta, shape === "wide" ? W * 0.3 : textW - 80 * u, Math.round(44 * u), Math.round(32 * u), 800), padX = Math.round(36 * u), padY = Math.round(22 * u);+ const ctaW = measure(spec.cta, font(800, ctaPx)) + 2 * padX, ctaH = ctaPx + 2 * padY;+ // the stamp sits on the venue's baseline, on the right (wide); under the event lines, still left-aligned, elsewhere: never centred+ const inlineX = margin + Math.max(date.w, venue.w) + Math.round(72 * u);+ const cta = shape === "wide" ? { x: spec.stamp === "inline" ? Math.min(inlineX, W - margin - ctaW) : W - margin - ctaW, y: venue.y + venue.h - ctaH + padY, w: ctaW, h: ctaH, px: ctaPx } : { x: margin, y: venue.y + venue.h + Math.round(48 * u), w: ctaW, h: ctaH, px: ctaPx };+ const on = (spec.sponsors?.list ?? []).filter((s) => s.on !== false);+ const bottom = shape === "tall" ? Math.round(H * 0.74) : H - margin; // 9:16: above the platforms' bottom band+ let label: EndCardLayout["label"] = null, logos: EndCardLayout["logos"] = [], hairY = bottom;+ if (on.length) {+ const labelPx = Math.round(38 * u), logoH = Math.round((shape === "wide" ? 0.062 : 0.05) * H * 1.3) /* v12: logos 1.3x after the designer's pass */, gap = Math.max(Math.round(56 * u), air), text = spec.sponsors?.label ?? "Sponsors";+ const perRow = shape === "wide" ? on.length : Math.min(on.length, 3), rows = Math.ceil(on.length / perRow), bandH = labelPx + air + rows * logoH + (rows - 1) * air;+ hairY = bottom - bandH - Math.round(36 * u);+ label = { x: margin, y: hairY + Math.round(36 * u), w: measure(text, font(800, labelPx)), h: labelPx, px: labelPx };+ const avail = W - 2 * margin, y0 = label.y + labelPx + air;+ for (let r = 0; r < rows; r++) {+ const row = on.slice(r * perRow, (r + 1) * perRow); let h = logoH, ws = row.map((s) => s.aspect * h), tot = ws.reduce((a, b) => a + b, 0) + gap * (row.length - 1);+ if (tot > avail) { const k = (avail - gap * (row.length - 1)) / (tot - gap * (row.length - 1)); h *= k; ws = ws.map((w) => w * k); }+ let x = margin; row.forEach((s, i) => { logos.push({ name: s.name, x, y: y0 + r * (logoH + air) + (logoH - h) / 2, w: ws[i], h }); x += ws[i] + gap; });+ }+ }+ return { margin, lockup, date, venue, cta, hairY, label, logos, shape };+};++/** Draw the end card; p 0..1 is its arrival (each part rises into place in turn, no fade). */+export const drawEndCard = (ctx: Ctx, env: Env, spec: EndCardSpec, p = 1) => {+ const font = spec.font ?? FONT, L = endCardLayout(env.W, env.H, spec, (t, f) => { ctx.font = f; return ctx.measureText(t).width; });+ const parts = 4 + (L.label ? 1 : 0), part = (i: number) => { const q = Math.max(0, Math.min(1, p * (1 + 0.25 * (parts - 1)) - 0.25 * i)); return 1 - Math.pow(1 - q, 3); };+ const rise = (i: number, r: Rect, draw: () => void) => { const e = part(i); if (e <= 0) return; ctx.save(); ctx.beginPath(); ctx.rect(r.x - 4, r.y - r.h * 0.3, r.w + 8, r.h * 1.6); ctx.clip(); ctx.translate(0, (1 - e) * r.h * 1.2); draw(); ctx.restore(); };+ if (p >= 1) probeRect(ctx, env, L.margin * 0.5, L.margin * 0.5, env.W - L.margin, env.H - L.margin, "end card");+ rise(0, L.lockup, () => spec.lockup.draw(ctx, L.lockup));+ ctx.textBaseline = "top"; ctx.textAlign = "left";+ rise(1, L.date, () => { ctx.fillStyle = spec.colors.ink; ctx.font = font(800, L.date.px); ctx.fillText(spec.date, L.date.x, L.date.y); });+ rise(2, L.venue, () => { ctx.fillStyle = spec.colors.ink; ctx.font = font(600, L.venue.px); ctx.fillText(spec.venue, L.venue.x, L.venue.y); });+ rise(3, L.cta, () => {+ const r = L.cta, rad = r.h * 0.22; ctx.fillStyle = spec.colors.accent; ctx.beginPath(); ctx.roundRect(r.x, r.y, r.w, r.h, rad); ctx.fill();+ ctx.fillStyle = spec.colors.ctaInk; ctx.font = font(800, r.px); ctx.textBaseline = "middle"; ctx.fillText(spec.cta, r.x + (r.w - ctx.measureText(spec.cta).width) / 2, r.y + r.h / 2); ctx.textBaseline = "top";+ });+ if (L.label) {+ const e = part(4); if (e > 0) { ctx.save(); ctx.strokeStyle = spec.colors.hair ?? spec.colors.ink; ctx.globalAlpha *= 0.35; ctx.lineWidth = Math.max(1, env.H / 1080); ctx.beginPath(); ctx.moveTo(L.margin, L.hairY); ctx.lineTo(L.margin + (env.W - 2 * L.margin) * e, L.hairY); ctx.stroke(); ctx.restore(); }+ rise(4, L.label, () => { ctx.fillStyle = spec.colors.ink; ctx.font = font(800, L.label!.px); ctx.fillText(spec.sponsors?.label ?? "Sponsors", L.label!.x, L.label!.y); });+ const on = (spec.sponsors?.list ?? []).filter((s) => s.on !== false);+ L.logos.forEach((b, i) => rise(4, b, () => { on[i].draw(ctx, b); probeRect(ctx, env, b.x, b.y, b.w, b.h, `sponsor:${b.name}`); }));+ }+ return L;+};diff --git a/skills/anidoodle/engine/src/canvas-core/film.ts b/skills/anidoodle/engine/src/canvas-core/film.tsindex 0e3f804..8c21478 100644--- a/skills/anidoodle/engine/src/canvas-core/film.ts+++ b/skills/anidoodle/engine/src/canvas-core/film.ts@@ -34,6 +34,10 @@ export type Film = { meta: {captions?: { from: number; to: number; text: string }[];// a legible frame for the poster image and the thumbnail (render --poster-frame, launch.mjs ship)poster?: number;+ // what the film tells the ship checks about itself (shipMeta.ts: layout exemptions, length budget, brand fonts)+ checks?: import("./shipMeta").ShipMeta;+ // what the film tells the motion scans (motionMeta.ts: brand colours, temperament, approved shots, exceptions)+ motion?: import("./motionMeta").MotionMeta;}; assets: Assets; shots: Shot[]; audio?: FilmAudio;// the same film composed for another frame shape (launch template films); hosts/page.ts calls it for <film>-<shape>reshape?: (shape: string) => Film };diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureDeck.ts b/skills/anidoodle/engine/src/canvas-core/fixtureDeck.tsnew file mode 100644index 0000000..507ab01--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureDeck.ts@@ -0,0 +1,2 @@+// TEST FIXTURE: the module the page build resolves by film name. The film lives in fixtureMotion.ts beside its twin.+export { fixtureDeck } from "./fixtureMotion";diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureMotion.ts b/skills/anidoodle/engine/src/canvas-core/fixtureMotion.tsnew file mode 100644index 0000000..8f9287b--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureMotion.ts@@ -0,0 +1,67 @@+// TEST FIXTURES for tools/motionscan.mjs, tools/layerscan.mjs and the render blur mask: a brand launch+// faults in six seconds, and the same material built the way the kit now builds it.+// fixtureDeck RED: slides cut one after another in one layout (a carousel), a cross-dissolve, the+// old ease-out text exit, type whipped off at speed, brand yellow faded in, a frieze+// sliding across a speaker's face.+// fixtureWorld GREEN: one world, one camera travelling between regions, setType entries and exits,+// alternate() sides, opaque brand colour, the frieze behind the speaker.+import { probeRect, type Ctx, type Env } from "./core";+import type { Film } from "./film";+import { setType } from "./kinetic";+import { alternate } from "./motionKit";+import { world } from "./world";++const W = 640, H = 360, FPS = 30, BG = "#111111", YEL = "#ffde59";+const meta = (title: string, durationFrames: number) => ({ title, W, H, fps: FPS, bpm: 120, durationFrames });+const clamp = (v: number) => Math.max(0, Math.min(1, v));+const screen = (ctx: Ctx, env: Env) => ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+const TITLES = ["You talk to AI all day.", "Nobody has a prompt for that.", "Half a day with marketers.", "Real systems, real results.", "Meet the speakers.", "See you there."];++// the hand-rolled exit a brand launch film used first: words sink on an EASE-OUT over 1.0x the size+const oldRise = (ctx: Ctx, s: string, x: number, y: number, px: number, p: number) => {+ if (p === 0) return; const sink = p < 0, q0 = Math.abs(p);+ ctx.font = `800 ${px}px Helvetica, Arial, sans-serif`; ctx.textBaseline = "alphabetic"; ctx.fillStyle = "#ffffff";+ const words = s.split(" "), sp = ctx.measureText(" ").width, wd = words.map((v) => ctx.measureText(v).width), total = wd.reduce((a, b) => a + b, 0) + sp * (words.length - 1);+ let cx = x; ctx.save(); ctx.beginPath(); ctx.rect(cx - px, y - px * 1.05, total + 2 * px, px * 1.35); ctx.clip();+ words.forEach((v, i) => { const q = clamp(q0 * (1 + 0.3 * (words.length - 1)) - 0.3 * i), e = 1 - Math.pow(1 - q, 3); if (sink ? q < 1 : q > 0) ctx.fillText(v, cx, y + (sink ? e : 1 - e) * px * 1.0); cx += wd[i] + sp; });+ ctx.restore();+};++// ---------------------------------------------------------------- RED: 4 slides of 60 frames (rise, hold, sink); slide 2 whips, slide 3 dissolves in, slide 4 has the speaker+const slide = (ctx: Ctx, env: Env, i: number, local: number) => {+ screen(ctx, env); ctx.fillStyle = BG; ctx.fillRect(0, 0, W, H);+ ctx.globalAlpha = clamp(local / 10); ctx.fillStyle = YEL; ctx.fillRect(40, 60, 260, 240); ctx.globalAlpha = 1; // brand yellow faded in: olive mud+ const whip = i === 1 && local >= 54, x = 330 + (whip ? (local - 53) * 70 : 0); // slide 2 whips its title off at 70 px a frame+ oldRise(ctx, TITLES[i], x, 190, 28, whip ? 1 : local < 8 ? local / 8 : local >= 30 ? -clamp((local - 30) / 28) : 1);+ if (i === 3) { const img = env.image?.("person"); if (img) { ctx.drawImage(img, 120, 80, 120, 160); } ctx.fillStyle = "#e0457b"; const fx = -60 + local * 9; probeRect(ctx, env, fx, 90, 140, 40, "brand:frieze"); ctx.fillRect(fx, 90, 140, 40); } // a frieze slides across the face+};+export const fixtureDeck: Film = {+ meta: { ...meta("fixture: deck", 240), motion: { brandColors: [YEL] } },+ assets: { images: { person: "test/fixtures/motion-person.png" } },+ shots: [0, 1, 2, 3].map((i) => ({ id: `slide${i + 1}`, start: i * 60, end: i * 60 + 60, draw: (ctx: Ctx, local: number, env: Env) => {+ slide(ctx, env, i, local);+ if (i === 2 && local < 12) { // a cross-dissolve from the slide before+ const u = local / 12; ctx.save(); ctx.globalAlpha = 1 - u; ctx.fillStyle = BG; ctx.fillRect(0, 0, W, H); ctx.fillStyle = YEL; ctx.fillRect(40, 60, 260, 240); ctx.restore();+ }+ } })),+};++// ---------------------------------------------------------------- GREEN+const W3 = world({ W, H, regions: [0, 1, 2, 3].map((i) => ({ id: `r${i}`, rect: [i * 680, 0, 640, 360] as [number, number, number, number] })),+ stops: [{ f: 0, at: "r0", hold: 10 }, { f: 80, at: "r1", hold: 10 }, { f: 160, at: "r2", hold: 10 }, { f: 239, at: "r3" }], alive: { amp: 1.5, seed: 4 } });+export const fixtureWorld: Film = {+ meta: { ...meta("fixture: one world", 240), motion: { brandColors: [YEL], temperament: "lively" } },+ assets: { images: { person: "test/fixtures/motion-person.png" } },+ shots: [{ id: "world", start: 0, end: 240, draw: (ctx: Ctx, f: number, env: Env) => {+ screen(ctx, env); ctx.fillStyle = BG; ctx.fillRect(0, 0, W, H);+ W3.begin(ctx, env, f);+ [0, 1, 2, 3].forEach((i) => W3.region(ctx, `r${i}`, (r) => {+ const [x, y] = r.rect, side = alternate(i, ["left", "right"]), cardX = side === "left" ? x + 40 : x + 340;+ ctx.fillStyle = YEL; ctx.fillRect(cardX, y + 60, 260, 240); // opaque, always+ if (i === 2) { ctx.fillStyle = "#e0457b"; ctx.fillRect(cardX + 20 + Math.sin(f / 9) * 30, y + 90, 140, 40); const img = env.image?.("person"); if (img) ctx.drawImage(img, cardX + 70, y + 80, 120, 160); } // the frieze moves BEHIND the speaker+ const enter = clamp((f - (i * 80 - 20)) / 14), leave = clamp((f - (i * 80 + 40)) / 28); // the same 28-frame exit the deck uses, done with setType out+ setType(ctx, env, TITLES[i], side === "left" ? x + 330 : x + 40, y + 190, 26, enter, { color: "#ffffff", weight: 800, space: "world", out: i === 3 ? 0 : leave });+ }));+ W3.end(ctx);+ } }],+};diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureShip.ts b/skills/anidoodle/engine/src/canvas-core/fixtureShip.tsnew file mode 100644index 0000000..a5f7695--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureShip.ts@@ -0,0 +1,86 @@+// TEST FIXTURES for tools/framecheck.mjs and tools/ship.mjs, not films. Two cuts of one 10 s launch beat+// (a typed AI reply, then the end card), rebuilt from a brand launch film's real faults and their fixes.+// fixtureShipRed the reply held 0.9 s after its last character (the film's number; it needs 3.3 s),+// "blah" texture drawn as readable text, the v3 end card (eight items packed into a+// corner), the card landing twice around a stinger, a 14 px CTA in the last second.+// framecheck must FAIL it on every one of those.+// fixtureShipGreen the same beat built with the kit: chatHoldFrames for the reply, texture() for the+// blah, drawEndCard for one asymmetric card that lands once. framecheck must PASS it.+// A small mark drifts the whole time, so the gate's dead-air rule has motion to see on both.+import { probeRect, type Ctx, type Env } from "./core";+import type { Film } from "./film";+import { chatHoldFrames, texture } from "./readable";+import { drawEndCard, type EndCardSpec } from "./endCard";++const W = 1920, H = 1080, FPS = 30, N = 300;+const REPLY = "I can handle the non-human part. Ingrid has the human one.";+const BG = "#111214", INK = "#f4f1ea", ACC = "#FFDE59";+const SANS = (w: number, px: number) => `${w} ${px}px "Helvetica Neue", Helvetica, Arial, sans-serif`;++const ground = (ctx: Ctx, env: Env, f: number) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = BG; ctx.fillRect(0, 0, W, H);+ const a = (f / FPS) * 0.9; ctx.fillStyle = ACC; ctx.beginPath(); ctx.arc(W - 120 + Math.cos(a) * 40, 120 + Math.sin(a) * 40, 14, 0, Math.PI * 2); ctx.fill(); // the drifting mark+};+/** The reply typed from frame t0 at 52 chars/s; returns nothing, draws the typed part. */+const typed = (ctx: Ctx, env: Env, f: number, t0: number, card: boolean) => {+ const n = Math.max(0, Math.min(REPLY.length, Math.floor(((f - t0) / FPS) * 52)));+ if (card) { ctx.fillStyle = "#24262b"; ctx.beginPath(); ctx.roundRect(160, 380, 1600, 220, 28); ctx.fill(); probeRect(ctx, env, 160, 380, 1600, 220, "reply card"); }+ if (n) { ctx.fillStyle = INK; ctx.font = SANS(600, 44); ctx.textBaseline = "alphabetic"; ctx.fillText(REPLY.slice(0, n), 220, 506); }+};+const blah = (ctx: Ctx, as: "read" | "texture") => {+ const draw = () => { ctx.fillStyle = "#8a8d93"; ctx.font = SANS(500, 34); for (let i = 0; i < 3; i++) ctx.fillText("blah blah blah blah blah blah", 360, 160 + i * 52); };+ if (as === "texture") texture(ctx, draw); else draw();+};++// ---- RED: the faults, as the film shipped them+const redDraw = (ctx: Ctx, f: number, env: Env) => {+ ground(ctx, env, f);+ if (f < 10) blah(ctx, "read"); // a cold open of greeked text drawn as real words, up a third of a second+ const typedEnd = 18 + Math.ceil((REPLY.length / 52) * FPS), hold = Math.round(0.9 * FPS);+ if (f >= 18 && f < typedEnd + hold) typed(ctx, env, f, 18, true);+ const card = (f >= typedEnd + hold && f < 200) || f >= 240;+ if (card) {+ probeRect(ctx, env, 40, 40, W - 80, H - 80, "end card");+ ctx.fillStyle = INK; ctx.textBaseline = "top";+ ["Kestrel Live", "May 03, 2027", "Santiago", "The Old Mill", "Reserve a Spot!", "www.example.com", "Sponsors", "Nordic Wren"].forEach((s, i) => { ctx.font = SANS(i === 0 ? 800 : 600, i === 0 ? 40 : 26); ctx.fillText(s, 80 + (i % 2) * 300, 80 + Math.floor(i / 2) * 64); });+ }+ if (f >= 200 && f < 240) { ctx.fillStyle = INK; ctx.font = SANS(700, 64); ctx.textBaseline = "alphabetic"; ctx.fillText("You're absolutely right.", 520, 560); } // the stinger, between two landings+ if (f >= 270) { ctx.fillStyle = ACC; ctx.font = SANS(800, 14); ctx.textBaseline = "top"; ctx.fillText("Reserve a Spot!", 1500, 980); } // shrunk under the stinger+};++// ---- GREEN: the same beat on the kit+const hold = chatHoldFrames(REPLY, FPS, { cps: 52, think: 0.6 }), T0 = hold.think, CARD = T0 + hold.typing + hold.read;+const SPEC: EndCardSpec = {+ lockup: { aspect: 3, draw: (ctx, b) => { ctx.fillStyle = ACC; ctx.beginPath(); ctx.ellipse(b.x + b.h / 2, b.y + b.h / 2, b.h / 2, b.h / 2, 0, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = INK; ctx.fillRect(b.x + b.h * 1.2, b.y + b.h * 0.3, b.w - b.h * 1.2, b.h * 0.4); } },+ date: "May 03, 2027", venue: "Santiago The Old Mill", cta: "Reserve a Spot!",+ colors: { ink: INK, accent: ACC, ctaInk: BG },+ sponsors: { list: ["northwind", "kestrel", "brightstar", "headland"].map((name, i) => ({ name, aspect: 2.4 + (i % 2) * 0.6, draw: (ctx: Ctx, b: { x: number; y: number; w: number; h: number }) => { ctx.fillStyle = "#5c5f66"; ctx.beginPath(); ctx.roundRect(b.x, b.y, b.w, b.h, b.h * 0.2); ctx.fill(); } })) },+};+const greenDraw = (ctx: Ctx, f: number, env: Env) => {+ ground(ctx, env, f);+ if (f < 10) blah(ctx, "texture"); // the same greek, marked as texture: not meant to be read+ if (f >= T0 && f < CARD) typed(ctx, env, f, T0, true);+ if (f >= CARD) { ctx.textBaseline = "top"; drawEndCard(ctx, env, SPEC, Math.min(1, (f - CARD) / 24)); }+};++const film = (title: string, draw: (ctx: Ctx, f: number, env: Env) => void, extra: Partial<Film["meta"]> = {}): Film => ({+ meta: { title, W, H, fps: FPS, bpm: 60, durationFrames: N, kind: "launch", ...extra },+ assets: { images: {} },+ shots: [{ id: "beat", start: 0, end: N, draw: (ctx, local, env) => draw(ctx, local, env) }],+});+export const fixtureShipRed: Film = film("fixtureShipRed", redDraw);+// the reads are declared holds (the gate's dead-air rule then knows the stillness is meant)+// Every check ship runs must be able to look at it: a calm temperament and the brand's colours for the motion+// scans; the review ledger and the claims, which a test fixture has none of, are declared with a reason.+export const GREEN_NONE = { review: "a test fixture: no critic and no person is ever shown it", facts: "a test fixture: its lines are a made-up chat, not claims about a product" };+export const fixtureShipGreen: Film = film("fixtureShipGreen", greenDraw, { checks: { length: { target: 10, max: 12 }, none: GREEN_NONE }, motion: { temperament: "calm", brandColors: [ACC] }, holds: [[T0, CARD, "the reply types (a few letters a frame) and is read"], [CARD + 16, N, "the end card settles and is read"]] });+// fixtureShipTrack the green beat whose music is an external track (meta.checks.music.track): ship must run+// track.mjs check, soundcheck --sfx and cues --check on it, and verify-export must tie the+// delivered mix to the pinned take. tools/ship-e2e.mjs writes the take and its manifest.+export const SHIP_E2E_TRACK = ".tmp/ship-e2e/take.wav.track.json";+export const fixtureShipTrack: Film = { ...fixtureShipGreen, meta: { ...fixtureShipGreen.meta, title: "fixtureShipTrack", checks: { ...fixtureShipGreen.meta.checks, music: { track: SHIP_E2E_TRACK } } } };+// fixtureShipLocked the green beat with an approved shot whose sha is wrong: ship's locks row must FAIL.+export const fixtureShipLocked: Film = { ...fixtureShipGreen, meta: { ...fixtureShipGreen.meta, title: "fixtureShipLocked", motion: { approved: [["beat", "0".repeat(32), "fixture: a sha no render produces"]] } } };+// fixtureShipBlind the green beat with nothing for four checks to look at (no temperament, no brand colours, no+// ledger or claims declared, no length budget): ship must FAIL each of those rows, never pass.+export const fixtureShipBlind: Film = { ...fixtureShipGreen, meta: { ...fixtureShipGreen.meta, title: "fixtureShipBlind", checks: {}, motion: undefined } };diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureShipBlind.ts b/skills/anidoodle/engine/src/canvas-core/fixtureShipBlind.tsnew file mode 100644index 0000000..38a5dea--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureShipBlind.ts@@ -0,0 +1,2 @@+// TEST FIXTURE, not a film: built in fixtureShip.ts (tools/ship.mjs must FAIL it: four checks cannot look).+export { fixtureShipBlind } from "./fixtureShip";diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureShipGreen.ts b/skills/anidoodle/engine/src/canvas-core/fixtureShipGreen.tsnew file mode 100644index 0000000..73cb8bf--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureShipGreen.ts@@ -0,0 +1,2 @@+// TEST FIXTURE, not a film: built in fixtureShip.ts (tools/framecheck.mjs and tools/ship.mjs must PASS it).+export { fixtureShipGreen } from "./fixtureShip";diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureShipLocked.ts b/skills/anidoodle/engine/src/canvas-core/fixtureShipLocked.tsnew file mode 100644index 0000000..a155f50--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureShipLocked.ts@@ -0,0 +1,2 @@+// TEST FIXTURE, not a film: built in fixtureShip.ts (tools/ship-e2e.mjs).+export { fixtureShipLocked } from "./fixtureShip";diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureShipRed.ts b/skills/anidoodle/engine/src/canvas-core/fixtureShipRed.tsnew file mode 100644index 0000000..efbe3d5--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureShipRed.ts@@ -0,0 +1,2 @@+// TEST FIXTURE, not a film: built in fixtureShip.ts (tools/framecheck.mjs and tools/ship.mjs must FAIL it).+export { fixtureShipRed } from "./fixtureShip";diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureShipTrack.ts b/skills/anidoodle/engine/src/canvas-core/fixtureShipTrack.tsnew file mode 100644index 0000000..568846a--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureShipTrack.ts@@ -0,0 +1,2 @@+// TEST FIXTURE, not a film: built in fixtureShip.ts (tools/ship-e2e.mjs).+export { fixtureShipTrack } from "./fixtureShip";diff --git a/skills/anidoodle/engine/src/canvas-core/fixtureWorld.ts b/skills/anidoodle/engine/src/canvas-core/fixtureWorld.tsnew file mode 100644index 0000000..c343e85--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/fixtureWorld.ts@@ -0,0 +1,2 @@+// TEST FIXTURE: the module the page build resolves by film name. The film lives in fixtureMotion.ts beside its twin.+export { fixtureWorld } from "./fixtureMotion";diff --git a/skills/anidoodle/engine/src/canvas-core/kinetic.ts b/skills/anidoodle/engine/src/canvas-core/kinetic.tsindex 21dedf0..612c6c1 100644--- a/skills/anidoodle/engine/src/canvas-core/kinetic.ts+++ b/skills/anidoodle/engine/src/canvas-core/kinetic.ts@@ -14,9 +14,12 @@import { fractal, probeRect, rng, sample, type Ctx, type Env, type Layer, type P } from "./core";import { G, type Glyph } from "./drafting";import { DOT, TAIL, WORD, inkStroke, outlineOf, type Nib } from "./lettering";+import { typeExit } from "./motionKit";export type KStyle = "ink" | "crayon" | "thread" | "chalk" | "brick" | "marker";-export type WriteOpts = { color?: string; align?: "left" | "center" | "right"; slant?: number; track?: number; seed?: number; tool?: boolean; weight?: number; pop?: number };+// `out` 0..1 is a written line's exit, as setType's: the line sinks behind its own baseline on the same+// ease-in (motionKit.typeExit, 1.3x its size) and stops reporting itself to the frame probe while it leaves+export type WriteOpts = { color?: string; align?: "left" | "center" | "right"; slant?: number; track?: number; seed?: number; tool?: boolean; weight?: number; pop?: number; out?: number };const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));const lerp = (a: number, b: number, t: number) => a + (b - a) * t;@@ -89,6 +92,17 @@ const layout = (env: Env, text: string, x: number, y: number, size: number, o: Wconst total = strokes.reduce((a, k2) => a + k2.L + GAP, 0);const L: Layout = { strokes, boxes, W, total }; env.cache.set(key, L); return L;};+/** Where a line written in the ink style starts and ends, in px from its left-aligned origin: [left, right]. measure()+ * is the advance width, which starts at the first letter's origin, not its first stroke, so a line centred+ * by measure() sits a side bearing off its axis (the end card's name, a fresh critic's d4-1). */+export const inkSpan = (text: string, size: number, o: WriteOpts = {}): [number, number] => {+ const lay = layout({ cache: new Map() } as unknown as Env, text, 0, size, size, { ...o, align: "left" });+ // (the strokes are the nib's centre line; the ink style's nib is up to 0.115 of the size wide, so its edge+ // reaches half that past them: drawInk's `sh`)+ const pen = size * (o.weight ?? 1) * 0.115 / 2;+ let lo = Infinity, hi = -Infinity; for (const k of lay.strokes) for (const [x] of k.pts) { lo = Math.min(lo, x); hi = Math.max(hi, x); }+ return lo <= hi ? [lo - pen, hi + pen] : [0, lay.W];+};// how much of each stroke is laid at progress p (a constant-speed hand, pen lifts between)const reach = (lay: Layout, p: number) => { let d = clamp(p) * lay.total; return lay.strokes.map((k) => { const u = clamp(d / k.L); d -= k.L + GAP; return u; }); };const cut = (k: KStroke, u: number): P[] => { if (u >= 1) return k.pts; const want = u * k.L, out: P[] = [k.pts[0]]; for (let i = 1; i < k.pts.length; i++) { if (k.len[i] <= want) out.push(k.pts[i]); else { const f = (want - k.len[i - 1]) / (k.len[i] - k.len[i - 1] || 1); out.push([k.pts[i - 1][0] + (k.pts[i][0] - k.pts[i - 1][0]) * f, k.pts[i - 1][1] + (k.pts[i][1] - k.pts[i - 1][1]) * f]); break; } } return out.length > 1 ? out : [k.pts[0], k.pts[0]]; };@@ -291,19 +305,25 @@ const drawBricks = (c: Ctx, env: Env, lay: Layout, p: number, size: number, key:// ---------------------------------------------------------------- writeOnexport const writeOn = (ctx: Ctx, env: Env, text: string, x: number, y: number, size: number, p: number, style: KStyle, o: WriteOpts = {}) => {- if (p <= 0) return;+ const out = Math.max(0, Math.min(1, o.out ?? 0));+ if (p <= 0 || out >= 1) return;screen(ctx, env);if (style === "brick" && o.track === undefined) o = { ...o, track: 2.6, slant: o.slant ?? 0 };- const lay = layout(env, text, x, y, size, o), us = reach(lay, p), color = o.color ?? PALETTE[style], popK = o.pop ?? 1, seed = o.seed ?? 1;- if (env.root && lay.boxes.length) { const bx = lay.boxes; probeRect(ctx, env, Math.min(...bx.map((b) => b.c[0] - b.w / 2)), y - size * 1.05, Math.max(...bx.map((b) => b.c[0] + b.w / 2)) - Math.min(...bx.map((b) => b.c[0] - b.w / 2)), size * 1.3, text, "text"); }+ // a leaving line is laid out lower by its sink and drawn inside its own window (cap height plus the+ // ink's reach under the baseline), so every style, textured ones included, sinks out of it the same way+ const sink = out > 0 ? typeExit(out) * size * 1.4 : 0;+ const lay = layout(env, text, x, y + sink, size, o), us = reach(lay, p), color = o.color ?? PALETTE[style], popK = o.pop ?? 1, seed = o.seed ?? 1;+ if (out > 0) { const xs = lay.boxes.map((b) => b.c[0]), x0 = Math.min(...xs) - size, x1 = Math.max(...xs) + size; ctx.save(); ctx.beginPath(); ctx.rect(x0, y - size * 1.15, x1 - x0, size * 1.4); ctx.clip(); }+ if (out <= 0 && env.root && lay.boxes.length) { const bx = lay.boxes; probeRect(ctx, env, Math.min(...bx.map((b) => b.c[0] - b.w / 2)), y - size * 1.05, Math.max(...bx.map((b) => b.c[0] + b.w / 2)) - Math.min(...bx.map((b) => b.c[0] - b.w / 2)), size * 1.3, text, "text"); }ctx.save();if (style === "ink") drawInk(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);else if (style === "marker") drawMarker(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);else if (style === "crayon") textured(ctx, env, "crayon", waxHoles(env), 1, (c) => drawCrayon(c, lay, us, size * (o.weight ?? 1), color, p, popK, seed));else if (style === "chalk") textured(ctx, env, "chalk", chalkHoles(env), 1, (c) => drawChalk(c, lay, us, size * (o.weight ?? 1), color, p, popK, seed));else if (style === "thread") drawThread(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);- else if (style === "brick") drawBricks(ctx, env, lay, p, size, `${text}|${x}|${y}|${size}|${o.seed}|${o.align}|${o.track}`, o.color);+ else if (style === "brick") drawBricks(ctx, env, lay, p, size, `${text}|${x}|${y + sink}|${size}|${o.seed}|${o.align}|${o.track}`, o.color);ctx.restore();+ if (out > 0) { ctx.restore(); return; } // the line's window; a leaving line has no tool// the tool, while the hand is still writingif (o.tool === false || p >= 1 || style === "brick") return;const tp = tipOf(lay, us); if (!tp) return;@@ -422,13 +442,21 @@ export const caption = (ctx: Ctx, env: Env, text: string, x: number, y: number,// Type as the design: a line SET in a heavy sans, not written. Each word rises into place from// behind its own baseline (a mask the size of the line), one after another, on an out-cubic: a// gentle move with no bounce and no fade-in. `p` 0..1 is the line's progress. Screen space.-export type SetOpts = { color?: string; align?: "left" | "center" | "right"; weight?: number; font?: (w: number, px: number) => string; track?: number };+// `out` 0..1 is its exit: the words sink back behind the baseline, last word first, on an EASE-IN over+// 1.3x the size (motionKit.typeExit), so they accelerate away and clear the clip whole. The ease-out,+// 1.0x exit left letter tops at the clip edge for half a second on a brand launch film.+// `space: "world"` draws in the CURRENT transform (inside a camera, a world region) instead of+// resetting to the screen: x, y and size are then world units.+export type SetOpts = { color?: string; align?: "left" | "center" | "right"; weight?: number; font?: (w: number, px: number) => string; track?: number; out?: number; space?: "screen" | "world" };const SET_FONT = (w: number, px: number) => `${w} ${px}px "Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;export const setWidth = (ctx: Ctx, text: string, size: number, o: SetOpts = {}) => { ctx.font = (o.font ?? SET_FONT)(o.weight ?? 700, size); return ctx.measureText(text).width + Math.max(0, text.length - 1) * (o.track ?? -0.02) * size; };export const setType = (ctx: Ctx, env: Env, text: string, x: number, y: number, size: number, p: number, o: SetOpts = {}) => {- if (p <= 0) return;- screen(ctx, env);- { const w = setWidth(ctx, text, size, o), x0 = o.align === "center" ? x - w / 2 : o.align === "right" ? x - w : x; probeRect(ctx, env, x0, y - size * 0.8, w, size, text, "text"); }+ const out = Math.max(0, Math.min(1, o.out ?? 0));+ if (p <= 0 || out >= 1) return;+ if (o.space !== "world") screen(ctx, env);+ // a standing line reports its box to the frame probe; a line on its way out does not, because its+ // glyphs speak for what is still showing (the whole-line box let a one-frame "read" through on the exit)+ if (out <= 0) { const w = setWidth(ctx, text, size, o), x0 = o.align === "center" ? x - w / 2 : o.align === "right" ? x - w : x; probeRect(ctx, env, x0, y - size * 0.8, w, size, text, "text"); }ctx.save();ctx.font = (o.font ?? SET_FONT)(o.weight ?? 700, size); ctx.textBaseline = "alphabetic"; ctx.fillStyle = o.color ?? "#111214";const tr = (o.track ?? -0.02) * size, words = text.split(" "), space = ctx.measureText(" ").width;@@ -437,7 +465,8 @@ export const setType = (ctx: Ctx, env: Env, text: string, x: number, y: number,ctx.beginPath(); ctx.rect(cx - size, y - size * 1.05, total + 2 * size, size * 1.35); ctx.clip(); // the line's own window: words rise into itwords.forEach((w, i) => {const q = Math.max(0, Math.min(1, p * (1 + 0.35 * (words.length - 1)) - 0.35 * i)), e = 1 - Math.pow(1 - q, 3);- if (q > 0) { const dy = (1 - e) * size * 0.9; let wx = cx; for (const ch of w) { ctx.fillText(ch, wx, y + dy); wx += ctx.measureText(ch).width + tr; } }+ const qo = Math.max(0, Math.min(1, out * (1 + 0.3 * (words.length - 1)) - 0.3 * (words.length - 1 - i))), sink = typeExit(qo) * size; // last word leaves first+ if (q > 0 && qo < 1) { const dy = (1 - e) * size * 0.9 + sink; let wx = cx; for (const ch of w) { ctx.fillText(ch, wx, y + dy); wx += ctx.measureText(ch).width + tr; } }cx += wOf(w) + space;});ctx.restore();diff --git a/skills/anidoodle/engine/src/canvas-core/launch.ts b/skills/anidoodle/engine/src/canvas-core/launch.tsindex ef52b93..33befd0 100644--- a/skills/anidoodle/engine/src/canvas-core/launch.ts+++ b/skills/anidoodle/engine/src/canvas-core/launch.ts@@ -26,6 +26,7 @@ import type { Film } from "./film";import {C, CHAT, GEN, HOME, INPUT, MONO, REPLY, SANS, TEXT, artCard, blot, camLerp, caretAt, clamp, drawChatFrame, expo, inOut, lerp, lerpP,out3, pathOf, plateLayer, pointer, press, ramp, rr, selfLayer, softShadow, spring, useCam, type Cam, type ChatState,+ frozenNone,} from "./launchKit";import { koiDraw } from "./koiDraw";import { koi } from "./koi";@@ -65,7 +66,10 @@ const typedAt = (text: string, f: number, t0: number, rate: number, seed: number// ---------------------------------------------------------------- camerasconst CARD_C: P = [REPLY.x + REPLY.s / 2, REPLY.y + REPLY.s / 2];-const CARD_CAM: Cam = { c: CARD_C, z: 1000 / REPLY.s }; // the reply card at 1000 px, centred+// The push onto the reply card. It frames the card and its byline above it with ~45 px to spare top and+// bottom, so no text sits cut by the frame's edge while the camera holds there. The card stays centred+// across the frame; the sent message to its right fades out as the camera pushes in (a focus pull).+const CARD_CAM: Cam = { c: [CARD_C[0], (REPLY.y - 35 + REPLY.y + REPLY.s) / 2], z: 1.55 };const GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];// ---------------------------------------------------------------- 1 + 2: the first request, Generate, ink@@ -78,7 +82,10 @@ const koiLayer = (env: Env, f: number) => (f < KOI_DONE ? plateLayer(env, "koiDrconst typeCam = (ctx: Ctx, f: number): Cam => {const typed = typedAt(KOI_PROMPT, f, KOI_TYPE.t0, KOI_TYPE.rate, KOI_TYPE.seed), [cx] = caretAt(ctx, typed);- const macro: Cam = { c: [Math.max(TEXT.x + 330, cx - 110), 934], z: 2.7 };+ // the macro follows the caret, but never so far that the start of the line leaves the frame:+ // the whole prompt fits at this zoom, so once it is long the camera holds and the caret walks on+ const z = 2.7, keepStart = TEXT.x + (W / 2 - 60) / z;+ const macro: Cam = { c: [Math.min(keepStart, Math.max(TEXT.x + 330, cx - 110)), 934], z };return f < 112 ? macro : camLerp(macro, HOME, expo(ramp(f, 112, 150)));};const leanCam = (f: number): Cam => { const lean = expo(ramp(f, DROP.land - 4, DROP.full + 20)) * 0.09; return { c: lerpP(HOME.c, CARD_C, lean * 1.6), z: 1 + lean }; };@@ -102,7 +109,8 @@ const drawInk = (ctx: Ctx, env: Env, f: number, D: typeof DROP, art: CanvasImagefor (let i = 0; i < 9; i++) { const a = i * 2.39 + 0.4, d = 30 + (i % 3) * 22 + 160 * out3(ramp(u, 0, 0.3)), s = (1 - ramp(u, 0.12, 0.34)) * (4 + (i % 4) * 2.5); if (s <= 0.2) continue; ctx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(land[0] + Math.cos(a) * d, land[1] + Math.sin(a) * d, s, 0, Math.PI * 2); ctx.fill(); }};-const sceneOpen = (ctx: Ctx, env: Env, f: number) => {+// `chrome` fades the thread's head, the byline and the composer (1 = shown): only the ink test uses it+const sceneOpen = (ctx: Ctx, env: Env, f: number, chrome = 1) => {useCam(ctx, env, f < T.gen[0] ? typeCam(ctx, f) : leanCam(f));const typed = typedAt(KOI_PROMPT, f, KOI_TYPE.t0, KOI_TYPE.rate, KOI_TYPE.seed);const s: ChatState = {@@ -110,16 +118,18 @@ const sceneOpen = (ctx: Ctx, env: Env, f: number) => {placeholder: "Describe what you want drawn…",sent: f >= PRESS.up ? KOI_PROMPT : undefined, sentAlpha: ramp(f, PRESS.up, PRESS.up + 10),genPress: press(f, PRESS.down, PRESS.up), genHot: ramp(f, 150, 158),- label: f >= DROP.land ? "marker comic" : undefined, labelAlpha: ramp(f, DROP.land, DROP.land + 10),+ label: f >= DROP.land ? "marker comic" : undefined, labelAlpha: ramp(f, DROP.land, DROP.land + 10) * chrome,+ head: chrome, composer: chrome,};drawChatFrame(ctx, s);if (f >= DROP.land) softShadow(ctx, REPLY.x, REPLY.y, REPLY.s, REPLY.s, 22, ramp(f, DROP.land, DROP.full));drawInk(ctx, env, f, DROP, koiLayer(env, f).canvas);- if (f >= 112) pointer(ctx, lerpP([1760, 1130], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, 116, 158))), press(f, PRESS.down, PRESS.up) * 0.8);+ if (f >= 112 && chrome > 0) { ctx.globalAlpha = chrome; pointer(ctx, lerpP([1760, 1130], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, 116, 158))), press(f, PRESS.down, PRESS.up) * 0.8); ctx.globalAlpha = 1; }};-const sceneDraw = (ctx: Ctx, env: Env, f: number) => {- useCam(ctx, env, camLerp(leanCam(f), CARD_CAM, expo(ramp(f, T.draw[0] + 8, T.draw[0] + 80))));- drawChatFrame(ctx, { typed: "", caret: false, placeholder: "Describe what you want drawn…", sent: KOI_PROMPT, label: "marker comic" });+const sceneDraw = (ctx: Ctx, env: Env, f: number, chrome = 1) => {+ const push = expo(ramp(f, T.draw[0] + 8, T.draw[0] + 80));+ useCam(ctx, env, camLerp(leanCam(f), CARD_CAM, push));+ drawChatFrame(ctx, { typed: "", caret: false, placeholder: "Describe what you want drawn…", sent: KOI_PROMPT, sentAlpha: 1 - push, label: "marker comic", labelAlpha: chrome, head: chrome, composer: chrome });artCard(ctx, REPLY.x, REPLY.y, REPLY.s, koiLayer(env, f));};@@ -140,7 +150,7 @@ const sceneTurn = (ctx: Ctx, env: Env, f: number, tn: Turn, art: (f: number) =>const typed = typedAt(tn.prompt, f, k.typeFrom, tn.rate ?? 0.9, tn.seed), img = tn.attach ? env.image?.(tn.attach) : undefined;drawChatFrame(ctx, {typed: f < k.up ? typed : "", caret: f < k.up, placeholder: "Describe what you want drawn…",- sent: f >= k.up ? tn.prompt : undefined, sentAlpha: ramp(f, k.up, k.up + 10),+ sent: f >= k.up ? tn.prompt : undefined, sentAlpha: ramp(f, k.up, k.up + 10) * (1 - pushU), // the push fades it (focus pull)attach: f >= k.up && img ? { img, label: "" } : null,genPress: press(f, k.down, k.up), genHot: ramp(f, k.down - 8, k.down),label: f >= k.landAt ? tn.label : undefined, labelAlpha: ramp(f, k.landAt, k.landAt + 10),@@ -421,7 +431,12 @@ const launchAudio = (sr: number): [Float32Array, Float32Array] => {const withRail = (draw: (ctx: Ctx, env: Env, f: number) => void) => (ctx: Ctx, env: Env, f: number) => { draw(ctx, env, f); drawRail(ctx, env, f); };const shot = (id: keyof typeof T, draw: (ctx: Ctx, env: Env, f: number) => void) => ({ id, start: T[id][0], end: T[id][1], draw: (ctx: Ctx, local: number, env: Env) => draw(ctx, env, T[id][0] + local) });export const launch: Film = {- meta: { title: "anidoodle · launch", W, H, fps: FPS, bpm: 90, durationFrames: N, raster: "cpu", kind: "launch" },+ meta: {+ title: "anidoodle · launch", W, H, fps: FPS, bpm: 90, durationFrames: N, raster: "cpu", kind: "launch",+ // the reveal pulls back into the editor that draws the film: a full screen of its own code, the words+ // gathering over it into the sentence. The dense code is the point (it is all code), not a layout fault.+ checks: { layoutExempt: [[T.reveal[0], T.reveal[1], "the reveal: the editor that draws this film, full of its own code, the words gathering over it"]], none: frozenNone(["gate:identical", "gate:still"]) },+ },assets: { images: { almond: "assets/refs/vangogh-almond-blossom.jpg" } }, // public domain; provenance in engine/assets/refs/PROVENANCE.jsonshots: [shot("type", withRail(sceneOpen)), shot("gen", withRail(sceneOpen)), shot("draw", withRail(sceneDraw)), shot("swim", withRail(sceneSwim)),@@ -431,10 +446,32 @@ export const launch: Film = {audio: Object.assign(launchAudio, { scores: [launchLofi()] }),};-// THE MOTION TEST: the Generate press, the drop and the bloom, on their own.-export const launchClip: Film = {- meta: { ...launch.meta, title: "anidoodle · launch, the ink test", durationFrames: 120 },+// THE MOTION TEST: the Generate press, the drop and the bloom, on their own. The chat's small print (the+// thread's head, the byline, the composer and its button) fades out in the half second before the last+// one, so the test ends on the bloomed card and the request: nothing under 28 px is left on the end.+// Its declarations are its own (the launch film's exemptions are for frames this test does not have):+// anidoodle's temperament and colours, a length budget, and the two words on screen that claim+// something, each in facts/launchClip.json with its source. Its critic record is reviews/launchClip.json.+export const launchClip: Film & { claims: string[] } = {+ meta: {+ ...launch.meta, title: "anidoodle · launch, the ink test", durationFrames: 120,+ checks: { length: { target: 4, max: 5 } },+ // alive but never violent: the press, the drop's arc and the card's spring land small and settle short.+ // anidoodle's brand colour is its orange accent. The near-black is the drawing ink, a neutral that+ // washes and trails at part strength by nature in the drawn look, so it is not declared as a brand fill+ motion: { temperament: "lively", brandColors: [C.accent] },+ holds: [+ [7, 27, "the pointer settles on Generate and presses it: a small move on a still chat, the beat before the ink"],+ [90, 120, "the koi's first pencil lines: fine strokes on a still card, the test ends on the card itself"],+ ],+ },assets: launch.assets,- shots: [{ id: "ink", start: 0, end: 120, draw: (ctx, local, env) => { const f = 140 + local, sh = launch.shots.find((x) => f >= x.start && f < x.end)!; sh.draw(ctx, f - sh.start, env); } }],+ // the thread's subline says how the art is made, and the card's byline names its style; the prompt is+ // a user's request and the rest is the chat's own interface, which claim nothing+ claims: ["drawn in code", "marker comic"],+ shots: [{ id: "ink", start: 0, end: 120, draw: (ctx, local, env) => {+ const f = 140 + local, chrome = 1 - inOut(ramp(local, 75, 89)), scene = f < T.draw[0] ? sceneOpen : sceneDraw;+ scene(ctx, env, f, chrome); drawRail(ctx, env, f);+ } }],};export const KEYS = () => ({ SWIM: SW, BRICK: BK, REF: RF, EMB: EM, WEB: WB, FILM: FM, KOI_DONE, SWIM_OPEN, DIVE });diff --git a/skills/anidoodle/engine/src/canvas-core/launch2.ts b/skills/anidoodle/engine/src/canvas-core/launch2.tsindex 9f20c6a..831f36c 100644--- a/skills/anidoodle/engine/src/canvas-core/launch2.ts+++ b/skills/anidoodle/engine/src/canvas-core/launch2.ts@@ -8,10 +8,12 @@// styles as a rolling wall the camera punches into; the full website tour; the words drawn in their// media; the corner logo throughout; an end card composed for the frame, with both install lines.import type { Ctx, Env, P } from "./core";+import { texture } from "./readable";import type { Film } from "./film";import {C, GEN, HOME, INPUT, MONO, REPLY, SANS, TEXT, blot, camLerp, caretAt, charTimes, clamp, drawChatFrame, expo, inkDrop, inOut, lerp, lerpP,out3, pathOf, plateLayer, pointer, press, ramp, rr, selfLayer, softShadow, typedAt, useCam, type Cam,+ frozenNone,} from "./launchKit";import { koiDraw } from "./koiDraw";import { koi } from "./koi";@@ -99,9 +101,9 @@ const drawCard = (ctx: Ctx, env: Env, it: Extract<Item, { kind: "card" }>, x: nu};// the drop in flight from Generate to where the new card will landconst drawDrop = (ctx: Ctx, f: number, d: { t0: number; land: number }, to: P) => inkDrop(ctx, f, d, to);-type ChatO = { typed: string; caret: boolean; press: number; hot: number; flip?: number; hideCard?: number };+type ChatO = { typed: string; caret: boolean; press: number; hot: number; flip?: number; hideCard?: number; composer?: number };const drawChat = (ctx: Ctx, env: Env, f: number, o: ChatO) => {- drawChatFrame(ctx, { typed: o.typed, caret: o.caret, placeholder: "Describe what you want drawn…", genPress: o.press, genHot: o.hot });+ drawChatFrame(ctx, { typed: o.typed, caret: o.caret, placeholder: "Describe what you want drawn…", genPress: o.press, genHot: o.hot, composer: o.composer });const sc = scrollAt(f);ctx.save(); ctx.beginPath(); ctx.rect(300, 158, 1320, VIEW_BOTTOM - 158); ctx.clip();LAYOUT.forEach((L, i) => {@@ -133,16 +135,19 @@ const sceneOpen = (ctx: Ctx, env: Env, f: number) => {// ---------------------------------------------------------------- 1: the askconst askCam = (ctx: Ctx, f: number): Cam => {- const typed = typedAt(KOI_PROMPT, f, ASK.times), [cx] = caretAt(ctx, typed), macro: Cam = { c: [Math.max(TEXT.x + 330, cx - 110), 934], z: 2.4 };+ // the macro follows the caret, but never so far that the start of the line leaves the frame+ const typed = typedAt(KOI_PROMPT, f, ASK.times), [cx] = caretAt(ctx, typed), z = 2.4, keepStart = TEXT.x + (W / 2 - 60) / z;+ const macro: Cam = { c: [Math.min(keepStart, Math.max(TEXT.x + 330, cx - 110)), 934], z };return f < 136 ? macro : camLerp(macro, HOME, expo(ramp(f, 136, 158)));};// the code composition: the koi card at left of centre, its code streaming on the rightconst CODE_CAM = (): Cam => { const r = cardRect(1, 230), z = 1.25; return { c: [r.x + r.s / 2 + (W / 2 - 520) / z, r.y + r.s / 2 - (620 - H / 2) / z], z }; }; // the card lands at (520, 620), the words above it, the code at rightconst sceneAsk = (ctx: Ctx, env: Env, f: number) => {- const cam = f < T2.ask[1] ? (f < 160 ? askCam(ctx, f) : camLerp(HOME, CODE_CAM(), expo(ramp(f, 186, 226)))) : HOME;+ const push = f < T2.ask[1] && f >= 160 ? expo(ramp(f, 186, 226)) : 0, cam = f < T2.ask[1] ? (f < 160 ? askCam(ctx, f) : camLerp(HOME, CODE_CAM(), push)) : HOME;useCam(ctx, env, cam);const typed = typedAt(KOI_PROMPT, f, ASK.times);- drawChat(ctx, env, f, { typed: f < ASK.up ? typed : "", caret: f < ASK.up, press: press(f, ASK.down, ASK.up), hot: ramp(f, 150, 158) });+ // the code composition crops the composer at the frame's edge: it fades out as the camera pushes in (a focus pull)+ drawChat(ctx, env, f, { typed: f < ASK.up ? typed : "", caret: f < ASK.up, press: press(f, ASK.down, ASK.up), hot: ramp(f, 150, 158), composer: 1 - push });if (f >= 136) pointer(ctx, lerpP([1760, 1130], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, 138, 158))), press(f, ASK.down, ASK.up) * 0.8);bug(ctx, env, f);};@@ -151,20 +156,22 @@ const sceneAsk = (ctx: Ctx, env: Env, f: number) => {const sceneCode = (ctx: Ctx, env: Env, f: number) => {const back = expo(ramp(f, 328, 359));useCam(ctx, env, camLerp(CODE_CAM(), HOME, back));- drawChat(ctx, env, f, { typed: "", caret: false, press: 0, hot: 0 });+ drawChat(ctx, env, f, { typed: "", caret: false, press: 0, hot: 0, composer: back }); // the composer returns with the camera// the editor slides in from the right, the lines stream in time with the drawingscreen(ctx, env);const inU = expo(ramp(f, 200, 222)) * (1 - back), ex = lerp(W + 40, 1010, inU), ey = 110, ew = 830, eh = 860;if (inU > 0.001) {softShadow(ctx, ex, ey, ew, eh, 22, 1.6); ctx.fillStyle = "#1f1c18"; rr(ctx, ex, ey, ew, eh, 22); ctx.fill();- ctx.fillStyle = "#8f8676"; ctx.font = MONO(16); ctx.textBaseline = "middle"; ctx.fillText("koi.ts · drawFish() · running", ex + 26, ey + 30);+ ctx.fillStyle = "#8f8676"; ctx.font = MONO(16); ctx.textBaseline = "middle"; texture(ctx, () => ctx.fillText("koi.ts · drawFish() · running", ex + 26, ey + 30)); // the editor's title bar, part of the code textureconst prog = clamp((f - DROP0.land) / (KOI_DONE - DROP0.land)), shown = Math.floor(prog * KOI_CODE.length), first = Math.max(0, shown - 24);ctx.save(); ctx.beginPath(); ctx.rect(ex, ey + 56, ew, eh - 70); ctx.clip();- for (let i = first; i < Math.min(KOI_CODE.length, shown + 1); i++) {+ // the code streams in time with the drawing: it shows THAT the koi is code, it is not there to be read+ // line by line, so its lines are texture to the reading-time rule (readable.ts texture())+ texture(ctx, () => { for (let i = first; i < Math.min(KOI_CODE.length, shown + 1); i++) {const y = ey + 80 + (i - first) * 32, ln = KOI_CODE[i], partial = i === shown ? ln.slice(0, Math.floor(((prog * KOI_CODE.length) % 1) * ln.length)) : ln;ctx.fillStyle = "#5d564b"; ctx.font = MONO(13); ctx.fillText(String(i + 1).padStart(3, " "), ex + 16, y);ctx.font = MONO(15); ctx.fillStyle = partial.trim().startsWith("//") ? "#8faa7c" : "#ece4d6"; ctx.fillText(partial, ex + 56, y);- }+ } });ctx.restore();}// the point, drawn: no image model@@ -245,7 +252,9 @@ const sceneHand = (ctx: Ctx, env: Env, f: number) => {};const sceneLoop = (ctx: Ctx, env: Env, f: number) => {const flip = Math.cos(Math.PI * inOut(ramp(f, FLIP - 8, FLIP + 8))), r = cardRect(4, f), push = inOut(ramp(f, FLIP + 12, FLIP + 52));- useCam(ctx, env, camLerp(HOME, { c: [r.x + r.s / 2, r.y + r.s / 2], z: 1040 / r.s }, push));+ // the push frames the card and its byline above it, so the byline is never cut by the frame's top edge+ const top = r.y - 40, z = (H - 60) / (r.y + r.s - top);+ useCam(ctx, env, camLerp(HOME, { c: [r.x + r.s / 2, (top + r.y + r.s) / 2], z }, push));drawChat(ctx, env, f, { typed: "", caret: false, press: 0, hot: 0, flip: Math.abs(flip) < 0.02 ? 0.02 : Math.abs(flip) });bug(ctx, env, f);};@@ -318,7 +327,7 @@ const audio2 = (sr: number): [Float32Array, Float32Array] => {// ---------------------------------------------------------------- the filmconst shot = (id: keyof typeof T2, draw: (ctx: Ctx, env: Env, f: number) => void) => ({ id, start: T2[id][0], end: T2[id][1], draw: (ctx: Ctx, local: number, env: Env) => draw(ctx, env, T2[id][0] + local) });export const launch2: Film = {- meta: { title: "anidoodle · launch, cut 2", W, H, fps: FPS, bpm: 90, durationFrames: N, raster: "cpu", kind: "launch" },+ meta: { title: "anidoodle · launch, cut 2", W, H, fps: FPS, bpm: 90, durationFrames: N, raster: "cpu", kind: "launch", checks: { none: frozenNone(["gate:identical", "gate:still"]) } },assets: { images: { almond: "assets/refs/vangogh-almond-blossom.jpg" } }, // public domain; provenance in engine/assets/refs/PROVENANCE.jsonshots: [shot("open", sceneOpen), shot("ask", sceneAsk), shot("code", sceneCode), shot("swim", sceneSwim), shot("wall", sceneWall), shot("brick", sceneBrick),diff --git a/skills/anidoodle/engine/src/canvas-core/launch3.ts b/skills/anidoodle/engine/src/canvas-core/launch3.tsindex 4a21756..54b9cb8 100644--- a/skills/anidoodle/engine/src/canvas-core/launch3.ts+++ b/skills/anidoodle/engine/src/canvas-core/launch3.ts@@ -5,7 +5,7 @@// off to reveal the next scene. (Chosen: the ink bloom, and every word in ink.) 29 bars of the score (launchLofi3), 77 s.import type { Ctx, Env } from "./core";import type { Film } from "./film";-import { C } from "./launchKit";+import { C, frozenNone } from "./launchKit";import { content2, SFX2, T2, WEB_SKIP } from "./launch2";import { logoBug } from "./kinetic";import { beatGrid, makeCut, pic, type, typeFrame, type Seg, type TypeSeg } from "./launchCut";@@ -100,7 +100,10 @@ const ACCEPTED3: [number, number, string][] = [];export const launch3: Film = {- meta: { title: "anidoodle · launch, cut 3", W, H, fps: FPS, bpm: 90, durationFrames: N3, raster: "cpu", kind: "launch", holds: [...HOLDS3, ...ACCEPTED3] },+ meta: { title: "anidoodle · launch, cut 3", W, H, fps: FPS, bpm: 90, durationFrames: N3, raster: "cpu", kind: "launch", holds: [...HOLDS3, ...ACCEPTED3],+ // the code composition: the editor slides in over the chat, so its title bar crosses the sent prompt.+ // The overlap is the move (the koi IS this code); the editor is opaque, the probe cannot see that.+ checks: { layoutExempt: [[205, 283, "the code editor slides in over the chat: an opaque panel crossing the sent prompt, by design"]], none: frozenNone(["gate:identical"]) } },assets: { images: { almond: "assets/refs/vangogh-almond-blossom.jpg" } }, // public domain; provenance in engine/assets/refs/PROVENANCE.jsonshots: [{ id: "cut", start: 0, end: N3, draw: (ctx, F, env) => { const { s, local } = at(F); if (s.kind === "pic") content2(ctx, env, contentOf(s, local)); else drawType(ctx, env, s, local, F); } }],audio: Object.assign(audio3, { scores: [launchLofi3()] }),diff --git a/skills/anidoodle/engine/src/canvas-core/launchCut.ts b/skills/anidoodle/engine/src/canvas-core/launchCut.tsindex 9576c66..e4fc04c 100644--- a/skills/anidoodle/engine/src/canvas-core/launchCut.ts+++ b/skills/anidoodle/engine/src/canvas-core/launchCut.ts@@ -55,18 +55,19 @@ export type BloomOpts = { inF?: number; outF?: number; close?: boolean; radius?:// where the bloom opens from (default the frame's centre): a match cut opens it from the motif (motif.ts)center?: P;// "circle": a clean round iris instead of the ink blot (the clean preset); rim: the ink edge's width (default 26)- shape?: "blot" | "circle"; rim?: number };+ shape?: "blot" | "circle"; rim?: number;+ // the opening's ease, 0..1 over inF + 2 frames (default expo: shut, then most of the frame in four frames)+ ease?: (t: number) => number };// A full-frame page inside an ink bloom. `under` draws the picture the bloom opens over (and closes// onto); `page` draws the page, in screen coordinates, on an offscreen sheet. With close: false the// bloom stays open (an end card).// the bloom's radius at a local frame: a page is fully covered while it is 1110 or more (1920x1080)export const bloomRadius = (local: number, len: number, o: BloomOpts = {}) => {- const IN = o.inF ?? 14, OUT = o.outF ?? 14, u = expo(ramp(local, 0, IN + 2)), v = o.close === false ? 0 : expo(ramp(local, len - OUT, len));+ const IN = o.inF ?? 14, OUT = o.outF ?? 14, u = (o.ease ?? expo)(ramp(local, 0, IN + 2)), v = o.close === false ? 0 : expo(ramp(local, len - OUT, len));return (o.radius ?? 1250) * (v > 0 ? 1 - v : u);};export const bloomFrame = (ctx: Ctx, env: Env, local: number, len: number, under: (first: boolean) => void, page: (c: Ctx) => void, o: BloomOpts = {}) => {- const IN = o.inF ?? 14, OUT = o.outF ?? 14, W = o.W ?? 1920, H = o.H ?? 1080;- const u = expo(ramp(local, 0, IN + 2)), v = o.close === false ? 0 : expo(ramp(local, len - OUT, len)), R = (o.radius ?? 1250) * (v > 0 ? 1 - v : u);+ const W = o.W ?? 1920, H = o.H ?? 1080, R = bloomRadius(local, len, o);under(local < len / 2);if (R < 2) return;const L = selfLayer(env, "sheet", Math.round(W * env.scale), Math.round(H * env.scale)), c = L.ctx;diff --git a/skills/anidoodle/engine/src/canvas-core/launchExample.ts b/skills/anidoodle/engine/src/canvas-core/launchExample.tsindex 8921124..0990cdb 100644--- a/skills/anidoodle/engine/src/canvas-core/launchExample.ts+++ b/skills/anidoodle/engine/src/canvas-core/launchExample.ts@@ -1,15 +1,15 @@-// LAUNCH EXAMPLE. A 16-second launch film for a made-up product, built only from the template: two-// prompts answered by two plates drawing themselves, one type frame, the end card on bar 4.-// Copying it: everything here is a PLACEHOLDER. The lighthouse and fox are stock style plates-// standing in; your film's plates are drawn fresh for YOUR product's subject, in the style recipe-// the brief chose (references/styles.md). The film is silent because a score is composed per-// product (references/music/compose.md); pass that piece as `score`. bpm comes from the brief.-// node tools/still.mjs launchExample --frame 0 the first frame is the thumbnail: check it-// node tools/render.mjs launchExample+// LAUNCH EXAMPLE. A launch film for a made-up product, built only from the template (preset "drawn", the+// default): two prompts answered by two plates drawing themselves, one word page, the end card on bar 5.+// Copying it: everything here is a PLACEHOLDER. The lighthouse and fox are stock style plates standing in;+// your film's plates are drawn fresh for YOUR product's subject, in the style recipe the brief chose+// (references/styles.md). Its score is composed for this made-up product (launchExampleScore.ts); a real+// film composes its own (references/music/compose.md). bpm comes from the brief.+// node tools/launch.mjs ship launchExample --shapes 16x9,9x16import { C } from "./launchKit";import { makeLaunchFilm } from "./launchTemplate";import { lighthouseDraw } from "./lighthouseDraw";import { foxDraw } from "./foxDraw";+import { sketchScore } from "./launchExampleScore";export const launchExample = makeLaunchFilm({title: "Your Product",@@ -23,6 +23,31 @@ export const launchExample = makeLaunchFilm({tagline: "One sentence that says what it is",install: ["npm install your-product", "your-product init"],footer: "yourproduct.example",- bpm: 90, askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 4,- score: null, // silent: compose this product's own score and pass it here+ // THE DECLARATIONS ship reads (node tools/ship.mjs). A check with nothing declared cannot look, and a+ // check that cannot look fails, so every film fills these from its brief. This example's are filled for+ // its made-up product, as a worked example: replace each with your own.+ motion: {+ // how the brand moves, from the brief: "calm", "lively" or "snappy" (motionKit.ts TEMPERAMENTS). A warm+ // drawing tool: alive, never violent. The end card's bloom is paced by it too.+ temperament: "lively",+ // the brand's own colours, #rrggbb: layerscan fails a fill in them at a see-through alpha (olive mud).+ // This made-up product owns its orange; the near-black ink is the drawn look's pen, the neutral every+ // line is written in (a drop's trail of ink ghosts, a byline easing in), so it is not listed here.+ // A brand whose colour IS a dark ink lists it, and the drawn look's ghosts then fail, as they should.+ brandColors: [C.accent],+ },+ // every claim beyond the words and the tagline (which are claims already), each listed in the facts+ // ledger with its source (facts/launchExample.json here; facts.json beside your project). The plates'+ // labels are bylines of placeholder art and claim nothing; a real product's real numbers ARE claims.+ claims: [],+ checks: {+ // the length budget in seconds: over max fails ship, over target flags it+ length: { target: 19, max: 22 },+ // the critic's record is reviews/launchExample.json: this example's own, written by a fresh critic for+ // anidoodle, never a person's review of your film. Your film gets its own (review.md).+ },+ bpm: 90, askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 5,+ // the example's own score, composed for this made-up product's brief (launchExampleScore.ts); a real+ // film composes its own product's score (references/music/compose.md), never this one+ score: sketchScore,});diff --git a/skills/anidoodle/engine/src/canvas-core/launchExampleBrand.ts b/skills/anidoodle/engine/src/canvas-core/launchExampleBrand.tsnew file mode 100644index 0000000..635f91d--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/launchExampleBrand.ts@@ -0,0 +1,110 @@+// LAUNCH EXAMPLE, A BRAND'S OWN LOOK. The template dressed as somebody else's product, to prove a launch film+// can look like YOUR product and still pass ship: "Lantern", an INVENTED reading desk (no real company), on+// a dark ground, its own serif display face (Lora Bold) and text face (Instrument Sans Bold), square+// bubbles, a square composer, its own logo (assets/brand/lantern/lanternMark.svg, drawn for it and imported with+// `node tools/brand.mjs import`), a chat ask and a product ask:+// 1 a chat ask: the question typed as the hook, Ask pressed, the answer opening as an iris on a map of+// sources drawing itself (the two that disagree lit in the accent, a clash mark between them);+// 2 a word page;+// 3 the product's own library from data, its words beside it.+// Everything here is a PLACEHOLDER for a made-up product; your film's look comes from YOUR product (its+// brand.json, its fonts, its colours), its answer plate is drawn for it and its score composed for its brief.+// node tools/launch.mjs ship launchExampleBrand --shapes 16x9,9x16+import type { Film } from "./film";+import { makeLaunchFilm } from "./launchTemplate";+import type { ProductUI } from "./productUI";+import { tallyScore } from "./launchExampleCleanScore";+import lora from "../../assets/fonts/Lora-Bold.ttf";+import instrument from "../../assets/fonts/InstrumentSans-Bold.ttf";+import lanternBrand from "../../assets/brand/lantern/brand.json";++// the brand's colours, as its own design file would name them (a dark reading desk, one lamp-light accent)+// (the window a clear step lighter than the ground and the answer's ground lighter again: on a dark page a+// window one shade off its ground changed too few pixels as the room crept, and read as a freeze to the gate)+const LANTERN = { bg: "#0f1113", card: "#1f2228", ink: "#f3ede0", soft: "#b8b0a2", mute: "#8f897e", line: "#3a3f48", chip: "#30343c", accent: "#f2b544", accentDeep: "#c98f22", paper: "#272b32" };++// the answer: six sources laid out as pages, each drawing itself (a page, its heading bar, its lines), joined+// where they cite each other; then the two that DISAGREE light up in the lamp's amber, joined by a bold+// amber line with a clash mark on it. No words inside: the card's byline says what it is.+const PAGES: [number, number][] = [[200, 230], [560, 170], [840, 260], [260, 640], [610, 560], [860, 760]];+const LINKS: [number, number][] = [[0, 1], [1, 2], [0, 3], [3, 4], [1, 4], [4, 5], [2, 5]];+const PW = 190, PH = 230, CLASH: [number, number] = [1, 3];+const sources: Film = {+ meta: { title: "Lantern answer: which sources disagree", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 150 },+ assets: { images: {} },+ shots: [{ id: "map", start: 0, end: 150, draw: (ctx, f, env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ // (a ground a step off the card's, so the iris that opens onto it is seen)+ ctx.fillStyle = "#353a43"; ctx.fillRect(0, 0, 1080, 1080);+ const q = (t0: number, len: number) => { const u = Math.min(1, Math.max(0, (f - t0) / len)); return 1 - (1 - u) ** 3; };+ const ctr = (i: number): [number, number] => [PAGES[i][0] + PW / 2, PAGES[i][1] + PH / 2];+ // the links first, under the pages+ ctx.lineWidth = 7; ctx.strokeStyle = "#5a6070"; ctx.lineCap = "round";+ LINKS.forEach(([a, b], i) => { const e = q(16 + i * 6, 18); if (e <= 0) return; const [x0, y0] = ctr(a), [x1, y1] = ctr(b); ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + (x1 - x0) * e, y0 + (y1 - y0) * e); ctx.stroke(); });+ const hot = q(78, 18); // the two that disagree light up+ PAGES.forEach(([x, y], i) => {+ const e = q(4 + i * 6, 16); if (e <= 0) return;+ const h = PH * e, lit = CLASH.includes(i) ? hot : 0;+ ctx.fillStyle = "#f3ede0"; ctx.fillRect(x, y + PH - h, PW, h);+ if (lit > 0) { ctx.lineWidth = 12; ctx.strokeStyle = "#f2b544"; ctx.strokeRect(x - 10 * lit, y + PH - h - 10 * lit, PW + 20 * lit, h + 20 * lit); }+ // the page's heading bar and its lines, written as the page rises+ ctx.fillStyle = lit > 0.5 ? "#c98f22" : "#4a505c"; if (e > 0.6) ctx.fillRect(x + 22, y + 26, (PW - 70) * q(10 + i * 6, 14), 22);+ ctx.fillStyle = "#9aa0ab"; for (let r = 0; r < 5; r++) { const w = q(14 + i * 6 + r * 2, 12); if (w > 0) ctx.fillRect(x + 22, y + 72 + r * 30, (PW - 44 - (r % 2) * 40) * w, 12); }+ });+ // the clash: a bold amber line between the two, and a mark where it crosses+ if (hot > 0) {+ const [x0, y0] = ctr(CLASH[0]), [x1, y1] = ctr(CLASH[1]), e = q(88, 16), mx = (x0 + x1) / 2, my = (y0 + y1) / 2;+ ctx.strokeStyle = "#f2b544"; ctx.lineWidth = 14; ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + (x1 - x0) * e, y0 + (y1 - y0) * e); ctx.stroke();+ const b = q(100, 14); if (b > 0) { ctx.fillStyle = "#f2b544"; ctx.beginPath(); ctx.arc(mx, my, 46 * b, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = "#0f1113"; ctx.lineWidth = 10; ctx.beginPath(); ctx.moveTo(mx - 20 * b, my - 20 * b); ctx.lineTo(mx + 20 * b, my + 20 * b); ctx.moveTo(mx + 20 * b, my - 20 * b); ctx.lineTo(mx - 20 * b, my + 20 * b); ctx.stroke(); }+ }+ } }],+};++const library: ProductUI = {+ title: "Lantern", nav: ["Library", "Notes", "Map"], action: "Check all",+ // (rows keep their places and gain their tag as they are checked: no crossing rows)+ before: { items: [+ { id: "a", label: "Field notes, 2019", value: "12 p." },+ { id: "b", label: "Survey, spring", value: "40 p." },+ { id: "c", label: "Interview, May", value: "8 p." },+ ] },+ after: { items: [+ { id: "a", label: "Field notes, 2019", value: "12 p.", tag: "cited", done: true, accent: true },+ { id: "b", label: "Survey, spring", value: "40 p.", tag: "cited", done: true },+ { id: "c", label: "Interview, May", value: "8 p.", tag: "cited", done: true },+ ] },+};++export const launchExampleBrand = makeLaunchFilm({+ title: "Lantern", subtitle: "your reading desk", placeholder: "Ask Lantern…", fps: 60,+ // THE LOOK: the brand's own, field by field (launch-video-kit.md, Looks). `from` fills the palette and the+ // logo from the brand file; the explicit palette wins over it; the fonts are the brand's files.+ look: {+ base: "clean",+ from: lanternBrand,+ palette: LANTERN,+ fonts: { display: { family: "Lora", file: lora }, text: { family: "Instrument Sans", file: instrument } },+ shape: { radius: 14, bubble: "square", composer: "box", button: "square", buttonLabel: "Ask" },+ chat: { title: "Lantern", subtitle: "your reading desk", bubble: { fill: "#353a43", ink: "#f3ede0" }, reply: { fill: "#272b32", ink: "#f3ede0" } },+ },+ asks: [+ { prompt: "which sources disagree?", plate: sources, label: "Your sources, mapped" },+ { kind: "ui", ui: library, split: [{ text: "Then it cites", style: "ink", color: LANTERN.ink }, { text: "every page.", style: "ink", color: LANTERN.accent }] },+ ],+ words: [[{ text: "READ LESS.", style: "ink", color: LANTERN.ink }, { text: "KNOW MORE.", style: "ink", color: LANTERN.accent }]],+ tagline: "A reading desk that keeps your sources straight",+ install: ["npm install lantern"],+ footer: "lantern.example",+ // THE DECLARATIONS ship reads (node tools/ship.mjs), filled for this made-up product as a worked example+ motion: { temperament: "lively", brandColors: [LANTERN.accent, LANTERN.ink] },+ claims: [],+ checks: {+ length: { target: 22, max: 25 },+ // the split beat IS the product's own library beside its two words: its rows are what the viewer came to see+ layoutExempt: [[560, 960, "the library beat: the product's own rows beside its two words"]],+ // the critic's record is reviews/launchExampleBrand.json, this example's own+ },+ bpm: 90, askBeats: 8, typeBeats: 6, endBeats: 8, claimBar: 6,+ // the clean example's score (a made-up product and brief); a real film composes its own+ score: tallyScore,+});diff --git a/skills/anidoodle/engine/src/canvas-core/launchExampleClean.ts b/skills/anidoodle/engine/src/canvas-core/launchExampleClean.tsindex 116e98e..b0fb2cb 100644--- a/skills/anidoodle/engine/src/canvas-core/launchExampleClean.ts+++ b/skills/anidoodle/engine/src/canvas-core/launchExampleClean.ts@@ -10,6 +10,7 @@// node tools/launch.mjs ship launchExampleClean --shapes 16x9,9x16import { makeLaunchFilm } from "./launchTemplate";import type { ProductUI } from "./productUI";+import { tallyScore } from "./launchExampleCleanScore";const inbox: ProductUI = {title: "Tally", nav: ["Inbox", "Books", "Reports"], action: "Match all", command: "Ask Tally…",@@ -18,8 +19,8 @@ const inbox: ProductUI = {items: [{ id: "a", label: "Design tool, Sep", value: "$144", tag: "no receipt" },{ id: "b", label: "Cloud hosting, Sep", value: "$1,208", tag: "no receipt" },- { id: "c", label: "Team lunch, Thu", value: "$86", tag: "no receipt" },- { id: "d", label: "Train to Leeds", value: "$42", tag: "no receipt" },+ { id: "c", label: "Team lunch, Sep", value: "$86", tag: "no receipt" },+ { id: "d", label: "Train fare, Sep", value: "$42", tag: "no receipt" },],},after: {@@ -27,8 +28,8 @@ const inbox: ProductUI = {items: [{ id: "b", label: "Cloud hosting, Sep", value: "$1,208", tag: "matched", done: true, accent: true },{ id: "a", label: "Design tool, Sep", value: "$144", tag: "matched", done: true },- { id: "c", label: "Team lunch, Thu", value: "$86", tag: "matched", done: true },- { id: "d", label: "Train to Leeds", value: "$42", tag: "matched", done: true },+ { id: "c", label: "Team lunch, Sep", value: "$86", tag: "matched", done: true },+ { id: "d", label: "Train fare, Sep", value: "$42", tag: "matched", done: true },],},};@@ -60,13 +61,47 @@ export const launchExampleClean = makeLaunchFilm({title: "Tally", preset: "clean", fps: 60,asks: [{ kind: "ui", ui: inbox, prompt: "match every receipt from September" },- { kind: "ui", ui: books, split: [{ text: "Books close", style: "ink", color: "#15161a" }, { text: "themselves.", style: "ink", color: "#2f54eb" }] },+ { kind: "ui", ui: books, split: [{ text: "Month end,", style: "ink", color: "#15161a" }, { text: "one click.", style: "ink", color: "#2f54eb" }] }, // the words say what the picture shows: one press closes the month{ kind: "ui", ui: reports, split: [{ text: "And it shows", style: "ink", color: "#15161a" }, { text: "you where.", style: "ink", color: "#2f54eb" }] },],words: [[{ text: "ASK ONCE.", style: "ink", color: "#15161a" }, { text: "DONE.", style: "ink", color: "#2f54eb" }]],tagline: "Bookkeeping that does itself",install: ["npm install tally", "tally init"],footer: "tally.example",- bpm: 90, askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 6,- score: null, // silent here: compose this product's own score and pass it+ // the end card on endCard.ts's asymmetric grid: the name top-left with the drop as its full stop,+ // the line and the install line under it, the footer as a stamp on the right (never a centred stack)+ endCard: "grid",+ // THE DECLARATIONS ship reads (node tools/ship.mjs). A check with nothing declared cannot look, and a+ // check that cannot look fails, so every film fills these from its brief. This example's are filled+ // for its made-up product, as a worked example: replace each with your own.+ motion: {+ // how the brand moves, from the brief: "calm", "lively" or "snappy" (motionKit.ts TEMPERAMENTS).+ // A UI product with quick arrivals; motionscan fails any stretch faster than this allows.+ temperament: "snappy",+ // the brand's own colours, #rrggbb: layerscan fails a fill in them at a see-through alpha (olive mud)+ brandColors: ["#2f54eb", "#15161a"],+ },+ // every claim beyond the words, split words and tagline (which are claims already), each listed in the+ // facts ledger with its source (facts/launchExampleClean.json here; facts.json beside your project).+ // The UI's figures are made-up sample data in a mock screen and claim nothing; a real product's real+ // numbers on screen ARE claims: list each one here with its source.+ claims: [],+ checks: {+ // the length budget in seconds: over max fails ship, over target flags it+ length: { target: 22, max: 25 },+ // each ask IS the product's own screen: its title, nav, command bar, stats and rows are the UI the+ // viewer came to see, so their density is the point, not a layout fault. Only those beats (60 fps+ // frames, the travels into and out of them included); the word page and the end card are still judged.+ layoutExempt: [+ [0, 330, "the first ask shows the product's whole inbox: dense UI is the subject"],+ [440, 680, "the books beat: the product's own cards beside its two words"],+ [680, 960, "the reports beat: the product's own report rows beside its two words"],+ ],+ // the critic's record is reviews/launchExampleClean.json: this example's own, written by a fresh+ // critic for anidoodle, never a person's review of your film. Your film gets its own (review.md).+ },+ bpm: 90, askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 6,+ // the example's own score, composed for this made-up product's brief (launchExampleCleanScore.ts);+ // a real film composes its own product's score (references/music/compose.md), never this one+ score: tallyScore,});diff --git a/skills/anidoodle/engine/src/canvas-core/launchExampleCleanChat.ts b/skills/anidoodle/engine/src/canvas-core/launchExampleCleanChat.tsnew file mode 100644index 0000000..33f1e90--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/launchExampleCleanChat.ts@@ -0,0 +1,83 @@+// LAUNCH EXAMPLE, CLEAN, WITH A CHAT ASK. The clean look (preset "clean": a quiet canvas, one accent,+// type as the design) on a product people ask in a chat, at 60 fps:+// 1 a chat ask: the question typed as the hook, Generate pressed, and the answer card opening as an+// iris on a chart drawing itself (the answer is any film of this engine, here a small bar chart);+// 2 a word page;+// 3 the product's own screen from data, with its words beside it.+// Everything here is a PLACEHOLDER for a made-up product; your film's answer is drawn for YOUR product,+// its UI data comes from its real screens, and its score is composed for its brief.+// node tools/launch.mjs ship launchExampleCleanChat --shapes 16x9,9x16+import type { Film } from "./film";+import { CLEAN, makeLaunchFilm } from "./launchTemplate";+import type { ProductUI } from "./productUI";+import { tallyScore } from "./launchExampleCleanScore";++// the answer: four months of a spend line as bars, rising one after another, the last in the accent.+// No words inside it: the card's byline says what it is, at a size the frame checks can read.+const BARS = [0.42, 0.47, 0.45, 0.78];+const chart: Film = {+ meta: { title: "Tally answer: hosting by month", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 150 },+ assets: { images: {} },+ shots: [{ id: "chart", start: 0, end: 150, draw: (ctx, f, env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ // (a cool tint, not the card's paper: the answer opens as an iris, and paper on paper hid it, cc1-3)+ ctx.fillStyle = "#e8ecf6"; ctx.fillRect(0, 0, 1080, 1080);+ ctx.fillStyle = CLEAN.line; for (let j = 1; j <= 4; j++) ctx.fillRect(120, 900 - j * 170, 840, 3);+ ctx.fillStyle = CLEAN.ink; ctx.fillRect(120, 900, 840, 5);+ BARS.forEach((v, i) => {+ // each bar rises on an out-cubic, 12 frames after the one before; the accent bar last and tallest+ const q = Math.min(1, Math.max(0, (f - 6 - i * 12) / 30)), e = 1 - (1 - q) ** 3, h = 700 * v * e;+ ctx.fillStyle = i === BARS.length - 1 ? CLEAN.accent : "#b9bfcc";+ ctx.fillRect(170 + i * 205, 900 - h, 150, h);+ });+ } }],+};++const inbox: ProductUI = {+ title: "Tally", nav: ["Inbox", "Books", "Reports"], action: "Match all",+ // (the rows keep their places and gain their tag as they match, the hosting row the chat asked about in+ // the accent: rows that traded places passed through each other, and a fresh critic read the crossing as+ // rows going see-through and vanishing, cc1-2. The words beside them are read through the press, a+ // declared hold, so the in-place change is never dead air)+ before: { items: [+ { id: "a", label: "Cloud hosting, Sep", value: "$1,208" },+ { id: "b", label: "Design tool, Sep", value: "$144" },+ { id: "c", label: "Team lunch, Sep", value: "$86" },+ ] },+ after: { items: [+ { id: "a", label: "Cloud hosting, Sep", value: "$1,208", tag: "matched", done: true, accent: true },+ { id: "b", label: "Design tool, Sep", value: "$144", tag: "matched", done: true },+ { id: "c", label: "Team lunch, Sep", value: "$86", tag: "matched", done: true },+ ] },+};++export const launchExampleCleanChat = makeLaunchFilm({+ title: "Tally", subtitle: "your books, answered", placeholder: "Ask Tally…", genLabel: "Ask", preset: "clean", fps: 60,+ asks: [+ { prompt: "why did hosting go up?", plate: chart, label: "Cloud hosting, by month" },+ { kind: "ui", ui: inbox, split: [{ text: "Then it fixes", style: "ink", color: "#15161a" }, { text: "the books.", style: "ink", color: "#2f54eb" }] },+ ],+ words: [[{ text: "ASK IT.", style: "ink", color: "#15161a" }, { text: "SEE WHY.", style: "ink", color: "#2f54eb" }]],+ tagline: "Bookkeeping that does itself",+ install: ["npm install tally", "tally init"],+ footer: "tally.example",+ // the end card on endCard.ts's asymmetric grid: with two install lines a centred stack is five blocks on one+ // axis, the centred stack framecheck rejects+ endCard: "grid",+ // THE DECLARATIONS ship reads (node tools/ship.mjs). Filled for this made-up product as a worked example:+ // replace each with your own (launchExampleClean.ts explains each one)+ motion: { temperament: "snappy", brandColors: ["#2f54eb", "#15161a"] },+ claims: [],+ checks: {+ length: { target: 22, max: 25 },+ // the split beat IS the product's own inbox beside its words: its rows are what the viewer came to see+ // (60 fps frames, the travel into it included); the chat, the word page and the end card are still judged+ layoutExempt: [[560, 960, "the inbox beat: the product's own rows beside its two words"]],+ // the critic's record is reviews/launchExampleCleanChat.json, this example's own+ },+ // (askBeats 8: the chart answering the chat ask has time to be seen; claimBar 6 lands the end card on bar 6,+ // so the score leaves it a 5.3 s hold, as the other examples have)+ bpm: 90, askBeats: 8, typeBeats: 6, endBeats: 8, claimBar: 6,+ // the clean example's own score (the same made-up product and brief); a real film composes its own+ score: tallyScore,+});diff --git a/skills/anidoodle/engine/src/canvas-core/launchExampleCleanScore.ts b/skills/anidoodle/engine/src/canvas-core/launchExampleCleanScore.tsnew file mode 100644index 0000000..6a0b983--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/launchExampleCleanScore.ts@@ -0,0 +1,52 @@+// THE EXAMPLE'S SCORE. Composed for the clean launch example's made-up product (a calm, confident+// bookkeeping app) the way a user composes one for their own brief (references/music/compose.md). It is+// a worked example of the format, never a score to reuse: your film's music is written for YOUR brief.+//+// The brief as numbers: a 21 s launch film at 90 bpm in 4/4 (a bar is 2.67 s), cut on the template's+// beat grid. Picture beats: the ask typed from frame 0, the word page at 4.0 s, the books screen at+// 6.7 s, the reports screen on bar 4 (10.7 s), the end card on bar 6 (16.0 s, claimBar 6).+// The arc: a quiet start under the typing, the groove as the screens work, a breath on bar 5, the+// home chord and the motif's last word on the end card, then a short ring. Loudness stays even (a+// product film is watched with the sound low), so the energy moves by layers more than by level.+// The motif: an upbeat start, a third up, then steps home; answered a step lower, sequenced up,+// lifted to its peak on the reports screen, fragmented in the breath, augmented at the end.+import type { Material } from "./music";++export const tallyScore = (): Material => ({+ style: "lofiElectronic", title: "Tally, balanced", seed: 41, mood: "hopeful",+ bpm: 90, key: "A", mode: "major", meter: "4/4",+ moodControls: { energy: 0.45, warmth: 0.55, brightness: 0.7, tension: 0.35, space: 0.85 },+ swing: 0.53, dyn: [0.6, 0.64], tail: 0, // no ring bar: the held home chord is the ring, released inside the film+ // the warm bass, not the round sub: a bed under a voice-free film needs body, not rumble+ voices: { bass: "warm", lead: "bell" },+ levels: { lead: 2, counter: -6, chords: -3, kick: -2 }, // the answering line sits under the tune, never over it+ chords: {+ A: { voicing: "[G#3 B3 C#4 E4]", bass: "A2:1.5 E3:.5 A2:1 C#3:1" },+ Fsm: { voicing: "[E3 A3 C#4 G#4]", bass: "F#2:1.5 C#3:.5 F#2:.5 r:.5 A2:1" },+ D: { voicing: "[F#3 A3 C#4 E4]", bass: "D3:1.5 A2:.5 D3:1 E3:1" },+ E: { voicing: "[E3 A3 B3 D4]", bass: "E3:1.5 B2:.5 E3:1 r:1" },+ Bm: { voicing: "[E3 A3 C#4 D4]", bass: "B2:1.5 F#3:.5 B2:2" },+ Esus: { voicing: "[E3 A3 B3 D4]", bass: "E3:4" },+ Home: { voicing: "[E3 G#3 C#4 E4]", bass: "A2:4" },+ },+ motifs: {+ state: "r:.5 C#5:.5 E5:1 D5:.5 C#5:.5 B4:1",+ answer: "r:.5 B4:.5 D5:1 C#5:.5 B4:.5 A4:1",+ rise: "r:.5 D5:.5 F#5:1 E5:.5 D5:.5 C#5:1",+ peak: "r:.5 E5:.5 A5:1.5 G#5:.5 E5:1",+ lean: "r:.5 C#5:.5 E5:.5 F#5:.5 E5:2",+ breath: "r:.5 C#5:.5 E5:1 r:.5 D5:.5 B4:1",+ last: "C#5:1 E5:1 A4:2",+ rest: "r:4",+ },+ grooves: { main: { family: "bounce", density: 0.35, variation: 0.3 }, half: { family: "halfTime", density: 0.3 } },+ sections: [+ { kind: "intro", bars: 1, harmony: ["A"], chordVel: 0.55, energy: 0.45 },+ { kind: "groove", bars: 2, harmony: ["Fsm", "D"], lead: ["state", "answer"], groove: "main", energy: 0.5 },+ { kind: "hook", bars: 2, harmony: ["A", "E"], lead: ["peak", "lean"], counter: ["rise", "rest"], groove: "main", energy: 0.58 },+ { kind: "half", bars: 1, harmony: ["Bm Esus"], lead: ["breath"], bass: ["B2:1.5 F#3:.5 E3:1.5 r:.5"], groove: "half", energy: 0.5 },+ { kind: "outro", bars: 2, harmony: ["Home", "~"], lead: ["last", "rest"], comp: ["x:4", "~:2 r:2"], energy: 0.6 },+ // the stretch: one more held bar of home, played 0 or more times so the film is whole bars of the score+ { kind: "outro", bars: 1, harmony: ["~"], lead: ["rest"], stretch: true, energy: 0.5 },+ ],+});diff --git a/skills/anidoodle/engine/src/canvas-core/launchExampleScore.ts b/skills/anidoodle/engine/src/canvas-core/launchExampleScore.tsnew file mode 100644index 0000000..eaa7033--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/launchExampleScore.ts@@ -0,0 +1,55 @@+// THE DRAWN EXAMPLE'S SCORE. Composed for the drawn launch example's made-up product (a warm, lively tool+// that turns a sentence into a hand-drawn picture) the way a user composes one for their own brief+// (references/music/compose.md). It is a worked example of the format, never a score to reuse: your film's+// music is written for YOUR brief.+//+// The brief as numbers: a 16 to 19 s launch film at 90 bpm in 4/4 (a bar is 2.67 s), cut on the template's+// beat grid. Picture beats: the first prompt typed from frame 0 and Generate pressed at 1.8 s, the word+// page at 4.0 s, the second prompt at 8.0 s and its press at 10.5 s, the end card on bar 5 (13.3 s,+// claimBar 5). The arc: a fingerpicked start under the typing, the tune on the word page, the lift as the+// second answer draws itself, the home chord and the tune's last word on the end card, then a short ring.+// Loudness stays even (a product film is watched with the sound low): the energy moves by layers.+// The motif: a rising sixth and a step back, a sketch of a line being drawn; answered lower, lifted on the+// second answer, and set down whole on the end card.+import type { Material } from "./music";++export const sketchScore = (): Material => ({+ style: "folk", title: "Your Product, sketched", seed: 23, mood: "hopeful",+ bpm: 90, key: "D", mode: "major", meter: "4/4",+ moodControls: { energy: 0.5, warmth: 0.7, brightness: 0.6, tension: 0.3, space: 0.75 },+ swing: 0.52, dyn: [0.6, 0.66], tail: 0, // the held home chord is the ring, released inside the film+ // (the lead is set 2 dB under where it was: the harp's soft layer is recorded about 12 dB hot against its+ // model and the sample loader trims at most 9 dB, so its D5 to A5 tune sat 3 dB hot in the 300 Hz to+ // 1.2 kHz body and crowded it, the sound check's one warning)+ levels: { lead: 0, counter: -6, chords: -2 },+ chords: {+ D: { voicing: "[D3 A3 D4 F#4]", bass: "D2:1.5 A2:.5 D2:1 F#2:1" },+ Bm: { voicing: "[B2 F#3 B3 D4]", bass: "B1:1.5 F#2:.5 B1:1 D2:1" },+ G: { voicing: "[G2 D3 G3 B3]", bass: "G2:1.5 D2:.5 G2:1 B2:1" },+ A: { voicing: "[A2 E3 A3 C#4]", bass: "A2:1.5 E2:.5 A2:1 C#3:1" },+ Em: { voicing: "[E3 G3 B3 D4]", bass: "E2:1.5 B2:.5 E2:2" },+ Asus: { voicing: "[A2 D3 E3 A3]", bass: "A2:4" },+ Home: { voicing: "[D3 A3 D4 F#4 A4]", bass: "D2:4" },+ },+ motifs: {+ open: "r:1 D5:.5 E5:.5 F#5:1 A4:1",+ sketch: "r:.5 A4:.5 F#5:1 E5:.5 D5:.5 B4:1",+ reply: "r:.5 F#4:.5 D5:1 C#5:.5 B4:.5 A4:1",+ lift: "r:.5 B4:.5 G5:1 F#5:.5 E5:.5 D5:1",+ crest: "r:.5 C#5:.5 A5:1.5 G5:.5 E5:1",+ lean: "r:.5 D5:.5 E5:.5 F#5:.5 E5:2",+ last: "A4:1 F#5:1 D5:2",+ ring: "r:1 F#4:1 A4:1 D5:1", // the last bar keeps sounding under the held card: a held chord alone sagged 16 LU (sound check)+ rest: "r:4",+ },+ // brushes under the picking: a light kit that moves without pushing (a drawing tool, not a dance floor)+ grooves: { main: { family: "brushes", density: 0.3, variation: 0.3 } },+ sections: [+ { kind: "intro", bars: 1, harmony: ["D"], lead: ["open"], chordVel: 0.6, energy: 0.5 }, // the tune's first notes under the typing: no hole before the press+ { kind: "verse", bars: 2, harmony: ["Bm", "G"], lead: ["sketch", "reply"], groove: "main", energy: 0.55 },+ { kind: "hook", bars: 2, harmony: ["G A", "Em Asus"], lead: ["lift", "crest"], counter: ["rest", "lean"], bass: ["G2:1.5 D2:.5 A2:1.5 E2:.5", "E2:1.5 B2:.5 A2:2"], groove: "main", energy: 0.6 },+ { kind: "outro", bars: 2, harmony: ["Home", "Home"], lead: ["last", "ring"], groove: "main", energy: 0.6 },+ // the stretch: one more held bar of home, played 0 or more times so the film is whole bars of the score+ { kind: "outro", bars: 1, harmony: ["~"], lead: ["rest"], stretch: true, energy: 0.5 },+ ],+});diff --git a/skills/anidoodle/engine/src/canvas-core/launchKit.ts b/skills/anidoodle/engine/src/canvas-core/launchKit.tsindex 3d92c4c..1c055e6 100644--- a/skills/anidoodle/engine/src/canvas-core/launchKit.ts+++ b/skills/anidoodle/engine/src/canvas-core/launchKit.ts@@ -5,8 +5,18 @@// plate drawn live by its own code, never a recording of it.import { fractal, type Ctx, type Env, type Layer, type P } from "./core";import { renderFrame, type Film } from "./film";+import { drawEl, type BrandElement } from "./brandKit";// ---------------------------------------------------------------- palette and type+// THE FROZEN LAUNCH FILMS. launch, launch2 and launch3 are the source of anidoodle's published launch film+// (README). They were made before the 0.10 checks and are kept as they were published: never re-cut to+// meet a later check, and never a template to copy (references/workflows/launch-video-kit.md). Each declares+// the ship rows that cannot look, and the dead-air gate rows it fails, in meta.checks.none with this reason.+export const FROZEN = "frozen source of the published launch film; made before the 0.10 checks";+/** meta.checks.none for a frozen launch film: the ship rows with nothing declared to judge against, plus the named gate rows. */+export const frozenNone = (gateRows: ("gate:identical" | "gate:still")[] = []): Record<string, string> =>+ Object.fromEntries([...["motion:temperament", "layers:translucent", "facts", "review", "length"].map((k) => [k, FROZEN]), ...gateRows.map((k) => [k, `${FROZEN}: its still beats are the pace it was published with, and declaring them as holds one by one would be a re-cut on paper`])]);+export const C = {bg: "#ece6da", card: "#fffdf8", ink: "#1d1a16", soft: "#6f675c", mute: "#a39a8c", line: "#e0d8c8",chip: "#f3ede1", accent: "#d4622b", accentDeep: "#a9471a", paper: "#fbf9f3", shadow: "rgba(60,40,20,0.10)",@@ -99,12 +109,13 @@ export const blot = (c: P, R: number, seed: number, n = 96): P[] => {export const pathOf = (ctx: Ctx, pts: P[]) => { ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); };// ---------------------------------------------------------------- pointer-export const pointer = (ctx: Ctx, p: P, down = 0, s = 1.35) => {+// (`tone`: its fill and edge; a dark look passes a light arrow, which a black one on a dark page is not seen)+export const pointer = (ctx: Ctx, p: P, down = 0, s = 1.35, tone: { fill: string; edge: string } = { fill: "#111", edge: "#fff" }) => {const k = s * (1 - 0.12 * down);const shape: P[] = [[0, 0], [0, 25], [6.4, 19.2], [10.6, 29], [14.8, 27.2], [10.8, 17.8], [19, 17.8]];ctx.save(); ctx.translate(p[0], p[1]); ctx.scale(k, k);ctx.fillStyle = "rgba(0,0,0,0.18)"; pathOf(ctx, shape.map(([x, y]) => [x + 1.2, y + 2] as P)); ctx.fill();- pathOf(ctx, shape); ctx.fillStyle = "#111"; ctx.fill(); ctx.lineWidth = 1.6; ctx.strokeStyle = "#fff"; ctx.lineJoin = "round"; ctx.stroke();+ pathOf(ctx, shape); ctx.fillStyle = tone.fill; ctx.fill(); ctx.lineWidth = 1.6; ctx.strokeStyle = tone.edge; ctx.lineJoin = "round"; ctx.stroke();ctx.restore();};@@ -118,6 +129,7 @@ export const TEXT = { x: 404, base: 948, px: 34 };export type ChatState = {typed: string; caret: boolean; placeholder?: string;+ full?: string; // the whole prompt being typed: a wrapping composer breaks where it will (composerLines)sent?: string; sentAlpha?: number; // the user's message once it has gone upattach?: { img: CanvasImageSource; label: string } | null;genPress?: number; genHot?: number; // the button: press depth 0..1, hover glow 0..1@@ -143,7 +155,17 @@ export type ChatGeom = {theme?: Partial<typeof C>;drop?: string; // the ink drop's colour (default the ink): the clean preset's drop is its one accentiris?: boolean; // the answer card opens as a clean round iris instead of an ink bloom (the clean preset)+ wrapAs?: { px: number; maxW: number }; // wrap the typed words as at this type size and width (a composer easing between two sizes keeps one set of line breaks), drawn at TEXT.px+ look?: ChatLook; // a custom look (launchLook.ts): its text face, shapes, header and label colour; absent, the stock chat+};+/** What the chat takes from a custom look (launchLook.ts resolves it): its faces, its shapes and its window. */+export type ChatLook = {+ fonts: { text: (w: number, px: number) => string };+ shape: { bubble: "rounded" | "square" | "none"; composer: "box" | "bar"; button: "pill" | "square"; radius?: number; buttonLabel?: string };+ chat: { header?: boolean; title?: string; subtitle?: string; logo?: BrandElement; bubble?: { fill: string; ink: string }; reply?: { fill: string; ink: string } };+ onAccent: string;};+const FT = (g: ChatGeom) => g.look?.fonts.text ?? SANS;export const CHAT_GEOM: ChatGeom = { CHAT, INPUT, GEN, REPLY, TEXT, k: 1, px: { head: 22, sub: 18, bubble: 26, label: 20, gen: 24 }, wrap: 0, lineH: 44 };// the same component at any size: derived from the window's rectangle, a length scale and the type// sizes. chatGeom(CHAT, 1, CHAT_GEOM.px, TEXT.px, 0) IS CHAT_GEOM (a test holds it to that).@@ -157,9 +179,16 @@ export const chatGeom = (chat: Rect & { r?: number }, k: number, px: ChatGeom["pconst pal = (g: ChatGeom) => (g.theme ? { ...C, ...g.theme } : C);// the typed words as they sit in a wrapping composer: whole words per line, a word longer than the// line broken where it must. Measured with the real font, so the lines are what the viewer sees.-export const composerLines = (ctx: Ctx, typed: string, g: ChatGeom): string[] => {- const maxW = g.GEN.x - 20 * g.k - g.TEXT.x;- ctx.font = SANS(500, g.TEXT.px);+// `full`: the whole prompt being typed. Given it, the words break where the finished prompt breaks, so a word+// starts on the line it will end on (a half-typed word that fit jumped a line as it grew, its line read 0.15 s)+export const composerLines = (ctx: Ctx, typed: string, g: ChatGeom, full?: string): string[] => {+ if (full !== undefined && full !== typed && full.startsWith(typed)) {+ const all = composerLines(ctx, full, g), out: string[] = []; let left = typed.length;+ for (const l of all) { if (left <= 0 && out.length) break; out.push(l.slice(0, Math.max(0, left))); left -= l.length; }+ return out;+ }+ const maxW = g.wrapAs ? g.wrapAs.maxW : g.GEN.x - 20 * g.k - g.TEXT.x;+ ctx.font = FT(g)(500, g.wrapAs ? g.wrapAs.px : g.TEXT.px);const out: string[] = []; let line = "";for (const tok of typed.split(/(?<= )/)) {if (ctx.measureText(line + tok).width <= maxW || !line) line += tok; else { out.push(line); line = tok; }@@ -173,18 +202,30 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState, g: ChatGeom = CHAT_GEOM) =const { CHAT, INPUT, GEN, REPLY, TEXT, k, px } = g, P = pal(g);ctx.fillStyle = P.bg; ctx.fillRect(-2000, -2000, 6000, 6000);softShadow(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, CHAT.r, 1.2);- ctx.fillStyle = P.card; rr(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, CHAT.r); ctx.fill();- // the thread's head: a small ink dot and a name, nothing that belongs to anyone else+ const LO = g.look, F = FT(g), winR = LO?.shape.radius !== undefined ? LO.shape.radius * k : CHAT.r;+ ctx.fillStyle = P.card; rr(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, winR); ctx.fill();+ // the thread's head: a small ink dot and a name, nothing that belongs to anyone else (a custom look: the+ // product's own logo in the dot's place, or no header at all)+ if (LO?.chat.header !== false) {if (s.head !== undefined) ctx.globalAlpha = s.head;- ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(CHAT.x + 58 * k, CHAT.y + 52 * k, 9 * k, 0, Math.PI * 2); ctx.fill();- ctx.font = SANS(600, px.head); ctx.fillStyle = P.ink; ctx.textBaseline = "middle"; ctx.fillText(s.title ?? "anidoodle", CHAT.x + 80 * k, CHAT.y + 53 * k);- const subX = s.title === undefined ? CHAT.x + 196 * k : CHAT.x + 80 * k + ctx.measureText(s.title).width + 16 * k;- ctx.font = SANS(500, px.sub); ctx.fillStyle = P.mute; ctx.fillText(s.subtitle ?? "drawn in code", subX, CHAT.y + 54 * k);+ // (the clean look's ink is never see-through, layerscan translucent: its dot is cut in or out whole, at half)+ { const a = ctx.globalAlpha; if (g.iris) ctx.globalAlpha = a >= 0.5 ? 1 : 0;+ const logo = LO?.chat.logo;+ if (logo) { const sc = (26 * k) / Math.max(logo.w, logo.h); ctx.save(); ctx.translate(CHAT.x + 58 * k - (logo.w * sc) / 2, CHAT.y + 52 * k - (logo.h * sc) / 2); ctx.scale(sc, sc); drawEl(ctx, logo, { name: "logo" }); ctx.restore(); }+ else { ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(CHAT.x + 58 * k, CHAT.y + 52 * k, 9 * k, 0, Math.PI * 2); ctx.fill(); }+ ctx.globalAlpha = a; }+ const title = LO?.chat.title ?? s.title, sub = LO?.chat.subtitle ?? s.subtitle;+ // (with a logo the words stand 34 px or more clear of it: framecheck's gap between a brand element and text)+ const tx = LO?.chat.logo ? CHAT.x + 71 * k + Math.max(34, 36 * k) : CHAT.x + 80 * k;+ ctx.font = F(600, px.head); ctx.fillStyle = P.ink; ctx.textBaseline = "middle"; ctx.fillText(title ?? "anidoodle", tx, CHAT.y + 53 * k);+ const subX = title === undefined ? tx + 116 * k : tx + ctx.measureText(title).width + 16 * k;+ ctx.font = F(500, px.sub); ctx.fillStyle = P.mute; ctx.fillText(sub ?? "drawn in code", subX, CHAT.y + 54 * k);ctx.fillStyle = P.line; ctx.fillRect(CHAT.x + 32 * k, CHAT.y + 98 * k, CHAT.w - 64 * k, 1.5 * k);if (s.head !== undefined) ctx.globalAlpha = 1;+ }// the sent message, right alignedif (s.sent) {- ctx.globalAlpha = s.sentAlpha ?? 1; ctx.font = SANS(500, px.bubble);+ ctx.globalAlpha = s.sentAlpha ?? 1; ctx.font = F(500, px.bubble);const tw = ctx.measureText(s.sent).width, pad = 26 * k, bw = tw + pad * 2, bx = CHAT.x + CHAT.w - 60 * k - bw, by = CHAT.y + 124 * k;let ay = by;if (s.attach) { const iw = 240 * k, ih = 150 * k; ay = by; ctx.save(); rr(ctx, CHAT.x + CHAT.w - 60 * k - iw, ay, iw, ih, 16 * k); ctx.clip(); ctx.drawImage(s.attach.img, CHAT.x + CHAT.w - 60 * k - iw, ay, iw, ih); ctx.restore(); ay += ih + 10 * k; }@@ -192,17 +233,19 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState, g: ChatGeom = CHAT_GEOM) =ctx.fillStyle = P.ink; ctx.textBaseline = "middle"; ctx.fillText(s.sent, bx + pad, ay + 29 * k);ctx.globalAlpha = 1;}- if (s.label) { ctx.globalAlpha = s.labelAlpha ?? 1; ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(REPLY.x + 9 * k, REPLY.y - 26 * k, 7 * k, 0, Math.PI * 2); ctx.fill(); ctx.font = SANS(600, px.label); ctx.textBaseline = "middle"; ctx.fillText(s.label, REPLY.x + 26 * k, REPLY.y - 25 * k); ctx.globalAlpha = 1; }+ if (s.label) { ctx.globalAlpha = s.labelAlpha ?? 1; ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(REPLY.x + 9 * k, REPLY.y - 26 * k, 7 * k, 0, Math.PI * 2); ctx.fill(); ctx.font = F(600, px.label); ctx.textBaseline = "middle"; ctx.fillText(s.label, REPLY.x + 26 * k, REPLY.y - 25 * k); ctx.globalAlpha = 1; }// the composer{ const g2 = s.composerGeom ?? g, { INPUT, GEN, TEXT, k, px } = g2;if (s.composer !== undefined) ctx.globalAlpha = s.composer;- ctx.fillStyle = P.paper; rr(ctx, INPUT.x, INPUT.y, INPUT.w, INPUT.h, INPUT.r); ctx.fill();+ // (a bar: round ends at one line's height; a composer grown to three lines keeps those ends, never an oval)+ const inR = LO ? (LO.shape.composer === "bar" ? Math.min(INPUT.h / 2, 52 * k) : LO.shape.radius !== undefined ? LO.shape.radius * k : INPUT.r) : INPUT.r;+ ctx.fillStyle = P.paper; rr(ctx, INPUT.x, INPUT.y, INPUT.w, INPUT.h, inR); ctx.fill();ctx.lineWidth = 2 * k; ctx.strokeStyle = P.line; ctx.stroke();- ctx.font = SANS(500, TEXT.px); ctx.textBaseline = "alphabetic";+ ctx.font = F(500, TEXT.px); ctx.textBaseline = "alphabetic";if (!s.typed && s.placeholder) { ctx.fillStyle = P.mute; ctx.fillText(s.placeholder, TEXT.x, TEXT.base); }const acc = s.accent ?? P.accent;if (g2.wrap > 0) {- const lines = composerLines(ctx, s.typed, g2); ctx.font = SANS(500, TEXT.px); ctx.fillStyle = P.ink;+ const lines = composerLines(ctx, s.typed, g2, s.full); ctx.font = F(500, TEXT.px); ctx.fillStyle = P.ink;lines.forEach((l, i) => ctx.fillText(l, TEXT.x, TEXT.base + i * g2.lineH));if (s.caret) { const i = lines.length - 1, x = TEXT.x + ctx.measureText(lines[i]).width + 3 * k; ctx.fillStyle = acc; ctx.fillRect(x, TEXT.base + i * g2.lineH - 0.94 * TEXT.px, 3 * k, 1.18 * TEXT.px); }} else {@@ -211,14 +254,16 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState, g: ChatGeom = CHAT_GEOM) =}// Generateconst pr = s.genPress ?? 0, hot = s.genHot ?? 0, q = 1 - 0.07 * pr, gx = GEN.x + (GEN.w * (1 - q)) / 2, gy = GEN.y + (GEN.h * (1 - q)) / 2;- ctx.fillStyle = hot > 0 ? mixHex(acc, s.accent ? deepen(acc) : P.accentDeep, 0.35 * hot + 0.4 * pr) : acc; rr(ctx, gx, gy, GEN.w * q, GEN.h * q, GEN.r * q); ctx.fill();- ctx.fillStyle = "#fff"; ctx.font = SANS(600, px.gen * q); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText(s.genLabel ?? "Generate", GEN.x + GEN.w / 2, GEN.y + GEN.h / 2 + 1 * k); ctx.textAlign = "left";+ { const a = ctx.globalAlpha; if (g.iris) ctx.globalAlpha = a >= 0.5 ? 1 : 0; // (the clean look's accent button, cut whole, as its dot)+ const genR = LO?.shape.button === "square" ? Math.min(GEN.r, 8 * k) : GEN.r;+ ctx.fillStyle = hot > 0 ? mixHex(acc, s.accent ? deepen(acc) : P.accentDeep, 0.35 * hot + 0.4 * pr) : acc; rr(ctx, gx, gy, GEN.w * q, GEN.h * q, genR * q); ctx.fill(); ctx.globalAlpha = a; }+ ctx.fillStyle = LO?.onAccent ?? "#fff"; ctx.font = F(600, px.gen * q); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText(s.genLabel ?? "Generate", GEN.x + GEN.w / 2, GEN.y + GEN.h / 2 + 1 * k); ctx.textAlign = "left";if (s.composer !== undefined) ctx.globalAlpha = 1; }};// where the caret is: the end of the typed words (on their last line in a wrapping composer)-export const caretAt = (ctx: Ctx, typed: string, g: ChatGeom = CHAT_GEOM): P => {- if (g.wrap > 0) { const lines = composerLines(ctx, typed, g), i = lines.length - 1; ctx.font = SANS(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(lines[i]).width, g.TEXT.base + i * g.lineH - 0.35 * g.TEXT.px]; }- ctx.font = SANS(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(typed).width, g.TEXT.base - 12];+export const caretAt = (ctx: Ctx, typed: string, g: ChatGeom = CHAT_GEOM, full?: string): P => {+ if (g.wrap > 0) { const lines = composerLines(ctx, typed, g, full), i = lines.length - 1; ctx.font = FT(g)(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(lines[i]).width, g.TEXT.base + i * g.lineH - 0.35 * g.TEXT.px]; }+ ctx.font = FT(g)(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(typed).width, g.TEXT.base - 12];};const hx = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));@@ -240,12 +285,21 @@ export const charTimes = (text: string, t0: number, rate: number, seed: number)export const typedAt = (text: string, f: number, times: number[]) => text.slice(0, times.filter((t) => f >= t).length);// The drop: a bead of ink lifts off Generate and arcs to where the answer card will land.export type Drop = { t0: number; land: number; full: number };+// the drop's progress along its path: the drawn look's in-out; the clean look's keeps 60 % of a steady pace, so+// it lands still moving, a hit the iris takes over (an in-out's slow last third crawled for half a second on a+// lively brand's longer flight: dead air to the gate)+const dropEase = (u: number, g: ChatGeom) => (g.iris ? 0.4 * inOut(u) + 0.6 * u : inOut(u));+// (and it flies straight: the 150 px arc, falling again as the drop rose to a card above the button, cancelled+// its climb near the end on a phone frame, where the path is mostly upward, and the drop hung there)+const dropArc = (g: ChatGeom) => (g.iris ? 0 : 150);export const inkDrop = (ctx: Ctx, f: number, d: { t0: number; land: number }, to: P, g: ChatGeom = CHAT_GEOM) => {const { GEN, k } = g, ink = g.drop ?? pal(g).ink, GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];if (f < d.t0 - 6 || f >= d.land) return;if (f < d.t0) { const w = out3(ramp(f, d.t0 - 6, d.t0)); ctx.fillStyle = ink; ctx.beginPath(); ctx.arc(GEN_C[0], GEN.y + 6 * k - w * 22 * k, 30 * k * (0.3 + 0.7 * w), 0, Math.PI * 2); ctx.fill(); return; }- const at = (t: number): P => { const u = ramp(t, d.t0, d.land), e = inOut(u); return [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * 150 * k]; };- for (let j = 24; j >= 0; j--) { const p = at(f - j * 0.1); ctx.fillStyle = ink; ctx.globalAlpha = j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(p[0], p[1], 30 * k * (1 - j * 0.022), 0, Math.PI * 2); ctx.fill(); }+ const at = (t: number): P => { const u = ramp(t, d.t0, d.land), e = dropEase(u, g); return [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * dropArc(g) * k]; };+ // the drawn look trails ghosts of ink; the clean look's drop (its one accent, never see-through) stretches+ // into one solid, tapering streak along its path instead, as the motif's drop does+ for (let j = 24; j >= 0; j--) { const p = at(f - j * 0.1); ctx.fillStyle = ink; ctx.globalAlpha = g.iris || j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(p[0], p[1], 30 * k * (g.iris ? 1 - j * 0.034 : 1 - j * 0.022), 0, Math.PI * 2); ctx.fill(); }ctx.globalAlpha = 1;};// where the drop is at frame f (null when it is not in flight): the motif's position for a match cut@@ -253,23 +307,44 @@ export const inkDropAt = (f: number, d: { t0: number; land: number }, to: P, g:const { GEN, k } = g, GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];if (f < d.t0 - 6 || f >= d.land) return null;if (f < d.t0) { const w = out3(ramp(f, d.t0 - 6, d.t0)); return { p: [GEN_C[0], GEN.y + 6 * k - w * 22 * k], r: 30 * k * (0.3 + 0.7 * w) }; }- const u = ramp(f, d.t0, d.land), e = inOut(u);- return { p: [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * 150 * k], r: 30 * k };+ const u = ramp(f, d.t0, d.land), e = dropEase(u, g);+ return { p: [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * dropArc(g) * k], r: 30 * k };};// The answer card in the thread: a byline, then the art, revealed by the landed drop blooming open.// `art` is any layer (plateLayer gives a live plate); `crop` picks a source rectangle.// `grow` (default an out-cubic from land to full) is how open the card is at frame f: the template// passes a spring, so the card lands on the spring's first arrival and its sound cue can sit there-export const inkCard = (ctx: Ctx, x: number, y: number, s: number, f: number, d: Drop, art: Layer, label: string, crop?: [number, number, number, number], g: ChatGeom = CHAT_GEOM, growAt?: (f: number) => number) => {+/** Set by a surface that faded or withheld the last fillText to the share of it drawn, 0..1 (launchTemplate's placed(), fading a line before a zone), so a mark that belongs to the line fades and leaves with it. */+export const TEXT_SHOWN = Symbol.for("anidoodle.textShown");+export const inkCard = (ctx: Ctx, x: number, y: number, s: number, f: number, d: Drop, art: Layer, label: string, crop?: [number, number, number, number], g: ChatGeom = CHAT_GEOM, growAt?: (f: number) => number, labelA = 1) => {const k = g.k, P = pal(g), A = ctx.globalAlpha; // a card drawn under a focus pull keeps the caller's opacity- ctx.fillStyle = P.ink; ctx.globalAlpha = A * ramp(f, d.land, d.land + 10); ctx.beginPath(); ctx.arc(x + 9 * k, y - 16 * k, 7 * k, 0, Math.PI * 2); ctx.fill();- ctx.font = SANS(600, g.px.label); ctx.textBaseline = "middle"; ctx.fillText(label, x + 26 * k, y - 15 * k); ctx.globalAlpha = A;+ // the byline: a dot and its words, drawn together or not at all (a dot left alone reads as a stray mark)+ const LA = A * ramp(f, d.land, d.land + 10) * Math.max(0, Math.min(1, labelA));+ if (label && LA > 0.001) {+ // the words first: a surface that fades or withholds a line (a travel's zone fade) says how much of it+ // it drew through TEXT_SHOWN, and the dot is drawn at that much too, fading and leaving with its words+ ctx.fillStyle = g.look?.chat.reply?.ink ?? P.ink; ctx.globalAlpha = LA; ctx.font = FT(g)(600, g.px.label); ctx.textBaseline = "middle";+ const c = ctx as Ctx & { [TEXT_SHOWN]?: number }; c[TEXT_SHOWN] = 1; ctx.fillText(label, x + 26 * k, y - 15 * k);+ const shown = Math.max(0, Math.min(1, Number(c[TEXT_SHOWN] ?? 1)));+ // (the clean look's dot is its ink, never see-through: it grows in and shrinks out with its words instead)+ if (shown > 0) { ctx.globalAlpha = g.iris ? 1 : LA * shown; ctx.beginPath(); ctx.arc(x + 9 * k, y - 16 * k, 7 * k * (g.iris ? LA * shown : 1), 0, Math.PI * 2); ctx.fill(); }+ }+ ctx.globalAlpha = A;const grow = growAt ? growAt(f) : out3(ramp(f, d.land, d.full)), c: P = [x + s / 2, y + s / 2];softShadow(ctx, x, y, s, s, 20 * k, Math.min(1, grow) * 1.3);ctx.save(); rr(ctx, x, y, s, s, 20 * k); ctx.clip();if (grow < 1 && g.iris) { ctx.beginPath(); ctx.arc(c[0], c[1], Math.max(0, lerp(18 * k, s * 0.72, grow)), 0, Math.PI * 2); ctx.clip(); }else if (grow < 1) { pathOf(ctx, blot(c, lerp(16 * k, s * 0.8, grow) + 28 * k * (1 - grow), 77)); ctx.fillStyle = g.drop ?? P.ink; ctx.fill(); pathOf(ctx, blot(c, Math.max(0, lerp(16 * k, s * 0.8, grow) - 5 * k), 77)); ctx.clip(); }- ctx.fillStyle = P.paper; ctx.fillRect(x, y, s, s);+ ctx.fillStyle = g.look?.chat.reply?.fill ?? P.paper; ctx.fillRect(x, y, s, s);if (crop) ctx.drawImage(art.canvas, ...crop, x, y, s, s); else ctx.drawImage(art.canvas, x, y, s, s);ctx.restore();+ // the clean iris's edge while it opens: a solid ring in the drop's colour, so the landed drop visibly opens+ // into it (a pale disc on a cream card read as the answer fading in, a fresh critic's cc1-3)+ // (only while the whole ring is inside the card: wider, it showed as four arcs in the corners, cc3-2)+ const rimR = Math.max(0, lerp(18 * k, s * 0.72, grow));+ if (grow < 1 && g.iris && rimR < s / 2 - 2 * k) {+ ctx.save(); rr(ctx, x, y, s, s, 20 * k); ctx.clip();+ ctx.beginPath(); ctx.arc(c[0], c[1], rimR, 0, Math.PI * 2);+ ctx.strokeStyle = g.drop ?? P.accent; ctx.lineWidth = 4 * k; ctx.stroke(); ctx.restore();+ }};diff --git a/skills/anidoodle/engine/src/canvas-core/launchLayout.ts b/skills/anidoodle/engine/src/canvas-core/launchLayout.tsindex d7b1f48..2f88a41 100644--- a/skills/anidoodle/engine/src/canvas-core/launchLayout.ts+++ b/skills/anidoodle/engine/src/canvas-core/launchLayout.ts@@ -44,6 +44,8 @@ const ZONE_GAP = 8;// phone-safe minimums, px at the delivered size: `read` = a line the viewer must read (a prompt, a// label, the words, the install lines); `chrome` = the UI around them (a header, a button's word)+// the footer is where the film says the product lives: it is on screen in the last second, so it meets+// framecheck's last-second floor (28 px at 1080, tools/framerules.mjs RULES.endPx), not the chrome floorexport const MIN_PX = { phone: { read: 32, chrome: 24, type: 64 }, desk: { read: 18, chrome: 16, type: 80 } };// A build-time estimate of a sans line's width, deliberately a little wide: layout decisions (how@@ -104,7 +106,7 @@ export type LaunchLayout = {safe: Rect; zones: boolean;roles: Role[];};-export type LayoutContent = { prompts: string[]; install: string[]; tagline: string; title?: string; band?: boolean };+export type LayoutContent = { prompts: string[]; install: string[]; tagline: string; title?: string; band?: boolean; wrap?: (text: string, px: number, maxW: number) => string[] }; // wrap: the look's text face (default the stock estimate)// the desktop composition: the exact numbers of the 1920x1080 filmconst desk = (c: LayoutContent): LaunchLayout => {@@ -113,9 +115,10 @@ const desk = (c: LayoutContent): LaunchLayout => {shape: "16x9", W, H, k: 1, phone: false, chat: g,thread: { top: 170, viewBottom: VIEW_BOTTOM, clip: [300, 158, 1320, VIEW_BOTTOM - 158], bubbleH: 58, bubbleLineH: 34, bubblePad: 26, bubbleR: 1560, bubbleMaxW: 1080, bubbleRad: 22, gap: 26, card: 460, cardX: g.REPLY.x, cardDy: 34, bubbles: c.prompts.map((p) => [p]) },cam: { home: { c: [960, 540], z: 1 }, macroZ: 2.4, macroCreep: 0.25, macroX0: 330, macroY: 934, follow: true, leanZ: 1.18, pointerOff: [1780, 1140], pointerS: 1.35, pointerOn: [g.GEN.x + g.GEN.w / 2 + 18, g.GEN.y + g.GEN.h / 2 + 6] },- bug: { x: W - 40, y: H - 34, px: 24 },+ // the corner mark sits in the gutter right of the window, clear of its corner (24 px at the old 24 px size touched it)+ bug: { x: W - 36, y: H - 30, px: 22 },type: { maxW: 1560, cap1: 190, capN: 130, minPx: MIN_PX.desk.type, cover: 1110 },- end: { cx: W / 2, titleY: 400, titleMax: 150, titleW: 1300, tagline: [c.tagline], taglineY: 520, taglinePx: 30, taglineLH: 40, panelY: py, monoPx: 30, rows: c.install.map((text) => ({ text, indent: 0 })), wrapped: false, rowH: 60, padX: 60, lineY0: py + 55, footerPx: 24, footerY: py + ph + 60, caret: [16, 34] },+ end: { cx: W / 2, titleY: 400, titleMax: 150, titleW: 1300, tagline: [c.tagline], taglineY: 520, taglinePx: 30, taglineLH: 40, panelY: py, monoPx: 30, rows: c.install.map((text) => ({ text, indent: 0 })), wrapped: false, rowH: 60, padX: 60, lineY0: py + 55, footerPx: 28, footerY: py + ph + 60, caret: [16, 34] },// a two-column grid on the frame's centre line: words 40 %, a 100 px gutter, the live UI 46 %, equal marginssplit: { words: { x: 150, y: 150, w: 720, h: 780 }, ui: { x: 970, y: 120, w: 800, h: 840 }, vertical: false, wordsPx: 96 },stage: { x: 0, y: 0, w: W, h: H }, band: null,@@ -135,27 +138,31 @@ const phone = (shape: Exclude<Shape, "16x9">, c: LayoutContent, H0: number, S: Rconst E = zones ? { x0: 0, y0: S.y - (m - ZONE_GAP), x1: S.x + S.w + (m - ZONE_GAP), y1: Math.min(S.y + S.h, H) } : { x0: 0, y0: 0, x1: W, y1: H };const Ew = E.x1 - E.x0, Eh = E.y1 - E.y0;const px = { head: Math.max(22 * k, min.chrome), sub: Math.max(18 * k, min.chrome), bubble: Math.max(26 * k, min.read), label: Math.max(20 * k, min.read), gen: Math.max(24 * k, min.chrome) };- // the window stops above the corner mark's own strip: the mark never sits on the UI- const bugPx = Math.max(24 * k, min.chrome), bugStrip = Math.round(bugPx + 34);+ // the window stops above the corner mark's own strip: the mark never sits on the UI, and its letters stay+ // clear of the window's corner while the hook's camera creeps 2 % about the window's centre+ const bugPx = Math.max(24 * k, min.chrome), bugStrip = Math.round(bugPx + 56), bugY = zones ? E.y1 - 0.3 * bugPx - 2 : E.y1 - 20;const promptPx = Math.max(34 * k, min.read), chatR = { x: E.x0 + m, y: E.y0 + m, w: Ew - 2 * m, h: Eh - m - bugStrip, r: 34 * k };// the composer holds the longest prompt; the button sits on its last lineconst base = chatGeom(chatR, k, px, promptPx, 1), textW = base.GEN.x - 20 * k - base.TEXT.x;- const lines = Math.min(3, Math.max(1, ...c.prompts.map((p) => wrapEst(p, promptPx, textW).length)));+ const lines = Math.min(3, Math.max(1, ...c.prompts.map((p) => (c.wrap ?? wrapEst)(p, promptPx, textW).length)));const g = chatGeom(chatR, k, px, promptPx, lines);const top = g.CHAT.y + 114 * k, viewBottom = g.INPUT.y - 26 * k, bubbleMaxW = g.INPUT.w * 0.86, bubbleLineH = Math.round(px.bubble * 1.3);- const bubbles = c.prompts.map((p) => wrapEst(p, px.bubble, bubbleMaxW - 52 * k));+ const bubbles = c.prompts.map((p) => (c.wrap ?? wrapEst)(p, px.bubble, bubbleMaxW - 52 * k));// the answer card: as wide as the thread allows, and short enough that a card and the prompt above it both fit the viewconst card = Math.round(Math.min(g.INPUT.w, viewBottom - top - 58 * k - 2 * bubbleLineH - 60 * k));const cardX = g.CHAT.x + (g.CHAT.w - card) / 2;- // the end card, stacked and centred in E- const inst = installRows(c.install, Ew - 2 * 32 - 2 * 36, min.read, 30 * k), mono = inst.px;- const taglinePx = Math.max(30 * k, min.read), tagline = wrapEst(c.tagline, taglinePx, Ew - 2 * m - 60), tLH = Math.round(taglinePx * 1.3);+ // the end card, stacked and centred. On 9x16 it centres on the frame itself, the column a viewer sees+ // (centred on the safe rectangle it sat 60 px left of the middle, and read off-centre outside a feed), and+ // stays as narrow as the room between the middle and the right-hand zone allows+ const endCol = zones ? { cx: W / 2, w: 2 * (S.x + S.w + (m - ZONE_GAP) - W / 2) } : { cx: E.x0 + Ew / 2, w: Ew };+ const inst = installRows(c.install, endCol.w - 2 * 32 - 2 * 36, min.read, 30 * k), mono = inst.px;+ const taglinePx = Math.max(30 * k, min.read), tagline = (c.wrap ?? wrapEst)(c.tagline, taglinePx, endCol.w - 2 * m - 60), tLH = Math.round(taglinePx * 1.3);const titleMax = 150 * k, rowH = Math.round(mono * 2), ph = rowH * inst.rows.length + 50 * k;const block = titleMax + 60 + tagline.length * tLH + 60 + ph + 80, y0 = E.y0 + (Eh - block) / 2 - 20;const titleY = y0 + titleMax * 0.62, taglineY = y0 + titleMax + 60 + tLH / 2, panelY = taglineY + (tagline.length - 0.5) * tLH + 50;// the split beat, stacked: the words on top, the live UI under them. On 9x16 both sit in the window's// rectangle, and the UI is inset so its push (12 % at most) never carries its text past that rectangle.- const PUSH = 1.12, R = { x: chatR.x, y: chatR.y, w: chatR.w, h: chatR.h };+ const PUSH = 1.12, R = { x: chatR.x, y: chatR.y, w: chatR.w, h: chatR.h + 22 }; // (+22: a product's panel keeps the room the corner mark's wider strip took from the chat window; it never creeps as the hook does)const wordsH = Math.round(R.h * 0.32), uiTop = R.y + wordsH + 30, uiW = Math.floor(R.w / PUSH), uiH = Math.floor((R.y + R.h - uiTop) / PUSH);const split = zones? { words: { x: R.x + 20, y: R.y + 10, w: R.w - 40, h: wordsH }, ui: { x: Math.round(R.x + (R.w - uiW) / 2), y: Math.round(uiTop + (R.y + R.h - uiTop - uiH) / 2), w: uiW, h: uiH }, vertical: true, wordsPx: 96 }@@ -171,9 +178,9 @@ const phone = (shape: Exclude<Shape, "16x9">, c: LayoutContent, H0: number, S: Rthread: { top, viewBottom, clip: [g.CHAT.x, g.CHAT.y + 102 * k, g.CHAT.w, viewBottom - (g.CHAT.y + 102 * k)], bubbleH: 58 * k + (px.bubble - 26 * k) * 1.2, bubbleLineH, bubblePad: 26 * k, bubbleR: g.INPUT.x + g.INPUT.w, bubbleMaxW, bubbleRad: 22 * k, gap: 26 * k, card, cardX, cardDy: 34 * k + (px.label - 20 * k), bubbles },// on 9x16 the lean on a new card goes further: the card is smaller there, and the rest of the window fades as it leaves the safe areacam: { home: { c: [W / 2, H / 2], z: 1 }, macroZ, macroCreep: macroZ * 0.08, macroX0: W / 2 / macroZ - 60 * k, macroY: g.INPUT.y + g.INPUT.h / 2, follow: true, leanZ: zones ? 1.5 : 1.1, pointerOff: [W - 110, H + 70], pointerS: 1.35 * k, pointerOn: [g.GEN.x + g.GEN.w / 2 + 18 * k, g.GEN.y + g.GEN.h / 2 + 6 * k] },- bug: { x: E.x1 - m - 10, y: E.y1 - bugStrip / 2 + bugPx * 0.1, px: bugPx },+ bug: { x: chatR.x + chatR.w - 20, y: bugY, px: bugPx }, // under the window's right edge, 20 px in: aligned to the content, with room before the right-hand zonetype: { maxW: Ew - 2 * 90, cap1: 190, capN: 150, minPx: min.type, cover: zones ? Math.ceil(Math.max(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot(x - typeAt[0], y - typeAt[1])))) + 9 : Math.ceil(Math.hypot(W, H) / 2) + 9, ...(zones ? { at: typeAt } : {}) }, // cover: the bloom's reach to the farthest corner from where it opens- end: { cx: E.x0 + Ew / 2, titleY, titleMax, titleW: Ew - 2 * m - 80, tagline, taglineY, taglinePx, taglineLH: tLH, panelY, monoPx: mono, rows: inst.rows, wrapped: inst.wrapped, rowH, padX: 36, lineY0: panelY + 25 * k + rowH / 2, footerPx: Math.max(24 * k, min.read), footerY: panelY + ph + 60, caret: [Math.round(mono * 0.53), Math.round(mono * 1.13)] },+ end: { cx: endCol.cx, titleY, titleMax, titleW: endCol.w - 2 * m - 80, tagline, taglineY, taglinePx, taglineLH: tLH, panelY, monoPx: mono, rows: inst.rows, wrapped: inst.wrapped, rowH, padX: 36, lineY0: panelY + 25 * k + rowH / 2, footerPx: Math.max(28 * k, min.read), footerY: panelY + ph + 60, caret: [Math.round(mono * 0.53), Math.round(mono * 1.13)] },split, stage: { x: 0, y: 0, w: W, h: H }, band: null, uiFull, safe: S, zones,roles: [],};diff --git a/skills/anidoodle/engine/src/canvas-core/launchLook.ts b/skills/anidoodle/engine/src/canvas-core/launchLook.tsnew file mode 100644index 0000000..1a6cea2--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/launchLook.ts@@ -0,0 +1,211 @@+// THE LOOK. A launch film has to look like the product it launches, not like us. The template draws every+// colour, typeface and shape through one resolved look, built here from the spec's `look` block:+//+// look.base "drawn" | "clean" | any look registered with registerLook(): the starting point (ink and+// blooms with hand lettering, or a quiet canvas with set type), never the only option.+// `preset` is the old shorthand for look.base and keeps working.+// look.from a brand file from `tools/brand.mjs import` (import brand from "<dir>/brand.json"): its+// colours fill the palette and its logo the chat header. Explicit fields always win.+// look.palette any of bg, card, ink, soft, mute, line, chip, accent, accentDeep, paper, over the base.+// look.fonts { display, text, mono }: each a family name and a local font file, imported by path+// (import serif from "../../assets/fonts/MySerif-Bold.ttf"). The file travels inside the+// film (no network), is registered as a FontFace before the first frame, and every measure,+// wrap and reading time is taken from its own glyph advances, never from another face.+// look.shape corner radius, the user bubble (rounded, square, none), the composer (box or bar), the+// button's shape and label.+// look.chat the chat window as the product draws its own: header on or off, title and subtitle, a+// logo (a brand element) in place of the dot, the user bubble's and the answer's colours.+// A product with no chat: use `kind: "ui"` asks, its own screen with its command bar.+//+// A custom colour can never make an unreadable film: resolveLook checks every pair the film sets text in+// (WCAG AA: 4.5:1 for body text, 3:1 for large type and the hint text) wherever a pair has a colour the look+// changed, and throws naming the token and the pair.+import { C, SANS, MONO } from "./launchKit";+import { estWidth, monoWidth } from "./launchLayout";+import { parseTTF, type Font } from "../three-core/ttf";+import type { BrandElement } from "./brandKit";++/** A font file as the build carries it: imported by path, its bytes inside the film (tools/overlay.mjs). */+export type FontFile = { path: string; format: "ttf" | "otf" | "woff2"; data: string };+export type LookFont = { family: string; file: FontFile };+export type PaletteKey = "bg" | "card" | "ink" | "soft" | "mute" | "line" | "chip" | "accent" | "accentDeep" | "paper";+export type Palette = Record<PaletteKey, string> & { shadow: string };+export type LookShape = {+ radius?: number; // corner radius of the window, the composer and the cards, in layout px (default: the base's)+ bubble?: "rounded" | "square" | "none"; // the user's sent message: a rounded chip, a square one, or plain words+ composer?: "box" | "bar"; // the input: a box with the button inside, or one rounded bar+ button?: "pill" | "square"; // the send button's shape+ buttonLabel?: string; // its word ("Generate", "Ask", "Send")+};+export type LookChat = {+ header?: boolean; // the window's header (dot or logo, title, subtitle, rule); false hides it+ title?: string; subtitle?: string; // the header's words (default: the film's title and subtitle)+ logo?: BrandElement; // the product's mark, drawn in place of the dot (a brand.mjs import element)+ bubble?: { fill: string; ink: string }; // the user's sent message+ reply?: { fill: string; ink: string }; // the answer: its card's frame and its byline+};+/** What `tools/brand.mjs import` writes as brand.json (only what a look reads). */+export type BrandFile = { elements: Record<string, { w: number; h: number; parts: readonly unknown[] }>; palette: { hex: string; share: number }[]; fonts?: string[] }; // (as a JSON import types it: parts are brandKit's BrandPart)+export type LaunchLook = {+ base?: string;+ from?: BrandFile;+ palette?: Partial<Record<PaletteKey, string>>;+ fonts?: { display?: LookFont; text?: LookFont; mono?: LookFont };+ shape?: LookShape;+ chat?: LookChat;+};+export type FontFn = (weight: number, px: number) => string;+export type ResolvedLook = {+ base: string;+ clean: boolean; // the base's grammar: set type, travels and an iris (clean), or ink (drawn)+ palette: Palette;+ onAccent: string; // the label colour on the accent (white unless the accent is pale)+ custom: boolean; // anything beyond the base and the legacy accent+ fonts: { display: FontFn; text: FontFn; mono: (px: number) => string };+ /** widths at px, from the chosen face: custom fonts by their own advances, the stock ones by the template's estimates */+ measure: { text: (t: string, px: number) => number; display: (t: string, px: number) => number; mono: (t: string, px: number) => number };+ wrap: (text: string, px: number, maxW: number) => string[];+ wrapDisplay: (text: string, px: number, maxW: number) => string[]; // the same, by the display face (set words)+ customDisplay: boolean; // the display face is a font file (measured from it), not the stock set sans+ /** the width of text set in a CSS font string the look made: a custom face by its own advances, else the stock estimate */+ measureFont: (t: string, font: string) => number;+ shape: Required<Omit<LookShape, "radius" | "buttonLabel">> & { radius?: number; buttonLabel?: string };+ chat: LookChat;+ faces: { family: string; file: FontFile }[]; // the font files to register before the first frame+ /** the pointer's colours: the stock black arrow with a white edge, a light arrow with a dark edge on a dark ground */+ pointer: { fill: string; edge: string };+};++// the clean base: a quiet canvas, one accent, type as the design. Our own palette, drawn for it.+export const CLEAN: Palette = { bg: "#f3f2ef", card: "#ffffff", ink: "#15161a", soft: "#5b5f68", mute: "#9da1a9", line: "#e4e4e1", chip: "#efefec", accent: "#2f54eb", accentDeep: "#2442bf", paper: "#fbfbf9", shadow: "rgba(20,24,30,0.08)" };+type LookDef = { clean: boolean; palette: Palette };+const LOOKS = new Map<string, LookDef>([["drawn", { clean: false, palette: C as Palette }], ["clean", { clean: true, palette: CLEAN }]]);+/** A new starting point: a name, the grammar it draws with (clean or drawn), and its palette. */+export const registerLook = (name: string, def: { clean: boolean; palette: Palette }) => { LOOKS.set(name, def); };+export const lookNames = () => [...LOOKS.keys()];++// ---------------------------------------------------------------- colour and contrast (WCAG 2)+const rgb = (hex: string): [number, number, number] => {+ const m = /^#([0-9a-f]{6})$/i.exec(hex.trim()); if (!m) throw new Error(`look: colour '${hex}' is not #rrggbb`);+ const v = parseInt(m[1], 16); return [(v >> 16) & 255, (v >> 8) & 255, v & 255];+};+const lum = (hex: string) => { const [r, g, b] = rgb(hex).map((c) => { const s = c / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }); return 0.2126 * r + 0.7152 * g + 0.0722 * b; };+/** The contrast ratio of two colours, 1 to 21. */+export const contrast = (a: string, b: string) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };+const sat = (hex: string) => { const [r, g, b] = rgb(hex), mx = Math.max(r, g, b), mn = Math.min(r, g, b); return mx === 0 ? 0 : (mx - mn) / mx; };+/** Every pair the template sets text in: [text token, ground token, the bar, what it is]. */+export const TEXT_PAIRS: [PaletteKey, PaletteKey, number, string][] = [+ ["ink", "card", 4.5, "the chat's words and the product's rows"],+ ["ink", "bg", 4.5, "the word pages and the end card"],+ ["ink", "paper", 4.5, "the typed prompt"],+ ["ink", "chip", 4.5, "the sent message"],+ ["soft", "bg", 4.5, "the tagline and the footer"],+ ["soft", "card", 4.5, "the product's secondary words"],+ ["mute", "paper", 3, "the composer's placeholder (hint text, large-type bar)"],+ ["mute", "card", 3, "the header's subtitle (hint text, large-type bar)"],+ ["accent", "bg", 3, "accent words on the page (large type)"],+];+/** Throws naming the token when a pair the look changed falls under its bar. `changed`: the tokens the look set. */+export const checkContrast = (p: Palette, changed: Set<string>, extra: [string, string, number, string][] = []) => {+ const bad: string[] = [];+ for (const [t, g, bar, what] of TEXT_PAIRS) {+ if (!changed.has(t) && !changed.has(g)) continue;+ const fg = p[t], r = contrast(fg, p[g]);+ if (r < bar) bad.push(`'${t}' ${fg} on '${g}' ${p[g]} is ${r.toFixed(2)}:1, under ${bar}:1 (${what})`);+ }+ for (const [fg, bg, bar, what] of extra) { const r = contrast(fg, bg); if (r < bar) bad.push(`${what}: ${fg} on ${bg} is ${r.toFixed(2)}:1, under ${bar}:1`); }+ if (bad.length) throw new Error(`look: unreadable colours. ${bad.join("; ")}. Change the token named first (a darker ink or a lighter ground) until each pair reaches its bar (WCAG AA)`);+};++/** A brand file's colours as palette tokens: the most saturated as the accent; when the brand has a dark and a+ * light colour, the darkest as ink and the lightest as the ground (or the other way round for a dark brand,+ * whose most-used colour is dark). Only what the brand file says; the rest stays the base's. */+export const paletteFromBrand = (b: BrandFile): Partial<Record<PaletteKey, string>> => {+ const cols = b.palette.map((p) => p.hex.toLowerCase()).filter((h) => /^#[0-9a-f]{6}$/.test(h));+ if (!cols.length) return {};+ const out: Partial<Record<PaletteKey, string>> = {};+ const accent = [...cols].sort((x, y) => sat(y) - sat(x))[0]; if (sat(accent) > 0.35) out.accent = accent;+ const byL = [...cols].sort((x, y) => lum(x) - lum(y)), dark = byL[0], light = byL[byL.length - 1];+ if (contrast(dark, light) >= 7) { if (lum(cols[0]) < 0.2) { out.bg = dark; out.ink = light; } else { out.ink = dark; } }+ return out;+};+/** The brand file's logo: an element named like a logo or a mark, else its first. */+export const logoFromBrand = (b: BrandFile): BrandElement | undefined => { const names = Object.keys(b.elements); const n = names.find((x) => /logo|mark|symbol|icon/i.test(x)) ?? names[0]; return n ? (b.elements[n] as unknown as BrandElement) : undefined; };++// ---------------------------------------------------------------- fonts+const FONT_CACHE = new Map<string, Font>();+const fontOf = (f: LookFont, role: string): Font => {+ if (!f || typeof f.family !== "string" || !f.family) throw new Error(`look.fonts.${role}: give { family, file } (a family name and the imported font file)`);+ if (!f.file || typeof f.file.data !== "string") throw new Error(`look.fonts.${role}: '${f.family}' has no font file. Import it by path: import f from "../../assets/fonts/<file>.ttf", then { family: "${f.family}", file: f }`);+ if (f.file.format !== "ttf") throw new Error(`look.fonts.${role}: ${f.file.path} is a .${f.file.format}; the film measures every line from the font's own glyphs, which needs the TrueType .ttf of the face (convert it, or use the .ttf the family ships)`);+ const key = `${f.file.path}#${f.file.data.length}`;+ if (!FONT_CACHE.has(key)) FONT_CACHE.set(key, parseTTF(f.file.data));+ return FONT_CACHE.get(key)!;+};+/** Width of text at px in a parsed face: the glyphs' own advances and pair kerning, as a canvas sets them. */+export const fontWidth = (font: Font, text: string, px: number) => {+ let w = 0, prev = -1; const s = px / font.unitsPerEm;+ for (const ch of text) { const g = font.glyphIndex(ch.codePointAt(0)!); if (prev >= 0) w += font.kerning(prev, g); w += font.glyph(g).advance; prev = g; }+ return w * s;+};+const css = (family: string, fallback: string) => (w: number, px: number) => `${w} ${px}px "${family}", ${fallback}`;+const SANS_FALLBACK = `"Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;++/** Registers the look's font files as FontFaces (in a page; in node it does nothing), once per family. */+const registered = new Set<string>();+export const registerFaces = (faces: ResolvedLook["faces"]) => {+ const g = globalThis as unknown as { FontFace?: new (f: string, s: ArrayBuffer, d?: Record<string, string>) => { load(): Promise<unknown> }; document?: { fonts: { add(f: unknown): void } } };+ if (!g.FontFace || !g.document) return;+ for (const { family, file } of faces) {+ if (registered.has(family)) continue; registered.add(family);+ const bin = atob(file.data), u8 = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);+ // (one face for every weight: the film is measured from this face's own advances, so the browser must not+ // swap in a synthesized bold that is wider than the measure)+ const face = new g.FontFace(family, u8.buffer, { weight: "1 1000", style: "normal" }); g.document.fonts.add(face); void face.load();+ }+};++// ---------------------------------------------------------------- resolve+export type LookSpec = { preset?: string; accent?: string; look?: LaunchLook };+export const resolveLook = (spec: LookSpec): ResolvedLook => {+ const L = spec.look ?? {}, base = L.base ?? spec.preset ?? "drawn";+ if (spec.preset !== undefined && L.base !== undefined && spec.preset !== L.base) throw new Error(`look: preset '${spec.preset}' and look.base '${L.base}' disagree; keep one (preset is the shorthand for look.base)`);+ const def = LOOKS.get(base); if (!def) throw new Error(`look: base '${base}' is not a registered look (${lookNames().join(", ")}); registerLook() adds one`);+ const fromP = L.from ? paletteFromBrand(L.from) : {}, own = L.palette ?? {};+ for (const [k, v] of Object.entries(own)) { if (!(k in CLEAN)) throw new Error(`look.palette: '${k}' is not a token (${Object.keys(CLEAN).filter((x) => x !== "shadow").join(", ")})`); rgb(String(v)); }+ const legacy = spec.accent ? { accent: spec.accent } : {};+ const palette: Palette = { ...def.palette, ...(def.clean ? legacy : {}), ...fromP, ...own } as Palette;+ const changed = new Set([...Object.keys(fromP), ...Object.keys(own)]);+ const chat: LookChat = { ...(L.from ? { logo: logoFromBrand(L.from) } : {}), ...(L.chat ?? {}) };+ const extra: [string, string, number, string][] = [];+ if (chat.bubble) extra.push([chat.bubble.ink, chat.bubble.fill, 4.5, "look.chat.bubble (ink on fill)"]);+ if (chat.reply) extra.push([chat.reply.ink, palette.card, 4.5, "look.chat.reply.ink on the card"]);+ // the label on the accent (the button, the product's action): white, or on a pale accent the darker of ink+ // and ground; whichever it is, it must reach the large-type bar+ const onAccent = contrast("#ffffff", palette.accent) >= 3 ? "#ffffff" : contrast(palette.ink, palette.accent) >= contrast(palette.bg, palette.accent) ? palette.ink : palette.bg;+ if (changed.has("accent") || changed.has("ink") || changed.has("bg")) extra.push([onAccent, palette.accent, 3, `the button's label on 'accent' ${palette.accent}`]);+ checkContrast(palette, changed, extra);+ const F = L.fonts ?? {}, faces: ResolvedLook["faces"] = [];+ const pick = (role: "display" | "text" | "mono") => { const f = F[role]; if (!f) return null; const font = fontOf(f, role); faces.push({ family: f.family, file: f.file }); return { f, font }; };+ const d = pick("display"), t = pick("text"), mo = pick("mono");+ const textFn: FontFn = t ? css(t.f.family, SANS_FALLBACK) : SANS;+ const displayFn: FontFn = d ? css(d.f.family, SANS_FALLBACK) : t ? textFn : SANS;+ const monoFn = mo ? (px: number) => `${px}px "${mo.f.family}", "SF Mono", Menlo, monospace` : MONO;+ const textW = t ? (s: string, px: number) => fontWidth(t.font, s, px) : estWidth;+ const measure = {+ text: textW,+ // (the stock display face is the heavy set sans, wider than the body estimate: the template's 1.12)+ display: d ? (s: string, px: number) => fontWidth(d.font, s, px) : t ? textW : (s: string, px: number) => estWidth(s, px) * 1.12,+ mono: mo ? (s: string, px: number) => fontWidth(mo.font, s, px) : monoWidth,+ };+ const wrapBy = (m: (s: string, px: number) => number) => (text: string, px: number, maxW: number) => { const out: string[] = []; let line = ""; for (const w of text.split(" ")) { const s = line ? `${line} ${w}` : w; if (!line || m(s, px) <= maxW) line = s; else { out.push(line); line = w; } } out.push(line); return out; };+ const wrap = wrapBy(measure.text), wrapDisplay = d ? wrapBy(measure.display) : wrap;+ const byFamily = [d, t, mo].filter((x): x is { f: LookFont; font: Font } => !!x);+ const measureFont = (s: string, fontStr: string) => { const px = Number(/([\d.]+)px/.exec(fontStr)?.[1] ?? 40), hit = byFamily.find((x) => fontStr.includes(`"${x.f.family}"`)); return hit ? fontWidth(hit.font, s, px) : estWidth(s, px); };+ const S = L.shape ?? {};+ if (S.bubble && !["rounded", "square", "none"].includes(S.bubble)) throw new Error(`look.shape.bubble: '${S.bubble}' is not rounded, square or none`);+ if (S.composer && !["box", "bar"].includes(S.composer)) throw new Error(`look.shape.composer: '${S.composer}' is not box or bar`);+ if (S.button && !["pill", "square"].includes(S.button)) throw new Error(`look.shape.button: '${S.button}' is not pill or square`);+ const custom = changed.size > 0 || faces.length > 0 || Object.keys(S).length > 0 || Object.keys(chat).length > 0;+ return { base, clean: def.clean, palette, onAccent, custom, fonts: { display: displayFn, text: textFn, mono: monoFn }, measure, wrap, wrapDisplay, customDisplay: !!d, measureFont, pointer: contrast("#111111", palette.bg) >= 3 ? { fill: "#111", edge: "#fff" } : { fill: contrast("#ffffff", palette.bg) >= contrast(palette.ink, palette.bg) ? "#fff" : palette.ink, edge: "#111" }, shape: { bubble: S.bubble ?? "rounded", composer: S.composer ?? "box", button: S.button ?? "pill", radius: S.radius, buttonLabel: S.buttonLabel }, chat, faces };+};diff --git a/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts b/skills/anidoodle/engine/src/canvas-core/launchTemplate.tsindex 13ff45f..cd5c1f2 100644--- a/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts+++ b/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts@@ -25,14 +25,15 @@import { probeRect, type Ctx, type Env, type P } from "./core";import type { Film } from "./film";import {- C, SANS, MONO, camLerp, caretAt, charTimes, clamp, drawChatFrame, expo, inOut, inkCard, inkDrop,+ C, TEXT_SHOWN, camLerp, caretAt, charTimes, clamp, drawChatFrame, expo, inOut, inkCard, inkDrop,lerp, lerpP, out3, plateLayer, pointer, press, ramp, rr, spring, toScreen, typedAt, useCam, type Cam, type Drop, type ChatGeom, type Rect,} from "./launchKit";-import { launchLayout, estWidth, installRows, wrapEst, SHAPES, type LaunchLayout, type Shape } from "./launchLayout";-import { chatGeom } from "./launchKit";-import { beatGrid, bloomFrame, bloomRadius, makeCut, pic, type, typeFrame, type Seg, type TypeLine } from "./launchCut";-import { measure, writeOn, setType } from "./kinetic";-import { drawProductUI, springLand, uiActionAt, uiCommandAt, uiSettles, uiWindow, type ProductUI, type UiTheme } from "./productUI";+import { launchLayout, estWidth, installRows, SHAPES, type LaunchLayout, type Shape } from "./launchLayout";+import { resolveLook, registerFaces, CLEAN as LOOK_CLEAN, type LaunchLook } from "./launchLook";+import { chatGeom, inkDropAt } from "./launchKit";+import { beatGrid, bloomFrame, bloomRadius, makeCut, pic, type, type Seg, type TypeLine } from "./launchCut";+import { inkSpan, measure, writeOn, setType } from "./kinetic";+import { drawProductUI, springLand, uiActionAt, uiActionRect, uiCommandAt, uiSettles, uiWindow, type ProductUI, type UiTheme } from "./productUI";import { relay, checkRelay, type MotifPose, type Seam } from "./motif";import { launchAudio, type LaunchCue } from "./launchSound";import { fitScore, limiter, renderPiece } from "./music/render";@@ -46,6 +47,13 @@ import { composePiece, stretchIndex, withStretch, type Material } from "./music/import { perform } from "./music/perform";import { beatsPerBar } from "./music/plan";import { novelty } from "./music/novelty";+import { drawEndCard, endCardLayout, type EndCardSpec } from "./endCard";+import { drawEl } from "./brandKit";+import type { ShipMeta } from "./shipMeta";+import type { MotionMeta } from "./motionMeta";+import { readS } from "./readable";+import { TEMPERAMENTS } from "./motionKit";+import { speedCeiling } from "./seams";/** chat -> Generate -> a plate drawing itself in the answer card (the default kind) */export type PlateAsk = {@@ -72,9 +80,15 @@ export type LaunchSpec = {tagline: string; // the one line under the name on the end cardinstall: string[]; // the exact lines a viewer copies; held on screen for the whole end cardfooter?: string; // small print under the panel (where it runs, the repo)+ // the clean end card's layout: "stack" (default) centres name, line, install panel and footer on one+ // axis; "grid" lays them on endCard.ts's asymmetric grid: the name top-left with the drop as its full+ // stop, the line and the install lines under it, the footer as a stamp on the right. Clean preset only.+ endCard?: "stack" | "grid";+ checks?: ShipMeta; // what the film tells the ship checks (shipMeta.ts): its length budget { target, max } in seconds, layoutExempt for a deliberately dense UI beat, and in `none` only a check with truly nothing to look at+ motion?: MotionMeta; // what the film tells the motion scans (motionMeta.ts): the brand's temperament ("calm", "lively", "snappy") and its colours (#rrggbb), both from the briefbpm: number; // the beat grid: bpm comes from the brief (the score composed for it)fps?: 30 | 60; // 60 for UI-heavy films (smoother scrolls and springs); the timing is the same- askBeats?: number; typeBeats?: number; endBeats?: number; // default 6, 4, 8+ askBeats?: number; typeBeats?: number; endBeats?: number; // default 6, 6 (a word page has a travel in, the words' own arrival, their read and their sink), 8claimBar?: number; // land the end card on this bar's downbeat, counting from bar 0 (solves the last ask)// The score: a piece COMPOSED for this product's brief (references/music/compose.md), or null for// a silent film. Required, so no film inherits a score by default. anidoodle's own pieces are@@ -84,7 +98,8 @@ export type LaunchSpec = {audio?: Film["audio"]; // or your own finished mix; wins over score and sfxlimit?: boolean; // let a look-ahead limiter take the score's last peaks so it reaches -14 LUFS (default off: the peak ceiling wins)shape?: Shape; // the frame: 16x9 (default), 1x1, 4x5, 9x16. Every shape is re-composed by launchLayout, never cropped; film.reshape(s) gives the same film in another shape- preset?: "drawn" | "clean"; // the look: ink, blooms and hand lettering (default), or a quiet canvas, one accent and set type+ preset?: string; // the shorthand for look.base: "drawn" (ink, blooms and hand lettering, default) or "clean" (a quiet canvas, one accent and set type)+ look?: LaunchLook; // how the film looks like YOUR product: base, palette, fonts, shape, chat, from (launchLook.ts; references/workflows/launch-video-kit.md, Looks)sfx?: boolean; // sound cues from the picture's timing (default true; false = the score alone)motif?: boolean; // the relay into the end card (default true): the drop becomes the mark's dotcaptions?: "sidecar" | "burn"; // .srt/.vtt only (default), or also burned into their own band (phone shapes)@@ -92,7 +107,8 @@ export type LaunchSpec = {};// the clean preset: a quiet canvas, one accent, type as the design. Our own palette, drawn for it.-export const CLEAN = { bg: "#f3f2ef", card: "#ffffff", ink: "#15161a", soft: "#5b5f68", mute: "#9da1a9", line: "#e4e4e1", chip: "#efefec", accent: "#2f54eb", accentDeep: "#2442bf", paper: "#fbfbf9", shadow: "rgba(20,24,30,0.08)" };+// (it lives in launchLook.ts with the other looks)+export const CLEAN = LOOK_CLEAN;// anidoodle's own pieces (the demos and our launch score) are examples of the composer, never a// user's soundtrack. Refused by identity, by title and by content (the novelty gate), so a thin or@@ -108,25 +124,115 @@ const refuseOurs = (score: () => Piece | Material) => {const v = novelty(asPiece(score)(), corpus);if (!v.pass) throw new Error(`launchTemplate: "${score().title}" is too close to anidoodle's own "${v.worst.name.replace(/ #\d+$/, "")}" (similarity ${v.worst.score}, ${v.worst.reusedFragments} reused 6-note fragments); compose a score for this product's brief (references/music/compose.md) or pass score: null`);};-const TYPE_O = { lead: -4, stagger: 18 }; // the word starts as the bloom closes over the frame; lines run on without a gap-const TR = 16; // a bloom-in: frames it takes to open over the previous scene (a seam between kinds, with no word page)-const DL = 14; // the motif relay: the drop's flight into the end card, in frames (it lands ON the end card's first frame)+// THE CLEAN PRESET'S SEAMS TRAVEL (references/motion-grammar.md, 5. Continuous canvas). Its asks and its+// word pages are places on one canvas, each the size of the frame, and the camera travels from one to the+// next: the next place is in the world before the move starts, nothing is swapped in place, so no seam+// reads as a slide (motionscan slidecut) and no text is left in slivers by an iris crawling over it+// (layerscan exits). The drawn preset keeps its ink blooms. TRV is how long a travel takes, in frames at+// 30 fps: type may never move faster than half the speed ceiling (layerscan fasttext: 0.5 x 2.5 frame+// widths a second), and a travel of one frame width on a sine ease peaks at pi/2 x its mean speed, so+// with a tenth in hand it takes (pi/2) / (0.9 x 1.25) s = 1.4 s. It is the same in every shape, so the+// cut and the sound never change with the shape. (The glide below peaks lower, at 1.11 x its mean, so+// the bound is generous.)+const TRV = Math.ceil((Math.PI / 2 / (0.9 * 0.5 * 2.5)) * 30);+/**+ * The travel's ease, a GLIDE: its speed rises in a straight line over the first tenth, cruises, and falls+ * over the last tenth (no step at either end, peak 1.11 x the mean). A sine ease crept under a pixel a+ * frame for its first and last frames, and a dense screen of type shifted that slowly reads as swapped,+ * not moved (motionscan slidecut cannot tell the camera is travelling).+ */+const GLIDE = 0.1;+const glide = (q: number) => { const c = clamp(q), r = GLIDE, v = 1 / (1 - r); return c < r ? (v * c * c) / (2 * r) : c > 1 - r ? 1 - (v * (1 - c) * (1 - c)) / (2 * r) : v * (c - r / 2); };+/**+ * A scene drawn at another place in the one world. Every transform the scene sets is scaled by z about+ * (cx, cy) and moved by (dx, dy) first, so a scene that sets its own camera (setTransform) can sit beside+ * another on one canvas, or creep closer as a whole. With `fade`, each line of text gets an opacity from+ * where it lands (logical px), so a phone shape's travel fades text before it reaches a platform zone.+ */+const placed = (ctx: Ctx, env: Env, o: { z?: number; c?: P; d?: P; fade?: (x0: number, y0: number, x1: number, y1: number, d: P) => number }): Ctx => {+ const z = o.z ?? 1, S = env.scale, [cx, cy] = o.c ?? [0, 0], [dx, dy] = o.d ?? [0, 0], ox = (cx * (1 - z) + dx) * S, oy = (cy * (1 - z) + dy) * S, fade = o.fade;+ if (z === 1 && !ox && !oy && !fade) return ctx;+ const setT = (a: number, b: number, c: number, d: number, e: number, f: number) => ctx.setTransform(z * a, z * b, z * c, z * d, z * e + ox, z * f + oy);+ return new Proxy(ctx, {+ get(t, k) {+ if (k === "setTransform") return (...a: unknown[]) => { if (typeof a[0] === "object" && a[0]) { const m = a[0] as DOMMatrix2DInit; return setT(m.a ?? 1, m.b ?? 0, m.c ?? 0, m.d ?? 1, m.e ?? 0, m.f ?? 0); } return setT(...(a as [number, number, number, number, number, number])); };+ if (k === "resetTransform") return () => setT(1, 0, 0, 1, 0, 0);+ if (k === "fillText" && fade) return (s: string, x: number, y: number, mw?: number) => {+ const m = t.getTransform(), q = t.measureText(s), x0 = x - q.actualBoundingBoxLeft, x1 = x + q.actualBoundingBoxRight, y0 = y - q.actualBoundingBoxAscent, y1 = y + q.actualBoundingBoxDescent;+ const xs = [m.a * x0 + m.c * y0 + m.e, m.a * x1 + m.c * y1 + m.e], ys = [m.b * x0 + m.d * y0 + m.f, m.b * x1 + m.d * y1 + m.f];+ const k = fade(Math.min(...xs) / S, Math.min(...ys) / S, Math.max(...xs) / S, Math.max(...ys) / S, [dx, dy]), was = t.globalAlpha;+ (t as unknown as Record<symbol, number>)[TEXT_SHOWN] = Math.max(0, k); // (inkCard fades a byline's dot with its words)+ if (k <= 0) return; t.globalAlpha = was * k; if (mw === undefined) t.fillText(s, x, y); else t.fillText(s, x, y, mw); t.globalAlpha = was;+ };+ const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v;+ },+ set(t, k, v) { return Reflect.set(t, k, v); },+ });+};+// THE DRAWN LOOK'S WORDS WRITE THEMSELVES, with no pen in the frame. A hand-lettering pen crosses a line in+// 18 frames, at up to 90 px a frame on a phone frame: nearly twice what a lively brand allows (motionscan+// temperament), and the eye follows the pen, not the word. The ink still goes down stroke by stroke.+const PEN = false;+const DL0 = 14; // the motif relay: the drop's flight into the end card, in frames (it lands ON the end card's first frame); DL in the filmconst LIFT = 6; // ...after a bead of ink swells on its source for this many framesconst isChat = (a: LaunchAsk): a is PlateAsk => !a.kind || a.kind === "plate";-// the timing inside one chat ask, from its prompt and its length (`a0` delays the typing past a bloom-in)-const askTiming = (prompt: string, i: number, ASK: number, a0 = 0) => {+// the timing inside one chat ask, from its prompt and its length (`a0` delays the typing: after a travel+// in, typing starts halfway through it, as the composer arrives, the way a split beat's words rise)+// SETTLE: once the prompt is typed, the hook's composer docks (or the close-up eases out to the room) over+// this many frames, and Generate is pressed only once it has landed: a button is never pressed on the move.+// An in-out over a second keeps type under half the speed ceiling on every shape (layerscan fasttext); the+// expo ease it replaced moved the docking prompt at 118 px a frame on a phone frame.+const SETTLE = 30;+/**+ * THE CLEAN HOOK'S DOCK travels as one object and stays that object: the big composer glides down whole (its+ * own size, its own line breaks) to the foot of the window in MOVE frames, and that is the dock. It never+ * shrinks: a composer that shrank as it moved, its words rewrapping halfway, replaced 64 % of a clean frame in+ * 0.1 s (a slide cut to motionscan), and one that scaled down once it had landed read to a fresh critic as a+ * second move (cc1-1). MOVE is short enough that the glide reads to motionscan as a move (over 10 px a frame+ * at 60 fps on 16:9) and long enough that its type stays under half the speed ceiling on a phone frame+ * (layerscan fasttext). (`shrink` stays in the record, at 0 frames, for the grammar's dock window.)+ */+// REST: once landed it rests 15 frames before Ask is pressed (the room's creep still moving), the time the+// scale used to take: the typed question is read whole before it is sent (framecheck reading time, 1.5 s).+const CLEAN_DOCK = { at: -2, move: 14, shrink: 0, rest: 15 };+/**+ * The first prompt is already being typed at frame 0 (a silent-readable hook), so frame 0, the thumbnail,+ * shows what is typed so far. It must end on a whole word ("a lighthouse at", never "a lighthouse at s":+ * a fresh critic read the broken word as a broken frame). Typing runs from `a` to `b`, keeping each key's+ * share of the line (`raw`); this returns the start nearest `want` at which frame 0 falls between the last+ * key of a word and the space after it.+ */+export const wholeWordStart = (prompt: string, raw: number[], b: number, want: number) => {+ const last = raw[raw.length - 1] || 1, r = (j: number) => raw[j] / last;+ let best = want, gap = Infinity;+ for (let e = 1; e < prompt.length; e++) {+ if (prompt[e] !== " " || prompt[e - 1] === " ") continue;+ // key e-1 (the word's last) at or before frame 0, key e (the space) after it+ const hi = (-r(e - 1) * b) / (1 - r(e - 1)), lo = (-r(e) * b) / (1 - r(e)) + 0.25;+ if (lo > hi) continue;+ const a = clamp(want, lo, hi), d = Math.abs(a - want); if (d < gap) { gap = d; best = a; }+ }+ return best;+};+// `dock`: where the composer's settle starts against the last key, and how long it takes (the clean hook's+// dock, CLEAN_DOCK, is its own); `fly`: the ink drop's flight to the answer card, in frames (14, or the clean+// look's, from its distance)+const askTiming = (prompt: string, i: number, ASK: number, a0 = 0, dock: { at: number; len: number } = { at: -8, len: SETTLE }, fly = 14) => {const raw = charTimes(prompt, 0, 1, 7 + i * 4), last = raw[raw.length - 1] || 1;- const b = Math.round(ASK * 0.25) + a0, a = i === 0 ? -Math.round(b * 1.2) : 4 + a0; // the first prompt is under way at frame 0+ const b = Math.round(ASK * 0.25) + a0, a = i === 0 ? wholeWordStart(prompt, raw, b, -Math.round(b * 1.2)) : 4 + a0; // the first prompt is under way at frame 0, on a whole wordconst times = raw.map((t) => a + (t / last) * (b - a));- const down = b + 16, up = down + 5, drop: Drop = { t0: up + 5, land: up + 19, full: up + 40 };+ const down = b + dock.at + dock.len + 2, up = down + 5, drop: Drop = { t0: up + 5, land: up + 5 + fly, full: up + 26 + fly };return { times, b, down, up, drop };};// a UI ask: the ask typed into the product's command bar (if it has a prompt), then its action pressed-const uiTiming = (prompt: string | undefined, i: number, ASK: number, a0: number, split = false) => {- const b = Math.round(ASK * (prompt ? 0.3 : split ? 0.13 : 0.2)) + a0; // a split beat's words are the wait: its press follows them+const uiTiming = (prompt: string | undefined, i: number, ASK: number, a0: number, split = false, travelled = false) => {+ // a split beat's words are the wait: its press follows them. After a travel (clean) they rose on the way+ // in and are read as it lands, so the press comes 2 frames after: the after state then has the rest of+ // the beat to be read (a row's new tag needs its own reading time before the next seam)+ const b = split && travelled ? a0 + 2 : Math.round(ASK * (prompt ? 0.3 : split ? 0.13 : 0.2)) + a0;let times: number[] = [];- if (prompt) { const raw = charTimes(prompt, 0, 1, 11 + i * 4), last = raw[raw.length - 1] || 1, a = i === 0 ? -Math.round(b * 0.8) : 6 + a0; times = raw.map((t) => a + (t / last) * (b - a)); }+ if (prompt) { const raw = charTimes(prompt, 0, 1, 11 + i * 4), last = raw[raw.length - 1] || 1, a = i === 0 ? wholeWordStart(prompt, raw, b, -Math.round(b * 0.8)) : 6 + a0; times = raw.map((t) => a + (t / last) * (b - a)); }const down = b + 14, up = down + 5;return { times, b, down, up, drop: { t0: up + 2, land: up + 2, full: up + 2 } as Drop };};@@ -139,34 +245,165 @@ export type LaunchFilm = Omit<Film, "reshape"> & {timing: { base: number; len: number; tin: number; b: number; down: number; up: number; drop: Drop; times: number[] }[]; // each ask's own timing, content frames at 30 fpscaptions: { from: number; to: number; text: string }[]; // = meta.captionsclaims: string[]; // every claim the film makes, each to be listed in facts.json with its source (tools/facts.mjs)+ // the moves the film is built from, as data (content frames at 30 fps, world px), for tests and critics:+ // each chat ask's thread scroll, every travel's direction, each word page's sink, the end card's bloom,+ // and where the motif's drop swells before it flies+ grammar: {+ scrolls: { i: number; d: number; from: number; len: number }[];+ travels: { seam: string; ax: P }[];+ pages: { i: number; set: number; out: number }[];+ endBloom: { frames: number; radius: number };+ lift: P;+ endCard: { creep: P; cx: number; group: [number, number]; logo: Rect | null; tagline: string[]; taglineW: number[]; room: [number, number] }; // + the clean card's tagline lines, their measured widths, and the x span they may use (inside the phone-safe rectangle) // the point the end card's settle zooms about, the card's axis, and its name-and-dot group's ink, left and right+ rests: { i: number; tip: P; win: Rect; s: number }[];+ splits: { i: number; lines: string[]; size: number; tall: number; room: Rect }[];+ // the clean hook's dock (null without one): the frames it glides whole and the frames it then scales in, the+ // hook's and the dock's prompt size, the docked composer, the chat window, and where the thread's view ends+ dock: { move: [number, number]; shrink: [number, number]; creep: number; heroPx: number; dockPx: number; composer: Rect; window: Rect; viewBottom: number } | null; // each split beat's words as set: their lines, size, the height they take, and their column+ // the drawn hook's dock (null without one): its frames (30 fps units) and its fastest point on screen, px a+ // 30 fps frame, read off the composer's corners, its button and its type as the camera sees them+ heroDock: { frames: [number, number]; peak: number; wraps: number } | null;+ // the last ask's words with the motif (null without): the content frame they have sunk by, and the frames the+ // drop flies over (it leaves its bead at the first, lands as the end card's dot at the second)+ lastWords: { gone: number; flight: [number, number] } | null;+ // each chat ask's ink drop: its flight (content frames) and its fastest point on screen, px a 30 fps frame+ drops: { i: number; flight: [number, number]; peak: number; landing: number }[];+ };};+/** A travelled string's opacity on a phone shape (its box x0..x1, y0..y1 on screen, its place moved by d):+ * none inside a zone (the top band, the bottom band, the right-hand column; the left side has none), and a+ * fade over `band` px before one, measured from where it rests, so it leaves in some five frames of the+ * travel, never in one, and a string resting near a safe edge does not dim the moment a travel starts. */+export const zoneFadeOf = (S: { x: number; y: number; w: number; h: number }, band = 120) => {+ const dist = (y0: number, x1: number, y1: number) => Math.min(S.x + S.w - x1, y0 - S.y, S.y + S.h - y1);+ return (_x0: number, y0: number, x1: number, y1: number, d: P) => {+ const now = dist(y0, x1, y1); if (now < 0) return 0;+ const rest = dist(y0 - d[1], x1 - d[0], y1 - d[1]);+ return clamp(now / Math.max(1e-6, rest > 0 ? Math.min(band, rest) : band));+ };+};+/** How far line j of nL has sunk (0..1) at q (0..1) of a page's sink: the last line leaves first, and each+ * next one starts while the one below is 40 % from gone, so some line is always moving. Back to back, each+ * line's ease-in start left still frames between two lines (identical frames at 60 fps, the gate). */+export const sinkOf = (q: number, j: number, nL: number) => { const D = 1 / (1 + (nL - 1) * 0.6), start = (nL - 1 - j) * 0.6 * D; return clamp((q - start) / D); };export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {- const fps = spec.fps ?? 30, m = fps / 30, n = spec.asks.length, shape = spec.shape ?? "16x9", clean = spec.preset === "clean";+ const fps = spec.fps ?? 30, m = fps / 30, n = spec.asks.length, shape = spec.shape ?? "16x9", LK = resolveLook(spec), clean = LK.clean;if (fps !== 30 && fps !== 60) throw new Error(`launchTemplate: fps ${fps}; a launch film runs at 30, or 60 for a UI-heavy film`);if (!(shape in SHAPES)) throw new Error(`launchTemplate: shape '${shape}' is not one of ${Object.keys(SHAPES).join(", ")}`);- if (spec.preset !== undefined && spec.preset !== "drawn" && spec.preset !== "clean") throw new Error(`launchTemplate: preset '${spec.preset}' is not "drawn" or "clean"`);if (!(spec.bpm > 0)) throw new Error("launchTemplate: set bpm from the brief (the tempo of the score composed for this film)");if (spec.score === undefined && !spec.audio) throw new Error("launchTemplate: `score` is required: a piece composed for this product (references/music/compose.md), or null for silence");if (n < 1 || n > 3) throw new Error("launchTemplate: 1 to 3 asks; more is a feature list, not a story");if (spec.score) refuseOurs(spec.score);+ if (spec.endCard !== undefined && spec.endCard !== "stack" && spec.endCard !== "grid") throw new Error(`launchTemplate: endCard '${spec.endCard}' is not "stack" or "grid"`);+ if (spec.endCard === "grid" && !clean) throw new Error('launchTemplate: endCard "grid" is the clean preset\'s card; the drawn look keeps its written name');const chatIdx = spec.asks.map((a, i) => (isChat(a) ? i : -1)).filter((i) => i >= 0), chatOrd = (i: number) => chatIdx.indexOf(i);const burn = spec.captions === "burn" && shape !== "16x9";- const L = launchLayout(shape, { prompts: chatIdx.map((i) => (spec.asks[i] as PlateAsk).prompt), install: spec.install, tagline: spec.tagline, title: spec.title, band: burn });- const PAL = clean ? { ...CLEAN, ...(spec.accent ? { accent: spec.accent } : {}) } : C;- const ACC = spec.accent ?? (clean ? CLEAN.accent : undefined), INK = clean ? PAL.accent : PAL.ink; // the drop, the motif: ink, or the one accent- const G: ChatGeom = clean ? { ...L.chat, theme: CLEAN, drop: INK, iris: true } : L.chat;- const W = L.W, H = L.stage.h, TH = L.thread, CAM = L.cam, CARD = TH.card, VIEW_BOTTOM = TH.viewBottom, k = G.k, minPx = L.phone ? 32 : 18;- const GEN_C: P = [G.GEN.x + G.GEN.w / 2, G.GEN.y + G.GEN.h / 2];+ const L = launchLayout(shape, { prompts: chatIdx.map((i) => (spec.asks[i] as PlateAsk).prompt), install: spec.install, tagline: spec.tagline, title: spec.title, band: burn, wrap: LK.wrap });+ // THE LOOK (launchLook.ts): the stock looks draw exactly as before; a custom one brings its palette, faces,+ // shapes and chat. Its font files are registered as FontFaces before the first frame (in a page).+ registerFaces(LK.faces);+ const PAL = clean || LK.custom ? LK.palette : C;+ const ACC = clean || LK.custom ? PAL.accent : spec.accent, INK = clean ? PAL.accent : PAL.ink; // the drop, the motif: ink, or the one accent+ const G0: ChatGeom = clean ? { ...L.chat, theme: PAL, drop: INK, iris: true, look: LK.custom ? LK : undefined } : LK.custom ? { ...L.chat, theme: PAL, look: LK } : L.chat;+ const W = L.W, H = L.stage.h, CAM = L.cam, k = G0.k, minPx = L.phone ? 32 : 18;const UI_FULL: Rect = L.uiFull;+ const CALM = (spec.motion?.temperament ?? "lively") === "calm" || (typeof spec.motion?.temperament === "object" && spec.motion.temperament.maxSpeed <= TEMPERAMENTS.calm.maxSpeed);+ const DL = DL0;// 9x16: text stays inside the platforms' safe rectangle SAFE (launchLayout.PHONE_SAFE). The camera's// close-ups zoom about a point that stays put, and whatever a move carries toward a zone fades first.const ZONES = L.zones, SAFE = L.safe, SC: P = [SAFE.x + SAFE.w / 2, SAFE.y + SAFE.h / 2];+ // the empty state: on a phone the first ask's composer starts in the middle of the empty thread (the+ // way a chat app opens) and docks at the bottom as Generate is pressed; the hook is the prompt, centred+ // THE HOOK: the first prompt is the hero. It is typed in a big composer in the middle of the frame+ // (at least 64 px type on a phone frame, 56 px on 16x9, wrapping to 2-3 lines, never clipped),+ // which shrinks and docks at the bottom of the chat as Generate is pressed.+ // (clean: it holds as many lines as the longest prompt needs at its size, since the dock is this same+ // composer scaled down, and a later prompt is typed into it)+ // (clean, on 9x16: 40 px narrower, since the hook's composer is also the dock, and docked at the window's+ // foot under the hook's 4 % creep its right edge reached the phone's right-hand zone, where seen() faded+ // it: its accent caret and button see-through, layerscan translucent)+ const HERO = (() => {+ if (!isChat(spec.asks[0])) return null;+ const prompt = spec.asks[0].prompt, min = L.phone ? 64 : 56, inW = ZONES ? G0.CHAT.w - (clean ? 64 : 24) : Math.min(L.phone ? W * 0.9 : W * 0.72, G0.CHAT.w - 60 * k); // most of the width, inside the chat window (on 9x16 all of it: the window is narrower there)+ // (clean: from the smallest size, since this composer is the dock all film long; larger, it left the answer+ // card a thumbnail on 16:9, cc3-1)+ for (let px = clean ? min : L.phone ? 76 : 68; px >= min; px -= 2) {+ const kh = px / 34, genW = 166 * kh, textW = inW - 44 * kh - genW - 44 * kh, lines = LK.wrap(prompt, px, textW).length;+ if (lines > 3 && px > min) continue;+ if (lines > 3) throw new Error(`launchTemplate ${shape}: the first prompt "${prompt}" needs ${lines} lines at the hook's ${min} px; shorten it (the hook must read muted in the first 2 s)`);+ const rows = clean ? Math.min(3, Math.max(lines, ...chatIdx.map((j) => LK.wrap((spec.asks[j] as PlateAsk).prompt, px, textW).length))) : lines;+ // centred in the frame, or on 9x16 in the chat window (which is centred in the safe rectangle)+ const h = 104 * kh + (rows - 1) * Math.round(px * 1.3), fake = ZONES+ ? { x: G0.CHAT.x + (G0.CHAT.w - inW) / 2 - 60 * kh, y: G0.CHAT.y + G0.CHAT.h / 2 - H * 0.5, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh }+ : { x: (W - inW) / 2 - 60 * kh, y: 0, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh };+ const g = chatGeom(fake, kh, { ...G0.px, gen: 24 * kh }, px, rows, genW);+ return { ...g, CHAT: G0.CHAT, theme: G0.theme, drop: G0.drop, iris: G0.iris } as ChatGeom;+ }+ return null;+ })();+ // the hook's composer, its foot (the middle of its bottom edge) moved to `to` and scaled by s about it: every+ // part of it at once, its type size and its line breaks with it (the clean look's dock)+ const footOf = (g: ChatGeom): P => [g.INPUT.x + g.INPUT.w / 2, g.INPUT.y + g.INPUT.h];+ const scaledComposer = (g: ChatGeom, s: number, to: P): ChatGeom => {+ const [fx, fy] = footOf(g), X = (x: number) => to[0] + (x - fx) * s, Y = (y: number) => to[1] + (y - fy) * s;+ const R = (r: Rect & { r: number }) => ({ x: X(r.x), y: Y(r.y), w: r.w * s, h: r.h * s, r: r.r * s });+ return { ...g, INPUT: R(g.INPUT), GEN: R(g.GEN), TEXT: { x: X(g.TEXT.x), base: Y(g.TEXT.base), px: g.TEXT.px * s }, k: g.k * s, px: { ...g.px, gen: g.px.gen * s }, lineH: g.lineH * s };+ };+ // THE CLEAN DOCK is the hook's composer itself, at its own size, standing on the laid-out composer's foot:+ // one composer all film long, so the dock is one move of one object, never a re-layout or a rescale+ const DOCK_S = 1;+ const G: ChatGeom = clean && HERO ? (() => { const d = scaledComposer(HERO, DOCK_S, footOf(G0)); return { ...G0, INPUT: d.INPUT, GEN: d.GEN, TEXT: d.TEXT, wrap: d.wrap, lineH: d.lineH, px: { ...G0.px, gen: d.px.gen } }; })() : G0;+ // (the thread's view ends above the dock: on a phone the dock can stand taller than the laid-out composer,+ // and the answer card then shrinks, on every shape, to keep a card and the prompt above it in view together)+ const TH = (() => {+ const T0 = L.thread, vb = Math.min(T0.viewBottom, G.INPUT.y - 26 * k), d = T0.viewBottom - vb; if (d <= 0) return T0;+ // (on every shape: on 16:9 a card kept at its size made the thread scroll the question off, cc2-1)+ const card = Math.round(T0.card - d);+ return { ...T0, viewBottom: vb, clip: [T0.clip[0], T0.clip[1], T0.clip[2], T0.clip[3] - d] as [number, number, number, number], card, cardX: L.phone ? G.CHAT.x + (G.CHAT.w - card) / 2 : T0.cardX };+ })();+ const CARD = TH.card, VIEW_BOTTOM = TH.viewBottom;+ // THE CLEAN DROP'S FLIGHT follows its distance: 14 frames, or more when the streak (one solid, coherent thing+ // to motionscan, unlike the drawn look's fading trail) would top out past nine tenths of what the brand's+ // temperament allows, flown to where the thread's first card sits (later ones scroll in to sit lower; a+ // flight sized to the top of the view instead was so slow that a phone frame stood still: the gate's dead+ // air). With the hook's+ // composer docked at its own size+ // on a phone frame, the 14-frame flight moved at 45 px a frame against snappy's 36.+ const FLY = (() => {+ if (!clean || !TH.bubbles.length) return 14; // (no chat ask, no drop)+ const t = spec.motion?.temperament ?? "lively", share = typeof t === "string" ? (TEMPERAMENTS[t] ?? TEMPERAMENTS.lively).maxSpeed : t.maxSpeed, cap = 0.85 * share * speedCeiling(W, 30); // (0.85: the room creeps in a few per cent around it)+ // (the drop's own path, inkDropAt's, flown at each length until its fastest step is under the cap)+ const to: P = [TH.cardX + CARD / 2, TH.top + TH.bubbleH + (TH.bubbles[0].length - 1) * TH.bubbleLineH + TH.gap + TH.cardDy + CARD / 2], d0 = { t0: 0, land: 14 };+ for (let N = 14; N < 60; N++) {+ d0.land = N; let peak = 0;+ for (let c = 0; c < N - 0.5; c += 0.5) { const a = inkDropAt(c, d0, to, G), b = inkDropAt(c + 0.5, d0, to, G); if (a && b) peak = Math.max(peak, 2 * Math.hypot(b.p[0] - a.p[0], b.p[1] - a.p[1])); }+ if (peak <= cap) return N;+ }+ return 60;+ })();+ // THE DRAWN DOCK'S LENGTH follows the distance it covers: an in-out over SETTLE frames, or longer when the+ // hook's composer travels far enough that its fastest point would pass nine tenths of what the brand's+ // temperament allows (or of half the speed ceiling, the type's own limit). A calm brand's hook on a phone+ // frame docked at 44 px a frame against calm's 31 (motionscan temperament, layerscan fasttext on the+ // drawn scaffold); a lively one keeps its second on a wide frame. (The cubic in-out tops out at 3 times its average.)+ const DOCK_SHARE = (() => { const t = spec.motion?.temperament ?? "lively"; return Math.min(0.5, typeof t === "string" ? (TEMPERAMENTS[t] ?? TEMPERAMENTS.lively).maxSpeed : t.maxSpeed); })();+ const DOCK_LEN = (() => {+ if (!HERO || clean) return SETTLE;+ const pts = (g: ChatGeom): P[] => [[g.INPUT.x, g.INPUT.y], [g.INPUT.x + g.INPUT.w, g.INPUT.y], [g.INPUT.x, g.INPUT.y + g.INPUT.h], [g.INPUT.x + g.INPUT.w, g.INPUT.y + g.INPUT.h], [g.GEN.x, g.GEN.y], [g.TEXT.x, g.TEXT.base]];+ const a = pts(HERO), b = pts(G), D = Math.max(...a.map((p, j) => Math.hypot(p[0] - b[j][0], p[1] - b[j][1]))) * (ZONES ? 1.04 : 1.02); // (at the hook's creep zoom)+ return Math.max(SETTLE, Math.ceil((3 * D) / (0.9 * DOCK_SHARE * speedCeiling(W, 30))));+ })();+ // (a longer dock starts its extra frames sooner, over the prompt's last words, and lands when a one-second+ // dock would: everything after it keeps its time. Landing later squeezed the lean onto the answer card+ // into fewer frames, 55 px a frame on the calm scaffold's phone frame)+ const DOCK_AT = -8 - (DOCK_LEN - SETTLE);+ const GEN_C: P = [G.GEN.x + G.GEN.w / 2, G.GEN.y + G.GEN.h / 2];const about = (p: P, z: number): P => [p[0] - (p[0] - W / 2) / z, p[1] - (p[1] - H / 2) / z]; // a camera at zoom z that leaves world point p where it is on screen- const THEME: UiTheme = { bg: PAL.bg, card: PAL.card, ink: PAL.ink, soft: PAL.soft, mute: PAL.mute, line: PAL.line, chip: PAL.chip, accent: ACC ?? PAL.accent, paper: PAL.paper };+ const THEME: UiTheme = { bg: PAL.bg, card: PAL.card, ink: PAL.ink, soft: PAL.soft, mute: PAL.mute, line: PAL.line, chip: PAL.chip, accent: ACC ?? PAL.accent, paper: PAL.paper, ...(LK.custom ? { font: LK.fonts.text, onAccent: LK.onAccent, radius: LK.shape.radius, button: LK.shape.button } : {}) };// ---------------------------------------------------------------- the beat grid and the asks' lengths (30 fps units; 60 fps draws between them)const grid = beatGrid(spec.bpm, 30);- const ASK = Math.round((spec.askBeats ?? 6) * grid.beat), TYPE = Math.round((spec.typeBeats ?? 4) * grid.beat), END0_HOLD = Math.round((spec.endBeats ?? 8) * grid.beat);+ const ASK = Math.round((spec.askBeats ?? 6) * grid.beat), TYPE = Math.round((spec.typeBeats ?? 6) * grid.beat), END0_HOLD = Math.round((spec.endBeats ?? 8) * grid.beat);let END = END0_HOLD; // the end card is a hold: a scored film sets it so the film is whole bars of its scoreif (ASK < 100) throw new Error(`launchTemplate: an ask beat needs 100 frames or more (it has ${ASK}); raise askBeats`);if (END < MIN_END(30)) throw new Error("launchTemplate: the end card must hold the install lines 3 s or more; raise endBeats");@@ -178,8 +415,10 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const LEN = spec.asks.map((_, i) => (i === n - 1 ? Math.max(ASK, SOLVED) : ASK)); // content frames per askconst BASE = LEN.map((_, i) => LEN.slice(0, i).reduce((a, b) => a + b, 0));// a seam between two kinds (or into a UI or a film) with no word page on it opens with a bloom-in- const TIN = spec.asks.map((a, i) => (i > 0 && !(isChat(a) && isChat(spec.asks[i - 1])) && !words[i - 1]?.length ? TR : 0));- const T = spec.asks.map((a, i) => ({ ...(isChat(a) ? askTiming(a.prompt, i, ASK, TIN[i]) : a.kind === "ui" ? uiTiming(a.prompt, i, ASK, TIN[i], !!a.split?.length) : { times: [], b: 0, down: 0, up: 0, drop: { t0: 0, land: 0, full: 0 } }), base: BASE[i], len: LEN[i], tin: TIN[i] }));+ // (clean: every seam into an ask is a travel, from the word page before it or from the ask before it;+ // chat to chat with no word page stays in the one thread, with no seam at all)+ const TIN = spec.asks.map((a, i) => (i === 0 ? 0 : words[i - 1]?.length || !(isChat(a) && isChat(spec.asks[i - 1])) ? TRV : 0));+ const T = spec.asks.map((a, i) => ({ ...(isChat(a) ? askTiming(a.prompt, i, ASK, Math.round(TIN[i] / 2), HERO && i === 0 ? (clean ? { at: CLEAN_DOCK.at, len: CLEAN_DOCK.move + CLEAN_DOCK.shrink + CLEAN_DOCK.rest } : { at: DOCK_AT, len: DOCK_LEN }) : undefined, FLY) : a.kind === "ui" ? uiTiming(a.prompt, i, ASK, TIN[i], !!a.split?.length, TIN[i] > 0) : { times: [], b: 0, down: 0, up: 0, drop: { t0: 0, land: 0, full: 0 } }), base: BASE[i], len: LEN[i], tin: TIN[i] }));const END0 = BASE[n - 1] + LEN[n - 1]; // content frame where the end card startsconst askOf = (f: number) => { let i = n - 1; while (i > 0 && T[i].base > f) i--; return i; };@@ -188,22 +427,34 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const items: Item[] = [];chatIdx.forEach((i) => { const t = T[i], o = chatOrd(i); items.push({ at: t.base + t.up, h: TH.bubbleH + (TH.bubbles[o].length - 1) * TH.bubbleLineH, user: (spec.asks[i] as PlateAsk).prompt, lines: TH.bubbles[o] }); items.push({ at: t.base + t.drop.land, h: CARD + TH.cardDy, card: i }); });const ys = (() => { let y = TH.top; return items.map((it) => { const r = y; y += it.h + TH.gap; return r; }); })();- const scrollAt = (f: number) => { let s = 0; items.forEach((it, k) => { const want = Math.max(0, ys[k] + it.h - VIEW_BOTTOM); if (want > s) s += (want - s) * expo(ramp(f, it.at - 2, it.at + 16)); }); return s; };+ // THE THREAD SCROLLS ONCE PER ASK, as Generate is pressed: one move makes room for the sent prompt and+ // its answer card together (two overlapping scrolls added up). It is a glide (peak 1.11 times its mean)+ // whose length follows the distance, so the thread's type moves at three quarters of half the speed+ // ceiling at most (layerscan fasttext; the rest is the sent prompt's own rise, which rides on it), never+ // in under a second (an expo here moved the thread at 150 px a frame on a phone frame), and the camera+ // leans onto the card only once it has settled (cardSettled): a scroll and a lean at once carried the+ // thread's type past the ceiling on a phone frame.+ const scrolls = (() => { let done = 0; return chatIdx.map((i) => { const want = Math.max(0, ...items.map((it, k) => (it.card === i || it.user === (spec.asks[i] as PlateAsk).prompt && items[k + 1]?.card === i ? ys[k] + it.h - VIEW_BOTTOM : 0))), d = Math.max(0, want - done); done = Math.max(done, want);+ return { i, d, from: T[i].base + T[i].down - 2, len: Math.max(30, Math.ceil((1.12 * d) / (0.75 * 0.5 * speedCeiling(W, 30)))) }; }); })();+ const scrollAt = (f: number) => scrolls.reduce((s, q) => s + q.d * glide(ramp(f, q.from, q.from + q.len)), 0);+ const cardSettled = (i: number) => { const q = scrolls.find((x) => x.i === i)!; return q.from + q.len - T[i].base; }; // local frame its scroll landsconst cardY = (i: number, f: number) => ys[items.findIndex((it) => it.card === i)] + TH.cardDy - scrollAt(f);const plateFrame = (i: number, f: number) => { const a = spec.asks[i] as PlateAsk, t = T[i], from = a.from ?? 0, to = a.to ?? a.plate.meta.durationFrames - 1; return lerp(from, to, ramp(f, t.base + t.drop.land, t.base + t.len - 8)); };// the card opens on a spring and lands on its first arrival (its sound sits on that frame)const OMEGA = 4.163 / 21, ZETA = 0.8, arrive = (i: number) => springLand(T[i].base + T[i].drop.land, OMEGA, ZETA);const growAt = (i: number) => (f: number) => (f >= arrive(i) ? 1 : spring(f, T[i].base + T[i].drop.land, OMEGA, ZETA));+ let quietBug = false; // while a travel draws two places, the corner mark is drawn once, where it sits on the screenconst bug = (c: Ctx, env: Env) => {- if (clean) { c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.font = SANS(600, L.bug.px * 0.8); c.fillStyle = PAL.soft; c.textAlign = "right"; c.textBaseline = "alphabetic"; c.fillText(spec.title, L.bug.x, L.bug.y); c.textAlign = "left"; return; }+ if (quietBug) return;+ if (clean) { c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.font = LK.fonts.text(600, L.bug.px * 0.8); c.fillStyle = PAL.soft; c.textAlign = "right"; c.textBaseline = "alphabetic"; c.fillText(spec.title, L.bug.x, L.bug.y); c.textAlign = "left"; return; }writeOn(c, env, spec.title, L.bug.x, L.bug.y, L.bug.px, 1, "ink", { color: C.soft, align: "right", seed: 3 });};// focus: while the camera is close on the composer the thread recedes (it would be cut by the frame's// edge), and while it leans on a card everything but that card does; nothing is ever half off-frame// And whatever the camera's edge is about to cut fades before it does: an element's opacity is how// far inside the view it sits (full at 24 px in, none at the edge), so nothing shows half off-frame.- type Focus = { macro: number; lean: number; keep: number; cam: Cam };+ type Focus = { lean: number; keep: number; cam: Cam };// (on 9x16 the edge that counts is the safe rectangle's, so text fades before it reaches a zone; the fade// is short, ZONE_FADE px, because the hook's composer spans the window and a zone's line is not a visible edge)const ZONE_FADE = 8;@@ -211,27 +462,40 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const seen = ZONES ? seenSafe : (cam: Cam, x0: number, y0: number, x1: number, y1: number) => { const hw = W / 2 / cam.z, hh = H / 2 / cam.z, d = Math.min(x0 - (cam.c[0] - hw), cam.c[0] + hw - x1, y0 - (cam.c[1] - hh), cam.c[1] + hh - y1) * cam.z; return clamp(d / (24 * k)); };// (on a phone the close-up is nearly the whole window, so the header and thread stay, cut only by `seen`)// a card's width with its byline, which can run past the card (an estimate that errs wide)- const cardSpan = (i: number) => Math.max(CARD, 26 * k + estWidth((spec.asks[i] as PlateAsk).label, G.px.label));- const chat = (ctx: Ctx, env: Env, f: number, typed: string, caret: boolean, pr: number, hot: number, fo: Focus = { macro: 0, lean: 0, keep: -1, cam: CAM.home }, Gc: ChatGeom = G) => {- const C0 = G.CHAT, mf = L.phone || Gc !== G ? 0 : fo.macro, headA = Math.min(1 - mf, seen(fo.cam, C0.x + 40 * k, C0.y + 30 * k, C0.x + C0.w - 40 * k, C0.y + 76 * k)), compA = seen(fo.cam, Gc.INPUT.x, Gc.INPUT.y, Gc.INPUT.x + Gc.INPUT.w, Gc.INPUT.y + Gc.INPUT.h);- drawChatFrame(ctx, { typed, caret, placeholder: spec.placeholder ?? "Describe what you want…", genPress: pr, genHot: hot, title: spec.title, subtitle: spec.subtitle ?? "", genLabel: spec.genLabel, accent: ACC, head: headA, composer: compA, composerGeom: Gc === G ? undefined : Gc }, G);- const sc = scrollAt(f), rest = (1 - mf) * (1 - fo.lean), [, cyT, , chH] = TH.clip;+ const cardSpan = (i: number) => Math.max(CARD, 26 * k + LK.measure.text((spec.asks[i] as PlateAsk).label, G.px.label));+ const chat = (ctx: Ctx, env: Env, f: number, typed: string, caret: boolean, pr: number, hot: number, fo: Focus = { lean: 0, keep: -1, cam: CAM.home }, Gc: ChatGeom = G) => {+ // (the thread stays drawn under the composer's close-up: it used to fade out there and back in as the+ // camera eased out, and a thread fading in while the camera moves is content swapped, not carried: a+ // slide cut to motionscan. What the close-up's edge would cut, seen() fades as the camera reaches it.)+ // (the header recedes with the rest of the window while the camera leans on a card, as the thread does:+ // left at 60 %, the travel that follows carried it off the frame's top edge in a frame, a cut)+ // (clean: the window stays whole and opaque while the camera leans on a card, the lean a pure camera move;+ // the header and the thread receding in brand ink were see-through fills to layerscan and, with the move,+ // most of a sparse frame replaced in 0.1 s: a slide cut to motionscan)+ const recede = clean ? 0 : fo.lean;+ const C0 = G.CHAT, headA = (1 - recede) * seen(fo.cam, C0.x + 40 * k, C0.y + 30 * k, C0.x + C0.w - 40 * k, C0.y + 76 * k), compA = seen(fo.cam, Gc.INPUT.x, Gc.INPUT.y, Gc.INPUT.x + Gc.INPUT.w, Gc.INPUT.y + Gc.INPUT.h);+ drawChatFrame(ctx, { typed, full: ((a) => (isChat(a) ? a.prompt : undefined))(spec.asks[askOf(f)]), caret, placeholder: spec.placeholder ?? "Describe what you want…", genPress: pr, genHot: hot, title: spec.title, subtitle: spec.subtitle ?? "", genLabel: LK.shape.buttonLabel ?? spec.genLabel, accent: ACC, head: headA, composer: compA, composerGeom: Gc === G ? undefined : Gc }, G);+ const sc = scrollAt(f), rest = 1 - recede, [, cyT, , chH] = TH.clip;ctx.save(); ctx.beginPath(); ctx.rect(...TH.clip); ctx.clip();items.forEach((it, k) => {if (f < it.at) return;const y = ys[k] - sc; if (y > VIEW_BOTTOM || y + it.h < (ZONES ? cyT : 100)) return; // (on 9x16 an item scrolled wholly under the window's top is not drawn)// what of it the thread's window shows, and whether the camera shows all of thatconst vy0 = Math.max(y, cyT), vy1 = Math.min(y + it.h, cyT + chH), x0 = it.card !== undefined ? TH.cardX : TH.bubbleR - TH.bubbleMaxW, x1 = it.card !== undefined ? TH.cardX + (ZONES ? cardSpan(it.card) : CARD) : TH.bubbleR;- const A = (it.card === fo.keep ? 1 - mf : rest) * (vy1 > vy0 ? seen(fo.cam, x0, vy0, x1, vy1) : 1); if (A < 0.01) return;+ const A = (it.card === fo.keep ? 1 : rest) * (vy1 > vy0 ? seen(fo.cam, x0, vy0, x1, vy1) : 1); if (A < 0.01) return;if (it.user !== undefined) {- ctx.globalAlpha = A * ramp(f, it.at, it.at + 8); ctx.font = SANS(500, G.px.bubble);- const bw = Math.max(...it.lines!.map((l) => ctx.measureText(l).width)) + 2 * TH.bubblePad; ctx.fillStyle = PAL.chip; rr(ctx, TH.bubbleR - bw, y, bw, it.h - 2, TH.bubbleRad); ctx.fill();- ctx.fillStyle = PAL.ink; ctx.textBaseline = "middle"; it.lines!.forEach((l, j) => ctx.fillText(l, TH.bubbleR - bw + TH.bubblePad, y + TH.bubbleH / 2 + j * TH.bubbleLineH)); ctx.globalAlpha = 1;+ // the sent prompt rises into the thread from the composer it left (a bubble that only faded in was a dissolve to motionscan)+ const by = y + (1 - out3(ramp(f, it.at, it.at + 14))) * it.h * 0.3;+ ctx.globalAlpha = A * ramp(f, it.at, it.at + 3); ctx.font = LK.fonts.text(500, G.px.bubble);+ // (a custom look's bubble: its colours, square corners, or no bubble at all, the words alone)+ const bw = Math.max(...it.lines!.map((l) => ctx.measureText(l).width)) + 2 * TH.bubblePad, BS = LK.custom ? LK.shape.bubble : "rounded";+ if (BS !== "none") { ctx.fillStyle = LK.chat.bubble?.fill ?? PAL.chip; rr(ctx, TH.bubbleR - bw, by, bw, it.h - 2, BS === "square" ? 4 * k : TH.bubbleRad); ctx.fill(); }+ ctx.fillStyle = LK.chat.bubble?.ink ?? PAL.ink; ctx.textBaseline = "middle"; it.lines!.forEach((l, j) => ctx.fillText(l, TH.bubbleR - bw + TH.bubblePad, by + TH.bubbleH / 2 + j * TH.bubbleLineH)); ctx.globalAlpha = 1;} else {const i = it.card!, a = spec.asks[i] as PlateAsk;const d = T[i].drop, b = T[i].base;{ const py0 = Math.max(y + TH.cardDy, cyT), py1 = Math.min(y + TH.cardDy + CARD, cyT + chH); ctx.globalAlpha = A; if (py1 > py0) probeRect(ctx, env, TH.cardX, py0, CARD, py1 - py0, `answer card ${i}`); } // the part the thread's window shows- inkCard(ctx, TH.cardX, y + TH.cardDy, CARD, f, { t0: b + d.t0, land: b + d.land, full: b + d.full }, plateLayer(env, `ask${i}`, a.plate, plateFrame(i, f), 1080), y + TH.cardDy - 30 * k > cyT ? a.label : "", a.crop, G, growAt(i)); // a byline scrolled under the window's top is not drawn at all+ inkCard(ctx, TH.cardX, y + TH.cardDy, CARD, f, { t0: b + d.t0, land: b + d.land, full: b + d.full }, plateLayer(env, `ask${i}`, a.plate, plateFrame(i, f), 1080), a.label, a.crop, G, growAt(i), clamp((y + TH.cardDy - 30 * k - cyT) / (14 * k))); // a byline nearing the window's top fades out, dot and words togetherctx.globalAlpha = 1;}});@@ -243,8 +507,11 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {// with a margin on every sideconst HOME = CAM.home;const inView = (c: P, z: number): P => { const hw = W / 2 / z, hh = H / 2 / z; return [clamp(c[0], Math.min(hw, W - hw), Math.max(hw, W - hw)), clamp(c[1], Math.min(hh, H - hh), Math.max(hh, H - hh))]; };- // (a phone composer is nearly the frame's width, so there the close-up IS the window: the empty state, creeping 3 %)- const MZ = L.phone ? 1 : Math.max(1, Math.min(CAM.macroZ, (0.9 * W) / (G.INPUT.w + 48 * k), (0.8 * H) / (G.INPUT.h + 48 * k)) / 1.03);+ // A later ask is typed with the whole room in view, the camera creeping 3 % toward its composer (as it+ // always was on a phone, where the composer is nearly the frame's width). A close-up on the composer had+ // to ease back out before the press, and the thread above it could only arrive whole: each earlier card+ // stayed hidden until the move had brought it wholly inside the view, then appeared in two frames (a+ // slide cut to motionscan, and a pop to the eye).const leanOn = (i: number): Cam => {const cy = cardY(i, T[i].base + T[i].len), lab = 44 * k, box = { x: TH.cardX, y: cy - lab, w: ZONES ? cardSpan(i) : CARD, h: CARD + lab }, m = 36 * k;if (ZONES) {@@ -258,68 +525,78 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {return { c: [clamp(c[0], box.x + box.w + m - hw, box.x - m + hw), clamp(c[1], box.y + box.h + m - hh, box.y - m + hh)], z };};type CaretFn = (typed: string) => P;+ // the hook's creep: 2 % on a wide frame, 4 % on 9x16, 5 % there in the clean look (its composer, the dock+ // too, is narrower, so its typing changed too little of the tall frame: dead air to the gate, frames 13 to 46)+ const HOOK_CREEP = 1 + (ZONES ? (clean ? 0.05 : 0.04) : 0.02);+const prevChat = (i: number) => i > 0 && isChat(spec.asks[i - 1]) && T[i].tin === 0;- // the empty state: on a phone the first ask's composer starts in the middle of the empty thread (the- // way a chat app opens) and docks at the bottom as Generate is pressed; the hook is the prompt, centred- // THE HOOK: the first prompt is the hero. It is typed in a big composer in the middle of the frame- // (at least 64 px type on a phone frame, 56 px on 16x9, wrapping to 2-3 lines, never clipped),- // which shrinks and docks at the bottom of the chat as Generate is pressed.- const HERO = (() => {- if (!isChat(spec.asks[0])) return null;- const prompt = spec.asks[0].prompt, min = L.phone ? 64 : 56, inW = ZONES ? G.CHAT.w - 24 : Math.min(L.phone ? W * 0.9 : W * 0.72, G.CHAT.w - 60 * k); // most of the width, inside the chat window (on 9x16 all of it: the window is narrower there)- for (let px = L.phone ? 76 : 68; px >= min; px -= 2) {- const kh = px / 34, genW = 166 * kh, textW = inW - 44 * kh - genW - 44 * kh, lines = wrapEst(prompt, px, textW).length;- if (lines > 3 && px > min) continue;- if (lines > 3) throw new Error(`launchTemplate ${shape}: the first prompt "${prompt}" needs ${lines} lines at the hook's ${min} px; shorten it (the hook must read muted in the first 2 s)`);- // centred in the frame, or on 9x16 in the chat window (which is centred in the safe rectangle)- const h = 104 * kh + (lines - 1) * Math.round(px * 1.3), fake = ZONES- ? { x: G.CHAT.x + (G.CHAT.w - inW) / 2 - 60 * kh, y: G.CHAT.y + G.CHAT.h / 2 - H * 0.5, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh }- : { x: (W - inW) / 2 - 60 * kh, y: 0, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh };- const g = chatGeom(fake, kh, { ...G.px, gen: 24 * kh }, px, lines, genW);- return { ...g, CHAT: G.CHAT, theme: G.theme, drop: G.drop, iris: G.iris } as ChatGeom;- }- return null;- })();+ // (the drawn dock's two sets of line breaks: the hook's, then halfway, as its rows change, the dock's own, kept+ // to the landing; a one-line dock never wraps)+ const HERO_WRAP = HERO ? { px: HERO.TEXT.px, maxW: HERO.GEN.x - 20 * HERO.k - HERO.TEXT.x } : undefined;+ const DOCK_WRAP = { px: G.TEXT.px, maxW: G.wrap > 0 ? G.GEN.x - 20 * G.k - G.TEXT.x : Infinity };const heroAt = (i: number, l: number): ChatGeom => {if (!HERO || i !== 0) return G;- const u = expo(ramp(l, T[i].b - 4, T[i].down)); if (u >= 1) return G;+ if (clean) { // the clean dock: a glide down whole, at its own size (CLEAN_DOCK)+ const a0 = T[i].b + CLEAN_DOCK.at, q1 = glide(ramp(l, a0, a0 + CLEAN_DOCK.move));+ if (q1 >= 1) return G;+ return scaledComposer(HERO, DOCK_S, lerpP(footOf(HERO), footOf(G), q1));+ }+ const u = inOut(ramp(l, T[i].b + DOCK_AT, T[i].b + DOCK_AT + DOCK_LEN)); if (u >= 1) return G;const mix = (a: number, b: number) => a + (b - a) * u, R = <T extends Record<string, number>>(a: T, b: T) => Object.fromEntries(Object.keys(a).map((key) => [key, mix(a[key], b[key])])) as T;+ // (wrapped as the hook, then as the dock, never afresh at each eased width: words jumped between lines three+ // times on the move; now the breaks change once, halfway, with the composer's rows)const dockLines = Math.max(1, G.wrap);- return { ...G, INPUT: R(HERO.INPUT, G.INPUT), GEN: R(HERO.GEN, G.GEN), TEXT: R(HERO.TEXT, G.TEXT), k: mix(HERO.k, G.k), px: R(HERO.px, G.px), lineH: mix(HERO.lineH, G.lineH), wrap: u < 0.5 ? HERO.wrap : dockLines };+ return { ...G, INPUT: R(HERO.INPUT, G.INPUT), GEN: R(HERO.GEN, G.GEN), TEXT: R(HERO.TEXT, G.TEXT), k: mix(HERO.k, G.k), px: R(HERO.px, G.px), lineH: mix(HERO.lineH, G.lineH), wrap: u < 0.5 ? HERO.wrap : dockLines, wrapAs: u < 0.5 ? HERO_WRAP : DOCK_WRAP };};- // `lean` (0..1) is how far the camera leans in, `macro` how close it is on the composer; the corner- // mark steps aside while it leans, since the lean carries the composer under the corner- const camAt = (_caret: CaretFn, f: number, i: number): { cam: Cam; lean: number; macro: number; keep: number } => {+ // `lean` (0..1) is how far the camera leans in; the corner mark steps aside while it leans, since the+ // lean carries the composer under the corner+ const camAt = (_caret: CaretFn, f: number, i: number): { cam: Cam; lean: number; keep: number } => {const t = T[i], l = f - t.base;- // the close-up creeps in while the words arrive: the frame is never a still- // (the hero hook is its own close-up: the camera holds the whole frame, creeping 2 %)- const hero = !!HERO && i === 0, mz = hero ? 1 + 0.02 * ramp(l, -20, t.b) : MZ * (1 + 0.03 * ramp(l, -20, t.b));- // (9x16: the creep is about the window's centre for the hook, the composer's otherwise, so neither moves toward a zone)- const macro: Cam = ZONES ? { c: inView(about(hero ? [G.CHAT.x + G.CHAT.w / 2, G.CHAT.y + G.CHAT.h / 2] : [G.INPUT.x + G.INPUT.w / 2, G.INPUT.y + G.INPUT.h / 2], mz), mz), z: mz } : { c: inView(hero ? HOME.c : [G.INPUT.x + G.INPUT.w / 2, G.INPUT.y + G.INPUT.h / 2], mz), z: mz };- if (prevChat(i) && l < 16) { const q = inOut(ramp(l, 0, 16)); return { cam: camLerp(leanOn(i - 1), macro, q), lean: 1 - q, macro: q, keep: i - 1 }; }- if (l > t.drop.full - 10) { const q = inOut(ramp(l, t.drop.full - 10, t.len)); return { cam: camLerp(HOME, leanOn(i), q), lean: q, macro: 0, keep: i }; }- const w = l < t.b - 4 ? 1 : 1 - expo(ramp(l, t.b - 4, t.down));- return { cam: l < t.b - 4 ? macro : camLerp(macro, HOME, expo(ramp(l, t.b - 4, t.down))), lean: 0, macro: w, keep: -1 };+ // the room, creeping in while the words arrive and on through the press: the frame is never a still (a+ // camera that stopped as the pointer arrived left two identical frames before Generate went down, a+ // freeze to the gate). The hook creeps 2 % on the whole frame (4 % on 9x16, where typing alone changes too+ // little of a tall frame to read as motion), a later ask 3 % toward its composer.+ const hero = !!HERO && i === 0, mz = hero ? 1 + (HOOK_CREEP - 1) * ramp(l, -20, t.up + 10) : 1 + 0.03 * ramp(l, -20, t.up + 10);+ // (9x16: the creep is about the window's centre for the hook, the composer's otherwise, so neither moves toward a zone;+ // on a wide frame it is about the window's bottom right corner, so the window never grows into the corner mark beside it)+ const room: Cam = ZONES ? { c: inView(about(hero ? [G.CHAT.x + G.CHAT.w / 2, G.CHAT.y + G.CHAT.h / 2] : [G.INPUT.x + G.INPUT.w / 2, G.INPUT.y + G.INPUT.h / 2], mz), mz), z: mz } : { c: inView(about([G.CHAT.x + G.CHAT.w, G.CHAT.y + G.CHAT.h], mz), mz), z: mz };+ // (from the card before to this composer: in-out until the settle begins, never a 16-frame whip)+ if (prevChat(i) && l < t.b - 8) { const q = inOut(ramp(l, 0, t.b - 8)); return { cam: camLerp(leanOn(i - 1), room, q), lean: 1 - q, keep: i - 1 }; }+ const lean0 = Math.max(t.drop.full - 10, cardSettled(i));+ // (clean: when a travel or the end card follows, the lean is still moving as the ask ends, so the camera+ // never crawls to rest on a sparse frame before it moves again: its last slow frames, a near-still camera+ // over thin type, replaced most of the frame in 0.1 s with too little move to explain it, a slide cut)+ const leanEnd = clean && !(i < n - 1 && T[i + 1].tin === 0) ? t.len + 12 : t.len;+ if (l > lean0) { const q = inOut(ramp(l, lean0, leanEnd)); return { cam: camLerp(room, leanOn(i), q), lean: q, keep: i }; }+ return { cam: room, lean: 0, keep: -1 };};// the same camera without a canvas (for the sound's pan): the caret from the build-time width estimateconst caretEst: CaretFn = (typed) => {- if (G.wrap > 0) { const ls = wrapEst(typed, G.TEXT.px, G.GEN.x - 20 * k - G.TEXT.x); return [G.TEXT.x + estWidth(ls[ls.length - 1], G.TEXT.px), G.TEXT.base + (ls.length - 1) * G.lineH - 0.35 * G.TEXT.px]; }- return [G.TEXT.x + estWidth(typed, G.TEXT.px), G.TEXT.base - 12];+ if (G.wrap > 0) { const ls = LK.wrap(typed, G.TEXT.px, G.GEN.x - 20 * k - G.TEXT.x); return [G.TEXT.x + LK.measure.text(ls[ls.length - 1], G.TEXT.px), G.TEXT.base + (ls.length - 1) * G.lineH - 0.35 * G.TEXT.px]; }+ return [G.TEXT.x + LK.measure.text(typed, G.TEXT.px), G.TEXT.base - 12];};- const pointerPath = (ctx: Ctx, l: number, t: { b: number; down: number; up: number }, on: P, pr: number) => {- const off: P = CAM.pointerOff;- if (l >= t.b - 4 && l < t.up + 24) pointer(ctx, l < t.up + 4 ? lerpP(off, on, out3(ramp(l, t.b - 4, t.down))) : lerpP(on, off, inOut(ramp(l, t.up + 4, t.up + 24))), pr * 0.8, CAM.pointerS);+ // THE POINTER comes in for the press (from `from`, off the frame), and once the press is up it eases a+ // step aside, off the button's word, and rests there for the rest of the ask: a hand that clicked and let+ // go. It used to glide back out of frame and read as drifting into empty space after every click.+ const pointerPath = (ctx: Ctx, l: number, t: { b: number; down: number; up: number }, on: P, pr: number, from: P = CAM.pointerOff, restAt?: P) => {+ if (l < t.b - 4) return;+ const rest: P = restAt ?? [on[0] + 26 * k, on[1] + 30 * k];+ // (it arrives still moving a little, and the press stops it: an out-cubic came to rest a frame early and+ // left two identical frames before the press at 60 fps)+ const arrive = (q: number) => 0.85 * out3(q) + 0.15 * q;+ pointer(ctx, l < t.up + 4 ? lerpP(from, on, arrive(ramp(l, t.b - 4, t.down))) : lerpP(on, rest, inOut(ramp(l, t.up + 4, t.up + 22))), pr * 0.8, CAM.pointerS, LK.pointer);};const chatScene = (ctx: Ctx, env: Env, f: number, i: number) => {- const t = T[i], l = f - t.base, Gc = heroAt(i, l), caret: CaretFn = (s) => caretAt(ctx, s, Gc);- const { cam, lean, macro, keep } = camAt(caret, f, i);+ const t = T[i], l = f - t.base, Gc = heroAt(i, l), caret: CaretFn = (s) => caretAt(ctx, s, Gc, (spec.asks[i] as PlateAsk).prompt);+ const { cam, lean, keep } = camAt(caret, f, i);useCam(ctx, env, cam);const typed = typedAt((spec.asks[i] as PlateAsk).prompt, l, t.times), pr = press(l, t.down, t.up);- chat(ctx, env, f, l < t.up ? typed : "", l < t.up, pr, ramp(l, t.down - 10, t.down - 2), { macro, lean, keep, cam }, Gc);- // the pointer comes in for the press and glides back out; it never pops- pointerPath(ctx, l, t, [Gc.GEN.x + Gc.GEN.w / 2 + 18 * Gc.k, Gc.GEN.y + Gc.GEN.h / 2 + 6 * Gc.k], pr);+ chat(ctx, env, f, l < t.up ? typed : "", l < t.up, pr, ramp(l, t.down - 10, t.down - 2), { lean, keep, cam }, Gc);+ // the pointer comes in for the press and glides back out; it never pops (it fades as the camera leans on+ // the new card, so the travel that follows starts without it instead of dropping it in one frame)+ { const pa = keep === i ? 1 - lean : 1; if (pa > 0.01) { ctx.globalAlpha = pa; pointerPath(ctx, l, t, [Gc.GEN.x + Gc.GEN.w / 2 + 18 * Gc.k, Gc.GEN.y + Gc.GEN.h / 2 + 6 * Gc.k], pr); ctx.globalAlpha = 1; } }// the mark is gone BEFORE the lean moves the composer under it, and back only once the camera has left- const show = lean > 0 && l > ASK / 2 ? 1 - ramp(l, t.drop.full - 18, t.drop.full - 10) : prevChat(i) && l < 24 ? ramp(l, 16, 24) : 1;+ const show = lean > 0 && l > ASK / 2 ? 0 : l > ASK / 2 && l > t.drop.full - 18 ? 1 - ramp(l, t.drop.full - 18, t.drop.full - 10) : prevChat(i) && l < t.b ? ramp(l, t.b - 8, t.b) : 1;if (show > 0) { ctx.globalAlpha = show; bug(ctx, env); ctx.globalAlpha = 1; }};// ---------------------------------------------------------------- the product UI, a film in a card, and a split beat's words@@ -338,20 +615,55 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const fit = ZONES ? Math.max(1, Math.min((0.94 * SAFE.w) / win.w, (0.92 * SAFE.h) / win.h)) : Math.max(1, Math.min((0.94 * W) / win.w, (0.92 * H) / win.h));const toward = (z: number): Cam => (ZONES ? { c: inView(about(wc, z), z), z } : { c: inView(lerpP(HOME.c, wc, clamp((z - 1) / (fit - 1 || 1))), z), z });if (l >= t.down) return toward(1 + (fit - 1) * 0.9 * inOut(ramp(l, t.down, t.len + 40))); // from the press on, never resting; still moving when the ask ends- const open = toward(1 + (fit - 1) * 0.5 * ramp(l, -20, t.b)); // already creeping on frame 0- return camLerp(open, HOME, expo(ramp(l, t.b - 4, t.down)));+ // (on 9x16 a window that already fills the safe rectangle has little fit left to creep into, and the+ // typing alone changed too little of a tall frame: dead air to the gate. There it creeps 6 % at least+ // while the words arrive, about its centre: fitted to 94 % of the safe rectangle, it stays inside it+ // with its padding, and eases back to the whole window for the press)+ const open = toward(1 + (ZONES ? Math.max((fit - 1) * 0.35, 0.06) : (fit - 1) * 0.35) * ramp(l, -20, t.b)); // already creeping on frame 0+ // the ease back for the press is one long in-out, never a snap: an expo here took most of the zoom in+ // 3 frames, and a text-dense window zoomed that fast is replaced pixel for pixel (a slide cut to+ // motionscan). Kept this gentle, typing, ease-back and press read as ONE beat of one screen, not+ // three stills of the same layout (motionscan repeat: the carousel)+ return camLerp(open, HOME, inOut(ramp(l, t.b - 24, t.down)));+ };+ let quietGround = false; // inside a travel the ground is already laid, once, under both places+ const ground = (ctx: Ctx, env: Env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); if (quietGround) return; ctx.fillStyle = PAL.bg; ctx.fillRect(0, 0, W, H); };+ // where the pointer rests after a product's click: up off the window, just above its header, so it never+ // settles on a row's figure (down and right of the button, as the chat's rest, it sat on "$1,208" on 9:16)+ const uiRest = (i: number) => {+ const a = spec.asks[i] as UiAsk, r = panelOf(i), [ax, ay] = uiActionAt(r, a.ui, minPx), on: P = [ax + 14 * k, ay + 8 * k], win = uiWindow(r, a.ui, minPx);+ return { i, tip: [on[0] + 20 * k, win.y - 29 * CAM.pointerS - 10 * k] as P, win, s: CAM.pointerS };};- const ground = (ctx: Ctx, env: Env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAL.bg; ctx.fillRect(0, 0, W, H); };const uiScene = (ctx: Ctx, env: Env, f: number, i: number) => {const a = spec.asks[i] as UiAsk, t = T[i], l = f - t.base, r = panelOf(i), pr = press(l, t.down, t.up);ground(ctx, env); if (a.split?.length) push(ctx, env, r, l, t.len, t.drop.t0); else useCam(ctx, env, uiCam(i, l));const typed = a.prompt ? typedAt(a.prompt, l, t.times) : "";{ const w = uiWindow(r, a.ui, minPx); probeRect(ctx, env, w.x, w.y, w.w, w.h, "product window"); }drawProductUI(ctx, r, a.ui, { f: l, t0: t.drop.t0 }, THEME, { minPx, typed, caret: !!a.prompt && l < t.down, press: pr, hot: ramp(l, t.down - 10, t.down - 2), accent: ACC });- pointerPath(ctx, l, t, (([x, y]) => [x + 14 * k, y + 8 * k] as P)(uiActionAt(r, a.ui, minPx)), pr);- if (a.split?.length) splitWords(ctx, env, a.split, l, t.tin);+ // (into a product's action from the right, along its header: a path up from the corner crossed the rows and paused on a figure)+ { const [ax, ay] = uiActionAt(r, a.ui, minPx), q = uiRest(i); pointerPath(ctx, l, t, [ax + 14 * k, ay + 8 * k], pr, [ax + 0.5 * W, ay - 20 * k], q.tip); }+ if (a.split?.length) splitWords(ctx, env, a.split, l, wordsAt(t.tin), wordsOut(i, l));bug(ctx, env);};+ // TYPE ARRIVES WITH ITS PLACE AND LEAVES IN PLACE (clean). A split beat's words rise halfway through the+ // travel in (a word rising while the camera is still is a slide to motionscan; carried by the move it is+ // part of the move), and sink out (setType's out: typeExit, ease-in, 1.3x their size), bottom line first,+ // in the last SINK frames before the camera leaves, so no line is carried across a platform zone or+ // sliced by the frame's edge (framecheck zones, layerscan exits). The last ask's words stay: the end card+ // blooms over them.+ const SINK = 18; // 0.6 s: type leaves in 0.5 to 0.7 s (motion-grammar.md)+ const wordsAt = (tin: number) => Math.round(tin / 2);+ // 0..1 over the sink, staggered per line by sunk(). The last ask's words sink too, before the motif's+ // drop starts to swell, so the drop flies and the end card blooms over clear canvas, never over a word+ // (a fresh critic saw the drop land on the headline's last letter and the bloom eat it mid-word)+ // (the last ask's words finish sinking halfway through the drop's flight, still gone before it lands and the+ // end card blooms; they sink while the bead swells beside the product's action and the drop leaves it, away+ // from them. Gone before the swell, and then before the flight, they left a phone frame its small product+ // window alone for over half a second: "6 text blocks packed into 25 % of the frame")+ const sinkAt = (i: number) => (i < n - 1 ? T[i].len - SINK - 1 : MOTIF ? T[i].len - Math.floor(DL / 2) - SINK - 1 : T[i].len);+ const wordsOut = (i: number, l: number) => (i < n - 1 || MOTIF ? (l - sinkAt(i)) / SINK : 0);+ /** Line j of nL leaving at sink progress q: the bottom line first, each in its own share of the sink with no overlap, so a sinking line never drops into the band of a line still leaving (a reader sees the two run together as one line). */+ const sunk = sinkOf;const filmCard = (i: number): Rect => { const a = spec.asks[i] as FilmAsk, r = panelOf(i), s = Math.min(r.w / a.film.meta.W, r.h / a.film.meta.H), w = a.film.meta.W * s, h = a.film.meta.H * s; return { x: r.x + (r.w - w) / 2, y: r.y + (r.h - h) / 2, w, h }; };const filmScene = (ctx: Ctx, env: Env, f: number, i: number) => {const a = spec.asks[i] as FilmAsk, t = T[i], l = f - t.base, c = filmCard(i), from = a.from ?? 0, to = a.to ?? a.film.meta.durationFrames - 1;@@ -360,20 +672,33 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {ctx.save(); rr(ctx, c.x, c.y, c.w, c.h, 22 * k); ctx.clip();ctx.drawImage(plateLayer(env, `film${i}`, a.film, lerp(from, to, ramp(l, 0, t.len - 1)), Math.round(c.w * env.scale)).canvas, c.x, c.y, c.w, c.h);ctx.restore();- if (a.split?.length) splitWords(ctx, env, a.split, l, t.tin);+ if (a.split?.length) splitWords(ctx, env, a.split, l, wordsAt(t.tin), wordsOut(i, l));bug(ctx, env);};// words in their own column beside the live UI (stacked above it on a phone): sized to the column, written or set on// the words are the design of the beat: as large as their column allows (set type is wider than it is tall, so its cap is higher)- const wordsCap = clean ? L.split.wordsPx * 1.6 : L.split.wordsPx, wOf = (t: string, sz: number) => (clean ? estWidth(t, sz) * 1.12 : measure(t, sz));- const splitLines = (lines: TypeLine[]) => { const col = L.split.words, out: TypeLine[] = []; for (const ln of lines) { const size = Math.min(wordsCap, (col.w / wOf(ln.text, 100)) * 100); if (size >= wordsCap * 0.62 || !ln.text.includes(" ")) out.push(ln); else wrapEst(ln.text, wordsCap, col.w * 1.05).forEach((t) => out.push({ ...ln, text: t })); } return out; };- const splitWords = (ctx: Ctx, env: Env, lines0: TypeLine[], l: number, tin: number) => {- const col = L.split.words, lines = splitLines(lines0), size = Math.min(wordsCap, ...lines.map((x) => (col.w / wOf(x.text, 100)) * 100)), gap = size * (clean ? 1.08 : 1.3);+ const wordsCap = clean ? L.split.wordsPx * 1.6 : L.split.wordsPx, wOf = (t: string, sz: number) => (clean ? LK.measure.display(t, sz) : measure(t, sz));+ const splitLines = (lines: TypeLine[]) => { const col = L.split.words, out: TypeLine[] = []; for (const ln of lines) { const size = Math.min(wordsCap, (col.w / wOf(ln.text, 100)) * 100); if (size >= wordsCap * 0.62 || !ln.text.includes(" ")) out.push(ln); else LK.wrapDisplay(ln.text, wordsCap, col.w * 1.05).forEach((t) => out.push({ ...ln, text: t })); } return out; };+ // ...and as tall as their column allows: on a phone the column is a third of the window, and the+ // scaffold's stand-in words, wrapped to four lines at the width's size, ran down over the product window+ // (framecheck: text over text, text over the window's edge). Words too tall for it are set smaller and+ // wrapped again at that size until they fit; under the phone-safe size it is an error+ const splitFit = (lines0: TypeLine[]): { lines: TypeLine[]; size: number } => {+ const col = L.split.words, gk = clean ? 1.08 : 1.3, tall = (nL: number, sz: number) => (L.split.vertical ? sz * 1.25 : sz * 1.05) + (nL - 1) * sz * gk;+ const at = (cap: number) => { const ls: TypeLine[] = []; for (const ln of lines0) { if ((col.w / wOf(ln.text, 100)) * 100 >= cap * 0.62 || !ln.text.includes(" ")) ls.push(ln); else LK.wrapDisplay(ln.text, cap, col.w * 1.05).forEach((t) => ls.push({ ...ln, text: t })); } return { lines: ls, size: Math.min(cap, ...ls.map((x) => (col.w / wOf(x.text, 100)) * 100)) }; };+ const first = { lines: splitLines(lines0), size: 0 }; first.size = Math.min(wordsCap, ...first.lines.map((x) => (col.w / wOf(x.text, 100)) * 100));+ if (tall(first.lines.length, first.size) <= col.h) return first;+ for (let cap = wordsCap * 0.95; cap >= L.split.wordsPx * 0.5; cap *= 0.95) { const f = at(cap); if (tall(f.lines.length, f.size) <= col.h && f.size >= minWords) return f; }+ throw new Error(`launchTemplate ${shape}: the split words "${lines0.map((x) => x.text).join(" ")}" do not fit their column (${Math.round(col.w)} x ${Math.round(col.h)} px) at the phone-safe size; use fewer words`);+ };+ const minWords = L.type.minPx * 0.75;+ const splitWords = (ctx: Ctx, env: Env, lines0: TypeLine[], l: number, tin: number, out = 0) => {+ const col = L.split.words, { lines, size } = splitFit(lines0), gap = size * (clean ? 1.08 : 1.3);const y0 = L.split.vertical ? col.y + size : col.y + col.h / 2 - ((lines.length - 1) * gap) / 2 + size * 0.35;lines.forEach((x, j) => {const p = ramp(l, tin + j * 12, tin + 18 + j * 12);- if (clean) setType(ctx, env, x.text, col.x, y0 + j * gap, size, p, { color: x.color === C.accent ? THEME.accent : x.color ?? PAL.ink, weight: 800 });- else writeOn(ctx, env, x.text, col.x, y0 + j * gap, size, p, x.style, { color: x.color, align: "left", seed: 21 + j });+ if (clean) { if (lineShown(ctx, env, x.text, col.x, y0 + j * gap, size)) setType(ctx, env, x.text, col.x, y0 + j * gap, size, p, { font: LK.fonts.display, color: x.color === C.accent ? THEME.accent : x.color ?? PAL.ink, weight: 800, out: sunk(out, j, lines.length) }); }+ else if (lineShown(ctx, env, x.text, col.x, y0 + j * gap, size, measure(x.text, size))) writeOn(ctx, env, x.text, col.x, y0 + j * gap, size, p, x.style, { color: x.color, align: "left", seed: 21 + j, out: sunk(out, j, lines.length), tool: PEN });});};// where a UI ask's world point is on screen at content frame f (its camera, or the split panel's push)@@ -382,30 +707,198 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const bloomOpts = clean ? { shape: "circle" as const, rim: 0, bg: PAL.bg } : {};const CLEAN_ST = 12; // a clean word page's lines follow each other closer: set type settles sooner than a brush+ // ---------------------------------------------------------------- the clean preset's travels and word pages+ // where the next place is: below on a wide frame; on a tall one to the left, the one side of a phone+ // frame with no platform zone, so everything ARRIVES clear of the zones (strings that arrived through the+ // right-hand column popped in on the last frame). Tall places sit one safe width apart, not one frame+ // width: they overlap only in the right-hand column, which holds nothing at rest, so the next place's+ // content is in view from the first frame of the move and no frame between two places is empty. Either+ // way no travel is longer than one frame width, so TRV holds for every shape.+ // (a wide or square frame alternates between travels: down, then up, then down, in the order the seams come.+ // Every travel going down read as one move repeated: "two travels from below", a fresh critic. Sideways+ // was tried: a wide place a frame width away is wholly out of view until the move brings it in, so the+ // frame emptied and then filled, a slide cut to motionscan)+ const SEAMS: string[] = []; spec.asks.forEach((_, i) => { if (i > 0 && TIN[i] > 0) SEAMS.push(`ask:${i}`); if (i < n - 1 && words[i]?.length) SEAMS.push(`page:${i}`); });+ const axOf = (seam: string): P => (W < H ? [-(SAFE.x + SAFE.w), 0] : SEAMS.indexOf(seam) % 2 ? [0, -H] : [0, H]);+ // on a phone shape the UI's own strings (its labels and figures) that the travel carries through a+ // platform zone (the top band, the bottom band, the right-hand column) are not drawn there: each fades,+ // whole, as it reaches one, as the chat's seen() does. The left side has no zone; there the frame's edge+ // is a clean cut while the camera moves. Set words never travel (wordsOut, the page's sink).+ // (a string fades over the ZONE_BAND px before it reaches a zone, so it leaves in about five frames of the+ // travel, never in one. The band is measured from where the string rests (the place at its own spot, d = 0):+ // one that rests nearer the zone than the band fades from its rest distance, so nothing near a safe edge+ // dims the moment a travel starts or snaps back when it ends. Inside a zone it is never drawn.)+ const inSafe = (y0: number, x1: number, y1: number) => x1 <= SAFE.x + SAFE.w && y0 >= SAFE.y && y1 <= SAFE.y + SAFE.h;+ // (on a frame with no zones the drawn look fades a carried string the same way before the frame's own+ // top and bottom edges, so a byline never leaves in one frame there either; the clean look's strings are+ // its brand ink, which never goes see-through, so they stay cut by the edge as the camera carries them)+ const zoneFade = ZONES ? zoneFadeOf(SAFE) : clean ? undefined : zoneFadeOf({ x: 0, y: 0, w: W, h: H });+ /** A set line inside a travel on a phone shape: drawn whole only while it is wholly inside the safe area (else not at all, so no line is ever half in a zone). */+ const lineShown = (c: Ctx, env: Env, text: string, x: number, y: number, size: number, width = LK.measure.display(text, size)) => {+ if (!ZONES || !quietGround) return true;+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); const m = c.getTransform(), S = env.scale, w = width;+ const xs = [x, x + w].map((v) => (m.a * v + m.e) / S), ys = [y - size * 0.8, y + size * 0.25].map((v) => (m.d * v + m.f) / S);+ return inSafe(Math.min(...ys), Math.max(...xs), Math.max(...ys));+ };+ /** The camera travels from one place to the next over q 0..1: both drawn where they sit in the world, each inside its own frame-sized place. */+ // (the ground is laid once under both places, so where two places overlap neither paints over the other)+ // (`hidden`: the place it leaves ended with the corner mark stepped aside, as a chat ask's lean does; the+ // mark then comes back over the travel's second half, never popping in on its first frame)+ // (callers sample a travel at mid-frame, (l + 0.5) / length: its first frame then already moves off the+ // place's last frame, which a place held still (a chat ask's lean) drew identically, a frozen pair to the gate)+ const travel = (ctx: Ctx, env: Env, q: number, from: (c: Ctx) => void, to: (c: Ctx) => void, AX: P, hidden = false) => {+ const u = glide(q), side = (k: number, draw: (c: Ctx) => void) => {+ const d: P = [AX[0] * k, AX[1] * k]; if (Math.abs(d[0]) >= W || Math.abs(d[1]) >= H) return;+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.beginPath(); ctx.rect(d[0], d[1], W, H); ctx.clip();+ draw(placed(ctx, env, { d, fade: zoneFade })); ctx.restore();+ };+ ground(ctx, env);+ quietBug = quietGround = true; try { side(-u, from); side(1 - u, to); } finally { quietBug = quietGround = false; }+ const a = hidden ? ramp(q, 0.5, 0.9) : 1; if (a > 0) { ctx.globalAlpha = a; bug(ctx, env); ctx.globalAlpha = 1; }+ };+ // a word page as a place: the camera comes in to it as its lines rise into place at the margin, they are read, and+ // sink out (typeExit) as the camera starts to leave; the page creeps closer (6 %) all the time it is on+ const PAGE_ON = Math.round(TRV / 2); // local frame the first line starts to rise: halfway, at the travel's top speed, so the rise is part of the move+ // local frame the lines start to sink: on a frame with no zones as the travel out starts, so they sink as+ // the camera carries them off; on a phone so the last line is gone at the last frame before the move+ // could carry the widest line (the page's full measure, crept 3 %) into the right-hand column+ // (a phone's word page sets its lines to three quarters of the measure, from the same left margin: the+ // room it leaves before the right-hand column lets the lines sink while the camera already moves)+ const PAGE_MEASURE = ZONES ? 0.75 : 1;+ // A sideways travel (a tall frame) carries the page right, and two edges then cross its lines: the right-hand+ // column (or the frame's right edge) ahead of them, and behind them the left edge of the page's own place,+ // which the next place is uncovering. The lines are gone before the move reaches either: a line sliced by+ // the edge of its place reads as a cut, not a move (a fresh look at the drawn example's 9:16 page found+ // "IDEA IN." still standing, its first letter shaved off, as the chat came in from the left).+ const pageRoom = () => {+ const at = L.type.at, cx = at ? at[0] : W / 2, x0 = at ? at[0] - L.type.maxW / 2 : (W - L.type.maxW) / 2, right = cx + (x0 + L.type.maxW * PAGE_MEASURE - cx) * 1.03, left = cx + (x0 - cx) * 1.03;+ return Math.min((ZONES ? SAFE.x + SAFE.w : W) - right, left) - 2;+ };+ const pageOut = (i: number) => { // (word page i: the travel that leaves it is the one into ask i + 1)+ const AX = axOf(`ask:${i + 1}`);+ // a travel down: the lines sink as it starts, carried off with the camera. A calm brand's lines do not+ // sink: the camera carries them off whole. Sinking while carried they moved at the travel's pace plus+ // their own, past what calm allows on a wide frame (motionscan temperament, 30 px a frame against 28),+ // and sunk before the travel they left its first frames a blank page moving (identical frames to the gate)+ if (!AX[0]) return CALM ? TYPE + TRV : TYPE;+ const room = pageRoom();+ let l = 0; while (l < TRV && glide((l + 1) / TRV) * Math.abs(AX[0]) <= room) l++;+ return TYPE + l - SINK;+ };+ // (the drawn look's lines are written in ink, left on the same margin: a hand line is narrower than its+ // set width estimate, so it is measured by its own glyphs. Each takes 12 frames, 10 after the one before,+ // so the page is written by the time the travel lands: ink alone changes too little of a phone frame to+ // read as motion (the gate's dead air), and the page must be done moving before it holds to be read)+ const ST = clean ? CLEAN_ST : 10, WR = clean ? 18 : 12, lineW = (t: string, size: number) => (clean ? LK.measure.display(t, size) : measure(t, size));+ const pageFit = (lines: TypeLine[]) => {+ const nL = lines.length, at = L.type.at, x0 = at ? at[0] - L.type.maxW / 2 : (W - L.type.maxW) / 2, maxW = L.type.maxW * PAGE_MEASURE;+ const size = Math.min(nL === 1 ? 220 : 170, ...lines.map((l) => (maxW / lineW(l.text, 100)) * 100)), gap = size * (clean ? 1.12 : 1.3), y0 = (at ? at[1] : H / 2) - ((nL - 1) * gap) / 2 + size * 0.36;+ return { x0, y0, size, gap, c: (at ?? [W / 2, H / 2]) as P };+ };+ const pageSet = (n: number) => PAGE_ON + WR + (n - 1) * ST - (clean ? 9 : 0); // local frame the last line is set (set type's out-cubic settles to the pixel 9 frames early; a pen line is done when its last stroke is)+ const pageScene = (ctx: Ctx, env: Env, lines: TypeLine[], local: number, k: number) => {+ const PAGE_OUT = pageOut(k);+ ground(ctx, env);+ const g = pageFit(lines), c = placed(ctx, env, { z: 1 + 0.06 * ramp(local, 0, TYPE + TRV), c: g.c });+ lines.forEach((l, i) => {+ const y = g.y0 + i * g.gap, p = ramp(local, PAGE_ON + i * ST, PAGE_ON + WR + i * ST), out = sunk((local - PAGE_OUT) / SINK, i, lines.length);+ if (!lineShown(c, env, l.text, g.x0, y, g.size, lineW(l.text, g.size))) return;+ if (clean) setType(c, env, l.text, g.x0, y, g.size, p, { font: LK.fonts.display, color: l.color === C.accent ? THEME.accent : l.color ?? PAL.ink, weight: 800, out });+ else writeOn(c, env, l.text, g.x0, y, g.size, p, l.style, { color: l.color, align: "left", seed: 7 + i, out, tool: PEN });+ });+ bug(ctx, env);+ };+ // the place a travel into ask i leaves: the word page before it (still creeping), or the ask before it, on its last frame+ const fitted = words.map((w) => (w?.length ? fitWords(w, L) : null));+ // a word page is read from the frame its last line is set until its lines start to sink: that must be+ // the reading rule's time (readable.ts readS), or the beat is too short for its words+ fitted.forEach((wl, i) => {+ if (!wl || i >= n - 1) return;+ const need = Math.ceil(readS(wl.map((x) => x.text).join(" ")) * 30), have = Math.min(TYPE, pageOut(i)) - pageSet(wl.length); // (read until the sink, or until the travel carries the page off)+ if (have < need) throw new Error(`launchTemplate: the word page "${wl.map((x) => x.text).join(" ")}" is up ${(have / 30).toFixed(2)} s once set and needs ${(need / 30).toFixed(2)} s to be read (readS), after ${(TRV / 30).toFixed(1)} s of travel in and before its 0.6 s sink; raise typeBeats or use fewer words`);+ });+ const prevPlace = (c: Ctx, env: Env, i: number, l: number) => { const wl = fitted[i - 1]; if (wl) pageScene(c, env, wl, TYPE + l, i - 1); else sceneOf(c, env, T[i].base - 1, i - 1); };+// ---------------------------------------------------------------- the motif: the drop that becomes the mark's dotconst MOTIF = spec.motif !== false;- const titleSize = clean ? Math.min(L.end.titleMax * 1.6, (L.end.titleW / (estWidth(spec.title, 100) * 1.1)) * 100) : Math.min(L.end.titleMax, (L.end.titleW / measure(spec.title, 100)) * 100);+ // a split beat's words are read too: from the frame the last line is set until they have sunk (the frame+ // check reads a line until it leaves; a beat shorter than its words' reading time is an error here, early)+ spec.asks.forEach((a, i) => {+ if (isChat(a) || !a.split?.length) return;+ const lines = splitFit(a.split).lines, set = wordsAt(TIN[i]) + 18 + (lines.length - 1) * 12, sink = sinkAt(i);+ const text = a.split.map((x) => x.text).join(" "), need = Math.ceil(readS(text) * 30), have = sink + SINK - set;+ if (have < need) throw new Error(`launchTemplate: the split words "${text}" of ask ${i} are up ${(have / 30).toFixed(2)} s once set, to the end of their sink, and need ${(need / 30).toFixed(2)} s to be read (readS); raise ${i === n - 1 && spec.claimBar !== undefined ? "claimBar (a later bar for the end card)" : "askBeats"} or use fewer words`);+ });+ // THE LOGO SIGNS THE CLEAN END CARD (a look with a logo, the stacked card): it stands before the name on its+ // baseline, LOGO_H of the name's size tall, and the group (logo, name, dot) shares the name's width budget+ const END_LOGO = clean && spec.endCard !== "grid" ? LK.chat.logo : undefined, LOGO_H = 0.86, LOGO_GAP = 0.24;+ const logoW1 = END_LOGO ? (LOGO_H * END_LOGO.w) / END_LOGO.h + LOGO_GAP : 0; // per unit of the name's size+ const titleSize = clean ? Math.min(L.end.titleMax * 1.6, (L.end.titleW / ((LK.customDisplay ? LK.measure.display(spec.title, 100) : estWidth(spec.title, 100) * 1.1) + 100 * logoW1)) * 100) : Math.min(L.end.titleMax, (L.end.titleW / measure(spec.title, 100)) * 100);// the clean end card is ONE centred group with presence: the wordmark large, the line under it,// the install block, the footer, stacked and centred in the frame (the drawn one keeps its layout)const END_L = (() => {if (!clean) return L.end;// (9x16: measured on the safe rectangle's width and centred on its height)- const AW = ZONES ? SAFE.w - 24 : W, E = L.end, tp = E.taglinePx * 1.5, tl = wrapEst(spec.tagline, tp, AW * (ZONES ? 0.9 : 0.8)), tLH = Math.round(tp * 1.3);- const inst = installRows(spec.install, AW * 0.86 - 2 * E.padX, minPx, E.monoPx * 1.35), mono = inst.px, rowH = Math.round(mono * 2), ph = rowH * inst.rows.length + 50 * k;+ // (on a phone the card is centred on the frame's axis, which sits left of the safe rectangle's: each line+ // gets the width the axis leaves it inside that rectangle, 10 px clear on each side, never 90 % of the+ // whole safe width: a line set in a real face ran into the button column)+ const AW = ZONES ? SAFE.w - 24 : W, E = L.end, axisW = ZONES ? 2 * Math.min(SAFE.x + SAFE.w - E.cx, E.cx - SAFE.x) - 20 : Infinity;+ const tp = E.taglinePx * 1.5, tl = LK.wrap(spec.tagline, tp, Math.min(axisW, AW * (ZONES ? 0.9 : 0.8))), tLH = Math.round(tp * 1.3);+ const inst = installRows(spec.install, Math.min(axisW, AW * 0.86) - 2 * E.padX, minPx, E.monoPx * 1.35), mono = inst.px, rowH = Math.round(mono * 2), ph = rowH * inst.rows.length + 50 * k;if (mono < minPx - 1e-9) throw new Error(`launchTemplate ${shape}: the install lines would be ${mono.toFixed(1)} px on the clean end card (phone-safe minimum ${minPx} px). Shorten the install line, or ship this shape without it`);const g1 = titleSize * 0.42, g2 = tLH * 0.9, g3 = spec.footer ? 44 * k : 0, block = titleSize * 0.74 + g1 + tl.length * tLH + g2 + ph + g3 + (spec.footer ? E.footerPx : 0);const titleY = (ZONES ? SAFE.y * 2 + SAFE.h - block : H - block) / 2 + titleSize * 0.74, taglineY = titleY + g1 + tLH / 2, panelY = taglineY + (tl.length - 0.5) * tLH + g2;return { ...E, titleY, tagline: tl, taglinePx: tp, taglineLH: tLH, taglineY, panelY, monoPx: mono, rows: inst.rows, wrapped: inst.wrapped, rowH, lineY0: panelY + 25 * k + rowH / 2, footerY: panelY + ph + g3 + E.footerPx / 2, caret: [Math.round(mono * 0.53), Math.round(mono * 1.13)] as [number, number] };})();- const titleW = clean ? estWidth(spec.title, titleSize) * 1.08 : measure(spec.title, titleSize);- const dotR = titleSize * (clean ? 0.1 : 0.085), dotGap = titleSize * 0.1;- const P1: P = [END_L.cx + titleW / 2 - (dotGap + 2 * dotR) / 2 + dotGap + dotR, END_L.titleY - dotR * 1.05];+ const titleW = clean ? (LK.customDisplay ? LK.measure.display(spec.title, titleSize) : estWidth(spec.title, titleSize) * 1.08) : measure(spec.title, titleSize);+ // the grid end card (endCard.ts): its lockup is the name set right up to the drop, which sits on the+ // baseline as the name's full stop. The lockup's box is fixed by its aspect, so the dot's place is+ // known here, before anything is drawn, and the motif's drop can fly to it.+ const GRID = spec.endCard === "grid", GRID_ON = 30, LOCK = { cap: 0.74, dot: 0.1, gap: 0.1 }; // per unit of the name's type size+ const CARD_SPEC: EndCardSpec | null = GRID ? {+ // (the name sits on the box's foot: a descender hangs about 0.3 of the box below it, and the line under+ // it keeps its air under the letters: a fresh critic saw the y's tail 15 px over the tagline)+ lockup: { aspect: ((LK.customDisplay ? LK.measure.display(spec.title, 100) : estWidth(spec.title, 100)) + 100 * (LOCK.gap + 2 * LOCK.dot)) / (100 * LOCK.cap), descent: /[gjpqy,;]/.test(spec.title) ? 0.3 : 0, draw: (c, b) => {+ const size = b.h / LOCK.cap, room = b.w - size * (LOCK.gap + 2 * LOCK.dot); // the dot is drawn by the end page: it is where the drop lands+ // the box comes from an estimate of the name's width: the real face is scaled to fill it exactly, so+ // the name starts on the card's margin and ends one gap before the dot (within 25 % either way)+ c.font = LK.fonts.display(800, size); const k = clamp(room / c.measureText(spec.title).width, 0.75, 1.25);+ c.font = LK.fonts.display(800, size * k); c.fillStyle = PAL.ink; c.textAlign = "right"; c.textBaseline = "alphabetic"; c.fillText(spec.title, b.x + room, b.y + b.h); c.textAlign = "left";+ } },+ date: spec.tagline, venue: spec.install.join(" · "), cta: spec.footer ?? `Get ${spec.title}`,+ // no sponsor band under this card: the stamp sits one gap after the text block, not at the far edge+ stamp: "inline",+ // the install line is set in mono, as a viewer would type it: it sits in the card's venue slot, its only 600-weight line+ colors: { ink: PAL.ink, accent: ACC ?? PAL.accent, ctaInk: LK.custom ? LK.onAccent : "#ffffff" }, font: (w, px) => (w === 600 ? LK.fonts.mono(px) : w >= 800 ? LK.fonts.display(w, px) : LK.fonts.text(w, px)),+ } : null;+ const CARD_L = CARD_SPEC ? endCardLayout(W, L.H, CARD_SPEC, (t, font) => LK.measureFont(t, font)) : null, LOCKUP = CARD_L?.lockup ?? null;+ // with no sponsor band at its foot the card's group is centred on the height (9:16: on the platforms'+ // safe band), so it does not hang from the top margin over an empty lower half+ const CARD_DY = CARD_L ? (() => { const top = CARD_L.lockup.y, bottom = Math.max(CARD_L.venue.y + CARD_L.venue.h, CARD_L.cta.y + CARD_L.cta.h), [lo, hi] = CARD_L.shape === "tall" ? [L.H * 0.17, L.H * 0.74] : [0, L.H]; return CARD_L.logos.length ? 0 : Math.round((lo + hi - (bottom - top)) / 2 - top); })() : 0;+ const dotR = LOCKUP ? (LOCKUP.h / LOCK.cap) * LOCK.dot : titleSize * (clean ? 0.1 : 0.085), dotGap = titleSize * 0.1;+ // the name and its dot are centred on the card's axis by their INK: a written name's first stroke starts a+ // side bearing after its advance width does, and centred by the advance it sat that far right of the axis+ const titleInkL = clean ? 0 : inkSpan(spec.title, titleSize, { seed: 11 })[0];+ const LOGO_W = logoW1 * titleSize; // the logo and its gap, in px+ const P1: P = LOCKUP ? [LOCKUP.x + LOCKUP.w - dotR, LOCKUP.y + CARD_DY + LOCKUP.h - dotR * 1.05] : [END_L.cx + (titleW + dotGap - titleInkL + LOGO_W) / 2, END_L.titleY - dotR * 1.05];+ // the logo's box: its left edge opens the group, its foot on the name's baseline+ const LOGO_BOX = END_LOGO ? (() => { const h = LOGO_H * titleSize, w = (h * END_LOGO.w) / END_LOGO.h, right = MOTIF ? P1[0] - dotR - dotGap - titleW - LOGO_GAP * titleSize : END_L.cx + (titleW + LOGO_W) / 2 - titleW - LOGO_GAP * titleSize; return { x: right - w, y: END_L.titleY - h, w, h }; })() : null;const coverFrom = (p: P) => Math.max(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot(x - p[0], y - p[1])));- const RAD = coverFrom(P1) * 1.14, R0 = bloomRadius(2, 1e6, { inF: 16, close: false, radius: RAD }), RIM = Math.max(1, dotR - R0);+ // THE END CARD'S BLOOM opens at an even pace, its rim never faster than nine tenths of the brand's+ // temperament allows (motionKit.TEMPERAMENTS; lively when the brief names none), so the frames it takes+ // follow the distance it covers: about 30 on a wide frame, 43 on a phone one. The expo it had took most+ // of the frame in four, then the name's first strokes on the bare page were a second swap: two slide+ // cuts in a row on a phone frame (motionscan), and its rim swept past at 200 px a frame.+ const RAD = coverFrom(P1) * 1.14, TEMPER = spec.motion?.temperament ?? "lively", RIM_PACE = 0.9 * (typeof TEMPER === "string" ? TEMPERAMENTS[TEMPER] ?? TEMPERAMENTS.lively : TEMPER).maxSpeed * speedCeiling(W, 30);+ // (the page is drawn from local frame 2, so the even opening starts there, from nothing: the landed drop is+ // its first size, never a disc already 150 px across that the drop had to swell into on its way)+ const BLOOM_N = Math.ceil(RAD / RIM_PACE), END_BLOOM = { inF: BLOOM_N, ease: (t: number) => clamp((t * (BLOOM_N + 2) - 2) / BLOOM_N), close: false };+ const R0 = bloomRadius(2, 1e6, { ...END_BLOOM, radius: RAD }), RIM = Math.max(1, dotR - R0);// where the drop lifts off: Generate as the viewer sees it on the last chat ask (the card's centre if the lean hid it), the product's action, or the film's cardconst liftAt = (f: number): P => {const i = n - 1, a = spec.asks[i];- if (!isChat(a)) return a.kind === "ui" ? uiScreen(i, f, uiActionAt(panelOf(i), a.ui, minPx)) : ((c) => [c.x + c.w / 2, c.y + c.h / 2] as P)(filmCard(i));+ // (a product's drop swells beside its action, to the left on the header, never on the button's word)+ if (!isChat(a)) return a.kind === "ui" ? uiScreen(i, f, (({ x, y, h }) => [x - 56 * k, y + h / 2] as P)(uiActionRect(panelOf(i), a.ui, minPx))) : ((c) => [c.x + c.w / 2, c.y + c.h / 2] as P)(filmCard(i));const cam = camAt(caretEst, f, i).cam, g = toScreen(cam, GEN_C, W, H), inFrame = g[0] > 60 && g[0] < W - 60 && g[1] > 60 && g[1] < H - 60;return inFrame ? g : toScreen(cam, [TH.cardX + CARD / 2, cardY(i, f) + CARD / 2], W, H);};@@ -415,7 +908,10 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {if (!MOTIF || f < END0 - DL - LIFT || f >= END0) return;ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = INK;if (f < END0 - DL) { const w = out3(ramp(f, END0 - DL - LIFT, END0 - DL)); ctx.beginPath(); ctx.arc(S0[0], S0[1], 30 * k * camZ * (0.2 + 0.8 * w), 0, Math.PI * 2); ctx.fill(); return; }- for (let j = 24; j >= 0; j--) { const q = path(Math.max(END0 - DL, f - j * 0.1)); if (!q) continue; ctx.globalAlpha = j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(q.p[0], q.p[1], q.r * (1 - j * 0.02), 0, Math.PI * 2); ctx.fill(); }+ // the drawn look trails ghosts of ink; the clean look's one accent is never see-through (layerscan+ // translucent: a brand colour at a part alpha reads as mud), so its drop stretches into one solid,+ // tapering streak along its path instead+ for (let j = 24; j >= 0; j--) { const q = path(Math.max(END0 - DL, f - j * 0.1)); if (!q) continue; ctx.globalAlpha = clean || j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(q.p[0], q.p[1], q.r * (clean ? 1 - j * 0.034 : 1 - j * 0.02), 0, Math.PI * 2); ctx.fill(); }ctx.globalAlpha = 1;};// the seam, checked: the drop's pose as it lands (the ask's side) is the ink the end card blooms from@@ -426,42 +922,69 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const i = askOf(f), t = T[i], l = f - t.base;// a seam between kinds: the new scene blooms open over the last frame of the one before// (+4: a bloom's first frames open by less than a pixel)- if (t.tin && l < t.tin) bloomFrame(ctx, env, l + 4, 1e6, () => sceneOf(ctx, env, t.base - 1, i - 1), (c) => sceneOf(c, env, f, i), { close: false, inF: 14, W, H, ...bloomOpts });+ if (t.tin && l < t.tin) travel(ctx, env, (l + 0.5) / t.tin, (c) => prevPlace(c, env, i, l), (c) => sceneOf(c, env, f, i), axOf(`ask:${i}`), !fitted[i - 1] && isChat(spec.asks[i - 1]));else sceneOf(ctx, env, f, i);if (withDrop) motifDrop(ctx, env, f);};// ---------------------------------------------------------------- the end card+ // the stacked card's name: end-card frames it writes (or sets) over; with the motif it starts as the page+ // opens from the dot, without it a little later. NAME_ON is the frame it is all on (set type's out-cubic+ // settles to the pixel 9 frames early; an ink line is done when its last stroke is). The drawn name is+ // written in 24 frames, as the bloom opens: written slower, its last strokes on the open page were too+ // small a change to read as motion and too early to be the hold (the gate's dead air)+ const NAME_W: [number, number] = clean ? (MOTIF ? [4, 26] : [8, 30]) : MOTIF ? [4, 28] : [10, 34], NAME_ON = NAME_W[1] - (clean ? 9 : 0) + 1;const endPage = (c: Ctx, env: Env, e: number) => {- const E = END_L, cx = E.cx, size = titleSize;+ if (CARD_SPEC) { // the grid card: its parts rise into place in turn beside the landed drop+ // once it is all on, the card settles (endZ) and then rests: the frame people read and screenshot+ const k = c;+ k.setTransform(env.scale, 0, 0, env.scale, 0, env.scale * CARD_DY); drawEndCard(k, env, CARD_SPEC, ramp(e, 4, GRID_ON));+ k.setTransform(env.scale, 0, 0, env.scale, 0, 0); k.fillStyle = INK; k.beginPath(); k.arc(P1[0], P1[1], dotR, 0, Math.PI * 2); k.fill();+ c.textAlign = "left"; c.textBaseline = "alphabetic"; return;+ }+ const E = END_L, cx = E.cx, size = titleSize, [n0, n1] = NAME_W;// (with the motif the page blooms from the dot, wider and sooner: the name starts as it opens, so no frame waits)- if (MOTIF) { const tx = P1[0] - dotR - dotGap; if (clean) setType(c, env, spec.title, tx, E.titleY, size, ramp(e, 4, 26), { align: "right", color: PAL.ink, weight: 800 }); else writeOn(c, env, spec.title, tx, E.titleY, size, ramp(e, 4, 40), "ink", { color: C.ink, align: "right", seed: 11 }); c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = INK; c.beginPath(); c.arc(P1[0], P1[1], dotR, 0, Math.PI * 2); c.fill(); }- else if (clean) setType(c, env, spec.title, cx, E.titleY, size, ramp(e, 8, 30), { align: "center", color: PAL.ink, weight: 800 });- else writeOn(c, env, spec.title, cx, E.titleY, size, ramp(e, 10, 44), "ink", { color: C.ink, align: "center", seed: 11 });+ if (MOTIF) { const tx = P1[0] - dotR - dotGap; if (clean) setType(c, env, spec.title, tx, E.titleY, size, ramp(e, n0, n1), { font: LK.fonts.display, align: "right", color: PAL.ink, weight: 800 }); else writeOn(c, env, spec.title, tx, E.titleY, size, ramp(e, n0, n1), "ink", { color: C.ink, align: "right", seed: 11, tool: PEN }); c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = INK; c.beginPath(); c.arc(P1[0], P1[1], dotR, 0, Math.PI * 2); c.fill(); }+ else if (clean) setType(c, env, spec.title, cx + LOGO_W / 2, E.titleY, size, ramp(e, n0, n1), { font: LK.fonts.display, align: "center", color: PAL.ink, weight: 800 });+ else writeOn(c, env, spec.title, cx, E.titleY, size, ramp(e, n0, n1), "ink", { color: C.ink, align: "center", seed: 11, tool: PEN });+ // the logo grows in about its own foot with the name (whole, never see-through: a brand element is opaque)+ if (END_LOGO && LOGO_BOX) { const g = out3(ramp(e, n0, n0 + 12)); if (g > 0.01) { const B = LOGO_BOX, sc = (B.h / END_LOGO.h) * g; c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.save(); c.translate(B.x + B.w / 2, B.y + B.h); c.scale(sc, sc); c.translate(-END_LOGO.w / 2, -END_LOGO.h); drawEl(c, END_LOGO, { name: "logo" }); c.restore(); } }c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.textAlign = "center"; c.textBaseline = "middle";- const Q = clean && MOTIF ? -14 : 0; // the clean name is set in 22 frames, not written in 36: the rest follows it closer- // the clean look's lines rise into place as they appear, like its type (the drawn look's fade in under the written name)- const rise = (a: number) => (clean ? (1 - out3(ramp(e, a, a + 12))) * 22 * L.k : 0);- c.globalAlpha = ramp(e, 34 + Q, 46 + Q); c.fillStyle = PAL.soft; c.font = SANS(500, E.taglinePx); E.tagline.forEach((t, j) => c.fillText(t, cx, E.taglineY + j * E.taglineLH + rise(34 + Q)));- c.translate(0, rise(40 + Q));- c.globalAlpha = ramp(e, 40 + Q, 52 + Q); c.font = MONO(E.monoPx);- // one row per install line, centred; a wrapped line's rows are set left in the panel, its continuation indented+ // THE LINE, THE INSTALL PANEL AND THE FOOTER OPEN WITH THE PAGE: the bloom reveals them whole, and only the+ // name writes itself. Each used to fade in after the name (a dissolve to motionscan), and a big dark panel+ // arriving on an empty page in a few frames was a second slide cut after the bloom's. Open from the+ // first frame, the install lines are on screen for the whole end card.+ c.fillStyle = PAL.soft; c.font = LK.fonts.text(500, E.taglinePx); E.tagline.forEach((t, j) => c.fillText(t, cx, E.taglineY + j * E.taglineLH));+ c.font = LK.fonts.mono(E.monoPx);+ // one row per install line, every row set left in the panel as a terminal sets them (centred rows started+ // at different places and read as a caption); a wrapped line's continuation is indentedconst rows = E.rows, nI = rows.length, cw = c.measureText("0").width, rowW = (r: { text: string; indent: number }) => c.measureText(r.text).width + r.indent * cw;const pw = (E.wrapped ? Math.max(...rows.map(rowW)) : Math.max(...spec.install.map((s) => c.measureText(s).width))) + 2 * E.padX, ph = E.rowH * nI + 2 * (E.lineY0 - E.panelY) - E.rowH, py = E.panelY, x0 = cx - pw / 2 + E.padX;c.fillStyle = clean ? PAL.ink : "#1f1c18"; rr(c, cx - pw / 2, py, pw, ph, 22 * L.k); c.fill();- c.fillStyle = clean ? "#ffffff" : "#ece4d6";- if (E.wrapped) { c.textAlign = "left"; rows.forEach((r, j) => c.fillText(r.text, x0 + r.indent * cw, E.lineY0 + j * E.rowH)); c.textAlign = "center"; }- else spec.install.forEach((s, j) => c.fillText(s, cx, E.lineY0 + j * E.rowH));+ // (a custom look's panel is its ink with its ground's colour for the words: a light ink took white words)+ c.fillStyle = clean ? (LK.custom ? PAL.bg : "#ffffff") : "#ece4d6";+ c.textAlign = "left"; rows.forEach((r, j) => c.fillText(r.text, x0 + r.indent * cw, E.lineY0 + j * E.rowH)); c.textAlign = "center";// a terminal caret blinks after the last row: the hold reads as live, never as a freeze- const lastW = c.measureText(rows[nI - 1].text).width, caretX = E.wrapped ? x0 + rowW(rows[nI - 1]) + 8 * (E.monoPx / 30) : cx + lastW / 2 + 8 * (E.monoPx / 30);- if (Math.floor((e - 40 - Q) / 15) % 2 === 0) { if (clean) c.fillStyle = THEME.accent; c.fillRect(caretX, E.lineY0 + (nI - 1) * E.rowH - E.caret[1] / 2, E.caret[0], E.caret[1]); }- if (spec.footer) { c.fillStyle = PAL.soft; c.font = SANS(500, E.footerPx); c.fillText(spec.footer, cx, E.footerY); }+ const lastW = c.measureText(rows[nI - 1].text).width, caretX = x0 + rowW(rows[nI - 1]) + 8 * (E.monoPx / 30);+ if (Math.floor((e - NAME_ON) / 15) % 2 === 0) { if (clean) c.fillStyle = THEME.accent; c.fillRect(caretX, E.lineY0 + (nI - 1) * E.rowH - E.caret[1] / 2, E.caret[0], E.caret[1]); }+ if (spec.footer) { c.fillStyle = PAL.soft; c.font = LK.fonts.text(500, E.footerPx); c.fillText(spec.footer, cx, E.footerY); }c.globalAlpha = 1; c.textAlign = "left"; c.setTransform(env.scale, 0, 0, env.scale, 0, 0);};+ // THE END CARD SETTLES, never a dead hold: as its last part lands the page leans in 3 % (END_CREEP),+ // easing out to rest a second before the end (the frame people screenshot). A fresh critic read four+ // seconds of a still card as the film stopping. The install lines stay put to the eye: at its fastest the+ // lean moves a line's end by under a pixel a frame. It starts while the parts still land and only slows+ // from there: a creep that started from still (linear, or an in-out) left still stretches on both sides of+ // its move, and motionscan read them on 9x16 as one layout settling three times in a row.+ // (the stacked card leans in about a point on its own axis, level with the dot: about the dot itself, which+ // sits at the name's right end, the lean carried every line of the card left by 3 % of the dot's distance+ // from the axis, 20 px on 16:9, a fresh critic's d4-1. The grid card is not centred: it leans about its dot)+ const END_CREEP: P = GRID ? P1 : [END_L.cx, P1[1]];+ const ALL_ON = GRID ? GRID_ON : NAME_ON, endZ = (e: number) => 1 + 0.03 * out3(ramp(e, ALL_ON - 10, END - 30));const content = (ctx: Ctx, env: Env, f: number, exact: boolean) => {const g = clamp(exact ? Math.round(f) : f, 0, END0 + END - 1);if (g < END0) return askScene(ctx, env, g);const e = g - END0;- bloomFrame(ctx, env, e + 2, END + 2, () => askScene(ctx, env, END0 - 1, false), (c) => endPage(c, env, e), { close: false, inF: 16, W, H, ...bloomOpts, ...(MOTIF ? { center: P1, radius: RAD, rim: lerp(RIM, clean ? 0 : 26, out3(ramp(e, 0, 7))), ink: INK } : {}) });+ bloomFrame(ctx, env, e + 2, END + 2, () => askScene(ctx, env, END0 - 1, false), (c) => endPage(placed(c, env, { z: endZ(e), c: END_CREEP }), env, e), { ...END_BLOOM, W, H, ...bloomOpts, ...(MOTIF ? { center: P1, radius: RAD, rim: lerp(RIM, clean ? 0 : 26, out3(ramp(e, 0, 7))), ink: INK } : {}) });};// ---------------------------------------------------------------- the cut, as data@@ -470,7 +993,7 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const last = i === n - 1;const b = BASE[i], e = b + LEN[i];segs.push(last && spec.claimBar !== undefined ? pic(b, e, SOLVED) : pic(b, e)); // SOLVED < ASK plays the ask faster; never slower- if (!last && words[i]?.length) segs.push(type(fitWords(words[i], L), TYPE, e - 1, e));+ if (!last && words[i]?.length) segs.push(type(fitted[i]!, TYPE, e - 1, e)); // (the fitted lines themselves: a page knows its index by them)});// the score plays at the film's bpm, exactly: the cuts sit on this grid. Sync wins over length, so// the end-card hold (not the tempo) takes up the difference: the film becomes whole bars of the score.@@ -478,24 +1001,12 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {if (bed) END = bed.end;segs.push(pic(END0, END0 + END));const cut = makeCut(segs);- // a clean word page: a round iris, the lines SET (heavy sans, left-aligned at the margin, each rising into place)- const cleanType = (ctx: Ctx, env: Env, lines: TypeLine[], local: number, len: number, under: (first: boolean) => void) => bloomFrame(ctx, env, local, len, under, (c) => {- const nL = lines.length, maxW = L.type.maxW, at = L.type.at, x0 = at ? at[0] - maxW / 2 : (W - maxW) / 2;- const size = Math.min(nL === 1 ? 220 : 170, ...lines.map((l) => (maxW / (estWidth(l.text, 100) * 1.12)) * 100)), gap = size * 1.12, y0 = (at ? at[1] : H / 2) - ((nL - 1) * gap) / 2 + size * 0.36;- lines.forEach((l, i) => setType(c, env, l.text, x0, y0 + i * gap, size, ramp(local, 14 + TYPE_O.lead + i * CLEAN_ST, 14 + TYPE_O.lead + 18 + i * CLEAN_ST), { color: l.color === C.accent ? THEME.accent : l.color ?? PAL.ink, weight: 800 }));- bug(c, env);- }, { W, H, ...bloomOpts, rim: 4, ink: THEME.accent, radius: TYPE_R, ...(L.type.at ? { center: L.type.at } : {}) });- // a word page's bloom is sized to the frame it covers (the desktop's 1250 px over a 1110 px cover):- // on a smaller frame a fixed bloom would cover it before the words start, and two frames would match- const TYPE_R = L.shape === "16x9" ? undefined : Math.round((1250 * L.type.cover) / 1110);- // (9x16: the page blooms from the words' centre, so its first drop lands where the words will be)- const TYPE_OPTS = L.shape === "16x9" ? TYPE_O : { ...TYPE_O, W, H, maxW: L.type.maxW, radius: TYPE_R, ...(L.type.at ? { text: L.type.at, center: L.type.at } : {}) };const drawStage = (ctx: Ctx, env: Env, t: number) => {const { s, local } = cut.at(t), exact = Number.isInteger(t);if (s.kind === "pic") content(ctx, env, cut.contentOf(s, local), exact);// offset by 2 frames at each end so the bloom is already moving on the first and last frame- else if (clean) cleanType(ctx, env, s.lines, local + 2, s.len + 4, (first) => content(ctx, env, first ? s.before : s.after, true));- else typeFrame(ctx, env, s.lines, local + 2, s.len + 4, (first) => content(ctx, env, first ? s.before : s.after, true), (c) => bug(c, env), TYPE_OPTS);+ // (clean: the camera travels from the ask to the word page; it travels on to the next ask in that ask's own first frames)+ else { const k = fitted.indexOf(s.lines); if (local < TRV) travel(ctx, env, (local + 0.5) / TRV, (c) => content(c, env, s.before, true), (c) => pageScene(c, env, s.lines, local, k), axOf(`page:${k}`), isChat(spec.asks[k])); else pageScene(ctx, env, s.lines, local, k); }};// ---------------------------------------------------------------- captions: the words a viewer reads, in cut frames@@ -505,7 +1016,7 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const t = T[i], lo = cut.STARTS[cut.SEGS.findIndex((sg) => sg.kind === "pic" && sg.from === t.base)] ?? 0;if (isChat(a) || (a.kind === "ui" && a.prompt)) { const from = Math.max(lo, cutAt(t.base + Math.max(t.tin, t.times[0] ?? 0))), to = cutAt(t.base + Math.min(t.len - 1, isChat(a) ? t.drop.full : t.drop.t0 + 24)); if (from >= 0 && to > from) caps.push({ from, to, text: isChat(a) ? a.prompt : a.prompt! }); }const split = !isChat(a) ? a.split : undefined;- if (split?.length) { const from = cutAt(t.base + t.tin + 4), to = cutAt(t.base + t.len - 1) + 1; caps.push({ from, to, text: split.map((x) => x.text).join(" ") }); }+ if (split?.length) { const from = cutAt(t.base + wordsAt(t.tin) + 4), to = cutAt(t.base + t.len - 1) + 1; caps.push({ from, to, text: split.map((x) => x.text).join(" ") }); }});cut.SEGS.forEach((sg, k) => { if (sg.kind === "type") caps.push({ from: cut.STARTS[k] + 12, to: cut.STARTS[k] + sg.len, text: sg.lines.map((x) => x.text).join(" ") }); });const endAt = cut.STARTS[cut.SEGS.length - 1];@@ -519,8 +1030,8 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {ctx.fillStyle = PAL.card; ctx.fillRect(B.x, B.y, B.w, B.h); ctx.fillStyle = PAL.line; ctx.fillRect(B.x, B.y, B.w, 2);const c = capAt(t); if (!c) return;const TX = ZONES ? { x: SAFE.x, w: SAFE.w } : B; // the caption's own column: on 9x16 clear of the right-hand buttons- const px = Math.max(36, Math.round(B.h * 0.2)), lines = wrapEst(c.text, px, TX.w - 120).slice(0, 2), a = Math.min(ramp(t, c.from, c.from + 6), 1 - ramp(t, c.to - 6, c.to));- ctx.globalAlpha = a; ctx.fillStyle = PAL.ink; ctx.font = SANS(600, px); ctx.textAlign = "center"; ctx.textBaseline = "middle";+ const px = Math.max(36, Math.round(B.h * 0.2)), lines = LK.wrap(c.text, px, TX.w - 120).slice(0, 2), a = Math.min(ramp(t, c.from, c.from + 6), 1 - ramp(t, c.to - 6, c.to));+ ctx.globalAlpha = a; ctx.fillStyle = PAL.ink; ctx.font = LK.fonts.text(600, px); ctx.textAlign = "center"; ctx.textBaseline = "middle";lines.forEach((l, j) => ctx.fillText(l, TX.x + TX.w / 2, B.y + B.h / 2 + (j - (lines.length - 1) / 2) * px * 1.25)); ctx.globalAlpha = 1; ctx.textAlign = "left";};const draw = (ctx: Ctx, F: number, env: Env) => {@@ -534,19 +1045,29 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const holds: [number, number][] = [];cut.SEGS.forEach((s, k) => {if (s.kind !== "type") return;- const written = 14 + TYPE_O.lead + 18 + (s.lines.length - 1) * (clean ? CLEAN_ST : TYPE_O.stagger) - (clean ? 9 : 2); // local frame the last line is done (set type's out-cubic settles to the pixel sooner)- // last frame the page still fills the frame (a round iris only clips the corners for its first closing frames: still a still)- const cover = clean ? (L.type.at ? (L.type.cover - 9) * 0.9 : Math.hypot(W, H) / 2 * 0.9) : L.type.cover;- let open = s.len - 1; while (open > written && bloomRadius(open + 2, s.len + 4, { radius: TYPE_R }) < cover) open--;- holds.push([cut.STARTS[k] + written + 1, cut.STARTS[k] + open + 1]);+ // the page is fully set (or written) from pageSet until its lines sink; it creeps, but slowly enough to read as a hold+ holds.push([cut.STARTS[k] + pageSet(s.lines.length), cut.STARTS[k] + Math.min(TYPE, pageOut(fitted.indexOf(s.lines))) + 6]); // (+6: a sink's first frames are an ease-in, still to the eye)});// a solved ask longer than the grid's: the finished card rests on screen until the end card blooms// (with the motif the drop is in flight over those frames, so they are not a hold)if (LEN[n - 1] > ASK && isChat(spec.asks[n - 1]) && !MOTIF) { const S = cut.STARTS[cut.SEGS.length - 2]; holds.push([S + LEN[n - 1] - 18, S + LEN[n - 1] + 6]); }- holds.push([cut.N - END + (clean && MOTIF ? 39 : 53), cut.N]); // the end card, all on: read it, screenshot it+ holds.push([cut.N - END + (GRID ? GRID_ON - 2 : NAME_ON), cut.N]); // the end card, all on: read it, screenshot it (the grid card's out-cubic rise settles to the pixel 2 frames before GRID_ON)// a UI ask's action button bottoms out: the press lands before the items move (a stationary point by// design, one or two frames; at 60 fps and in small shapes the gate reads it as a still)spec.asks.forEach((a, i) => { if (isChat(a) || a.kind !== "ui") return; const F = cut.cutOf(T[i].base + T[i].up); if (F > 0) holds.push([F - 1, F + 2]); });+ // a split beat's words, once they are set and the product beside them has landed, are read until they+ // sink, as a word page's are: the panel creeps, but over a sparse product screen (a scaffold's stand-in,+ // two rows) the creep alone changes too little of the frame to be told from a freeze (the gate's dead air)+ spec.asks.forEach((a, i) => {+ if (isChat(a) || !a.split?.length) return;+ // (set type's out-cubic settles to the pixel 9 frames before its rise ends, as pageSet counts it; an item+ // has landed at its spring's first arrival, its overshoot after it under what the eye reads as moving)+ const t = T[i], set = wordsAt(t.tin) + 18 + (splitFit(a.split).lines.length - 1) * 12 - (clean ? 9 : 0), landed = a.kind === "ui" ? Math.max(t.drop.t0, ...uiSettles(a.ui, { t0: t.drop.t0 }).map((q) => q.frame)) : 0;+ // (reached by a travel, the words are set before the press and read while the product rests in its before+ // state: the hold starts with them, or that rest is dead air to the gate; otherwise once both have landed)+ const sink = sinkAt(i), from = cut.cutOf(t.base + (t.tin > 0 && t.drop.t0 > set ? set : Math.max(set, landed))), to = cut.cutOf(t.base + sink) + 6;+ if (from >= 0 && to > from) holds.push([from, to]);+ });// ---------------------------------------------------------------- sound: the picture's own cuesconst cues: LaunchCue[] = [];@@ -558,8 +1079,8 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const t = T[i], b = t.base;const prompt = isChat(a) ? a.prompt : a.kind === "ui" ? a.prompt : undefined;// a key for every character typed, a word's first key a touch firmer, the space bar its own sound- if (prompt) t.times.forEach((tm, j) => { if (tm < Math.max(0, t.tin)) return; const ch = prompt[j], first = j === 0 || prompt[j - 1] === " ";- const x = isChat(a) ? screenX(i, b + tm, caretEst(prompt.slice(0, j + 1))) : ((r) => (r ? r.x + 26 * k + estWidth(prompt.slice(0, j + 1), 26) : W / 2))(uiCommandAt(panelOf(i), (a as UiAsk).ui, minPx));+ if (prompt) t.times.forEach((tm, j) => { if (tm < 0) return; /* a key typed before frame 0 is not heard; one typed as the composer travels in is */ const ch = prompt[j], first = j === 0 || prompt[j - 1] === " ";+ const x = isChat(a) ? screenX(i, b + tm, caretEst(prompt.slice(0, j + 1))) : ((r) => (r ? r.x + 26 * k + LK.measure.text(prompt.slice(0, j + 1), 26) : W / 2))(uiCommandAt(panelOf(i), (a as UiAsk).ui, minPx));add(b + tm, { kind: "tick", variant: ch === " " ? "space" : "key", gainDb: first && ch !== " " ? 1.5 : 0, x, role: "key", label: `key ${JSON.stringify(ch)}` }); });if (isChat(a)) {const card = (c: number): P => [TH.cardX + CARD / 2, cardY(i, c) + CARD / 2];@@ -588,11 +1109,23 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {let memo: Map<string, LaunchFilm> | null = null;const self: LaunchFilm = {meta: { title: `${spec.title} · launch${shape === "16x9" ? "" : ` · ${shape}`}`, W, H: L.H, fps, bpm: spec.bpm, durationFrames: cut.N * m, raster: "cpu", kind: "launch", holds: holds.map(([a, b]) => [a * m - (m - 1), b * m] as [number, number]), ...(bed ? { score: { tempo: spec.bpm, form: bed.form, grid: true } } : {}),- sync, captions: caps.map((c) => ({ from: Math.round(c.from * m), to: Math.round(c.to * m), text: c.text })), poster: Math.round((cut.N - END + 60) * m) },+ sync, captions: caps.map((c) => ({ from: Math.round(c.from * m), to: Math.round(c.to * m), text: c.text })), poster: Math.round((cut.N - END + 60) * m), ...(spec.checks ? { checks: spec.checks } : {}), ...(spec.motion ? { motion: spec.motion } : {}) },assets: { images: {} },shots: [{ id: "cut", start: 0, end: cut.N * m, draw }],audio,claims: [...new Set([...words.flat().map((x) => x.text), ...spec.asks.flatMap((a) => (isChat(a) ? [] : (a.split ?? []).map((x) => x.text))), spec.tagline, ...(spec.claims ?? [])].map((x) => x.trim()).filter(Boolean))],+ grammar: { scrolls, travels: SEAMS.map((seam) => ({ seam, ax: axOf(seam) })), pages: fitted.flatMap((wl, i) => (wl ? [{ i, set: pageSet(wl.length), out: pageOut(i) }] : [])), endBloom: { frames: BLOOM_N, radius: RAD }, lift: S0, endCard: { creep: END_CREEP, cx: END_L.cx, group: [LOGO_BOX ? LOGO_BOX.x : P1[0] - dotR - dotGap - titleW + titleInkL, P1[0] + dotR], logo: LOGO_BOX, tagline: END_L.tagline, taglineW: END_L.tagline.map((t) => LK.measure.text(t, END_L.taglinePx)), room: ZONES ? [SAFE.x, SAFE.x + SAFE.w] : [0, W] }, rests: spec.asks.flatMap((a, i) => (isChat(a) || a.kind !== "ui" ? [] : [uiRest(i)])), dock: clean && HERO ? (() => { const a0 = T[0].b + CLEAN_DOCK.at; return { move: [a0, a0 + CLEAN_DOCK.move] as [number, number], shrink: [a0 + CLEAN_DOCK.move, a0 + CLEAN_DOCK.move + CLEAN_DOCK.shrink] as [number, number], creep: HOOK_CREEP, heroPx: HERO.TEXT.px, dockPx: G.TEXT.px, composer: { x: G.INPUT.x, y: G.INPUT.y, w: G.INPUT.w, h: G.INPUT.h }, window: { x: G.CHAT.x, y: G.CHAT.y, w: G.CHAT.w, h: G.CHAT.h }, viewBottom: VIEW_BOTTOM }; })() : null, drops: chatIdx.map((i) => {+ const t = T[i], d = { t0: t.base + t.drop.t0, land: t.base + t.drop.land }, to: P = [TH.cardX + CARD / 2, cardY(i, t.base + t.drop.land) + CARD / 2];+ const at = (c: number) => { const q = inkDropAt(c, d, to, G); return q ? toScreen(camAt(caretEst, c, i).cam, q.p, W, H) : null; };+ // (`landing`: the slowest it moves over the last 30 % of the flight, where an in-out crawled)+ let peak = 0, landing = Infinity; for (let c = d.t0; c < d.land - 1; c += 0.5) { const a = at(c), b = at(c + 0.5); if (!a || !b) continue; const v = 2 * Math.hypot(b[0] - a[0], b[1] - a[1]); peak = Math.max(peak, v); if (c >= d.land - 0.3 * (d.land - d.t0)) landing = Math.min(landing, v); }+ return { i, flight: [d.t0, d.land] as [number, number], peak, landing };+ }), lastWords: MOTIF && !isChat(spec.asks[n - 1]) && (spec.asks[n - 1] as UiAsk | FilmAsk).split?.length ? { gone: T[n - 1].base + sinkAt(n - 1) + SINK, flight: [END0 - DL, END0] } : null, heroDock: HERO && !clean ? (() => {+ const a0 = T[0].b + DOCK_AT, pts = (l: number): P[] => { const g = heroAt(0, l), cam = camAt(caretEst, T[0].base + l, 0).cam; return ([[g.INPUT.x, g.INPUT.y], [g.INPUT.x + g.INPUT.w, g.INPUT.y], [g.INPUT.x, g.INPUT.y + g.INPUT.h], [g.INPUT.x + g.INPUT.w, g.INPUT.y + g.INPUT.h], [g.GEN.x, g.GEN.y], [g.TEXT.x, g.TEXT.base]] as P[]).map((p) => toScreen(cam, p, W, H)); };+ let peak = 0; for (let l = a0; l < a0 + DOCK_LEN + 1; l++) { const p = pts(l), q = pts(l + 1); peak = Math.max(peak, ...p.map((x, j) => Math.hypot(q[j][0] - x[0], q[j][1] - x[1]))); }+ const seen = new Set<string>(); for (let l = a0; l < a0 + DOCK_LEN; l++) { const g = heroAt(0, l); seen.add(g.wrapAs ? `${g.wrapAs.px}/${g.wrapAs.maxW}` : `fresh ${l}`); }+ return { frames: [a0, a0 + DOCK_LEN] as [number, number], peak, wraps: seen.size };+ })() : null, splits: spec.asks.flatMap((a, i) => (isChat(a) || !a.split?.length ? [] : [(({ lines, size }) => ({ i, lines: lines.map((x) => x.text), size, tall: (L.split.vertical ? size * 1.25 : size * 1.05) + (lines.length - 1) * size * (clean ? 1.08 : 1.3), room: L.split.words }))(splitFit(a.split))])) },cut, layout: L, cues, seams, heroPx: HERO ? HERO.TEXT.px : null, timing: T, captions: caps.map((c) => ({ from: Math.round(c.from * m), to: Math.round(c.to * m), text: c.text })),// the same film composed for another frame shape (one timeline: the cut, the timing and the sound do not change)reshape: (s: string) => { if (s === shape) return self; memo ??= new Map(); let f = memo.get(s); if (!f) { f = makeLaunchFilm({ ...spec, shape: s as Shape }); memo.set(s, f); } return f; },diff --git a/skills/anidoodle/engine/src/canvas-core/motionKit.ts b/skills/anidoodle/engine/src/canvas-core/motionKit.tsnew file mode 100644index 0000000..2922f96--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/motionKit.ts@@ -0,0 +1,123 @@+// MOTION KIT. Small helpers that keep a motion-graphics film from turning into a slide deck. Each one+// exists because a brand launch film needed it and wrote it by hand (or got it wrong):+//+// alternate(i, ["left", "right"]) side, direction or entry for the i-th item of a list, never the same twice running+// entryFrom(i) a different entry direction for each item: no carousel+// chatScroll(f, steps, o) a chat column that scrolls over 18-24 frames on an ease-out, never a snap+// temperament(name | spec) the brand's motion temperament as numbers: top speed, settle time, overshoot+// cubicBezier(x1, y1, x2, y2) a CSS / Figma easing curve as a function (brand motion tokens)+// motionTokens(tokens) a brand's exported motion tokens as named eases and durations+// typeExit(q) how far a line of type has sunk on its way out (ease-in, 1.3x its size)+//+// Every function is pure arithmetic over its arguments: no clock, no state, any frame order.+import { speedCeiling } from "./seams";++const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));++/**+ * The i-th choice of a list that never repeats twice running: alternate(i, ["left", "right"]) gives+ * left, right, left. With three or more choices it walks a fixed shuffle so a list of eight items does+ * not read as a strict ping-pong either. The designer's note on the speakers: "each time pop up from a+ * different place".+ */+export const alternate = <T>(i: number, choices: readonly T[]): T => {+ if (!Number.isInteger(i) || i < 0) throw new Error(`alternate: i is a whole index from 0 (got ${i})`);+ if (choices.length < 2) throw new Error("alternate: give at least two choices; one choice repeated is the carousel this helper exists to stop");+ if (choices.length === 2) return choices[i % 2];+ // a stride coprime with the length visits every choice before repeating and never lands on the same one twice in a row+ const n = choices.length; let s = 2; while (gcd(s, n) !== 1) s++;+ return choices[(i * s) % n];+};+const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);++export type Entry = "left" | "right" | "below" | "above";+/** A different entry for each item: from the left, then the right, then below, then above, in the alternate() walk. */+export const entryFrom = (i: number, from: readonly Entry[] = ["left", "right", "below", "above"]): Entry => alternate(i, from);++/** Where a chat column sits at frame f: each step is { f, by } (start frame, pixels to scroll). Ease-out over `frames` (18-24). */+export const chatScroll = (f: number, steps: readonly { f: number; by: number }[], o: { frames?: number } = {}) => {+ const n = o.frames ?? 20;+ if (!(n >= 18 && n <= 24)) throw new Error(`chatScroll: a scroll takes 18 to 24 frames (got ${n}); fewer is the 100 px-a-frame snap that ghosts the text`);+ let y = 0;+ for (const s of steps) { const u = clamp((f - s.f) / n); y += s.by * (1 - Math.pow(1 - u, 3)); }+ return y;+};++// ---------------------------------------------------------------- temperament+/**+ * A brand's motion temperament, set in the brief before any motion is made. A brand launch film was+ * first "violent" and then "flat": nobody had written down how fast, how soft, and whether things+ * overshoot. maxSpeed is a share of speedCeiling (2.5 frame widths a second), settle is how long an+ * arrival takes in seconds, overshoot says whether arrivals may pass their mark and come back.+ */+export type Temperament = { name: string; maxSpeed: number; settle: [number, number]; overshoot: boolean };+export const TEMPERAMENTS: Record<string, Temperament> = {+ // poured liquid: long, soft, no bounce (a brand launch film, Apple "Intention")+ calm: { name: "calm", maxSpeed: 0.35, settle: [0.5, 1.0], overshoot: false },+ // alive but never violent: small landings, short settles+ lively: { name: "lively", maxSpeed: 0.55, settle: [0.3, 0.7], overshoot: true },+ // snappy product UI: quick arrivals, still under the ceiling+ snappy: { name: "snappy", maxSpeed: 0.8, settle: [0.2, 0.45], overshoot: true },+};+export const temperament = (t: string | Temperament): Temperament & { pxPerFrame: (W: number, fps: number) => number; settleFrames: (fps: number) => [number, number]; arrive: (u: number) => number } => {+ const spec = typeof t === "string" ? TEMPERAMENTS[t] : t;+ if (!spec) throw new Error(`temperament: '${t}' is not one of ${Object.keys(TEMPERAMENTS).join(", ")}; or pass { maxSpeed, settle, overshoot }`);+ if (!(spec.maxSpeed > 0 && spec.maxSpeed <= 1)) throw new Error(`temperament: maxSpeed is a share of speedCeiling, in (0, 1] (got ${spec.maxSpeed})`);+ if (!(spec.settle[0] > 0 && spec.settle[1] >= spec.settle[0])) throw new Error(`temperament: settle is [shortest, longest] seconds (got ${spec.settle})`);+ // an arrival curve that matches: with overshoot a small back-ease (passes by about 4 %), without it a quintic out+ const arrive = spec.overshoot ? (u: number) => { const c = clamp(u), s = 1.2; return 1 + (s + 1) * Math.pow(c - 1, 3) + s * Math.pow(c - 1, 2); } : (u: number) => 1 - Math.pow(1 - clamp(u), 5);+ return { ...spec, arrive, pxPerFrame: (W, fps) => spec.maxSpeed * speedCeiling(W, fps), settleFrames: (fps) => [Math.round(spec.settle[0] * fps), Math.round(spec.settle[1] * fps)] };+};++// ---------------------------------------------------------------- brand motion tokens+/** cubic-bezier(x1, y1, x2, y2) as an easing function of u in [0, 1]: the curve a designer types in Figma or CSS. */+export const cubicBezier = (x1: number, y1: number, x2: number, y2: number) => {+ if (![x1, x2].every((x) => x >= 0 && x <= 1)) throw new Error(`cubicBezier: x1 and x2 must lie in [0, 1] (got ${x1}, ${x2})`);+ const bx = (t: number) => 3 * x1 * t * (1 - t) ** 2 + 3 * x2 * t * t * (1 - t) + t ** 3;+ const by = (t: number) => 3 * y1 * t * (1 - t) ** 2 + 3 * y2 * t * t * (1 - t) + t ** 3;+ return (u: number) => {+ const x = clamp(u); if (x === 0 || x === 1) return x;+ let lo = 0, hi = 1; for (let i = 0; i < 40; i++) { const m = (lo + hi) / 2; if (bx(m) < x) lo = m; else hi = m; } // bisection: exact enough, and never fails to converge+ return by((lo + hi) / 2);+ };+};+/** A brand's motion tokens (brand.mjs import writes brand.motion from Figma's prototype timings). */+export type MotionToken = { ease: [number, number, number, number] | "linear"; ms: number; distance?: number };+/** Named eases and frame counts from the tokens: motionTokens(brand.motion, 60).turn.ease(u), .turn.frames. */+export const motionTokens = (tokens: Record<string, MotionToken>, fps: number) => Object.fromEntries(Object.entries(tokens).map(([k, t]) => {+ if (!(t.ms > 0)) throw new Error(`motionTokens: token "${k}" has no duration (ms ${t.ms})`);+ return [k, { ease: t.ease === "linear" ? (u: number) => clamp(u) : cubicBezier(...t.ease), frames: Math.max(1, Math.round((t.ms / 1000) * fps)), distance: t.distance }];+})) as Record<string, { ease: (u: number) => number; frames: number; distance?: number }>;++// ---------------------------------------------------------------- type exits+/** How far type travels when it sinks out, as a share of its font size: 1.3 clears ascenders and i-dots past the clip. */+export const TYPE_EXIT_TRAVEL = 1.3;+/**+ * A line of type leaving: q 0..1 is its exit progress, the result is how far it has sunk in font sizes.+ * EASE-IN, so it accelerates away and nothing lingers at the clip edge. The ease-out exit (1.0x) on+ * a brand launch film left letter tops visible for about half a second: the director saw them.+ */+export const typeExit = (q: number) => TYPE_EXIT_TRAVEL * Math.pow(clamp(q), 3);++// ---------------------------------------------------------------- the blur mask+/**+ * Draw something that must stay sharp under render --blur (a logo lockup, a UI card with small type):+ * the renderer leaves it out of the blurred subframes and lays the sharp frame's pixels over them.+ * Text and photos are kept sharp automatically; this is for anything else that reads as type.+ */+export const sharp = (draw: () => void) => { if ((globalThis as { __ANIDOODLE_SHARP__?: string }).__ANIDOODLE_SHARP__ === "skip") return; draw(); };++// ---------------------------------------------------------------- landings+/**+ * Squash and stretch for a landing, volume kept: [sx, sy] at frame t for a body landing at frame+ * `land`. Stretched into the ground, squashed for a few frames on contact, round again after (the+ * proof-3 grammar the director called "better than before"). A brand mark keeps its shape: pass brand: true+ * and this refuses unless `gag` names why the squash is the joke (brandKit.drawEl asks the same).+ */+export const landSquash = (t: number, land: number, o: { amount?: number; frames?: number; brand?: boolean; gag?: string } = {}): [number, number] => {+ if (o.brand && !o.gag?.trim()) throw new Error("landSquash: a brand mark keeps its shape (an ellipse of a brand circle is a redraw); pass { gag: \"<why the squash is the joke>\" } or squash a shape that is not the brand's");+ const amt = o.amount ?? 0.25, n = o.frames ?? 6, u = t - land;+ if (u < -n || u > n) return [1, 1];+ const sy = u < 0 ? 1 + amt * 0.6 * (1 + u / n) : 1 - amt * (1 - u / n) ** 2; // fullest squash on the contact frame (the classic contact pose), round again n frames later+ return [1 / Math.sqrt(sy), sy];+};diff --git a/skills/anidoodle/engine/src/canvas-core/motionMeta.ts b/skills/anidoodle/engine/src/canvas-core/motionMeta.tsnew file mode 100644index 0000000..0658537--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/motionMeta.ts@@ -0,0 +1,14 @@+// MOTION META. What a film tells the motion scans about itself (Film.meta.motion). Plain data, so it+// survives the page boundary; every field is read by a tool (motionscan.mjs, layerscan.mjs, lock.mjs).+import type { Temperament } from "./motionKit";++export type MotionMeta = {+ /** The brand's colours (#rrggbb). layerscan fails any fill in them at an alpha between 5 % and 95 % (olive mud). */+ brandColors?: string[];+ /** The brand's motion temperament, by name ("calm", "lively", "snappy") or as numbers. motionscan fails stretches past its top speed. */+ temperament?: string | Temperament;+ /** Approved shots, frozen: [shot id, sha from `lock.mjs <film> --shot <id>`, who approved it and when]. lock.mjs fails if the shot's frames change. */+ approved?: [shot: string, sha: string, note: string][];+ /** Deliberate exceptions, [fromFrame, toFrame, reason]: a hard cut on a beat (slide cut), a dissolve the story needs, a declared brand fade. */+ allow?: { slideCut?: [number, number, string][]; dissolve?: [number, number, string][]; translucent?: [number, number, string][] };+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfx.ts b/skills/anidoodle/engine/src/canvas-core/music/sfx.tsindex be694fe..cb24977 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sfx.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sfx.ts@@ -1,5 +1,5 @@// anidoodle sound effects: the kit (sfxKit), its building blocks (sfxCore) and film placement (sfxMix).// Docs: references/music/sound-design.md. Tool: engine/tools/sfx.mjs.-export { SFX, SFX_KINDS, sfxVariants, sfxInfo, renderSfx, validateSfx, sfxNeeds, parseKey, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";+export { SFX, SFX_KINDS, sfxVariants, sfxInfo, sfxDuckDb, renderSfx, validateSfx, sfxNeeds, parseKey, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";export { placeSfx, sfxDuck, sfxAudibility, sfxHarshness, SFX_HARSH_CAPS, mixSfx, assertSfxAudible, filmSfx, validateSfxPlan, resolveSfxPlan, type SfxCue, type SfxPlan, type SfxSnap, type PlacedCue, type SfxAudibility, type SfxHarshOptions, type SfxHarshness, type SfxMix } from "./sfxMix";export { type SfxStereo } from "./sfxCore";diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxKit.tsindex d1cad69..b62e963 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts@@ -495,11 +495,55 @@ const thread: Def = {},};-export const SFX = { tick, press, pop, ink, scratch, paper, whoosh, swish, riser, impact, chime, bubble, brick, thread } as const;+// The unpitched family, for films whose music the engine does not control (a generated or supplied+// track). Every layer is filtered noise or a falling sweep under 150 Hz, and the contact lasts a few+// milliseconds, so nothing carries a note that could clash with the track's key: a brand launch+// note was "the sound effects cannot be melodic, it makes disharmonious interruptions to the music".+// Modelled on that film's approved kit (strikes cut to 10-25 ms from their peak). tools/track.mjs kit+// prints each variant's pitch salience; trackMix refuses anything over 0.5 under an external track.+const tap: Def = {+ variants: ["tick", "tickHi", "tock", "thump", "impact"], level: -19, duckDb: 0,+ use: "under someone else's music: a small landing or a typed line (tick), a sparkle-sized touch (tickHi), a card or button (tock), a stage or block landing (thump), the one big lock-in (impact). No pitch, so no clash with the track's key",+ make(c, v) {+ const { sr, r } = c, p0 = (r() - 0.5) * 0.3;+ if (v === "tick" || v === "tickHi") {+ const hi = v === "tickHi", b = new Bus(sr, secs(sr, 0.05));+ b.add(burst(sr, r, hi ? 0.01 : 0.016, c.j(hi ? 0.0007 : 0.0013, 0.1), { hp: hi ? 3200 : 1800, lp: hi ? 14000 : 9000 }), 0, 1, p0);+ b.add(burst(sr, r, 0.004, 0.0004, { hp: hi ? 6000 : 4000 }), 0, 0.5, p0);+ punch(b, 0.3);+ return { bus: b, hit: 0 };+ }+ if (v === "tock") {+ const b = new Bus(sr, secs(sr, 0.08));+ b.add(burst(sr, r, 0.03, c.j(0.0045, 0.1), { hp: 450, lp: 5500 }), 0, 1, p0);+ b.add(burst(sr, r, 0.004, 0.0005, { hp: 2500 }), 0, 0.45, p0);+ punch(b, 0.35);+ return { bus: b, hit: 0 };+ }+ const big = v === "impact", n = secs(sr, big ? 1.8 : 0.16), b = new Bus(sr, n);+ // weight: a sweep that falls from about 110 to 45 Hz, under the 150 Hz line where a sound reads as a note+ const lo = c.j(big ? 42 : 48, 0.04), tau = big ? 0.42 : 0.045;+ b.add(chirp(sr, secs(sr, big ? 1.7 : 0.15), (t) => lo + 65 * Math.exp(-t / 0.018), ad(0.0015, tau)).map((x) => Math.tanh(x * 1.6) / Math.tanh(1.6)), 0, 1, 0);+ // body: low noise (lowpassed twice, as the approved kit was) and a dull contact so phones hear the hit+ const body = burst(sr, r, big ? 1.6 : 0.12, c.j(big ? 0.35 : 0.03, 0.1), { lp: big ? 500 : 160 }); filt(body, sr, { lp: big ? 500 : 160 });+ b.add(body, 0, big ? 1.6 : 1.2, p0 * 0.5);+ b.add(burst(sr, r, 0.006, 0.0009, { hp: 1200, lp: 6000 }), 0, big ? 0.22 : 0.3, p0);+ if (big) space(b, r, { rt60: 0.9, mix: 0.12, hp: 120, lp: 3000 });+ punch(b, 0.3);+ return { bus: b, hit: 0 };+ },+};++export const SFX = { tick, press, pop, ink, scratch, paper, whoosh, swish, riser, impact, chime, bubble, brick, thread, tap } as const;+/** Per-variant level (LUFS over the speaking window) where a kind's variants differ a lot in weight. */+const VARIANT_LEVEL: Partial<Record<string, number>> = { "tap:tickHi": -22, "tap:tock": -18, "tap:thump": -14, "tap:impact": -10 };+const VARIANT_DUCK: Partial<Record<string, number>> = { "tap:thump": 1.5, "tap:impact": 6 };export type SfxKind = keyof typeof SFX;export const SFX_KINDS = Object.keys(SFX) as SfxKind[];/** kind -> its variants (the first is the default). */export const sfxVariants = (k: SfxKind) => SFX[k].variants;+/** How far the score dips under one variant (dB): the kind's own, or the variant's where weights differ. */+export const sfxDuckDb = (k: SfxKind, variant?: string) => VARIANT_DUCK[`${k}:${variant ?? SFX[k].variants[0]}`] ?? SFX[k].duckDb;export const sfxInfo = (k: SfxKind) => ({ variants: SFX[k].variants, levelLufs: SFX[k].level, duckDb: SFX[k].duckDb, use: SFX[k].use });export const parseKey = (key: string) => {@@ -543,7 +587,7 @@ export const renderSfx = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSoundconst c: Ctx = { sr, r, P: Math.pow(2, (o.pitch ?? 0) / 12) * wobble, o, dir: o.dir ?? 1, key: o.key === undefined ? null : parseKey(o.key), bpm: o.bpm ?? NaN, j: (x, amt) => x * (1 + (r() * 2 - 1) * amt) };const made = d.make(c, variant), [L, R] = finish(made.bus, made.hit);const kL = kWeight(L, sr), kR = kWeight(R, sr), window = speakingWindow(kL, kR, sr), now = winLufs(kL, kR, window[0], window[1]);- let g = d.level + (r() * 2 - 1) + (o.gainDb ?? 0) - now;+ let g = (VARIANT_LEVEL[`${kind}:${variant}`] ?? d.level) + (r() * 2 - 1) + (o.gainDb ?? 0) - now;let peak = 0; for (let i = 0; i < L.length; i++) peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i]));g = Math.min(g, -1 - 20 * Math.log10(Math.max(peak, 1e-9)));const G = db(g); for (let i = 0; i < L.length; i++) { L[i] *= G; R[i] *= G; }diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxMix.tsindex 6e4160b..5270ab2 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts@@ -2,7 +2,7 @@// ducked under the cues that matter, one final master (a look-ahead true-peak ceiling), and an// audibility guarantee: every cue is measured against the ducked score at its own moment and the// mix FAILS if a cue sits more than minDb under it (a cue nobody hears is a bug, not a choice).-import { renderSfx, validateSfx, sfxNeeds, SFX, SFX_KINDS, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";+import { renderSfx, validateSfx, sfxNeeds, sfxDuckDb, SFX, SFX_KINDS, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";import { kWeight, winLufs, mixSeed, strSeed, secs, type SfxStereo } from "./sfxCore";import { Biquad, db } from "./dsp";import { MODES } from "./theory";@@ -137,7 +137,7 @@ export const placeSfx = (plan: SfxPlan, sr: number): PlacedCue[] => {export const sfxDuck = (placed: PlacedCue[], n: number, sr: number, o: SfxPlan["duck"] = {}) => {const g = new Float32Array(n).fill(1), att = secs(sr, o.attackS ?? 0.04), maxDb = o.maxDb ?? 9;for (const pc of placed) {- const depth = Math.min(maxDb, pc.cue.duckDb ?? SFX[pc.cue.kind].duckDb); if (depth <= 0) continue;+ const depth = Math.min(maxDb, pc.cue.duckDb ?? sfxDuckDb(pc.cue.kind, pc.sound.variant)); if (depth <= 0) continue;const rel = secs(sr, pc.cue.kind === "impact" ? 1.2 : o.releaseS ?? 0.28), lo = db(-depth), [a, b] = pc.window;for (let i = Math.max(0, a - att); i < Math.min(n, b + rel); i++) {const s = i < a ? 0.5 - 0.5 * Math.cos((Math.PI * (i - (a - att))) / att) : i < b ? 1 : 0.5 + 0.5 * Math.cos((Math.PI * (i - b)) / rel);diff --git a/skills/anidoodle/engine/src/canvas-core/music/track.ts b/skills/anidoodle/engine/src/canvas-core/music/track.tsnew file mode 100644index 0000000..7950cac--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/track.ts@@ -0,0 +1,327 @@+// EXTERNAL TRACKS. A supplied or generated piece of music (a Lyria take, a licensed track, a client's+// jingle) measured and cut to a film by numbers, so nobody does it by hand per version again.+// analyzeTrack tempo, beat phase, downbeats, the bar grid with each bar's level, sections, key, the+// real last-note time and any designed stops. A generative model ignores exact+// timestamps in its prompt, so the picture is fitted to what the track really does.+// parseSegs a cut list from text, robust to the shapes people write ("0 6\n8 36", "0:6, 8:36",+// no final newline: a brand launch film's mix silently lost its last segment to a shell+// `while read` loop on a file with no trailing newline).+// planCut checks a cut before it is rendered: joins on downbeats, the outro keeps the track's+// own ending, no silence after the last note, and the music never ends before the picture.+// renderCut the edit, with short centred crossfades so the length is exactly the sum of the segments.+// trackGrid the edit's downbeats as a grid that solves holds, so a picture event lands on a bar.+// pitchSalience how much a short sound carries a note. Under someone else's music, effects must be+// transients, never notes (a brand launch "disharmonious" note).+// Pure functions of sample arrays: no files, no clock. The command line is tools/track.mjs.+import { fft } from "./meter";++export type Stereo = [Float32Array, Float32Array];+export type Bar = { i: number; t: number; rmsDb: number };+export type Section = { fromBar: number; toBar: number; fromS: number; toS: number; level: "silent" | "quiet" | "mid" | "full"; rmsDb: number };+export type TrackAnalysis = {+ sr: number; durationS: number;+ bpm: number; beatS: number; beatsPerBar: number; barS: number;+ /** the strongest tempo peaks with their comb score relative to the winner (1 = the winner); empty when bpm was pinned */+ tempoCandidates: { bpm: number; rel: number }[];+ /** time of the first downbeat at or after 0 (s); earlier material is a pickup */+ downbeatS: number;+ bars: Bar[]; sections: Section[];+ key: { name: string; confidence: number; runnerUp: string };+ /** the median level of the bars that play (dB), the yardstick for everything below */+ bodyDb: number;+ /** when the last note has decayed into silence (s): the track's real end, whatever the file length says */+ lastSoundS: number;+ /** silence in the file after the last note (s) */+ tailS: number;+ /** stretches inside the track that drop out (a designed hard stop), at least 0.2 s long */+ stops: { atS: number; lenS: number }[];+};++const dB = (x: number) => 10 * Math.log10(x + 1e-20);+export const monoOf = (L: Float32Array, R: Float32Array = L) => { const m = new Float32Array(L.length); for (let i = 0; i < L.length; i++) m[i] = 0.5 * (L[i] + R[i]); return m; };++/** Mean power per block of `hop` samples, as dB. */+const levels = (x: Float32Array, hop: number) => {+ const n = Math.floor(x.length / hop), out = new Float64Array(n);+ for (let b = 0; b < n; b++) { let s = 0; for (let i = b * hop; i < (b + 1) * hop; i++) s += x[i] * x[i]; out[b] = dB(s / hop); }+ return out;+};+const median = (a: number[]) => { if (!a.length) return -Infinity; const s = [...a].sort((p, q) => p - q); return s[s.length >> 1]; };++/** Onset strength at a 5 ms hop: the rise of log energy (full band) and of the low band (the kick), mean removed. */+const onsetCurves = (x: Float32Array, sr: number) => {+ const hop = Math.max(1, Math.round(sr * 0.005)), n = Math.floor(x.length / hop), full = new Float64Array(n), low = new Float64Array(n);+ const k = 1 - Math.exp((-2 * Math.PI * 120) / sr); let lp = 0;+ for (let b = 0; b < n; b++) {+ let s = 0, sl = 0;+ for (let i = b * hop; i < (b + 1) * hop; i++) { lp += k * (x[i] - lp); s += x[i] * x[i]; sl += lp * lp; }+ full[b] = Math.log(1e-9 + s / hop); low[b] = Math.log(1e-9 + sl / hop);+ }+ const flux = (e: Float64Array) => { const o = new Float64Array(n); for (let b = 1; b < n; b++) o[b] = Math.max(0, e[b] - e[b - 1]); let m = 0; for (const v of o) m += v; m /= n || 1; for (let b = 0; b < n; b++) o[b] -= m; return o; };+ return { hopS: hop / sr, full: flux(full), low: flux(low) };+};+/** Mean onset strength on a beat comb of period P hops starting at phase ph (fractional positions, linear read). */+const combAt = (O: Float64Array, P: number, ph: number) => {+ let s = 0, c = 0;+ for (let t = ph; t < O.length - 1; t += P) { const i = Math.floor(t), f = t - i; s += O[i] * (1 - f) + O[i + 1] * f; c++; }+ return c ? s / c : -Infinity;+};+const bestPhase = (O: Float64Array, P: number, step = 1) => { let best = -Infinity, ph = 0; for (let p = 0; p < P; p += step) { const v = combAt(O, P, p); if (v > best) { best = v; ph = p; } } return { ph, score: best }; };++// Krumhansl-Kessler key profiles (major, minor), index 0 = the tonic.+const KK_MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88];+const KK_MINOR = [6.33, 2.68, 3.52, 5.38, 2.6, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17];+const NAMES = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];+const corr = (a: number[], b: number[]) => { const ma = a.reduce((p, q) => p + q, 0) / a.length, mb = b.reduce((p, q) => p + q, 0) / b.length; let s = 0, da = 0, db = 0; for (let i = 0; i < a.length; i++) { s += (a[i] - ma) * (b[i] - mb); da += (a[i] - ma) ** 2; db += (b[i] - mb) ** 2; } return da && db ? s / Math.sqrt(da * db) : 0; };++/**+ * Pitch-class energy from 55 Hz to 2 kHz: frames of 16384 samples (3 Hz bins at 48 kHz, finer than a+ * semitone at 55 Hz), power of spectral PEAKS only, so a tone's window lobe does not leak into its+ * neighbours (a 4096 frame smeared A into G# and Bb). At most 200 frames, spread over the track.+ */+export const chroma = (x: Float32Array, sr: number) => {+ const N = 16384, out = new Array(12).fill(0), frames = Math.max(1, Math.floor((x.length - N) / (N / 2))), stride = Math.max(1, Math.floor(frames / 200));+ const re = new Float64Array(N), im = new Float64Array(N), win = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N)), pw = new Float64Array(N / 2);+ for (let f = 0; f < frames; f += stride) {+ const a = f * (N / 2); if (a + N > x.length) break;+ for (let i = 0; i < N; i++) { re[i] = x[a + i] * win[i]; im[i] = 0; }+ fft(re, im);+ for (let k = 0; k < N / 2; k++) pw[k] = re[k] * re[k] + im[k] * im[k];+ for (let k = Math.max(1, Math.ceil((55 * N) / sr)); k <= Math.floor((2000 * N) / sr); k++) {+ if (!(pw[k] > pw[k - 1] && pw[k] >= pw[k + 1])) continue;+ const d = (0.5 * (pw[k - 1] - pw[k + 1])) / (pw[k - 1] - 2 * pw[k] + pw[k + 1] || 1), hz = ((k + d) * sr) / N; // parabolic peak+ out[((Math.round(12 * Math.log2(hz / 440)) % 12) + 12 + 9) % 12] += Math.sqrt(pw[k]);+ }+ }+ return out as number[];+};+/** The best of the 24 major and minor keys for a chroma vector, with the margin over the runner-up as confidence. */+export const keyOf = (ch: number[]) => {+ const all: { name: string; r: number }[] = [];+ for (let t = 0; t < 12; t++) {+ const rot = (p: number[]) => ch.map((_, i) => p[(i - t + 12) % 12]);+ all.push({ name: NAMES[t], r: corr(ch, rot(KK_MAJOR)) }, { name: NAMES[t] + "m", r: corr(ch, rot(KK_MINOR)) });+ }+ all.sort((a, b) => b.r - a.r);+ return { name: all[0].name, confidence: +(all[0].r - all[1].r).toFixed(3), runnerUp: all[1].name };+};++/**+ * Measure a track. `bpm` pins the tempo when you know it (the prompt asked for 120 and the take obeyed);+ * otherwise it is found between bpmRange by a comb over the onset curve and refined to 0.01 bpm.+ * `downbeatS` pins the bar phase when the ear disagrees with the kick-drum guess.+ */+export const analyzeTrack = (L: Float32Array, R: Float32Array, sr: number, o: { bpm?: number; bpmRange?: [number, number]; beatsPerBar?: number; downbeatS?: number } = {}): TrackAnalysis => {+ if (!Number.isSafeInteger(sr) || sr < 4000) throw new Error(`analyzeTrack: sample rate must be an integer of at least 4000, got ${sr}`);+ if (L.length < sr * 2) throw new Error(`analyzeTrack: the track is ${(L.length / sr).toFixed(2)} s; at least 2 s are needed to find a tempo`);+ const x = monoOf(L, R), durationS = x.length / sr, beatsPerBar = o.beatsPerBar ?? 4, [lo, hi] = o.bpmRange ?? [70, 180];+ if (o.bpm !== undefined && !(o.bpm >= 20 && o.bpm <= 300)) throw new Error(`analyzeTrack: bpm must be 20..300, got ${o.bpm}`);+ const { hopS, full, low } = onsetCurves(x, sr);+ let bpm = o.bpm ?? 0; const coarse: [number, number][] = [];+ if (!bpm) {+ // coarse: every 0.5 bpm, the best phase per tempo; then fine: 0.01 bpm around the winner+ let best = -Infinity;+ for (let b = lo; b <= hi + 1e-9; b += 0.5) { const P = 60 / b / hopS, s = bestPhase(full, P, 2).score; coarse.push([b, s]); if (s > best) { best = s; bpm = b; } }+ let fineBest = -Infinity, fine = bpm;+ for (let b = bpm - 0.6; b <= bpm + 0.6 + 1e-9; b += 0.01) { const P = 60 / b / hopS, s = bestPhase(full, P, 1).score; if (s > fineBest) { fineBest = s; fine = b; } }+ bpm = Math.round(fine * 100) / 100;+ }+ const beatS = 60 / bpm, P = beatS / hopS, barS = beatS * beatsPerBar;+ const beatPh = bestPhase(full, P, 0.25).ph * hopS; // first beat time in [0, beatS)+ let downbeatS = o.downbeatS;+ if (downbeatS === undefined) {+ // the bar's phase: of the beatsPerBar candidate beats, the one where the low band (kick) rises hardest+ let best = -Infinity; downbeatS = beatPh;+ for (let k = 0; k < beatsPerBar; k++) { const t = beatPh + k * beatS, s = combAt(low, barS / hopS, t / hopS) + 0.5 * combAt(full, barS / hopS, t / hopS); if (s > best) { best = s; downbeatS = t; } }+ }+ downbeatS = ((downbeatS % barS) + barS) % barS;+ // bars and their levels+ const bars: Bar[] = [];+ for (let i = 0, t = downbeatS; t < durationS - 1e-6; i++, t = downbeatS + i * barS) {+ const a = Math.floor(t * sr), b = Math.min(x.length, Math.floor((t + barS) * sr)); let s = 0; for (let j = a; j < b; j++) s += x[j] * x[j];+ bars.push({ i, t: +t.toFixed(4), rmsDb: +dB(s / Math.max(1, b - a)).toFixed(1) });+ }+ const bodyDb = median(bars.filter((b) => b.rmsDb > -70).map((b) => b.rmsDb));+ const cls = (v: number): Section["level"] => (v < bodyDb - 30 ? "silent" : v < bodyDb - 9 ? "quiet" : v < bodyDb - 3 ? "mid" : "full");+ const sections: Section[] = [];+ for (const b of bars) {+ const c = cls(b.rmsDb), last = sections[sections.length - 1];+ if (last && last.level === c) { last.toBar = b.i + 1; last.toS = +Math.min(durationS, b.t + barS).toFixed(3); last.rmsDb = Math.max(last.rmsDb, b.rmsDb); }+ else sections.push({ fromBar: b.i, toBar: b.i + 1, fromS: b.t, toS: +Math.min(durationS, b.t + barS).toFixed(3), level: c, rmsDb: b.rmsDb });+ }+ // the real end and the stops, on 50 ms blocks against the body level+ const blk = Math.round(sr * 0.05), lv = levels(x, blk), body50 = median([...lv].filter((v) => v > -70));+ let last = lv.length - 1; while (last >= 0 && lv[last] < body50 - 40) last--;+ const lastSoundS = +(((last + 1) * blk) / sr).toFixed(3), stops: TrackAnalysis["stops"] = [];+ let first = 0; while (first < lv.length && lv[first] < body50 - 40) first++;+ for (let b = first; b <= last; ) { if (lv[b] >= body50 - 30) { b++; continue; } const a = b; while (b <= last && lv[b] < body50 - 30) b++; const len = ((b - a) * blk) / sr; if (len >= 0.2) stops.push({ atS: +((a * blk) / sr).toFixed(2), lenS: +len.toFixed(2) }); }+ const peaks = coarse.filter(([, v], i) => v > (coarse[i - 1]?.[1] ?? -Infinity) && v >= (coarse[i + 1]?.[1] ?? -Infinity)).sort((p, q) => q[1] - p[1]).slice(0, 4);+ const tempoCandidates = peaks.map(([b, v]) => ({ bpm: b, rel: +(v / (peaks[0][1] || 1)).toFixed(3) }));+ return { sr, durationS: +durationS.toFixed(3), bpm, tempoCandidates, beatS: +beatS.toFixed(5), beatsPerBar, barS: +barS.toFixed(5), downbeatS: +downbeatS.toFixed(4), bars, sections, key: keyOf(chroma(x, sr)), bodyDb: +bodyDb.toFixed(1), lastSoundS, tailS: +Math.max(0, durationS - lastSoundS).toFixed(3), stops };+};++// ------------------------------------------------------------------------------------------- cutting+export type Seg = { from: number; to: number };+/**+ * A cut list from text. Accepts one segment per line ("8 36"), comma lists ("0:6, 8:36", "0-6"),+ * comments after #, CRLF, and no final newline. Bars ("bars 0-2, 4-17": whole bars, end exclusive)+ * need the analysis. Anything else throws with the line it could not read.+ */+export const parseSegs = (text: string, a?: Pick<TrackAnalysis, "downbeatS" | "barS">): Seg[] => {+ const body = text.replace(/#.*$/gm, "").trim();+ if (!body) throw new Error("cut: the segment list is empty");+ const bars = /^bars\b/i.test(body), parts = body.replace(/^bars\b/i, "").split(/[\n,;]+/).map((s) => s.trim()).filter(Boolean);+ if (bars && !a) throw new Error("cut: a bar list needs the track's analysis (tempo and downbeat)");+ return parts.map((p) => {+ const m = /^(-?\d+(?:\.\d+)?)\s*(?:[\s:\-]|to)\s*(-?\d+(?:\.\d+)?)$/.exec(p.replace(/\s+/g, " "));+ if (!m) throw new Error(`cut: cannot read segment "${p}" (write "from to" in seconds, or "bars a-b")`);+ const x = Number(m[1]), y = Number(m[2]);+ return bars ? { from: +(a!.downbeatS + x * a!.barS).toFixed(4), to: +(a!.downbeatS + y * a!.barS).toFixed(4) } : { from: x, to: y };+ });+};++export type CutPlan = {+ segs: Seg[]; lengthS: number;+ /** each join: where it falls in the edit, and how far each side is from a downbeat (ms) */+ joins: { atS: number; fromOffMs: number; toOffMs: number }[];+ /** the edit's downbeats (s), for trackGrid */+ downbeats: number[];+ /** the track's designed stops as they fall in the edit (s): declared silences, so the shape check does not call them holes */+ quiet: { fromS: number; toS: number; reason: string }[];+ errors: string[]; warnings: string[];+};+const offBar = (a: Pick<TrackAnalysis, "downbeatS" | "barS">, t: number) => { const k = Math.round((t - a.downbeatS) / a.barS); return { ms: (t - (a.downbeatS + k * a.barS)) * 1000, bar: k, at: a.downbeatS + k * a.barS }; };+/**+ * Check a cut against the track before rendering it. Errors (refuse): a segment outside the file, a join+ * off a downbeat by more than `barTolMs`, an outro that stops before the track's last note (unless the+ * film fades it on purpose with `fadeOutS`), a segment that carries silence from after the last note,+ * and an edit shorter than the picture. Warnings: an edit that runs past the picture (the mux cuts it).+ */+export const planCut = (a: TrackAnalysis, segs: Seg[], o: { filmS?: number; barTolMs?: number; fadeOutS?: number; endTolS?: number } = {}): CutPlan => {+ const errors: string[] = [], warnings: string[] = [], tol = o.barTolMs ?? 30, endTol = o.endTolS ?? 0.5; // the same half second filmshape allows at the end; a shipped brand-launch v12 ended 0.72 s past the last note and fails it+ if (!segs.length) errors.push("the cut has no segments");+ segs.forEach((s, i) => {+ const where = `segment ${i + 1} (${s.from}-${s.to} s)`;+ if (!(Number.isFinite(s.from) && Number.isFinite(s.to)) || s.to <= s.from) errors.push(`${where} has no length`);+ if (s.from < 0 || s.to > a.durationS + 1e-6) errors.push(`${where} lies outside the track (0-${a.durationS} s)`);+ // the first segment may start at 0 (a pickup), the last may end at the track's own end; every join sits on a bar+ if (i > 0 || s.from > 0.05) { const b = offBar(a, s.from); if (Math.abs(b.ms) > tol) errors.push(`${where} starts ${b.ms.toFixed(0)} ms off a downbeat: start at bar ${b.bar} (${b.at.toFixed(3)} s)`); }+ if (i < segs.length - 1) { const b = offBar(a, s.to); if (Math.abs(b.ms) > tol) errors.push(`${where} ends ${b.ms.toFixed(0)} ms off a downbeat: end at bar ${b.bar} (${b.at.toFixed(3)} s)`); }+ if (s.to > a.lastSoundS + endTol) errors.push(`${where} runs ${(s.to - a.lastSoundS).toFixed(2)} s past the track's last note at ${a.lastSoundS} s, so the edit carries silence; end it at ${a.lastSoundS} s (a brand launch film went silent 4 s early this way)`);+ });+ const lastSeg = segs[segs.length - 1];+ if (lastSeg && lastSeg.to < a.lastSoundS - 0.05 && !(o.fadeOutS && o.fadeOutS > 0)) errors.push(`the outro stops at ${lastSeg.to} s, before the track's last note at ${a.lastSoundS} s: end the last segment on the track's own ending (cut whole bars earlier instead), or fade it on purpose with fadeOutS`);+ const lengthS = segs.reduce((p, s) => p + (s.to - s.from), 0);+ if (o.filmS !== undefined) {+ // where the music is last heard in the edit: the last segment's own end, or the track's last note if that comes first+ const soundEnd = lastSeg ? lengthS - (lastSeg.to - Math.min(lastSeg.to, Math.max(lastSeg.from, a.lastSoundS))) : 0;+ if (soundEnd < o.filmS - 0.5) errors.push(`the music is last heard at ${soundEnd.toFixed(2)} s of the edit and the picture runs to ${o.filmS.toFixed(2)} s: ${(o.filmS - soundEnd).toFixed(2)} s of silence at the end; add ${Math.ceil((o.filmS - soundEnd) / a.barS)} bar(s) before the outro, or end the picture with the music`);+ else if (soundEnd > o.filmS + 0.5) { const over = soundEnd - o.filmS, bars = Math.floor(over / a.barS); warnings.push(`the music plays ${over.toFixed(2)} s past the picture; the mux would cut its ending mid-note: ${bars ? `drop ${bars} bar(s) before the outro, or ` : ""}extend the last shot by ${over.toFixed(2)} s`); }+ }+ const joins: CutPlan["joins"] = [], downbeats: number[] = [], quiet: CutPlan["quiet"] = [];+ let at = 0;+ segs.forEach((s, i) => {+ if (i > 0) joins.push({ atS: +at.toFixed(4), fromOffMs: +offBar(a, segs[i - 1].to).ms.toFixed(1), toOffMs: +offBar(a, s.from).ms.toFixed(1) });+ for (const b of a.bars) if (b.t >= s.from - 1e-6 && b.t < s.to - 1e-6) downbeats.push(+(at + b.t - s.from).toFixed(4));+ for (const st of a.stops) { const x = Math.max(st.atS, s.from), y = Math.min(st.atS + st.lenS, s.to); if (y > x) quiet.push({ fromS: +Math.max(0, at + x - s.from - 0.1).toFixed(3), toS: +(at + y - s.from + 0.1).toFixed(3), reason: `the track's own stop at ${st.atS} s` }); }+ at += s.to - s.from;+ });+ return { segs, lengthS: +lengthS.toFixed(4), joins, downbeats, quiet, errors, warnings };+};++/**+ * Render a cut. Each join is a centred equal-power crossfade of `xfadeMs` (default 12): the outgoing+ * segment runs half a fade past its end and the incoming one starts half a fade early, so the edit is+ * exactly the sum of the segments and every bar stays where planCut said it is. `fadeOutS` fades the end.+ */+export const renderCut = (L: Float32Array, R: Float32Array, sr: number, segs: Seg[], o: { xfadeMs?: number; fadeOutS?: number } = {}): Stereo => {+ const h = Math.round(((o.xfadeMs ?? 12) / 1000) * sr / 2), total = segs.reduce((p, s) => p + Math.round(s.to * sr) - Math.round(s.from * sr), 0);+ const oL = new Float32Array(total), oR = new Float32Array(total);+ let at = 0;+ segs.forEach((s, i) => {+ const a = Math.round(s.from * sr), b = Math.round(s.to * sr), pre = i > 0 ? h : 0, post = i < segs.length - 1 ? h : 0;+ for (let j = -pre; j < b - a + post; j++) {+ const src = a + j, dst = at + j; if (src < 0 || src >= L.length || dst < 0 || dst >= total) continue;+ let g = 1;+ if (j < pre) g = Math.sin((Math.PI / 2) * ((j + pre) / (2 * pre || 1))); // fade in across the join+ if (j >= b - a - post) g *= Math.cos((Math.PI / 2) * ((j - (b - a - post)) / (2 * post || 1))); // fade out across the next join+ oL[dst] += L[src] * g; oR[dst] += R[src] * g;+ }+ at += b - a;+ });+ if (o.fadeOutS && o.fadeOutS > 0) { const n = Math.min(total, Math.round(o.fadeOutS * sr)); for (let i = 0; i < n; i++) { const g = Math.sin((Math.PI / 2) * (i / n)); oL[total - 1 - i] *= g; oR[total - 1 - i] *= g; } }+ return [oL, oR];+};++// ------------------------------------------------------------------------------------------- the grid+/**+ * The edit's bar grid, to fit flexible holds to the music (a brand launch film's holds were solved by hand+ * bisection per version). holdTo(startS, minS) is the shortest hold of at least minS whose end lands+ * on a downbeat; landOn(t) is the downbeat nearest t.+ */+export const trackGrid = (downbeats: number[], fps?: number) => {+ if (!downbeats.length) throw new Error("trackGrid: no downbeats (analyse the track, or plan the cut first)");+ const sorted = [...downbeats].sort((a, b) => a - b);+ const next = (t: number) => sorted.find((d) => d >= t - 1e-9);+ return {+ downbeats: sorted,+ landOn: (t: number) => sorted.reduce((p, d) => (Math.abs(d - t) < Math.abs(p - t) ? d : p), sorted[0]),+ holdTo: (startS: number, minS: number) => {+ const d = next(startS + minS);+ if (d === undefined) throw new Error(`trackGrid: no downbeat after ${(startS + minS).toFixed(2)} s; the music ends at bar ${sorted.length}`);+ return { holdS: +(d - startS).toFixed(4), landS: d, bar: sorted.indexOf(d), frame: fps ? Math.round(d * fps) : undefined };+ },+ };+};++// ------------------------------------------------------------------------------------------- pitch+/**+ * How much a short sound carries a note, 0..1: the normalised autocorrelation's highest peak between+ * 90 Hz and 2 kHz (past the first zero crossing, so the broad lobe of noise does not count), scaled by+ * how long the sound rings within 20 dB of its peak, against 60 ms. Calibrated on real sounds: the+ * a brand launch kit the director approved (strikes cut to 8-22 ms, a 174 ms boom) measures 0.07 to 0.45; full+ * notes from the sound pack (marimba, glockenspiel, harp, tubular bell, 150 ms and longer) measure 0.77+ * to 0.98. Below 90 Hz a boom reads as weight, not a note. Over 0.5 under someone else's music fails.+ */+export const pitchSalience = (x: Float32Array, sr: number, o: { fMin?: number; fMax?: number; ringMs?: number } = {}) => {+ let pk = 0, at = 0; for (let i = 0; i < x.length; i++) if (Math.abs(x[i]) > pk) { pk = Math.abs(x[i]); at = i; }+ if (pk < 1e-6) return { salience: 0, hz: NaN, ringMs: 0, raw: 0 };+ // ring: how long the 2 ms envelope stays within 20 dB of the peak, from the peak on+ const w = Math.max(1, Math.round(sr * 0.002)), floor = pk * 0.1; let end = at;+ for (let i = at; i < x.length; i += w) { let m = 0; for (let j = i; j < Math.min(x.length, i + w); j++) m = Math.max(m, Math.abs(x[j])); if (m >= floor) end = i + w; else break; }+ const ringMs = ((end - at) / sr) * 1000;+ // autocorrelation over the ringing part (at most 120 ms)+ const a = Math.max(0, at - Math.round(sr * 0.002)), b = Math.min(x.length, Math.max(end, a + Math.round(sr * 0.01)), a + Math.round(sr * 0.12)), n = b - a;+ const lagMin = Math.max(1, Math.floor(sr / (o.fMax ?? 2000))), lagMax = Math.min(n - 1, Math.ceil(sr / (o.fMin ?? 90)));+ let r0 = 0; for (let i = a; i < b; i++) r0 += x[i] * x[i];+ if (r0 <= 0 || lagMax <= lagMin) return { salience: 0, hz: NaN, ringMs, raw: 0 };+ const r = (lag: number) => { let s = 0; for (let i = a; i + lag < b; i++) s += x[i] * x[i + lag]; return s / r0; };+ let lag = 1; while (lag < lagMax && r(lag) > 0) lag++; // past the main lobe+ let raw = 0, best = NaN;+ for (let L = Math.max(lag, lagMin); L <= lagMax; L++) { const v = r(L); if (v > raw) { raw = v; best = L; } }+ const salience = raw * Math.min(1, ringMs / (o.ringMs ?? 60));+ return { salience: +salience.toFixed(3), hz: Number.isFinite(best) ? +(sr / best).toFixed(1) : NaN, ringMs: +ringMs.toFixed(1), raw: +raw.toFixed(3) };+};+export const PITCHED = 0.5;++/** When the music in a mix stops being audible (s), on 50 ms blocks against its own body level. */+export const lastSoundOf = (L: Float32Array, R: Float32Array, sr: number, belowBodyDb = 40) => {+ const blk = Math.round(sr * 0.05), lv = levels(monoOf(L, R), blk), body = median([...lv].filter((v) => v > -70));+ if (!Number.isFinite(body)) return 0;+ let last = lv.length - 1; while (last >= 0 && lv[last] < body - belowBodyDb) last--;+ return ((last + 1) * blk) / sr;+};++/**+ * Each effect in an effects stem (silent between cues) with its pitch salience: an effect starts where+ * the 2 ms peak envelope rises out of silence (2 % of the stem's peak) after at least 20 ms below it,+ * and is measured up to the next effect or 400 ms. For soundcheck --sfx on a film over an external track.+ */+export const stemCues = (L: Float32Array, R: Float32Array, sr: number) => {+ const x = monoOf(L, R), hop = Math.max(1, Math.round(sr * 0.002)), n = Math.floor(x.length / hop), env = new Float64Array(n);+ let peak = 0;+ for (let b = 0; b < n; b++) { let m = 0; for (let i = b * hop; i < (b + 1) * hop; i++) m = Math.max(m, Math.abs(x[i])); env[b] = m; peak = Math.max(peak, m); }+ const thr = peak * 0.02, on: number[] = []; let below = 10;+ for (let b = 0; b < n; b++) { if (env[b] <= thr) { below++; continue; } if (below >= 10) on.push(b); below = 0; }+ return on.map((b, k) => { const a = b * hop, e = Math.min(x.length, (on[k + 1] ?? n) * hop, a + Math.round(sr * 0.4)); return { atS: +(a / sr).toFixed(3), ...pitchSalience(x.subarray(a, e), sr) }; });+};diff --git a/skills/anidoodle/engine/src/canvas-core/music/trackMix.ts b/skills/anidoodle/engine/src/canvas-core/music/trackMix.tsnew file mode 100644index 0000000..a3168b0--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/music/trackMix.ts@@ -0,0 +1,87 @@+// A FILM'S EFFECTS OVER SOMEONE ELSE'S MUSIC. The engine's mix (launchSound.mixLaunch: panned cues,+// the score ducked under the ones that matter, every cue measured against the music at its own moment+// and raised until it is heard, the dense delivery master) applied to a generated or supplied track,+// plus the three rules a brand launch film learned by ear:+// 1. Effects are transients, never notes. A tuned kind (a chime, a tuned riser, impact:bloom,+// press:confirm) is refused, and every placed sound's pitch salience must stay under 0.5.+// A cue may carry a note only when `pitched` says why in words.+// 2. Every cue is heard: the buried-cue guard measures the track's local loudness at each cue (the+// film's effects stem once sat 29 dB under the music and nobody could tell without listening).+// 3. The music never ends before the picture: the track's last audible moment must reach the film's end.+// Pure: arrays in, arrays out. tools/track.mjs mix reads the files.+import { mixLaunch, type LaunchCue } from "../launchSound";+import { sfxNeeds, SFX, SFX_KINDS, type SfxKind } from "./sfxKit";+import type { SfxCue, SfxPlan, PlacedCue, SfxAudibility } from "./sfxMix";+import type { Delivered } from "./delivery";+import { pitchSalience, lastSoundOf, monoOf, PITCHED, type Stereo } from "./track";++export type TrackCue = SfxCue & {+ /** stereo position -1 (left) .. 1 (right) */+ pan?: number;+ /** why this cue may carry a note under the track (a deliberate musical button). Without it, a pitched cue fails. */+ pitched?: string;+};+export type TrackPlan = Omit<SfxPlan, "cues" | "score" | "key"> & { cues: TrackCue[] };+export type TrackMix = {+ L: Float32Array; R: Float32Array; sfx: Stereo; placed: PlacedCue[]; audibility: SfxAudibility[];+ raised: { i: number; db: number }[];+ pitch: { i: number; label: string; kind: string; salience: number; hz: number; ringMs: number; allowed?: string; ok: boolean }[];+ ending: { musicEndS: number; filmS: number; ok: boolean; msg?: string };+ lufs: number; dbtp: number; delivered?: Delivered; ok: boolean; problems: string[];+};++/** "tap:thump -9 pan=0.3" -> { kind, variant, gainDb, pan }. Gain is optional, in dB on top of the kind's level. */+export const parseSoundSpec = (spec: string): Omit<TrackCue, "frame"> => {+ const parts = String(spec).trim().split(/\s+/), [kind, variant] = parts[0].split(":");+ if (!(kind in SFX)) throw new Error(`sound "${spec}": unknown kind "${kind}" (kinds: ${SFX_KINDS.join(", ")})`);+ const k = kind as SfxKind;+ if (variant !== undefined && !SFX[k].variants.includes(variant)) throw new Error(`sound "${spec}": ${kind} has no variant "${variant}" (variants: ${SFX[k].variants.join(", ")})`);+ const out: Omit<TrackCue, "frame"> = { kind: k, variant };+ for (const p of parts.slice(1)) {+ const m = /^(pan|duck|snap)=(.+)$/.exec(p);+ if (m) { if (m[1] === "pan") out.pan = Number(m[2]); else if (m[1] === "duck") out.duckDb = Number(m[2]); else out.snap = m[2] as TrackCue["snap"]; continue; }+ if (/^[+-]?\d+(\.\d+)?$/.test(p)) { out.gainDb = Number(p); continue; }+ throw new Error(`sound "${spec}": cannot read "${p}" (write e.g. "tap:thump -9 pan=0.3")`);+ }+ if (out.pan !== undefined && !(out.pan >= -1 && out.pan <= 1)) throw new Error(`sound "${spec}": pan must be -1..1`);+ return out;+};++/** Refuse tuned kinds under a track the engine does not control, unless the cue says why. */+export const checkTrackCues = (plan: TrackPlan) => {+ plan.cues.forEach((c, i) => {+ const v = c.variant ?? SFX[c.kind]?.variants[0];+ if (c.kind in SFX && sfxNeeds(c.kind, v, c).key && !c.pitched?.trim())+ throw new Error(`track mix: cue #${i} ${c.kind}:${v}${c.label ? ` "${c.label}"` : ""} is tuned to a key, and the music here is a track the engine did not write: under someone else's music, effects are transients, never notes. Use tap:${c.kind === "impact" ? "impact" : "tock"} (or another tap variant), or set pitched: "<why this note belongs>"`);+ });+};++export const mixOverTrack = (music: Stereo | null, plan: TrackPlan, sr = 48000, o: { maxRaiseDb?: number } = {}): TrackMix => {+ checkTrackCues(plan);+ const filmS = plan.frames / plan.fps, n = Math.round(filmS * sr), problems: string[] = [];+ const cues: LaunchCue[] = plan.cues.map((c) => ({ ...c, role: "land", x: c.pan === undefined ? undefined : (c.pan + 1) / 2 }));+ const m = mixLaunch(music, { ...plan, cues, W: 1, spread: 1, master: plan.master ?? "dense" }, sr, o.maxRaiseDb ?? 8);+ // the effects stem, rebuilt from the placed (panned, raised) sounds+ const fx: Stereo = [new Float32Array(n), new Float32Array(n)];+ for (const pc of m.placed) for (let i = 0; i < pc.sound.L.length && pc.start + i < n; i++) { fx[0][pc.start + i] += pc.sound.L[i]; fx[1][pc.start + i] += pc.sound.R[i]; }+ const pitch = m.placed.map((pc) => {+ const c = plan.cues[pc.i], p = pitchSalience(monoOf(pc.sound.L, pc.sound.R), sr), allowed = c.pitched?.trim() || undefined;+ return { i: pc.i, label: c.label ?? `${c.kind}:${pc.sound.variant}`, kind: `${c.kind}:${pc.sound.variant}`, salience: p.salience, hz: p.hz, ringMs: p.ringMs, allowed, ok: !!allowed || p.salience <= PITCHED };+ });+ for (const p of pitch) if (!p.ok) problems.push(`cue #${p.i} "${p.label}" (${p.kind}) carries a note (pitch salience ${p.salience.toFixed(2)} at ${p.hz} Hz, rings ${p.ringMs} ms): use a tap variant, or set pitched with the reason`);+ for (const a of m.audibility) if (!a.ok) problems.push(`cue #${a.i} "${a.label}" is buried ${a.marginDb.toFixed(1)} dB under the track at ${a.atS.toFixed(2)} s even after raising it 8 dB: give it a bigger kind (tock, thump) or a duck`);+ const musicEndS = music ? Math.min(lastSoundOf(music[0], music[1], sr), music[0].length / sr) : 0;+ const ending = { musicEndS: +musicEndS.toFixed(3), filmS: +filmS.toFixed(3), ok: !music || musicEndS >= filmS - 0.3, msg: undefined as string | undefined };+ if (!ending.ok) { ending.msg = `the music ends at ${musicEndS.toFixed(2)} s and the picture at ${filmS.toFixed(2)} s: ${(filmS - musicEndS).toFixed(2)} s of silence at the end. Extend the outro by whole bars (track.mjs cut --film-s ${filmS.toFixed(2)}) or end the picture with the music`; problems.push(ending.msg); }+ return { L: m.L, R: m.R, sfx: fx, placed: m.placed, audibility: m.audibility, raised: m.raised.map(({ i, db }) => ({ i, db })), pitch, ending, lufs: m.lufs, dbtp: m.dbtp, delivered: m.delivered, ok: !problems.length, problems };+};++/** The mix as a table a person reads: each cue's margin over the track, any raise, its pitch salience; then the problems. */+export const trackMixReport = (m: TrackMix) => {+ const o = [`MIX OVER TRACK ${m.placed.length} cues, ${m.lufs.toFixed(1)} LUFS, ${m.dbtp.toFixed(2)} dBTP; music ends ${m.ending.musicEndS} s, picture ${m.ending.filmS} s`];+ o.push(` ${"at s".padStart(7)} ${"cue".padEnd(26)} ${"kind".padEnd(13)} ${"margin".padStart(7)} ${"raised".padStart(7)} ${"pitch".padStart(6)}`);+ const raised = new Map(m.raised.map((r) => [r.i, r.db]));+ m.audibility.forEach((a, k) => { const p = m.pitch[k]; o.push(` ${a.atS.toFixed(2).padStart(7)} ${String(a.label || p.label).slice(0, 26).padEnd(26)} ${p.kind.padEnd(13)} ${a.marginDb.toFixed(1).padStart(6)} ${(raised.has(a.i) ? "+" + raised.get(a.i)!.toFixed(1) : "").padStart(7)} ${p.salience.toFixed(2).padStart(6)}${a.ok && p.ok ? "" : " <-"}`); });+ for (const p of m.problems) o.push(` FAIL ${p}`);+ return o.join("\n");+};diff --git a/skills/anidoodle/engine/src/canvas-core/people.ts b/skills/anidoodle/engine/src/canvas-core/people.tsnew file mode 100644index 0000000..c07d4aa--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/people.ts@@ -0,0 +1,80 @@+// PEOPLE. Real people in a film, placed by the size of their HEAD, not the size of their photo.+// On a brand launch film three speaker cut-outs were placed by photo size and their heads came out+// 370, 270 and 190 px; the director: "ines's image looks bigger than tomas and priya... check proportions".+// headOf(alpha, w, h) the head box of a head-and-shoulders cut-out, from its alpha alone+// placePerson(head, o) the scale and offset that put that head at headPx tall, crown at crownY+// drawPerson(ctx, env, o) draws the cut-out so, and reports "head:<group>/<name>" to the frame+// probe: framecheck fails a group whose heads differ by more than 10 %+// popOut(ctx, circle, draw) a person on a disc: the body clipped by the circle, the head free above it+// A per-asset head box from the manifest (o.head) always wins over the detected one.+import { probeRect, type Ctx, type Env } from "./core";++export type Box = { x0: number; y0: number; x1: number; y1: number };++/**+ * The head box of a cut-out from its alpha channel (one byte per pixel, row-major, or RGBA when+ * `stride` is 4). The head is the part above the neck, and the neck is the narrowest row between 12 %+ * and 50 % of the figure's height under its crown that is clearly narrower than both the head above+ * and the shoulders below. With no such row (a head-only crop, an oval portrait) the whole figure is+ * the head. Returns null for an empty image.+ */+export const headOf = (alpha: ArrayLike<number>, w: number, h: number, stride = 1, threshold = 32): Box | null => {+ const left = new Array<number>(h).fill(-1), right = new Array<number>(h).fill(-1);+ let top = -1, bottom = -1;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (alpha[(y * w + x) * stride + (stride - 1)] > threshold) { if (left[y] < 0) left[y] = x; right[y] = x; if (top < 0) top = y; bottom = y; }+ if (top < 0) return null;+ const bh = bottom - top + 1, from = top + Math.max(1, Math.floor(0.12 * bh)), to = Math.min(bottom, top + Math.floor(0.5 * bh));+ const wdOf = (y: number) => (left[y] < 0 ? 0 : right[y] - left[y] + 1);+ // the widest row from each row down (the shoulders a neck must sit on)+ const below = new Array<number>(h + 1).fill(0); for (let y = bottom; y >= top; y--) below[y] = Math.max(below[y + 1], wdOf(y));+ // A neck is a row clearly narrower than the head above it AND the shoulders below it. The top of+ // an oval cut-out or a head-only crop is narrow too, but nothing above it is wider: no neck there.+ let neck = -1, best = Infinity, above = 0;+ for (let y = top; y < from; y++) above = Math.max(above, wdOf(y));+ for (let y = from; y <= to; y++) { const wd = wdOf(y); if (wd > 0 && wd < best && above >= wd * 1.15 && below[y + 1] >= wd * 1.15) { best = wd; neck = y; } above = Math.max(above, wd); }+ // no neck: the whole figure is the head (scaling it by a sliver of its top made the person ~8x too big)+ const end = neck < 0 ? bottom + 1 : neck;+ let x0 = w, x1 = 0; for (let y = top; y < end; y++) if (left[y] >= 0) { x0 = Math.min(x0, left[y]); x1 = Math.max(x1, right[y]); }+ return { x0, y0: top, x1: x1 + 1, y1: end };+};++/** Scale and top-left that draw an image whose head is `head` (image px) at headPx tall, crown at (cx, crownY). */+export const placePerson = (head: Box, o: { cx: number; crownY: number; headPx: number }) => {+ const s = o.headPx / Math.max(1, head.y1 - head.y0);+ return { s, x: o.cx - ((head.x0 + head.x1) / 2) * s, y: o.crownY - head.y0 * s };+};++const headCache = (env: Env, name: string, img: CanvasImageSource & { width: number; height: number }) => {+ const k = `people:head:${name}`; let b = env.cache.get(k) as Box | null | undefined;+ if (b === undefined) { const L = env.canvas(img.width, img.height); L.ctx.drawImage(img, 0, 0); b = headOf(L.ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); env.cache.set(k, b); }+ return b;+};++/**+ * Draw the cut-out asset `name` with its head `headPx` tall, centred on cx, crown at crownY (film px),+ * and report the head box to the frame probe as head:<group>/<name>. Returns the placement and the head+ * box on screen. People shown as one sequence share a group and a headPx.+ */+export const drawPerson = (ctx: Ctx, env: Env, o: { name: string; group: string; cx: number; crownY: number; headPx: number; head?: Box; alpha?: number }) => {+ const img = env.image?.(o.name) as (CanvasImageSource & { width: number; height: number }) | undefined;+ if (!img) throw new Error(`drawPerson: no image asset '${o.name}'`);+ const head = o.head ?? headCache(env, o.name, img); if (!head) throw new Error(`drawPerson: '${o.name}' has no opaque pixels (a cut-out needs alpha)`);+ const p = placePerson(head, o);+ ctx.save(); if (o.alpha !== undefined) ctx.globalAlpha *= o.alpha;+ ctx.drawImage(img, p.x, p.y, img.width * p.s, img.height * p.s);+ probeRect(ctx, env, p.x + head.x0 * p.s, p.y + head.y0 * p.s, (head.x1 - head.x0) * p.s, (head.y1 - head.y0) * p.s, `head:${o.group}/${o.name}`);+ ctx.restore();+ return { ...p, head: { x0: p.x + head.x0 * p.s, y0: p.y + head.y0 * p.s, x1: p.x + head.x1 * p.s, y1: p.y + head.y1 * p.s } };+};++/**+ * A person on a disc (the hosts card): `draw` is clipped to the circle below its centre line and free+ * above it, so the body sits in the circle and the head pops out over the rim. The disc itself is the+ * caller's (a coded circle stays a perfect circle).+ */+export const popOut = (ctx: Ctx, c: { cx: number; cy: number; r: number }, draw: () => void) => {+ ctx.save(); ctx.beginPath();+ ctx.arc(c.cx, c.cy, c.r, 0, Math.PI * 2);+ ctx.rect(c.cx - c.r, c.cy - c.r * 4, c.r * 2, c.r * 4); // the band above the centre line, as wide as the disc (same winding: one region)+ ctx.clip(); draw(); ctx.restore();+};diff --git a/skills/anidoodle/engine/src/canvas-core/productUI.ts b/skills/anidoodle/engine/src/canvas-core/productUI.tsindex 9a609ad..f63f2c1 100644--- a/skills/anidoodle/engine/src/canvas-core/productUI.ts+++ b/skills/anidoodle/engine/src/canvas-core/productUI.ts@@ -27,7 +27,7 @@ export type ProductUI = {layout?: "list" | "cards";before: UiState; after: UiState;};-export type UiTheme = { bg: string; card: string; ink: string; soft: string; mute: string; line: string; chip: string; accent: string; paper: string };+export type UiTheme = { bg: string; card: string; ink: string; soft: string; mute: string; line: string; chip: string; accent: string; paper: string; font?: (w: number, px: number) => string; onAccent?: string; radius?: number; button?: "pill" | "square" }; // font, onAccent: a custom look's text face and the label colour on its accent; radius: every corner's ceiling at 1x; button: its action's shape// the move: t0 is the press; items leave one after another, `stagger` frames apart, each on a springexport type UiMorph = { f: number; t0: number; stagger?: number; omega?: number; zeta?: number };export type UiOpts = { minPx?: number; typed?: string; caret?: boolean; press?: number; hot?: number; accent?: string };@@ -51,7 +51,9 @@ const geo = (r0: Rect, ui: ProductUI, minPx: number): Geo => { // sized to own iconst top = headH + 18 * u + (ui.command !== undefined ? cmdH + 18 * u : 0) + (nStats ? statH + 18 * u : 0);const n = Math.max(ui.before.items.length, ui.after.items.length, 1), cards = ui.layout === "cards", rows = cards ? Math.ceil(n / 2) : n;const bodyW = r0.w - 2 * pad, room = r0.h - top - pad;- const row = cards ? Math.min(room / rows, (bodyW / 2) * 0.62) : clamp(room / rows, px.row * 2.3, px.row * 3.2);+ // (in a tall rectangle, a phone frame's, a list's rows are tall touch rows and the window fills its+ // rectangle; capped at a desktop height there, it left the lower third of a 9:16 frame empty)+ const row = cards ? Math.min(room / rows, (bodyW / 2) * 0.62) : clamp(room / rows, px.row * 2.3, px.row * (r0.h > r0.w * 1.05 ? 4.5 : 3.2));const h = Math.min(r0.h, top + rows * row + pad), r = { x: r0.x, y: r0.y + (r0.h - h) / 2, w: r0.w, h };const head = { x: r.x, y: r.y, w: r.w, h: headH };const aw = Math.min(r.w * 0.42, px.row * 0.62 * ui.action.length + 64 * u), ah = Math.max(52 * u, px.row * 1.9);@@ -70,6 +72,8 @@ const slot = (g: Geo, ui: ProductUI, i: number): Rect => {export const uiWindow = (r: Rect, ui: ProductUI, minPx = 0): Rect => geo(r, ui, minPx).win;/** Where the action button is (its centre), for the pointer and the sound's pan. */export const uiActionAt = (r: Rect, ui: ProductUI, minPx = 0): P => { const a = geo(r, ui, minPx).action; return [a.x + a.w / 2, a.y + a.h / 2]; };+/** The action button's rectangle (where a drop can sit beside it, clear of its word). */+export const uiActionRect = (r: Rect, ui: ProductUI, minPx = 0): Rect => geo(r, ui, minPx).action;/** Where the command bar's caret starts (its left text edge and centre line), when the UI has one. */export const uiCommandAt = (r: Rect, ui: ProductUI, minPx = 0): Rect | null => geo(r, ui, minPx).command;@@ -102,25 +106,27 @@ const num = (a: number | string | undefined, b: number | string | undefined, p:// ---------------------------------------------------------------- drawingexport const drawProductUI = (ctx: Ctx, r0: Rect, ui: ProductUI, m: UiMorph, T: UiTheme, o: UiOpts = {}) => {const g = geo(r0, ui, o.minPx ?? 0), u = g.u, acc = o.accent ?? T.accent, r = g.win;+ // (a look's radius caps every corner, so a square brand's product is square too; a square button is square)+ const RAD = (x: number) => (T.radius !== undefined ? Math.min(x, T.radius * u) : x);// the window- for (let i = 5; i >= 1; i--) { ctx.fillStyle = "rgba(20,24,30,0.022)"; rr(ctx, r.x - i * 2, r.y + i * 3, r.w + i * 4, r.h + i * 3, 24 * u + i * 2); ctx.fill(); }- ctx.fillStyle = T.card; rr(ctx, r.x, r.y, r.w, r.h, 24 * u); ctx.fill();+ for (let i = 5; i >= 1; i--) { ctx.fillStyle = "rgba(20,24,30,0.022)"; rr(ctx, r.x - i * 2, r.y + i * 3, r.w + i * 4, r.h + i * 3, RAD(24 * u + i * 2)); ctx.fill(); }+ ctx.fillStyle = T.card; rr(ctx, r.x, r.y, r.w, r.h, RAD(24 * u)); ctx.fill();ctx.lineWidth = 1.5 * u; ctx.strokeStyle = T.line; ctx.stroke();// the head: the product's name, its sections, the action- ctx.textBaseline = "middle"; ctx.font = SANS(700, g.px.title); ctx.fillStyle = T.ink;+ ctx.textBaseline = "middle"; ctx.font = (T.font ?? SANS)(700, g.px.title); ctx.fillStyle = T.ink;ctx.fillText(ui.title, r.x + 28 * u, g.head.y + g.head.h / 2);let nx = r.x + 28 * u + ctx.measureText(ui.title).width + 26 * u;- ctx.font = SANS(500, g.px.nav);- (ui.nav ?? []).forEach((t, i) => { const w = ctx.measureText(t).width; if (nx + w > g.action.x - 20 * u) return; if (i === 0) { ctx.fillStyle = T.chip; rr(ctx, nx - 12 * u, g.head.y + g.head.h / 2 - g.px.nav * 0.95, w + 24 * u, g.px.nav * 1.9, g.px.nav); ctx.fill(); } ctx.fillStyle = i === 0 ? T.ink : T.mute; ctx.fillText(t, nx, g.head.y + g.head.h / 2); nx += w + 36 * u; });+ ctx.font = (T.font ?? SANS)(500, g.px.nav);+ (ui.nav ?? []).forEach((t, i) => { const w = ctx.measureText(t).width; if (nx + w > g.action.x - 20 * u) return; if (i === 0) { ctx.fillStyle = T.chip; rr(ctx, nx - 12 * u, g.head.y + g.head.h / 2 - g.px.nav * 0.95, w + 24 * u, g.px.nav * 1.9, RAD(g.px.nav)); ctx.fill(); } ctx.fillStyle = i === 0 ? T.ink : T.mute; ctx.fillText(t, nx, g.head.y + g.head.h / 2); nx += w + 36 * u; });const pr = o.press ?? 0, q = 1 - 0.06 * pr, a = g.action;const hot = Math.max(o.hot ?? 0, pr); ctx.fillStyle = hot > 0 ? shade(acc, 1 - 0.18 * hot) : acc;- rr(ctx, a.x + (a.w * (1 - q)) / 2, a.y + (a.h * (1 - q)) / 2, a.w * q, a.h * q, (a.h * q) / 2); ctx.fill();- ctx.fillStyle = "#fff"; ctx.font = SANS(600, g.px.row * 0.8 * q); ctx.textAlign = "center"; ctx.fillText(ui.action, a.x + a.w / 2, a.y + a.h / 2 + 1); ctx.textAlign = "left";+ rr(ctx, a.x + (a.w * (1 - q)) / 2, a.y + (a.h * (1 - q)) / 2, a.w * q, a.h * q, RAD(T.button === "square" ? Math.min(8 * u, (a.h * q) / 2) : (a.h * q) / 2)); ctx.fill();+ ctx.fillStyle = T.onAccent ?? "#fff"; ctx.font = (T.font ?? SANS)(600, g.px.row * 0.8 * q); ctx.textAlign = "center"; ctx.fillText(ui.action, a.x + a.w / 2, a.y + a.h / 2 + 1); ctx.textAlign = "left";ctx.fillStyle = T.line; ctx.fillRect(r.x, g.head.y + g.head.h, r.w, 1.5 * u);// the command barif (g.command) {- const c = g.command; ctx.fillStyle = T.paper; rr(ctx, c.x, c.y, c.w, c.h, c.h / 2); ctx.fill(); ctx.strokeStyle = T.line; ctx.lineWidth = 1.5 * u; ctx.stroke();- ctx.font = SANS(500, g.px.row); ctx.textBaseline = "middle"; const tx = c.x + 26 * u;+ const c = g.command; ctx.fillStyle = T.paper; rr(ctx, c.x, c.y, c.w, c.h, RAD(c.h / 2)); ctx.fill(); ctx.strokeStyle = T.line; ctx.lineWidth = 1.5 * u; ctx.stroke();+ ctx.font = (T.font ?? SANS)(500, g.px.row); ctx.textBaseline = "middle"; const tx = c.x + 26 * u;if (o.typed) { ctx.fillStyle = T.ink; ctx.fillText(fitTail(ctx, o.typed, c.w - 60 * u), tx, c.y + c.h / 2); } else { ctx.fillStyle = T.mute; ctx.fillText(ui.command!, tx, c.y + c.h / 2); }if (o.caret) { const w = o.typed ? ctx.measureText(fitTail(ctx, o.typed, c.w - 60 * u)).width : 0; ctx.fillStyle = acc; ctx.fillRect(tx + w + 3 * u, c.y + c.h / 2 - g.px.row * 0.6, 3 * u, g.px.row * 1.2); }}@@ -129,35 +135,46 @@ export const drawProductUI = (ctx: Ctx, r0: Rect, ui: ProductUI, m: UiMorph, T:const bs = ui.before.stats ?? [], as = ui.after.stats ?? [], n = Math.max(bs.length, as.length), w = g.stats.w / n, p = spring(m.f, m.t0, m.omega ?? DEF.omega, m.zeta ?? DEF.zeta);for (let i = 0; i < n; i++) {const b = bs[i], x = as[i] ?? b, sx = g.stats.x + i * w;- ctx.font = SANS(500, g.px.small); ctx.fillStyle = T.soft; ctx.fillText((x ?? b).label, sx, g.stats.y + g.px.small * 0.7);- ctx.font = SANS(700, g.px.stat); ctx.fillStyle = T.ink; ctx.fillText(num(b?.value, x?.value, p, x?.unit ?? b?.unit ?? ""), sx, g.stats.y + g.px.small * 1.6 + g.px.stat * 0.62);+ ctx.font = (T.font ?? SANS)(500, g.px.small); ctx.fillStyle = T.soft; ctx.fillText((x ?? b).label, sx, g.stats.y + g.px.small * 0.7);+ ctx.font = (T.font ?? SANS)(700, g.px.stat); ctx.fillStyle = T.ink; counted(ctx, num(b?.value, x?.value, p, x?.unit ?? b?.unit ?? ""), sx, g.stats.y + g.px.small * 1.6 + g.px.stat * 0.62, "left", counting(b?.value, x?.value, p));}}// the items, each on its own spring- ctx.save(); rr(ctx, g.body.x - 8 * u, g.body.y - 8 * u, g.body.w + 16 * u, g.body.h + 16 * u, 12 * u); ctx.clip();- for (const s of poses(g, ui, m).sort((x, y) => (x.to ? 1 : 0) - (y.to ? 1 : 0))) {- const p = s.p, e = clamp(p), alpha = !s.from ? e : !s.to ? 1 - e : 1, k = !s.from ? 0.94 + 0.06 * out3(e) : 1;+ ctx.save(); rr(ctx, g.body.x - 8 * u, g.body.y - 8 * u, g.body.w + 16 * u, g.body.h + 16 * u, RAD(12 * u)); ctx.clip();+ // draw order: leaving items first, then the ones at rest, then the movers, the one rising last (it+ // lifts over the others). Two rows that trade places pass through each other; the one passed over+ // RECEDES: its words dim as the rising row comes within two lines of it and return as it clears, so the+ // two rows' words never stand a line apart reading as one ("$1,208 $144"). Rows at rest are never dimmed.+ const all = poses(g, ui, m).map((s) => { const p = s.p, e = clamp(p), moving = !!(s.from && s.to && (s.a.y !== s.b.y || s.a.x !== s.b.x)); return { s, e, moving, box: { x: lerp(s.a.x, s.b.x, p), y: lerp(s.a.y, s.b.y, p) + (!s.from ? (1 - e) * 14 * u : 0), w: s.a.w, h: s.a.h } as Rect }; });+ const z = (q: (typeof all)[number]) => (!q.s.to ? 0 : !q.moving ? 1 : q.s.b.y < q.s.a.y || (q.s.b.y === q.s.a.y && q.s.b.x < q.s.a.x) ? 3 : 2);+ all.sort((x, y) => z(x) - z(y) || x.s.order - y.s.order);+ const near = 2.15 * g.px.row, R = Math.max(g.row, near + 0.3 * g.px.row);+ const crosses = (x: Pose, y: Pose) => x.from && x.to && y.from && y.to && Math.sign(x.a.y - y.a.y || x.a.x - y.a.x) !== Math.sign(x.b.y - y.b.y || x.b.x - y.b.x);+ for (let i = 0; i < all.length; i++) {+ const { s, e, box } = all[i], p = s.p, alpha = !s.from ? e : !s.to ? 1 - e : 1, k = !s.from ? 0.94 + 0.06 * out3(e) : 1;if (alpha <= 0.002) continue;- const box: Rect = { x: lerp(s.a.x, s.b.x, p), y: lerp(s.a.y, s.b.y, p) + (!s.from ? (1 - e) * 14 * u : 0), w: s.a.w, h: s.a.h };- const it = e < 0.5 ? s.from ?? s.item : s.to ?? s.item, lift = s.from && s.to && (s.a.y !== s.b.y || s.a.x !== s.b.x) ? Math.sin(Math.PI * e) : 0;+ let words = 1;+ for (let j = i + 1; j < all.length; j++) { const o = all[j]; if (!o.moving || !crosses(s, o.s) || Math.abs(o.box.x - box.x) > box.w / 2) continue; words = Math.min(words, clamp((Math.abs(o.box.y - box.y) - near) / (R - near))); }+ const it = e < 0.5 ? s.from ?? s.item : s.to ?? s.item, lift = all[i].moving ? Math.sin(Math.PI * e) : 0;ctx.save(); ctx.globalAlpha = alpha; ctx.translate(box.x + box.w / 2, box.y + box.h / 2); ctx.scale(k, k); ctx.translate(-box.w / 2, -box.h / 2);- if (lift > 0) { ctx.fillStyle = `rgba(20,24,30,${0.07 * lift})`; rr(ctx, -4 * u, 6 * u, box.w + 8 * u, box.h + 4 * u, 14 * u); ctx.fill(); }- ctx.fillStyle = it.accent ? mixA(acc, T.card, 0.9) : ui.layout === "cards" ? T.paper : T.card; rr(ctx, 0, 0, box.w, box.h, 14 * u); ctx.fill();+ if (lift > 0) { ctx.fillStyle = `rgba(20,24,30,${0.07 * lift})`; rr(ctx, -4 * u, 6 * u, box.w + 8 * u, box.h + 4 * u, RAD(14 * u)); ctx.fill(); }+ ctx.fillStyle = it.accent ? mixA(acc, T.card, 0.9) : ui.layout === "cards" ? T.paper : T.card; rr(ctx, 0, 0, box.w, box.h, RAD(14 * u)); ctx.fill();ctx.strokeStyle = it.accent ? mixA(acc, T.card, 0.6) : T.line; ctx.lineWidth = 1.5 * u; ctx.stroke();const cy = ui.layout === "cards" ? g.px.row * 1.1 : box.h / 2 - (it.bar !== undefined ? 7 * u : 0), lx = 22 * u + g.px.row * 0.9;// a status mark: a ring, a filled accent dot, or a tick when doneconst done = s.from && s.to ? (e < 0.5 ? !!s.from.done : !!s.to.done) : !!it.done, mr = g.px.row * 0.3, mx = 22 * u + mr;ctx.lineWidth = 2.2 * u; ctx.strokeStyle = it.accent || done ? acc : T.mute; ctx.beginPath(); ctx.arc(mx, cy, mr, 0, Math.PI * 2);- if (done) { ctx.fillStyle = acc; ctx.fill(); ctx.strokeStyle = "#fff"; ctx.beginPath(); ctx.moveTo(mx - mr * 0.45, cy); ctx.lineTo(mx - mr * 0.1, cy + mr * 0.38); ctx.lineTo(mx + mr * 0.5, cy - mr * 0.35); ctx.stroke(); } else ctx.stroke();- ctx.font = SANS(600, g.px.row); ctx.fillStyle = T.ink; ctx.textBaseline = "middle";+ if (done) { ctx.fillStyle = acc; ctx.fill(); ctx.strokeStyle = T.onAccent ?? "#fff"; ctx.beginPath(); ctx.moveTo(mx - mr * 0.45, cy); ctx.lineTo(mx - mr * 0.1, cy + mr * 0.38); ctx.lineTo(mx + mr * 0.5, cy - mr * 0.35); ctx.stroke(); } else ctx.stroke();+ ctx.font = (T.font ?? SANS)(600, g.px.row); ctx.fillStyle = T.ink; ctx.textBaseline = "middle";const val = num(s.from?.value, s.to?.value ?? s.from?.value, s.from && s.to ? p : 1, it.unit ?? "");- ctx.font = SANS(700, g.px.value); const vw = val ? ctx.measureText(val).width : 0;- ctx.font = SANS(600, g.px.row); ctx.fillText(fitTail(ctx, it.label, box.w - lx - vw - 60 * u, true), lx, cy);- if (it.tag) { ctx.font = SANS(600, g.px.small); const tw = ctx.measureText(it.tag).width, tx = ui.layout === "cards" ? lx : Math.min(lx + ctx.measureText(it.label).width * (g.px.row / g.px.small) + 18 * u, box.w - vw - tw - 60 * u); if (tx > lx + 40 * u || ui.layout === "cards") { const ty = ui.layout === "cards" ? cy + g.px.row * 1.25 : cy; ctx.fillStyle = it.accent ? acc : T.chip; rr(ctx, tx - 10 * u, ty - g.px.small * 0.75, tw + 20 * u, g.px.small * 1.5, g.px.small * 0.75); ctx.fill(); ctx.fillStyle = it.accent ? "#fff" : T.soft; ctx.fillText(it.tag, tx, ty); } }- if (val) { ctx.font = SANS(700, g.px.value); ctx.fillStyle = it.accent ? acc : T.ink; ctx.textAlign = "right"; ctx.fillText(val, box.w - 22 * u, ui.layout === "cards" ? box.h - g.px.value : cy); ctx.textAlign = "left"; }+ ctx.font = (T.font ?? SANS)(700, g.px.value); const vw = val ? ctx.measureText(val).width : 0;+ const said = (draw: () => void) => { if (words <= 0) return; ctx.globalAlpha = alpha * words; draw(); ctx.globalAlpha = alpha; };+ ctx.font = (T.font ?? SANS)(600, g.px.row); said(() => ctx.fillText(fitTail(ctx, it.label, box.w - lx - vw - 60 * u, true), lx, cy));+ if (it.tag) { ctx.font = (T.font ?? SANS)(600, g.px.small); const tw = ctx.measureText(it.tag).width, tx = ui.layout === "cards" ? lx : Math.min(lx + ctx.measureText(it.label).width * (g.px.row / g.px.small) + 18 * u, box.w - vw - tw - 60 * u); if (tx > lx + 40 * u || ui.layout === "cards") { const ty = ui.layout === "cards" ? cy + g.px.row * 1.25 : cy; ctx.fillStyle = it.accent ? acc : T.chip; rr(ctx, tx - 10 * u, ty - g.px.small * 0.75, tw + 20 * u, g.px.small * 1.5, RAD(g.px.small * 0.75)); ctx.fill(); ctx.fillStyle = it.accent ? T.onAccent ?? "#fff" : T.soft; said(() => ctx.fillText(it.tag!, tx, ty)); } }+ if (val) { ctx.font = (T.font ?? SANS)(700, g.px.value); ctx.fillStyle = it.accent ? acc : T.ink; said(() => counted(ctx, val, box.w - 22 * u, ui.layout === "cards" ? box.h - g.px.value : cy, "right", !!(s.from && s.to) && counting(s.from.value, s.to.value, p))); ctx.textAlign = "left"; }if (it.bar !== undefined || s.from?.bar !== undefined) {const b0 = s.from?.bar ?? 0, b1 = s.to?.bar ?? b0, bv = clamp(s.from && s.to ? lerp(b0, b1, p) : b1, 0, 1.02), by = ui.layout === "cards" ? box.h - 16 * u : cy + g.px.row * 0.75, bw = box.w - lx - (ui.layout === "cards" ? 22 * u : vw + 60 * u);- ctx.fillStyle = T.chip; rr(ctx, lx, by, bw, 6 * u, 3 * u); ctx.fill(); ctx.fillStyle = it.accent ? acc : T.ink; rr(ctx, lx, by, Math.max(6 * u, bw * bv), 6 * u, 3 * u); ctx.fill();+ ctx.fillStyle = T.chip; rr(ctx, lx, by, bw, 6 * u, RAD(3 * u)); ctx.fill(); ctx.fillStyle = it.accent ? acc : T.ink; rr(ctx, lx, by, Math.max(6 * u, bw * bv), 6 * u, RAD(3 * u)); ctx.fill();}ctx.restore();}@@ -165,6 +182,16 @@ export const drawProductUI = (ctx: Ctx, r0: Rect, ui: ProductUI, m: UiMorph, T:ctx.globalAlpha = 1; ctx.textBaseline = "alphabetic";};+// A number on its way from one value to another is set digit by digit on a tabular grid: the figures+// do not jitter sideways as they count, and no passing value is drawn as one word (a "70%" counting+// through one card is not the "70%" resting in the next). At rest it is one word again.+const counting = (a: number | string | undefined, b: number | string | undefined, p: number) => typeof a === "number" && typeof b === "number" && a !== b && Math.abs(p - 1) > 0.002 && p > 0.002;+const counted = (ctx: Ctx, s: string, x: number, y: number, align: "left" | "right", tabular: boolean) => {+ if (!tabular) { ctx.textAlign = align; ctx.fillText(s, x, y); ctx.textAlign = "left"; return; }+ const fig = ctx.measureText("0").width, adv = (ch: string) => (/[0-9]/.test(ch) ? fig : ctx.measureText(ch).width), w = [...s].reduce((a, ch) => a + adv(ch), 0);+ let cx = align === "right" ? x - w : x; ctx.textAlign = "left";+ for (const ch of s) { ctx.fillText(ch, cx + (adv(ch) - ctx.measureText(ch).width) / 2, y); cx += adv(ch); }+};// the end of a line when it overflows (a command bar scrolls), or its start with an ellipsis (a label)const fitTail = (ctx: Ctx, s: string, w: number, head = false) => {if (ctx.measureText(s).width <= w) return s;diff --git a/skills/anidoodle/engine/src/canvas-core/readable.ts b/skills/anidoodle/engine/src/canvas-core/readable.tsnew file mode 100644index 0000000..5a400dd--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/readable.ts@@ -0,0 +1,55 @@+// READABLE. Holds and type sizes from the reading rule, so a film's timing comes from its words, not+// from feel. A brand launch film typed its AI replies at 52 chars/s and held them a fixed 0.9 s after+// the last character; an 11-word reply was up about 2.5 s where the rule wants 3.3 s, and viewers said+// "too fast" twice, even after a 25 % slowdown. These helpers make the rule the default.+// readS(text) seconds a text needs: max(0.7 s, 0.3 s per word) (the same rule framecheck checks)+// chatHold(text, o) a typed reply: think + typing + reading AFTER the last character, times pace+// paced(s, pace, part) one pace scalar (or one per section) that every hold multiplies: "20 % slower" is pace 1.2+// texture(ctx, draw) text drawn inside is texture, not meant to be read ("blah blah"): framecheck skips it+// fitText(ctx, text, maxW, o) the largest size from maxPx down to minPx at which a line fits maxW+import type { Ctx } from "./core";++export const MIN_READ_S = 0.7, READ_S_PER_WORD = 0.3; // must equal tools/textrules.mjs (test/readable.test.ts holds them together)+const words = (t: string) => t.trim().split(/\s+/).filter(Boolean).length;++/** Seconds a viewer needs to read `text`. */+export const readS = (text: string) => Math.max(MIN_READ_S, READ_S_PER_WORD * words(text));++/** A pace: one number for the whole film, or one per named section (`default` for the rest). 1 = the rule; 1.25 = 25 % longer holds. */+export type Pace = number | ({ default?: number } & Record<string, number>);+export const paceOf = (pace: Pace = 1, section?: string) => (typeof pace === "number" ? pace : (section !== undefined && pace[section] !== undefined ? pace[section] : pace.default ?? 1));+/** Seconds times the pace for a section. Every hold of a film goes through this, so length changes are one number. */+export const paced = (s: number, pace: Pace = 1, section?: string) => s * paceOf(pace, section);++/**+ * A typed reply's timeline in seconds: a think beat, the typing, then the full reading time after the+ * last character (a reader cannot start before the sentence exists). `cps` is characters per second.+ * Pace stretches the think and the read, never the typing speed (typing speed is a character trait).+ */+export const chatHold = (text: string, o: { cps?: number; think?: number; pace?: Pace; section?: string } = {}) => {+ const k = paceOf(o.pace ?? 1, o.section), think = (o.think ?? 0.6) * k, typing = text.length / (o.cps ?? 52), read = readS(text) * k;+ return { think, typing, read, total: think + typing + read };+};+/** chatHold in whole frames (rounded up, so the hold never lands a frame short of the rule). */+export const chatHoldFrames = (text: string, fps: number, o: Parameters<typeof chatHold>[1] = {}) => { const h = chatHold(text, o); return { think: Math.ceil(h.think * fps), typing: Math.ceil(h.typing * fps), read: Math.ceil(h.read * fps), total: Math.ceil(h.think * fps) + Math.ceil(h.typing * fps) + Math.ceil(h.read * fps) }; };++/** Draw words meant as texture, not reading (fast "blah" behind a joke): framecheck's reading time and layout rules skip them. */+export const texture = (ctx: Ctx, draw: () => void) => {+ const c = ctx as Ctx & { __texture?: boolean }, was = c.__texture;+ c.__texture = true;+ try { draw(); } finally { c.__texture = was; }+};++/**+ * The largest whole px size, from maxPx down to minPx, at which `text` fits `maxW` in this font; sets+ * ctx.font to it. `fits` is false when even minPx overflows (shorten the copy: never let it clip).+ */+export const fitText = (ctx: Ctx, text: string, maxW: number, o: { maxPx: number; minPx: number; font: (px: number) => string }) => {+ let lo = Math.ceil(o.minPx), hi = Math.floor(o.maxPx);+ const w = (px: number) => { ctx.font = o.font(px); return ctx.measureText(text).width; };+ if (w(hi) <= maxW) return { px: hi, fits: true };+ if (w(lo) > maxW) return { px: lo, fits: false };+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (w(mid) <= maxW) lo = mid; else hi = mid; }+ ctx.font = o.font(lo);+ return { px: lo, fits: true };+};diff --git a/skills/anidoodle/engine/src/canvas-core/shipMeta.ts b/skills/anidoodle/engine/src/canvas-core/shipMeta.tsnew file mode 100644index 0000000..60d3ca4--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/shipMeta.ts@@ -0,0 +1,23 @@+// SHIP META. What a film tells the ship checks about itself (Film.meta.checks). Every field is+// optional and every one is read by a tool: framecheck.mjs, ship.mjs. Plain data, so it survives the+// page boundary as it is.+export type ShipMeta = {+ /** [fromFrame, toFrame, reason]: frames where the layout rules (density, gaps, centred stack, text over+ * text or over a box edge) are not judged. A deliberate wall of words or a collision that is the joke. */+ layoutExempt?: [from: number, to: number, reason: string][];+ /** The length budget in seconds (D1). ship prints the film's length and its shots against it; over max fails. */+ length?: { target: number; max: number };+ /** The brand's own font families (T8). Text set in any other family is listed for review. */+ fonts?: string[];+ /** Brand face -> the family standing in for it while the font file is missing (T8): every line set in a stand-in is listed. */+ standIns?: Record<string, string>;+ /** Music that is a supplied or generated track, not a score the page composes (X3). `track` is the take's+ * manifest from `track.mjs import` (<take>.track.json). verify-export then expects an audio stream, checks the+ * delivered mix came from that take, and ship runs track.mjs check and soundcheck --sfx on the file. */+ music?: { track: string };+ /** Checks with truly nothing to look at, by ship row name, each with its reason: { "review": "a test fixture+ * nobody is shown", "layers:translucent": "the brand has no colour of its own" }. A check that cannot look+ * FAILS in ship.mjs; a row named here is NONE instead, with the reason printed in the table. Gate check 5+ * reads "3d" the same way (a 3D film that registers no grip or rig to check). */+ none?: Record<string, string>;+};diff --git a/skills/anidoodle/engine/src/canvas-core/subtitles.ts b/skills/anidoodle/engine/src/canvas-core/subtitles.tsindex 45957e7..cc53d7b 100644--- a/skills/anidoodle/engine/src/canvas-core/subtitles.ts+++ b/skills/anidoodle/engine/src/canvas-core/subtitles.ts@@ -123,7 +123,11 @@ const splitLine = (words: string[], d: ReturnType<typeof defaults>, problems: stexport const phrasePlan = (timing: VoiceTiming, o: PhraseOpts = {}) => {const fps = timing.fps, d = defaults(fps, o), problems: string[] = [], events: CaptionEvent[] = [];const raw: { line: string; words: TimedWord[] }[] = [];- for (const ln of timing.lines) for (const ix of splitLine(ln.words.map((w) => w.w), d, problems, ln.id)) raw.push({ line: ln.id, words: ix.map((i) => ln.words[i]) });+ for (const ln of timing.lines) {+ // a line with nothing to show (its display text was "") has no phrase to time: say which, then go on+ if (!ln.words?.length) { problems.push(`${ln.id}: no words to caption (is its display text empty?)`); continue; }+ for (const ix of splitLine(ln.words.map((w) => w.w), d, problems, ln.id)) raw.push({ line: ln.id, words: ix.map((i) => ln.words[i]) });+ }// Speech runs at about the reading rule's own pace (0.3 s a word), so phrases placed greedily drift// late. Two passes keep them on their words: backward, the latest each phrase may appear and still// leave every later phrase its reading time; forward, each appears at its ideal frame (lead before itsdiff --git a/skills/anidoodle/engine/src/canvas-core/threeHello.ts b/skills/anidoodle/engine/src/canvas-core/threeHello.tsindex b22b89a..6a556fa 100644--- a/skills/anidoodle/engine/src/canvas-core/threeHello.ts+++ b/skills/anidoodle/engine/src/canvas-core/threeHello.ts@@ -30,7 +30,9 @@ const turn = (ctx: Ctx, f: number, env: Env) => {draw3d(ctx, env, scene, cam, { clear: "#0f0d1a" });};export const threeHello: Film = {- meta: { title: "three hello", W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "loop" },+ meta: { title: "three hello", W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "loop",+ // gate check 5 FAILS a 3D film that registers nothing; this one has nothing physical to go wrong+ checks: { none: { "3d": "one star turning alone in the middle of the frame: no character, nothing held, nothing for it to pass through" } } },assets: { images: {} },shots: [{ id: "turn", start: 0, end: N, draw: turn }],};diff --git a/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.ts b/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.tsindex cc7a6e8..931f973 100644--- a/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.ts+++ b/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.ts@@ -12,6 +12,7 @@ import type { Ctx, Env } from "./core";import type { Film } from "./film";import * as THREE from "three";import { draw3d, memo } from "../three-core/stage";+import { checking, registerPath, registerSize, runChecks } from "../three-core/checks3d";import { ease, seg, tween } from "../three-core/time";import { crane, dolly, dutch, handheld, hash01, look, orbit, path, place, pushIn, then, whipPan, withMods, type CamState, type Move, type V3 } from "../three-core/camera";import { assemble, dropIn, explode, grid, indicate, lagged, morph, moveAlongPath, popIn, riseFromFloor, wave, writeOn, writeTube } from "../three-core/mograph";@@ -138,6 +139,17 @@ const draw = (ctx: Ctx, f: number, env: Env) => {s.rim.position.set(at[0] - 4, 5, at[2] - 8); s.rim.target.position.set(at[0], 1, at[2]);place(s.cam, c, env);draw3d(ctx, env, s.scene, s.cam, { clear: BG, shadows: true });+ // what each station must keep true (checks3d, gate check 5): its subject big enough to read, and the bead+ // riding the ribbon never passes through a pillar (an upright cylinder the bead's size around its centre)+ if (checking()) {+ if (f < CUT.write) registerSize(s.tiles, 40);+ else if (f < CUT.morph) {+ registerSize(s.pillars, 40);+ if (f >= w0) registerPath({ at: (ff) => s.swoop.getPointAt(ease.inOutSine(seg(ff, w0, w1))).clone().setY(s.swoop.getPointAt(ease.inOutSine(seg(ff, w0, w1))).y - 0.24), from: f, to: f, radius: 0.24, height: 0.48, name: "bead" }, s.pillars.children.map((c, i) => ({ name: `pillar ${i + 1}`, box: c })));+ } else if (f < WHIP) registerSize(s.ringTube, 40);+ else if (f >= CUT.explode) registerSize(s.blockWrap, 40);+ runChecks(f, s.cam, env);+ }};const shot = (id: string, start: number, end: number) => ({ id, start, end, draw: (ctx: Ctx, local: number, env: Env) => draw(ctx, start + local, env) });diff --git a/skills/anidoodle/engine/src/canvas-core/threeTypeDemo.ts b/skills/anidoodle/engine/src/canvas-core/threeTypeDemo.tsindex 282ef43..49af520 100644--- a/skills/anidoodle/engine/src/canvas-core/threeTypeDemo.ts+++ b/skills/anidoodle/engine/src/canvas-core/threeTypeDemo.ts@@ -7,6 +7,7 @@ import type { Ctx, Env } from "./core";import type { Film } from "./film";import * as THREE from "three";import { draw3d, memo, probe3d } from "../three-core/stage";+import { checking, registerSize, runChecks } from "../three-core/checks3d";import { ease, lerp, seg, spring, tween } from "../three-core/time";import { defaultFont, text3d, textPlane, type Letter } from "../three-core/type3d";import { contactShadow, grain, matte, outline, satin, studio, toon, vignette } from "../three-core/look";@@ -68,9 +69,12 @@ const sceneA = (ctx: Ctx, env: Env, f: number) => {letters.forEach((l, i) => drop(l, f, -6 + i * 3.2, i, shadows[i]));const t = tween(f, 0, 96, ease.outCubic);cam.position.set(lerp(-0.7, 0.5, t), lerp(2.9, 2.2, t), lerp(12.6, 11.2, t)); cam.lookAt(0, -0.05, 0);- draw3d(ctx, env, scene, cam, { clear: "#efe3d2" }); if (f >= 48) probe3d(ctx, env, letters[0].parent!, cam, "anidoodle"); /* the letters drop in from above the frame on purpose; the word must read whole once it has landed */+ draw3d(ctx, env, scene, cam, { clear: "#efe3d2" }); if (f >= 48) { probe3d(ctx, env, letters[0].parent!, cam, "anidoodle"); sizeCheck(f, letters[0].parent!, cam, env); } /* the letters drop in from above the frame on purpose; the word must read whole once it has landed */};+// what the type must keep true (checks3d, gate check 5): the word, once it has landed, is big enough to read+const sizeCheck = (f: number, word: THREE.Object3D, cam: THREE.Camera, env: Env) => { if (!checking()) return; registerSize(word, 60); runChecks(f, cam, env); };+// ---------------------------------------------------------------- scene B: "now in 3D", toon and inkconst buildB = (env: Env) => {const scene = new THREE.Scene();@@ -102,6 +106,7 @@ const sceneB = (ctx: Ctx, env: Env, f: number) => {const t = tween(f, 0, 96, ease.inOutSine);cam.position.set(lerp(0.8, -0.4, t), lerp(2.8, 2.1, t), lerp(12.2, 11.0, t)); cam.lookAt(0, -0.1, 0);draw3d(ctx, env, scene, cam, { clear: "#2d3f8f" }); probe3d(ctx, env, word, cam, "now in 3D");+ if (f >= 2 + (letters.length - 1) * 2.5 + 12) sizeCheck(f, word, cam, env); // every letter has popped up};// ---------------------------------------------------------------- scene C: the end card@@ -129,7 +134,7 @@ const sceneC = (ctx: Ctx, env: Env, f: number) => {(made.material as THREE.MeshBasicMaterial).opacity = pm; made.position.y = 1.3 + (1 - pm) * 0.12;const t = tween(f, 0, 48, ease.outCubic);cam.position.set(0, lerp(0.7, 0.55, t), lerp(9.2, 8.6, t)); cam.lookAt(0, 0.2, 0);- draw3d(ctx, env, scene, cam, { clear: "#efe3d2" }); probe3d(ctx, env, letters[0].parent!, cam, "anidoodle");+ draw3d(ctx, env, scene, cam, { clear: "#efe3d2" }); probe3d(ctx, env, letters[0].parent!, cam, "anidoodle"); sizeCheck(f, letters[0].parent!, cam, env);};// ---------------------------------------------------------------- finish and shotsdiff --git a/skills/anidoodle/engine/src/canvas-core/timeRemap.ts b/skills/anidoodle/engine/src/canvas-core/timeRemap.tsindex 54e8d8c..d54a4a8 100644--- a/skills/anidoodle/engine/src/canvas-core/timeRemap.ts+++ b/skills/anidoodle/engine/src/canvas-core/timeRemap.ts@@ -26,8 +26,14 @@// filmFrameOf(sceneFrame). A slowed world under a score at its own tempo is the effect.// Every function here is arithmetic over (frame, keys): no clock, no state, any order.+// WHERE A KEY SITS, IN NAMED UNITS. `f` is a film frame. `film: s` is film time in seconds and `scene:+// s` is SCENE time in seconds (the key lands on the first film frame that shows that scene moment);+// both need timeRemap(keys, { fps }). Exactly one of the three, never a bare number: a brand launch+// logo keys were typed in scene seconds where film seconds were meant, and nothing complained.export type TimeKey = {- f: number; // the film frame this speed starts from (whole, increasing)+ f?: number; // the film frame this speed starts from (whole, increasing)+ film?: number; // or: film time in seconds (needs fps)+ scene?: number; // or: scene time in seconds, resolved through the keys before this one (needs fps)speed: number; // scene frames per film frame from here on: 1 real time, 0.25 slow motion, 0 a freeze, 2 fast (0 or at least MIN_SPEED)ramp?: number; // frames over which the speed glides from the old value to this one (default 0, a hard change)curve?: "smooth" | "linear"; // the glide's shape: smoothstep (default; no kick at either end) or a straight line@@ -56,7 +62,8 @@ export const MIN_SPEED = 0.01;type Seg = { f: number; from: number; to: number; ramp: number; curve: (typeof CURVES)["smooth"]; t0: number };-export const timeRemap = (keys: readonly TimeKey[]): TimeRemap => {+export const timeRemap = (input: readonly TimeKey[], opts: { fps?: number } = {}): TimeRemap => {+ const keys = resolveKeys(input, opts.fps);let last = -1, prevSpeed = 1;const segs: Seg[] = [], freezes: Freeze[] = [];// the frames first, all of them, so a later check never reports a symptom of keys out of order@@ -110,3 +117,24 @@ const sceneAt = (s: Seg, f: number): number => {if (s.ramp > 0 && x < s.ramp) return s.t0 + s.ramp * (s.from * (x / s.ramp) + (s.to - s.from) * s.curve.area(x / s.ramp));return s.t0 + s.ramp * (s.from + (s.to - s.from) * s.curve.area(1)) + s.to * (x - s.ramp);};++// Every key's place in film frames, from whichever unit it names. A scene-time key is found on the+// remap built from the keys before it, so "the logo starts at scene 30 s" means what it says even+// after a slowdown earlier in the film.+type Resolved = TimeKey & { f: number };+const resolveKeys = (keys: readonly TimeKey[], fps?: number): Resolved[] => {+ const out: Resolved[] = [];+ for (const [i, k] of keys.entries()) {+ if (typeof k !== "object" || k === null) throw new Error(`timeRemap: key ${i} is ${JSON.stringify(k)}; a key is an object that names its unit: { f: frame }, { film: seconds } or { scene: seconds }, plus speed`);+ const named = (["f", "film", "scene"] as const).filter((u) => k[u] !== undefined);+ if (named.length !== 1) throw new Error(`timeRemap: key ${i} ${named.length ? `names ${named.join(" and ")}` : "names no time"}; give exactly one of f (film frame), film (film seconds) or scene (scene seconds)`);+ const u = named[0], v = k[u]!;+ if (!Number.isFinite(v)) throw new Error(`timeRemap: key ${i} has ${u} = ${v}; it must be a number`);+ if (u === "f") { out.push({ ...k, f: v }); continue; }+ if (!(fps && fps > 0)) throw new Error(`timeRemap: key ${i} is in ${u} seconds; pass timeRemap(keys, { fps }) so seconds can become frames`);+ if (u === "film") { out.push({ ...k, f: Math.round(v * fps) }); continue; }+ const before = timeRemap(out.map(({ f, speed, ramp, curve, keepsMoving }) => ({ f, speed, ramp, curve, keepsMoving })));+ out.push({ ...k, f: before.filmFrameOf(v * fps) });+ }+ return out;+};diff --git a/skills/anidoodle/engine/src/canvas-core/voice.ts b/skills/anidoodle/engine/src/canvas-core/voice.tsindex 031f30a..4440ba3 100644--- a/skills/anidoodle/engine/src/canvas-core/voice.ts+++ b/skills/anidoodle/engine/src/canvas-core/voice.ts@@ -42,14 +42,17 @@ export const resample = (x: Float32Array, from: number, to: number) => {return out;};-const decoded = new Map<string, Float32Array>(); // per (line, rate): decoding is pure, so caching it changes nothing+// Decoded takes, keyed on the take's own base64 text and then on (source rate, target rate). Keying on the+// exact text means two voices that share a line id and a take length can never be served each other's take.+const decoded = new Map<string, Map<string, Float32Array>>();/** Every line's take on one mono track of `frames` film frames, each starting exactly on its start frame. */export const voiceTrack = (v: BakedVoice, sr: number, frames = v.timing.totalFrames) => {const fps = v.timing.fps, out = new Float32Array(Math.round((frames / fps) * sr));for (const ln of v.timing.lines) {const b64 = v.pcm[ln.id]; if (!b64) throw new Error(`voice: no take for line '${ln.id}' (re-run narrate.mjs bake)`);- const key = `${ln.id}@${sr}@${b64.length}`;- let x = decoded.get(key); if (!x) { x = resample(decodePcm16(b64), v.sampleRate, sr); decoded.set(key, x); }+ let rates = decoded.get(b64); if (!rates) { rates = new Map(); decoded.set(b64, rates); }+ const key = `${v.sampleRate}>${sr}`;+ let x = rates.get(key); if (!x) { x = resample(decodePcm16(b64), v.sampleRate, sr); rates.set(key, x); }const at = Math.round((ln.start / fps) * sr);for (let i = 0; i < x.length && at + i < out.length; i++) out[at + i] += x[i];}diff --git a/skills/anidoodle/engine/src/canvas-core/world.ts b/skills/anidoodle/engine/src/canvas-core/world.tsnew file mode 100644index 0000000..4c9b62c--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/world.ts@@ -0,0 +1,99 @@+// ONE WORLD. The default architecture for a motion-graphics film: every beat is a REGION placed on+// one canvas in world coordinates, and a single camera travels between them. Nothing is rebuilt per+// scene, so nothing can cut like a slide. This is the fix for "DUDE YOUR VIDEO IS A LITERAL SLIDE+// DECK" on a brand launch film: it cut from screen to screen instead of being one moving world.+//+// const w = world({ W: 1920, H: 1080, regions: [+// { id: "chat", rect: [0, 0, 1600, 900] },+// { id: "crowd", rect: [1900, 200, 2400, 1350] },+// ], stops: [+// { f: 0, at: "chat", hold: 90 },+// { f: 150, at: "crowd", hold: 60 }, // the camera travels chat -> crowd over frames 90..150+// ], alive: { amp: 3, seed: 7 } });+// w.begin(ctx, env, f); // the camera's transform: draw in world units now+// w.region(ctx, "chat", () => drawChat(ctx)); // clipped to its own rect by default (no leaking edges)+// w.depth(ctx, env, f, 0.33, () => frieze(ctx)); // a layer of brand shapes at a third of camera speed+// w.end(ctx);+//+// CRAFT, and why it works this way:+// - REGIONS ARE THE STORYBOARD. A row of the board is a place in the world plus the camera move into+// it, so a board with two rows and no move between them cannot be built here.+// - A STOP FRAMES A REGION. Its zoom fits the region's rect inside the frame with `pad` around it, so a+// region can be any size and the camera works out the dolly. Several regions may share a stop.+// - REGIONS CLIP BY DEFAULT. A speaker's pink panel edge leaked into the next question on a brand launch film;+// a region draws only inside its own rect unless it says clip: false.+// - THE CAMERA BREATHES. `alive` adds a slow handheld drift in screen px (never per-frame noise): a parked+// camera reads as a slide even when the world is one.+// - ONE LAYOUT PER SHAPE. `regions` may be a function of the frame shape, so a 9:16 cut re-composes the+// same world (a chat card that fills the phone) instead of cropping it.+// Every function is pure in the frame number; the camera is camera.ts's, so seams.ts's numbers apply.+import { Camera, heroScale, type Cam, type CamKey, type EaseName } from "./camera";+import { fractal, type Ctx, type Env, type P } from "./core";++export type Rect = [x: number, y: number, w: number, h: number];+export type Region = { id: string; rect: Rect; clip?: boolean };+export type Stop = { f: number; at: string | { look: P; zoom: number }; hold?: number; pad?: number; ease?: EaseName };+export type Shape = { W: number; H: number; name?: string };+export type WorldSpec = { W: number; H: number; regions: Region[] | ((shape: Shape) => Region[]); stops: Stop[]; alive?: { amp: number; seed: number; freq?: number }; shape?: string };++/** The zoom that fits rect inside a W x H frame with `pad` (a share of the rect) around it. */+export const fitZoom = (rect: Rect, W: number, H: number, pad = 0.08) => Math.min(W / (rect[2] * (1 + 2 * pad)), H / (rect[3] * (1 + 2 * pad)));+export const centreOf = (r: Rect): P => [r[0] + r[2] / 2, r[1] + r[3] / 2];+/** The fewest frames a camera move of `distPx` screen px may take so its peak stays under `maxPxPerFrame` (an in-out cubic peaks at 3x its mean). Use with temperament(...).pxPerFrame(W, fps). */+export const minTravel = (distPx: number, maxPxPerFrame: number) => { if (!(maxPxPerFrame > 0)) throw new Error(`minTravel: the speed limit must be above 0 (got ${maxPxPerFrame})`); return Math.max(2, Math.ceil((3 * Math.abs(distPx)) / maxPxPerFrame)); };++export const world = (spec: WorldSpec) => {+ const { W, H } = spec, regions = typeof spec.regions === "function" ? spec.regions({ W, H, name: spec.shape }) : spec.regions;+ if (!spec.stops.length) throw new Error("world: give at least one stop: where the camera starts");+ const byId = new Map<string, Region>();+ for (const r of regions) {+ if (byId.has(r.id)) throw new Error(`world: two regions are called "${r.id}"`);+ if (!(r.rect[2] > 0 && r.rect[3] > 0)) throw new Error(`world: region "${r.id}" has no size (${r.rect})`);+ byId.set(r.id, r);+ }+ const frame = (s: Stop): { look: P; zoom: number } => {+ if (typeof s.at !== "string") return s.at;+ const r = byId.get(s.at); if (!r) throw new Error(`world: stop at frame ${s.f} goes to "${s.at}", which is not a region (${[...byId.keys()].join(", ")})`);+ return { look: centreOf(r.rect), zoom: fitZoom(r.rect, W, H, s.pad) };+ };+ // each stop is an arrival key and, with a hold, a departure key: the camera travels between them+ const keys: CamKey[] = [];+ let last = -1;+ for (const s of spec.stops) {+ if (!Number.isInteger(s.f) || s.f <= last) throw new Error(`world: stops sit on whole, increasing frames (${last} then ${s.f}); a stop's hold must end before the next stop, and a move takes at least one frame (a jump between regions is the slide cut this scaffold exists to stop)`);+ const c = frame(s); keys.push({ f: s.f, ...c, ease: s.hold ? "linear" : s.ease ?? "inout" });+ if (s.hold) { if (!(Number.isInteger(s.hold) && s.hold > 0)) throw new Error(`world: hold at frame ${s.f} is a whole number of frames (got ${s.hold})`); keys.push({ f: s.f + s.hold, ...c, ease: s.ease ?? "inout" }); last = s.f + s.hold; } else last = s.f;+ }+ const camera = new Camera([W / 2, H / 2], keys);+ // handheld breathing: smooth gradient noise in screen px, the same at every zoom+ const breath = (f: number): P => {+ const a = spec.alive; if (!a || !(a.amp > 0)) return [0, 0];+ const q = a.freq ?? 0.02; return [a.amp * (fractal(a.seed, f * q, 0, 1, 1, 2) * 2 - 1), a.amp * (fractal(a.seed + 31, f * q, 0, 1, 1, 2) * 2 - 1)];+ };+ /** The camera at frame f, breathing included: look in world units, zoom in screen px per world unit. */+ const cam = (f: number): Cam => { const c = camera.at(f), [bx, by] = breath(f), k = heroScale(c); return { ...c, look: [c.look[0] - bx / k, c.look[1] - by / k] }; };+ /** Set the context to draw in world units at frame f (env.scale included). Pair with end(). */+ const begin = (ctx: Ctx, env: Env, f: number) => {+ const c = cam(f), k = heroScale(c);+ ctx.save(); ctx.setTransform(env.scale * k, 0, 0, env.scale * k, env.scale * (W / 2 - k * c.look[0]), env.scale * (H / 2 - k * c.look[1]));+ };+ const end = (ctx: Ctx) => ctx.restore();+ /** Draw a region: clipped to its rect unless it says clip: false. Call inside begin()/end(). */+ const region = (ctx: Ctx, id: string, draw: (r: Region) => void) => {+ const r = byId.get(id); if (!r) throw new Error(`world: no region "${id}"`);+ ctx.save(); if (r.clip !== false) { ctx.beginPath(); ctx.rect(...r.rect); ctx.clip(); } draw(r); ctx.restore();+ };+ /** A depth layer that travels at `speed` x the camera (0.33: a third as fast, far behind). Its own transform; do not nest in begin(). */+ const depth = (ctx: Ctx, env: Env, f: number, speed: number, draw: () => void) => {+ if (!(speed > 0)) throw new Error(`world.depth: speed is a share of the camera's, above 0 (got ${speed})`);+ const c = cam(f), k = heroScale(c);+ ctx.save(); ctx.setTransform(env.scale * k, 0, 0, env.scale * k, env.scale * (W / 2 - k * c.look[0] * speed), env.scale * (H / 2 - k * c.look[1] * speed)); draw(); ctx.restore();+ };+ /** Where a world point lands on screen at frame f (logical px). */+ const toScreen = (p: P, f: number): P => { const c = cam(f), k = heroScale(c); return [W / 2 + k * (p[0] - c.look[0]), H / 2 + k * (p[1] - c.look[1])]; };+ /** The region the camera frames at f (its centre nearest the look point), for captions and checks. */+ const regionAt = (f: number): Region | undefined => { const c = cam(f); let best: Region | undefined, d = Infinity; for (const r of regions) { const [x, y] = centreOf(r.rect), e = Math.hypot(x - c.look[0], y - c.look[1]); if (e < d) { d = e; best = r; } } return best; };+ /** The camera's moves between stops, [from, to] frames: the seams of the film, every one a move. */+ const moves = () => { const out: { from: number; to: number; into: string }[] = []; for (let i = 1; i < spec.stops.length; i++) { const p = spec.stops[i - 1], s = spec.stops[i]; out.push({ from: p.f + (p.hold ?? 0), to: s.f, into: typeof s.at === "string" ? s.at : "point" }); } return out; };+ return { camera, cam, begin, end, region, depth, toScreen, regionAt, moves, regions: byId };+};diff --git a/skills/anidoodle/engine/src/fonts.d.ts b/skills/anidoodle/engine/src/fonts.d.tsnew file mode 100644index 0000000..42ab140--- /dev/null+++ b/skills/anidoodle/engine/src/fonts.d.ts@@ -0,0 +1,4 @@+// A font file imported by path (tools/overlay.mjs inlines it): import serif from "../../assets/fonts/X.ttf"+declare module "*.ttf" { const f: { path: string; format: "ttf" | "otf" | "woff2"; data: string }; export default f; }+declare module "*.otf" { const f: { path: string; format: "ttf" | "otf" | "woff2"; data: string }; export default f; }+declare module "*.woff2" { const f: { path: string; format: "ttf" | "otf" | "woff2"; data: string }; export default f; }diff --git a/skills/anidoodle/engine/src/hosts/instrument.ts b/skills/anidoodle/engine/src/hosts/instrument.tsnew file mode 100644index 0000000..f8f79a9--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/instrument.ts@@ -0,0 +1,147 @@+// LAYER INSTRUMENTS (hosts only; the art core never sees them). Two jobs, both by watching what a+// frame DRAWS rather than guessing from its pixels:+//+// 1. THE BLUR MASK (render --blur). Motion blur is for the world and the camera. Type and photos are+// drawn sharp: on a brand launch film, blurred whips on type and faces read as the violent motion+// the director rejected (critic round 2). While the subframes are drawn, every line of text, every photo+// (a film asset drawn with drawImage) and everything inside sharp() is left out; the frame is then+// drawn twice more, whole and without them, and the pixels that differ are taken from the whole+// sharp frame. What remains is a blurred world under sharp type.+// 2. THE LAYER PROBE (tools/layerscan.mjs). Per frame: every line of text, every photo, every probeRect+// box (brand elements report themselves through drawEl), in draw order; the fills made in a brand+// colour at a translucent alpha; and, on request, how much ink one line of text puts on screen+// (the frame drawn with and without it). layerscan turns these into its findings.+// Only the frame's own context and full-frame sheets (__frame) count: a cached plate is drawn once+// and reused, so leaving text out of it would leave it out forever.+// THE BLUR MASK'S LIMIT. So type drawn into an offscreen layer (a sheet, a bake() sprite, a plate) and+// composited later is NOT kept sharp: it blurs with the world. Neither is 3D type (three-core text3d), which+// is drawn by WebGL, not fillText. sharpLayers counts the layers holding type that a frame composites+// (layerType), so the render can say how much type it could not keep sharp instead of claiming all of it.+import type { Ctx } from "../canvas-core/core";++type Proto = Record<string, (...a: unknown[]) => unknown>;+// src: "fill" a fillText call (setType draws one per character), "probe" a whole line or box the art reported (probeRect, drawEl)+type Rec = { kind: "text" | "box" | "photo"; src: "fill" | "probe" | "image"; label: string; x0: number; y0: number; x1: number; y1: number; alpha: number; order: number };+const protos = (): Proto[] => [CanvasRenderingContext2D.prototype, ...(typeof OffscreenCanvasRenderingContext2D !== "undefined" ? [OffscreenCanvasRenderingContext2D.prototype] : [])] as unknown as Proto[];+const G = globalThis as { __ANIDOODLE_SHARP__?: "skip"; __ANIDOODLE_PROBE__?: (r: { kind: "text" | "box"; label: string; x0: number; y0: number; x1: number; y1: number }) => void };++const boxOf = (c: Ctx, pts: number[][]) => { const T = c.getTransform(), q = pts.map(([u, v]) => [T.a * u + T.c * v + T.e, T.b * u + T.d * v + T.f]); return { x0: Math.min(...q.map((p) => p[0])), y0: Math.min(...q.map((p) => p[1])), x1: Math.max(...q.map((p) => p[0])), y1: Math.max(...q.map((p) => p[1])) }; };+const textBox = (c: Ctx, t: string, x: number, y: number) => {+ const m = c.measureText(t), a = c.textAlign, dx = a === "center" ? -m.width / 2 : a === "right" || a === "end" ? -m.width : 0;+ return boxOf(c, [[x + dx, y - m.actualBoundingBoxAscent], [x + dx + m.width, y - m.actualBoundingBoxAscent], [x + dx, y + m.actualBoundingBoxDescent], [x + dx + m.width, y + m.actualBoundingBoxDescent]]);+};+// drawImage(img, dx, dy), (img, dx, dy, dw, dh) or (img, sx, sy, sw, sh, dx, dy, dw, dh): the destination box+const imageBox = (c: Ctx, img: { width?: number; height?: number }, a: number[]) => {+ const [dx, dy, dw, dh] = a.length >= 8 ? [a[4], a[5], a[6], a[7]] : a.length >= 4 ? a : [a[0], a[1], Number(img.width), Number(img.height)];+ return boxOf(c, [[dx, dy], [dx + dw, dy], [dx, dy + dh], [dx + dw, dy + dh]]);+};+const hex = (s: string) => s.trim().toLowerCase();+const two = (n: number) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, "0");+/**+ * A declared brand colour as the #rrggbb a canvas reports for its fills, or null when it is not one this+ * can read. #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba() and hsl()/hsla() are read (alpha is ignored:+ * the colour is the brand's, the alpha is what the scan measures). A short "#c41" or an hsl() used to be+ * compared as written, never matched a fill, and the translucent check passed without looking.+ */+export const brandHex = (c: unknown): string | null => {+ if (typeof c !== "string") return null;+ const s = c.trim().toLowerCase();+ let m = /^#([0-9a-f]{3,4})$/.exec(s); if (m) return "#" + [...m[1].slice(0, 3)].map((d) => d + d).join("");+ m = /^#([0-9a-f]{6})([0-9a-f]{2})?$/.exec(s); if (m) return "#" + m[1];+ m = /^rgba?\(\s*([\d.]+)\s*[, ]\s*([\d.]+)\s*[, ]\s*([\d.]+)\s*(?:[,/]\s*[\d.]+%?\s*)?\)$/.exec(s); if (m) return "#" + [m[1], m[2], m[3]].map((v) => two(Number(v))).join("");+ m = /^hsla?\(\s*([\d.]+)(?:deg)?\s*[, ]\s*([\d.]+)%\s*[, ]\s*([\d.]+)%\s*(?:[,/]\s*[\d.]+%?\s*)?\)$/.exec(s);+ if (m) {+ const h = ((Number(m[1]) % 360) + 360) % 360, sat = Number(m[2]) / 100, l = Number(m[3]) / 100, k = (n: number) => (n + h / 30) % 12, a = sat * Math.min(l, 1 - l);+ const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));+ return "#" + [f(0), f(8), f(4)].map((v) => two(v * 255)).join("");+ }+ return null;+};+const colourAlpha = (fill: unknown): { c: string; a: number } | null => {+ if (typeof fill !== "string") return null;+ const m = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/.exec(fill.replace(/\s+/g, " ").trim());+ if (m) return { c: "#" + [m[1], m[2], m[3]].map((v) => Number(v).toString(16).padStart(2, "0")).join(""), a: m[4] === undefined ? 1 : Number(m[4]) };+ return /^#[0-9a-f]{6}$/i.test(fill) ? { c: hex(fill), a: 1 } : null;+};++export const instruments = (o: { ctx: () => Ctx; images: () => Set<unknown>; draw: (frame: number) => void; read: () => Uint8ClampedArray; clearCache?: () => void }) => {+ const own = (c: Ctx & { __frame?: boolean }) => c === o.ctx() || !!c.__frame; // ctx is a getter: the page mounts its context after building the instruments+ // TYPED LAYERS (the blur mask's limit, above). From the first blurred frame on, every surface that is not+ // the frame's own and gets text (or a typed surface drawn into it) is marked, and each frame counts how+ // many marked surfaces it composites. Installed only when a blur runs, so a shipped player is untouched;+ // the film's layer memo is emptied once then so the layers already built are rebuilt and marked.+ const typed = new WeakSet<object>(); let counting = false, layerType = 0, marking = false;+ const mark = () => {+ if (marking) return; marking = true;+ protos().forEach((p) => {+ const ft = p.fillText, st = p.strokeText, di = p.drawImage;+ p.fillText = function (this: Ctx, ...a: unknown[]) { if (!own(this) && String(a[0]).trim()) typed.add(this.canvas); return ft.apply(this, a); };+ p.strokeText = function (this: Ctx, ...a: unknown[]) { if (!own(this) && String(a[0]).trim()) typed.add(this.canvas); return st.apply(this, a); };+ p.drawImage = function (this: Ctx, ...a: unknown[]) { if (typed.has(a[0] as object)) { if (own(this)) { if (counting) layerType++; } else typed.add(this.canvas); } return di.apply(this, a); };+ });+ o.clearCache?.();+ };+ // hide: leave text / photos out of the frame's own drawing while fn runs. Restores the prototypes even on a throw.+ const hiding = <T>(what: { text?: boolean | string; photo?: boolean }, fn: () => T): T => {+ const ps = protos(), saved = ps.map((p) => ({ fillText: p.fillText, strokeText: p.strokeText, drawImage: p.drawImage })), imgs = o.images();+ const skipText = (t: unknown) => what.text === true || (typeof what.text === "string" && String(t) === what.text);+ ps.forEach((p, i) => {+ for (const k of ["fillText", "strokeText"] as const) { const f = saved[i][k]; p[k] = function (this: Ctx, ...a: unknown[]) { if (own(this) && skipText(a[0])) return; return f.apply(this, a); }; }+ const d = saved[i].drawImage; p.drawImage = function (this: Ctx, ...a: unknown[]) { if (what.photo && own(this) && imgs.has(a[0])) return; return d.apply(this, a); };+ });+ const prev = G.__ANIDOODLE_SHARP__; if (what.text === true || what.photo) G.__ANIDOODLE_SHARP__ = "skip";+ try { return fn(); } finally { ps.forEach((p, i) => Object.assign(p, saved[i])); G.__ANIDOODLE_SHARP__ = prev; }+ };++ /**+ * The sharp layers of frame n: [mask of pixels the type/photos/sharp() own, the whole sharp frame], or null+ * when the frame has none. layerType: how many layers holding type the frame composites (those blur).+ */+ const sharpLayers = (n: number) => {+ mark(); layerType = 0; counting = true;+ try { o.draw(n); } finally { counting = false; }+ const whole = o.read().slice(), lt = layerType;+ hiding({ text: true, photo: true }, () => o.draw(n)); const bare = o.read();+ const mask = new Uint8Array(whole.length / 4); let any = 0;+ for (let i = 0, p = 0; p < whole.length; i++, p += 4) if (whole[p] !== bare[p] || whole[p + 1] !== bare[p + 1] || whole[p + 2] !== bare[p + 2] || whole[p + 3] !== bare[p + 3]) { mask[i] = 1; any++; }+ return any || lt ? { mask, whole, count: any, layerType: lt } : null;+ };+ /** Run fn (the subframe loop) with the sharp layers left out. */+ const withoutSharp = <T>(fn: () => T) => hiding({ text: true, photo: true }, fn);++ /** Layer records for each frame asked, in draw order, plus brand-colour fills at a translucent alpha. */+ const layers = (frames: number[], brand: string[] = []) => {+ // declared colours are read as #rrggbb (brandHex); one that cannot be read is returned in `unread`, and+ // layerscan fails the translucent check on it rather than comparing a colour no fill can match+ const unread = brand.filter((c) => !brandHex(c)), brandSet = new Set(brand.map(brandHex).filter((c): c is string => !!c));+ const out: { frame: number; recs: Rec[]; translucent: { colour: string; alpha: number }[]; unread?: string[] }[] = [], ps = protos(), imgs = o.images();+ const saved = ps.map((p) => ({ fillText: p.fillText, drawImage: p.drawImage, fill: p.fill, fillRect: p.fillRect, stroke: p.stroke }));+ let recs: Rec[] = [], tr: { colour: string; alpha: number }[] = [], order = 0;+ const brandFill = (c: Ctx, style: unknown) => { if (!brandSet.size || !own(c)) return; const ca = colourAlpha(style); if (!ca || !brandSet.has(ca.c)) return; const a = c.globalAlpha * ca.a; if (a > 0.05 && a < 0.95) tr.push({ colour: ca.c, alpha: +a.toFixed(3) }); };+ ps.forEach((p, i) => {+ const s = saved[i];+ p.fillText = function (this: Ctx, ...a: unknown[]) { if (own(this) && this.globalAlpha >= 0.1 && String(a[0]).trim()) recs.push({ kind: "text", src: "fill", label: String(a[0]), ...textBox(this, String(a[0]), Number(a[1]), Number(a[2])), alpha: this.globalAlpha, order: order++ }); return s.fillText.apply(this, a); };+ p.drawImage = function (this: Ctx, ...a: unknown[]) { if (own(this) && imgs.has(a[0])) recs.push({ kind: "photo", src: "image", label: String((a[0] as { __name?: string }).__name ?? "image"), ...imageBox(this, a[0] as { width?: number; height?: number }, a.slice(1).map(Number)), alpha: this.globalAlpha, order: order++ }); return s.drawImage.apply(this, a); };+ p.fill = function (this: Ctx, ...a: unknown[]) { brandFill(this, this.fillStyle); return s.fill.apply(this, a); };+ p.fillRect = function (this: Ctx, ...a: unknown[]) { brandFill(this, this.fillStyle); return s.fillRect.apply(this, a); };+ p.stroke = function (this: Ctx, ...a: unknown[]) { brandFill(this, this.strokeStyle); return s.stroke.apply(this, a); };+ });+ const prevProbe = G.__ANIDOODLE_PROBE__;+ G.__ANIDOODLE_PROBE__ = (r) => { recs.push({ ...r, src: "probe", alpha: 1, order: order++ }); };+ try { for (const f of frames) { recs = []; tr = []; order = 0; o.draw(f); out.push({ frame: f, recs, translucent: tr, ...(unread.length ? { unread } : {}) }); } }+ finally { ps.forEach((p, i) => Object.assign(p, saved[i])); G.__ANIDOODLE_PROBE__ = prevProbe; }+ return out;+ };++ /** Visible ink of the text inside each box on frame n: pixels that change when ALL text is left out, counted per box (device px). */+ const ink = (n: number, boxes: { x0: number; y0: number; x1: number; y1: number }[], width: number) => {+ o.draw(n); const whole = o.read().slice();+ hiding({ text: true }, () => o.draw(n)); const bare = o.read(), height = whole.length / 4 / width;+ return boxes.map((b) => {+ let k = 0; const x0 = Math.max(0, Math.floor(b.x0)), x1 = Math.min(width, Math.ceil(b.x1)), y0 = Math.max(0, Math.floor(b.y0)), y1 = Math.min(height, Math.ceil(b.y1));+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const p = (y * width + x) * 4; if (Math.abs(whole[p] - bare[p]) + Math.abs(whole[p + 1] - bare[p + 1]) + Math.abs(whole[p + 2] - bare[p + 2]) > 24) k++; }+ return k;+ });+ };+ return { sharpLayers, withoutSharp, layers, ink };+};diff --git a/skills/anidoodle/engine/src/hosts/page-fixtureDeck.ts b/skills/anidoodle/engine/src/hosts/page-fixtureDeck.tsnew file mode 100644index 0000000..01f0754--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-fixtureDeck.ts@@ -0,0 +1,5 @@+// TEST FIXTURE for tools/motionscan.mjs and tools/layerscan.mjs (see canvas-core/fixtureMotion.ts).+import { fixtureDeck } from "../canvas-core/fixtureMotion";+import { mountFilm } from "./page";++mountFilm(fixtureDeck);diff --git a/skills/anidoodle/engine/src/hosts/page-fixtureShipBlind.ts b/skills/anidoodle/engine/src/hosts/page-fixtureShipBlind.tsnew file mode 100644index 0000000..7b77b0c--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-fixtureShipBlind.ts@@ -0,0 +1,5 @@+// TEST FIXTURE for tools/ship.mjs (src/canvas-core/fixtureShip.ts): four checks cannot look, so ship must FAIL it.+import { fixtureShipBlind } from "../canvas-core/fixtureShipBlind";+import { mountFilm } from "./page";++mountFilm(fixtureShipBlind);diff --git a/skills/anidoodle/engine/src/hosts/page-fixtureShipGreen.ts b/skills/anidoodle/engine/src/hosts/page-fixtureShipGreen.tsnew file mode 100644index 0000000..5aebe37--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-fixtureShipGreen.ts@@ -0,0 +1,5 @@+// TEST FIXTURE for tools/framecheck.mjs and tools/ship.mjs (src/canvas-core/fixtureShip.ts).+import { fixtureShipGreen } from "../canvas-core/fixtureShipGreen";+import { mountFilm } from "./page";++mountFilm(fixtureShipGreen);diff --git a/skills/anidoodle/engine/src/hosts/page-fixtureShipLocked.ts b/skills/anidoodle/engine/src/hosts/page-fixtureShipLocked.tsnew file mode 100644index 0000000..00fe0fa--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-fixtureShipLocked.ts@@ -0,0 +1,5 @@+// TEST FIXTURE for tools/ship-e2e.mjs (src/canvas-core/fixtureShip.ts).+import { fixtureShipLocked } from "../canvas-core/fixtureShipLocked";+import { mountFilm } from "./page";++mountFilm(fixtureShipLocked);diff --git a/skills/anidoodle/engine/src/hosts/page-fixtureShipRed.ts b/skills/anidoodle/engine/src/hosts/page-fixtureShipRed.tsnew file mode 100644index 0000000..65a3d68--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-fixtureShipRed.ts@@ -0,0 +1,5 @@+// TEST FIXTURE for tools/framecheck.mjs and tools/ship.mjs (src/canvas-core/fixtureShip.ts).+import { fixtureShipRed } from "../canvas-core/fixtureShipRed";+import { mountFilm } from "./page";++mountFilm(fixtureShipRed);diff --git a/skills/anidoodle/engine/src/hosts/page-fixtureShipTrack.ts b/skills/anidoodle/engine/src/hosts/page-fixtureShipTrack.tsnew file mode 100644index 0000000..9cb8b3a--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-fixtureShipTrack.ts@@ -0,0 +1,5 @@+// TEST FIXTURE for tools/ship-e2e.mjs (src/canvas-core/fixtureShip.ts).+import { fixtureShipTrack } from "../canvas-core/fixtureShipTrack";+import { mountFilm } from "./page";++mountFilm(fixtureShipTrack);diff --git a/skills/anidoodle/engine/src/hosts/page-fixtureWorld.ts b/skills/anidoodle/engine/src/hosts/page-fixtureWorld.tsnew file mode 100644index 0000000..6e3050e--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-fixtureWorld.ts@@ -0,0 +1,5 @@+// TEST FIXTURE for tools/motionscan.mjs and tools/layerscan.mjs (see canvas-core/fixtureMotion.ts).+import { fixtureWorld } from "../canvas-core/fixtureMotion";+import { mountFilm } from "./page";++mountFilm(fixtureWorld);diff --git a/skills/anidoodle/engine/src/hosts/page-launchExampleBrand.ts b/skills/anidoodle/engine/src/hosts/page-launchExampleBrand.tsnew file mode 100644index 0000000..393a86e--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-launchExampleBrand.ts@@ -0,0 +1,4 @@+import { launchExampleBrand } from "../canvas-core/launchExampleBrand";+import { mountFilm } from "./page";++mountFilm(launchExampleBrand);diff --git a/skills/anidoodle/engine/src/hosts/page-launchExampleCleanChat.ts b/skills/anidoodle/engine/src/hosts/page-launchExampleCleanChat.tsnew file mode 100644index 0000000..2156c8c--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-launchExampleCleanChat.ts@@ -0,0 +1,4 @@+import { launchExampleCleanChat } from "../canvas-core/launchExampleCleanChat";+import { mountFilm } from "./page";++mountFilm(launchExampleCleanChat);diff --git a/skills/anidoodle/engine/src/hosts/page.ts b/skills/anidoodle/engine/src/hosts/page.tsindex abf30a9..bd7635d 100644--- a/skills/anidoodle/engine/src/hosts/page.ts+++ b/skills/anidoodle/engine/src/hosts/page.ts@@ -1,9 +1,11 @@// THE ONE GENERATED PAGE. Playwright, the HTML player and (Phase 5) Hyperframes all drive this// same page through window.FILM. Everything host-specific (DOM, clocks, asset decoding, Web// Audio) lives HERE; the art core never sees it.-import type { Ctx, Env, Layer, ProbeRec } from "../canvas-core/core";+import type { Ctx, Env, Layer } from "../canvas-core/core";import { Film, renderFrame, validate } from "../canvas-core/film";import { embeddedAudio, type AudioPayload } from './audio';+import { instruments } from "./instrument";+import { frameProbe } from "./probe";declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string>; __BAKE_SRC__?: Record<string, string>; __ANIDOODLE_SRC__?: WeakMap<object, string>; __SHAPE__?: string; __AUDIO__?: AudioPayload } }@@ -48,7 +50,10 @@ export const mountFilm = (film: Film) => {// contract rule 4: every asset is loaded AND decoded before frame 0, or the film refuses to startconst ready = (async () => {const problems = validate(film); if (problems.length) throw new Error("timeline: " + problems.join("; "));- await Promise.all(Object.entries(film.assets.images).map(async ([name, url]) => { const img = new Image(); img.src = window.__ASSETS__?.[name] ?? url; await img.decode(); images.set(name, img); }));+ await Promise.all(Object.entries(film.assets.images).map(async ([name, url]) => { const img = new Image(); img.src = window.__ASSETS__?.[name] ?? url; await img.decode(); (img as unknown as { __name: string }).__name = name; images.set(name, img); }));+ // a launch look's own font files (launchLook.registerFaces) are loaded before frame 0, so no frame is set+ // in a fallback face; a film that added none waits for nothing+ if ((document.fonts as unknown as { size: number }).size) await document.fonts.ready;mount(1); return film.meta;})();const seek = (frame: number) => { const t0 = performance.now(); const shot = renderFrame(film, ctx, frame, env); ctx.getImageData(0, 0, 1, 1); current = frame; return { shot, ms: performance.now() - t0 }; }; // getImageData forces the deferred raster so the timing is real@@ -74,7 +79,9 @@ export const mountFilm = (film: Film) => {// divided by `px` (default 3: subframes at most 3 px apart), is the count, 1 on a still frame (the// sharp frame itself, untouched), at most `max` (default 32). Pure pixels in, a number out:// deterministic like the frames it measures.- type BlurSpec = { samples?: number; shutter?: number; max?: number; px?: number };+ // sharp: true (the default) keeps type, photos and sharp() out of the blur (hosts/instrument.ts); false blurs everything.+ type BlurSpec = { samples?: number; shutter?: number; max?: number; px?: number; sharp?: boolean };+ const inst = instruments({ ctx: () => ctx, images: () => new Set(images.values()), draw: (f) => { renderFrame(film, ctx, f, env); }, read: () => ctx.getImageData(0, 0, canvas.width, canvas.height).data, clearCache: () => env.cache.clear() });const lumaGrid = (f: number, cell: number) => {renderFrame(film, ctx, f, env); const w = canvas.width, h = canvas.height, d = ctx.getImageData(0, 0, w, h).data, gw = Math.floor(w / cell), gh = Math.floor(h / cell), g = new Float32Array(gw * gh);for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) { let s = 0; for (let yy = 0; yy < cell; yy += 2) for (let xx = 0; xx < cell; xx += 2) { const p = ((y * cell + yy) * w + x * cell + xx) * 4, a = d[p + 3] / 255; s += (0.2126 * d[p] + 0.7152 * d[p + 1] + 0.0722 * d[p + 2]) * a; } g[y * gw + x] = s / ((cell * cell) / 4); }@@ -113,49 +120,27 @@ export const mountFilm = (film: Film) => {if (shot && !stepped && samples === 0) { speed = speedOf(win(n - sh / 2), win(n + sh / 2)); samples = Math.max(1, Math.min(o.max ?? 32, Math.ceil(speed / (o.px ?? 3)))); }if (!shot || samples < 2 || stepped) { const r = seek(n); return { shot: r.shot, ms: r.ms, samples: 1, speed }; }const t0 = performance.now(), w = canvas.width, h = canvas.height, acc = new Float64Array(w * h * 4);- for (let i = 0; i < samples; i++) {+ const keep = o.sharp === false ? null : inst.sharpLayers(n); // the frame's type and photos, drawn sharp+ const sub = () => { for (let i = 0; i < samples; i++) {const t = win(n + ((i + 0.5) / samples - 0.5) * sh);renderFrame(film, ctx, t, env);const d = ctx.getImageData(0, 0, w, h).data;for (let p = 0; p < d.length; p += 4) { const a = d[p + 3], k = a / 255; acc[p] += toLin[d[p]] * k; acc[p + 1] += toLin[d[p + 1]] * k; acc[p + 2] += toLin[d[p + 2]] * k; acc[p + 3] += a; }- }+ } };+ if (keep) inst.withoutSharp(sub); else sub();const img = ctx.createImageData(w, h), out = img.data, inv = 1 / samples, full = 255 * samples;for (let p = 0; p < out.length; p += 4) {const A = acc[p + 3]; if (A === 0) continue; // nothing was ever drawn here: stays transparent blackconst c = A === full ? inv : 255 / A; // premultiplied average, un-premultiplied by the mean alphaout[p] = fromLin(acc[p] * c); out[p + 1] = fromLin(acc[p + 1] * c); out[p + 2] = fromLin(acc[p + 2] * c); out[p + 3] = Math.round(A * inv);}+ if (keep) for (let i = 0, p = 0; i < keep.mask.length; i++, p += 4) if (keep.mask[i]) { out[p] = keep.whole[p]; out[p + 1] = keep.whole[p + 1]; out[p + 2] = keep.whole[p + 2]; out[p + 3] = keep.whole[p + 3]; }ctx.putImageData(img, 0, 0); current = n;- return { shot: shot.id, ms: performance.now() - t0, samples, speed };- };- // THE FRAME PROBE (tools/framecheck.mjs). For each frame asked, every line of text (fillText on the- // frame or a full-frame sheet, writeOn, setType) and every content box the art core reports- // (probeRect: a card, a window) is collected in device pixels; a box the frame's edge cuts through- // is returned. Whatever lies wholly outside the frame, or wholly inside it, is fine. With `all`, every- // visible line of text is returned too (cut: false when whole), for the checks that judge where- // text sits (the 9:16 safe zones, textrules.mjs).- const probe = (frames: number[], all = false) => {- const out: (ProbeRec & { frame: number; cut?: boolean })[] = [], g = globalThis as { __ANIDOODLE_PROBE__?: (r: ProbeRec) => void };- const protos = [CanvasRenderingContext2D.prototype, ...(typeof OffscreenCanvasRenderingContext2D !== "undefined" ? [OffscreenCanvasRenderingContext2D.prototype] : [])] as unknown as { fillText: (t: string, x: number, y: number, w?: number) => void }[];- const orig = protos.map((p) => p.fillText);- let frame = 0, recs: ProbeRec[] = [];- protos.forEach((p, i) => { p.fillText = function (this: Ctx & { __frame?: boolean }, t: string, x: number, y: number, w?: number) {- if ((this === ctx || this.__frame) && this.globalAlpha >= 0.1 && String(t).trim()) {- const m = this.measureText(t), a = this.textAlign, dx = a === "center" ? -m.width / 2 : a === "right" || a === "end" ? -m.width : 0, T = this.getTransform();- const bx = [[x + dx, y - m.actualBoundingBoxAscent], [x + dx + m.width, y - m.actualBoundingBoxAscent], [x + dx, y + m.actualBoundingBoxDescent], [x + dx + m.width, y + m.actualBoundingBoxDescent]].map(([u, v]) => [T.a * u + T.c * v + T.e, T.b * u + T.d * v + T.f]);- recs.push({ kind: "text", label: String(t), x0: Math.min(...bx.map((q) => q[0])), y0: Math.min(...bx.map((q) => q[1])), x1: Math.max(...bx.map((q) => q[0])), y1: Math.max(...bx.map((q) => q[1])) });- }- return (orig[i] as (t: string, x: number, y: number, w?: number) => void).call(this, t, x, y, w);- }; });- g.__ANIDOODLE_PROBE__ = (r) => recs.push(r);- try {- for (frame of frames) {- recs = []; seek(frame); const W = canvas.width, H = canvas.height, tol = 1.5;- for (const r of recs) { const inter = r.x1 > 0 && r.x0 < W && r.y1 > 0 && r.y0 < H, inside = r.x0 >= -tol && r.y0 >= -tol && r.x1 <= W + tol && r.y1 <= H + tol; if (inter && !inside) out.push({ ...r, frame }); else if (all && inter && r.kind === "text") out.push({ ...r, frame, cut: false }); }- }- } finally { protos.forEach((p, i) => (p.fillText = orig[i] as never)); delete g.__ANIDOODLE_PROBE__; }- return out;+ return { shot: shot.id, ms: performance.now() - t0, samples, speed, sharpPx: keep?.count ?? 0, typeInLayers: keep?.layerType ?? 0 }; // typeInLayers: layers holding type that blurred (instrument.ts)};+ // THE FRAME PROBE (tools/framecheck.mjs): hosts/probe.ts. Every call rebuilds the film's layer memo under+ // its hooks, so text in a reused layer (a bake() sprite, a held plate) is seen in every batch.+ const probe = frameProbe({ canvas: () => canvas, ctx: () => ctx, seek: (f) => { seek(f); }, clearCache: () => env.cache.clear() });// 3D CHECKS (tools/gate.mjs, still.mjs --grips). Turns three-core/checks3d.ts on, draws each frame asked// and returns what every frame's runChecks found, plus where its grips sit on screen (logical px).// A frame whose film never calls runChecks returns no record. Off by default: no hook, no cost.@@ -187,7 +172,11 @@ export const mountFilm = (film: Film) => {if (u > 0 && posterOf) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = Math.min(1, u); ctx.globalCompositeOperation = "source-over"; if (u >= 1) ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(posterOf.img, 0, 0); ctx.restore(); }current = n; return r;};- window.FILM = { probe, checks3d, meta: { ...film.meta, hasAudio: typeof film.audio === "function", shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, poster, bakes: { load: bakes.load, take: bakes.take, hashes: bakes.hashes, stats: () => bakes.stats }, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };+ // THE LAYER PROBE (tools/layerscan.mjs): per frame, text, photos and reported boxes in draw order, and+ // translucent fills in the brand's colours; ink(): how much each text box shows on a frame.+ const layers = (frames: number[], brand: string[] = []) => { const r = inst.layers(frames, brand); current = frames[frames.length - 1] ?? current; return r; };+ const ink = (frame: number, boxes: { x0: number; y0: number; x1: number; y1: number }[]) => inst.ink(frame, boxes, canvas.width);+ window.FILM = { probe, checks3d, layers, ink, meta: { ...film.meta, placeholders: (window as unknown as { __PLACEHOLDERS__?: string[] }).__PLACEHOLDERS__ ?? [], hasAudio: typeof film.audio === "function", shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, poster, bakes: { load: bakes.load, take: bakes.take, hashes: bakes.hashes, stats: () => bakes.stats }, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };// ---- the player: click or space to play, arrows to step, ?frame=N to open on a frameready.then(() => {diff --git a/skills/anidoodle/engine/src/hosts/probe.ts b/skills/anidoodle/engine/src/hosts/probe.tsnew file mode 100644index 0000000..622167a--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/probe.ts@@ -0,0 +1,124 @@+// THE FRAME PROBE (tools/framecheck.mjs), host side. For each frame asked, every line of text (fillText on+// the frame or a full-frame sheet, writeOn, setType) and every content box the art core reports+// (probeRect: a card, a window) is collected in device pixels; a box the frame's edge cuts through+// is returned. Whatever lies wholly outside the frame, or wholly inside it, is fine. With `all`, every+// visible line of text is returned too (cut: false when whole), for the checks that judge where+// text sits (the 9:16 safe zones, textrules.mjs).+// Text is followed through offscreen layers: every fillText/strokeText on ANY surface is recorded in+// that surface's own pixels, and a drawImage of a surface carries its text onto the surface it is+// drawn into (through the source rectangle, the destination rectangle and the current transform).+// So text a film sets on a sheet and composites later is seen exactly like text on the frame+// (the reading-time check was blind to it before). A full clearRect, or an opaque full fillRect,+// forgets a surface's text. Each text record also carries its alpha, its type size in device px,+// its font family and the texture mark (texture(): words not meant to be read).+//+// It lives in its own module (page.ts mounts it) so the unit tests can drive it with a stand-in+// canvas in node: test/probe.test.ts.+import type { Ctx, ProbeRec } from "../canvas-core/core";++type TextRec = ProbeRec & { alpha: number; px: number; family: string; texture?: boolean };+type B = { x0: number; y0: number; x1: number; y1: number };+export type ProbeOut = (ProbeRec | TextRec) & { frame: number; cut?: boolean };++/**+ * canvas/ctx are getters (the page mounts a new context at each scale). seek draws one frame.+ * clearCache empties the film's layer memo (env.cache): a pure memo, so emptying it changes no pixel.+ */+export const frameProbe = (o: { canvas: () => { width: number; height: number }; ctx: () => Ctx; seek: (frame: number) => void; clearCache: () => void }) => (frames: number[], all = false) => {+ const canvas = o.canvas(), ctx = o.ctx();+ const out: ProbeOut[] = [], g = globalThis as { __ANIDOODLE_PROBE__?: (r: ProbeRec) => void };+ type Proto = Record<string, (...a: unknown[]) => void>;+ const protos = [CanvasRenderingContext2D.prototype, ...(typeof OffscreenCanvasRenderingContext2D !== "undefined" ? [OffscreenCanvasRenderingContext2D.prototype] : [])] as unknown as Proto[];+ const names = ["fillText", "strokeText", "drawImage", "clearRect", "fillRect", "beginPath", "rect", "roundRect", "arc", "arcTo", "ellipse", "moveTo", "lineTo", "bezierCurveTo", "quadraticCurveTo", "clip", "save", "restore", "reset"] as const, orig = protos.map((p) => Object.fromEntries(names.map((n) => [n, p[n]])) as Proto);+ const texts = new WeakMap<object, TextRec[]>(), of = (c: object) => { let l = texts.get(c); if (!l) texts.set(c, (l = [])); return l; };+ const box = (T: DOMMatrix, pts: number[][]) => { const q = pts.map(([u, v]) => [T.a * u + T.c * v + T.e, T.b * u + T.d * v + T.f]); return { x0: Math.min(...q.map((p) => p[0])), y0: Math.min(...q.map((p) => p[1])), x1: Math.max(...q.map((p) => p[0])), y1: Math.max(...q.map((p) => p[1])) }; };+ const zoom = (T: DOMMatrix) => Math.sqrt(Math.abs(T.a * T.d - T.b * T.c));+ // CLIPS. A text drawn under a clip (an input field that scrolls its text, a mask a line rises through)+ // is seen only inside it. The probe keeps each context's clip as the bounding box of the path it was+ // made from (rect, roundRect, arc, arcTo, ellipse, lines and curves, in device px), intersected down the+ // save/restore stack, and cuts every text box to it; a text wholly outside its clip is not drawn.+ // A clip the probe cannot measure (a Path2D, or a path with no area it could read) is treated as no+ // clip: the text stays in view of the checks. Reading an unknown clip as "clips everything" made every+ // line under it vanish, and the checks then passed on text they never saw.+ const clipOf = new WeakMap<object, { box: B | null; stack: (B | null)[]; path: B | null }>(), cs = (c: object) => { let v = clipOf.get(c); if (!v) clipOf.set(c, (v = { box: null, stack: [], path: null })); return v; };+ const meet = (a: B | null, b: B | null): B | null => (!a ? b : !b ? a : { x0: Math.max(a.x0, b.x0), y0: Math.max(a.y0, b.y0), x1: Math.min(a.x1, b.x1), y1: Math.min(a.y1, b.y1) });+ const grow = (c: Ctx, pts: number[][]) => { const st = cs(c), r = box(c.getTransform(), pts); st.path = st.path ? { x0: Math.min(st.path.x0, r.x0), y0: Math.min(st.path.y0, r.y0), x1: Math.max(st.path.x1, r.x1), y1: Math.max(st.path.y1, r.y1) } : r; };+ const clipped = <T extends B>(c: Ctx, t: T): T | null => { const k = clipOf.get(c)?.box; if (!k) return t; const m = meet(t, k)!; return m.x1 - m.x0 <= 0.5 || m.y1 - m.y0 <= 0.5 ? null : { ...t, ...m }; };+ const text = function (this: Ctx & { __texture?: boolean }, t: string, x: number, y: number) {+ if (!String(t).trim() || this.globalAlpha < 0.01) return;+ const m = this.measureText(t), a = this.textAlign, dx = a === "center" ? -m.width / 2 : a === "right" || a === "end" ? -m.width : 0, T = this.getTransform();+ const fm = /(\d+(?:\.\d+)?)px\s*(.*)$/.exec(this.font), px = (fm ? Number(fm[1]) : 10) * zoom(T), family = (fm?.[2] ?? "").split(",")[0].trim().replace(/^["']|["']$/g, "");+ const rec = clipped(this, { kind: "text" as const, label: String(t), ...box(T, [[x + dx, y - m.actualBoundingBoxAscent], [x + dx + m.width, y - m.actualBoundingBoxAscent], [x + dx, y + m.actualBoundingBoxDescent], [x + dx + m.width, y + m.actualBoundingBoxDescent]]), alpha: this.globalAlpha, px, family, texture: this.__texture || undefined });+ if (rec) of(this.canvas).push(rec);+ };+ const opaque = new WeakSet<object>(); // surfaces whose last full-size fill was opaque: drawn at alpha 1 they cover what is under them+ const solid = (c: Ctx) => c.globalAlpha >= 1 && c.globalCompositeOperation === "source-over" && typeof c.fillStyle === "string" && !/rgba|hsla|transparent|#[0-9a-f]{4}$|#[0-9a-f]{8}$/i.test(c.fillStyle);+ const full = (c: Ctx, x: number, y: number, w: number, h: number) => { const r = box(c.getTransform(), [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]); return r.x0 <= 0 && r.y0 <= 0 && r.x1 >= c.canvas.width && r.y1 >= c.canvas.height; };+ const forget = (c: Ctx, x: number, y: number, w: number, h: number) => {+ const l = texts.get(c.canvas); if (!l?.length) return;+ const r = box(c.getTransform(), [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]), cw = c.canvas.width, ch = c.canvas.height;+ if (r.x0 <= 0 && r.y0 <= 0 && r.x1 >= cw && r.y1 >= ch) { l.length = 0; return; }+ // what lies wholly under an opaque fill is covered: the viewer cannot see it, so it is no longer drawn text+ texts.set(c.canvas, l.filter((t) => !(t.x0 >= r.x0 && t.y0 >= r.y0 && t.x1 <= r.x1 && t.y1 <= r.y1)));+ };+ const isPath2D = (v: unknown) => typeof Path2D !== "undefined" && v instanceof Path2D;+ protos.forEach((p, i) => {+ p.fillText = function (this: Ctx, ...a: unknown[]) { text.call(this, a[0] as string, a[1] as number, a[2] as number); return orig[i].fillText.apply(this, a); };+ p.strokeText = function (this: Ctx, ...a: unknown[]) { text.call(this, a[0] as string, a[1] as number, a[2] as number); return orig[i].strokeText.apply(this, a); };+ p.clearRect = function (this: Ctx, ...a: unknown[]) { const q = a as [number, number, number, number]; forget(this, ...q); if (full(this, ...q)) opaque.delete(this.canvas); return orig[i].clearRect.apply(this, a); };+ p.fillRect = function (this: Ctx, ...a: unknown[]) { const q = a as [number, number, number, number]; if (solid(this)) { forget(this, ...q); if (full(this, ...q)) opaque.add(this.canvas); } return orig[i].fillRect.apply(this, a); };+ p.drawImage = function (this: Ctx, ...a: unknown[]) {+ const src = texts.get(a[0] as object), s = a[0] as { width: number; height: number }, n = a.length;+ const [sx, sy, sw, sh, dx, dy, dw, dh] = (n >= 9 ? a.slice(1, 9) : n >= 5 ? [0, 0, s.width, s.height, ...a.slice(1, 5)] : [0, 0, s.width, s.height, a[1], a[2], s.width, s.height]) as number[];+ if (opaque.has(a[0] as object) && this.globalAlpha >= 1 && this.globalCompositeOperation === "source-over") forget(this, dx, dy, dw, dh); // an opaque sheet covers what was under it+ if (src?.length && this.globalAlpha >= 0.01) {+ const kx = dw / sw, ky = dh / sh, T = this.getTransform(), z = zoom(T) * Math.sqrt(Math.abs(kx * ky)), dst = of(this.canvas);+ for (const t of src) {+ if (t.x1 <= sx || t.x0 >= sx + sw || t.y1 <= sy || t.y0 >= sy + sh) continue; // outside the source rectangle: not drawn+ const u0 = dx + (t.x0 - sx) * kx, v0 = dy + (t.y0 - sy) * ky, u1 = dx + (t.x1 - sx) * kx, v1 = dy + (t.y1 - sy) * ky;+ const rec = clipped(this, { ...t, ...box(T, [[u0, v0], [u1, v0], [u0, v1], [u1, v1]]), alpha: t.alpha * this.globalAlpha, px: t.px * z }); if (rec) dst.push(rec);+ }+ }+ return orig[i].drawImage.apply(this, a);+ };+ const num = (a: unknown[]) => a as number[];+ p.beginPath = function (this: Ctx, ...a: unknown[]) { cs(this).path = null; return orig[i].beginPath.apply(this, a); };+ p.rect = function (this: Ctx, ...a: unknown[]) { const [x, y, w, h] = num(a); grow(this, [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]); return orig[i].rect.apply(this, a); };+ if (orig[i].roundRect) p.roundRect = function (this: Ctx, ...a: unknown[]) { const [x, y, w, h] = num(a); grow(this, [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]); return orig[i].roundRect.apply(this, a); };+ p.arc = function (this: Ctx, ...a: unknown[]) { const [x, y, r] = num(a); grow(this, [[x - r, y - r], [x + r, y - r], [x - r, y + r], [x + r, y + r]]); return orig[i].arc.apply(this, a); };+ // arcTo (rounded rects built by hand, launchKit rr()): the arc lies inside the triangle of the pen, the+ // corner and the far point, so the two control points bound it with the pen already in the box+ if (orig[i].arcTo) p.arcTo = function (this: Ctx, ...a: unknown[]) { const q = num(a); grow(this, [[q[0], q[1]], [q[2], q[3]]]); return orig[i].arcTo.apply(this, a); };+ p.ellipse = function (this: Ctx, ...a: unknown[]) { const [x, y, rx, ry] = num(a), r = Math.max(rx, ry); grow(this, [[x - r, y - r], [x + r, y - r], [x - r, y + r], [x + r, y + r]]); return orig[i].ellipse.apply(this, a); };+ p.moveTo = function (this: Ctx, ...a: unknown[]) { const [x, y] = num(a); grow(this, [[x, y]]); return orig[i].moveTo.apply(this, a); };+ p.lineTo = function (this: Ctx, ...a: unknown[]) { const [x, y] = num(a); grow(this, [[x, y]]); return orig[i].lineTo.apply(this, a); };+ p.bezierCurveTo = function (this: Ctx, ...a: unknown[]) { const q = num(a); grow(this, [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]]]); return orig[i].bezierCurveTo.apply(this, a); };+ p.quadraticCurveTo = function (this: Ctx, ...a: unknown[]) { const q = num(a); grow(this, [[q[0], q[1]], [q[2], q[3]]]); return orig[i].quadraticCurveTo.apply(this, a); };+ p.clip = function (this: Ctx, ...a: unknown[]) {+ const st = cs(this), b = st.path;+ // only a clip with a measured area narrows what the checks see; anything else is an unknown clip (see CLIPS)+ if (!isPath2D(a[0]) && b && b.x1 - b.x0 > 0.5 && b.y1 - b.y0 > 0.5) st.box = meet(st.box, b);+ return orig[i].clip.apply(this, a);+ };+ p.save = function (this: Ctx, ...a: unknown[]) { const st = cs(this); st.stack.push(st.box); return orig[i].save.apply(this, a); };+ p.restore = function (this: Ctx, ...a: unknown[]) { const st = cs(this); st.box = st.stack.length ? st.stack.pop()! : null; return orig[i].restore.apply(this, a); };+ if (orig[i].reset) p.reset = function (this: Ctx, ...a: unknown[]) { clipOf.delete(this); return orig[i].reset.apply(this, a); };+ });+ let frame = 0;+ // boxes the art reports (probeRect) join the frame's own list, so an opaque fill drawn over them covers them too+ g.__ANIDOODLE_PROBE__ = (r) => { of(canvas).push({ ...r, alpha: 1, px: undefined as unknown as number, family: "" }); };+ try {+ // Text records live only as long as this call (the hooks come off at the end). A layer the film built+ // once and reuses (a bake() sprite, a plate that skips its redraw) carries records only if it is drawn+ // under these hooks, so EVERY call starts by emptying the film's layer memo and each layer is rebuilt+ // here. Emptying it only on the first call left reused layers without records from the second batch+ // on (framecheck asks 40 frames at a time), and every text check then passed on text it never saw.+ // Plate frames from the bake store are the one blind spot left: framecheck opens the page with the bake cache off.+ o.clearCache();+ for (frame of frames) {+ of(canvas).length = 0; clipOf.delete(ctx); o.seek(frame); const W = canvas.width, H = canvas.height, tol = 1.5;+ for (const r of of(canvas).filter((t) => t.alpha >= 0.1)) { const inter = r.x1 > 0 && r.x0 < W && r.y1 > 0 && r.y0 < H, inside = r.x0 >= -tol && r.y0 >= -tol && r.x1 <= W + tol && r.y1 <= H + tol; if (inter && !inside) out.push({ ...r, frame }); else if (all && inter) out.push({ ...r, frame, cut: false }); }+ }+ } finally { protos.forEach((p, i) => names.forEach((n) => { if (orig[i][n]) p[n] = orig[i][n]; })); delete g.__ANIDOODLE_PROBE__; }+ return out;+};diff --git a/skills/anidoodle/engine/src/three-core/checks3d.ts b/skills/anidoodle/engine/src/three-core/checks3d.tsindex 896f179..26b367b 100644--- a/skills/anidoodle/engine/src/three-core/checks3d.ts+++ b/skills/anidoodle/engine/src/three-core/checks3d.ts@@ -31,6 +31,8 @@ const fmt = (p: V3) => p.toArray().map((x) => x.toFixed(2)).join(", ");type Obj = THREE.Object3D;const objOf = (x: Rig | Obj): Obj => ("hips" in x && "limbs" in x ? (x as Rig).root : (x as Obj));const within = (o: Obj, anc: Obj) => { let n: Obj | null = o; while (n) { if (n === anc) return true; n = n.parent; } return false; };+// visible itself and every ancestor visible: what the renderer would actually draw+const shown = (o: Obj) => { let n: Obj | null = o; while (n) { if (!n.visible) return false; n = n.parent; } return true; };const partName = (m: THREE.Mesh) => String(m.userData.part ?? (m.name || m.geometry.type));// ---------------------------------------------------------------- surface sampling@@ -43,21 +45,29 @@ const localSamples = (g: THREE.BufferGeometry, spacing: number): Float32Array =>let byS = sampleCache.get(g); if (!byS) sampleCache.set(g, (byS = new Map()));const hit = byS.get(spacing); if (hit) return hit;const pos = g.attributes.position, idx = g.index, n = idx ? idx.count : pos.count, tri = (i: number) => (idx ? idx.getX(i) : i);- const A = v3(), B = v3(), C = v3(), out: number[] = [];- let sp = spacing;- for (let pass = 0; pass < 6; pass++) {- out.length = 0;- // every vertex once, then extra points only inside triangles bigger than the spacing (a dense- // sphere needs no more than its vertices; a two-triangle wall needs a grid)- for (let i = 0; i < pos.count; i++) out.push(pos.getX(i), pos.getY(i), pos.getZ(i));- for (let t = 0; t + 2 < n; t += 3) {- A.fromBufferAttribute(pos, tri(t)); B.fromBufferAttribute(pos, tri(t + 1)); C.fromBufferAttribute(pos, tri(t + 2));- const k = Math.ceil(Math.max(A.distanceTo(B), B.distanceTo(C), C.distanceTo(A)) / sp);- if (k < 2) continue;- for (let i = 0; i <= k; i++) for (let j = 0; j <= k - i; j++) { if ((i === 0 && j === 0) || (i === k && j === 0) || (i === 0 && j === k)) continue; const a = i / k, b = j / k, c = 1 - a - b; out.push(A.x * c + B.x * a + C.x * b, A.y * c + B.y * a + C.y * b, A.z * c + B.z * a + C.z * b); }- }- if (out.length / 3 <= MAX_PTS) break;- sp *= 1.6;+ const A = v3(), B = v3(), C = v3();+ // The longest edge of each triangle, once. Then COUNT the points a spacing would make before making+ // any: a rig built in centimetres, or a prop scaled to almost nothing, asks for millions of points+ // at the spacing it was given. The spacing grows by 1.6x until the count fits the cap (or only the+ // vertices are left), so a tiny or non-finite spacing can never stall or overflow an array.+ const edge: number[] = [];+ for (let t = 0; t + 2 < n; t += 3) {+ A.fromBufferAttribute(pos, tri(t)); B.fromBufferAttribute(pos, tri(t + 1)); C.fromBufferAttribute(pos, tri(t + 2));+ edge.push(Math.max(A.distanceTo(B), B.distanceTo(C), C.distanceTo(A)));+ }+ const extra = (s: number) => { let c = 0; for (const e of edge) { const k = Math.ceil(e / s); if (k >= 2) c += ((k + 1) * (k + 2)) / 2 - 3; } return c; };+ const longest = edge.reduce((m, e) => Math.max(m, e), 0);+ let sp = Number.isFinite(spacing) && spacing > 0 ? spacing : longest || 1;+ for (let c = extra(sp); c > 0 && pos.count + c > MAX_PTS; c = extra(sp)) sp *= 1.6;+ // every vertex once, then extra points only inside triangles bigger than the spacing (a dense+ // sphere needs no more than its vertices; a two-triangle wall needs a grid)+ const out: number[] = [];+ for (let i = 0; i < pos.count; i++) out.push(pos.getX(i), pos.getY(i), pos.getZ(i));+ for (let t = 0, e = 0; t + 2 < n; t += 3, e++) {+ const k = Math.ceil(edge[e] / sp);+ if (k < 2) continue;+ A.fromBufferAttribute(pos, tri(t)); B.fromBufferAttribute(pos, tri(t + 1)); C.fromBufferAttribute(pos, tri(t + 2));+ for (let i = 0; i <= k; i++) for (let j = 0; j <= k - i; j++) { if ((i === 0 && j === 0) || (i === k && j === 0) || (i === 0 && j === k)) continue; const a = i / k, b = j / k, c = 1 - a - b; out.push(A.x * c + B.x * a + C.x * b, A.y * c + B.y * a + C.y * b, A.z * c + B.z * a + C.z * b); }}const arr = new Float32Array(out); byS.set(spacing, arr); return arr;};@@ -186,7 +196,11 @@ const handPart = (prop: Obj, m: THREE.Mesh) => !!m.userData.handlePart || (withiexport const checkGrip = (holder: Rig | Obj, hand: Limb | Obj, prop: Obj, frame = 0, camera?: THREE.Camera, o: GripOpts = {}): CheckResult => {const H = objOf(holder), end = isLimb(hand) ? hand.end : hand, F: Finding[] = [], where = `${H.name || "holder"} holding ${prop.name || "prop"}`;H.updateWorldMatrix(true, true); prop.updateWorldMatrix(true, true);- const h = handleOf(prop), sc = prop.getWorldScale(v3()).x, a = prop.localToWorld(h.a.clone()), b = prop.localToWorld(h.b.clone()), r = h.r * sc;+ // Hidden objects never count: a prop switched off, inside a hidden group, or still scaled to almost+ // nothing (popIn starts at 2.2e-16) is not held yet, so there is nothing to judge.+ const sc = prop.getWorldScale(v3()).x;+ if (!shown(prop) || !(Math.abs(sc) >= 1e-3 * Math.abs(H.getWorldScale(v3()).x))) return result([]);+ const h = handleOf(prop), a = prop.localToWorld(h.a.clone()), b = prop.localToWorld(h.b.clone()), r = h.r * sc;const { point: gp } = gripFrame(hand);const handMeshes = meshesOf(end), handPts = handMeshes.flatMap((m) => surfacePoints(m, r * 0.6));const handR = handPts.reduce((mx, p) => Math.max(mx, p.distanceTo(gp)), 0);diff --git a/skills/anidoodle/engine/src/three-core/mograph.ts b/skills/anidoodle/engine/src/three-core/mograph.tsindex 89b8170..861bd67 100644--- a/skills/anidoodle/engine/src/three-core/mograph.ts+++ b/skills/anidoodle/engine/src/three-core/mograph.ts@@ -103,6 +103,9 @@ export const moveAlongPath = (o: THREE.Object3D, curve: THREE.Curve<THREE.Vector// ---- morphs/** n points spaced evenly by arc length along a polyline (closed adds the edge back to the start) */export const resample = (pts: V3[], n: number, closed = false): V3[] => {+ if (!pts.length) throw new Error("resample: the shape has no points");+ // a single point (a dot that grows into a line) has no length to walk: it is that point n times+ if (pts.length === 1) return Array.from({ length: Math.max(0, n) }, () => [...pts[0]] as V3);const P = closed ? [...pts, pts[0]] : pts, cum = [0];for (let i = 1; i < P.length; i++) cum.push(cum[i - 1] + Math.hypot(P[i][0] - P[i - 1][0], P[i][1] - P[i - 1][1], P[i][2] - P[i - 1][2]));const L = cum[cum.length - 1], out: V3[] = [], m = closed ? n : n - 1;@@ -179,6 +182,37 @@ export const wave = (g: THREE.Object3D | THREE.Object3D[], f: number, at: numbercs.forEach((c, i) => { const r = rest(c), d = (i - head) / w, b = Math.abs(d) < 1 ? 0.5 + 0.5 * Math.cos(Math.PI * d) : 0; c.position.copy(r.position).addScaledVector(ax, (o.height ?? 0.4) * b); });};+/**+ * Give each object its own copy of any material it shares with another one in the list. text3d puts+ * one material on every letter, so fading letter by letter wrote all of them, and the last letter's+ * opacity won (the whole word hid). The copy starts from the shared material's REST state, so it does+ * not matter which frame is drawn first. Done once per object; the material passed in is never changed.+ */+const OWN = "anidoodleOwnMaterials";+const ownMaterials = (objs: THREE.Object3D[]) => {+ if (objs.every((o) => o.userData[OWN])) return;+ const users = new Map<THREE.Material, Set<THREE.Object3D>>();+ for (const o of objs) for (const m of mats(o)) { let u = users.get(m); if (!u) users.set(m, (u = new Set())); u.add(o); }+ for (const o of objs) {+ if (o.userData[OWN]) continue;+ o.userData[OWN] = true;+ const copies = new Map<THREE.Material, THREE.Material>();+ const own = (m: THREE.Material) => {+ if ((users.get(m)?.size ?? 0) < 2) return m;+ let c = copies.get(m);+ if (!c) {+ const r = matRest(m); c = m.clone();+ c.opacity = r.opacity; c.transparent = r.transparent;+ const em = (c as THREE.MeshStandardMaterial).emissive; if (em && r.emissive) em.copy(r.emissive);+ c.userData[REST] = { opacity: r.opacity, transparent: r.transparent, emissive: r.emissive?.clone() } as MatRest;+ copies.set(m, c);+ }+ return c;+ };+ o.traverse((n) => { const mesh = n as THREE.Mesh; if (mesh.material) mesh.material = Array.isArray(mesh.material) ? mesh.material.map(own) : own(mesh.material); });+ }+};+/** a verb as lagged() and grid() call it: one child, the frame, its own start frame, its index */export type Verb = (o: THREE.Object3D, f: number, at: number, i: number) => void;/** start a verb on each child `stagger` frames after the one before (Manim's LaggedStart) */@@ -199,6 +233,7 @@ export const grid = (g: THREE.Object3D | THREE.Object3D[], f: number, start: num*/export const kinetic = (letters: THREE.Object3D, f: number, start: number, stagger = 2, o: { style?: "rise" | "pop" | "drop" | "spin"; len?: number } = {}) => {const len = o.len ?? 12, style = o.style ?? "rise";+ if (style === "rise") ownMaterials(kids(letters));lagged(letters, f, start, stagger, (c, ff, at) => {if (style === "pop") popIn(c, ff, at, len);else if (style === "drop") dropIn(c, ff, at, len, { height: 1 });diff --git a/skills/anidoodle/engine/src/three-core/stage.ts b/skills/anidoodle/engine/src/three-core/stage.tsindex ab971dd..e10046c 100644--- a/skills/anidoodle/engine/src/three-core/stage.ts+++ b/skills/anidoodle/engine/src/three-core/stage.ts@@ -30,7 +30,7 @@ export type StageOpts = {export type Stage = { renderer: THREE.WebGLRenderer; w: number; h: number; ss: number };const KEY = "three:stage";-/** The film's one WebGL renderer, sized to the frame at env.scale (x ss). Built on first use, then kept. */+/** The film's one WebGL renderer, sized to the frame at env.scale (x ss). Built on first use, then kept. draw3d sets its tone mapping and exposure on every call. */export const stage = (env: Env, opts: StageOpts = {}): Stage => {const ss = Math.max(1, Math.min(3, Math.round(opts.ss ?? 2)));const w = Math.round(env.W * env.scale * ss), h = Math.round(env.H * env.scale * ss);@@ -72,6 +72,10 @@ export const memo = <T>(env: Env, key: string, build: (env: Env) => T): T => {*/export const draw3d = (ctx: Ctx, env: Env, scene: THREE.Scene, camera: THREE.Camera, opts: StageOpts & { clear?: string | null } = {}) => {const st = stage(env, opts), { renderer } = st;+ // the renderer is shared by every shot of this size, but its look belongs to THIS shot: set it on+ // every call, or a shot inherits the exposure of whichever shot happened to build the renderer+ renderer.toneMapping = opts.toneMapping ?? THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = opts.exposure ?? 1;if ((camera as THREE.PerspectiveCamera).isPerspectiveCamera) { const c = camera as THREE.PerspectiveCamera; c.aspect = env.W / env.H; c.updateProjectionMatrix(); }scene.updateMatrixWorld(true);if (renderer.shadowMap.enabled) renderer.shadowMap.needsUpdate = true;diff --git a/skills/anidoodle/engine/src/three-core/time.ts b/skills/anidoodle/engine/src/three-core/time.tsindex a441e2f..94f5d80 100644--- a/skills/anidoodle/engine/src/three-core/time.ts+++ b/skills/anidoodle/engine/src/three-core/time.ts@@ -45,6 +45,9 @@ export const tween = (f: number, a: number, b: number, e: Ease = ease.inOutCubic* after a turn). Closed form, so frame 300 never needs frames 0-299. freq in Hz, damping 0-1.*/export const spring = (f: number, at: number, fps: number, freq = 2.2, damping = 0.28) => {+ // a 0 fps or a 0 Hz spring has no time to ring in: it would return NaN, and a NaN position draws nothing+ if (!(fps > 0) || !Number.isFinite(fps)) throw new Error(`spring: fps must be a positive number of frames per second (got ${fps})`);+ if (!(freq > 0) || !Number.isFinite(freq)) throw new Error(`spring: freq must be a positive number of Hz (got ${freq})`);if (f < at) return 0;const t = (f - at) / fps, w = 2 * Math.PI * freq, z = Math.min(0.999, Math.max(0, damping)), wd = w * Math.sqrt(1 - z * z);return Math.exp(-z * w * t) * (Math.cos(wd * t) + ((z * w) / wd) * Math.sin(wd * t));@@ -63,6 +66,7 @@ export const beatFrames = (bpm: number, fps: number) => (60 * fps) / bpm;* use the real frame directly.*/export const storyClock = (anchors: [story: number, real: number][]) => {+ if (!anchors.length) throw new Error("storyClock: give at least one [storyFrame, realFrame] anchor");const a = [...anchors].sort((x, y) => x[0] - y[0]);for (let i = 1; i < a.length; i++) if (!(a[i][0] > a[i - 1][0] && a[i][1] > a[i - 1][1])) throw new Error(`storyClock: anchors must increase in both columns (at ${a[i - 1]} -> ${a[i]})`);const map = (x: number, from: 0 | 1, to: 0 | 1) => {diff --git a/skills/anidoodle/engine/src/three-core/transitions.ts b/skills/anidoodle/engine/src/three-core/transitions.tsindex 66a7ea9..27494f9 100644--- a/skills/anidoodle/engine/src/three-core/transitions.ts+++ b/skills/anidoodle/engine/src/three-core/transitions.ts@@ -18,6 +18,7 @@// test/threeTransitions.test.ts.import type { Ctx, Env, Layer } from "../canvas-core/core";import { fractal } from "../canvas-core/core";+import * as THREE from "three";import { ease, type Ease } from "./time";export type DrawInto = (ctx: Ctx, env: Env) => void;@@ -38,8 +39,11 @@ export const wipe = (dir: Dir = "right", o: Base & { feather?: number } = {}): T/** an iris opening from (x, y), given as 0-1 of the frame; feather in frame pixels */export const radialWipe = (o: Base & { x?: number; y?: number; feather?: number } = {}): TransitionKind => ({ kind: "radial", x: o.x ?? 0.5, y: o.y ?? 0.5, feather: o.feather ?? 80, ease: o.ease });/** an ink-blot dissolve from seeded noise; scale = blot size in frame pixels; ink = rim colour (null for none) */-export const noiseWipe = (seed = 1, o: Base & { scale?: number; soft?: number; ink?: string | null; inkWidth?: number } = {}): TransitionKind =>- ({ kind: "noise", seed, scale: o.scale ?? 360, soft: o.soft ?? 0.02, ink: o.ink === undefined ? "#1b1622" : o.ink, inkWidth: o.inkWidth ?? 0.014, ease: o.ease ?? ease.inOutSine });+export const noiseWipe = (seed = 1, o: Base & { scale?: number; soft?: number; ink?: string | null; inkWidth?: number } = {}): TransitionKind => {+ const ink = o.ink === undefined ? "#1b1622" : o.ink;+ if (ink) inkRGB(ink); // a bad colour fails here, where the wipe is written, not mid-render+ return { kind: "noise", seed, scale: o.scale ?? 360, soft: o.soft ?? 0.02, ink, inkWidth: o.inkWidth ?? 0.014, ease: o.ease ?? ease.inOutSine };+};/** B pushes A out: both move in `dir` */export const slide = (dir: Dir = "left", o: Base = {}): TransitionKind => ({ kind: "slide", dir, ease: o.ease });/** fly through A onto B; amount = how far A grows (4 = to four times its size); A is gone by 52 % so the middle never reads as a double exposure */@@ -116,7 +120,21 @@ const putMask = (env: Env, slot: string, w: number, h: number, a: Uint8ClampedArfor (let p = 0; p < a.length; p++) { const q = p * 4; img.data[q] = rgb[0]; img.data[q + 1] = rgb[1]; img.data[q + 2] = rgb[2]; img.data[q + 3] = a[p]; }l.ctx.putImageData(img, 0, 0); return l;};-const hex = (s: string): [number, number, number] => { const m = s.replace("#", ""); const v = m.length === 3 ? m.split("").map((c) => c + c).join("") : m; return [0, 2, 4].map((i) => parseInt(v.slice(i, i + 2), 16)) as [number, number, number]; };+/**+ * The rim colour as 0-255 sRGB. Hex is read exactly; any other CSS colour (a name, rgb(), hsl()) goes+ * through three's own CSS parser. Anything else throws: a hex-only parser read "red" as a dark teal+ * and drew it without a word.+ */+export const inkRGB = (s: string): [number, number, number] => {+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(s.trim());+ if (m) { const v = m[1].length === 3 ? m[1].split("").map((c) => c + c).join("") : m[1]; return [0, 2, 4].map((i) => parseInt(v.slice(i, i + 2), 16)) as [number, number, number]; }+ const c = new THREE.Color(); c.r = -1; // three leaves an unknown colour untouched, so -1 marks "not parsed"+ const t = typeof s === "string" ? s.trim() : "";+ // only a CSS name, rgb() or hsl() reaches three's parser (so it never prints its own warning)+ if (/^(rgb|hsl)a?\(/i.test(t) || Object.hasOwn(THREE.Color.NAMES, t.toLowerCase())) c.setStyle(t);+ if (c.r === -1) throw new Error(`noiseWipe: ink "${s}" is not a colour (use hex like "#1b1622", a CSS name, rgb() or hsl())`);+ const h = c.getHex(); return [(h >> 16) & 255, (h >> 8) & 255, h & 255];+};/*** Draw the frame of a transition at progress t (0-1) from what drawA and drawB paint. Each draw@@ -154,7 +172,7 @@ export const transition = (ctx: Ctx, env: Env, t: number, kind: TransitionKind,const M = putMask(env, "m", mw, mh, m.alpha);B.ctx.save(); B.ctx.globalCompositeOperation = "destination-in"; B.ctx.imageSmoothingEnabled = true; B.ctx.imageSmoothingQuality = "high"; B.ctx.drawImage(src(M), 0, 0, mw * cell, mh * cell); B.ctx.restore();ctx.drawImage(src(A), 0, 0); ctx.drawImage(src(B), 0, 0);- if (m.ink && kind.ink) { const I = putMask(env, "i", mw, mh, m.ink, hex(kind.ink)); ctx.drawImage(src(I), 0, 0, mw * cell, mh * cell); }+ if (m.ink && kind.ink) { const I = putMask(env, "i", mw, mh, m.ink, inkRGB(kind.ink)); ctx.drawImage(src(I), 0, 0, mw * cell, mh * cell); }break;}}diff --git a/skills/anidoodle/engine/test/board.test.ts b/skills/anidoodle/engine/test/board.test.tsnew file mode 100644index 0000000..87086b3--- /dev/null+++ b/skills/anidoodle/engine/test/board.test.ts@@ -0,0 +1,38 @@+// BOARD TESTS. A brief and storyboard are checked before anything is drawn: rows that carry nothing+// (a slide deck), a logo with no bridge, an abstract promise, jokes on the audience's own tool, counts+// that change for no reason, endings that end twice, events with no hosts or sponsors, texture text in+// real words. The red fixture is the first board of a brand launch film; the green one its fixed board.+// @ts-ignore: a plain ES module shared with the tools+import { checkBoard, BOARD_TEMPLATE } from "../tools/boardrules.mjs";+import good from "./fixtures/board/good.json";+import slides from "./fixtures/board/slides.json";++export const name = "board";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const g = checkBoard(good);+ ok(g.status === "PASS", `the fixed board passes (${g.problems.map((p: { why: string }) => p.why).join("; ") || "no problems"})`);+ ok(g.table[1].carry === "the three dots" && g.seconds === 22, "the board prints each beat's carry and the total length");+ const r = checkBoard(slides), has = (re: RegExp) => r.problems.some((p: { where: string; why: string }) => re.test(`${p.where}: ${p.why}`));+ ok(r.status === "FAIL", "RED: the slide-deck board fails");+ ok(has(/carry nothing in from the row before/), "RED: two rows in a row with nothing carried are a slide cut");+ ok(has(/no bridge/) && has(/built from/), "RED: a logo that appears with no bridge and is built from nothing on screen");+ ok(has(/abstract word \(Multiply\)/) && has(/`does`/), "RED: a brand tagline as the promise, with nothing the viewer does or leaves with");+ ok(has(/brief.message/) && has(/brief.premise/), "RED: no message and no comic premise");+ ok(has(/people.hosts/) && has(/people.sponsors/), "RED: an event film with no hosts or sponsors listed");+ ok(has(/from 3 to 2 with no reason/), "RED: an actor's count changes with no reason");+ ok(has(/texture text .* real words/), "RED: filler text written in real words");+ ok(has(/repeats "400\+ marketers"/), "RED: a line said twice");+ ok(has(/returns to the card after the stinger/) && has(/stinger with nothing to answer/), "RED: card, stinger, card again: the film ends twice");+ ok(has(/never on the tool the audience relies on/) && has(/who gets it/), "RED: a joke on the audience's own tool, with no one named who gets it");+ ok(has(/spans 1 comic device/) && has(/no twist/), "RED: a pitch batch of one device, observations with no twist");+ ok(has(/mystery speaker/) && has(/talk title/), "RED: a mystery speaker and a long talk title in the program");+ ok(has(/brief.reference/), "RED: a brand film with no reference film");+ ok(checkBoard(BOARD_TEMPLATE).problems.some((p: { why: string }) => /TODO/.test(p.why)), "the starting template fails until its TODOs are filled");+ ok(checkBoard({ brief: good.brief, rows: [] }).status === "FAIL", "NEGATIVE: an empty board is never a pass");+ const long = { ...good, rows: good.rows.map((x: object) => ({ ...x, seconds: 20 })) };+ ok(checkBoard(long).problems.some((p: { where: string }) => p.where === "length"), "RED: rows that add up past length.max fail");+ const sameJokes = { ...good, jokes: good.jokes.map((j: object) => ({ ...j, device: "verbal" })) };+ ok(checkBoard(sameJokes).problems.some((p: { why: string }) => /use one device/.test(p.why)), "RED: every joke in one format fails");+ const noVoice = { ...good, brief: { ...good.brief, voices: {} } };+ ok(checkBoard(noVoice).problems.some((p: { why: string }) => /visual voice/.test(p.why)), "RED: a character's line with no registered visual voice fails");+};diff --git a/skills/anidoodle/engine/test/brand.test.ts b/skills/anidoodle/engine/test/brand.test.tsnew file mode 100644index 0000000..4bef594--- /dev/null+++ b/skills/anidoodle/engine/test/brand.test.ts@@ -0,0 +1,135 @@+// BRAND TESTS. The brand import reads SVG exports into exact paths and measures what the marks can do+// in motion; the inventory makes "is X in the design file?" a search; the kit refuses to squash a brand+// mark. Held to known answers, with the failing cases (red fixtures) beside the passing ones.+// @ts-ignore: plain ES modules shared with the tools+import { parsePath, flatten, bboxOf, importSvg, symmetry, repeats, logoMetrics, monochrome, toSvg, parseTransform, apply, brandModule, equaliseLogos, inkArea } from "../tools/brandsvg.mjs";+// @ts-ignore+import { framesFromFigma, framesFromFiles, renderInventory, parseInventory, checkInventory, findInInventory, motionTokens } from "../tools/brandinv.mjs";+import { drawEl, distortion, placeEl, type BrandElement } from "../src/canvas-core/brandKit";++const near = (a: number, b: number, e = 0.01) => Math.abs(a - b) <= e;+// the hourglass: two dots joined by an S-curve neck, the same after a half turn (built from two quarter circles and a bar)+const HOURGLASS = `<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">+<circle cx="50" cy="50" r="40" fill="#FFD900"/><circle cx="150" cy="150" r="40" fill="#FFD900"/><path d="M60 70 C100 70 100 110 140 110 L140 130 C100 130 100 90 60 90 Z" fill="#FFD900"/></svg>`;+const ELL = `<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"><path d="M0 0H20V80H100V100H0Z" fill="#111"/></svg>`;+const FRIEZE = `<svg width="400" height="50" xmlns="http://www.w3.org/2000/svg">${[0, 1, 2, 3].map((i) => `<rect x="${i * 100}" y="0" width="60" height="50" fill="${i % 2 ? "#ff00aa" : "#ff6a00"}"/>`).join("")}</svg>`;++export const name = "brand";+export const run = (ok: (cond: boolean, label: string) => void) => {+ // ---- path data: relatives, shorthands and compact arc flags resolve to absolute commands+ const cmds = parsePath("m10 10 h20 v20 h-20 z M0 0 l5 5 s 5 5 10 0 a5 5 0 015 5");+ ok(cmds[0].join(",") === "M,10,10" && cmds[1].join(",") === "L,30,10" && cmds[2].join(",") === "L,30,30" && cmds[3].join(",") === "L,10,30", "relative m h v resolve to absolute points");+ ok(cmds.find((c: unknown[]) => c[0] === "A")?.join(",") === "A,5,5,0,0,1,20,10", "a compact arc 'a5 5 0 015 5' reads its flags as single digits");+ let threw = ""; try { parsePath("M0 0 L x"); } catch (e) { threw = String(e); }+ ok(/bad path data/.test(threw), "NEGATIVE: unreadable path data throws with where it broke");+ const circle = bboxOf(flatten("M10 50 A40 40 0 1 0 90 50 A40 40 0 1 0 10 50 Z"));+ ok(near(circle[0], 10, 0.2) && near(circle[2], 80, 0.5) && near(circle[3], 80, 0.5), `an arc circle's box is its diameter (${circle.map((v: number) => v.toFixed(1))})`);+ ok(apply(parseTransform("translate(10 20) scale(2)"), 1, 1).join(",") === "12,22", "transforms compose left to right as SVG does");++ // ---- the import: viewBox, classes, <use>, gradients in object-box units, warnings+ const svg = `<svg width="200" height="100" viewBox="0 0 400 200" xmlns="http://www.w3.org/2000/svg"><style>.a{fill:#FFDE59}</style>+<defs><linearGradient id="g"><stop offset="0" stop-color="red"/><stop offset="100%" stop-color="#00f" stop-opacity=".5"/></linearGradient><path id="dot" d="M0 0h10v10H0z"/></defs>+<g transform="translate(10 0)"><rect class="a" width="100" height="50"/><circle cx="200" cy="100" r="40" fill="url(#g)"/><use href="#dot" x="300" y="20"/></g></svg>`;+ const el = importSvg(svg);+ ok(el.w === 200 && el.h === 100 && el.parts.length === 3, `three parts in a 200x100 element (${el.parts.length})`);+ ok(el.parts[0].fill.c === "#ffde59" && el.parts[0].bb.join(",") === "5,0,50,25", `a <style> class fills the rect, and the viewBox halves its box (${el.parts[0].bb})`);+ ok(el.parts[0].d.startsWith("M0 0H100") && el.parts[0].m.join(",") === "0.5,0,0,0.5,5,0", "the path is kept as exported; the transform is a matrix beside it, never baked into new path data");+ const g = el.parts[1].fill;+ ok(g.type === "lin" && g.stops[0][1] === "#ff0000" && g.stops[1][2] === 0.5 && g.m.join(",") === "80,0,0,80,160,60", "an object-box gradient is mapped onto the shape's own box, stops and alpha kept");+ ok(el.parts[2].bb.join(",") === "155,10,5,5", "<use> places its target at x, y");+ ok(!el.warnings.length, "a clean export raises no warnings");+ const masked = importSvg(`<svg width="10" height="10"><mask id="m"><rect width="5" height="5" fill="#888"/></mask><rect width="10" height="10" mask="url(#m)"/><text font-family="Brand Grotesk">Hi</text><image href="x.png"/></svg>`);+ ok(masked.warnings.some((w: string) => /mask/.test(w)) && masked.warnings.some((w: string) => /live text/.test(w)) && masked.warnings.some((w: string) => /raster image/.test(w)), "RED: a mask, live text and an embedded image are each named, never silently dropped");+ const hard = importSvg(`<svg width="10" height="10"><mask id="m"><rect width="5" height="10" fill="#fff"/></mask><rect width="10" height="10" mask="url(#m)"/></svg>`);+ ok(!hard.warnings.length && hard.parts[0].clip?.paths[0].d.startsWith("M0 0H5"), "a hard white mask is imported as a clip, exactly");+ ok(masked.fonts.includes("Brand Grotesk"), "the live text's font is listed so it can be asked for early");+ const clipped = importSvg(`<svg width="10" height="10"><clipPath id="c"><circle cx="5" cy="5" r="5"/></clipPath><rect width="10" height="10" clip-path="url(#c)" fill="#000"/></svg>`);+ ok(clipped.parts[0].clip?.paths.length === 1, "a clip-path is carried onto the part, not dropped");+ let notSvg = ""; try { importSvg("<html></html>"); } catch (e) { notSvg = String(e); }+ ok(/no <svg>/.test(notSvg), "NEGATIVE: a file with no <svg> is refused");++ // ---- what the marks can do in motion+ const hg = importSvg(HOURGLASS), ell = importSvg(ELL);+ ok(symmetry(hg).rotational === 2, `the hourglass is the same after a half turn, so it can land from a spin without a jump (${JSON.stringify(symmetry(hg))})`);+ ok(symmetry(ell).rotational === 1 && !symmetry(ell).mirrorX, "NEGATIVE: an L shape has no rotational or mirror symmetry");+ const fr = repeats(importSvg(FRIEZE));+ ok(fr.some((r: { what: string; copies: number; step: number[]; seamless: boolean }) => r.what === "shape" && r.copies === 4 && r.step[0] === 100 && r.seamless), `the frieze's marks repeat every 100 units and tile without a seam (${JSON.stringify(fr)})`);+ ok(fr.some((r: { what: string; step: number[] }) => r.what === "pattern" && r.step[0] === 200), "its two-colour pattern repeats every 200 units");+ ok(!repeats(ell).length, "NEGATIVE: a single L shape has no repeat");++ // ---- logos: ink, overlapping outlines (check with the owner), a one-colour version+ const two = importSvg(`<svg width="100" height="20"><rect x="0" width="40" height="20"/><rect x="60" width="40" height="20"/></svg>`);+ const shared = importSvg(`<svg width="100" height="20"><rect x="0" width="60" height="20"/><rect x="40" width="60" height="20"/></svg>`);+ ok(near(logoMetrics(two).ink, 1600) && logoMetrics(two).overlaps === 0, `ink is the filled area (${logoMetrics(two).ink})`);+ ok(logoMetrics(shared).overlaps === 1, "RED: two outlines that cross are flagged 'check with the owner' (a wordmark that shares strokes may be the design)");+ ok(near(inkArea(flatten("M0 0H10V10H0Z M2 2V8H8V2Z")), 64), "a counter-wound hole is subtracted from the ink");+ const white = monochrome(hg, "#ffffff");+ ok(white.parts.every((p: { fill: { c: string } }) => p.fill.c === "#ffffff") && /viewBox="10 10 180 180"/.test(toSvg(white, { tight: true })), "a mono logo for a dark ground, written with a viewBox trimmed to its ink");+ const eq = equaliseLogos([{ name: "a", h: 10, ink: 100 }, { name: "b", h: 10, ink: 25 }, { name: "c", h: 10, ink: 50 }], 80);+ ok(eq[1].height > eq[2].height && eq[2].height === 80 && eq[0].height < 80, `a light logo is drawn taller and a heavy one shorter so they read equally (${eq.map((l: { height: number }) => l.height)})`);++ // ---- the brand module a film imports+ const mod = brandModule({ elements: { mark: hg }, palette: [{ hex: "#ffd900", share: 1 }], fonts: [], motion: {} }, "./brandKit");+ ok(/export const BRAND/.test(mod) && /export const brandMeta = \{"colors":\["#ffd900"\],"elements":\["mark"\]\}/.test(mod), "the module exports BRAND and brandMeta (colours and element names for meta.brand)");+ ok(/export const brandMotion = \{"brandColors":\["#ffd900"\]\}/.test(mod), "and brandMotion, the brand colours in the shape meta.motion reads (layerscan's translucent check)");++ // ---- inventory: every frame listed, find answers from all of it, check holds the read marks+ const file = { document: { children: [+ { name: "Brand", children: [{ id: "1:2", name: "Logo lockup", type: "FRAME", absoluteBoundingBox: { width: 1197, height: 496 }, children: [] }] },+ { name: "Social", children: [{ id: "4:7", name: "Social Media partners", type: "FRAME", absoluteBoundingBox: { width: 1080, height: 1080 }, children: [{ type: "TEXT", characters: "Thank you to our sponsors" }],+ interactions: [{ actions: [{ transition: { type: "SMART_ANIMATE", duration: 0.5, easing: { type: "CUSTOM_CUBIC_BEZIER", easingFunctionCubicBezier: { x1: 0, y1: 0, x2: 0.58, y2: 1 } } } }] }] }] },+ ] } };+ const inv = framesFromFigma(file);+ ok(inv.frames.length === 2 && inv.frames[1].text.includes("sponsors"), "every top-level frame on every page is listed, with the words on it");+ const tok = motionTokens(inv.motion);+ ok(tok.socialMediaPartners?.ms === 500 && tok.socialMediaPartners.ease.join(",") === "0,0,0.58,1", `the file's own transition timing becomes a named motion token in motionKit's shape (${JSON.stringify(tok)})`);+ ok(motionTokens([{ ms: 300, easing: "spring(mass 1, stiffness 100, damping 15)", from: ["x"] }])._springs.length === 1, "NEGATIVE: a spring easing is set aside for a person, never turned into a guessed curve");+ const md = renderInventory("test", inv.frames), rows = parseInventory(md);+ ok(rows.length === 2 && rows[0].mark === "[ ]", "the inventory page has one unticked read box per frame");+ ok(findInInventory(rows, "sponsor").length === 1 && findInInventory(rows, "partners").length === 1, "find matches a frame by its words ('sponsor') as well as its name ('partners')");+ ok(findInInventory(rows, "speaker photos").length === 0, "NEGATIVE: a word in no frame finds nothing, and the tool says how many frames it searched");+ const red = checkInventory(rows);+ ok(red.status === "FAIL" && red.unread.length === 2, "RED: check fails while frames are unread");+ const marked = parseInventory(renderInventory("test", inv.frames, new Map([["1:2", "[x]"], ["4:7", "[-]"]])));+ ok(checkInventory(marked).status === "FAIL" && checkInventory(marked).bareSkips.length === 1, "RED: a skip with no reason fails");+ const green = parseInventory(renderInventory("test", inv.frames, new Map([["1:2", "[x]"], ["4:7", "[-] social crops of the lockup, same elements"]])));+ ok(checkInventory(green).status === "PASS", "every frame read or skipped with a reason passes");+ ok(checkInventory([]).status === "FAIL", "NEGATIVE: an empty inventory is never a pass");+ // M8: a mark that is not exactly [x] or "[-] reason" was never read, so it fails+ for (const bad of ["[]", "[ ]", "[?]", "[o]", "[-]reason"]) {+ const rowsBad = [{ mark: "[x]", page: "p", name: "a", id: "1", words: "" }, { mark: bad, page: "p", name: "b", id: "2", words: "" }];+ ok(checkInventory(rowsBad).status === "FAIL", `RED (M8): a row marked ${JSON.stringify(bad)} is not read and fails the check`);+ }+ ok(checkInventory([{ mark: "[X]", page: "p", name: "a", id: "1", words: "" }]).status === "PASS", "GREEN (M8): a capital [X] counts as read");+ ok(framesFromFiles(["b.svg", "a.png", ".DS_Store"]).map((f: { name: string }) => f.name).join(",") === "a,b", "a folder of exports is an inventory too, one row per file");++ // ---- the kit: brand marks are moved, never squashed+ (globalThis as unknown as { Path2D: unknown }).Path2D = class { constructor(public d?: string) {} addPath() {} };+ const calls: string[] = [];+ const ctx = (m: { a: number; b: number; c: number; d: number; e?: number; f?: number }) => ({ globalAlpha: 0.5, getTransform: () => m, save() {}, restore() {}, transform() {}, translate() {}, rotate() {}, scale() {}, fill(this: { globalAlpha: number }) { calls.push(`fill@${this.globalAlpha}`); }, set fillStyle(_v: unknown) {} }) as unknown as CanvasRenderingContext2D;+ const mark: BrandElement = { w: 10, h: 10, parts: [{ d: "M0 0H10V10H0Z", fill: { type: "solid", c: "#ffd900" }, rule: "nonzero", op: 1, bb: [0, 0, 10, 10] }] };+ let squash = ""; try { drawEl(ctx({ a: 1.3, b: 0, c: 0, d: 0.8 }), mark, { name: "dot" }); } catch (e) { squash = String(e); }+ ok(/non-uniform scale/.test(squash) && /'dot'/.test(squash) && /allowSquash/.test(squash), "RED: drawing a brand mark squashed throws, naming the element and the way out");+ let skew = ""; try { drawEl(ctx({ a: 1, b: 0, c: 0.4, d: 1 }), mark); } catch (e) { skew = String(e); }+ ok(/skew/.test(skew), "RED: a skewed brand mark throws");+ let allowed = true; try { drawEl(ctx({ a: 1.3, b: 0, c: 0, d: 0.8 }), mark, { allowSquash: "crushed by the falling chat window" }); } catch { allowed = false; }+ ok(allowed, "a squash that names its gag is drawn");+ const r = Math.PI / 5, rot = { a: 2 * Math.cos(r), b: 2 * Math.sin(r), c: -2 * Math.sin(r), d: 2 * Math.cos(r) };+ ok(distortion(rot).squash < 1e-9 && Math.abs(distortion(rot).skew) < 1e-9, "a rotation with an even scale is not a distortion");+ calls.length = 0; drawEl(ctx(rot), mark, { alpha: 0.5 });+ ok(calls[0] === "[email protected]", `the caller's alpha is multiplied, never reset (a fade of a brand group keeps working) (${calls[0]})`);+ // the frame probe sees brand marks (layerscan's shape-over-a-face check reads these boxes)+ const recs: { kind: string; label: string; x0: number; y0: number; x1: number; y1: number }[] = [];+ (globalThis as unknown as { __ANIDOODLE_PROBE__?: unknown }).__ANIDOODLE_PROBE__ = (r: (typeof recs)[number]) => recs.push(r);+ drawEl(ctx({ a: 2, b: 0, c: 0, d: 2, e: 100, f: 50 } as never), mark, { name: "dot" });+ ok(recs.length === 1 && recs[0].kind === "box" && recs[0].label === "brand:dot" && recs[0].x0 === 100 && recs[0].y0 === 50 && recs[0].x1 === 120 && recs[0].y1 === 70, `drawEl reports the mark's on-screen box to the frame probe (${JSON.stringify(recs[0])})`);+ recs.length = 0; drawEl(ctx({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } as never), mark, { name: "dot", env: { root: false } as never });+ ok(recs.length === 0, "drawn on a plate (env not the frame's root) it reports nothing, as probeRect does");+ recs.length = 0; drawEl(ctx({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } as never), mark, { probe: false });+ ok(recs.length === 0, "probe: false keeps a mark out of the probe");+ delete (globalThis as unknown as { __ANIDOODLE_PROBE__?: unknown }).__ANIDOODLE_PROBE__;+ recs.length = 0; drawEl(ctx({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 } as never), mark);+ ok(recs.length === 0, "with no probe installed nothing is reported (no cost)");+ let placed = true; try { placeEl(ctx({ a: 1, b: 0, c: 0, d: 1 }), mark, { x: 50, y: 50, h: 40, rot: 1 }); } catch { placed = false; }+ ok(placed, "placeEl places by centre and height, uniform by construction");+};diff --git a/skills/anidoodle/engine/test/cleanChatDock.test.ts b/skills/anidoodle/engine/test/cleanChatDock.test.tsnew file mode 100644index 0000000..ef9e8ce--- /dev/null+++ b/skills/anidoodle/engine/test/cleanChatDock.test.ts@@ -0,0 +1,37 @@+// THE CLEAN LOOK TAKES CHAT ASKS (shipped in 0.9.6: the answer card opens as an iris). A trial film failed+// ship on its chat path, and 0.10's first fix made the clean preset refuse chat asks: a regression. The chat+// path is rebuilt in the clean register instead (references/workflows/launch-video-kit.md, Looks):+// the hook's composer glides down whole and IS the dock: it never shrinks, on the move (64 % of a sparse+// frame replaced in 0.1 s, a slide cut) or after it lands (a fresh critic, cc1-1: a shrink once it had+// nearly landed read as a second move), and Ask is pressed only once it has landed, inside the window;+// the thread's view ends above the dock;+// the window stays opaque while the camera leans on the answer card (no see-through brand ink).+// launchExampleCleanChat is the worked example, 16:9 and 9:16; ship passes it on both.+// node tools/test.mjs cleanChatDock+import { makeLaunchFilm, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import { launchExampleCleanChat } from "../src/canvas-core/launchExampleCleanChat";+import type { Film } from "../src/canvas-core/film";++export const name = "the clean look's chat ask";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const plate: Film = { meta: { title: "plate", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 60 }, assets: { images: {} }, shots: [{ id: "p", start: 0, end: 60, draw: () => {} }] };+ let err = ""; try { makeLaunchFilm({ title: "Tally", preset: "clean", asks: [{ prompt: "draw it", plate, label: "l" }, { kind: "film", film: plate }], tagline: "t", install: ["npm i tally"], bpm: 90, score: null }); } catch (e) { err = (e as Error).message; }+ ok(err === "", `RED: a clean film with a chat ask builds (${err.slice(0, 90) || "ok"})`);+ for (const sh of ["16x9", "9x16"]) {+ const f = (launchExampleCleanChat as LaunchFilm).reshape(sh), d = (f as Partial<LaunchFilm>).grammar?.dock, T = f.timing[0];+ if (!d) { ok(false, `RED ${sh}: the clean hook exposes its dock`); continue; }+ ok(d.shrink[1] === d.shrink[0], `RED ${sh}: the composer glides whole (frames ${d.move.join("-")}) and never scales after it lands (${d.shrink.join("-")})`);+ ok(T.down >= d.move[1], `${sh}: Ask goes down at ${T.down}, once the composer has landed at ${d.move[1]}`);+ // (the hook is also the dock all film long, so it is set at the hook's smallest size, never larger: at 68 px+ // on 16:9 it stood 296 px tall and left the answer card a thumbnail, cc3-1, and three beats in a row+ // settled into one layout, motionscan repeat)+ ok(d.heroPx === (sh === "9x16" ? 64 : 56), `RED ${sh}: the clean hook is set at the hook's smallest size (${d.heroPx} px)`);+ ok(Math.abs(d.dockPx - d.heroPx) < 1e-6, `RED ${sh}: the dock is the hook's composer at the hook's own size (${d.heroPx} px, docked ${d.dockPx.toFixed(1)} px)`);+ const c = d.composer, w = d.window;+ ok(c.x >= w.x && c.x + c.w <= w.x + w.w && c.y >= w.y && c.y + c.h <= w.y + w.h, `${sh}: the docked composer sits inside the chat window`);+ // (on a phone the hook creeps 5 % in the clean look: its composer is narrower, so its typing alone changed+ // too little of the tall frame, and with the 4 % creep frames 13 to 46 of 9:16 were dead air to the gate)+ if (sh === "9x16") ok(d.creep >= 1.05, `RED ${sh}: the clean hook creeps 5 % (${((d.creep - 1) * 100).toFixed(0)} %)`);+ ok(d.viewBottom <= c.y, `${sh}: the thread's view ends (${Math.round(d.viewBottom)}) above the dock (${Math.round(c.y)})`);+ }+};diff --git a/skills/anidoodle/engine/test/cleanDropPace.test.ts b/skills/anidoodle/engine/test/cleanDropPace.test.tsnew file mode 100644index 0000000..1a74bfb--- /dev/null+++ b/skills/anidoodle/engine/test/cleanDropPace.test.ts@@ -0,0 +1,30 @@+// THE CLEAN DROP KEEPS TO THE BRAND'S TEMPERAMENT. A chat ask's ink drop flies from the button to its answer+// card in 14 frames. In the clean look the drop is one solid streak, which motionscan follows as a coherent+// thing, and on a phone frame, with the hook's composer docked at its own size, the flight was long enough+// that the streak moved at 45 px a frame where a snappy brand allows 36 (launchExampleCleanChat 9:16, 2.8 s).+// The clean drop's flight now takes the frames its distance needs; the drawn look's trail is unchanged.+// node tools/test.mjs cleanDropPace+import { launchExampleCleanChat } from "../src/canvas-core/launchExampleCleanChat";+import { launchExample } from "../src/canvas-core/launchExample";+import { launchExampleBrand } from "../src/canvas-core/launchExampleBrand";+import type { LaunchFilm } from "../src/canvas-core/launchTemplate";+import { TEMPERAMENTS } from "../src/canvas-core/motionKit";+import { speedCeiling } from "../src/canvas-core/seams";++export const name = "the clean drop keeps to the brand's temperament";+export const run = (ok: (cond: boolean, label: string) => void) => {+ for (const sh of ["16x9", "9x16"]) {+ const r = launchExampleCleanChat.reshape(sh) as LaunchFilm, cap = 0.95 * TEMPERAMENTS.snappy.maxSpeed * speedCeiling(r.meta.W, 30);+ for (const d of r.grammar?.drops ?? []) ok(d.peak <= cap, `RED ${sh}: ask ${d.i}'s drop tops out at ${d.peak.toFixed(1)} px a frame, under ${cap.toFixed(1)} (${d.flight[1] - d.flight[0]} frames)`);+ if (!r.grammar?.drops?.length) ok(false, `${sh}: the film exposes its drops`);+ }+ // THE LANDING. A lively or calm brand's drop takes longer to fly, and an in-out flight's slow last third then+ // crawled for half a second over a dark page (launchExampleBrand, frames 203-233 of 16:9: dead air to the+ // gate). The clean drop keeps a share of its speed to the end and lands as a hit the iris takes over.+ for (const [nm, film] of [["launchExampleCleanChat", launchExampleCleanChat], ["launchExampleBrand", launchExampleBrand]] as const) for (const sh of ["16x9", "9x16"]) {+ const r = (film as LaunchFilm).reshape(sh) as LaunchFilm;+ for (const d of r.grammar?.drops ?? []) ok(d.landing >= 0.3 * d.peak, `RED ${nm} ${sh}: ask ${d.i}'s drop still moves at ${d.landing.toFixed(1)} px a frame as it lands (at least 30 % of its ${d.peak.toFixed(1)} peak)`);+ }+ const w = (launchExample as LaunchFilm).reshape("9x16") as LaunchFilm;+ ok((w.grammar?.drops ?? []).every((d) => d.flight[1] - d.flight[0] === 14), `the drawn example's drops keep their 14 frames`);+};diff --git a/skills/anidoodle/engine/test/cleanThreadRoom.test.ts b/skills/anidoodle/engine/test/cleanThreadRoom.test.tsnew file mode 100644index 0000000..bc69c70--- /dev/null+++ b/skills/anidoodle/engine/test/cleanThreadRoom.test.ts@@ -0,0 +1,16 @@+// THE FIRST ANSWER FITS UNDER ITS QUESTION. In the clean look the hook's composer docks at its own size, so it+// stands taller than the laid-out one and the thread's view ends higher. On a phone the answer card shrank to+// fit; on 16:9 it kept its size, so the thread scrolled the question bubble up under the header rule and off,+// and still clipped the card's foot (a fresh critic, cc2-1: "the answer opens with no question above it").+// The card now shrinks to the view on every shape, so the first question and its answer fit with no scroll.+// node tools/test.mjs cleanThreadRoom+import { launchExampleCleanChat } from "../src/canvas-core/launchExampleCleanChat";+import type { LaunchFilm } from "../src/canvas-core/launchTemplate";++export const name = "the first answer fits under its question";+export const run = (ok: (cond: boolean, label: string) => void) => {+ for (const sh of ["16x9", "9x16"]) {+ const g = (launchExampleCleanChat.reshape(sh) as LaunchFilm).grammar, q = g?.scrolls.find((x) => x.i === 0);+ ok(!!q && q.d <= 0.5, `RED ${sh}: the first question and its answer fit the thread's view with no scroll (scrolls ${q?.d.toFixed(0)} px)`);+ }+};diff --git a/skills/anidoodle/engine/test/counterFlash60.test.ts b/skills/anidoodle/engine/test/counterFlash60.test.tsnew file mode 100644index 0000000..0c0643b--- /dev/null+++ b/skills/anidoodle/engine/test/counterFlash60.test.ts@@ -0,0 +1,24 @@+// A COUNTER STEP IS AN ANIMATION AT ANY FRAME RATE. A product's figure counting down (3, 2, 1, 0) shows each+// digit for about 0.1 s. framecheck skipped a text replaced in place within 3 frames as an animation step,+// counted in frames: at 30 fps that is 0.1 s, but at 60 fps a digit up 6 frames was timed as a read and+// failed ("1" up 0.1 s, reading it takes 0.7 s: the clean scaffold on 9:16, frame 126). The window is now+// 0.1 s at the film's rate. The case that stays red: a word up 0.2 s, then replaced, is still a read.+// node tools/test.mjs counterFlash60+// @ts-ignore: a plain ES module shared with the tools+import { autoCues, framesOf, readingVerdict } from "../tools/framerules.mjs";++export const name = "framerules: a counter step at 60 fps";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const T = (label: string, frame: number) => ({ kind: "text", label, frame, x0: 500, y0: 500, x1: 500 + label.length * 40, y1: 560, cut: false, alpha: 1, px: 80, family: "Inter" });+ const range = (a: number, b: number) => Array.from({ length: b - a }, (_, i) => a + i);+ // 3, 2, 1 for 6 frames each at 60 fps, then 0 held 1.5 s+ const digit = (f: number) => (f < 6 ? "3" : f < 12 ? "2" : f < 18 ? "1" : "0");+ const fr = range(0, 120), m = framesOf(fr.map((f) => T(digit(f), f)), fr), c = autoCues(m, fr, { last: 120, fps: 60 });+ ok(c.cues.length === 1 && c.cues[0].text === "0", `RED: a count-down at 60 fps times only its last figure (cues: ${c.cues.map((x: { text: string }) => x.text).join(", ")})`);+ // at 30 fps the same count in 3-frame steps is unchanged+ const d30 = (f: number) => (f < 3 ? "3" : f < 6 ? "2" : f < 9 ? "1" : "0"), fr30 = range(0, 60), c30 = autoCues(framesOf(fr30.map((f) => T(d30(f), f)), fr30), fr30, { last: 60, fps: 30 });+ ok(c30.cues.length === 1 && c30.cues[0].text === "0", "at 30 fps a count in 3-frame steps still times only its last figure");+ // stays red: a word up 0.2 s at 60 fps, then replaced in place, is a read too short+ const w = (f: number) => (f < 12 ? "Saved" : "Synced"), frw = range(0, 120), cw = autoCues(framesOf(frw.map((f) => T(w(f), f)), frw), frw, { last: 120, fps: 60 });+ ok(readingVerdict(cw, [], 60, 120).status === "FAIL" && cw.cues.some((x: { text: string }) => x.text === "Saved"), "a word up 0.2 s at 60 fps, then replaced, is still a read too short");+};diff --git a/skills/anidoodle/engine/test/cues.test.ts b/skills/anidoodle/engine/test/cues.test.tsnew file mode 100644index 0000000..ccb50a2--- /dev/null+++ b/skills/anidoodle/engine/test/cues.test.ts@@ -0,0 +1,68 @@+// CUE SHEET TESTS. Events declared once in the film, in explicit units, carried through the film's own+// time maps; the hand-mirrored timing that drifted in a brand launch film is reproduced and caught.+// node tools/test.mjs cues+import { cueSheet, cueFrame, withCues, diffCues, diffSheets, invertRemap, sheetCues, type CueDef } from "../src/canvas-core/cues";+import { timeRemap } from "../src/canvas-core/timeRemap";+import type { Film } from "../src/canvas-core/film";++export const name = "cue sheet (sound and sync cued from the film's own maps)";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const throws = (fn: () => unknown, re: RegExp, label: string) => { try { fn(); ok(false, `${label} (did not throw)`); } catch (e) { ok(re.test((e as Error).message), `${label}: ${(e as Error).message.slice(0, 90)}`); } };+ const fps = 60, meta = { fps, durationFrames: 100 * fps };+ // a brand launch film's master pace map (a hand-kept timing script): fast cold open, then 0.8x (25 % longer) from frame 303+ const master = timeRemap([{ f: 87, speed: 1.2, ramp: 12 }, { f: 303, speed: 0.8, ramp: 12 }]);+ // a slow-motion fall inside it (the dots), applied first+ const slow = timeRemap([{ f: 687, speed: 0.3, ramp: 16 }, { f: 729, speed: 1, ramp: 24 }]);++ ok(cueFrame({ frame: 120 }, fps) === 120 && cueFrame({ film: 2 }, fps) === 120, "frames and film seconds are taken as given");+ ok(cueFrame({ scene: 2 }, fps) === 120, "a scene time with no maps is film time");+ throws(() => cueFrame(4.4 as never, fps), /no units/, "RED (M14 class): a bare number has no units and is refused");+ throws(() => cueFrame({ seconds: 4.4 } as never, fps), /no units/, "an unknown unit is refused");++ // the inverse of a map is exact: the frame found shows the scene time asked for+ const f = invertRemap(master, 40 * fps);+ ok(Math.abs(master.at(f) - 40 * fps) < 1e-4, `invertRemap: film frame ${f.toFixed(3)} shows scene frame ${master.at(f).toFixed(4)}`);++ // RED FIXTURE (A8): the hand-kept timing script re-implemented the map by hand and left a section at 1:1 after the slowdown+ const defs: CueDef[] = [{ name: "x-lock", at: { scene: 40, through: [master] }, sound: "tap:impact", sync: true }, { name: "fall", at: { scene: 11.94, through: [slow, master] } }, { name: "card", at: { film: 90 } }];+ const sheet = cueSheet(meta, defs), xl = sheet.find((c) => c.name === "x-lock")!;+ const handMirror = [{ ...xl, frame: 40 * fps }, ...sheet.filter((c) => c.name !== "x-lock")]; // scene seconds copied as if they were film seconds+ ok(xl.frame > 40 * fps + 400, `the slowed film shows the x-lock at frame ${xl.frame}, not 2400: ${((xl.frame - 2400) / fps).toFixed(1)} s later than a hand copy in scene seconds`);+ const d = diffCues(handMirror, sheet);+ ok(d.length === 1 && /moved "x-lock"/.test(d[0]), `RED (A8): the hand-mirrored sheet is caught as out of date: ${d[0]}`);+ ok(diffCues(sheet, cueSheet(meta, defs)).length === 0, "the same film gives the same sheet (deterministic)");+ // M9: a changed sound, a dropped sync mark or a changed frame rate makes the old mix out of date too+ const reSound = sheet.map((c) => (c.name === "x-lock" ? { ...c, sound: "tap:thump" } : c));+ ok(diffCues(sheet, reSound).some((x) => /x-lock.*sound/.test(x)), `RED (M9): a cue whose sound changed from tap:impact to tap:thump is caught: ${diffCues(sheet, reSound)[0]}`);+ const unSync = sheet.map((c) => (c.name === "x-lock" ? { ...c, sync: undefined } : c));+ ok(diffCues(sheet, unSync).some((x) => /x-lock.*sync/.test(x)), "RED (M9): a cue that lost its sync mark is caught");+ const was = { fps: 60, durationFrames: meta.durationFrames, cues: sheet }, nowFps = { fps: 30, durationFrames: meta.durationFrames, cues: sheet };+ ok(diffSheets(was, nowFps).some((x) => /fps/.test(x)), "RED (M9): a sheet written at 60 fps is out of date for the film at 30 fps");+ ok(diffSheets(was, { ...was }).length === 0, "GREEN (M9): the same sheet has no differences");+ ok(diffSheets({ ...was, durationFrames: 10 }, was).some((x) => /frames/.test(x)), "a changed length is still caught");+ // nested maps: innermost first+ const fall = sheet.find((c) => c.name === "fall")!, byHand = Math.ceil(invertRemap(master, invertRemap(slow, 11.94 * fps)) - 1e-6);+ ok(fall.frame === byHand && fall.frame !== Math.ceil(invertRemap(slow, invertRemap(master, 11.94 * fps)) - 1e-6), `maps apply innermost first (frame ${fall.frame})`);+ ok(sheet.map((c) => c.frame).every((v, i, a) => i === 0 || a[i - 1] <= v) && Math.abs(xl.t - xl.frame / fps) < 1 / fps, "sorted by frame, each with its exact time");++ throws(() => cueSheet(meta, [{ name: "a", at: { film: 1 } }, { name: "a", at: { film: 2 } }]), /declared twice/, "duplicate names are refused");+ throws(() => cueSheet(meta, [{ name: "late", at: { film: 120 } }]), /outside the film/, "a cue past the end is refused");+ throws(() => cueSheet(meta, [{ name: "", at: { film: 1 } }]), /needs a name/, "a cue needs a name");++ // withCues: the sheet rides on the film, and sync cues become verify-export markers+ const film = { meta: { title: "t", W: 16, H: 9, fps, bpm: 120, durationFrames: meta.durationFrames, sync: [{ frame: 6, label: "old" }] }, assets: { images: {} }, shots: [] } as unknown as Film;+ const cued = withCues(film, defs);+ ok(cued.cues.length === 3 && cued.meta.sync!.length === 2 && cued.meta.sync![1].label === "x-lock" && film.meta.sync!.length === 1, "withCues adds the sheet and the sync markers without touching the original film");++ // RED (cues.mjs crash): a launch template film carries its SOUND cues as film.cues ({ frame, kind,+ // variant, label }, no name, no t). cues.mjs wrote them raw, then crashed printing c.t.toFixed, and+ // --check keyed every cue by an undefined name, so all of them collapsed into one and nothing moved.+ const launchCues = [{ frame: 4, kind: "tick", variant: "key", label: 'key "m"' }, { frame: 9, kind: "tick", variant: "key", label: 'key "m"' }, { frame: 30, kind: "press", variant: "thock", label: "Match all", sync: undefined }, { frame: 31, kind: "pop" }];+ const s = sheetCues(launchCues, 60);+ ok(s.length === 4 && s.every((c) => typeof c.t === "number" && typeof c.name === "string" && c.name.length > 0), "every exported cue has a name and a time in seconds");+ ok(new Set(s.map((c) => c.name)).size === 4, `names are unique, a repeated label numbered in frame order: ${s.map((c) => c.name).join(" | ")}`);+ ok(Math.abs(s[2].t - 0.5) < 1e-9 && s[2].sound === "press:thock" && s[3].name.startsWith("pop"), "t is frame / fps, the sound is kind:variant, a cue with no label is named by its kind");+ const moved = sheetCues(launchCues.map((c, i) => (i === 2 ? { ...c, frame: 40 } : c)), 60);+ ok(diffCues(s, moved).some((x) => /moved "Match all"/.test(x)), "RED: a launch sound cue that moved is caught by --check (it was invisible under one undefined name)");+ ok(sheetCues(sheet, fps).every((c, i) => c.name === sheet[i].name && c.t === sheet[i].t), "a withCues sheet passes through unchanged");+};diff --git a/skills/anidoodle/engine/test/dockKeepsBreaks.test.ts b/skills/anidoodle/engine/test/dockKeepsBreaks.test.tsnew file mode 100644index 0000000..7dafb3b--- /dev/null+++ b/skills/anidoodle/engine/test/dockKeepsBreaks.test.ts@@ -0,0 +1,28 @@+// THE DRAWN DOCK KEEPS THE HOOK'S LINE BREAKS. The drawn hook's composer docks by easing its size and its+// type size together, and its words were wrapped afresh each frame at the eased width: "TODO / what a / user+// types" became "TODO what / a user types", then "TODO what a / user types", then "TODO what a user / types",+// words jumping between lines as it moved. Once the calm dock grew longer and started over the prompt's last+// words, the line "TODO what a user" stood 0.13 s (framecheck reading time, the drawn scaffold on 9:16).+// The composer now wraps as the hook did (ChatGeom.wrapAs), then halfway, as its rows change, as the dock+// does: one change of breaks, never one per frame. (Kept as the hook's to the landing, the hook's second line+// hung under the shrinking one-line dock on 16:9 and was clipped: layerscan exits, "types" in slivers.)+// node tools/test.mjs dockKeepsBreaks+import { composerLines, type ChatGeom } from "../src/canvas-core/launchKit";+import { makeLaunchFilm, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import { lighthouseDraw } from "../src/canvas-core/lighthouseDraw";++export const name = "the drawn dock keeps the hook's line breaks";+export const run = (ok: (cond: boolean, label: string) => void) => {+ // a measuring stub: every character half its type size wide+ const stub = { font: "", measureText: (t: string) => ({ width: t.length * parseFloat(/([\d.]+)px/.exec(stub.font)?.[1] ?? "10") * 0.5 }) };+ const ctx = stub as unknown as Parameters<typeof composerLines>[0];+ const geom = (px: number, w: number): ChatGeom => ({ k: 1, TEXT: { x: 0, base: 0, px }, GEN: { x: w + 20, y: 0, w: 10, h: 10, r: 1 } } as unknown as ChatGeom);+ const hero = geom(70, 420), mid = geom(40, 400), text = "TODO what a user types";+ const lh = composerLines(ctx, text, hero), lm = composerLines(ctx, text, mid);+ ok(lh.join("|") !== lm.join("|"), `the eased geometry alone wraps differently (${lh.join(" / ")} against ${lm.join(" / ")})`);+ const kept = composerLines(ctx, text, { ...mid, wrapAs: { px: 70, maxW: 420 } });+ ok(kept.join("|") === lh.join("|"), `RED: wrapped as the hook, the docking composer keeps its breaks (${kept.join(" / ")})`);+ // and the template's drawn dock asks for it on every frame of the move+ const f = makeLaunchFilm({ title: "TODO Product", asks: [{ prompt: text, plate: lighthouseDraw, label: "l" }, { prompt: "TODO the follow-up", plate: lighthouseDraw, label: "l" }], tagline: "t", install: ["npm i x"], bpm: 90, motion: { temperament: "calm", brandColors: ["#cc5533"] }, score: null, sfx: false });+ for (const sh of ["16x9", "9x16"]) { const d = (f.reshape(sh) as LaunchFilm).grammar?.heroDock; ok(!!d && d.wraps <= 2, `RED ${sh}: the drawn dock wraps as the hook, then as the dock, nothing between (${d?.wraps} sets of breaks)`); }+};diff --git a/skills/anidoodle/engine/test/drawnDockTemperament.test.ts b/skills/anidoodle/engine/test/drawnDockTemperament.test.tsnew file mode 100644index 0000000..338a9a5--- /dev/null+++ b/skills/anidoodle/engine/test/drawnDockTemperament.test.ts@@ -0,0 +1,25 @@+// THE DRAWN DOCK KEEPS TO THE BRAND'S TEMPERAMENT. The drawn hook's composer docks over an in-out of a+// second. On a phone frame it travels from the middle of the window to its foot, and a calm brand's hook+// (the default drawn scaffold) moved at 44 px a frame where calm allows 31 (motionscan temperament) and its+// type at 45 against half the speed ceiling (layerscan fasttext). The dock now takes longer when the distance+// asks for it; a lively brand's dock keeps its second.+// node tools/test.mjs drawnDockTemperament+import { makeLaunchFilm, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import { launchExample } from "../src/canvas-core/launchExample";+import { lighthouseDraw } from "../src/canvas-core/lighthouseDraw";+import { TEMPERAMENTS } from "../src/canvas-core/motionKit";+import { speedCeiling } from "../src/canvas-core/seams";++export const name = "the drawn dock keeps to the brand's temperament";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const calm = makeLaunchFilm({ title: "TODO Product", subtitle: "TODO the one line it lives by", placeholder: "Ask for anything…", asks: [{ prompt: "TODO what a user types", plate: lighthouseDraw, label: "TODO byline" }, { prompt: "TODO the follow-up", plate: lighthouseDraw, label: "TODO byline" }], tagline: "t", install: ["npm i x"], bpm: 90, motion: { temperament: "calm", brandColors: ["#cc5533"] }, score: null, sfx: false });+ for (const [id, film, t] of [["calm scaffold", calm, "calm"], ["lively example", launchExample as LaunchFilm, "lively"]] as const) for (const sh of ["16x9", "9x16"]) {+ const r = film.reshape(sh) as LaunchFilm, d = r.grammar?.heroDock;+ if (!d) { ok(false, `${id} ${sh}: the film exposes its dock`); continue; }+ const cap = 0.95 * Math.min(0.5, TEMPERAMENTS[t].maxSpeed) * speedCeiling(r.meta.W, 30);+ ok(d.peak <= cap, `RED ${id} ${sh}: the dock's fastest point ${d.peak.toFixed(1)} px a frame, under ${cap.toFixed(1)} (${d.frames[1] - d.frames[0]} frames)`);+ }+ // a lively brand keeps the one-second dock where the distance allows it+ const w = (launchExample as LaunchFilm).reshape("16x9") as LaunchFilm;+ ok(w.grammar?.heroDock?.frames[1]! - w.grammar?.heroDock?.frames[0]! === 30, `the lively example's wide dock is still 30 frames`);+};diff --git a/skills/anidoodle/engine/test/endCardCentre.test.ts b/skills/anidoodle/engine/test/endCardCentre.test.tsnew file mode 100644index 0000000..d56c5a9--- /dev/null+++ b/skills/anidoodle/engine/test/endCardCentre.test.ts@@ -0,0 +1,29 @@+// END CARD CENTRE (critic finding d4-1). The stacked end card sat 8 to 20 px left of the frame's centre+// on both shapes, every line of it by the same amount. The cause was its settle: the page leans in 3 %+// about the motif's dot, which sits at the right end of the name, so the lean carried the whole card+// left by 3 % of the dot's distance from the axis (20 px on 16:9, 11 px on 9:16). The settle now zooms+// about a point on the card's own axis, and the name with its dot is centred on that axis by its ink+// (kinetic.inkSpan), not its advance width. Measured on the render after the fix: every line of the drawn+// example's card within 1.5 px of the centre on both shapes.+// node tools/test.mjs endCardCentre+import { launchExample } from "../src/canvas-core/launchExample";+import { makeLaunchFilm, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import type { ProductUI } from "../src/canvas-core/productUI";+import { inkSpan, measure } from "../src/canvas-core/kinetic";++export const name = "end card centre (d4-1)";+export const run = (ok: (cond: boolean, label: string) => void) => {+ // a written name's ink starts a side bearing after its advance does (measured on the render: 6 px at 150 px)+ { const [l, r] = inkSpan("Your Product", 150, { seed: 11 }); ok(l > 2 && l < 12 && r > measure("Your Product", 150) - 20, `RED a written line's ink span is its strokes plus the nib (${l.toFixed(1)} to ${r.toFixed(1)}, advance ${measure("Your Product", 150).toFixed(1)})`); }+ const ui: ProductUI = { title: "T", nav: ["A"], action: "Go", before: { items: [{ id: "a", label: "x", value: 1 }] }, after: { items: [{ id: "a", label: "x", value: 0, done: true }] } };+ const clean = makeLaunchFilm({ title: "Tally", preset: "clean", asks: [{ kind: "ui", ui, prompt: "match every receipt" }], tagline: "Bookkeeping that does itself", install: ["npm i tally"], bpm: 90, score: null });+ for (const [id, f] of [["drawn", launchExample as LaunchFilm], ["clean stack", clean]] as const) for (const sh of ["16x9", "9x16"]) {+ const g = (f.reshape(sh) as Partial<LaunchFilm>).grammar?.endCard;+ if (!g) { ok(false, `RED ${id} ${sh}: the film exposes its end card's geometry`); continue; }+ // where the card's axis lands once the settle has leaned in its full 3 %+ const z = 1.03, axis = g.creep[0] + (g.cx - g.creep[0]) * z;+ ok(Math.abs(axis - g.cx) < 0.5, `RED ${id} ${sh}: the settle keeps the card on its axis (x ${g.cx.toFixed(0)} lands at ${axis.toFixed(1)}; it zooms about x ${g.creep[0].toFixed(0)})`);+ const mid = (g.group[0] + g.group[1]) / 2;+ ok(Math.abs(mid - g.cx) < 1, `${id} ${sh}: the name and its dot are centred on the axis (their middle ${mid.toFixed(1)}, the axis ${g.cx.toFixed(0)})`);+ }+};diff --git a/skills/anidoodle/engine/test/endCardStamp.test.ts b/skills/anidoodle/engine/test/endCardStamp.test.tsnew file mode 100644index 0000000..3ffacc9--- /dev/null+++ b/skills/anidoodle/engine/test/endCardStamp.test.ts@@ -0,0 +1,23 @@+// END CARD, WITHOUT A SPONSOR BAND. The approved card puts the call-to-action stamp at the right edge, on+// the venue's baseline, over a sponsor band that spans the width. The launch template's card has no band,+// and there a fresh critic saw the stamp float far right of the text block. `stamp: "inline"` sets it one+// gap after the line it sits on. And a lockup whose letters hang below its box (a name's descender) says+// how far with `descent`, so the next line keeps its air under the letters, not under the box.+// node tools/test.mjs endCardStamp+import { endCardLayout, type EndCardSpec } from "../src/canvas-core/endCard";++export const name = "endCard: an inline stamp and a lockup's descent";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const measure = (t: string, font: string) => t.length * Number(/(\d+)px/.exec(font)![1]) * 0.55;+ const spec: EndCardSpec = { lockup: { aspect: 3.2, draw: () => {} }, date: "Bookkeeping that does itself", venue: "npm install tally · tally init", cta: "tally.example", colors: { ink: "#111", accent: "#2f54eb", ctaInk: "#fff" } };+ const edge = endCardLayout(1920, 1080, spec, measure);+ ok(edge.cta.x + edge.cta.w === 1920 - edge.margin, "16:9 default: the approved card's stamp stays at the right margin");+ const inl = endCardLayout(1920, 1080, { ...spec, stamp: "inline" } as never, measure), lineEnd = Math.max(inl.date.x + inl.date.w, inl.venue.x + inl.venue.w);+ ok(inl.cta.x > lineEnd && inl.cta.x - lineEnd <= 120, `RED: an inline stamp sits one gap after the text block (stamp at ${Math.round(inl.cta.x)}, the lines end at ${Math.round(lineEnd)})`);+ ok(Math.abs(inl.cta.y - edge.cta.y) < 1e-9, "the inline stamp keeps the venue's baseline");+ const hang = endCardLayout(1920, 1080, { ...spec, lockup: { ...spec.lockup, descent: 0.3 } } as never, measure);+ ok(hang.date.y - (hang.lockup.y + hang.lockup.h) >= edge.date.y - (edge.lockup.y + edge.lockup.h) + 0.3 * hang.lockup.h - 1e-9, `RED: a lockup that hangs 30 % below its box pushes the next line down by as much (gap ${Math.round(hang.date.y - hang.lockup.y - hang.lockup.h)} against ${Math.round(edge.date.y - edge.lockup.y - edge.lockup.h)})`);+ // inline never runs past the frame: a long line puts the stamp back at the margin+ const longL = endCardLayout(1920, 1080, { ...spec, venue: "npm install a-very-long-package-name-for-the-product && product init --all", stamp: "inline" } as never, measure);+ ok(longL.cta.x + longL.cta.w <= 1920 - longL.margin + 1e-9, "a long line never pushes an inline stamp past the right margin");+};diff --git a/skills/anidoodle/engine/test/endInstallRows.test.ts b/skills/anidoodle/engine/test/endInstallRows.test.tsnew file mode 100644index 0000000..e7883b3--- /dev/null+++ b/skills/anidoodle/engine/test/endInstallRows.test.ts@@ -0,0 +1,32 @@+// THE END CARD'S INSTALL LINES, SET AS A TERMINAL SETS THEM. The launch template's end card holds the+// exact lines a viewer copies in a dark panel. They were each centred on their own, so two lines of+// different lengths started at different places: a fresh critic read it as a caption, not a terminal+// (a P1 on the drawn example). Every line starts at the panel's left padding, in both presets and shapes.+// node tools/test.mjs endInstallRows+import { launchExample } from "../src/canvas-core/launchExample";+import { launchExampleClean } from "../src/canvas-core/launchExampleClean";+import { renderFrame } from "../src/canvas-core/film";+import type { Ctx, Env, Layer } from "../src/canvas-core/core";+import type { LaunchFilm } from "../src/canvas-core/launchTemplate";+import { FakeCanvas } from "./fakeCanvas";++// offscreen layers (the paper's grain) write pixels: the fake surface takes them and keeps none+const pixels = <T extends object>(c: T) => Object.assign(c, { createPattern: () => ({ setTransform: () => {} }), createLinearGradient: () => ({ addColorStop: () => {} }), createRadialGradient: () => ({ addColorStop: () => {} }), createImageData: (w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }), putImageData: () => {}, getImageData: (_x: number, _y: number, w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }) });++export const name = "launch end card: install lines start together, left in the panel";+export const run = (ok: (cond: boolean, label: string) => void) => {+ for (const [id, base] of [["drawn", launchExample], ["clean", launchExampleClean]] as const) for (const sh of ["16x9", "9x16"]) {+ const film = (base as LaunchFilm).reshape(sh), L = film.layout;+ const canvas = new FakeCanvas(L.W, L.H), raw = pixels(canvas.ctx), seen: { text: string; left: number }[] = [];+ // every surface's fillText, the page's and any layer's: where a line's left edge lands on its surface+ const proto = Object.getPrototypeOf(raw) as { fillText: (s: string, x: number, y: number) => void }, keep = proto.fillText;+ proto.fillText = function (this: CanvasRenderingContext2D, t: string, x: number) { const w = this.measureText(t).width, a = this.textAlign; seen.push({ text: t, left: a === "center" ? x - w / 2 : a === "right" || a === "end" ? x - w : x }); };+ const ctx = raw as unknown as Ctx;+ const env = { W: L.W, H: L.H, scale: 1, root: true, cache: new Map(), canvas: (w: number, h: number) => { const c = new FakeCanvas(w, h); return { canvas: c, ctx: pixels(c.ctx), w, h } as unknown as Layer; } } as unknown as Env;+ try { renderFrame(film, ctx, film.meta.durationFrames - 1, env); } finally { proto.fillText = keep; }+ const rows = seen.filter((r) => /install|init|\$ |npx|npm|brew|pip/.test(r.text) && r.text.length > 6);+ const lefts = rows.map((r) => Math.round(r.left));+ if (id === "clean" && rows.length === 1) { ok(true, `clean ${sh}: the grid card sets its install lines as one line ("${rows[0].text}")`); continue; }+ ok(rows.length >= 2 && Math.max(...lefts) - Math.min(...lefts) <= 1, `RED ${id} ${sh}: the install lines start at one x (${rows.map((r, j) => `"${r.text}" at ${lefts[j]}`).join(", ") || "none found"})`);+ }+};diff --git a/skills/anidoodle/engine/test/endTaglineSafe.test.ts b/skills/anidoodle/engine/test/endTaglineSafe.test.tsnew file mode 100644index 0000000..53d188c--- /dev/null+++ b/skills/anidoodle/engine/test/endTaglineSafe.test.ts@@ -0,0 +1,18 @@+// THE END CARD'S LINE STAYS IN THE SAFE RECTANGLE. On a phone the clean end card centres its tagline on the+// frame's axis, but wrapped it to 90 % of the safe rectangle's width, which is narrower on the right (the+// platforms' button column): a line measured from a real face ran into that column for 259 frames+// (launchExampleBrand 9:16, framecheck zones). Each line is now wrapped to the width the axis leaves it inside+// the safe rectangle.+// node tools/test.mjs endTaglineSafe+import { launchExampleBrand } from "../src/canvas-core/launchExampleBrand";+import { launchExampleClean } from "../src/canvas-core/launchExampleClean";+import type { LaunchFilm } from "../src/canvas-core/launchTemplate";++export const name = "the end card's line stays in the safe rectangle";+export const run = (ok: (cond: boolean, label: string) => void) => {+ for (const [id, film] of [["brand", launchExampleBrand], ["clean", launchExampleClean]] as const) for (const sh of ["16x9", "9x16"]) {+ const e = ((film as LaunchFilm).reshape(sh) as LaunchFilm).grammar.endCard;+ const worst = Math.max(...e.taglineW.map((w) => e.cx + w / 2 - e.room[1]), ...e.taglineW.map((w) => e.room[0] - (e.cx - w / 2)));+ ok(worst <= -8, `RED ${id} ${sh}: every tagline line ends 8 px or more inside the room (${e.tagline.join(" / ")}: ${worst.toFixed(0)} px)`);+ }+};diff --git a/skills/anidoodle/engine/test/factsDupes.test.ts b/skills/anidoodle/engine/test/factsDupes.test.tsnew file mode 100644index 0000000..24d394d--- /dev/null+++ b/skills/anidoodle/engine/test/factsDupes.test.ts@@ -0,0 +1,22 @@+// FACTS DUPES TESTS. A fact said twice wastes a beat (a launch film said "about 400" in the hook and+// "400+" on a numbers card); a live site is a source with a date. Held to known answers, red and green.+// @ts-ignore: a plain ES module shared with the tools+import { checkFacts, dupes, entryProblems } from "../tools/factsrules.mjs";++export const name = "factsDupes";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const site = { sentence: "Over 400 marketers joined last year.", url: "https://example.com/about", kind: "site", fetched: "2026-10-27" };+ const hook = { claim: "Actually, about 400 of them.", where: "on-screen", source: site };+ const card = { claim: "400+ marketers who figured it out", where: "on-screen", source: site };+ const red = checkFacts([hook.claim, card.claim], { claims: [hook, card] });+ ok(red.status === "FAIL" && red.problems.some((p: { why: string }) => /states 400 again/.test(p.why)), "RED: the same number on two cards fails, naming where it was first");+ ok(checkFacts([hook.claim, card.claim], { claims: [hook, { ...card, reuse: "the hook's number returns as the proof card's headline" }] }).status === "PASS", "a repeat with a reason passes");+ ok(checkFacts([hook.claim], { claims: [hook] }).status === "PASS", "one use passes");+ ok(dupes(["Nobody's on mute.", "nobody's on mute"], []).length === 1, "RED: the same line declared twice is caught, ignoring case and end punctuation");+ ok(dupes(["Day 1", "Step 1 of 3"], [{ claim: "Day 1" }, { claim: "Step 1 of 3" }]).length === 0, "single digits are counting words, not facts: never flagged");+ ok(dupes([], [{ claim: "03.05.2027 in Santiago" }, { claim: "See you 03.05.2027" }]).length === 1, "RED: a date repeated on two cards needs a reason too");+ ok(entryProblems({ claim: "c", source: { sentence: "c", url: "https://a.b", kind: "site" } }).some((w: string) => /fetched date/.test(w)), "RED: a site source with no fetched date fails");+ ok(entryProblems({ claim: "c", source: { sentence: "c", url: "https://a.b", kind: "site", fetched: "2026-10-27" } }).length === 0, "a site source with its date passes");+ // a visual count is a number: six '?' dots claim six more speakers+ ok(entryProblems({ claim: "6 more speakers coming", where: "on-screen", generated: true, note: "six ? dots" }).some((w: string) => /number/.test(w)), "RED: a drawn count listed as generated fails (a count is a claim: source it or draw one symbol)");+};diff --git a/skills/anidoodle/engine/test/fakeCanvas.ts b/skills/anidoodle/engine/test/fakeCanvas.tsnew file mode 100644index 0000000..b0df72a--- /dev/null+++ b/skills/anidoodle/engine/test/fakeCanvas.ts@@ -0,0 +1,36 @@+// A STAND-IN 2D CANVAS for the host instrument tests (probe.test.ts, instrument.test.ts). Node has no+// canvas, and the probes only need what they hook: the prototype methods, a transform, a save/restore+// stack, measureText, and pixels for the instruments that compare two draws. Pixels are a plain RGBA+// buffer; fillText paints its measured box solid, fillRect paints its rectangle, drawImage copies at+// integer offsets. Install it as globalThis.CanvasRenderingContext2D before a probe runs.+export type M = { a: number; b: number; c: number; d: number; e: number; f: number };+export class FakeCtx {+ canvas: FakeCanvas; globalAlpha = 1; globalCompositeOperation = "source-over"; textAlign = "left"; font = "20px Sans"; fillStyle: string = "#000000"; strokeStyle: string = "#000000";+ T: M = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }; stack: M[] = [];+ constructor(c: FakeCanvas) { this.canvas = c; }+ getTransform() { return { ...this.T }; }+ setTransform(a: number, b: number, c: number, d: number, e: number, f: number) { this.T = { a, b, c, d, e, f }; }+ translate(x: number, y: number) { this.T = { ...this.T, e: this.T.e + this.T.a * x + this.T.c * y, f: this.T.f + this.T.b * x + this.T.d * y }; }+ scale(x: number, y: number) { this.T = { ...this.T, a: this.T.a * x, b: this.T.b * x, c: this.T.c * y, d: this.T.d * y }; }+ save() { this.stack.push({ ...this.T }); }+ restore() { this.T = this.stack.pop() ?? this.T; }+ reset() { this.T = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }; this.stack = []; this.canvas.px.fill(0); }+ measureText(t: string) { const s = Number(/(\d+)px/.exec(this.font)?.[1] ?? 10); return { width: t.length * s * 0.5, actualBoundingBoxAscent: s * 0.75, actualBoundingBoxDescent: s * 0.25 }; }+ private paint(x0: number, y0: number, x1: number, y1: number, rgb: [number, number, number]) {+ const { width: W, height: H, px } = this.canvas, T = this.T;+ const X0 = Math.max(0, Math.floor(T.a * x0 + T.e)), Y0 = Math.max(0, Math.floor(T.d * y0 + T.f)), X1 = Math.min(W, Math.ceil(T.a * x1 + T.e)), Y1 = Math.min(H, Math.ceil(T.d * y1 + T.f));+ for (let y = Y0; y < Y1; y++) for (let x = X0; x < X1; x++) { const p = (y * W + x) * 4; px[p] = rgb[0]; px[p + 1] = rgb[1]; px[p + 2] = rgb[2]; px[p + 3] = 255; }+ }+ fillText(t: string, x: number, y: number) { const m = this.measureText(t); this.paint(x, y - m.actualBoundingBoxAscent, x + m.width, y + m.actualBoundingBoxDescent, [255, 255, 255]); }+ strokeText(t: string, x: number, y: number) { this.fillText(t, x, y); }+ fillRect(x: number, y: number, w: number, h: number) { this.paint(x, y, x + w, y + h, [40, 40, 40]); }+ clearRect(x: number, y: number, w: number, h: number) { const { width: W, height: H, px } = this.canvas; for (let yy = Math.max(0, y); yy < Math.min(H, y + h); yy++) for (let xx = Math.max(0, x); xx < Math.min(W, x + w); xx++) px.fill(0, (yy * W + xx) * 4, (yy * W + xx) * 4 + 4); }+ drawImage(src: FakeCanvas, dx: number, dy: number) {+ const { width: W, height: H, px } = this.canvas, ox = Math.round(this.T.a * dx + this.T.e), oy = Math.round(this.T.d * dy + this.T.f);+ for (let y = 0; y < src.height; y++) for (let x = 0; x < src.width; x++) { const s = (y * src.width + x) * 4, X = x + ox, Y = y + oy; if (src.px[s + 3] && X >= 0 && Y >= 0 && X < W && Y < H) px.set(src.px.subarray(s, s + 4), (Y * W + X) * 4); }+ }+ getImageData(_x: number, _y: number, w: number, h: number) { return { data: this.canvas.px.slice(0, w * h * 4) }; }+ fill(..._a: unknown[]) {} stroke(..._a: unknown[]) {} beginPath() {} closePath() {} rect(..._a: unknown[]) {} roundRect(..._a: unknown[]) {} arc(..._a: unknown[]) {} arcTo(..._a: unknown[]) {} ellipse(..._a: unknown[]) {} moveTo(..._a: unknown[]) {} lineTo(..._a: unknown[]) {} bezierCurveTo(..._a: unknown[]) {} quadraticCurveTo(..._a: unknown[]) {} clip(..._a: unknown[]) {}+}+export class FakeCanvas { px: Uint8ClampedArray; ctx: FakeCtx; constructor(public width: number, public height: number) { this.px = new Uint8ClampedArray(width * height * 4); this.ctx = new FakeCtx(this); } getContext() { return this.ctx; } }+export const installFakeCanvas = () => { (globalThis as Record<string, unknown>).CanvasRenderingContext2D = FakeCtx; };diff --git a/skills/anidoodle/engine/test/fixtures/board/good.json b/skills/anidoodle/engine/test/fixtures/board/good.jsonnew file mode 100644index 0000000..7f4354e--- /dev/null+++ b/skills/anidoodle/engine/test/fixtures/board/good.json@@ -0,0 +1,22 @@+{ "version": 1,+ "brief": { "story": "A marketer stuck in a chat window finds the room of people who already figured it out.",+ "message": "AI is changing marketing. Nobody has a prompt for that.",+ "premise": { "pain": "marketers who talk to AI all day", "stereotype": "the assistant's em-dash habit and fake enthusiasm" },+ "promise": { "line": "Half a day with marketers who already figured it out.", "does": "spend half a day with marketers", "leaves": "real systems that get real results" },+ "actor": "the three typing dots", "kind": "event",+ "people": { "hosts": ["Host A", "Host B"], "sponsors": ["Sponsor One"], "partners": "excluded: none this year, decided by the organisers", "speakers": ["Speaker A"] },+ "voices": { "ai": "three dots, then white type in the reply bubble" },+ "reference": { "film": "a classic keynote title film", "notes": "reference/deconstruction.md" },+ "length": { "target": 60, "max": 90 } },+ "rows": [+ { "id": "hook", "seconds": 3, "action": "the three typing dots bounce in an empty chat, then type a fast reply", "texture": ["blah blah blah"], "lines": [{ "speaker": "ai", "text": "Great question!" }] },+ { "id": "fall", "seconds": 4, "action": "the dots fall out of the chat and land in a crowd of dots", "carry": "the three dots" },+ { "id": "crowd", "seconds": 4, "action": "the crowd of dots wires itself into a network and spirals into one dot", "carry": "the crowd of dots", "counts": [{ "of": "dots", "from": 3, "to": 1, "why": "two dots join the network; one hops up and becomes the logo's dot" }] },+ { "id": "logo", "seconds": 5, "action": "the network thread becomes the mark's neck and the lockup rises", "carry": "the one dot", "brand": true, "bridge": "the people who connected ARE the event", "builtFrom": "the network thread and the one dot" },+ { "id": "card", "seconds": 4, "kind": "card", "action": "the lockup slides to the corner and the date, venue and call land on the grid", "carry": "the lockup", "words": ["Reserve a spot"] },+ { "id": "sting", "seconds": 2, "kind": "stinger", "action": "the dots type one last reply under the card", "carry": "the card", "answers": "the call to reserve a spot on the card", "lines": [{ "speaker": "ai", "text": "You're absolutely right." }] } ],+ "jokes": [+ { "line": "Great question!", "device": "verbal", "butt": "the habit of empty praise", "who": "anyone who chats with an assistant daily knows the opener", "row": "hook" },+ { "line": "an 'I'm not a robot' box ticked at '100% in person'", "device": "visual", "butt": "the situation of proving you are human", "who": "everyone has clicked that box", "row": "card" },+ { "line": "the dots hesitate, then type 'make no mistakes'", "device": "interaction", "butt": "the habit of over-prompting", "who": "prompt writers recognise their own line", "row": "hook" } ],+ "program": [ { "name": "Speaker A", "role": "Head of Growth", "company": "Example Co", "logo": "logos/example.svg" } ] }diff --git a/skills/anidoodle/engine/test/fixtures/board/slides.json b/skills/anidoodle/engine/test/fixtures/board/slides.jsonnew file mode 100644index 0000000..d2b541b--- /dev/null+++ b/skills/anidoodle/engine/test/fixtures/board/slides.json@@ -0,0 +1,14 @@+{ "version": 1,+ "_about": "RED fixture: the first board of a brand launch film, a list of facts that played as a slide deck",+ "brief": { "story": "An event for marketers.", "promise": { "line": "Multiply your marketing intelligence" }, "kind": "event", "people": { "speakers": ["?", "?"] } },+ "rows": [+ { "id": "s1", "seconds": 3, "action": "You talk to AI all day." },+ { "id": "s2", "seconds": 3, "action": "Keynotes" },+ { "id": "s3", "seconds": 3, "action": "Topics strip" },+ { "id": "logo", "seconds": 3, "action": "the logo appears", "brand": true, "counts": [{ "of": "dots", "from": 3, "to": 2 }], "texture": ["Here is a detailed plan for your campaign"] },+ { "id": "card", "seconds": 4, "kind": "card", "action": "end card", "words": ["400+ marketers"] },+ { "id": "joke", "seconds": 2, "kind": "stinger", "action": "see you there?", "words": ["400+ marketers"] },+ { "id": "card2", "seconds": 4, "kind": "card", "action": "end card again" } ],+ "jokes": [ { "line": "the AI is too dumb to count", "device": "verbal", "butt": "the AI tool" } ],+ "pitches": [ { "line": "AI loves em-dashes", "device": "verbal" }, { "line": "AI says great question", "device": "verbal" } ],+ "program": [ { "name": "Mystery speaker", "role": "", "company": "" }, { "name": "Speaker B", "role": "CMO", "company": "B Co", "title": "Inside the playbook of a very long talk title" } ] }diff --git a/skills/anidoodle/engine/test/fixtures/brand/hardmask.svg b/skills/anidoodle/engine/test/fixtures/brand/hardmask.svgnew file mode 100644index 0000000..cc5d899--- /dev/null+++ b/skills/anidoodle/engine/test/fixtures/brand/hardmask.svg@@ -0,0 +1,5 @@+<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">+ <!-- GREEN fixture: a hard white mask is imported as a clip and draws exactly -->+ <mask id="half"><rect width="50" height="100" fill="#fff"/></mask>+ <rect width="100" height="100" fill="#FFD900" mask="url(#half)"/>+</svg>diff --git a/skills/anidoodle/engine/test/fixtures/brand/hourglass.svg b/skills/anidoodle/engine/test/fixtures/brand/hourglass.svgnew file mode 100644index 0000000..7a0b9a5--- /dev/null+++ b/skills/anidoodle/engine/test/fixtures/brand/hourglass.svg@@ -0,0 +1,5 @@+<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">+ <!-- GREEN fixture: two dots and an S-curve neck, the same after a half turn -->+ <circle cx="50" cy="50" r="40" fill="#FFD900"/><circle cx="150" cy="150" r="40" fill="#FFD900"/>+ <path d="M60 70 C100 70 100 110 140 110 L140 130 C100 130 100 90 60 90 Z" fill="#FFD900"/>+</svg>diff --git a/skills/anidoodle/engine/test/fixtures/brand/masked.svg b/skills/anidoodle/engine/test/fixtures/brand/masked.svgnew file mode 100644index 0000000..6a6d9e0--- /dev/null+++ b/skills/anidoodle/engine/test/fixtures/brand/masked.svg@@ -0,0 +1,6 @@+<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">+ <!-- RED fixture for the brand contact sheet: a soft (gradient) mask fades the right half in the browser; the import cannot draw a soft mask, so the sheet must FAIL -->+ <defs><linearGradient id="fade"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#000"/></linearGradient></defs>+ <mask id="soft"><rect width="100" height="100" fill="url(#fade)"/></mask>+ <rect width="100" height="100" fill="#FFD900" mask="url(#soft)"/>+</svg>diff --git a/skills/anidoodle/engine/test/fixtures/motion-person.png b/skills/anidoodle/engine/test/fixtures/motion-person.pngnew file mode 100644index 0000000..9137c61Binary files /dev/null and b/skills/anidoodle/engine/test/fixtures/motion-person.png differdiff --git a/skills/anidoodle/engine/test/framerules.test.ts b/skills/anidoodle/engine/test/framerules.test.tsnew file mode 100644index 0000000..9f063b4--- /dev/null+++ b/skills/anidoodle/engine/test/framerules.test.ts@@ -0,0 +1,120 @@+// FRAME RULES TESTS. Every rule framecheck applies to what a film draws, held to a case that must fail+// (a brand launch film's real faults, rebuilt as probe records) and one that must pass.+// @ts-ignore: a plain ES module shared with the tools+import { RULES, autoCues, blocksOf, checkedFrames, edgeCuts, endCardRuns, endSizeFindings, fontReport, framesOf, headSpread, layoutFindings, readingFloor, readingVerdict, rectGap } from "../tools/framerules.mjs";++type R = { kind: string; label: string; frame: number; x0: number; y0: number; x1: number; y1: number; cut?: boolean; alpha?: number; px?: number; family?: string; texture?: boolean };+const T = (label: string, frame: number, x0: number, y0: number, px = 40, o: Partial<R> = {}): R => ({ kind: "text", label, frame, x0, y0, x1: x0 + label.length * px * 0.5, y1: y0 + px * 0.75, cut: false, alpha: 1, px, family: "Inter", ...o });+const BOX = (label: string, frame: number, x0: number, y0: number, x1: number, y1: number): R => ({ kind: "box", label, frame, x0, y0, x1, y1, cut: false });+const range = (a: number, b: number) => Array.from({ length: b - a }, (_, i) => a + i);++export const name = "framerules";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const fps = 30, W = 1920, H = 1080;+ // ---- blocks: glyphs drawn one by one read as words+ const glyphs = [..."Hi you"].map((ch, i) => (ch === " " ? null : T(ch, 0, 100 + i * 22 + (i > 2 ? 12 : 0), 100, 40))).filter(Boolean) as R[];+ const bl = blocksOf(glyphs);+ ok(bl.length === 1 && bl[0].key === "Hi you", `glyphs drawn one at a time join into one block with its word gap ("${bl[0]?.key}")`);+ ok(blocksOf([T("Line one of it", 0, 100, 100), T("line two", 0, 100, 145)]).length === 1, "two lines of one paragraph are one block");+ ok(blocksOf([T("Title", 0, 100, 100), T("Far away", 0, 1200, 800)]).length === 2, "text far apart is two blocks");++ // ---- reading time from drawn text (T2): a brand launch film's reply, 11 words up 2.5 s, fails; 3.3 s passes+ const reply = "I can handle the non-human part. Ingrid has the human one.";+ const shown = (s: number, from = 30) => { const fr = range(0, 200), m = framesOf(range(from, from + Math.round(s * fps)).map((f) => T(reply, f, 100, 400)), fr); return { m, fr }; };+ const short = shown(2.5), sv = readingVerdict(autoCues(short.m, short.fr, { last: 200, fps }), [], fps, short.fr.length);+ ok(sv.status === "FAIL" && sv.bad[0]?.need === 3.3, `NEGATIVE: the 11-word reply up 2.5 s fails, it needs 3.3 s (${JSON.stringify(sv.bad[0])})`);+ const long = shown(3.4), lv = readingVerdict(autoCues(long.m, long.fr, { last: 200, fps }), [], fps, long.fr.length);+ ok(lv.status === "PASS" && lv.checked === 1, "the same reply up 3.4 s passes");+ // typed text: the read starts after the last character+ const typedRecs: R[] = []; const words = reply.split(" ");+ for (let f = 0; f < 120; f++) { const n = Math.min(words.length, 1 + Math.floor(f / 6)); typedRecs.push(T(words.slice(0, n).join(" "), f, 100, 400)); }+ const typed = autoCues(framesOf(typedRecs, range(0, 130)), range(0, 130), { last: 130, fps });+ ok(typed.cues.length === 1 && typed.cues[0].from === 60 && typed.skipped.typing >= 9, `a typed reply is one cue, timed from its last word (from ${typed.cues[0]?.from}, ${typed.skipped.typing} typing steps skipped)`);+ ok(readingVerdict(typed, [], fps, 130).status === "FAIL", "NEGATIVE: typed for 2 s then held 2 s (under 3.3 s after the last word) fails");+ // texture text is skipped, and a film with text can never be N/A+ const blah = framesOf(range(0, 10).map((f) => T("blah blah blah blah blah", f, 100, 100, 40, { texture: true })), range(0, 10));+ const bv = readingVerdict(autoCues(blah, range(0, 10), { fps }), [], fps, 10);+ ok(bv.status === "FAIL" && /no cue/.test(bv.reason), "NEGATIVE: text drawn but nothing timed is a FAIL that says why, never N/A");+ const none = readingVerdict(autoCues(framesOf([], range(0, 10)), range(0, 10), { fps }), [], fps, 10);+ ok(none.status === "NONE" && /no text was drawn/.test(none.reason), "a film that draws no text says so with its evidence (NONE), not N/A");+ ok(readingVerdict(autoCues(framesOf([], []), [], { fps }), [], fps, 0).status === "FAIL", "NEGATIVE: no frame checked is a FAIL (an empty run proves nothing)");+ ok(autoCues(blah, range(0, 10), { fps }).texture === 10, "texture blocks are counted, not judged");+ // a count-up is an animation, not ten reads+ const count = framesOf(range(0, 80).map((f) => T(String(Math.min(400, f * 10)), f, 500, 500, 80)), range(0, 80));+ const cc = autoCues(count, range(0, 80), { last: 80, fps });+ ok(cc.cues.length === 1 && cc.cues[0].text === "400" && cc.skipped.flash > 5, `a count-up times only its final number (${cc.cues.map((c: { text: string }) => c.text).join(",")})`);+ // the same words moving from the input to the bubble are one read; a return of read text is not judged again+ const moved = framesOf([...range(0, 40).map((f) => T("hello there", f, 100, 900)), ...range(41, 60).map((f) => T("hello there", f, 900, 300))], range(0, 100));+ ok(autoCues(moved, range(0, 100), { last: 100, fps }).cues.length === 1, "a sent message (input, then bubble, one frame apart) is one cue");+ const back = framesOf([...range(0, 40).map((f) => T("Header", f, 100, 100)), ...range(80, 84).map((f) => T("Header", f, 100, 100))], range(0, 100));+ const bc = autoCues(back, range(0, 100), { last: 100, fps });+ ok(bc.cues.length === 1 && bc.skipped.seen === 1, "a header read in full and back for 4 frames later is not a new read");+ // a line leaving word by word (last word first) leaves remnants that are exit steps, not reads+ const leaving: R[] = []; for (let f = 0; f < 60; f++) leaving.push(T("Beat two: one line", f, 100, 400)); ["Beat two: one", "Beat two:", "Beat"].forEach((k, i) => leaving.push(T(k, 60 + i, 100, 400)));+ const lv2 = autoCues(framesOf(leaving, range(0, 70)), range(0, 70), { last: 70, fps });+ ok(lv2.cues.length === 1 && lv2.skipped.exit === 3, `a sinking exit's remnants ("Beat" for 1 frame) are exit steps, not reads (${lv2.skipped.exit})`);+ // RED (launch template): a sinking line drops behind its clip glyph by glyph, short letters first, so+ // "And" leaves "A d" (the n gone below the edge first). The remnant is not a substring of "And", but its+ // letters are, in order, in the same place: an exit step, not a 1-frame read+ const sink: R[] = []; for (let f = 0; f < 60; f++) sink.push(T("And it shows", f, 100, 400)); sink.push(T("And", 60, 100, 400));+ for (const f of [61, 62]) sink.push(T("A", f, 100, 400), T("d", f, 140, 400));+ const gl = autoCues(framesOf(sink, range(0, 70)), range(0, 70), { last: 70, fps });+ ok(gl.cues.length === 1 && gl.cues[0].text === "And it shows", `RED: glyphs left by a sinking word ("A d") are an exit step (${gl.cues.map((c: { text: string }) => c.text).join(" | ")})`);+ // but a different text that only shares letters with what was there is still a read+ const swap: R[] = []; for (let f = 0; f < 60; f++) swap.push(T("And it shows", f, 100, 400)); for (let f = 60; f < 62; f++) swap.push(T("dish", f, 100, 400));+ ok(autoCues(framesOf(swap, range(0, 70)), range(0, 70), { last: 70, fps }).cues.some((c: { text: string }) => c.text === "dish"), "a new short word in the same place is still a read, not an exit");+ // the edge: held cuts fail, a pan across the edge does not+ const cutRec = (f: number, x0: number) => ({ kind: "text", label: "Beat 3: one line", frame: f, x0, y0: 400, x1: x0 + 800, y1: 460 });+ ok(edgeCuts(range(0, 17).map((f) => cutRec(f, 1500 - f * 20)), range(0, 30))[0].fail === false, "a line sliding across the edge with the camera is a pan, not a fault");+ ok(edgeCuts(range(0, 30).map((f) => cutRec(f, 1500)), range(0, 30))[0].fail === true, "NEGATIVE: a line sliced by the edge and left there (the 196-frame cut) fails");+ ok(edgeCuts([cutRec(0, 1500), cutRec(1, 1500)], range(0, 30))[0].fail === false && edgeCuts([0, 1, 2].map((f) => cutRec(f, 1500)), range(0, 30))[0].fail, "held means 3 checked frames in a row, unmoved");+ const fl = readingFloor([{ from: 0, to: 90, text: "one two three four" }, { from: 30, to: 60, text: "five" }], fps);+ ok(Math.abs(fl.floorS - 1.7) < 1e-9 && Math.abs(fl.spareS - 2.1) < 1e-9, `reading floor: union of the needs (${fl.floorS} s), spare = time beyond them (${fl.spareS.toFixed(2)} s)`);++ // ---- layout (C1, C2, C4, T9)+ const lay = (recs: R[], n = 30, exemptRanges?: unknown) => layoutFindings(framesOf(range(0, n).flatMap((f) => recs.map((r) => ({ ...r, frame: f }))), range(0, n)), range(0, n), { W, H, fps, exemptRanges });+ const corner = ["Kestrel Live", "May 03", "Santiago", "The Old Mill", "Reserve a Spot!", "www.example.com", "Sponsors", "Nordic"].map((s, i) => T(s, 0, 60 + (i % 2) * 260, 60 + Math.floor(i / 2) * 90, 28));+ const cf = lay(corner);+ ok(cf.some((x: { rule: string }) => x.rule === "density") && cf.some((x: { msg: string }) => /packed into/.test(x.msg)), `NEGATIVE: the v3 end card, eight items in one corner, fails density (${cf.map((x: { msg: string }) => x.msg).join(" | ").slice(0, 160)})`);+ const stack = ["Kestrel Live", "May 03", "Santiago", "Reserve a Spot!", "www.example.com"].map((s, i) => { const t = T(s, 0, 0, 200 + i * 150, 48); const w = t.x1 - t.x0; return { ...t, x0: 960 - w / 2, x1: 960 + w / 2 }; });+ ok(lay(stack).some((x: { rule: string }) => x.rule === "centred stack"), "NEGATIVE: five lines centred on one axis fail as a centred stack");+ const grid = [T("Kestrel Live", 0, 150, 150, 64), T("May 3, Santiago ", 0, 150, 400, 44), T("Reserve a Spot!", 0, 1400, 400, 44), T("Sponsors", 0, 150, 800, 38)];+ ok(lay(grid).length === 0, "the approved asymmetric card (lockup, event lines, CTA right, sponsors foot) passes");+ const close = [BOX("bubble", 0, 600, 300, 1300, 500), BOX("dots", 0, 900, 520, 1000, 560)];+ ok(lay(close).some((x: { rule: string }) => x.rule === "gap"), "NEGATIVE: the '?' dots 20 px under the bubble fail the 3% gap");+ ok(lay([BOX("bubble", 0, 600, 300, 1300, 500), BOX("dots", 0, 900, 600, 1000, 640)]).length === 0, "the dots moved 100 px down pass");+ ok(lay([T("Line over line", 0, 100, 100, 60), T("Another text", 0, 140, 110, 60)]).some((x: { rule: string }) => x.rule === "text over text"), "NEGATIVE: two texts on top of each other fail");+ ok(lay([BOX("card", 0, 400, 400, 900, 700), T("crossing the card edge", 0, 700, 500, 40)]).some((x: { rule: string }) => x.rule === "text over an edge"), "NEGATIVE: text running over a card's edge fails");+ ok(lay([BOX("card", 0, 400, 400, 1500, 700), T("inside", 0, 500, 500, 40)]).length === 0, "text inside its card passes");+ ok(lay(corner, 10).length === 0, "a layout held under 0.5 s (a passing move) is not judged");+ ok(lay(corner, 30, [[0, 30, "the joke is the wall of text"]]).length === 0, "a declared layoutExempt range with a reason is not judged");+ ok(rectGap({ x0: 0, y0: 0, x1: 10, y1: 10 }, { x0: 13, y0: 14, x1: 20, y1: 20 }) === 5, "rectGap is the edge-to-edge distance");++ // ---- the last second (T10), the end card (S9), heads (C5), fonts (T8)+ const endRecs = framesOf(range(270, 300).map((f) => T("Reserve a Spot!", f, 1500, 900, 14)), range(0, 300));+ ok(endSizeFindings(endRecs, range(0, 300), { W, H, fps, durationFrames: 300 }).length === 1, "NEGATIVE: a 14 px CTA in the last second fails");+ ok(endSizeFindings(framesOf(range(270, 300).map((f) => T("Reserve a Spot!", f, 1500, 900, 44)), range(0, 300)), range(0, 300), { W, H, fps, durationFrames: 300 }).length === 0, "a 44 px CTA passes");+ const card = (fs: number[]) => framesOf(fs.map((f) => BOX("end card", f, 50, 50, 1870, 1030)), range(0, 300));+ ok(!endCardRuns(card([...range(100, 150), ...range(200, 300)]), range(0, 300)).ok, "NEGATIVE: card, stinger, card (two landings) fails");+ ok(endCardRuns(card(range(200, 300)), range(0, 300)).ok, "one landing passes");+ const heads = (hs: number[]) => framesOf(hs.map((h, i) => BOX(`head:speakers/${["ines", "tomas", "priya"][i]}`, i, 0, 0, h * 0.8, h)), range(0, 3));+ const hs = headSpread(heads([370, 270, 190]), range(0, 3));+ ok(hs.length === 1 && !hs[0].ok && hs[0].people.length === 3, "NEGATIVE: heads of 370, 270 and 190 px in one sequence fail");+ ok(headSpread(heads([300, 290, 305]), range(0, 3))[0].ok, "heads within 10% pass");+ const fonts = fontReport(framesOf([T("Speaker", 0, 0, 0, 40, { family: "Helvetica" }), T("Title", 0, 0, 200, 40, { family: "Acid Grotesk" })], [0]), [0], { fonts: ["Acid Grotesk"], standIns: { "Acid Grotesk": "Helvetica" } });+ ok(fonts.find((f: { family: string }) => f.family === "Helvetica")?.standFor === "Acid Grotesk" && !fonts.find((f: { family: string }) => f.family === "Acid Grotesk")?.offBrand, "a stand-in face is named with the brand face it stands in for");+ ok(fontReport(framesOf([T("x", 0, 0, 0, 40, { family: "Comic Sans" })], [0]), [0], { fonts: ["Acid Grotesk"] })[0].offBrand, "NEGATIVE: a face outside the brand's is flagged");+ ok(RULES.endPx === 28 && RULES.gapShare === 0.03 && RULES.maxBlocks === 7, "the numbers: 28 px at the end, 3% gaps, at most 7 blocks");+ // ---- M13: one label drawn twice on a frame (two "Learn more" buttons, setType's per-character fills)+ const twin = (f: number, x0: number) => ({ kind: "text", label: "Learn more", frame: f, x0, y0: 400, x1: x0 + 300, y1: 440 });+ const two = edgeCuts(range(0, 6).flatMap((f) => [twin(f, 1700), twin(f, 200 + f * 37)]), range(0, 30));+ ok(two[0].fail === true && two[0].held === 6, `NEGATIVE M13: a cut held 6 frames is found while a second record with the same label moves (held ${two[0].held})`);+ ok(edgeCuts(range(0, 6).flatMap((f) => [twin(f, 1700 - f * 20), twin(f, 200 + f * 37)]), range(0, 30))[0].fail === false, "M13 two same-label records that both move are not a held cut");+ // ---- M2/M3: the frames a check looks at. A bad --every, --from or --to is refused, never a check of frame 0 alone+ const bad = (o: Record<string, unknown>, N = 100) => { try { checkedFrames(o, N); return ""; } catch (e) { return String((e as Error).message); } };+ ok(checkedFrames({ every: 1 }, 5).join(",") === "0,1,2,3,4" && checkedFrames({ every: 2, from: 1, to: 6 }, 10).join(",") === "1,3,5", "frames: every, from, to");+ ok(/--every/.test(bad({ every: NaN })), "NEGATIVE M2: --every abc (NaN) is refused, never a check of frame 0 alone");+ ok(/--every/.test(bad({ every: 0 })) && /--every/.test(bad({ every: 1.5 })) && /--every/.test(bad({ every: -2 })), "NEGATIVE M3: --every 0 (a loop with no end), 1.5 or -2 is refused");+ ok(/--from/.test(bad({ every: 1, from: 120 })) && /--from/.test(bad({ every: 1, from: NaN })), "NEGATIVE M3: --from past the end, or not a number, is refused (0 frames checked proves nothing)");+ ok(/--to/.test(bad({ every: 1, from: 10, to: 10 })) && /--to/.test(bad({ every: 1, to: NaN })), "NEGATIVE M3: --to at or before --from, or not a number, is refused");+};diff --git a/skills/anidoodle/engine/test/gaterules.test.ts b/skills/anidoodle/engine/test/gaterules.test.tsnew file mode 100644index 0000000..4ad8818--- /dev/null+++ b/skills/anidoodle/engine/test/gaterules.test.ts@@ -0,0 +1,39 @@+// GATE RULES TESTS. Check 5 (3D) decided as a pure function, with the case that used to pass without+// looking: a 3D film whose rig registers nothing for checks3d printed a note, counted nothing, and the+// gate said PASS without one 3D check having run (H4).+// @ts-ignore: a plain ES module shared with the tools+import { deadAirVerdict, gripFindings, threeDVerdict } from "../tools/gaterules.mjs";++export const name = "gaterules";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const none = threeDVerdict({ recs: [], sampled: 48, fill: 0, meta: {} });+ ok(none.counted && !none.ok, `NEGATIVE H4: a 3D film that registers nothing to check FAILS check 5 (got ${JSON.stringify(none)})`);+ const declared = threeDVerdict({ recs: [], sampled: 48, fill: 0, meta: { checks: { none: { "3d": "a product turntable: no characters, nothing held" } } } });+ ok(!declared.counted && /turntable/.test(declared.detail), "H4 a 3D film that declares why there is nothing to check (meta.checks.none['3d']) is listed with its reason, not failed");+ const clean = threeDVerdict({ recs: [{ frame: 0, findings: [], grips: [{ name: "cup", x: 1, y: 1 }] }], sampled: 1, fill: 0, meta: {} });+ ok(clean.counted && clean.ok, "H4 frames checked with no finding pass");+ const bad = threeDVerdict({ recs: [{ frame: 3, findings: [{ frame: 3, kind: "grip", where: "hand", detail: "through the handle" }], grips: [] }], sampled: 1, fill: 0, meta: {} });+ ok(bad.counted && !bad.ok && /through the handle/.test(bad.detail), "a finding fails, and is printed");+ // ---- L6: still --grips labelled every crop with every grip finding on the frame+ const fs = [+ { frame: 5, kind: "grip-gap", where: "chef holding cup", detail: "floats" },+ { frame: 5, kind: "grip-through-hand", where: "waiter holding tray", detail: "through" },+ { frame: 5, kind: "grip-prop-in-holder", where: "chef / cup at (0,1,0)", detail: "6 points" },+ { frame: 5, kind: "self", where: "chef: arm into its own body", detail: "x" },+ ];+ const cup = gripFindings({ name: "chef/cup" }, fs).map((x: { kind: string }) => x.kind).join(","), tray = gripFindings({ name: "waiter/tray" }, fs).map((x: { kind: string }) => x.kind).join(",");+ ok(cup === "grip-gap,grip-prop-in-holder" && tray === "grip-through-hand", `NEGATIVE L6: each grip crop carries only its own findings (cup: ${cup}; tray: ${tray})`);+ ok(gripFindings({ name: "a/b/c" }, [{ frame: 0, kind: "grip-open", where: "a/b holding c", detail: "" }]).length === 1, "L6 a holder name with a slash in it still matches its grip");++ // CHECK 3, DEAD AIR: a film made before a check existed (a frozen, published film) may declare one dead-air+ // row in meta.checks.none with its reason. The row is then listed with the reason AND its findings, never+ // counted as a pass that looked; a film with no declaration still FAILS; a passing row is unaffected.+ const stillRow = deadAirVerdict("gate:identical", false, "1, 2, 3", {});+ ok(stillRow.counted && !stillRow.ok, "NEGATIVE: identical frames with no declaration FAIL the gate");+ const frozen = deadAirVerdict("gate:identical", false, "1, 2, 3", { checks: { none: { "gate:identical": "frozen source of a published film" } } });+ ok(!frozen.counted && /published/.test(frozen.detail) && /1, 2, 3/.test(frozen.detail), "a declared dead-air row is listed with its reason and its findings, not counted");+ ok(deadAirVerdict("gate:identical", false, "1", { checks: { none: { "gate:identical": " " } } }).counted, "NEGATIVE: an empty reason is no declaration");+ ok(deadAirVerdict("gate:still", false, "4-19", { checks: { none: { "gate:identical": "x" } } }).counted, "NEGATIVE: a declaration covers only the row it names");+ const fine = deadAirVerdict("gate:still", true, "none", { checks: { none: { "gate:still": "x" } } });+ ok(fine.counted && fine.ok, "a row that passes is a pass whether or not it is declared");+};diff --git a/skills/anidoodle/engine/test/inkCardByline.test.ts b/skills/anidoodle/engine/test/inkCardByline.test.tsnew file mode 100644index 0000000..bcb0b16--- /dev/null+++ b/skills/anidoodle/engine/test/inkCardByline.test.ts@@ -0,0 +1,37 @@+// AN ANSWER CARD'S BYLINE, DOT AND WORDS TOGETHER. The card's byline is a dot and a line of words. The+// launch template leaves the words out once the thread scrolls them under its window's top, and a fresh+// critic saw the dot stay behind on its own (9:16, the lean before the word page). The dot belongs to+// the words: no words, no dot, and a byline fading out (labelA) takes both with it.+// node tools/test.mjs inkCardByline+import { inkCard, TEXT_SHOWN } from "../src/canvas-core/launchKit";+import type { Ctx, Layer } from "../src/canvas-core/core";+import { FakeCanvas } from "./fakeCanvas";++export const name = "inkCard: the byline's dot goes with its words";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const raw = new FakeCanvas(400, 400).ctx;+ const marks: { kind: string; alpha: number }[] = [];+ const ctx = new Proxy(raw, {+ get(t, k) {+ if (k === "arc") return () => marks.push({ kind: "dot", alpha: t.globalAlpha });+ if (k === "fillText") return () => marks.push({ kind: "words", alpha: t.globalAlpha });+ const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v;+ },+ set(t, k, v) { return Reflect.set(t, k, v); },+ }) as unknown as Ctx;+ const art = { canvas: new FakeCanvas(10, 10) } as unknown as Layer, d = { t0: 0, land: 10, full: 30 };+ const shown = (label: string, labelA?: number) => { marks.length = 0; (inkCard as (...a: unknown[]) => void)(ctx, 20, 60, 200, 100, d, art, label, undefined, undefined, () => 1, labelA); return marks.filter((m) => m.alpha > 0.001).map((m) => m.kind); };+ const full = shown("print · drawn in code");+ ok(full.includes("dot") && full.includes("words"), `a card with a byline draws its dot and its words (${full.join(", ")})`);+ ok(!shown("").includes("dot"), "RED: a card whose byline is left out draws no dot either");+ // a surface that withholds the words (a travel's zone fade) says so, and the dot stays out with them+ const surface = (share: number) => new Proxy(ctx as object, { get(t, k) { if (k === "fillText") return () => { (t as Record<symbol, number>)[TEXT_SHOWN] = share; }; const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v; }, set(t, k, v) { return Reflect.set(t, k, v); } }) as unknown as Ctx;+ marks.length = 0; (inkCard as (...a: unknown[]) => void)(surface(0), 20, 60, 200, 100, d, art, "print · drawn in code", undefined, undefined, () => 1);+ ok(!marks.some((m) => m.kind === "dot"), `RED: words withheld by the surface (a zone fade) take the dot with them (${marks.map((m) => m.kind).join(", ") || "nothing"})`);+ // and words the surface draws at 40 % (fading toward a zone) take the dot down to 40 % with them+ marks.length = 0; (inkCard as (...a: unknown[]) => void)(surface(0.4), 20, 60, 200, 100, d, art, "print · drawn in code", undefined, undefined, () => 1);+ const dot = marks.find((m) => m.kind === "dot");+ ok(!!dot && Math.abs(dot.alpha - 0.4) < 1e-6, `RED: words faded to 40 % by the surface fade their dot to 40 % too (dot at ${dot ? dot.alpha.toFixed(2) : "none"})`);+ const faded = shown("print · drawn in code", 0);+ ok(!faded.includes("dot") && !faded.includes("words"), `RED: a byline faded to nothing takes its dot with it (${faded.join(", ") || "nothing"})`);+};diff --git a/skills/anidoodle/engine/test/instrument.test.ts b/skills/anidoodle/engine/test/instrument.test.tsnew file mode 100644index 0000000..aaf4b71--- /dev/null+++ b/skills/anidoodle/engine/test/instrument.test.ts@@ -0,0 +1,36 @@+// LAYER INSTRUMENT TESTS (hosts/instrument.ts), driven with a stand-in canvas. Each case is one way the+// instruments passed without looking:+// L1 a brand colour declared short ("#c41") or as hsl() never matched a fill, so translucent passed+// L2 type drawn into an offscreen layer is not kept sharp by the blur mask; the mask now counts those+// layers (layerType) so the render can say so instead of claiming every line was kept sharp+import { brandHex, instruments } from "../src/hosts/instrument";+import { FakeCanvas, installFakeCanvas } from "./fakeCanvas";++export const name = "instrument";+export const run = (ok: (cond: boolean, label: string) => void) => {+ installFakeCanvas();+ const mk = (draw: (ctx: FakeCanvas["ctx"], cache: Map<string, unknown>, f: number) => void) => {+ const canvas = new FakeCanvas(320, 180), cache = new Map<string, unknown>();+ const inst = instruments({ ctx: () => canvas.ctx as never, images: () => new Set(), draw: (f) => { canvas.ctx.reset(); draw(canvas.ctx, cache, f); }, read: () => canvas.px, clearCache: () => cache.clear() });+ return inst;+ };+ // ---- L1+ ok(brandHex("#c41") === "#cc4411" && brandHex("#CC4411") === "#cc4411" && brandHex("#cc4411ff") === "#cc4411", "L1 #rgb, #RRGGBB and #rrggbbaa read as the canvas's #rrggbb");+ ok(brandHex("rgb(204, 68, 17)") === "#cc4411" && brandHex("hsl(16.36, 84.6%, 43.33%)") === "#cc4411", `L1 rgb() and hsl() read too (hsl gave ${brandHex("hsl(16.36, 84.6%, 43.33%)")})`);+ ok(brandHex("olive-ish") === null && brandHex(7) === null, "L1 a colour that cannot be read is null, never compared as written");+ const fills = mk((ctx) => { ctx.globalAlpha = 0.5; ctx.fillStyle = "#cc4411"; ctx.fillRect(0, 0, 50, 50); });+ const short = fills.layers([0], ["#c41"]), hsl = fills.layers([0], ["hsl(16.36, 84.6%, 43.33%)"]);+ ok(short[0].translucent.length === 1 && hsl[0].translucent.length === 1, `NEGATIVE L1: a half-alpha fill in the brand colour is found when the colour is declared #c41 or hsl() (${short[0].translucent.length}, ${hsl[0].translucent.length})`);+ const bad = fills.layers([0], ["olive mud"]);+ ok(bad[0].unread?.[0] === "olive mud", "NEGATIVE L1: an unreadable brand colour is returned as unread (layerscan fails translucent on it), never silently ignored");+ // ---- L2+ const sheet = mk((ctx, cache) => {+ let L = cache.get("sheet") as FakeCanvas | undefined;+ if (!L) { L = new FakeCanvas(200, 60); L.ctx.font = "30px Sans"; L.ctx.fillText("On a sheet", 5, 40); cache.set("sheet", L); }+ ctx.fillRect(0, 0, 320, 180); ctx.drawImage(L, 20, 20); ctx.font = "20px Sans"; ctx.fillText("Own", 20, 150);+ });+ sheet.layers([0]); // builds the sheet's cache before any blur, as a real render's warm-up does+ const k = sheet.sharpLayers(0);+ ok(!!k && (k as { layerType?: number }).layerType === 1, `NEGATIVE L2: the blur mask counts the layer holding type it cannot keep sharp (layerType ${(k as { layerType?: number } | null)?.layerType})`);+ ok(!!k && k.count > 0, "L2 the frame's own type is still masked sharp");+};diff --git a/skills/anidoodle/engine/test/irisRim.test.ts b/skills/anidoodle/engine/test/irisRim.test.tsnew file mode 100644index 0000000..f9c4395--- /dev/null+++ b/skills/anidoodle/engine/test/irisRim.test.ts@@ -0,0 +1,29 @@+// THE CLEAN IRIS HAS AN EDGE. The clean look's answer card opens as an iris: a circle growing from where the+// drop landed, the answer inside it. With nothing but the answer's own ground to mark it, a fresh critic saw+// a pale disc on a cream card, "the chart fading in, not an iris opening" (cc1-3; on 9:16 the card is small+// and the disc was faint at speed). While it opens, the iris now draws its rim in the drop's colour, solid,+// so the drop visibly opens into the ring; once open, the card has no rim.+// node tools/test.mjs irisRim+import { CHAT_GEOM, inkCard, type ChatGeom } from "../src/canvas-core/launchKit";+import type { Ctx, Layer } from "../src/canvas-core/core";+import { FakeCanvas } from "./fakeCanvas";++export const name = "the clean iris has an edge while it opens";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const raw = new FakeCanvas(400, 400).ctx, strokes: { style: string; alpha: number }[] = [];+ const ctx = new Proxy(raw, {+ get(t, k) { if (k === "stroke") return () => strokes.push({ style: String(t.strokeStyle), alpha: t.globalAlpha }); const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v; },+ set(t, k, v) { return Reflect.set(t, k, v); },+ }) as unknown as Ctx;+ const art = { canvas: new FakeCanvas(10, 10) } as unknown as Layer, d = { t0: 0, land: 10, full: 30 };+ const g: ChatGeom = { ...CHAT_GEOM, iris: true, drop: "#2f54eb" };+ const at = (grow: number) => { strokes.length = 0; (inkCard as (...a: unknown[]) => void)(ctx, 20, 60, 200, 20, d, art, "", undefined, g, () => grow); return strokes.filter((s) => s.style.toLowerCase() === "#2f54eb"); };+ const opening = at(0.5);+ ok(opening.length > 0 && opening.every((s) => s.alpha === 1), `RED: half open, the iris draws a solid rim in the drop's colour (${opening.length} stroke(s))`);+ ok(at(1).length === 0, "open, the card has no rim");+ // (once the ring is wider than the card it showed as four blue arcs at the corners, a fresh critic's cc3-2)+ ok(at(0.9).length === 0, "RED: a ring wider than the card is not drawn (no arcs left in its corners)");+ const drawn = { ...CHAT_GEOM, drop: "#2f54eb" } as ChatGeom; strokes.length = 0;+ (inkCard as (...a: unknown[]) => void)(ctx, 20, 60, 200, 20, d, art, "", undefined, drawn, () => 0.5);+ ok(!strokes.some((s) => s.style.toLowerCase() === "#2f54eb"), "the drawn look's ink bloom is unchanged (no rim)");+};diff --git a/skills/anidoodle/engine/test/lastWordsFlight.test.ts b/skills/anidoodle/engine/test/lastWordsFlight.test.tsnew file mode 100644index 0000000..0853580--- /dev/null+++ b/skills/anidoodle/engine/test/lastWordsFlight.test.ts@@ -0,0 +1,22 @@+// THE LAST WORDS STAY INTO THE DROP'S FLIGHT. With the motif, the last split beat's words sank before the drop+// left its bead, and the drop then flew for 0.47 s: on a phone frame the clean scaffold's small product window+// stood alone for 0.53 s, six text blocks in a quarter of the frame (framecheck density, frames 929 to 961,+// over its 0.5 s). The words now finish sinking halfway through the flight, still gone before the drop lands+// and the end card blooms (a fresh critic once saw the bloom eat a word mid-letter).+// node tools/test.mjs lastWordsFlight+import { makeLaunchFilm, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import { launchExampleClean } from "../src/canvas-core/launchExampleClean";+import type { ProductUI } from "../src/canvas-core/productUI";++export const name = "the last words stay into the drop's flight";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const ui: ProductUI = { title: "TODO", action: "TODO action", before: { items: [{ id: "a", label: "TODO first item" }, { id: "b", label: "TODO second item" }] }, after: { items: [{ id: "b", label: "TODO second item", done: true, accent: true }, { id: "a", label: "TODO first item", tag: "TODO", done: true }] } };+ const f = makeLaunchFilm({ title: "TODO Product", preset: "clean", fps: 60, asks: [{ kind: "ui", ui, prompt: "TODO what a user asks" }, { kind: "ui", ui, split: [{ text: "TODO the feature,", style: "ink", color: "#15161a" }, { text: "in five words.", style: "ink", color: "#2f54eb" }] }], words: [[{ text: "TODO CLAIM.", style: "ink", color: "#15161a" }]], tagline: "t", install: ["npm i x"], bpm: 90, claimBar: 6, score: null, motion: { temperament: "calm", brandColors: ["#2f54eb"] } });+ for (const [id, film] of [["scaffold", f], ["clean example", launchExampleClean as LaunchFilm]] as const) for (const sh of ["16x9", "9x16"]) {+ const w = (film.reshape(sh) as LaunchFilm).grammar?.lastWords;+ if (!w) { ok(false, `${id} ${sh}: the film exposes its last words' timing`); continue; }+ const [a, b] = w.flight, half = a + Math.floor((b - a) / 2);+ ok(w.gone >= half - 1, `RED ${id} ${sh}: the words are still leaving halfway through the flight (gone at ${w.gone}, flight ${a}-${b})`);+ ok(w.gone < b, `${id} ${sh}: and gone before the drop lands (${w.gone} < ${b})`);+ }+};diff --git a/skills/anidoodle/engine/test/launchGrammar.test.ts b/skills/anidoodle/engine/test/launchGrammar.test.tsnew file mode 100644index 0000000..dd86d02--- /dev/null+++ b/skills/anidoodle/engine/test/launchGrammar.test.ts@@ -0,0 +1,81 @@+// LAUNCH TEMPLATE GRAMMAR. The moves both presets are built from, checked as data on the two worked+// examples (launchExample, drawn; launchExampleClean, clean) in 16:9 and 9:16, so a film copied from the+// template passes ship's motion and layer scans by construction. Each line is a fix a ship run or a fresh+// critic forced (reports/TEMPLATE2.md):+// the drawn preset's word pages are places the camera travels to, never an ink bloom swapped in place+// (seven slide cuts in sixteen seconds on the drawn example);+// Generate is pressed only once the hook's composer has docked (a button pressed on the move);+// frame 0, the thumbnail, shows the first prompt typed to a whole word ("a lighthouse at s");+// the thread scrolls once per ask, at most three quarters of half the speed ceiling (type at 150 px a frame);+// the end card's bloom opens no faster than the brand's temperament allows (its rim at 200 px a frame);+// a wide frame's travels alternate (down, up, down), never one direction twice in a row;+// on a tall frame a word page's lines are gone before the travel's edge reaches them;+// a product's drop swells beside its action, never on the button's word.+// node tools/test.mjs launchGrammar+import { launchExample } from "../src/canvas-core/launchExample";+import { launchExampleClean } from "../src/canvas-core/launchExampleClean";+import { typedAt } from "../src/canvas-core/launchKit";+import { TEMPERAMENTS } from "../src/canvas-core/motionKit";+import { speedCeiling } from "../src/canvas-core/seams";+import { uiActionRect, type ProductUI } from "../src/canvas-core/productUI";+import { sinkOf, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import { typeExit } from "../src/canvas-core/motionKit";++export const name = "launch template grammar (both presets, 16:9 and 9:16)";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const films: [string, LaunchFilm][] = [];+ for (const [id, f] of [["drawn", launchExample], ["clean", launchExampleClean]] as const) for (const sh of ["16x9", "9x16"]) films.push([`${id} ${sh}`, (f as LaunchFilm).reshape(sh)]);+ const TRV = 42, glide = (q: number) => { const c = Math.min(1, Math.max(0, q)), r = 0.1, v = 1 / (1 - r); return c < r ? (v * c * c) / (2 * r) : c > 1 - r ? 1 - (v * (1 - c) * (1 - c)) / (2 * r) : v * (c - r / 2); };+ for (const [id, film] of films) {+ const g = (film as Partial<LaunchFilm>).grammar, W = film.layout.W, T = film.timing;+ // frame 0 is a whole word+ const prompts = id.startsWith("drawn") ? ["a lighthouse at sunset, as a print"] : ["match every receipt from September"];+ const typed = typedAt(prompts[0], 0, T[0].times), next = prompts[0][typed.length];+ ok(typed.length > 0 && (next === " " || next === undefined), `RED ${id}: frame 0 shows "${typed}", a whole word`);+ // the drawn preset travels into and out of its word pages; Generate waits for the dock+ if (id.startsWith("drawn")) {+ ok(T[1].tin > 0 && (!g || (g.travels.some((t) => t.seam === "page:0") && g.travels.some((t) => t.seam === "ask:1"))), `RED ${id}: the word page is reached by a travel and left by one (into ask 1 over ${T[1].tin} frames)`);+ ok(T[0].down >= T[0].b - 8 + 30, `RED ${id}: Generate goes down at ${T[0].down}, after the dock lands at ${T[0].b - 8 + 30}`);+ }+ ok(!!g, `RED ${id}: the film exposes its grammar`);+ if (!g) continue;+ // one scroll per ask, under the pace+ const cap = 0.75 * 0.5 * speedCeiling(W, 30);+ ok(g.scrolls.every((q) => (1.12 * q.d) / q.len <= cap + 1e-9 && q.len >= 30), `RED ${id}: every thread scroll peaks at or under ${cap.toFixed(1)} px a frame (${g.scrolls.map((q) => `${Math.round(q.d)} px in ${q.len}`).join(", ") || "no chat ask"})`);+ // the end bloom's rim keeps to the temperament+ const temper = TEMPERAMENTS[id.startsWith("drawn") ? "lively" : "snappy"], pace = temper.maxSpeed * speedCeiling(W, 30);+ ok(g.endBloom.radius / g.endBloom.frames <= 0.9 * pace + 1e-9, `RED ${id}: the end card's bloom opens at ${(g.endBloom.radius / g.endBloom.frames).toFixed(1)} px a frame, the ${temper.name} limit is ${pace.toFixed(1)}`);+ // and it opens from the landed drop: the drop arrives at the dot's own size, never swelling into a disc+ ok(film.seams.every((m) => m.into.r <= 0.06 * g.endBloom.radius), `${id}: the drop lands at the dot's size (${film.seams.map((m) => Math.round(m.into.r)).join(", ")} px; the bloom ends at ${Math.round(g.endBloom.radius)})`);+ // travels turn on a wide frame+ if (W > film.layout.H) ok(g.travels.every((t, j) => j === 0 || t.ax[0] !== g.travels[j - 1].ax[0] || t.ax[1] !== g.travels[j - 1].ax[1]), `RED ${id}: no two travels in a row go the same way (${g.travels.map((t) => (t.ax[1] > 0 ? "down" : t.ax[1] < 0 ? "up" : "sideways")).join(", ")})`);+ // on a tall frame the page's lines are gone before the travel's edge reaches them+ if (W < film.layout.H) for (const p of g.pages) {+ const L = film.layout, at = L.type.at!, x0 = at[0] - L.type.maxW / 2, left = at[0] + (x0 - at[0]) * 1.03, ax = Math.abs(g.travels.find((t) => t.seam === `ask:${p.i + 1}`)!.ax[0]);+ const gone = p.out + 18 - 120; // frames into the travel out when the last line has sunk (SINK 18, TYPE 120)+ ok(glide(gone / TRV) * ax <= left, `RED ${id}: page ${p.i}'s lines are gone ${gone} frames into the travel, when its edge has moved ${Math.round(glide(gone / TRV) * ax)} px of the ${Math.round(left)} px before them`);+ }+ }+ // after a product's click the pointer rests above its window, never on a row's figure (a fresh critic saw it+ // settle on "$1,208" on 9:16); the arrow's glyph is 29 units tall at its scale+ for (const sh of ["16x9", "9x16"]) {+ const g = ((launchExampleClean as LaunchFilm).reshape(sh) as Partial<LaunchFilm>).grammar as (LaunchFilm["grammar"] & { rests?: { i: number; tip: [number, number]; win: { x: number; y: number; w: number; h: number }; s: number }[] }) | undefined;+ const rests = g?.rests ?? [];+ ok(rests.length > 0 && rests.every((q) => q.tip[1] + 29 * q.s <= q.win.y), `RED clean ${sh}: after each click the pointer rests clear above the product window (${rests.map((q) => `ask ${q.i}: arrow ends ${Math.round(q.tip[1] + 29 * q.s)}, window starts ${Math.round(q.win.y)}`).join("; ") || "no rest recorded"})`);+ }+ // a page's lines sink one after another with no still frame between them (two lines back to back left+ // the gate an identical pair at 60 fps): over a 0.6 s sink at 60 fps, every frame moves some line+ for (const nL of [2, 3]) {+ const N = 36, low: number[] = [];+ for (let f = 1; f <= N; f++) { let m = 0; for (let j = 0; j < nL; j++) m = Math.max(m, Math.abs(typeExit(sinkOf(f / N, j, nL)) - typeExit(sinkOf((f - 1) / N, j, nL)))); if (m < 0.004 && f > 12) low.push(f); } // (its first 6 frames at 30 fps are an ease-in from rest, declared with the page's hold)+ ok(!low.length && [...Array(nL).keys()].every((j) => sinkOf(1, j, nL) === 1), `RED ${nL} lines: every frame of the sink past its declared start moves a line, and all are gone at its end (still at ${low.join(", ") || "none"})`);+ }+ // the clean example's last ask is a product screen: its drop swells beside the action, clear of its word+ // (the drop's centre plus its radius stays left of the button at any push the split panel can have, 1 to 1.13)+ for (const sh of ["16x9", "9x16"]) {+ const f = (launchExampleClean as LaunchFilm).reshape(sh), g = (f as Partial<LaunchFilm>).grammar, L = f.layout;+ const ui = { title: "Tally", nav: ["Reports", "Books"], action: "Explain", before: { items: [0, 1, 2, 3].map((i) => ({ id: `${i}`, label: "x", value: "$1", bar: 0.5 })) }, after: { items: [0, 1, 2, 3].map((i) => ({ id: `${i}`, label: "x", value: "$1", bar: 0.5 })) } } as ProductUI;+ const r = L.split.ui, a = uiActionRect(r, ui, L.phone ? 32 : 18), cx = r.x + r.w / 2, left = Math.min(...[1, 1.13].map((z) => cx + (a.x - cx) * z)), rad = 30 * L.k;+ ok(!!g && g.lift[0] + rad <= left, `RED clean ${sh}: the drop swells beside Explain (its edge at ${g ? Math.round(g.lift[0] + rad) : "?"}, the button starts at ${Math.round(left)})`);+ }+};diff --git a/skills/anidoodle/engine/test/launchLayout.test.ts b/skills/anidoodle/engine/test/launchLayout.test.tsindex 8cbbc94..c2cf83c 100644--- a/skills/anidoodle/engine/test/launchLayout.test.ts+++ b/skills/anidoodle/engine/test/launchLayout.test.ts@@ -4,6 +4,7 @@import { CHAT_GEOM, chatGeom, CHAT } from "../src/canvas-core/launchKit";import { launchLayout, SHAPES, MIN_PX, PHONE_SAFE, estWidth, installRows, monoWidth, parseShapes, type Shape } from "../src/canvas-core/launchLayout";import { makeLaunchFilm, fitWords } from "../src/canvas-core/launchTemplate";+import { measure } from "../src/canvas-core/kinetic"; // the drawn corner mark, written on: the wider of the two presets' marksimport type { Film } from "../src/canvas-core/film";type R = { x: number; y: number; w: number; h: number };@@ -26,6 +27,10 @@ export const run = (ok: (cond: boolean, label: string) => void) => {ok(L.thread.cardX >= c.CHAT.x && L.thread.cardX + L.thread.card <= c.CHAT.x + c.CHAT.w && L.thread.card > 0, `${shape}: the answer card (${L.thread.card} px) sits inside the thread`);ok(L.thread.bubbles.every((ls) => ls.length <= 3), `${shape}: prompts wrap to at most 3 bubble lines (${L.thread.bubbles.map((b) => b.length).join(", ")})`);ok(L.bug.y > c.CHAT.y + c.CHAT.h, `${shape}: the corner mark sits below the chat window, never on it`);+ // and clear of it, not touching its corner (a fresh critic saw them kiss on 16:9 and 9:16, frame 0): beside+ // the window by 16 px or more, or under it by 24 px plus what the hook's creep about the window's centre adds (2 %, 4 % on 9:16)+ { const bw = measure("Your Product", L.bug.px), side = L.bug.x - bw - (c.CHAT.x + c.CHAT.w), under = L.bug.y - 0.75 * L.bug.px - (c.CHAT.y + c.CHAT.h);+ ok(side >= 16 * L.k || under >= 24 * L.k + (L.zones ? 0.04 : 0.02) * c.CHAT.h / 2, `RED ${shape}: the corner mark clears the window (${Math.round(side)} px beside it, ${Math.round(under)} px under it)`); }const pw = Math.max(...L.end.rows.map((r) => monoWidth(r.text, L.end.monoPx) + r.indent * L.end.monoPx * 0.61)) + 2 * L.end.padX;ok(pw <= L.W, `${shape}: the install panel (${pw.toFixed(0)} px at ${L.end.monoPx.toFixed(1)} px mono) fits the frame's width`);ok(L.end.titleY < L.end.taglineY && L.end.taglineY < L.end.panelY && L.end.footerY < L.stage.h, `${shape}: the end card stacks title, line, panel, footer, all in frame`);@@ -41,6 +46,7 @@ export const run = (ok: (cond: boolean, label: string) => void) => {const bugW = estWidth("Your Product", L.bug.px) * 1.2;ok(inside({ x: L.bug.x - bugW, y: L.bug.y - L.bug.px, w: bugW, h: L.bug.px * 1.3 }, S), "9x16: the corner mark sits inside the safe rectangle");const at = L.type.at!; ok(!!at && inside({ x: at[0] - L.type.maxW / 2, y: at[1] - 10, w: L.type.maxW, h: 20 }, S), "9x16: a word page's lines are centred in the safe rectangle and no wider than it");+ ok(Math.abs(E.cx - L.W / 2) < 1e-9, `RED 9x16: the end card centres on the frame (x ${E.cx.toFixed(0)}), not on the safe rectangle, which read 60 px left of the middle`);const pw0 = pw;ok(inside({ x: E.cx - Math.max(E.titleW, pw0) / 2, y: E.titleY - E.titleMax, w: Math.max(E.titleW, pw0), h: E.footerY + E.footerPx - (E.titleY - E.titleMax) }, S), "9x16: the end card (name, line, install panel, footer) sits inside the safe rectangle");}@@ -77,5 +83,13 @@ export const run = (ok: (cond: boolean, label: string) => void) => {ok((Object.keys(SHAPES) as Shape[]).every((sh) => { const x = f.reshape(sh); return (x.heroPx ?? 0) >= (x.layout.phone ? 64 : 56); }), `the first prompt is the hero: ${(Object.keys(SHAPES) as Shape[]).map((sh) => `${sh} ${f.reshape(sh).heroPx} px`).join(", ")} (>= 64 on a phone frame, 56 on 16x9)`);let long = ""; try { makeLaunchFilm({ title: "Tally", shape: "9x16", asks: [{ prompt: "a very long first prompt that goes on and on about everything it could possibly want drawn today", plate, label: "l" }], tagline: "t", install: ["npm i tally"], bpm: 90, score: null }); } catch (e) { long = (e as Error).message; }ok(/shorten it/.test(long), "a first prompt too long for a readable hook is an error, never tiny type");+ // a split beat's words are read too: up for their reading time (readS) before they sink, or the spec is an+ // error that says how to make room (the clean scaffold's defaults left "Every receipt, matched for you." up 0.45 s)+ const ui = { title: "T", nav: ["A"], action: "Go", before: { items: [{ id: "a", label: "x", value: 1 }] }, after: { items: [{ id: "a", label: "x", value: 0, done: true }] } };+ const splitSpec = (claimBar: number) => ({ title: "Tally", preset: "clean" as const, fps: 60 as const, asks: [{ kind: "ui" as const, ui, prompt: "match every receipt" }, { kind: "ui" as const, ui, split: [{ text: "Every receipt,", style: "ink" as const, color: "#111111" }, { text: "matched for you.", style: "ink" as const, color: "#2f54eb" }] }], words: [[{ text: "ASK ONCE.", style: "ink" as const, color: "#111111" }]], tagline: "t", install: ["npm i tally"], bpm: 90, askBeats: 6, typeBeats: 6, endBeats: 8, claimBar, score: null });+ let short = ""; try { makeLaunchFilm(splitSpec(4)); } catch (e) { short = (e as Error).message; }+ ok(/split words/.test(short) && /claimBar|askBeats/.test(short), `RED: split words up too short to read are an error that says how to make room ("${short.slice(0, 90)}")`);+ let roomy = ""; try { makeLaunchFilm(splitSpec(6)); } catch (e) { roomy = (e as Error).message; }+ ok(roomy === "", `a split beat with room to be read builds (${roomy.slice(0, 80) || "ok"})`);ok(wide.length === 1 && tall.length === 2, `a word page re-sets its lines for a narrow frame (16x9: ${wide.length} line, 9x16: ${tall.map((l) => l.text).join(" / ")})`);};diff --git a/skills/anidoodle/engine/test/launchSound.test.ts b/skills/anidoodle/engine/test/launchSound.test.tsindex 6f4e4ac..dc4d77c 100644--- a/skills/anidoodle/engine/test/launchSound.test.ts+++ b/skills/anidoodle/engine/test/launchSound.test.ts@@ -23,8 +23,9 @@ export const run = (ok: (cond: boolean, label: string) => void) => {const f = makeLaunchFilm(spec), cues = f.cues, at = (c: number) => Math.round(f.cut.cutOf(c));const by = (r: string) => cues.filter((c) => c.role === r);- // keys: one per character typed on screen (the first prompt is under way at frame 0: only what is typed after it)- const typed = f.timing.reduce((a, t) => a + t.times.filter((x) => x >= Math.max(0, t.tin)).length, 0);+ // keys: one per character typed on screen (the first prompt is under way at frame 0: only what is typed+ // after it; a later prompt starts as its composer travels in, and those keys are on screen and heard)+ const typed = f.timing.reduce((a, t) => a + t.times.filter((x) => x >= 0).length, 0);ok(by("key").length === typed, `a key cue for every character typed on screen (${by("key").length} of ${typed})`);const spaces = prompts.join("").split("").filter((c) => c === " ").length;ok(by("key").filter((c) => c.variant === "space").length <= spaces && by("key").some((c) => c.variant === "space"), "the space bar has its own sound");diff --git a/skills/anidoodle/engine/test/linkedEngine.test.ts b/skills/anidoodle/engine/test/linkedEngine.test.tsnew file mode 100644index 0000000..722eb51--- /dev/null+++ b/skills/anidoodle/engine/test/linkedEngine.test.ts@@ -0,0 +1,27 @@+// LINKED PROJECTS. A project made by scaffold.mjs --linked runs the engine's tools from its own folder,+// which has no copy of the engine's src/. Every engine file a tool reads must come through enginePath,+// or the tool looks in the project folder and fails. render.mjs once built the loudness meter from+// resolve("src/canvas-core/music/meter.ts") and could not find it in a linked project.+const fsModule = "node:fs", cpModule = "node:child_process", osModule = "node:os", pathModule = "node:path";+const { readFileSync, mkdtempSync, rmSync, existsSync } = await import(fsModule);+const { spawnSync } = await import(cpModule);+const { tmpdir } = await import(osModule);+const { join, resolve } = await import(pathModule);++export const name = "linked projects find the engine's files (enginePath)";+export function run(ok: (cond: boolean, label: string) => void) {+ // 1. render.mjs builds the meter through enginePath, never from the working directory+ const render = readFileSync("tools/render.mjs", "utf8");+ ok(/enginePath\("src\/canvas-core\/music\/meter\.ts"\)/.test(render), "render.mjs builds the loudness meter from enginePath");+ ok(!/resolve\("src\//.test(render), "render.mjs resolves no engine file against the working directory");++ // 2. run from an empty project folder, enginePath still lands on the engine's meter+ const engine = resolve("."), project = mkdtempSync(join(tmpdir(), "anidoodle-linked-"));+ try {+ const script = `import(${JSON.stringify(join(engine, "tools/overlay.mjs"))}).then((m) => console.log(m.enginePath("src/canvas-core/music/meter.ts")))`;+ const r = spawnSync(process.execPath, ["--input-type=module", "-e", script], { cwd: project, encoding: "utf8" });+ const got = String(r.stdout).trim();+ ok(r.status === 0, `enginePath runs from a project folder (exit ${r.status}${r.stderr ? `: ${String(r.stderr).trim().split("\n")[0]}` : ""})`);+ ok(got === join(engine, "src/canvas-core/music/meter.ts") && existsSync(got), `from a project folder the meter resolves to the engine's copy (${got})`);+ } finally { rmSync(project, { recursive: true, force: true }); }+}diff --git a/skills/anidoodle/engine/test/lookChat.test.ts b/skills/anidoodle/engine/test/lookChat.test.tsnew file mode 100644index 0000000..0be97c8--- /dev/null+++ b/skills/anidoodle/engine/test/lookChat.test.ts@@ -0,0 +1,75 @@+// THE CHAT TAKES THE LOOK. A custom look draws the chat the way the product draws its own: its text face in+// every line (header, prompt, button), its logo in the dot's place, no header when it has none, square or+// bar shapes, and a label colour the accent can carry. Without a look the chat draws exactly the stock calls.+// node tools/test.mjs lookChat+import { CHAT_GEOM, drawChatFrame, type ChatGeom } from "../src/canvas-core/launchKit";+import { resolveLook } from "../src/canvas-core/launchLook";+import { makeLaunchFilm, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import type { Ctx } from "../src/canvas-core/core";+import type { Film } from "../src/canvas-core/film";+import { FakeCanvas } from "./fakeCanvas";+import { drawProductUI, type UiTheme } from "../src/canvas-core/productUI";+import { launchExampleBrand } from "../src/canvas-core/launchExampleBrand";+import lora from "../assets/fonts/Lora-Bold.ttf";+import instrument from "../assets/fonts/InstrumentSans-Regular.ttf";++export const name = "the chat takes the look";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const raw = new FakeCanvas(1920, 1080).ctx, log: { op: string; font: string; fill: string; text?: string; r?: number; x?: number }[] = [];+ const ctx = new Proxy(raw, {+ get(t, k) {+ if (k === "fillText") return (s: string, x: number, y: number) => { log.push({ op: "text", font: t.font, fill: String(t.fillStyle), text: s, x }); t.fillText(s, x, y); };+ if (k === "arc") return (...a: number[]) => { log.push({ op: "arc", font: t.font, fill: String(t.fillStyle), r: a[2] }); };+ if (k === "arcTo") return (...a: number[]) => { log.push({ op: "arcTo", font: "", fill: "", r: a[4] }); };+ const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v;+ },+ set(t, k, v) { return Reflect.set(t, k, v); },+ }) as unknown as Ctx;+ const state = { typed: "why did it go up?", caret: true, title: "Tally", subtitle: "your books", genLabel: "Ask" };+ log.length = 0; drawChatFrame(ctx, state, CHAT_GEOM);+ const stock = log.filter((l) => l.op === "text");+ ok(stock.every((l) => l.font.includes('"Avenir Next"')) && stock.some((l) => l.text === "Tally"), "no look: the stock face and the stock header");+ const LK = resolveLook({ look: { base: "clean", fonts: { display: { family: "Lora", file: lora }, text: { family: "Instrument Sans", file: instrument } }, palette: { bg: "#121316", card: "#1a1b20", paper: "#202127", chip: "#2a2b31", ink: "#f2efe8", soft: "#b9b4aa", mute: "#8d8a84", line: "#2c2d33", accent: "#e8c547" }, shape: { composer: "bar", button: "square" }, chat: { header: false } } });+ const g: ChatGeom = { ...CHAT_GEOM, theme: LK.palette, look: LK };+ log.length = 0; drawChatFrame(ctx, state, g);+ const texts = log.filter((l) => l.op === "text");+ ok(texts.length > 0 && texts.every((l) => l.font.includes('"Instrument Sans"')), `RED: every line of the chat is set in the look's text face (${texts.map((l) => l.text).join(" | ")})`);+ ok(!texts.some((l) => l.text === "Tally" || l.text === "your books"), "RED: header: false draws no header");+ const label = texts.find((l) => l.text === "Ask");+ ok(!!label && label.fill.toLowerCase() === LK.onAccent.toLowerCase() && LK.onAccent !== "#ffffff", `RED: the button's label takes the colour the pale accent can carry (${label?.fill})`);+ // a logo in the dot's place (node has no Path2D: a stand-in, the fake canvas only records the calls)+ const G = globalThis as unknown as { Path2D?: unknown }; if (!G.Path2D) G.Path2D = class { constructor(_d?: string) {} };+ const logo = { w: 20, h: 20, parts: [{ d: "M0 0L20 0L20 20L0 20Z", fill: { type: "solid", c: "#e8c547" }, rule: "nonzero", op: 1, bb: [0, 0, 20, 20] }] } as never;+ const LK2 = resolveLook({ look: { base: "clean", chat: { logo, title: "Acme" } } });+ log.length = 0; drawChatFrame(ctx, state, { ...CHAT_GEOM, theme: LK2.palette, look: LK2 });+ ok(!log.some((l) => l.op === "arc" && Math.abs((l.r ?? 0) - 9) < 1e-9) && log.some((l) => l.text === "Acme"), "RED: a logo replaces the header's dot, and the look's title is the header's");+ // (framecheck's gap rule: a brand element and text 32 px apart or more; the logo is wider than the dot was)+ const titleX = log.find((l) => l.text === "Acme")?.x ?? 0, logoRight = CHAT_GEOM.CHAT.x + 58 * CHAT_GEOM.k + 13 * CHAT_GEOM.k;+ ok(titleX - logoRight >= 34, `RED: the title stands 34 px or more clear of the logo (${(titleX - logoRight).toFixed(0)} px)`);+ // the template builds with a look, and its chat geometry carries it+ const plate: Film = { meta: { title: "p", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 60 }, assets: { images: {} }, shots: [{ id: "p", start: 0, end: 60, draw: () => {} }] };+ const f = makeLaunchFilm({ title: "Acme", look: { base: "clean", fonts: { display: { family: "Lora", file: lora } }, palette: { accent: "#0b6e4f" } }, asks: [{ prompt: "draw the plan", plate, label: "the plan" }, { kind: "film", film: plate }], tagline: "Plans that draw themselves", install: ["npm i acme"], bpm: 90, score: null }) as LaunchFilm;+ ok(f.layout.chat !== undefined && f.meta.W === 1920, "a film with a look builds");+ let err = ""; try { makeLaunchFilm({ title: "Acme", look: { base: "clean", palette: { bg: "#202020" } }, asks: [{ kind: "film", film: plate }], tagline: "t", install: ["npm i acme"], bpm: 90, score: null }); } catch (e) { err = (e as Error).message; }+ ok(/'ink' #15161a on 'bg' #202020/.test(err), `RED: the template refuses an unreadable look at build (${err.slice(0, 70)})`);+ // THE PRODUCT'S OWN UI TAKES THE SHAPE TOO. A square brand's chat had square corners while its library's+ // action stayed a pill, its window 24 px round and its command bar a capsule: three corner styles in one film+ // (a fresh critic, br1-1: "reads as the template recoloured"). At 1x (a 720 x 600 panel) the look's radius+ // is every corner's ceiling and a square button is square.+ const ui = { title: "Lantern", nav: ["Library", "Notes"], action: "Check all", command: "Ask Lantern", before: { items: [{ id: "a", label: "Field notes", value: "12 p." }] }, after: { items: [{ id: "a", label: "Field notes", value: "12 p.", tag: "cited", done: true }] } };+ const TH: UiTheme = { bg: "#0f1113", card: "#1f2228", ink: "#f3ede0", soft: "#b8b0a2", mute: "#8f897e", line: "#3a3f48", chip: "#30343c", accent: "#f2b544", paper: "#272b32" };+ const radii = (T: UiTheme) => { log.length = 0; drawProductUI(ctx, { x: 0, y: 0, w: 720, h: 600 }, ui, { f: 0, t0: 10 }, T); return log.filter((e) => e.op === "arcTo").map((e) => e.r ?? 0); };+ const stockUi = radii(TH), sq = radii({ ...TH, radius: 6, button: "square" });+ ok(Math.max(...stockUi) > 20, `the stock product UI keeps its round corners (largest ${Math.max(...stockUi).toFixed(1)} px)`);+ ok(sq.length > 0 && Math.max(...sq) <= 6 + 1e-6, `RED: a square look's product UI has no corner rounder than its radius (largest ${Math.max(...sq).toFixed(1)} px, look 6)`);+ // THE LOGO SIGNS THE END CARD. A look with a logo showed it only as a 26 px header glyph and never on the+ // end card (a fresh critic, br1-5): the frame people screenshot had the name and no mark. The clean end+ // card now sets the logo before the name, on its baseline, and the whole group (logo, name, dot) is centred.+ for (const sh of ["16x9", "9x16"]) {+ const r = (launchExampleBrand as LaunchFilm).reshape(sh) as LaunchFilm, e = r.grammar?.endCard;+ if (!e) { ok(false, `${sh}: the end card is exposed`); continue; }+ ok(!!e.logo && e.logo.w > 40 && Math.abs(e.logo.x - e.group[0]) < 1e-6, `RED ${sh}: the logo opens the end card's group (${JSON.stringify(e.logo)})`);+ ok(Math.abs((e.group[0] + e.group[1]) / 2 - e.cx) < 2, `${sh}: logo, name and dot are centred on the card's axis (${((e.group[0] + e.group[1]) / 2).toFixed(1)} vs ${e.cx.toFixed(1)})`);+ ok(e.group[0] >= e.room[0] && e.group[1] <= e.room[1], `${sh}: the group stays inside the room`);+ }+};diff --git a/skills/anidoodle/engine/test/lookLayer.test.ts b/skills/anidoodle/engine/test/lookLayer.test.tsnew file mode 100644index 0000000..48bc706--- /dev/null+++ b/skills/anidoodle/engine/test/lookLayer.test.ts@@ -0,0 +1,65 @@+// THE LOOK LAYER. A launch film looks like the product it launches: look.base (any registered look; preset is+// its shorthand), look.palette (any token over the base), look.fonts (a family and a local .ttf, measured+// from its own glyphs), look.shape, look.chat, look.from (a brand.mjs import). The stock looks resolve to+// exactly what the template drew before (so the frozen films cannot move); a custom palette is checked for+// readable contrast, naming the token.+// node tools/test.mjs lookLayer+import { resolveLook, contrast, checkContrast, CLEAN, fontWidth, paletteFromBrand, registerLook, type FontFile } from "../src/canvas-core/launchLook";+import { C, SANS, MONO } from "../src/canvas-core/launchKit";+import { estWidth } from "../src/canvas-core/launchLayout";+import { parseTTF } from "../src/three-core/ttf";+import lora from "../assets/fonts/Lora-Bold.ttf";+import instrument from "../assets/fonts/InstrumentSans-Regular.ttf";++export const name = "the look layer";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const throws = (f: () => unknown, re: RegExp) => { try { f(); return false; } catch (e) { return re.test((e as Error).message); } };+ // the stock looks are what the template drew before+ const d = resolveLook({});+ ok(d.base === "drawn" && !d.clean && d.palette === C || JSON.stringify(d.palette) === JSON.stringify(C), "no look: the drawn base, palette C");+ ok(d.fonts.text === SANS && d.fonts.mono === MONO && d.measure.text === estWidth && !d.custom, "no look: the stock fonts and the stock measure, nothing custom");+ const c = resolveLook({ preset: "clean", accent: "#cc2200" });+ ok(c.clean && c.palette.accent === "#cc2200" && c.palette.bg === CLEAN.bg && !c.custom, "preset clean is look.base clean, the legacy accent kept");+ ok(resolveLook({ look: { base: "clean" } }).clean, "look.base clean");+ ok(throws(() => resolveLook({ preset: "clean", look: { base: "drawn" } }), /disagree/), "RED: preset and look.base that disagree are an error");+ ok(throws(() => resolveLook({ look: { base: "neon" } }), /not a registered look.*registerLook/), "RED: an unknown base names registerLook");+ registerLook("night", { clean: true, palette: { ...CLEAN, bg: "#101114", card: "#17181c", ink: "#f2efe8", paper: "#1d1e22", chip: "#26272c", soft: "#b9b4aa", mute: "#8d8a84", line: "#2c2d33" } });+ ok(resolveLook({ look: { base: "night" } }).palette.bg === "#101114", "a registered look is a base like the stock ones");+ // the palette, merged over the base, every key checked+ const p = resolveLook({ look: { base: "clean", palette: { accent: "#0b6e4f" } } });+ ok(p.palette.accent === "#0b6e4f" && p.palette.ink === CLEAN.ink && p.custom, "look.palette sets a token over the base");+ ok(throws(() => resolveLook({ look: { palette: { glow: "#fff" } as never } }), /'glow' is not a token/), "RED: an unknown token is an error naming it");+ // the readability guard (WCAG AA): every text pair a changed token touches+ ok(Math.abs(contrast("#000000", "#ffffff") - 21) < 0.01 && Math.abs(contrast("#777777", "#ffffff") - 4.48) < 0.02, "contrast is the WCAG ratio");+ ok(throws(() => resolveLook({ look: { base: "clean", palette: { bg: "#1a1a1a" } } }), /'ink' #15161a on 'bg' #1a1a1a/), "RED: a dark ground under the stock dark ink is refused, naming ink on bg");+ ok(resolveLook({ look: { base: "night", palette: { accent: "#ffe14d" } } }).onAccent === "#101114", "a pale accent takes a dark label (here the night ground), not white");+ ok(throws(() => resolveLook({ look: { base: "clean", palette: { accent: "#ffe14d" } } }), /'accent' #ffe14d on 'bg'/), "RED: a pale accent on a pale ground is refused as accent words, naming accent on bg");+ ok(throws(() => resolveLook({ look: { base: "clean", palette: { accent: "#a0a4ab", ink: "#6d7179", bg: "#a9adb5" } } }), /button's label on 'accent'/), "RED: an accent no label can be read on is refused, naming the accent");+ ok(throws(() => resolveLook({ look: { base: "clean", palette: { soft: "#c8c8c8" } } }), /'soft'.*under 4.5:1/), "RED: grey body text under 4.5:1 is refused");+ ok(!throws(() => resolveLook({ look: { base: "night", palette: { accent: "#e2b04a", accentDeep: "#b98a2c" } } }), /./), "a readable custom palette builds (a gold accent with a dark label)");+ ok(throws(() => checkContrast({ ...CLEAN, mute: "#d8d8d8" }, new Set(["mute"])), /'mute'.*under 3:1 \(the composer's placeholder/), "RED: hint text under 3:1 is refused");+ ok(throws(() => resolveLook({ look: { base: "clean", chat: { bubble: { fill: "#2f54eb", ink: "#1b2a7a" } } } }), /look.chat.bubble/), "RED: an unreadable bubble is refused, naming look.chat.bubble");+ // fonts: a family and its file; measured from the face itself+ const font = parseTTF(lora.data), f = resolveLook({ look: { base: "clean", fonts: { display: { family: "Lora", file: lora }, text: { family: "Instrument Sans", file: instrument } } } });+ ok(lora.path === "assets/fonts/Lora-Bold.ttf" && lora.format === "ttf" && lora.data.length > 1000, `a font imported by path arrives as its bytes (${lora.path}, ${lora.format})`);+ ok(Math.abs(f.measure.display("Hamburgefonts", 100) - fontWidth(font, "Hamburgefonts", 100)) < 1e-9 && Math.abs(f.measure.display("Hamburgefonts", 100) - estWidth("Hamburgefonts", 100) * 1.12) > 5, `RED: the display face measures from Lora's own advances (${f.measure.display("Hamburgefonts", 100).toFixed(1)} px, the stock estimate ${(estWidth("Hamburgefonts", 100) * 1.12).toFixed(1)})`);+ ok(f.fonts.display(700, 50).startsWith('700 50px "Lora"') && f.fonts.text(500, 20).startsWith('500 20px "Instrument Sans"'), "the faces are named in every font string");+ ok(f.wrap("one two three four five six", 40, 200).every((l) => f.measure.text(l, 40) <= 200 || !l.includes(" ")), "lines wrap by the text face's own widths");+ ok(f.faces.length === 2 && f.faces[0].family === "Lora", "the font files are listed for registration before the first frame");+ const woff: FontFile = { path: "x.woff2", format: "woff2", data: "AAAA" };+ ok(throws(() => resolveLook({ look: { fonts: { text: { family: "X", file: woff } } } }), /x\.woff2 is a \.woff2.*TrueType \.ttf/), "RED: a woff2 is refused with the fix (its .ttf)");+ ok(throws(() => resolveLook({ look: { fonts: { text: { family: "X" } as never } } }), /has no font file\. Import it by path/), "RED: a family with no file says how to import it");+ // from: a brand.mjs import fills the palette and the logo; explicit fields win+ const brand = { elements: { acmeLogo: { w: 10, h: 10, parts: [] } }, palette: [{ hex: "#0e0f12", share: 0.6 }, { hex: "#f4efe6", share: 0.3 }, { hex: "#e0662d", share: 0.1 }] };+ const fp = paletteFromBrand(brand);+ ok(fp.accent === "#e0662d" && fp.bg === "#0e0f12" && fp.ink === "#f4efe6", `a dark brand file: its saturated colour the accent, its dark the ground, its light the ink (${JSON.stringify(fp)})`);+ const fr = resolveLook({ look: { base: "night", from: brand, palette: { accent: "#e8743b" } } });+ ok(fr.palette.accent === "#e8743b" && fr.palette.bg === "#0e0f12" && fr.chat.logo === brand.elements.acmeLogo, "look.from fills palette and logo; an explicit token wins");+ // shape+ ok(throws(() => resolveLook({ look: { shape: { bubble: "blob" as never } } }), /bubble: 'blob'/), "RED: an unknown bubble style is an error");+ // the pointer: the stock black arrow on a light ground, a light arrow on a dark one (a black arrow on a dark+ // page was a white outline only: it changed so few pixels the gate read its approach as dead air)+ ok(d.pointer.fill === "#111" && d.pointer.edge === "#fff", "stock looks: the black pointer with its white edge");+ const dk = resolveLook({ look: { base: "night" } });+ ok(contrast(dk.pointer.fill === "#fff" ? "#ffffff" : dk.pointer.fill, dk.palette.bg) >= 4.5 && contrast(dk.pointer.edge === "#111" ? "#111111" : dk.pointer.edge, dk.pointer.fill === "#fff" ? "#ffffff" : dk.pointer.fill) >= 4.5, `RED: a dark ground gets a light pointer (${JSON.stringify(dk.pointer)})`);+};diff --git a/skills/anidoodle/engine/test/motionKit.test.ts b/skills/anidoodle/engine/test/motionKit.test.tsnew file mode 100644index 0000000..509ac37--- /dev/null+++ b/skills/anidoodle/engine/test/motionKit.test.ts@@ -0,0 +1,80 @@+// MOTION KIT AND ONE-WORLD TESTS. motionKit.ts, world.ts and timeRemap's named units are arithmetic,+// so their claims (no item repeats its neighbour's side, scrolls never snap, a world camera travels+// between regions and never jumps, a key's unit is always named) are held to numbers here.+// node tools/test.mjs motionKit+import { alternate, chatScroll, sharp, cubicBezier, entryFrom, landSquash, motionTokens, temperament, typeExit } from "../src/canvas-core/motionKit";+import { fitZoom, minTravel, world } from "../src/canvas-core/world";+import { timeRemap } from "../src/canvas-core/timeRemap";+import { speedCeiling } from "../src/canvas-core/seams";++export const name = "motionKit";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) <= eps;+ const throws = (fn: () => unknown, re?: RegExp) => { try { fn(); return false; } catch (e) { return re ? re.test(String(e)) : true; } };++ // alternate (M2)+ for (const n of [2, 3, 4, 5, 6, 8]) {+ const ch = Array.from({ length: n }, (_, i) => i), seq = Array.from({ length: 3 * n }, (_, i) => alternate(i, ch));+ ok(seq.every((v, i) => i === 0 || v !== seq[i - 1]) && new Set(seq.slice(0, n)).size === n, `alternate over ${n} choices: never the same twice running, every choice used once per round (${seq.slice(0, n).join(",")})`);+ }+ ok(throws(() => alternate(0, ["left"]), /carousel/), "RED: one choice is refused (it is the carousel)");+ const ent = Array.from({ length: 4 }, (_, i) => entryFrom(i)); ok(new Set(ent).size === 4 && ent[0] === "left", `entryFrom walks all four directions, never two alike in a row (${ent.join(", ")})`);++ // chatScroll (M11)+ const steps = [{ f: 10, by: 100 }];+ const ys = Array.from({ length: 40 }, (_, f) => chatScroll(f, steps));+ const maxStep = Math.max(...ys.slice(1).map((y, i) => y - ys[i]));+ ok(near(ys[39], 100) && ys[9] === 0 && maxStep < 16, `GREEN: a 100 px scroll over 20 frames moves at most ${maxStep.toFixed(1)} px a frame (the film snapped 100 px in 2-3 frames)`);+ ok(throws(() => chatScroll(0, steps, { frames: 3 }), /snap/), "RED: a 3-frame scroll is refused");++ // temperament (M7)+ const calm = temperament("calm");+ ok(near(calm.pxPerFrame(1920, 30), 0.35 * speedCeiling(1920, 30)) && calm.settleFrames(30)[0] === 15, "calm: top speed is 35 % of the ceiling, settles in 0.5-1 s");+ ok(Math.max(...Array.from({ length: 101 }, (_, i) => calm.arrive(i / 100))) <= 1 + 1e-9, "calm arrivals never overshoot");+ ok(Math.max(...Array.from({ length: 101 }, (_, i) => temperament("lively").arrive(i / 100))) > 1.01, "lively arrivals pass their mark a little");+ ok(throws(() => temperament("violent")), "an unknown temperament is refused, with the list");++ // brand motion tokens (M13): Figma's hourglass turn, cubic-bezier(0.5, 0, 0.5, 1) over 2 s+ const turn = cubicBezier(0.5, 0, 0.5, 1);+ ok(near(turn(0.5), 0.5, 1e-6) && turn(0.1) < 0.05 && turn(0.9) > 0.95, "cubic-bezier(0.5,0,0.5,1) is a symmetric in-out");+ const ease = cubicBezier(0.25, 0.1, 0.25, 1); ok(near(ease(0.5), 0.8024, 2e-3), `CSS 'ease' at 0.5 is about 0.802 (${ease(0.5).toFixed(4)})`);+ const tok = motionTokens({ turn: { ease: [0.5, 0, 0.5, 1], ms: 2000 }, slideIn: { ease: [0, 0, 0.58, 1], ms: 500, distance: 200 } }, 60);+ ok(tok.turn.frames === 120 && tok.slideIn.frames === 30 && tok.slideIn.distance === 200, "motion tokens become frame counts at the film's fps");++ // type exit (T5)+ ok(typeExit(0) === 0 && near(typeExit(1), 1.3) && typeExit(0.5) < 0.65 * 0.5, "typeExit: ease-in, 1.3x the size at the end");++ // the blur mask's tag: sharp() draws normally, and is left out while the renderer draws blurred subframes+ { const g = globalThis as { __ANIDOODLE_SHARP__?: string }; let n = 0; sharp(() => n++); g.__ANIDOODLE_SHARP__ = "skip"; sharp(() => n++); delete g.__ANIDOODLE_SHARP__; sharp(() => n++); ok(n === 2, "sharp() draws, except while the blur's subframes are drawn"); }++ // landings (M8, M9)+ const sq = landSquash(100, 100); ok(sq[1] < 1 && near(sq[0] * sq[1] * sq[0], sq[0] * sq[0] * sq[1]) && near(sq[0] * Math.sqrt(sq[1]), 1), "landSquash keeps volume (sx = 1 / sqrt(sy)) and squashes on contact");+ ok(landSquash(130, 100)[1] === 1, "round again after the landing");+ ok(throws(() => landSquash(100, 100, { brand: true }), /redraw/) && !throws(() => landSquash(100, 100, { brand: true, gag: "crushed by the chat window" })), "RED: a brand mark refuses the squash unless the gag is named");++ // one world (M1, C6, D4)+ const w = world({ W: 1920, H: 1080, regions: [{ id: "chat", rect: [0, 0, 1920, 1080] }, { id: "crowd", rect: [2400, 0, 3840, 2160] }], stops: [{ f: 0, at: "chat", hold: 30 }, { f: 90, at: "crowd", hold: 30 }] });+ ok(near(w.cam(0).zoom, fitZoom([0, 0, 1920, 1080], 1920, 1080)) && near(w.cam(10).look[0], 960), "a stop frames its region: centred, fitted with padding");+ ok(near(w.cam(120).look[0], 2400 + 1920) && w.cam(120).zoom < w.cam(0).zoom, "the second stop frames the bigger region further out");+ const xs = Array.from({ length: 121 }, (_, f) => w.cam(f).look[0]), steps2 = xs.slice(1).map((x, i) => x - xs[i]);+ ok(steps2.every((d) => d >= -1e-9) && Math.max(...steps2) < 200, `the camera travels between regions on every frame of the move (largest step ${Math.max(...steps2).toFixed(1)} world units), never jumps`);+ { const n = minTravel(600, 20), mv = world({ W: 1920, H: 1080, regions: [{ id: "a", rect: [0, 0, 1920, 1080] }, { id: "b", rect: [600 / fitZoom([0, 0, 1920, 1080], 1920, 1080), 0, 1920, 1080] }], stops: [{ f: 0, at: "a" }, { f: n, at: "b" }] }), xs2 = Array.from({ length: n + 1 }, (_, f) => mv.toScreen([0, 0], f)[0]);+ ok(Math.max(...xs2.slice(1).map((x, i) => Math.abs(x - xs2[i]))) <= 20.0001, `minTravel(600 px, 20 px a frame) = ${n} frames keeps the move's peak under 20 px a frame`); }+ ok(w.regionAt(5)?.id === "chat" && w.regionAt(120)?.id === "crowd", "regionAt names the region on screen");+ ok(w.moves().length === 1 && w.moves()[0].from === 30 && w.moves()[0].to === 90, "moves() lists the seams, each one a camera move");+ ok(throws(() => world({ W: 1920, H: 1080, regions: [{ id: "a", rect: [0, 0, 10, 10] }, { id: "b", rect: [20, 0, 10, 10] }], stops: [{ f: 0, at: "a", hold: 30 }, { f: 30, at: "b" }] }), /slide cut/), "RED: a stop with no frames to travel (a jump between regions) is refused");+ const tall = world({ W: 1080, H: 1920, shape: "9x16", regions: (s) => [{ id: "chat", rect: s.W < s.H ? [0, 0, 1080, 1920] : [0, 0, 1920, 1080] }], stops: [{ f: 0, at: "chat" }] });+ ok(near(tall.cam(0).look[1], 960), "regions as a function of the shape re-compose the world for 9:16");+ const alive = world({ W: 1920, H: 1080, regions: [{ id: "a", rect: [0, 0, 1920, 1080] }], stops: [{ f: 0, at: "a" }], alive: { amp: 3, seed: 2 } });+ const drift = Array.from({ length: 60 }, (_, f) => alive.cam(f).look[0]);+ ok(Math.max(...drift) - Math.min(...drift) > 0.5 && Math.max(...drift.slice(1).map((x, i) => Math.abs(x - drift[i]))) < 1, "an alive camera breathes slowly, never per-frame noise");++ // time remap units (M14)+ ok(throws(() => timeRemap([{ speed: 0.8 } as never]), /exactly one/), "RED: a key with no unit is refused");+ ok(throws(() => timeRemap([30 as never]), /names its unit/), "RED: a bare number is refused");+ ok(throws(() => timeRemap([{ f: 30, film: 1, speed: 1 }]), /exactly one/), "RED: a key naming two units is refused");+ ok(throws(() => timeRemap([{ film: 1, speed: 1 }]), /fps/), "seconds without fps are refused");+ const slow = timeRemap([{ film: 1, speed: 0.8 }, { scene: 10, speed: 1.1 }], { fps: 30 });+ ok(near(slow.at(30), 30) && near(slow.speedAt(31), 0.8), "film seconds land on film frames: 1 s is frame 30");+ ok(near(slow.speedAt(367), 0.8) && near(slow.speedAt(368), 1.1) && near(slow.at(368), 300, 1), "the scene-10 s key lands on film frame 368, where the slowed scene reaches 300 (typed as frame 300 it would be 68 frames early)");+};diff --git a/skills/anidoodle/engine/test/motionPushIn.test.ts b/skills/anidoodle/engine/test/motionPushIn.test.tsnew file mode 100644index 0000000..e66e984--- /dev/null+++ b/skills/anidoodle/engine/test/motionPushIn.test.ts@@ -0,0 +1,42 @@+// A SLOW PUSH-IN IS A CAMERA MOVE. The camera leaning in on a chat's answer card (1.18x over about half a+// second, off the frame's centre) on a sparse clean frame of thin type replaced 63 to 77 % of the content in+// 0.1 s, and the camera fit (globalMotion) could only try zooms of 3 % and 6 % a frame: a lean of about 1 %+// a frame matched none of them, the move "explained" under half the change, and motionscan read the lean+// as a slide cut (launchExampleCleanChat 16:9, frames 209 to 225). The fit now also tries the zooms between+// its coarse steps, at full size. The case that must stay red: two different layouts swapped in place.+// node tools/test.mjs motionPushIn+// @ts-ignore: a plain ES module shared with the tools+import { globalMotion, scanSlideCuts } from "../tools/motionscan-core.mjs";++export const name = "motionscan: a slow push-in is a camera move";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const W = 192, H = 108, PAPER = 250;+ // a sparse page of thin type: short dark strokes in a few lines and a card outline, on white+ const page = (seed: number) => (x: number, y: number) => {+ const row = Math.floor((y - 10 - seed * 7) / 14), inRow = (y - 10 - seed * 7) % 14;+ if (row >= 0 && row < 5 && inRow >= 0 && inRow < 3 && x > 20 + seed * 30 && x < 120 + row * 9 && (Math.floor(x / 3) + row + seed) % 5 < 3) return 40;+ if ((Math.abs(x - 140 + seed * 60) < 1 || Math.abs(x - 175 + seed * 60) < 1) && y > 50 && y < 95) return 120;+ return PAPER;+ };+ // the camera at zoom z about (cx, cy), sampled (bilinear, so a sub-pixel move shows as a sub-pixel move)+ const shot = (src: (x: number, y: number) => number, z: number, cx: number, cy: number) => {+ const o = new Uint8Array(W * H);+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {+ const u = cx + (x - cx) / z, v = cy + (y - cy) / z, x0 = Math.floor(u), y0 = Math.floor(v), fx = u - x0, fy = v - y0;+ const p = (a: number, b: number) => src(a, b);+ o[y * W + x] = Math.round((1 - fy) * ((1 - fx) * p(x0, y0) + fx * p(x0 + 1, y0)) + fy * ((1 - fx) * p(x0, y0 + 1) + fx * p(x0 + 1, y0 + 1)));+ }+ return o;+ };+ // a lean: 1.0 to 1.18 over 30 frames (in-out), about a point left of and below the centre+ const ease = (q: number) => (q < 0.5 ? 2 * q * q : 1 - 2 * (1 - q) ** 2);+ const lean = Array.from({ length: 40 }, (_, f) => shot(page(0), 1 + 0.18 * ease(Math.min(1, Math.max(0, (f - 5) / 30))), 70, 70));+ const g = globalMotion(lean[19], lean[20], W, H, { between: true });+ ok(g.explained >= 0.6, `RED: one step of the lean is explained by one zoom and shift (explained ${g.explained.toFixed(2)}, scale ${g.scale})`);+ const r = scanSlideCuts(lean, { width: W, height: H, fps: 60 });+ ok(r.events.length === 0, `RED: a slow push-in on a sparse page of type is no slide cut (${r.events.length} found${r.events.length ? ` at ${r.events.map((e: { frame: number }) => e.frame).join(", ")}` : ""})`);+ // the case that stays red: one sparse page swapped for another in place, in 3 frames, the camera still+ const swap = Array.from({ length: 24 }, (_, f) => { const a = shot(page(0), 1, 96, 54), b = shot(page(1), 1, 96, 54), q = Math.min(1, Math.max(0, (f - 10) / 3)); return a.map((v, i) => Math.round(v + (b[i] - v) * q)); });+ const s = scanSlideCuts(swap.map((x) => Uint8Array.from(x)), { width: W, height: H, fps: 60 });+ ok(s.events.length > 0, `two layouts swapped in place still read as a slide cut (${s.events.length} found)`);+};diff --git a/skills/anidoodle/engine/test/motionReveal.test.ts b/skills/anidoodle/engine/test/motionReveal.test.tsnew file mode 100644index 0000000..c118416--- /dev/null+++ b/skills/anidoodle/engine/test/motionReveal.test.ts@@ -0,0 +1,27 @@+// A REVEAL IS NOT A MOVE. An end card that opens as a growing disc (a bloom's rim) uncovers the new page+// and covers the old one; nothing in either moves. The block matcher read it as fast motion: a block of the+// old page's text, covered by the rim, "found" its look-alike in the text still standing beside it, a few+// letters over, and that false match was the fastest thing in the frame (launchExampleClean 9:16 frames+// 979 to 985 read 51 px a frame against the snappy limit of 36). A block whose match lands on content that+// was already there, unchanged, did not move there: it was covered. Real motion still reads, the green+// case that must stay red: a textured card crossing flat ground fast.+// node tools/test.mjs motionReveal+// @ts-ignore: a plain ES module shared with the tools+import { speedProfile } from "../tools/motionscan-core.mjs";++export const name = "motionscan: a reveal edge is not motion";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const W = 192, H = 108, PAPER = 236;+ // lines of "text": letters as dark strokes on a short period, so a letter has look-alikes a few px away+ const text = (x: number, y: number) => { const row = Math.floor(y / 12), inRow = y % 12; if (row < 1 || row > 7 || inRow < 3 || inRow > 9) return PAPER; const cx = (x + row * 3) % 7; return cx < 2 || (cx === 4 && inRow % 3 === 0) ? 30 : PAPER; };+ const page = (x: number, y: number) => ((Math.floor(x / 5) + Math.floor(y / 5)) % 3 === 0 ? 120 : 200); // the new page: other content, flat-ish+ const frame = (r: number) => { const o = new Uint8Array(W * H); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) o[y * W + x] = Math.hypot(x - 150, y - 50) < r ? page(x, y) : text(x, y); return o; };+ const reveal = Array.from({ length: 24 }, (_, f) => frame(4 + 3 * f)); // the rim grows 3 analysis px a frame+ const sp = speedProfile(reveal, { width: W, height: H, scale: 1, R: 10 }), top = Math.max(...sp.slice(2));+ ok(top <= 4.5, `RED: a disc opening at 3 px a frame over standing text reads at most its rim's pace (fastest ${top.toFixed(1)} px a frame)`);+ // the green case that stays red: a textured card crossing flat ground at 9 px a frame is fast motion+ const tex = (x: number, y: number) => (((x * 7) ^ (y * 13)) % 11 < 5 ? 40 : 190);+ const cross = Array.from({ length: 12 }, (_, f) => { const o = new Uint8Array(W * H).fill(PAPER), x0 = 10 + 9 * f; for (let y = 30; y < 80; y++) for (let x = x0; x < Math.min(W, x0 + 50); x++) o[y * W + x] = tex(x - x0, y); return o; });+ const sc = speedProfile(cross, { width: W, height: H, scale: 1, R: 10 }), fast = Math.max(...sc.slice(2));+ ok(fast >= 8, `a card crossing flat ground at 9 px a frame still reads as fast (${fast.toFixed(1)} px a frame)`);+};diff --git a/skills/anidoodle/engine/test/motionSubpixel.test.ts b/skills/anidoodle/engine/test/motionSubpixel.test.tsnew file mode 100644index 0000000..6065fff--- /dev/null+++ b/skills/anidoodle/engine/test/motionSubpixel.test.ts@@ -0,0 +1,29 @@+// THE CAMERA'S SPEED TO A FRACTION OF A PIXEL. The temperament check reads the camera's move off frames+// 128 px wide, so one analysis pixel is 8.4 px of a phone frame and 15 px of a wide one, and the camera fit+// knew only whole pixels: a travel at 12.3 px a frame on 9:16 read as 8.4 or 16.9 by turns, and the 16.9s+// failed a calm brand's 15.75 (the clean scaffold, frames 249 to 286). The fit now places the shift between+// pixels (a parabola through the error at the best whole shift and its neighbours) for the speed profile. The case that stays+// red: a pan really at 2.2 analysis px a frame still reads above 2.+// node tools/test.mjs motionSubpixel+// @ts-ignore: a plain ES module shared with the tools+import { globalMotion, motionBetween } from "../tools/motionscan-core.mjs";++export const name = "motionscan: the camera's speed to a fraction of a pixel";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const W = 128, H = 228;+ // a smooth textured page (blurred blobs), so a sub-pixel pan is a sub-pixel change+ const tex = (x: number, y: number) => 128 + 50 * Math.sin(x * 0.21 + Math.sin(y * 0.13) * 2) * Math.cos(y * 0.17 + x * 0.05);+ const pan = (dx: number) => { const o = new Uint8Array(W * H); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) o[y * W + x] = Math.round(tex(x - dx, y)); return o; };+ const reads = [0, 1, 2, 3, 4].map((f) => globalMotion(pan(f * 1.46), pan((f + 1) * 1.46), W, H, { subpixel: true }).speed);+ ok(reads.every((v) => Math.abs(v - 1.46) <= 0.3), `RED: a pan at 1.46 analysis px a frame reads 1.46 within 0.3 on every frame (${reads.map((v) => v.toFixed(2)).join(", ")})`);+ const fast = globalMotion(pan(0), pan(2.2), W, H, { subpixel: true }).speed;+ ok(fast > 2, `a pan at 2.2 px a frame still reads above 2 (${fast.toFixed(2)})`);+ // the same for the block matcher, the profile's other reading (the fastest coherent element): the clean+ // scaffold's carried word lines at 11.5 px a frame read 8.4 or 16.9 by turns there, after the camera fit was fixed+ const blocks = [0, 1, 2, 3, 4].map((f) => motionBetween(pan(f * 1.46), pan((f + 1) * 1.46), W, H, { R: 10, subpixel: true }).speed);+ ok(blocks.every((v) => Math.abs(v - 1.46) <= 0.3), `RED: the block matcher reads a 1.46 px pan within 0.3 on every frame (${blocks.map((v) => v.toFixed(2)).join(", ")})`);+ const fastB = motionBetween(pan(0), pan(2.2), W, H, { R: 10, subpixel: true }).speed;+ ok(fastB > 2, `the block matcher still reads a 2.2 px pan above 2 (${fastB.toFixed(2)})`);+ const whole = motionBetween(pan(0), pan(1.46), W, H, { R: 10 }).speed;+ ok(Number.isInteger(whole), `without subpixel the block matcher keeps whole pixels (${whole})`);+};diff --git a/skills/anidoodle/engine/test/motionscan.test.ts b/skills/anidoodle/engine/test/motionscan.test.tsnew file mode 100644index 0000000..631ee75--- /dev/null+++ b/skills/anidoodle/engine/test/motionscan.test.ts@@ -0,0 +1,109 @@+// MOTION SCAN TESTS. tools/motionscan-core.mjs is pure, so every detector is held to synthetic frames+// here: a red fixture it must fail (the brand launch film fault it exists for) next to a green case it must+// pass (the fix). node tools/test.mjs motionscan+// @ts-ignore: a plain ES module shared with the tools+import { TEMPERAMENT_MAX, layoutIoU, layoutOf, motionBetween, scanDissolves, scanExits, scanFaceCover, scanFastText, scanRepeats, scanSlideCuts, scanTarget, scanTemperament, scanTranslucent, speedProfile } from "../tools/motionscan-core.mjs";+import { TEMPERAMENTS, TYPE_EXIT_TRAVEL, typeExit } from "../src/canvas-core/motionKit";++export const name = "motionscan";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const W = 128, H = 72, FPS = 30;+ // value noise in 4 px cells: texture block matching can lock onto+ const noise = (seed: number, w: number, h: number) => { const o = new Uint8Array(w * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let s = (Math.floor(x / 4) * 73856093) ^ (Math.floor(y / 4) * 19349663) ^ (seed * 83492791); s ^= s << 13; s ^= s >>> 17; s ^= s << 5; o[y * w + x] = 30 + ((s >>> 0) % 200); } return o; };+ const crop = (src: Uint8Array, sw: number, ox: number) => { const o = new Uint8Array(W * H); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) o[y * W + x] = src[y * sw + x + ox]; return o; };+ const blend = (a: Uint8Array, b: Uint8Array, t: number) => a.map((v, i) => Math.round(v + (b[i] - v) * t));+ const card = (seed: number, x0: number, y0: number, x1: number, y1: number) => { const o = new Uint8Array(W * H).fill(40), n = noise(seed, W, H); for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) o[y * W + x] = n[y * W + x]; return o; };+ const opts = { width: W, height: H, fps: FPS };++ // ---- motion between frames: the tool every scan stands on+ const world = noise(1, 600, H);+ const m = motionBetween(crop(world, 600, 10), crop(world, 600, 13), W, H);+ ok(m.matched > 0.9 && Math.abs(m.speed - 3) < 0.6, `a 3 px pan reads as motion: speed ${m.speed.toFixed(2)}, matched ${m.matched.toFixed(2)}`);+ const cut = motionBetween(noise(1, W, H), noise(2, W, H), W, H);+ ok(cut.matched < 0.3, `a hard cut finds nothing to match (matched ${cut.matched.toFixed(2)})`);++ // ---- slide cuts (M1)+ const deck = Array.from({ length: 100 }, (_, f) => noise(10 + Math.floor(f / 20), W, H)); // a new "slide" every 20 frames+ const sc = scanSlideCuts(deck, opts);+ ok(sc.fail && sc.events.length === 4, `RED: a deck that swaps the whole picture every 20 frames: ${sc.events.length} slide cuts, fails`);+ const pan = Array.from({ length: 100 }, (_, f) => crop(world, 600, 3 * f));+ const sp = scanSlideCuts(pan, opts);+ ok(!sp.fail && sp.events.length === 0, `GREEN: one world under a travelling camera has no slide cuts (${sp.events.length})`);+ ok(!scanSlideCuts(deck.slice(0, 50), opts).fail, "GREEN: two cuts in a short film is within 2 a minute");+ ok(!scanSlideCuts(deck, { ...opts, allow: [[0, 100]] }).fail, "declared cuts (allow) are not counted");+ const darkDeck = Array.from({ length: 100 }, (_, f) => card(40 + Math.floor(f / 20), (Math.floor(f / 20) % 2) * 60 + 4, 10, (Math.floor(f / 20) % 2) * 60 + 60, 40).map((v) => (v === 40 ? 17 : v)));+ ok(scanSlideCuts(darkDeck, opts).fail, "RED: slides on a dark ground (most pixels never change) are still slide cuts: content, not ground, is measured");++ // ---- dissolves (M3)+ const A = noise(3, W, H), B = noise(4, W, H);+ const fade = [...Array(10).fill(A), ...Array.from({ length: 12 }, (_, i) => blend(A, B, (i + 1) / 13)), ...Array(10).fill(B)];+ const dv = scanDissolves(fade, opts);+ ok(dv.fail && dv.findings[0]?.area === 1, `RED: a 12-frame cross-dissolve over the whole frame is found (${JSON.stringify(dv.findings[0])})`);+ ok(!scanDissolves(pan.slice(0, 40), opts).fail && scanDissolves(pan.slice(0, 40), opts).findings.length === 0, "GREEN: a camera move is motion, not a blend");+ ok(!scanDissolves([...Array(10).fill(A), ...Array(10).fill(B)], opts).findings.length, "GREEN: a hard cut is not a dissolve");+ ok(!scanDissolves(fade, { ...opts, allow: [[0, 40]] }).fail, "a declared dissolve (allow) is reported but does not fail");+ const elFade = [...Array(8).fill(card(5, 0, 0, 16, 9).fill(40)), ...Array.from({ length: 10 }, (_, i) => { const o = new Uint8Array(W * H).fill(40), c = noise(5, W, H); for (let y = 0; y < 9; y++) for (let x = 0; x < 16; x++) o[y * W + x] = Math.round(40 + (c[y * W + x] - 40) * ((i + 1) / 11)); return o; })];+ const ef = scanDissolves(elFade, opts);+ ok(ef.findings.length === 1 && !ef.fail, `a small element fading in is listed (area ${ef.findings[0]?.area}) but is not a dissolve seam`);+ const cardFade = [...Array(8).fill(new Uint8Array(W * H).fill(17)), ...Array.from({ length: 10 }, (_, i) => blend(new Uint8Array(W * H).fill(17), card(6, 8, 8, 60, 64), (i + 1) / 11)), ...Array(6).fill(card(6, 8, 8, 60, 64))];+ ok(scanDissolves(cardFade, opts).fail, "RED: a card faded in on a dark ground (the deck's entrance) fails: it is a fade, not a move");++ // ---- repeated layouts (M2)+ const hold = (f: Uint8Array, n = 20) => Array(n).fill(f) as Uint8Array[];+ const carousel = [0, 1, 2, 3].flatMap((i) => hold(card(20 + i, 8, 8, 60, 64)));+ const rp = scanRepeats(carousel, opts);+ ok(rp.fail && rp.runs[0]?.length === 4, `RED: four beats settle into the same card with new content: one run of ${rp.runs[0]?.length}`);+ const sides = [0, 1, 2, 3].flatMap((i) => hold(i % 2 ? card(20 + i, 68, 8, 120, 64) : card(20 + i, 8, 8, 60, 64)));+ ok(!scanRepeats(sides, opts).fail, "GREEN: alternate() sides (left, right, left, right) is not a carousel");+ const same = [0, 1, 2, 3].flatMap(() => hold(card(20, 8, 8, 60, 64)));+ ok(!scanRepeats(same, opts).fail, "GREEN: one beat held (no new content) is not a repeat");+ ok(layoutIoU(layoutOf(card(1, 8, 8, 60, 64), W, H), layoutOf(card(2, 8, 8, 60, 64), W, H)) > 0.9, "the layout map ignores what is inside a box, only where it is");++ // ---- temperament (M7)+ const prof = speedProfile(pan.slice(0, 6), { width: W, height: H, scale: 15 });+ ok(Math.abs(prof[3] - 45) < 10, `speed profile scales analysis px to the film's size (3 px at 1/15 size = ${prof[3].toFixed(1)} px)`);+ const tm = scanTemperament([0, 10, 90, 95, 99, 20, 0, 85, 0], { maxPx: 64 });+ ok(tm.fail && tm.stretches.length === 1 && tm.stretches[0].from === 2, "RED: three frames past the temperament's top speed fail; a one-frame peak does not");+ ok(!scanTemperament([0, 10, 40, 60, 20], { maxPx: 64 }).fail, "GREEN: a move under the temperament passes");+ ok(Object.entries(TEMPERAMENTS).every(([k, t]) => (TEMPERAMENT_MAX as Record<string, number>)[k] === t.maxSpeed) && Object.keys(TEMPERAMENT_MAX).length === Object.keys(TEMPERAMENTS).length, "the tool's temperament table equals motionKit's");++ // ---- text exits (T5): the ink a line shows as it sinks under its clip, from the geometry of rise()+ // glyph from baseline - 0.95 size (ascenders, dots) to + 0.2 size; the clip ends 0.3 size under the baseline+ const inkAt = (dy: number) => Math.max(0, Math.min(1.15, 0.3 + 0.95 - dy)) / 1.15;+ const series = (sink: (q: number) => number, frames = 18) => Array.from({ length: frames }, (_, i) => ({ frame: 100 + i, ink: Math.round(1000 * inkAt(sink(i / frames))) }));+ const oldRise = series((q) => 1.0 * (1 - Math.pow(1 - q, 3))), newRise = series((q) => typeExit(q));+ const ex = scanExits({ "old rise": [...Array.from({ length: 30 }, (_, i) => ({ frame: 70 + i, ink: 1000 })), ...oldRise] }, { fps: FPS });+ ok(ex.fail && ex.findings[0].frames >= 6, `RED: the brand launch exit (ease-out, 1.0x) leaves slivers for ${ex.findings[0]?.frames} frames (${ex.findings[0]?.seconds} s)`);+ const ok2 = scanExits({ "new rise": [...Array.from({ length: 30 }, (_, i) => ({ frame: 70 + i, ink: 1000 })), ...newRise] }, { fps: FPS });+ ok(!ok2.fail, `GREEN: typeExit (ease-in, ${TYPE_EXIT_TRAVEL}x) clears the clip with no lingering slivers`);+ ok(inkAt(typeExit(1)) === 0 && inkAt(1.0) > 0.2, "1.3x travel clears ascenders and dots; 1.0x leaves a fifth of the letters showing");+ ok(!scanExits({ cut: [{ frame: 1, ink: 900 }, { frame: 2, ink: 900 }, { frame: 3, ink: 0 }] }, { fps: FPS }).fail, "GREEN: a line that simply ends leaves nothing");++ // ---- fast text (M4)+ const lay = (frames: number, v: number) => Array.from({ length: frames }, (_, f) => ({ frame: f, recs: [{ kind: "text", src: "probe", label: "Nobody has a prompt for that.", x0: 100 + v * f, y0: 500, x1: 900 + v * f, y1: 560, alpha: 1, order: 0 }], translucent: [] }));+ const ft = scanFastText(lay(10, 120), { W: 1920, fps: FPS });+ ok(ft.fail && ft.cap === 80, `RED: type whipping out at 120 px a frame is past half the speed ceiling (${ft.cap} px)`);+ ok(!scanFastText(lay(10, 30), { W: 1920, fps: FPS }).fail, "GREEN: type leaving at 30 px a frame (0.5-0.7 s) passes");++ // M3: sampled every 2 frames, type whipping at 120 px a frame is still caught (the scan used to need consecutive frames)+ const every2 = lay(20, 120).filter((l) => l.frame % 2 === 0);+ ok(scanFastText(every2, { W: 1920, fps: FPS, step: 2 }).fail, "NEGATIVE M3: fast type is still found when the frames are sampled every 2 (step)");+ ok(!scanFastText(lay(20, 30).filter((l) => l.frame % 2 === 0), { W: 1920, fps: FPS, step: 2 }).fail, "M3 slow type sampled every 2 frames passes");++ // ---- faces covered by a moving shape (M12)+ const face = (moveShape: boolean, behind = false) => Array.from({ length: 6 }, (_, f) => ({ frame: f, translucent: [], recs: [+ { kind: "photo", src: "image", label: "priya", x0: 800, y0: 200, x1: 1100, y1: 700, alpha: 1, order: behind ? 1 : 0 },+ { kind: "box", src: "probe", label: "brand:frieze", x0: 700 + (moveShape ? 20 * f : 0), y0: 220, x1: 1000 + (moveShape ? 20 * f : 0), y1: 330, alpha: 1, order: behind ? 0 : 1 },+ ] }));+ ok(scanFaceCover(face(true)).fail, "RED: a frieze sliding across a speaker's face (whack-a-mole) is found");+ ok(!scanFaceCover(face(true, true)).fail, "GREEN: the same frieze moving BEHIND the photo passes");+ ok(!scanFaceCover(face(false)).fail, "GREEN: a shape that moves with the person (their stage) passes");++ // ---- translucent brand colour (M3, M10)+ const tr = [{ frame: 3, recs: [], translucent: [{ colour: "#ffde59", alpha: 0.5 }] }, { frame: 4, recs: [], translucent: [{ colour: "#ffde59", alpha: 0.4 }] }];+ ok(scanTranslucent(tr).fail && scanTranslucent(tr).findings[0].frames.length === 2, "RED: brand yellow filled at 40-50 % alpha is found on both frames");+ ok(!scanTranslucent(tr, { allow: [[0, 10]] }).fail, "GREEN: inside a declared fade it passes");+ // ---- L5: the file a scan reads+ ok(scanTarget("x.mov") === "x.mov" && scanTarget("cuts/x.M4V") === "cuts/x.M4V" && scanTarget("x.mp4") === "x.mp4", "NEGATIVE L5: a .mov or .m4v is scanned as given, never rewritten to out/x.mov.mp4");+ ok(scanTarget("brandLaunch") === "out/brandLaunch.mp4", "L5 a film name reads out/<film>.mp4");+};diff --git a/skills/anidoodle/engine/test/narrate.test.ts b/skills/anidoodle/engine/test/narrate.test.tsindex 75c48e8..c06a92d 100644--- a/skills/anidoodle/engine/test/narrate.test.ts+++ b/skills/anidoodle/engine/test/narrate.test.ts@@ -95,6 +95,13 @@ export const run = (ok: (cond: boolean, label: string) => void) => {const baked: BakedVoice = { sampleRate: 1000, pcm: { a: b64(Array.from({ length: 200 }, (_, i) => (i % 2 ? 0x40 : 0x00))) }, timing: { version: 1, fps: 10, totalFrames: 20, lines: [{ id: "a", text: "x", start: 5, end: 7, words: [] }] } };const vt = voiceTrack(baked, 1000);ok(vt.length === 2000 && vt[499] === 0 && vt[500] === 0.5 && vt[599] === 0.5 && vt[600] === 0, "a take lands on its start frame to the sample (frame 5 at 10 fps = sample 500)");+ // L8: two baked voices with the same line id and the same take length must each play their own take+ const twinA: BakedVoice = { ...baked, pcm: { a: b64(Array.from({ length: 200 }, (_, i) => (i % 2 ? 0x20 : 0x00))) } };+ const twinB: BakedVoice = { ...baked, pcm: { a: b64(Array.from({ length: 200 }, (_, i) => (i % 2 ? 0x10 : 0x00))) } };+ const ta = voiceTrack(twinA, 1000), tb = voiceTrack(twinB, 1000);+ ok(ta[500] === 0.25 && tb[500] === 0.125, `RED (L8): same line id and length, different takes, each plays its own (${ta[500]}, ${tb[500]})`);+ const slow: BakedVoice = { ...twinB, sampleRate: 500 };+ ok(voiceTrack(slow, 1000).length === 2000 && voiceTrack(slow, 1000).filter((x) => x !== 0).length > 150, "RED (L8): the same take at another sample rate is resampled again, not served from the cache");// the duck: silence 1 s, voice 1 s, silence 2 sconst S = 8000, v = new Float32Array(4 * S); for (let i = S; i < 2 * S; i++) v[i] = 0.3 * Math.sin(i * 0.2);diff --git a/skills/anidoodle/engine/test/people.test.ts b/skills/anidoodle/engine/test/people.test.tsnew file mode 100644index 0000000..fc1e7a8--- /dev/null+++ b/skills/anidoodle/engine/test/people.test.ts@@ -0,0 +1,24 @@+// PEOPLE EDGE TESTS. src/canvas-core/people.ts headOf on cut-outs with no neck: a head-only crop and+// an oval portrait. The neck search took the narrowest row 12 % under the crown (the top of an oval is+// narrowest), so the "head" came out about 12 % of the figure and the person was scaled about 8x.+// With no neck, the whole figure is the head. (The head-and-shoulders case is in readable.test.ts.)+// node tools/test.mjs people+import { headOf, placePerson } from "../src/canvas-core/people";++const W = 100, H = 120;+const img = (inside: (x: number, y: number) => boolean) => { const a = new Uint8Array(W * H); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) if (inside(x, y)) a[y * W + x] = 255; return a; };++export const name = "people";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const oval = headOf(img((x, y) => ((x - 50) / 40) ** 2 + ((y - 60) / 55) ** 2 <= 1), W, H)!;+ const ovalH = oval.y1 - oval.y0;+ ok(ovalH >= 100, `L13 an oval cut-out has no neck: the whole oval is the head (${ovalH} px of 111)`);+ const p = placePerson(oval, { cx: 500, crownY: 100, headPx: 220 });+ ok(p.s < 2.2, `L13 so a 220 px head scales it about 2x, not 8x (scale ${p.s.toFixed(2)})`);+ // a head-only crop: a round head with a short neck stub and no shoulders under it+ const crop = headOf(img((x, y) => ((x - 50) / 30) ** 2 + ((y - 45) / 38) ** 2 <= 1 || (y >= 80 && y < 96 && x >= 42 && x < 58)), W, H)!;+ ok(crop.y1 - crop.y0 >= 75, `L13 a head-only crop with no shoulders keeps its whole head (${crop.y1 - crop.y0} px tall, from ${crop.y0})`);+ // GREEN: a real head and shoulders still ends the head at the neck+ const hs = headOf(img((x, y) => (((x - 50) / 22) ** 2 + ((y - 30) / 26) ** 2 <= 1) || (y >= 54 && y < 64 && x >= 42 && x < 58) || (y >= 64 && x >= 4 && x < 96)), W, H)!;+ ok(hs.y0 === 4 && hs.y1 >= 54 && hs.y1 <= 64, `GREEN head and shoulders: the head ends at the neck (${hs.y0}-${hs.y1})`);+};diff --git a/skills/anidoodle/engine/test/probe.test.ts b/skills/anidoodle/engine/test/probe.test.tsnew file mode 100644index 0000000..b16104e--- /dev/null+++ b/skills/anidoodle/engine/test/probe.test.ts@@ -0,0 +1,53 @@+// FRAME PROBE TESTS (hosts/probe.ts, what framecheck sees). Driven with a stand-in canvas, each case is+// one way the probe went blind and framecheck passed on text it never saw:+// H1 text in a layer built once and reused (a bake() sprite, a held plate) vanished from the second+// 40-frame batch on, because only the first call rebuilt the layer memo under the hooks+// H2 text under a hand-built rounded rect (moveTo + four arcTo, launchKit rr()) vanished, because arcTo+// was not measured and the clip collapsed to a point+import { frameProbe } from "../src/hosts/probe";+import { FakeCanvas, installFakeCanvas } from "./fakeCanvas";++export const name = "probe";+export const run = (ok: (cond: boolean, label: string) => void) => {+ installFakeCanvas();+ const W = 1920, H = 1080;+ const mk = (draw: (ctx: FakeCanvas["ctx"], cache: Map<string, unknown>, f: number) => void) => {+ const canvas = new FakeCanvas(W, H), cache = new Map<string, unknown>();+ const seek = (f: number) => { canvas.ctx.reset(); draw(canvas.ctx, cache, f); };+ return frameProbe({ canvas: () => canvas, ctx: () => canvas.ctx as never, seek, clearCache: () => cache.clear() });+ };+ const range = (a: number, b: number) => Array.from({ length: b - a }, (_, i) => a + i);+ const labels = (rs: { label: string; frame: number }[], f: number) => rs.filter((r) => r.frame === f).map((r) => r.label).sort().join("|");++ // ---- H1: a sprite with a line of text, baked once into the memo and drawn every frame+ const sprite = mk((ctx, cache, f) => {+ let L = cache.get("sprite") as FakeCanvas | undefined;+ if (!L) { L = new FakeCanvas(400, 100); L.ctx.font = "40px Sans"; L.ctx.fillText("Learn more", 10, 60); cache.set("sprite", L); }+ ctx.drawImage(L, 200 + f, 400);+ });+ const a = sprite(range(0, 40), true), b = sprite(range(40, 80), true);+ ok(labels(a, 0) === "Learn more", `H1 the sprite's text is seen in the first batch (${labels(a, 0) || "nothing"})`);+ ok(range(40, 80).every((f) => labels(b, f) === "Learn more"), `NEGATIVE H1: the sprite's text is still seen in the second 40-frame batch (frame 40: ${labels(b, 40) || "nothing"})`);+ ok(b.length === a.length, `H1 both batches return the same number of records (${a.length} and ${b.length})`);+ // the same sprite, its edge cut by the frame: the cut must be reported in batch two as in batch one+ const cutSprite = mk((ctx, cache) => {+ let L = cache.get("s") as FakeCanvas | undefined;+ if (!L) { L = new FakeCanvas(400, 100); L.ctx.font = "40px Sans"; L.ctx.fillText("Sign up now", 10, 60); cache.set("s", L); }+ ctx.drawImage(L, W - 150, 400);+ });+ ok(cutSprite([0]).length === 1 && cutSprite([40]).length === 1, "NEGATIVE H1: a reused sprite cut by the frame's edge is reported on every call, not only the first");++ // ---- H2: a rounded card clip built from moveTo + four arcTo, text inside it+ const card = mk((ctx) => {+ const x = 600, y = 300, w = 700, h = 300, r = 24;+ ctx.save(); ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.clip();+ ctx.font = "48px Sans"; ctx.fillText("Your reply", x + 40, y + 120); ctx.restore();+ });+ ok(labels(card([0], true), 0) === "Your reply", `NEGATIVE H2: text inside an arcTo rounded-rect clip is seen (got: ${labels(card([0], true), 0) || "nothing"})`);+ // a clip the probe cannot measure (no path at all) must never hide the text from the checks+ const blindClip = mk((ctx) => { ctx.save(); ctx.beginPath(); ctx.clip(); ctx.font = "48px Sans"; ctx.fillText("Hidden?", 100, 200); ctx.restore(); });+ ok(labels(blindClip([0], true), 0) === "Hidden?", "NEGATIVE H2: a clip with no measured area is unknown, never 'clips everything'");+ // and a real clip still cuts: text wholly outside a measured rect clip is not drawn+ const outside = mk((ctx) => { ctx.save(); ctx.beginPath(); ctx.rect(0, 0, 300, 300); ctx.clip(); ctx.font = "48px Sans"; ctx.fillText("Off card", 800, 800); ctx.restore(); });+ ok(outside([0], true).length === 0, "a measured clip still hides text wholly outside it");+};diff --git a/skills/anidoodle/engine/test/productUITall.test.ts b/skills/anidoodle/engine/test/productUITall.test.tsnew file mode 100644index 0000000..969f1f4--- /dev/null+++ b/skills/anidoodle/engine/test/productUITall.test.ts@@ -0,0 +1,20 @@+// A PRODUCT WINDOW IN A TALL FRAME. On 9:16 a product's own screen is given a tall rectangle (the safe area+// less its margins), and its rows were capped at a desktop height, so the window came out at 70 % of that+// height, centred, with the lower third of the frame empty under it (a fresh critic). On a phone a list's+// rows are tall touch rows: in a tall rectangle they grow until the window fills it. A wide rectangle keeps+// the desktop rows exactly.+// node tools/test.mjs productUITall+import { uiWindow, type ProductUI } from "../src/canvas-core/productUI";++export const name = "productUI: a tall rectangle gets tall rows";+const WIDE_H = 1580.53; // the desktop window height before this change, measured (to the hundredth)+export const run = (ok: (cond: boolean, label: string) => void) => {+ const ui: ProductUI = { title: "Tally", nav: ["Inbox"], action: "Match all", command: "Ask…",+ before: { stats: [{ label: "Unmatched", value: 14 }], items: ["a", "b", "c", "d"].map((id) => ({ id, label: `Row ${id}`, value: "$1" })) },+ after: { stats: [{ label: "Unmatched", value: 0 }], items: ["a", "b", "c", "d"].map((id) => ({ id, label: `Row ${id}`, value: "$1" })) } };+ const tall = { x: 60, y: 300, w: 830, h: 1030 }, wide = { x: 100, y: 100, w: 1700, h: 1600 } /* not tall: under 1.05 high per wide */;+ const t = uiWindow(tall, ui, 32), w = uiWindow(wide, ui, 18);+ ok(t.h >= 0.85 * tall.h, `RED: in a tall rectangle the window fills it (${Math.round(t.h)} of ${tall.h} px, ${Math.round((100 * t.h) / tall.h)} %)`);+ ok(Math.abs(t.y + t.h / 2 - (tall.y + tall.h / 2)) < 1e-6, "it stays centred in its rectangle");+ ok(Math.abs(w.h - WIDE_H) < 0.01, `a wide rectangle keeps its desktop rows (${w.h.toFixed(2)} px, was ${WIDE_H.toFixed(2)})`);+};diff --git a/skills/anidoodle/engine/test/readable.test.ts b/skills/anidoodle/engine/test/readable.test.tsnew file mode 100644index 0000000..f82a3f5--- /dev/null+++ b/skills/anidoodle/engine/test/readable.test.ts@@ -0,0 +1,57 @@+// READABLE, PEOPLE AND END CARD TESTS. The kit helpers the ship checks expect films to use, held to the+// Brand-launch numbers: a typed reply's hold, one pace scalar, head-size placement and the end card grid.+// @ts-ignore: a plain ES module shared with the tools+import { MIN_READ_S as TR_MIN, READ_S_PER_WORD as TR_WORD, readingNeed } from "../tools/textrules.mjs";+// @ts-ignore: a plain ES module shared with the tools+import { RULES, layoutFindings, framesOf } from "../tools/framerules.mjs";+import { MIN_READ_S, READ_S_PER_WORD, chatHold, chatHoldFrames, paced, paceOf, readS } from "../src/canvas-core/readable";+import { headOf, placePerson } from "../src/canvas-core/people";+import { endCardLayout, type EndCardSpec } from "../src/canvas-core/endCard";++export const name = "readable";+export const run = (ok: (cond: boolean, label: string) => void) => {+ ok(MIN_READ_S === TR_MIN && READ_S_PER_WORD === TR_WORD, "the kit's reading rule is the one framecheck checks");+ const reply = "I can handle the non-human part. Ingrid has the human one.";+ ok(readS(reply) === readingNeed(reply) && Math.abs(readS(reply) - 3.3) < 1e-9, "an 11-word reply needs 3.3 s");+ const h = chatHold(reply, { cps: 58, think: 0.6 });+ ok(Math.abs(h.read - 3.3) < 1e-9 && Math.abs(h.typing - reply.length / 58) < 1e-9 && Math.abs(h.total - (0.6 + reply.length / 58 + 3.3)) < 1e-9, `a typed reply holds think + typing + the full read after the last character (${h.total.toFixed(2)} s)`);+ ok(h.read > 0.9 * 1.25, "NEGATIVE: the film's fixed 0.9 s hold (even x1.25) is under the read the helper gives");+ const slow = chatHold(reply, { cps: 58, think: 0.6, pace: 1.2 });+ ok(Math.abs(slow.read - 3.96) < 1e-9 && slow.typing === h.typing, "pace 1.2 stretches the think and the read, not the typing speed");+ const f = chatHoldFrames(reply, 30, { cps: 58 });+ ok(f.read === 99 && f.total === f.think + f.typing + f.read, "frames round up, so the hold never lands a frame short");+ ok(paceOf({ default: 1.1, coldOpen: 0.8 }, "coldOpen") === 0.8 && paceOf({ default: 1.1 }, "rest") === 1.1 && paced(2, 1.25) === 2.5, "pace per section with a default; paced() multiplies");++ // ---- people: the head of a cut-out from alpha, and placement by head height+ const w = 40, hh = 100, a = new Uint8Array(w * hh);+ const fill = (x0: number, x1: number, y0: number, y1: number) => { for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) a[y * w + x] = 255; };+ fill(12, 28, 5, 30); fill(17, 23, 30, 36); fill(2, 38, 36, 100); // head 5..30, neck 30..36, shoulders below+ const head = headOf(a, w, hh);+ ok(!!head && head.y0 === 5 && head.y1 >= 30 && head.y1 <= 35 && head.x0 === 12 && head.x1 === 28, `the head ends at the neck, the narrowest row under the crown (${JSON.stringify(head)})`);+ ok(headOf(new Uint8Array(100), 10, 10) === null, "an empty image has no head");+ const p1 = placePerson({ x0: 0, y0: 50, x1: 100, y1: 420 }, { cx: 500, crownY: 200, headPx: 300 }), p2 = placePerson({ x0: 0, y0: 20, x1: 60, y1: 210 }, { cx: 900, crownY: 200, headPx: 300 });+ ok(Math.abs((420 - 50) * p1.s - 300) < 1e-9 && Math.abs((210 - 20) * p2.s - 300) < 1e-9 && Math.abs(p1.y + 50 * p1.s - 200) < 1e-9, "two photos of different sizes come out with equal heads, crowns level");++ // ---- the end card grid, in every shape: inside the frame, no centred stack, no gap under 3 %, sponsors switchable+ const spec: EndCardSpec = { lockup: { aspect: 3.2, draw: () => {} }, date: "May 03, 2027", venue: "Santiago The Old Mill", cta: "Reserve a Spot!", colors: { ink: "#fff", accent: "#FFDE59", ctaInk: "#111" },+ sponsors: { list: ["Northwind", "Kestrel", "Bright Star", "Headland Media", "Appsworth", "Elmwood"].map((n, i) => ({ name: n, aspect: 2 + (i % 3) * 0.5, on: i < 4, draw: () => {} })) } };+ const measure = (t: string, font: string) => t.length * Number(/(\d+)px/.exec(font)![1]) * 0.55;+ for (const [W, H] of [[1920, 1080], [1080, 1080], [1080, 1350], [1080, 1920]]) {+ const L = endCardLayout(W, H, spec, measure);+ const rects = [L.lockup, L.date, L.venue, L.cta, ...(L.label ? [L.label] : []), ...L.logos];+ ok(rects.every((r) => r.x >= 0 && r.y >= 0 && r.x + r.w <= W && r.y + r.h <= H), `${W}x${H}: every part inside the frame`);+ ok(L.logos.length === 4, `${W}x${H}: the switched-off sponsors are left out (4 of 6 shown)`);+ const recs = [["date", L.date], ["venue", L.venue], ["cta", L.cta], ["label", L.label!]].map(([label, r]) => { const q = r as { x: number; y: number; w: number; h: number; px: number }; return { kind: "text", label, frame: 0, x0: q.x, y0: q.y, x1: q.x + q.w, y1: q.y + q.h, cut: false, alpha: 1, px: q.px }; });+ const boxes = [L.lockup, ...L.logos].map((r, i) => ({ kind: "box", label: `b${i}`, frame: 0, x0: r.x, y0: r.y, x1: r.x + r.w, y1: r.y + r.h, cut: false }));+ const fr = Array.from({ length: 30 }, (_, i) => i), by = framesOf(fr.flatMap((f) => [...recs, ...boxes].map((r) => ({ ...r, frame: f }))), fr);+ const found = layoutFindings(by, fr, { W, H, fps: 30 });+ ok(found.length === 0, `${W}x${H}: the card passes framecheck's layout rules${found.length ? `: ${found.map((x: { msg: string }) => x.msg).join(" | ")}` : ""}`);+ ok(L.label!.px >= Math.round(38 * Math.min(W, H) / 1080) && L.cta.px * (1080 / Math.min(W, H)) >= RULES.endPx, `${W}x${H}: the sponsors label is 38 px at 1080 and the CTA clears the last-second floor`);+ if (H / W > 1.5) ok(L.lockup.y >= H * 0.14 && L.logos.every((r) => r.y + r.h <= H * 0.75), "9:16: clear of the platforms' top and bottom bands");+ }+ // 9:16 with long lines (a product's tagline and install line): every line ends left of the platforms' right button column+ const long = endCardLayout(1080, 1920, { ...spec, date: "Bookkeeping that does itself", venue: "npm install tally · tally init" }, measure);+ ok([long.date, long.venue, long.cta].every((r) => r.x + r.w <= 1080 * 0.86), `9:16: long lines stay out of the right 14 % column (date ends ${Math.round(long.date.x + long.date.w)}, venue ${Math.round(long.venue.x + long.venue.w)}, limit ${1080 * 0.86})`);+ const wide = endCardLayout(1920, 1080, spec, measure);+ ok(wide.cta.x > 960 && Math.abs(wide.cta.y + wide.cta.h - 22 - (wide.venue.y + wide.venue.h)) < 1, "16:9: the CTA stamp sits right, on the venue's baseline (the approved v12 card)");+};diff --git a/skills/anidoodle/engine/test/renderBlurReport.test.ts b/skills/anidoodle/engine/test/renderBlurReport.test.tsnew file mode 100644index 0000000..6805790--- /dev/null+++ b/skills/anidoodle/engine/test/renderBlurReport.test.ts@@ -0,0 +1,15 @@+// RENDER'S BLUR REPORT (review L2). The blur mask keeps type sharp only where the frame's own canvas draws+// it: type composited from an offscreen layer blurs with the picture. The page's blur() now says how many+// layers holding type blurred (typeInLayers); render must carry that through the adapter and say it, so+// "type kept sharp on N frames" never overstates what the mask did.+const fsModule = "node:fs";+const { readFileSync } = await import(fsModule);++export const name = "render reports type that blurred inside layers (L2)";+export function run(ok: (cond: boolean, label: string) => void) {+ const adapter = readFileSync("tools/adapters/playwright.mjs", "utf8"), render = readFileSync("tools/render.mjs", "utf8");+ const blurLine = adapter.split("\n").find((l: string) => /^\s*blur: async/.test(l)) ?? "";+ ok(/typeInLayers: r\.typeInLayers/.test(blurLine), "the playwright adapter's blur() passes the page's typeInLayers through");+ ok(/cost\.push\(\{[^}]*typeInLayers: f\.typeInLayers/.test(render), "render records typeInLayers per frame");+ ok(/frame\(s\) composited type from layers that blurred/.test(render), "render prints how many frames composited type from layers that blurred");+}diff --git a/skills/anidoodle/engine/test/renderSidecar.test.ts b/skills/anidoodle/engine/test/renderSidecar.test.tsnew file mode 100644index 0000000..c2ebd1f--- /dev/null+++ b/skills/anidoodle/engine/test/renderSidecar.test.ts@@ -0,0 +1,13 @@+// THE RENDER SIDECAR (<file>.film.json) travels with the film when a person sends both. It must name the+// file by its name only: an absolute path carries the maker's home folder (their user name) to whoever+// receives it. No tool reads the path back; the sha256 is what ties the sidecar to the file.+const fsModule = "node:fs";+const { readFileSync } = await import(fsModule);++export const name = "render's sidecar names the file without its folder";+export function run(ok: (cond: boolean, label: string) => void) {+ const src = readFileSync("tools/render.mjs", "utf8"), write = src.match(/writeFileSync\(`\$\{out\}\.film\.json`, JSON\.stringify\(\{([^\n]*)/)?.[1] ?? "";+ ok(write.length > 0, "render.mjs writes the sidecar in one place (found it)");+ ok(/\bfile: basename\(out\)/.test(write), "the sidecar's file field is basename(out), never the absolute path");+ ok(!/\bfile: out\b/.test(write), "NEGATIVE: the absolute output path is not written into the sidecar");+}diff --git a/skills/anidoodle/engine/test/setTypeExit.test.ts b/skills/anidoodle/engine/test/setTypeExit.test.tsnew file mode 100644index 0000000..129ca06--- /dev/null+++ b/skills/anidoodle/engine/test/setTypeExit.test.ts@@ -0,0 +1,31 @@+// SET TYPE, LEAVING. A line that sinks out (setType's `out`) used to report its whole line to the frame+// probe on every frame of its exit. Once its glyphs had dropped below their window, the reader rules let+// the probe stand for the words again beside the last stray glyphs ("Month end, h"), a one-frame "read"+// that framecheck failed on a launch template film. A leaving line reports nothing: its glyphs speak for it.+// node tools/test.mjs setTypeExit+import { setType } from "../src/canvas-core/kinetic";+import type { Ctx, Env } from "../src/canvas-core/core";++export const name = "setType: a leaving line does not report itself whole";+export const run = (ok: (cond: boolean, label: string) => void) => {+ let m = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };+ const fills: string[] = [];+ const ctx = {+ font: "", fillStyle: "", textBaseline: "", globalAlpha: 1,+ setTransform: (a: number, b: number, c: number, d: number, e: number, f: number) => { m = { a, b, c, d, e, f }; },+ getTransform: () => m, save: () => {}, restore: () => {}, beginPath: () => {}, rect: () => {}, clip: () => {},+ measureText: (s: string) => ({ width: 10 * s.length }), fillText: (s: string) => { fills.push(s); },+ } as unknown as Ctx;+ const env = { W: 100, H: 100, scale: 1, root: true } as unknown as Env;+ const recs: { label: string }[] = [];+ const G = globalThis as unknown as { __ANIDOODLE_PROBE__?: unknown };+ G.__ANIDOODLE_PROBE__ = (r: { label: string }) => recs.push(r);+ try {+ setType(ctx, env, "Month end,", 10, 50, 40, 1);+ ok(recs.length === 1 && recs[0].label === "Month end,", `a standing line reports its box to the probe (${recs.length})`);+ recs.length = 0; fills.length = 0;+ setType(ctx, env, "Month end,", 10, 50, 40, 1, { out: 0.5 });+ ok(recs.length === 0, `RED: a line on its way out reports nothing (got ${recs.length}: ${recs.map((r) => r.label).join(", ")})`);+ ok(fills.length > 0, "its glyphs are still drawn while they sink");+ } finally { delete G.__ANIDOODLE_PROBE__; }+};diff --git a/skills/anidoodle/engine/test/shiprules.test.ts b/skills/anidoodle/engine/test/shiprules.test.tsnew file mode 100644index 0000000..a010466--- /dev/null+++ b/skills/anidoodle/engine/test/shiprules.test.ts@@ -0,0 +1,57 @@+// SHIP RULES TESTS. The decisions ship.mjs makes, each with a case that must fail: an open P0 from a+// critic, a film over its length budget, a skipped gate, and a check that could not look.+// @ts-ignore: a plain ES module shared with the tools+import { blindRow, lengthRow, reviewRows, row, scannerRows, sheetFrames, shipEvery, verdict, waiver } from "../tools/shiprules.mjs";++export const name = "shiprules";+export const run = (ok: (cond: boolean, label: string) => void) => {+ // ---- review ledger (R2, R3, R4)+ const led = { findings: [{ id: "r1-1", p: "P0", status: "open", note: "the middle 37-72 s is a carousel" }, { id: "r1-2", p: "P1", status: "open", note: "fades through olive" }, { id: "r1-3", p: "P0", status: "fixed", note: "five-ball blob" }],+ notes: ["make it 20% slower", "that last slide composition is a mess", "who is gonna read this overload of info?", "ugly... too many slides now"].map((text, i) => ({ at: `21:3${i}`, from: "director", text })) };+ const rr = reviewRows(led, "reviews/x.json");+ ok(rr[0].status === "FAIL" && rr[0].lines.length === 2, "NEGATIVE: an open P0 from the critic fails the ship; open P0 and P1 are listed");+ ok(rr[1]?.step === "notes" && rr[1].lines.length === 3 && rr[1].lines[2].includes("too many slides"), "the person's last three notes are printed verbatim, newest last");+ ok(reviewRows({ findings: [{ p: "P0", status: "fixed" }] }, "r.json")[0].status === "PASS", "every P0 fixed passes");+ ok(reviewRows({ findings: [{ p: "P1" }] }, "r.json")[0].status === "FLAG", "an open P1 (no status = open) flags, it does not pass silently");+ ok(reviewRows(null, "r.json")[0].status === "FAIL", "NEGATIVE H3: no review ledger cannot look, so it FAILS (it was a FLAG, and FLAG passed)");+ ok(reviewRows(null, "r.json", null, { checks: { none: { review: "a test fixture nobody is shown" } } })[0].status === "NONE", "H3 no ledger with a declared reason (meta.checks.none.review) is NONE, and the reason is printed");+ ok(reviewRows(null, "r.json", "Unexpected token")[0].status === "FAIL", "NEGATIVE: an unreadable ledger fails");+ // ---- length (D1)+ const meta = (s: number, length?: { target: number; max: number }) => ({ durationFrames: Math.round(s * 30), fps: 30, checks: length ? { length } : undefined, shots: [{ id: "a", start: 0, end: Math.round(s * 30) }] });+ ok(lengthRow(meta(108.7, { target: 75, max: 90 }), null).status === "FAIL", "NEGATIVE: the 108.7 s cut against a 90 s max fails");+ ok(lengthRow(meta(88.8, { target: 75, max: 90 }), null).status === "FLAG", "88.8 s is under max, over target: flagged");+ ok(lengthRow(meta(70, { target: 75, max: 90 }), null).status === "PASS", "under target passes");+ ok(lengthRow(meta(70), { floorS: 40, spareS: 12 }).status === "FAIL" && /reading needs 40\.0 s/.test(lengthRow(meta(70), { floorS: 40, spareS: 12 }).detail), "NEGATIVE H3: no budget cannot look, so it FAILS, and the reading floor is printed");+ ok(lengthRow({ ...meta(70), checks: { none: { length: "a loop with no fixed length" } } }, null).status === "NONE", "H3 no budget with a declared reason is NONE");+ // ---- L4: a budget with no max used to never fail+ ok(lengthRow(meta(100, { target: 75 } as never), null).status === "FAIL", "NEGATIVE L4: a budget with only a target fails a film past it (max falls back to target)");+ ok(lengthRow(meta(70, { max: "90" } as never), null).status === "FAIL", "NEGATIVE L4: a budget with no number to judge against fails, never passes");+ // ---- L3: a ledger of the wrong shape is a FAIL row, never a crash with no SHIP.md+ let l3 = "crash"; try { l3 = reviewRows({ findings: { id: "r1", p: "P0" } }, "r.json")[0].status; } catch { /* the crash is the bug */ }+ ok(l3 === "FAIL", `NEGATIVE L3: findings as an object is a FAIL row (got ${l3})`);+ let l3b = "crash"; try { l3b = reviewRows({ findings: [null, "x"], notes: "not a list" }, "r.json")[0].status; } catch { /* the crash is the bug */ }+ ok(l3b === "FAIL", `NEGATIVE L3: findings that are not objects, or notes that are not a list, fail (got ${l3b})`);+ // ---- the critic sheet and the verdict+ const fr = sheetFrames({ durationFrames: 300, fps: 30, shots: [{ start: 0 }, { start: 75 }] });+ ok(fr.includes(0) && fr.includes(75) && fr.includes(299) && fr.includes(60), `sheet: every 2 s, every shot start, the last frame (${fr.join(",")})`);+ ok(sheetFrames({ durationFrames: 30 * 600, fps: 30, shots: [] }).length === 60, "a long film's sheet is capped at 60 frames");+ ok(verdict([row("a", "PASS", ""), row("b", "NONE", ""), row("c", "FLAG", "")], false) === "PASS", "PASS, NONE (checked, absent) and FLAG (looked, review it) rows pass");+ ok(verdict([row("a", "PASS", ""), row("b", "N/A", "")], false) === "FAIL", "NEGATIVE H3: a row whose status is anything else (N/A) fails the ship");+ // ---- H3: a scanner check that did not look+ const na = { checks: { temperament: { status: "N/A", reason: "no temperament declared" }, slidecut: { status: "PASS" }, faces: { status: "NONE", reason: "no photos drawn" } } };+ const sr = scannerRows("motion", na, {});+ ok(sr.find((r: { step: string }) => r.step === "motion:temperament")?.status === "FAIL", "NEGATIVE H3: a scanner's N/A (did not look) is a FAIL row, never FLAG");+ ok(sr.find((r: { step: string }) => r.step === "motion:faces")?.status === "NONE" && sr.find((r: { step: string }) => r.step === "motion:slidecut")?.status === "PASS", "H3 NONE (looked, nothing there) stays NONE; PASS stays PASS");+ ok(scannerRows("motion", na, { checks: { none: { "motion:temperament": "an archive cut, no brand motion" } } }).find((r: { step: string }) => r.step === "motion:temperament")?.status === "NONE", "H3 a declared reason turns the blind row into NONE with the reason");+ ok(waiver({ checks: { none: { review: " " } } }, "review") === null && blindRow({}, "x", "why").status === "FAIL", "H3 an empty reason is no reason: still FAIL");+ // the whole H3 input: no temperament, no brand colours, no ledger, no budget. It used to print SHIP: PASS.+ const h3 = [...scannerRows("motion", na, {}), ...reviewRows(null, "r.json"), lengthRow(meta(10), null)];+ ok(verdict(h3, false) === "FAIL", "NEGATIVE H3: a film where several checks could not look does not ship");+ // ---- M2: ship's --every+ ok(shipEvery(undefined).every === 1 && !shipEvery(undefined).quick, "M2 ship checks every frame by default");+ ok(shipEvery("3").every === 3 && shipEvery("3").quick === true, "NEGATIVE M2: ship --every 3 is a quick look: the verdict is QUICK, never PASS");+ let m2 = ""; try { shipEvery("abc"); } catch (e) { m2 = String((e as Error).message); }+ ok(/--every/.test(m2), "NEGATIVE M2: ship --every abc is refused, never passed through to check frame 0 alone");+ ok(verdict([row("a", "PASS", ""), row("b", "FAIL", "")], false) === "FAIL", "NEGATIVE: any FAIL row fails the ship");+ ok(verdict([row("a", "PASS", "")], true) === "QUICK", "NEGATIVE: a --quick run (gate skipped) is QUICK, never PASS");+};diff --git a/skills/anidoodle/engine/test/splitReadHold.test.ts b/skills/anidoodle/engine/test/splitReadHold.test.tsnew file mode 100644index 0000000..bbbf276--- /dev/null+++ b/skills/anidoodle/engine/test/splitReadHold.test.ts@@ -0,0 +1,25 @@+// A SPLIT BEAT'S WORDS ARE READ FROM THE MOMENT THEY ARE SET. On a clean split beat reached by a travel, the+// words rise on the way in and the action is pressed after them; between the landing and the press the+// product rests in its before state while the words are read. The declared reading hold began only once the+// after state had landed, so those half-second of reading read to the gate as dead air+// (launchExampleCleanChat 16:9, frames 661 to 697). The hold now starts when the words are set.+// The press's own short hold and the end card's are unchanged.+// node tools/test.mjs splitReadHold+import { launchExampleCleanChat } from "../src/canvas-core/launchExampleCleanChat";+import type { LaunchFilm } from "../src/canvas-core/launchTemplate";++export const name = "a split beat's words are read from when they are set";+export const run = (ok: (cond: boolean, label: string) => void) => {+ for (const sh of ["16x9", "9x16"]) {+ const f = launchExampleCleanChat.reshape(sh) as LaunchFilm, holds = (f.meta.holds ?? []) as [number, number][];+ // the press's hold is the short one inside the inbox beat (560 to 960 at 60 fps)+ const press = holds.find(([a, b]) => a > 560 && a < 960 && b - a < 10);+ if (!press) { ok(false, `${sh}: the inbox beat declares its press`); continue; }+ const covered = (x: number) => holds.some(([a, b]) => a <= x && x <= b);+ const gaps = []; for (let x = press[0] - 40; x < press[0]; x++) if (!covered(x)) gaps.push(x);+ ok(gaps.length === 0, `RED ${sh}: the 40 frames before the press, words set and being read, are declared (${gaps.length} not: ${gaps[0] ?? ""}-${gaps[gaps.length - 1] ?? ""})`);+ // and the hold still ends where the words sink, not at the end card+ const read = holds.find(([a, b]) => a <= press[0] - 1 && b >= press[1] && b - a > 10);+ ok(!!read && read[1] < 960, `${sh}: the reading hold ends inside the beat (${read?.join("-")})`);+ }+};diff --git a/skills/anidoodle/engine/test/splitWordsFit.test.ts b/skills/anidoodle/engine/test/splitWordsFit.test.tsnew file mode 100644index 0000000..49c854b--- /dev/null+++ b/skills/anidoodle/engine/test/splitWordsFit.test.ts@@ -0,0 +1,23 @@+// SPLIT WORDS FIT THEIR COLUMN. On a phone the split beat stacks its words over the live product, in a+// column a third of the window tall. The words were sized to the column's width only: the clean scaffold's+// stand-in "TODO the feature, TODO in five words." wrapped to four lines and ran down over the product+// window (framecheck: text over text, and over the window's edge, frames 595 to 890 on 9:16). They are now+// set smaller and wrapped again until they fit the column's height too, never under the phone-safe size.+// node tools/test.mjs splitWordsFit+import { makeLaunchFilm, type LaunchFilm } from "../src/canvas-core/launchTemplate";+import { launchExampleClean } from "../src/canvas-core/launchExampleClean";+import type { ProductUI } from "../src/canvas-core/productUI";++export const name = "split words fit their column";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const ui: ProductUI = { title: "T", action: "Go", before: { items: [{ id: "a", label: "x" }] }, after: { items: [{ id: "a", label: "x", done: true }] } };+ const f = makeLaunchFilm({ title: "TODO Product", preset: "clean", fps: 60, asks: [{ kind: "ui", ui, prompt: "TODO what a user asks the product" }, { kind: "ui", ui, split: [{ text: "TODO the feature,", style: "ink", color: "#15161a" }, { text: "TODO in five words.", style: "ink", color: "#2f54eb" }] }], words: [[{ text: "TODO CLAIM.", style: "ink", color: "#15161a" }]], tagline: "t", install: ["npm i x"], bpm: 90, claimBar: 6, score: null });+ for (const [id, film] of [["scaffold words", f], ["clean example", launchExampleClean as LaunchFilm]] as const) for (const sh of ["16x9", "9x16"]) {+ const g = (film.reshape(sh) as Partial<LaunchFilm>).grammar;+ for (const q of g?.splits ?? []) ok(q.tall <= q.room.h + 0.5, `RED ${id} ${sh}: ask ${q.i}'s words (${q.lines.length} lines at ${q.size.toFixed(0)} px) take ${q.tall.toFixed(0)} px of their ${q.room.h.toFixed(0)} px column`);+ if (!g?.splits?.length) ok(false, `${id} ${sh}: the film exposes its split words`);+ }+ // the clean example's words, which already fitted, are set exactly as before+ const s9 = ((launchExampleClean as LaunchFilm).reshape("9x16") as LaunchFilm).grammar.splits;+ ok(s9.every((q) => q.lines.length === 2), `the clean example's words keep their two lines on 9:16 (${s9.map((q) => q.lines.join(" / ")).join("; ")})`);+};diff --git a/skills/anidoodle/engine/test/subtitles.test.ts b/skills/anidoodle/engine/test/subtitles.test.tsindex 0c78b57..d65d14d 100644--- a/skills/anidoodle/engine/test/subtitles.test.ts+++ b/skills/anidoodle/engine/test/subtitles.test.ts@@ -92,4 +92,15 @@ export const run = (ok: (cond: boolean, label: string) => void) => {ok(b2.y + b2.h <= 1080 * 0.95 && b2.x >= 1920 * 0.05, "16:9: a phrase stays inside 5 % margins");const b3 = subtitleBox(fake, env169, e0, 50, { home: (f) => (f < 48 ? [0.3, 0.2] : [0.7, 0.2]) });ok(Math.abs(b3.x + b3.w / 2 - 0.7 * 1920) < 1, "a per-shot home moves the phrase only where the function says (a cut)");++ // L7: a line whose display text is "" reaches the planner with no words; phrasePlan read words[0] of+ // an empty list and `narrate check` died on a TypeError instead of saying which line was empty.+ {+ const tm = timing([["a", "the first line is fine"], ["b", "so is the third"]]);+ tm.lines.splice(1, 0, { id: "blank", text: "", start: tm.lines[0].end + 6, end: tm.lines[0].end + 12, words: [] });+ let plan: ReturnType<typeof phrasePlan> | null = null, err = "";+ try { plan = phrasePlan(tm); } catch (e) { err = String(e); }+ ok(!!plan && plan.problems.some((p) => p.includes("blank") && p.includes("no words")), `L7 a line with no words is a named problem, not a crash (${err || plan?.problems.join(" | ")})`);+ ok(!!plan && plan.events.every((e) => e.text.length > 0) && plan.events.some((e) => e.line === "b"), "L7 and the lines around it are still planned");+ }};diff --git a/skills/anidoodle/engine/test/threeChecks.test.ts b/skills/anidoodle/engine/test/threeChecks.test.tsindex 57e00c3..48e36ff 100644--- a/skills/anidoodle/engine/test/threeChecks.test.ts+++ b/skills/anidoodle/engine/test/threeChecks.test.ts@@ -4,7 +4,7 @@// node tools/test.mjs threeChecksimport * as THREE from "three";import { grip, gripFrame, handle, limb, makeRig, part, pose, type Rig } from "../src/three-core/rig";-import { checkGrip, checking, collectChecks, labelVisible, pathClear, placeLabel, faceCamera, proximity, registerGrip, registerRig, runChecks, screenSizeOk, selfClear, type Finding } from "../src/three-core/checks3d";+import { checkGrip, checking, collectChecks, labelVisible, pathClear, placeLabel, faceCamera, proximity, registerGrip, registerRig, runChecks, screenSizeOk, selfClear, surfacePoints, type Finding } from "../src/three-core/checks3d";import { rigDemoFrame } from "../src/canvas-core/threeRigDemo";const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);@@ -119,6 +119,39 @@ export const run = (ok: (cond: boolean, label: string) => void) => {const r = selfClear(h, { frame: 3 });ok(!r.ok && r.findings[0].kind === "self" && r.findings[0].where.includes("arms.right"), `RED a hand driven into its own torso: ${r.findings[0]?.where}`);}+ // ---- L12: a rig built in centimetres (a 60 x 80 x 40 torso). The sampler kept 6 passes of 1.6x and+ // then gave up, so one 20-unit box at the self-check spacing came back with 307,800 points (cap 6000).+ {+ const big = new THREE.Mesh(new THREE.BoxGeometry(20, 20, 20), mat);+ const t0 = Date.now(), n = surfacePoints(big, 0.012).length, ms = Date.now() - t0;+ ok(n <= 6000, `L12 a 20-unit box sampled at 0.012 stays under the 6000-point cap (${n} points, ${ms} ms)`);+ const cm = makeRig("cm", { hipHeight: 100 });+ part(cm, cm.body, "torso", new THREE.Mesh(new THREE.BoxGeometry(60, 80, 40), mat)).position.y = 40;+ for (const [side, s] of [["left", 1], ["right", -1]] as const) limb(cm, `arms.${side}`, { at: [36 * s, 75, 0], lengths: [35, 35], radius: 5, rest: [5 * s, -65, 5], pole: [20 * s, 0, -100], material: mat,+ end: () => new THREE.Mesh(new THREE.SphereGeometry(6, 12, 8), mat) });+ pose(cm, {}); scene(cm.root);+ const c0 = Date.now(), green = selfClear(cm), cms = Date.now() - c0;+ ok(green.ok && cms < 1500, `L12 GREEN a centimetre rig at rest is clean, and checked in ${cms} ms`);+ pose(cm, { arms: { right: { target: v3(5, 135, 0) } } });+ const red = selfClear(cm, { frame: 3 });+ ok(!red.ok && red.findings[0].where.includes("arms.right"), `L12 RED the same rig with a hand in its torso is still caught: ${red.findings[0]?.where}`);+ }+ // ---- H7: a held prop before its popIn starts (scale 2.2e-16, hidden). The sampler asked for+ // unbounded points at the handle's tiny radius: frame 0 stalled, then threw RangeError.+ {+ const h = holder(), p = lantern(); scene(h.root, p); holding(h, p, v3(-0.3, 1.2, 0.3));+ p.scale.setScalar(2.2e-16); p.visible = false; p.updateMatrixWorld(true);+ let res: ReturnType<typeof checkGrip> | null = null, err = ""; const t0 = Date.now();+ try { res = checkGrip(h, h.limbs["arms.right"], p, 0); } catch (e) { err = String(e); }+ ok(!!res && res.ok && Date.now() - t0 < 500, `H7 a hidden, popping-in prop is skipped, fast and without a crash (${err || `${Date.now() - t0} ms`})`);+ p.visible = true; p.scale.setScalar(1e-5); p.updateMatrixWorld(true);+ res = null; err = ""; const t1 = Date.now();+ try { res = checkGrip(h, h.limbs["arms.right"], p, 0); } catch (e) { err = String(e); }+ ok(!!res && res.ok && Date.now() - t1 < 500, `H7 a visible prop at a thousandth of its size is too small to judge: skipped (${err || `${Date.now() - t1} ms`})`);+ const box = new THREE.Group(); box.add(p); scene(h.root, box); box.visible = false; p.scale.setScalar(1);+ res = checkGrip(h, h.limbs["arms.right"], p, 0);+ ok(res.ok, "H7 a prop inside a hidden group never counts");+ }// ---- pathClear (walking through a closed prop, lesson 22){diff --git a/skills/anidoodle/engine/test/threeMograph.test.ts b/skills/anidoodle/engine/test/threeMograph.test.tsindex bf4d7a0..4f9064c 100644--- a/skills/anidoodle/engine/test/threeMograph.test.ts+++ b/skills/anidoodle/engine/test/threeMograph.test.ts@@ -3,6 +3,8 @@// both shapes to equal counts by arc length.// node tools/test.mjs threeMographimport * as THREE from "three";+import type { Env } from "../src/canvas-core/core";+import { defaultFont, text3d } from "../src/three-core/type3d";import { assemble, dropIn, explode, extrudeIn, fadeIn, fadeOut, grid, growFrom, indicate, kinetic, lagged, morph, moveAlongPath, popIn, popOut, resample, riseFromFloor, wave, wiggle, writeOn, writePoints, writeTube } from "../src/three-core/mograph";export const name = "threeMograph";@@ -70,6 +72,32 @@ export const run = (ok: (cond: boolean, label: string) => void) => {kinetic(word, 0, 2, 3); const k0 = word.children.map((c) => c.visible);kinetic(word, 50, 2, 3); ok(k0.every((v) => !v) && word.children.map(pose).every((p, i) => p === wr[i]), "kinetic: letters hidden before, all at rest after");kinetic(word, 9, 2, 3); ok(word.children.map((c) => c.visible).join() === "true,true,true,false", "and each letter enters 3 frames after the one before");+ // M1: text3d letters share one material, so "rise" set every letter's opacity to the last letter's.+ // The old test looked at .visible only; this one reads the opacity each letter is drawn with.+ {+ const env = { W: 1920, H: 1080, scale: 1, cache: new Map(), canvas: () => { throw new Error("no canvas in node"); } } as unknown as Env;+ const own = new THREE.MeshStandardMaterial({ color: "#336699" });+ for (const [label, abcd] of [["default material", text3d(env, defaultFont(), "ABCD")], ["one material passed in", text3d(env, defaultFont(), "ABCD", { material: own })]] as const) {+ const L = abcd.userData.letters, op = () => L.map((l) => (l.material as THREE.Material).opacity);+ kinetic(abcd, 9, 2, 3); const mid = op();+ ok(mid[0] > 0.5 && mid[1] > 0.2 && mid[2] > 0 && mid[3] === 0 && mid[0] > mid[1] && mid[1] > mid[2], `M1 kinetic rise on text3d (${label}): each letter fades in on its own (${mid.map((x) => x.toFixed(2)).join(", ")})`);+ kinetic(abcd, 0, 2, 3); kinetic(abcd, 50, 2, 3);+ ok(op().every((x) => x === 1) && L.every((l) => !(l.material as THREE.Material).transparent && l.visible), `M1 and after the last letter lands every letter is fully opaque again, drawn opaque (${label})`);+ kinetic(abcd, 9, 2, 3); ok(op().join() === mid.join(), `M1 the same frame drawn again gives the same opacities (${label})`);+ }+ ok(own.opacity === 1 && !own.transparent, "M1 the material passed in is left as it was (each letter fades its own copy)");+ }+ // L14: a one-point shape (a dot morphing into a line) threw a TypeError in resample+ {+ let err = ""; let r1: number[][] = [];+ try { r1 = resample([[1, 2, 3]], 4); } catch (e) { err = String(e); }+ ok(!err && r1.length === 4 && r1.every((p) => p.join() === "1,2,3"), `L14 resample of a one-point shape gives that point n times (${err || r1.length})`);+ let m: number[][] = []; err = "";+ try { m = morph([[0, 0, 0]], [[0, 0, 0], [2, 0, 0]], 0.5); } catch (e) { err = String(e); }+ ok(!err && m.length === 2 && m[1][0] === 1, `L14 a dot morphs into a line (${err || JSON.stringify(m)})`);+ let threw = ""; try { resample([], 3); } catch (e) { threw = String(e); }+ ok(threw.includes("resample"), `L14 an empty shape is refused with a clear error (${threw})`);+ }// 4. paths: writeOn draws whole tube segments, moveAlongPath runs at constant speedconst curve = new THREE.CatmullRomCurve3([new THREE.Vector3(0, 0, 0), new THREE.Vector3(1, 2, 0), new THREE.Vector3(1.2, 2.1, 0), new THREE.Vector3(5, 0, 1)]);diff --git a/skills/anidoodle/engine/test/threeStage.test.ts b/skills/anidoodle/engine/test/threeStage.test.tsnew file mode 100644index 0000000..719397e--- /dev/null+++ b/skills/anidoodle/engine/test/threeStage.test.ts@@ -0,0 +1,28 @@+// THREE STAGE TESTS. src/three-core/stage.ts keeps one renderer per size and shadow setting. Its+// tone mapping and exposure belong to the SHOT, so each draw3d must set them: a renderer cached from+// an earlier shot must not lend that shot's look to the next one (or the look depends on draw order).+// node tools/test.mjs threeStage+import * as THREE from "three";+import type { Ctx, Env } from "../src/canvas-core/core";+import { draw3d, stage } from "../src/three-core/stage";++export const name = "threeStage";+export const run = (ok: (cond: boolean, label: string) => void) => {+ // a stand-in renderer: records what each render saw (no WebGL in node)+ const seen: string[] = [];+ const renderer = { toneMapping: THREE.ACESFilmicToneMapping as THREE.ToneMapping, toneMappingExposure: 1, shadowMap: { enabled: false, needsUpdate: false }, domElement: {},+ setClearColor() {}, getContext: () => ({ isContextLost: () => false }), render() { seen.push(`${renderer.toneMapping}@${renderer.toneMappingExposure}`); } };+ const ctx = new Proxy({}, { get: () => () => {}, set: () => true }) as unknown as Ctx;+ const env = { W: 64, H: 36, scale: 1, cache: new Map(), webgl: () => { throw new Error("the renderer is already cached"); } } as unknown as Env;+ env.cache.set(`three:stage:${64 * 2}x${36 * 2}:0`, { renderer, w: 128, h: 72, ss: 2 });+ ok(stage(env).renderer === (renderer as unknown), "GREEN the stand-in is the cached renderer draw3d will use");+ const scene = new THREE.Scene(), cam = new THREE.PerspectiveCamera();+ draw3d(ctx, env, scene, cam, { exposure: 1.6 });+ draw3d(ctx, env, scene, cam, { exposure: 0.7, toneMapping: THREE.NeutralToneMapping });+ draw3d(ctx, env, scene, cam);+ const want = [`${THREE.ACESFilmicToneMapping}@1.6`, `${THREE.NeutralToneMapping}@0.7`, `${THREE.ACESFilmicToneMapping}@1`];+ ok(seen.join() === want.join(), `M12 every draw3d renders with its own exposure and tone mapping, whatever was drawn before (${seen.join(" ")})`);+ seen.length = 0;+ draw3d(ctx, env, scene, cam); draw3d(ctx, env, scene, cam, { exposure: 1.6 });+ ok(seen.join() === [want[2], want[0]].join(), "M12 the same shots drawn in the other order look the same");+};diff --git a/skills/anidoodle/engine/test/threeTime.test.ts b/skills/anidoodle/engine/test/threeTime.test.tsnew file mode 100644index 0000000..cb20b58--- /dev/null+++ b/skills/anidoodle/engine/test/threeTime.test.ts@@ -0,0 +1,20 @@+// THREE TIME EDGE TESTS. src/three-core/time.ts on the inputs a film can hand it by mistake: a spring+// at 0 fps, a story clock with no anchors. Each must fail loudly with a message that says what to fix,+// never return NaN (a NaN position draws nothing and no check notices) or throw a bare TypeError.+// node tools/test.mjs threeTime+import { spring, storyClock } from "../src/three-core/time";++const err = (f: () => unknown) => { try { const v = f(); return `returned ${v}`; } catch (e) { return String(e); } };++export const name = "threeTime";+export const run = (ok: (cond: boolean, label: string) => void) => {+ ok(spring(10, 0, 24) > -1 && spring(10, 0, 24) < 1 && spring(0, 0, 24) === 1 && spring(-1, 0, 24) === 0, "GREEN a spring at 24 fps starts at 1, rings inside +-1, is 0 before its kick");+ for (const [label, f] of [["fps 0", () => spring(5, 0, 0)], ["fps 0 at the kick", () => spring(0, 0, 0)], ["freq 0", () => spring(5, 0, 24, 0)], ["fps NaN", () => spring(5, 0, NaN)]] as const) {+ const e = err(f);+ ok(e.includes("spring:"), `L14 spring with ${label} is refused by name, not NaN (${e})`);+ }+ const e = err(() => storyClock([]));+ ok(e.includes("storyClock:"), `L14 storyClock([]) is refused when it is built, not a TypeError on first use (${e})`);+ const one = storyClock([[10, 40]]);+ ok(one.real(12) === 42 && one.story(42) === 12, "GREEN one anchor is a plain offset both ways");+};diff --git a/skills/anidoodle/engine/test/threeTransitions.test.ts b/skills/anidoodle/engine/test/threeTransitions.test.tsindex ecbd210..c04a352 100644--- a/skills/anidoodle/engine/test/threeTransitions.test.ts+++ b/skills/anidoodle/engine/test/threeTransitions.test.ts@@ -49,6 +49,25 @@ export const run = (ok: (cond: boolean, label: string) => void) => {let grows = true; for (let e = 0; e < 1; e += 0.1) { const a = noiseMask(5, e, mw, mh).alpha, b = noiseMask(5, e + 0.1, mw, mh).alpha; if (b.some((v, i) => v < a[i])) grows = false; }ok(grows, "the blots only grow");ok(noiseMask(5, 0.5, mw, mh, { ink: false }).ink === null, "ink: false draws no rim");+ // L15: the rim colour went through a hex-only parser, so ink: "red" drew a BLACK rim, silently.+ // Run the real transition on recording layers and read the colour the rim was painted with.+ {+ const rimRGB = (ink: string) => {+ const puts: Uint8ClampedArray[] = [];+ const fake = (): Ctx => new Proxy({}, { get: (_t, k) => k === "createImageData" ? (w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }) : k === "putImageData" ? (img: { data: Uint8ClampedArray }) => puts.push(img.data) : k === "createLinearGradient" || k === "createRadialGradient" ? () => ({ addColorStop() {} }) : () => {}, set: () => true }) as unknown as Ctx;+ const env = { W: 64, H: 36, scale: 1, cache: new Map(), canvas: () => ({ canvas: {}, ctx: fake() }) } as unknown as Env;+ transition(fake(), env, 0.5, noiseWipe(5, { ink, inkWidth: 0.2 }), () => {}, () => {});+ const rim = puts[1]; if (!rim) return "no rim drawn";+ for (let q = 0; q < rim.length; q += 4) if (rim[q + 3] > 0) return [rim[q], rim[q + 1], rim[q + 2]].join(",");+ return "rim empty";+ };+ ok(rimRGB("#14112a") === "20,17,42", `GREEN a hex ink paints the rim that colour (${rimRGB("#14112a")})`);+ ok(rimRGB("red") === "255,0,0", `L15 a CSS colour name paints the rim that colour, not black (${rimRGB("red")})`);+ ok(rimRGB("rgb(10, 200, 30)") === "10,200,30", `L15 rgb() works too (${rimRGB("rgb(10, 200, 30)")})`);+ ok(rimRGB("#abc") === "170,187,204", `GREEN short hex (${rimRGB("#abc")})`);+ let e = ""; try { noiseWipe(5, { ink: "not-a-colour" }); } catch (x) { e = String(x); }+ ok(e.includes("noiseWipe"), `L15 an ink that is not a colour is refused when the wipe is made (${e || "no error"})`);+ }// 5. slide: A leaves as B arrives, B lands exactly homefor (const dir of ["left", "right", "up", "down"] as Dir[]) {diff --git a/skills/anidoodle/engine/test/track.test.ts b/skills/anidoodle/engine/test/track.test.tsnew file mode 100644index 0000000..f6ec794--- /dev/null+++ b/skills/anidoodle/engine/test/track.test.ts@@ -0,0 +1,96 @@+// EXTERNAL TRACK TESTS. Tempo, bars, the real end and the stops of a supplied track; cut lists read the+// way people write them; cuts refused for the faults that broke a brand launch film's mix; the edit's bar+// grid; and pitch salience, calibrated so short strikes pass and notes fail.+// node tools/test.mjs track+import { analyzeTrack, parseSegs, planCut, renderCut, trackGrid, pitchSalience, lastSoundOf, stemCues, chroma, keyOf, PITCHED } from "../src/canvas-core/music/track";+import { renderSfx, sfxVariants } from "../src/canvas-core/music/sfxKit";++export const name = "external track (analyse, cut, grid, pitch)";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const throws = (fn: () => unknown, re: RegExp, label: string) => { try { fn(); ok(false, `${label} (did not throw)`); } catch (e) { ok(re.test((e as Error).message), `${label}: ${(e as Error).message.slice(0, 90)}`); } };+ // a synthetic "track": 120 bpm, first downbeat at 0.25 s, a kick on every downbeat and a hat on every+ // beat, a designed stop over bar 6, then 3 s of silence after the last note+ const sr = 16000, len = 30, music = (bpm = 120, d0 = 0.25, endS = 27, stop: [number, number] | null = [12.25, 13.25]) => {+ const n = sr * len, L = new Float32Array(n), beat = 60 / bpm;+ let seed = 7; const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff - 0.5; };+ for (let k = 0; d0 + k * beat < endS; k++) {+ const t0 = d0 + k * beat; if (stop && t0 >= stop[0] - 1e-6 && t0 < stop[1]) continue;+ const a = Math.round(t0 * sr), down = k % 4 === 0;+ for (let i = 0; i < sr * 0.25 && a + i < n; i++) { const t = i / sr; L[a + i] += (down ? 0.6 * Math.sin(2 * Math.PI * 60 * t) * Math.exp(-t / 0.08) : 0) + 0.15 * rnd() * Math.exp(-t / 0.015) + 0.05 * Math.sin(2 * Math.PI * 330 * t) * Math.exp(-t / 0.2); }+ }+ // a quiet sustained pad under everything except the stop, as real music has (hits alone decay to silence)+ for (let i = 0; i < Math.round(endS * sr); i++) { const t = i / sr; if (!(stop && t >= stop[0] && t < stop[1])) L[i] += 0.03 * Math.sin(2 * Math.PI * 220 * t); }+ return [L, L.slice()] as [Float32Array, Float32Array];+ };+ const [L, R] = music(), a = analyzeTrack(L, R, sr);+ ok(Math.abs(a.bpm - 120) < 0.2, `tempo found: ${a.bpm} bpm (120 played)`);+ ok(Math.abs(a.downbeatS - 0.25) < 0.02, `first downbeat found on the kick: ${a.downbeatS} s (0.25 played)`);+ ok(Math.abs(a.lastSoundS - 27.2) < 0.4 && a.tailS > 2.3, `the real end: last note ${a.lastSoundS} s, ${a.tailS} s of silence after it (27.0 + the ring)`);+ ok(a.stops.some((s) => Math.abs(s.atS - 12.4) < 0.4 && s.lenS >= 0.5), `the designed stop is found: ${JSON.stringify(a.stops)}`);+ ok(a.bars.length >= 14 && Math.abs(a.bars[1].t - 2.25) < 0.03, `bars on the grid: bar 1 at ${a.bars[1]?.t} s`);+ ok(a.sections.some((s) => s.level === "silent" || s.level === "quiet"), `sections mark the stop and the tail: ${a.sections.map((s) => s.level).join(",")}`);+ ok(analyzeTrack(L, R, sr, { bpm: 120 }).tempoCandidates.length === 0, "a pinned tempo is used as given");+ throws(() => analyzeTrack(L.subarray(0, sr), R.subarray(0, sr), sr), /at least 2 s/, "a track too short to measure is refused");+ // key: an A minor triad spread over octaves reads as A minor+ const n = sr * 3, k = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr; k[i] = 0.3 * Math.sin(2 * Math.PI * 220 * t) + 0.2 * Math.sin(2 * Math.PI * 261.63 * t) + 0.2 * Math.sin(2 * Math.PI * 329.63 * t) + 0.1 * Math.sin(2 * Math.PI * 110 * t); }+ ok(keyOf(chroma(k, sr)).name === "Am", `an A minor chord reads as Am (${keyOf(chroma(k, sr)).name})`);++ // ---- cut lists as people write them+ const segsText = "0 6\n8 36\n36 48\n56 64\n28 38\n40 60\n68 72.72"; // a brand launch film's list: no final newline+ ok(parseSegs(segsText).length === 7 && parseSegs(segsText)[6].to === 72.72, "RED FIXTURE (A4): the last segment of a list with no final newline is kept (a shell `while read` loop dropped it)");+ const naive = segsText.split("\n").slice(0, -1); // what `while read a b` did with the unterminated last line+ ok(naive.length === 6, "the dropped-segment bug reproduced: a line reader that needs a newline sees 6 of 7 segments");+ ok(parseSegs("0:6, 8:36 # groove\r\n36-48").length === 3, "comma, colon, dash, CRLF and comments all read");+ ok(JSON.stringify(parseSegs("bars 0-3, 5-6", a)) === JSON.stringify([{ from: 0.25, to: 6.25 }, { from: 10.25, to: 12.25 }]), "a bar list becomes seconds on the track's grid");+ throws(() => parseSegs("zero to six"), /cannot read segment/, "an unreadable segment names itself");+ throws(() => parseSegs("bars 0-3"), /needs the track's analysis/, "a bar list without an analysis is refused");++ // ---- planCut: green, then each fault it refuses+ const bar = (i: number) => +(a.downbeatS + i * a.barS).toFixed(4), last = a.lastSoundS;+ const green = planCut(a, [{ from: 0, to: bar(4) }, { from: bar(7), to: last }], { filmS: bar(4) + last - bar(7) - 0.2 });+ ok(green.errors.length === 0, `a cut on bars that keeps the track's ending passes (${green.errors.join("; ")})`);+ ok(green.downbeats.includes(+(bar(4)).toFixed(4)) && green.joins.length === 1 && Math.abs(green.joins[0].toOffMs) < 30, "the edit's downbeats and its join are reported");+ ok(planCut(a, [{ from: 0, to: bar(4) + 0.3 }, { from: bar(7), to: last }]).errors.some((e) => /off a downbeat/.test(e)), "RED: a join 300 ms off a downbeat is refused, naming the bar to use");+ ok(planCut(a, [{ from: 0, to: bar(4) }, { from: bar(7), to: 29.5 }]).errors.some((e) => /past the track's last note/.test(e)), "RED (A4): a segment that carries the silence after the last note is refused");+ ok(planCut(a, [{ from: 0, to: bar(4) }, { from: bar(7), to: bar(10) }]).errors.some((e) => /before the track's last note/.test(e)), "RED: an outro that stops before the track's own ending is refused");+ ok(planCut(a, [{ from: 0, to: bar(4) }, { from: bar(7), to: bar(10) }], { fadeOutS: 2 }).errors.every((e) => !/before the track's last note/.test(e)), "a declared fade-out may end early on purpose");+ const short = planCut(a, [{ from: 0, to: bar(4) }, { from: bar(7), to: last }], { filmS: bar(4) + last - bar(7) + 4 });+ ok(short.errors.some((e) => /4\.\d\d s of silence at the end/.test(e)), "RED (A4): music that ends 4 s before the picture is refused, with the bars to add");+ ok(planCut(a, [{ from: 0, to: last }], { filmS: 20 }).warnings.some((w) => /past the picture/.test(w)), "music that runs well past the picture warns (the mux would cut its ending)");+ ok(green.quiet.length === 0 && planCut(a, [{ from: 0, to: last }]).quiet.some((q) => q.fromS < 12.5 && q.toS > 13), "the track's own stop is carried into the edit as a declared quiet range");++ // ---- renderCut: exact length, bars stay where planned+ const imp = new Float32Array(sr * 10); imp[Math.round(4.25 * sr)] = 1; // an impulse on a downbeat+ const [cL] = renderCut(imp, imp, sr, [{ from: 0, to: 2.25 }, { from: 4.25, to: 8.25 }]);+ ok(cL.length === Math.round(2.25 * sr) + Math.round(8.25 * sr) - Math.round(4.25 * sr), `the edit is exactly the sum of its segments (${(cL.length / sr).toFixed(3)} s)`);+ let at = 0, pk = 0; for (let i = 0; i < cL.length; i++) if (Math.abs(cL[i]) > pk) { pk = Math.abs(cL[i]); at = i; }+ ok(Math.abs(at / sr - 2.25) < 0.001, `a downbeat lands where the plan says (${(at / sr).toFixed(4)} s in the edit)`);+ const sine = Float32Array.from({ length: sr * 6 }, (_, i) => Math.sin((2 * Math.PI * 100 * i) / sr)), [sL] = renderCut(sine, sine, sr, [{ from: 0, to: 2 }, { from: 4, to: 6 }]);+ let jump = 0; for (let i = 1; i < sL.length; i++) jump = Math.max(jump, Math.abs(sL[i] - sL[i - 1]));+ ok(jump < 0.06, `the crossfade joins a continuous sine without a click (largest step ${jump.toFixed(3)})`);++ // ---- trackGrid+ const g = trackGrid(green.downbeats, 60), h = g.holdTo(1.0, 1.5);+ ok(green.downbeats.includes(h.landS) && h.landS >= 2.5 && h.holdS === +(h.landS - 1).toFixed(4) && h.frame === Math.round(h.landS * 60), `holdTo lands a hold of at least 1.5 s on a downbeat (${h.holdS} s, lands ${h.landS} s, frame ${h.frame})`);+ ok(g.landOn(4.3) === 4.25, "landOn snaps to the nearest downbeat");+ throws(() => g.holdTo(30, 5), /no downbeat after/, "a hold past the music's last bar is refused");++ // ---- pitch salience: notes fail, strikes pass+ const S = 48000, note = (hz: number, ms: number, tau: number) => Float32Array.from({ length: Math.round((S * ms) / 1000) }, (_, i) => Math.sin((2 * Math.PI * hz * i) / S) * Math.exp(-i / S / tau) + 0.3 * Math.sin((2 * Math.PI * hz * 2 * i) / S) * Math.exp(-i / S / tau));+ let s0 = 3; const noise = (ms: number, tau: number) => Float32Array.from({ length: Math.round((S * ms) / 1000) }, (_, i) => { s0 = (s0 * 16807) % 2147483647; return (s0 / 2147483647 - 0.5) * Math.exp(-i / S / tau); });+ const marimba = pitchSalience(note(523, 400, 0.25), S), strike = pitchSalience(note(523, 14, 0.004), S), tap = pitchSalience(noise(20, 0.004), S), harp = pitchSalience(note(110, 400, 0.3), S);+ ok(marimba.salience > PITCHED && Math.abs(marimba.hz - 523) < 15, `RED (A5): a 400 ms C5 note carries a note (${marimba.salience}, ${marimba.hz} Hz)`);+ ok(harp.salience > PITCHED, `RED: a low A2 note is caught too (${harp.salience})`);+ ok(strike.salience <= PITCHED, `a 14 ms strike of the same note is too short to name (${strike.salience}, rings ${strike.ringMs} ms)`);+ ok(tap.salience < 0.2, `a noise tap carries no note (${tap.salience})`);+ for (const v of sfxVariants("tap")) { const s = renderSfx("tap", { variant: v, seed: 3 }, S), p = pitchSalience(Float32Array.from(s.L, (x, i) => 0.5 * (x + s.R[i])), S); ok(p.salience <= PITCHED, `tap:${v} carries no note (${p.salience})`); }+ const chime = renderSfx("chime", { key: "Am", seed: 1 }, S), pc = pitchSalience(Float32Array.from(chime.L, (x, i) => 0.5 * (x + chime.R[i])), S);+ ok(pc.salience > PITCHED, `RED: the engine's own tuned chime is flagged as a note (${pc.salience})`);++ // ---- stemCues + lastSoundOf+ const stem = new Float32Array(S * 4), put = (x: Float32Array, t: number) => stem.set(x, Math.round(t * S));+ put(noise(20, 0.004), 0.5); put(noise(20, 0.004), 1.0); put(note(523, 400, 0.25), 2.0); put(noise(20, 0.004), 3.2);+ const sc = stemCues(stem, stem, S);+ ok(sc.length === 4 && sc.filter((c) => c.salience > PITCHED).length === 1 && Math.abs(sc[2].atS - 2.0) < 0.01, `stemCues finds 4 effects and the one note among them (${sc.map((c) => c.salience).join(", ")})`);+ ok(Math.abs(lastSoundOf(L, R, sr) - a.lastSoundS) < 0.06, "lastSoundOf agrees with the analysis");+};diff --git a/skills/anidoodle/engine/test/trackMix.test.ts b/skills/anidoodle/engine/test/trackMix.test.tsnew file mode 100644index 0000000..c6d3702--- /dev/null+++ b/skills/anidoodle/engine/test/trackMix.test.ts@@ -0,0 +1,52 @@+// MIX OVER A TRACK TESTS. Effects under someone else's music: tuned kinds refused, every placed sound+// checked for a note, buried cues raised or failed, the music never ending before the picture, and the+// dense master. node tools/test.mjs trackMix+import { mixOverTrack, parseSoundSpec, checkTrackCues, type TrackPlan } from "../src/canvas-core/music/trackMix";+import { renderSfx, sfxNeeds, sfxDuckDb } from "../src/canvas-core/music/sfxKit";++export const name = "mix over an external track";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const throws = (fn: () => unknown, re: RegExp, label: string) => { try { fn(); ok(false, `${label} (did not throw)`); } catch (e) { ok(re.test((e as Error).message), `${label}: ${(e as Error).message.slice(0, 100)}`); } };+ const sr = 24000, fps = 30, filmS = 8;+ // a stand-in track: a steady chord with a soft pulse, `musicS` long+ const track = (musicS: number, amp = 0.12): [Float32Array, Float32Array] => { const n = Math.round(musicS * sr), L = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr; L[i] = amp * (Math.sin(2 * Math.PI * 220 * t) + 0.6 * Math.sin(2 * Math.PI * 277.2 * t) + 0.5 * Math.sin(2 * Math.PI * 329.6 * t)) * (0.8 + 0.2 * Math.sin(2 * Math.PI * 2 * t)); } return [L, L.slice()]; };+ const plan = (cues: TrackPlan["cues"]): TrackPlan => ({ fps, frames: filmS * fps, cues, seed: 1 });+ const taps = [{ frame: 30, kind: "tap" as const, variant: "tock", label: "card lands" }, { frame: 90, kind: "tap" as const, variant: "thump", label: "stage lands", pan: -0.4 }, { frame: 150, kind: "tap" as const, variant: "impact", label: "x locks" }];++ // sound specs+ ok((({ kind, variant, gainDb, pan }) => kind === "tap" && variant === "thump" && gainDb === -9 && pan === 0.3)(parseSoundSpec("tap:thump -9 pan=0.3")), "a sound spec reads kind, variant, gain and pan");+ throws(() => parseSoundSpec("tap:boing"), /no variant "boing"/, "an unknown variant names the real ones");+ throws(() => parseSoundSpec("kazoo"), /unknown kind/, "an unknown kind is refused");+ throws(() => parseSoundSpec("tap:tick pan=3"), /pan must be -1..1/, "a pan outside -1..1 is refused");++ // the tap kind needs no key and ducks by variant+ ok(!sfxNeeds("tap", "impact").key && renderSfx("tap", { variant: "tick" }).L.length > 0, "tap renders without a key (nothing in it is tuned)");+ ok(sfxDuckDb("tap", "impact") === 6 && sfxDuckDb("tap", "tick") === 0, "a tap impact ducks the track 6 dB, a tick does not duck");++ // tuned kinds are refused under a track+ throws(() => checkTrackCues(plan([{ frame: 30, kind: "chime", label: "sparkle" }])), /transients, never notes/, "RED (A5): a tuned chime under an external track is refused");+ throws(() => checkTrackCues(plan([{ frame: 30, kind: "impact", variant: "bloom", label: "reveal" }])), /tap:impact/, "RED: impact:bloom (tuned shimmer) is refused and pointed to tap:impact");+ ok((() => { try { checkTrackCues(plan([{ frame: 30, kind: "press", variant: "confirm", key: "Am", pitched: "the track's own key, a deliberate button on the last downbeat" }])); return true; } catch { return false; } })(), "a tuned cue that says why it belongs is allowed");++ // green: the whole thing+ const m = mixOverTrack(track(filmS + 1), plan(taps), sr);+ ok(m.ok, `taps over a track that covers the picture pass (${m.problems.join("; ")})`);+ ok(Math.abs(m.lufs + 14) < 1 && m.dbtp <= -1, `mastered dense: ${m.lufs.toFixed(1)} LUFS, ${m.dbtp.toFixed(2)} dBTP`);+ ok(m.L.length === filmS * sr && m.sfx[0].length === filmS * sr, "the mix and the effects stem are exactly the film's length");+ ok(m.pitch.every((p) => p.salience <= 0.5) && m.pitch.length === 3, "every placed effect is measured for pitch");+ ok(m.audibility.every((a) => a.ok), "every cue is heard over the track");++ // RED (A4): music that stops 4 s before the picture (the v9 film's silent ending)+ const early = mixOverTrack(track(filmS - 4), plan(taps), sr);+ ok(!early.ok && /ends at 4\.\d\d s and the picture at 8\.00 s/.test(early.ending.msg ?? ""), `RED (A4): music ending 4 s early fails: ${early.ending.msg?.slice(0, 80)}`);++ // RED (A7): a tick under a loud track cannot be raised enough+ const buried = mixOverTrack(track(filmS + 1, 0.3), plan([{ frame: 60, kind: "tap", variant: "tickHi", gainDb: -20, label: "a whisper" }]), sr, { maxRaiseDb: 0 });+ ok(!buried.ok && buried.problems.some((p) => /buried/.test(p)), "RED (A7): a cue buried under the track's local loudness fails, named");+ const raised = mixOverTrack(track(filmS + 1, 0.3), plan([{ frame: 60, kind: "tap", variant: "tock", gainDb: -6, label: "a card" }]), sr);+ ok(raised.ok && raised.raised.length === 1 && raised.raised[0].db > 0, `a quiet cue is raised until it is heard (+${raised.raised[0]?.db.toFixed(1)} dB)`);++ // RED (A5): a pitched cue allowed by reason passes the pitch rule; the same sound without a reason is caught at placement+ const allowed = mixOverTrack(track(filmS + 1), plan([{ frame: 60, kind: "chime", key: "A", pitched: "the logo's own note, agreed with the director" }]), sr);+ ok(allowed.pitch[0].salience > 0.5 && allowed.pitch[0].ok && allowed.ok, `a chime with a reason is measured (${allowed.pitch[0].salience}) and allowed`);+};diff --git a/skills/anidoodle/engine/test/typedWrap.test.ts b/skills/anidoodle/engine/test/typedWrap.test.tsnew file mode 100644index 0000000..fb49965--- /dev/null+++ b/skills/anidoodle/engine/test/typedWrap.test.ts@@ -0,0 +1,21 @@+// A WORD BEING TYPED STAYS ON ITS LINE. A wrapping composer broke the words as they were typed so far: a word+// that fit half typed ("which sources dis") jumped to the next line once it grew past the edge, and the line it+// left had stood 0.15 s (framecheck reading time, launchExampleBrand 9:16). Given the whole prompt, the+// composer breaks where the finished prompt breaks, so a word starts on the line it will end on.+// node tools/test.mjs typedWrap+import { composerLines, type ChatGeom } from "../src/canvas-core/launchKit";++export const name = "a word being typed stays on its line";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const stub = { font: "", measureText: (t: string) => ({ width: t.length * parseFloat(/([\d.]+)px/.exec(stub.font)?.[1] ?? "10") * 0.5 }) };+ const ctx = stub as unknown as Parameters<typeof composerLines>[0];+ const g = { k: 1, TEXT: { x: 0, base: 0, px: 20 }, GEN: { x: 190, y: 0, w: 10, h: 10, r: 1 } } as unknown as ChatGeom; // 17 characters a line+ const full = "which sources disagree?";+ const old = composerLines(ctx, "which sources dis", g);+ ok(old.length === 1 && old[0] === "which sources dis", `without the prompt the half-typed word sits on the first line (${old.join(" / ")})`);+ const kept = composerLines(ctx, "which sources dis", g, full);+ ok(kept.length === 2 && kept[1] === "dis", `RED: with the prompt the word starts on the line it ends on (${kept.join(" / ")})`);+ ok(composerLines(ctx, full, g, full).join("|") === composerLines(ctx, full, g).join("|"), "the finished prompt breaks as before");+ ok(composerLines(ctx, "", g, full).join("|") === "", "nothing typed is one empty line");+ ok(composerLines(ctx, "other words here", g, full).join("|") === composerLines(ctx, "other words here", g).join("|"), "words that are not the prompt's start wrap as before");+};diff --git a/skills/anidoodle/engine/test/writeOnExit.test.ts b/skills/anidoodle/engine/test/writeOnExit.test.tsnew file mode 100644index 0000000..efb2067--- /dev/null+++ b/skills/anidoodle/engine/test/writeOnExit.test.ts@@ -0,0 +1,42 @@+// WRITTEN LINES, LEAVING. The drawn launch preset's word pages are places on one canvas, like the clean+// preset's: the camera travels to them and on, so a written line needs a way to leave IN PLACE before the+// move carries it into a platform zone or across the frame's edge. writeOn's `out` sinks the written+// line behind its own baseline (the same ease-in exit as setType), and a leaving line reports nothing to+// the frame probe: its strokes speak for what is still showing.+// node tools/test.mjs writeOnExit+import { writeOn } from "../src/canvas-core/kinetic";+import type { Ctx, Env } from "../src/canvas-core/core";+import { FakeCanvas } from "./fakeCanvas";++export const name = "writeOn: a written line sinks out and stops reporting itself";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const canvas = new FakeCanvas(400, 400), raw = canvas.ctx;+ // the y of every point the strokes are drawn through, in device pixels+ const ys: number[] = [];+ const dev = (x: number, y: number) => raw.T.b * x + raw.T.d * y + raw.T.f;+ const ctx = new Proxy(raw, {+ get(t, k) {+ if (k === "moveTo" || k === "lineTo") return (x: number, y: number) => { ys.push(dev(x, y)); };+ if (k === "quadraticCurveTo") return (_cx: number, _cy: number, x: number, y: number) => { ys.push(dev(x, y)); };+ const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v;+ },+ set(t, k, v) { return Reflect.set(t, k, v); },+ }) as unknown as Ctx;+ const env = { W: 400, H: 400, scale: 1, root: true, cache: new Map() } as unknown as Env;+ const recs: { label: string }[] = [];+ const G = globalThis as unknown as { __ANIDOODLE_PROBE__?: unknown };+ G.__ANIDOODLE_PROBE__ = (r: { label: string }) => recs.push(r);+ const mean = (a: number[]) => a.reduce((s, v) => s + v, 0) / Math.max(1, a.length);+ try {+ writeOn(ctx, env, "IDEA IN.", 20, 200, 60, 1, "ink");+ const standing = mean(ys);+ ok(recs.length === 1 && ys.length > 0, `a standing written line reports its box and draws (${recs.length} record, ${ys.length} points)`);+ recs.length = 0; ys.length = 0;+ writeOn(ctx, env, "IDEA IN.", 20, 200, 60, 1, "ink", { out: 0.6 } as never);+ ok(recs.length === 0, `RED: a written line on its way out reports nothing (got ${recs.length})`);+ ok(ys.length > 0 && mean(ys) > standing + 10, `RED: its strokes sink below where they stood (mean y ${mean(ys).toFixed(1)} against ${standing.toFixed(1)})`);+ ys.length = 0;+ writeOn(ctx, env, "IDEA IN.", 20, 200, 60, 1, "ink", { out: 1 } as never);+ ok(ys.length === 0, `RED: a line that has left draws nothing (${ys.length} points)`);+ } finally { delete G.__ANIDOODLE_PROBE__; }+};diff --git a/skills/anidoodle/engine/test/zoneFade.test.ts b/skills/anidoodle/engine/test/zoneFade.test.tsnew file mode 100644index 0000000..8193e0e--- /dev/null+++ b/skills/anidoodle/engine/test/zoneFade.test.ts@@ -0,0 +1,23 @@+// A STRING LEAVING THROUGH A PLATFORM ZONE FADES, IT DOES NOT POP. On 9:16 a travel carries the last place+// right, through the right-hand column, where no text may sit. Each string used to be drawn whole until it+// touched the zone and not at all the next frame: a fresh critic saw the answer card's byline vanish in one+// frame (launchExample 9:16, 133 to 134). Now it fades over the 120 px before the zone, measured from where+// it rests, so a string resting near a safe edge is not dimmed the moment a travel starts.+// node tools/test.mjs zoneFade+import { zoneFadeOf } from "../src/canvas-core/launchTemplate";++export const name = "launch template: strings fade before a platform zone";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const S = { x: 0, y: 269, w: 929, h: 1171 }, fade = zoneFadeOf(S);+ // a byline 380 px wide resting at x 450..830, carried right 25 px a frame+ const a = (f: number) => fade(450 + 25 * f, 500, 830 + 25 * f, 534, [25 * f, 0]);+ const seq = Array.from({ length: 12 }, (_, f) => a(f));+ ok(seq[0] === 1, `a string at rest is drawn whole (${seq[0]})`);+ const between = seq.filter((v) => v > 0.02 && v < 0.98).length;+ ok(between >= 3, `RED: carried into the right-hand zone it fades over several frames, never in one (${seq.map((v) => v.toFixed(2)).join(" ")})`);+ ok(seq.every((v, f) => f === 0 || v <= seq[f - 1] + 1e-9) && seq[11] === 0, "it only fades as it goes, and is gone inside the zone");+ // a string resting 10 px from the zone is whole at rest and starts fading only as it moves+ ok(fade(500, 500, 919, 534, [0, 0]) === 1 && fade(503, 500, 922, 534, [3, 0]) < 1, "a string resting near the zone is whole at rest, and fades from there as it moves");+ // the left side has no zone: a string carried off the left edge is not faded by this rule+ ok(fade(-200, 500, 200, 534, [-500, 0]) === 1, "the left side has no zone");+};diff --git a/skills/anidoodle/engine/tools/adapters/playwright.mjs b/skills/anidoodle/engine/tools/adapters/playwright.mjsindex d791fb7..31ea003 100644--- a/skills/anidoodle/engine/tools/adapters/playwright.mjs+++ b/skills/anidoodle/engine/tools/adapters/playwright.mjs@@ -38,7 +38,7 @@ export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workerhash: (n, w = 0) => pick(w).evaluate((f) => { window.FILM.seek(f); return window.FILM.hash(); }, n),// motion-blurred frame: `samples` subframes averaged in the page (see hosts/page.ts blur)// `samples` is a count (a 360-degree shutter, as before) or a spec { samples: N | 0 (auto), shutter, max, px }- blur: async (n, samples, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, s]) => { const r = window.FILM.blur(f, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0, samples: r.samples, speed: r.speed }; },+ blur: async (n, samples, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, s]) => { const r = window.FILM.blur(f, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0, samples: r.samples, speed: r.speed, sharpPx: r.sharpPx ?? 0, typeInLayers: r.typeInLayers ?? 0 }; },// a frame of the poster dissolve (see hosts/page.ts poster): frame n with poster frame p over itposter: async (n, p, fade, samples = 1, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, pf, fd, s]) => { const r = window.FILM.poster(f, pf, fd, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, p, fade, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },posterHash: (n, p, fade, samples = 1, w = 0) => pick(w).evaluate(([f, pf, fd, s]) => { window.FILM.poster(f, pf, fd, s); return window.FILM.hash(); }, [n, p, fade, samples]),@@ -47,6 +47,10 @@ export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workeraudio: (sr) => pages[0].evaluate((s) => window.FILM.audio(s), sr),// the frame probe (hosts/page.ts): text and content boxes the frame's edge cuts throughprobe: (frames, all = false) => pages[0].evaluate(([fs, a]) => window.FILM.probe(fs, a), [frames, all]),+ // the layer probe (hosts/instrument.ts, tools/layerscan.mjs): text, photos and boxes per frame in draw order, translucent brand fills+ layers: (frames, brand = []) => pages[0].evaluate(([fs, b]) => window.FILM.layers(fs, b), [frames, brand]),+ // visible ink of the text inside each box on one frame (device px)+ ink: (frame, boxes) => pages[0].evaluate(([f, bs]) => window.FILM.ink(f, bs), [frame, boxes]),// keeps the fresh bakes, then closes; returns how many plate frames were storedclose: async () => { let saved = 0; if (useBakes) for (const p of pages) saved += await saveBakes(p, bv).catch(() => 0); await browser.close(); return saved; },};diff --git a/skills/anidoodle/engine/tools/board.mjs b/skills/anidoodle/engine/tools/board.mjsnew file mode 100644index 0000000..eb1b004--- /dev/null+++ b/skills/anidoodle/engine/tools/board.mjs@@ -0,0 +1,28 @@+// BOARD. Checks a brief and its storyboard (board.json) before anything is drawn, and prints the board+// with a CARRY column: what each beat takes in from the one before. A board whose rows carry nothing is a+// slide deck however well it is animated later. The rules and the file format: tools/boardrules.mjs.+// node tools/board.mjs board.json check it; exit 1 with each problem and its fix+// node tools/board.mjs init [board.json] write a starting board with every field (never overwrites)+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { resolve } from "node:path";+import { isMain } from "./is-main.mjs";+import { BOARD_TEMPLATE, checkBoard } from "./boardrules.mjs";++export const printBoard = (r) => {+ const out = [` ${"beat".padEnd(12)} ${"s".padStart(5)} ${"carry (in from the beat before)".padEnd(34)} action`];+ for (const t of r.table) out.push(` ${String(t.id).slice(0, 12).padEnd(12)} ${t.seconds.toFixed(1).padStart(5)} ${(t.carry || "-- nothing --").slice(0, 34).padEnd(34)} ${t.action.slice(0, 70)}`);+ out.push(` ${"total".padEnd(12)} ${r.seconds.toFixed(1).padStart(5)}`);+ return out.join("\n");+};++if (isMain(import.meta.url)) {+ const [cmd, arg] = process.argv.slice(2);+ if (cmd === "init") { const f = resolve(arg ?? "board.json"); if (existsSync(f)) { console.log(`board: ${f} already exists; left as it is`); process.exit(0); } writeFileSync(f, JSON.stringify(BOARD_TEMPLATE, null, 2) + "\n"); console.log(`board: wrote ${f}`); process.exit(0); }+ if (!cmd) { console.error("usage: node tools/board.mjs <board.json> | init [board.json]"); process.exit(2); }+ let board; try { board = JSON.parse(readFileSync(resolve(cmd), "utf8")); } catch (e) { console.error(`board: cannot read ${cmd}: ${e.message}`); process.exit(1); }+ const r = checkBoard(board);+ console.log(`BOARD ${cmd}\n${printBoard(r)}\n`);+ for (const p of r.problems) console.log(` FAIL ${p.where}: ${p.why}`);+ console.log(r.status === "PASS" ? `BOARD: PASS ${r.table.length} beats, each carrying the last; brief complete` : `BOARD: FAIL ${r.problems.length} problem(s)`);+ process.exit(r.status === "PASS" ? 0 : 1);+}diff --git a/skills/anidoodle/engine/tools/boardrules.mjs b/skills/anidoodle/engine/tools/boardrules.mjsnew file mode 100644index 0000000..8398fa3--- /dev/null+++ b/skills/anidoodle/engine/tools/boardrules.mjs@@ -0,0 +1,121 @@+// BOARD RULES. The pure half of board.mjs: what a brief and a storyboard must hold before anything is+// drawn. Every rule here was a round of notes on a brand launch film: a board of facts that played as a+// slide deck, a logo that arrived with no reason, a brand tagline nobody understood, jokes that were all+// the same shape (and one that made the audience's own tool look stupid), a count of dots read as a+// promise of six more speakers, an ending that ended twice, organisers and sponsors forgotten, filler+// text that viewers tried to read. A rule that can be a check is a check; each failure names its fix.+//+// board.json+// { "version": 1,+// "brief": { "story": "...", "message": "...", "premise": { "pain": "...", "stereotype": "..." } | "none: <why>",+// "promise": { "line": "...", "does": "<what the viewer does>", "leaves": "<what they leave with>" },+// "actor": "<the one object that carries the seams>", "kind": "event" | "product" | "story",+// "people": { "hosts": [...] | "excluded: <why, who decided>", "sponsors": ..., "partners": ..., "speakers": ... }, (events)+// "voices": { "<speaker>": "<how their lines look: dots then white type>" },+// "reference": { "film": "<a film chosen with the person>", "notes": "<its deconstruction>" } | "none: <why>",+// "length": { "target": 60, "max": 90 } },+// "rows": [ { "id": "hook", "seconds": 3, "action": "<what moves>", "carry": "<what comes in from the previous row>",+// "words": ["..."], "lines": [{ "speaker": "ai", "text": "..." }], "texture": ["blah blah"], "kind": "beat" | "card" | "stinger",+// "brand": true, "bridge": "<why the logo appears now, from what is on screen>", "builtFrom": "<the thing that just acted>",+// "counts": [{ "of": "dots", "from": 3, "to": 1, "why": "..." }], "answers": "<a stinger: what it answers, visible in the last 3 s>" } ],+// "jokes": [ { "line": "...", "device": "verbal|visual|interaction|physical|structural", "butt": "situation|habit|...", "who": "<who gets it and why>", "row": "hook" } ],+// "pitches": [ { "line": "...", "device": "...", "twist": "<the turn that makes it a joke>" } ],+// "program": [ { "name": "...", "role": "...", "company": "...", "logo": "..." } ], "programTitles": "on: <why>" (titles are off by default) }++export const DEVICES = ["verbal", "visual", "interaction", "physical", "structural"];+const ABSTRACT = /\b(intelligence|synerg\w*|unlock\w*|empower\w*|transform\w*|multipl\w*|next[- ]level|leverag\w*|revolution\w*|elevat\w*|supercharg\w*|reimagin\w*|amplif\w*|innovat\w*)\b/i;+const MYSTERY = /^(tba|tbd|\?+|mystery|secret|to be announced|surprise)( speaker)?$/i;+const GREEK = /\b(blah|lorem|ipsum|dolor|lipsum)\b|x{3,}|~{2,}|_{3,}/i;+const words = (s) => String(s ?? "").toLowerCase().match(/[a-z0-9']+/g) ?? [];+const set = (v) => (Array.isArray(v) ? v.length > 0 : typeof v === "string" && /^(excluded|none)\s*:\s*\S/.test(v.trim()));+const reasoned = (v) => typeof v === "string" && /^(excluded|none|on)\s*:\s*\S/.test(v.trim());+const norm = (s) => String(s ?? "").toLowerCase().replace(/\s+/g, " ").replace(/^[\s"'“”]+|[\s.!?:;"'“”]+$/g, "");+const STOP = new Set(["the", "a", "an", "of", "to", "and", "in", "on", "it", "its", "is", "into", "from", "that", "then", "with", "as", "at", "by", "for", "they", "their", "one", "two", "three"]);+const shares = (a, b) => { const A = new Set(words(a).filter((w) => !STOP.has(w))); return words(b).some((w) => !STOP.has(w) && (A.has(w) || A.has(w.replace(/s$/, "")) || A.has(`${w}s`))); };++/** -> { status: "PASS" | "FAIL", problems: [{ where, why }], table: [{ id, seconds, carry, action }] , seconds } */+export const checkBoard = (board) => {+ const P = [], add = (where, why) => P.push({ where, why });+ if (!board || typeof board !== "object") return { status: "FAIL", problems: [{ where: "board", why: "is not a board object" }], table: [], seconds: 0 };+ const b = board.brief ?? {}, rows = Array.isArray(board.rows) ? board.rows : [];+ const todo = (v, path) => { if (typeof v === "string" && /^todo\b/i.test(v.trim())) add(path, "is still a TODO"); else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) todo(x, `${path}.${k}`); };+ todo(board.brief, "brief"); todo(board.rows, "rows");+ // ---- the brief+ if (!String(b.story ?? "").trim()) add("brief.story", "is missing: one sentence the film proves, written before anything else");+ if (!String(b.message ?? "").trim()) add("brief.message", "is missing: the line the viewer should leave repeating (a film of information with no message is a deck)");+ if (!b.premise || (typeof b.premise === "string" ? !reasoned(b.premise) : !(String(b.premise.pain ?? "").trim() && String(b.premise.stereotype ?? "").trim()))) add("brief.premise", "needs the comic premise { pain: whose pain, stereotype: which habit }, or \"none: <why this film plays it straight>\"");+ const pr = b.promise;+ if (!pr || !String(pr.line ?? "").trim()) add("brief.promise", "is missing: the promise line, naming what the viewer DOES and LEAVES WITH");+ else {+ if (!String(pr.does ?? "").trim() || !String(pr.leaves ?? "").trim()) add("brief.promise", "needs `does` (what the viewer does) and `leaves` (what they leave with): an abstract claim nobody can picture is not a promise");+ if (ABSTRACT.test(pr.line) && !reasoned(pr.taglineApproved)) add("brief.promise", `"${pr.line}" leans on an abstract word (${pr.line.match(ABSTRACT)[0]}); say what the viewer does and leaves with, or set taglineApproved: "on: <who approved it and why it reads>"`);+ }+ if (!String(b.actor ?? "").trim()) add("brief.actor", "is missing: name the one object that carries the film across its seams (the motif)");+ if (b.kind === "event") for (const k of ["hosts", "sponsors", "partners", "speakers"]) if (!set(b.people?.[k])) add(`brief.people.${k}`, `is missing: an event film lists its ${k}, or says "excluded: <why, and who decided>"`);+ if (["event", "product"].includes(b.kind) && !(b.reference && (reasoned(b.reference) || (String(b.reference.film ?? "").trim() && String(b.reference.notes ?? "").trim())))) add("brief.reference", "is missing: one reference film chosen with the person and deconstructed (shot lengths, seams, camera, type entry and exit), or \"none: <why>\"");+ // ---- the rows+ if (!rows.length) add("rows", "the board has no rows (an empty board is never a pass)");+ const table = [], seen = new Map();+ let seconds = 0, lastCard = -1, stingerAfterCard = -1;+ rows.forEach((r, i) => {+ const id = r.id ?? `row ${i + 1}`, at = `rows.${id}`;+ seconds += Number(r.seconds) || 0;+ if (!String(r.action ?? "").trim()) add(at, "has no action: a row says what MOVES and what it becomes, never only what is shown (a fact on a frame is a slide)");+ if (i > 1 && !String(r.carry ?? "").trim() && !String(rows[i - 1].carry ?? "").trim()) add(at, `and ${rows[i - 1].id ?? `row ${i}`} carry nothing in from the row before: two cuts in a row with nothing carried play as a slide deck. Name what moves across (an object, a shape, the camera)`);+ if (i > 0 && String(r.carry ?? "").trim() && !shares(r.carry, `${rows[i - 1].kind ?? ""} ${rows[i - 1].action} ${rows[i - 1].carry ?? ""} ${(rows[i - 1].words ?? []).join(" ")}`)) add(at, `carries "${r.carry}", which the row before never shows: the carried thing must be on screen on both sides of the seam`);+ if (r.brand) {+ if (!String(r.bridge ?? "").trim()) add(at, "reveals the brand with no bridge: answer \"why does the logo appear now?\" in one sentence from what is on screen (the brand arrives as the answer, shown as an action)");+ if (!String(r.builtFrom ?? "").trim()) add(at, "reveals the brand without saying what it is built from: the mark should be built from the thing that just acted");+ else if (i > 0 && !shares(r.builtFrom, `${rows[i - 1].action} ${rows[i - 1].carry ?? ""} ${r.action}`)) add(at, `builds the brand from "${r.builtFrom}", which is not what just acted on screen`);+ }+ for (const c of r.counts ?? []) if (c.from !== c.to && !String(c.why ?? "").trim()) add(at, `changes the count of ${c.of ?? "an actor"} from ${c.from} to ${c.to} with no reason on screen: keep the count, or show why it changes`);+ for (const t of r.texture ?? []) if (!GREEK.test(t) && words(t).length >= 3) add(at, `texture text "${String(t).slice(0, 40)}" is real words: text that is not meant to be read must look unreadable (blah, greeked), or the eye tries to read it`);+ for (const l of r.lines ?? []) if (!b.voices?.[l.speaker]) add(at, `has a line by "${l.speaker}", who has no visual voice in brief.voices: a character's lines always look the same (same bubble, same type)`);+ for (const w of [...(r.words ?? []), ...(r.lines ?? []).map((l) => l.text)]) { const k = norm(w); if (!k) continue; if (seen.has(k)) add(at, `repeats "${String(w).slice(0, 40)}" (first in ${seen.get(k)}): say a line once`); else seen.set(k, id); }+ if (r.kind === "card") { if (stingerAfterCard >= 0 && stingerAfterCard > lastCard) add(at, "returns to the card after the stinger: the film ends twice. One landing: the card OR the stinger is the last thing on screen"); lastCard = i; }+ if (r.kind === "stinger") { if (lastCard >= 0) stingerAfterCard = i; if (!String(r.answers ?? "").trim()) add(at, "is a stinger with nothing to answer: it must answer something visible in the 3 s before it"); }+ table.push({ id, seconds: Number(r.seconds) || 0, carry: r.carry ?? "", action: r.action ?? "" });+ });+ // ---- jokes+ const jokes = Array.isArray(board.jokes) ? board.jokes : [];+ for (const [i, j] of jokes.entries()) {+ const at = `jokes.${i + 1}`;+ if (!DEVICES.includes(j.device)) add(at, `"${String(j.line ?? "").slice(0, 40)}" needs a device: ${DEVICES.join(", ")}`);+ if (!String(j.who ?? "").trim()) add(at, `"${String(j.line ?? "").slice(0, 40)}" needs who gets it and why, in one line; a gag that needs explaining to the client is cut or rewritten`);+ if (/\b(tool|product|person|people|audience|user|ai)\b/i.test(String(j.butt ?? "")) || !String(j.butt ?? "").trim()) add(at, `the butt of "${String(j.line ?? "").slice(0, 40)}" is ${j.butt ? `"${j.butt}"` : "unnamed"}: the joke is on a situation or a habit, never on the tool the audience relies on or a real person`);+ }+ if (jokes.length >= 3) { const top = Math.max(...DEVICES.map((d) => jokes.filter((j) => j.device === d).length)); if (top / jokes.length > 0.6) add("jokes", `${top} of ${jokes.length} jokes use one device: vary it (a visual pun, an interaction, physical comedy, structure), one format repeated stops being funny`); }+ const pitches = Array.isArray(board.pitches) ? board.pitches : [];+ if (pitches.length) {+ const devices = new Set(pitches.map((p) => p.device).filter((d) => DEVICES.includes(d)));+ if (devices.size < Math.min(4, pitches.length)) add("pitches", `the batch spans ${devices.size} comic device(s): a pitch batch spans at least four (${DEVICES.join(", ")})`);+ for (const [i, p] of pitches.entries()) if (!String(p.twist ?? "").trim()) add(`pitches.${i + 1}`, `"${String(p.line ?? "").slice(0, 40)}" has no twist: an observation (true, with no turn) is not a joke`);+ }+ // ---- the program (events)+ for (const [i, s] of (board.program ?? []).entries()) {+ const at = `program.${i + 1}`;+ if (MYSTERY.test(String(s.name ?? "").trim())) add(at, `"${s.name}" is a mystery speaker: list real people only; for more to come, one symbol (a single "?") never a count`);+ for (const k of ["name", "role", "company"]) if (!String(s[k] ?? "").trim()) add(at, `${s.name ?? "a speaker"} has no ${k}: the program shows name, role and company logo for every speaker`);+ if (s.title && !reasoned(board.programTitles)) add(at, `${s.name} shows a talk title: titles are off by default (too long to read in a film); set programTitles: "on: <why>" to keep them`);+ }+ // ---- length+ const L = b.length ?? {};+ if (L.max && seconds > L.max) add("length", `the rows add up to ${seconds} s, over the ${L.max} s maximum: cut whole beats (never speed up reading)`);+ return { status: P.length ? "FAIL" : "PASS", problems: P, table, seconds };+};++/** A starting board with every field, for `board.mjs init`. */+export const BOARD_TEMPLATE = {+ version: 1,+ brief: {+ story: "TODO one sentence the film proves", message: "TODO the line the viewer leaves repeating",+ premise: { pain: "TODO whose pain", stereotype: "TODO which habit" },+ promise: { line: "TODO", does: "TODO what the viewer does", leaves: "TODO what they leave with" },+ actor: "TODO the one object that carries the seams", kind: "product",+ voices: { ai: "TODO how its lines look" },+ reference: { film: "TODO a film chosen with the person", notes: "TODO path to its deconstruction" },+ length: { target: 60, max: 90 },+ },+ rows: [{ id: "hook", seconds: 3, action: "TODO what moves and what it becomes", carry: "", words: [] }],+ jokes: [],+};diff --git a/skills/anidoodle/engine/tools/brand-unit.mjs b/skills/anidoodle/engine/tools/brand-unit.mjsnew file mode 100644index 0000000..81684a8--- /dev/null+++ b/skills/anidoodle/engine/tools/brand-unit.mjs@@ -0,0 +1,84 @@+#!/usr/bin/env node+// Unit + end-to-end tests for tools/brand.mjs that need node's own modules (zlib, files), so they run+// here rather than in the bundled test/brand.test.ts. Temp folder under out/, removed afterwards.+// node tools/brand-unit.mjs (add --browser to also run the contact-sheet red/green pair)+import { strict as assert } from "node:assert";+import { execFileSync, spawnSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { alphaBox, crop, decodePng, encodePng, inkOf, opaqueCorners, tint } from "./pngio.mjs";++const ENGINE = join(dirname(fileURLToPath(import.meta.url)), ".."), TOOL = join(ENGINE, "tools", "brand.mjs"), FIX = join(ENGINE, "test", "fixtures", "brand");+const root = join(ENGINE, "out", ".brand-unit"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true });+let n = 0; const t = (label, fn) => { fn(); n++; console.log(` PASS ${label}`); };+const run = (...args) => spawnSync(process.execPath, [TOOL, ...args], { cwd: root, encoding: "utf8" });+try {+ // ---- PNG: written and read back, trimmed to ink, tinted+ const w = 40, h = 20, data = new Uint8Array(w * h * 4);+ for (let y = 5; y < 15; y++) for (let x = 10; x < 30; x++) { const i = (y * w + x) * 4; data.set([200, 30, 30, 255], i); }+ const back = decodePng(encodePng({ w, h, data }));+ t("a PNG written and read back is the same pixels", () => assert.deepEqual([...back.data], [...data]));+ t("the transparent margin is found and trimmed to 20x10 with 200 px of ink", () => { const b = alphaBox(back); assert.deepEqual(b, [10, 5, 20, 10]); assert.equal(inkOf(crop(back, b)), 200); });+ t("tinted white keeps alpha", () => { const x = tint(back, [255, 255, 255]); const i = (5 * w + 10) * 4; assert.deepEqual([...x.data.slice(i, i + 4)], [255, 255, 255, 255]); });+ t("RED: a logo on a solid background is caught", () => assert.ok(opaqueCorners({ w: 2, h: 2, data: new Uint8Array(16).fill(255) }) && !opaqueCorners(back)));+ t("NEGATIVE: not a PNG is refused", () => assert.throws(() => decodePng(Buffer.from([1, 2, 3])), /not a PNG/));+ const rgb = execFileSync("ffmpeg", ["-loglevel", "error", "-f", "lavfi", "-i", "color=c=red:s=8x4", "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "image2pipe", "-vcodec", "png", "-"]);+ t("an RGB PNG from another encoder (ffmpeg, filtered rows) decodes", () => { const p = decodePng(rgb); assert.equal(p.w, 8); assert.ok(p.data[0] > 240 && p.data[1] < 12 && p.data[3] === 255, String([...p.data.slice(0, 4)])); });++ // ---- inventory -> find -> check, through the command line+ const figma = { document: { children: [{ name: "Social", children: [+ { id: "4:7", name: "Social Media partners", type: "FRAME", absoluteBoundingBox: { width: 1080, height: 1080 }, children: [{ type: "TEXT", characters: "Thank you to our sponsors" }] },+ { id: "4:8", name: "Story cover", type: "FRAME", absoluteBoundingBox: { width: 1080, height: 1920 }, children: [] }] }] } };+ writeFileSync(join(root, "file.json"), JSON.stringify(figma));+ t("inventory lists every frame", () => { const r = run("inventory", "--figma-json", "file.json"); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /2 frames/); });+ t("find answers from the words on a frame", () => assert.match(run("find", "sponsors").stdout, /Social Media partners/));+ t("find says what it searched when nothing matches", () => assert.match(run("find", "speakers").stdout, /not in the names or words of the 2 frames/));+ t("RED: check fails while frames are unread", () => { const r = run("check"); assert.equal(r.status, 1); assert.match(r.stdout, /UNREAD/); });+ const md = join(root, "brand", "INVENTORY.md"); writeFileSync(md, readFileSync(md, "utf8").replace("| [ ] | Social | Social Media partners", "| [x] | Social | Social Media partners").replace("| [ ] | Social | Story cover", "| [-] same elements as the lockup | Social | Story cover"));+ t("check passes once every frame is read or skipped with a reason", () => assert.equal(run("check").status, 0));+ t("re-running inventory keeps the read marks", () => { run("inventory", "--figma-json", "file.json"); assert.equal(run("check").status, 0); });++ // ---- import and logos, through the command line+ t("import writes brand.json and a TS module, and reports the half-turn symmetry", () => { const r = run("import", join(FIX, "hourglass.svg"), "--ts", "src/canvas-core/demoBrand.ts"); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /same after 1\/2 turn/); assert.ok(existsSync(join(root, "src/canvas-core/demoBrand.ts"))); });+ t("import names the mask it cannot draw", () => assert.match(run("import", join(FIX, "masked.svg"), "--out", "b2").stdout, /WARN .*mask/));+ mkdirSync(join(root, "logos")); writeFileSync(join(root, "logos", "wide.png"), encodePng({ w, h, data })); writeFileSync(join(root, "logos", "solid.png"), encodePng({ w: 2, h: 2, data: new Uint8Array(16).fill(255) }));+ writeFileSync(join(root, "logos", "shared.svg"), `<svg width="100" height="20" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="20" fill="#123456"/><rect x="40" width="60" height="20" fill="#123456"/></svg>`);+ t("logos trims, skips a solid background, and flags shared outlines for the owner", () => { const r = run("logos", "logos", "--on", "dark"); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /trimmed 40x20 -> 20x10/); assert.match(r.stdout, /SKIP\s+solid\.png has a solid background/); assert.match(r.stdout, /CHECK WITH OWNER/); assert.ok(existsSync(join(root, "brand/logos/shared-dark.svg"))); });++ // ---- M7: a flag that takes no value must not swallow the file after it; an unknown flag is refused+ t("RED (M7): an unknown flag is refused, never read as a value or a file", () => { const r = run("import", join(FIX, "hourglass.svg"), "--sheeet", join(FIX, "hardmask.svg"), "--out", "m7a"); assert.notEqual(r.status, 0); assert.match(r.stderr, /unknown flag --sheeet/); });++ t("RED: brand.json records each source relative to itself, never an absolute path", () => { const r = run("import", join(FIX, "hourglass.svg"), "--out", "relsrc"); assert.equal(r.status, 0, r.stdout + r.stderr); const j = JSON.parse(readFileSync(join(root, "relsrc", "brand.json"), "utf8")); for (const s of Object.values(j.sources)) { assert.ok(!s.file.startsWith("/") && !/^[A-Za-z]:/.test(s.file), `absolute path written: ${s.file}`); assert.ok(existsSync(join(root, "relsrc", s.file)), `relative path does not resolve: ${s.file}`); } });++ // ---- the test override can never send the Figma token off this machine+ await (async () => {+ const { figmaBase } = await import("./brand.mjs");+ t("RED: ANIDOODLE_FIGMA_API pointing at another host is refused", () => { assert.throws(() => figmaBase({ ANIDOODLE_FIGMA_API: "https://evil.example.com" }), /local test server/); assert.throws(() => figmaBase({ ANIDOODLE_FIGMA_API: "http://127.0.0.1.evil.example.com" }), /local test server/); });+ t("no override gives Figma itself; a localhost override is kept", () => { assert.equal(figmaBase({}), "https://api.figma.com"); assert.equal(figmaBase({ ANIDOODLE_FIGMA_API: "http://127.0.0.1:4010/" }), "http://127.0.0.1:4010"); });+ })();++ // ---- L10: a Figma image fetch that fails is an error, never an .svg holding the error page+ await (async () => {+ const { createServer } = await import("node:http"), { spawn } = await import("node:child_process");+ const srv = createServer((q, s) => {+ if (q.url.startsWith("/v1/files/")) { s.setHeader("content-type", "application/json"); s.end(JSON.stringify({ nodes: { "1:2": { document: { name: "Mark" } } } })); }+ else if (q.url.startsWith("/v1/images/")) { s.setHeader("content-type", "application/json"); s.end(JSON.stringify({ images: { "1:2": `http://127.0.0.1:${srv.address().port}/img.svg` } })); }+ else { s.statusCode = 403; s.end("<Error><Code>AccessDenied</Code></Error>"); }+ });+ await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));+ const env = { ...process.env, FIGMA_TOKEN: "test-token", ANIDOODLE_FIGMA_API: `http://127.0.0.1:${srv.address().port}` };+ const r = await new Promise((ok) => { const c = spawn(process.execPath, [TOOL, "import", "--figma", "KEY", "--nodes", "1:2", "--out", "l10"], { cwd: root, env }); let out = "", err = ""; c.stdout.on("data", (d) => (out += d)); c.stderr.on("data", (d) => (err += d)); c.on("close", (status) => ok({ status, stdout: out, stderr: err })); });+ srv.close();+ t("RED (L10): a Figma image fetch that returns 403 fails the import and writes no .svg", () => { assert.notEqual(r.status, 0, r.stdout); assert.match(r.stderr, /403/); assert.ok(!existsSync(join(root, "l10", "src", "Mark.svg")), "the error page was saved as Mark.svg"); });+ })();++ if (process.argv.includes("--browser")) {+ t("RED (M7): a file after --sheet is imported too, not dropped as the flag's value", () => { const r = run("import", join(FIX, "hourglass.svg"), "--sheet", join(FIX, "hardmask.svg"), "--out", "m7"); assert.match(r.stdout, /2 file\(s\)/, r.stdout + r.stderr); assert.equal(Object.keys(JSON.parse(readFileSync(join(root, "m7", "brand.json"), "utf8")).report).length, 2); });+ t("the contact sheet passes an exact import", () => { const r = run("import", join(FIX, "hourglass.svg"), "--out", "g", "--sheet"); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stdout, /BRAND: PASS/); });+ t("a hard white mask imports as a clip and passes the sheet", () => { const r = run("import", join(FIX, "hardmask.svg"), "--out", "h", "--sheet"); assert.equal(r.status, 0, r.stdout + r.stderr); });+ t("RED: the contact sheet fails the masked mark the import cannot draw", () => { const r = run("import", join(FIX, "masked.svg"), "--out", "r", "--sheet"); assert.equal(r.status, 1); assert.match(r.stdout, /BRAND: FAIL/); });+ }+ console.log(`\nBRAND-UNIT: PASS ${n} checks`);+} catch (e) { console.log(` FAIL ${e.message}`); console.log("\nBRAND-UNIT: FAIL"); process.exitCode = 1; }+finally { rmSync(root, { recursive: true, force: true }); }diff --git a/skills/anidoodle/engine/tools/brand.mjs b/skills/anidoodle/engine/tools/brand.mjsnew file mode 100644index 0000000..d517483--- /dev/null+++ b/skills/anidoodle/engine/tools/brand.mjs@@ -0,0 +1,233 @@+// BRAND. A brand film uses the brand's EXACT elements, logos and motion, imported and signed off before+// the first storyboard. Drawing them anew from screenshots cost a launch film four rounds of rejection+// ("use the right elements, exact ones from the design file, never invent or draw the official ones+// anew"). This tool turns the source into a brand file the film draws from, and makes the sign-off a check.+//+// node tools/brand.mjs import <file.svg|dir ...> [--out brand] [--ts src/canvas-core/myBrand.ts] [--sheet] [--on #111]+// exact paths per element (fills, gradients, transforms, <use>, clip-paths resolved) -> brand/brand.json and a TS+// module (BRAND + brandMeta for meta.brand); prints each element's parts, symmetry and repeat period.+// --sheet draws every element twice, from its source SVG and from the import, and fails past 1% different ink.+// node tools/brand.mjs import --figma <fileKey> --nodes <id,id> [...] route 1: the Figma REST API, read only,+// token in FIGMA_TOKEN; exports SVG with text outlined, then imports as above. Never writes to the file.+// node tools/brand.mjs inventory (--figma <fileKey> | --figma-json file.json | --dir <exports>) [--out brand]+// EVERY frame of the source -> brand/INVENTORY.md (a read box per frame) + inventory.json + the source's own+// transition timings as motion tokens (brand/motion.json, merged into brand.json on the next import).+// node tools/brand.mjs find <words> [--out brand] "is X in the file?" answered from the whole inventory+// node tools/brand.mjs check [--out brand] fails while any frame is unread, or skipped with no reason+// node tools/brand.mjs logos <dir> --on dark|light [--out brand/logos]+// each logo (SVG or PNG): trimmed to its ink, a one-colour version for the ground, ink measured, a size that+// makes every logo read equally, outlines that overlap flagged "check with the owner" (never auto-fixed);+// writes logos.json and strip.html (+ strip.png when a browser is installed).+// node tools/brand.mjs logo <film-render.svg|png> --ref <production-screenshot.png> [--out brand/logo-check.png]+// the production logo and the film's logo side by side at the same height, for a human to sign off first.+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";+import { basename, dirname, extname, join, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { isMain } from "./is-main.mjs";+import { brandModule, coloursOf, equaliseLogos, importSvg, logoMetrics, monochrome, repeats, symmetry, toSvg } from "./brandsvg.mjs";+import { checkInventory, findInInventory, framesFromFigma, framesFromFiles, motionTokens, parseInventory, renderInventory } from "./brandinv.mjs";+import { alphaBox, crop, decodePng, encodePng, inkOf, opaqueCorners, tint } from "./pngio.mjs";++const ENGINE = join(dirname(fileURLToPath(import.meta.url)), "..");+const sha = (b) => createHash("sha256").update(b).digest("hex");+const ident = (s) => { const w = String(s).replace(/\.[^.]+$/, "").split(/[^A-Za-z0-9]+/).filter(Boolean); const id = w.map((x, i) => (i ? x[0].toUpperCase() + x.slice(1) : x[0].toLowerCase() + x.slice(1))).join(""); return /^[0-9]/.test(id) ? `el${id}` : id || "element"; };+const svgFiles = (paths) => paths.flatMap((p) => statSync(p).isDirectory() ? readdirSync(p).filter((f) => f.toLowerCase().endsWith(".svg")).sort().map((f) => join(p, f)) : [p]);++/** The import, pure apart from reading the files: -> { elements, report, palette, fonts, sources }. */+export const importFiles = (files) => {+ const elements = {}, report = {}, sources = {}, palette = new Map(), fonts = new Set();+ for (const f of files) {+ const text = readFileSync(f, "utf8"), name = ident(basename(f)), el = importSvg(text);+ if (elements[name]) throw new Error(`two sources map to the element name '${name}' (${sources[name].file} and ${f}); rename one`);+ elements[name] = { w: el.w, h: el.h, parts: el.parts }; sources[name] = { file: f, sha256: sha(text) };+ for (const [c, a] of coloursOf(el)) palette.set(c, (palette.get(c) ?? 0) + a);+ el.fonts.forEach((x) => fonts.add(x));+ report[name] = { parts: el.parts.length, size: `${el.w}x${el.h}`, symmetry: el.parts.length ? symmetry(el) : null, repeats: repeats(el), warnings: el.warnings, fonts: el.fonts };+ }+ const total = [...palette.values()].reduce((a, b) => a + b, 0) || 1;+ return { elements, report, sources, fonts: [...fonts], palette: [...palette].sort((a, b) => b[1] - a[1]).map(([hex, a]) => ({ hex, share: Math.round((a / total) * 1000) / 1000 })) };+};+const describe = (r) => [+ r.symmetry ? (r.symmetry.rotational > 1 ? `same after 1/${r.symmetry.rotational} turn (lands from a spin without a jump)` : "no rotational symmetry") + (r.symmetry.mirrorX ? ", mirror left-right" : "") + (r.symmetry.mirrorY ? ", mirror top-bottom" : "") : "empty",+ ...r.repeats.map((p) => `${p.what === "pattern" ? "colour pattern" : "shape"}: ${p.copies} copies every ${p.step[0] || p.step[1]} units ${p.step[0] ? "across" : "down"}${p.seamless ? ", tiles without a seam" : ""}`),+].join("; ");++// ------------------------------------------------------------------ browser pages (contact sheet, logo strip, side by side)+const kitBundle = async () => {+ const { build } = await import("esbuild");+ return (await build({ entryPoints: [join(ENGINE, "src", "canvas-core", "brandKit.ts")], bundle: true, write: false, format: "iife", globalName: "BK", logLevel: "error" })).outputFiles[0].text;+};+// JSON inside a <script> must not carry '<' (a '</script>' or '<!--' in an SVG comment ends or bends the script)+const safeJson = (v) => JSON.stringify(v).replace(/</g, "\\u003c");+/** Contact sheet: each element from its source SVG, from the import, and their difference in red. */+export const sheetHtml = (brand, svgTexts, kit, ground = "checker") => `<!doctype html><html><head><meta charset="utf-8"><style>+body{margin:0;padding:24px;font:14px/1.4 Poppins,Arial,sans-serif;background:#f4f2ec;color:#111}h1{font-size:20px;margin:0 0 16px}+.row{display:grid;grid-template-columns:200px repeat(3,360px);gap:16px;align-items:center;margin-bottom:18px}+.cell{width:360px;height:240px;display:flex;align-items:center;justify-content:center;${ground === "checker" ? "background:repeating-conic-gradient(#ddd 0 25%,#fff 0 50%) 0 0/16px 16px" : `background:${ground}`}}+img,canvas{max-width:340px;max-height:220px}.bad{color:#b3261e;font-weight:700}</style></head><body>+<h1>Brand contact sheet: source / import / difference</h1><div id="rows"></div>+<script>${kit}</script><script>+const B=${safeJson(brand.elements)}, S=${safeJson(svgTexts)}, out={};+(async()=>{for(const name of Object.keys(B)){const el=B[name], k=Math.min(1400/el.w,600/el.h), W=Math.max(1,Math.round(el.w*k)), H=Math.max(1,Math.round(el.h*k));+ const row=document.createElement('div');row.className='row';row.innerHTML='<div><b>'+name+'</b><br>'+el.parts.length+' parts<br><span id="r-'+name+'"></span></div>';+ const img=new Image();img.width=W;img.height=H;img.src='data:image/svg+xml;base64,'+btoa(unescape(encodeURIComponent(S[name])));const okImg=await img.decode().then(()=>true,()=>false);if(!okImg){out[name]={ink:0,diff:0,share:1,broken:true};row.innerHTML+='<div class=bad>the source SVG does not render in a browser (invalid XML?)</div>';document.getElementById('rows').appendChild(row);continue;}+ const a=document.createElement('canvas');a.width=W;a.height=H;const ca=a.getContext('2d');ca.drawImage(img,0,0,W,H);+ const b=document.createElement('canvas');b.width=W;b.height=H;const cb=b.getContext('2d');cb.scale(k,k);BK.drawEl(cb,el,{name});+ const d=document.createElement('canvas');d.width=W;d.height=H;const cd=d.getContext('2d');const A=ca.getImageData(0,0,W,H).data,Bd=cb.getImageData(0,0,W,H).data,D=cd.createImageData(W,H);+ let ink=0,diff=0;for(let i=0;i<A.length;i+=4){const on=A[i+3]>40||Bd[i+3]>40;if(on)ink++;const dd=Math.max(Math.abs(A[i]*A[i+3]-Bd[i]*Bd[i+3]),Math.abs(A[i+1]*A[i+3]-Bd[i+1]*Bd[i+3]),Math.abs(A[i+2]*A[i+3]-Bd[i+2]*Bd[i+3]),Math.abs(A[i+3]-Bd[i+3])*255)/255;+ // a difference a 1 px shift explains is antialiasing, not a different shape: count it only when no neighbour of the source matches+ let real=false;if(dd>64){real=true;const x=(i/4)%W,y=Math.floor(i/4/W);for(let oy=-1;oy<=1&ℜoy++)for(let ox=-1;ox<=1&ℜox++){const xx=x+ox,yy=y+oy;if(xx<0||yy<0||xx>=W||yy>=H)continue;const j=(yy*W+xx)*4;+ const e=Math.max(Math.abs(A[j]*A[j+3]-Bd[i]*Bd[i+3]),Math.abs(A[j+1]*A[j+3]-Bd[i+1]*Bd[i+3]),Math.abs(A[j+2]*A[j+3]-Bd[i+2]*Bd[i+3]),Math.abs(A[j+3]-Bd[i+3])*255)/255;if(e<=64)real=false}}+ if(real){diff++;D.data[i]=220;D.data[i+3]=255}else if(on){D.data[i]=D.data[i+1]=D.data[i+2]=180;D.data[i+3]=120}}+ cd.putImageData(D,0,0);const share=ink?diff/ink:0;out[name]={ink,diff,share};+ for(const c of [img,b,d]){const w=document.createElement('div');w.className='cell';w.appendChild(c);row.appendChild(w)}+ document.getElementById('rows').appendChild(row);const r=document.getElementById('r-'+name);r.textContent=(share*100).toFixed(2)+'% of ink differs';if(share>0.01)r.className='bad';}+ window.__results=out;document.body.dataset.done='1';})();+</script></body></html>`;+const shoot = async (html, out, width = 1400) => {+ const { detect } = await import("./detect.mjs"), env = detect();+ if (!env.pw.ok || !env.browser.ok) return { shot: false, why: `no browser (${env.report.playwright}; ${env.report.browser}); open the .html file instead` };+ const browser = await env.pw.lib.chromium.launch({ executablePath: env.browser.executablePath });+ try {+ const page = await browser.newPage({ viewport: { width, height: 800 }, deviceScaleFactor: 1 });+ const errors = []; page.on("pageerror", (e) => errors.push(e.message));+ await page.setContent(html); await page.waitForSelector("body[data-done]", { timeout: 30000 }).catch((e) => { throw new Error(`the page never finished${errors.length ? `: ${errors.join("; ")}` : ""} (${e.message.split("\n")[0]})`); });+ const results = await page.evaluate(() => window.__results ?? null);+ mkdirSync(dirname(out), { recursive: true }); await page.screenshot({ path: out, fullPage: true });+ return { shot: true, results };+ } finally { await browser.close(); }+};++// ------------------------------------------------------------------ logos+const logoStripHtml = (logos, ground) => `<!doctype html><html><head><meta charset="utf-8"><style>body{margin:0;padding:40px;background:${ground};font:13px Poppins,Arial,sans-serif;color:${ground === "#111111" ? "#eee" : "#111"}}+.strip{display:flex;gap:56px;align-items:center;flex-wrap:wrap}figure{margin:0;text-align:center}figcaption{margin-top:10px;opacity:.8}</style></head><body><div class="strip">+${logos.map((l) => `<figure><img style="height:${l.height}px" src="data:${l.mime};base64,${l.b64}"><figcaption>${l.name}${l.overlaps ? " · check with owner" : ""}</figcaption></figure>`).join("")}+</div><script>Promise.all([...document.images].map(i=>i.decode().catch(()=>{}))).then(()=>{document.body.dataset.done='1'})</script></body></html>`;++// ------------------------------------------------------------------ Figma REST (route 1). Read only.+// ANIDOODLE_FIGMA_API points the calls at a local stand-in for the unit tests. It is accepted only on+// this machine (localhost), so a stray environment variable can never send the token to another host.+export const figmaBase = (env = process.env) => {+ const v = env.ANIDOODLE_FIGMA_API; if (!v) return "https://api.figma.com";+ let u; try { u = new URL(v); } catch { throw new Error(`ANIDOODLE_FIGMA_API is not a URL: unset it to use Figma itself`); }+ if (u.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(u.hostname)) throw new Error(`ANIDOODLE_FIGMA_API must be a local test server (http://127.0.0.1:<port>), got ${u.host}: unset it to use Figma itself`);+ return v.replace(/\/$/, "");+};+const figma = async (path) => {+ const token = process.env.FIGMA_TOKEN; if (!token) throw new Error("FIGMA_TOKEN is not set: make a personal access token (Figma > Settings > Security, read-only file scope) and export FIGMA_TOKEN=..., or use route 4 (ask for an SVG export) in references/workflows/brand-film.md");+ const r = await fetch(`${figmaBase()}/v1/${path}`, { headers: { "X-Figma-Token": token } });+ if (!r.ok) throw new Error(`Figma API ${r.status} on ${path.split("?")[0]}: ${(await r.text()).slice(0, 200)}`);+ return r.json();+};++if (isMain(import.meta.url)) {+ const argv = process.argv.slice(2), cmd = argv[0], opt = (k, d) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : d; }, has = (k) => argv.includes(k);+ // Only the flags that take a value skip the word after them; --sheet takes none, so a file after it is+ // still a file. An unknown flag is refused rather than guessed at.+ const VALUED = ["--out", "--ts", "--on", "--figma", "--nodes", "--figma-json", "--dir", "--ref"], BOOL = ["--sheet"];+ const bad = argv.slice(1).find((a) => a.startsWith("--") && !VALUED.includes(a) && !BOOL.includes(a));+ if (bad) { console.error(`brand: unknown flag ${bad} (flags: ${[...VALUED, ...BOOL].join(" ")})`); process.exit(2); }+ const pos = argv.slice(1).filter((a, i, all) => !a.startsWith("--") && !VALUED.includes(all[i - 1]));+ const OUT = resolve(opt("--out", "brand"));+ const die = (m) => { console.error(`brand: ${m}`); process.exit(1); };+ try {+ if (cmd === "import") {+ let files = pos.length ? svgFiles(pos.map((p) => resolve(p))) : [];+ if (opt("--figma")) {+ const key = opt("--figma"), ids = String(opt("--nodes", "")).split(",").filter(Boolean); if (!ids.length) die("--figma needs --nodes <id,id> (brand.mjs inventory lists every frame id)");+ const names = await figma(`files/${key}/nodes?ids=${encodeURIComponent(ids.join(","))}`), urls = await figma(`images/${key}?ids=${encodeURIComponent(ids.join(","))}&format=svg&svg_outline_text=true&svg_simplify_stroke=false`);+ mkdirSync(join(OUT, "src"), { recursive: true });+ for (const id of ids) { const u = urls.images?.[id]; if (!u) die(`Figma rendered nothing for node ${id}`); const res = await fetch(u); if (!res.ok) die(`Figma's image for node ${id} failed: HTTP ${res.status} (nothing written; the link may have expired, run the import again)`); const svg = await res.text(); if (!/<svg[\s>]/i.test(svg)) die(`Figma's image for node ${id} is not an SVG (nothing written)`); const f = join(OUT, "src", `${ident(names.nodes?.[id]?.document?.name ?? id)}.svg`); writeFileSync(f, svg); files.push(f); }+ }+ if (!files.length) die("nothing to import: give SVG files or folders, or --figma <fileKey> --nodes <ids>");+ const brand = importFiles(files), motionFile = join(OUT, "motion.json");+ brand.motion = existsSync(motionFile) ? JSON.parse(readFileSync(motionFile, "utf8")) : {};+ mkdirSync(OUT, { recursive: true });+ // source paths are written relative to brand.json, so the file never carries the person's folder names+ // (a brand.json is often committed or shared); the sheet below still reads the absolute paths in memory+ const relSources = Object.fromEntries(Object.entries(brand.sources).map(([n, s]) => [n, { ...s, file: relative(OUT, s.file).split("\\").join("/") }]));+ writeFileSync(join(OUT, "brand.json"), JSON.stringify({ version: 1, ...brand, sources: relSources }, null, 1));+ const tsOut = resolve(opt("--ts", join(OUT, "brand.ts"))), kit = [resolve("src/canvas-core/brandKit.ts"), join(ENGINE, "src/canvas-core/brandKit.ts")].find(existsSync);+ const kitImport = kit ? (relative(dirname(tsOut), kit).replace(/\\/g, "/").replace(/\.ts$/, "")) : null;+ mkdirSync(dirname(tsOut), { recursive: true }); writeFileSync(tsOut, brandModule(brand, kitImport && (kitImport.startsWith(".") ? kitImport : `./${kitImport}`)));+ console.log(`BRAND IMPORT ${files.length} file(s) -> ${relative(process.cwd(), join(OUT, "brand.json"))}, ${relative(process.cwd(), tsOut)}\n`);+ for (const [n, r] of Object.entries(brand.report)) { console.log(` ${n.padEnd(18)} ${String(r.parts).padStart(3)} parts ${r.size.padEnd(11)} ${describe(r)}`); for (const w of r.warnings) console.log(` ${"".padEnd(18)} WARN ${w}`); }+ console.log(`\n palette: ${brand.palette.slice(0, 10).map((p) => `${p.hex} ${(p.share * 100).toFixed(0)}%`).join(", ")}`);+ if (brand.fonts.length) console.log(` fonts (live text in the source): ${brand.fonts.join(", ")}. Ask once, early, for the font files (OTF/TTF/WOFF2), or re-export with text outlined. A stand-in face is recorded in the brief and flagged on the review page.`);+ const tokens = Object.entries(brand.motion).filter(([k]) => k !== "_springs");+ if (tokens.length) console.log(` motion tokens from the source (motionKit motionTokens(BRAND.motion, fps)): ${tokens.slice(0, 4).map(([k, m]) => `${k} ${m.ms} ms ${m.ease === "linear" ? "linear" : `cubic-bezier(${m.ease.join(", ")})`}`).join("; ")}`);+ if (brand.motion._springs) console.log(` ${brand.motion._springs.length} spring easing(s) have no bezier form; translate them with the person (motion.json _springs)`);+ if (has("--sheet")) {+ const texts = Object.fromEntries(Object.entries(brand.sources).map(([n, s]) => [n, readFileSync(s.file, "utf8")])), html = sheetHtml(brand, texts, await kitBundle(), opt("--on", "checker"));+ writeFileSync(join(OUT, "sheet.html"), html); const r = await shoot(html, join(OUT, "sheet.png"));+ if (!r.shot) { console.log(`\n SHEET ${relative(process.cwd(), join(OUT, "sheet.html"))} written; ${r.why}. The match is unmeasured until it renders.`); process.exit(1); }+ const bad = Object.entries(r.results).filter(([, v]) => v.share > 0.01);+ console.log(`\n SHEET ${relative(process.cwd(), join(OUT, "sheet.png"))}: ${Object.entries(r.results).map(([n, v]) => v.broken ? `${n} SOURCE DOES NOT RENDER` : `${n} ${(v.share * 100).toFixed(2)}%`).join(", ")}`);+ console.log(bad.length ? `BRAND: FAIL ${bad.map(([n]) => n).join(", ")} draw(s) more than 1% differently from the source; open sheet.png, fix the import (a mask, filter or pattern the warnings name), never redraw by eye` : "BRAND: PASS every element draws as its source. Show sheet.png to the person for sign-off before the first storyboard.");+ process.exit(bad.length ? 1 : 0);+ }+ console.log("\nNext: brand.mjs import ... --sheet, and show sheet.png for sign-off before the first storyboard.");+ } else if (cmd === "inventory") {+ let src, inv;+ if (opt("--figma")) { src = `figma ${opt("--figma")}`; inv = framesFromFigma(await figma(`files/${opt("--figma")}?depth=4`)); }+ else if (opt("--figma-json")) { src = basename(opt("--figma-json")); inv = framesFromFigma(JSON.parse(readFileSync(resolve(opt("--figma-json")), "utf8"))); }+ else if (opt("--dir")) { src = opt("--dir"); inv = { frames: framesFromFiles(readdirSync(resolve(opt("--dir")))), motion: [] }; }+ else die("inventory needs --figma <fileKey>, --figma-json <file.json> (the REST file JSON) or --dir <exports>");+ mkdirSync(OUT, { recursive: true });+ const mdFile = join(OUT, "INVENTORY.md"), prev = new Map(existsSync(mdFile) ? parseInventory(readFileSync(mdFile, "utf8")).map((r) => [r.id, r.mark]) : []);+ writeFileSync(mdFile, renderInventory(src, inv.frames, prev)); writeFileSync(join(OUT, "inventory.json"), JSON.stringify(inv.frames, null, 1));+ if (inv.motion.length) writeFileSync(join(OUT, "motion.json"), JSON.stringify(motionTokens(inv.motion), null, 1));+ console.log(`INVENTORY ${inv.frames.length} frames from ${src} -> ${relative(process.cwd(), mdFile)}${inv.motion.length ? `; ${inv.motion.length} motion token(s) -> motion.json` : ""}\nMark each frame [x] once read, or [-] <reason>. brand.mjs check holds it.`);+ } else if (cmd === "find") {+ const mdFile = join(OUT, "INVENTORY.md"); if (!existsSync(mdFile)) die(`no ${relative(process.cwd(), mdFile)}: run brand.mjs inventory first; without it, "not in the file" is a guess`);+ const rows = parseInventory(readFileSync(mdFile, "utf8")), q = pos.join(" "), hits = findInInventory(rows, q);+ if (hits.length) { console.log(`FIND "${q}": ${hits.length} frame(s)`); for (const h of hits) console.log(` ${h.page} / ${h.name} (${h.id})${h.words ? ` "${h.words.slice(0, 90)}"` : ""}`); }+ else console.log(`FIND "${q}": not in the names or words of the ${rows.length} frames in ${relative(process.cwd(), mdFile)}. Say exactly that, and ask; the person may know a frame by another name.`);+ } else if (cmd === "check") {+ const mdFile = join(OUT, "INVENTORY.md"), r = checkInventory(existsSync(mdFile) ? parseInventory(readFileSync(mdFile, "utf8")) : []);+ if (r.why) { console.log(`BRAND CHECK: FAIL ${r.why}`); process.exit(1); }+ for (const u of r.unread) console.log(` UNREAD ${u.page} / ${u.name} (${u.id})`);+ for (const u of r.bareSkips) console.log(` SKIPPED WITH NO REASON ${u.page} / ${u.name} (${u.id})`);+ console.log(r.status === "PASS" ? `BRAND CHECK: PASS all ${r.total} frames read or skipped with a reason` : `BRAND CHECK: FAIL ${r.unread.length + r.bareSkips.length} of ${r.total} frames not accounted for; open each, then mark it [x], or [-] <why it does not matter>`);+ process.exit(r.status === "PASS" ? 0 : 1);+ } else if (cmd === "logos") {+ const dir = pos[0] ? resolve(pos[0]) : die("logos needs a folder of logo files"), on = opt("--on", "dark"), out = resolve(opt("--out", join(OUT, "logos")));+ if (!["dark", "light"].includes(on)) die("--on is dark or light");+ const colour = on === "dark" ? "#ffffff" : "#111111", rgb = on === "dark" ? [255, 255, 255] : [17, 17, 17]; mkdirSync(out, { recursive: true });+ const logos = [];+ for (const f of readdirSync(dir).filter((x) => /\.(svg|png)$/i.test(x)).sort()) {+ const name = ident(f), p = join(dir, f);+ if (/\.svg$/i.test(f)) {+ const el = importSvg(readFileSync(p, "utf8")), m = logoMetrics(el), mono = toSvg(monochrome(el, colour), { tight: true });+ writeFileSync(join(out, `${name}.svg`), toSvg(el, { tight: true })); writeFileSync(join(out, `${name}-${on}.svg`), mono);+ logos.push({ name, file: f, kind: "svg", h: m.bbox[3], w: m.bbox[2], ink: m.ink, overlaps: m.overlaps, mime: "image/svg+xml", b64: Buffer.from(mono).toString("base64"), warnings: el.warnings });+ } else {+ const img = decodePng(readFileSync(p)), box = alphaBox(img);+ if (opaqueCorners(img)) { logos.push({ name, file: f, kind: "png", skipped: "has a solid background: ask for a transparent PNG or the SVG (a cut-out by eye is a redraw)" }); continue; }+ if (!box) { logos.push({ name, file: f, kind: "png", skipped: "is fully transparent" }); continue; }+ const trimmed = crop(img, box), mono = tint(trimmed, rgb), bytes = encodePng(mono);+ writeFileSync(join(out, `${name}.png`), encodePng(trimmed)); writeFileSync(join(out, `${name}-${on}.png`), bytes);+ logos.push({ name, file: f, kind: "png", w: box[2], h: box[3], ink: inkOf(trimmed), overlaps: 0, trimmed: `${img.w}x${img.h} -> ${box[2]}x${box[3]}`, mime: "image/png", b64: bytes.toString("base64") });+ }+ }+ const ok = equaliseLogos(logos.filter((l) => !l.skipped)), table = [...ok, ...logos.filter((l) => l.skipped)];+ writeFileSync(join(out, "logos.json"), JSON.stringify(table.map(({ b64, mime, ...l }) => l), null, 1));+ console.log(`LOGOS ${dir} on ${on} -> ${relative(process.cwd(), out)}\n`);+ for (const l of table) console.log(l.skipped ? ` SKIP ${l.file} ${l.skipped}` : ` ${l.name.padEnd(18)} ${l.kind} ${String(l.w).padStart(5)}x${String(l.h).padEnd(5)} ink density ${String(l.density).padEnd(6)} -> draw ${l.height} px tall${l.trimmed ? ` (trimmed ${l.trimmed})` : ""}${l.overlaps ? ` CHECK WITH OWNER: ${l.overlaps} outline(s) overlap; it may be their design, never fix it yourself` : ""}`);+ const html = logoStripHtml(ok, on === "dark" ? "#111111" : "#f4f2ec"); writeFileSync(join(out, "strip.html"), html);+ const r = await shoot(html, join(out, "strip.png")); console.log(r.shot ? `\n strip: ${relative(process.cwd(), join(out, "strip.png"))} (show it before use)` : `\n strip: ${relative(process.cwd(), join(out, "strip.html"))}; ${r.why}`);+ } else if (cmd === "logo") {+ const film = pos[0] ? resolve(pos[0]) : die("logo needs the film's logo (svg or png)"), ref = opt("--ref") ? resolve(opt("--ref")) : die("logo needs --ref <a screenshot of the logo where it is used in production>");+ const uri = (f) => `data:${/\.svg$/i.test(f) ? "image/svg+xml" : "image/png"};base64,${readFileSync(f).toString("base64")}`, out = resolve(opt("--out", join(OUT, "logo-check.png")));+ const html = `<!doctype html><html><body style="margin:0;padding:32px;background:#f4f2ec;font:14px Poppins,Arial,sans-serif"><div style="display:flex;gap:48px;align-items:flex-end">+<figure style="margin:0"><img style="height:160px" src="${uri(ref)}"><figcaption>production: ${basename(ref)}</figcaption></figure>+<figure style="margin:0;background:#111;padding:16px"><img style="height:128px" src="${uri(film)}"><figcaption style="color:#eee">film: ${basename(film)}</figcaption></figure></div>+<script>Promise.all([...document.images].map(i=>i.decode().catch(()=>{}))).then(()=>{document.body.dataset.done='1'})</script></body></html>`;+ writeFileSync(out.replace(/\.png$/, ".html"), html); const r = await shoot(html, out, 1200);+ console.log(r.shot ? `LOGO ${relative(process.cwd(), out)}: production left, film right. Compare order, colour and spacing of every part, and show it to the person before the logo is used.` : `LOGO ${out.replace(/\.png$/, ".html")}; ${r.why}`);+ } else {+ console.log(readFileSync(fileURLToPath(import.meta.url), "utf8").split("\n").filter((l) => l.startsWith("//")).slice(0, 26).map((l) => l.slice(3)).join("\n")); process.exit(cmd ? 2 : 0);+ }+ } catch (e) { die(e.message); }+}diff --git a/skills/anidoodle/engine/tools/brandinv.mjs b/skills/anidoodle/engine/tools/brandinv.mjsnew file mode 100644index 0000000..b468a2d--- /dev/null+++ b/skills/anidoodle/engine/tools/brandinv.mjs@@ -0,0 +1,87 @@+// BRAND INVENTORY. The pure half of `brand.mjs inventory | find | check` (no files, no network).+// A launch film once answered "the sponsors are not in the design file" after searching only its own+// exports, while the file had two frames named "Social Media partners". The fix is a class fix: on first+// access, list EVERY frame of the source (name, id, size, the words on it), keep that list beside the+// film, and answer any "is X in the file?" from a search of the whole list, never from memory.+// The list also carries a read mark per frame, and `check` fails while any frame is unmarked, so+// "I read the brand file" is a claim the tool can hold.++/** Figma REST file JSON (GET /v1/files/:key) -> { frames, motion }. Top-level children of each page are the frames. */+export const framesFromFigma = (file) => {+ const pages = file?.document?.children ?? [], frames = [], motion = new Map();+ const textOf = (n, out = []) => { if (n.type === "TEXT" && n.characters) out.push(n.characters); for (const k of n.children ?? []) textOf(k, out); return out; };+ const motionOf = (n) => {+ const add = (dur, easing, from) => { if (!dur) return; const key = `${Math.round(dur * 1000)}|${JSON.stringify(easing)}`; const m = motion.get(key) ?? { ms: Math.round(dur * 1000), easing, uses: 0, from: [] }; m.uses++; if (m.from.length < 5) m.from.push(from); motion.set(key, m); };+ for (const it of n.interactions ?? []) for (const a of it.actions ?? (it.action ? [it.action] : [])) { const t = a?.transition; if (t) add(t.duration, easingOf(t.easing), `${n.name} (${t.type ?? "transition"})`); }+ if (n.transitionDuration) add(n.transitionDuration / 1000, easingOf(n.transitionEasing), n.name);+ for (const k of n.children ?? []) motionOf(k);+ };+ for (const page of pages) for (const n of page.children ?? []) {+ const box = n.absoluteBoundingBox ?? {};+ frames.push({ page: page.name, name: n.name, id: n.id, type: n.type, w: Math.round(box.width ?? 0), h: Math.round(box.height ?? 0), text: textOf(n).join(" | ").slice(0, 4000) });+ motionOf(n);+ }+ return { frames, motion: [...motion.values()].sort((a, b) => b.uses - a.uses) };+};+const easingOf = (e) => {+ if (!e) return null; if (typeof e === "string") return e;+ const b = e.easingFunctionCubicBezier; if (b) return `cubic-bezier(${b.x1}, ${b.y1}, ${b.x2}, ${b.y2})`;+ const s = e.easingFunctionSpring; if (s) return `spring(mass ${s.mass}, stiffness ${s.stiffness}, damping ${s.damping})`;+ return e.type ?? null;+};+/** A folder of exports -> frames, one per file. */+export const framesFromFiles = (names) => names.filter((f) => !f.startsWith(".")).sort().map((f) => ({ page: "(files)", name: f.replace(/\.[^.]+$/, ""), id: f, type: f.split(".").pop().toUpperCase(), w: 0, h: 0, text: "" }));++const cell = (s) => String(s ?? "").replace(/\|/g, "/").replace(/\s+/g, " ").trim();+/** The inventory page: one row per frame, an unticked read box each. Existing marks are kept by id. */+export const renderInventory = (source, frames, prev = new Map()) => [+ `# Brand inventory: ${source}`,+ "",+ `${frames.length} frames. Mark each one when you have looked at it: \`[x]\` read, or \`[-] reason\` skipped on purpose.`,+ "Answer \"is X in the file?\" with `brand.mjs find X`, which searches every name and every word below, never from memory.",+ "",+ "| read | page | frame | id | size | words on it |",+ "|---|---|---|---|---|---|",+ ...frames.map((f) => `| ${prev.get(f.id) ?? "[ ]"} | ${cell(f.page)} | ${cell(f.name)} | ${cell(f.id)} | ${f.w && f.h ? `${f.w}x${f.h}` : "-"} | ${cell(f.text).slice(0, 160)} |`),+ "",+].join("\n");+/** INVENTORY.md -> rows { mark, page, name, id, words }. */+export const parseInventory = (md) => String(md).split("\n").filter((l) => /^\|\s*\[/.test(l)).map((l) => {+ const c = l.split("|").slice(1, -1).map((x) => x.trim());+ return { mark: c[0], page: c[1], name: c[2], id: c[3], size: c[4], words: c[5] ?? "" };+});+/** Every frame read or skipped with a reason. -> { status, total, unread: [rows], bareSkips: [rows] } */+export const checkInventory = (rows) => {+ if (!rows.length) return { status: "FAIL", total: 0, unread: [], bareSkips: [], why: "the inventory lists no frames: run brand.mjs inventory first (an empty list is never a pass)" };+ // Only two marks count: [x] (read) and "[-] reason" (skipped on purpose). Anything else, such as [], [ ]+ // or [?], was never read, so it fails rather than passing unseen.+ const read = (m) => /^\[[xX]\]/.test(m), skip = (m) => /^\[-\]\s+\S/.test(m), bare = (m) => /^\[-\]\s*$/.test(m);+ const unread = rows.filter((r) => !read(r.mark) && !skip(r.mark) && !bare(r.mark)), bareSkips = rows.filter((r) => bare(r.mark));+ return { status: unread.length || bareSkips.length ? "FAIL" : "PASS", total: rows.length, unread, bareSkips };+};+const fold = (s) => String(s).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();+/** Frames whose name or words contain every query word (or a close plural/singular of it). */+export const findInInventory = (rows, query) => {+ const words = fold(query).split(" ").filter(Boolean); if (!words.length) return [];+ const stem = (w) => w.replace(/(ies|es|s)$/, "");+ return rows.filter((r) => { const hay = ` ${fold(`${r.page} ${r.name} ${r.words}`)} `; return words.every((w) => hay.includes(` ${w}`) || hay.includes(` ${stem(w)}`)); });+};+/**+ * Motion tokens for the brand file, in the shape motionKit.ts motionTokens() reads:+ * { <name>: { ease: [x1, y1, x2, y2] | "linear", ms, uses, from } }, named after the first frame that uses each timing.+ * Spring easings have no cubic-bezier form; they are listed under `_springs` for a person to translate, never guessed.+ */+export const motionTokens = (motion) => {+ const out = {}, springs = [], NAMED = { EASE_IN: [0.42, 0, 1, 1], EASE_OUT: [0, 0, 0.58, 1], EASE_IN_AND_OUT: [0.42, 0, 0.58, 1], LINEAR: "linear", EASE_IN_BACK: [0.3, -0.05, 0.7, -0.5], EASE_OUT_BACK: [0.45, 1.45, 0.8, 1], EASE_IN_AND_OUT_BACK: [0.7, -0.4, 0.4, 1.4] };+ for (const m of motion) {+ const e = String(m.easing ?? "LINEAR"), bz = e.match(/^cubic-bezier\(([^)]*)\)$/);+ const ease = bz ? bz[1].split(",").map(Number) : NAMED[e] ?? null;+ if (!ease) { springs.push({ ms: m.ms, easing: e, from: m.from }); continue; }+ let name = String(m.from?.[0] ?? "motion").replace(/\s*\(.*\)$/, "").split(/[^A-Za-z0-9]+/).filter(Boolean).map((w, i) => (i ? w[0].toUpperCase() + w.slice(1).toLowerCase() : w.toLowerCase())).join("") || "motion";+ if (/^[0-9]/.test(name)) name = `m${name}`;+ let k = name, n = 2; while (out[k]) k = `${name}${n++}`;+ out[k] = { ease, ms: m.ms, uses: m.uses, from: m.from };+ }+ if (springs.length) out._springs = springs;+ return out;+};diff --git a/skills/anidoodle/engine/tools/brandsvg.mjs b/skills/anidoodle/engine/tools/brandsvg.mjsnew file mode 100644index 0000000..1783dd8--- /dev/null+++ b/skills/anidoodle/engine/tools/brandsvg.mjs@@ -0,0 +1,362 @@+// BRAND SVG. The pure half of brand.mjs (no files, no browser), so it is unit-tested. It reads an SVG+// export (from Figma, a site or a brand pack) into the exact paths a film draws: every fill, gradient,+// transform and <use> resolved, each part with its bounding box. Nothing is redrawn or simplified,+// because a brand element approximated by eye is a different element in the owner's eyes.+// It also measures what the marks can do in motion: rotational and mirror symmetry (a mark that looks+// the same after a half turn can land from a spin without a jump) and repeat periods (a frieze that+// repeats every N units tiles without a seam).++// ------------------------------------------------------------------ XML, small and strict enough+const ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };+const unent = (s) => String(s).replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => e[0] === "#" ? String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : ENT[e] ?? m);+/** -> root node { tag, attrs, kids, text } of the first <svg>. Throws on input with no <svg>. */+export const parseXml = (src) => {+ const s = String(src).replace(/<!--[\s\S]*?-->/g, "").replace(/<\?[\s\S]*?\?>/g, "").replace(/<!DOCTYPE[\s\S]*?>/gi, "").replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_, t) => t.replace(/</g, "<"));+ const root = { tag: "#root", attrs: {}, kids: [], text: "" }, stack = [root], TAG = /<(\/?)([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;+ for (const m of s.matchAll(TAG)) {+ const top = stack[stack.length - 1];+ if (m[5] !== undefined) { top.text += unent(m[5]); continue; }+ if (m[1]) { while (stack.length > 1 && stack.pop().tag !== m[2]); continue; }+ const attrs = {}; for (const a of m[3].matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[a[1]] = unent(a[2] ?? a[3]);+ const node = { tag: m[2].replace(/^svg:/, ""), attrs, kids: [], text: "", parent: top };+ top.kids.push(node); if (!m[4]) stack.push(node);+ }+ const find = (n) => n.tag === "svg" ? n : n.kids.map(find).find(Boolean);+ const svg = find(root); if (!svg) throw new Error("not an SVG: no <svg> element found");+ return svg;+};++// ------------------------------------------------------------------ affine matrices [a b c d e f]+export const I = [1, 0, 0, 1, 0, 0];+export const mul = (m, n) => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3], m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];+export const apply = (m, x, y) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];+export const isIdentity = (m) => m.every((v, i) => Math.abs(v - I[i]) < 1e-9);+const nums = (s) => (String(s).match(/-?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g) ?? []).map(Number);+/** SVG transform attribute -> one matrix. */+export const parseTransform = (t) => {+ let m = I;+ for (const [, fn, args] of String(t ?? "").matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)) {+ const a = nums(args), r = (d) => (d * Math.PI) / 180;+ let n = I;+ if (fn === "matrix" && a.length === 6) n = a;+ else if (fn === "translate") n = [1, 0, 0, 1, a[0] ?? 0, a[1] ?? 0];+ else if (fn === "scale") n = [a[0] ?? 1, 0, 0, a[1] ?? a[0] ?? 1, 0, 0];+ else if (fn === "rotate") { const c = Math.cos(r(a[0] ?? 0)), s = Math.sin(r(a[0] ?? 0)), cx = a[1] ?? 0, cy = a[2] ?? 0; n = mul(mul([1, 0, 0, 1, cx, cy], [c, s, -s, c, 0, 0]), [1, 0, 0, 1, -cx, -cy]); }+ else if (fn === "skewX") n = [1, 0, Math.tan(r(a[0] ?? 0)), 1, 0, 0];+ else if (fn === "skewY") n = [1, Math.tan(r(a[0] ?? 0)), 0, 1, 0, 0];+ m = mul(m, n);+ }+ return m;+};++// ------------------------------------------------------------------ path data -> absolute commands -> points+/** d -> [[cmd, ...absolute numbers]] with M L C Q A Z only (H V S T and relatives resolved). */+export const parsePath = (d) => {+ const src = String(d ?? ""), out = []; let i = 0, cmd = "", x = 0, y = 0, sx = 0, sy = 0, lc = null, lq = null;+ const ws = () => { while (i < src.length && /[\s,]/.test(src[i])) i++; };+ const num = () => { ws(); const m = /^[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/.exec(src.slice(i)); if (!m) throw new Error(`bad path data near "${src.slice(i, i + 12)}"`); i += m[0].length; return Number(m[0]); };+ const flag = () => { ws(); const c = src[i++]; if (c !== "0" && c !== "1") throw new Error(`bad arc flag near "${src.slice(i - 1, i + 10)}"`); return c === "1" ? 1 : 0; };+ for (;;) {+ ws(); if (i >= src.length) break;+ if (/[a-zA-Z]/.test(src[i])) cmd = src[i++]; else if (!cmd) throw new Error("path data must start with a command");+ const rel = cmd === cmd.toLowerCase() && cmd !== "z" ? true : cmd === "z", C = cmd.toUpperCase(), ox = rel && C !== "Z" ? x : 0, oy = rel && C !== "Z" ? y : 0;+ if (C === "Z") { out.push(["Z"]); x = sx; y = sy; lc = lq = null; continue; }+ if (C === "M") { x = num() + ox; y = num() + oy; sx = x; sy = y; out.push(["M", x, y]); cmd = rel ? "l" : "L"; lc = lq = null; continue; }+ if (C === "L") { x = num() + ox; y = num() + oy; out.push(["L", x, y]); lc = lq = null; continue; }+ if (C === "H") { x = num() + ox; out.push(["L", x, y]); lc = lq = null; continue; }+ if (C === "V") { y = num() + oy; out.push(["L", x, y]); lc = lq = null; continue; }+ if (C === "C" || C === "S") {+ let x1, y1; if (C === "C") { x1 = num() + ox; y1 = num() + oy; } else [x1, y1] = lc ? [2 * x - lc[0], 2 * y - lc[1]] : [x, y];+ const x2 = num() + ox, y2 = num() + oy; x = num() + ox; y = num() + oy; out.push(["C", x1, y1, x2, y2, x, y]); lc = [x2, y2]; lq = null; continue;+ }+ if (C === "Q" || C === "T") {+ let x1, y1; if (C === "Q") { x1 = num() + ox; y1 = num() + oy; } else [x1, y1] = lq ? [2 * x - lq[0], 2 * y - lq[1]] : [x, y];+ x = num() + ox; y = num() + oy; out.push(["Q", x1, y1, x, y]); lq = [x1, y1]; lc = null; continue;+ }+ if (C === "A") { const rx = num(), ry = num(), rot = num(), la = flag(), sw = flag(); x = num() + ox; y = num() + oy; out.push(["A", rx, ry, rot, la, sw, x, y]); lc = lq = null; continue; }+ throw new Error(`unknown path command "${cmd}"`);+ }+ return out;+};++// endpoint arc -> centre form (SVG spec F.6.5), sampled+const arcPoints = (x0, y0, rx, ry, rotDeg, la, sw, x, y, n = 16) => {+ if (!rx || !ry) return [[x, y]];+ rx = Math.abs(rx); ry = Math.abs(ry); const phi = (rotDeg * Math.PI) / 180, c = Math.cos(phi), s = Math.sin(phi);+ const dx = (x0 - x) / 2, dy = (y0 - y) / 2, x1 = c * dx + s * dy, y1 = -s * dx + c * dy;+ const L = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); if (L > 1) { rx *= Math.sqrt(L); ry *= Math.sqrt(L); }+ const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1, den = rx * rx * y1 * y1 + ry * ry * x1 * x1;+ const k = (la === sw ? -1 : 1) * Math.sqrt(Math.max(0, num / den)), cx1 = (k * rx * y1) / ry, cy1 = (-k * ry * x1) / rx;+ const cx = c * cx1 - s * cy1 + (x0 + x) / 2, cy = s * cx1 + c * cy1 + (y0 + y) / 2;+ const ang = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);+ const t0 = ang(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry); let dt = ang((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry);+ if (!sw && dt > 0) dt -= 2 * Math.PI; else if (sw && dt < 0) dt += 2 * Math.PI;+ const pts = []; for (let j = 1; j <= n; j++) { const t = t0 + (dt * j) / n; pts.push([cx + rx * Math.cos(t) * c - ry * Math.sin(t) * s, cy + rx * Math.cos(t) * s + ry * Math.sin(t) * c]); }+ return pts;+};+/** d -> subpaths of points (curves sampled), each point through matrix m. */+export const flatten = (d, m = I, steps = 16) => {+ const subs = []; let cur = null, x = 0, y = 0, x0 = 0, y0 = 0;+ const put = (px, py) => cur.push(apply(m, px, py));+ for (const c of parsePath(d)) {+ if (c[0] === "M") { cur = []; subs.push(cur); x = x0 = c[1]; y = y0 = c[2]; put(x, y); continue; }+ if (!cur) { cur = []; subs.push(cur); put(x, y); }+ if (c[0] === "L") { x = c[1]; y = c[2]; put(x, y); }+ else if (c[0] === "C") { for (let j = 1; j <= steps; j++) { const t = j / steps, u = 1 - t; put(u * u * u * x + 3 * u * u * t * c[1] + 3 * u * t * t * c[3] + t * t * t * c[5], u * u * u * y + 3 * u * u * t * c[2] + 3 * u * t * t * c[4] + t * t * t * c[6]); } x = c[5]; y = c[6]; }+ else if (c[0] === "Q") { for (let j = 1; j <= steps; j++) { const t = j / steps, u = 1 - t; put(u * u * x + 2 * u * t * c[1] + t * t * c[3], u * u * y + 2 * u * t * c[2] + t * t * c[4]); } x = c[3]; y = c[4]; }+ else if (c[0] === "A") { for (const p of arcPoints(x, y, c[1], c[2], c[3], c[4], c[5], c[6], c[7], steps)) put(p[0], p[1]); x = c[6]; y = c[7]; }+ else if (c[0] === "Z") { if (cur.length) cur.push([cur[0][0], cur[0][1]]); x = x0; y = y0; cur = null; }+ }+ return subs.filter((s) => s.length > 1);+};+export const bboxOf = (subs) => {+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ for (const s of subs) for (const [x, y] of s) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; }+ return x0 === Infinity ? [0, 0, 0, 0] : [x0, y0, x1 - x0, y1 - y0];+};+/** Signed shoelace area per subpath, summed: an outline with counter-wound holes gives its ink area. */+export const signedArea = (sub) => { let a = 0; for (let i = 0; i < sub.length; i++) { const [x0, y0] = sub[i], [x1, y1] = sub[(i + 1) % sub.length]; a += x0 * y1 - x1 * y0; } return a / 2; };+/** Ink area of one part under its fill rule (holes subtract when wound the other way; evenodd: holes subtract when nested). */+export const inkArea = (subs, rule = "nonzero") => {+ if (rule !== "evenodd") return Math.abs(subs.reduce((s, p) => s + signedArea(p), 0));+ // even-odd: a subpath inside an odd number of others is a hole+ return subs.reduce((s, p, i) => { const depth = subs.filter((q, j) => j !== i && inside(p[0], q)).length; return s + (depth % 2 ? -1 : 1) * Math.abs(signedArea(p)); }, 0);+};+/** Ray-cast point-in-polygon. */+export const inside = ([x, y], poly) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) c = !c; } return c; };++// ------------------------------------------------------------------ shapes -> d+const n0 = (v, d = 0) => { const x = parseFloat(v); return Number.isFinite(x) ? x : d; };+export const shapeToD = (node) => {+ const a = node.attrs, t = node.tag;+ if (t === "path") return a.d ?? null;+ if (t === "rect") {+ const x = n0(a.x), y = n0(a.y), w = n0(a.width), h = n0(a.height); if (!w || !h) return null;+ let rx = a.rx != null ? n0(a.rx) : a.ry != null ? n0(a.ry) : 0, ry = a.ry != null ? n0(a.ry) : rx; rx = Math.min(rx, w / 2); ry = Math.min(ry, h / 2);+ if (!rx || !ry) return `M${x} ${y}H${x + w}V${y + h}H${x}Z`;+ return `M${x + rx} ${y}H${x + w - rx}A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}V${y + h - ry}A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}H${x + rx}A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}V${y + ry}A${rx} ${ry} 0 0 1 ${x + rx} ${y}Z`;+ }+ if (t === "circle" || t === "ellipse") {+ const cx = n0(a.cx), cy = n0(a.cy), rx = t === "circle" ? n0(a.r) : n0(a.rx), ry = t === "circle" ? n0(a.r) : n0(a.ry); if (!rx || !ry) return null;+ return `M${cx - rx} ${cy}A${rx} ${ry} 0 1 0 ${cx + rx} ${cy}A${rx} ${ry} 0 1 0 ${cx - rx} ${cy}Z`;+ }+ if (t === "polygon" || t === "polyline") { const p = nums(a.points); if (p.length < 4) return null; let d = `M${p[0]} ${p[1]}`; for (let i = 2; i + 1 < p.length; i += 2) d += `L${p[i]} ${p[i + 1]}`; return t === "polygon" ? d + "Z" : d; }+ if (t === "line") return `M${n0(a.x1)} ${n0(a.y1)}L${n0(a.x2)} ${n0(a.y2)}`;+ return null;+};++// ------------------------------------------------------------------ styles: attributes, style="", <style> classes, inheritance+const NAMED = { white: "#ffffff", black: "#000000", red: "#ff0000", green: "#008000", lime: "#00ff00", blue: "#0000ff", yellow: "#ffff00", orange: "#ffa500", purple: "#800080", magenta: "#ff00ff", fuchsia: "#ff00ff", cyan: "#00ffff", aqua: "#00ffff", gray: "#808080", grey: "#808080", silver: "#c0c0c0", navy: "#000080", teal: "#008080", maroon: "#800000", olive: "#808000", pink: "#ffc0cb", none: "none", transparent: "none" };+export const normColor = (c) => {+ const s = String(c ?? "").trim().toLowerCase(); if (!s) return null;+ if (NAMED[s]) return NAMED[s];+ const h = s.match(/^#([0-9a-f]{3,8})$/); if (h) { const v = h[1]; return "#" + (v.length === 3 || v.length === 4 ? v.slice(0, 3).split("").map((ch) => ch + ch).join("") : v.slice(0, 6)); }+ const r = s.match(/^rgba?\(([^)]*)\)$/); if (r) { const [R, G, B] = r[1].split(/[\s,/]+/).map((v) => (v.endsWith("%") ? (parseFloat(v) * 255) / 100 : parseFloat(v))); return "#" + [R, G, B].map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0")).join(""); }+ return s;+};+const INHERIT = ["fill", "fill-rule", "fill-opacity", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap", "stroke-linejoin", "font-family", "color"];+const styleOf = (node, classes) => {+ const st = {};+ for (const cls of String(node.attrs.class ?? "").split(/\s+/).filter(Boolean)) Object.assign(st, classes[cls] ?? {});+ for (const k of [...INHERIT, "opacity", "stop-color", "stop-opacity", "clip-path", "mask", "display", "visibility"]) if (node.attrs[k] != null) st[k] = node.attrs[k];+ for (const decl of String(node.attrs.style ?? "").split(";")) { const [k, ...v] = decl.split(":"); if (k && v.length) st[k.trim()] = v.join(":").trim(); }+ return st;+};+const parseClasses = (svg) => {+ const out = {}, walk = (n) => { if (n.tag === "style") for (const m of n.text.matchAll(/([^{}]+)\{([^}]*)\}/g)) { const decls = {}; for (const d of m[2].split(";")) { const [k, ...v] = d.split(":"); if (k && v.length) decls[k.trim()] = v.join(":").trim(); } for (const sel of m[1].split(",")) { const c = sel.trim().match(/^\.([\w-]+)$/); if (c) out[c[1]] = { ...(out[c[1]] ?? {}), ...decls }; } } n.kids.forEach(walk); };+ walk(svg); return out;+};++// ------------------------------------------------------------------ the import+const pct = (v, d) => (v == null ? d : String(v).trim().endsWith("%") ? parseFloat(v) / 100 : parseFloat(v));+const urlRef = (v) => String(v ?? "").match(/url\(\s*['"]?#([^'")\s]+)['"]?\s*\)/)?.[1];+const round = (v) => Math.round(v * 100) / 100;++/**+ * SVG text -> { w, h, parts, fonts, warnings }. Each part: { d, fill, rule, op, bb, m? , stroke?, clip? }.+ * fill: { type: "solid", c } | { type: "lin", x1, y1, x2, y2, stops, m? } | { type: "rad", cx, cy, r, fx, fy, stops, m? }.+ * m is the part's own matrix (transforms and the viewBox folded in); the path data is never rewritten.+ */+export const importSvg = (text) => {+ const svg = parseXml(text), classes = parseClasses(svg), byId = new Map(), warnings = new Set(), fonts = new Set();+ const index = (n) => { if (n.attrs.id) byId.set(n.attrs.id, n); n.kids.forEach(index); }; index(svg);+ const vb = nums(svg.attrs.viewBox ?? svg.attrs.viewbox ?? ""), w = n0(svg.attrs.width, vb[2] ?? 0), h = n0(svg.attrs.height, vb[3] ?? 0);+ let root = I; if (vb.length === 4 && vb[2] && vb[3]) { const s = Math.min(w / vb[2], h / vb[3]); root = [s, 0, 0, s, -vb[0] * s + (w - vb[2] * s) / 2, -vb[1] * s + (h - vb[3] * s) / 2]; }+ const stopsOf = (g, seen = new Set()) => {+ const own = g.kids.filter((k) => k.tag === "stop"); if (own.length || seen.has(g)) return own.map((s) => { const st = styleOf(s, classes); return [pct(s.attrs.offset, 0), normColor(st["stop-color"] ?? "#000"), pct(st["stop-opacity"], 1)]; });+ seen.add(g); const ref = byId.get(String(g.attrs["xlink:href"] ?? g.attrs.href ?? "").replace(/^#/, "")); return ref ? stopsOf(ref, seen) : [];+ };+ const paint = (v, bbLocal) => {+ if (v == null || v === "none") return null;+ const id = urlRef(v);+ if (!id) { const c = normColor(v === "currentColor" ? "#000" : v); return c === "none" ? null : { type: "solid", c }; }+ const g = byId.get(id); if (!g) { warnings.add(`a fill points at #${id}, which the file does not define; drawn black`); return { type: "solid", c: "#000000" }; }+ if (g.tag === "pattern") { warnings.add(`#${id} is a pattern fill (often an embedded image); not imported, check the contact sheet`); return null; }+ const stops = stopsOf(g), obb = (g.attrs.gradientUnits ?? "objectBoundingBox") === "objectBoundingBox";+ let gm = g.attrs.gradientTransform ? parseTransform(g.attrs.gradientTransform) : I;+ if (obb) gm = mul([bbLocal[2], 0, 0, bbLocal[3], bbLocal[0], bbLocal[1]], gm);+ const f = g.tag === "radialGradient"+ ? { type: "rad", cx: pct(g.attrs.cx, 0.5), cy: pct(g.attrs.cy, 0.5), r: pct(g.attrs.r, 0.5), fx: pct(g.attrs.fx ?? g.attrs.cx, 0.5), fy: pct(g.attrs.fy ?? g.attrs.cy, 0.5), stops }+ : { type: "lin", x1: pct(g.attrs.x1, 0), y1: pct(g.attrs.y1, 0), x2: pct(g.attrs.x2, 1), y2: pct(g.attrs.y2, 0), stops };+ if (!isIdentity(gm)) f.m = gm.map(round6);+ return f;+ };+ const parts = [];+ const visit = (node, m, inh, op, clipOuter) => {+ const t = node.tag; if (["defs", "symbol", "clipPath", "mask", "linearGradient", "radialGradient", "pattern", "style", "title", "desc", "metadata", "filter", "marker"].includes(t)) return;+ const own = styleOf(node, classes); if (own.display === "none" || own.visibility === "hidden") return;+ const st = { ...inh }; for (const k of INHERIT) if (own[k] != null) st[k] = own[k];+ let mm = node.attrs.transform ? mul(m, parseTransform(node.attrs.transform)) : m, o = op * pct(own.opacity, 1);+ let clipFromMask = null;+ if (own.mask) {+ // a mask made only of solid white shapes is a clip (Figma exports simple masks this way); a soft or grey mask is not+ const mk = byId.get(urlRef(own.mask)), shapes = mk ? mk.kids.filter((k) => shapeToD(k)) : [];+ const hard = mk && shapes.length && shapes.length === mk.kids.length && shapes.every((k) => { const ks = styleOf(k, classes); return ["#ffffff"].includes(normColor(ks.fill ?? "#000")) && pct(ks.opacity, 1) === 1 && pct(ks["fill-opacity"], 1) === 1; });+ if (hard) clipFromMask = { paths: shapes.map((k) => ({ d: shapeToD(k), m: (k.attrs.transform ? mul(mm, parseTransform(k.attrs.transform)) : mm).map(round6) })) };+ else warnings.add(`an element uses a soft or grey mask (${own.mask}); the import draws it unmasked, check the contact sheet`);+ }+ if (own.filter || node.attrs.filter) warnings.add("an element uses an SVG filter (blur, shadow); the import leaves it out, the film draws shadows itself");+ let clip = clipFromMask ?? clipOuter; const cid = urlRef(own["clip-path"]);+ if (cid) { const cp = byId.get(cid); const ds = cp ? cp.kids.map((k) => shapeToD(k) && { d: shapeToD(k), m: k.attrs.transform ? mul(mm, parseTransform(k.attrs.transform)) : mm }).filter(Boolean) : []; if (ds.length) clip = { paths: ds.map((x) => ({ d: x.d, m: x.m.map(round6) })) }; else warnings.add(`clip-path #${cid} could not be read; drawn unclipped`); }+ if (t === "text") { warnings.add("the file has live text: export with text outlined (Figma: svgOutlineText) or supply the font file, never set it in a stand-in face silently"); fonts.add(own["font-family"] ?? st["font-family"] ?? "(unnamed)"); return; }+ if (t === "image") { warnings.add("the file embeds a raster image; it is not a path, so it is not imported (bring it as an asset pinned by sha256)"); return; }+ if (t === "use") {+ const ref = byId.get(String(node.attrs["xlink:href"] ?? node.attrs.href ?? "").replace(/^#/, ""));+ if (!ref) { warnings.add(`a <use> points at a missing element`); return; }+ const um = mul(mm, [1, 0, 0, 1, n0(node.attrs.x), n0(node.attrs.y)]);+ if (ref.tag === "symbol") { ref.kids.forEach((k) => visit(k, um, st, o, clip)); return; }+ visit({ ...ref, attrs: { ...ref.attrs, id: undefined } }, um, st, o, clip); return;+ }+ if (t === "g" || t === "svg" || t === "a" || t === "switch") { node.kids.forEach((k) => visit(k, mm, st, o, clip)); return; }+ const d = shapeToD(node); if (!d) return;+ let local; try { local = bboxOf(flatten(d)); } catch (e) { warnings.add(`skipped a ${t} with unreadable path data (${e.message})`); return; }+ const isLine = t === "line" || t === "polyline";+ const fill = isLine ? null : paint(st.fill ?? "#000", local), stroke = paint(st.stroke, local);+ if (!fill && !stroke) return;+ const subs = flatten(d, mm), bb = bboxOf(subs), sw = n0(st["stroke-width"], 1) * Math.sqrt(Math.abs(mm[0] * mm[3] - mm[1] * mm[2]));+ const part = { d, fill: fill ?? { type: "none" }, rule: st["fill-rule"] === "evenodd" ? "evenodd" : "nonzero", op: round(o * pct(st["fill-opacity"], 1)), bb: (stroke ? [bb[0] - sw / 2, bb[1] - sw / 2, bb[2] + sw, bb[3] + sw] : bb).map(round) };+ if (!isIdentity(mm)) part.m = mm.map(round6);+ if (stroke) { part.stroke = { paint: stroke, w: n0(st["stroke-width"], 1), cap: st["stroke-linecap"] ?? "butt", join: st["stroke-linejoin"] ?? "miter", op: round(o * pct(st["stroke-opacity"], 1)) }; warnings.add("the file has strokes; they are drawn as strokes (export with outlined strokes for an exact match at every scale)"); }+ if (clip) part.clip = clip;+ parts.push(part);+ };+ svg.kids.forEach((k) => visit(k, root, {}, 1, null));+ return { w, h, parts, fonts: [...fonts], warnings: [...warnings] };+};+const round6 = (v) => Math.round(v * 1e6) / 1e6;++// ------------------------------------------------------------------ what the marks can do in motion+/** Outline points of a whole element, resampled so long curves and short lines weigh the same. */+export const outline = (el, spacing) => {+ const pts = [];+ for (const p of el.parts) for (const s of flatten(p.d, p.m ?? I)) for (let i = 1; i < s.length; i++) {+ const [x0, y0] = s[i - 1], [x1, y1] = s[i], L = Math.hypot(x1 - x0, y1 - y0), n = Math.max(1, Math.ceil(L / spacing));+ for (let j = 0; j < n; j++) pts.push([x0 + ((x1 - x0) * j) / n, y0 + ((y1 - y0) * j) / n]);+ }+ return pts;+};+const grid = (pts, cell) => { const g = new Map(); for (const p of pts) { const k = `${Math.floor(p[0] / cell)},${Math.floor(p[1] / cell)}`; (g.get(k) ?? g.set(k, []).get(k)).push(p); } return g; };+const nearest = (g, cell, [x, y]) => { let best = Infinity; const cx = Math.floor(x / cell), cy = Math.floor(y / cell); for (let i = -1; i <= 1; i++) for (let j = -1; j <= 1; j++) for (const q of g.get(`${cx + i},${cy + j}`) ?? []) best = Math.min(best, Math.hypot(q[0] - x, q[1] - y)); return best; };+/** Worst distance from the mapped outline back to the outline, as a share of the diagonal. */+const mismatch = (pts, map, tol) => { const g = grid(pts, tol); let worst = 0; for (const p of pts) { const d = nearest(g, tol, map(p)); if (d > worst) worst = d; if (worst === Infinity) break; } return worst; };+/**+ * Symmetry of an element about its bounding-box centre. -> { rotational: n (1 = none; 2 = same after a half turn), mirrorX, mirrorY }+ * A tolerance of 1% of the diagonal: exports carry rounding, a real asymmetry is far larger.+ */+export const symmetry = (el, tolShare = 0.01) => {+ const bb = bboxOf(el.parts.map((p) => flatten(p.d, p.m ?? I)).flat()), diag = Math.hypot(bb[2], bb[3]) || 1, tol = diag * tolShare;+ const pts = outline(el, tol / 2), cx = bb[0] + bb[2] / 2, cy = bb[1] + bb[3] / 2;+ const rot = (a) => ([x, y]) => [cx + (x - cx) * Math.cos(a) - (y - cy) * Math.sin(a), cy + (x - cx) * Math.sin(a) + (y - cy) * Math.cos(a)];+ const holds = (map) => mismatch(pts, map, tol) <= tol;+ let rotational = 1; for (const n of [6, 5, 4, 3, 2]) if (holds(rot((2 * Math.PI) / n))) { rotational = n; break; }+ return { rotational, mirrorX: holds(([x, y]) => [2 * cx - x, y]), mirrorY: holds(([x, y]) => [x, 2 * cy - y]) };+};+/**+ * Repeats inside an element: parts with the same shape (same size, fill and outline) placed at a constant step.+ * -> [{ copies, step: [dx, dy], seamless }]; seamless when copies x step spans the element's own width or height, so it tiles end to end.+ */+export const repeats = (el, tol = 0.5) => {+ // a gradient's coordinates move with each copy, so a copy is matched by its colours, not by its gradient vector+ const colours = (f) => (f.type === "solid" ? f.c : f.type === "none" ? "none" : JSON.stringify(f.stops));+ const shapeSig = (p) => `${Math.round(p.bb[2] / tol)}x${Math.round(p.bb[3] / tol)}|${parsePath(p.d).length}`;+ const out = [], seen = new Set();+ for (const [what, sig] of [["shape", shapeSig], ["pattern", (p) => `${shapeSig(p)}|${colours(p.fill)}`]]) {+ const groups = new Map(); for (const p of el.parts) { const k = sig(p); (groups.get(k) ?? groups.set(k, []).get(k)).push(p); }+ for (const g of groups.values()) {+ if (g.length < 2) continue;+ for (const axis of [0, 1]) {+ const pos = g.map((p) => p.bb[axis]).sort((a, b) => a - b), steps = pos.slice(1).map((v, i) => v - pos[i]);+ if (!steps.every((s) => s > tol && Math.abs(s - steps[0]) <= tol)) continue;+ const step = round(steps[0]), span = axis ? el.h : el.w, key = `${what}|${axis}|${step}`;+ if (seen.has(key) || (what === "pattern" && seen.has(`shape|${axis}|${step}`))) continue; seen.add(key);+ out.push({ what, copies: g.length, step: axis ? [0, step] : [step, 0], seamless: Math.abs(g.length * step - span) <= Math.max(1, span * 0.005) });+ }+ }+ }+ return out;+};++/** Every colour an element uses, from fills, strokes and gradient stops. */+export const coloursOf = (el) => {+ const out = new Map(), add = (c, area) => { if (!c || c === "none") return; out.set(c, (out.get(c) ?? 0) + area); };+ const fromPaint = (f, area) => { if (!f) return; if (f.type === "solid") add(f.c, area); else for (const s of f.stops ?? []) add(s[1], area / (f.stops.length || 1)); };+ for (const p of el.parts) { const area = p.bb[2] * p.bb[3]; fromPaint(p.fill, area); if (p.stroke) fromPaint(p.stroke.paint, area * 0.1); }+ return out;+};++/**+ * Logo metrics for sizing a strip of logos so they read equally: ink area (outline area under the fill rule),+ * ink bbox, and overlapping outlines between separate parts (flagged "check with the owner": shared strokes in a+ * wordmark may be the design, so they are never auto-fixed).+ */+export const logoMetrics = (el) => {+ const shapes = el.parts.map((p) => ({ subs: flatten(p.d, p.m ?? I), rule: p.rule, bb: p.bb }));+ const ink = shapes.reduce((s, x) => s + inkArea(x.subs, x.rule), 0), bb = bboxOf(shapes.map((x) => x.subs).flat());+ let overlaps = 0;+ for (let i = 0; i < shapes.length; i++) for (let j = i + 1; j < shapes.length; j++) {+ const a = shapes[i].bb, b = shapes[j].bb; if (a[0] > b[0] + b[2] || b[0] > a[0] + a[2] || a[1] > b[1] + b[3] || b[1] > a[1] + a[3]) continue;+ // a vertex of one outline strictly inside the other's outer ring means the shapes cross or share a stroke+ const outer = (s) => s.subs.reduce((m, p) => (Math.abs(signedArea(p)) > Math.abs(signedArea(m)) ? p : m), s.subs[0]);+ const A = outer(shapes[i]), B = outer(shapes[j]);+ if (A && B && (A.some((p) => inside(p, B)) || B.some((p) => inside(p, A)))) overlaps++;+ }+ return { ink: round(ink), bbox: bb.map(round), aspect: bb[3] ? round(bb[2] / bb[3]) : 0, overlaps };+};+/** Recolour every paint of an element to one colour (a logo for a dark or light ground). Gradients become the colour too. */+export const monochrome = (el, colour) => ({ ...el, parts: el.parts.map((p) => ({ ...p, fill: p.fill.type === "none" ? p.fill : { type: "solid", c: colour }, ...(p.stroke ? { stroke: { ...p.stroke, paint: { type: "solid", c: colour } } } : {}) })) });+/** Write an element back out as a standalone SVG (tight viewBox around its ink, for logos). */+export const toSvg = (el, { tight = false, pad = 0 } = {}) => {+ const bb = tight ? bboxOf(el.parts.map((p) => flatten(p.d, p.m ?? I)).flat()) : [0, 0, el.w, el.h];+ const vb = [bb[0] - pad, bb[1] - pad, bb[2] + 2 * pad, bb[3] + 2 * pad].map(round);+ const defs = [], paintAttr = (f) => {+ if (!f || f.type === "none") return "none"; if (f.type === "solid") return f.c;+ const id = `g${defs.length}`, stops = f.stops.map(([o, c, a]) => `<stop offset="${o}" stop-color="${c}" stop-opacity="${a}"/>`).join(""), gt = f.m ? ` gradientTransform="matrix(${f.m.join(" ")})"` : "";+ defs.push(f.type === "lin" ? `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${f.x1}" y1="${f.y1}" x2="${f.x2}" y2="${f.y2}"${gt}>${stops}</linearGradient>` : `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${f.cx}" cy="${f.cy}" r="${f.r}" fx="${f.fx}" fy="${f.fy}"${gt}>${stops}</radialGradient>`);+ return `url(#${id})`;+ };+ const body = el.parts.map((p) => `<path d="${p.d}" fill="${paintAttr(p.fill)}" fill-rule="${p.rule}"${p.op !== 1 ? ` opacity="${p.op}"` : ""}${p.m ? ` transform="matrix(${p.m.join(" ")})"` : ""}${p.stroke ? ` stroke="${paintAttr(p.stroke.paint)}" stroke-width="${p.stroke.w}"` : ""}/>`).join("");+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${vb[2]}" height="${vb[3]}" viewBox="${vb.join(" ")}">${defs.length ? `<defs>${defs.join("")}</defs>` : ""}${body}</svg>`;+};++// ------------------------------------------------------------------ outputs+/** The TS module a film imports. brandMeta goes into meta.brand so the gate knows the brand's colours and elements. */+export const brandModule = (brand, kitImport) => [+ `// Written by tools/brand.mjs import from ${Object.keys(brand.elements).length} source file(s); never edit by hand, re-import instead.`,+ "// These are the brand's exact paths: move, rotate, scale evenly, clip and layer them (brandKit.ts), never redraw them.",+ kitImport ? `import type { BrandElement } from "${kitImport}";` : "type BrandElement = { w: number; h: number; parts: any[] };",+ "",+ `export const BRAND: { elements: Record<string, BrandElement>; palette: { hex: string; share: number }[]; fonts: string[]; motion: Record<string, any> } = ${JSON.stringify({ elements: brand.elements, palette: brand.palette, fonts: brand.fonts, motion: brand.motion ?? {} })};`,+ "",+ `/** For the film's meta.brand: the brand's colours (never drawn translucent outside a declared exception) and its element names. */`,+ `export const brandMeta = ${JSON.stringify({ colors: brand.palette.map((p) => p.hex).filter((h) => /^#[0-9a-f]{6}$/.test(h)), elements: Object.keys(brand.elements) })};`,+ "/** For the film's meta.motion: layerscan fails a brand colour filled half-transparent. Spread it: meta.motion = { ...brandMotion, temperament: \"calm\" }. */",+ `export const brandMotion = ${JSON.stringify({ brandColors: brand.palette.map((p) => p.hex).filter((h) => /^#[0-9a-f]{6}$/.test(h)) })};`,+ "",+].join("\n");++/** Size every logo so its ink matches the median logo's ink at the strip height: equal visual weight, not equal boxes. */+export const equaliseLogos = (logos, height = 80) => {+ // ink per unit of height squared, so logos of different heights compare+ const dens = logos.map((l) => l.ink / (l.h * l.h)), sorted = [...dens].sort((a, b) => a - b), median = sorted[Math.floor(sorted.length / 2)] || 1;+ return logos.map((l, i) => ({ ...l, density: Math.round(dens[i] * 1000) / 1000, height: Math.round(height * Math.sqrt(median / (dens[i] || median))) }));+};diff --git a/skills/anidoodle/engine/tools/build-page.mjs b/skills/anidoodle/engine/tools/build-page.mjsindex 0fbcce2..cb9a9f9 100644--- a/skills/anidoodle/engine/tools/build-page.mjs+++ b/skills/anidoodle/engine/tools/build-page.mjs@@ -4,7 +4,7 @@ import { build } from "esbuild";import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";import { createHash } from "node:crypto";import { extname, join, relative, resolve } from "node:path";-import { overlay, resolveOverlay } from "./overlay.mjs";+import { enginePath, overlay, resolveOverlay } from "./overlay.mjs";import { requireFilm, splitShape } from "./names.mjs";import { loadFilmModule, prepareFilmSounds, filmFloat32 } from './audio.mjs';import { isMain } from "./is-main.mjs";@@ -55,15 +55,21 @@ export const buildPage = async ({ entry, out, title, plugins: extra = [] }) => {// read the manifest out of the film module itself, so the page and the film can never disagreeconst { film, music } = await loadFilmModule(shape ? `${title}-${shape}` : title, plugins);const recorded = prepareFilmSounds(film, music), audio = recorded ? filmFloat32(film) : null;- const assets = Object.fromEntries(Object.entries(film.assets.images).map(([name, file]) => { const mime = MIME[extname(file).toLowerCase()]; if (!mime) throw new Error(`asset '${name}': unsupported type ${file}`); return [name, `data:${mime};base64,${readFileSync(join(process.cwd(), file)).toString("base64")}`]; }));+ // PLACEHOLDERS (ANIDOODLE_PLACEHOLDERS=1, render/still/framecheck alike): a missing image asset becomes a+ // labelled grey box so the film can be worked on before every photo arrives. The page lists them in+ // FILM.meta.placeholders and verify-export --delivery (and ship) refuse such a file.+ const placeholders = [], PH = process.env.ANIDOODLE_PLACEHOLDERS === "1";+ const stand = (name) => { placeholders.push(name); const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="800"><rect width="800" height="800" fill="#9a9a9a"/><path d="M0 0L800 800M800 0L0 800" stroke="#7a7a7a" stroke-width="6"/><text x="400" y="410" font-family="sans-serif" font-size="44" text-anchor="middle" fill="#fff">MISSING: ${name.replace(/[<&>"]/g, "")}</text></svg>`; return [name, `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`]; };+ const assets = Object.fromEntries(Object.entries(film.assets.images).map(([name, file]) => { if (PH && !existsSync(join(process.cwd(), file))) return stand(name); const mime = MIME[extname(file).toLowerCase()]; if (!mime) throw new Error(`asset '${name}': unsupported type ${file}`); return [name, `data:${mime};base64,${readFileSync(join(process.cwd(), file)).toString("base64")}`]; }));// the renderer that draws every plate frame, and the assets any plate may read, salt every key- const salt = [BAKE_FORMAT, ...["src/canvas-core/film.ts", "src/canvas-core/core.ts"].map((f) => readFileSync(resolve(f), "utf8")), JSON.stringify(assets)].join("\0");+ const salt = [BAKE_FORMAT, ...["src/canvas-core/film.ts", "src/canvas-core/core.ts"].map((f) => readFileSync(enginePath(f), "utf8")), JSON.stringify(assets)].join("\0");const bakeSrc = bakeHashes(main.metafile, salt);const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${film.meta.title}</title><style>html,body{margin:0;height:100%;background:#1b1a1a;display:grid;place-items:center}canvas{max-width:100vw;max-height:100vh;aspect-ratio:${film.meta.W}/${film.meta.H};cursor:pointer;background:#fff}</style></head>-<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};window.__BAKE_SRC__=${JSON.stringify(bakeSrc)};${audio ? `window.__AUDIO__=${JSON.stringify(audio)};` : ''}${shape ? `window.__SHAPE__=${JSON.stringify(shape)};` : ""}</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;+<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};window.__BAKE_SRC__=${JSON.stringify(bakeSrc)};${audio ? `window.__AUDIO__=${JSON.stringify(audio)};` : ''}${shape ? `window.__SHAPE__=${JSON.stringify(shape)};` : ""}${placeholders.length ? `window.__PLACEHOLDERS__=${JSON.stringify(placeholders)};` : ""}</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;mkdirSync(join(out, ".."), { recursive: true }); writeFileSync(out, html);const meta = film.meta;- return { out, bytes: html.length, meta, assets: Object.keys(film.assets.images) };+ if (placeholders.length) console.warn(`build: ${placeholders.length} missing asset(s) drawn as placeholders: ${placeholders.join(", ")} (never for delivery)`);+ return { out, bytes: html.length, meta, assets: Object.keys(film.assets.images), placeholders };};if (isMain(import.meta.url)) { const title = requireFilm(process.argv[2], "build-page", "node tools/build-page.mjs <film>"); const r = await buildPage({ entry: `src/hosts/page-${title}.ts`, out: `dist/${title}.html`, title }); console.log(`built ${r.out} (${(r.bytes / 1024).toFixed(0)} KB, self-contained)`); }diff --git a/skills/anidoodle/engine/tools/cues.mjs b/skills/anidoodle/engine/tools/cues.mjsnew file mode 100644index 0000000..d78c73a--- /dev/null+++ b/skills/anidoodle/engine/tools/cues.mjs@@ -0,0 +1,44 @@+#!/usr/bin/env node+// CUES. Writes a film's cue sheet (src/canvas-core/cues.ts: withCues) as JSON from the film's own+// source and time maps, so the sound mix never reads a hand-copied timing file again.+// node tools/cues.mjs <film> [--out out/<film>.cues.json] [--check out/<film>.cues.json]+// --check: exit 1 when the film's cues moved since that sheet was written (the mix built from it is+// out of date: rebuild it). A film with no cue sheet exits 2 with how to declare one, never a quiet pass.+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { build } from "esbuild";+import { fileURLToPath } from "node:url";+import { isMain } from "./is-main.mjs";+import { loadFilmModule } from "./audio.mjs";++// fileURLToPath, never URL.pathname: a space in the path stays a space and a Windows drive stays C:\+export const loadCues = async () => { const r = await build({ stdin: { contents: `export * from "./src/canvas-core/cues";`, resolveDir: join(dirname(fileURLToPath(import.meta.url)), ".."), loader: "ts" }, bundle: true, write: false, format: "esm", platform: "neutral", logLevel: "error" }); return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64")); };++/** The sheet as written to disk: the film, its frame rate and length, and every cue. */+export const exportCues = async (name) => {+ const { film } = await loadFilmModule(name);+ if (!Array.isArray(film.cues) || !film.cues.length) throw Object.assign(new Error(`${name} declares no cues. Wrap the film: export const ${name} = withCues(film, [{ name: "x-lock", at: { scene: 22, through: [master] } }, ...]) (src/canvas-core/cues.ts). Sound and sync are cued from these, never from a hand-copied timing file.`), { code: 2 });+ // a launch template film's cues are sound cues with no name and no time: sheetCues names and times them+ // (written raw, the print below crashed on c.t.toFixed and --check saw every cue as one)+ const { sheetCues } = await loadCues();+ return { film: name, fps: film.meta.fps, durationFrames: film.meta.durationFrames, durationS: +(film.meta.durationFrames / film.meta.fps).toFixed(4), cues: sheetCues(film.cues, film.meta.fps) };+};++if (isMain(import.meta.url)) {+ const argv = process.argv.slice(2), name = argv.find((a, i) => !a.startsWith("--") && !["--out", "--check"].includes(argv[i - 1]));+ const opt = (k) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : undefined; };+ if (!name) { console.error("usage: node tools/cues.mjs <film> [--out out/<film>.cues.json] [--check old.cues.json]"); process.exit(2); }+ try {+ const sheet = await exportCues(name);+ if (opt("--check")) {+ const f = resolve(opt("--check")); if (!existsSync(f)) { console.error(`cues: no sheet at ${f}`); process.exit(2); }+ const { diffSheets } = await loadCues(), d = diffSheets(JSON.parse(readFileSync(f, "utf8")), sheet);+ if (d.length) { console.log(`CUES ${name}: the sheet ${opt("--check")} is out of date, so is any mix built from it:`); for (const x of d) console.log(` ${x}`); console.log(`fix: node tools/cues.mjs ${name} --out ${opt("--check")} and rebuild the mix (node tools/track.mjs mix ...)\nVERDICT: FAIL`); process.exit(1); }+ console.log(`CUES ${name}: ${sheet.cues.length} cues match ${opt("--check")}\nVERDICT: PASS`); process.exit(0);+ }+ const out = resolve(opt("--out") ?? `out/${name}.cues.json`); mkdirSync(dirname(out), { recursive: true });+ writeFileSync(out, JSON.stringify(sheet, null, 1) + "\n");+ console.log(`CUES ${name}: ${sheet.cues.length} cues over ${sheet.durationS} s -> ${out}`);+ for (const c of sheet.cues) console.log(` ${String(c.frame).padStart(6)} ${c.t.toFixed(3).padStart(8)} s ${c.name.padEnd(24)} ${c.sound ?? ""}${c.sync ? " (sync marker)" : ""}`);+ } catch (e) { console.error(`cues: ${e.message}`); process.exit(e.code === 2 ? 2 : 2); }+}diff --git a/skills/anidoodle/engine/tools/facts.mjs b/skills/anidoodle/engine/tools/facts.mjsindex daa4d19..248cdb5 100644--- a/skills/anidoodle/engine/tools/facts.mjs+++ b/skills/anidoodle/engine/tools/facts.mjs@@ -20,7 +20,9 @@// - a sourced entry has the exact sentence and a URL (http/https) or a file;// - a generated entry says what it is, and states no number (a number needs a source);// - every number in a sourced claim appears in its source sentence;-// - a TODO is not a claim yet.+// - a TODO is not a claim yet;+// - a fact is said once: the same line twice, or the same number in two entries, needs `reuse: "<reason>"`;+// - a site source ({ kind: "site", url, fetched: "YYYY-MM-DD" }) carries the day it was read.import { existsSync, readFileSync, writeFileSync } from "node:fs";import { resolve } from "node:path";import { isMain } from "./is-main.mjs";diff --git a/skills/anidoodle/engine/tools/factsrules.mjs b/skills/anidoodle/engine/tools/factsrules.mjsindex 1f347d7..c28b313 100644--- a/skills/anidoodle/engine/tools/factsrules.mjs+++ b/skills/anidoodle/engine/tools/factsrules.mjs@@ -16,6 +16,8 @@ export const entryProblems = (e) => {return out;}const src = e.source ?? {}, sentence = String(src.sentence ?? "").trim();+ // a live site changes: a site source carries the day it was read, so a viewer's "that's wrong now" can be dated+ if (src.kind === "site") { if (!src.url) out.push("is a site source with no url"); if (!/^\d{4}-\d{2}-\d{2}$/.test(String(src.fetched ?? ""))) out.push("is a site source with no fetched date (YYYY-MM-DD, the day the page was read)"); }if (!sentence) out.push("has no source.sentence (the exact sentence it comes from)");if (!String(src.url ?? "").trim() && !String(src.file ?? "").trim()) out.push("has no source.url or source.file");else if (src.url && !/^https?:\/\/\S+$/i.test(String(src.url).trim())) out.push(`source.url '${src.url}' is not an http(s) link`);@@ -28,7 +30,7 @@ export const entryProblems = (e) => {* -> { status: "PASS" | "FAIL" | "N/A", checked, problems: [{ claim, why }] }*/export const checkFacts = (claims, facts) => {- const declared = [...new Set((Array.isArray(claims) ? claims : []).map((c) => String(c).trim()).filter(Boolean))];+ const raw = (Array.isArray(claims) ? claims : []).map((c) => String(c).trim()).filter(Boolean), declared = [...new Set(raw)];if (!declared.length) return { status: "N/A", checked: 0, problems: [], reason: "the film declares no claims (film.claims), so nothing was checked" };if (!facts) return { status: "FAIL", checked: declared.length, problems: declared.map((c) => ({ claim: c, why: "has no facts.json to be listed in (node tools/facts.mjs init)" })) };const entries = Array.isArray(facts.claims) ? facts.claims : [], problems = [];@@ -40,6 +42,7 @@ export const checkFacts = (claims, facts) => {if (!e) { problems.push({ claim: c, why: "is on screen but not listed in facts.json" }); continue; }for (const why of entryProblems(e)) problems.push({ claim: c, why });}+ problems.push(...dupes(raw, entries));const declaredKeys = new Set(declared.map(normClaim));for (const e of entries) if (!declaredKeys.has(normClaim(e?.claim))) for (const why of entryProblems(e)) problems.push({ claim: String(e?.claim ?? "(no claim)"), why }); // narrated and other listed claims are held to the same shapereturn { status: problems.length ? "FAIL" : "PASS", checked: declared.length, problems };@@ -48,3 +51,23 @@ export const checkFacts = (claims, facts) => {/** The film's declared claims (a launch film: film.claims; any film may set film.claims or meta.claims). */export const claimsOf = (film) => film?.claims ?? film?.meta?.claims;++// A fact said twice is a beat wasted: a launch film said "about 400 of them" in the hook and "400+" on a+// numbers card, and the second one was cut late. Numbers worth repeating are rare enough to ask for a reason.+const FACT_NUMBER = /\d[\d.,]*\d[%+x]?|\d[%+x]|\d{2,}/g;+const factNumbers = (s) => [...new Set((String(s).match(FACT_NUMBER) ?? []).map((n) => n.replace(/[.,]+$/, "").replace(/[%+x]$/, "").replace(/,/g, "")).filter((n) => n.length >= 2 || /[%+x]/.test(n)))];+/**+ * Repeats across one film: the same line declared twice, or the same number stated by two entries.+ * The later entry may carry `reuse: "<why the repeat earns its place>"`. -> [{ claim, why }]+ */+export const dupes = (raw, entries = []) => {+ const out = [], seen = new Map();+ for (const c of raw ?? []) { const k = normClaim(c); if (seen.has(k)) { const e = entries.find((x) => normClaim(x?.claim) === k); if (!String(e?.reuse ?? "").trim()) out.push({ claim: c, why: "is on screen twice; cut one, or give its entry reuse: \"<why the repeat earns its place>\"" }); } seen.set(k, true); }+ const firstBy = new Map();+ for (const e of entries) for (const n of factNumbers(e?.claim)) {+ const first = firstBy.get(n);+ if (first === undefined) { firstBy.set(n, e); continue; }+ if (first !== e && !String(e.reuse ?? "").trim()) out.push({ claim: String(e.claim), why: `states ${n} again (first in "${String(first.claim).slice(0, 40)}"); say a fact once, or give this entry reuse: "<reason>"` });+ }+ return out;+};diff --git a/skills/anidoodle/engine/tools/framecheck.mjs b/skills/anidoodle/engine/tools/framecheck.mjsindex f4079b8..95cd52e 100644--- a/skills/anidoodle/engine/tools/framecheck.mjs+++ b/skills/anidoodle/engine/tools/framecheck.mjs@@ -1,49 +1,91 @@-// FRAMECHECK. Design faults the determinism gate cannot see, found on the frames themselves.-// 1. Cut by the edge. Every line of text (fillText, writeOn, setType) and every content box the art-// reports (probeRect: an answer card, a product window, a film's card) must lie wholly inside the-// frame or wholly outside it, on every frame checked. A deliberate full-bleed is not reported as a box.-// 2. Reading time. Each declared text cue (meta.captions) stays up for max(0.7 s, 0.3 s per word).-// A film that declares no cues reports N/A, never a pass.-// 3. Phone safe zones, 9:16 frames only. No text inside the top band, the bottom band or the right-// button column the platforms cover with their own interface. Other shapes report N/A.-// The rules and their numbers are textrules.mjs.-// node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn]-// --zones warn lists safe-zone text as FLAG and does not fail the run (launch.mjs ship passes it on with-// its own --zones warn; by default safe-zone text fails). Reading time and the edge cut always fail.+// FRAMECHECK. Design faults the determinism gate cannot see, found on the frames themselves, from the+// text and boxes every frame actually draws (the frame probe in hosts/page.ts follows text through+// offscreen layers, so a sheet composited later counts like text on the frame).+// 1. Cut by the edge. No line of text and no content box the art reports (probeRect) SITS cut by the+// frame's edge: cut and unmoved on 3 checked frames in a row fails. Sliding across the edge while+// the camera travels (one world, a pan) is motion, and is listed, not failed.+// 2. Reading time. EVERY block of text the film draws is a cue, timed from the frame it is complete+// (a typed reply: after its last character) to the last frame it is up, and must stay up+// max(0.7 s, 0.3 s per word); meta.captions are checked too. A film that draws text can never be+// N/A: it was on a brand launch film, which shipped "text too fast" with this check printing N/A.+// Words meant as texture (readable.ts texture()) are skipped and counted.+// 3. Phone safe zones, 9:16 only: no text in the platforms' top band, bottom band or right column.+// 4. Layout: too many text blocks, blocks packed into a corner, a centred stack, a gap under 3 % of+// the height, text across the edge of a content box, text over text (framerules.mjs, held 0.5 s).+// 5. The last second: no text under 28 px at 1080. The end card lands once. Heads in one group+// within 10 %. Font families listed (brand faces, stand-ins: meta.checks.fonts / standIns).+// The rules and their numbers are textrules.mjs and framerules.mjs.+// node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn] [--json out.json]+// --zones warn lists safe-zone text as FLAG and does not fail the run. Everything else fails.+import { writeFileSync } from "node:fs";import { resolve } from "node:path";import { buildPage } from "./build-page.mjs";import { detect } from "./detect.mjs";import * as playwright from "./adapters/playwright.mjs";import { requireFilm } from "./names.mjs";import { isMain } from "./is-main.mjs";-import { SAFE_ZONES, isPortrait916, readingTime, safeZoneHits } from "./textrules.mjs";+import { SAFE_ZONES, isPortrait916, safeZoneHits } from "./textrules.mjs";+import { autoCues, checkedFrames, edgeCuts, endCardRuns, endSizeFindings, fontReport, framesOf, headSpread, layoutFindings, readingFloor, readingVerdict } from "./framerules.mjs";-const USAGE = "node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn]";+const USAGE = "node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn] [--json out.json]";export const frameCheck = async (film, { every = 1, from = 0, to } = {}) => {const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });- const s = await playwright.open(detect(), page.out, { workers: 1 }), meta = await s.info(), N = to ?? meta.durationFrames, portrait = isPortrait916(meta.W, meta.H);- const frames = []; for (let f = from; f < N; f += every) frames.push(f);- const recs = []; for (let i = 0; i < frames.length; i += 40) recs.push(...(await s.probe(frames.slice(i, i + 40), portrait)));+ // the bake cache stays off: a plate frame read back from disk carries no text records+ const s = await playwright.open(detect(), page.out, { workers: 1, bakeCache: false }), meta = await s.info();+ let frames; try { frames = checkedFrames({ every, from, to }, meta.durationFrames); } catch (e) { await s.close(); throw new Error(`framecheck: ${e.message}`); }+ const recs = []; for (let i = 0; i < frames.length; i += 40) recs.push(...(await s.probe(frames.slice(i, i + 40), true)));await s.close();- return { meta, frames: frames.length, bad: recs.filter((r) => r.cut !== false), reading: readingTime(meta.captions, meta.fps), zones: safeZoneHits(recs, meta.W, meta.H) };+ const scale = 1, W = meta.W * scale, H = meta.H * scale, byFrame = framesOf(recs, frames), ck = meta.checks ?? {};+ const auto = autoCues(byFrame, frames, { first: 0, last: meta.durationFrames, fps: meta.fps });+ return {+ meta, frames: frames.length, every, // every > 1: a quick look (holds measured in steps of `every` frames), never a ship PASS+ bad: recs.filter((r) => r.cut !== false), cuts: edgeCuts(recs.filter((r) => r.cut !== false), frames),+ reading: readingVerdict(auto, meta.captions, meta.fps, frames.length), auto,+ floor: readingFloor(auto.cues, meta.fps),+ zones: safeZoneHits(recs.filter((r) => r.cut === false), W, H),+ layout: layoutFindings(byFrame, frames, { W, H, fps: meta.fps, exemptRanges: ck.layoutExempt }),+ endSize: endSizeFindings(byFrame, frames, { W, H, fps: meta.fps, durationFrames: meta.durationFrames, scale }),+ endCard: endCardRuns(byFrame, frames),+ heads: headSpread(byFrame, frames),+ fonts: fontReport(byFrame, frames, ck),+ };};++/** The verdict lines of a frameCheck result, and how many of them fail. Shared with ship.mjs. */+export const frameReport = (film, r, { warnZones = false } = {}) => {+ const lines = [], list = (fs) => `${fs.slice(0, 8).join(", ")}${fs.length > 8 ? " ..." : ""}`, out = (l) => lines.push(l);+ const cuts = r.cuts.filter((c) => c.fail), passing = r.cuts.length - cuts.length;+ out(`FRAMECHECK ${film} ${r.meta.W}x${r.meta.H}, ${r.frames} frames`);+ for (const c of cuts) out(` FAIL ${c.kind} "${String(c.label).slice(0, 48)}" cut by the frame's edge and held there ${c.held} frames (${c.frames.length} cut in all): ${list(c.frames)} box ${c.box.map((v) => Math.round(v)).join(",")}`);+ const rd = r.reading, zn = r.zones;+ for (const b of rd.bad) out(` FAIL text "${b.text.slice(0, 48)}" is up ${b.seconds} s from frame ${b.from}; reading it takes ${b.need} s (hold it longer: readable.ts chatHold/readS, or mark texture() if it is not meant to be read)`);+ for (const h of zn.hits ?? []) out(` ${warnZones ? "FLAG" : "FAIL"} text "${h.label.slice(0, 48)}" sits in the ${h.zone} on ${h.frames.length} frame(s): ${list(h.frames)}`);+ for (const x of r.layout) out(` FAIL ${x.msg} frames ${x.from}-${x.to} (declare a deliberate one in meta.checks.layoutExempt with a reason)`);+ for (const x of r.endSize) out(` FAIL ${x.msg}`);+ if (!r.endCard.ok) out(` FAIL ${r.endCard.msg}`);+ for (const g of r.heads) if (!g.ok) out(` FAIL heads in "${g.group}" differ by ${Math.round(g.spread * 100)}% (at most 10%): ${g.people.map((p) => `${p.name} ${p.h} px`).join(", ")}; place them with people.ts drawPerson and one headPx`);+ for (const f of r.fonts) if (f.standFor || f.offBrand) out(` FLAG ${f.lines} line(s) set in ${f.family}${f.standFor ? `, standing in for ${f.standFor} (the font file is missing: ask for it)` : ", not one of the brand's faces (meta.checks.fonts)"}`);+ const zp = (x) => Math.round(x * 100), a = r.auto;+ if (passing) out(` EDGE: ${passing} line(s) or box(es) crossed the edge while moving (a pan or a camera travel, not held there): not a fault`);+ out(` READING-TIME: ${rd.status}${rd.reason ? ` ${rd.reason}` : ` ${rd.checked} cue(s) (${a.cues.length} drawn, the rest meta.captions), each at least max(0.7 s, 0.3 s per word)`}${a.texture ? `; ${a.texture} texture block(s) skipped` : ""}${a.skipped.partial ? `; ${a.skipped.partial} cut off by the range` : ""}${a.skipped.seen ? `; ${a.skipped.seen} return(s) of text already read` : ""}${a.skipped.exit ? `; ${a.skipped.exit} exit step(s)` : ""}`);+ if (a.cues.length) out(` READING-FLOOR: text needs at least ${r.floor.floorS.toFixed(1)} s of the film's ${(r.meta.durationFrames / r.meta.fps).toFixed(1)} s; text stays up ${r.floor.spareS.toFixed(1)} s beyond its reading time in all (cut length from there, or from moves, never from reading)`);+ out(` SAFE-ZONES: ${zn.status === "FAIL" && warnZones ? "FLAG" : zn.status}${zn.status === "N/A" ? ` ${zn.reason}` : ` ${zn.hits.length ? `${zn.hits.length} text(s) inside` : "no text in"} the top ${zp(SAFE_ZONES.top)}%, bottom ${zp(SAFE_ZONES.bottom)}% or right ${zp(SAFE_ZONES.right)}% of the frame`}`);+ out(` LAYOUT: ${r.layout.length ? `FAIL ${r.layout.length} finding(s)` : "PASS density, gaps, stacks, overlaps"}; LAST SECOND ${r.endSize.length ? "FAIL" : "PASS"}; END CARD ${r.endCard.runs.length ? (r.endCard.ok ? "PASS (lands once)" : "FAIL") : "none reported"}; HEADS ${r.heads.length ? (r.heads.every((g) => g.ok) ? "PASS" : "FAIL") : "none reported"}`);+ const nz = zn.hits?.length ?? 0, readFail = rd.status === "FAIL" ? Math.max(1, rd.bad.length) : 0;+ const fails = cuts.length + readFail + (warnZones ? 0 : nz) + r.layout.length + r.endSize.length + (r.endCard.ok ? 0 : 1) + r.heads.filter((g) => !g.ok).length;+ out(fails ? `FRAMECHECK: FAIL ${fails} problem(s): ${cuts.length} cut by the frame's edge, ${readFail} reading time, ${warnZones ? 0 : nz} in a phone safe zone, ${r.layout.length} layout, ${r.endSize.length} too small at the end` : `FRAMECHECK: PASS no text or box cut by the edge; reading time ${rd.status}; layout clean; safe zones ${nz ? `FLAGGED (${nz} text(s))` : zn.status}`);+ return { lines, fails };+};+if (isMain(import.meta.url)) {const pos = [], opt = {};for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }const film = requireFilm(pos[0], "framecheck", USAGE), warnZones = opt.zones === "warn";if (opt.zones !== undefined && !["fail", "warn"].includes(opt.zones)) { console.error(`framecheck: --zones is fail or warn, got '${opt.zones}'\nusage: ${USAGE}`); process.exit(2); }- const r = await frameCheck(film, { every: Number(opt.every ?? 1), from: Number(opt.from ?? 0), to: opt.to === undefined ? undefined : Number(opt.to) });- const list = (fs) => `${fs.slice(0, 8).join(", ")}${fs.length > 8 ? " ..." : ""}`;- const groups = new Map(); for (const b of r.bad) { const k = `${b.kind} "${b.label.slice(0, 48)}"`; const g = groups.get(k) ?? []; g.push(b.frame); groups.set(k, g); }- console.log(`FRAMECHECK ${film} ${r.meta.W}x${r.meta.H}, ${r.frames} frames`);- for (const [k, fs] of groups) { const b = r.bad.find((x) => `${x.kind} "${x.label.slice(0, 48)}"` === k); console.log(` FAIL ${k} cut by the frame's edge on ${fs.length} frame(s): ${list(fs)} box ${[b.x0, b.y0, b.x1, b.y1].map((v) => Math.round(v)).join(",")}`); }- const rd = r.reading, zn = r.zones;- for (const b of rd.bad) console.log(` FAIL text "${b.text.slice(0, 48)}" is up ${b.seconds} s from frame ${b.from}; reading it takes ${b.need} s`);- for (const h of zn.hits ?? []) console.log(` ${warnZones ? "FLAG" : "FAIL"} text "${h.label.slice(0, 48)}" sits in the ${h.zone} on ${h.frames.length} frame(s): ${list(h.frames)}`);- const zp = (x) => Math.round(x * 100);- console.log(` READING-TIME: ${rd.status}${rd.status === "N/A" ? ` ${rd.reason}` : ` ${rd.checked} cue(s), each at least max(0.7 s, 0.3 s per word)`}`);- console.log(` SAFE-ZONES: ${zn.status === "FAIL" && warnZones ? "FLAG" : zn.status}${zn.status === "N/A" ? ` ${zn.reason}` : ` ${zn.hits.length ? `${zn.hits.length} text(s) inside` : "no text in"} the top ${zp(SAFE_ZONES.top)}%, bottom ${zp(SAFE_ZONES.bottom)}% or right ${zp(SAFE_ZONES.right)}% of the frame`}`);- const nz = zn.hits?.length ?? 0, fails = groups.size + rd.bad.length + (warnZones ? 0 : nz);- console.log(fails ? `FRAMECHECK: FAIL ${fails} problem(s): ${groups.size} cut by the frame's edge, ${rd.bad.length} read too briefly, ${warnZones ? 0 : nz} in a phone safe zone` : `FRAMECHECK: PASS no text or content box cut by the frame's edge; reading time ${rd.status}; safe zones ${nz ? `FLAGGED (${nz} text(s))` : zn.status}`);- process.exit(fails ? 1 : 0);+ let r; try { r = await frameCheck(film, { every: Number(opt.every ?? 1), from: Number(opt.from ?? 0), to: opt.to === undefined ? undefined : Number(opt.to) }); }+ catch (e) { if (!/^framecheck: --/.test(e.message)) throw e; console.error(`${e.message}\nusage: ${USAGE}`); process.exit(2); }+ const rep = frameReport(film, r, { warnZones });+ console.log(rep.lines.join("\n"));+ if (opt.json) writeFileSync(resolve(opt.json), JSON.stringify({ ...r, bad: r.bad.slice(0, 200) }, null, 1));+ process.exit(rep.fails ? 1 : 0);}diff --git a/skills/anidoodle/engine/tools/framerules.mjs b/skills/anidoodle/engine/tools/framerules.mjsnew file mode 100644index 0000000..4a193a8--- /dev/null+++ b/skills/anidoodle/engine/tools/framerules.mjs@@ -0,0 +1,276 @@+// FRAME RULES. What framecheck judges on the text and boxes a film draws, as pure functions (records in,+// findings out, no browser) so every rule is unit-tested with a case that must fail.+// Records come from the frame probe (hosts/page.ts): { kind: "text"|"box", label, frame, x0, y0, x1, y1 }+// in device pixels, text also with { alpha, px, family, texture } and cut: false when wholly in frame.+// They exist because a brand launch film passed every check while its viewers said the text+// was too fast, its end card was a crowded corner and its CTA was 14 px tall. Each rule below names+// the note it answers.+import { readingNeed, readingTime, wordCount } from "./textrules.mjs";++export const RULES = {+ gapShare: 0.03, // C4: two things closer than 3 % of the frame's short side read as touching ("circles way too close")+ maxBlocks: 7, // C2: more than 7 separate text blocks on one frame is a wall of text (the ledger said 6; a+ // product-UI beat, header + bubbles + placeholder + button, is 7 and was never the complaint)+ clusterMin: 5, // C2: 5 or more blocks ...+ clusterShare: 0.3, // ... packed into under 30 % of the frame is "an insane amount of text in a small spot"+ stackMin: 5, // C1: 5 or more blocks centred on one axis is the centred stack the director rejected+ stackTol: 0.015, // centres within 1.5 % of the width count as one axis+ overlapShare: 0.2, // T9: two text blocks sharing 20 % of the smaller one collide+ endPx: 28, // T10: text in the last second smaller than 28 px at 1080 is unreadable on a phone+ endWindowS: 1,+ headSpread: 0.1, // C5: people shown as one sequence differ in head height by at most 10 %+ persistS: 0.5, // a layout finding counts when it holds this long (a passing move is not a layout)+ flashFrames: 3, // a text replaced in place within 3 frames at 30 fps (0.1 s, scaled to the film's rate) is an animation step (a counter), not a read+};+const CURSOR = /[\s|▍▌▎█_]+$/u;++const inter = (a, b) => Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)) * Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0));+const area = (a) => Math.max(0, a.x1 - a.x0) * Math.max(0, a.y1 - a.y0);+const contains = (a, b, tol = 1) => b.x0 >= a.x0 - tol && b.y0 >= a.y0 - tol && b.x1 <= a.x1 + tol && b.y1 <= a.y1 + tol;+const centreIn = (r, b) => { const cx = (r.x0 + r.x1) / 2, cy = (r.y0 + r.y1) / 2; return cx >= b.x0 && cx <= b.x1 && cy >= b.y0 && cy <= b.y1; };+const union = (list) => list.reduce((u, r) => ({ x0: Math.min(u.x0, r.x0), y0: Math.min(u.y0, r.y0), x1: Math.max(u.x1, r.x1), y1: Math.max(u.y1, r.y1) }), { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity });+/** Edge-to-edge distance of two rectangles (0 when they touch or overlap). */+export const rectGap = (a, b) => { const dx = Math.max(0, a.x0 - b.x1, b.x0 - a.x1), dy = Math.max(0, a.y0 - b.y1, b.y0 - a.y1); return Math.hypot(dx, dy); };+const lineH = (r) => (r.px > 0 ? r.px : Math.max(1, r.y1 - r.y0));++/**+ * The text blocks of ONE frame: lines of text (single glyphs, words or whole lines, however the film+ * drew them) joined into the blocks a viewer reads as one thing. A probeRect text box with real glyphs+ * inside it gives way to the glyphs (they show what is actually drawn); one with none (writeOn draws+ * strokes) stands for its words. -> [{ key, words, x0, y0, x1, y1, px, texture, family }]+ */+export const blocksOf = (recs) => {+ const fill = recs.filter((r) => r.kind === "text" && r.px !== undefined), probes = recs.filter((r) => r.kind === "text" && r.px === undefined);+ const T = [...fill, ...probes.filter((p) => !fill.some((f) => centreIn(f, p)))];+ const parent = T.map((_, i) => i), find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));+ const sameLine = (a, b) => { const h = Math.min(lineH(a), lineH(b)), vo = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0); return vo > 0.4 * Math.min(a.y1 - a.y0, b.y1 - b.y0) && Math.max(a.x0 - b.x1, b.x0 - a.x1) < 1.0 * h; };+ const stacked = (a, b) => { const h = Math.min(lineH(a), lineH(b)); return Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0) > 0 && Math.max(a.y0 - b.y1, b.y0 - a.y1) < 0.75 * h; };+ for (let i = 0; i < T.length; i++) for (let j = i + 1; j < T.length; j++) if (sameLine(T[i], T[j]) || stacked(T[i], T[j])) parent[find(i)] = find(j);+ const groups = new Map(); T.forEach((r, i) => { const k = find(i); (groups.get(k) ?? groups.set(k, []).get(k)).push(r); });+ return [...groups.values()].map((g) => {+ // lines: by vertical overlap, top to bottom; inside a line left to right, a space where the ink gap is a word gap+ const lines = []; for (const r of [...g].sort((a, b) => a.y0 - b.y0)) { const l = lines.find((L) => Math.min(L.y1, r.y1) - Math.max(L.y0, r.y0) > 0.4 * Math.min(L.y1 - L.y0, r.y1 - r.y0)); if (l) { l.rs.push(r); l.y0 = Math.min(l.y0, r.y0); l.y1 = Math.max(l.y1, r.y1); } else lines.push({ y0: r.y0, y1: r.y1, rs: [r] }); }+ lines.sort((a, b) => a.y0 - b.y0);+ const key = lines.map((L) => { const rs = L.rs.sort((a, b) => a.x0 - b.x0); let s = ""; rs.forEach((r, i) => { const lbl = String(r.label).trim(); if (i && (r.x0 - rs[i - 1].x1 > 0.18 * lineH(r) || r.label.startsWith(" ") || rs[i - 1].label.endsWith(" "))) s += " "; s += lbl; }); return s; }).join(" ").replace(CURSOR, "").trim();+ const fam = new Map(); for (const r of g) if (r.family) fam.set(r.family, (fam.get(r.family) ?? 0) + 1);+ return { key, words: wordCount(key), ...union(g), px: Math.max(...g.map(lineH)), texture: g.every((r) => r.texture), family: [...fam.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? "" };+ });+};++/** Records grouped by frame, only what the viewer can see: in frame, not cut, alpha 0.1 and over. */+export const framesOf = (recs, frames) => {+ const m = new Map(frames.map((f) => [f, []]));+ for (const r of recs) if (r.cut === false && (r.alpha ?? 1) >= 0.1) m.get(r.frame)?.push(r);+ return m;+};++/**+ * READING TIME FROM WHAT IS DRAWN (T2). Every block of text the film shows becomes a cue, timed from the+ * first frame it is complete to the last frame it is up. Text still being typed or built (the next frame+ * shows a longer text containing it, in the same place) is not a cue yet: the read starts after the last+ * character, so a typed reply needs typing time PLUS reading time (T3). A text replaced in place within+ * RULES.flashFrames frames is an animation step (a count-up), not a read. What is left of a longer text as it+ * leaves (words sinking last-first) is an exit step, not a read. Texture text (texture()) is+ * words not meant to be read (S13). A cue cut off by the checked range is partial and not judged.+ * frames: the checked frame numbers, ascending. -> { cues, skipped: { typing, flash, partial }, texture, blocks }+ */+// what a sinking line leaves behind its clip, glyph by glyph: short letters drop out first, so "And"+// leaves "A d". True when each remnant piece is letters of one word of the longer text, in order, the+// pieces in the words' order ("A d" from "And it shows"); a new word that only shares letters ("dish")+// is not.+export const glyphsOf = (k, longer) => {+ if (longer.replace(/\s+/g, "").length <= k.replace(/\s+/g, "").length) return false; // fewer letters than were there+ const words = longer.split(/\s+/).filter(Boolean); let w = 0, c = 0;+ const inWord = (t, word, from) => { let i = from; for (const ch of t) { i = word.indexOf(ch, i); if (i < 0) return -1; i++; } return i; };+ for (const t of k.split(/\s+/).filter(Boolean)) {+ let at = -1; while (w < words.length && (at = inWord(t, words[w], c)) < 0) { w++; c = 0; }+ if (w >= words.length) return false; c = at;+ }+ return true;+};+export const autoCues = (byFrame, frames, { first = 0, last = Infinity, fps = 30 } = {}) => {+ const step = frames.length > 1 ? frames[1] - frames[0] : 1, B = new Map(frames.map((f) => [f, blocksOf(byFrame.get(f) ?? [])]));+ const cues = [], skipped = { typing: 0, flash: 0, partial: 0 }, open = new Map(); let texture = 0, blocks = 0;+ const close = (run, next) => {+ const nb = next === undefined ? [] : (B.get(next) ?? []).filter((b) => !b.texture), near = (b) => inter(b, run.box) > 0 || rectGap(b, run.box) < run.px;+ if (nb.some((b) => b.key.length > run.key.length && b.key.includes(run.key) && near(b))) { skipped.typing++; return; } // typed on, or joined by the next line of its block+ if (run.exiting) { skipped.exit = (skipped.exit ?? 0) + 1; return; }+ const span = run.last - run.first + step;+ // (flashFrames is 0.1 s at 30 fps: at 60 fps a counter's digit is up 6 frames, and was timed as a read)+ if (span <= RULES.flashFrames * Math.max(1, fps / 30) * step && nb.some((b) => b.key !== run.key && near(b))) { skipped.flash++; return; }+ if ((run.first === frames[0] && frames[0] > first) || (next === undefined && run.last === frames[frames.length - 1] && run.last + step < last)) { skipped.partial++; return; }+ cues.push({ from: run.first, to: run.last + step, text: run.key, box: run.box });+ };+ frames.forEach((f, i) => {+ const bs = B.get(f), seen = new Set();+ for (const b of bs) {+ blocks++; if (b.texture) { texture++; continue; } if (!b.key) continue;+ const k = b.key; if (seen.has(k)) continue; seen.add(k);+ const r = open.get(k);+ if (r && r.last === frames[i - 1]) { r.last = f; r.box = b; r.px = b.px; } else {+ if (r) close(r, frames[frames.indexOf(r.last) + 1]);+ // what is left of a longer text in the same place as it leaves (words sinking last-first) is an exit, not a new read+ const prev = i ? (B.get(frames[i - 1]) ?? []) : [], exiting = prev.some((p) => ((p.key.length > k.length && p.key.includes(k)) || glyphsOf(k, p.key)) && (inter(p, b) > 0 || rectGap(p, b) < b.px));+ open.set(k, { key: k, first: f, last: f, box: b, px: b.px, exiting });+ }+ }+ for (const [k, r] of open) if (!seen.has(k) && r.last === frames[i - 1]) { close(r, f); open.delete(k); }+ });+ for (const r of open.values()) close(r, undefined);+ // the same words gone for at most two checked frames and back (a sent message leaving the input for its+ // bubble, a cut between two framings of one card) are one read, not two+ cues.sort((a, b) => a.from - b.from);+ const joined = [];+ for (const c of cues) { const p = joined.findLast((q) => q.text === c.text); if (p && c.from - p.to <= 2 * step) p.to = Math.max(p.to, c.to); else joined.push({ ...c }); }+ // a text read once in full is not read again: when it comes back later (the chat's header in the next+ // shot, a placeholder after each send) a short return is not a reading fault+ const read = new Set(), out = [];+ for (const c of joined) { if (read.has(c.text)) { skipped.seen = (skipped.seen ?? 0) + 1; continue; } out.push(c); if (c.to - c.from >= Math.ceil(readingNeed(c.text) * fps - 1e-9)) read.add(c.text); }+ return { cues: out, skipped, texture, blocks };+};++/** The reading-time verdict on drawn text plus any declared captions. Never N/A while text is drawn. */+export const readingVerdict = (auto, captions, fps, framesChecked) => {+ const r = readingTime([...auto.cues, ...(Array.isArray(captions) ? captions : [])], fps);+ if (!framesChecked) return { ...r, status: "FAIL", reason: "no frame was checked: an empty run proves nothing" };+ if (r.status === "N/A") return auto.blocks ? { ...r, status: "FAIL", reason: `text was drawn (${auto.blocks} block(s)) but no cue could be timed: ${JSON.stringify(auto.skipped)}` } : { ...r, status: "NONE", reason: `no text was drawn on any of the ${framesChecked} frames checked` };+ return r;+};++/**+ * THE READING FLOOR (D2). The seconds the film cannot lose without cutting into reading time: the union+ * of every cue's [start, start + need]. Spare = how long text stays up beyond its need, summed: the only+ * place a cut for length may come from without making the text too fast.+ */+export const readingFloor = (cues, fps) => {+ const iv = cues.map((c) => [c.from, c.from + Math.ceil(readingNeed(c.text) * fps)]).sort((a, b) => a[0] - b[0]);+ let total = 0, end = -Infinity; for (const [a, b] of iv) { if (a > end) { total += b - a; end = b; } else if (b > end) { total += b - end; end = b; } }+ const spare = cues.reduce((s, c) => s + Math.max(0, c.to - c.from - Math.ceil(readingNeed(c.text) * fps)), 0);+ return { floorS: total / fps, spareS: spare / fps };+};++const exempt = (f, ranges) => (ranges ?? []).some(([a, b]) => f >= a && f < b);+/** Findings that hold at least RULES.persistS: [{ id, msg }] per frame -> [{ msg, from, to }] runs. */+const persist = (perFrame, frames, fps) => {+ const step = frames.length > 1 ? frames[1] - frames[0] : 1, need = Math.max(1, Math.round((RULES.persistS * fps) / step)), runs = new Map(), out = [];+ frames.forEach((f, i) => { for (const { id, msg } of perFrame.get(f) ?? []) { const r = runs.get(id); if (r && r.last === frames[i - 1]) { r.last = f; r.n++; } else { if (r && r.n >= need) out.push({ msg: r.msg, from: r.first, to: r.last + step }); runs.set(id, { msg, first: f, last: f, n: 1 }); } } });+ for (const r of runs.values()) if (r.n >= need) out.push({ msg: r.msg, from: r.first, to: r.last + step });+ // a run interrupted and resumed is reported once per stretch; collapse identical messages+ return out.sort((a, b) => a.from - b.from);+};++/**+ * LAYOUT (C1, C2, C4, T9). On every checked frame: too many text blocks, blocks packed into a corner, a+ * centred stack, two things nearly touching, text over the edge of a content box, text over text.+ * A finding counts when it holds RULES.persistS. meta.checks.layoutExempt [from, to, reason] ranges are+ * not judged (a deliberate wall of words, a gag that collides on purpose).+ * -> [{ rule, msg, from, to }]+ */+export const layoutFindings = (byFrame, frames, { W, H, fps, exemptRanges } = {}) => {+ const per = new Map();+ for (const f of frames) {+ if (exempt(f, exemptRanges)) continue;+ const recs = byFrame.get(f) ?? [], bl = blocksOf(recs).filter((b) => !b.texture && b.key), boxes = recs.filter((r) => r.kind === "box"), list = [];+ if (bl.length > RULES.maxBlocks) list.push({ id: "density", msg: `density: ${bl.length} text blocks on one frame (at most ${RULES.maxBlocks})` });+ if (bl.length >= RULES.clusterMin) { const u = union(bl), share = area(u) / (W * H); if (share < RULES.clusterShare) list.push({ id: "cluster", msg: `density: ${bl.length} text blocks packed into ${Math.round(share * 100)}% of the frame (spread them over at least ${RULES.clusterShare * 100}%)` }); }+ if (bl.length >= RULES.stackMin) { const cx = bl.map((b) => (b.x0 + b.x1) / 2).sort((a, b) => a - b), med = cx[cx.length >> 1], on = cx.filter((c) => Math.abs(c - med) <= RULES.stackTol * W).length; if (on >= RULES.stackMin) list.push({ id: "stack", msg: `centred stack: ${on} text blocks centred on one axis (compose an asymmetric grid: references/workflows/launch-video.md, end card)` }); }+ // collisions are judged on the lines themselves: two overlapping lines would otherwise merge into one block+ const lines = recs.filter((r) => r.kind === "text" && !r.texture && String(r.label).trim().length > 1);+ for (let i = 0; i < lines.length; i++) for (let j = i + 1; j < lines.length; j++) { const a = lines[i], b = lines[j]; if (a.label !== b.label && inter(a, b) > RULES.overlapShare * Math.min(area(a), area(b))) list.push({ id: `tt:${a.label}|${b.label}`, msg: `text over text: "${String(a.label).slice(0, 32)}" and "${String(b.label).slice(0, 32)}" overlap` }); }+ const items = [...bl.map((b) => ({ ...b, label: b.key, isText: true })), ...boxes.map((b) => ({ ...b, isText: false }))], floor = RULES.gapShare * Math.min(W, H); // of the short side: on 9:16 the height is not what the eye measures a gap against+ for (let i = 0; i < items.length; i++) for (let j = i + 1; j < items.length; j++) {+ const a = items[i], b = items[j]; if (a.label === b.label) continue;+ const ia = inter(a, b), q = (s) => `"${String(s).slice(0, 32)}"`;+ if (a.isText && b.isText) continue;+ if (ia > 0) { if (a.isText !== b.isText && !contains(a.isText ? b : a, a.isText ? a : b) && !contains(a.isText ? a : b, a.isText ? b : a)) list.push({ id: `edge:${a.label}|${b.label}`, msg: `text over an edge: ${q(a.isText ? a.label : b.label)} crosses the edge of ${q(a.isText ? b.label : a.label)}` }); continue; }+ const d = rectGap(a, b); if (d > 0 && d < floor) list.push({ id: `gap:${a.label}|${b.label}`, msg: `gap: ${q(a.label)} sits ${Math.round(d)} px from ${q(b.label)} (at least ${Math.round(floor)} px, ${RULES.gapShare * 100}% of the short side)` });+ }+ per.set(f, list);+ }+ return persist(per, frames, fps).map((x) => ({ rule: x.msg.split(":")[0], ...x }));+};++/** T10: text in the last second smaller than RULES.endPx at 1080. scale = device px per film px. */+export const endSizeFindings = (byFrame, frames, { W, H, fps, durationFrames, scale = 1 }) => {+ const from = durationFrames - Math.round(RULES.endWindowS * fps), small = new Map();+ for (const f of frames) if (f >= from) for (const b of blocksOf(byFrame.get(f) ?? [])) {+ if (b.texture || !b.key) continue; const at1080 = (b.px / scale) * (1080 / Math.min(W, H));+ if (at1080 < RULES.endPx) small.set(b.key, Math.min(small.get(b.key) ?? Infinity, at1080));+ }+ return [...small].map(([text, px]) => ({ text, px: Math.round(px), msg: `"${text.slice(0, 40)}" is ${Math.round(px)} px at 1080 in the last ${RULES.endWindowS} s (at least ${RULES.endPx}): grow it, or keep the card full size under the stinger` }));+};++export const END_CARD = "end card";+/** S9/C1: the end card lands once. Boxes labelled "end card" (endCard.ts probes it) seen in more than one run is card, something else, card. */+export const endCardRuns = (byFrame, frames) => {+ const runs = []; let on = false;+ for (const f of frames) { const vis = (byFrame.get(f) ?? []).some((r) => r.kind === "box" && r.label === END_CARD); if (vis && !on) runs.push([f, f]); if (vis) runs[runs.length - 1][1] = f; on = vis; }+ return { runs, ok: runs.length <= 1, msg: runs.length > 1 ? `the end card lands ${runs.length} times (${runs.map(([a, b]) => `${a}-${b}`).join(", ")}): one landing only, end on the card or on the stinger, never card-stinger-card` : "" };+};++/** C5: heads in one sequence match. Boxes labelled "head:<group>/<name>" (people.ts); each person's settled (largest) head height per group. */+export const headSpread = (byFrame, frames) => {+ const best = new Map();+ for (const f of frames) for (const r of byFrame.get(f) ?? []) { if (r.kind !== "box" || !String(r.label).startsWith("head:")) continue; const h = r.y1 - r.y0; if (h > (best.get(r.label) ?? 0)) best.set(r.label, h); }+ const groups = new Map(); for (const [label, h] of best) { const [g, name] = label.slice(5).split("/"); (groups.get(g) ?? groups.set(g, []).get(g)).push({ name: name ?? g, h: Math.round(h) }); }+ return [...groups].map(([group, people]) => { const hs = people.map((p) => p.h), spread = Math.min(...hs) > 0 ? (Math.max(...hs) - Math.min(...hs)) / Math.min(...hs) : 0; return { group, people, spread, ok: people.length < 2 || spread <= RULES.headSpread }; });+};++/** T8: which font families set the text, and the lines in a declared stand-in or outside the brand's faces. */+export const fontReport = (byFrame, frames, { fonts, standIns } = {}) => {+ const fam = new Map(); for (const f of frames) for (const r of byFrame.get(f) ?? []) if (r.kind === "text" && r.family && !r.texture) { const e = fam.get(r.family) ?? { family: r.family, lines: new Set() }; e.lines.add(r.label); fam.set(r.family, e); }+ const brand = new Set((fonts ?? []).map((s) => s.toLowerCase())), stand = Object.fromEntries(Object.entries(standIns ?? {}).map(([want, used]) => [String(used).toLowerCase(), want]));+ return [...fam.values()].map((e) => { const k = e.family.toLowerCase(), standFor = stand[k]; return { family: e.family, lines: e.lines.size, standFor, offBrand: brand.size > 0 && !brand.has(k) && !standFor }; });+};++/**+ * CUT BY THE EDGE, held (T7, M11). A line or box the frame's edge cuts through is a fault when it SITS+ * there: a sliced line left at the top edge for 196 frames, a name that overflows. Text sliding across+ * the edge while the camera travels in one world is a pan, not a fault. So a cut counts once the same+ * label is cut, unmoved (under half a pixel), on 3 checked frames in a row.+ * bad: the probe's cut records. -> [{ kind, label, frames, box, held }] with held = the longest still run.+ */+export const edgeCuts = (bad, frames, minHeld = 3) => {+ const idx = new Map(frames.map((f, i) => [f, i])), groups = new Map();+ for (const b of bad) { const k = `${b.kind}\u0000${b.label}`; (groups.get(k) ?? groups.set(k, []).get(k)).push(b); }+ const gap = (a, b) => Math.abs(a.x0 - b.x0) + Math.abs(a.y0 - b.y0) + Math.abs(a.x1 - b.x1) + Math.abs(a.y1 - b.y1);+ const out = [];+ for (const list of groups.values()) {+ // One label can be drawn more than once on a frame (two "Learn more" buttons, setType's fill per+ // character). Each record is followed as its own track: matched to the nearest record of the same+ // label on the checked frame before, nearest pairs first. Grouping by label alone compared the two+ // copies with each other, so a cut held for 6 frames read as never held.+ list.sort((a, b) => a.frame - b.frame);+ const byFrame = new Map(); for (const b of list) (byFrame.get(b.frame) ?? byFrame.set(b.frame, []).get(b.frame)).push(b);+ let live = [], prevIdx = null, held = 1, heldBox = list[0];+ for (const [f, recs] of byFrame) {+ const i = idx.get(f), cand = i !== undefined && prevIdx !== null && i === prevIdx + 1 ? live : [];+ const pairs = []; recs.forEach((r, ri) => cand.forEach((t, ti) => pairs.push([gap(r, t.last), ri, ti]))); pairs.sort((a, b) => a[0] - b[0]);+ const usedR = new Set(), usedT = new Set(), next = [];+ for (const [d, ri, ti] of pairs) {+ if (usedR.has(ri) || usedT.has(ti)) continue; usedR.add(ri); usedT.add(ti);+ const run = d < 0.5 ? cand[ti].run + 1 : 1; next.push({ last: recs[ri], run }); if (run > held) { held = run; heldBox = recs[ri]; }+ }+ recs.forEach((r, ri) => { if (!usedR.has(ri)) next.push({ last: r, run: 1 }); });+ live = next; prevIdx = i ?? null;+ }+ out.push({ kind: list[0].kind, label: list[0].label, frames: [...byFrame.keys()], box: [heldBox.x0, heldBox.y0, heldBox.x1, heldBox.y1], held, fail: held >= minHeld });+ }+ return out;+};++/**+ * THE FRAMES A CHECK LOOKS AT (framecheck, layerscan, ship): from `from` up to `to` (default: the whole film)+ * every `every` frames. A bad value is refused with the flag named, never quietly bent: --every abc used to+ * check frame 0 alone and print PASS, --every 0 looped until memory ran out, and a --from past the end+ * checked nothing and passed. Zero frames checked is refused too: an empty run proves nothing.+ */+export const checkedFrames = ({ every = 1, from = 0, to } = {}, N) => {+ const int = (v) => typeof v === "number" && Number.isInteger(v);+ if (!int(every) || every < 1) throw new Error(`--every wants a whole number of frames, 1 or more; got '${every}'`);+ if (!int(from) || from < 0 || from >= N) throw new Error(`--from wants a frame from 0 to ${N - 1}; got '${from}'`);+ const end = to === undefined ? N : to;+ if (!int(end) || end <= from) throw new Error(`--to wants a frame after --from (${from}); got '${to}'`);+ const out = []; for (let f = from; f < Math.min(end, N); f += every) out.push(f);+ return out;+};diff --git a/skills/anidoodle/engine/tools/gate.mjs b/skills/anidoodle/engine/tools/gate.mjsindex 3898a1c..03a9633 100644--- a/skills/anidoodle/engine/tools/gate.mjs+++ b/skills/anidoodle/engine/tools/gate.mjs@@ -8,20 +8,26 @@// 2 CONTRACT a static scan of every module the film draws through.// 3 DEAD AIR no identical consecutive frames, no half-second window under 0.5 % changed per 1/30 s.// 5 3D CHECKS 3D films only: three-core/checks3d.ts on sampled frames plus every frame of a-// grip's contact window. Any finding (a prop through a hand, rigs clipping) fails.+// grip's contact window. Any finding (a prop through a hand, rigs clipping) fails, and+// so does a 3D film that registers nothing to check (unless meta.checks.none["3d"] says why).+// A film made before a check existed (a frozen source of a published film) may declare a dead-air row,+// meta.checks.none["gate:identical"] or ["gate:still"], with its reason: listed with the reason, never counted.//// The gate NEVER writes to out/. It renders into .tmp/gate/ and it only ever READS the MP4 it is// pointed at, so running it can never damage a finished film.import { execFileSync, spawnSync } from "node:child_process";import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";-import { resolve } from "node:path";+import { join, resolve } from "node:path";+import { ROOTS } from "./overlay.mjs";+import { trackProvenance } from "./sidecar.mjs";import { readdirSync } from "node:fs";import { defaultOutput, requireFilm } from "./names.mjs";import { changedArea } from "./motion.mjs";import { pathToFileURL } from "node:url";import { glArgs } from "./adapters/playwright.mjs";import { detect } from "./detect.mjs";+import { deadAirVerdict, threeDVerdict } from "./gaterules.mjs";const VAL = new Set(["adapter", "mp4", "samples", "scale", "workers"]);const pos = [], opt = {};@@ -69,7 +75,8 @@ const walk = (dir, out = []) => { for (const e of execFileSync("find", [dir, "-nconst contractScan = () => {head(2, "CONTRACT the art core cannot reach a clock, the network or a file");// the worked example is part of the same tree at build time (tools/overlay.mjs): scan it too- const files = [...walk("src/canvas-core"), ...(existsSync("src/three-core") ? walk("src/three-core") : []), ...(existsSync("../example/src/canvas-core") ? walk("../example/src/canvas-core") : []), `src/hosts/page-${film}.ts`].filter((f) => existsSync(f));+ // a linked project (scaffold --linked) draws through the engine's modules too: scan the whole tree the build sees+ const files = [...new Set(ROOTS.flatMap((r) => ["canvas-core", "three-core"].map((d) => join(r, d))).filter((d) => existsSync(d)).flatMap((d) => walk(d)))].concat(existsSync(`src/hosts/page-${film}.ts`) ? [`src/hosts/page-${film}.ts`] : []);const hits = [];for (const f of files) { const src = stripComments(readFileSync(f, "utf8")); FORBIDDEN.forEach(([re, label]) => { const m = src.match(new RegExp(re.source, "g")); if (m) hits.push(`${f}: ${label} x${m.length}`); }); }say(hits.length === 0, `no forbidden call in ${files.length} art-core modules`, hits.length ? hits.slice(0, 6).join(" | ") : "Math.random, Date, performance.now, ctx.filter, network, image/font loads: none");@@ -93,8 +100,10 @@ const deadAir = async (mp4, meta) => {const merged = []; win.forEach((f) => { const l = merged[merged.length - 1]; if (l && f <= l[1]) l[1] = f + windowSize; else merged.push([f, f + windowSize]); });for (const [from, to, reason] of meta.locked ?? []) console.log(` LOCKED ${from}-${to}: ${reason}; violations remain failures`);for (const [from, to, reason] of meta.holds ?? []) if (reason) console.log(` HOLD ${from}-${to}: ${reason}`);- say(still.length === 0, "no unexplained identical consecutive frames", still.length ? still.slice(0, 20).join(", ") : "none");- say(merged.length === 0, `no ${windowSize}-frame window under ${meta.kind === "drawing" ? "0.02" : "0.5"}% changed`, merged.map(([a, b]) => `${a}-${b}`).join(", ") || "none");+ // (a frozen film made before these checks may declare a row in meta.checks.none: listed with its reason, never counted as a pass)+ const row = (key, ok, label, detail) => { const v = deadAirVerdict(key, ok, detail, meta); if (v.counted) say(v.ok, label, v.detail); else note(`${label} (not judged)`, v.detail); };+ row("gate:identical", still.length === 0, "no unexplained identical consecutive frames", still.length ? still.slice(0, 20).join(", ") : "none");+ row("gate:still", merged.length === 0, `no ${windowSize}-frame window under ${meta.kind === "drawing" ? "0.02" : "0.5"}% changed`, merged.map(([a, b]) => `${a}-${b}`).join(", ") || "none");const mvt = changed.slice(1).sort((a, b) => a - b);console.log(` ${n} frames measured; median ${((mvt[mvt.length >> 1] ?? 0) * 100).toFixed(2)}% min ${((mvt[0] ?? 0) * 100).toFixed(2)}%`);};@@ -123,9 +132,9 @@ const checks3d = async (pagePath, meta) => {const fill = []; for (let i = 0; i + 1 < sampled.length; i++) { const a = byFrame.get(sampled[i]), b = byFrame.get(sampled[i + 1]); if (a?.grips.length || b?.grips.length) for (let f = sampled[i] + 1; f < sampled[i + 1]; f++) fill.push(f); }recs.push(...(await ask(fill)));if (errors.length) { say(false, "the 3D check pass drew without errors", errors.slice(0, 3).join("; ")); return; }- const findings = recs.flatMap((r) => r.findings), withGrip = recs.filter((r) => r.grips.length).length;- if (!recs.length) { note(`no frame registers anything to check (${sampled.length} sampled)`, "a 3D film with characters or held props should register them: three-core/checks3d.ts"); return; }- say(findings.length === 0, `${recs.length} frames checked (${sampled.length} sampled + ${fill.length} in grip windows), ${withGrip} with a grip`, findings.length ? `${findings.length} finding(s): ` + findings.slice(0, 6).map((x) => `${x.frame} ${x.kind} ${x.where}: ${x.detail}`).join(" | ") : "no finding");+ // nothing registered is a check that could not look: FAIL, unless the film declares why (gaterules.mjs)+ const v = threeDVerdict({ recs, sampled: sampled.length, fill: fill.length, meta });+ if (v.counted) say(v.ok, v.label, v.detail); else note(v.label, v.detail);} finally { await browser.close(); }};@@ -211,6 +220,14 @@ const run = async () => {console.log(` ${art.path} (${(art.bytes / 1024).toFixed(0)} KB, ${art.kind})`);art.checks.forEach((c) => say(c.ok, c.label, c.detail));}+ // EXTERNAL MUSIC (meta.checks.music.track). "Any score is synthesized in the page" holds for the page; a+ // film whose music is a supplied or generated track is mixed outside it (track.mjs), so the gate holds+ // the delivered file to the take its manifest pins instead of waving it through (X3).+ if (meta.checks?.music?.track) {+ head("4b", "EXTERNAL TRACK the music in the file is the pinned take");+ const mp4 = resolve(opt.mp4 ?? defaultOutput(film)), pv = trackProvenance(resolve(meta.checks.music.track), mp4);+ say(pv.ok, "the delivered mix comes from the take its manifest pins", pv.detail);+ }await checks3d(resolve(`dist/${film}.html`), meta);console.log(`\n${"=".repeat(58)}`);diff --git a/skills/anidoodle/engine/tools/gaterules.mjs b/skills/anidoodle/engine/tools/gaterules.mjsnew file mode 100644index 0000000..cecbd05--- /dev/null+++ b/skills/anidoodle/engine/tools/gaterules.mjs@@ -0,0 +1,43 @@+// GATE RULES. The decisions gate.mjs makes that can be made without a browser, as pure functions, so each+// is unit-tested with a case that must fail (test/gaterules.test.ts).++/**+ * CHECK 5, 3D: what the page's runChecks returned on the frames asked. A 3D film with no frame that registers+ * anything to check (no grip, no rig) did not look: that FAILS, unless the film declares why there is+ * nothing to check in meta.checks.none["3d"] (a turntable with no characters and nothing held). It used to+ * print a note, count nothing, and let the gate say PASS without one 3D check having run.+ * -> { counted, ok, label, detail }: counted false is a listed note with the film's reason.+ */+export const threeDVerdict = ({ recs, sampled, fill, meta }) => {+ if (!recs.length) {+ const why = meta?.checks?.none?.["3d"];+ if (typeof why === "string" && why.trim()) return { counted: false, ok: true, label: `no frame registers anything to check (${sampled} sampled)`, detail: `declared in meta.checks.none["3d"]: ${why.trim()}` };+ return { counted: true, ok: false, label: `a 3D film with no frame registering anything to check (${sampled} sampled): the 3D checks could not look`, detail: 'register its characters and held props (three-core/checks3d.ts runChecks, registerGrip), or declare meta.checks.none["3d"] = "<reason>" when there is truly nothing to check' };+ }+ const findings = recs.flatMap((r) => r.findings), withGrip = recs.filter((r) => r.grips.length).length;+ return { counted: true, ok: findings.length === 0, label: `${recs.length} frames checked (${sampled} sampled + ${fill} in grip windows), ${withGrip} with a grip`, detail: findings.length ? `${findings.length} finding(s): ` + findings.slice(0, 6).map((x) => `${x.frame} ${x.kind} ${x.where}: ${x.detail}`).join(" | ") : "no finding" };+};++/**+ * The findings that belong to one grip (still.mjs --grips labels each crop with them). A grip is named+ * "<holder>/<prop>"; checkGrip's findings say "<holder> holding <prop>" and its proximity finding+ * "<holder> / <prop> at ...". Every crop used to carry every grip finding on the frame.+ */+export const gripFindings = (grip, findings) => {+ const name = String(grip.name), heads = [];+ for (let i = name.indexOf("/"); i >= 0; i = name.indexOf("/", i + 1)) { const h = name.slice(0, i), p = name.slice(i + 1); heads.push(`${h} holding ${p}`, `${h} / ${p} `); }+ return findings.filter((x) => (x.kind.startsWith("grip") || x.kind === "proximity") && heads.some((h) => String(x.where).startsWith(h)));+};++/**+ * CHECK 3, DEAD AIR, one row ("gate:identical" identical consecutive frames, "gate:still" a still window).+ * A film made before the check existed (a frozen source of a published film, whose pace was approved)+ * may declare the row in meta.checks.none with its reason: the row is then listed with the reason and its+ * findings, and not counted. Undeclared, it is a PASS or a FAIL as it was.+ * -> { counted, ok, detail }+ */+export const deadAirVerdict = (key, ok, detail, meta) => {+ const why = meta?.checks?.none?.[key];+ if (!ok && typeof why === "string" && why.trim()) return { counted: false, ok: true, detail: `declared in meta.checks.none["${key}"]: ${why.trim()}; found: ${detail}` };+ return { counted: true, ok, detail };+};diff --git a/skills/anidoodle/engine/tools/launch.mjs b/skills/anidoodle/engine/tools/launch.mjsindex 11003e2..a7ed65e 100644--- a/skills/anidoodle/engine/tools/launch.mjs+++ b/skills/anidoodle/engine/tools/launch.mjs@@ -51,8 +51,18 @@ export const ${n} = makeLaunchFilm({title: "TODO Product", // the exact product namesubtitle: "TODO the one line it lives by",placeholder: "Ask for anything…",+ // THE LOOK: your product's own, field by field (launch-video-kit.md, Looks). Uncomment what you need;+ // every field is optional and the base's value stands for the rest. launchExampleBrand.ts is a worked example.+ // look: {+ // base: "drawn", // a registered look: "drawn" or "clean" (or one you registerLook)+ // from: brandJson, // import brandJson from "../../brand/brand.json" (node tools/brand.mjs import): fills palette, logo+ // palette: { bg: "#rrggbb", card: "#rrggbb", ink: "#rrggbb", soft: "#rrggbb", mute: "#rrggbb", line: "#rrggbb", chip: "#rrggbb", accent: "#rrggbb", accentDeep: "#rrggbb", paper: "#rrggbb" }, // checked for contrast (WCAG AA)+ // fonts: { display: { family: "Your Serif", file: yourSerif }, text: { family: "Your Sans", file: yourSans } }, // import yourSans from "../../assets/fonts/YourSans.ttf" (a local .ttf, no network)+ // shape: { radius: 12, bubble: "rounded", composer: "box", button: "pill", buttonLabel: "Send" }, // bubble rounded|square|none, composer box|bar, button pill|square+ // chat: { header: true, title: "Product", subtitle: "its line", logo: undefined, bubble: { fill: "#rrggbb", ink: "#rrggbb" }, reply: { fill: "#rrggbb", ink: "#rrggbb" } },+ // },asks: [- { prompt: "TODO what a user types, in their words", plate: lighthouseDraw, label: "TODO the card's byline" },+ { prompt: "TODO what a user types", plate: lighthouseDraw, label: "TODO the card's byline" },{ prompt: "TODO the follow-up", plate: foxDraw, label: "TODO byline" },],words: [[{ text: "TODO CLAIM.", style: "ink", color: C.ink }, { text: "TODO PROOF.", style: "ink", color: C.accent }]],@@ -60,8 +70,18 @@ export const ${n} = makeLaunchFilm({install: ["TODO the exact install line"], // shown exactly as given, held 3 s or morefooter: "TODO where it lives",bpm: 90, // TODO the tempo of the score composed for this brief- askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 4,- score: null, // TODO the score composed for this product (references/music/compose.md)+ // THE DECLARATIONS ship reads (node tools/ship.mjs): a check with nothing declared cannot look, and+ // a check that cannot look fails. Fill each from the brief (launchExample.ts is a worked example).+ motion: {+ temperament: "calm", // TODO how the brand moves: "calm", "lively" or "snappy"+ brandColors: [C.accent], // TODO the brand's own colours, #rrggbb (no see-through fills in them; the drawn look's ink is its pen, not a brand colour unless yours is ink)+ },+ claims: [], // TODO every claim beyond the words and tagline (a real number on screen), each in facts.json+ checks: { length: { target: 30, max: 45 } }, // TODO the length budget in seconds: over max fails, over target flags+ // the review is yours: a fresh critic's findings go in reviews/${n}.json (references/workflows/review.md)+ askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 5,+ score: null, // TODO the score composed for this product (references/music/compose.md; launchExampleScore.ts is a worked example)+ sfx: false, // TODO true once the score is in: the sound cues ride the score, and alone they are clicks on silence (soundcheck fails their loudness)});`;const CLEAN = (n) => `// ${n}: a UI-first launch film on the template, in the clean preset (a quiet canvas, one accent,@@ -72,24 +92,54 @@ const CLEAN = (n) => `// ${n}: a UI-first launch film on the template, in the climport { makeLaunchFilm } from "./launchTemplate";import type { ProductUI } from "./productUI";+// (the stand-in is three plain rows on purpose, and the split beat shows it without its command bar: it renders+// and ships as it is. Your real screen will have more on it,+// its nav, its figures, its tags; a frame of it over 7 text blocks is dense, and framecheck says so: declare+// those beats in checks.layoutExempt below once you see them)const main: ProductUI = { // TODO your product's own UI, its before and after- title: "TODO", nav: ["TODO", "TODO"], action: "TODO action", command: "TODO Ask…",- before: { items: [{ id: "a", label: "TODO item", value: 3, tag: "TODO" }, { id: "b", label: "TODO item", value: 8 }] },- after: { items: [{ id: "b", label: "TODO item", value: 0, done: true, accent: true }, { id: "a", label: "TODO item", value: 0, done: true }] },+ title: "TODO", action: "TODO action",+ before: { items: [{ id: "a", label: "TODO first item", tag: "TODO" }, { id: "b", label: "TODO second item" }, { id: "c", label: "TODO third item" }] },+ after: { items: [{ id: "b", label: "TODO second item", done: true, accent: true }, { id: "a", label: "TODO first item", tag: "TODO", done: true }, { id: "c", label: "TODO third item", done: true }] },};export const ${n} = makeLaunchFilm({title: "TODO Product", preset: "clean", fps: 60,+ // THE LOOK: your product's own, field by field (launch-video-kit.md, Looks). Uncomment what you need;+ // every field is optional and the base's value stands for the rest. launchExampleBrand.ts is a worked example.+ // look: {+ // base: "clean", // a registered look (preset: "clean" above is its shorthand; keep one of the two)+ // from: brandJson, // import brandJson from "../../brand/brand.json" (node tools/brand.mjs import): fills palette, logo+ // palette: { bg: "#rrggbb", card: "#rrggbb", ink: "#rrggbb", soft: "#rrggbb", mute: "#rrggbb", line: "#rrggbb", chip: "#rrggbb", accent: "#rrggbb", accentDeep: "#rrggbb", paper: "#rrggbb" }, // checked for contrast (WCAG AA)+ // fonts: { display: { family: "Your Serif", file: yourSerif }, text: { family: "Your Sans", file: yourSans } }, // import yourSans from "../../assets/fonts/YourSans.ttf" (a local .ttf, no network)+ // shape: { radius: 12, bubble: "rounded", composer: "box", button: "pill", buttonLabel: "Send" }, // bubble rounded|square|none, composer box|bar, button pill|square+ // chat: { header: true, title: "Product", subtitle: "its line", logo: undefined, bubble: { fill: "#rrggbb", ink: "#rrggbb" }, reply: { fill: "#rrggbb", ink: "#rrggbb" } },+ // },asks: [- { kind: "ui", ui: main, prompt: "TODO what a user asks the product" },- { kind: "ui", ui: main, split: [{ text: "TODO the feature,", style: "ink", color: "#15161a" }, { text: "TODO in five words.", style: "ink", color: "#2f54eb" }] },+ { kind: "ui", ui: { ...main, command: "TODO Ask…" }, prompt: "TODO what a user asks the product" }, // the ask typed into its command bar+ { kind: "ui", ui: main, split: [{ text: "TODO the feature,", style: "ink", color: "#15161a" }, { text: "in five words.", style: "ink", color: "#2f54eb" }] }, // TODO the feature in about five words],words: [[{ text: "TODO CLAIM.", style: "ink", color: "#15161a" }]],tagline: "TODO one sentence that says what it is",install: ["TODO the exact install line"],footer: "TODO where it lives",- bpm: 90, askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 4,- score: null, // TODO the score composed for this product+ // THE DECLARATIONS ship reads (node tools/ship.mjs): a check with nothing declared cannot look, and+ // a check that cannot look fails. Fill each from the brief (launchExampleClean.ts is a worked example).+ motion: {+ temperament: "calm", // TODO how the brand moves: "calm", "lively" or "snappy"+ brandColors: ["#15161a", "#2f54eb"], // TODO the brand's own colours, #rrggbb (no see-through fills in them)+ },+ claims: [], // TODO every claim beyond the words and tagline (a real number on screen), each in facts.json+ checks: {+ length: { target: 30, max: 45 }, // TODO the length budget in seconds: over max fails, over target flags+ // a product screen dense with rows is the point of its beat, not a layout fault: once you see the beats,+ // declare each as [from, to, "why"] in film frames (ship's frame row names them; launchExampleClean.ts shows how)+ // layoutExempt: [[0, 330, "TODO the first ask shows the product's whole inbox: dense UI is the subject"]],+ },+ // the review is yours: a fresh critic's findings go in reviews/${n}.json (references/workflows/review.md)+ // (claimBar 6: the split beat's words need their reading time before the end card; the template says so if not)+ bpm: 90, askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 6,+ score: null, // TODO the score composed for this product (launchExampleCleanScore.ts is a worked example)+ sfx: false, // TODO true once the score is in: the sound cues ride the score, and alone they are clicks on silence (soundcheck fails their loudness)});`;diff --git a/skills/anidoodle/engine/tools/layerscan.mjs b/skills/anidoodle/engine/tools/layerscan.mjsnew file mode 100644index 0000000..68366b1--- /dev/null+++ b/skills/anidoodle/engine/tools/layerscan.mjs@@ -0,0 +1,75 @@+// node tools/layerscan.mjs <film> [--checks exits,fasttext,faces,translucent] [--every 1] [--from F] [--to T] [--json]+// LAYER SCAN. Watches what each frame DRAWS (hosts/instrument.ts: every line of text, every photo, every+// box the art reports, every fill in a brand colour) and fails the faults that pixels alone cannot pin+// on an element. Each one is a note from a brand launch film:+// exits a line of text leaves slivers behind at its clip edge for 0.2 s or more ("pixels are+// left for about half a second longer than they should... check each and every frame")+// fasttext type moving faster than half the speed ceiling: a whip that blurs ("violent exits")+// faces a moving shape drawn over a real person's face ("whack-a-mole", "swallowing the head")+// translucent a brand colour filled between 5 % and 95 % alpha ("olive mud"); needs meta.motion.brandColors+// Exceptions live in meta.motion.allow. Exit 0 pass, 1 fail, 2 usage. Detectors: motionscan-core.mjs.+import { resolve } from "node:path";+import { buildPage } from "./build-page.mjs";+import { detect } from "./detect.mjs";+import * as playwright from "./adapters/playwright.mjs";+import { requireFilm } from "./names.mjs";+import { isMain } from "./is-main.mjs";+import { checkedFrames } from "./framerules.mjs";+import { scanExits, scanFaceCover, scanFastText, scanTranslucent, textLines } from "./motionscan-core.mjs";++export const LAYER_CHECKS = ["exits", "fasttext", "faces", "translucent"];+const pad = (b, k = 0.45) => { const h = b.y1 - b.y0, w = b.x1 - b.x0; return { x0: b.x0 - w * 0.02, y0: b.y0 - h * k, x1: b.x1 + w * 0.02, y1: b.y1 + h * k }; };++export const layerScan = async (film, { checks = LAYER_CHECKS, every = 1, from = 0, to } = {}) => {+ const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });+ const s = await playwright.open(detect(), page.out, { workers: 1 }), meta = await s.info(), motion = meta.motion ?? {}, allow = motion.allow ?? {};+ // a bad --every/--from/--to is refused (framerules.mjs checkedFrames): --every 0 looped forever, and zero frames checked passed+ let frames; try { frames = checkedFrames({ every, from, to }, meta.durationFrames); } catch (e) { await s.close(); throw new Error(`layerscan: ${e.message}`); }+ const N = Math.min(to ?? meta.durationFrames, meta.durationFrames);+ const layers = []; for (let i = 0; i < frames.length; i += 40) layers.push(...(await s.layers(frames.slice(i, i + 40), motion.brandColors ?? [])));+ const out = {};+ try {+ if (checks.includes("exits")) {+ // the ink each line shows over the last 2 s of its life, measured frame by frame (every frame, whatever --every says)+ const lines = textLines(layers), tailF = Math.round(2 * meta.fps), want = new Map();+ for (const [label, pts] of Object.entries(lines)) { const last = pts[pts.length - 1].frame, first = pts[0].frame; for (let f = Math.max(first, last - tailF); f <= Math.min(N - 1, last + every); f++) { const box = pts.filter((p) => p.frame <= f).pop() ?? pts[0]; (want.get(f) ?? want.set(f, []).get(f)).push({ label, box: pad(box) }); } }+ const series = {};+ // the box at each frame is the line's own box that frame when it was drawn, else its last one+ const detail = new Map(); for (const l of layers) detail.set(l.frame, l);+ for (const [f, items] of [...want].sort((a, b) => a[0] - b[0])) {+ const here = textLines(detail.has(f) ? [detail.get(f)] : (await s.layers([f], [])));+ const boxes = items.map((it) => (here[it.label] ? pad(here[it.label][0]) : it.box));+ const ink = await s.ink(f, boxes);+ items.forEach((it, i) => (series[it.label] ??= []).push({ frame: f, ink: here[it.label] ? ink[i] : 0 }));+ }+ const r = scanExits(series, { fps: meta.fps }); out.exits = { status: Object.keys(lines).length ? (r.fail ? "FAIL" : "PASS") : "NONE", lines: Object.keys(lines).length, ...r };+ if (!Object.keys(lines).length) out.exits.reason = "the film draws no lines of text: looked, none there";+ }+ if (checks.includes("fasttext")) { const r = scanFastText(layers, { W: meta.W, fps: meta.fps, scale: 1, step: every }); out.fasttext = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("faces")) { const photos = layers.some((l) => l.recs.some((r) => r.kind === "photo")); const r = scanFaceCover(layers); out.faces = photos ? { status: r.fail ? "FAIL" : "PASS", ...r } : { status: "NONE", reason: "the film draws no photos (film assets): looked, none there", ...r }; }+ if (checks.includes("translucent")) { const r = scanTranslucent(layers, { allow: (allow.translucent ?? []).map(([a, b]) => [a, b]) }); out.translucent = layers[0]?.unread?.length ? { status: "FAIL", reason: `brand colour(s) ${layers[0].unread.join(", ")} in meta.motion.brandColors cannot be read: give #rrggbb, rgb() or hsl()`, ...r, findings: [], fail: true } : motion.brandColors?.length ? { status: r.fail ? "FAIL" : "PASS", ...r } : { status: "N/A", reason: "the film declares no brand colours (meta.motion.brandColors)", ...r }; }+ } finally { await s.close(); }+ return { film, meta, frames: frames.length, checks: out, fail: Object.values(out).some((c) => c.status === "FAIL") };+};++export const printLayers = (r) => {+ const c = r.checks, s = (f) => (f / r.meta.fps).toFixed(2), list = (fs) => `${fs.slice(0, 8).join(", ")}${fs.length > 8 ? " ..." : ""}`;+ console.log(`LAYERSCAN ${r.film} ${r.meta.W}x${r.meta.H}, ${r.frames} frames`);+ if (c.exits) { for (const e of c.exits.findings) console.log(` FAIL text "${e.label.slice(0, 48)}" leaves slivers for ${e.frames} frames (${e.seconds} s, frames ${e.from}-${e.to - 1}) as it exits: sink it with setType's out (ease-in, 1.3x its size) so it clears the clip`); console.log(` EXITS: ${c.exits.status}${c.exits.status === "NONE" ? ` ${c.exits.reason}` : ` ${c.exits.lines} line(s), residue limit ${c.exits.limit} frames`}`); }+ if (c.fasttext) { for (const t of c.fasttext.findings) console.log(` FAIL text "${t.label.slice(0, 48)}" moves at up to ${t.top} px a frame, frames ${t.from}-${t.to - 1} (${s(t.from)} s): type leaves over 0.5-0.7 s; the fast whip is for the camera`); console.log(` FAST-TEXT: ${c.fasttext.status} limit ${c.fasttext.cap} px a frame (half the speed ceiling)`); }+ if (c.faces) { for (const f of c.faces.findings) console.log(` FAIL "${f.shape}" moves across the face of "${f.photo}" on ${f.frames.length} frame(s): ${list(f.frames)}: a person enters and leaves with their stage; draw the shape behind them or move it with them`); console.log(` FACES: ${c.faces.status}${c.faces.status === "NONE" ? ` ${c.faces.reason}` : ""}`); }+ if (c.translucent) { if (c.translucent.status === "FAIL" && c.translucent.reason) console.log(` FAIL ${c.translucent.reason}`); for (const t of c.translucent.findings) console.log(` FAIL brand colour ${t.colour} filled at ${t.alphas.join(", ")} % alpha on ${t.frames.length} frame(s): ${list(t.frames)}: cut it in or out whole, or declare the fade in meta.motion.allow.translucent`); console.log(` TRANSLUCENT: ${c.translucent.status}${c.translucent.status === "N/A" || c.translucent.reason ? ` ${c.translucent.reason}` : ""}`); }+ console.log(`LAYERSCAN: ${r.fail ? "FAIL" : "PASS"}`);+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a === "--json") opt.json = true; else if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const usage = "node tools/layerscan.mjs <film> [--checks exits,fasttext,faces,translucent] [--every 1] [--from F] [--to T] [--json]";+ const film = requireFilm(pos[0], "layerscan", usage), checks = opt.checks ? String(opt.checks).split(",") : LAYER_CHECKS, bad = checks.filter((c) => !LAYER_CHECKS.includes(c));+ if (bad.length) { console.error(`layerscan: unknown check ${bad.join(", ")}; the checks are ${LAYER_CHECKS.join(", ")}\nusage: ${usage}`); process.exit(2); }+ let r; try { r = await layerScan(film, { checks, every: Number(opt.every ?? 1), from: Number(opt.from ?? 0), to: opt.to === undefined ? undefined : Number(opt.to) }); }+ catch (e) { if (!/^layerscan: --/.test(e.message)) throw e; console.error(`${e.message}\nusage: ${usage}`); process.exit(2); }+ if (opt.json) console.log(JSON.stringify(r, null, 1)); else printLayers(r);+ process.exit(r.fail ? 1 : 0);+}diff --git a/skills/anidoodle/engine/tools/lock.mjs b/skills/anidoodle/engine/tools/lock.mjsnew file mode 100644index 0000000..25c317a--- /dev/null+++ b/skills/anidoodle/engine/tools/lock.mjs@@ -0,0 +1,63 @@+// node tools/lock.mjs <film> --shot <id> print the approval sha of a shot (every frame hashed)+// node tools/lock.mjs <film> [--unlock a,b] check every approved shot (meta.motion.approved) still draws the same+// APPROVED SHOTS STAY APPROVED. On a brand launch film the logo shot the director approved ("the elements flying+// together, rotating. It was actually good") was replaced by a "better" idea while iterating, and had to+// be rebuilt exactly. Once a shot is approved its sha goes in the film:+// meta.motion.approved: [["logo", "<sha>", "director 2026-10-27 16:50"]]+// and any change to its frames fails here until it is unlocked on purpose (--unlock logo), which is the+// moment to ask the person again. The sha is over every frame's pixel hash, drawn sharp in the page.+// Exit 0 pass, 1 a locked shot changed (or is missing), 2 usage.+import { createHash } from "node:crypto";+import { resolve } from "node:path";+import { buildPage } from "./build-page.mjs";+import { detect } from "./detect.mjs";+import * as playwright from "./adapters/playwright.mjs";+import { requireFilm } from "./names.mjs";+import { isMain } from "./is-main.mjs";++/** The approval sha of each shot asked for: sha256 over the pixel hash of every frame, in order. */+export const shotShas = async (film, ids) => {+ const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });+ const s = await playwright.open(detect(), page.out, { workers: 1, bakeCache: false }), meta = await s.info(), out = {};+ try {+ for (const id of ids) {+ const shot = meta.shots.find((x) => x.id === id); if (!shot) { out[id] = { missing: true, shots: meta.shots.map((x) => x.id) }; continue; }+ const h = createHash("sha256"); for (let f = shot.start; f < shot.end; f++) h.update(`${f - shot.start}:${await s.hash(f)}\n`);+ out[id] = { sha: h.digest("hex").slice(0, 16), frames: shot.end - shot.start };+ }+ } finally { await s.close(); }+ return { meta, shas: out };+};++/** Check every approved shot. Returns { checked: [{ shot, status: "same" | "changed" | "missing" | "unlocked", ... }], fail }. */+// `approved` overrides the film's own list (the self-test checks a live sha and a wrong one without editing a film)+export const checkLocks = async (film, { unlock = [], approved: given } = {}) => {+ let approved = given;+ if (!approved) { const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film }); const s0 = await playwright.open(detect(), page.out, { workers: 1, bakeCache: false }); approved = (await s0.info()).motion?.approved ?? []; await s0.close(); }+ if (!approved.length) return { checked: [], fail: false, none: true };+ const { shas } = await shotShas(film, approved.map(([id]) => id)), checked = [];+ for (const [shot, sha, note] of approved) {+ const got = shas[shot];+ if (unlock.includes(shot)) checked.push({ shot, status: "unlocked", note, sha: got.sha });+ else if (got.missing) checked.push({ shot, status: "missing", note, shots: got.shots });+ else checked.push({ shot, status: got.sha === sha ? "same" : "changed", note, sha: got.sha, want: sha });+ }+ return { checked, fail: checked.some((c) => c.status === "changed" || c.status === "missing") };+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const usage = "node tools/lock.mjs <film> --shot <id> | node tools/lock.mjs <film> [--unlock a,b]";+ const film = requireFilm(pos[0], "lock", usage);+ if (opt.shot) {+ const { shas } = await shotShas(film, String(opt.shot).split(","));+ for (const [id, r] of Object.entries(shas)) { if (r.missing) { console.error(`lock: no shot "${id}"; this film's shots are ${r.shots.join(", ")}`); process.exit(2); } console.log(`${id}: ${r.sha} (${r.frames} frames)\n meta.motion.approved: [["${id}", "${r.sha}", "<who approved it, when>"]]`); }+ process.exit(0);+ }+ const r = await checkLocks(film, { unlock: opt.unlock ? String(opt.unlock).split(",") : [] });+ if (r.none) { console.log("LOCKS: N/A no approved shots (meta.motion.approved); lock one with --shot <id> once the person approves it"); process.exit(0); }+ for (const c of r.checked) console.log(` ${c.status === "same" ? "PASS" : c.status === "unlocked" ? "NOTE" : "FAIL"} ${c.shot} (${c.note}): ${c.status === "same" ? "unchanged" : c.status === "unlocked" ? `unlocked for this run, now ${c.sha}: show the person before re-approving` : c.status === "missing" ? `no such shot any more (shots: ${c.shots.join(", ")})` : `CHANGED (${c.sha}, approved ${c.want}): restore it, or ask the person and run with --unlock ${c.shot}`}`);+ console.log(`LOCKS: ${r.fail ? "FAIL" : "PASS"}`);+ process.exit(r.fail ? 1 : 0);+}diff --git a/skills/anidoodle/engine/tools/motion-e2e.mjs b/skills/anidoodle/engine/tools/motion-e2e.mjsnew file mode 100644index 0000000..edf16df--- /dev/null+++ b/skills/anidoodle/engine/tools/motion-e2e.mjs@@ -0,0 +1,71 @@+#!/usr/bin/env node+// END-TO-END TESTS for the motion lane's tools on real rendered films (the unit tests in+// test/motionscan.test.ts and test/motionKit.test.ts feed the detectors synthetic data; this runs the+// whole path: page, render, decode). Two fixture films (src/canvas-core/fixtureMotion.ts):+// fixtureDeck RED: must fail motionscan (slide cuts, carousel, fade-in) and layerscan (lingering+// exits, fast text, a frieze over a face, translucent brand yellow)+// fixtureWorld GREEN: the same material as one world under one camera: must pass both+// plus the render blur mask (type stays sharp under --blur, blurs under --blur-all) and lock.mjs (a live+// sha passes, a wrong one fails, --unlock lets it through), and worldfilm.mjs (a scaffolded one-world film+// passes both scans; its two files are removed afterwards). Renders only under .tmp/motion-e2e/.+// node tools/motion-e2e.mjs+import { strict as assert } from "node:assert";+import { execFileSync } from "node:child_process";+import { mkdirSync, rmSync } from "node:fs";+import { resolve } from "node:path";+import { buildPage } from "./build-page.mjs";+import { detect } from "./detect.mjs";+import * as playwright from "./adapters/playwright.mjs";+import { motionScan } from "./motionscan.mjs";+import { layerScan } from "./layerscan.mjs";+import { checkLocks, shotShas } from "./lock.mjs";++const dir = resolve(".tmp/motion-e2e"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true });+let pass = 0; const ok = (label) => console.log(`PASS ${++pass} ${label}`);+const render = (film, ...extra) => { const out = `${dir}/${film}.mp4`; execFileSync(process.execPath, ["tools/render.mjs", film, "--out", out, ...extra], { stdio: "pipe" }); return out; };++const deck = await motionScan(render("fixtureDeck"), { temperament: "lively" }), world = await motionScan(render("fixtureWorld"), { temperament: "lively" });+assert.equal(deck.checks.slidecut.status, "FAIL"); assert.equal(deck.checks.repeat.status, "FAIL"); assert.equal(deck.checks.dissolve.status, "FAIL");+ok(`motionscan RED fixtureDeck: ${deck.checks.slidecut.events.length} slide cuts, ${deck.checks.repeat.runs[0].length} beats in one layout, a fade-in`);+assert.equal(world.fail, false, JSON.stringify(Object.fromEntries(Object.entries(world.checks).map(([k, v]) => [k, v.status]))));+ok("motionscan GREEN fixtureWorld: no slide cut, no carousel, no dissolve, inside the lively temperament");++const ld = await layerScan("fixtureDeck"), lw = await layerScan("fixtureWorld");+for (const c of ["exits", "fasttext", "faces", "translucent"]) assert.equal(ld.checks[c].status, "FAIL", c);+ok(`layerscan RED fixtureDeck: ${ld.checks.exits.findings.length} lingering exits, ${ld.checks.fasttext.findings.length} fast lines, a face covered, translucent brand yellow`);+for (const c of ["exits", "fasttext", "faces", "translucent"]) assert.equal(lw.checks[c].status, "PASS", c);+ok("layerscan GREEN fixtureWorld: setType exits clear, type moves slowly, the frieze is behind the speaker, yellow is opaque");++// the blur mask, on the frame where slide 2 whips its title off+{+ const page = await buildPage({ entry: "src/hosts/page-fixtureDeck.ts", out: resolve("dist/fixtureDeck.html"), title: "fixtureDeck" });+ const s = await playwright.open(detect(), page.out, { workers: 1, bakeCache: false }), n = 116;+ const [layer] = await s.layers([n], []), t = layer.recs.find((r) => r.kind === "text"), sharp = await s.frame(n), masked = await s.blur(n, { samples: 8, shutter: 360, sharp: true }), all = await s.blur(n, { samples: 8, shutter: 360 , sharp: false });+ await s.close();+ const grey = (png) => execFileSync("ffmpeg", ["-v", "error", "-i", "-", "-vf", `crop=${Math.round(t.x1 - t.x0) - 4}:${Math.round(t.y1 - t.y0)}:${Math.round(t.x0) + 2}:${Math.round(t.y0)},format=gray`, "-f", "rawvideo", "-"], { input: png });+ const d = (a, b) => a.reduce((s, v, i) => s + Math.abs(v - b[i]), 0) / a.length, A = grey(sharp.png);+ assert.ok(masked.sharpPx > 0 && d(A, grey(masked.png)) < 0.5 && d(A, grey(all.png)) > 5, `masked ${d(A, grey(masked.png))}, all ${d(A, grey(all.png))}`);+ ok(`render --blur keeps the whipping title sharp (${masked.sharpPx} px kept); --blur-all smears it`);+}++// lock.mjs+{+ const { shas } = await shotShas("fixtureWorld", ["world"]), live = shas.world.sha;+ assert.equal((await checkLocks("fixtureWorld", { approved: [["world", live, "e2e"]] })).fail, false); ok(`lock: the approved shot unchanged passes (${live})`);+ const bad = await checkLocks("fixtureWorld", { approved: [["world", "0000000000000000", "e2e"]] }); assert.equal(bad.fail, true); assert.equal(bad.checked[0].status, "changed"); ok("lock RED: a shot whose frames changed since approval fails");+ assert.equal((await checkLocks("fixtureWorld", { approved: [["world", "0000000000000000", "e2e"]], unlock: ["world"] })).fail, false); ok("lock: --unlock lets a deliberate change through (and says so)");+ assert.equal((await checkLocks("fixtureWorld", { approved: [["gone", "0", "e2e"]] })).checked[0].status, "missing"); ok("lock RED: an approved shot that no longer exists fails");+}+// worldfilm.mjs: a film started as one world passes both scans out of the box+{+ const name = "motionE2eWorld", mod = `src/canvas-core/${name}.ts`, host = `src/hosts/page-${name}.ts`;+ try {+ execFileSync(process.execPath, ["tools/worldfilm.mjs", name, "--beats", "3"], { stdio: "pipe" });+ const r = await motionScan(render(name, "--scale", "0.5")), l = await layerScan(name, { every: 2 });+ assert.equal(r.fail, false, JSON.stringify(Object.fromEntries(Object.entries(r.checks).map(([k, v]) => [k, v.status]))));+ assert.equal(l.fail, false, JSON.stringify(Object.fromEntries(Object.entries(l.checks).map(([k, v]) => [k, v.status]))));+ ok(`worldfilm: a new one-world film passes motionscan (temperament ${r.checks.temperament.status}) and layerscan as scaffolded`);+ } finally { for (const f of [mod, host, `dist/${name}.html`]) rmSync(f, { force: true }); }+}+rmSync(dir, { recursive: true, force: true });+console.log(`\nMOTION E2E: PASS ${pass}`);diff --git a/skills/anidoodle/engine/tools/motionscan-core.mjs b/skills/anidoodle/engine/tools/motionscan-core.mjsnew file mode 100644index 0000000..29b4c4f--- /dev/null+++ b/skills/anidoodle/engine/tools/motionscan-core.mjs@@ -0,0 +1,318 @@+// MOTION SCAN DETECTORS. Pure: frames (or layer records) in, findings out, no I/O, so the unit tests+// feed them synthetic frames and the CLIs (motionscan.mjs, layerscan.mjs) feed them a real film.+// Each detector answers one note the director or a critic gave a brand launch film:+//+// scanSlideCuts "a LITERAL SLIDE DECK": most of the frame replaced within 6 frames with no camera move+// scanRepeats "moves like a carousel": three beats in a row settle into the same layout+// scanDissolves "olive mud" cross-dissolves: a region blends linearly from one picture to another+// speedProfile how fast the picture moves, frame by frame, for the brand's motion temperament+// scanTemperament stretches faster than the temperament allows ("violent")+// scanExits text that leaves pixels behind ("pixels left for about half a second")+// scanFastText type moving faster than half the speed ceiling (reads as a blurred whip)+// scanFaceCover a moving shape drawn over a real person's face ("whack-a-mole", "swallowing the head")+// scanTranslucent brand colours drawn half-transparent+//+// Frames are greyscale Uint8Arrays of width*height (motion.mjs greyFrames decodes them small).++const median = (xs) => { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); return s[s.length >> 1]; };++// ---------------------------------------------------------------- motion between two frames+/**+ * Block matching between two small grey frames. Returns the 98th-percentile displacement of the+ * coherent textured blocks (analysis px per frame pair), and `matched`: the share of textured blocks+ * that found their content somewhere nearby. A camera move: high matched, real speed. A cut or a slide+ * reset: low matched. A dissolve or a still: matched at speed 0.+ */+export const motionBetween = (A, Z, W, H, { B = 8, R = 8, subpixel = false } = {}) => {+ const vec = new Map(), frac = new Map(), cols = Math.floor((W - 2 * R - B) / B) + 1; let textured = 0, matched = 0;+ for (let by = R, row = 0; by + B + R <= H; by += B, row++) for (let bx = R, col = 0; bx + B + R <= W; bx += B, col++) {+ let mean = 0, v = 0; for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) mean += A[(by + y) * W + bx + x]; mean /= B * B;+ for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) v += (A[(by + y) * W + bx + x] - mean) ** 2;+ if (v / (B * B) < 12) continue; // flat: no motion can be read off it+ textured++;+ let best = Infinity, mx = 0, my = 0, md = Infinity; const cost = new Float64Array((2 * R + 1) ** 2);+ for (let dy = -R; dy <= R; dy++) for (let dx = -R; dx <= R; dx++) { let sad = 0; for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) sad += Math.abs(A[(by + y) * W + bx + x] - Z[(by + y + dy) * W + bx + x + dx]); cost[(dy + R) * (2 * R + 1) + dx + R] = sad; if (sad < best) best = sad; }+ if (best / (B * B) > 6) continue; // its content went nowhere nearby: changed, not moved+ matched++;+ for (let dy = -R; dy <= R; dy++) for (let dx = -R; dx <= R; dx++) { const c = cost[(dy + R) * (2 * R + 1) + dx + R], d = Math.hypot(dx, dy); if (c <= best * 1.1 + B * B * 0.5 && d < md) { md = d; mx = dx; my = dy; } }+ // a match on content that was already there, unchanged, is not a move: the block was covered (a reveal+ // edge, a bloom's rim) and its look-alike beside it stood still. Text beside text matched a few letters+ // over and read as the fastest thing in the frame (a launch film's end bloom, 51 px a frame).+ if (mx || my) { let still = 0; for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) { const i = (by + y + my) * W + bx + x + mx; still += Math.abs(A[i] - Z[i]); } if (still / (B * B) <= 6) continue; }+ vec.set(row * cols + col, [mx, my]);+ // asked for (`subpixel`, the speed profile), the move between whole pixels: a parabola through the block's+ // cost at its best whole shift and its two neighbours on each axis, about the cheapest shift found. One+ // analysis pixel is 8 to 15 px of the film, and word lines carried at 1.4 pixels a frame read 1 or 2 by+ // turns (and 2 failed a calm brand on a phone frame). Neighbour agreement still uses the whole shifts+ if (subpixel) {+ // (about the shift the block was given, the nearest of the near-best: on a repeating texture the cheapest+ // shift can be a period away, and a parabola there would measure the pattern, not the move)+ const bx0 = mx, by0 = my, at = (dx, dy) => cost[(dy + R) * (2 * R + 1) + dx + R], c0 = at(bx0, by0);+ const sub = (ea, e0, eb) => { const d = ea - 2 * e0 + eb; return d > 1e-9 ? Math.max(-0.5, Math.min(0.5, (ea - eb) / (2 * d))) : 0; };+ const fx = bx0 > -R && bx0 < R ? sub(at(bx0 - 1, by0), c0, at(bx0 + 1, by0)) : 0, fy = by0 > -R && by0 < R ? sub(at(bx0, by0 - 1), c0, at(bx0, by0 + 1)) : 0;+ frac.set(row * cols + col, Math.hypot(bx0 + fx, by0 + fy));+ }+ }+ const disp = [];+ for (const [key, [x, y]] of vec) { const r = Math.floor(key / cols), c = key % cols; let agree = 0; for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) { if (!dr && !dc) continue; const nb = vec.get((r + dr) * cols + c + dc); if (nb && c + dc >= 0 && c + dc < cols && Math.hypot(nb[0] - x, nb[1] - y) <= 1.5) agree++; } if (agree >= 2) disp.push(subpixel ? frac.get(key) : Math.hypot(x, y)); }+ disp.sort((a, b) => a - b);+ return { speed: disp.length ? disp[Math.min(disp.length - 1, Math.floor(disp.length * 0.98))] : 0, matched: textured ? matched / textured : 1, textured };+};++// ---------------------------------------------------------------- the camera's own move+const down = (f, W, H, k) => { const w = Math.floor(W / k), h = Math.floor(H / k), o = new Float32Array(w * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let s = 0; for (let yy = 0; yy < k; yy++) for (let xx = 0; xx < k; xx++) s += f[(y * k + yy) * W + x * k + xx]; o[y * w + x] = s / (k * k); } return { o, w, h }; };+// mean absolute difference of A against Z seen through a zoom s about the centre and a shift (dx, dy), over the overlap+const warpErr = (A, Z, w, h, s, dx, dy) => { let e = 0, n = 0; const cx = w / 2, cy = h / 2; for (let y = 1; y < h - 1; y += 1) for (let x = 1; x < w - 1; x += 1) { const u = Math.round(cx + (x - cx) * s + dx), v = Math.round(cy + (y - cy) * s + dy); if (u < 0 || v < 0 || u >= w || v >= h) continue; e += Math.abs(A[y * w + x] - Z[v * w + u]); n++; } return n > (w * h) / 4 ? e / n : Infinity; };+/**+ * The camera's move between two frames as ONE zoom and shift for the whole picture (coarse to fine, up+ * to a third of the frame per step). `explained`: how much of the difference that move accounts for+ * (1 - err / err at rest). A pan, a push-in or a pull-out explains most of it; a cut or a swapped slide+ * explains none, whatever the texture: flat cards on a flat ground still move as one.+ */+export const globalMotion = (A, Z, W, H, { between = false, subpixel = false } = {}) => {+ const k = Math.max(1, Math.floor(W / 48)), a = down(A, W, H, k), z = down(Z, W, H, k), R = Math.ceil(a.w / 6);+ const e0 = warpErr(a.o, z.o, a.w, a.h, 1, 0, 0);+ let best = { e: e0, s: 1, dx: 0, dy: 0 };+ for (const sc of [1, 0.94, 0.97, 1.03, 1.06]) for (let dy = -R; dy <= R; dy++) for (let dx = -R; dx <= R; dx++) { const e = warpErr(a.o, z.o, a.w, a.h, sc, dx, dy); if (e < best.e - 1e-9) best = { e, s: sc, dx, dy }; }+ // refine the shift at full size within one coarse cell: a 3 px pan must read as 3, not as a whole cell+ const f0 = Float32Array.from(A), f1 = Float32Array.from(Z); let fine = { e: warpErr(f0, f1, W, H, best.s, best.dx * k, best.dy * k), dx: best.dx * k, dy: best.dy * k };+ for (let dy = -k; dy <= k; dy++) for (let dx = -k; dx <= k; dx++) { const e = warpErr(f0, f1, W, H, best.s, best.dx * k + dx, best.dy * k + dy); if (e < fine.e - 1e-9) fine = { e, dx: best.dx * k + dx, dy: best.dy * k + dy }; }+ // and, asked for (`between`), the zooms between the coarse steps, at full size and sub-pixel shifts: a camera+ // leaning in at about 1 % a frame matched neither 1 nor 1.03, so its push-in explained under half the+ // change and read as a slide cut (a clean chat's lean onto its answer card, thin type on a sparse frame,+ // where a shift off by half a pixel misses every stroke). Slide cuts ask for it on the few frames they judge.+ let sc = best.s;+ if (between) {+ // (both frames softened by a 3 x 3 box first: a stroke one pixel wide resampled half a pixel over is a+ // different set of pixels, and the fit would judge the sampling, not the move)+ const soft = (F) => { const o = new Float32Array(W * H); for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) { let t = 0; for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) t += F[(y + j) * W + x + i]; o[y * W + x] = t / 9; } return o; };+ const s0 = soft(f0), s1 = soft(f1);+ const lin = (F, x, y) => { const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0, i = y0 * W + x0; return (1 - fy) * ((1 - fx) * F[i] + fx * F[i + 1]) + fy * ((1 - fx) * F[i + W] + fx * F[i + W + 1]); };+ const err = (s2, dx, dy) => { let e = 0, n = 0; const cx = W / 2, cy = H / 2; for (let y = 3; y < H - 3; y++) for (let x = 3; x < W - 3; x++) { const u = cx + (x - cx) * s2 + dx, v = cy + (y - cy) * s2 + dy; if (u < 2 || v < 2 || u >= W - 3 || v >= H - 3) continue; e += Math.abs(s0[y * W + x] - lin(s1, u, v)); n++; } return n > (W * H) / 4 ? e / n : Infinity; };+ const rest2 = err(1, 0, 0);+ let b2 = { e: err(best.s, fine.dx, fine.dy), s: best.s, dx: fine.dx, dy: fine.dy };+ for (let ds = -0.02; ds <= 0.0201; ds += 0.0025) for (let dy = -1.5; dy <= 1.5; dy += 0.25) for (let dx = -1.5; dx <= 1.5; dx += 0.25) { const e = err(best.s + ds, fine.dx + dx, fine.dy + dy); if (e < b2.e - 1e-9) b2 = { e, s: best.s + ds, dx: fine.dx + dx, dy: fine.dy + dy }; }+ // judged on the softened frames, so both errors are: the share of the change the move explains+ // (its speed is the fastest point of the frame, a corner, under the zoom and the shift together: a lean that+ // pans as it zooms moves its corners by both, and neither alone says how far the picture moved)+ const corner = Math.max(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot((b2.s - 1) * (x - W / 2) + b2.dx, (b2.s - 1) * (y - H / 2) + b2.dy)));+ if (rest2 > 0 && 1 - b2.e / rest2 > 1 - fine.e / warpErr(f0, f1, W, H, 1, 0, 0)) return { speed: corner, explained: Math.max(0, 1 - b2.e / rest2), dx: b2.dx, dy: b2.dy, scale: +b2.s.toFixed(4), err: b2.e, rest: warpErr(f0, f1, W, H, 1, 0, 0) };+ }+ // the shift between whole pixels: a parabola through the error at the best whole shift and its two+ // neighbours, on each axis. One analysis pixel is 8 to 15 px of the film, and a travel at 1.46 pixels a frame+ // read as 1 or 2 by turns: its 2s failed a calm brand's limit on a phone frame, which the move never reached.+ // The speed profile asks for it (`subpixel`); slide cuts keep whole pixels, their "it moved" floor is one+ const sub = (ea, e0, eb) => { const d = ea - 2 * e0 + eb; return d > 1e-9 ? Math.max(-0.5, Math.min(0.5, (ea - eb) / (2 * d))) : 0; };+ const ox = subpixel ? sub(warpErr(f0, f1, W, H, sc, fine.dx - 1, fine.dy), fine.e, warpErr(f0, f1, W, H, sc, fine.dx + 1, fine.dy)) : 0;+ const oy = subpixel ? sub(warpErr(f0, f1, W, H, sc, fine.dx, fine.dy - 1), fine.e, warpErr(f0, f1, W, H, sc, fine.dx, fine.dy + 1)) : 0;+ const rest = warpErr(f0, f1, W, H, 1, 0, 0), shift = Math.hypot(fine.dx + ox, fine.dy + oy), zoom = Math.abs(sc - 1) * W / 2;+ return { speed: Math.max(shift, zoom), explained: rest > 0.05 ? Math.max(0, 1 - fine.e / rest) : 0, dx: fine.dx, dy: fine.dy, scale: sc, err: fine.e, rest };+};++const changedShare = (a, b, thresh) => { let n = 0; for (let i = 0; i < a.length; i++) if (Math.abs(a[i] - b[i]) > thresh) n++; return n / a.length; };+// the ground: the most common grey level (a dark or a paper background), read off a 32-level histogram+const groundOf = (f) => { const h = new Uint32Array(32); for (let i = 0; i < f.length; i += 3) h[f[i] >> 3]++; let b = 0; for (let k = 1; k < 32; k++) if (h[k] > h[b]) b = k; return b * 8 + 4; };+/**+ * Of the pixels that hold CONTENT in either frame (not the plain ground), the share that changed. A deck+ * on a dark ground keeps most pixels dark from slide to slide; what it replaces is the content.+ */+export const contentReplaced = (a, b, thresh = 16) => {+ const ga = groundOf(a), gb = groundOf(b); let content = 0, changed = 0;+ for (let i = 0; i < a.length; i++) { if (Math.abs(a[i] - ga) <= 12 && Math.abs(b[i] - gb) <= 12) continue; content++; if (Math.abs(a[i] - b[i]) > thresh) changed++; }+ return content < a.length * 0.01 ? 0 : changed / content;+};++// ---------------------------------------------------------------- slide cuts+/**+ * A slide cut: more than `replaced` of the frame's CONTENT pixels (contentReplaced: the plain ground+ * does not count) change within `win` frames while the camera is not travelling (the content did not+ * move there, it was swapped). Fades count: a dissolve between two layouts is the same deck transition, slower. Fails when any 60 s stretch holds more than+ * `perMinute` (2) of them. `allow`: [from, to] frame ranges that are deliberate (a hard cut on a beat).+ */+export const scanSlideCuts = (frames, { width: W, height: H, fps, win = 6, replaced = 0.6, thresh = 16, perMinute = 2, allow = [] } = {}) => {+ const n = frames.length, rep = new Float64Array(n);+ for (let f = win; f < n; f++) rep[f] = contentReplaced(frames[f - win], frames[f], thresh);+ const events = [];+ for (let f = win; f < n; f++) {+ if (rep[f] < replaced) continue;+ let peak = f; while (f + 1 < n && rep[f + 1] >= replaced) { f++; if (rep[f] > rep[peak]) peak = f; }+ const a = Math.max(1, peak - win), pairs = [];+ for (let g = a; g <= peak; g++) pairs.push(globalMotion(frames[g - 1], frames[g], W, H, { between: true }));+ // the camera carried it: on the pairs where the picture changed, one zoom and shift explains most of the change+ // (a change spread so thin that no single step shows it is a slow drift or a fade: dissolve's business, not a cut)+ const changing = pairs.filter((p) => p.rest > 0.05), travel = !changing.length || (median(changing.map((p) => p.explained)) >= 0.5 && median(changing.map((p) => p.speed)) >= 1);+ if (travel || allow.some(([x, y]) => peak >= x && peak < y)) continue;+ events.push({ frame: peak, from: a, replaced: +rep[peak].toFixed(3), explained: +median(changing.map((p) => p.explained)).toFixed(2) });+ }+ const span = Math.round(60 * fps), dense = [];+ for (let i = 0; i < events.length; i++) { const inWin = events.filter((e) => e.frame >= events[i].frame && e.frame < events[i].frame + span); if (inWin.length > perMinute) { dense.push(inWin.map((e) => e.frame)); } }+ return { events, fail: dense.length > 0, worst: dense.sort((a, b) => b.length - a.length)[0] ?? [], perMinute };+};++// ---------------------------------------------------------------- repeated layouts (the carousel)+const pool = (f, W, H, k) => { const w = Math.floor(W / k), h = Math.floor(H / k), o = new Float32Array(w * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let s = 0; for (let yy = 0; yy < k; yy++) for (let xx = 0; xx < k; xx++) s += f[(y * k + yy) * W + x * k + xx]; o[y * w + x] = s / (k * k); } return { o, w, h }; };+/** Where a settled frame has content: a cols x rows grid of cells with edges in them (text, photos, shapes). */+export const layoutOf = (f, W, H, { cols = 32, rows = 18, edge = 10 } = {}) => {+ const occ = new Uint8Array(cols * rows), e = new Float64Array(cols * rows), cnt = new Uint32Array(cols * rows);+ for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) { const g = Math.abs(f[y * W + x + 1] - f[y * W + x - 1]) + Math.abs(f[(y + 1) * W + x] - f[(y - 1) * W + x]); const c = Math.min(rows - 1, Math.floor((y * rows) / H)) * cols + Math.min(cols - 1, Math.floor((x * cols) / W)); e[c] += g; cnt[c]++; }+ for (let i = 0; i < occ.length; i++) occ[i] = cnt[i] && e[i] / cnt[i] > edge ? 1 : 0;+ return occ;+};+export const layoutIoU = (a, b) => { let i = 0, u = 0; for (let k = 0; k < a.length; k++) { if (a[k] && b[k]) i++; if (a[k] || b[k]) u++; } return u ? i / u : 1; };+/**+ * Beats that settle into the same layout with new content, three or more in a row: the template ran+ * again. A beat is a settled stretch (under `still` of the frame changing per frame, judged on a coarse+ * copy so a breathing camera still counts as settled) at least `hold` seconds long.+ */+export const scanRepeats = (frames, { width: W, height: H, fps, hold = 0.4, still = 0.01, same = 0.75, newContent = 0.05, run = 3 } = {}) => {+ const k = Math.max(1, Math.floor(W / 64)), small = frames.map((f) => pool(f, W, H, k)), sw = small[0]?.w ?? 0, sh = small[0]?.h ?? 0, minLen = Math.max(2, Math.round(hold * fps));+ const holds = []; let start = 0;+ const settledAt = (f) => { let n = 0; const a = small[f - 1].o, b = small[f].o; for (let i = 0; i < a.length; i++) if (Math.abs(a[i] - b[i]) > 6) n++; return n / a.length < still; };+ for (let f = 1; f <= frames.length; f++) { if (f < frames.length && settledAt(f)) continue; if (f - start >= minLen) holds.push([start, f]); start = f; }+ const beats = holds.map(([a, b]) => { const m = (a + b) >> 1; return { from: a, to: b, mid: m, layout: layoutOf(frames[m], W, H) }; });+ const links = []; // beat i and i+1 share a layout and show new content+ for (let i = 1; i < beats.length; i++) links.push(layoutIoU(beats[i - 1].layout, beats[i].layout) >= same && contentReplaced(frames[beats[i - 1].mid], frames[beats[i].mid]) >= newContent);+ const runs = []; let i = 0;+ while (i < links.length) { if (!links[i]) { i++; continue; } let j = i; while (j < links.length && links[j]) j++; if (j - i + 1 >= run) runs.push(beats.slice(i, j + 1).map((b) => [b.from, b.to])); i = j; }+ return { beats: beats.map(({ from, to }) => [from, to]), runs, fail: runs.length > 0, size: [sw, sh] };+};++// ---------------------------------------------------------------- dissolves+/**+ * A cross-dissolve or fade: inside a tile, frame t equals A + a(t) (B - A) for a rising a(t), over at+ * least `minFrames` frames, where A and B are the pictures before and after: pixels blending, nothing+ * moving. Findings are merged across tiles per stretch of frames, with `area` (share of the frame) and+ * `share` (of the tiles that changed at all in that stretch, how many blended). It FAILS when the blend+ * is how the stretch changes (share >= 0.5) over at least `minArea` of the frame: a dissolve seam, or a+ * card faded in instead of moved in (motion-grammar bans both). Small fades (a caption) are listed.+ */+export const scanDissolves = (frames, { width: W, height: H, grid = 8, minFrames = 6, minDelta = 10, fit = 0.25, minArea = 0.05, allow = [] } = {}) => {+ const n = frames.length, tiles = [];+ for (let ty = 0; ty < grid; ty++) for (let tx = 0; tx < grid; tx++) tiles.push([Math.floor((tx * W) / grid), Math.floor((ty * H) / grid), Math.floor(((tx + 1) * W) / grid), Math.floor(((ty + 1) * H) / grid)]);+ const tdiff = (a, b, [x0, y0, x1, y1]) => { let s = 0; for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) s += Math.abs(a[y * W + x] - b[y * W + x]); return s / ((x1 - x0) * (y1 - y0)); };+ const hits = [], diffs = [];+ tiles.forEach((t, ti) => {+ const d = new Float64Array(n); for (let f = 1; f < n; f++) d[f] = tdiff(frames[f - 1], frames[f], t); diffs.push(d);+ for (let f = 1; f < n; f++) {+ if (d[f] < 0.4) continue;+ const a = f; while (f + 1 < n && d[f + 1] >= 0.4) f++;+ const b = f; if (b - a + 1 < minFrames) continue;+ const A = frames[a - 1], Bf = frames[b], [x0, y0, x1, y1] = t;+ let dd = 0, cnt = 0; for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const q = Bf[y * W + x] - A[y * W + x]; dd += q * q; cnt++; }+ if (Math.sqrt(dd / cnt) < minDelta) continue;+ let ok = true, mid = 0, last = -Infinity;+ for (let g = a; g < b; g++) {+ let num = 0, res = 0; const F = frames[g];+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const i = y * W + x; num += (F[i] - A[i]) * (Bf[i] - A[i]); }+ const al = num / dd;+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const i = y * W + x, p = A[i] + al * (Bf[i] - A[i]); res += (F[i] - p) ** 2; }+ if (Math.sqrt(res / cnt) > fit * Math.sqrt(dd / cnt) || al < last - 0.05) { ok = false; break; }+ last = al; if (al > 0.1 && al < 0.9) mid++;+ }+ if (ok && mid >= Math.min(4, minFrames - 2)) hits.push({ tile: ti, from: a, to: b + 1 });+ }+ });+ // merge tiles whose stretches overlap into one finding per seam+ hits.sort((p, q) => p.from - q.from); const out = [];+ for (const h of hits) { const g = out.find((o) => h.from < o.to && h.to > o.from); if (g) { g.from = Math.min(g.from, h.from); g.to = Math.max(g.to, h.to); g.tiles.add(h.tile); } else out.push({ from: h.from, to: h.to, tiles: new Set([h.tile]) }); }+ const findings = out.map((o) => {+ let moving = 0; for (const d of diffs) { let any = false; for (let f = o.from; f < Math.min(n, o.to); f++) if (d[f] >= 0.4) { any = true; break; } if (any) moving++; }+ const area = +(o.tiles.size / tiles.length).toFixed(3), share = +(o.tiles.size / Math.max(1, moving)).toFixed(2);+ return { from: o.from, to: o.to, area, share, seam: area >= minArea && share >= 0.5, allowed: allow.some(([x, y]) => o.from < y && o.to > x) };+ });+ return { findings, fail: findings.some((f) => f.seam && !f.allowed), minArea };+};++// ---------------------------------------------------------------- speed and temperament+// the temperaments' top speeds as shares of speedCeiling, as motionKit.ts defines them (kept here so the+// tool needs no bundler); test/motionscan.test.ts holds the two equal+export const TEMPERAMENT_MAX = { calm: 0.35, lively: 0.55, snappy: 0.8 };+/** Per-frame on-screen speed in FULL-SIZE px per frame (scale = full width / analysis width). Frame 0 is 0. */+export const speedProfile = (frames, { width: W, height: H, scale = 1, R = 8 } = {}) => {+ const out = [0];+ for (let f = 1; f < frames.length; f++) { const g = globalMotion(frames[f - 1], frames[f], W, H, { subpixel: true }), cam = g.explained >= 0.5 ? g.speed : 0; out.push(Math.max(cam, motionBetween(frames[f - 1], frames[f], W, H, { R, subpixel: true }).speed) * scale); } // the camera's move, or the fastest coherent element+ return out;+};+/** Stretches of at least `min` frames moving faster than `maxPx` per frame: past the temperament ("violent"). */+export const scanTemperament = (speeds, { maxPx, min = 3 } = {}) => {+ const out = []; for (let f = 0; f < speeds.length; f++) { if (speeds[f] <= maxPx) continue; const a = f; let top = speeds[f]; while (f + 1 < speeds.length && speeds[f + 1] > maxPx) { f++; top = Math.max(top, speeds[f]); } if (f - a + 1 >= min) out.push({ from: a, to: f + 1, top: +top.toFixed(1) }); }+ return { stretches: out, fail: out.length > 0, maxPx };+};++// ---------------------------------------------------------------- layer-record detectors (layerscan)+const lineLabel = (r) => r.kind === "text" && (r.src === "probe" || r.label.trim().length > 1);+/**+ * Text that leaves pixels behind. `series`: per text line, [{ frame, ink }] (visible ink, px) over its+ * life. Its residue is the run at the END of its life where it shows ink but under `tail` (35 %) of its+ * peak: slivers of letters lingering at a clip edge. `max` seconds of that fails (0.2 s, 6 frames at 30+ * fps). An ease-in sink over 1.3x the size crosses that band in about 2 frames; the ease-out 1.0x sink+ * of a brand launch film sat in it for half its exit and left a fifth of the letters showing.+ */+export const scanExits = (series, { fps, tail = 0.35, max = 0.2 } = {}) => {+ const limit = Math.max(2, Math.round(max * fps)), out = [];+ for (const [label, pts] of Object.entries(series)) {+ const peak = Math.max(0, ...pts.map((p) => p.ink)); if (!peak) continue;+ let k = pts.length - 1; while (k >= 0 && pts[k].ink === 0) k--; // frames where it is drawn but fully clipped show nothing: not residue+ let n = 0; const end = k; while (k >= 0 && pts[k].ink > 0 && pts[k].ink <= tail * peak) { n++; k--; }+ if (n >= limit) out.push({ label, from: pts[k + 1].frame, to: pts[end].frame + 1, frames: n, seconds: +(n / fps).toFixed(2), peak, last: pts[end].ink });+ }+ return { findings: out, fail: out.length > 0, limit };+};+/** Each line of text's box per frame, keyed by label: { label: [{ frame, x0, y0, x1, y1 }] } (lines, not per-character fills). */+export const textLines = (layers) => { const out = {}; for (const { frame, recs } of layers) { const seen = new Set(); for (const r of recs) { if (!lineLabel(r) || seen.has(r.label)) continue; seen.add(r.label); (out[r.label] ??= []).push({ frame, x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1 }); } } return out; };+/**+ * Type moving faster than `ratio` x speedCeiling (2.5 frame widths a second) on consecutive checked frames:+ * a whip, not a read. `step`: the frames were sampled every `step` frames (layerscan --every), so two+ * checked frames `step` apart are neighbours and the move between them is shared over `step` frames.+ * Without it a sampled scan never saw two neighbours and could not fire.+ */+export const scanFastText = (layers, { W, fps, scale = 1, ratio = 0.5, min = 2, step = 1 } = {}) => {+ const cap = ((2.5 * W) / fps) * ratio * scale, lines = textLines(layers), out = [];+ for (const [label, pts] of Object.entries(lines)) {+ let run = [];+ const flush = () => { if (run.length >= min) out.push({ label, from: run[0].frame, to: run[run.length - 1].frame + 1, top: +Math.max(...run.map((r) => r.v)).toFixed(1) }); run = []; };+ for (let i = 1; i < pts.length; i++) {+ const a = pts[i - 1], b = pts[i]; if (b.frame !== a.frame + step) { flush(); continue; }+ const v = Math.hypot((b.x0 + b.x1 - a.x0 - a.x1) / 2, (b.y0 + b.y1 - a.y0 - a.y1) / 2) / step;+ if (v > cap) run.push({ frame: b.frame, v: v / scale }); else flush();+ }+ flush();+ }+ return { findings: out, fail: out.length > 0, cap: +(cap / scale).toFixed(1) };+};+const overlap = (a, b) => Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)) * Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0));+/**+ * A real person's face covered by a moving shape. The face is the top `face` (30 %) of a photo's box+ * (cut-outs are framed head-first); a box drawn AFTER the photo that covers more than `min` of the+ * face, and moved against the photo since the frame before, is the "whack-a-mole" the critic named.+ * The person enters and leaves WITH their stage; nothing slides across them.+ */+export const scanFaceCover = (layers, { face = 0.3, min = 0.1 } = {}) => {+ const out = new Map(); let prev = null;+ for (const { frame, recs } of layers) {+ const photos = recs.filter((r) => r.kind === "photo"), boxes = recs.filter((r) => r.kind === "box");+ for (const p of photos) {+ const fb = { x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y0 + (p.y1 - p.y0) * face }, area = (fb.x1 - fb.x0) * (fb.y1 - fb.y0); if (!(area > 0)) continue;+ for (const b of boxes) {+ if (b.order < p.order || overlap(fb, b) / area < min) continue;+ const pp = prev?.recs.find((r) => r.kind === "photo" && r.label === p.label), pb = prev?.recs.find((r) => r.kind === "box" && r.label === b.label);+ const moved = pp && pb ? Math.hypot((b.x0 - p.x0) - (pb.x0 - pp.x0), (b.y0 - p.y0) - (pb.y0 - pp.y0)) > 0.5 : false;+ if (!moved) continue;+ const k = `${p.label}|${b.label}`, e = out.get(k) ?? { photo: p.label, shape: b.label, frames: [] }; e.frames.push(frame); out.set(k, e);+ }+ }+ prev = { frame, recs };+ }+ const findings = [...out.values()];+ return { findings, fail: findings.length > 0 };+};+/** Frames where a brand colour was filled at a translucent alpha, outside the film's declared fades. */+export const scanTranslucent = (layers, { allow = [] } = {}) => {+ const out = new Map();+ for (const { frame, translucent } of layers) for (const t of translucent ?? []) { if (allow.some(([a, b]) => frame >= a && frame < b)) continue; const e = out.get(t.colour) ?? { colour: t.colour, frames: [], alphas: new Set() }; if (e.frames[e.frames.length - 1] !== frame) e.frames.push(frame); e.alphas.add(Math.round(t.alpha * 100)); out.set(t.colour, e); }+ const findings = [...out.values()].map((e) => ({ colour: e.colour, frames: e.frames, alphas: [...e.alphas].sort((a, b) => a - b) }));+ return { findings, fail: findings.length > 0 };+};++/** The file a motion scan reads: a path to any video file as given, else out/<film>.mp4 (a .mov or .m4v was rewritten to out/x.mov.mp4). */+export const scanTarget = (arg) => (/\.(mp4|mov|m4v|mkv|webm)$/i.test(String(arg)) ? String(arg) : `out/${arg}.mp4`);diff --git a/skills/anidoodle/engine/tools/motionscan.mjs b/skills/anidoodle/engine/tools/motionscan.mjsnew file mode 100644index 0000000..6b8f2eb--- /dev/null+++ b/skills/anidoodle/engine/tools/motionscan.mjs@@ -0,0 +1,81 @@+// node tools/motionscan.mjs <film|path.mp4> [--checks slidecut,repeat,dissolve,temperament] [--temperament calm] [--json]+// MOTION SCAN. Reads the RENDERED film (any MP4, made by anidoodle or not) and fails the motion that+// made a brand launch film read as a slide deck:+// slidecut most of the frame replaced within 6 frames with no camera move; more than 2 in any minute fails+// repeat three or more beats in a row settle into the same layout with new content (a carousel)+// dissolve a cross-dissolve over a quarter of the frame or more (smaller element fades are listed)+// temperament stretches faster than the film's motion temperament allows (meta.motion.temperament or --temperament)+// The film's meta comes from the render's sidecar (<file>.film.json, written by render.mjs), so a+// renamed or versioned file still knows its exceptions (meta.motion.allow) and its temperament.+// Exit 0 pass, 1 fail, 2 usage. The detectors are motionscan-core.mjs (pure, unit-tested).+import { existsSync, readFileSync } from "node:fs";+import { execFileSync } from "node:child_process";+import { resolve } from "node:path";+import { greyFrames } from "./motion.mjs";+import { isMain } from "./is-main.mjs";+import { TEMPERAMENT_MAX, scanTarget, scanDissolves, scanRepeats, scanSlideCuts, scanTemperament, speedProfile } from "./motionscan-core.mjs";++export const CHECKS = ["slidecut", "repeat", "dissolve", "temperament"];+const ranges = (xs) => (xs ?? []).map(([a, b]) => [a, b]);++/** The sidecar render.mjs writes beside a delivered file, or null. */+export const sidecarOf = (file) => { const p = `${file}.film.json`; try { return existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : null; } catch { return null; } };++/** Run the motion checks on a rendered file. Returns { checks: { name: { status, ... } }, fail }. */+export const motionScan = async (file, { checks = CHECKS, temperament, size = 192, meta: given } = {}) => {+ const st = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate", "-of", "json", file])).streams[0];+ const [fn, fd] = st.avg_frame_rate.split("/").map(Number), fps = fn / fd, W = size, H = Math.max(24, Math.round((size * st.height) / st.width / 2) * 2);+ const meta = given ?? sidecarOf(file)?.meta ?? {}, motion = meta.motion ?? {}, allow = motion.allow ?? {};+ const frames = []; for await (const f of greyFrames(file, W, H)) frames.push(f);+ const out = {}, o = { width: W, height: H, fps };+ if (checks.includes("slidecut")) { const r = scanSlideCuts(frames, { ...o, allow: ranges(allow.slideCut) }); out.slidecut = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("repeat")) { const r = scanRepeats(frames, o); out.repeat = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("dissolve")) { const r = scanDissolves(frames, { ...o, allow: ranges(allow.dissolve) }); out.dissolve = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("temperament")) {+ const t = temperament ?? motion.temperament, share = typeof t === "string" ? TEMPERAMENT_MAX[t] : t?.maxSpeed;+ if (t !== undefined && !share) throw new Error(`motionscan: temperament '${JSON.stringify(t)}' is not one of ${Object.keys(TEMPERAMENT_MAX).join(", ")} or { maxSpeed }`);+ if (!share) out.temperament = { status: "N/A", reason: "the film declares no motion temperament (meta.motion.temperament); pass --temperament calm|lively|snappy to judge it" };+ else {+ const sw = 128, sh = Math.max(24, Math.round((sw * st.height) / st.width / 2) * 2), small = []; for await (const f of greyFrames(file, sw, sh)) small.push(f);+ const maxPx = share * (2.5 * st.width) / fps, speeds = speedProfile(small, { width: sw, height: sh, scale: st.width / sw, R: 10 }), r = scanTemperament(speeds, { maxPx });+ out.temperament = { status: r.fail ? "FAIL" : "PASS", temperament: t, top: +Math.max(...speeds).toFixed(1), ...r };+ }+ }+ return { file, fps, frames: frames.length, checks: out, fail: Object.values(out).some((c) => c.status === "FAIL") };+};++export const printScan = (r) => {+ const s = (f) => (f / r.fps).toFixed(2), c = r.checks;+ console.log(`MOTIONSCAN ${r.file} ${r.frames} frames @ ${r.fps.toFixed(2)} fps`);+ if (c.slidecut) {+ for (const e of c.slidecut.events) console.log(` ${c.slidecut.fail ? "FAIL" : "NOTE"} slide cut at frame ${e.frame} (${s(e.frame)} s): ${Math.round(e.replaced * 100)} % of the frame replaced in 6 frames with no camera move`);+ console.log(` SLIDE-CUTS: ${c.slidecut.status} ${c.slidecut.events.length} found${c.slidecut.fail ? `, ${c.slidecut.worst.length} inside one minute (limit ${c.slidecut.perMinute}): carry the eye with a camera move into the next region (world.ts), or declare the cut in meta.motion.allow.slideCut` : ""}`);+ }+ if (c.repeat) {+ for (const run of c.repeat.runs) console.log(` FAIL ${run.length} beats in a row settle into the same layout: ${run.map(([a, b]) => `${s(a)}-${s(b)} s`).join(", ")}`);+ console.log(` REPEATS: ${c.repeat.status} ${c.repeat.beats.length} settled beats${c.repeat.fail ? ": give each beat its own layout and entry (motionKit alternate(i), entryFrom(i))" : ""}`);+ }+ if (c.dissolve) {+ for (const d of c.dissolve.findings) console.log(` ${d.seam && !d.allowed ? "FAIL" : "NOTE"} ${d.seam ? "dissolve or fade-in" : "small fade"} frames ${d.from}-${d.to - 1} (${s(d.from)}-${s(d.to)} s): ${Math.round(d.area * 100)} % of the frame blends, ${Math.round(d.share * 100)} % of what changes there${d.allowed ? " (declared)" : ""}`);+ console.log(` DISSOLVES: ${c.dissolve.status}${c.dissolve.fail ? " a fade is not a transition: move the camera, mask a wipe, or let the outgoing element leave" : ""}`);+ }+ if (c.temperament) {+ if (c.temperament.status === "N/A") console.log(` TEMPERAMENT: N/A ${c.temperament.reason}`);+ else { for (const t of c.temperament.stretches) console.log(` FAIL frames ${t.from}-${t.to} (${s(t.from)} s) move at up to ${t.top} px a frame; the ${JSON.stringify(c.temperament.temperament)} temperament allows ${c.temperament.maxPx.toFixed(0)}`); console.log(` TEMPERAMENT: ${c.temperament.status} fastest ${c.temperament.top} px a frame, limit ${c.temperament.maxPx.toFixed(0)}${c.temperament.fail ? ": lengthen the move or travel less" : ""}`); }+ }+ console.log(`MOTIONSCAN: ${r.fail ? "FAIL" : "PASS"}`);+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a === "--json") opt.json = true; else if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const usage = "usage: node tools/motionscan.mjs <film|path.mp4> [--checks slidecut,repeat,dissolve,temperament] [--temperament calm|lively|snappy] [--json]";+ if (!pos[0]) { console.error(usage); process.exit(2); }+ const file = resolve(scanTarget(pos[0]));+ if (!existsSync(file)) { console.error(`motionscan: no such file ${file}; render it first (node tools/render.mjs ${pos[0]}) or give the video file's path\n${usage}`); process.exit(2); }+ const checks = opt.checks ? String(opt.checks).split(",") : CHECKS, bad = checks.filter((c) => !CHECKS.includes(c));+ if (bad.length) { console.error(`motionscan: unknown check ${bad.join(", ")}; the checks are ${CHECKS.join(", ")}`); process.exit(2); }+ const r = await motionScan(file, { checks, temperament: opt.temperament });+ if (opt.json) console.log(JSON.stringify(r, (k, v) => (v instanceof Set ? [...v] : v), 1)); else printScan(r);+ process.exit(r.fail ? 1 : 0);+}diff --git a/skills/anidoodle/engine/tools/narrate.mjs b/skills/anidoodle/engine/tools/narrate.mjsindex 0405fec..88fc987 100644--- a/skills/anidoodle/engine/tools/narrate.mjs+++ b/skills/anidoodle/engine/tools/narrate.mjs@@ -25,6 +25,7 @@// the environment and never printed. say (macOS), kokoro (local) and files (your own recordings) stay// on this machine.import { spawnSync } from "node:child_process";+import { enginePath } from "./overlay.mjs";import { createHash } from "node:crypto";import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { homedir } from "node:os";@@ -38,6 +39,7 @@ import * as openai from "./narrate/providers/openai.mjs";import * as elevenlabs from "./narrate/providers/elevenlabs.mjs";import * as kokoro from "./narrate/providers/kokoro.mjs";import * as files from "./narrate/providers/files.mjs";+import { which } from "./narrate/providers/util.mjs";export const PROVIDERS = { say, gemini, openai, elevenlabs, kokoro, files };const SR = 24000, CACHE = resolve(".cache/voice"), POST = "trim45-pad40-80-lufs20-pk3-v1"; // POST names the take processing: change it and every take is made again@@ -117,7 +119,7 @@ export const findModel = (flag) => {if (!pick) die(`no whisper.cpp model in ${dir}. Get one (MIT, about 148 MB):\n mkdir -p ~/.cache/whisper && curl -L -o ~/.cache/whisper/ggml-base.en.bin https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.en.bin\n(ggml-small.en.bin, about 488 MB, hears better)`);return join(dir, pick);};-const whisperBin = () => { for (const c of ["whisper-cli", "whisper-cpp"]) { const r = spawnSync("/usr/bin/env", ["which", c], { encoding: "utf8" }); if (r.status === 0) return r.stdout.trim(); } die("whisper.cpp is not installed (brew install whisper-cpp gives whisper-cli)"); };+const whisperBin = () => { for (const c of ["whisper-cli", "whisper-cpp"]) { const f = which(c); if (f) return f; } die("whisper.cpp is not installed (brew install whisper-cpp gives whisper-cli)"); };/** Transcribe a take with NO prompt (the check must hear what was said, not what was meant). Cached by take + model. */export const transcribe = (file, model, lang = "en") => {const key = sha(readFileSync(file).toString("base64") + "\0" + basename(model) + "\0" + lang + "\0ml1-sow"), dir = join(CACHE, "asr"), hit = join(dir, `${key}.json`);@@ -153,7 +155,7 @@ export const timeScript = async (s, o = {}) => {// ---------------------------------------------------------------- check// the phrase subtitles, built by the film's own module, so the check and the film can never disagreeconst loadSubtitles = async () => {- const js = (await build({ entryPoints: [resolve("src/canvas-core/subtitles.ts")], bundle: true, format: "esm", write: false, platform: "neutral", logLevel: "error" })).outputFiles[0].text;+ const js = (await build({ entryPoints: [enginePath("src/canvas-core/subtitles.ts")], bundle: true, format: "esm", write: false, platform: "neutral", logLevel: "error" })).outputFiles[0].text;return import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));};const show = (p) => { const r = relative(process.cwd(), p); return r.startsWith("..") ? p : r; };@@ -187,8 +189,7 @@ export const checkScript = async (s, o = {}) => {// the film plays the BAKED takes: a module baked from other takes (or another timing) is a stale filmconst mod = resolve(o.module ?? `src/canvas-core/${s.name}Voice.ts`); let stale = false;if (existsSync(mod)) {- const src = readFileSync(mod, "utf8"), hashes = [...src.matchAll(/"hash":"([0-9a-f]{64})"/g)].map((m) => m[1]), frames = Number((src.match(/"totalFrames":(\d+)/) ?? [])[1]);- stale = !o.ignoreStale && hashes.join() !== timing.lines.map((l) => l.hash).join() || frames !== timing.totalFrames;+ stale = bakedStale(readFileSync(mod, "utf8"), timing, !!o.ignoreStale);console.log(` BAKED ${show(mod)}: ${stale ? "FAIL baked from other takes or timing: run narrate.mjs bake" : "matches these takes and this timing"}`);} else console.log(` BAKED ${show(mod)}: not baked yet (narrate.mjs bake writes it)`);const bad = rows.filter((r) => r.problems.length).length + (plan.problems.length ? 1 : 0) + (mixBad ? 1 : 0) + (stale ? 1 : 0);@@ -196,6 +197,16 @@ export const checkScript = async (s, o = {}) => {return { ok: !bad, rows, timing, plan };};+/**+ * Is a baked module out of date for these takes and this timing? It is when its take hashes or its+ * length differ. `all` passes ignoreStale, because re-baking a stale module is the job it exists to do:+ * the parentheses make that cover a changed length too, not only changed takes.+ */+export const bakedStale = (src, timing, ignoreStale = false) => {+ const hashes = [...src.matchAll(/"hash":"([0-9a-f]{64})"/g)].map((m) => m[1]), frames = Number((src.match(/"totalFrames":(\d+)/) ?? [])[1]);+ return !ignoreStale && (hashes.join() !== timing.lines.map((l) => l.hash).join() || frames !== timing.totalFrames);+};+// ---------------------------------------------------------------- bakeexport const bakeScript = async (s, o = {}) => {const { timing, per } = await timeScript(s, o), mod = resolve(o.module ?? `src/canvas-core/${s.name}Voice.ts`), name = `${s.name}Voice`;diff --git a/skills/anidoodle/engine/tools/narrate/providers/util.mjs b/skills/anidoodle/engine/tools/narrate/providers/util.mjsindex bf99fbe..137e474 100644--- a/skills/anidoodle/engine/tools/narrate/providers/util.mjs+++ b/skills/anidoodle/engine/tools/narrate/providers/util.mjs@@ -1,8 +1,22 @@// Shared bits for the providers: PATH lookup, a key read from the environment (never printed), and a// POST that returns bytes and reports a failure WITHOUT echoing headers (the key lives there).-import { spawnSync } from "node:child_process";+import { accessSync, constants, statSync } from "node:fs";+import { delimiter, join } from "node:path";-export const which = (cmd) => { const r = spawnSync("/usr/bin/env", ["which", cmd], { encoding: "utf8" }); return r.status === 0 ? r.stdout.trim() : null; };+/**+ * A program's full path from the PATH, or null. Read in node rather than by running `which`, which+ * Windows does not have: there every PATHEXT ending (.EXE, .CMD, ...) is tried, and a folder with a space+ * is just a folder. `o` overrides the PATH, PATHEXT and platform (the tests use it).+ */+export const which = (cmd, o = {}) => {+ const win = o.win ?? process.platform === "win32", path = o.path ?? process.env.PATH ?? process.env.Path ?? "";+ const exts = win ? [...String(o.pathext ?? process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)] : [""];+ for (const dir of path.split(delimiter).filter(Boolean)) for (const e of exts) {+ const f = join(dir.replace(/^"(.*)"$/, "$1"), cmd + e);+ try { if (!statSync(f).isFile()) continue; if (!win) accessSync(f, constants.X_OK); return f; } catch { /* not here */ }+ }+ return null;+};export const envKey = (...names) => { for (const n of names) if (process.env[n]?.trim()) return { name: n, value: process.env[n].trim() }; return null; };export const post = async (url, headers, body, what) => {const r = await fetch(url, { method: "POST", headers, body: typeof body === "string" ? body : JSON.stringify(body) });diff --git a/skills/anidoodle/engine/tools/overlay.mjs b/skills/anidoodle/engine/tools/overlay.mjsindex c8ed050..691bc39 100644--- a/skills/anidoodle/engine/tools/overlay.mjs+++ b/skills/anidoodle/engine/tools/overlay.mjs@@ -4,12 +4,22 @@// example keeps importing "../core"; a launch film can import "./mechanicalLepidoptera" and get// the committed example. Order matters: engine/src first, so the engine always wins a name clash.// tsconfig.json says the same thing to tsc with "rootDirs", so the checker and the bundler agree.-import { existsSync, statSync } from "node:fs";+import { existsSync, readFileSync, statSync } from "node:fs";import { dirname, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";const ENGINE = resolve(dirname(fileURLToPath(import.meta.url)), "..");-export const ROOTS = [join(ENGINE, "src"), resolve(ENGINE, "../example/src")];+// A LINKED PROJECT (scaffold.mjs --linked): a folder of its own films that runs the installed engine's+// tools from its own working directory. Its src/ joins the tree first, so a project film's "./core"+// resolves to the engine's and a project never needs a copy of the engine (a brand launch film was+// built in a forked engine for exactly this reason). When cwd is the engine itself nothing changes.+// A folder counts as a linked project only when it carries the marker scaffold --linked writes: any other+// repo run from (one with its own src/hosts/page.ts, say) must never replace the engine's files.+export const PROJECT_MARKER = "anidoodle-project.json";+const PROJECT = resolve(process.cwd(), "src"), LINKED = PROJECT !== join(ENGINE, "src") && existsSync(PROJECT) && existsSync(resolve(process.cwd(), PROJECT_MARKER));+export const ROOTS = [...(LINKED ? [PROJECT] : []), join(ENGINE, "src"), resolve(ENGINE, "../example/src")];+/** An engine file by its path inside the engine (src/canvas-core/film.ts): a linked project's copy if it has one, else the engine's. */+export const enginePath = (rel) => (LINKED && existsSync(resolve(rel)) ? resolve(rel) : join(ENGINE, rel));const EXT = ["", ".ts", ".tsx", ".js", ".mjs", "/index.ts", "/index.js"];const file = (p) => { for (const e of EXT) { const f = p + e; if (existsSync(f) && statSync(f).isFile()) return f; } return null; };const rootOf = (p) => ROOTS.find((r) => p === r || p.startsWith(r + sep));@@ -32,6 +42,18 @@ export const overlay = {name: "anidoodle-overlay",setup(b) {b.onResolve({ filter: /^three$/ }, () => ({ path: THREE_MODULE }));+ // FONT FILES. A launch look imports its typefaces by path (import serif from "../../assets/fonts/X.ttf"):+ // the bytes are inlined as { path, format, data } so the film carries them and nothing is fetched. A path+ // that is not there is a build error that says where to put the file.+ b.onResolve({ filter: /\.(ttf|otf|woff2)$/i }, (a) => {+ const want = resolve(a.resolveDir, a.path), f = existsSync(want) ? want : resolveOverlay(a.path, a.resolveDir);+ if (!f) return { errors: [{ text: `font file not found: ${a.path} (looked for ${want}). Put the font file (.ttf) there, or fix the import's path; the engine's own fonts are in engine/assets/fonts` }] };+ return { path: f, namespace: "anidoodle-font" };+ });+ b.onLoad({ filter: /.*/, namespace: "anidoodle-font" }, (a) => {+ const format = a.path.toLowerCase().split(".").pop(), rel = relative(ENGINE, a.path).split(sep).join("/");+ return { contents: `export default ${JSON.stringify({ path: rel, format, data: readFileSync(a.path).toString("base64") })};`, loader: "js" };+ });b.onResolve({ filter: /^\.\.?\// }, (a) => {const f = resolveOverlay(a.path, a.resolveDir);return f ? { path: f } : undefined;diff --git a/skills/anidoodle/engine/tools/pngio.mjs b/skills/anidoodle/engine/tools/pngio.mjsnew file mode 100644index 0000000..df46993--- /dev/null+++ b/skills/anidoodle/engine/tools/pngio.mjs@@ -0,0 +1,63 @@+// PNG IO. Just enough PNG to trim a logo's transparent margins and measure its ink, with no+// dependency: 8-bit greyscale, grey+alpha, RGB, RGBA and palette images, not interlaced. Anything else+// gets a message naming the fix (re-export as 8-bit RGBA), never a wrong answer.+import { deflateSync, inflateSync } from "node:zlib";++const SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);+const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();+const crc32 = (buf) => { let c = 0xffffffff; for (const b of buf) c = CRC[(c ^ b) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };++/** PNG bytes -> { w, h, data: RGBA Uint8Array }. */+export const decodePng = (buf) => {+ if (!Buffer.isBuffer(buf) || buf.length < 8 || !buf.subarray(0, 8).equals(SIG)) throw new Error("not a PNG file");+ let pos = 8, w = 0, h = 0, depth = 0, type = 0, interlace = 0, palette = null, trns = null; const idat = [];+ while (pos < buf.length) {+ const len = buf.readUInt32BE(pos), kind = buf.toString("latin1", pos + 4, pos + 8), body = buf.subarray(pos + 8, pos + 8 + len); pos += 12 + len;+ if (kind === "IHDR") { w = body.readUInt32BE(0); h = body.readUInt32BE(4); depth = body[8]; type = body[9]; interlace = body[12]; }+ else if (kind === "PLTE") palette = body; else if (kind === "tRNS") trns = body; else if (kind === "IDAT") idat.push(body); else if (kind === "IEND") break;+ }+ if (depth !== 8) throw new Error(`PNG bit depth ${depth} is not read here: re-export the logo as an 8-bit RGBA PNG (or bring the SVG)`);+ if (interlace) throw new Error("interlaced PNGs are not read here: re-export without interlacing (or bring the SVG)");+ const ch = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[type]; if (!ch) throw new Error(`PNG colour type ${type} is not supported`);+ const raw = inflateSync(Buffer.concat(idat)), stride = w * ch, px = new Uint8Array(stride * h);+ for (let y = 0; y < h; y++) {+ const f = raw[y * (stride + 1)], src = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)), row = y * stride;+ for (let x = 0; x < stride; x++) {+ const a = x >= ch ? px[row + x - ch] : 0, b = y ? px[row - stride + x] : 0, c = x >= ch && y ? px[row - stride + x - ch] : 0;+ let v = src[x];+ if (f === 1) v += a; else if (f === 2) v += b; else if (f === 3) v += (a + b) >> 1;+ else if (f === 4) { const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c); v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; }+ px[row + x] = v & 255;+ }+ }+ const data = new Uint8Array(w * h * 4);+ for (let i = 0; i < w * h; i++) {+ const s = i * ch, d = i * 4;+ if (type === 6) { data[d] = px[s]; data[d + 1] = px[s + 1]; data[d + 2] = px[s + 2]; data[d + 3] = px[s + 3]; }+ else if (type === 2) { data[d] = px[s]; data[d + 1] = px[s + 1]; data[d + 2] = px[s + 2]; data[d + 3] = 255; }+ else if (type === 0) { data[d] = data[d + 1] = data[d + 2] = px[s]; data[d + 3] = 255; }+ else if (type === 4) { data[d] = data[d + 1] = data[d + 2] = px[s]; data[d + 3] = px[s + 1]; }+ else { const k = px[s]; data[d] = palette[k * 3]; data[d + 1] = palette[k * 3 + 1]; data[d + 2] = palette[k * 3 + 2]; data[d + 3] = trns && k < trns.length ? trns[k] : 255; }+ }+ return { w, h, data };+};+/** { w, h, data: RGBA } -> PNG bytes (filter 0, which is plenty for logos). */+export const encodePng = ({ w, h, data }) => {+ const raw = Buffer.alloc((w * 4 + 1) * h); for (let y = 0; y < h; y++) Buffer.from(data.buffer, data.byteOffset + y * w * 4, w * 4).copy(raw, y * (w * 4 + 1) + 1);+ const chunk = (kind, body) => { const len = Buffer.alloc(4); len.writeUInt32BE(body.length); const kb = Buffer.concat([Buffer.from(kind, "latin1"), body]), c = Buffer.alloc(4); c.writeUInt32BE(crc32(kb)); return Buffer.concat([len, kb, c]); };+ const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 6;+ return Buffer.concat([SIG, chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);+};+/** Box of pixels with alpha over `min` (a PNG's transparent margin removed). -> [x, y, w, h], or null when it is empty. */+export const alphaBox = ({ w, h, data }, min = 8) => {+ let x0 = w, y0 = h, x1 = -1, y1 = -1;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (data[(y * w + x) * 4 + 3] > min) { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }+ return x1 < 0 ? null : [x0, y0, x1 - x0 + 1, y1 - y0 + 1];+};+export const crop = (img, [x, y, w, h]) => { const data = new Uint8Array(w * h * 4); for (let r = 0; r < h; r++) data.set(img.data.subarray(((y + r) * img.w + x) * 4, ((y + r) * img.w + x + w) * 4), r * w * 4); return { w, h, data }; };+/** Ink: the summed alpha, in whole-pixel units (a half-transparent pixel counts half). */+export const inkOf = ({ data }) => { let s = 0; for (let i = 3; i < data.length; i += 4) s += data[i]; return s / 255; };+/** Paint every visible pixel one colour, keeping its alpha (a white logo for a dark ground). */+export const tint = (img, [r, g, b]) => { const data = new Uint8Array(img.data); for (let i = 0; i < data.length; i += 4) { data[i] = r; data[i + 1] = g; data[i + 2] = b; } return { ...img, data }; };+/** Does the image have a solid (non-transparent) background? Corner pixels all opaque means yes. */+export const opaqueCorners = ({ w, h, data }) => [0, w - 1, (h - 1) * w, h * w - 1].every((i) => data[i * 4 + 3] > 245);diff --git a/skills/anidoodle/engine/tools/render.mjs b/skills/anidoodle/engine/tools/render.mjsindex 0a97fa2..55abc1c 100644--- a/skills/anidoodle/engine/tools/render.mjs+++ b/skills/anidoodle/engine/tools/render.mjs@@ -9,6 +9,9 @@// matching two sharp renders at the shutter's ends: subframes at most --blur-px apart// (default 3 px), 1 on a still frame (the sharp frame, untouched), at most --blur-max (32).// Deterministic: the count is a function of the frame's pixels.+// Type, photos and anything drawn inside sharp() are NEVER blurred (hosts/instrument.ts): they+// are left out of the subframes and laid over the result sharp. Blurred type and faces read+// as violent motion (a brand launch film, critic round 2). --blur-all blurs everything, as before.// --shutter DEG the shutter angle: 180 (default, film's standard: half the frame interval) to 360// (the whole interval, the old --blur behaviour). 180-240 reads as natural motion.// --from/--to render only frames [from, to): for checking a passage, not for shipping. A range@@ -28,6 +31,8 @@// whatever sits behind the page shows through// .apng animated PNG, alpha kept, loops forever, plays in every browser// --width only applies to the silent formats; the MP4 is always the film's own size.+// Every render also writes <out>.film.json beside the file: the film id, frame range, blur, sha256 and+// the film's meta, so the checks on a delivered file never infer the film from its name.// --shapes 16x9,1x1,4x5,9x16 a launch template film in several frame shapes from ONE timeline: each// shape is re-composed by its layout (launchLayout.ts), never cropped, and rendered as the// film <film>-<shape> to out/<film>-<shape>.mp4, one after another, with the other flags.@@ -35,8 +40,9 @@ import { spawn, spawnSync, execFileSync } from "node:child_process";import { createHash } from "node:crypto";import { mkdirSync, writeFileSync } from "node:fs";import { cpus } from "node:os";-import { join, resolve } from "node:path";+import { basename, join, resolve } from "node:path";import { buildPage } from "./build-page.mjs";+import { enginePath } from "./overlay.mjs";import { detect } from "./detect.mjs";import * as playwright from "./adapters/playwright.mjs";import { defaultOutput, requireFilm } from "./names.mjs";@@ -58,7 +64,8 @@ const BLUR = arg("blur", "1") === "auto" ? "auto" : Number(arg("blur", 1)), SHUTif (BLUR !== "auto" && (!Number.isInteger(BLUR) || BLUR < 1)) { console.error(`--blur wants a whole number of subframes >= 1 or 'auto', got '${arg("blur")}'`); process.exit(2); }if (!(SHUTTER > 0 && SHUTTER <= 360)) { console.error(`--shutter wants an angle in (0, 360] degrees, got '${arg("shutter")}'`); process.exit(2); }if (!Number.isInteger(BMAX) || BMAX < 2 || !(BPX > 0)) { console.error(`--blur-max wants a whole number >= 2 and --blur-px a number > 0`); process.exit(2); }-const BLURRED = BLUR === "auto" || BLUR > 1, BSPEC = BLUR === "auto" ? { samples: 0, shutter: SHUTTER, max: BMAX, px: BPX } : { samples: BLUR, shutter: SHUTTER };+const SHARP = !process.argv.includes("--blur-all"); // type and photos stay sharp under the blur unless asked otherwise+const BLURRED = BLUR === "auto" || BLUR > 1, BSPEC = BLUR === "auto" ? { samples: 0, shutter: SHUTTER, max: BMAX, px: BPX, sharp: SHARP } : { samples: BLUR, shutter: SHUTTER, sharp: SHARP };const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2)))));const HASHES = arg("hashes", null) ? new Map() : null;const RANGE_ASKED = process.argv.includes("--from") || process.argv.includes("--to");@@ -92,7 +99,7 @@ const drawAt = (n, w) => (posterAt(n) ? session.poster(n, POSTER, FADE, BLURRED// a film whose cuts sit on its beat grid (meta.score.grid) must hear its score at that grid's tempoif (meta.score?.grid && Math.abs(meta.score.tempo / meta.bpm - 1) > 0.005) { console.error(`render: the score plays at ${meta.score.tempo.toFixed(2)} bpm but this film's cuts sit on a ${meta.bpm} bpm grid (${((meta.score.tempo / meta.bpm - 1) * 100).toFixed(1)} %, limit 0.5 %): the cuts would drift off the downbeats. Play the score at the film's bpm and make the film whole bars of it (launchTemplate does), or compose a 1-bar stretch section`); process.exit(2); }console.log(`film: "${meta.title}" ${meta.W}x${meta.H} @ ${meta.fps} fps, ${N} frames, ${meta.bpm} bpm, scale ${scale}, ${session.workers} page(s)`);-if (BLURRED) console.log(`motion blur: ${BLUR === "auto" ? `adaptive (subframes <= ${BPX} px apart, max ${BMAX})` : `${BLUR} subframes per frame`}, ${SHUTTER}-degree shutter, linear light`);+if (BLURRED) console.log(`motion blur: ${BLUR === "auto" ? `adaptive (subframes <= ${BPX} px apart, max ${BMAX})` : `${BLUR} subframes per frame`}, ${SHUTTER}-degree shutter, linear light, ${SHARP ? "type and photos kept sharp" : "EVERYTHING blurred (--blur-all), type and photos too"}`);if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent by design`);// audio: the page returns its embedded recorded track or its code-built mix -> WAV here@@ -100,7 +107,8 @@ if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent bmkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = ranged ? null : await session.audio(48000);if (a) writeFileSync(wav, float32Wav(a));if (a) { // the audio report: loudness and true peak, and the score's fit against the picture's grid- const { build } = await import("esbuild"), js = (await build({ entryPoints: [resolve("src/canvas-core/music/meter.ts")], bundle: true, write: false, format: "esm", platform: "neutral", logLevel: "error" })).outputFiles[0].text;+ // the meter is an engine file: a linked project (scaffold --linked) runs from its own folder and has no copy+ const { build } = await import("esbuild"), js = (await build({ entryPoints: [enginePath("src/canvas-core/music/meter.ts")], bundle: true, write: false, format: "esm", platform: "neutral", logLevel: "error" })).outputFiles[0].text;const { loudness, truePeak } = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));const pcm = new Float32Array(Uint8Array.from(Buffer.from(a.float32, "base64")).buffer), L = new Float32Array(a.frames), R = new Float32Array(a.frames);for (let i = 0; i < a.frames; i++) { L[i] = pcm[2 * i]; R[i] = pcm[2 * i + 1]; }@@ -129,7 +137,7 @@ const done = new Promise((res, rej) => ff.on("close", (c) => (c ? rej(new Error(const cost = [], pending = new Map(); let next, write;const pump = async () => { while (pending.has(write)) { const b = pending.get(write); pending.delete(write); if (!ff.stdin.write(b)) await new Promise((r) => ff.stdin.once("drain", r)); write++; } };next = FROM; write = FROM;-await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await drawAt(n, w); if (HASHES) HASHES.set(n, createHash("md5").update(f.png).digest("hex")); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs, samples: f.samples ?? 1 }); pending.set(n, f.png); await pump(); } }));+await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await drawAt(n, w); if (HASHES) HASHES.set(n, createHash("md5").update(f.png).digest("hex")); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs, samples: f.samples ?? 1, sharp: f.sharpPx ?? 0, typeInLayers: f.typeInLayers ?? 0 }); pending.set(n, f.png); await pump(); } }));await pump(); ff.stdin.end(); await done;const wall = (Date.now() - t0) / 1000;if (HASHES) { const hf = resolve(arg("hashes")); mkdirSync(join(hf, ".."), { recursive: true }); writeFileSync(hf, [...HASHES].sort((a, b) => a[0] - b[0]).map(([n, h]) => `${n} ${h}`).join("\n") + "\n"); console.log(`frame hashes -> ${hf}`); }@@ -151,6 +159,22 @@ for (const n of probe) fwd.push(await hashOf(n, 0)); for (const n of [...probe].const same = probe.filter((_, i) => fwd[i] === rev[i]).length;console.log(`\ndeterminism: ${same}/${probe.length} probe frames${BLURRED ? ` (blurred, ${BLUR === "auto" ? "adaptive" : `${BLUR} subframes`}, ${SHUTTER} degrees)` : ""} hash-identical (forward on page 0 vs reversed on page ${session.workers - 1})${same === probe.length ? "" : " -> fall back to PSNR > 45 dB in the Phase 2 gate"}`);await session.close();+// THE SIDECAR. <out>.film.json says which film and which frames this file is, so the checks that read a+// delivered file (verify-export, motionscan, soundcheck) never have to guess the film from its name: the+// A brand film's deliverables were called brandLaunch-v12.mp4 while the film was brandHook, and verify-export+// could not find them. The sha256 ties the sidecar to these exact bytes; a re-encode or a rename-and-+// replace is caught by comparing it. The file is named without its folder: the sidecar travels with the+// film, and an absolute path would carry the maker's home folder with it.+{+ const { readFileSync } = await import("node:fs"), sha = createHash("sha256").update(readFileSync(out)).digest("hex");+ const pick = ({ title, W, H, fps, bpm, durationFrames, kind, holds, quiet, sync, captions, poster, motion, checks, shots }) => ({ title, W, H, fps, bpm, durationFrames, kind, holds, quiet, sync, captions, poster, motion, checks, shots });+ writeFileSync(`${out}.film.json`, JSON.stringify({ film, file: basename(out), sha256: sha, frames: [FROM, TO], scale, blur: BLURRED ? { samples: BLUR, shutter: SHUTTER, sharp: SHARP } : null, poster: POSTER, meta: pick(meta) }, null, 1) + "\n");+}+const sharpFrames = cost.filter((c) => c.sharp > 0).length;+if (BLURRED && SHARP) console.log(`blur mask: type and photos kept sharp on ${sharpFrames} of ${cost.length} frames`);+// the mask only sees type drawn on the frame's own canvas: type composited from an offscreen layer blurs with it (instrument.ts)+const layerTypeFrames = cost.filter((c) => c.typeInLayers > 0).length;+if (BLURRED && SHARP && layerTypeFrames) console.log(` NOTE ${layerTypeFrames} frame(s) composited type from layers that blurred: that type is NOT kept sharp. Draw it on the frame's canvas, not in a layer, to keep it crisp`);const pr = execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height,nb_frames,duration", "-of", "csv=p=0", out]).toString().trim().split("\n");-console.log(`\noutput: ${out}`); pr.forEach((l) => console.log(` ${l}`));+console.log(`\noutput: ${out}\nsidecar: ${out}.film.json`); pr.forEach((l) => console.log(` ${l}`));if (fmt === "mp4" && !ranged) { const t = firstFrameBlank(out); if (t.blank) console.log(`\nWARNING frame 0 is near-blank (${t.detail}). Platforms use frame 0 as the thumbnail: re-render with --poster-frame N (a legible frame: the wall, the logo).`); }diff --git a/skills/anidoodle/engine/tools/scaffold.mjs b/skills/anidoodle/engine/tools/scaffold.mjsindex 8f2f0c9..2f7310b 100644--- a/skills/anidoodle/engine/tools/scaffold.mjs+++ b/skills/anidoodle/engine/tools/scaffold.mjs@@ -1,6 +1,8 @@// SCAFFOLD. Turn the skill's engine into a working project: a still, a film, or both.//// node <skill>/engine/tools/scaffold.mjs <dir> [--still myPicture] [--film myFilm] [--duration seconds] [--size WxH | --format 9x16] [--fps N] [--bpm N] [--example]+// node <skill>/engine/tools/scaffold.mjs <dir> --linked --film myFilm [--world] [...] a project that USES the engine, no copy;+// --world starts the film as one world under one camera (worldfilm.mjs), the default for launch films//// The engine ships as parts, not as a project: `engine/src` holds the portable art core and the// one page host, `example/src` holds the worked butterfly. A film needs them in ONE tree, because@@ -17,8 +19,9 @@// use; the launch KIT (launchKit, kinetic, launchCut, launchTemplate, launchExample)// always ships, because that is what your own launch film is built on.import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";-import { dirname, join, resolve, sep } from "node:path";+import { dirname, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";+import { PROJECT_MARKER } from "./overlay.mjs";const HERE = dirname(fileURLToPath(import.meta.url));const ENGINE = resolve(HERE, "..");@@ -63,6 +66,51 @@ const ownFilmFiles = () => {for (const f of files) if (!reach.has(f)) out.add(f);return out;};+// --linked: a project of the person's own, beside their brand files and photos, that USES the installed+// engine instead of copying it. Only the film, its host page, a tsconfig that sees the engine's modules+// and a package.json whose scripts call the engine's tools are written. The tools run from the project+// folder (cwd); overlay.mjs puts the project's src/ in front of the engine's, so "./core" resolves to the+// engine. An engine update reaches every linked project; nothing is forked (lesson X4 from a brand launch film).+if (opt.linked) {+ if (still || opt.example) die("--linked takes --film only (a still or the example need the full copy)");+ if (!film) die("--linked needs --film <name>");+ const mod = join(target, "src/canvas-core", `${film}.ts`), host = join(target, "src/hosts", `page-${film}.ts`);+ if (existsSync(mod) || existsSync(host)) die(`${film} already exists in ${target}; refusing to overwrite`);+ mkdirSync(join(target, "src/canvas-core"), { recursive: true }); mkdirSync(join(target, "src/hosts"), { recursive: true });+ const rel = (p) => relative(target, p).split(sep).join("/");+ if (opt.world) { const { worldFilmSource } = await import("./worldfilm.mjs"); writeFileSync(mod, worldFilmSource(film, { format: opt.format ?? "16x9", fps, ...(opt.bpm ? { bpm } : {}) })); } // the one-world starter (worldfilm.mjs): the default for a motion or launch film+ else writeFileSync(mod, `// ${film}: a film in a linked project. "./core", "./film" and every kit module come from the engine at+// ${rel(join(ENGINE, "src"))} (tools/overlay.mjs). Keep this folder for the film's own modules, assets and facts.+import { rng, type Ctx, type Env } from "./core";+import type { Film } from "./film";++const FPS = ${fps}, BPM = ${bpm}, DURATION = ${durationFrames};+const draw = (ctx: Ctx, local: number, env: Env) => {+ const W = env.W * env.scale, H = env.H * env.scale, r = rng(1), t = local / DURATION;+ ctx.fillStyle = "#12161c"; ctx.fillRect(0, 0, W, H);+ for (let i = 0; i < 90; i++) { const a = r() * Math.PI * 2, rad = (0.08 + r() * 0.36) * Math.min(W, H); ctx.globalAlpha = 0.25 + r() * 0.6; ctx.fillStyle = "#e8e3d2"; ctx.beginPath(); ctx.arc(W / 2 + Math.cos(a + t * Math.PI * 2) * rad, H / 2 + Math.sin(a + t * Math.PI * 2) * rad, (1 + r() * 2.5) * env.scale, 0, Math.PI * 2); ctx.fill(); }+ ctx.globalAlpha = 1;+};+export const ${film}: Film = {+ meta: { title: "${film}", W: ${size[0]}, H: ${size[1]}, fps: FPS, bpm: BPM, durationFrames: DURATION },+ assets: { images: {} },+ shots: [{ id: "one", start: 0, end: DURATION, draw }],+};+`);+ writeFileSync(host, `import { ${film} } from "../canvas-core/${film}";\nimport { mountFilm } from "./page";\nmountFilm(${film});\n`);+ const eng = rel(ENGINE);+ if (!existsSync(join(target, "tsconfig.json"))) writeFileSync(join(target, "tsconfig.json"), JSON.stringify({ compilerOptions: { target: "ES2022", module: "ESNext", moduleResolution: "bundler", strict: true, noEmit: true, skipLibCheck: true, lib: ["DOM", "ES2022"], rootDirs: ["src", `${eng}/src`], paths: { three: [`${eng}/vendor/three/types/Three.d.ts`] } }, include: ["src"] }, null, 2) + "\n");+ // npm runs a script through a shell (sh, or cmd.exe on Windows): the tool path is quoted so a folder+ // with a space stays one word. Single quotes on sh (nothing inside expands), double quotes on cmd.exe.+ const quote = (p) => (process.platform === "win32" ? `"${p}"` : `'${p.replace(/'/g, `'\\''`)}'`);+ const tool = (t) => `node ${quote(join(ENGINE, "tools", t))}`;+ // the marker that makes this folder a linked project: overlay.mjs puts its src/ in front of the engine's+ // only when this file is here, so another repo that happens to have a src/ never replaces engine files+ if (!existsSync(join(target, PROJECT_MARKER))) writeFileSync(join(target, PROJECT_MARKER), JSON.stringify({ linked: true, film, engine: ENGINE }, null, 2) + "\n");+ if (!existsSync(join(target, "package.json"))) writeFileSync(join(target, "package.json"), JSON.stringify({ name: film.toLowerCase(), private: true, type: "module", scripts: { still: `${tool("still.mjs")} ${film}`, render: `${tool("render.mjs")} ${film}`, framecheck: `${tool("framecheck.mjs")} ${film}`, ship: `${tool("ship.mjs")} ${film}` } }, null, 2) + "\n");+ console.log(`linked project ${target}\n src/canvas-core/${film}.ts, src/hosts/page-${film}.ts, tsconfig.json, package.json, ${PROJECT_MARKER}\n engine: ${ENGINE}\nnext (from ${target}):\n ${tool("still.mjs")} ${film} --out out/look.png\n ${tool("render.mjs")} ${film}\n ${tool("ship.mjs")} ${film}`);+ process.exit(0);+}const skip = opt.example ? new Set() : ownFilmFiles();mkdirSync(target, { recursive: true });diff --git a/skills/anidoodle/engine/tools/ship-e2e.mjs b/skills/anidoodle/engine/tools/ship-e2e.mjsnew file mode 100644index 0000000..2a247a6--- /dev/null+++ b/skills/anidoodle/engine/tools/ship-e2e.mjs@@ -0,0 +1,122 @@+#!/usr/bin/env node+// END-TO-END TESTS for ship.mjs on real rendered files: every check ship wires in has a case that must go+// red, and the green fixture must ship. Fixtures: src/canvas-core/fixtureShip.ts.+// fixtureShipGreen ships (every row PASS, NONE or FLAG), even renamed: its sidecar names it; every check+// looks (temperament, brand colours), and the two with nothing there say why (meta.checks.none)+// fixtureShipBlind the same beat with no temperament, brand colours, ledger, claims or budget: those rows+// FAIL (a check that cannot look), where they used to FLAG and ship printed PASS+// no sidecar a file with no sidecar is scanned with the film's own meta (temperament, allow)+// --every abc is refused (exit 2); 2 is a QUICK run, never PASS+// fixtureShipRed frame FAILs (reading time, density, end card twice, 14 px CTA); motion:slidecut FAILs+// fixtureShipLocked locks FAILs (an approved shot whose sha no render produces)+// fixtureShipTrack an external track: verify FAILs without the mix sidecar, track FAILs on music that+// stops early, sfx FAILs without a stem, cues FAILs without a sheet; with the pinned take+// the provenance passes, and soundcheck --sfx tells a pitched stem from a click stem+// gate the external-track exception holds the file to the pinned take (red without it)+// input an empty file and a renamed file with no sidecar are refused, never judged+// Everything is written under .tmp/ship-e2e/. node tools/ship-e2e.mjs+import { strict as assert } from "node:assert";+import { execFileSync, spawnSync } from "node:child_process";+import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createHash } from "node:crypto";+import { resolve } from "node:path";++const dir = resolve(".tmp/ship-e2e"); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true });+let pass = 0; const ok = (label) => console.log(`PASS ${++pass} ${label}`);+const node = (args) => spawnSync(process.execPath, args, { encoding: "utf8", maxBuffer: 1 << 27 });+const render = (film, name = film) => { const out = `${dir}/${name}.mp4`; execFileSync(process.execPath, ["tools/render.mjs", film, "--out", out], { stdio: "pipe" }); return out; };+const ship = (target, ...extra) => { const out = `${dir}/sheet-${pass}-${Math.abs(target.length)}`; const r = node(["tools/ship.mjs", target, "--out", out, ...extra]); let j = null; try { j = JSON.parse(readFileSync(`${out}/ship.json`, "utf8")); } catch { /* refused before any row */ } return { code: r.status, out: r.stdout + r.stderr, j, row: (step) => j?.rows.find((x) => x.step === step) }; };+const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]);+const sha = (f) => createHash("sha256").update(readFileSync(f)).digest("hex");++// ---- green: ships from a renamed file, through its sidecar+const green = render("fixtureShipGreen", "green-v3");+const g = ship(green);+assert.equal(g.j?.verdict, "PASS", g.out.split("\n").filter((l) => /FAIL/.test(l)).join("\n"));+assert.equal(g.row("motion:temperament").status, "PASS", JSON.stringify(g.row("motion:temperament"))); assert.equal(g.row("layers:translucent").status, "PASS", JSON.stringify(g.row("layers:translucent")));+assert.equal(g.row("review").status, "NONE"); assert.ok(/no critic/.test(g.row("review").detail), g.row("review").detail);+ok(`GREEN fixtureShipGreen ships from a renamed file (${g.j.rows.length} rows, none FAIL; temperament and brand colours looked)`);++// ---- blind: checks that cannot look FAIL (H3), never FLAG into a PASS+const bl = ship(render("fixtureShipBlind"), "--quick");+for (const step of ["motion:temperament", "layers:translucent", "review", "facts", "length"]) assert.equal(bl.row(step)?.status, "FAIL", `${step}: ${JSON.stringify(bl.row(step))}`);+assert.equal(bl.j.verdict, "FAIL");+ok("RED fixtureShipBlind: no temperament, brand colours, ledger, claims or budget: each row FAILS and the ship FAILS");++// ---- no sidecar (M5): the film's own meta reaches motionscan+copyFileSync(green, `${dir}/no-sidecar.mp4`);+const ns = ship("fixtureShipGreen", "--file", `${dir}/no-sidecar.mp4`, "--quick");+assert.equal(ns.row("motion:temperament")?.status, "PASS", JSON.stringify(ns.row("motion:temperament")));+ok("fixtureShipGreen with no sidecar: motionscan still judges the film's calm temperament (meta passed in, not N/A)");++// ---- --every (M2)+const ea = ship(green, "--every", "abc"); assert.equal(ea.code, 2, ea.out.slice(-300)); assert.ok(/--every/.test(ea.out));+const e2 = ship(green, "--every", "2"); assert.equal(e2.j?.verdict, "QUICK", e2.out.slice(-300)); assert.notEqual(e2.code, 0);+ok("RED ship --every abc is refused (exit 2); --every 2 is QUICK, never PASS");++// ---- red: frame and motion+const red = ship(render("fixtureShipRed", "brandLaunch-v12"), "--quick");+assert.equal(red.row("frame").status, "FAIL"); assert.ok(red.row("frame").lines.some((l) => /reading it takes 3\.3 s/.test(l)), "the 0.9 s reply hold");+assert.ok(red.row("frame").lines.some((l) => /14 px at 1080/.test(l)) && red.row("frame").lines.some((l) => /density/.test(l)), "tiny CTA and density");+assert.equal(red.row("motion:slidecut").status, "FAIL"); assert.equal(red.j.verdict, "FAIL");+ok("RED fixtureShipRed: frame FAILs (3.3 s reply held 0.9 s, density, 14 px CTA, card twice) and motion:slidecut FAILs");+const quick = ship(green, "--quick");+assert.equal(quick.j.verdict, "QUICK"); assert.notEqual(quick.code, 0);+ok("RED --quick never passes: the verdict is QUICK and the exit code is 1");++// ---- locks+const lk = ship(render("fixtureShipLocked"), "--quick");+assert.equal(lk.row("locks").status, "FAIL", JSON.stringify(lk.row("locks")));+ok("RED fixtureShipLocked: an approved shot that changed fails the locks row");++// ---- external track+const pic = render("fixtureShipTrack"), take = `${dir}/take.wav`;+ff(["-f", "lavfi", "-i", "anoisesrc=d=10:c=pink:a=0.25", "-af", "lowpass=f=3000", "-ar", "48000", "-ac", "2", take]);+assert.equal(node(["tools/track.mjs", "import", take, "--provider", "fixture", "--cost", "0", "--licence", "test only"]).status, 0, "track import");+const short = `${dir}/track-short.mp4`; ff(["-i", pic, "-i", take, "-t", "10", "-af", "atrim=0:6,apad=whole_dur=10", "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "256k", short]);+copyFileSync(`${pic}.film.json`, `${short}.film.json`); const sc = JSON.parse(readFileSync(`${short}.film.json`, "utf8")); sc.sha256 = sha(short); writeFileSync(`${short}.film.json`, JSON.stringify(sc));+const t1 = ship(short, "--quick");+assert.equal(t1.row("verify").status, "FAIL"); assert.ok(t1.row("verify").lines.some((l) => /pinned|mix sidecar/.test(l)), JSON.stringify(t1.row("verify")));+assert.equal(t1.row("track").status, "FAIL"); assert.equal(t1.row("sfx").status, "FAIL"); assert.equal(t1.row("cues").status, "FAIL");+ok("RED fixtureShipTrack: no mix sidecar (verify), music stopping at 6 s of 10 (track), no effects stem (sfx), no cue sheet (cues): all FAIL");+const full = `${dir}/track-full.mp4`; ff(["-i", pic, "-i", take, "-t", "10", "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "256k", full]);+copyFileSync(`${pic}.film.json`, `${full}.film.json`); const sf = JSON.parse(readFileSync(`${full}.film.json`, "utf8")); sf.sha256 = sha(full); writeFileSync(`${full}.film.json`, JSON.stringify(sf));+// the mix record names the cue sheet it was made from (sidecar.mjs trackProvenance: a stale effects mix fails)+const cueSheet = `${dir}/fixtureShipTrack.cues.json`; writeFileSync(cueSheet, JSON.stringify({ film: "fixtureShipTrack", fps: 30, durationFrames: 300, durationS: 10, cues: [] }));+writeFileSync(`${full}.mix.json`, JSON.stringify({ music: take, musicSha256: sha(take), cues: cueSheet, cuesSha256: sha(cueSheet), quiet: [] }));+const pitched = `${dir}/stem-pitched.wav`, clicks = `${dir}/stem-clicks.wav`;+ff(["-f", "lavfi", "-i", "sine=f=440:d=0.4", "-af", "apad=pad_dur=1.6,aloop=loop=4:size=96000", "-ar", "48000", "-ac", "2", "-t", "10", pitched]);+ff(["-f", "lavfi", "-i", "anoisesrc=d=0.015:c=white:a=0.9", "-af", "apad=pad_dur=1.985,aloop=loop=4:size=96000", "-ar", "48000", "-ac", "2", "-t", "10", clicks]);+const t2 = ship(full, "--quick", "--sfx", pitched), t3 = ship(full, "--quick", "--sfx", clicks);+assert.ok(!t2.row("verify").lines.some((l) => /pinned take/.test(l)), `provenance passes with the pinned take: ${JSON.stringify(t2.row("verify"))}`);+assert.ok(t2.row("sound").lines.some((l) => /pitch|note/i.test(l)), `the pitched stem is caught: ${JSON.stringify(t2.row("sound"))}`);+assert.ok(!t3.row("sound").lines.some((l) => /effects pitch|carry a note|carry notes/i.test(l)), `the click stem is not: ${JSON.stringify(t3.row("sound"))}`);+ok("fixtureShipTrack: the mix from the pinned take passes provenance; soundcheck --sfx fails a 440 Hz stem and passes a click stem");++const gs = node(["tools/gate.mjs", "fixtureShipTrack", "--mp4", short]), gf = node(["tools/gate.mjs", "fixtureShipTrack", "--mp4", full]);+assert.equal(gs.status, 1, gs.stdout.slice(-400)); assert.equal(gf.status, 0, gf.stdout.slice(-400)); assert.ok(/EXTERNAL TRACK/.test(gf.stdout));+ok("gate on an external-track film: FAIL with no mix sidecar, PASS when the mix comes from the pinned take");++// ---- input+writeFileSync(`${dir}/empty.mp4`, "");+const e = ship("fixtureShipGreen", "--file", `${dir}/empty.mp4`);+assert.equal(e.row("input").status, "FAIL"); assert.equal(e.j.verdict, "FAIL");+ok("RED an empty file is a FAIL row, never judged");+copyFileSync(green, `${dir}/renamed.mp4`);+const rn = node(["tools/ship.mjs", `${dir}/renamed.mp4`]);+assert.equal(rn.status, 2); assert.ok(/--file/.test(rn.stderr), rn.stderr);+ok("RED a renamed file with no sidecar is refused with the --file form to run");+// ---- a linked project (scaffold --linked, X4) whose photo has not arrived yet (placeholders, X11)+{+ const proj = `${dir}/linked`, E = resolve("."), run = (args, env = {}) => spawnSync(process.execPath, args, { cwd: proj, encoding: "utf8", env: { ...process.env, ...env }, maxBuffer: 1 << 27 });+ assert.equal(node(["tools/scaffold.mjs", proj, "--linked", "--film", "promoFilm", "--duration", "2", "--format", "16x9"]).status, 0);+ const mod = `${proj}/src/canvas-core/promoFilm.ts`; writeFileSync(mod, readFileSync(mod, "utf8").replace("assets: { images: {} }", 'assets: { images: { speaker: "photos/speaker.png" } }'));+ const refused = run([`${E}/tools/still.mjs`, "promoFilm", "--frame", "0", "--out", "out/a.png"]);+ assert.notEqual(refused.status, 0, "a missing photo stops the build without placeholders");+ const ph = run([`${E}/tools/render.mjs`, "promoFilm", "--out", "out/promo.mp4"], { ANIDOODLE_PLACEHOLDERS: "1" });+ assert.equal(ph.status, 0, ph.stdout.slice(-600) + ph.stderr.slice(-600));+ const v = run([`${E}/tools/verify-export.mjs`, "out/promo.mp4", "--delivery"], { ANIDOODLE_PLACEHOLDERS: "1" });+ assert.equal(v.status, 1); assert.ok(/placeholder asset/.test(v.stdout), v.stdout.slice(-800));+ ok("linked project: its film renders from the engine with no copy; a missing photo renders as a labelled placeholder and --delivery refuses the file");+}+console.log(`\nSHIP-E2E: PASS ${pass} cases`);diff --git a/skills/anidoodle/engine/tools/ship.mjs b/skills/anidoodle/engine/tools/ship.mjsnew file mode 100644index 0000000..b092d7f--- /dev/null+++ b/skills/anidoodle/engine/tools/ship.mjs@@ -0,0 +1,181 @@+// SHIP. The one command a film passes before anyone is shown it, for ANY film (hand-built or template),+// on the exact file that will be delivered. On a brand launch film nine versions reached the director with no+// check at all, and the checks that did run passed while blind (reading time "N/A", verify-export unable+// to resolve a renamed file). Ship runs every check on the file, prints one table and writes a critic-+// ready sheet. Its rule: a check that cannot look is a FAIL, never a pass.+//+// node tools/ship.mjs <film|file.mp4> [--file out/x.mp4] [--shapes 16x9,9x16 [--file out/x-{shape}.mp4]]+// [--every 1] [--zones warn] [--quick] [--sfx stem.wav]+// [--review reviews/<film>.json] [--out <dir>]+//+// input the file exists, is not empty, decodes; its sidecar (render's <file>.film.json) names this+// film and covers the whole film (a range render never ships)+// frame framecheck: edges, reading time on every drawn text, safe zones, layout, the last second,+// the end card landing once, head sizes, fonts (framerules.mjs)+// verify verify-export --delivery on the file: size, frames, duration, score, sync, true peak,+// loudness, a legible frame 0, no placeholder assets+// gate determinism, the contract scan, dead air on the file (skipped only with --quick, and then+// the verdict is QUICK, never PASS)+// motion motionscan on the file (slide cuts, carousels, dissolves, temperament) and layerscan on the+// film (exit residue, fast type, shapes over faces, translucent brand colour), lock (approved+// shots unchanged): Lane MOTION's scanners, one row per check; a check that reports N/A did not look+// and FAILS, unless the film names why there is nothing to check in meta.checks.none (then NONE)+// sound the engine's score: soundcheck on the file. An external track (meta.checks.music.track):+// track.mjs check on the file (holes, the ending against the track's own last note) and+// soundcheck --sfx <stem> (effects carry no pitch under someone else's music); verify-export+// checks the mix came from the pinned take. cues --check whenever the film declares cues+// facts every claim the film declares is in its facts ledger with a source+// review reviews/<film>.json: an open P0 from a critic fails; open P1s are listed; the person's last+// three notes are printed to re-read against the new sheet+// length meta.checks.length: over max fails, over target flags, and the reading floor is printed+// sheet <file>.ship/sheet.jpg beside the file (a frame every 2 s, every shot start, the last frame),+// SHIP.md and ship.json: the table to attach whenever a version is shown+// A check that cannot look (no temperament, no brand colours, no review ledger, no length budget, text with+// no claims) FAILS; a film that truly has nothing there declares it, with a reason, in meta.checks.none+// { "<row>": "<reason>" }, and the row is NONE with the reason printed. --every above 1 is a QUICK run.+// Exit 0 PASS, 1 FAIL (or QUICK), 2 bad input.+import { spawnSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { isMain } from "./is-main.mjs";+import { knownFilms, requireFilm, SHAPE_NAMES } from "./names.mjs";+import { filmOfFile, readSidecar } from "./sidecar.mjs";+import { frameCheck, frameReport } from "./framecheck.mjs";+import { blindRow, lengthRow, reviewRows, row, scannerRows, sheetFrames, shipEvery, verdict } from "./shiprules.mjs";++const TOOLS = dirname(fileURLToPath(import.meta.url));+const USAGE = "node tools/ship.mjs <film|file.mp4> [--file out/x.mp4] [--shapes 16x9,9x16] [--every 1] [--zones warn] [--quick] [--review reviews/<film>.json] [--out dir]";+++/** Run a tool, read its verdict from the exit code. A tool that could not run (exit 2, or missing) is a FAIL. */+export const runTool = (script, args, { label = script, none = /\bN\/A\b/ } = {}) => {+ const path = join(TOOLS, script);+ if (!existsSync(path)) return row(label, "FAIL", `tools/${script} is not installed: this check cannot look, so it fails`);+ const r = spawnSync(process.execPath, [path, ...args], { encoding: "utf8", maxBuffer: 1 << 27 });+ const out = `${r.stdout ?? ""}${r.stderr ?? ""}`, lines = out.split("\n"), verdict = [...lines].reverse().find((l) => /^[A-Z][A-Z-]+:\s/.test(l.trim())) ?? lines.filter(Boolean).pop() ?? "";+ const fails = lines.filter((l) => /^\s*FAIL\b/.test(l)).map((l) => l.trim());+ if (r.status === 0) return row(label, none.test(verdict) ? "NONE" : "PASS", verdict.trim());+ if (r.status === 1) return row(label, "FAIL", verdict.trim(), fails.length ? fails : lines.filter(Boolean).slice(-6));+ return row(label, "FAIL", `could not run (exit ${r.status}): ${out.trim().split("\n").slice(-2).join(" ")}`);+};++/**+ * A scanner from another lane, run in-process: one row per check it reports (shiprules.mjs scannerRows).+ * FAIL fails, PASS passes, NONE (looked, nothing there) is NONE, and N/A (did not look) FAILS unless the+ * film declares why there is nothing to check (meta.checks.none). A scanner that is missing or throws is a+ * FAIL row: a check that cannot look is not a pass.+ */+export const scanner = async (label, script, fn, printer, call, shape, meta = null) => {+ const path = join(TOOLS, script);+ if (!existsSync(path)) return [row(label, "FAIL", `tools/${script} is not installed: this check cannot look, so it fails`)];+ // a file URL, never a bare path: on Windows C:\\... is not a module specifier, and every scanner row failed there+ let mod, r; try { mod = await import(pathToFileURL(path).href); r = await call(mod[fn]); } catch (e) { return [row(label, "FAIL", `${script} could not run: ${String(e.message ?? e).split("\n")[0]}`)]; }+ if (shape) return shape(r);+ const printed = []; if (printer && mod[printer]) { const log = console.log; console.log = (...a) => printed.push(a.join(" ")); try { mod[printer](r); } finally { console.log = log; } }+ return scannerRows(label, r, meta, printed.filter((l) => /^\s*FAIL\b/.test(l)).map((l) => l.trim()));+};++const audioStreams = (file) => { const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0", file], { encoding: "utf8" }); return r.status === 0 ? r.stdout.split("\n").filter(Boolean).length : -1; };+const videoFrames = (file) => { const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=codec_name", "-of", "csv=p=0", file], { encoding: "utf8" }); return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null; };++/** Every check on one (film, file). -> { rows, meta } */+export const shipOne = async (film, file, o = {}) => {+ const rows = [];+ // ---- input: never judge an empty or wrong file+ if (!existsSync(file)) return { rows: [row("input", "FAIL", `${file} does not exist: render it first (node tools/render.mjs ${film})`)] };+ if (statSync(file).size === 0) return { rows: [row("input", "FAIL", `${file} is empty (0 bytes): an empty input is never a pass`)] };+ const codec = videoFrames(file); if (!codec) return { rows: [row("input", "FAIL", `${file} has no decodable video stream`)] };+ const sc = readSidecar(file);+ if (sc?.error) rows.push(row("input", "FAIL", sc.error));+ else if (sc && sc.film !== film) rows.push(row("input", "FAIL", `${basename(file)} was rendered from '${sc.film}' (its sidecar), not '${film}'`));+ else if (sc?.stale) rows.push(row("input", "FAIL", `${basename(file)} changed after render wrote its sidecar: re-render it`));+ else rows.push(row("input", "PASS", `${basename(file)} (${codec}, ${(statSync(file).size / 1e6).toFixed(1)} MB)${sc ? ", sidecar matches" : ", no sidecar (an older render): the film is the one named"}`));++ // ---- frame+ let fc; try { fc = await frameCheck(film, { every: o.every ?? 1 }); } catch (e) { rows.push(row("frame", "FAIL", `the film did not draw: ${String(e.message ?? e).split("\n")[0]}${/one shape/.test(String(e.message)) ? " (a hand-built film takes --shapes once it has film.reshape: compose each shape from one timeline, never a crop)" : ""}`)); return { rows }; }+ const meta = fc.meta, rep = frameReport(film, fc, { warnZones: o.zones === "warn" });+ if (sc?.frames && Array.isArray(sc.frames) && (sc.frames[0] !== 0 || sc.frames[1] !== meta.durationFrames)) rows.push(row("input", "FAIL", `a range render (frames ${sc.frames.join("-")} of ${meta.durationFrames}) cannot ship`));+ rows.push(row("frame", rep.fails ? "FAIL" : "PASS", rep.lines[rep.lines.length - 1].replace(/^FRAMECHECK:\s*/, ""), rep.lines.filter((l) => /^\s+(FAIL|FLAG)\b/.test(l)).map((l) => l.trim())));+ if (meta.placeholders?.length) rows.push(row("assets", "FAIL", `placeholder asset(s): ${meta.placeholders.join(", ")}`));++ // ---- the file+ rows.push(runTool("verify-export.mjs", [film, "--file", file, "--delivery"], { label: "verify" }));+ if (o.quick) rows.push(row("gate", "FLAG", "skipped (--quick): determinism, contract and dead air not run, so this run cannot pass"));+ else rows.push(runTool("gate.mjs", [film, "--mp4", file], { label: "gate" }));+ // Lane MOTION's scanners, one row per check: N/A comes back as FLAG with its reason (listed, never a pass)+ // the film's own meta goes to motionscan: a file with no sidecar (an older render, track.mjs master) used to+ // be scanned with no temperament and no meta.motion.allow, so declared cuts and fades failed falsely+ rows.push(...await scanner("motion", "motionscan.mjs", "motionScan", "printScan", (m) => m(file, { meta }), null, meta));+ rows.push(...await scanner("layers", "layerscan.mjs", "layerScan", "printLayers", (m) => m(film), null, meta));+ rows.push(...await scanner("locks", "lock.mjs", "checkLocks", null, (m) => m(film), (r) => (r.none ? [row("locks", "NONE", "no approved shots yet (meta.motion.approved): lock one with lock.mjs --shot <id> once the person approves it")] : [row("locks", r.fail ? "FAIL" : "PASS", `${r.checked.length} approved shot(s)`, r.checked.filter((c) => c.status !== "same").map((c) => `${c.status === "unlocked" ? "FLAG" : "FAIL"} ${c.shot} (${c.note}) ${c.status}`))])));+ // sound: the engine's own score, or an external track (meta.checks.music.track: Lane SOUND's route)+ const na = audioStreams(file), ext = meta.checks?.music?.track, base = film.replace(/-(16x9|1x1|4x5|9x16)$/, "");+ if (na < 0) rows.push(row("sound", "FAIL", "ffprobe could not read the audio streams"));+ else if (na === 0) rows.push(meta.hasAudio || ext ? row("sound", "FAIL", "the film has music but the file has no audio stream") : row("sound", "NONE", "no audio stream, and the film declares no score (verify checks the same)"));+ else if (ext) {+ rows.push(runTool("track.mjs", ["check", file], { label: "track" }));+ if (!o.sfx) rows.push(row("sfx", "FAIL", "an external track needs its effects stem measured for pitch: pass --sfx <stem.wav> (track.mjs mix --stem wrote it)"));+ else rows.push(runTool("soundcheck.mjs", [file, "--sfx", o.sfx], { label: "sound" }));+ } else rows.push(runTool("soundcheck.mjs", [file], { label: "sound" }));+ // cues: a film that declares cues must have its sheet exported and current (the mix reads it)+ let cuesDeclared = false; try { const { loadFilm } = await import("./captions.mjs"); cuesDeclared = ((await loadFilm(base)).cues ?? []).length > 0; } catch { /* the facts row below reports a film that will not load */ }+ const cueSheet = resolve(`out/${base}.cues.json`);+ if (existsSync(cueSheet)) rows.push(runTool("cues.mjs", [base, "--check", cueSheet], { label: "cues" }));+ else if (cuesDeclared || ext) rows.push(row("cues", "FAIL", `the film's cue sheet ${cueSheet} is missing: export it with node tools/cues.mjs ${base} (the mix and the sync are cued from it)`));++ // ---- the film's own records+ try {+ const { loadFilm } = await import("./captions.mjs"), { checkFacts, claimsOf } = await import("./factsrules.mjs"), { factsFile, readFacts } = await import("./facts.mjs");+ const fx = readFacts(factsFile(film)), res = fx.error ? { status: "FAIL", checked: 0, problems: [{ claim: "(facts.json)", why: fx.error }] } : checkFacts(claimsOf(await loadFilm(film)), fx.facts);+ const drawn = fc.auto.cues.length;+ rows.push(res.status === "N/A" ? (drawn ? blindRow(meta, "facts", `the film declares no claims (film.claims) but draws ${drawn} text cue(s): list every claim with its source (references/workflows/facts.md)`) : row("facts", "NONE", "the film declares no claims and draws no text")) : row("facts", res.status, `${res.checked} claim(s)`, res.problems.map((p) => `FAIL "${String(p.claim).slice(0, 60)}" ${p.why}`)));+ } catch (e) { rows.push(row("facts", "FAIL", `could not read the film's claims: ${e.message}`)); }+ { const rp = resolve(o.review ?? `reviews/${film.replace(/-(16x9|1x1|4x5|9x16)$/, "")}.json`); let j = null, err = null; if (existsSync(rp)) try { j = JSON.parse(readFileSync(rp, "utf8")); } catch (e) { err = e.message; } rows.push(...reviewRows(j, rp, err, meta)); }+ rows.push(lengthRow(meta, fc.auto.cues.length ? fc.floor : null));++ // ---- the critic sheet+ if (o.out) {+ mkdirSync(o.out, { recursive: true });+ const fr = sheetFrames(meta), sheet = join(o.out, "sheet.jpg");+ const st = spawnSync(process.execPath, [join(TOOLS, "still.mjs"), film, "--frames", fr.join(","), "--out", join(o.out, "frames", "f-{frame}.png"), "--sheet", sheet], { encoding: "utf8", maxBuffer: 1 << 26 });+ rows.push(row("sheet", st.status === 0 && existsSync(sheet) ? "PASS" : "FAIL", st.status === 0 ? `${sheet} (${fr.length} frames: every 2 s, every shot start, the last frame)` : `still.mjs failed: ${(st.stderr || st.stdout).trim().split("\n").pop()}`));+ }+ return { rows, meta, frame: rep.lines };+};++const table = (name, rows) => [`SHIP ${name}`, ...rows.flatMap((r) => [` ${r.step.padEnd(18)} ${r.status.padEnd(5)} ${r.detail}`, ...r.lines.slice(0, 12).map((l) => ` ${l}`), ...(r.lines.length > 12 ? [` ... ${r.lines.length - 12} more`] : [])])];++if (isMain(import.meta.url)) {+ const pos = [], opt = {}, FLAGS = new Set(["quick"]);+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) { const k = a.slice(2); opt[k] = FLAGS.has(k) ? true : process.argv[++i]; } else pos.push(a); }+ if (!pos[0]) { console.error(`usage: ${USAGE}`); process.exit(2); }+ let film = pos[0];+ if (/\.(mp4|mov|m4v)$/i.test(film)) { if (opt.file) { console.error("ship: give the file once"); process.exit(2); } opt.file = film; const who = filmOfFile(film, knownFilms()); if (!who.film) { console.error(`ship: ${who.why.replace("verify-export.mjs", "ship.mjs")}`); process.exit(2); } film = who.film; }+ requireFilm(film, "ship", USAGE);+ if (opt.zones !== undefined && !["fail", "warn"].includes(opt.zones)) { console.error(`ship: --zones is fail or warn, got '${opt.zones}'`); process.exit(2); }+ // --every: checked here, before any row (abc used to reach framecheck as NaN and check frame 0 alone); above 1 the run is QUICK+ let ev; try { ev = shipEvery(opt.every); } catch (e) { console.error(`ship: ${e.message}\nusage: ${USAGE}`); process.exit(2); }+ const quick = !!opt.quick || ev.quick;+ const shapes = opt.shapes ? String(opt.shapes).split(",").map((s) => s.trim()).filter(Boolean) : [null];+ const badShape = shapes.filter((s) => s && !SHAPE_NAMES.includes(s)); if (badShape.length) { console.error(`ship: --shapes wants ${SHAPE_NAMES.join(", ")}, got '${opt.shapes}'`); process.exit(2); }+ const results = [];+ for (const sh of shapes) {+ const f = sh ? `${film}-${sh}` : film, file = resolve(opt.file ? String(opt.file).replace("{shape}", sh ?? "") : `out/${f}.mp4`);+ if (sh && opt.file && !String(opt.file).includes("{shape}") && shapes.length > 1) { console.error("ship: with several --shapes, --file needs {shape} in it (out/x-{shape}.mp4)"); process.exit(2); }+ const out = resolve(opt.out ? String(opt.out).replace("{shape}", sh ?? "") + (sh && !String(opt.out).includes("{shape}") ? `-${sh}` : "") : join(dirname(file), `${basename(file).replace(/\.[^.]+$/, "")}.ship`));+ console.log(`\n==================== ${f} ${file}`);+ const r = await shipOne(f, file, { every: ev.every, zones: opt.zones, quick: !!opt.quick, review: opt.review, sfx: opt.sfx ? resolve(String(opt.sfx).replace("{shape}", sh ?? "")) : undefined, out });+ const v = verdict(r.rows, quick), t = table(f, r.rows);+ console.log(t.join("\n")); console.log(`SHIP ${f}: ${v}`);+ { mkdirSync(out, { recursive: true }); // the table is written even when the input was refused: that refusal is the record+ writeFileSync(join(out, "ship.json"), JSON.stringify({ film: f, file, verdict: v, rows: r.rows }, null, 1) + "\n");+ writeFileSync(join(out, "SHIP.md"), [`# Ship: ${f}`, "", `File: \`${file}\` `, `Verdict: **${v}**`, "", "| check | status | detail |", "|---|---|---|", ...r.rows.map((x) => `| ${x.step} | ${x.status} | ${x.detail.replace(/\|/g, "/")} |`), "", "## Findings", "", ...r.rows.flatMap((x) => x.lines.map((l) => `- ${x.step}: ${l}`)), "", "", ""].join("\n"));+ console.log(`critic sheet and table: ${join(out, "SHIP.md")}`);+ }+ results.push(v);+ }+ const all = results.every((v) => v === "PASS") ? "PASS" : results.includes("FAIL") ? "FAIL" : "QUICK";+ console.log(`\nSHIP: ${all}${all === "QUICK" ? ` (${opt.quick ? "--quick skips the gate" : `--every ${ev.every} checks every ${ev.every}th frame`}: run without it before showing anyone)` : ""}`);+ process.exit(all === "PASS" ? 0 : all === "FAIL" ? 1 : 1);+}diff --git a/skills/anidoodle/engine/tools/shiprules.mjs b/skills/anidoodle/engine/tools/shiprules.mjsnew file mode 100644index 0000000..7f9d898--- /dev/null+++ b/skills/anidoodle/engine/tools/shiprules.mjs@@ -0,0 +1,90 @@+// SHIP RULES. The parts of ship.mjs that decide, as pure functions (rows in, verdict out), so each is+// unit-tested with a case that must fail: the review ledger, the length budget, the critic sheet's+// frames and the verdict itself.+//+// reviews/<film>.json, the review ledger a critic writes and ship reads:+// { "findings": [{ "id": "r1-4", "p": "P0", "status": "open" | "fixed" | "wontfix", "note": "...", "by": "critic r1" }],+// "notes": [{ "at": "2026-10-27 21:36", "from": "the director", "text": "who is gonna read this overload of info?" }] }++/** One row of the table. status: PASS, FAIL, NONE (checked, nothing there, with the evidence), FLAG (looked, review it). */+export const row = (step, status, detail, lines = []) => ({ step, status, detail, lines });++// A CHECK THAT CANNOT LOOK FAILS. When a check has nothing to judge against (no temperament, no brand+// colours, no review ledger, no length budget) it did not look, and that is a FAIL, never a FLAG that+// passes: six such rows once added up to SHIP: PASS. A film that truly has nothing there says so, with a+// reason, in meta.checks.none: { "<row>": "<reason>" }, e.g. { "review": "a test fixture nobody is shown" }.+// That row is then NONE and the reason is printed in the table for the reader to judge.++/** The film's declared reason that a check has nothing to look at (meta.checks.none[step]), or null. */+export const waiver = (meta, step) => { const r = meta?.checks?.none?.[step]; return typeof r === "string" && r.trim() ? r.trim() : null; };+/** The row of a check that could not look: FAIL, or NONE with the film's declared reason. */+export const blindRow = (meta, step, why, lines = []) => {+ const r = waiver(meta, step);+ return r ? row(step, "NONE", `not checked, declared in meta.checks.none: ${r}`, lines) : row(step, "FAIL", `${why}: this check cannot look, so it fails (declare meta.checks.none["${step}"] = "<reason>" only when there is truly nothing to check)`, lines);+};+/**+ * A scanner's checks as rows (motionscan, layerscan): PASS and FAIL as they are, NONE (looked, nothing there)+ * as NONE, N/A (did not look) as a blind row. Any other status is a FAIL: it is not one ship knows.+ */+export const scannerRows = (label, r, meta, fails = []) => {+ let given = false;+ return Object.entries(r.checks ?? {}).map(([name, c]) => {+ const step = `${label}:${name}`, lines = c.status === "FAIL" && !given ? ((given = true), fails) : []; // the printer's findings go under the first failing check+ if (c.status === "N/A") return blindRow(meta, step, `did not look: ${c.reason}`);+ if (c.status === "NONE") return row(step, "NONE", c.reason ?? "nothing there to check");+ if (c.status === "PASS") return row(step, "PASS", "clean");+ if (c.status === "FAIL") return row(step, "FAIL", `${name} failed`, lines);+ return row(step, "FAIL", `unknown status '${c.status}' from the scanner`);+ });+};+/** ship --every: a whole number of frames, 1 or more. Above 1 it is a quick look (holds measured in steps), so the verdict is QUICK. */+export const shipEvery = (v) => {+ const n = v === undefined ? 1 : Number(v);+ if (!Number.isInteger(n) || n < 1) throw new Error(`--every wants a whole number of frames, 1 or more; got '${v}'`);+ return { every: n, quick: n > 1 };+};++/** The review ledger (R2/R3/R4): critic findings with a priority and a status, and the person's notes, verbatim. */+export const reviewRows = (j, path, err = null, meta = null) => {+ if (err) return [row("review", "FAIL", `${path} is not valid JSON: ${err}`)];+ if (!j) return [blindRow(meta, "review", `no ${path}: no critic findings recorded for this version (review.md: run a fresh critic and record its P0/P1 list there)`)];+ // the ledger's shape, before any of it is read: a wrong shape is a FAIL row, never a crash with no SHIP.md+ const shape = typeof j !== "object" || Array.isArray(j) ? "the ledger is not an object"+ : j.findings !== undefined && (!Array.isArray(j.findings) || j.findings.some((f) => !f || typeof f !== "object" || Array.isArray(f))) ? "findings is not a list of objects"+ : j.notes !== undefined && (!Array.isArray(j.notes) || j.notes.some((n) => !n || typeof n !== "object")) ? "notes is not a list of objects" : null;+ if (shape) return [row("review", "FAIL", `${path}: ${shape} ({ "findings": [{ "id", "p", "status", "note" }], "notes": [{ "at", "from", "text" }] })`)];+ const open = (j.findings ?? []).filter((f) => (f.status ?? "open") === "open"), p0 = open.filter((f) => f.p === "P0"), p1 = open.filter((f) => f.p === "P1");+ const out = [row("review", p0.length ? "FAIL" : p1.length ? "FLAG" : "PASS", `${(j.findings ?? []).length} finding(s) recorded, ${p0.length} open P0, ${p1.length} open P1`, [...p0, ...p1].map((f) => `${p0.includes(f) ? "FAIL" : "FLAG"} ${f.p} ${f.id ?? ""} ${f.note ?? ""}`.trim()))];+ const notes = (j.notes ?? []).slice(-3);+ if (notes.length) out.push(row("notes", "FLAG", `the person's last ${notes.length} note(s): re-read each against the new sheet before showing it`, notes.map((n) => `${n.at ?? ""} ${n.from ?? ""}: "${n.text}"`.trim())));+ return out;+};++/** Length against meta.checks.length (D1), seconds. */+export const lengthRow = (meta, floor) => {+ const s = meta.durationFrames / meta.fps, L = meta.checks?.length, f = floor ? `; reading needs ${floor.floorS.toFixed(1)} s of it, text holds ${floor.spareS.toFixed(1)} s beyond reading` : "";+ const shots = (meta.shots ?? []).map((x) => `${x.id} ${((x.end - x.start) / meta.fps).toFixed(1)} s`).join(", ");+ const sh = shots ? [`shots: ${shots}`] : [];+ if (!L) return blindRow(meta, "length", `${s.toFixed(1)} s, no length budget (meta.checks.length { target, max })${f}`, sh);+ // a budget needs a number to judge against: max, else the target stands in for it (a budget with no max never failed)+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0, max = num(L.max) ? L.max : num(L.target) ? L.target : null, target = num(L.target) ? L.target : max;+ if (max === null) return row("length", "FAIL", `${s.toFixed(1)} s, the length budget has no number to judge against: give meta.checks.length { target, max } in seconds${f}`, sh);+ return row("length", s > max ? "FAIL" : s > target ? "FLAG" : "PASS", `${s.toFixed(1)} s against target ${target} s, max ${max} s${num(L.max) ? "" : " (no max: the target is the limit)"}${f}`, sh);+};++/** The frames of the critic sheet: one every 2 s, every shot start, the last frame (at most 60). */+export const sheetFrames = (meta) => {+ const N = meta.durationFrames, step = Math.max(1, Math.round(2 * meta.fps)), set = new Set([0, N - 1]);+ for (let f = 0; f < N; f += step) set.add(f); for (const s of meta.shots ?? []) set.add(s.start);+ let fr = [...set].filter((f) => f >= 0 && f < N).sort((a, b) => a - b);+ if (fr.length > 60) { const k = fr.length / 60; fr = Array.from({ length: 60 }, (_, i) => fr[Math.floor(i * k)]); fr[59] = N - 1; }+ return fr;+};++/**+ * PASS only when every row is PASS, NONE (checked, absent, with evidence) or FLAG (looked, review it); a row+ * with any other status fails. QUICK when the run was a quick look (--quick, or --every above 1).+ */+const KNOWN = new Set(["PASS", "NONE", "FLAG"]);+export const verdict = (rows, quick) => (rows.some((r) => !KNOWN.has(r.status)) ? "FAIL" : quick ? "QUICK" : "PASS");+diff --git a/skills/anidoodle/engine/tools/sidecar.mjs b/skills/anidoodle/engine/tools/sidecar.mjsnew file mode 100644index 0000000..f99d3b5--- /dev/null+++ b/skills/anidoodle/engine/tools/sidecar.mjs@@ -0,0 +1,57 @@+// SIDECAR. A rendered file says which film it is in <file>.film.json beside it, so a file that has been+// renamed or versioned (out/brandLaunch-v12.mp4 from the film brandHook) still resolves. On a brand launch film verify-export inferred the film from the file name, failed with "unknown film+// 'brandFilm-v2-frozen'", and was never run again. Tools read the sidecar first, the name second.+// render.mjs writes it after the encode ({ film, file, sha256, frames: [from, to], scale, blur, poster, meta }).+// readSidecar(file) -> the record, or null when there is none+// filmOfFile(file, known) -> { film, how } | { film: null, why } (sidecar, then the name, then nothing)+import { createHash } from "node:crypto";+import { existsSync, readFileSync } from "node:fs";+import { basename } from "node:path";++export const sidecarPath = (file) => `${file}.film.json`;+const sha = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");++/** The sidecar beside `file`, with `stale: true` when the file changed after it was written. */+export const readSidecar = (file) => {+ const p = sidecarPath(file); if (!existsSync(p)) return null;+ try { const rec = JSON.parse(readFileSync(p, "utf8")); return { ...rec, stale: existsSync(file) && rec.sha256 ? rec.sha256 !== sha(file) : false }; } catch (e) { return { error: `unreadable sidecar ${p}: ${e.message}` }; }+};++/** Which film a file is: its sidecar, else its name (out/<film>[.<from>-<to>].<ext>). `known` lists the films that exist. */+export const filmOfFile = (file, known) => {+ const sc = readSidecar(file);+ if (sc?.film) return { film: sc.film, how: sc.stale ? "sidecar (STALE: the file changed after render wrote it)" : "sidecar", sidecar: sc };+ const byName = basename(file).split(".")[0];+ if (known.includes(byName)) return { film: byName, how: "file name" };+ return { film: null, why: `'${basename(file)}' has no sidecar (${basename(sidecarPath(file))}) and its name is not a film. Name the film: node tools/verify-export.mjs <film> --file ${file}` };+};++/**+ * EXTERNAL MUSIC PROVENANCE (X3). A film whose music is a supplied or generated track declares the+ * track's manifest (meta.checks.music.track: the <take>.track.json that `track.mjs import` writes, with+ * its sha256, provider, cost and licence). The delivered file's mix sidecar (<file>.mix.json, written by+ * `track.mjs mix` and copied by `master`) must have been made from that take: its music is the take+ * itself, or a bar cut whose <cut>.cut.json names the take's sha256 as its source. The mix must also+ * have been made from the cue sheet as it is now (cuesSha256), so the effects are on the current frames.+ * -> { ok, detail }+ */+export const trackProvenance = (trackJson, file) => {+ if (!existsSync(trackJson)) return { ok: false, detail: `no track manifest ${trackJson}: pin the take with node tools/track.mjs import <take> --provider ...` };+ let man, mix; try { man = JSON.parse(readFileSync(trackJson, "utf8")); } catch (e) { return { ok: false, detail: `unreadable ${trackJson}: ${e.message}` }; }+ if (!man.sha256 || !man.provider) return { ok: false, detail: `${trackJson} has no sha256 or provider` };+ const mixJson = `${file}.mix.json`;+ if (!existsSync(mixJson)) return { ok: false, detail: `no mix sidecar ${basename(mixJson)}: master the file with node tools/track.mjs master <picture> <mix.wav> -o ${basename(file)}` };+ try { mix = JSON.parse(readFileSync(mixJson, "utf8")); } catch (e) { return { ok: false, detail: `unreadable ${mixJson}: ${e.message}` }; }+ // The effects in the mix land on the cue sheet it was made from: a sheet changed since then (or a mix+ // record that never named its sheet) is a stale mix, whatever the music says.+ if (!mix.cuesSha256 || !mix.cues) return { ok: false, detail: `${basename(mixJson)} names no cue sheet, so the effects in the mix cannot be checked: re-mix with node tools/track.mjs mix --cues out/<film>.cues.json` };+ if (!existsSync(mix.cues)) return { ok: false, detail: `the cue sheet the mix was made from (${basename(String(mix.cues))}) is gone: export it (node tools/cues.mjs <film>) and re-mix` };+ if (sha(mix.cues) !== mix.cuesSha256) return { ok: false, detail: `the cue sheet ${basename(String(mix.cues))} changed after the mix was made, so its effects land on the old frames: re-mix (node tools/track.mjs mix ...) and master again` };+ if (mix.musicSha256 === man.sha256) return { ok: true, detail: `the mix plays the pinned take itself (${man.provider}${man.licence ? `, ${man.licence}` : ""})` };+ const cutJson = `${mix.music}.cut.json`;+ if (!existsSync(cutJson)) return { ok: false, detail: `the mix's music ${basename(String(mix.music))} is not the pinned take and has no cut record (${basename(cutJson)})` };+ const cut = JSON.parse(readFileSync(cutJson, "utf8"));+ if (cut.sourceSha256 !== man.sha256) return { ok: false, detail: `the mix was cut from a different take (sha ${String(cut.sourceSha256).slice(0, 12)}, the manifest pins ${man.sha256.slice(0, 12)})` };+ if (existsSync(mix.music) && sha(mix.music) !== mix.musicSha256) return { ok: false, detail: `the cut ${basename(mix.music)} changed after the mix was made: re-mix` };+ return { ok: true, detail: `the mix plays a bar cut of the pinned take (${man.provider}${man.licence ? `, ${man.licence}` : ""}${man.costUsd != null ? `, $${man.costUsd}` : ""})` };+};diff --git a/skills/anidoodle/engine/tools/sound-unit.mjs b/skills/anidoodle/engine/tools/sound-unit.mjsnew file mode 100644index 0000000..46c14b5--- /dev/null+++ b/skills/anidoodle/engine/tools/sound-unit.mjs@@ -0,0 +1,124 @@+#!/usr/bin/env node+// Unit + end-to-end tests for the sound and project tools that need node's own modules, ffmpeg and real+// files: track.mjs master and listen, the mix sidecar's provenance, cues.mjs and scaffold.mjs from a+// folder whose path has a space, narrate's baked-module staleness and its PATH lookup, and overlay's+// linked-project rule. Each test was written red first, against the bug it names. Temp folder under+// out/, removed afterwards. No paid API is ever called.+// node tools/sound-unit.mjs+import { strict as assert } from "node:assert";+import { execFileSync, spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { chmodSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { delimiter, dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const ENGINE = join(dirname(fileURLToPath(import.meta.url)), ".."), TOOLS = join(ENGINE, "tools");+const root = join(ENGINE, "out", ".sound-unit"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true });+let n = 0, failed = 0;+const t = async (label, fn) => { try { await fn(); n++; console.log(` PASS ${label}`); } catch (e) { failed++; console.log(` FAIL ${label}\n ${String(e.message).split("\n").slice(0, 6).join("\n ")}`); } };+const node = (args, o = {}) => spawnSync(process.execPath, args, { encoding: "utf8", cwd: root, ...o });+const ff = (...a) => execFileSync("ffmpeg", ["-y", "-v", "error", ...a]);+const dur = (f) => Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", f]).toString().trim());+const sha = (f) => createHash("sha256").update(readFileSync(f)).digest("hex");+const tone = (f, s) => ff("-f", "lavfi", "-i", `sine=frequency=330:sample_rate=48000:duration=${s}`, "-af", "volume=0.3", "-ac", "2", f);+const isWin = process.platform === "win32";++try {+ // ---------------------------------------------------------------- track.mjs master (H5, M10)+ const pic = join(root, "picture.mp4"); ff("-f", "lavfi", "-i", "color=c=gray:s=64x36:r=30:d=6", "-c:v", "mpeg4", pic);+ const short = join(root, "short.wav"), full = join(root, "full.wav"), long = join(root, "long.wav"); tone(short, 4); tone(full, 6); tone(long, 8);+ const master = (mix, out) => node([join(TOOLS, "track.mjs"), "master", pic, mix, "-o", out]);+ await t("RED (H5): a 4 s mix under a 6 s picture is refused, and no file shorter than the picture is written", () => {+ const out = join(root, "h5.mp4"), r = master(short, out);+ assert.notEqual(r.status, 0, r.stdout); assert.match(r.stdout + r.stderr, /shorter than the picture/);+ assert.ok(!existsSync(out) || dur(out) >= 5.9, `a ${existsSync(out) ? dur(out).toFixed(2) : "?"} s file was written for a 6 s picture`);+ });+ await t("GREEN (H5): a mix as long as the picture masters to the full 6 s", () => { const out = join(root, "h5ok.mp4"), r = master(full, out); assert.equal(r.status, 0, r.stdout + r.stderr); assert.ok(Math.abs(dur(out) - 6) < 0.15, `${dur(out)} s`); });+ await t("H5: a mix longer than the picture is trimmed to the picture, never the other way round", () => { const out = join(root, "h5long.mp4"), r = master(long, out); assert.equal(r.status, 0, r.stdout + r.stderr); assert.ok(Math.abs(dur(out) - 6) < 0.15, `${dur(out)} s`); });+ await t("RED (M10): mastering again from a mix with no sidecar removes the old <out>.mix.json", () => {+ const out = join(root, "m10.mp4"), a = join(root, "a.wav"), b = join(root, "b.wav"); cpSync(full, a); cpSync(full, b);+ writeFileSync(a + ".mix.json", JSON.stringify({ music: "x", musicSha256: "old", quiet: [] }));+ master(a, out); assert.ok(existsSync(out + ".mix.json"), "the first master did not copy the sidecar");+ const r = master(b, out); assert.ok(!existsSync(out + ".mix.json"), "the previous mix's record is still beside the new file"); assert.match(r.stdout, /no mix sidecar/);+ });+ await t("RED (M5): master carries the picture's film sidecar to the output, re-hashed, so ship scans with the film's settings", async () => {+ const { readSidecar } = await import(pathToFileURL(join(TOOLS, "sidecar.mjs")).href);+ const p2 = join(root, "m5pic.mp4"), out = join(root, "m5.mp4"); cpSync(pic, p2);+ writeFileSync(p2 + ".film.json", JSON.stringify({ film: "m5Film", file: "m5pic.mp4", sha256: sha(p2), frames: [0, 180], meta: { fps: 30, motion: { temperament: "calm" } } }));+ const r2 = node([join(TOOLS, "track.mjs"), "master", p2, full, "-o", out]);+ assert.equal(r2.status, 0, r2.stdout + r2.stderr);+ const sc = readSidecar(out); assert.ok(sc, "no <out>.film.json beside the mastered file");+ assert.equal(sc.film, "m5Film"); assert.equal(sc.meta.motion.temperament, "calm"); assert.equal(sc.stale, false, "the sidecar still carries the picture's hash"); assert.equal(sc.file, "m5.mp4");+ });+ await t("master leaves no .master.wav temp file behind", () => assert.deepEqual(readdirSync(root).filter((f) => f.endsWith(".master.wav")), []));++ // ---------------------------------------------------------------- the mix sidecar names its cue sheet (H6)+ const { trackProvenance } = await import(pathToFileURL(join(TOOLS, "sidecar.mjs")).href);+ const take = join(root, "take.wav"); cpSync(full, take);+ const man = join(root, "take.wav.track.json"); writeFileSync(man, JSON.stringify({ sha256: sha(take), provider: "test" }));+ const cues = join(root, "film.cues.json"), file = join(root, "film.mp4"); writeFileSync(file, "x");+ writeFileSync(cues, JSON.stringify({ film: "film", fps: 30, durationFrames: 180, cues: [{ name: "hit", frame: 30, t: 1, sound: "tap:tock" }] }));+ const mixRec = (extra) => writeFileSync(file + ".mix.json", JSON.stringify({ music: take, musicSha256: sha(take), cues, cuesSha256: sha(cues), quiet: [], ...extra }));+ await t("GREEN (H6): a mix made from the current cue sheet passes provenance", () => { mixRec(); const p = trackProvenance(man, file); assert.ok(p.ok, p.detail); });+ await t("RED (H6): the cue sheet changed after the mix was made, so the effects are stale and provenance fails", () => {+ mixRec(); writeFileSync(cues, JSON.stringify({ film: "film", fps: 30, durationFrames: 180, cues: [{ name: "hit", frame: 60, t: 2, sound: "tap:tock" }] }));+ const p = trackProvenance(man, file); assert.ok(!p.ok, p.detail); assert.match(p.detail, /cue sheet/);+ });+ await t("RED (H6): a mix record with no cue sheet hash cannot be checked, so it fails", () => { mixRec({ cuesSha256: undefined }); const p = trackProvenance(man, file); assert.ok(!p.ok, p.detail); });+ await t("RED (H6): a mix whose cue sheet is gone fails", () => { mixRec(); rmSync(cues); const p = trackProvenance(man, file); assert.ok(!p.ok, p.detail); });++ // ---------------------------------------------------------------- track.mjs listen without a shell rm (M11)+ await t("RED (M11): listen runs with no rm on the PATH (as on Windows) and leaves no temp WAVs", () => {+ const dir = join(root, "listen"), r = node([join(TOOLS, "track.mjs"), "listen", dir, "--mix", full, "--at", "0", "--len", "2"], { env: { ...process.env, PATH: dirname(execFileSync(isWin ? "where" : "which", ["ffmpeg"]).toString().split(/\r?\n/)[0]) } });+ assert.equal(r.status, 0, r.stderr); assert.deepEqual(readdirSync(dir).filter((f) => f.endsWith(".wav")), []);+ });++ // ---------------------------------------------------------------- narrate (M6, M11)+ const { bakedStale } = await import(pathToFileURL(join(TOOLS, "narrate.mjs")).href);+ const timing = { totalFrames: 120, lines: [{ hash: "a".repeat(64) }] }, mod = (frames, hash = "a".repeat(64)) => `export const v = {"timing":{"totalFrames":${frames},"lines":[{"hash":"${hash}"}]}}`;+ await t("RED (M6): narrate all may re-bake after the script's length changed (ignoreStale covers frames too)", () => assert.equal(bakedStale(mod(100), timing, true), false));+ await t("M6: check still calls a module baked at another length stale", () => assert.equal(bakedStale(mod(100), timing, false), true));+ await t("M6: check still calls a module baked from other takes stale", () => assert.equal(bakedStale(mod(120, "b".repeat(64)), timing, false), true));+ await t("M6: a module baked from these takes at this length is current", () => assert.equal(bakedStale(mod(120), timing, false), false));+ const { which } = await import(pathToFileURL(join(TOOLS, "narrate", "providers", "util.mjs")).href);+ const bin = join(root, "bin dir"); mkdirSync(bin); const exe = join(bin, isWin ? "kokoro-x.cmd" : "kokoro-x"); writeFileSync(exe, isWin ? "@echo off\r\n" : "#!/bin/sh\n"); chmodSync(exe, 0o755);+ await t("RED (M11): which finds a program on PATH with no /usr/bin/env or which (a folder with a space)", () => { const was = process.env.PATH; process.env.PATH = bin; try { assert.equal(which("kokoro-x"), exe); } finally { process.env.PATH = was; } });+ await t("M11: which reads Windows PATHEXT, so kokoro-x finds kokoro-x.CMD", () => {+ const win = join(root, "win"); mkdirSync(win); writeFileSync(join(win, "whisper-cli.CMD"), "");+ assert.equal(which("whisper-cli", { path: [join(root, "nope"), win].join(delimiter), pathext: ".EXE;.CMD", win: true }), join(win, "whisper-cli.CMD"));+ });+ await t("M11: which says null for a program that is not there", () => assert.equal(which("no-such-program-xyz", { path: bin }), null));++ // ---------------------------------------------------------------- a copy of the engine in a folder with a space (M11, L9, L11)+ const spaced = join(root, "my engine", "engine"); mkdirSync(spaced, { recursive: true });+ for (const d of ["tools", "src"]) cpSync(join(ENGINE, d), join(spaced, d), { recursive: true });+ cpSync(join(ENGINE, "package.json"), join(spaced, "package.json"));+ await t("RED (M11): cues.mjs builds its cue module from an engine whose path has a space", async () => {+ const { loadCues } = await import(pathToFileURL(join(spaced, "tools", "cues.mjs")).href);+ const m = await loadCues(); assert.equal(typeof m.diffSheets, "function");+ });+ const proj = join(root, "my film project");+ await t("RED (L9): scaffold --linked quotes the engine path in package.json, so the scripts survive a space", () => {+ const r = node([join(spaced, "tools", "scaffold.mjs"), proj, "--linked", "--film", "spaceFilm"]); assert.equal(r.status, 0, r.stdout + r.stderr);+ const scripts = JSON.parse(readFileSync(join(proj, "package.json"), "utf8")).scripts;+ for (const [k, cmd] of Object.entries(scripts)) {+ assert.match(cmd, /^node /, k);+ if (isWin) { assert.match(cmd, /^node "[^"]+" spaceFilm$/, cmd); continue; }+ // npm runs a script through sh: the first word after node must be the whole tool path+ const words = execFileSync("sh", ["-c", `printf '%s\\n' ${cmd.slice(5)}`]).toString().trim().split("\n");+ assert.equal(words[0], join(spaced, "tools", `${k}.mjs`), `${k}: sh split the path into ${JSON.stringify(words)}`);+ assert.equal(words[1], "spaceFilm");+ }+ });+ const overlayRoots = (cwd) => { const r = node(["--input-type=module", "-e", `const o = await import(${JSON.stringify(pathToFileURL(join(TOOLS, "overlay.mjs")).href)}); console.log(JSON.stringify({ roots: o.ROOTS, page: o.enginePath("src/hosts/page.ts") }));`], { cwd }); assert.equal(r.status, 0, r.stderr); return JSON.parse(r.stdout); };+ await t("RED (L11): another repo's src/hosts/page.ts never replaces the engine's (no linked-project marker)", () => {+ const other = join(root, "other repo"); mkdirSync(join(other, "src", "hosts"), { recursive: true }); writeFileSync(join(other, "src", "hosts", "page.ts"), "// not ours\n");+ const o = overlayRoots(other); assert.equal(o.page, join(ENGINE, "src", "hosts", "page.ts")); assert.ok(!o.roots.includes(join(other, "src")), JSON.stringify(o.roots));+ });+ await t("GREEN (L11): a project made by scaffold --linked joins the tree first", () => {+ assert.ok(existsSync(join(proj, "src")), "the L9 test did not scaffold the project");+ const o = overlayRoots(proj); assert.equal(o.roots[0], join(proj, "src"));+ });+} finally { rmSync(root, { recursive: true, force: true }); }+console.log(`\nSOUND-UNIT: ${failed ? "FAIL" : "PASS"} ${n} passed, ${failed} failed`);+process.exitCode = failed ? 1 : 0;diff --git a/skills/anidoodle/engine/tools/soundcheck.mjs b/skills/anidoodle/engine/tools/soundcheck.mjsindex dadf6b8..1a0799c 100644--- a/skills/anidoodle/engine/tools/soundcheck.mjs+++ b/skills/anidoodle/engine/tools/soundcheck.mjs@@ -2,7 +2,10 @@// it without any model, checks each value against a range, and lists the changes to make, most// important first, each tied to a moment in the film.// node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile references/music/sound-profile.json]-// [--allow 3.1:3.6,...] [--no-video] [--json] [--out f.json]+// [--allow 3.1:3.6,...] [--no-video] [--json] [--out f.json] [--sfx stem.wav]+// --sfx: the effects stem of a film whose music is an external track (track.mjs mix --stem). Every+// effect in it must be a transient, never a note: a cue with pitch salience over 0.5 FAILS, because a+// note the engine did not choose clashes with the track's key (a brand launch "disharmonious" note).// node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name "drawing film"]// Decodes what a player would (ffmpeg, stereo float at 48 kHz). The metrics are pure functions in// src/canvas-core/music/soundcheck.ts (unit-tested on synthetic signals); visual sync reuses@@ -43,7 +46,19 @@ export const loadProfile = (C, path) => {};/** Everything for one file: measures, curves, visual sync (when there is a picture and `video`), rows and the fix list. */-export const check = async (C, file, { profile, allow = [], video = "auto" } = {}) => {+let trackP = null;+const loadPitch = () => (trackP ??= build({ entryPoints: [join(here, "../src/canvas-core/music/track.ts")], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" }).then((r) => import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"))));+/** One row per effect in an effects stem: its onset, and how much of a note it carries. */+export const pitchedCues = async (stemFile) => { const T = await loadPitch(), [L, R] = decode(stemFile); return T.stemCues(L, R, SR); };+export const pitchRows = (cues, threshold = 0.5) => {+ const bad = cues.filter((c) => c.salience > threshold), worst = [...cues].sort((a, b) => b.salience - a.salience)[0];+ const at = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(2).padStart(5, "0")}`;+ if (!cues.length) return [{ key: "sfxPitch", label: "effects pitch (external track)", value: null, text: "no effects found", status: "FAIL", fix: "the --sfx stem is silent: pass the stem track.mjs mix --stem wrote" }];+ return [{ key: "sfxPitch", label: "effects pitch (external track)", value: worst.salience, text: `${bad.length} of ${cues.length} carry a note`, status: bad.length ? "FAIL" : "PASS", range: { max: threshold }, at: bad[0]?.atS,+ fix: bad.length ? `effects carry notes under a track the engine did not write (${bad.slice(0, 4).map((c) => `${at(c.atS)} ${c.hz} Hz, salience ${c.salience}`).join("; ")}): use the tap kind (sfx.mjs list) or cut strikes under 25 ms (track.mjs kit --from-pack)` : undefined }];+};++export const check = async (C, file, { profile, allow = [], video = "auto", sfx = null } = {}) => {const p = probe(file);if (!p.audio) throw new Error(`${basename(file)} has no audio stream`);const [L, R] = decode(file), prof = profile ?? C.DEFAULT_PROFILE;@@ -55,6 +70,7 @@ export const check = async (C, file, { profile, allow = [], video = "auto" } = {sync = { ...C.visualSync(events, curves.onsets, measures.durationS), times: events, fps: p.video.fps };}const rows = C.evaluate(measures, prof);+ if (sfx) rows.push(...pitchRows(await pitchedCues(sfx)));return { file, profile: prof.name, measures, curves, sync, rows, fixes: C.startHere(rows), video: p.video, L, R };};@@ -87,7 +103,7 @@ export const asJson = (r) => ({ file: r.file, profile: r.profile, verdict: r.rowif (isMain(import.meta.url)) {const argv = process.argv.slice(2), flag = (k) => argv.includes(`--${k}`), opt = (...ks) => { for (const k of ks) { const i = argv.indexOf(k); if (i >= 0) return argv[i + 1]; } return undefined; };- const VAL = new Set(["--profile", "--out", "--allow", "-o", "--name"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));+ const VAL = new Set(["--profile", "--out", "--allow", "-o", "--name", "--sfx"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));const die = (msg, code = 2) => { console.error(msg); process.exit(code); };if (!pos.length) die("usage: node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile p.json] [--allow a:b] [--no-video] [--json] [--out f.json]\n node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name \"drawing film\"]");const C = await loadCheck();@@ -101,7 +117,7 @@ if (isMain(import.meta.url)) {console.log(`profile of ${sets.length} film(s) -> ${out}`); for (const [k, v] of Object.entries(p.metrics)) console.log(` ${pad(k, 12)} ${v.min} .. ${v.max} median ${v.median}`);process.exit(0);}- const file = resolveInput(pos[0]), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")), video: flag("no-video") ? false : "auto" });+ const file = resolveInput(pos[0]), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")), video: flag("no-video") ? false : "auto", sfx: opt("--sfx") ? resolveInput(opt("--sfx")) : null });const j = asJson(r);if (opt("--out")) { mkdirSync(dirname(resolve(opt("--out"))), { recursive: true }); writeFileSync(resolve(opt("--out")), JSON.stringify(j, null, 1) + "\n"); }console.log(flag("json") ? JSON.stringify(j, null, 1) : report(C, r));diff --git a/skills/anidoodle/engine/tools/still.mjs b/skills/anidoodle/engine/tools/still.mjsindex f86ec84..ae54b39 100644--- a/skills/anidoodle/engine/tools/still.mjs+++ b/skills/anidoodle/engine/tools/still.mjs@@ -13,6 +13,7 @@// frame, plus one board of them all, each labelled PASS or with its findings. A green// check with a prop through a hand is still a failure: look at the crops (lesson 37).// With no --frame/--frames, one still per shot, at the shot's first frame.+import { gripFindings } from "./gaterules.mjs";import { createHash } from "node:crypto";import { spawnSync } from "node:child_process";import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";@@ -114,7 +115,7 @@ if (opt.grips) {const full = resolve(dir, `.frame-${n}.png`); writeFileSync(full, Buffer.from(r.png, "base64"));rec.grips.forEach((g, i) => {const w = CW * K, h = CH * K, x = Math.max(0, Math.min(meta.W * K - w, Math.round(g.x * K - w / 2))), y = Math.max(0, Math.min(meta.H * K - h, Math.round(g.y * K - h / 2)));- const out = resolve(dir, `${film}-${n}-grip${i}.png`), bad = rec.findings.filter((x) => x.kind.startsWith("grip") || x.kind === "proximity");+ const out = resolve(dir, `${film}-${n}-grip${i}.png`), bad = gripFindings(g, rec.findings); // this grip's own findings, not every grip's on the frameconst cr = spawnSync("ffmpeg", ["-v", "error", "-y", "-i", full, "-vf", `crop=${w}:${h}:${x}:${y}`, out], { encoding: "utf8" });if (cr.status !== 0) die(`grip crop failed: ${cr.stderr.trim()}`);crops.push(out);diff --git a/skills/anidoodle/engine/tools/track.mjs b/skills/anidoodle/engine/tools/track.mjsnew file mode 100644index 0000000..624368f--- /dev/null+++ b/skills/anidoodle/engine/tools/track.mjs@@ -0,0 +1,314 @@+#!/usr/bin/env node+// TRACK. Supplied or generated music (a Lyria take, a licensed track) as a first-class path: measured,+// cut by whole bars, mixed under the film's own cues with unpitched effects, mastered, and checked on+// the muxed file. A brand launch film did all of this by hand in Python and shell, and shipped a+// silent ending twice. Generation itself stays with the person's chosen provider: `prompt` writes the+// request and states the price, it never calls a paid API.+//+// node tools/track.mjs analyze <audio> [--bpm 120] [--downbeat 0.02] [--json] [--out a.json]+// node tools/track.mjs cut <audio> (--segs "0:6,8:36" | --segs-file f.txt | --bars "0-3,4-18")+// [--film <name> | --film-s 88.8] [--fade-out S] [--end-tol 0.5] [--xfade 12] [--bpm N] -o cut.wav+// node tools/track.mjs import <audio> --provider "lyria-3.5" [--cost 0.08] [--prompt p.txt] [--licence "..."]+// node tools/track.mjs prompt --len 70 --bpm 120 --style "..." [--key "A minor"] [--sections "0-11 Intro: ...; 11-12 Hard stop: ..."] [-o p.txt]+// node tools/track.mjs kit <outdir> [--from-pack]+// node tools/track.mjs mix --music cut.wav --cues out/<film>.cues.json [--sounds map.json] -o mix.wav [--stem sfx.wav]+// node tools/track.mjs master <picture.mp4> <mix.wav> -o out.mp4 [--tp -1] [--lufs -14]+// node tools/track.mjs check <file.mp4|wav> [--film-s S] [--fps 60] [--quiet-from cut.json|mix.json] [--json]+// node tools/track.mjs listen <outdir> --mix mix.wav [--at 20] [--len 10] [--takes a.wav,b.wav]+// Exit 1 on a failed check or a refused cut, 2 on bad input.+import { build } from "esbuild";+import { execFileSync, spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync, readFileSync, writeFileSync, mkdirSync, copyFileSync, readdirSync, rmSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { homedir } from "node:os";+import { isMain } from "./is-main.mjs";+import { filmShape } from "./filmshape.mjs";++const here = dirname(fileURLToPath(import.meta.url)), SR = 48000;+let modP = null;+/** The pure modules (track analysis, the mix over a track, the effects kit, meters) in one bundle. */+export const loadTrack = () => (modP ??= (async () => {+ const src = `export * from "./src/canvas-core/music/track"; export * from "./src/canvas-core/music/trackMix"; export * from "./src/canvas-core/music/meter"; export { renderSfx, sfxInfo, sfxVariants } from "./src/canvas-core/music/sfxKit";`;+ const r = await build({ stdin: { contents: src, resolveDir: join(here, ".."), loader: "ts" }, bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });+ return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));+})());++// ---------------------------------------------------------------- audio in and out+export const decode = (file, sr = SR) => {+ if (!existsSync(file)) throw new Error(`no such file: ${file}`);+ const b = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", "2", "-ar", String(sr), "pipe:1"], { maxBuffer: 2 ** 31 });+ const f = new Float32Array(b.buffer, b.byteOffset, b.length / 4), n = f.length / 2, L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }+ return [L, R];+};+/** 32-bit float stereo WAV: nothing clips on the way to the encoder. */+export const writeWav = (path, L, R, sr = SR) => {+ const n = L.length, data = Buffer.alloc(n * 8), h = Buffer.alloc(44);+ for (let i = 0; i < n; i++) { data.writeFloatLE(L[i], i * 8); data.writeFloatLE(R[i], i * 8 + 4); }+ h.write("RIFF", 0); h.writeUInt32LE(36 + data.length, 4); h.write("WAVEfmt ", 8); h.writeUInt32LE(16, 16); h.writeUInt16LE(3, 20); h.writeUInt16LE(2, 22);+ h.writeUInt32LE(sr, 24); h.writeUInt32LE(sr * 8, 28); h.writeUInt16LE(8, 32); h.writeUInt16LE(32, 34); h.write("data", 36); h.writeUInt32LE(data.length, 40);+ mkdirSync(dirname(resolve(path)), { recursive: true }); writeFileSync(path, Buffer.concat([h, data]));+};+const sha256 = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");+const probeDur = (file) => { const j = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,duration,avg_frame_rate:format=duration", "-of", "json", file]).toString()); const v = j.streams.find((s) => s.codec_type === "video"); const [a, b] = (v?.avg_frame_rate ?? "0/1").split("/").map(Number); return { video: v ? Number(v.duration ?? j.format.duration) : null, fps: b ? a / b : 0, duration: Number(j.format.duration), audio: j.streams.some((s) => s.codec_type === "audio") }; };+/** ffmpeg's own EBU R128 reading of a file: integrated loudness and true peak (what a platform measures). */+export const ebur = (file) => {+ const r = spawnSync("ffmpeg", ["-hide_banner", "-nostats", "-i", file, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"], { encoding: "utf8", maxBuffer: 1 << 26 });+ const s = r.stderr.slice(r.stderr.lastIndexOf("Summary:")), I = /I:\s+(-?[\d.]+|-inf) LUFS/.exec(s), P = /Peak:\s+(-?[\d.]+|-inf) dBFS/.exec(s);+ if (!I || !P) throw new Error(`could not meter ${file}: ${r.stderr.slice(-300)}`);+ return { lufs: Number(I[1]), tp: P[1] === "-inf" ? -Infinity : Number(P[1]) };+};+/** A film's length in seconds from its module (meta.durationFrames / meta.fps). */+const filmSeconds = async (name) => { const { loadFilmModule } = await import("./audio.mjs"); const { film } = await loadFilmModule(name); return { s: film.meta.durationFrames / film.meta.fps, fps: film.meta.fps }; };++// ---------------------------------------------------------------- arguments+const parseArgs = (argv) => {+ const pos = [], o = {};+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === "-o") { o.out = argv[++i]; continue; }+ if (a.startsWith("--")) { const k = a.slice(2), nx = argv[i + 1]; if (nx === undefined || nx.startsWith("--") || ["json", "from-pack"].includes(k)) o[k] = true; else { o[k] = nx; i++; } continue; }+ pos.push(a);+ }+ return { pos, o };+};+const num = (v, name) => { if (v === undefined) return undefined; const n = Number(v); if (!Number.isFinite(n)) throw new Error(`--${name} wants a number, got "${v}"`); return n; };++// ---------------------------------------------------------------- analyze+export const analyzeFile = async (file, o = {}) => { const T = await loadTrack(), [L, R] = decode(file); return T.analyzeTrack(L, R, SR, { bpm: o.bpm, downbeatS: o.downbeatS }); };+const fmtAnalysis = (a, file) => {+ const out = [`TRACK ${file}`, ` ${a.durationS} s, ${a.bpm} bpm (beat ${a.beatS} s, bar ${a.barS} s), first downbeat ${a.downbeatS} s`,+ ` tempo candidates: ${a.tempoCandidates.length ? a.tempoCandidates.map((c) => `${c.bpm} (${c.rel})`).join(", ") + " <- if your ear or the prompt says another, pin it with --bpm" : "pinned with --bpm"}`,+ ` key ${a.key.name}${a.key.confidence < 0.1 ? " (unclear: margin " + a.key.confidence + " over " + a.key.runnerUp + "; a generated take often ignores the key asked for)" : ` (margin ${a.key.confidence} over ${a.key.runnerUp})`}`,+ ` last note ends ${a.lastSoundS} s; ${a.tailS} s of silence after it${a.tailS > 0.5 ? " <- an edit must not reach past the last note" : ""}`,+ ` stops (designed drop-outs): ${a.stops.length ? a.stops.map((s) => `${s.atS} s for ${s.lenS} s`).join(", ") : "none"}`, "", " SECTIONS (by bar level against the body, " + a.bodyDb + " dB)"];+ for (const s of a.sections) out.push(` bars ${String(s.fromBar).padStart(3)}-${String(s.toBar).padEnd(4)} ${String(s.fromS).padStart(7)}-${String(s.toS).padEnd(8)} ${s.level.padEnd(6)} peak bar ${s.rmsDb} dB`);+ out.push("", " BARS (bar: start s, level dB)");+ for (let i = 0; i < a.bars.length; i += 6) out.push(" " + a.bars.slice(i, i + 6).map((b) => `${String(b.i).padStart(3)}: ${b.t.toFixed(2).padStart(6)} ${String(b.rmsDb).padStart(6)}`).join(" "));+ return out.join("\n");+};++// ---------------------------------------------------------------- cut+const readSegs = (T, o, a) => {+ const n = ["segs", "segs-file", "bars"].filter((k) => o[k] !== undefined);+ if (n.length !== 1) throw new Error("cut wants exactly one of --segs, --segs-file or --bars");+ const text = o["segs-file"] ? readFileSync(resolve(o["segs-file"]), "utf8") : o.bars ? `bars ${o.bars}` : String(o.segs);+ return T.parseSegs(text, a);+};+export const cutFile = async (file, o) => {+ const T = await loadTrack(), [L, R] = decode(file), a = T.analyzeTrack(L, R, SR, { bpm: num(o.bpm, "bpm"), downbeatS: num(o.downbeat, "downbeat") });+ const segs = readSegs(T, o, a), film = o.film ? await filmSeconds(o.film) : null, filmS = film?.s ?? num(o["film-s"], "film-s");+ const plan = T.planCut(a, segs, { filmS, fadeOutS: num(o["fade-out"], "fade-out"), endTolS: num(o["end-tol"], "end-tol") });+ return { a, plan, render: () => T.renderCut(L, R, SR, plan.segs, { xfadeMs: num(o.xfade, "xfade"), fadeOutS: num(o["fade-out"], "fade-out") }) };+};++// ---------------------------------------------------------------- prompt (never calls the provider)+export const PRICES = { "lyria-3.5": { usd: 0.08, unit: "song", checked: "2026-10-27", source: "https://ai.google.dev/gemini-api/docs/pricing" } };+export const promptText = (o) => {+ const len = num(o.len, "len"), bpm = num(o.bpm, "bpm");+ if (!len || !bpm) throw new Error("prompt wants --len <seconds> and --bpm <tempo>");+ const bar = (240 / bpm).toFixed(2), sections = String(o.sections ?? "").split(";").map((s) => s.trim()).filter(Boolean);+ const lines = [+ `Tempo is locked at exactly ${bpm} BPM (one beat every ${(60 / bpm).toFixed(2)} seconds, one bar every ${bar} seconds), steady metronomic tempo throughout, no tempo changes. Section boundaries fall exactly on bar lines.`, "",+ `${o.style ?? "Warm modern downtempo instrumental."}${o.key ? ` In ${o.key}.` : ""} Instrumental only, no vocals, no voices, no choir. Exactly ${bpm} BPM in 4/4, the first downbeat lands at 0:00 with no pickup or silence before it. Total length ${len} seconds, ending cleanly on one final button hit with under 2 seconds of tail and no long fade.`,+ ];+ if (sections.length) { lines.push(""); for (const s of sections) { const m = /^(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)\s+(.*)$/.exec(s); if (!m) throw new Error(`--sections: cannot read "${s}" (write "from-to Name: what happens")`); const t = (x) => `${Math.floor(x / 60)}:${String(Math.round(x % 60)).padStart(2, "0")}`; lines.push(`[${t(+m[1])} - ${t(+m[2])}] ${m[3]}`); } }+ return lines.join("\n");+};++// ---------------------------------------------------------------- kit+// The recorded route, ported from a brand launch film's hand-written kit script with its bug fixed by construction: every+// strike is cut from its own PEAK (the first cut trimmed leading silence and kept a -46 dB tick), then+// filtered, faded and normalised to -6 dBFS. Too short to carry a note under someone else's music.+export const PACK_KIT = [+ { name: "tick", pat: /^C7_l3_rr1.*\.flac$/, dir: "marimba", preMs: 1.5, lenMs: 16, af: "highpass=f=1800,afade=t=in:d=0.0008,afade=t=out:st=0.006:d=0.010" },+ { name: "tickHi", pat: /^C8_l2_rr1.*\.flac$/, dir: "glockenspiel", preMs: 1.0, lenMs: 10, af: "highpass=f=3000,afade=t=in:d=0.0006,afade=t=out:st=0.004:d=0.006" },+ { name: "tock", pat: /^C5_l3_rr1.*\.flac$/, dir: "marimba", preMs: 2.0, lenMs: 26, af: "highpass=f=500,lowpass=f=6000,afade=t=in:d=0.001,afade=t=out:st=0.010:d=0.016" },+ { name: "thump", pat: /^Timpani2A_l3_rr1.*\.flac$/, dir: "timpani", preMs: 3.0, lenMs: 110, af: "lowpass=f=150,lowpass=f=150,afade=t=in:d=0.002,afade=t=out:st=0.04:d=0.07" },+ { name: "impact", pat: /^Timpani3A_l3_rr1.*\.flac$/, dir: "timpani", preMs: 3.0, lenMs: 1600, af: "lowpass=f=500,afade=t=in:d=0.002,afade=t=out:st=0.6:d=1.0" },+];+/** Cut one transient from its peak: the sample index of the loudest sample, minus preMs. */+export const cutFromPeak = (x, sr, preMs, lenMs) => {+ let pk = 0, at = 0; for (let i = 0; i < x.length; i++) if (Math.abs(x[i]) > pk) { pk = Math.abs(x[i]); at = i; }+ const s = Math.max(0, at - Math.round((preMs * sr) / 1000)); return x.slice(s, s + Math.round((lenMs * sr) / 1000));+};++// ---------------------------------------------------------------- mix+/** A sounds map: cue name (or a prefix ending in *) -> "tap:thump -9 pan=0.3". The cue's own `sound` wins. */+const soundFor = (cue, map) => cue.sound ?? map[cue.name] ?? Object.entries(map).find(([k]) => k.endsWith("*") && cue.name.startsWith(k.slice(0, -1)))?.[1];++// ---------------------------------------------------------------- check (the muxed file)+/**+ * Everything a delivered external-track mix must pass, on the exact file: integrated loudness near the+ * target, true peak at or under the ceiling (AAC adds peak, so it is measured AFTER encoding), and the+ * film shape: the sound starts with the picture, has no hole, and does not stop before the picture does.+ */+export const checkFile = async (file, o = {}) => {+ const p = probeDur(file); if (!p.audio) throw new Error(`${basename(file)} has no audio stream`);+ const [L, R] = decode(file), m = ebur(file), rows = [], fps = num(o.fps, "fps") ?? (p.fps || 30);+ const lufsT = num(o.lufs, "lufs") ?? -14, tpT = num(o.tp, "tp") ?? -1;+ const picS = num(o["film-s"], "film-s") ?? p.video ?? p.duration, soundS = L.length / SR;+ const add = (ok, label, value, fix) => rows.push({ status: ok ? "PASS" : "FAIL", label, value, fix: ok ? undefined : fix });+ add(Math.abs(m.lufs - lufsT) <= 1, "integrated loudness", `${m.lufs} LUFS (target ${lufsT})`, `re-master to ${lufsT} LUFS: node tools/track.mjs master <picture> <mix.wav> -o <out>`);+ add(m.tp <= tpT, "true peak after encoding", `${m.tp} dBTP (ceiling ${tpT})`, "AAC adds about 3 dB of peak: master again (track.mjs master lowers the limiter until the ENCODED file passes)");+ const quiet = quietFrom(file, o).map(({ fromS, toS }) => [Math.floor(fromS * fps), Math.ceil(toS * fps)]);+ const shape = filmShape(L, R, SR, { fps, quiet });+ for (const pr of shape.problems) add(false, `sound shape: ${pr.kind}`, pr.msg, pr.kind === "dead end" ? "the music ends before the picture: extend the outro by whole bars (track.mjs cut --film-s), or end the picture on the music's last note" : "declare a designed silence in meta.quiet, or fill it");+ if (!shape.problems.length) add(true, "sound shape", `starts ${shape.firstS.toFixed(1)} s, longest hole ${shape.holeS.toFixed(1)} s, ends ${shape.endS.toFixed(1)} s before the picture`);+ if (p.video !== null || o["film-s"] !== undefined) add(soundS >= picS - 0.1, "sound covers the picture", `${soundS.toFixed(2)} s of sound for ${picS.toFixed(2)} s of picture`, "the audio stream is shorter than the picture: rebuild the mix at the film's length");+ return { file, rows, verdict: rows.some((r) => r.status === "FAIL") ? "FAIL" : "PASS", lufs: m.lufs, tp: m.tp };+};+/**+ * Designed silences in seconds: --quiet-from <cut.json|mix.json>, else the sidecars next to the file+ * (<out>.mix.json written by mix and copied by master), so a track's own hard stops are declared once,+ * by the analysis, and never reported as holes.+ */+const quietFrom = (file, o) => {+ const cands = [o["quiet-from"], `${file}.mix.json`, `${file}.cut.json`].filter(Boolean).map((f) => resolve(f));+ const f = cands.find((c) => existsSync(c)); if (o["quiet-from"] && !existsSync(resolve(o["quiet-from"]))) throw new Error(`--quiet-from: no such file ${o["quiet-from"]}`);+ return f ? JSON.parse(readFileSync(f, "utf8")).quiet ?? [] : [];+};+const printRows = (title, rows, verdict) => { console.log(title); for (const r of rows) console.log(` ${r.status.padEnd(5)} ${r.label.padEnd(28)} ${r.value}${r.fix ? `\n fix: ${r.fix}` : ""}`); console.log(`VERDICT: ${verdict}`); };++// ---------------------------------------------------------------- master+/**+ * The delivery chain a brand launch film ended on (loudnorm to the target, a limiter, AAC 256k), with+ * the step it did by hand made automatic: the true peak is read from the ENCODED file, and while it is+ * over the ceiling the limiter comes down by the excess and the file is encoded again (at most 5 times).+ */+export const master = (picture, mix, out, o = {}) => {+ const lufs = num(o.lufs, "lufs") ?? -14, ceil = num(o.tp, "tp") ?? -1;+ // The picture's length is measured on the SOURCE picture, never on the output: the film is never cut to+ // the mix. A mix shorter than the picture is refused before anything is written; a longer one is trimmed+ // to the picture.+ const pv = probeDur(picture), pictureS = pv.video ?? pv.duration, mixS = probeDur(mix).duration;+ if (!(pictureS > 0)) throw new Error(`${basename(picture)} has no picture to master onto`);+ if (mixS < pictureS - 0.05) return { out, ok: false, refused: `the mix ${basename(mix)} is ${mixS.toFixed(2)} s, shorter than the picture ${basename(picture)} (${pictureS.toFixed(2)} s): rebuild the mix at the film's length (track.mjs cut --film-s ${pictureS.toFixed(2)}). Nothing written.`, pictureS };+ let limitDb = ceil - 2.6, m = null; const tmp = out.replace(/\.[^.]+$/, "") + ".master.wav";+ try {+ for (let k = 0; k < 5; k++) {+ execFileSync("ffmpeg", ["-y", "-v", "error", "-i", mix, "-af", `loudnorm=I=${lufs}:TP=${ceil - 0.5}:LRA=11:linear=true,alimiter=limit=${Math.pow(10, limitDb / 20).toFixed(4)}:level=false:attack=3:release=60`, "-ar", String(SR), tmp]);+ execFileSync("ffmpeg", ["-y", "-v", "error", "-i", picture, "-t", pictureS.toFixed(4), "-i", tmp, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "256k", out]);+ m = ebur(out);+ if (m.tp <= ceil) break;+ limitDb -= m.tp - ceil + 0.3;+ }+ } finally { rmSync(tmp, { force: true }); }+ return { out, limitDb: +limitDb.toFixed(2), ...m, ok: m.tp <= ceil, pictureS };+};++// ---------------------------------------------------------------- listen+const listenPage = (title, items) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title>+<style>:root{--bg:#F0EEE6;--ink:#1d1b16;--line:#d8d3c4}@media (prefers-color-scheme:dark){:root{--bg:#1b1a17;--ink:#eeeae0;--line:#34322c}}body{background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,sans-serif;max-width:900px;margin:auto;padding:24px 16px}h1{font-size:24px}h2{font-size:17px;margin-top:24px}.g{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:10px}.c{border:1px solid var(--line);border-radius:10px;padding:10px 12px}audio{width:100%}</style></head><body>+<h1>${title}</h1><p>Listen before the full mix: the effects on their own, then ten seconds of the mix, then the takes. Your ears are the check the tools cannot make.</p>+${items.map(([h, list]) => `<h2>${h}</h2><div class="g">${list.map(([f, t, d]) => `<div class="c"><b>${t}</b><div>${d}</div><audio controls preload="none" src="${f}"></audio></div>`).join("")}</div>`).join("\n")}+</body></html>`;++// ---------------------------------------------------------------- command line+if (isMain(import.meta.url)) {+ const { pos, o } = parseArgs(process.argv.slice(2)), cmd = pos[0];+ const die = (msg, code = 2) => { console.error(`track: ${msg}`); process.exit(code); };+ try {+ if (cmd === "analyze") {+ if (!pos[1]) die("usage: node tools/track.mjs analyze <audio> [--bpm N] [--downbeat S] [--json] [--out a.json]");+ const a = await analyzeFile(resolve(pos[1]), { bpm: num(o.bpm, "bpm"), downbeatS: num(o.downbeat, "downbeat") });+ if (o.out) writeFileSync(resolve(o.out), JSON.stringify(a, null, 1) + "\n");+ console.log(o.json ? JSON.stringify(a, null, 1) : fmtAnalysis(a, pos[1]));+ } else if (cmd === "cut") {+ if (!pos[1] || !o.out) die("usage: node tools/track.mjs cut <audio> (--segs \"0:6,8:36\" | --segs-file f.txt | --bars \"0-3,4-18\") [--film <name> | --film-s S] [--fade-out S] -o cut.wav");+ const { a, plan, render } = await cutFile(resolve(pos[1]), o);+ console.log(`CUT ${pos[1]} (${a.bpm} bpm, bar ${a.barS} s, last note ${a.lastSoundS} s)`);+ plan.segs.forEach((s, i) => console.log(` ${String(i + 1).padStart(2)}. ${s.from}-${s.to} s (${(s.to - s.from).toFixed(2)} s, ${((s.to - s.from) / a.barS).toFixed(2)} bars)`));+ console.log(` edit length ${plan.lengthS} s; joins at ${plan.joins.map((j) => j.atS.toFixed(2)).join(", ") || "none"}`);+ for (const w of plan.warnings) console.log(` WARN ${w}`);+ for (const e of plan.errors) console.log(` FAIL ${e}`);+ if (plan.errors.length) { console.log("VERDICT: REFUSED (nothing written)"); process.exit(1); }+ const [L, R] = render(); writeWav(o.out, L, R);+ writeFileSync(o.out + ".cut.json", JSON.stringify({ source: resolve(pos[1]), sourceSha256: sha256(resolve(pos[1])), segs: plan.segs, lengthS: plan.lengthS, downbeats: plan.downbeats, quiet: plan.quiet, bpm: a.bpm }, null, 1) + "\n");+ console.log(`wrote ${o.out} (${(L.length / SR).toFixed(3)} s) and ${o.out}.cut.json (the edit's downbeats, for trackGrid)\nVERDICT: PASS`);+ } else if (cmd === "import") {+ if (!pos[1] || !o.provider) die("usage: node tools/track.mjs import <audio> --provider <model or source> [--cost USD] [--prompt p.txt] [--licence \"...\"]");+ const f = resolve(pos[1]), a = await analyzeFile(f, {});+ const man = { file: basename(f), sha256: sha256(f), provider: o.provider, costUsd: num(o.cost, "cost") ?? null, prompt: o.prompt ? readFileSync(resolve(o.prompt), "utf8") : null, licence: o.licence ?? null, importedAt: new Date().toISOString().slice(0, 10), analysis: { durationS: a.durationS, bpm: a.bpm, downbeatS: a.downbeatS, key: a.key.name, lastSoundS: a.lastSoundS, tailS: a.tailS, stops: a.stops } };+ writeFileSync(f + ".track.json", JSON.stringify(man, null, 1) + "\n");+ console.log(`pinned ${man.file} sha256 ${man.sha256.slice(0, 16)}... -> ${basename(f)}.track.json\n${fmtAnalysis(a, pos[1]).split("\n").slice(0, 4).join("\n")}`);+ } else if (cmd === "prompt") {+ const text = promptText(o), model = o.model ?? "lyria-3.5", price = PRICES[model];+ if (o.out) writeFileSync(resolve(o.out), text + "\n");+ console.log(text);+ console.log(`\n---\nNot sent. This tool never calls a paid API. ${price ? `${model} costs $${price.usd} per ${price.unit} (checked ${price.checked}, ${price.source}); check the page again before running.` : `No price on record for ${model}: look it up before running.`}\nState the cost to the person before generating, log every take in a COST.md ledger (date, model, result, cost), and ask for 3 to 4 takes: a model ignores exact timestamps, so the picture is fitted to the take with 'track.mjs analyze' and 'cut'.`);+ } else if (cmd === "kit") {+ if (!pos[1]) die("usage: node tools/track.mjs kit <outdir> [--from-pack]");+ const T = await loadTrack(), dir = resolve(pos[1]); mkdirSync(dir, { recursive: true });+ const rows = [];+ if (o["from-pack"]) {+ const pack = process.env.ANIDOODLE_SOUNDS || join(homedir(), ".anidoodle", "sounds");+ for (const k of PACK_KIT) {+ const d = join(pack, k.dir); if (!existsSync(d)) die(`the sound pack has no ${k.dir}/ (fetch it: node tools/soundfetch.mjs)`);+ const src = readdirSync(d).filter((f) => k.pat.test(f)).sort()[0]; if (!src) die(`no ${k.pat} in ${d}`);+ const [xl, xr] = decode(join(d, src)), seg = cutFromPeak(T.monoOf(xl, xr), SR, k.preMs, k.lenMs), raw = join(dir, `_${k.name}.wav`), out = join(dir, `${k.name}.wav`);+ writeWav(raw, seg, seg); execFileSync("ffmpeg", ["-y", "-v", "error", "-i", raw, "-af", k.af, "-c:a", "pcm_f32le", join(dir, `_${k.name}2.wav`)]);+ const [y] = decode(join(dir, `_${k.name}2.wav`)); let pk = 0; for (const v of y) pk = Math.max(pk, Math.abs(v)); const g = Math.pow(10, -6 / 20) / Math.max(pk, 1e-9); const z = y.map((v) => v * g);+ writeWav(out, z, z); for (const f of [raw, join(dir, `_${k.name}2.wav`)]) rmSync(f, { force: true });+ rows.push([k.name, T.pitchSalience(z, SR), `${src}`]);+ }+ } else {+ for (const v of T.sfxVariants("tap")) { const s = T.renderSfx("tap", { variant: v, seed: 1 }, SR); writeWav(join(dir, `${v}.wav`), s.L, s.R); rows.push([v, T.pitchSalience(T.monoOf(s.L, s.R), SR), "engine tap:" + v]); }+ }+ console.log(`KIT ${dir}`); for (const [n, p, src] of rows) console.log(` ${(p.salience > T.PITCHED ? "FAIL" : "PASS").padEnd(5)} ${n.padEnd(8)} pitch salience ${p.salience.toFixed(2)} (raw ${p.raw}, rings ${p.ringMs} ms${Number.isFinite(p.hz) ? `, ${p.hz} Hz` : ""}) ${src}`);+ if (rows.some(([, p]) => p.salience > T.PITCHED)) process.exit(1);+ } else if (cmd === "mix") {+ if (!o.music || !o.cues || !o.out) die("usage: node tools/track.mjs mix --music cut.wav --cues out/<film>.cues.json [--sounds map.json] -o mix.wav [--stem sfx.wav]");+ const T = await loadTrack(), cuesDoc = JSON.parse(readFileSync(resolve(o.cues), "utf8")), map = o.sounds ? JSON.parse(readFileSync(resolve(o.sounds), "utf8")) : {};+ if (!Array.isArray(cuesDoc.cues) || !cuesDoc.fps || !cuesDoc.durationFrames) die(`${o.cues} is not a cue sheet (write one with: node tools/cues.mjs <film>)`);+ const cues = []; const unsounded = [];+ for (const c of cuesDoc.cues) { const spec = soundFor(c, map); if (spec === undefined) { unsounded.push(c.name); continue; } if (spec === null || spec === "none") continue; cues.push({ ...T.parseSoundSpec(spec), frame: c.frame, label: c.name }); }+ if (unsounded.length) console.log(` note: ${unsounded.length} cue(s) have no sound (silent on purpose?): ${unsounded.slice(0, 8).join(", ")}${unsounded.length > 8 ? " ..." : ""}`);+ const music = decode(resolve(o.music)), m = T.mixOverTrack(music, { fps: cuesDoc.fps, frames: cuesDoc.durationFrames, cues, seed: 1 }, SR);+ console.log(T.trackMixReport(m));+ if (!m.ok) { console.log("VERDICT: FAIL (nothing written)"); process.exit(1); }+ writeWav(o.out, m.L, m.R); if (o.stem) writeWav(o.stem, m.sfx[0], m.sfx[1]);+ const cutJson = resolve(o.music) + ".cut.json", quiet = existsSync(cutJson) ? JSON.parse(readFileSync(cutJson, "utf8")).quiet ?? [] : [];+ writeFileSync(o.out + ".mix.json", JSON.stringify({ music: resolve(o.music), musicSha256: sha256(resolve(o.music)), cues: resolve(o.cues), cuesSha256: sha256(resolve(o.cues)), film: cuesDoc.film ?? null, lufs: m.lufs, dbtp: m.dbtp, quiet }, null, 1) + "\n");+ console.log(`wrote ${o.out}${o.stem ? ` and ${o.stem}` : ""}\nVERDICT: PASS`);+ } else if (cmd === "master") {+ if (!pos[1] || !pos[2] || !o.out) die("usage: node tools/track.mjs master <picture.mp4> <mix.wav> -o out.mp4 [--tp -1] [--lufs -14]");+ const r = master(resolve(pos[1]), resolve(pos[2]), resolve(o.out), o);+ if (r.refused) { console.log(`MASTER ${o.out}\n FAIL ${r.refused}\nVERDICT: FAIL`); process.exit(1); }+ // The sidecar beside the output always describes THIS mix: an older one is removed first, so+ // provenance never reads the previous mix's record.+ const side = resolve(o.out) + ".mix.json"; rmSync(side, { force: true });+ if (existsSync(resolve(pos[2]) + ".mix.json")) copyFileSync(resolve(pos[2]) + ".mix.json", side);+ else console.log(` note: no mix sidecar beside ${basename(pos[2])} (track.mjs mix writes one), so ${basename(side)} is not written and provenance will fail`);+ // The picture's film sidecar (<picture>.film.json, written by render) goes with it, re-hashed for the+ // mastered file, so ship and verify-export read the film's own settings from the delivered file. An+ // older one beside the output is removed first, as with the mix sidecar.+ const filmSide = resolve(o.out) + ".film.json", picSide = resolve(pos[1]) + ".film.json"; rmSync(filmSide, { force: true });+ if (existsSync(picSide)) { const rec = JSON.parse(readFileSync(picSide, "utf8")); writeFileSync(filmSide, JSON.stringify({ ...rec, file: basename(resolve(o.out)), sha256: sha256(resolve(o.out)), masteredFrom: basename(resolve(pos[1])) }, null, 1) + "\n"); }+ else console.log(` note: no film sidecar beside ${basename(pos[1])} (render writes one), so ${basename(filmSide)} is not written`);+ console.log(`MASTER ${o.out}: ${r.lufs} LUFS, ${r.tp} dBTP after AAC (limiter at ${r.limitDb} dB)`);+ // the picture length comes from the source picture, so the check can never measure a cut output against itself+ const c = await checkFile(resolve(o.out), { ...o, "film-s": o["film-s"] ?? r.pictureS }); printRows("CHECK (the muxed file)", c.rows, c.verdict);+ process.exit(r.ok && c.verdict === "PASS" ? 0 : 1);+ } else if (cmd === "check") {+ if (!pos[1]) die("usage: node tools/track.mjs check <file.mp4|wav> [--film-s S] [--fps N] [--lufs -14] [--tp -1] [--json]");+ const c = await checkFile(resolve(pos[1]), o);+ if (o.json) console.log(JSON.stringify(c, null, 1)); else printRows(`TRACK CHECK ${pos[1]}`, c.rows, c.verdict);+ process.exit(c.verdict === "PASS" ? 0 : 1);+ } else if (cmd === "listen") {+ if (!pos[1] || !o.mix) die("usage: node tools/track.mjs listen <outdir> --mix mix.wav [--at 20] [--len 10] [--takes a.wav,b.wav] [--kit dir]");+ const T = await loadTrack(), dir = resolve(pos[1]); mkdirSync(dir, { recursive: true });+ const mp3 = (src, out, extra = []) => execFileSync("ffmpeg", ["-y", "-v", "error", ...extra, "-i", src, "-codec:a", "libmp3lame", "-b:a", "256k", join(dir, out)]);+ const kitRows = [];+ if (o.kit) for (const f of readdirSync(resolve(o.kit)).filter((f) => f.endsWith(".wav")).sort()) { mp3(join(resolve(o.kit), f), `kit-${f.replace(/\.wav$/, ".mp3")}`); kitRows.push([`kit-${f.replace(/\.wav$/, ".mp3")}`, f.replace(/\.wav$/, ""), "recorded transient"]); }+ else for (const v of T.sfxVariants("tap")) { const s = T.renderSfx("tap", { variant: v, seed: 1 }, SR), w = join(dir, `_${v}.wav`); writeWav(w, s.L, s.R); mp3(w, `kit-${v}.mp3`); rmSync(w, { force: true }); kitRows.push([`kit-${v}.mp3`, `tap:${v}`, T.sfxInfo("tap").use]); }+ const at = num(o.at, "at") ?? 20, len = num(o.len, "len") ?? 10;+ mp3(resolve(o.mix), "mix-sample.mp3", ["-ss", String(at), "-t", String(len)]);+ const takes = String(o.takes ?? "").split(",").filter(Boolean).map((t, i) => { mp3(resolve(t), `take-${i + 1}.mp3`); return [`take-${i + 1}.mp3`, basename(t), ""]; });+ writeFileSync(join(dir, "index.html"), listenPage("Sound check by ear", [["The effects, alone", kitRows], [`The mix, ${len} s from ${at} s`, [["mix-sample.mp3", "mix sample", basename(o.mix)]]], ...(takes.length ? [["The takes", takes]] : [])]));+ console.log(`wrote ${join(dir, "index.html")}: ${kitRows.length} effects, a ${len} s mix sample${takes.length ? `, ${takes.length} takes` : ""}. Open it and listen before rendering the full mix.`);+ } else die("commands: analyze, cut, import, prompt, kit, mix, master, check, listen (see the header of tools/track.mjs)");+ } catch (e) { die(e.message, 2); }+}diff --git a/skills/anidoodle/engine/tools/verify-export.mjs b/skills/anidoodle/engine/tools/verify-export.mjsindex b7624df..f59090e 100644--- a/skills/anidoodle/engine/tools/verify-export.mjs+++ b/skills/anidoodle/engine/tools/verify-export.mjs@@ -5,7 +5,9 @@// colour to assert, and a one-shot film has no seam to hide.//// node tools/verify-export.mjs <film> [--file out/x.mp4] [--adapter html-player]-// node tools/verify-export.mjs out/<film>.mp4 [...] the file itself: the film is its name (out/<film>[.<from>-<to>].<ext>)+// node tools/verify-export.mjs out/<file>.mp4 [...] the file itself: the film is its sidecar's (<file>.film.json,+// written by render), else its name (out/<film>[.<from>-<to>].<ext>); a renamed file+// with neither gets the --file form to run instead// [--width W] expected pixel width of a .gif/.webm/.apng made with render --width// (default: the film's own; height follows the aspect). Not for .mp4:// render always writes the MP4 at the film's size (x --scale), so@@ -33,7 +35,8 @@import { execFileSync, spawnSync } from "node:child_process";import { existsSync, mkdirSync, writeFileSync } from "node:fs";import { basename, resolve } from "node:path";-import { defaultOutput, requireFilm } from "./names.mjs";+import { defaultOutput, knownFilms, requireFilm } from "./names.mjs";+import { filmOfFile, readSidecar, trackProvenance } from "./sidecar.mjs";import { firstFrameBlank } from "./thumb.mjs";import { mono, onsetNear, xcorrOffset } from "./avsync.mjs";import { filmShape } from "./filmshape.mjs";@@ -46,7 +49,9 @@ const USAGE = "node tools/verify-export.mjs <film> [--file out/<film>.mp4] [--fiif (pos[0] && /\.(mp4|gif|webm|apng|png)$/i.test(pos[0])) {if (opt.file) { console.error(`verify-export: give the file once: '${pos[0]}' or --file ${opt.file}`); process.exit(2); }if (!existsSync(pos[0])) { console.error(`verify-export: no file '${pos[0]}'`); process.exit(2); }- opt.file = pos[0]; pos[0] = basename(pos[0]).split(".")[0];+ opt.file = pos[0]; const who = filmOfFile(pos[0], knownFilms());+ if (!who.film) { console.error(`verify-export: ${who.why}`); process.exit(2); }+ pos[0] = who.film; console.log(`film "${who.film}" from the ${who.how}`);}const film = requireFilm(pos[0], "verify-export", USAGE);const adapterName = opt.adapter ?? "html-player";@@ -80,6 +85,13 @@ const file = resolve(opt.file ?? defaultOutput(film));console.log(`VERIFY-EXPORT film "${meta.title}" file ${file}`);if (!existsSync(file)) die(`${file} not found`);const isMp4 = /\.(mp4|m4v|mov)$/i.test(file);+// the sidecar render wrote beside the file: it must name THIS film, and a placeholder render never ships+{ const sc = readSidecar(file);+ if (sc?.error) die(sc.error);+ if (sc?.film && sc.film !== film) die(`${basename(file)} was rendered from film '${sc.film}' (its sidecar), not '${film}'`);+ if (sc?.stale) note("the sidecar's hash does not match the file", "the file changed after render wrote it: re-render, or check what touched it");+ const ph = [...new Set([...(sc?.placeholders ?? []), ...(meta.placeholders ?? [])])];+ if (ph.length) (opt.delivery ? (l, d) => say(false, l, d) : note)(`rendered with ${ph.length} placeholder asset(s): ${ph.join(", ")}`, "a labelled grey box stands in for each; --delivery refuses it"); }if (opt.width && isMp4) die(`--width does not apply to an MP4: render writes it at the film's own size (x --scale); use --scale to check a scaled render`);const FRAME = opt.frame === undefined ? 0 : Number(opt.frame);if (!Number.isInteger(FRAME) || FRAME < 0 || FRAME >= N) die(`--frame wants a frame number in [0, ${N - 1}], got '${opt.frame}'`);@@ -100,7 +112,9 @@ say(Math.abs(dur - wantDur) <= slack, `duration ${dur.toFixed(3)} s`, `expectedif (isMp4) {head("1b", "SOUND the score is in the file, as long as the picture, and audible");const a = ffprobe(["-select_streams", "a", "-show_entries", "stream=codec_name,duration,sample_rate,channels", "-of", "csv=p=0", file]).split("\n").filter(Boolean);- const hasAudio = meta.hasAudio ?? Boolean(await s.audio?.(48000)); // older pages / other adapters: ask the score itself+ // a supplied or generated track (meta.checks.music.track) is mixed outside the page: the file must carry it+ const ext = meta.checks?.music?.track ? resolve(meta.checks.music.track) : null;+ const hasAudio = ext ? true : meta.hasAudio ?? Boolean(await s.audio?.(48000)); // older pages / other adapters: ask the score itselfif (!hasAudio) say(a.length === 0, "no audio stream (the film has no score)", a.length ? `found ${a.length}: ${a.join(" | ")}` : "");else if (!a.length) say(false, "an audio stream (the film has a score)", "none found: was it a range render?");else {@@ -111,6 +125,11 @@ if (isMp4) {const mx = Number(((vd.stdout + vd.stderr).match(/max_volume:\s*(-?[0-9.]+|-inf) dB/) ?? [])[1]);say(Number.isFinite(mx) && mx > -40 && mx <= 0, `audio peak ${Number.isFinite(mx) ? mx.toFixed(1) : "-inf"} dBFS`, "audible (> -40 dBFS) and not clipped past 0");+ if (ext) {+ head("1c", "TRACK the music is the pinned take (an external track, mixed by track.mjs)");+ const pv = trackProvenance(ext, file); say(pv.ok, "the delivered mix comes from the take its manifest pins", pv.detail);+ note("shape, holes and the ending of an external track", "track.mjs check measures them on this file against the track's declared stops (ship runs it)");+ } else {head("1c", "SYNC the delivered sound sits on the picture's frames");const SR = 48000, dec = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-map", "0:a:0", "-f", "f32le", "-ac", "2", "-ar", String(SR), "-"], { maxBuffer: 1 << 30 });if (dec.status !== 0) die(`ffmpeg could not decode the audio: ${dec.stderr.toString().trim()}`);@@ -138,6 +157,8 @@ if (isMp4) {}}+ }+head("1d", "PEAK the true peak of the file as delivered (after the encode)");const eb = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", file, "-map", "0:a:0", "-af", "ebur128=peak=true", "-f", "null", "-"], { encoding: "utf8", maxBuffer: 1 << 26 });const txt = eb.stdout + eb.stderr, tp = Number((txt.match(/True peak:\s*\n\s*Peak:\s*(-?[0-9.]+|-inf) dBFS/) ?? [])[1]), il = Number((txt.match(/Integrated loudness:\s*\n\s*I:\s*(-?[0-9.]+) LUFS/) ?? [])[1]);diff --git a/skills/anidoodle/engine/tools/worldfilm.mjs b/skills/anidoodle/engine/tools/worldfilm.mjsnew file mode 100644index 0000000..973797e--- /dev/null+++ b/skills/anidoodle/engine/tools/worldfilm.mjs@@ -0,0 +1,75 @@+// node tools/worldfilm.mjs <name> [--dir .] [--beats 4] [--format 16x9|9x16|1x1|4x5] [--fps 30] [--temperament calm|lively|snappy]+// A NEW MOTION FILM, STARTED AS ONE WORLD. Writes src/canvas-core/<name>.ts and src/hosts/page-<name>.ts:+// every beat is a region of one canvas, one camera travels between them (world.ts), each beat's title+// enters and leaves with setType (exit on an ease-in, 1.3x), sides alternate (alternate(i)), the camera+// breathes, and meta.motion names the temperament and the brand colours for motionscan and layerscan.+// It is the default for a launch or motion-graphics film because a brand launch film was built scene+// by scene and read as "a LITERAL SLIDE DECK". Replace the titles and the cards; keep the structure.+// Refuses to overwrite. Prints the next commands.+import { existsSync, mkdirSync, writeFileSync } from "node:fs";+import { join, resolve } from "node:path";+import { isMain } from "./is-main.mjs";++const SHAPES = { "16x9": [1920, 1080], "9x16": [1080, 1920], "1x1": [1080, 1080], "4x5": [1080, 1350] };++/** The source of a one-world film module: `beats` regions, a hold and a camera move each, on the beat grid. */+export const worldFilmSource = (name, { beats = 4, format = "16x9", fps = 30, bpm = 120, temperament = "calm" } = {}) => {+ const [W, H] = SHAPES[format] ?? (() => { throw new Error(`worldfilm: format is one of ${Object.keys(SHAPES).join(", ")}`); })();+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(name)) throw new Error(`worldfilm: '${name}' must be a bare identifier (it becomes a module and an export name)`);+ if (!(Number.isInteger(beats) && beats >= 2 && beats <= 12)) throw new Error(`worldfilm: --beats is 2 to 12 (got ${beats})`);+ const beat = (60 / bpm) * fps; if (!Number.isInteger(beat)) throw new Error(`worldfilm: ${bpm} bpm at ${fps} fps is not a whole number of frames a beat`);+ const share = { calm: 0.35, lively: 0.55, snappy: 0.8 }[temperament]; if (!share) throw new Error(`worldfilm: temperament is calm, lively or snappy (got ${temperament})`);+ const portrait = H > W, zoom = 1 / 1.16, step = portrait ? Math.hypot(0.35 * W, 1.1 * H) : Math.hypot(1.1 * W, 0.35 * H);+ // the camera's move is long enough for the temperament: an in-out cubic peaks at 3x its mean speed (world.minTravel)+ const move = Math.ceil(Math.ceil((3 * step * zoom) / ((share * 2.5 * W) / fps)) / beat) * beat, hold = beat * 4, dur = beats * hold + (beats - 1) * move + beat * 2; // 4 beats on each region, then the move, 2 beats to land+ return `// ${name}: ONE WORLD. Every beat is a region of one canvas; one camera travels between them. Replace the+// titles and the card drawing; keep the structure: no beat is a slide, every seam is a camera move.+// Check it with: node tools/motionscan.mjs ${name} and node tools/layerscan.mjs ${name}+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import { setType } from "./kinetic";+import { alternate } from "./motionKit";+import { world, type Rect } from "./world";++const W = ${W}, H = ${H}, FPS = ${fps}, BPM = ${bpm}, HOLD = ${hold}, MOVE = ${move};+const INK = "#111214", PAPER = "#f4f1ea", ACCENT = "#ffde59"; // put the brand's own colours here (and in meta.motion.brandColors)+const TITLES = [${Array.from({ length: beats }, (_, i) => `"Beat ${i + 1}: one line that says it"`).join(", ")}];+const clamp = (v: number) => Math.max(0, Math.min(1, v));++// regions sit along a gentle path, ${portrait ? "stacked down the canvas for a phone frame" : "across the canvas"}; each is one frame big+const REGIONS = TITLES.map((_, i) => ({ id: \`b\${i}\`, rect: [${portrait ? "(i % 2) * W * 0.35, i * H * 1.1" : "i * W * 1.1, (i % 2) * H * 0.35"}, W, H] as Rect }));+const STOPS = TITLES.map((_, i) => ({ f: i * (HOLD + MOVE), at: \`b\${i}\`, hold: HOLD }));+const W0 = world({ W, H, regions: REGIONS, stops: STOPS, alive: { amp: 3, seed: 7 } });++const draw = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H);+ W0.begin(ctx, env, f);+ TITLES.forEach((title, i) => W0.region(ctx, \`b\${i}\`, (r) => {+ const [x, y, w, h] = r.rect, left = alternate(i, [true, false]), t0 = i * (HOLD + MOVE);+ ctx.fillStyle = ACCENT; ctx.fillRect(left ? x + w * 0.06 : x + w * 0.54, y + h * 0.18, w * 0.4, h * 0.64); // the beat's card: opaque, moved by the camera, never faded+ const enter = clamp((f - t0 + MOVE * 0.4) / (FPS * 0.6)), leave = clamp((f - t0 - HOLD) / (FPS * 0.6));+ setType(ctx, env, title, left ? x + w * 0.52 : x + w * 0.06, y + h * 0.52, ${portrait ? 64 : 72}, enter, { color: INK, weight: 800, space: "world", out: i === TITLES.length - 1 ? 0 : leave });+ }));+ W0.end(ctx);+};++export const ${name}: Film = {+ meta: { title: "${name}", W, H, fps: FPS, bpm: BPM, durationFrames: ${dur}, motion: { temperament: "${temperament}", brandColors: [ACCENT] } },+ assets: { images: {} },+ shots: [{ id: "world", start: 0, end: ${dur}, draw }],+};+`;+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const name = pos[0], dir = resolve(opt.dir ?? ".");+ if (!name) { console.error("usage: node tools/worldfilm.mjs <name> [--dir .] [--beats 4] [--format 16x9|9x16|1x1|4x5] [--fps 30] [--temperament calm|lively|snappy]"); process.exit(2); }+ let src; try { src = worldFilmSource(name, { beats: Number(opt.beats ?? 4), format: opt.format ?? "16x9", fps: Number(opt.fps ?? 30), temperament: opt.temperament ?? "calm" }); } catch (e) { console.error(String(e.message ?? e)); process.exit(2); }+ const mod = join(dir, "src/canvas-core", `${name}.ts`), host = join(dir, "src/hosts", `page-${name}.ts`);+ if (existsSync(mod) || existsSync(host)) { console.error(`worldfilm: ${name} already exists in ${dir}; refusing to overwrite`); process.exit(2); }+ mkdirSync(join(dir, "src/canvas-core"), { recursive: true }); mkdirSync(join(dir, "src/hosts"), { recursive: true });+ writeFileSync(mod, src); writeFileSync(host, `import { ${name} } from "../canvas-core/${name}";\nimport { mountFilm } from "./page";\n\nmountFilm(${name});\n`);+ console.log(`one-world film ${name}\n ${mod}\n ${host}\nnext:\n node tools/still.mjs ${name} --frames 0,${Math.round(0.5 * 30 * 4)} --sheet out/${name}-sheet.jpg\n node tools/render.mjs ${name}\n node tools/motionscan.mjs ${name} node tools/layerscan.mjs ${name}`);+}diff --git a/skills/anidoodle/engine/tsconfig.json b/skills/anidoodle/engine/tsconfig.jsonindex abb6fe7..a4c8c4a 100644--- a/skills/anidoodle/engine/tsconfig.json+++ b/skills/anidoodle/engine/tsconfig.json@@ -1,7 +1,7 @@{"compilerOptions": {"target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx",- "strict": true, "noEmit": true, "skipLibCheck": true, "esModuleInterop": true, "lib": ["DOM", "ES2022"],+ "strict": true, "noEmit": true, "skipLibCheck": true, "esModuleInterop": true, "resolveJsonModule": true, "lib": ["DOM", "ES2022"],"rootDirs": ["src", "../example/src"],"paths": { "three": ["./vendor/three/types/Three.d.ts"] }},diff --git a/skills/anidoodle/references/camera.md b/skills/anidoodle/references/camera.mdindex 7f4b942..c687731 100644--- a/skills/anidoodle/references/camera.md+++ b/skills/anidoodle/references/camera.md@@ -95,6 +95,10 @@ name(g, f); // the writing, on the film's own framecues.push({ frame: t.filmFrameOf(LANDING), kind: "paper" }); // a sound on a remapped event```+- **Every key names its unit**: `f` (a film frame), `film` (seconds of film time) or `scene` (seconds of+ scene time, resolved through the keys before it), exactly one. A bare number throws, because a+ speed key set in scene seconds when film seconds were meant once put a logo's speed-up in the wrong+ place.- **A ramp eases the speed**, on a smoothstep (or `curve: "linear"`), so it starts and ends withno kick. `ramp` defaults to 0, a deliberate hard change of speed; give it frames to glide. A slowed scene is asked for frames between its frames, so it mustdraw at fractional time (motion is a function of time, never of a frame counter).diff --git a/skills/anidoodle/references/formats.md b/skills/anidoodle/references/formats.mdindex 6b9c422..47240b5 100644--- a/skills/anidoodle/references/formats.md+++ b/skills/anidoodle/references/formats.md@@ -90,9 +90,21 @@ Render options that hold for every moving format:Words on screen, wherever the shape:-- **Reading time.** Each text stays up at least `max(0.7 s, 0.3 s per word)`. A launch film's cues- are `meta.captions`; `node tools/framecheck.mjs <name>` fails any cue held shorter and reports- `N/A` for a film that declares no cues (it cannot see words it was not told about).+- **Reading time.** Each text stays up at least `max(0.7 s, 0.3 s per word)`. `node tools/framecheck.mjs+ <name>` times every block of text the film DRAWS (glyphs joined into words and blocks, through+ layers and clips; typed text is timed from its last character) and fails any block held shorter.+ It is never N/A while text is drawn: a film that draws none says NONE with the evidence, and no+ frame checked is a FAIL. Text meant as texture is drawn inside `texture(ctx, draw)` and skipped.+ Build holds from the rule, not by feel: `readable.ts` `chatHold(text)` is think time (about 0.6 s)+ plus typing (about 52 characters a second) plus the full read AFTER the last character, times one+ `pace` scalar (`paced`, per section if needed). Worked example: an 11-word typed reply needs 3.3 s+ of reading after it finishes; a launch film held it 0.9 s, viewers said "too fast" twice, and even a+ 25% slowdown left it under the floor. "20% slower" is then one number, `pace: 1.2`.+- **Layout and the last second.** framecheck also fails more than 7 text blocks in a frame, 5 or more+ packed into under 30% of it, a centred stack of 5 or more, gaps under 3% of the short side, text+ over text or across a card's edge (held 0.5 s), any line under 28 px at 1080 in the last second,+ an end card that lands twice, and people in one sequence whose heads differ by more than 10%.+ A deliberate dense frame (a UI beat) is declared in `meta.checks.layoutExempt` with its reason.- **No text on a busy picture without a plate** (`craft-bar.md`).- **Phone safe zones, 9:16 only.** Reels, TikTok and Shorts lay their own name, caption, buttonsand progress bar over the frame. Keep text and key content out of the top 14 % and bottom 25 %@@ -118,6 +130,13 @@ frame `--fidelity-psnr` compares; default 0). All of it is opt-in beyond the conso transparent and non-uniform pieces pass cleanly. For a file that ships, add `--delivery`: anear-blank frame 0 then FAILS instead of warning; the fix is `render --poster-frame N`.+**Venue screens.** A film that will also loop on screens at an event: ask first what plays it (a+video player, a presentation app), make the loop seam clean (`gate` checks the last frame against+frame 0 for loops), and never depend on the sound, which venues often mute.++**Ship.** Before any version is shown to anyone, `node tools/ship.mjs <film> --file out/<file>.mp4`+runs every check on that exact file and writes a table and a critic sheet beside it (`workflows/review.md`).+A still needs a browser only (`npx playwright-core install chromium`). Anything that moves also needs`ffmpeg`. `gate.mjs` runs on all of them and marks the checks that do not apply to the piece,a silent loop's audio or a still's dead air, as `----` rather than passing them.diff --git a/skills/anidoodle/references/motion-grammar.md b/skills/anidoodle/references/motion-grammar.mdindex c0f995c..5a127a9 100644--- a/skills/anidoodle/references/motion-grammar.md+++ b/skills/anidoodle/references/motion-grammar.md@@ -146,6 +146,10 @@ roughest. The difference is arithmetic, and `engine/src/canvas-core/seams.ts` docamera look; the entry distance is worked out from the exit speed, so the two always agree.The incoming shot owns the cut frame: the outgoing shot's last frame on screen is the onebefore it, and that is its fastest.+ **This short, fast exit is for camera and world moves only.** Type and photos of people leave in+ 0.5 to 0.7 s, eased in (they accelerate away from rest), and are never motion-blurred: a launch+ film that whipped every speaker card out in 0.4 s with blur on type and faces was called violent,+ twice. A fast exit used as the seam for many cuts is a preset, however well each is timed.- **Through the cut, in depth.** `matchedZoom({ push, exitF, entryF })` does the same for acamera that flies into one shot and out in the next: a dolly push through the cut. A push is aratio, so both sides run in log space and grow at the same rate per frame across the cut. With the default push the@@ -154,7 +158,8 @@ roughest. The difference is arithmetic, and `engine/src/canvas-core/seams.ts` do- **There is a top speed.** Past about two and a half frame widths a second(`speedCeiling(W, fps)`), blur stops reading as motion and shows as a streak with steppedcopies. A move that needs more than that wants a shorter travel with the rest hidden behind- the cut, or a plain cut on the beat. Render fast seams with `--blur auto`.+ the cut, or a plain cut on the beat. Render fast seams with `--blur auto`, which leaves text+ and photo layers sharp.- **Match everything, once.** Whatever crosses the cut keeps its position, size, colour andedge; a property that flips on the cut frame pops. And the resting pose is shown once: if oneshot settles onto a pose and the next opens on it, the first shot's last frame is the move'sdiff --git a/skills/anidoodle/references/music/README.md b/skills/anidoodle/references/music/README.mdindex ca1f0b5..ce0f049 100644--- a/skills/anidoodle/references/music/README.md+++ b/skills/anidoodle/references/music/README.md@@ -21,6 +21,8 @@ notes. You compose every note, and nothing is filled in for you. There is no defPages:- [`compose.md`](compose.md): the workflow, the material format, craft, and the never-reuse rule.+- [`generated-tracks.md`](generated-tracks.md): when the person wants a music-model take or a licensed+ track instead: pinned and costed, cut by whole bars, unpitched effects, mastered and checked.- [`theory/`](theory/README.md): the craft behind it: melody, harmony, rhythm, mood mapping, form andorchestration, sound (psychoacoustics for voicing and mixing). Cited, and measured by`node tools/music.mjs craft`.diff --git a/skills/anidoodle/references/music/generated-tracks.md b/skills/anidoodle/references/music/generated-tracks.mdnew file mode 100644index 0000000..5c01de3--- /dev/null+++ b/skills/anidoodle/references/music/generated-tracks.md@@ -0,0 +1,99 @@+# Generated or supplied music: someone else's track, cut to the film++**Contents:** When to take this path · The route · Prompting a music model · Cutting by bars · Effects under someone else's music · Mastering and the checks · What it cannot do++anidoodle composes its own scores (`compose.md`). Sometimes the person wants a track from a music+model (Lyria, through the Gemini API), or brings a licensed one. That is a first-class path with its+own tools: `engine/tools/track.mjs` (analyse, cut, mix, master, check) and `engine/tools/cues.mjs`+(the film's own event times). Every step below closes a failure from a brand launch film whose+music was made this way by hand: the music ended four seconds before the picture, twice, and the+effects were notes that clashed with the track.++## When to take this path++When the person asks for it, or when they have heard the composed score and want a register the+engine does not reach. Never as a shortcut around composing. The person chooses the provider and+pays for it; anidoodle never calls a paid API. Cost is stated before anything runs, and every take+is logged with its price in a `COST.md` beside the music.++## The route++1. **Agree** tempo, length, sections and style with the person.+2. **Prompt.** `track.mjs prompt --len 70 --bpm 120 --style "..." --sections "0-11 Intro: ...; 11-12 Hard stop: ..."`+ writes the request (a tempo-lock line, "Instrumental only", timestamped sections) and prints the+ price with its source and the date it was checked. It says the request was **not sent**.+3. **The person runs their provider.** For Lyria via the Gemini API: `POST+ https://generativelanguage.googleapis.com/v1beta/interactions` with+ `{"model": "lyria-3.5", "input": <prompt>, "response_format": {"type": "audio", "mime_type": "audio/wav"}}`+ and their key from their keychain ($0.08 per song on the paid tier, checked 2026-10-27; check+ again). Ask for 3 to 4 takes: the model ignores exact timestamps, so takes differ in where they land.+4. **Pin the take.** `track.mjs import <take.wav> --provider lyria-3.5 --cost 0.08 --prompt p.txt+ --licence "..."` writes `<take>.track.json` (sha256, provider, cost, prompt, licence). The film+ declares it as `meta.score = { external: "<take>.track.json" }`.+5. **Analyse.** `track.mjs analyze <take.wav>`: tempo (top candidates printed; pin `--bpm` when the+ ear disagrees, tempo octaves happen), first downbeat, bars with levels, sections, a key estimate+ (marked unclear when weak; takes often ignore the key asked for), the track's own stops, and the+ **real last note**.+6. **Fit the picture to the music.** `trackGrid(cut.downbeats, fps).holdTo(start, minHold)` gives the+ shortest hold that lands on a downbeat; land the logo lock, the card's arrival and other key hits+ on downbeats.+7. **Cut by whole bars.** `track.mjs cut <take.wav> --bars "0-3,4-18" --film <name> -o cut.wav`+ (below).+8. **Cues from the film itself.** Wrap the film with `withCues(film, [{ name, at: { scene: 22, through:+ [master] } }, ...])` and run `cues.mjs <film>`; the cue sheet comes from the film's own time maps, so+ a slowdown or a time-map change moves every cue with it. Never copy times into a second file:+ a hand-mirrored timing script drifted twice on the film this page comes from. `cues.mjs <film>+ --check` fails a sheet (or a mix) that is out of date.+9. **Listen first.** `track.mjs listen <dir> --mix mix.wav` makes a page with each effect alone, a+ 10 s sample of the mix and the takes. A human hears it before the full mix.+10. **Mix.** `track.mjs mix --music cut.wav --cues out/<film>.cues.json --sounds map.json -o mix.wav --stem sfx.wav`.+11. **Master and check.** `track.mjs master <picture.mp4> mix.wav -o film.mp4`, then `track.mjs check`+ and the ship command on the delivered file.++## Prompting a music model++- Say the tempo twice (in the tempo-lock line and in the style), the length, "Instrumental only",+ and the sections with times. A designed stop ("hard stop, one beat of silence") is worth asking for+ at the moment the picture holds its breath.+- Expect to fit the cut by bars afterwards: timestamps in the prompt are wishes.+- Keep the prompts and the takes; the person picks by ear ("take 2, love it").++## Cutting by bars++`track.mjs cut` joins whole bars with centred 12 ms crossfades, so the edit's length is exact and+every join sits on a downbeat. It refuses, and names the bars to add:++- a join more than a little off a downbeat;+- a segment that carries the silence after the last note;+- an outro that stops before the track's own ending (unless you ask for `--fade-out`);+- an edit whose last audible moment ends more than 0.5 s before the picture (`--end-tol`).++The edit's own downbeats are written beside it (`cut.wav.cut.json`) for `trackGrid`, and the track's+own stops become declared quiet ranges, so the dead-air and shape checks do not call them holes.+A segment list with no final newline is read whole (a shell loop once dropped the last segment).++## Effects under someone else's music++**Under a track the engine does not control, effects are transients, never notes.** A note that is+not in the track's key, or not on its chord, is a clash ("the sound effects cannot be melodic, they+make disharmonious interruptions"). Use the `tap` kind (`tick`, `tickHi`, `tock`, `thump`,+`impact`): short strikes too brief for the ear to name a pitch. Tuned kinds (chime, tuned riser,+`impact:bloom`, `press:confirm`) are refused under an external track unless the cue says why+(`pitched: "..."`). Every placed sound's pitch salience is measured in the mix, and `soundcheck.mjs+<file> --sfx sfx.wav` measures the rendered stem: a cue over 0.5 fails. The buried-cue guard runs+against the track too: a quiet cue is raised up to 8 dB against the track's local loudness, and fails+by name if it is still buried. `track.mjs kit --from-pack` cuts a transient kit from the sound pack,+each strike cut from its peak (cutting from the onset kept leading silence and lost the hit).++## Mastering and the checks++`track.mjs master` normalises to -14 LUFS, limits, encodes AAC 256k, then reads the true peak from the+**encoded** file and lowers the limiter until it is at or under -1 dBTP (AAC adds up to about 3 dB to+a peak). It then runs `check` on the muxed file: loudness, peak, the end of the music against the end+of the picture (filmshape), and the declared stops. The ship command runs `track.mjs check`,+`soundcheck --sfx` and `cues.mjs --check` for any film with an external track.++## What it cannot do++It cannot hear. Tempo, key and the last note are measurements; taste is the person's. A take's+own silent tail can still fail the end check by a fraction of a second: add the bars, or ask.diff --git a/skills/anidoodle/references/music/sound-design.md b/skills/anidoodle/references/music/sound-design.mdindex 2ece5e4..c44bcd6 100644--- a/skills/anidoodle/references/music/sound-design.md+++ b/skills/anidoodle/references/music/sound-design.md@@ -50,6 +50,11 @@ speaking window (K-weighted, see below). Duck is how far the score dips under it| brick | clack, snap, tumble | toy bricks: tap, press onto studs, drop on a pile | -15 | 1.5 || thread | pull, pierce, stitch | embroidery: thread through cloth (hit = the tug), the needle | -17.5 | 1.5 |+**Under someone else's music, effects are transients, never notes.** Use the unpitched `tap` kind+(tick, tickHi, tock, thump, impact); tuned kinds are refused unless the cue says why (`pitched`).+The impact's in-key shimmer applies only to scores the engine composes. The route for a generated or+supplied track: `generated-tracks.md`.+## Placing effects in a filmCues are addressed by **film frame**, a whole number (a fractional frame throws; to land a hitdiff --git a/skills/anidoodle/references/storytelling.md b/skills/anidoodle/references/storytelling.mdindex 19f6775..43e1cf5 100644--- a/skills/anidoodle/references/storytelling.md+++ b/skills/anidoodle/references/storytelling.md@@ -30,3 +30,66 @@**Tests before you build.** Say it in three sentences. Name the frame of the turn. Name the token and the two frames where it appears. For every shot ask "what changed for the character"; a shot where the answer is "the rendering style" is a shot to cut. And: every element in frame gets a one-line reason. In our meadow each flower colour, the footpath and the sun all had one. The oval bokeh blobs had none, and they were the first thing the eye caught as fake.**No dead air.** The first riso and watercolour acts were static for half their length and opened on three seconds of empty stock. The rule since: something visibly moves in every second, from frame 0, and a "hold" means the camera creeps while the subject keeps living. Check it with a tool (per-frame changed-pixel fraction, no identical consecutive frames, no 15-frame window under half a percent) and ALSO by eye: a creeping camera changes every pixel and satisfies the tool while the eye sees a still. We shipped a second of exactly that before I caught it on the contact sheet.++## Launch, brand and event films: a story, not a list++> Earned on a brand launch film that went through twelve versions. Its first board was nine facts,+> one per frame, and the note was "the whole thing literally looks like a deck". `tools/board.mjs`+> checks every rule below on the board, before anything is drawn.++- **A row is an action, never a fact.** Each storyboard row says what MOVES and what it becomes, and+ what it **carries** in from the row before (an object, a shape, the camera). Two rows in a row that+ carry nothing are two slide cuts. "You talk to AI all day" on its own frame is a slide; the AI's+ typing dots falling out of the chat into a crowd is a film.+- **A message, not just information.** Write the line the viewer should leave repeating ("AI is+ changing marketing. Nobody has a prompt for that.") beside the story sentence. A film that only+ informs plays as a promo deck.+- **The brand arrives as the answer.** After the problem line, the brand is shown as an action (the+ crowd wiring itself into a network) and the mark is **built from the thing that just acted** (the+ network's thread becomes the logo's neck). Test: "why does the logo appear now?" answered in one+ sentence from what is on screen. A thesis line followed by a logo, with no bridge, is a cut to an ad.+- **One actor carries the film.** Name it in the brief (the AI's three typing dots: its face, its+ fall, the crowd, the logo's dots, the last reply). It crosses every seam it can.+- **Counts change for a reason.** Three dots becoming two "for no reason" reads as noise. Keep the+ count, or show why it changes (one dot hops up and joins the network).+- **A count on screen is a claim.** Six "?" dots promise six more speakers. Use one symbol for "more+ to come", or source the number (`facts.md`).+- **The promise is what the viewer does and leaves with.** "Multiply your marketing intelligence"+ meant nothing to anyone; "Half a day with marketers who already figured it out. Leave with real+ systems that get real results." did. A brand tagline goes in only if it passes that test.+- **Say each thing once.** "About 400 of them" in the hook and "400+" on a numbers card is one fact+ told twice; cut one (`facts.mjs` fails a repeated number without a `reuse` reason).+- **One landing.** The last thing on screen is the end card OR the stinger, never card, stinger,+ card again. "Started with a conversation, end with a conversation." A stinger answers something+ visible in the three seconds before it.+- **Text that is not meant to be read must look unreadable.** Fast filler replies in real words make+ the eye try to read them; use "blah blah", greeked lines, or one real line then blah.+- **Events list their people.** Hosts and organisers, speakers (all of them, name, role and logo,+ no talk titles), sponsors and partners are brief fields, each present or excluded by the person.+ The hosts' own beat ("who's running this thing?") was the one viewers loved most.++## Comedy++> Same film. Its comedy scored 8 and 9 with critics, then most new jokes were "not funny, try harder",+> because every joke had one shape: the AI chimes in with a quip.++- **Pain first, then gags.** List the audience's lived pain points (the em-dash habit, "Great+ question!", "Compacting conversation...", "You've reached your limit, try again in 4 hours"), then+ write one gag per pain. Specific nouns beat generic AI jokes.+- **Punch at the situation or the habit, never at the tool the audience relies on, and never at a+ real person.** "Make it funnier without making AI look stupid": the AI became a witty wingman.+- **Pitch across devices.** A batch of pitches spans at least four: verbal, visual pun (an "I'm not a+ robot" box ticked beside "100% in person"), interaction (the user types "make no mistakes"),+ physical comedy, structural (self-editing copy, an empty chair). Each pitch names its device and+ where it lands. An observation (true, with no twist) is not a joke. Constraints you set yourself+ ("jokes only when the AI talks") are said out loud so the person can lift them.+- **Who gets it, in one line.** Every gag carries a note of who laughs and why. A gag that needs+ explaining to the client ("cameras can't be off"?) is cut or rewritten ("Nobody's on mute.").+- **A character keeps its visual voice.** A line spoken by the AI always looks like the AI's bubble+ (dots, then its type), even when it is the person's favourite joke dropped in late.+- **Self-aware hosts land.** "Three humans. I just take notes." The people behind the thing, laughing+ at their own role, beat any clever line about the product.++`board.mjs` holds the checkable half: each joke has a device, a "who gets it", and a butt that is a+situation or a habit; no device carries more than 60% of the jokes; pitches span four devices and+each has a twist; every speaking character has a registered visual voice.diff --git a/skills/anidoodle/references/workflows/brand-film.md b/skills/anidoodle/references/workflows/brand-film.mdnew file mode 100644index 0000000..fdfc14e--- /dev/null+++ b/skills/anidoodle/references/workflows/brand-film.md@@ -0,0 +1,167 @@+# Brand films: someone else's brand, exactly++**Contents:** Why this page exists · Step 0: one reference film · Step 1: the inventory · Step 2: getting the files out (four routes) · Step 3: import and sign-off · Step 4: logos · Step 5: fonts and motion tokens · Step 6: people and their photos · Step 7: the brief and the board · Step 8: the hardest shot first · What a brand element may do · Data from the live site · Design critique before the first render++A brand film is a launch, event or campaign film made in a brand that already exists: a logo, a+shape language, colours, fonts, maybe motion. Everything in `launch-video.md` applies. This page adds+what a brand changes, and every rule on it was paid for on a brand launch film that took twelve+versions: wrong elements drawn from screenshots, a logo morphed through goo, the wrong company logo+three times, sponsors "not in the design file" when two frames held them, and a font never supplied.++## Why this page exists++To the brand's owner, a mark redrawn by eye is a different mark, even when it is close. So brand+elements are **imported, never drawn**, and the film only ever **moves** them. Nothing on this page+is a style choice; each step closes a door a past film walked through.++## Step 0: one reference film++Before the brief, pick ONE reference film with the person (a launch film they admire, a keynote+title sequence). Deconstruct it into notes beside the project: frames every 0.5 s, shot lengths,+seam types, camera moves, how type enters and leaves, how long text holds. Take its **grammar,+never its content**. A film started with no reference drifts toward slides, and "this is the level+of mastery I expect" arrives as a note in round five instead of a target in round one. The board+records it as `brief.reference` (`board.mjs` fails a brand film without one, or without a reasoned+"none: ...").++## Step 1: the inventory++On first access to the brand source, list **every** frame in it, not only the ones you plan to use:++```bash+node <skill>/engine/tools/brand.mjs inventory --figma <fileKey> # Figma REST (FIGMA_TOKEN)+node <skill>/engine/tools/brand.mjs inventory --figma-json file.json # a saved REST response+node <skill>/engine/tools/brand.mjs inventory --dir brand-pack/ # a folder of exports+```++It writes `brand/INVENTORY.md` (page, frame, id, size, the words on it, a read box per frame),+`inventory.json`, and the file's own transition timings as `motion.json`. Then:++- **"Is X in the file?"** is answered with `brand.mjs find X`, which searches every frame name and+ every word on every frame. "Not there" is only ever said with the count of frames searched.+- **Read every frame.** Mark each `[x]`, or `[-] <why it does not matter>`. `brand.mjs check` fails+ while any frame is unmarked or skipped with no reason. Partner, sponsor and speaker frames hide+ under names like "Social Media partners".++## Step 2: getting the files out (four routes)++Try them in this order; never modify the source file.++1. **Figma REST API, read only.** The person makes a personal access token (file read scope) and+ exports it as `FIGMA_TOKEN`. `brand.mjs import --figma <fileKey> --nodes <id,id>` renders each node+ as SVG with text outlined and imports it. The node ids come from the inventory.+2. **Figma's own MCP server**, if the person has it connected: export each node as SVG with text+ outlined, then import the files.+3. **The plugin API in a browser tab**, when the file is open in a browser the agent can drive:+ `node.exportAsync({ format: "SVG_STRING", svgOutlineText: true })`. Browser tools often truncate+ results near 1,000 characters, so stage the string on `window` and read it back in slices.+ Slow and fragile; use it only when 1 and 2 are closed.+4. **Ask for an export**: one zip of SVGs (text outlined), one file per element, named for what it+ is. Asking costs one message; guessing costs a round.++A brand pack, a site's own SVGs, or an Illustrator export are imported the same way.++## Step 3: import and sign-off++```bash+node <skill>/engine/tools/brand.mjs import brand/src/ --ts src/canvas-core/myBrand.ts --sheet --on '#111'+```++- Each SVG becomes one element: its exact path data, fills, gradients (linear and radial, in either+ unit system), transforms, `<use>` and `<symbol>`, CSS classes, clip-paths and hard white masks,+ each part with its box. Path data is never rewritten; transforms ride beside it as a matrix.+- It writes `brand/brand.json` and a TS module exporting `BRAND` (elements, palette, fonts, motion)+ and `brandMeta` (colours and element names). Put `brandMeta` in the film's `meta.brand` so the+ gate knows which colours are the brand's, and spread `brandMotion` into `meta.motion` so layerscan+ fails a brand colour drawn half-transparent.+- It prints what each mark can do in motion: **rotational symmetry** (a mark that is the same after+ a half turn can land from a spin without a jump) and **repeat periods** (a frieze whose shapes+ repeat every N units tiles without a seam when stepped by N). Plan moves around those numbers.+- It names what it cannot draw (a soft mask, a filter, a pattern fill, an embedded image, live text)+ instead of dropping it silently.+- `--sheet` draws every element twice, from its source SVG in the browser and from the import, and+ **fails past 1% different ink**. Show `brand/sheet.png` to the person and get the sign-off before+ the first storyboard. Every later frame is built from what they signed.++## Step 4: logos++Partner, sponsor and company logos are the same problem in miniature.++- **Copy where it is rendered in production first.** Screenshot the logo where the company uses it+ (its site header, its product), then rebuild from its SVG. `brand.mjs logo film-logo.svg --ref+ shot.png` puts the two side by side at one height; the person sees that still before the logo+ goes in. A company with a mark and a wordmark has an order, a colour per part and a spacing; none+ of it is guessed.+- **One strip, equal weight.** `brand.mjs logos sponsors/ --on dark` trims transparent margins+ (a PNG with a wide margin renders tiny), writes a one-colour version for the ground, measures each+ logo's ink and prints the height at which every logo reads equally heavy, with a strip still.+ A PNG on a solid background is refused: ask for a transparent export or the SVG.+- **Never fix a client's mark.** Overlapping outlines (letters that share a stroke) are flagged+ "check with the owner". It is usually their real design; ask, do not repair.++## Step 5: fonts and motion tokens++- **Fonts.** The import lists any live text's font. Ask ONCE, early, for the font files (OTF, TTF+ or WOFF2) or for exports with text outlined. If the font never arrives, the brief records the+ stand-in face, and the review page flags every line set in it. A stand-in that mixes with the+ brand face in one frame reads as a mistake.+- **Motion tokens.** If the source has prototype transitions (Figma interactions), the inventory+ saves their durations and easings (`motion.json`, merged into `BRAND.motion` as named tokens).+ `motionTokens(BRAND.motion, fps)` in `motionKit.ts` turns them into eases and frame counts. A+ brand's own turn (say a half-turn over 2 s on `cubic-bezier(0.5, 0, 0.5, 1)`) is the film's first+ easing choice. Spring easings have no bezier form and are set aside for the person, never guessed.+- **Temperament.** Set it before motion: how fast things may move (a share of `speedCeiling`),+ how long they settle, whether anything overshoots (`temperament()` in `motionKit.ts`). A brand that moves "like poured liquid" never+ springs; a playful one may. A film corrected first for "violent" and then for "flat" never had one.++## Step 6: people and their photos++- **Program data comes from the live site**, cited as a site source with its date (`facts.md`):+ name, role, company logo, slot. Every speaker is listed (no mystery speakers); talk titles are off+ by default because nobody reads them in a film (`board.mjs` program rules).+- **Hosts, organisers, sponsors and partners are brief fields** for an event: present, or excluded+ by the person with a reason. The people running the event are often the beat viewers like most.+- **Photo restoration and cut-outs.** When the person asks, a supplied photo may be restored or cut+ out by an image model they choose (through their own subscription tool). Show the original and the+ result side by side on the film's background before use; the original file stays untouched; record+ the model and date in the asset manifest. A model may change clothes or lighting: compare, then ask.+- **Faces are sized by head, not by photo.** Normalise people in one sequence by head height with+ crowns level; a photo cropped looser makes its person look smaller.+- **A real face is never covered, cut or swallowed by a moving shape.** The person enters and+ leaves with their stage.++## Step 7: the brief and the board++`board.mjs init` writes a board with every field; `board.mjs board.json` checks it before anything is+drawn (`storytelling.md` has the why for each rule). For a brand film it requires: the story sentence+and the message; the comic premise or "none: why"; a promise that says what the viewer DOES and+LEAVES WITH (a brand tagline is used only if it passes that test); the actor that carries the seams;+the people fields; the reference film; and for every row, what it carries in from the row before.+The brand's reveal row says why the logo appears now and what it is built from.++## Step 8: the hardest shot first++No second scene until the hardest shot (usually the logo reveal) is rendered, critiqued and approved.+Once approved, **lock it** (`lock.mjs <film> --shot <id>`, the sha into `meta.motion.approved`,+`motion-film.md`): an approved shot is restored exactly, never "improved" in passing.++## What a brand element may do++Translate, rotate, scale evenly, clip, mask, layer, tile by its measured period, and appear part by+part (`riseIn`). It may not be squashed, skewed, blurred, morphed or blended into another mark, and a+brand colour is never shown half-transparent (yellow at 50% over black reads olive). In code:+`brandKit.ts` `drawEl` throws on a non-uniform scale or a skew; a squash that IS the joke passes+`{ allowSquash: "<the gag it serves>" }`. `placeEl` positions by centre and height and is uniform by+construction. Draw helpers multiply the caller's alpha and keep its transform, and every drawn mark+reports its on-screen box to the frame probe, so the scans see brand shapes crossing a face.++## Data from the live site++Fetch site data with the web reader the session has, not with ad-hoc downloads (security hooks block+those, rightly). Save what you used with its URL and date as the facts source.++## Design critique before the first render++Before the first full render, run a design critique on the storyboard stills with whatever design+skills the person has installed (name them in the brief), and re-read the person's last notes against+the new sheet. Judge hierarchy, flow and brand temperament first; collisions second.diff --git a/skills/anidoodle/references/workflows/facts.md b/skills/anidoodle/references/workflows/facts.mdindex 94c58cc..9b849e6 100644--- a/skills/anidoodle/references/workflows/facts.md+++ b/skills/anidoodle/references/workflows/facts.md@@ -15,6 +15,13 @@ research ledger (`explainer.md`) made general, and the launch film's list of appdata: `generated: true` with a note saying what it is. A generated entry states no number; anumber needs a source.- **A claim you cannot source is cut**, or shown plainly as a metaphor.+- **A count drawn on screen is a number.** Six "?" dots claim six more speakers; three seats claim+ three places left. List it with digits ("6 more speakers") so it needs a source, or draw one symbol.+- **Say each fact once.** The same line twice, or the same number on two cards ("about 400" and+ "400+"), fails; the later entry may carry `reuse: "<why the repeat earns its place>"` (a date on+ the hook and the end card, say). Single digits are counting words and never flagged.+- **A live site is a source with a date.** `"source": { "kind": "site", "url": "...", "fetched":+ "2026-10-27", "sentence": "..." }`: sites change, and the date says what was true when you read it.## The file@@ -42,7 +49,10 @@ and any `claims: [...]` in its spec; any other film sets `film.claims`. It fails- a sourced entry lacks the sentence, or a URL (http/https) or file;- a generated entry has no note, or states a number;- a number in a sourced claim is not in its source sentence;-- a claim is still a TODO.+- a claim is still a TODO;+- a line is declared twice, or two entries state the same number (10 or more, or with %, + or x),+ and the later one has no `reuse` reason;+- a `site` source has no URL or no `fetched` date.A film that declares no claims reports `N/A`, never a pass. The check is light on purpose: itcannot know a sentence is true. The critic does that by reading each source beside the filmdiff --git a/skills/anidoodle/references/workflows/launch-video-kit.md b/skills/anidoodle/references/workflows/launch-video-kit.mdindex fd9d96c..2303a26 100644--- a/skills/anidoodle/references/workflows/launch-video-kit.md+++ b/skills/anidoodle/references/workflows/launch-video-kit.md@@ -10,7 +10,9 @@ product. The rules they serve are in `launch-video.md`.`launchTemplate.ts` turns data into a film: one to three asks, a type frame between them, and anend card with your install lines. `launchExample.ts` is a complete one for a made-up product (thedrawn look, chat asks); `launchExampleClean.ts` is the second look on a UI-first product (the-product's own UI in three screens, two of them split beats, 60 fps). Copy their shape, not their contents:+product's own UI in three screens, two of them split beats, 60 fps), and `launchExampleCleanChat.ts`+is the clean look with a chat ask (the hook, an answer card opening as an iris, a word page, then the+product's screen). Copy their shape, not their contents:the plates, the UI data and the score are the product's own, made for its brief.```bash@@ -79,11 +81,20 @@ What you get, from data:- **Chat asks** (`kind` omitted): the hook: the first prompt is the hero, already being typed atframe 0 in a big composer across most of the frame (at least 64 px type on 1x1/4x5/9x16, 56 px on16x9, wrapping to 2-3 lines, never clipped; a prompt too long for that is an error), which shrinks- and docks at the bottom of the chat as Generate is pressed. Later prompts are typed with the whole+ and docks at the bottom of the chat as Generate is pressed (over a second, or longer when the+ distance would take its fastest point past what the brand's motion temperament allows: a calm+ brand's hook on a phone frame docks over nearly two). Later prompts are typed with the wholecomposer in frame, the camera easing out for the press, an ink drop arcing from Generateinto the thread and blooming open into a card where the plate draws itself live (the card openson a spring), the thread keeping earlier answers and scrolling, a gentle lean onto each new card that keeps it whole with a margin (what the camera is about- to cut fades first).+ to cut fades first). The drawn dock keeps the hook's line breaks until it lands (no word jumps a+ line on the move) and re-wraps once, at rest. In the clean look the hook's composer glides down+ whole and IS the dock: it never shrinks, on the move or after it lands, and rests a moment before+ Ask is pressed (on 9x16 it is laid out a little narrower, to dock clear of the phone's right-hand+ zone). The drop flies as one solid streak of the accent, over as many frames as its distance needs+ to stay inside the brand's temperament, the answer card opens as an iris, and the window+ stays whole and opaque while the camera leans in (still moving as a travel takes over), so no+ brand colour is ever see-through.- **UI asks** (`kind: "ui"`): the product's interface drawn from data (`productUI.ts`) in its`before` state; the ask typed into its command bar if it has a `prompt`; the pointer presses its`action`; every item springs to its place in the `after` state (matched by `id`: rows move,@@ -91,9 +102,13 @@ What you get, from data:- **Film asks** (`kind: "film"`): any film of this engine (a `webTour`, a loop, a plate) in a card.- **Split feature beats**: a UI or film ask with `split: [lines]` puts its words in their owncolumn beside the live UI (above it on a phone), never over it: faster than a full word page.+ The words are sized to their column's width and height (set smaller and rewrapped when they would+ run down over the product); their read, once set and the product has landed, is a declared hold+ (after a travel in, from the moment they are set, through the press, until they sink).- **Seams**: chat to chat is one thread; a seam between kinds with no word page opens as a bloom.- **The motif**: an ink drop lifts off Generate (or the product's action, or the film's card) andlands as the dot of the end card's mark ("NAME."); the end card blooms open FROM it and stays.+ The last split beat's words finish sinking halfway through its flight, gone before it lands.- **Sound from the picture** (`launchSound.ts`): a key per character typed (the space bar itsown), the press on the frame Generate goes down, the drop and its bloom, each card landing on itsspring's first arrival, each UI item's landing; every cue panned to where it happens on screen;@@ -135,13 +150,38 @@ Every line a viewer must read is phone-safe on 1x1, 4x5 and 9x16: at least 32 px(about 11 pt on a phone) for prompts, bubbles, card labels, tagline and install lines, 64 px for aword page; the layout throws with the fix when one cannot be (an install line too long for 9x16).-### Two looks--`preset: "drawn"` (default): ink blooms, hand-lettered words (`writeOn`), a warm paper palette.-`preset: "clean"`: a quiet canvas, ONE accent colour (the button, the drop, the dot, the caret;-`accent` sets it), type as the design: word pages SET in a heavy sans (`setType`: each word rises-into place behind its own baseline), round iris seams instead of ink, the answer card opening as-an iris. Both are ours: the clean look is a register, not a copy of anyone's film.+### Looks: the film wears the product's own look++A look is a base grammar plus the product's own tokens. `look.base` picks the grammar; every other+field dresses it, and any field left out keeps the base's value. `preset: "clean"` is shorthand for+`look: { base: "clean" }` (a preset and a base that disagree are an error). With no look the film+draws exactly what it drew before (launch, launch2 and launch3 render byte-identical).++The two bases:+- `drawn` (default): ink blooms, hand-lettered words (`writeOn`), a warm paper palette.+- `clean`: a quiet canvas, ONE accent (the button, the drop, the dot, the caret), type as the design:+ word pages SET in the display face (`setType`), round iris seams, the answer card opening as an+ iris. It takes every kind of ask: chat asks (the hook's composer glides down whole and IS the dock;+ give the answer plate a ground other than the card's, or the iris opens unseen), product screens and+ films. `registerLook(name, { clean, palette })` adds a base of your own.++| Field | What it sets | Notes |+|---|---|---|+| `look.base` | the grammar: `"drawn"`, `"clean"`, or a registered look | `preset` is its shorthand |+| `look.palette` | any of `bg card ink soft mute line chip accent accentDeep paper` | merged over the base; checked for contrast (below) |+| `look.fonts` | `{ display, text, mono }`, each `{ family, file }` | `file` is a local `.ttf` imported into the film (`import f from "../../assets/fonts/X.ttf"`); registered before the first frame, no network; every measure, wrap and reading-time path uses its own glyph advances. A missing file or an `.otf`/`.woff2` is a clear error (convert to `.ttf`) |+| `look.shape` | `radius`, `bubble` (`rounded` `square` `none`), `composer` (`box` `bar`), `button` (`pill` `square`), `buttonLabel` | the radius caps every corner, the chat's and the product UI's alike |+| `look.chat` | `header` on/off, `title`, `subtitle`, `logo` (a brand element, drawn with brandKit `drawEl`), `bubble` and `reply` `{ fill, ink }` | a logo also opens the clean end card, before the name, on its baseline |+| `look.from` | a brand file from `node tools/brand.mjs import` | fills the palette (its saturated colour the accent; a dark-first file the ground and ink) and the logo; explicit fields win |++The product's own screen is a `kind: "ui"` ask (`productUI.ts`): it takes the look's face, label colour+and shape too. READABILITY: a custom palette is checked pair by pair (WCAG AA: 4.5:1 for body text,+3:1 for large type and the button's label), only on pairs that touch a token you changed, and the build+fails naming the token and both colours. On a dark ground the pointer turns light. `launchExampleBrand.ts`+is the worked example: an invented brand, dark ground, a serif display face, square shapes, its own logo,+a chat ask and a product ask; `node tools/launch.mjs new` scaffolds a commented `look` block.+With two or more install lines, use `endCard: "grid"`: the stacked card is then five blocks centred+on one axis, which framecheck fails as a centred stack.### Frame rate and motion blur@@ -159,7 +199,7 @@ many subframes as each frame's measured on-screen speed needs (1 on a still fram| `claims` | extra on-screen or narrated claims for `facts.json`; the words, split words and tagline are claims already || `claimBar` | land the end card on this bar's downbeat, counting from bar 0 (`claimBar: 4` = frame 4 x bar); throws if it cannot. A longer last ask is really longer, never slowed || `score` (required) or `audio` | the score composed for this product (the `Material` function compose.md writes, or a `Piece`), as a bed; `null` for silence; or your own finished mix (not checked; it replaces the cues too) |-| `shape`, `preset`, `sfx`, `motif`, `captions` | the frame (16x9 default); the look (drawn, clean); sound cues (default on); the relay into the end card (default on); `"sidecar"` (default) or `"burn"` |+| `shape`, `preset`, `sfx`, `motif`, `captions` | the frame (16x9 default); the look (drawn, clean); sound cues (default on; `launch.mjs new` writes `sfx: false` beside `score: null`, since cues alone are clicks on silence that soundcheck fails: turn them on with the score); the relay into the end card (default on); `"sidecar"` (default) or `"burn"` |The template refuses a feature list (more than 3 asks) and an end card too short to read.@@ -182,7 +222,9 @@ The template refuses a feature list (more than 3 asks) and an end card too short- `writeOn(ctx, env, text, x, y, size, p, style, opts)`: a line written stroke by stroke by avisible tool, in `ink`, `crayon`, `thread`, `chalk`, `brick` or `marker`. `measure` sizes it.- `setType(ctx, env, text, x, y, size, p, opts)`: a line SET in a heavy sans, each word rising- into place behind its baseline: the clean look's type. `setWidth` measures it.+ into place behind its baseline: the clean look's type. `setWidth` measures it. `{ out }` sinks it out+ last word first on an ease-in over 1.3x its size (no slivers at the clip edge); `{ space: "world" }`+ draws it inside a camera or a region (`motion-film.md`).- `sentence` (one medium per word, one word per beat), `caption` (a small callout with anunderline or arrow), `logo`/`logoCentred` and `logoBug` (anidoodle's own wordmark and cornermark; for your product, write your name with `writeOn` as the template does).@@ -232,3 +274,4 @@ scaffold leaves them out; `scaffold.mjs <dir> --example` brings them in (with thare built on) to study. Study them for pacing, then build yours onthe template with your own pictures and your own music; anidoodle's launch is one example of thegrammar, not a skin to reuse.+`launch.ts`, `launch2.ts` and `launch3.ts` are frozen reference builds of that published film, made before the 0.10 checks (their declarations say so, `FROZEN` in `launchKit.ts`): never templates; start from `launch.mjs new`, whose examples pass `ship.mjs`.diff --git a/skills/anidoodle/references/workflows/launch-video.md b/skills/anidoodle/references/workflows/launch-video.mdindex 2ad39b9..ebcbd97 100644--- a/skills/anidoodle/references/workflows/launch-video.md+++ b/skills/anidoodle/references/workflows/launch-video.md@@ -12,7 +12,11 @@ a template film renders a 16 s launch for any product from data.Product screenshots, a logo, UI captures, a repo link, a feature list, the exact install orsign-up line. Images they bring may be embedded (pinned by sha256, provenance in the manifest);-everything around them is drawn in code. Never generate or fetch images.+everything around them is drawn in code. Never generate or fetch images on your own. One exception+the person opts into: a photo they supplied may be restored or cut out by an image model they choose,+shown beside the original on the film's background before use, with the original kept and the+model recorded in the manifest (`brand-film.md`, people). A film in someone else's brand starts with+`brand-film.md`: the brand's exact elements, logos and motion are imported and signed off first.## Ground it in the real product first@@ -50,6 +54,10 @@ pieces are examples of the craft, never material for someone else's film.- **Arc**: hook, one core interaction, a fast proof of range (a wall, never a slow tour), thebrand moment, the call. A visual payoff every 3-5 s; no dead waits.- **No footnotes, no eyebrow text, no terminal jargon on screen** unless the product is one.+- **A board row is an action, never a fact**, and names what it carries in from the row before; the+ brand arrives as the answer, built from the thing that just acted; one message line beside the+ story sentence; a promise that says what the viewer does and leaves with; one landing at the end.+ The why is `../storytelling.md` ("Launch, brand and event films", "Comedy"); `board.mjs` checks it.## Type@@ -69,11 +77,16 @@ pieces are examples of the craft, never material for someone else's film.- **3-7 words a frame, few frames.** Collapse word cards into one claim then proof ("JUST CODE."then "32 STYLES"); fewer cards leave more time for the proof.- **Hold each settled word 0.5 s or more**, longer for the claim.+- **Text meant as texture looks unreadable** ("blah blah", greeked lines). Real sentences that are+ up too briefly make viewers try, and fail, to read them.- **Judge DESIGN in review stills, not only collisions**: hierarchy, spacing, whether the framewould pass as a poster. A frame with nothing overlapping can still be ugly.## Motion+- **One world, one camera, by default.** Start with `worldfilm.mjs` and build on `world.ts`: every beat+ a region of one canvas, every seam a camera move. Built scene by scene, a film plays as slides however+ well each scene moves. `motionscan` and `layerscan` hold it (`motion-film.md`).- **A gentle move is the default transition**: bloom, card flip, push, the card GROWS into theframe. Ease in and out; the camera is `references/camera.md`.- **A hard cut is a judgement.** It works when it is matched: the same shape, position or@@ -115,8 +128,19 @@ into place), round iris seams, the product's own UI. Pick one per film; never mi## Brand and the end card- **The logo recurs**: a small corner mark on every frame (`logoBug`), not once at the start.+- **One landing.** The last thing on screen is the card or the stinger, never card, stinger, card.+- **Event programs** show every speaker as name, role and company logo (from the live site, dated),+ no talk titles and no mystery speakers; the panel's title once. Hosts and sponsors are in the brief.+- **Logos of other companies** are copied from where they are rendered in production, sized to equal+ visual weight, never "fixed" (`brand-film.md`, logos).- **The end card is composed for the frame**: the name, one line, the exact install lines in a- panel, held **3 s or more** so a viewer can screenshot them. anidoodle's are both lines:+ panel, held **3 s or more** so a viewer can screenshot them. For an event or campaign, build it on+ `endCard.ts` (`endCardLayout`, `drawEndCard`): one card, one frame, an asymmetric grid with the+ lockup top-left, the event lines under it, the call as a stamp on the right on the venue's baseline,+ a hairline, then a sponsor band (label 38 px, weight 800 at 1080; each sponsor switchable), in every+ shape. Never a centred stack of five or more items, never extra slides for what did not fit.+- **People** (speakers, hosts) are placed by head height with crowns level (`people.ts` `drawPerson`);+ `popOut` puts a person on a disc with the head free above it. anidoodle's are both lines:`/plugin marketplace add alexgreensh/anidoodle` and`/plugin install anidoodle@alexgreensh-anidoodle`. One primary call; the link smaller below.@@ -126,7 +150,11 @@ into place), round iris seams, the product's own UI. Pick one per film; never miCompose it for THIS brand: pick the style and a mood per section from the brief (energy,audience, where it runs), then write the notes (`references/music/compose.md`). anidoodle's ownlaunch chose chill lo-fi electronic, one example (`references/music/styles/lofi-electronic.md`);- never reuse our score or a stock piece.+ never reuse our score or a stock piece. When the person asks for a generated or licensed track,+ it takes its own route (`references/music/generated-tracks.md`): pinned and costed, cut by whole+ bars, effects unpitched, the music never ending before the picture.+- **Effects and a 10 s mix sample are heard first**, on a listening page (`track.mjs listen`), before+ the full mix. You cannot hear; the person can.- **Balance by stem RMS, not only LUFS**: an integrated -14 LUFS hid a sub 7-10 dB too hot.- **Cut on downbeats, not every beat.** Land the claim on a chord (launch3's lands on bar 26,the home chord); `beatGrid().solve()` fits a flexible segment so it does.@@ -141,8 +169,13 @@ into place), round iris seams, the product's own UI. Pick one per film; never mi## Delivery- **Length**: about 60 s for a launch post (LinkedIn, YouTube, the README); 15-45 s for X; cut- a platform version rather than pushing one master everywhere. Cut whole beats; never speed- the whole film up (it breaks the beat grid and reads rushed).+ a platform version rather than pushing one master everywhere. Set `length.target` and+ `length.max` in the brief before the board (`board.mjs` fails a board over the max), and the same+ numbers in the film's `meta.checks.length` (ship fails a cut over the max and prints the reading+ floor: how short the film can get without cutting into reading time). Cut whole+ beats, and only from non-reading holds; never speed the film up to hit a length (it reads rushed).+ Slowing everything for reading through one master pace map is fine, if the key hits are re-solved+ onto their downbeats afterwards.- **Shapes**: `16x9` for YouTube and the site, `1x1` or `4x5` for feeds, `9x16` for Reels andShorts. Re-compose per shape from one timeline; never crop a wide render. The template does itthrough `launchLayout.ts` (`launch.mjs ship <film> --shapes 16x9,1x1,9x16`), with phone-safe type:@@ -164,8 +197,10 @@ into place), round iris seams, the product's own UI. Pick one per film; never mi## The process-1. **Story sentence** and the sourced brief. ✋ One approval.-2. **Storyboard**: one line per beat with its length in beats, the words, the transition.+1. **Story sentence** and the sourced brief (a brand film: `brand-film.md` steps 0 to 5 first). ✋ One approval.+2. **Storyboard**: one row per beat with its length, the action, what it carries in, the words, the+ transition, as `board.json`; `node tools/board.mjs board.json` must pass. The person sees it as a+ page of drawn stills with timing, never text only.3. **Options sheet**: transitions and type styles side by side as one cheap still sheet (e.g.three blooms, three lettering media). The person picks; nothing is rendered in full yet.4. **One still per scene**, at 0.3-0.5 scale on a contact sheet, reviewed for design:@@ -178,7 +213,9 @@ into place), round iris seams, the product's own UI. Pick one per film; never misheets, cuts as before/after pairs, DESIGN first (type over art, spacing, hierarchy), then timing. Render only the changed range(`render.mjs --from F --to T` writes `out/<film>.<F>-<T>.mp4`, silent). Give notes in camera words ("slow this zoom to 0.7x","hold the word 10 frames longer"), never "make it better".-8. **QA**: review every shape's contact sheet against the design checklist in+8. **Ship before showing**: `node tools/ship.mjs <film> --file out/<file>.mp4` on the exact file you+ will send, for every version, its table attached (`review.md`). For template films, also:+ **QA**: review every shape's contact sheet against the design checklist in`launch-video-kit.md` (no clipped type, no edge-cropped content, balanced per shape, coherentcontent). `launch.mjs ship <film> --shapes ... --gate` runs, for EVERY shape shipped, `framecheck`(text and cards whole on every frame; each text up long enough to read; on 9:16 nothing underdiff --git a/skills/anidoodle/references/workflows/motion-film.md b/skills/anidoodle/references/workflows/motion-film.mdnew file mode 100644index 0000000..ca1105b--- /dev/null+++ b/skills/anidoodle/references/workflows/motion-film.md@@ -0,0 +1,102 @@+# Motion films: one world, one camera++**Contents:** Why one world · Start a film as one world · The kit · Type that enters and leaves · Brand temperament · Approved shots stay approved · The scans · Exceptions, declared · Rendering with blur++A motion-graphics film (a launch, a promo, an explainer in a clean register) is judged first on+whether it moves like one piece. A brand launch film built scene by scene, each scene rebuilding its+own layout, was called "a literal slide deck" four times; both of its critics flagged the same+carousel in its middle. The cure is architectural, and the scans below hold it.++## Why one world++Every beat is a **region** placed on one canvas in world coordinates, and a single **camera** travels+between them. Nothing is rebuilt per scene, so nothing can cut like a slide: every seam is a camera+move, and the thing on screen at the end of one beat is still in the world at the start of the next.+Regions clip their own drawing by default, so one region never leaks an edge into its neighbour.++## Start a film as one world++```bash+node tools/worldfilm.mjs promo --beats 4 --format 16x9 --temperament calm # writes the film and its host page+node tools/motionscan.mjs promo && node tools/layerscan.mjs promo # the scaffold passes both as written+```++`engine/src/canvas-core/world.ts`:++```ts+const w = world({ W: 1920, H: 1080, regions: [{ id: "chat", rect: [0, 0, 1600, 900] }, { id: "crowd", rect: [1900, 200, 2400, 1350] }],+ stops: [{ f: 0, at: "chat", hold: 90 }, { f: 150, at: "crowd", hold: 60 }], alive: { amp: 3, seed: 7 } });+w.begin(ctx, env, f); // the camera's transform: draw in world units+w.region(ctx, "chat", () => drawChat(ctx)); // clipped to its rect+w.end(ctx);+w.depth(ctx, env, f, 0.33, () => frieze(ctx)); // a layer of brand shapes at a third of the camera's speed+```++A stop with no frames to travel is refused: that is the slide cut. `minTravel(px, maxPxPerFrame)`+gives the frames a move needs at the temperament's top speed. `regionAt(f)` and `moves()` list where+the camera is and every seam. Regions may be a function of the frame shape, so one world re-composes+for 9:16 from day one.++## The kit++`engine/src/canvas-core/motionKit.ts`, all pure arithmetic over the frame:++| Call | For |+|---|---|+| `alternate(i, ["left", "right"])`, `entryFrom(i)` | the i-th item of a list enters from a different side each time: a program never plays as a carousel |+| `chatScroll(f, steps)` | a chat column that scrolls over 18 to 24 frames on an ease-out; a snap is refused |+| `temperament("calm" \| "lively" \| "snappy" \| spec)` | the brand's motion as numbers: top speed, settle frames, overshoot or not, an arrival ease |+| `cubicBezier(x1, y1, x2, y2)`, `motionTokens(BRAND.motion, fps)` | a brand's own easings (from `brand.mjs`) as eases and frame counts |+| `typeExit(q)` | how far a line has sunk on its way out (ease-in, 1.3x its size) |+| `sharp(() => draw())` | marks a layer the motion blur must leave sharp |+| `landSquash(t, land, { brand, gag })` | squash on landing, volume kept; refused on a brand mark unless the gag is named |++`world({ alive })` gives the camera a slow breath; `w.depth` the parallax layer. People: `people.ts`+places cut-outs by head height (`drawPerson`, `popOut`). Brand marks: `brandKit.ts`.++## Type that enters and leaves++- `setType(ctx, env, text, x, y, size, p, { out })`: words rise in, and with `out` sink out last+ word first on an **ease-in** over 1.3x their size, so they clear the clip edge at speed. A sink that+ eased out decelerated into the mask and left slivers for half a second ("check each and every frame").+- `{ space: "world" }` draws inside the current transform (a camera, a region); the default resets to+ screen space.+- Type and photos leave in 0.5 to 0.7 s and are never blurred (`../motion-grammar.md`).+- Holds come from the words: `readable.ts` (`chatHold`, `readS`, `paced`, `texture`, `fitText`).++## Brand temperament++Set `meta.motion.temperament` before any motion is built. Too violent and too flat are both a+missing temperament. `motionscan` fails any stretch faster than its top speed.++## Approved shots stay approved++When the person approves a shot, freeze it: `node tools/lock.mjs <film> --shot logo` prints its sha;+put `["logo", "<sha>", "<who approved it, and when>"]` in `meta.motion.approved`. `lock.mjs <film>`+fails if its frames change; `--unlock logo` lets a deliberate change through, which is the moment to+ask the person again. A shot that was "improved" in passing had to be rebuilt exactly.++## The scans++| Tool | Reads | Fails |+|---|---|---|+| `motionscan.mjs <film\|file.mp4>` | the rendered file (any MP4) | **slidecut**: most of the content replaced within 6 frames with no camera move, more than 2 a minute; **repeat**: 3 beats in a row settle into one layout (a carousel); **dissolve**: a cross-dissolve or fade-in over a real share of the frame; **temperament**: faster than the film allows |+| `layerscan.mjs <film>` | what each frame draws | **exits**: text residue at its clip edge for 0.2 s or more; **fasttext**: type faster than half the speed ceiling; **faces**: a moving shape (any probe box, brand marks included) over the top 30% of a person's photo; **translucent**: a brand colour filled between 5% and 95% alpha |+| `lock.mjs <film>` | approved shots | a locked shot that changed or went missing |++A check with no input says N/A with its reason (no temperament declared, no photos, no brand+colours); the ship command lists those, never counts them as passes.++## Exceptions, declared++`meta.motion.allow = { slideCut: [[from, to, reason]], dissolve: [...], translucent: [...] }`: a hard+cut on a strong beat, a dissolve the story needs, a declared brand fade. Each has its reason.+`meta.motion.brandColors` comes from `brandMotion` in the module `brand.mjs import` writes.++## Rendering with blur++`render.mjs --blur auto` blurs fast moves by their real speed and keeps text, photos and anything in+`sharp()` crisp (the pixels they own come from the sharp frame); `--blur-all` blurs everything, the+old behaviour. Text baked into a cached plate is blurred with the plate: draw type on the frame. Every+render writes `<out>.film.json` (film id, frames, blur, sha256, meta), so a renamed or versioned file+is still checked as its film.diff --git a/skills/anidoodle/references/workflows/review.md b/skills/anidoodle/references/workflows/review.mdindex 3aab465..c25f0c1 100644--- a/skills/anidoodle/references/workflows/review.md+++ b/skills/anidoodle/references/workflows/review.md@@ -1,6 +1,6 @@# The review: a fresh critic, three rounds at most-**Contents:** The loop · What the critic does · The four readings · Severity · The check before fixing · The scorecard · The gate · The fix ledger+**Contents:** The loop · No version is shown without its ship table · Before any critic: the design pass · What the critic does · The four readings · Severity · The check before fixing · The scorecard · The gate · The fix ledgerThe builder never judges its own work. A builder who has watched the film forty times sees whatthey meant, forgives the hand they know is hard, and grades the effort. So every review is done by@@ -15,7 +15,11 @@ film), and after each **full render**. The loop is the same each time.the builder is already re-rendering.2. **Brief the critic.** Give it the frozen file (for a storyboard, the rows), the story in threesentences, the shapes and sound the film promised, and this page. Give it none of the build:- no conclusions, no chat history, no list of what you think is wrong.+ no conclusions, no chat history, no list of what you think is wrong. DO give it the person's+ own earlier rejections, verbatim, from the project ledger ("that end card is a mess... who is+ going to read this overload of info?"). Critics calibrate on collisions and counts; the person's+ words are the only record of their taste for density, hierarchy and humour. A critic that called+ an end card "generous" which the person had already rejected three times was judging the wrong film.3. **The critic reports** (below). It returns ranked problems with timestamps and a verdict.4. **Fix the biggest problem first.** Then the next, if they share a rebuild. Re-render.5. **A NEW critic rechecks.** Not the one who found the problems; it would see only what it expects.@@ -24,6 +28,35 @@ film), and after each **full render**. The loop is the same each time.finds new taste, not new faults. After round 3, report what remains, honestly, in the ledgerand to the person ("two P2 left: the brush wipe is used twice, the tail rings 0.4 s long").+## No version is shown without its ship table++`node tools/ship.mjs <film> --file out/<the file you will send>.mp4` runs every check on the exact+delivered file (framecheck, verify-export, the gate, motionscan, layerscan, the locks, the sound or+track checks, the cues, facts, the review ledger, the length budget) and writes `SHIP.md`, `ship.json`+and a critic sheet (a frame every 2 s, every shot start, the last frame) beside it. A check that+cannot look is a FAIL, never a pass; an N/A shows as a FLAG with its reason; `--quick` skips the gate+and can never say PASS. Nine versions of a launch film reached the person with no check at all, and+the checks that did run had passed while blind. Attach the table to every version you show.++The critic's findings and the person's own notes live in `reviews/<film>.json`, which ship reads:++```json+{ "findings": [{ "id": "r1-4", "p": "P0", "status": "open", "note": "the end card is crammed", "by": "critic r1" }],+ "notes": [{ "at": "2026-10-27 21:36", "from": "<the person>", "text": "who is going to read this overload of info?" }] }+```++An open P0 fails the ship, an open P1 flags it, and the person's last three notes are printed+verbatim in the table, to be re-read against the new sheet.++## Before any critic: the design pass++The builder checks bugs well and taste badly ("I checked my frames for bugs, not for design"). So+before a version is shown to anyone, the builder judges a still sheet of it **for design first**:+hierarchy, flow, whether each frame would pass as a poster, the brand's temperament; then bugs. It+re-reads the person's last three notes against the new sheet, one by one. Before the first full+render, run a design critique of the storyboard stills with whatever design skills the person has+installed (name them in the brief). Changed beats are shown as a still sheet before any re-render.+## What the critic does**Pulls its own frames.** It does not use the builder's stills. From the frozen file:@@ -125,8 +158,8 @@ The film ships when all of these hold:- every line is 3 or more, Finish is 5, and the average is 4 or more;- no P0 is open (a P0 still open after round 3 is a blocker the person is told about, never shipped quietly);-- `gate.mjs` and `verify-export.mjs` pass, and for a scored film `music.mjs check` passes and a- human has listened;+- `ship.mjs` passes on the delivered file (it runs the gate, verify-export and every scan), and for+ a scored film `music.mjs check` passes and a human has listened;- the last critic's verdict is `ship`, or three rounds are used and what remains is in the ledger.After the rebuild, the new critic goes down the earlier list item by item against the new file anddiff --git a/skills/anidoodle/references/working-method.md b/skills/anidoodle/references/working-method.mdindex 87e81df..17171c6 100644--- a/skills/anidoodle/references/working-method.md+++ b/skills/anidoodle/references/working-method.md@@ -82,5 +82,13 @@ None of that was drawing. These habits cut it by an order of magnitude:prints it and keeps failing, so the decision stays visible. If the owner accepts it as shipped,it becomes a hold with that reason as its third field (`[from, to, "approved as shipped: ..."]`),which the gate prints and passes (`launch3.ts`).+- **Dense strips around a seam** come from `still.mjs --frames 840-880:2 --sheet out/seam.jpg`, never a+ hand-written ffmpeg tiling script.+- **A film beside its own files.** `scaffold.mjs <dir> --linked --film promo [--world]` makes a project+ that USES the installed engine (its film, host page, brand files and photos live in the project), so+ no film needs a copy of the engine, and every tool (`music.mjs check`, `ship.mjs`) finds it.+- **A photo that has not arrived yet.** `ANIDOODLE_PLACEHOLDERS=1` draws a labelled grey box for a+ missing image asset and lists it in `meta.placeholders`; `verify-export --delivery` and `ship` refuse+ a file that still has one. Never drop a stand-in photo in under the real name.- **`npm test`** (in `engine/`) runs the unit suites in `engine/test/*.test.ts` without abrowser (camera moves today). Run it with the gate after any engine change.