Skip to content

A Claude Code plugin that turns a story into a finished anime

Ruby

Integrate production feedback and local graphics tools for 0.5.0

Francesco 'makevoid' Canessa64bce9c60db4
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 0c66292..6cb3cc0 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "make-an-anime",
- "version": "0.4.0",
+ "version": "0.5.0",
"license": "MIT",
"description": "Create anime from a story: character sheets (GPT Image 2.6 Sunburst), cinematic MiniMax H3 shots, green-screen layered composites, ElevenLabs v4 character voices, ElevenLabs Music v2.5 scores, p5 titles and subtitles, SFX and Swift VFX. Works from a 12-second scene to a full episode.",
"author": {
diff --git a/README.md b/README.md
index 6b8e8cc..5616720 100644
--- a/README.md
+++ b/README.md
@@ -75,13 +75,15 @@ Each stage reads prompts from `prompts/<run>/` and writes to `output/<run>/`, so
<img src="https://github.com/user-attachments/assets/56267103-9aec-4482-a20b-f4c1d074eb2a" alt="One shot of Too Salty at four stages: the character sheet, the painted keyframe, a frame of the animated take, and the finished frame with subtitles" width="100%">
-1. **Character and location sheets.** A style bible (`config/style.md`) goes into every prompt, so the whole cast shares one look. GPT Image 2.6 draws a sheet for each character and location, and those sheets become the references for everything after.
+1. **Character and location sheets.** A style bible (`config/style.md`) guides the image prompts, so the whole cast shares one look. GPT Image 2.6 draws a sheet for each character and location, and those sheets become the references for everything after.
2. **Voices and score.** Each character gets one ElevenLabs voice in `config/cast.yml`. Voices come before animation because line lengths decide shot lengths. ElevenLabs Music then composes one score, and `gen:mix` ducks it under the voices.
3. **Keyframes.** GPT Image 2.6 paints the first frame of each shot from the sheets.
-4. **Shots.** MiniMax H3 animates each keyframe as one continuous take, with the camera move written into the prompt and the speaker's voice as target audio so the mouth follows the line. Held stills and colour inserts cost nothing. For moments that need exact placement, [layered scenes](skills/make-an-anime/references/layered-scenes.md) composite green-screen sprites over a painted plate.
+4. **Shots.** MiniMax H3 animates each keyframe as one continuous take, with the camera move written into the prompt and the speaker's voice as target audio so the mouth follows the line. Held stills and colour inserts cost nothing. Existing takes can be reused across scenes with `from_take`. For moments that need exact placement, [layered scenes](skills/make-an-anime/references/layered-scenes.md) composite green-screen sprites over a painted plate.
5. **Overlay.** A p5 script (`05_overlay.js`) draws titles, subtitles, fades and any composite work.
6. **Sound.** `sfx:gen` creates sound effects with Stable Audio, and `sfx:mix` places them from a cue list and levels them against the mix.
-7. **Finish.** `vfx:render` adds grain, glow or impact effects with Swift Core Image, on frame-accurate cues.
+7. **Finish.** `vfx:render` adds grain, glow or impact effects with Swift Core Image, on frame-accurate cues. The optional `vfx:bake` pass preserves the plain picture so repeating the finish does not accumulate effects.
+
+For detailed staging and playback review, see [Staging and review](skills/make-an-anime/references/staging-and-review.md). Local graphics tools include [deterministic particles and light-only glow](skills/make-an-anime/references/particles-and-glow.md), plus [game screens and asset cutting](skills/make-an-anime/references/game-screens.md).
The same steps as commands, once a project and its prompts exist:
diff --git a/docs/production-improvements.md b/docs/production-improvements.md
new file mode 100644
index 0000000..90f2a35
--- /dev/null
+++ b/docs/production-improvements.md
@@ -0,0 +1,24 @@
+# Production feedback incorporated in 0.5.0
+
+The local production trial supplied sixteen improvement notes. This integration carries reusable instructions and code into the plugin, without its story, reference photos, generated media, private paths or character identities.
+
+| Notes | Incorporated |
+| --- | --- |
+| 01–03: identity details, end frames, style | Design a repeated emblem separately; use endpoint images for staging; put the full palette in image prompts and concise style/light/place constraints in motion prompts. |
+| 04–07: contact, perspective, dark scenes, cost | Review feet and floor together, compare anatomy and props in the same camera, retain depth cues in dark rooms, budget attempts by shot difficulty. |
+| 08–10: review, anatomy, pacing | A written physical-review table, full playback alongside sampled frames, connected anatomy and reach checks, action-based shot duration. |
+| 11–12: voice and timing | Audible `speech_at` in timeline checks; skipped frames included in source duration; short-source rejection; skipped-prefix retiming. Existing repeated-word validation remains in place. |
+| 13: character performance | Purposeful motion and readable reactions, with intentional holds still available when the approved visual direction calls for them. |
+| 14–15: reuse, stale mix, dialogue, staging | `from_take` with source digests; mix settings/audio fingerprints; stale soundtrack refusal; music-only gain default; local muffled voices; running-water false-positive fix; practical door and missed-shot staging guidance. |
+| 16: graphics | Deterministic particles, a separate light layer and Swift halo, repeatable VFX bake, configurable RTS/mission/court helpers, sheet cutters, and face-icon collage recipes. |
+
+The new references are linked from the skill and task guide. Executable behavior is exercised with synthetic local fixtures, including real FFmpeg, Python, Chrome/p5 and Swift rendering. Paid model output quality still requires production review; offline fixtures cannot establish it.
+
+Automatic airborne-only retiming, arbitrary perspective-quad compositing, generalized room reconstruction and heuristic changes to transcription acceptance were not ported. Those require a separate design and evidence. The trial's ban on held characters was a film preference, so it became review guidance rather than a universal rule. Generated art, font files and project media are not bundled.
+
+## Verification
+
+- `ruby skills/make-an-anime/scripts/mv.rb test`: 96 offline examples, zero failures, including Chrome/p5 and Swift. Fal credentials were unset; no paid calls ran.
+- `npm audit`: zero vulnerabilities.
+- Strict Claude plugin and marketplace validation passed on an export containing only repository files. Gitleaks found no secrets in that export.
+- The skill-creator quick validator rejects the existing `compatibility` frontmatter field because its allowed-key list omits it; the strict Claude validator accepts the plugin. No metadata was removed to bypass that older helper.
diff --git a/skills/make-an-anime/SKILL.md b/skills/make-an-anime/SKILL.md
index e90a500..c19c134 100644
--- a/skills/make-an-anime/SKILL.md
+++ b/skills/make-an-anime/SKILL.md
@@ -11,7 +11,7 @@ Turn a story into a finished, voiced, scored anime: a cold open that hooks, char
**The footage must look real.** Light, contact, motion and camera agree across the whole frame, or it looks pasted together and AI-generated. Action is never on green screen: paint the character and the world in one H3 take, with one runner per shot and a camera that travels. Read [believable-motion.md](references/believable-motion.md) before planning any shot.
-The art direction comes from the story, the brief and the references. Write it down once as a style bible (`config/style.md`) and reuse it, unchanged, in every image and H3 prompt through `{{STYLE}}`.
+The art direction comes from the story, the brief and the references. Write it down once as a style bible (`config/style.md`) and reuse it in image prompts through `{{STYLE}}`. For H3, use a short style sentence plus this shot’s light and location; avoid pasting a multi-scene palette list into a motion prompt.
## Execution contract
@@ -41,6 +41,8 @@ Read the whole story and look at every reference photo. List the people who appe
## 2. Plan, then obtain approval
+For perspective, contact, recurring marks or precise acting, use [staging-and-review.md](references/staging-and-review.md). Allocate image edits, end frames and retries by shot difficulty, and choose durations for pace.
+
Write `docs/PLAN.md` from [the plan template](assets/plan-template.md): style bible, cast bible with reference photos per character, voice casting, location sheets, the beat-by-beat scene breakdown with exact frame ranges, every keyframe prompt, every H3 shot prompt **with its camera direction**, every dialogue line with timing and delivery, the score's composition plan, inserts/subtitles/titles drawn in p5, SFX, cost estimate and retry allowance.
Summarize the cast, look, voices, the opening hook, shot list and costs in chat. For a new creative direction, ask the user to validate the **character sheets plan, voices, shot list and general vibe** and authorize production; make no paid calls before that. When the user already explicitly asked you to produce a specific part, preserve that authorization: write the bounded plan, record the request with `NOTE='...' plan:approve` and continue. Material changes outside the approved scope need approval again; routine retries inside it do not.
@@ -59,13 +61,13 @@ Order of work, each step reviewed before the next:
4. **Keyframes** (`Steps::Keyframes`): one composed first frame per shot, edited from the cast/location sheets (`base: false`, `refs: [...]`).
5. **Shots** (`Steps::Shots`): H3 Max animates each keyframe at **768P** by default, with the shot's camera move written as its own `camera:` direction and the speaking character's mouth track as target audio. Still holds and solid inserts cost nothing. `review:camera` measures the move each shot actually made, and `review:believable` checks the prompts and takes for action on green and treadmill runs (`gen:clips` and `gen:shots` refuse the written failures before any paid call).
6. **Panels and layers, only for people who stay put** (`Steps::Clips`): two people far apart talk on one screen through painted panels with a paper cut (`key: none`, `Anim.paperCutPanels`), see [believable-motion.md](references/believable-motion.md). A keyed green performance is the last resort, for a still figure with no action; read [layered-scenes.md](references/layered-scenes.md) first.
-7. **Overlay** (`Steps::Overlay`): p5 draws screens, UI, title cards, subtitles and transitions over the plate, using `tools/p5/lib/screens.js` (code editor, typing, subtitles, place cards) and `tools/p5/lib/battle.js` (title slam, speed lines, impacts, camera roll). Then `sfx:gen`/`sfx:mix` and optional Swift VFX.
+7. **Overlay** (`Steps::Overlay`): p5 draws screens, UI, title cards, subtitles and transitions over the plate, using `tools/p5/lib/screens.js` (code editor, typing, subtitles, place cards) and `tools/p5/lib/battle.js` (title slam, speed lines, impacts, camera roll). For generated game interfaces, see [game-screens.md](references/game-screens.md); for deterministic particles and light-only glow, see [particles-and-glow.md](references/particles-and-glow.md). Bake a scene light pass with `vfx:bake[run]` before `sfx:mix` when configured, or finish to a distinct VFX output.
Delegate production to sub-agents in waves (**2 assets first → 3–4 → 4–8 → 6–10 repeatedly**) with `work:next`, `work:log`, `work:watch` and `work:accept`, as described in [production.md](references/production.md). A short pilot can run serially; say so. Schedule the opening and the emotional peak early. Never let concurrent workers edit shared config, cast or identity sheets.
## 4. Review and deliver
-Watch every shot at normal speed with sound. Run `review:believable`, then check the by-eye list in [believable-motion.md](references/believable-motion.md). Reject a shot that looks composited, whose runner stays in place while the world stands still, whose face drifts off-model, whose hands or anatomy break, whose camera does something other than the directed move, whose background morphs, or that invents text, people or props. For dialogue, check that the speaking character's mouth moves on their words and rests on others' lines; `target_audio_url` pins the soundtrack but is **not proof of lip-sync**. Regenerate within the retry allowance and report what remains imperfect.
+Watch every shot at normal speed with sound. Record the applicable physical and continuity checks from [staging-and-review.md](references/staging-and-review.md#review-record); frame-only review leaves pace and sound unverified. Run `review:believable`, then check the by-eye list in [believable-motion.md](references/believable-motion.md). Reject a shot that looks composited, whose runner stays in place while the world stands still, whose face drifts off-model, whose hands or anatomy break, whose camera does something other than the directed move, whose background morphs, or that invents text, people or props. For dialogue, check that the speaking character's mouth moves on their words and rests on others' lines; `target_audio_url` pins the soundtrack but is **not proof of lip-sync**. Regenerate within the retry allowance and report what remains imperfect.
A multi-scene episode has its own workflow: read [full-episode.md](references/full-episode.md) (playing order, loudness across scenes, seams, retakes). Assemble scenes contiguously (`episode:preview`, `media:concat`), check the frame count, mix SFX, and deliver the episode video, a clean version without SFX/VFX, the character sheets, the cast/voice table, the plan, research, manifests and a concise summary of revisions and unresolved issues. Completion means every planned scene of the requested part is assembled, reviewed and delivered.
diff --git a/skills/make-an-anime/assets/game-screens/console.txt b/skills/make-an-anime/assets/game-screens/console.txt
new file mode 100644
index 0000000..10f84ad
--- /dev/null
+++ b/skills/make-an-anime/assets/game-screens/console.txt
@@ -0,0 +1,14 @@
+Video game interface art asset for an original 2004 PC real-time strategy game, high-end pre-rendered look of that era. Not from any existing game: an original design.
+
+The image is one wide bottom HUD console, seen straight on, flat, front view, no perspective. It runs edge to edge across the full width of the image and fills only the bottom 30 percent of the image. Everything above the console is one flat, even, pure magenta colour (#FF00FF), with no gradient, no shadow and no texture, so it can be keyed out.
+
+The console: heavy sci-fi armour plating in dark gunmetal and brushed steel, with chamfered edges, rivets, small vents, thin cobalt-blue glowing trim lines and a few amber status lamps. Its top edge is not straight: it steps up into a raised armoured pod at the far left and a second, lower raised pod at the far right, joined by a lower middle section.
+
+Recessed into the console, from left to right, five empty screens, each with a bevelled metal bezel and a flat, solid black inside (#000000), with nothing drawn in them:
+1. in the raised left pod, a tall portrait screen, about one tenth of the image wide;
+2. a square minimap screen next to it;
+3. in the middle, one wide, low rectangular information screen, about a third of the image wide;
+4. a narrow vertical slot beside it;
+5. in the raised right pod, a command-card area: a grid of 4 columns by 3 rows of empty square button sockets, each socket flat solid black inside.
+
+Crisp, clean, symmetrical bevels, sharp detail, readable at small size. No text, no letters, no numbers, no symbols, no icons, no logos, no buttons with drawings on them, no characters, no units, no map, no watermark.
diff --git a/skills/make-an-anime/assets/game-screens/face-icons.txt b/skills/make-an-anime/assets/game-screens/face-icons.txt
new file mode 100644
index 0000000..f29a6a7
--- /dev/null
+++ b/skills/make-an-anime/assets/game-screens/face-icons.txt
@@ -0,0 +1 @@
+Redraw each face in this grid as a small stylised game-unit portrait of the same character, in the same cell. Keep their age, face shape, hair, clothing and distinguishing features. Preserve the grid, spacing, background and character order. One portrait per cell; no extra portraits. Use original icon frames with clear silhouettes. No text, letters, numbers, labels, logos or watermarks. Do not imitate an existing game.
diff --git a/skills/make-an-anime/assets/game-screens/icons.txt b/skills/make-an-anime/assets/game-screens/icons.txt
new file mode 100644
index 0000000..9f7a8dc
--- /dev/null
+++ b/skills/make-an-anime/assets/game-screens/icons.txt
@@ -0,0 +1,8 @@
+Video game interface art asset: an icon sheet of command buttons for an original 2004 PC real-time strategy game. Original designs, not from any existing game.
+
+Exactly 12 square icons in a grid of 4 columns by 3 rows, evenly spaced, all the same size, each with a clear gap of flat black between them, on a flat, even, pure black background (#000000). Each icon is a small square button: a dark gunmetal bevelled tile with a thin glowing cobalt-blue rim, and in the middle one bold, simple painted emblem in bright steel, white, cyan and amber, readable at very small size:
+row 1: a boot print with a forward arrow (move), an octagonal shield with a palm (stop), a crosshair over a short blade (attack), two curved arrows chasing each other in a circle (patrol);
+row 2: a planted kite shield with a down arrow (hold position), a wrench crossed with a hammer (build), a laser rifle with a bright muzzle glint (fire), a round grenade with a spark (grenade);
+row 3: a radar dish with wave arcs (scan), a hexagon shield with a plus (shield boost), a flag on a pole (rally point), a small rocket rising with a flame (missile).
+
+Crisp clean edges, high-end pre-rendered look of that era. No text, no letters, no numbers, no hotkey letters, no logos, no watermark.
diff --git a/skills/make-an-anime/assets/game-screens/map.txt b/skills/make-an-anime/assets/game-screens/map.txt
new file mode 100644
index 0000000..6109b9b
--- /dev/null
+++ b/skills/make-an-anime/assets/game-screens/map.txt
@@ -0,0 +1,5 @@
+Video game art asset: the battlefield terrain of an original 2004 PC real-time strategy game, as the player sees it, a high overhead camera looking down at about 60 degrees, a slight isometric three-quarter angle, the whole image filled with ground to every edge. High-end pre-rendered 2D terrain tiles of that era, crisp and detailed, readable at small size.
+
+An alien frontier world at night, lit by cold blue moonlight with warm amber work lights: a wide plateau of dusty ochre-grey dirt and cracked rock in the middle, raised rocky cliff ledges with sharp highlights along the top and the bottom edges, one ramp up between them, a dark chasm with glowing teal fissures in the lower left corner, a field of tall glowing blue crystals at the far left, a small green gas vent with a faint plume on the right, scattered boulders, metal debris, a few scorch marks and tread tracks across the open ground, a broken road of metal plates crossing from left to right.
+
+Only terrain: no units, no vehicles, no soldiers, no creatures, no buildings, no interface, no cursor, no selection marks, no minimap, no text, no letters, no numbers, no logos, no watermark.
diff --git a/skills/make-an-anime/assets/game-screens/portrait.txt b/skills/make-an-anime/assets/game-screens/portrait.txt
new file mode 100644
index 0000000..5e3a97b
--- /dev/null
+++ b/skills/make-an-anime/assets/game-screens/portrait.txt
@@ -0,0 +1,5 @@
+Video game art asset: the unit portrait for an original 2004 PC real-time strategy game, the face that talks in the console's portrait screen. High-end pre-rendered 3D CGI look of that era, cinematic, dramatic rim light. An original character design, not from any existing game.
+
+A head-and-shoulders bust, centred, filling the middle third of the image from the top of the head to the upper chest, turned slightly to the left with the eyes looking at the viewer. An original tall alien warrior in ornate ceremonial armour: a closed helmet with a high, swept-back crest made of three bronze fins and two short curled horns at the temples, a smooth mouthless faceplate of dark ivory with fine engraved lines, two narrow glowing eyes of hot amber-orange light behind the faceplate, a high armoured collar, layered pauldrons of deep violet enamel edged with polished bronze filigree and small inset green gemstones, a short cloak of dark teal cloth on one shoulder. No weapons, no blades, no energy blades, no tentacles, no tubes from the head.
+
+Behind the bust, a dark smoky blue-green background with faint soft light, plain, so the portrait can sit in a small screen. No text, no letters, no numbers, no logos, no interface, no frame, no watermark.
diff --git a/skills/make-an-anime/assets/game-screens/units.txt b/skills/make-an-anime/assets/game-screens/units.txt
new file mode 100644
index 0000000..d3dafec
--- /dev/null
+++ b/skills/make-an-anime/assets/game-screens/units.txt
@@ -0,0 +1,9 @@
+Video game sprite sheet for an original 2004 PC real-time strategy game: small game units for two factions, each seen from a high overhead camera at about 60 degrees, a slight isometric three-quarter angle, the way they look on the battlefield. High-end pre-rendered 3D sprites of that era, crisp, clean silhouettes, strong rim light, readable at small size. Original designs, not from any existing game.
+
+The background is one flat, even, pure magenta colour (#FF00FF) everywhere, with no shadows on it, no floor, no gradient, no texture, so the sprites can be keyed out. Each unit stands alone with wide empty magenta space around it, nothing touching, and no shadow under it.
+
+Exactly 8 units in a grid of 4 columns by 2 rows, evenly spaced:
+Top row, the blue faction, steel-blue and white armour with cobalt lights, all facing right: 1) an armoured infantry trooper with a long rifle and a big shoulder lamp, 2) a squat two-legged walker mech with twin cannons, 3) a low hover tank with a long barrel, 4) a small delta-wing gunship.
+Bottom row, the red faction, crimson and black plating with orange glowing vents, all facing left: 5) a four-legged spider drone with a single red eye, 6) a heavy armoured crawler with a spiked ram, 7) a fast raider skiff with two blades, 8) a tall stilt-legged war walker with a glowing core.
+
+No text, no letters, no numbers, no labels, no health bars, no selection circles, no interface, no logos, no watermark.
diff --git a/skills/make-an-anime/assets/plan-template.md b/skills/make-an-anime/assets/plan-template.md
index baa8511..f591d7f 100644
--- a/skills/make-an-anime/assets/plan-template.md
+++ b/skills/make-an-anime/assets/plan-template.md
@@ -27,11 +27,13 @@ Locations: id, description, light, full prompt, which scenes use it.
## Scene breakdown
-| Run | Frames [start, end) | Beat | Shot | Size/angle | Camera move (from → to, speed, timing) | Source (H3 / still / colour) | Speaker / audio track | Lines (at, text) | p5 (screens, titles, subtitles) | SFX | Dependencies |
-|---|---|---|---|---|---|---|---|---|---|---|---|
+| Run | Frames [start, end) | Beat | Shot class | Shot | Size/angle | Camera move (from → to, speed, timing) | Source (H3 / still / colour) | Speaker / audio track | Lines (at, text) | p5 (screens, titles, subtitles) | SFX | Dependencies |
+|---|---|---|---|---|---|---|---|---|---|---|---|---|
For every action shot, answer in the plan: is the character painted with the world in one take (never keyed)? If someone runs, is there one runner and a camera that travels, and what passes behind them? For two people talking far apart, use paper-cut panels. See `references/believable-motion.md`.
+Budget by class (quiet, talking, perspective, motion): guides, first/end frames, logo/cloth edits, retry takes and generated seconds. Name the pivotal motion shots and their review criteria; longer duration is not a substitute for a retry allowance.
+
For every shot: the keyframe prompt and refs, the H3 prompt, the `camera:` block, seconds, audio track, and acceptance (on-model faces, camera did the directed move, mouth on the right lines, no invented text).
## Dialogue and score
diff --git a/skills/make-an-anime/references/animation-audio-vfx.md b/skills/make-an-anime/references/animation-audio-vfx.md
index fc38dac..17d02ae 100644
--- a/skills/make-an-anime/references/animation-audio-vfx.md
+++ b/skills/make-an-anime/references/animation-audio-vfx.md
@@ -6,7 +6,7 @@ H3 supplies the characters and their world together, in one full-frame take; p5
## p5 scenes and overlays
-The renderer loads `tools/p5/lib/{core,time,fx,type,paper,riso,screens}.js` and calls a sketch for each frame at `t=frame/24`. Per-frame random seeds make repeats deterministic. Full-scene sketches draw on a background plate selected for the scene; overlay sketches leave transparent areas over an H3 plate. Load project fonts chosen for the approved art direction through `Anim.fonts`. Select drawing, texture and typography helpers to suit that direction. Library names and bundled examples do not prescribe a visual style.
+The renderer loads `tools/p5/lib/{core,time,fx,type,paper,riso,screens,battle,particles,rts,mission,court}.js` and calls a sketch for each frame at `t=frame/24`. Per-frame random seeds make repeats deterministic. Full-scene sketches draw on a background plate selected for the scene; overlay sketches leave transparent areas over an H3 plate. Load project fonts chosen for the approved art direction through `Anim.fonts`. Select drawing, texture and typography helpers to suit that direction. Library names and bundled examples do not prescribe a visual style.
### Project fonts
@@ -114,3 +114,7 @@ cues:
Core Image supports `punch`, `zoom`, `shake`, `whip`, `mblur`, `edgeblur`, `glow`, `flash`, `dark`, `rgb`, `glitch`, `tv`, `grain`. `f`/`dur` are integer frames; `pre` starts a transition early. See `tools/vfx/Sources/mvfx/Effects.swift` for exact knobs. `leak`, `flare`, `glints` are p5 light cues: set `lights: tools/p5/examples/lights.js` for the bundled leak/flare/glints implementation, or author `05_lights.js` in the VFX prompt folder (or set `lights:` to another sketch), read `Anim.data('vfx').cues`, draw on transparent black, and use screen blending in Swift. A light cue without its sketch is an error, not an invisible effect.
The Swift service builds the package through Ruby, uses FFmpeg rawvideo pipes and copies the source audio. Inspect a short clip and stills before the full render. Use distinct output paths for every finish revision. Effects should follow onsets/cuts/lyrics; start glow after a flash to avoid whiteouts, avoid double grain if p5 already draws it, and preserve deliberate quiet frames. A no-cue VFX render should resemble the clean encode; cued frames should differ measurably, which RSpec checks.
+
+## Generated interfaces and particle light passes
+
+[Game screens](game-screens.md) describes reusable original artwork, local sheet cutting, face collages and the RTS/mission/court helpers. [Particles and glow](particles-and-glow.md) documents deterministic emitters, `halo`, and `vfx:bake[run]` between overlay and SFX. The light pass blooms only explicitly emitted light, preserving the surrounding painting and readable HUD.
diff --git a/skills/make-an-anime/references/believable-motion.md b/skills/make-an-anime/references/believable-motion.md
index 4d4bda3..96a9537 100644
--- a/skills/make-an-anime/references/believable-motion.md
+++ b/skills/make-an-anime/references/believable-motion.md
@@ -80,6 +80,8 @@ Use this only for a word that was misread, never to push real action through.
## Review by eye
+For scale, anatomy, contact, pinned end frames, pacing and a written review record, use [staging-and-review.md](staging-and-review.md). These checks complement the metrics below.
+
Watch at normal speed, then look at a dense frame board around every hit and cut. Sparse boards miss short glitches.
- Do the feet land where the body travels, and does anyone run in place?
diff --git a/skills/make-an-anime/references/game-screens.md b/skills/make-an-anime/references/game-screens.md
new file mode 100644
index 0000000..e459c62
--- /dev/null
+++ b/skills/make-an-anime/references/game-screens.md
@@ -0,0 +1,54 @@
+# A game on a screen
+
+Use this for an original game interface inside a film, or for an intentional game-like diagram. Generate artwork without text, cut it locally, then draw all readable words, numbers, cursors and event timing in p5. Choose art and UI conventions for the story's era without copying a specific game's units, branding or layout. Use fonts licensed for the intended delivery; no font files are bundled.
+
+The optional modules `Anim.rts`, `Anim.mission` and `Anim.court` are loaded after `Anim.particles`. They provide a concrete RTS composition, mission-map primitives and court diagrams; other genres can reuse the asset tools and particles independently.
+
+## Artwork and cutting
+
+Starter prompts in `assets/game-screens/` cover `console.txt`, `map.txt`, `units.txt`, `icons.txt` and `portrait.txt`. Adapt them to the approved visual direction and register each as a normal `gen:ref_base` run. Paid calls follow the production plan and existing credential workflow. A 4-second screen does not require generating a full video if p5 can animate the planned action from these sheets.
+
+The console should contain empty flat-black screens; the sprites should have clear gaps. Inspect whether the returned file actually uses transparency, magenta or black. The cutting tools support all three; do not assume a requested key colour was returned.
+
+Run local tools through Ruby with JSON recipes, which allow commas and spaces inside paths and arrays:
+
+```json
+{"mode":"sprites","source":"output/game-units/01_ref_base.png","out":"output/game-art/units","names":["trooper","walker","tank","gunship","spider","crawler","skiff","stilt"],"key":"alpha"}
+```
+
+```sh
+ruby mv.rb 'game:cut[config/cut-units.json]'
+```
+
+| `mode` | Required recipe fields | Options |
+| --- | --- | --- |
+| `sprites` | `source`, `out` directory, `names` array | `key` (default alpha), `min_px`, `min_len`, `gap`, `margin` |
+| `grid` | `source`, `out` directory, `names` array | `key` (default black), `min_px`, `min_len`, `gap`, `size`, `inset` |
+| `frame` | `source`, `out` PNG, `slots` JSON | `key` (default alpha), `dark`, `scale`, `min_area` |
+| `fit` | `source`, `out`, `width` | `crop: [x,y,w,h]` |
+
+Sprite/icon names must be unique plain identifiers. A count mismatch stops instead of silently dropping a cell. `frame` locates connected dark rectangular areas, makes them transparent and writes their measured bounds. Inspect the holes and slot ordering; merged or decorative black regions can require a cleaner source or adjusted thresholds. `fit` resizes terrain/portraits and can crop first.
+
+`Anim.rts.load({dir, units, icons})` expects `map.jpg`, `console.png`, `console_slots.json`, `portrait.png`, and `units/<name>.png` / `icons/<name>.png` below `dir`. It assigns the large console slots left-to-right to portrait/minimap/info/gauge and small slots to commands; `game.hud.screens` overrides the large-slot labels. Keep the required empty screens distinct.
+
+## Choreography
+
+`scripts/tools/p5/examples/game-screen.js` is a generic starting sketch. Supply a data JSON such as `{"dir":"/output/game-art","units":["trooper"],"icons":["move"]}` via the renderer's `game` data entry when calling `Media::Anim#render` from a project Ruby recipe. The header of `rts.js` documents its game object: unit positions as functions of time, deaths, events, camera, selection, cursor, commands, portrait activity, minimap and counters.
+
+Keep named event times in one place and derive visual, light and sound cues from them. A cursor should travel to the button it presses. Minimap positions should follow the actual units. Tiny sprites may slide convincingly for a brief screen insert; larger or longer shots need pose cycles and facing changes. Single-pose art is not a walking animation.
+
+`Anim.mission` adds floor, fog, beacon, path and unit helpers. Configure `R.bezel = {box: [x,y,w,h], inset: [left,top,right,bottom], corner: pixels}` from your measured console art before calling `begin`/`end`; there is no universal pixel crop. Its bezel is nine-sliced. `Anim.court.half(box)` and `.full(box)` produce diagram geometry; the included court lines are illustrative and must be adapted to the sport, era and intended proportions. `drillSim` is an illustrative eight-second drill derived from a formation configuration; frames may be requested out of order. Longer or different choreography needs its own simulation or time functions.
+
+See [particles-and-glow.md](particles-and-glow.md) for `mode: 'light'`, occlusion and the `halo` pass. Size a screen effect's sound for the in-scene speakers; distant desktop audio need not have cinematic sub-bass. Measure the surrounding mix and inspect flashes for whiteouts.
+
+## Face icons
+
+Crop accepted character faces into a consistent grid, request one edit using `assets/game-screens/face-icons.txt`, then cut the result. The input spec describes only the chosen sheets and measured face boxes:
+
+```json
+{"cols":2,"rows":1,"cell":[460,520],"gap":40,"margin":60,"faces":[{"name":"pilot","sheet":"output/char-pilot/01_ref_base.png","box":[600,400,240]},{"name":"rival","sheet":"output/char-rival/01_ref_base.png","box":[600,400,240]}]}
+```
+
+`box` is centre x/y and crop width; optional `scale` converts measurements from a downscaled inspection image. Use a `game:faces` recipe `{"mode":"build","spec":"config/faces.json","out":"output/faces-collage.png"}`. After the approved image edit, use `{"mode":"cut","spec":"config/faces.json","source":"output/faces-edited.png","out":"output/game-art/faces","size":256}`.
+
+The cutter stops on ambiguous counts. Inspect the sheet before explicitly setting `grid_fallback: true`; this evenly splits the detected content bounds and still needs visual identity review. Verify every returned cell against its source face before using the name mapping. Project-specific face sheets, photos and character names are not part of the plugin.
diff --git a/skills/make-an-anime/references/particles-and-glow.md b/skills/make-an-anime/references/particles-and-glow.md
new file mode 100644
index 0000000..6487130
--- /dev/null
+++ b/skills/make-an-anime/references/particles-and-glow.md
@@ -0,0 +1,53 @@
+# Particles and light-only glow
+
+`Anim.particles` draws deterministic emitters in p5. It is loaded by the renderer after `battle`. Use it for screen content, sparks or an effect that belongs to the approved art direction; it does not replace a body's physical contact with its scene.
+
+Every event has a unique `id`, a start time `at` in seconds, and coordinates in the current canvas transform. `Anim.particles.draw(events, t, {mode: 'color'})` draws the full event; `mode: 'light'` draws only luminous parts. Use shot-local seconds for both event times and `t`.
+
+| Type | Main options |
+| --- | --- |
+| `sparks` | `x, y`, `count`, `speed: [min,max]`, `life: [min,max]`, `angle`, `spread`, `drag`, `gravity`, `color` |
+| `muzzle` | `x, y`, `angle`, `size`, `dur`, `color` |
+| `ring` | `x, y`, `radius`, `dur`, `weight`, `squash`, `color` |
+| `laser` | `from: [x,y]`, `to: [x,y]`, `dur`, `grow`, `width`, `color`, `hit`, `muzzle` |
+| `tracers` | `from`, `to`, `dur`, `rate`, `speed`, `len`, `spread`, `color` |
+| `explosion` | `x, y`, `size`, `dur`, `debris`, `smokeCount`, `palette`, `ring` |
+| `scorch` | `x, y`, `radius`; omitted in light mode |
+
+`rand(id,index,salt)`, `range`, `fly`, `rgba`, `glow` and `intensity(events,t)` are available for custom effects; inspect `scripts/tools/p5/lib/particles.js` for signatures. Derive a flash, shake and SFX cue from the same event time. For a shot starting at frame 168, an event at local 1.3 s maps to frame `168 + round(24 * 1.3)` and scene sound time `168 / 24 + 1.3`.
+
+An isolated frame must match a full render. Compute particle position and appearance from its seeded identity and absolute age; do not accumulate particles across frames or use unseeded randomness. `scripts/tools/p5/examples/particles.js` is a runnable example:
+
+```sh
+ruby mv.rb 'anim:render[tools/p5/examples/particles.js,output/particles-preview,48,320,180]'
+```
+
+## The light layer
+
+The same overlay can detect `ANIM.data.vfx !== undefined` and draw only light onto transparency. Keep the same camera and transforms. Mask occluding HUD/window geometry with `destination-out` so it does not receive the bloom. The Swift `halo` cue adds tight and wide Gaussian blooms to this layer before screen blending; unlike `glow`, it does not bloom the whole picture.
+
+```yaml
+source: output/scene/final_overlay_plain.mp4
+out: output/scene/final_overlay.mp4
+lights: prompts/scene/05_overlay.js
+cues:
+ - {fx: halo, f: 168, dur: 96, shape: span, fade: 1, amt: 1.0, radius: 11}
+ - {fx: flash, f: 199, dur: 7, amt: 0.28, color: "#ffd9a8"}
+ - {fx: shake, f: 199, dur: 10, amt: 8}
+```
+
+Inspect peak frames at full size: combined halo and flash can white out the action. Keep the HUD and subtitles sharp. A custom halo needs a custom light sketch; the bundled leak/flare/glints sketch does not invent emitter geometry for it.
+
+## Bake between overlay and sound effects
+
+Save the configuration above as `prompts/scene-vfx/cues.yml`, then:
+
+```sh
+RUN=scene ruby mv.rb gen:overlay
+ruby mv.rb 'vfx:bake[scene]'
+SFX=scene-sfx ruby mv.rb sfx:mix
+```
+
+`vfx:bake` keeps `final_overlay_plain.mp4`, renders into a temporary file and replaces `final_overlay.mp4` only on success. A receipt hashes the video stream separately from audio. Rerunning starts from the plain picture, so glow never stacks; an audio-only remix is copied onto that picture first. Missing or changed plain footage is an error for a recognized baked output. Rebuild `gen:overlay` to establish a fresh source. A per-scene lock serializes baking; finish the overlay/remix task before starting a bake.
+
+For a distinct final output instead, use ordinary `vfx:render`. Swift VFX requires macOS. Neither workflow makes model calls.
diff --git a/skills/make-an-anime/references/planning.md b/skills/make-an-anime/references/planning.md
index 0cbbd2b..1d7ed4b 100644
--- a/skills/make-an-anime/references/planning.md
+++ b/skills/make-an-anime/references/planning.md
@@ -31,3 +31,7 @@ Cut detection is a candidate list: flat graphics and hard flashes need visual co
Use `assets/plan-template.md`. The plan must cover the whole song, contain concrete prompts, and identify which details came from research. Estimate calls by model and generated seconds, allow a bounded number of retries and quote current pricing sources when available. If price cannot be established, say so and obtain a call-count budget. Do not invent a dollar total. The chat summary should let the user understand the video without reading every prompt, while the linked document makes each prompt reviewable.
Approval covers execution within those creative and cost bounds. Ask again for a changed creative plan, an unavailable model that needs substitution, or spending beyond the allowance. Routine failed local renders, recuts and edits within the plan can proceed.
+
+## Budget by shot difficulty
+
+Classify shots as quiet, talking, perspective or motion. Estimate the actual keyframes, guides, end frames, voice takes and H3 seconds per class; do not budget one attempt for every shot. As a starting allowance, quiet shots may need one take, talking shots one or two, and difficult contact/travel shots two or three plus start/end image edits. Adjust to the project's evidence and budget. Locally drawn guides cost no model calls. Give pivotal motion and perspective shots priority within the retry pool; choose their duration for pace, not importance. Include extra logo/cloth edits when a recurring mark must remain exact. See [staging-and-review.md](staging-and-review.md).
diff --git a/skills/make-an-anime/references/prompts.md b/skills/make-an-anime/references/prompts.md
index ebae772..6dca383 100644
--- a/skills/make-an-anime/references/prompts.md
+++ b/skills/make-an-anime/references/prompts.md
@@ -53,7 +53,7 @@ For a shot that continues the previous one, set `base:` to that keyframe and cha
`Fal::Models::H3MaxImageToVideo`, `minimax/h3-max/image-to-video`, **768P by default** (H3 offers 480P/768P/1080P; there is no 720P), prompt expansion disabled. `VIDEO_RES=1080P` refines a hero shot. Duration is the shot length (fractional seconds allowed, 0.92–15 s, at least 2 s with target audio; H3 may add up to ~0.7 s). The plate is upscaled to 1920×1080.
-Prompt (`prompt:` in `04_shots.yml`): identity and style (`{{STYLE}}`, "the same characters as in the image") → what happens, as two or three timed acting beats ("0–1 s: …; 1–2.5 s: …") → mouth ("speaks the line with natural lip movements; mouth closed before and after") → what must stay unchanged (faces on-model, outfit, background layout, light) → exclusions (no text, no extra people, no new props, no scene change). Anime acting reads best with clear holds and limited, purposeful motion: a blink, a breath, a head tilt, a slow smile, hair and cloth secondary motion, light flicker from a screen.
+Prompt (`prompt:` in `04_shots.yml`): identity and a short style sentence ("hand-drawn 2D anime; the same characters as in the image") → what happens, as two or three timed acting beats ("0–1 s: …; 1–2.5 s: …") → mouth ("speaks the line with natural lip movements; mouth closed before and after") → what must stay unchanged (faces on-model, outfit, background layout, light) → exclusions (no text, no extra people, no new props, no scene change). Anime acting reads best with clear holds and limited, purposeful motion: a blink, a breath, a head tilt, a slow smile, hair and cloth secondary motion, light flicker from a screen.
For a talking shot set `audio: <cast id>`; the shot then receives that character's mouth track from its own position in the scene. Never retime a talking shot.
@@ -115,3 +115,9 @@ If a take drifts off-model, reduce motion, shorten the shot or add an `end_image
Fetch `openapi:fetch` and read `openapi:summary`. The wrappers validate known properties/enums/ranges. Add any other Fal model as a Ruby `Fal::Models::Base` subclass, then a service/task. Do not call an SDK or curl directly. Do not silently substitute a model or quality setting.
Official sources: [H3 API](https://fal.ai/models/minimax/h3-max/image-to-video/api), [Sunburst generation](https://fal.ai/models/openai/gpt-image-2.6/sunburst/text-to-image/api), [Sunburst edit](https://fal.ai/models/openai/gpt-image-2.6/sunburst/edit/api), [ElevenLabs Eleven v4](https://fal.ai/models/elevenlabs/tts/eleven-v4/api), [ElevenLabs Music v2.5](https://fal.ai/models/elevenlabs/music/v2.5/api).
+
+## Difficult staging and small repairs
+
+Use [staging-and-review.md](staging-and-review.md) for perspective guides, connected anatomy, pinned endings, recurring marks, natural prop gestures, jumps, travel and playback review. Keep the full palette bible in image prompts; in H3 name only the current shot’s look, light and room, including full colour through the last frame when intended. A list of different palettes can become an unwanted colour transition.
+
+For a replay from another scene, set `from_take: source-run/shot-name`, `frames`, and optional `skip_frames` or `source_frames`. The original take is copied locally with provenance and a content digest; there is no model call. The copy refreshes when the source bytes change, and assembly rejects insufficient frames. Reused footage does not transfer the source scene’s dialogue: rebuild the destination mix and check synchronisation.
diff --git a/skills/make-an-anime/references/staging-and-review.md b/skills/make-an-anime/references/staging-and-review.md
new file mode 100644
index 0000000..7c94a98
--- /dev/null
+++ b/skills/make-an-anime/references/staging-and-review.md
@@ -0,0 +1,74 @@
+# Staging, physical continuity and playback review
+
+Use this when a shot depends on anatomy, perspective, contact, travel, recurring marks or exact prop placement. These recipes came from production failures; they improve the odds, but a successful first/last frame or a passing metric does not prove that the middle of a take works.
+
+## One camera, one body, one room
+
+For a person beside a door, rail, seat or other familiar object, put real dimensions and their visible consequence in the keyframe prompt: “The rail is above her head; she stands upright.” Avoid metaphors such as “folded under” when the actual clearance allows standing. For difficult perspective, draw a local guide from one camera before paying for an image. Keep its generating script with the project. Send the guide first, explicitly as geometry to repaint, followed by the character and location references. Its flat colours and stick figures must disappear in the finished painting.
+
+An end-frame guide keeps the first frame's camera, horizon and stationary figures; move only what the action changes. Otherwise the edit model may reframe the camera to match the new guide. Review the painting against the guide before animation.
+
+Describe a cropped or reaching body as a connected chain: facing direction, torso position (even outside the crop), shoulder → elbow → wrist → hand, then hips → knees → feet. Work out near/far limbs from the actual camera and pose. Do not prescribe a handedness from screen direction alone. Trace each visible limb back to one torso and count the fingers. If the hand cannot reach a handle without passing through a pot, turn the handle or move the prop before rewording the anatomy.
+
+For removing one of two people, identify both the person to retain and the person to remove by clothing and screen position. For standing up or a jump, leave room for the highest head position. A medium shot that fits the seated pose may crop the standing one.
+
+A dim room still has a floor that recedes into it, walls, soft background objects, contact shadows and shared light. A bright figure on an isolated floor patch against black can look pasted on. Describe distant lamps by apparent size, distance and blur. In a chain of closer `base:` edits, re-describe the new background; “keep the lamp” can enlarge it along with the subject. Location sheets should name where doors lead, and a doorway prompt should say what is visible through it.
+
+## Pin what must remain true
+
+Use `end_image` when possession of a prop, relative height, a landing position, camera travel or distant lighting must survive to the end. Make the end frame as a `base:` edit of the start, changing only the intended action. Include it in the budget from the start for difficult travel/contact shots; it is also a useful first retake strategy.
+
+For a tracking run, the end frame should show a different stretch of the same location at the same camera height and angle. State the distance travelled and the foreground/background features that pass. Run `review:believable` as well as watching the take: changing legs in a sparse contact sheet can disguise a stationary world. The existing 0.20 frame-width/s threshold is a heuristic for tracking runs, not a universal minimum for walking or a locked camera.
+
+Pinning the endpoints does not constrain the middle. Inspect limbs crossing faces, invented props, light flashes and background changes throughout.
+
+## Contact and pace
+
+For a grounded jump, landing, fall or body contact, prefer one take showing the body and its ground together. A feet insert followed by a torso shot can hide the actual take-off and break continuity. A level, locked wide view is a useful starting point for a vertical jump; tracking can be appropriate for travel. Keep shoes, contact shadows and room for the apex in frame. Write timed beats for load, push-off, airborne action and landing. The shadow stays on the ground.
+
+Choose duration from the intended pace. Importance calls for more review and retry allowance, not automatically a longer take. Check how many seconds elapse before the action begins. Review an early action take at normal speed before scaling up production; a frame board cannot verify pacing.
+
+For a jump, inspect feet at least eight times a second around take-off and landing, then count the actual airborne frames. Compare timing to the intended height, physical action and chosen slow-motion treatment. If only the airborne interval drags, a local edit can shorten that interval while preserving approach and landing. Preserve the downloaded original and account for every shifted shot, subtitle, voice, score and SFX cue. Never retime visible speech. `source_frames` plus `retime` trims/retimes the selected whole interval; it is not an automatic airborne-only repair.
+
+Anime often holds a drawing for two or three frames. Examine consecutive frames over the first twelve frames before diagnosing an opening “pop”; recurring held drawings are not a reason to discard the opening. `skip_frames` now contributes to generation duration, and assembly refuses a source that cannot fill its declared slot.
+
+For sports or other physical tasks, write the object's complete path rather than only the desired result. A miss needs a direction away from the target, not just “misses.” A pass should specify whether the receiver catches in stride. Use the intended court/field layout, distances and rules of the story's era; a full-court establishing view needs both ends, while a half-court drill may intentionally show one.
+
+## Acting, props and stills
+
+A roster or character entrance normally needs a small purposeful performance rather than a held action pose with moving labels. Budget for the people who must act. Keep an intentional freeze-frame, manga panel or still illustration when it fits the approved direction; record why it is static instead of treating every character still as a technical error.
+
+For a short take, give one visible action with timing. Hands must be visible and able to reach the object they manipulate. Describe a natural whole-hand gesture and its reason: sweeping small pieces into a palm and closing a fist, rather than plucking them like a specimen. Pin the final hand/prop position when it matters.
+
+Keep sound-only events in SFX cues. Naming a buzzer as a visual beat can make the model draw a new buzzer. Specify stable jersey markings and avoid inviting new text or equipment. Do not repeat names of absent objects unnecessarily: even exclusions can introduce them.
+
+## Recurring logos and marks
+
+For a mark included in the approved design, supply the actual artwork as a reference whenever it must be reproduced. Flatten a white transparent mark onto its intended backing colour if the model would otherwise see white on white. If placement must be exact, position it locally, then edit that composite with the mark as a reference so it follows cloth and perspective. Correct the character sheet first and use that accepted version downstream.
+
+Compare front, three-quarter and side views: the mark narrows as the surface turns, without damaging the silhouette or face. Inspect other characters and the floor too; references do not prevent invented marks elsewhere. Small detailed marks can blur in a wide 768P take; simplify them or plan a closer pinned end frame when readability matters. Budget the extra image edits.
+
+## Review record
+
+Watch with sound, then inspect the first, middle, last and decisive action frames at useful size. Write brief answers for applicable checks; mark a check unverified when only stills were inspected.
+
+| Check | Evidence to record |
+| --- | --- |
+| Scale and perspective | Person against a known-size object; camera, floor and wall lines agree |
+| Anatomy and reach | Continuous limbs connected to one torso; hands can reach their targets |
+| Contact | Actual take-off/landing/contact frame and shadows on the ground |
+| Room and light | Shared lighting, no unintended outlines, distant lamps retain size and softness |
+| Action and pace | Frame of the intended action, delay before it starts, playback judgment |
+| Mouths | Close face crops through pauses; silent people do not start talking |
+| Continuity | Last frame against next shot's first: feet, hands, props, possession and light |
+| Colour and cuts | Inspect consecutive frames, including the tail and immediately after flashes |
+
+Metrics identify failures; they do not certify believable performance. When the user finds an anatomy or scale fault, inspect other shots with the same setup. Retake within the approved allowance, or record the unresolved limitation. Do not invent a successful playback review from screenshots.
+
+## Voice and local repair
+
+`review:dialogue` already compares word multiplicities, so a repeated phrase can be flagged even when every word belongs to the script. Its Whisper call uses Fal and is paid; it is not local transcription. Listen to soft, whispered and non-Latin lines when transcription is uncertain rather than silently weakening acceptance.
+
+Use `gate_s` for unwanted leading speech and `keep_s` for a repeated tail when a clean take remains. Rebuild `gen:dialogue`, then `gen:mix`; `dialogue:timeline` uses `speech_at` for the audible start, consistent with subtitles. `muffled: true` applies a local closed-door filter; combine with `vo: true` when no mouth should move. Listen to the filtered result before accepting it.
+
+After a changed score, dialogue mix or mix settings, `gen:mix` fingerprints its actual audio inputs and settings and rebuilds locally. Shots and overlays refuse a missing/stale mix when dialogue exists. Music-only scenes default to -12 dB; set an explicit `music_db` for the intended balance and check neighbouring scenes by ear. Keep source/research credits in delivery notes or description text unless the approved film includes an on-screen credit sequence.
diff --git a/skills/make-an-anime/references/tasks.md b/skills/make-an-anime/references/tasks.md
index cfbe8a2..aeea982 100644
--- a/skills/make-an-anime/references/tasks.md
+++ b/skills/make-an-anime/references/tasks.md
@@ -109,7 +109,7 @@ Prompt files per run:
| `03_score.json` / `.txt` | ElevenLabs Music v2.5 composition plan (`{"chunks": [...]}`) or prompt; instrumental, scene length |
| `02_keyframes.yml` | Named image edit prompts, `base`, `refs` |
| `04_video.txt` | Single-shot H3 prompt (the Video step reads this stem) |
-| `04_shots.yml` | Ordered shots: `image`/`end_image`, `frames`, `prompt`, `camera`, `audio: <cast id>`, `seconds`, or `still:`/`color:` inserts |
+| `04_shots.yml` | Ordered shots: `image`/`end_image`, `frames`, `prompt`, `camera`, `audio: <cast id>`, `seconds`, `from_take: run/shot`, or `still:`/`color:` inserts |
| `04_clips.yml` | H3/still/source sprite specifications and chroma/crop |
| `05_overlay.js` | p5 sketch, rendered through Ruby |
@@ -153,7 +153,7 @@ Example `03_dialogue.yml` and `04_shots.yml` for a scene:
image: kid-bed
frames: 84
audio: kid
- prompt: "{{STYLE}} The boy from the image half-lifts his head from the pillow, eyes barely open; 0.5–2.5 s he mumbles his line with small sleepy mouth movements; blinks slowly; blanket shifts. Faces on-model, room unchanged, no text, no extra people."
+ prompt: "Same restrained cel-anime look and dim bedroom lighting. The boy from the image half-lifts his head from the pillow, eyes barely open; 0.5–2.5 s he mumbles his line with small sleepy mouth movements; blinks slowly; blanket shifts. Faces on-model, room unchanged, no text, no extra people."
camera: { move: locked-off, framing: medium close-up on the pillow, notes: "faint handheld micro-sway, no zoom" }
- name: screen
color: "#05070a"
@@ -200,12 +200,16 @@ RUN=ep01-s01 ruby scripts/mv.rb --project /absolute/project anim:overlay
ruby scripts/mv.rb --project /absolute/project 'media:preview[output/clean.mp4,ep01-s01,ep01-s02]'
```
-`gen:ref_base`, `gen:keyframes`, `gen:dialogue`, `gen:video`, `gen:shots`, H3 `gen:clips`, generated music/score, `review:dialogue`, `gen:overlay`, `review:music`, stems and SFX may call paid Fal endpoints. `gen:music` for an imported song is local processing plus CDN upload; `gen:overlay` uses paid Whisper unless re-rendering saved cues through `anim:overlay`. Reviews other than music are local. `pipeline:all` includes paid review calls; allocate them in the plan.
+`gen:ref_base`, `gen:keyframes`, `gen:dialogue`, `gen:video`, `gen:shots`, H3 `gen:clips`, generated music/score, `review:dialogue`, `gen:overlay`, `review:music`, stems and SFX may call paid Fal endpoints. `gen:music` for an imported song is local processing plus CDN upload; `gen:overlay` uses paid Whisper unless re-rendering saved cues through `anim:overlay`. Other review tasks are local. `pipeline:all` includes paid review calls; allocate them in the plan.
For existing reliable word timings, use `anim:prepare[full-song-words.json]` after the plate prerequisites exist, then `anim:preview`/`anim:overlay`. It accepts Whisper `chunks` or an array of `{w,s,e}` / `{word,start,end}`, selects this section and subtracts its song offset. With no argument it writes an empty cue list for sketches with explicitly authored timing. It also prepares configured tracks locally. `anim:overlay` records a complete manifest even on the first local render, so `review:overlay` works without a paid `gen:overlay` call.
`FORCE=1` changes cached work; `ONLY` confines ItemsStep work to named assets. A selected partial item set will not build the complete step's board until all items exist. `NEW_REQUEST=1` allows a new identical paid request; normal retries reuse saved receipts. `history[step]`, `adopt[step,request_id]`, `pick[step,index]`, `import[step,source_run]` support recovery and reuse. ItemsStep recovery uses per-item stored request IDs and reruns; adopt/pick are for single-output steps.
+`gen:mix` fingerprints its settings and source audio; changes invalidate the cached mix even when timestamps are preserved. Re-run `gen:dialogue` after line-placement/filter edits, then `gen:mix` before shots or overlays. Music-only scenes default to `music_db: -12`; scenes with dialogue retain `-4`, and explicit values win. `muffled: true` applies a local closed-door filter to a line's mix, leaving its raw take and mouth track intact. `dialogue:timeline` uses the audible `speech_at` after gating when available.
+
+Existing shots can be copied locally with `from_take: source-run/shot-name`. `skip_frames` trims the prefix; `source_frames` selects the interval length after that prefix. Assembly rejects short sources before writing a plate. `retime: true` stretches that selected interval and is refused for shots with audio. See [staging-and-review.md](staging-and-review.md) for physical review and timing decisions.
+
## Analysis, finishing and utility tasks
```sh
@@ -222,9 +226,14 @@ VFX=finish-vfx ruby scripts/mv.rb --project /absolute/project vfx:analyze
VFX=finish-vfx ruby scripts/mv.rb --project /absolute/project 'vfx:stills[0,24,120]'
VFX=finish-vfx ruby scripts/mv.rb --project /absolute/project 'vfx:clip[96,144]'
VFX=finish-vfx ruby scripts/mv.rb --project /absolute/project vfx:render
+ruby scripts/mv.rb --project /absolute/project 'vfx:bake[ep01-s01]'
+ruby scripts/mv.rb --project /absolute/project 'game:cut[config/cut-units.json]'
+ruby scripts/mv.rb --project /absolute/project 'game:faces[config/build-faces.json]'
ruby scripts/mv.rb --project /absolute/project 'media:twitter[output/finished.mp4,output/delivery-1080.mp4]'
```
+For local particles and a repeatable light-only halo pass, see [particles-and-glow.md](particles-and-glow.md). For game artwork recipes and p5 screen/mission/court helpers, see [game-screens.md](game-screens.md). `vfx:bake` requires the documented cues paths, preserves the plain picture, and finishes before `sfx:mix`.
+
`media:probe`, `media:sheet`, `media:frame`, `media:cut`, `media:cutout`, `media:sprite_box`, `media:style`, `media:concat`, `media:mux`, `media:upload` and `media:youtube` are listed by `-T` with their arguments. Export names denote encoding presets; they do not publish to platforms. For unlisted operations, add an OOP service under `lib/` and a thin registry delegate. Keep backend code under `tools/` and tests in `spec/`.
For detached lettering or debris in an RGBA sprite sequence, run `ruby scripts/mv.rb --project /absolute/project 'media:keep_component[output/raw-sprite,output/clean-sprite,320,400]'`. The seed is an integer pixel coordinate inside the intended subject in **every** input frame. The task preserves its four-connected nonzero-alpha component exactly and clears other alpha; it never expands or bridges components. Output must be a different, new or empty directory. Out-of-bounds or transparent seeds fail the whole sequence without publishing partial output. Touching text remains part of the subject and needs a separate mask; inspect the cleaned motion before use.
diff --git a/skills/make-an-anime/references/testing.md b/skills/make-an-anime/references/testing.md
index 6ca1b2b..6c3fd7e 100644
--- a/skills/make-an-anime/references/testing.md
+++ b/skills/make-an-anime/references/testing.md
@@ -26,6 +26,8 @@ Offline synthetic media is deliberately simple so placement/alpha/timing are mea
The media profile also checks seeded alpha-component cleanup through the public Ruby task: retained subject RGBA and soft alpha remain exact, detached lettering disappears, the original file remains unchanged, and invalid/missing seeds fail without publishing a partial sequence.
+Production regression examples cover source-length rejection before assembly, skipped-prefix retiming, cross-scene take reuse and replacement detection, gated speech timelines, water-versus-running language, audio/settings cache invalidation, and local muffled dialogue. Graphics fixtures verify deterministic particle frames in and out of order, a separate light layer, RTS/mission/court rendering, sheet and face cutting (including ambiguous-count rejection), and repeatable halo baking that preserves remixed audio and leaves the final unchanged on invalid cues.
+
## Paid live E2E
Live tests are excluded from routine runs. They require an explicit opt-in plus a real song excerpt and recognizable lyric words. This test invocation authorizes the listed test calls; it does not approve a new production plan.
diff --git a/skills/make-an-anime/scripts/lib/media/ffmpeg.rb b/skills/make-an-anime/scripts/lib/media/ffmpeg.rb
index 058eb06..f8d4a78 100644
--- a/skills/make-an-anime/scripts/lib/media/ffmpeg.rb
+++ b/skills/make-an-anime/scripts/lib/media/ffmpeg.rb
@@ -188,7 +188,7 @@ module Media
# Cut and join shots into one silent video at `fps`, sized like the first shot. segments: [{ path:, frames:,
# skip: (source frames to drop first), retime: (squeeze the whole source into `frames`), keep: (use only the source's
- # first N frames, before the trim or retime), roll: [from, to] (degrees, clockwise: a virtual camera roll, eased, scaled
+ # N frames after skip, before the retime), roll: [from, to] (degrees, clockwise: a virtual camera roll, eased, scaled
# up just enough to hide the corners; p5 layers follow it with Anim.withRoll) }].
# A stretched source can end a frame short of `frames` (fps drops the last stretched frame at EOF: a 72->96 retime
# gave 95). Clone the last frame a little before the trim so a retimed shot is always exactly `frames`.
@@ -198,12 +198,13 @@ module Media
first = summary(segments.first[:path])[:video]
size = "scale=#{w || first[:w]}:#{h || first[:h]}:flags=lanczos,setsar=1"
chains = segments.each_with_index.map do |seg, i|
- timing = if seg[:retime] && seg[:keep]
- "fps=#{fps},trim=end_frame=#{seg[:keep]},setpts=(PTS-STARTPTS)*#{seg[:frames].fdiv(seg[:keep]).round(6)},fps=#{fps},#{PAD_END},trim=end_frame=#{seg[:frames]}"
- elsif seg[:retime]
- "setpts=(PTS-STARTPTS)*#{(seg[:frames].fdiv(fps) / duration(seg[:path])).round(6)},fps=#{fps},#{PAD_END},trim=end_frame=#{seg[:frames]}"
+ skip = seg[:skip].to_i
+ timing = if seg[:retime]
+ keep = seg[:keep] || (duration(seg[:path]) * fps).round - skip
+ raise ArgumentError, "No source frames remain after skip" unless keep.positive?
+ "fps=#{fps},trim=start_frame=#{skip}:end_frame=#{skip + keep},setpts=(PTS-STARTPTS)*#{seg[:frames].fdiv(keep).round(6)},fps=#{fps},#{PAD_END},trim=end_frame=#{seg[:frames]}"
else
- "fps=#{fps},trim=start_frame=#{seg[:skip].to_i}:end_frame=#{seg[:skip].to_i + seg[:frames]}"
+ "fps=#{fps},trim=start_frame=#{skip}:end_frame=#{skip + seg[:frames]}"
end
"[#{i}:v]#{timing},setpts=PTS-STARTPTS,#{size}#{roll_filter(seg, w || first[:w], h || first[:h])}[v#{i}]"
end
@@ -260,6 +261,7 @@ module Media
gain += ",afade=t=in:st=#{l["gate_s"].to_f}:d=0.02" if l["gate_s"]
gain += ",afade=t=out:st=#{[l["keep_s"].to_f - 0.12, 0].max}:d=0.12,atrim=end=#{l["keep_s"].to_f}" if l["keep_s"]
gain += ",highpass=f=160,aecho=0.8:0.8:60|120:0.28|0.16" if l["inner"]
+ gain += ",lowpass=f=900,lowpass=f=1400,aecho=0.8:0.6:18|31:0.35|0.25" if l["muffled"]
"[#{i}:a]aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo#{gain},adelay=#{ms}|#{ms}[a#{i}]"
end
graph = "#{chains.join(";")};#{lines.each_index.map { |i| "[a#{i}]" }.join}amix=inputs=#{lines.size}:normalize=0,apad=whole_dur=#{seconds}[out]"
diff --git a/skills/make-an-anime/scripts/lib/media/game_assets.rb b/skills/make-an-anime/scripts/lib/media/game_assets.rb
new file mode 100644
index 0000000..fa96f9e
--- /dev/null
+++ b/skills/make-an-anime/scripts/lib/media/game_assets.rb
@@ -0,0 +1,39 @@
+require_relative "python"
+module Media
+ # JSON recipes avoid comma-separated task arguments for names, crops and paths.
+ class GameAssets
+ def cut(recipe)
+ r = JSON.parse(File.read(recipe))
+ mode = r.fetch("mode")
+ options = case mode
+ when "sprites", "grid" then %w[names key min_px min_len gap margin size inset]
+ when "frame" then %w[key dark scale min_area]
+ when "fit" then %w[width crop]
+ else raise ArgumentError, "mode must be sprites, grid, frame or fit"
+ end
+ args = [mode, r.fetch("source"), r.fetch("out")]
+ args << r.fetch("slots") if mode == "frame"
+ Python.new.call("cut_sheets.py", *args, *flags(r, options))
+ end
+
+ def faces(recipe)
+ r = JSON.parse(File.read(recipe))
+ args = case r.fetch("mode")
+ when "build" then ["build", r.fetch("spec"), r.fetch("out"), *flags(r, %w[preview])]
+ when "cut" then ["cut", r.fetch("source"), r.fetch("spec"), r.fetch("out"), *flags(r, %w[size tol])]
+ else raise ArgumentError, "mode must be build or cut"
+ end
+ args << "--grid-fallback" if r["mode"] == "cut" && r["grid_fallback"] == true
+ Python.new.call("face_collage.py", *args)
+ end
+
+ private
+
+ def flags(recipe, keys)
+ keys.select { recipe.key?(_1) }.flat_map do |key|
+ value = recipe[key]
+ ["--#{key.tr('_', '-')}", value.is_a?(Array) ? value.join(",") : value.to_s]
+ end
+ end
+ end
+end
diff --git a/skills/make-an-anime/scripts/lib/media/vfx.rb b/skills/make-an-anime/scripts/lib/media/vfx.rb
index fc6941b..e7edcd2 100644
--- a/skills/make-an-anime/scripts/lib/media/vfx.rb
+++ b/skills/make-an-anime/scripts/lib/media/vfx.rb
@@ -16,7 +16,7 @@ module Media
PACKAGE = File.join(ROOT, "tools", "vfx")
BIN = File.join(PACKAGE, ".build", "release", "mvfx")
CORE_IMAGE = %w[punch zoom shake whip mblur edgeblur glow flash dark rgb glitch tv grain].freeze
- LIGHTS = %w[leak flare glints].freeze
+ LIGHTS = %w[leak flare glints halo].freeze
attr_reader :name, :dir
@@ -99,11 +99,11 @@ module Media
end
# The whole video -> config `out` (the source's audio stream copied).
- def render
+ def render(out_path: out)
cues
lights
- mvfx("--out", out)
- out
+ mvfx("--out", out_path)
+ out_path
end
def frames = @frames ||= FFmpeg.new.run("ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries",
diff --git a/skills/make-an-anime/scripts/lib/media/vfx_bake.rb b/skills/make-an-anime/scripts/lib/media/vfx_bake.rb
new file mode 100644
index 0000000..47876f1
--- /dev/null
+++ b/skills/make-an-anime/scripts/lib/media/vfx_bake.rb
@@ -0,0 +1,54 @@
+require "digest"
+require_relative "vfx"
+
+module Media
+ # A local finish between gen:overlay and sfx:mix. Keep the plain picture and
+ # render to a temporary output so failures never replace the current overlay.
+ class VfxBake < Shell
+ def initialize(run, root: Vfx::ROOT)
+ raise ArgumentError, "Invalid run" unless run.match?(/\A[a-zA-Z0-9_-]+\z/)
+ @root, @name = root, run
+ end
+
+ def bake
+ dir = File.join(@root, "output", @name)
+ final, plain = %w[final_overlay.mp4 final_overlay_plain.mp4].map { File.join(dir, _1) }
+ raise ArgumentError, "Run gen:overlay first: #{final}" unless File.file?(final)
+ service = Vfx.new("#{@name}-vfx")
+ raise ArgumentError, "Bake cues must read #{plain} and write #{final}" unless service.source == plain && service.out == final
+ service.cues # validate before changing the backup
+ stamp = service.path("baked.json")
+ pending = "#{stamp}.pending"
+ temp = File.join(dir, ".baking.mp4")
+ File.open(service.path("bake.lock"), File::CREAT | File::RDWR) do |lock|
+ lock.flock(File::LOCK_EX)
+ digest = video_hash(final)
+ previous = [pending, stamp].filter_map { |p| JSON.parse(File.read(p)) if File.file?(p) }
+ baked = previous.find { |r| r["video_sha256"] == digest }
+ if baked
+ raise "Plain overlay missing or changed; rebuild gen:overlay before baking" unless File.file?(plain) && video_hash(plain) == baked["plain_sha256"]
+ # Preserve a later dialogue remix without processing the baked picture twice.
+ run("ffmpeg", "-v", "error", "-y", "-i", plain, "-i", final, "-map", "0:v:0", "-map", "1:a?", "-c", "copy", temp)
+ else
+ FileUtils.cp(final, temp)
+ end
+ File.rename(temp, plain)
+ service.render(out_path: temp)
+ receipt = { video_sha256: video_hash(temp), plain_sha256: video_hash(plain) }
+ File.write(pending, JSON.pretty_generate(receipt))
+ File.rename(temp, final)
+ # A pending receipt also recognizes a completed output after a crash here.
+ File.rename(pending, stamp)
+ { path: final, plain: plain, reused_plain: !!baked }
+ ensure
+ FileUtils.rm_f(temp)
+ end
+ end
+
+ private
+
+ def video_hash(path)
+ run("ffmpeg", "-v", "error", "-i", path, "-map", "0:v:0", "-c", "copy", "-f", "hash", "-hash", "sha256", "-", quiet: true).strip
+ end
+ end
+end
diff --git a/skills/make-an-anime/scripts/lib/pipeline/believability.rb b/skills/make-an-anime/scripts/lib/pipeline/believability.rb
index 0d8d55d..1d64eab 100644
--- a/skills/make-an-anime/scripts/lib/pipeline/believability.rb
+++ b/skills/make-an-anime/scripts/lib/pipeline/believability.rb
@@ -28,7 +28,10 @@ module Pipeline
# What the prompt actually asks for: the style bible and the negated phrases are removed, so a style that mentions a
# fight, or "no running" and "nobody falls", do not count as action.
- def asserted(text) = text.to_s.sub(Project.style.to_s, " ").gsub(NEGATED, " ")
+ def asserted(text)
+ text.to_s.sub(Project.style.to_s, " ").gsub(NEGATED, " ")
+ .gsub(/\b(?:water|liquid|stream|tap|faucet)\s+(?:is\s+)?running\b|\brunning\s+(?:water|liquid|stream|tap|faucet)\b/i, " ")
+ end
def camera_text(spec)
camera = spec["camera"]
@@ -37,7 +40,7 @@ module Pipeline
def keyed?(spec) = %w[green paper].include?(spec.fetch("key", "paper"))
- def generated?(spec) = !(spec["still"] || spec["color"] || spec["from_run"] || spec["same_take"] || spec["source"])
+ def generated?(spec) = !(spec["still"] || spec["color"] || spec["from_run"] || spec["from_take"] || spec["same_take"] || spec["source"])
def running?(spec) = generated?(spec) && !spec["believable"] && asserted(spec["prompt"]).match?(RUN_WORDS)
diff --git a/skills/make-an-anime/scripts/lib/pipeline/project.rb b/skills/make-an-anime/scripts/lib/pipeline/project.rb
index fb7bf91..55c463d 100644
--- a/skills/make-an-anime/scripts/lib/pipeline/project.rb
+++ b/skills/make-an-anime/scripts/lib/pipeline/project.rb
@@ -77,7 +77,13 @@ module Pipeline
def prompt?(stem) = !Dir[File.join(ROOT, "prompts", name, "#{stem}.*")].empty?
# The scene soundtrack: the Mix step's dialogue + score when present, else the Music step's audio.
- def soundtrack = self[:mix]&.dig("path") || fetch!(:music, :path)
+ def soundtrack
+ if self[:dialogue] || self[:mix]
+ raise "Soundtrack mix missing or stale: run gen:mix after gen:dialogue/gen:music or mix setting changes" unless Steps::Mix.new(project: self).done?
+ return fetch!(:mix, :path)
+ end
+ fetch!(:music, :path)
+ end
# The shared anime style bible (config/style.md), substituted for {{STYLE}} in every image and H3 prompt so one
# paragraph keeps every character sheet, keyframe and shot in the same look.
diff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/dialogue.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/dialogue.rb
index c23cafd..61b1b40 100644
--- a/skills/make-an-anime/scripts/lib/pipeline/steps/dialogue.rb
+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/dialogue.rb
@@ -15,6 +15,7 @@ module Pipeline
# subtitle: "Gatto! (Cat!)" # optional: what the subtitle shows instead of `text` (a gloss); not sent to TTS
# gate_s: 0.28 # optional: silence the start of the take in the mix (a blip before the first word)
# keep_s: 1.2 # optional: keep only this much of the take (a long tail of breath or silence)
+ # muffled: true # optional: voice heard through a closed door, applied locally to the mix
# inner: true # optional, with vo: a thought in the character's head, treated so it isn't heard as spoken
# subtitle: " " # a blank subtitle: a laugh or breath with no caption, not counted as speech when levelling
# gain_db: -5 # optional: level this take in the scene mix only (takes vary by ±8 dB); the mouth
@@ -65,7 +66,7 @@ module Pipeline
{ "name" => name, "character" => spec["character"], "text" => spec["text"], "at" => spec["at"].to_f,
"end" => (spec["at"] + (spec["keep_s"] || item["duration"])).round(3), "vo" => !!spec["vo"], "path" => item["path"],
"speech_at" => (spec["at"] + [ffmpeg.leading_silence(item["path"]), spec["gate_s"].to_f].max).round(3), "subtitle" => spec["subtitle"],
- "gate_s" => spec["gate_s"]&.to_f, "keep_s" => spec["keep_s"]&.to_f, "inner" => spec["inner"],
+ "gate_s" => spec["gate_s"]&.to_f, "keep_s" => spec["keep_s"]&.to_f, "inner" => spec["inner"], "muffled" => spec["muffled"],
"gain_db" => spec["gain_db"]&.to_f }.compact
end.sort_by { |l| l["at"] }
late = lines.select { |l| l["end"] > length + 0.05 }
@@ -76,7 +77,7 @@ module Pipeline
end
end
tracks = cast.keys.select { |c| lines.any? { |l| l["character"] == c } }.to_h do |character|
- own = lines.select { |l| l["character"] == character && !l["vo"] }.map { |l| l.except("gain_db") }
+ own = lines.select { |l| l["character"] == character && !l["vo"] }.map { |l| l.except("gain_db", "muffled") }
[character, ffmpeg.place_audio(own, project.path("03_voice_#{character}.wav"), seconds: length)]
end
words = lines.flat_map do |l|
diff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/mix.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/mix.rb
index fc7cb19..db1d445 100644
--- a/skills/make-an-anime/scripts/lib/pipeline/steps/mix.rb
+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/mix.rb
@@ -1,3 +1,4 @@
+require "digest"
module Pipeline
module Steps
# Step 3c — the scene soundtrack (local, no Fal call): the score (Music step) ducked under the dialogue (Dialogue step),
@@ -15,7 +16,9 @@ module Pipeline
built = File.mtime(project[key]["path"])
newer = [project[:music]&.dig("path"), project[:dialogue]&.dig("path")].compact.select { |p| File.exist?(p) && File.mtime(p) > built }
warn "[#{key}] stale: #{newer.join(", ")} newer than the mix -> rebuilding" if newer.any?
- newer.any?
+ changed = project[key]["fingerprint"] != fingerprint
+ warn "[#{key}] settings or source content changed -> rebuilding" if changed
+ newer.any? || changed
end
def submit
@@ -30,7 +33,7 @@ module Pipeline
# The mix without the lift stays beside it: sfx:mix reads cue levels from it, so a louder voice keeps the effects where they were.
ffmpeg.duck_mix(music, dialogue, project.path("03_mix_ref.wav"), seconds: project.duration, **opts) if lift.positive?
out = ffmpeg.duck_mix(music, dialogue, project.path("03_mix.wav"), seconds: project.duration, **opts, dialogue_db: opts.fetch(:dialogue_db, 0) + lift)
- { request_id: nil, endpoint: "local:mix", input: result.input.merge("music" => music, "dialogue" => dialogue), path: out }
+ { request_id: nil, endpoint: "local:mix", input: result.input.merge("music" => music, "dialogue" => dialogue), path: out, fingerprint: fingerprint }
end
def review
@@ -52,7 +55,14 @@ module Pipeline
private
- def settings = { "music_db" => -4, "dialogue_db" => 0, "duck" => true }.merge(project.generation.fetch(:mix, {}).transform_keys(&:to_s))
+ def fingerprint
+ sources = [project[:music]&.dig("path"), project[:dialogue]&.dig("path")].map do |path|
+ [path, path && File.file?(path) ? Digest::SHA256.file(path).hexdigest : nil]
+ end
+ Digest::SHA256.hexdigest(JSON.generate([settings.sort.to_h, project.duration, sources]))
+ end
+
+ def settings = { "music_db" => (project[:dialogue]&.dig("path") ? -4 : -12), "dialogue_db" => 0, "duck" => true }.merge(project.generation.fetch(:mix, {}).transform_keys(&:to_s))
end
end
end
diff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/shots.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/shots.rb
index 320e261..0df1aee 100644
--- a/skills/make-an-anime/scripts/lib/pipeline/steps/shots.rb
+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/shots.rb
@@ -1,3 +1,4 @@
+require "digest"
module Pipeline
module Steps
# Step 4b — a scene's edit (the anime default). prompts/<run>/04_shots.yml lists the shots in edit order, each `frames` long:
@@ -7,13 +8,14 @@ module Pipeline
# audio: <track> H3 target audio from this shot's position in the scene: a cast id (that character's mouth track from
# the Dialogue step, silent while others speak), "dialogue" (all lines) or true (the full soundtrack)
# seconds H3 generation length, fractional allowed (0.92..15, >= 2 with audio); default: the shot length
- # retime: true the whole H3 clip is squeezed into `frames` (fast camera moves; never with dialogue)
- # source_frames: N use only the take's first N frames (cut before a defect, e.g. invented lettering), then trim or
+ # retime: true the selected H3 interval is squeezed into `frames` (fast camera moves; never with dialogue)
+ # source_frames: N use N frames after skip_frames (cut before a defect, e.g. invented lettering), then trim or
# retime them to `frames`; the downloaded take stays whole, and a retake keeps the same cut point
# roll: [from, to] a virtual camera roll over the shot, in degrees (clockwise), applied to the plate locally; layers
# drawn in p5 follow it with Anim.withRoll(frame, fn) so sprites and background turn together
# still: <keyframe> no generation: the keyframe held (zoom: [1.0, 1.06] for a slow push) — inserts, held drawings
# color: "#05070a" no generation: a solid frame the overlay draws on (screens, title cards, smash-cut white)
+ # from_take: <run>/<shot> no generation: copy an existing take, validate its length and record its source digest
# from_run: <run> no generation: that run's video (same timeline) from this shot's position
# same_take: <shot> no generation: the footage of an earlier shot of this list, from skip_frames on, for a beat that must
# repeat exactly (a running gag). Place the repeated line at the same offset inside the shot.
@@ -42,10 +44,21 @@ module Pipeline
# those are compared by frame count only.
def run!(**)
Believability.refuse!(specs.flat_map { |name, spec| Believability.shot_problems(name, spec) })
+ specs.each do |name, spec|
+ raise ArgumentError, "#{name}: never retime a talking or singing shot" if spec["audio"] && spec["retime"]
+ raise ArgumentError, "#{name}: frames must be a positive integer" unless spec["frames"].is_a?(Integer) && spec["frames"].positive?
+ raise ArgumentError, "#{name}: skip_frames must be a nonnegative integer" unless spec.fetch("skip_frames", 0).is_a?(Integer) && spec.fetch("skip_frames", 0) >= 0
+ end
+ project.soundtrack # refuse missing/stale dialogue mixes before submitting a take
super
end
def stale_item?(name, spec, item)
+ if spec["from_take"]
+ source = imported_take(spec)
+ return item["from_take"] != spec["from_take"] || item["source_sha256"] != Digest::SHA256.file(source).hexdigest
+ end
+ return true if item["from_take"] # switching an imported item to a different source type
return false unless spec["still"] || spec["color"]
stale = item["spec"] ? item["spec"] != local_spec(spec) : ffmpeg.summary(item["path"]).dig(:video, :frames).to_i != spec["frames"]
warn "[#{key}] #{name}: local shot spec changed -> rebuilding" if stale
@@ -55,6 +68,17 @@ module Pipeline
def local_spec(spec) = spec.slice("frames", "color", "still", "zoom")
def generate(name, spec)
+ if spec["from_take"]
+ source = imported_take(spec)
+ validate_source!(name, spec, source)
+ out = project.path("04_shot_#{name}.mp4")
+ raise ArgumentError, "#{name}: from_take cannot overwrite its source" if File.expand_path(source) == File.expand_path(out)
+ tmp = "#{out}.tmp"
+ FileUtils.cp(source, tmp)
+ File.rename(tmp, out)
+ return { source: spec["from_take"], from_take: spec["from_take"], adopted: true,
+ source_sha256: Digest::SHA256.file(source).hexdigest, path: out }
+ end
if (run = spec["from_run"])
return { source: run, path: Project.new(run).fetch!(:video, :path) }
end
@@ -70,7 +94,7 @@ module Pipeline
end
raise ArgumentError, "Never retime a talking or singing shot" if spec["audio"] && spec["retime"]
seconds = spec.fetch("seconds") { default_seconds(spec) }
- raise ArgumentError, "shot #{name} needs more source frames (#{spec["frames"]} > #{seconds}s)" if !spec["retime"] && spec["frames"] > seconds * FPS
+ raise ArgumentError, "shot #{name} needs more source frames (#{spec["frames"]} > #{seconds}s)" if !spec["retime"] && (spec["source_frames"] || spec["frames"]) + spec.fetch("skip_frames", 0) > (seconds * FPS).round
raise ArgumentError, "shot #{name}: source_frames #{spec["source_frames"]} < frames #{spec["frames"]} needs retime: true" if spec["source_frames"] && !spec["retime"] && spec["source_frames"] < spec["frames"]
audio = audio_url(name, spec, seconds) if spec["audio"]
result = MODEL.new(client: client).animate(
@@ -91,6 +115,7 @@ module Pipeline
end
def finish(items)
+ specs.each { |name, spec| validate_source!(name, spec, items.fetch(name).fetch("path")) }
segments = specs.map do |name, spec|
{ path: items[name]["path"], frames: spec["frames"], retime: spec["retime"], keep: spec["source_frames"],
skip: source_skip(spec), roll: spec["roll"] }
@@ -131,6 +156,26 @@ module Pipeline
private
+ def imported_take(spec)
+ ref = spec.fetch("from_take")
+ raise ArgumentError, "from_take must be <run>/<shot>" unless ref.is_a?(String) && ref.match?(%r{\A[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+\z})
+ run, take = ref.split("/")
+ item = Project.new(run).fetch!(:shots, :items).fetch(take) { raise ArgumentError, "No take #{ref}" }
+ path = item.fetch("path")
+ raise ArgumentError, "Missing source take #{ref}: #{path}" unless File.file?(path)
+ path
+ end
+
+ def validate_source!(name, spec, path)
+ have = ffmpeg.summary(path).dig(:video, :frames).to_i
+ skip = source_skip(spec)
+ keep = spec["source_frames"]
+ raise ArgumentError, "#{name}: source_frames must be a positive integer" if keep && !(keep.is_a?(Integer) && keep.positive?)
+ need = skip + (keep || (spec["retime"] ? 1 : spec["frames"]))
+ raise ArgumentError, "#{name}: source has #{have} frames; needs #{need} including #{skip} skipped frames" if have < need
+ raise ArgumentError, "#{name}: source_frames < frames needs retime: true" if keep && !spec["retime"] && keep < spec["frames"]
+ end
+
def source_skip(spec)
return spec["start_frame"] if spec["from_run"]
@@ -145,7 +190,7 @@ module Pipeline
# The shot's own length (H3 may add ~0.7 s), at least 2 s when audio is pinned, rounded up to 0.1 s.
def default_seconds(spec)
- [(spec["frames"].fdiv(FPS) * 10).ceil / 10.0, spec["audio"] ? 2.0 : 1.0].max
+ [((spec["frames"] + spec.fetch("skip_frames", 0)).fdiv(FPS) * 10).ceil / 10.0, spec["audio"] ? 2.0 : 1.0].max
end
def keyframe_path(name)
diff --git a/skills/make-an-anime/scripts/lib/toolkit/anime_review.rb b/skills/make-an-anime/scripts/lib/toolkit/anime_review.rb
index 962c3b4..872f4ec 100644
--- a/skills/make-an-anime/scripts/lib/toolkit/anime_review.rb
+++ b/skills/make-an-anime/scripts/lib/toolkit/anime_review.rb
@@ -102,22 +102,22 @@ module Toolkit
end
issues = []
rows = shots.map do |s|
- inside = lines.select { |l| l["at"] < s[:to] && l["end"] > s[:from] }
+ inside = lines.select { |l| l.fetch("speech_at", l["at"]) < s[:to] && l["end"] > s[:from] }
if s[:audio].is_a?(String) && s[:audio] != "dialogue"
own = inside.reject { |l| l["vo"] }.select { |l| l["character"] == s[:audio] }
issues << "#{s[:name]}: audio #{s[:audio]} but none of their on-screen lines play here" if own.empty?
own.each do |l|
- next if l["at"] >= s[:from] && l["end"] <= s[:to]
- issues << format("%s: %s's line %s (%.2f–%.2f s) crosses the shot (%.2f–%.2f s)", s[:name], s[:audio], l["name"], l["at"], l["end"], s[:from], s[:to])
+ next if l.fetch("speech_at", l["at"]) >= s[:from] && l["end"] <= s[:to]
+ issues << format("%s: %s's line %s (%.2f–%.2f s) crosses the shot (%.2f–%.2f s)", s[:name], s[:audio], l["name"], l.fetch("speech_at", l["at"]), l["end"], s[:from], s[:to])
end
end
inside.reject { |l| l["vo"] }.each do |l|
- next if l["at"] >= s[:from] && l["end"] <= s[:to]
- issues << format("%s: on-screen line %s crosses a cut (%.2f–%.2f s); move the cut or the line", s[:name], l["name"], l["at"], l["end"])
+ next if l.fetch("speech_at", l["at"]) >= s[:from] && l["end"] <= s[:to]
+ issues << format("%s: on-screen line %s crosses a cut (%.2f–%.2f s); move the cut or the line", s[:name], l["name"], l.fetch("speech_at", l["at"]), l["end"])
end
need = s[:audio] ? ((inside.map { |l| l["end"] }.max || s[:from]) - s[:from] + 0.25) * FPS : nil
{ shot: s[:name], frames: s[:frames], seconds: format("%.2f–%.2f", s[:from], s[:to]), kind: s[:kind], audio: s[:audio],
- lines: inside.map { |l| format("%s%s %.2f–%.2f", l["name"], l["vo"] ? " (VO)" : "", l["at"], l["end"]) },
+ lines: inside.map { |l| format("%s%s %.2f–%.2f", l["name"], l["vo"] ? " (VO)" : "", l.fetch("speech_at", l["at"]), l["end"]) },
min_frames_for_lines: need&.ceil }
end
{ run: project.name, frames: shots.sum { _1[:frames] }, shots: rows, issues: issues.uniq, ok: issues.empty? }
diff --git a/skills/make-an-anime/scripts/lib/toolkit/mcp_server.rb b/skills/make-an-anime/scripts/lib/toolkit/mcp_server.rb
index 260d3e6..ab0c2a2 100644
--- a/skills/make-an-anime/scripts/lib/toolkit/mcp_server.rb
+++ b/skills/make-an-anime/scripts/lib/toolkit/mcp_server.rb
@@ -154,7 +154,7 @@ module Toolkit
when "initialize"
requested = params["protocolVersion"]
{ protocolVersion: PROTOCOLS.include?(requested) ? requested : PROTOCOLS.first,
- capabilities: { tools: {} }, serverInfo: { name: "anime", version: "0.4.0" } }
+ capabilities: { tools: {} }, serverInfo: { name: "anime", version: "0.5.0" } }
when "ping" then {}
when "tools/list" then { tools: TOOLS }
when "tools/call" then call_tool(params)
diff --git a/skills/make-an-anime/scripts/lib/toolkit/operations.rb b/skills/make-an-anime/scripts/lib/toolkit/operations.rb
index 244ff00..a6b6da0 100644
--- a/skills/make-an-anime/scripts/lib/toolkit/operations.rb
+++ b/skills/make-an-anime/scripts/lib/toolkit/operations.rb
@@ -1,3 +1,5 @@
+require_relative "../media/vfx_bake"
+require_relative "../media/game_assets"
require_relative "../workflow/approval"
require_relative "../workflow/waves"
require_relative "../workflow/journal"
@@ -59,6 +61,9 @@ module Toolkit
"media:twitter" => "1080p delivery [video,out.mp4] (local encode only)",
"media:upload" => "Upload [path] to Fal CDN",
"ref:import" => "Reuse existing hosted identity [new_run,local_image,original_manifest.json] (no upload)",
+ "vfx:bake" => "Bake a scene light pass without stacking it: [run] (local)",
+ "game:cut" => "Cut generated game sheets using a JSON recipe: [recipe.json] (local)",
+ "game:faces" => "Build or cut a face-icon collage using a JSON recipe: [recipe.json] (local)",
"vfx:build" => "Build Swift Core Image renderer (macOS)",
"vfx:analyze" => "Analyze VFX source beats and cuts; VFX=name",
"vfx:stills" => "Preview cued VFX frames [0,24,...]; VFX=name",
@@ -82,6 +87,9 @@ module Toolkit
end
def call(name, a)
case name
+ when "vfx:bake" then required(a, 1); emit Media::VfxBake.new(a[0]).bake
+ when "game:cut" then required(a, 1); emit Media::GameAssets.new.cut(a[0])
+ when "game:faces" then required(a, 1); emit Media::GameAssets.new.faces(a[0])
when "doctor" then doctor
when "setup" then setup
when "fonts:list" then emit Fonts.new.list
diff --git a/skills/make-an-anime/scripts/spec/graphics_tools_spec.rb b/skills/make-an-anime/scripts/spec/graphics_tools_spec.rb
new file mode 100644
index 0000000..bffad6a
--- /dev/null
+++ b/skills/make-an-anime/scripts/spec/graphics_tools_spec.rb
@@ -0,0 +1,139 @@
+require_relative "spec_helper"
+
+RSpec.describe "Deterministic graphics and asset tools", :media do
+ it "renders particle frames identically alone, out of order and in sequence, with a separate light layer" do
+ renderer = Media::Anim.new
+ sketch = File.join(RT, "tools/p5/examples/particles.js")
+ args = { width: 320, height: 180, fps: 24, frames: 18 }
+ renderer.render(sketch, file("sequence"), **args)
+ renderer.render(sketch, file("isolated"), **args, only: [17, 12, 0])
+ [0, 12, 17].each do |frame|
+ name = format("%04d.png", frame)
+ expect(pixels(file("isolated/#{name}"))).to eq(pixels(file("sequence/#{name}")))
+ end
+ expect(pixels(file("sequence/0000.png"))).not_to eq(pixels(file("sequence/0012.png")))
+ json(file("cues.json"), cues: [])
+ renderer.render(sketch, file("lights"), **args, only: [12], data: { vfx: file("cues.json") })
+ alpha = pixels(file("lights/0012.png")).map(&:last)
+ expect(alpha.min).to eq(0)
+ expect(alpha.max).to be > 0
+ end
+
+ it "cuts game sprites through the Ruby recipe task and refuses mismatched names" do
+ sheet = file("sheet.png")
+ magick.run("magick", "-size", "200x100", "xc:none", "-fill", "red", "-draw", "rectangle 10,10 70,80", "-fill", "blue", "-draw", "rectangle 120,10 180,80", sheet)
+ json(file("cut.json"), mode: "sprites", source: sheet, out: file("units"), names: %w[red blue])
+ out, err, status = cli("game:cut[#{file('cut.json')}]")
+ expect(status.success?).to be(true), err
+ expect(JSON.parse(out)["sprites"].keys).to eq(%w[red blue])
+ expect(pixels(file("units/red.png"))).to include([255, 0, 0, 255])
+ json(file("bad.json"), mode: "sprites", source: sheet, out: file("bad"), names: %w[red])
+ _, err, status = cli("game:cut[#{file('bad.json')}]")
+ expect(status.success?).to be(false)
+ expect(err).to include("found 2 sprites, expected 1")
+ expect(Dir[File.join(file("bad"), "*.png")]).to be_empty
+ end
+
+ it "renders the RTS example and mission/court helpers using local fixture art" do
+ assets = file("game-art"); FileUtils.mkdir_p(File.join(assets, "units")); FileUtils.mkdir_p(File.join(assets, "icons"))
+ magick.run("magick", "-size", "960x540", "gradient:#203040-#607050", File.join(assets, "map.jpg"))
+ magick.run("magick", "-size", "960x540", "xc:none", "-fill", "#304050", "-draw", "rectangle 0,400 959,539", File.join(assets, "console.png"))
+ magick.run("magick", "-size", "100x100", "xc:#708090", File.join(assets, "portrait.png"))
+ magick.run("magick", "-size", "40x60", "xc:#3090ff", File.join(assets, "units/trooper.png"))
+ json(File.join(assets, "console_slots.json"), w: 960, h: 540, top: 400, slots: [[20, 420, 100, 100], [140, 420, 100, 100], [260, 420, 280, 100], [560, 420, 50, 100], [650, 430, 20, 20], [680, 430, 20, 20], [710, 430, 20, 20], [740, 430, 20, 20]])
+ json(file("game.json"), dir: "/" + assets.delete_prefix("#{RT}/"), units: ["trooper"], icons: [])
+ renderer = Media::Anim.new
+ renderer.render(File.join(RT, "tools/p5/examples/game-screen.js"), file("game"), width: 960, height: 540, fps: 24, frames: 12, only: [0, 10], data: { game: file("game.json") })
+ expect(pixels(file("game/0000.png"))).not_to eq(pixels(file("game/0010.png")))
+ File.write(file("court.js"), <<~JS)
+ Anim.sketch({
+ async load(){this.R=await Anim.rts.load(Anim.data('game'));this.R.bezel={box:[0,400,120,120],inset:[8,8,8,8],corner:16}},
+ draw(t){
+ background('#102030'); const box={x:80,y:80,w:560,h:300};
+ Anim.mission.begin(this.R,box,{s:1});
+ Anim.mission.floor(box,{seed:'fixture',tile:40});
+ Anim.court.lines(Anim.court.full(box));
+ Anim.court.ball(t,300,230,{dribble:true});
+ Anim.mission.end(this.R,box,{s:1,logo:false});
+ }
+ });
+ JS
+ renderer.render(file("court.js"), file("court"), width: 720, height: 480, fps: 24, frames: 6, only: [0, 5], data: { game: file("game.json") })
+ expect(pixels(file("court/0000.png"))).not_to eq(pixels(file("court/0005.png")))
+ end
+
+ it "cuts icon grids, detects HUD holes and fits art through the recipe service" do
+ sheet = file("icons.png")
+ magick.run("magick", "-size", "200x100", "xc:black", "-fill", "red", "-draw", "rectangle 10,10 70,80", "-fill", "blue", "-draw", "rectangle 120,10 180,80", sheet)
+ service = Media::GameAssets.new
+ json(file("grid.json"), mode: "grid", source: sheet, out: file("icons"), names: %w[attack move], size: 64)
+ expect(service.cut(file("grid.json"))["tiles"].keys).to eq(%w[attack move])
+ magick.run("magick", "-size", "240x120", "xc:#808080", "-fill", "black", "-draw", "rectangle 20,20 100,100", file("console.png"))
+ json(file("frame.json"), mode: "frame", source: file("console.png"), out: file("cut-console.png"), slots: file("slots.json"), scale: 1, min_area: 100)
+ expect(service.cut(file("frame.json"))["slots"]).to eq(1)
+ expect(pixels(file("cut-console.png"))[60 * 240 + 60].last).to eq(0)
+ json(file("fit.json"), mode: "fit", source: sheet, out: file("map.jpg"), width: 100)
+ expect(service.cut(file("fit.json"))["size"]).to eq([100, 50])
+ end
+
+ it "builds and cuts a face collage and refuses ambiguous automatic assignment" do
+ red, blue = file("red.png"), file("blue.png")
+ magick.run("magick", "-size", "80x80", "xc:red", red)
+ magick.run("magick", "-size", "80x80", "xc:blue", blue)
+ spec = { cols: 2, rows: 1, cell: [80, 80], gap: 30, margin: 20, faces: [
+ { name: "pilot", sheet: red, box: [40, 40, 70] }, { name: "rival", sheet: blue, box: [40, 40, 70] }
+ ] }
+ json(file("faces.json"), spec)
+ json(file("build.json"), mode: "build", spec: file("faces.json"), out: file("collage.png"))
+ service = Media::GameAssets.new
+ expect(service.faces(file("build.json"))["cells"]).to eq(2)
+ json(file("split.json"), mode: "cut", spec: file("faces.json"), source: file("collage.png"), out: file("faces"), size: 64)
+ expect(service.faces(file("split.json"))["icons"].keys).to eq(%w[pilot rival])
+ expect(pixels(file("faces/pilot.png"))).to include([255, 0, 0, 255])
+ spec[:faces].pop
+ json(file("faces.json"), spec)
+ expect { service.faces(file("split.json")) }.to raise_error(Media::CommandError, /found 2 icons, expected 1/)
+ end
+end
+
+RSpec.describe "Baked light pass", :swift do
+ it "blooms only light pixels and reuses the plain picture on repeats and audio remixes" do
+ run = "e2e-bake-#{Process.pid}"
+ dir = File.join(RT, "output", run)
+ FileUtils.mkdir_p(dir)
+ final = File.join(dir, "final_overlay.mp4")
+ plain = File.join(dir, "final_overlay_plain.mp4")
+ ff.still_video(file("black.mp4"), frames: 24, fps: 24, color: "#101010", w: 320, h: 180)
+ ff.mux(file("black.mp4"), tone(file("tone.wav")), final, shortest: true)
+ prompts = File.join(RT, "prompts", "#{run}-vfx"); FileUtils.mkdir_p(prompts)
+ File.write(file("light.js"), "Anim.sketch({draw(){clear();noStroke();fill('#ffffff');rect(150,80,8,8)}})")
+ cfg = { source: "output/#{run}/final_overlay_plain.mp4", out: "output/#{run}/final_overlay.mp4",
+ lights: file("light.js").delete_prefix("#{RT}/"), cues: [{ fx: "halo", f: 6, dur: 12, shape: "span", fade: 1, amt: 1.0, radius: 9 }] }
+ File.write(File.join(prompts, "cues.yml"), YAML.dump(JSON.parse(JSON.generate(cfg))))
+ bake = Media::VfxBake.new(run)
+ expect(bake.bake[:reused_plain]).to be(false)
+ expect(ff.summary(final).dig(:video, :frames)).to eq(24)
+ expect(ff.summary(final).dig(:audio, :codec)).to eq("aac")
+ first = bake.send(:video_hash, final)
+ ff.frame_index(final, 10, file("glow.png"))
+ ff.frame_index(plain, 10, file("plain.png"))
+ # A region outside the 8px source light brightens; a far corner is preserved.
+ crop_luma = ->(path, box) { magick.run("magick", path, "-crop", box, "-colorspace", "gray", "-format", "%[fx:mean]", "info:", quiet: true).to_f }
+ expect(crop_luma.call(file("glow.png"), "12x12+135+77")).to be > crop_luma.call(file("plain.png"), "12x12+135+77") + 0.01
+ expect(crop_luma.call(file("glow.png"), "20x20+0+0")).to be_within(0.02).of(crop_luma.call(file("plain.png"), "20x20+0+0"))
+ expect(bake.bake[:reused_plain]).to be(true)
+ expect(bake.send(:video_hash, final)).to eq(first)
+ # Remux only audio, then bake again: the video must remain unchanged.
+ ff.run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "sine=frequency=300:duration=1", file("new.wav"))
+ ff.mux(final, file("new.wav"), file("remix.mp4"), shortest: false)
+ FileUtils.cp(file("remix.mp4"), final)
+ expect(bake.bake[:reused_plain]).to be(true)
+ expect(bake.send(:video_hash, final)).to eq(first)
+ # An invalid cue leaves the delivered overlay intact.
+ cfg[:cues][0][:fx] = "unknown"
+ File.write(File.join(prompts, "cues.yml"), YAML.dump(JSON.parse(JSON.generate(cfg))))
+ before = Digest::SHA256.file(final).hexdigest
+ expect { bake.bake }.to raise_error(ArgumentError, /unknown fx/)
+ expect(Digest::SHA256.file(final).hexdigest).to eq(before)
+ end
+end
diff --git a/skills/make-an-anime/scripts/spec/production_fixes_spec.rb b/skills/make-an-anime/scripts/spec/production_fixes_spec.rb
new file mode 100644
index 0000000..2d3b2fa
--- /dev/null
+++ b/skills/make-an-anime/scripts/spec/production_fixes_spec.rb
@@ -0,0 +1,129 @@
+require_relative "spec_helper"
+
+RSpec.describe "Production fixes", :core do
+ it "budgets skipped frames into H3 duration" do
+ shots = Pipeline::Steps::Shots.new
+ expect(shots.send(:default_seconds, { "frames" => 72, "skip_frames" => 2 })).to eq(3.1)
+ expect(shots.send(:default_seconds, { "frames" => 24, "audio" => "pilot" })).to eq(2.0)
+ end
+
+ it "refuses a short source before assembling a truncated plate" do
+ shots = Pipeline::Steps::Shots.new
+ ffmpeg = double
+ allow(shots).to receive(:ffmpeg).and_return(ffmpeg)
+ allow(shots).to receive(:specs).and_return("run" => { "frames" => 72, "skip_frames" => 2 })
+ allow(ffmpeg).to receive(:summary).and_return(video: { frames: 73 })
+ expect(ffmpeg).not_to receive(:concat_shots)
+ expect { shots.send(:finish, "run" => { "path" => "take.mp4" }) }.to raise_error(ArgumentError, /run: source has 73 frames; needs 74/)
+ end
+
+ it "does not mistake running water for a runner, but still catches a person running near it" do
+ rules = Pipeline::Believability
+ expect(rules.shot_problems("sink", { "prompt" => "Water is running from the tap.", "camera" => "locked" })).to be_empty
+ expect(rules.shot_problems("sink", { "prompt" => "He watches the running water.", "camera" => "locked" })).to be_empty
+ expect(rules.shot_problems("chase", { "prompt" => "Water is running. She runs past the sink.", "camera" => "locked" })).not_to be_empty
+ end
+
+ it "reports gated speech at its audible start and keeps legacy line timing" do
+ with_workspace do |dir|
+ stub_const("Pipeline::ROOT", dir)
+ stub_const("Pipeline::GENERATIONS", "gated" => { frames: 48, steps: [Pipeline::Steps::Shots] })
+ project = Pipeline::Project.new("gated")
+ FileUtils.mkdir_p("prompts/gated")
+ File.write("prompts/gated/04_shots.yml", YAML.dump([
+ { "name" => "pause", "color" => "#000000", "frames" => 24 },
+ { "name" => "line", "image" => "pilot", "frames" => 24, "audio" => "pilot" }
+ ]))
+ json(project.path("03_dialogue_lines.json"), [{ name: "hello", character: "pilot", at: 0.8, speech_at: 1.1, end: 1.8 }])
+ result = Toolkit::AnimeReview.new(project).timeline
+ expect(result[:ok]).to be(true)
+ expect(result[:shots][0][:lines]).to be_empty
+ expect(result[:shots][1][:lines]).to eq(["hello 1.10–1.80"])
+ json(project.path("03_dialogue_lines.json"), [{ name: "hello", character: "pilot", at: 0.8, end: 1.8 }])
+ expect(Toolkit::AnimeReview.new(project).timeline[:issues].join).to include("crosses a cut")
+ end
+ end
+end
+
+RSpec.describe "Local take and mix reuse", :media do
+ it "copies an existing take without Fal, catches short trims, and refreshes a replaced source" do
+ with_workspace do |dir|
+ stub_const("Pipeline::ROOT", dir)
+ stub_const("Pipeline::GENERATIONS", "dest" => { frames: 12, steps: [Pipeline::Steps::Shots] })
+ source = Pipeline::Project.new("source")
+ movie = video(file("original.mp4"))
+ source.record(:shots, items: { saved: { path: movie } })
+ dest = Pipeline::Project.new("dest")
+ dest.record(:music, path: tone(file("bed.wav")))
+ FileUtils.mkdir_p("prompts/dest")
+ spec = { "name" => "replay", "from_take" => "source/saved", "frames" => 12, "skip_frames" => 6 }
+ File.write("prompts/dest/04_shots.yml", YAML.dump([spec]))
+ step = Pipeline::Steps::Shots.new(project: dest)
+ expect(Fal::Client).not_to receive(:new)
+ step.run!
+ item = dest[:shots]["items"]["replay"]
+ expect(item).to include("adopted" => true, "from_take" => "source/saved")
+ expect(File.binread(item["path"])).to eq(File.binread(movie))
+ expect(ff.summary(dest[:shots]["path"]).dig(:video, :frames)).to eq(12)
+ expect(step.stale_item?("replay", spec, item)).to be(false)
+ ff.still_video(movie, frames: 24, fps: 24, color: "#0000ff")
+ expect(step.stale_item?("replay", spec, item)).to be(true)
+ step.run!
+ expect(File.binread(dest[:shots]["items"]["replay"]["path"])).to eq(File.binread(movie))
+ expect { step.send(:generate, "bad", spec.merge("skip_frames" => 20)) }.to raise_error(ArgumentError, /needs 32/)
+ expect { step.send(:generate, "bad", spec.merge("from_take" => "../saved")) }.to raise_error(ArgumentError, /from_take must/)
+ end
+ end
+
+ it "remixes changed settings or same-mtime source bytes and refuses a stale soundtrack" do
+ with_workspace do |dir|
+ stub_const("Pipeline::ROOT", dir)
+ stub_const("Pipeline::GENERATIONS", "mix" => { frames: 48, steps: [Pipeline::Steps::Mix] })
+ project = Pipeline::Project.new("mix")
+ source = tone(file("score.wav"))
+ project.record(:music, path: source)
+ step = Pipeline::Steps::Mix.new(project: project)
+ step.run!
+ expect(project[:mix]["input"]["music_db"]).to eq(-12)
+ first = Digest::SHA256.file(project[:mix]["path"]).hexdigest
+ Pipeline::GENERATIONS["mix"][:mix] = { music_db: -6 }
+ expect { project.soundtrack }.to raise_error(/mix missing or stale/)
+ step.run!
+ expect(Digest::SHA256.file(project.soundtrack).hexdigest).not_to eq(first)
+ mtime = File.mtime(source)
+ ff.run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "sine=frequency=300:duration=2", "-ac", "2", source)
+ File.utime(mtime, mtime, source)
+ expect(step.done?).to be(false)
+ step.run!
+ expect(step.done?).to be(true)
+ project.record(:dialogue, path: tone(file("voice.wav")))
+ expect { project.soundtrack }.to raise_error(/run gen:mix/)
+ end
+ end
+
+ it "drops the requested prefix before retiming with or without an explicit source length" do
+ ff.still_video(file("red.mp4"), frames: 12, fps: 24, color: "#ff0000", w: 64, h: 64)
+ ff.still_video(file("blue.mp4"), frames: 12, fps: 24, color: "#0000ff", w: 64, h: 64)
+ ff.concat_shots([{ path: file("red.mp4"), frames: 12 }, { path: file("blue.mp4"), frames: 12 }], file("take.mp4"), fps: 24)
+ [nil, 12].each_with_index do |keep, i|
+ out = file("retimed-#{i}.mp4")
+ ff.concat_shots([{ path: file("take.mp4"), skip: 12, keep: keep, retime: true, frames: 24 }], out, fps: 24)
+ expect(ff.summary(out).dig(:video, :frames)).to eq(24)
+ ff.frame_index(out, 0, file("first-#{i}.png"))
+ red, _, blue = pixels(file("first-#{i}.png")).first
+ expect(blue).to be > red + 100
+ end
+ end
+
+ it "muffles a voice locally without changing its duration or source" do
+ source = file("bright.wav")
+ ff.run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "sine=frequency=5000:duration=1", "-ac", "2", source)
+ before = Digest::SHA256.file(source).hexdigest
+ dry = ff.place_audio([{ "path" => source, "at" => 0 }], file("dry.wav"), seconds: 1)
+ wet = ff.place_audio([{ "path" => source, "at" => 0, "muffled" => true }], file("wet.wav"), seconds: 1)
+ rms = ->(path) { py.audio_energy(path)["windows"].map { |w| w["rms_db"] }.max }
+ expect(rms.call(wet)).to be < rms.call(dry) - 15
+ expect(ff.duration(wet)).to be_within(0.01).of(1)
+ expect(Digest::SHA256.file(source).hexdigest).to eq(before)
+ end
+end
diff --git a/skills/make-an-anime/scripts/tools/p5/examples/game-screen.js b/skills/make-an-anime/scripts/tools/p5/examples/game-screen.js
new file mode 100644
index 0000000..7d6c25e
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/p5/examples/game-screen.js
@@ -0,0 +1,25 @@
+// Supply --data game=recipe.json where recipe has {dir, units:[...], icons:[...]}.
+// Art is produced with the game-screens guide; no generated media is bundled.
+Anim.sketch({
+ async load() {
+ const config = Anim.data('game');
+ this.art = await Anim.rts.load(config);
+ const kind = config.units[0];
+ this.game = {
+ title: 'Orbital Command', logo: { text: 'ORBITAL', sub: 'COMMAND' },
+ fonts: { ui: 'sans-serif', uiBold: 'sans-serif', logo: 'sans-serif' },
+ map: { scale: 1, cam: t => [20 * t, 0] },
+ kinds: { [kind]: { w: 70 } },
+ units: [{ id: 'scout', kind, team: 'blue', at: t => [400 + 45 * t, 300] }],
+ selected: () => true,
+ events: [{ type: 'laser', id: 'shot', at: 0.3, dur: 0.3, from: [430, 265], to: [680, 250] }],
+ timer: t => `00:${String(Math.floor(t)).padStart(2, '0')}`,
+ resources: () => [{ icon: 'crystal', text: '120' }],
+ commands: config.icons || [], gauge: () => 0.7,
+ cursor: t => ({ x: 650 + 20 * t, y: 300, mode: 'target' })
+ };
+ },
+ draw(t, frame) {
+ Anim.rts.screen(t, this.art, this.game, { frame, mode: ANIM.data.vfx !== undefined ? 'light' : 'color' });
+ }
+});
diff --git a/skills/make-an-anime/scripts/tools/p5/examples/particles.js b/skills/make-an-anime/scripts/tools/p5/examples/particles.js
new file mode 100644
index 0000000..c00a85b
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/p5/examples/particles.js
@@ -0,0 +1,14 @@
+// Render through anim:render. The same sketch supplies its own VFX light layer.
+Anim.sketch({
+ draw(t) {
+ const light = ANIM.data.vfx !== undefined;
+ if (!light) background('#102030');
+ const events = [
+ { type: 'laser', id: 'beam', at: 0.1, dur: 0.5, from: [40, 130], to: [230, 80] },
+ { type: 'explosion', id: 'hit', at: 0.4, x: 230, y: 80, size: 0.45 },
+ { type: 'sparks', id: 'sparks', at: 0.4, x: 230, y: 80, count: 12, speed: [30, 100], gravity: 70 },
+ { type: 'scorch', id: 'mark', at: 0.4, x: 230, y: 80, radius: 15 }
+ ];
+ Anim.particles.draw(events, t, { mode: light ? 'light' : 'color' });
+ }
+});
diff --git a/skills/make-an-anime/scripts/tools/p5/lib/court.js b/skills/make-an-anime/scripts/tools/p5/lib/court.js
new file mode 100644
index 0000000..87915b4
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/p5/lib/court.js
@@ -0,0 +1,244 @@
+// Basketball courts as Orbital Command maps: a half court (the drills) and a full court (the match), with glowing
+// lines on steel deck plates, a dribbled ball, a pass, the sprite-to-face-icon swap, and the "fill the spaces" drill.
+// Needs mission.js (frame, floor, units, icons, fog), rts.js and particles.js.
+//
+// const C = Anim.court;
+// const geo = C.half(box); // 15 m across, 14 m deep, the basket at the top: geo.px(u), geo.py(v), geo.m
+// const geo = C.full(box); // 28 m long, 15 m across, baskets left and right: geo.px(x), geo.py(y)
+// C.lines(geo); // the painted lines, glowing
+// C.fromHalf([u, v]) // a half-court spot (attacking the right basket) on the full court
+// C.ball(t, x, y, { dribble }) // the ball at a hand, bouncing when dribbled
+// C.drill(R, f, local, cfg) // the whole "fill the spaces" view (see below)
+//
+// Everything is a pure function of t, as in particles.js: the drill's crawler is re-simulated from 0 each frame.
+window.Anim = window.Anim || {};
+
+(() => {
+ const C = {};
+ const M = () => Anim.mission;
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
+ const TAU = Math.PI * 2;
+ const LINE = "rgba(90,190,255,0.9)";
+
+ C.half = (box) => { const m = box.h / 14; return { kind: "half", box, m, px: (u) => box.x + u * m, py: (v) => box.y + v * m }; };
+ C.full = (box) => { const m = box.w / 28; return { kind: "full", box, m, px: (x) => box.x + x * m, py: (y) => box.y + y * m }; };
+ // A spot of the half court (u across, v out from the baseline) on the full court, attacking the right-hand basket.
+ C.fromHalf = ([u, v]) => [28 - v, u];
+
+ C.lines = (geo, { color = LINE, width: lw = 4 } = {}) => {
+ const { px, py, m } = geo, G = (d) => M().glowStroke(d, { color, width: lw, blur: 12, core: "rgba(230,248,255,0.9)" });
+ if (geo.kind === "half") {
+ // the same lines the drills always had: side lines, the key, the arc, the basket
+ G((c) => c.rect(px(0), py(0), 15 * m, 14 * m));
+ G((c) => c.rect(px(5.05), py(0), 4.9 * m, 5.8 * m));
+ G((c) => c.arc(px(7.5), py(1.575), 6.25 * m, 0, Math.PI));
+ G((c) => { c.moveTo(px(7.5) + 0.225 * m, py(1.575)); c.arc(px(7.5), py(1.575), 0.225 * m, 0, TAU); });
+ G((c) => { c.moveTo(px(6.6), py(1.2)); c.lineTo(px(8.4), py(1.2)); });
+ return;
+ }
+ G((c) => c.rect(px(0), py(0), 28 * m, 15 * m));
+ G((c) => { c.moveTo(px(14), py(0)); c.lineTo(px(14), py(15)); });
+ G((c) => { c.moveTo(px(14) + 1.8 * m, py(7.5)); c.arc(px(14), py(7.5), 1.8 * m, 0, TAU); });
+ for (const side of [0, 1]) {
+ const X = (x) => px(side ? 28 - x : x), dir = side ? -1 : 1;
+ G((c) => c.rect(Math.min(X(0), X(5.8)), py(5.05), 5.8 * m, 4.9 * m));
+ G((c) => { c.moveTo(X(5.8) + dir * 1.8 * m, py(7.5)); c.arc(X(5.8), py(7.5), 1.8 * m, side ? Math.PI : 0, side ? 3 * Math.PI : TAU); });
+ // the three-point line: straight in the corners, then the arc (6.75 m from the basket); a is the arc's half-angle
+ const a = Math.asin(6.6 / 6.75), hx = X(1.575);
+ G((c) => {
+ c.moveTo(X(0), py(0.9)); c.lineTo(X(2.99), py(0.9));
+ if (side) c.arc(hx, py(7.5), 6.75 * m, -Math.PI + a, Math.PI - a, true);
+ else c.arc(hx, py(7.5), 6.75 * m, -a, a, false);
+ c.lineTo(X(0), py(14.1));
+ });
+ G((c) => { c.moveTo(hx + 0.225 * m, py(7.5)); c.arc(hx, py(7.5), 0.225 * m, 0, TAU); });
+ G((c) => { c.moveTo(X(1.2), py(6.6)); c.lineTo(X(1.2), py(8.4)); });
+ }
+ };
+
+ // The ball: orange, with seams, a shadow, and a hot rim light. dribble: bounces from the hand (h px above the floor)
+ // to the floor, `hz` bounces a second.
+ C.ball = (t, x, y, { r = 13, dribble = false, hz = 2.6, h = 46, glow = true } = {}) => {
+ const g = drawingContext;
+ const lift = dribble ? h * (1 - Math.abs(Math.cos(Math.PI * hz * t))) ** 0.8 : 0;
+ const squash = dribble && lift < 4 ? 0.82 : 1;
+ g.save();
+ g.fillStyle = `rgba(0,0,0,${0.45 - 0.25 * lift / Math.max(1, h)})`;
+ g.beginPath(); g.ellipse(x, y + r * 0.6, r * (1.05 - 0.3 * lift / Math.max(1, h)), r * 0.35, 0, 0, TAU); g.fill();
+ g.translate(x, y - lift); g.scale(1 / squash ** 0.5, squash);
+ if (glow) { g.shadowColor = "rgba(255,140,40,0.9)"; g.shadowBlur = 14; }
+ const gr = g.createRadialGradient(-r * 0.35, -r * 0.4, r * 0.1, 0, 0, r);
+ gr.addColorStop(0, "#ffb15a"); gr.addColorStop(1, "#d0561a");
+ g.fillStyle = gr; g.beginPath(); g.arc(0, 0, r, 0, TAU); g.fill();
+ g.shadowBlur = 0; g.strokeStyle = "rgba(40,14,0,0.75)"; g.lineWidth = 1.6;
+ g.beginPath(); g.moveTo(-r, 0); g.lineTo(r, 0); g.moveTo(0, -r); g.lineTo(0, r); g.stroke();
+ g.restore();
+ };
+
+ // A pass from a to b over `dur` s from `at`: the ball's position, with a little loft, or null outside it.
+ C.pass = (t, at, dur, a, b, loft = 30) => {
+ const q = (t - at) / dur;
+ if (q < 0 || q > 1) return null;
+ const e = q * q * (3 - 2 * q);
+ return [a[0] + (b[0] - a[0]) * e, a[1] + (b[1] - a[1]) * e - loft * Math.sin(Math.PI * q)];
+ };
+
+ // Formation steps: dots run from one formation to the next at k * step, taking `move` s, then hold.
+ C.steps = (forms, t, { step, move, lag = 0 }) => {
+ const tt = Math.max(0, t - lag);
+ const k = Math.min(Math.floor(tt / step), forms.length - 1);
+ const p = k === 0 ? 0 : Anim.ease.inOutCubic(clamp01((tt - k * step) / move));
+ const prev = forms[Math.max(k - 1, 0)], next = forms[k];
+ return { k, p, dots: next.map((d, i) => [prev[i][0] + (d[0] - prev[i][0]) * p, prev[i][1] + (d[1] - prev[i][1]) * p]),
+ moving: next.map((d, i) => p > 0 && p < 1 && Math.hypot(d[0] - prev[i][0], d[1] - prev[i][1]) > 0.05),
+ dir: next.map((d, i) => Math.sign(d[0] - prev[i][0]) || 1) };
+ };
+
+ // A side panel of face icons: the squad, a lost one greyed and crossed. faces: [{img, name, lost}].
+ C.squadPanel = (R, f, x, y, w, h, faces, { title = "SQUAD", s = 1.2, t = 0, extra } = {}) => {
+ const g = drawingContext;
+ g.save(); g.fillStyle = "#05080c"; g.fillRect(x, y, w, h); g.restore();
+ const alive = faces.filter((q) => !q.lost).length;
+ Anim.rts.ui.styledText(`${title} ${alive}/${faces.length}`, x + w / 2, y + 34, { font: f.logo, size: 24, style: "#cfe8ff", glow: "rgba(60,160,255,0.8)", blur: 8 });
+ const cols = 2, cw = w / cols, sz = Math.min(cw - 40, 104), rh = sz + 26;
+ faces.forEach((q, i) => {
+ const cx = x + cw * (i % cols) + cw / 2, cy = y + 76 + sz / 2 + Math.floor(i / cols) * rh;
+ g.save(); g.globalAlpha = q.lost ? 0.35 : 1; g.filter = q.lost ? "grayscale(1)" : "none";
+ g.drawImage(q.img.canvas || q.img.elt || q.img, cx - sz / 2, cy - sz / 2, sz, sz);
+ g.restore();
+ if (q.lost) {
+ g.save(); g.strokeStyle = "rgba(255,60,40,0.95)"; g.lineWidth = 6; g.shadowColor = "rgba(255,40,20,1)"; g.shadowBlur = 10;
+ const d = sz * 0.3; g.beginPath(); g.moveTo(cx - d, cy - d); g.lineTo(cx + d, cy + d); g.moveTo(cx + d, cy - d); g.lineTo(cx - d, cy + d); g.stroke(); g.restore();
+ }
+ Anim.rts.ui.hpBar(cx, cy + sz / 2 + 8, sz * 0.8, q.lost ? 0 : 1, [60, 230, 80]);
+ });
+ if (extra) extra(x, y + h - 70, w);
+ M().bezel(R, { x, y, w, h }, { s });
+ };
+
+ // ---- the drill: "fill the spaces" ------------------------------------------------------------------------------
+ // cfg: { forms (4 formations of 8 [u, v]), step, move, faces (8 names, the squad), crawlerFrom [u, v], speed (m/s),
+ // chalk (v of the chalk line, optional), ball ([u, v], optional), line (the mission line), title }
+ // One red crawler hunts the nearest trooper. Bunched, they are easy; spread, it has to run and the one it chases steps
+ // away, so it runs further and cannot get them all. Its metres run are counted on the panel.
+ const simCache = {};
+ C.drillSim = (cfg, t) => {
+ const key = JSON.stringify([cfg.forms, cfg.step, cfg.move, cfg.crawlerFrom, cfg.speed]);
+ let sim = simCache[key];
+ if (!sim) {
+ const dt = 1 / 96, T = 8;
+ const n = cfg.forms[0].length, off = Array.from({ length: n }, () => [0, 0]);
+ let c = [...cfg.crawlerFrom], run = 0, pause = 0, target = -1;
+ const lost = [], frames = [];
+ for (let s = 0, tt = 0; tt <= T; s++, tt = s * dt) {
+ const base = C.steps(cfg.forms, tt, cfg).dots, spread = tt >= cfg.step;
+ const pos = base.map((b, i) => [b[0] + off[i][0], b[1] + off[i][1]]);
+ const aliveIdx = pos.map((_, i) => i).filter((i) => !lost.some((q) => q.i === i));
+ // the nearest one is the target
+ let best = -1, bd = Infinity;
+ for (const i of aliveIdx) { const d = Math.hypot(pos[i][0] - c[0], pos[i][1] - c[1]); if (d < bd) { bd = d; best = i; } }
+ target = best;
+ if (pause > 0) pause -= dt;
+ else if (best >= 0) {
+ const [dx, dy] = [pos[best][0] - c[0], pos[best][1] - c[1]], d = Math.hypot(dx, dy);
+ if (d < 0.55) { lost.push({ i: best, at: tt, x: pos[best][0], y: pos[best][1] }); pause = 0.45; }
+ else { const v = Math.min(cfg.speed * dt, d); c = [c[0] + dx / d * v, c[1] + dy / d * v]; run += v; }
+ }
+ // spread out, the one it closes on steps away from it (inside the half); the others drift back to their space
+ for (const i of aliveIdx) {
+ const [dx, dy] = [pos[i][0] - c[0], pos[i][1] - c[1]], d = Math.hypot(dx, dy) || 1;
+ if (spread && i === target && d < 2.2) {
+ const v = cfg.speed * 0.92 * dt;
+ off[i][0] += dx / d * v; off[i][1] += dy / d * v;
+ off[i][0] = Math.max(0.6 - base[i][0], Math.min(14.4 - base[i][0], off[i][0]));
+ off[i][1] = Math.max(0.6 - base[i][1], Math.min(13.4 - base[i][1], off[i][1]));
+ } else { off[i][0] *= 0.985; off[i][1] *= 0.985; }
+ }
+ frames.push({ c: [...c], run, target, off: off.map((o) => [...o]), lost: lost.length });
+ }
+ sim = simCache[key] = { dt, frames, lost };
+ }
+ const fr = sim.frames[Math.min(sim.frames.length - 1, Math.max(0, Math.round(t / sim.dt)))];
+ return { ...fr, lostList: sim.lost.slice(0, fr.lost) };
+ };
+
+ C.drill = (R, f, local, cfg) => {
+ const box = cfg.box || { x: 300, y: 170, w: 750, h: 700 };
+ const s = 1.4;
+ M().begin(R, box, { s });
+ const geo = C.half(box), { px, py, m } = geo;
+ M().floor(box, { seed: "court", tile: 50, tint: [36, 44, 54], light: 1.2 });
+ // the half's paint, a shade lighter in the key
+ drawingContext.save(); drawingContext.fillStyle = "rgba(70,150,255,0.10)"; drawingContext.fillRect(px(5.05), py(0), 4.9 * m, 5.8 * m); drawingContext.restore();
+ C.lines(geo);
+ if (cfg.chalk != null) M().glowStroke((c) => { c.moveTo(px(0), py(cfg.chalk)); c.lineTo(px(15), py(cfg.chalk)); }, { color: "rgba(255,255,255,0.85)", width: 6, blur: 6 });
+
+ const st = C.steps(cfg.forms, local, cfg), sim = C.drillSim(cfg, local);
+ const dots = st.dots.map((d, i) => [d[0] + sim.off[i][0], d[1] + sim.off[i][1]]);
+ const lostAt = (i) => sim.lostList.find((q) => q.i === i);
+ // fog: the floor near a trooper is lit, the rest stays dim, so the empty spaces show
+ // a ring on each space as a trooper arrives in it
+ if (st.k > 0 && local - st.k * cfg.step > cfg.move) {
+ const r = clamp01((local - st.k * cfg.step - cfg.move) / 0.35);
+ for (const [i, [a, b]] of cfg.forms[st.k].entries()) if (!lostAt(i)) M().glowStroke((c) => c.arc(px(a), py(b), 14 + 34 * r, 0, TAU), { color: `rgba(255,255,255,${0.85 * (1 - r)})`, width: 3, blur: 8 });
+ }
+ if (cfg.ball) {
+ C.ball(local, px(cfg.ball[0]), py(cfg.ball[1]), { r: 12 });
+ const settle = clamp01((local - 2.2) / 0.3);
+ if (settle > 0) { const r = (local * 1.1) % 1; M().glowStroke((c) => c.arc(px(cfg.ball[0]), py(cfg.ball[1]), 16 + 40 * r, 0, TAU), { color: `rgba(255,140,40,${0.9 * (1 - r) * settle})`, width: 3, blur: 8 }); }
+ }
+ // the crawler's chase line to its target
+ const tgt = sim.target;
+ if (tgt >= 0 && !lostAt(tgt)) M().orderPath(local, [[px(sim.c[0]), py(sim.c[1])], [px(dots[tgt][0]), py(dots[tgt][1])]], { color: "rgba(255,70,50,0.75)", a: 0.8 });
+ // units, back to front
+ const list = dots.map((d, i) => ({ i, v: d[1] })).concat([{ i: -1, v: sim.c[1] }]).sort((a, b) => a.v - b.v);
+ for (const o of list) {
+ if (o.i === -1) {
+ const dir = tgt >= 0 ? Math.sign(dots[tgt][0] - sim.c[0]) || -1 : -1;
+ M().unit(R, "crawler", px(sim.c[0]), py(sim.c[1]) + 26, 98, { dir, hp: 1, hpColour: [230, 60, 50], bob: Math.abs(Math.sin(local * 12)) * 3 });
+ continue;
+ }
+ const L = lostAt(o.i);
+ if (L && local - L.at > 0.5) continue;
+ const [a, b] = dots[o.i];
+ M().unit(R, "trooper", px(a), py(b) + 24, 60, { dir: st.dir[o.i], sel: !L, alpha: L ? 1 - clamp01((local - L.at) / 0.5) : 1,
+ hp: L ? 0 : 1, bob: st.moving[o.i] ? Math.abs(Math.sin(local * 14 + o.i)) * 3 : 0 });
+ }
+ // each loss: a small blast where it happened
+ const ev = sim.lostList.flatMap((q, j) => [
+ { type: "explosion", id: `drill-boom-${j}`, at: q.at, x: px(q.x), y: py(q.y), size: 0.6, smokeCount: 3 },
+ { type: "sparks", id: `drill-sparks-${j}`, at: q.at, x: px(q.x), y: py(q.y) - 10, count: 18, speed: [160, 520], life: [0.2, 0.5], color: "#ffcf70" },
+ ]);
+ Anim.particles.draw(ev, local);
+ M().end(R, box, { t: local, s, fonts: f, title: cfg.title || "TRAINING", headerY: 4, line: cfg.line });
+ // the squad panel, right of the court
+ const B = { x: box.x + box.w + 150, y: box.y - 10, w: 380, h: box.h + 20 };
+ C.squadPanel(R, f, B.x, B.y, B.w, B.h, cfg.faces.map((n, i) => ({ img: R.faces[n], lost: !!lostAt(i) })), {
+ t: local, extra: (x, y, w) => {
+ Anim.rts.ui.styledText(`CRAWLER RAN ${sim.run.toFixed(0)} m`, x + w / 2, y + 26, { font: f.logo, size: 22, style: "#ff8a6a", glow: "rgba(255,60,40,0.8)", blur: 8 });
+ },
+ });
+ return { sim, st };
+ };
+
+ // ---- the match: players as units, then as face icons -----------------------------------------------------------
+ // One player at its spot (canvas px): the team's sprite (blue troopers; the other team as tinted crawlers) or, once
+ // `icons` is on, its face icon on a team ring. o: { team: "blue"|"yellow"|"red", face (image), dir, moving, t, i, pop }
+ C.player = (R, x, y, { team = "blue", face = null, icons = false, dir = 1, moving = false, t = 0, i = 0, size = 1, pop = 1 } = {}) => {
+ const bob = moving ? Math.abs(Math.sin(t * 13 + i * 1.7)) * 3 : 0;
+ if (icons && face) {
+ const ring = team === "blue" ? "rgba(70,170,255,0.95)" : team === "yellow" ? "rgba(255,200,40,0.95)" : "rgba(255,70,50,0.95)";
+ const glow = team === "blue" ? "rgba(60,150,255,0.8)" : "rgba(255,180,30,0.85)";
+ M().icon(face, x, y - 30 * size - bob, 74 * size, { ring, glow, pop });
+ return { x, y, top: y - 70 * size, hand: [x + 26 * size, y - 4] };
+ }
+ if (team === "blue") {
+ const u = M().unit(R, "trooper", x, y, 62 * size, { dir, sel: true, ring: "rgba(70,170,255,0.95)", bob });
+ return { ...u, hand: [x + dir * 22 * size, y - 4] };
+ }
+ const u = M().unit(R, "crawler", x, y, 96 * size, { dir, sel: true, ring: team === "yellow" ? "rgba(255,200,40,0.9)" : "rgba(255,70,50,0.9)", tint: team === "yellow" ? "yellow" : null, bob });
+ return { ...u, hand: [x, y] };
+ };
+
+ Anim.court = C;
+})();
diff --git a/skills/make-an-anime/scripts/tools/p5/lib/mission.js b/skills/make-an-anime/scripts/tools/p5/lib/mission.js
new file mode 100644
index 0000000..a90f243
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/p5/lib/mission.js
@@ -0,0 +1,306 @@
+// Mission maps: the small top-down maps of a 2004 RTS (a campaign briefing, a zoomed minimap, a micro drill), drawn in
+// the Orbital Command look. The frame is the HUD console's own minimap bezel (9-sliced from console.png, so it stays
+// sharp at any size), the floor is steel deck plating, lines glow, units are the game's sprites with selection rings,
+// and there is fog of war, objective beacons, face-icon badges, a flash, and a typed mission line.
+// Needs rts.js (Anim.rts.load gives R; Anim.rts.ui gives the shared text, plate and cursor helpers) and particles.js.
+//
+// const R = await Anim.rts.load({ dir: "/output/ui-rts-assets", units: ["trooper", "crawler"] });
+// R.faces = await Anim.mission.loadFaces("/output/ui-rts-assets/faces", ["pilot", "rival"]); // optional
+// const box = { x: 250, y: 60, w: 1420, h: 820 }; // the map's screen rectangle (inside the bezel)
+// Anim.mission.begin(R, box, { t }); // background and console plate, clip to the map
+// Anim.mission.floor(box, { seed: "school", tile: 64 }); // deck plates
+// ...lines, walls, units, fog, beacons, in screen pixels...
+// Anim.mission.end(R, box, { t, fonts, title: "MISSION 3", line: { text: "Reach the stairs", at: 0.2 } });
+//
+// Everything is a pure function of t (see particles.js, the determinism rule): no state between frames.
+window.Anim = window.Anim || {};
+
+(() => {
+ const TAU = Math.PI * 2;
+ const M = {};
+ const UI = () => Anim.rts.ui;
+ const P = () => Anim.particles;
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
+
+ // The minimap bezel in console.png (its own pixels): the outer edge of the steel frame, and the frame's widths
+ // (left, top, right, bottom) up to the black screen. Corners are cut `corner` px deep so the rivets stay whole.
+ M.BEZEL = null; // Set from the measured console art, or pass R.bezel. No project-specific geometry.
+
+ // Which way each sprite faces as drawn on its sheet: the blue faction faces right, the red one left.
+ M.FACING = { trooper: 1, walker: 1, tank: 1, gunship: 1, spider: -1, crawler: -1, skiff: -1, stilt: -1 };
+
+ // Tints for a unit drawn in another team's colour (canvas filters on the red sprites).
+ M.TINT = {
+ yellow: "sepia(0.9) saturate(3.2) hue-rotate(8deg) brightness(1.12)",
+ red: "none",
+ };
+
+ M.loadFaces = async (dir, names) => {
+ const out = {};
+ for (const n of names) out[n] = await loadImage(`${dir}/${n}.png`);
+ return out;
+ };
+
+ // ---- frame ------------------------------------------------------------------------------------------------------
+
+ // The bezel round a screen rectangle, 9-sliced from the console: s scales the frame's thickness (2 ≈ 70 px).
+ M.bezel = (R, r, { s = 2 } = {}) => {
+ const bezel = R.bezel || M.BEZEL;
+ if (!bezel) throw new Error("Anim.mission: set R.bezel {box, inset, corner} from your console image");
+ const [bx, by, bw, bh] = bezel.box, [il, it, ir, ib] = bezel.inset, c = bezel.corner;
+ const g = drawingContext, img = R.console.canvas || R.console.elt || R.console;
+ const ox = r.x - il * s, oy = r.y - it * s, ow = r.w + (il + ir) * s, oh = r.h + (it + ib) * s;
+ const cs = c * s;
+ const sx = [bx, bx + c, bx + bw - c, bx + bw], dx = [ox, ox + cs, ox + ow - cs, ox + ow];
+ const sy = [by, by + c, by + bh - c, by + bh], dy = [oy, oy + cs, oy + oh - cs, oy + oh];
+ g.save();
+ g.imageSmoothingQuality = "high";
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) {
+ if (i === 1 && j === 1) continue; // the screen itself
+ const w = sx[i + 1] - sx[i], h = sy[j + 1] - sy[j];
+ g.drawImage(img, sx[i], sy[j], w, h, dx[i], dy[j], dx[i + 1] - dx[i], dy[j + 1] - dy[j]);
+ }
+ g.restore();
+ return { x: ox, y: oy, w: ow, h: oh };
+ };
+
+ // The background behind the map: dark gunmetal with a soft top light, and a recessed plate round the bezel.
+ M.begin = (R, r, { t = 0, s = 2, plate = true } = {}) => {
+ const g = drawingContext;
+ background(0);
+ const bg = g.createRadialGradient(width / 2, height * 0.42, 80, width / 2, height / 2, width * 0.75);
+ bg.addColorStop(0, "#1d242d"); bg.addColorStop(1, "#05070a");
+ g.save(); g.fillStyle = bg; g.fillRect(0, 0, width, height);
+ // faint panel seams across the background
+ g.strokeStyle = "rgba(255,255,255,0.035)"; g.lineWidth = 2;
+ for (let x = 0; x < width; x += 160) { g.beginPath(); g.moveTo(x, 0); g.lineTo(x, height); g.stroke(); }
+ g.restore();
+ if (plate) {
+ const bezel = R.bezel || M.BEZEL;
+ if (!bezel) throw new Error("Anim.mission: set R.bezel {box, inset, corner} from your console image");
+ const [il, it, ir, ib] = bezel.inset, pad = 26;
+ UI().bevelRect(r.x - il * s - pad, r.y - it * s - pad, r.w + (il + ir) * s + 2 * pad, r.h + (it + ib) * s + 2 * pad,
+ { face: "#222932", light: "#5d6978", dark: "#07090c", cut: 18 });
+ }
+ g.save(); g.fillStyle = "#000"; g.fillRect(r.x, r.y, r.w, r.h);
+ g.beginPath(); g.rect(r.x, r.y, r.w, r.h); g.clip();
+ };
+
+ // Close the map: the clip ends, then the bezel, an optional header (the logo plate and a title) and the mission line.
+ M.end = (R, r, { t = 0, s = 2, fonts, title, line, logo = true, logoText = "ORBITAL", headerY } = {}) => {
+ drawingContext.restore();
+ // inner shadow on the screen, under the bezel
+ const g = drawingContext;
+ g.save();
+ const sh = 26;
+ for (const [x, y, w, h, x0, y0, x1, y1] of [[r.x, r.y, r.w, sh, 0, r.y, 0, r.y + sh], [r.x, r.y, sh, r.h, r.x, 0, r.x + sh, 0]]) {
+ const gr = g.createLinearGradient(x0, y0, x1, y1); gr.addColorStop(0, "rgba(0,0,0,0.65)"); gr.addColorStop(1, "rgba(0,0,0,0)");
+ g.fillStyle = gr; g.fillRect(x, y, w, h);
+ }
+ g.restore();
+ const B = M.bezel(R, r, { s });
+ if (fonts && logo) {
+ const hy = headerY ?? Math.max(0, B.y - 74);
+ UI().logoPlate(t, { fonts, logo: { text: logoText, sub: title || "BATTLE" } }, width / 2, hy);
+ }
+ if (fonts && line) M.missionLine(t, line.text, { fonts, x: B.x + 40, y: line.y ?? Math.min(height - 46, B.y + B.h + 34), at: line.at ?? 0, label: line.label });
+ return B;
+ };
+
+ // ---- ground -----------------------------------------------------------------------------------------------------
+
+ const floorCache = {};
+ // Steel deck plates over a rectangle, the same every frame for a seed.
+ M.floor = (r, { seed = "deck", tile = 64, tint = [27, 32, 39], light = 1 } = {}) => {
+ const key = `${seed}|${r.w | 0}|${r.h | 0}|${tile}|${tint}|${light}`;
+ let c = floorCache[key];
+ if (!c) {
+ c = document.createElement("canvas"); c.width = Math.ceil(r.w); c.height = Math.ceil(r.h);
+ const g = c.getContext("2d");
+ const R = (k, s) => P().rand(seed, k, s);
+ for (let y = 0, j = 0; y < c.height; y += tile, j++) for (let x = 0, i = 0; x < c.width; x += tile, i++) {
+ const k = j * 997 + i, v = (R(k, 1) - 0.5) * 14 * light;
+ const [cr, cg, cb] = tint;
+ g.fillStyle = `rgb(${cr + v},${cg + v},${cb + v * 1.1})`; g.fillRect(x, y, tile, tile);
+ // bevel: light top and left, dark bottom and right
+ g.fillStyle = "rgba(255,255,255,0.06)"; g.fillRect(x, y, tile, 2); g.fillRect(x, y, 2, tile);
+ g.fillStyle = "rgba(0,0,0,0.55)"; g.fillRect(x, y + tile - 2, tile, 2); g.fillRect(x + tile - 2, y, 2, tile);
+ // rivets, some plates with a tread pattern, a rare grate
+ g.fillStyle = "rgba(160,175,190,0.22)";
+ for (const [a, b] of [[6, 6], [tile - 8, 6], [6, tile - 8], [tile - 8, tile - 8]]) g.fillRect(x + a, y + b, 2, 2);
+ const kind = R(k, 2);
+ if (kind < 0.18) {
+ g.strokeStyle = "rgba(255,255,255,0.05)"; g.lineWidth = 2;
+ for (let d = 10; d < tile - 6; d += 9) { g.beginPath(); g.moveTo(x + d, y + 10); g.lineTo(x + d - 5, y + tile - 10); g.stroke(); }
+ } else if (kind > 0.96) {
+ g.fillStyle = "rgba(0,0,0,0.45)";
+ for (let d = 12; d < tile - 10; d += 7) g.fillRect(x + 12, y + d, tile - 24, 3);
+ }
+ // grime
+ g.fillStyle = `rgba(0,0,0,${0.12 * R(k, 3)})`; g.fillRect(x, y, tile, tile);
+ }
+ floorCache[key] = c;
+ }
+ drawingContext.drawImage(c, r.x, r.y, r.w, r.h);
+ };
+
+ // Stroke a path with a glow: draw(path) builds it on the context. Two passes: a wide soft glow, then the crisp line.
+ M.glowStroke = (draw, { color = "rgba(70,170,255,0.95)", width: lw = 4, blur = 14, core = null } = {}) => {
+ const g = drawingContext;
+ g.save();
+ g.lineCap = "round"; g.lineJoin = "round";
+ g.shadowColor = color; g.shadowBlur = blur; g.strokeStyle = color; g.lineWidth = lw;
+ g.beginPath(); draw(g); g.stroke();
+ g.shadowBlur = 0;
+ if (core) { g.strokeStyle = core; g.lineWidth = Math.max(1, lw * 0.35); g.beginPath(); draw(g); g.stroke(); }
+ g.restore();
+ };
+
+ // A wall: a thick steel strip with a lit top edge and a cobalt trim line, between two points.
+ M.wall = (x0, y0, x1, y1, { w = 14, trim = "rgba(60,150,255,0.85)" } = {}) => {
+ const g = drawingContext;
+ g.save(); g.lineCap = "square";
+ g.strokeStyle = "#0a0d11"; g.lineWidth = w + 6; g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.stroke();
+ g.strokeStyle = "#4a5562"; g.lineWidth = w; g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.stroke();
+ g.strokeStyle = "#8e9bab"; g.lineWidth = 2; g.beginPath(); g.moveTo(x0, y0 - w / 2 + 2); g.lineTo(x1, y1 - w / 2 + 2); g.stroke();
+ g.shadowColor = trim; g.shadowBlur = 10; g.strokeStyle = trim; g.lineWidth = 2;
+ g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.stroke();
+ g.restore();
+ };
+
+ // A rectangle of walls with optional gaps: gaps [{ side: "top"|"bottom"|"left"|"right", at: px from the side's start, w }].
+ M.room = (x, y, w, h, { gaps = [], ...o } = {}) => {
+ const side = (name, ax, ay, bx, by) => {
+ const len = Math.hypot(bx - ax, by - ay), ux = (bx - ax) / len, uy = (by - ay) / len;
+ const cuts = gaps.filter((q) => q.side === name).sort((a, b) => a.at - b.at);
+ let s = 0;
+ for (const q of cuts) { if (q.at > s) M.wall(ax + ux * s, ay + uy * s, ax + ux * q.at, ay + uy * q.at, o); s = q.at + q.w; }
+ if (s < len) M.wall(ax + ux * s, ay + uy * s, bx, by, o);
+ };
+ side("top", x, y, x + w, y); side("bottom", x, y + h, x + w, y + h);
+ side("left", x, y, x, y + h); side("right", x + w, y, x + w, y + h);
+ };
+
+ // Fog of war over a rectangle: black (alpha `dark`) except soft round holes round each source [x, y, r].
+ const fogCanvas = document.createElement("canvas");
+ M.fog = (r, sources, { dark = 1, soft = 0.38, color = "0,0,0" } = {}) => {
+ const c = fogCanvas;
+ if (c.width !== width || c.height !== height) { c.width = width; c.height = height; }
+ const g = c.getContext("2d");
+ g.globalCompositeOperation = "source-over"; g.clearRect(0, 0, c.width, c.height);
+ g.fillStyle = `rgba(${color},${dark})`; g.fillRect(r.x, r.y, r.w, r.h);
+ g.globalCompositeOperation = "destination-out";
+ for (const [x, y, rad] of sources) {
+ const gr = g.createRadialGradient(x, y, 0, x, y, rad);
+ gr.addColorStop(0, "rgba(0,0,0,1)"); gr.addColorStop(1 - soft, "rgba(0,0,0,1)"); gr.addColorStop(1, "rgba(0,0,0,0)");
+ g.fillStyle = gr; g.fillRect(x - rad, y - rad, 2 * rad, 2 * rad);
+ }
+ drawingContext.drawImage(c, 0, 0);
+ };
+
+ // ---- units and markers ------------------------------------------------------------------------------------------
+
+ // A unit sprite at its foot point (x, y), w px wide. dir 1 faces right, -1 left. sel: a ring in `ring` colour.
+ M.unit = (R, kind, x, y, w, { dir = 1, sel = false, ring = "rgba(70,255,100,0.95)", tint = null, alpha = 1, hp = null, hpColour = [60, 230, 80], bob = 0 } = {}) => {
+ const img = R.units[kind];
+ const h = (w * img.height) / img.width, g = drawingContext;
+ g.save(); g.globalAlpha = alpha;
+ g.fillStyle = "rgba(0,0,0,0.5)"; g.beginPath(); g.ellipse(x, y + 2, w * 0.42, w * 0.16, 0, 0, TAU); g.fill();
+ if (sel) { g.strokeStyle = ring; g.lineWidth = 2.5; g.beginPath(); g.ellipse(x, y + 2, w * 0.52, w * 0.21, 0, 0, TAU); g.stroke(); }
+ const flip = dir !== (M.FACING[kind] ?? 1);
+ g.translate(x, y - bob);
+ if (flip) g.scale(-1, 1);
+ if (tint && M.TINT[tint]) g.filter = M.TINT[tint];
+ g.drawImage(img.canvas || img.elt || img, -w / 2, -h, w, h);
+ g.filter = "none";
+ g.restore();
+ if (hp != null) UI().hpBar(x, y - h - bob - 10, Math.min(w * 0.8, 56), hp, hpColour);
+ return { x, y, w, h, top: y - h - bob };
+ };
+
+ // A face icon badge (the SD unit icons) centred at (x, y), s px square, with a team ring under it.
+ M.icon = (img, x, y, s, { ring = "rgba(70,255,100,0.95)", glow = "rgba(60,150,255,0.8)", alpha = 1, pop = 1 } = {}) => {
+ const g = drawingContext, k = s * pop;
+ g.save(); g.globalAlpha = alpha;
+ g.fillStyle = "rgba(0,0,0,0.5)"; g.beginPath(); g.ellipse(x, y + k * 0.56, k * 0.46, k * 0.14, 0, 0, TAU); g.fill();
+ if (ring) { g.strokeStyle = ring; g.lineWidth = 3; g.beginPath(); g.ellipse(x, y + k * 0.56, k * 0.55, k * 0.18, 0, 0, TAU); g.stroke(); }
+ g.shadowColor = glow; g.shadowBlur = 16;
+ g.drawImage(img.canvas || img.elt || img, x - k / 2, y - k / 2, k, k);
+ g.restore();
+ };
+
+ // A pop for something appearing at `at`: 0 before, overshoots to about 1.15, settles at 1 by at + dur.
+ M.pop = (t, at, dur = 0.28) => {
+ const q = (t - at) / dur;
+ if (q <= 0) return 0;
+ if (q >= 1) return 1;
+ return 1 + 0.15 * Math.sin(q * Math.PI) - (1 - q) * (1 - q) * (1 - q);
+ };
+
+ // A full-screen flash at `at`: white, peaking in 2 frames, gone by at + dur. Returns its strength (0..1).
+ M.flash = (t, at, { dur = 0.4, color = "255,255,255", max = 1 } = {}) => {
+ const age = t - at;
+ if (age < -0.08 || age > dur) return 0;
+ const a = max * (age < 0 ? clamp01((age + 0.08) / 0.08) : Math.exp(-age / (dur * 0.32)));
+ const g = drawingContext;
+ g.save(); g.globalCompositeOperation = "lighter"; g.fillStyle = `rgba(${color},${a})`; g.fillRect(0, 0, width, height); g.restore();
+ return a;
+ };
+
+ // An objective beacon: a turning diamond, rings rising out of it, a soft column of light.
+ M.beacon = (t, x, y, { color = [255, 200, 60], size = 1 } = {}) => {
+ const g = drawingContext, [r, gg, b] = color;
+ g.save();
+ const col = g.createLinearGradient(0, y - 160 * size, 0, y);
+ col.addColorStop(0, `rgba(${r},${gg},${b},0)`); col.addColorStop(1, `rgba(${r},${gg},${b},0.28)`);
+ g.fillStyle = col; g.fillRect(x - 16 * size, y - 160 * size, 32 * size, 160 * size);
+ for (let i = 0; i < 2; i++) {
+ const q = ((t * 0.9 + i * 0.5) % 1);
+ g.strokeStyle = `rgba(${r},${gg},${b},${0.9 * (1 - q)})`; g.lineWidth = 3;
+ g.beginPath(); g.ellipse(x, y, (14 + 46 * q) * size, (6 + 18 * q) * size, 0, 0, TAU); g.stroke();
+ }
+ g.translate(x, y - 26 * size - 4 * Math.sin(t * 3)); g.scale(Math.cos(t * 2.4) * size, size);
+ g.shadowColor = `rgba(${r},${gg},${b},1)`; g.shadowBlur = 14;
+ g.fillStyle = `rgba(${r},${gg},${b},0.95)`;
+ g.beginPath(); g.moveTo(0, -16); g.lineTo(11, 0); g.lineTo(0, 16); g.lineTo(-11, 0); g.closePath(); g.fill();
+ g.restore();
+ };
+
+ // A path the player ordered: dashes moving along a polyline towards its end, with a chevron at the end.
+ M.orderPath = (t, pts, { color = "rgba(80,255,110,0.9)", a = 1 } = {}) => {
+ const g = drawingContext;
+ g.save(); g.globalAlpha = a; g.strokeStyle = color; g.lineWidth = 3; g.setLineDash([14, 12]); g.lineDashOffset = -t * 60;
+ g.beginPath(); pts.forEach(([x, y], i) => (i ? g.lineTo(x, y) : g.moveTo(x, y))); g.stroke();
+ g.setLineDash([]);
+ const [ax, ay] = pts[pts.length - 2], [bx, by] = pts[pts.length - 1], an = Math.atan2(by - ay, bx - ax);
+ g.lineWidth = 4; g.beginPath();
+ g.moveTo(bx - 18 * Math.cos(an - 0.5), by - 18 * Math.sin(an - 0.5)); g.lineTo(bx, by); g.lineTo(bx - 18 * Math.cos(an + 0.5), by - 18 * Math.sin(an + 0.5));
+ g.stroke(); g.restore();
+ };
+
+ // ---- text -------------------------------------------------------------------------------------------------------
+
+ // The mission line: a steel plate with a small label and the objective typed out from `at`, 38 characters a second.
+ M.missionLine = (t, str, { fonts, x, y, at = 0, label = "OBJECTIVE", cps = 38 } = {}) => {
+ const n = Math.max(0, Math.floor((t - at) * cps));
+ if (t < at) return;
+ const shown = str.slice(0, n), f = fonts.logo, g = drawingContext;
+ textFont(f); textSize(26);
+ const w = textWidth(str) + 250, h = 56;
+ UI().bevelRect(x, y - h / 2, w, h, { face: "#141a21", light: "#56616e", dark: "#05070a", cut: 10 });
+ g.save(); g.fillStyle = "rgba(255,190,60,0.95)"; g.fillRect(x + 12, y - 16, 6, 32); g.restore();
+ UI().styledText(label, x + 30, y + 1, { font: f, size: 16, style: "#ffc45a", align: [LEFT, CENTER], spacing: 3, glow: "rgba(255,170,40,0.8)", blur: 8, outline: "#140c00", weight: 2 });
+ UI().styledText(shown + (n < str.length && Math.floor(t * 6) % 2 ? "_" : ""), x + 190, y + 1, { font: f, size: 26, style: "#e8f2ff", align: [LEFT, CENTER], glow: "rgba(60,160,255,0.7)", blur: 8 });
+ };
+
+ // A small tag over a unit or icon, e.g. a name or "#14": dark plate, team colour edge.
+ M.tag = (str, x, y, { fonts, colour = "#3aa0ff", size = 18 } = {}) => {
+ const f = fonts.logo;
+ textFont(f); textSize(size);
+ const w = textWidth(str) + 18, h = size + 10, g = drawingContext;
+ g.save(); g.fillStyle = "rgba(4,8,14,0.82)"; g.fillRect(x - w / 2, y - h / 2, w, h); g.fillStyle = colour; g.fillRect(x - w / 2, y + h / 2 - 3, w, 3); g.restore();
+ UI().styledText(str, x, y, { font: f, size, style: "#eef6ff" });
+ };
+
+ Anim.mission = M;
+})();
diff --git a/skills/make-an-anime/scripts/tools/p5/lib/particles.js b/skills/make-an-anime/scripts/tools/p5/lib/particles.js
new file mode 100644
index 0000000..29eaef7
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/p5/lib/particles.js
@@ -0,0 +1,295 @@
+// Particles: sparks, explosions (flash + fireball + debris + smoke + shock ring), laser beams, tracer bullets, muzzle
+// flashes and impact rings, for any p5 overlay. Generic: nothing here knows about games, units or HUDs.
+//
+// const P = Anim.particles;
+// const events = [
+// { type: "laser", id: "l1", at: 0.40, from: [300, 500], to: [900, 420], color: "#5fd0ff" },
+// { type: "tracers", id: "t1", at: 0.20, dur: 1.2, from: [320, 520], to: [880, 440], rate: 14 },
+// { type: "explosion", id: "boom", at: 1.30, x: 900, y: 430, size: 1.4 },
+// ];
+// P.draw(events, t); // the picture
+// P.draw(events, t, { mode: "light" }); // only what emits light, on transparent black, for the Swift halo pass
+//
+// THE DETERMINISM RULE. The overlay may render any frame alone, in any order (previews, --only, a light layer rendered
+// later by another process). So no emitter keeps state between frames: every particle is seeded from its emitter's `id`
+// and its own index (P.rand(id, k, salt)), and its position, size and colour are closed-form functions of its age
+// (t - birth). Never use random(), Math.random(), frameCount or a list that grows frame by frame here.
+//
+// Every emitter takes `at` (s, when it starts) and an `id` (string or number, unique per emitter: it is the seed).
+// Times are in the same clock as the `t` passed to draw (use the shot's local seconds). Coordinates are canvas pixels in
+// the current p5 transform, so translate/scale before drawing to follow a scrolling map.
+//
+// mode "color" (default) draws everything. mode "light" draws only the hot parts (beam cores, muzzle flashes, tracer
+// heads, the explosion's flash and fireball, hot sparks) and skips smoke and dark debris. Render the same sketch a second
+// time with mode "light" onto a transparent canvas and give those PNGs to mvfx --lights: the halo cue blurs them into a
+// bloom and screen-blends them over the frame, so only the light sources glow, not the whole picture.
+window.Anim = window.Anim || {};
+
+(() => {
+ const TAU = Math.PI * 2;
+
+ // Stable hash of (id, k, salt) -> [0, 1). FNV-1a over the id string, then a 32-bit avalanche.
+ const hashStr = (s) => {
+ let h = 2166136261 >>> 0;
+ s = String(s);
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
+ return h;
+ };
+ const rand = (id, k = 0, salt = 0) => {
+ let h = (hashStr(id) ^ Math.imul(k + 1, 0x9e3779b1) ^ Math.imul(salt + 7, 0x85ebca77)) >>> 0;
+ h ^= h >>> 16; h = Math.imul(h, 0x7feb352d) >>> 0;
+ h ^= h >>> 15; h = Math.imul(h, 0x846ca68b) >>> 0;
+ h ^= h >>> 16;
+ return (h >>> 0) / 4294967296;
+ };
+ const range = (id, k, salt, lo, hi) => lo + (hi - lo) * rand(id, k, salt);
+ const pick = (v, id, k, salt) => (Array.isArray(v) ? range(id, k, salt, v[0], v[1]) : v);
+
+ // Closed-form ballistic motion with linear drag `drag` (1/s) and gravity `g` (px/s², +y down): position after `age` s.
+ const fly = (x, y, vx, vy, age, drag, g) => {
+ if (drag <= 1e-6) return [x + vx * age, y + vy * age + 0.5 * g * age * age];
+ const e = (1 - Math.exp(-drag * age)) / drag;
+ return [x + vx * e, y + vy * e + (g / drag) * (age - e)];
+ };
+ const velAt = (vx, vy, age, drag, g) => {
+ const k = Math.exp(-drag * age);
+ return [vx * k, vy * k + (drag > 1e-6 ? (g / drag) * (1 - k) : g * age)];
+ };
+
+ const hex = (c) => {
+ if (Array.isArray(c)) return c;
+ const v = parseInt(String(c).replace("#", ""), 16);
+ return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
+ };
+ const rgba = (c, a) => {
+ const [r, g, b] = hex(c);
+ return `rgba(${r | 0},${g | 0},${b | 0},${Math.max(0, Math.min(1, a)).toFixed(4)})`;
+ };
+ const mix = (a, b, q) => { const A = hex(a), B = hex(b); return A.map((v, i) => v + (B[i] - v) * q); };
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
+
+ // Soft radial glow at (x, y), radius r. Additive ("lighter") so overlapping light adds up, like light does.
+ const glow = (g, x, y, r, c, a, { core = 0.18 } = {}) => {
+ if (a <= 0.003 || r <= 0.5) return;
+ const grad = g.createRadialGradient(x, y, 0, x, y, r);
+ grad.addColorStop(0, rgba(c, a));
+ grad.addColorStop(core, rgba(c, a * 0.7));
+ grad.addColorStop(1, rgba(c, 0));
+ g.fillStyle = grad;
+ g.fillRect(x - r, y - r, 2 * r, 2 * r);
+ };
+
+ const withCtx = (fn, op = "source-over") => {
+ const g = drawingContext;
+ g.save();
+ g.globalCompositeOperation = op;
+ try { fn(g); } finally { g.restore(); }
+ };
+
+ const E = {};
+
+ // sparks: a burst of streaks. count 18, speed [180, 620] px/s, life [0.18, 0.5] s, angle 0 (rad, 0 = right),
+ // spread TAU (full circle), drag 3, gravity 500, color "#ffd27a", hot "#ffffff", width 2.2, len 0.035 (s of motion per streak).
+ E.sparks = (ev, t, mode) => {
+ const { id, at = 0, x, y, count = 18, speed = [180, 620], life = [0.18, 0.5], angle = 0, spread = TAU, drag = 3, gravity = 500,
+ color = "#ffd27a", hot = "#ffffff", width = 2.2, len = 0.035, alpha = 1 } = ev;
+ const age0 = t - at;
+ if (age0 < 0 || age0 > (Array.isArray(life) ? life[1] : life) + 0.05) return;
+ withCtx((g) => {
+ g.lineCap = "round";
+ for (let k = 0; k < count; k++) {
+ const L = pick(life, id, k, 1), age = age0 - range(id, k, 2, 0, 0.04);
+ if (age < 0 || age > L) continue;
+ const a = angle + (rand(id, k, 3) - 0.5) * spread, v = pick(speed, id, k, 4);
+ const vx = Math.cos(a) * v, vy = Math.sin(a) * v;
+ const [x1, y1] = fly(x, y, vx, vy, age, drag, gravity);
+ const [x0, y0] = fly(x, y, vx, vy, Math.max(0, age - len), drag, gravity);
+ const q = age / L, heat = 1 - q;
+ g.strokeStyle = rgba(mix(color, hot, heat * heat), alpha * (1 - q * q));
+ g.lineWidth = width * (0.6 + 0.8 * heat);
+ g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.stroke();
+ }
+ }, "lighter");
+ };
+
+ // muzzle: a 2-3 frame star flash at the barrel. angle (rad), size 1, color "#ffe7a0", dur 0.08.
+ E.muzzle = (ev, t, mode) => {
+ const { id, at = 0, x, y, angle = 0, size = 1, color = "#ffe7a0", dur = 0.08 } = ev;
+ const age = t - at;
+ if (age < 0 || age > dur) return;
+ const q = 1 - age / dur, s = size * (0.7 + 0.5 * rand(id, Math.floor(age * 60), 9));
+ withCtx((g) => {
+ glow(g, x, y, 26 * s, color, 0.9 * q);
+ g.translate(x, y); g.rotate(angle);
+ g.fillStyle = rgba("#ffffff", q);
+ g.beginPath(); g.moveTo(0, -3 * s); g.lineTo(30 * s * q + 8, 0); g.lineTo(0, 3 * s); g.closePath(); g.fill();
+ g.fillStyle = rgba(color, 0.8 * q);
+ g.beginPath(); g.moveTo(-2, -7 * s); g.lineTo(14 * s, 0); g.lineTo(-2, 7 * s); g.closePath(); g.fill();
+ }, "lighter");
+ };
+
+ // ring: an expanding impact/shock ring. radius 60, dur 0.35, color "#bfe8ff", weight 5, squash 0.55 (y scale, ground plane).
+ E.ring = (ev, t, mode) => {
+ const { x, y, at = 0, radius = 60, dur = 0.35, color = "#bfe8ff", weight = 5, squash = 0.55, alpha = 0.9 } = ev;
+ const age = t - at;
+ if (age < 0 || age > dur) return;
+ const q = age / dur, r = radius * (1 - Math.pow(1 - q, 3));
+ withCtx((g) => {
+ g.strokeStyle = rgba(color, alpha * (1 - q));
+ g.lineWidth = weight * (1 - q * 0.7);
+ g.beginPath(); g.ellipse(x, y, r, r * squash, 0, 0, TAU); g.stroke();
+ }, "lighter");
+ };
+
+ // laser: a beam from `from` to `to`. dur 0.16 (s on), grow 0.035 (s for the head to reach the target), color "#5fd0ff",
+ // width 5, flicker 0.25, hit true (sparks + glow at the target), muzzle true.
+ E.laser = (ev, t, mode) => {
+ const { id, at = 0, from, to, dur = 0.16, grow = 0.035, color = "#5fd0ff", width = 5, flicker = 0.25, hit = true, muzzle = true } = ev;
+ const age = t - at;
+ if (age < 0) return;
+ const [x0, y0] = from, [x1, y1] = to;
+ if (hit && age < dur + 0.4) E.sparks({ id: `${id}:hit`, at: at + grow, x: x1, y: y1, count: 10, speed: [120, 420], life: [0.1, 0.3],
+ color, hot: "#ffffff", width: 1.8, gravity: 300 }, t, mode);
+ if (age > dur) return;
+ const head = clamp01(age / grow), tail = clamp01((age - dur + grow) / grow);
+ const hx = x0 + (x1 - x0) * head, hy = y0 + (y1 - y0) * head;
+ const tx = x0 + (x1 - x0) * tail, ty = y0 + (y1 - y0) * tail;
+ const fl = 1 - flicker * rand(id, Math.floor(age * 48), 5);
+ withCtx((g) => {
+ g.lineCap = "round";
+ g.strokeStyle = rgba(color, 0.35 * fl); g.lineWidth = width * 3.2;
+ g.beginPath(); g.moveTo(tx, ty); g.lineTo(hx, hy); g.stroke();
+ g.strokeStyle = rgba(color, 0.9 * fl); g.lineWidth = width;
+ g.beginPath(); g.moveTo(tx, ty); g.lineTo(hx, hy); g.stroke();
+ g.strokeStyle = rgba("#ffffff", 0.95 * fl); g.lineWidth = Math.max(1, width * 0.35);
+ g.beginPath(); g.moveTo(tx, ty); g.lineTo(hx, hy); g.stroke();
+ if (head >= 1) glow(g, x1, y1, width * 7, color, 0.8 * fl);
+ }, "lighter");
+ if (muzzle) E.muzzle({ id: `${id}:mz`, at, x: x0, y: y0, angle: Math.atan2(y1 - y0, x1 - x0), size: width / 5, color }, t, mode);
+ };
+
+ // tracers: a stream of bullets from `from` to `to`. dur 1 (s of firing), rate 12 (shots/s), speed 2200 px/s,
+ // color "#ffd36b", len 34 (px streak), spread 14 (px of scatter at the target), jitter 0.3 (of a shot period),
+ // muzzle true, hit true (a small spark where each round lands).
+ E.tracers = (ev, t, mode) => {
+ const { id, at = 0, dur = 1, rate = 12, from, to, speed = 2200, color = "#ffd36b", len = 34, spread = 14, jitter = 0.3,
+ muzzle = true, hit = true, width = 2.4 } = ev;
+ if (t < at) return;
+ const n = Math.ceil(dur * rate);
+ for (let k = 0; k < n; k++) {
+ const fire = at + (k + (rand(id, k, 1) - 0.5) * jitter) / rate;
+ const age = t - fire;
+ if (age < 0) continue;
+ const tx = to[0] + (rand(id, k, 2) - 0.5) * spread * 2, ty = to[1] + (rand(id, k, 3) - 0.5) * spread;
+ const dist = Math.hypot(tx - from[0], ty - from[1]), flight = dist / speed;
+ if (muzzle) E.muzzle({ id: `${id}:m${k}`, at: fire, x: from[0], y: from[1], angle: Math.atan2(ty - from[1], tx - from[0]), size: 0.55, color, dur: 0.05 }, t, mode);
+ if (age <= flight) {
+ const q = age / flight, ux = (tx - from[0]) / dist, uy = (ty - from[1]) / dist;
+ const hx = from[0] + (tx - from[0]) * q, hy = from[1] + (ty - from[1]) * q;
+ withCtx((g) => {
+ g.lineCap = "round";
+ g.strokeStyle = rgba(color, 0.9); g.lineWidth = width;
+ g.beginPath(); g.moveTo(hx - ux * len, hy - uy * len); g.lineTo(hx, hy); g.stroke();
+ g.fillStyle = rgba("#ffffff", 1); g.beginPath(); g.arc(hx, hy, width * 0.7, 0, TAU); g.fill();
+ }, "lighter");
+ } else if (hit && age < flight + 0.2) {
+ E.sparks({ id: `${id}:h${k}`, at: fire + flight, x: tx, y: ty, count: 4, speed: [80, 260], life: [0.06, 0.16], color, width: 1.4, gravity: 200 }, t, mode);
+ }
+ }
+ };
+
+ // explosion: flash + fireball + debris + smoke + shock ring + scorch. size 1 (scale; 1 ≈ 90 px fireball),
+ // palette { flash "#fff6d8", fire ["#ffe08a", "#ff8a2a", "#c0381c"], smoke "#2c2a2a" }, debris 22, smokeCount 9,
+ // ring true, dur 1.6 (s until the smoke is gone).
+ E.explosion = (ev, t, mode) => {
+ const { id, at = 0, x, y, size = 1, debris = 22, smokeCount = 9, ring = true, dur = 1.6,
+ flash = "#fff6d8", fire = ["#ffe08a", "#ff8a2a", "#c0381c"], smoke = "#2c2a2a" } = ev;
+ const age = t - at;
+ if (age < 0 || age > dur) return;
+ const s = size;
+ // Smoke: grey puffs that rise, grow and thin out. Dark, so never in the light layer.
+ if (mode !== "light") {
+ withCtx((g) => {
+ for (let k = 0; k < smokeCount; k++) {
+ const born = 0.08 + rand(id, k, 11) * 0.25, a = age - born;
+ if (a < 0) continue;
+ const L = dur - born, q = clamp01(a / L);
+ const ang = rand(id, k, 12) * TAU, d = (20 + 40 * rand(id, k, 13)) * s * (1 - Math.exp(-3 * a));
+ const px = x + Math.cos(ang) * d + 18 * s * a, py = y + Math.sin(ang) * d * 0.55 - 55 * s * a;
+ const r = (22 + 30 * rand(id, k, 14)) * s * (0.5 + 0.9 * Math.sqrt(q));
+ const grad = g.createRadialGradient(px, py, 0, px, py, r);
+ const al = 0.55 * Math.sin(Math.PI * Math.min(1, q * 1.15)) * (0.6 + 0.4 * rand(id, k, 15));
+ grad.addColorStop(0, rgba(smoke, al)); grad.addColorStop(0.6, rgba(smoke, al * 0.6)); grad.addColorStop(1, rgba(smoke, 0));
+ g.fillStyle = grad; g.fillRect(px - r, py - r, 2 * r, 2 * r);
+ }
+ });
+ }
+ // Flash: one white-hot frame or two, then gone.
+ withCtx((g) => {
+ const fq = clamp01(1 - age / 0.12);
+ glow(g, x, y, 170 * s, flash, 0.85 * fq * fq, { core: 0.1 });
+ // Fireball: hot blobs that swell, cool from yellow to red and fade.
+ const fb = clamp01(age / 0.55);
+ for (let k = 0; k < 7; k++) {
+ const ang = rand(id, k, 21) * TAU, d = 28 * s * rand(id, k, 22) * Math.sqrt(fb);
+ const px = x + Math.cos(ang) * d, py = y + Math.sin(ang) * d * 0.6 - 10 * s * fb;
+ const r = (34 + 26 * rand(id, k, 23)) * s * (0.35 + 0.9 * Math.sqrt(fb));
+ const heat = 1 - fb;
+ const c = heat > 0.5 ? mix(fire[1], fire[0], (heat - 0.5) * 2) : mix(fire[2], fire[1], heat * 2);
+ glow(g, px, py, r, c, 0.9 * heat * (mode === "light" ? 0.9 : 1), { core: 0.3 });
+ }
+ }, "lighter");
+ if (ring) E.ring({ x, y: y + 6 * s, at, radius: 120 * s, dur: 0.32, color: "#ffe2b0", weight: 6 * s, alpha: 0.75 }, t, mode);
+ // Debris: hot fragments thrown out with gravity; they glow while hot, then dark chunks (colour mode only).
+ for (let k = 0; k < debris; k++) {
+ const L = range(id, k, 31, 0.35, 0.9), a = age - range(id, k, 32, 0, 0.03);
+ if (a < 0 || a > L) continue;
+ const ang = -Math.PI / 2 + (rand(id, k, 33) - 0.5) * Math.PI * 1.7, v = range(id, k, 34, 160, 520) * s;
+ const vx = Math.cos(ang) * v, vy = Math.sin(ang) * v * 0.8;
+ const [px, py] = fly(x, y, vx, vy, a, 1.6, 900 * s);
+ const q = a / L, hot = clamp01(1 - q * 2.2);
+ if (hot > 0) {
+ const [ux, uy] = velAt(vx, vy, a, 1.6, 900 * s), sp = Math.hypot(ux, uy) || 1;
+ withCtx((g) => {
+ g.strokeStyle = rgba(mix(fire[1], "#ffffff", hot * 0.6), hot); g.lineWidth = 2.2 * s; g.lineCap = "round";
+ g.beginPath(); g.moveTo(px - (ux / sp) * 9 * s, py - (uy / sp) * 9 * s); g.lineTo(px, py); g.stroke();
+ }, "lighter");
+ } else if (mode !== "light") {
+ withCtx((g) => { g.fillStyle = rgba("#1b1714", 1 - q); g.fillRect(px - 2 * s, py - 2 * s, 4 * s, 3 * s); });
+ }
+ }
+ };
+
+ // scorch: a dark burn mark left on the ground from `at` on (colour mode only). radius 46.
+ E.scorch = (ev, t, mode) => {
+ const { x, y, at = 0, radius = 46, alpha = 0.6 } = ev;
+ if (t < at || mode === "light") return;
+ const a = alpha * clamp01((t - at) / 0.2);
+ withCtx((g) => {
+ g.translate(x, y); g.scale(1, 0.55);
+ const grad = g.createRadialGradient(0, 0, 0, 0, 0, radius);
+ grad.addColorStop(0, `rgba(10,8,6,${a})`); grad.addColorStop(0.7, `rgba(20,14,10,${a * 0.5})`); grad.addColorStop(1, "rgba(0,0,0,0)");
+ g.fillStyle = grad; g.fillRect(-radius, -radius, 2 * radius, 2 * radius);
+ });
+ };
+
+ // The ground parts first (scorch), then everything else in list order.
+ const draw = (events, t, { mode = "color" } = {}) => {
+ for (const ev of events) if (ev.type === "scorch") E.scorch(ev, t, mode);
+ for (const ev of events) {
+ if (ev.type === "scorch") continue;
+ const fn = E[ev.type];
+ if (!fn) throw new Error(`Anim.particles: unknown emitter type "${ev.type}" (${Object.keys(E).join(", ")})`);
+ fn(ev, t, mode);
+ }
+ };
+
+ // How strongly the light events hit at t (0..1+): drive a screen flash, a shake or a sound cue from the same list.
+ const intensity = (events, t) => events.reduce((sum, ev) => {
+ const age = t - (ev.at ?? 0);
+ if (ev.type === "explosion" && age >= 0) return sum + (ev.size ?? 1) * Math.exp(-age / 0.12);
+ return sum;
+ }, 0);
+
+ Anim.particles = { draw, emitters: E, rand, range, fly, intensity, rgba, glow };
+})();
diff --git a/skills/make-an-anime/scripts/tools/p5/lib/rts.js b/skills/make-an-anime/scripts/tools/p5/lib/rts.js
new file mode 100644
index 0000000..20b1a27
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/p5/lib/rts.js
@@ -0,0 +1,533 @@
+// RTS game screen: a 2004-style real-time strategy game on a PC monitor, composed from generated art sheets (terrain,
+// HUD console frame, unit sprites, command icons, a unit portrait) with every readable word and number drawn here.
+// Needs particles.js (Anim.particles) for the shooting and the explosions.
+//
+// const R = await Anim.rts.load({ dir: "/output/ui-rts-assets", units: ["trooper", ...], icons: ["move", ...] });
+// const game = { ...the scene's battle: units, events, cursor, selection... (see "The game object" below) };
+// Anim.rts.screen(t, R, game); // the picture
+// Anim.rts.screen(t, R, game, { mode: "light" }); // only the light (lasers, flashes, eyes), for the mvfx halo pass
+//
+// Assets (tools/python/cut_sheets.py makes them from the five sheets): map.jpg (terrain), console.png (the HUD frame with
+// its screens cut transparent) + console_slots.json (their rectangles), units/<name>.png, icons/<name>.png, portrait.png.
+//
+// Layout: the console is drawn full width along the bottom at its own aspect. Its screens are classified from the slot
+// list: the large ones, left to right, are game.hud.screens (default ["portrait", "minimap", "info", "gauge"]), and the
+// small equal ones are the command-card sockets, row by row. Everything under a screen is drawn first, then the frame.
+//
+// The game object (all times in the same seconds as t; world coordinates are terrain pixels after map.scale):
+// title "Orbital Command" window title bar text top 44 (title bar height)
+// fonts { ui, uiBold, logo } p5 fonts logo { text: "ORBITAL", sub: "BATTLE" }
+// map { scale 0.9, cam(t) -> [x, y] } camera = world point at the viewport's top-left
+// kinds { name: { w, muzzle: [fx, fy], air } } draw width (px) and gun position as fractions of w from the foot point
+// units [{ id, kind, team, at(t) -> [x, y] foot point, dies (s) }] team "blue" (the player) or "red"; facing is the sprite's
+// selected(t, u) -> bool the player's selection target(t) -> unit id | null (red ring + hp bar)
+// events [particle events] world coordinates (see particles.js)
+// markers [{ at, x, y, kind: "attack" | "move" }] click markers on the ground
+// drag(t) -> null | { a: [x, y], b: [x, y] } selection box, screen coordinates
+// cursor(t) -> { x, y, down, mode: "arrow" | "target" } screen coordinates
+// resources(t) -> [{ icon: "crystal" | "gas" | "supply", text }] timer(t) -> "23:41"
+// commands [12 icon names] pressed [{ name, at }] gauge(t) -> 0..1
+// pings [{ at, x, y, color }] minimap alerts (world) portrait { eyes: [[x, y], ...] in portrait.png px,
+// eye "#ffa040", talk: [[from, to], ...] }
+// vision { radius 360 } fog of war around the player's units
+// alert(t) -> null | { text, sub, a } a warning across the battlefield ("Your base is under attack"), a = 0..1
+// iconOf(u) -> image | null a unit's tile in the info screen (e.g. a player's face icon) instead of its sprite
+window.Anim = window.Anim || {};
+
+(() => {
+ const TAU = Math.PI * 2;
+ const P = () => Anim.particles;
+ const TEAM = { blue: [60, 150, 255], red: [255, 70, 60] };
+ const clamp01 = (x) => Math.max(0, Math.min(1, x));
+
+ const loadJSON = async (url) => {
+ const r = await fetch(url);
+ if (!r.ok) throw new Error(`Anim.rts: ${url} ${r.status}`);
+ return r.json();
+ };
+
+ Anim.rts = {};
+
+ Anim.rts.load = async ({ dir, units = [], icons = [] }) => {
+ const R = { dir, units: {}, icons: {} };
+ R.map = await loadImage(`${dir}/map.jpg`);
+ R.console = await loadImage(`${dir}/console.png`);
+ R.slots = await loadJSON(`${dir}/console_slots.json`);
+ R.portrait = await loadImage(`${dir}/portrait.png`);
+ for (const n of units) R.units[n] = await loadImage(`${dir}/units/${n}.png`);
+ for (const n of icons) R.icons[n] = await loadImage(`${dir}/icons/${n}.png`);
+ R.fog = document.createElement("canvas");
+ return R;
+ };
+
+ // Screen rectangles of the console and its screens, for a canvas width W and height H.
+ Anim.rts.layout = (R, game, W = width, H = height) => {
+ const s = R.slots, k = W / s.w, y0 = H - s.h * k;
+ const rect = ([x, y, w, h]) => ({ x: x * k, y: y0 + y * k, w: w * k, h: h * k });
+ const areas = s.slots.map((r) => r[2] * r[3]).sort((a, b) => a - b);
+ const small = areas[Math.floor(areas.length / 4)];
+ const big = s.slots.filter((r) => r[2] * r[3] > small * 3).sort((a, b) => a[0] - b[0]);
+ const sockets = s.slots.filter((r) => r[2] * r[3] <= small * 3)
+ .sort((a, b) => (Math.abs(a[1] - b[1]) > a[3] / 2 ? a[1] - b[1] : a[0] - b[0]));
+ const names = game.hud?.screens || ["portrait", "minimap", "info", "gauge"];
+ const screens = Object.fromEntries(big.map((r, i) => [names[i] || `screen${i}`, rect(r)]));
+ return { k, y0, top: y0 + s.top * k, screens, sockets: sockets.map(rect), W, H };
+ };
+
+ // A unit's geometry at t: foot point, sprite box, gun and body centre, in world coordinates.
+ Anim.rts.geom = (R, game, u, t) => {
+ const kind = game.kinds[u.kind], img = R.units[u.kind];
+ const [x, y] = u.at(t);
+ const w = kind.w, h = (w * img.height) / img.width;
+ const lift = kind.air ? 46 + 4 * Math.sin(t * 3 + u.id.length) : 0;
+ const dir = u.team === "blue" ? 1 : -1;
+ const m = kind.muzzle || [0.45, -0.55];
+ return { x, y, w, h, lift, img, dir, air: !!kind.air,
+ muzzle: [x + dir * m[0] * w, y - lift + m[1] * h], center: [x, y - lift - h * 0.42] };
+ };
+
+ Anim.rts.alive = (u, t) => u.dies == null || t < u.dies;
+
+ // ---- drawing helpers -------------------------------------------------------------------------------------------
+
+ const bevelRect = (x, y, w, h, { face = "#2a3038", light = "#8b97a6", dark = "#0b0e12", cut = 6 } = {}) => {
+ const g = drawingContext;
+ g.save();
+ g.beginPath();
+ g.moveTo(x + cut, y); g.lineTo(x + w - cut, y); g.lineTo(x + w, y + cut); g.lineTo(x + w, y + h - cut);
+ g.lineTo(x + w - cut, y + h); g.lineTo(x + cut, y + h); g.lineTo(x, y + h - cut); g.lineTo(x, y + cut); g.closePath();
+ const grad = g.createLinearGradient(0, y, 0, y + h);
+ grad.addColorStop(0, light); grad.addColorStop(0.08, face); grad.addColorStop(0.92, face); grad.addColorStop(1, dark);
+ g.fillStyle = grad; g.fill();
+ g.strokeStyle = "rgba(0,0,0,0.85)"; g.lineWidth = 2; g.stroke();
+ g.restore();
+ };
+
+ // Text with a canvas fill style (gradient) or a colour, optional glow and outline. p5 caches its fill, so the
+ // context's fillStyle is set after fill() and right before text().
+ const styledText = (str, x, y, { font, size, style = "#fff", glow = null, blur = 0, outline = null, weight = 0, align = [CENTER, CENTER], spacing = 0 }) => {
+ textFont(font); textSize(size); textAlign(...align);
+ const g = drawingContext;
+ g.save();
+ g.letterSpacing = `${spacing}px`;
+ if (outline) {
+ noFill(); stroke(outline); strokeWeight(weight);
+ if (glow) { g.shadowColor = glow; g.shadowBlur = blur; }
+ text(str, x, y);
+ g.shadowBlur = 0;
+ }
+ noStroke(); fill(255);
+ g.fillStyle = style;
+ text(str, x, y);
+ g.restore();
+ };
+
+ // The game logo plate: a chamfered steel plate hanging from the top edge, the title in a heavy chiselled face with a
+ // steel bevel and an electric-blue glow.
+ const logoPlate = (t, game, cx, y) => {
+ const { text: main = "ORBITAL", sub = "BATTLE" } = game.logo || {};
+ const f = game.fonts.logo;
+ textFont(f); textSize(46);
+ drawingContext.letterSpacing = "3px";
+ const tw = textWidth(main);
+ drawingContext.letterSpacing = "0px";
+ const w = tw + 230, h = 78, x = cx - w / 2;
+ const g = drawingContext;
+ // plate
+ g.save();
+ g.beginPath();
+ g.moveTo(x, y); g.lineTo(x + w, y); g.lineTo(x + w - 34, y + h); g.lineTo(x + 34, y + h); g.closePath();
+ const pg = g.createLinearGradient(0, y, 0, y + h);
+ pg.addColorStop(0, "#1a2029"); pg.addColorStop(0.5, "#2b333e"); pg.addColorStop(1, "#11151b");
+ g.fillStyle = pg; g.fill();
+ g.strokeStyle = "#6d7b8c"; g.lineWidth = 2; g.stroke();
+ g.beginPath(); g.moveTo(x + 40, y + h - 7); g.lineTo(x + w - 40, y + h - 7);
+ g.strokeStyle = `rgba(70,160,255,${0.55 + 0.25 * Math.sin(t * 4)})`; g.lineWidth = 2; g.stroke();
+ g.restore();
+ // title: blue glow behind a dark outline, then a chrome gradient face, then a thin top highlight
+ const ty = y + 32;
+ const chrome = g.createLinearGradient(0, ty - 24, 0, ty + 22);
+ chrome.addColorStop(0, "#ffffff"); chrome.addColorStop(0.32, "#c9d3df"); chrome.addColorStop(0.5, "#5d6876");
+ chrome.addColorStop(0.56, "#3a4350"); chrome.addColorStop(0.78, "#aab6c4"); chrome.addColorStop(1, "#e9f1fb");
+ const pulse = 0.75 + 0.25 * Math.sin(t * 2.6);
+ styledText(main, cx, ty, { font: f, size: 46, style: chrome, outline: "#041226", weight: 7, glow: `rgba(40,150,255,${pulse})`, blur: 26, spacing: 3 });
+ // the sub line between two blue rules
+ const sy = y + 63;
+ styledText(sub, cx, sy, { font: f, size: 19, style: "#8fd0ff", glow: "rgba(40,150,255,0.9)", blur: 10, outline: "#03101e", weight: 3, spacing: 9 });
+ textFont(f); textSize(19); g.letterSpacing = "9px";
+ const sw = textWidth(sub); g.letterSpacing = "0px";
+ g.save();
+ g.strokeStyle = "rgba(80,170,255,0.85)"; g.lineWidth = 2;
+ g.beginPath(); g.moveTo(cx - sw / 2 - 90, sy); g.lineTo(cx - sw / 2 - 16, sy); g.moveTo(cx + sw / 2 + 10, sy); g.lineTo(cx + sw / 2 + 84, sy); g.stroke();
+ g.restore();
+ };
+
+ const resourceIcon = (kind, x, y) => {
+ const g = drawingContext;
+ g.save();
+ if (kind === "crystal") {
+ g.beginPath(); g.moveTo(x, y - 13); g.lineTo(x + 8, y - 2); g.lineTo(x + 3, y + 12); g.lineTo(x - 5, y + 10); g.lineTo(x - 8, y - 3); g.closePath();
+ const gr = g.createLinearGradient(x - 8, y - 13, x + 8, y + 12); gr.addColorStop(0, "#d8f4ff"); gr.addColorStop(0.5, "#3aa4ff"); gr.addColorStop(1, "#0b3d9a");
+ g.fillStyle = gr; g.shadowColor = "rgba(60,170,255,0.9)"; g.shadowBlur = 10; g.fill();
+ } else if (kind === "gas") {
+ g.beginPath(); g.arc(x, y + 3, 9, 0, TAU); g.moveTo(x - 6, y - 4); g.lineTo(x, y - 14); g.lineTo(x + 6, y - 4);
+ g.fillStyle = "#3fe07a"; g.shadowColor = "rgba(60,240,120,0.9)"; g.shadowBlur = 10; g.fill();
+ g.fillStyle = "rgba(255,255,255,0.7)"; g.beginPath(); g.arc(x - 3, y + 1, 2.5, 0, TAU); g.fill();
+ } else {
+ g.beginPath(); g.moveTo(x - 10, y + 10); g.lineTo(x - 10, y - 2); g.lineTo(x, y - 12); g.lineTo(x + 10, y - 2); g.lineTo(x + 10, y + 10); g.closePath();
+ g.fillStyle = "#c8d2de"; g.shadowColor = "rgba(120,180,255,0.8)"; g.shadowBlur = 8; g.fill();
+ g.fillStyle = "#1a3a6a"; g.fillRect(x - 4, y + 1, 8, 9);
+ }
+ g.restore();
+ };
+
+ const topHud = (t, game, L) => {
+ const top = game.top ?? 44, f = game.fonts;
+ // left: menu buttons and the game clock
+ ["MENU", "ALLIES"].forEach((label, i) => {
+ const x = 14 + i * 118, y = top + 8;
+ bevelRect(x, y, 108, 34, { face: "#262d36", light: "#7d8a99", cut: 5 });
+ styledText(label, x + 54, y + 18, { font: f.logo, size: 16, style: "#b9c7d6", spacing: 2 });
+ });
+ bevelRect(254, top + 8, 104, 34, { face: "#11161c", light: "#4c5866", cut: 5 });
+ styledText(game.timer(t), 306, top + 25, { font: f.logo, size: 20, style: "#e6f0ff", glow: "rgba(60,160,255,0.7)", blur: 6 });
+ logoPlate(t, game, L.W / 2, top);
+ // right: resources
+ const res = game.resources(t);
+ let x = L.W - 22;
+ textFont(f.logo); textSize(22);
+ for (let i = res.length - 1; i >= 0; i--) {
+ const r = res[i], tw = Math.max(textWidth(r.text), 52);
+ const bx = x - tw - 44;
+ drawingContext.save(); drawingContext.fillStyle = "rgba(4,8,14,0.55)"; drawingContext.fillRect(bx - 6, top + 8, tw + 54, 34); drawingContext.restore();
+ resourceIcon(r.icon, bx + 12, top + 25);
+ styledText(r.text, bx + 32, top + 26, { font: f.logo, size: 22, style: "#e8f2ff", align: [LEFT, CENTER], glow: null });
+ x = bx - 16;
+ }
+ };
+
+ // ---- the battlefield --------------------------------------------------------------------------------------------
+
+ const groundMarker = (t, m) => {
+ const age = t - m.at;
+ if (age < 0 || age > 0.45) return;
+ const q = age / 0.45, g = drawingContext;
+ g.save();
+ g.translate(m.x, m.y); g.scale(1, 0.55);
+ if (m.kind === "attack") {
+ const r = 34 * (1 - q) + 8;
+ g.strokeStyle = `rgba(255,60,50,${1 - q})`; g.lineWidth = 4;
+ g.beginPath(); g.arc(0, 0, r, 0, TAU); g.stroke();
+ g.beginPath(); g.moveTo(-r * 0.5, -r * 0.5); g.lineTo(r * 0.5, r * 0.5); g.moveTo(r * 0.5, -r * 0.5); g.lineTo(-r * 0.5, r * 0.5); g.stroke();
+ } else {
+ const r = 10 + 30 * q;
+ g.strokeStyle = `rgba(80,255,110,${1 - q})`; g.lineWidth = 4;
+ g.beginPath(); g.arc(0, 0, r, 0, TAU); g.stroke();
+ }
+ g.restore();
+ };
+
+ const hpBar = (x, y, w, hp, colour) => {
+ const n = Math.max(4, Math.round(w / 9)), sw = w / n;
+ noStroke(); fill(0, 0, 0, 200); rect(x - w / 2 - 2, y - 2, w + 4, 9);
+ for (let i = 0; i < n; i++) {
+ const on = (i + 0.5) / n <= hp;
+ fill(...(on ? colour : [50, 20, 20])); rect(x - w / 2 + i * sw + 0.5, y, sw - 1.5, 5);
+ }
+ };
+
+ const drawUnits = (t, R, game) => {
+ const live = game.units.filter((u) => Anim.rts.alive(u, t)).map((u) => ({ u, G: Anim.rts.geom(R, game, u, t) }))
+ .sort((a, b) => a.G.y - b.G.y);
+ const target = game.target?.(t);
+ const g = drawingContext;
+ for (const { u, G } of live) {
+ // shadow
+ g.save(); g.fillStyle = "rgba(0,0,0,0.45)"; g.beginPath();
+ g.ellipse(G.x + (G.air ? 22 : 0), G.y + (G.air ? 10 : 2), G.w * (G.air ? 0.32 : 0.42), G.w * (G.air ? 0.12 : 0.16), 0, 0, TAU); g.fill(); g.restore();
+ // selection ring
+ const sel = u.team === "blue" && game.selected(t, u), tgt = u.id === target;
+ if (sel || tgt) {
+ g.save(); g.strokeStyle = sel ? "rgba(70,255,100,0.95)" : "rgba(255,60,50,0.95)"; g.lineWidth = 2.5;
+ g.beginPath(); g.ellipse(G.x, G.y + 2, G.w * 0.5, G.w * 0.2, 0, 0, TAU); g.stroke(); g.restore();
+ }
+ imageMode(CORNER);
+ image(G.img, G.x - G.w / 2, G.y - G.lift - G.h, G.w, G.h);
+ if (sel || tgt) hpBar(G.x, G.y - G.lift - G.h - 10, Math.min(G.w * 0.8, 60), u.hp ? u.hp(t) : 1, sel ? [60, 230, 80] : [235, 60, 50]);
+ }
+ };
+
+ const drawFog = (t, R, game, L, cam, top) => {
+ const c = R.fog, W = L.W, H = L.H;
+ if (c.width !== W || c.height !== H) { c.width = W; c.height = H; }
+ const g = c.getContext("2d");
+ g.globalCompositeOperation = "source-over";
+ g.clearRect(0, 0, W, H);
+ g.fillStyle = `rgba(0,0,0,${game.vision?.dark ?? 0.55})`; g.fillRect(0, top, W, H - top);
+ g.globalCompositeOperation = "destination-out";
+ const r = game.vision?.radius ?? 360;
+ for (const u of game.units) {
+ if (u.team !== "blue" || !Anim.rts.alive(u, t)) continue;
+ const [x, y] = u.at(t), sx = x - cam[0], sy = y - cam[1] + top;
+ const grad = g.createRadialGradient(sx, sy, 0, sx, sy, r);
+ grad.addColorStop(0, "rgba(0,0,0,1)"); grad.addColorStop(0.62, "rgba(0,0,0,1)"); grad.addColorStop(1, "rgba(0,0,0,0)");
+ g.fillStyle = grad; g.fillRect(sx - r, sy - r, 2 * r, 2 * r);
+ }
+ drawingContext.drawImage(c, 0, 0);
+ };
+
+ const dragBox = (t, game) => {
+ const d = game.drag?.(t);
+ if (!d) return;
+ const [x0, y0] = d.a, [x1, y1] = d.b, g = drawingContext;
+ g.save();
+ g.fillStyle = "rgba(80,255,110,0.07)"; g.fillRect(Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0));
+ g.strokeStyle = "rgba(90,255,120,0.95)"; g.lineWidth = 2; g.strokeRect(Math.min(x0, x1), Math.min(y0, y1), Math.abs(x1 - x0), Math.abs(y1 - y0));
+ g.restore();
+ };
+
+ // ---- console screens --------------------------------------------------------------------------------------------
+
+ const minimap = (t, R, game, r, cam, L) => {
+ const g = drawingContext, ms = game.map.scale ?? 0.9;
+ const mw = R.map.width * ms, mh = R.map.height * ms;
+ const k = Math.min(r.w / mw, r.h / mh), ox = r.x + (r.w - mw * k) / 2, oy = r.y + (r.h - mh * k) / 2;
+ g.save();
+ g.fillStyle = "#000"; g.fillRect(r.x, r.y, r.w, r.h);
+ g.globalAlpha = 0.85; imageMode(CORNER); image(R.map, ox, oy, mw * k, mh * k); g.globalAlpha = 1;
+ // darkened unexplored edges
+ g.fillStyle = "rgba(0,0,0,0.35)"; g.fillRect(ox, oy, mw * k * 0.18, mh * k); g.fillRect(ox + mw * k * 0.86, oy, mw * k * 0.14, mh * k);
+ for (const u of game.units) {
+ if (!Anim.rts.alive(u, t)) continue;
+ const [x, y] = u.at(t);
+ g.fillStyle = u.team === "blue" ? "#4aa0ff" : "#ff4a3a";
+ g.fillRect(ox + x * k - 2, oy + y * k - 2, 4.5, 4.5);
+ }
+ // alerts: a ring that blinks where the fighting is
+ for (const p of game.pings || []) {
+ const age = t - p.at;
+ if (age < 0 || age > 1.2) continue;
+ const q = (age % 0.6) / 0.6;
+ g.strokeStyle = `rgba(${p.color || "255,60,50"},${1 - q})`; g.lineWidth = 2;
+ g.beginPath(); g.arc(ox + p.x * k, oy + p.y * k, 4 + 14 * q, 0, TAU); g.stroke();
+ }
+ // the camera box
+ const vh = (L.top - (game.top ?? 44));
+ g.strokeStyle = "rgba(255,255,255,0.95)"; g.lineWidth = 1.5;
+ g.strokeRect(ox + cam[0] * k, oy + cam[1] * k, L.W * k, vh * k);
+ g.restore();
+ };
+
+ const portraitScreen = (t, R, game, r, frame, mode) => {
+ const g = drawingContext, img = R.portrait, pc = game.portrait || {};
+ const cover = Math.max(r.w / img.width, r.h / img.height) * (1.04 + 0.012 * Math.sin(t * 0.9));
+ const dw = img.width * cover, dh = img.height * cover;
+ const ox = r.x + (r.w - dw) / 2 + 1.5 * Math.sin(t * 0.7), oy = r.y + (r.h - dh) / 2 + 2.2 * Math.sin(t * 1.6);
+ const talking = (pc.talk || []).some(([a, b]) => t >= a && t < b);
+ g.save();
+ g.beginPath(); g.rect(r.x, r.y, r.w, r.h); g.clip();
+ if (mode !== "light") {
+ g.fillStyle = "#000"; g.fillRect(r.x, r.y, r.w, r.h);
+ imageMode(CORNER); image(img, ox, oy, dw, dh);
+ // monitor tint and scanlines inside the little screen
+ g.fillStyle = "rgba(20,60,70,0.16)"; g.fillRect(r.x, r.y, r.w, r.h);
+ g.fillStyle = "rgba(0,0,0,0.22)";
+ for (let y = r.y + ((frame * 1.5) % 3); y < r.y + r.h; y += 3) g.fillRect(r.x, y, r.w, 1);
+ if (talking) {
+ for (let i = 0; i < 4; i++) {
+ const v = P().rand("portrait-static", frame * 7 + i, 1);
+ if (v < 0.45) continue;
+ g.fillStyle = `rgba(200,255,240,${0.08 + 0.12 * P().rand("portrait-static", frame * 7 + i, 2)})`;
+ g.fillRect(r.x, r.y + P().rand("portrait-static", frame * 7 + i, 3) * r.h, r.w, 2 + 6 * v);
+ }
+ }
+ }
+ // eyes: glow that pulses, brighter while it talks (in both layers, so the halo pass blooms them)
+ const pulse = 0.55 + 0.25 * Math.sin(t * 5.2) + (talking ? 0.3 : 0);
+ g.globalCompositeOperation = "lighter";
+ for (const [ex, ey] of pc.eyes || []) P().glow(g, ox + ex * cover, oy + ey * cover, 16 * cover * 2.2, pc.eye || "#ffa040", pulse * (mode === "light" ? 0.8 : 0.5));
+ g.restore();
+ };
+
+ const infoScreen = (t, R, game, r) => {
+ const g = drawingContext;
+ g.save();
+ g.fillStyle = "#03070c"; g.fillRect(r.x, r.y, r.w, r.h);
+ const sel = game.units.filter((u) => u.team === "blue" && Anim.rts.alive(u, t) && game.selected(t, u));
+ const cols = 8, pad = 10, tw = (r.w - pad * 2) / cols - 6, th = Math.min(tw, (r.h - pad * 2) / 2 - 6);
+ sel.slice(0, 16).forEach((u, i) => {
+ const x = r.x + pad + (i % cols) * (tw + 6), y = r.y + pad + Math.floor(i / cols) * (th + 6);
+ g.fillStyle = "#0b1622"; g.fillRect(x, y, tw, th);
+ g.strokeStyle = "rgba(70,160,255,0.75)"; g.lineWidth = 1.5; g.strokeRect(x + 0.5, y + 0.5, tw - 1, th - 1);
+ const face = game.iconOf?.(u);
+ imageMode(CORNER);
+ if (face) image(face, x + 2, y + 2, tw - 4, th - 14);
+ else {
+ const img = R.units[u.kind], k = Math.min((tw - 10) / img.width, (th - 18) / img.height);
+ g.globalAlpha = 0.95; image(img, x + (tw - img.width * k) / 2, y + 4 + (th - 18 - img.height * k) / 2, img.width * k, img.height * k); g.globalAlpha = 1;
+ }
+ const hp = u.hp ? u.hp(t) : 1;
+ g.fillStyle = hp > 0.6 ? "#3ee05a" : hp > 0.3 ? "#e8d040" : "#e84a3a";
+ g.fillRect(x + 4, y + th - 10, (tw - 8) * hp, 5);
+ });
+ g.restore();
+ };
+
+ const gaugeScreen = (t, game, r) => {
+ const g = drawingContext, v = clamp01(game.gauge ? game.gauge(t) : 0.7), n = 12;
+ g.save();
+ g.fillStyle = "#02060a"; g.fillRect(r.x, r.y, r.w, r.h);
+ const sh = (r.h - 16) / n;
+ for (let i = 0; i < n; i++) {
+ const on = (i + 0.5) / n <= v, y = r.y + r.h - 8 - (i + 1) * sh;
+ g.fillStyle = on ? `rgba(70,${170 + i * 6},255,${0.75 + 0.25 * Math.sin(t * 6 - i)})` : "rgba(30,50,70,0.6)";
+ g.fillRect(r.x + 10, y + 2, r.w - 20, sh - 4);
+ }
+ g.restore();
+ };
+
+ const commandCard = (t, R, game, L, cur) => {
+ const g = drawingContext;
+ (game.commands || []).forEach((name, i) => {
+ const r = L.sockets[i];
+ if (!r || !R.icons[name]) return;
+ const press = (game.pressed || []).find((p) => p.name === name && t >= p.at && t < p.at + 0.18);
+ const hover = cur && cur.x >= r.x && cur.x < r.x + r.w && cur.y >= r.y && cur.y < r.y + r.h;
+ const d = press ? 2 : 0;
+ g.save();
+ g.fillStyle = "#000"; g.fillRect(r.x, r.y, r.w, r.h);
+ imageMode(CORNER); image(R.icons[name], r.x + 1 + d, r.y + 1 + d, r.w - 2 - d, r.h - 2 - d);
+ if (hover) { g.globalCompositeOperation = "lighter"; g.fillStyle = "rgba(90,160,255,0.16)"; g.fillRect(r.x, r.y, r.w, r.h); }
+ if (press) { g.globalCompositeOperation = "source-over"; g.fillStyle = "rgba(0,0,0,0.3)"; g.fillRect(r.x, r.y, r.w, r.h);
+ g.strokeStyle = "rgba(255,255,255,0.9)"; g.lineWidth = 2; g.strokeRect(r.x + 1, r.y + 1, r.w - 2, r.h - 2); }
+ g.restore();
+ });
+ };
+
+ // An original cursor: an angular green gauntlet-arrow, or a red reticle while an attack order waits for its target.
+ const cursor = (c) => {
+ if (!c) return;
+ const g = drawingContext;
+ g.save();
+ g.translate(c.x, c.y);
+ if (c.mode === "target") {
+ g.strokeStyle = "rgba(255,70,50,0.95)"; g.lineWidth = 2.5; g.shadowColor = "rgba(255,40,30,0.9)"; g.shadowBlur = 8;
+ g.beginPath(); g.arc(0, 0, 15, 0, TAU); g.stroke();
+ g.beginPath();
+ for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { g.moveTo(dx * 9, dy * 9); g.lineTo(dx * 23, dy * 23); }
+ g.stroke();
+ g.fillStyle = "#ffd0c0"; g.beginPath(); g.arc(0, 0, 2.2, 0, TAU); g.fill();
+ } else {
+ const s = c.down ? 0.92 : 1;
+ g.scale(s, s);
+ g.beginPath();
+ g.moveTo(0, 0); g.lineTo(5, 33); g.lineTo(12, 25); g.lineTo(20, 38); g.lineTo(26, 35); g.lineTo(18, 22); g.lineTo(29, 19); g.closePath();
+ const gr = g.createLinearGradient(0, 0, 24, 36); gr.addColorStop(0, "#d6ffcf"); gr.addColorStop(0.35, "#5ef25a"); gr.addColorStop(1, "#167a24");
+ g.shadowColor = "rgba(80,255,90,0.75)"; g.shadowBlur = 10;
+ g.fillStyle = gr; g.fill();
+ g.shadowBlur = 0; g.strokeStyle = "#03200a"; g.lineWidth = 2; g.stroke();
+ g.strokeStyle = "rgba(255,255,255,0.7)"; g.lineWidth = 1; g.beginPath(); g.moveTo(3, 5); g.lineTo(6, 26); g.stroke();
+ }
+ g.restore();
+ };
+
+ // Windows-classic title bar, like the other PC screens in the film.
+ const titleBar = (game, W) => {
+ const g = drawingContext, top = game.top ?? 44;
+ const grad = g.createLinearGradient(0, 0, W, 0);
+ grad.addColorStop(0, "#0a246a"); grad.addColorStop(1, "#a6caf0");
+ g.save(); g.fillStyle = grad; g.fillRect(0, 0, W, top); g.restore();
+ styledText(game.title, 28, 21, { font: game.fonts.uiBold, size: 28, style: "#ffffff", align: [LEFT, CENTER] });
+ ["_", "o", "x"].forEach((c, i) => {
+ const x = W - 118 + i * 36;
+ noStroke(); fill("#d4d0c8"); rect(x, 8, 30, 28);
+ stroke("#ffffff"); line(x, 8, x + 30, 8); line(x, 8, x, 36);
+ stroke("#404040"); line(x, 36, x + 30, 36); line(x + 30, 8, x + 30, 36); noStroke();
+ styledText(c, x + 15, 19, { font: game.fonts.uiBold, size: 20, style: "#000000" });
+ });
+ };
+
+ // A warning across the battlefield, blinking, in the logo face: red letters on a dark band.
+ const alertBanner = (t, game, L) => {
+ const al = game.alert?.(t);
+ if (!al || !(al.a > 0)) return;
+ const f = game.fonts, g = drawingContext, y = (game.alertY ?? (L.top * 0.52));
+ const blink = 0.72 + 0.28 * (Math.floor(t * 4) % 2 ? 1 : 0.35);
+ g.save(); g.globalAlpha = al.a;
+ const band = g.createLinearGradient(0, 0, L.W, 0);
+ band.addColorStop(0, "rgba(40,0,0,0)"); band.addColorStop(0.25, "rgba(40,0,0,0.62)"); band.addColorStop(0.75, "rgba(40,0,0,0.62)"); band.addColorStop(1, "rgba(40,0,0,0)");
+ g.fillStyle = band; g.fillRect(0, y - 44, L.W, al.sub ? 110 : 84);
+ g.globalAlpha = al.a * blink;
+ styledText(al.text, L.W / 2, y, { font: f.logo, size: 44, style: "#ff4a36", outline: "#1a0000", weight: 6, glow: "rgba(255,40,20,0.95)", blur: 22, spacing: 3 });
+ if (al.sub) styledText(al.sub, L.W / 2, y + 44, { font: f.logo, size: 22, style: "#ffc8b8", glow: "rgba(255,60,40,0.7)", blur: 8, spacing: 4 });
+ g.restore();
+ };
+
+ Anim.rts.ui = { bevelRect, styledText, logoPlate, cursor, hpBar, groundMarker, titleBar, resourceIcon };
+
+ // ---- the whole screen -------------------------------------------------------------------------------------------
+
+ Anim.rts.screen = (t, R, game, { mode = "color", frame = ANIM.frame } = {}) => {
+ const L = Anim.rts.layout(R, game);
+ const top = game.top ?? 44, cam = game.map.cam(t), ms = game.map.scale ?? 0.9;
+ const ground = (game.events || []).filter((e) => e.type === "scorch");
+ const air = (game.events || []).filter((e) => e.type !== "scorch");
+ const g = drawingContext;
+ const cur = game.cursor?.(t);
+
+ if (mode === "light") {
+ g.save(); g.beginPath(); g.rect(0, top, L.W, L.top - top + 200); g.clip();
+ push(); translate(-cam[0], -cam[1] + top);
+ P().draw(air, t, { mode: "light" });
+ pop();
+ g.restore();
+ // Nothing shines through the console: cut its frame and its screens out of the light layer.
+ g.save(); g.globalCompositeOperation = "destination-out";
+ imageMode(CORNER); image(R.console, 0, L.y0, L.W, R.slots.h * L.k);
+ g.fillStyle = "#000";
+ for (const r of [...Object.values(L.screens), ...L.sockets]) g.fillRect(r.x, r.y, r.w, r.h);
+ g.fillRect(0, 0, L.W, top + 80);
+ g.restore();
+ if (L.screens.portrait) portraitScreen(t, R, game, L.screens.portrait, frame, "light");
+ return L;
+ }
+
+ background(0);
+ g.save(); g.beginPath(); g.rect(0, top, L.W, L.H - top); g.clip();
+ push(); translate(-cam[0], -cam[1] + top);
+ g.filter = game.map.filter || "brightness(1.22) contrast(1.06) saturate(1.08)";
+ imageMode(CORNER); image(R.map, 0, 0, R.map.width * ms, R.map.height * ms);
+ g.filter = "none";
+ P().draw(ground, t);
+ for (const m of game.markers || []) groundMarker(t, m);
+ drawUnits(t, R, game);
+ pop();
+ drawFog(t, R, game, L, cam, top);
+ push(); translate(-cam[0], -cam[1] + top);
+ P().draw(air, t);
+ pop();
+ g.restore();
+
+ dragBox(t, game);
+ alertBanner(t, game, L);
+ topHud(t, game, L);
+
+ const S = L.screens;
+ if (S.minimap) minimap(t, R, game, S.minimap, cam, L);
+ if (S.portrait) portraitScreen(t, R, game, S.portrait, frame, "color");
+ if (S.info) infoScreen(t, R, game, S.info);
+ if (S.gauge) gaugeScreen(t, game, S.gauge);
+ commandCard(t, R, game, L, cur);
+ imageMode(CORNER); image(R.console, 0, L.y0, L.W, R.slots.h * L.k);
+
+ cursor(cur);
+ titleBar(game, L.W);
+ return L;
+ };
+
+ // World point -> screen point for the current camera (to aim the cursor at a unit).
+ Anim.rts.toScreen = (game, t, [x, y]) => {
+ const cam = game.map.cam(t);
+ return [x - cam[0], y - cam[1] + (game.top ?? 44)];
+ };
+})();
diff --git a/skills/make-an-anime/scripts/tools/p5/render.mjs b/skills/make-an-anime/scripts/tools/p5/render.mjs
index 1e20c14..b7d118d 100644
--- a/skills/make-an-anime/scripts/tools/p5/render.mjs
+++ b/skills/make-an-anime/scripts/tools/p5/render.mjs
@@ -15,7 +15,7 @@ import { fileURLToPath } from "node:url";
import puppeteer from "puppeteer-core";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
-const LIB = ["core", "time", "fx", "type", "paper", "riso", "screens", "battle"];
+const LIB = ["core", "time", "fx", "type", "paper", "riso", "screens", "battle", "particles", "rts", "mission", "court"];
const CHROME = [
process.env.CHROME_PATH,
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
diff --git a/skills/make-an-anime/scripts/tools/python/cut_sheets.py b/skills/make-an-anime/scripts/tools/python/cut_sheets.py
new file mode 100644
index 0000000..895401b
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/python/cut_sheets.py
@@ -0,0 +1,249 @@
+#!/usr/bin/env python3
+"""Cut generated game-art sheets into transparent PNGs a p5 overlay loads, and measure a HUD frame's empty screens.
+
+Run with the project's venv and -I (the sheets are generated files, treat them as data):
+
+ .venv/bin/python -I tools/python/cut_sheets.py sprites <sheet.png> <out_dir> --names a,b,c,... [--key alpha|magenta|black]
+ Sprites laid out in rows with clear gaps (a unit sheet). Rows are found from the alpha (or keyed) coverage along y,
+ then sprites inside each row along x, so the order is row by row, left to right. Each sprite is trimmed with a
+ small margin and saved as <out_dir>/<name>.png. Specks smaller than --min-px pixels per row/column are ignored.
+
+ .venv/bin/python -I tools/python/cut_sheets.py grid <sheet.png> <out_dir> --names a,b,... [--key black] [--inset 0]
+ Icons on a flat background in a grid: the same row/column search, each tile saved square, at --size px (128).
+
+ .venv/bin/python -I tools/python/cut_sheets.py frame <console.png> <out.png> <slots.json> [--key alpha|magenta]
+ A HUD frame with a keyed-out top: writes the transparent frame (its flat-black screens made transparent too,
+ so whatever p5 draws under the frame shows through them) and slots.json, the screens' rectangles in the frame's
+ own pixels, largest first, as {"w", "h", "slots": [[x, y, w, h], ...]}.
+
+ .venv/bin/python -I tools/python/cut_sheets.py fit <image.png> <out.png> --width W [--crop x,y,w,h]
+ An opaque picture (terrain, portrait): optional crop, then resize to W wide.
+
+Prints a JSON summary on stdout. Needs Pillow and numpy only.
+"""
+import argparse
+import json
+import os
+import sys
+import re
+from collections import deque
+
+import numpy as np
+from PIL import Image
+
+
+def load_rgba(path):
+ return np.asarray(Image.open(path).convert("RGBA")).astype(np.int16)
+
+
+def coverage(a, key):
+ """Boolean mask of 'something here' for a sheet, by its keying mode."""
+ if key == "alpha":
+ return a[..., 3] > 24
+ r, g, b = a[..., 0], a[..., 1], a[..., 2]
+ if key == "magenta":
+ return (a[..., 3] > 24) & ~((r > 170) & (b > 170) & (g < 110))
+ if key == "black":
+ return (a[..., 3] > 24) & ((r + g + b) > 60)
+ raise SystemExit(f"unknown key {key}")
+
+
+def key_alpha(a, key):
+ """RGBA uint8 with the background made transparent (soft edge for magenta)."""
+ out = a.copy()
+ if key == "magenta":
+ r, g, b = a[..., 0], a[..., 1], a[..., 2]
+ dist = np.minimum(r, b) - g # high on magenta
+ alpha = np.clip((140 - dist) * 255 / 90, 0, 255)
+ out[..., 3] = np.minimum(a[..., 3], alpha)
+ spill = (out[..., 3] < 255) & (out[..., 3] > 0) # pull the magenta spill out of the soft edge
+ avg = (r + b) // 2
+ out[..., 0] = np.where(spill, np.minimum(r, g + 20), r)
+ out[..., 2] = np.where(spill, np.minimum(b, g + 20), b)
+ del avg
+ elif key == "black":
+ lum = a[..., :3].max(axis=2)
+ out[..., 3] = np.minimum(a[..., 3], np.clip((lum - 8) * 255 / 40, 0, 255))
+ return np.clip(out, 0, 255).astype(np.uint8)
+
+
+def runs(profile, min_px, min_len, gap=6):
+ """[(start, end)) spans where profile >= min_px, merging gaps shorter than `gap`, dropping spans shorter than min_len."""
+ on = profile >= min_px
+ spans, start, last = [], None, None
+ for i, v in enumerate(on):
+ if v:
+ if start is None:
+ start = i
+ elif last is not None and i - last > gap:
+ spans.append((start, last + 1))
+ start = i
+ last = i
+ if start is not None:
+ spans.append((start, last + 1))
+ return [(s, e) for s, e in spans if e - s >= min_len]
+
+
+def find_boxes(mask, min_px, min_len, gap):
+ boxes = []
+ for y0, y1 in runs(mask.sum(axis=1), min_px, min_len, gap):
+ band = mask[y0:y1]
+ for x0, x1 in runs(band.sum(axis=0), min_px, min_len, gap):
+ sub = band[:, x0:x1]
+ ys = np.where(sub.sum(axis=1) >= 1)[0]
+ boxes.append((x0, y0 + ys[0], x1 - x0, ys[-1] - ys[0] + 1))
+ return boxes
+
+
+def cmd_sprites(args):
+ a = load_rgba(args.sheet)
+ mask = coverage(a, args.key)
+ boxes = find_boxes(mask, args.min_px, args.min_len, args.gap)
+ names = args.names.split(",")
+ if len(boxes) != len(names):
+ raise SystemExit(f"found {len(boxes)} sprites, expected {len(names)}: {boxes}")
+ rgba = key_alpha(a, args.key)
+ os.makedirs(args.out, exist_ok=True)
+ out = {}
+ m = args.margin
+ for name, (x, y, w, h) in zip(names, boxes):
+ x0, y0 = max(0, x - m), max(0, y - m)
+ x1, y1 = min(a.shape[1], x + w + m), min(a.shape[0], y + h + m)
+ crop = rgba[y0:y1, x0:x1].copy()
+ if args.key != "alpha":
+ crop[..., 3] = np.where(coverage(a[y0:y1, x0:x1], args.key), crop[..., 3], 0)
+ Image.fromarray(crop, "RGBA").save(os.path.join(args.out, f"{name}.png"))
+ out[name] = {"box": [int(x0), int(y0), int(x1 - x0), int(y1 - y0)]}
+ print(json.dumps({"sprites": out}))
+
+
+def cmd_grid(args):
+ a = load_rgba(args.sheet)
+ mask = coverage(a, args.key)
+ boxes = find_boxes(mask, args.min_px, args.min_len, args.gap)
+ names = args.names.split(",")
+ if len(boxes) != len(names):
+ raise SystemExit(f"found {len(boxes)} tiles, expected {len(names)}: {boxes}")
+ os.makedirs(args.out, exist_ok=True)
+ out = {}
+ for name, (x, y, w, h) in zip(names, boxes):
+ s = max(w, h)
+ cx, cy = x + w // 2, y + h // 2
+ i = args.inset
+ if 2 * i >= s:
+ raise SystemExit("inset removes the entire tile")
+ tile = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8), "RGBA").crop((cx - s // 2 + i, cy - s // 2 + i, cx + s // 2 - i, cy + s // 2 - i))
+ tile.resize((args.size, args.size), Image.LANCZOS).save(os.path.join(args.out, f"{name}.png"))
+ out[name] = {"box": [int(x), int(y), int(w), int(h)]}
+ print(json.dumps({"tiles": out}))
+
+
+def label(mask):
+ """4-connected components of a small boolean mask -> list of (x, y, w, h, area)."""
+ h, w = mask.shape
+ seen = np.zeros_like(mask, dtype=bool)
+ comps = []
+ for y in range(h):
+ row = mask[y]
+ for x in np.where(row & ~seen[y])[0]:
+ if seen[y, x]:
+ continue
+ q = deque([(y, x)])
+ seen[y, x] = True
+ x0 = x1 = x
+ y0 = y1 = y
+ n = 0
+ while q:
+ cy, cx = q.popleft()
+ n += 1
+ x0, x1, y0, y1 = min(x0, cx), max(x1, cx), min(y0, cy), max(y1, cy)
+ for ny, nx in ((cy + 1, cx), (cy - 1, cx), (cy, cx + 1), (cy, cx - 1)):
+ if 0 <= ny < h and 0 <= nx < w and mask[ny, nx] and not seen[ny, nx]:
+ seen[ny, nx] = True
+ q.append((ny, nx))
+ comps.append((x0, y0, x1 - x0 + 1, y1 - y0 + 1, n))
+ return comps
+
+
+def cmd_frame(args):
+ a = load_rgba(args.console)
+ rgba = key_alpha(a, args.key) if args.key != "alpha" else np.clip(a, 0, 255).astype(np.uint8)
+ solid = rgba[..., 3] > 200
+ dark = solid & (a[..., :3].max(axis=2) < args.dark)
+ f = args.scale
+ small = dark[::f, ::f]
+ comps = [c for c in label(small) if c[4] >= args.min_area and c[4] >= 0.8 * c[2] * c[3]] # filled, box-like
+ comps.sort(key=lambda c: -c[4])
+ slots = [[int(x * f), int(y * f), int(w * f), int(h * f)] for x, y, w, h, _ in comps]
+ # Clear the screens so the layer under the frame shows through them.
+ hole = np.zeros(dark.shape, dtype=bool)
+ for x, y, w, h in slots:
+ hole[y:y + h, x:x + w] = True
+ rgba = rgba.copy()
+ rgba[..., 3] = np.where(hole & dark, 0, rgba[..., 3])
+ Image.fromarray(rgba, "RGBA").save(args.out)
+ top = int(np.where(solid.any(axis=1))[0][0]) if solid.any() else 0
+ json.dump({"w": int(a.shape[1]), "h": int(a.shape[0]), "top": top, "slots": slots}, open(args.slots, "w"), indent=1)
+ print(json.dumps({"frame": args.out, "slots": len(slots), "top": top}))
+
+
+def cmd_fit(args):
+ im = Image.open(args.image).convert("RGB")
+ if args.crop:
+ x, y, w, h = [int(v) for v in args.crop.split(",")]
+ im = im.crop((x, y, x + w, y + h))
+ W = args.width
+ im = im.resize((W, round(im.height * W / im.width)), Image.LANCZOS)
+ im.save(args.out)
+ print(json.dumps({"fit": args.out, "size": im.size}))
+
+
+def main():
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = p.add_subparsers(dest="cmd", required=True)
+ for name in ("sprites", "grid"):
+ s = sub.add_parser(name)
+ s.add_argument("sheet"); s.add_argument("out")
+ s.add_argument("--names", required=True)
+ s.add_argument("--key", default="alpha" if name == "sprites" else "black")
+ s.add_argument("--min-px", type=int, default=6)
+ s.add_argument("--min-len", type=int, default=40)
+ s.add_argument("--gap", type=int, default=24)
+ s.add_argument("--margin", type=int, default=6)
+ s.add_argument("--size", type=int, default=128)
+ s.add_argument("--inset", type=int, default=0)
+ s = sub.add_parser("frame")
+ s.add_argument("console"); s.add_argument("out"); s.add_argument("slots")
+ s.add_argument("--key", default="alpha")
+ s.add_argument("--dark", type=int, default=22)
+ s.add_argument("--scale", type=int, default=4)
+ s.add_argument("--min-area", type=int, default=300)
+ s = sub.add_parser("fit")
+ s.add_argument("image"); s.add_argument("out")
+ s.add_argument("--width", type=int, required=True)
+ s.add_argument("--crop")
+ args = p.parse_args()
+ if args.cmd in ("sprites", "grid"):
+ names = args.names.split(",")
+ if len(names) != len(set(names)) or any(not re.fullmatch(r"[A-Za-z0-9_-]+", n) for n in names):
+ p.error("names must be unique plain identifiers")
+ if min(args.min_px, args.min_len, args.size) <= 0 or min(args.gap, args.margin, args.inset) < 0:
+ p.error("invalid dimensions or detection thresholds")
+ outputs = [os.path.join(args.out, f"{n}.png") for n in names]
+ source = args.sheet
+ else:
+ source = args.console if args.cmd == "frame" else args.image
+ outputs = [args.out] + ([args.slots] if args.cmd == "frame" else [])
+ if args.cmd == "frame" and min(args.scale, args.min_area) <= 0:
+ p.error("scale and min-area must be positive")
+ if args.cmd == "fit" and args.width <= 0:
+ p.error("width must be positive")
+ if any(os.path.realpath(o) == os.path.realpath(source) for o in outputs):
+ p.error("outputs must not overwrite the source sheet")
+ for o in outputs:
+ os.makedirs(os.path.dirname(os.path.abspath(o)), exist_ok=True)
+ {"sprites": cmd_sprites, "grid": cmd_grid, "frame": cmd_frame, "fit": cmd_fit}[args.cmd](args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/make-an-anime/scripts/tools/python/face_collage.py b/skills/make-an-anime/scripts/tools/python/face_collage.py
new file mode 100644
index 0000000..24b06b2
--- /dev/null
+++ b/skills/make-an-anime/scripts/tools/python/face_collage.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+"""Game unit icons of real characters, in one image edit: crop each face from its character sheet, lay the faces out in
+a clean grid collage (no text), send the collage to the image-edit model with a prompt that redraws every cell as a
+super-deformed (chibi) unit icon of the same person in the same cell, then cut the cells back out.
+
+ .venv/bin/python -I tools/python/face_collage.py build <spec.json> <out.png> [--preview faces.jpg]
+ .venv/bin/python -I tools/python/face_collage.py cut <edited.png> <spec.json> <out_dir> [--size 256]
+
+spec.json:
+ {"cols": 4, "rows": 2, "cell": [460, 520], "gap": 40, "margin": 60, "background": "#d8d8d8", "aspect": 1.7778,
+ "faces": [{"name": "pilot", "sheet": "output/char-pilot-v1/01_ref_base.png", "box": [cx, cy, w], "scale": 4}, ...]}
+ box is the face's centre and width in the sheet's pixels divided by `scale` (measure on a downscaled copy and give
+ the copy's factor); the crop is w wide and 1.2 w tall, so hair and chin fit. Cells are filled row by row.
+
+`cut` does not trust the model to keep the exact pixel grid: it finds the icons by projection (anything that differs
+from the background colour), expects cols x rows of them in reading order, and saves each one square (centred, padded with
+transparency), at --size. If the count is off, it stops; --grid-fallback explicitly enables a measured content-grid fallback for review.
+Needs Pillow and numpy only. Prints a JSON summary.
+"""
+import argparse
+import json
+import os
+import sys
+import re
+
+import numpy as np
+from PIL import Image
+
+
+def hex_rgb(h):
+ h = h.lstrip("#")
+ return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
+
+
+def read_spec(path):
+ spec = json.load(open(path))
+ faces = spec["faces"]
+ names = [f["name"] for f in faces]
+ if not names or len(names) != len(set(names)) or any(not re.fullmatch(r"[A-Za-z0-9_-]+", n) for n in names):
+ raise SystemExit("face names must be unique plain identifiers")
+ if min(spec["cols"], spec["rows"], *spec["cell"]) <= 0 or len(faces) > spec["cols"] * spec["rows"]:
+ raise SystemExit("invalid collage dimensions or too many faces")
+ return spec
+
+
+def layout(spec):
+ cw, ch = spec["cell"]
+ g, m, cols, rows = spec.get("gap", 40), spec.get("margin", 60), spec["cols"], spec["rows"]
+ W, H = 2 * m + cols * cw + (cols - 1) * g, 2 * m + rows * ch + (rows - 1) * g
+ # Pad to the edit model's output shape (16:9 by default), grid centred, so it doesn't re-lay the cells to fit.
+ ar = spec.get("aspect", 16 / 9)
+ ox = oy = 0
+ if W / H < ar:
+ ox = (round(H * ar) - W) // 2; W = round(H * ar)
+ else:
+ oy = (round(W / ar) - H) // 2; H = round(W / ar)
+ cells = [(ox + m + c * (cw + g), oy + m + r * (ch + g), cw, ch) for r in range(rows) for c in range(cols)]
+ return W, H, cells
+
+
+def cmd_build(a):
+ spec = read_spec(a.spec)
+ W, H, cells = layout(spec)
+ bg = hex_rgb(spec.get("background", "#d8d8d8"))
+ out = Image.new("RGB", (W, H), bg)
+ for face, (x, y, w, h) in zip(spec["faces"], cells):
+ im = Image.open(face["sheet"]).convert("RGB")
+ s = face.get("scale", 1)
+ cx, cy, fw = [v * s for v in face["box"]]
+ fh = fw * h / w
+ crop = im.crop((round(cx - fw / 2), round(cy - fh / 2), round(cx + fw / 2), round(cy + fh / 2)))
+ out.paste(crop.resize((w, h), Image.LANCZOS), (x, y))
+ out.save(a.out)
+ if a.preview:
+ out.resize((W // 2, H // 2)).save(a.preview)
+ print(json.dumps({"collage": a.out, "size": [W, H], "cells": len(spec["faces"])}))
+
+
+def runs(profile, thresh, min_len):
+ on = profile >= thresh
+ spans, start = [], None
+ for i, v in enumerate(list(on) + [False]):
+ if v and start is None:
+ start = i
+ elif not v and start is not None:
+ if i - start >= min_len:
+ spans.append((start, i))
+ start = None
+ return spans
+
+
+def cmd_cut(a):
+ spec = read_spec(a.spec)
+ im = Image.open(a.edited).convert("RGBA")
+ arr = np.asarray(im).astype(np.int16)
+ # The background: the median of the image's border pixels.
+ border = np.concatenate([arr[:6].reshape(-1, 4), arr[-6:].reshape(-1, 4), arr[:, :6].reshape(-1, 4), arr[:, -6:].reshape(-1, 4)])
+ bg = np.median(border[:, :3], axis=0)
+ diff = np.abs(arr[..., :3] - bg).sum(axis=2)
+ mask = (diff > a.tol) & (arr[..., 3] > 24)
+ cols, rows, n = spec["cols"], spec["rows"], len(spec["faces"])
+ H, W = mask.shape
+ boxes = []
+ for y0, y1 in runs(mask.sum(axis=1), max(4, W * 0.02), H // (rows * 4)):
+ band = mask[y0:y1]
+ for x0, x1 in runs(band.sum(axis=0), max(4, (y1 - y0) * 0.02), W // (cols * 4)):
+ ys = np.where(band[:, x0:x1].any(axis=1))[0]
+ boxes.append((x0, y0 + ys[0], x1 - x0, ys[-1] - ys[0] + 1))
+ how = "found"
+ if len(boxes) != n:
+ if not a.grid_fallback:
+ raise SystemExit(f"found {len(boxes)} icons, expected {n}; inspect the sheet, or explicitly enable grid fallback")
+ if not mask.any():
+ raise SystemExit("edited sheet contains no detectable icons")
+ # Plates that nearly touch defeat the projection: split the content's bounding box evenly instead (the model
+ # spaces the grid evenly even when it moves it), then trim each cell to what is in it.
+ found = len(boxes)
+ ys, xs = np.where(mask.any(axis=1))[0], np.where(mask.any(axis=0))[0]
+ X0, X1, Y0, Y1 = xs[0], xs[-1] + 1, ys[0], ys[-1] + 1
+ cw, ch = (X1 - X0) / cols, (Y1 - Y0) / rows
+ boxes = []
+ for i in range(n):
+ x0, y0 = round(X0 + (i % cols) * cw), round(Y0 + (i // cols) * ch)
+ x1, y1 = round(x0 + cw), round(y0 + ch)
+ sub = mask[y0:y1, x0:x1]
+ yy, xx = np.where(sub.any(axis=1))[0], np.where(sub.any(axis=0))[0]
+ if not len(xx) or not len(yy):
+ raise SystemExit("grid fallback found an empty cell; inspect the edited sheet")
+ boxes.append((x0 + xx[0], y0 + yy[0], xx[-1] - xx[0] + 1, yy[-1] - yy[0] + 1))
+ how = f"even split of the content box (projection found {found}, expected {n})"
+ os.makedirs(a.out, exist_ok=True)
+ res = {}
+ for face, (x, y, w, h) in zip(spec["faces"], boxes):
+ tile = im.crop((x, y, x + w, y + h))
+ # Background-coloured pixels round the icon go transparent, so a round or chamfered plate keeps its shape.
+ t = np.asarray(tile).copy()
+ d = np.abs(t[..., :3].astype(np.int16) - bg).sum(axis=2)
+ t[..., 3] = np.where(d > a.tol, t[..., 3], 0)
+ tile = Image.fromarray(t, "RGBA")
+ s = max(w, h)
+ sq = Image.new("RGBA", (s, s), (0, 0, 0, 0))
+ sq.paste(tile, ((s - w) // 2, (s - h) // 2))
+ sq.resize((a.size, a.size), Image.LANCZOS).save(os.path.join(a.out, f"{face['name']}.png"))
+ res[face["name"]] = [int(x), int(y), int(w), int(h)]
+ print(json.dumps({"icons": res, "how": how, "background": [int(v) for v in bg]}))
+
+
+def main():
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = p.add_subparsers(dest="cmd", required=True)
+ b = sub.add_parser("build"); b.add_argument("spec"); b.add_argument("out"); b.add_argument("--preview")
+ c = sub.add_parser("cut"); c.add_argument("edited"); c.add_argument("spec"); c.add_argument("out")
+ c.add_argument("--size", type=int, default=256); c.add_argument("--tol", type=int, default=60)
+ c.add_argument("--grid-fallback", action="store_true")
+ a = p.parse_args()
+ spec = read_spec(a.spec)
+ sources = [a.spec] + ([f["sheet"] for f in spec["faces"]] if a.cmd == "build" else [a.edited])
+ outputs = [a.out] + ([a.preview] if a.preview else []) if a.cmd == "build" else [os.path.join(a.out, f["name"] + ".png") for f in spec["faces"]]
+ if any(os.path.realpath(o) == os.path.realpath(i) for o in outputs for i in sources):
+ p.error("outputs must not overwrite source files")
+ if a.cmd == "cut" and a.size <= 0:
+ p.error("size must be positive")
+ for o in outputs:
+ os.makedirs(os.path.dirname(os.path.abspath(o)), exist_ok=True)
+ {"build": cmd_build, "cut": cmd_cut}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Effects.swift b/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Effects.swift
index 8909943..64af3b1 100644
--- a/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Effects.swift
+++ b/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Effects.swift
@@ -20,6 +20,9 @@ import Foundation
// glitch span amt 1.0, fade 1: slices shoved sideways, RGB split, noise bars, flickering frame to frame
// tv span amt 1.0, fade 6, grain 0.09 (0 = none): scanlines, grain, soft focus, colour fade, vignette, rolling bar, line jitter
// grain span amt 0.25, fade 6: film grain on its own (soft-light, so flat paper takes less of it than midtones)
+// halo span amt 1.2, radius 12 (px), fade 1: blooms the --lights layer before it is screen-blended, so only what p5 drew
+// as light (laser cores, muzzle flashes, explosion flashes) glows; a tight blur plus a wide one 3.5x larger.
+// Also a light cue in lib/media/vfx.rb, so the light layer is rendered on its frames.
final class Effects {
let extent: CGRect
var w: CGFloat { extent.width }
@@ -35,6 +38,7 @@ final class Effects {
var bloom = 0.0, bloomRadius = 18.0
var flash = 0.0, flashColor = CIColor(red: 1, green: 0.98, blue: 0.94)
var dark = 0.0, rgb = 0.0, glitch = 0.0, tv = 0.0, tvGrain = 0.09, grain = 0.0
+ var halo = 0.0, haloRadius = 12.0
var seed = 0
}
@@ -114,6 +118,9 @@ final class Effects {
s.tvGrain = c.grain ?? 0.09
case "grain":
s.grain = max(s.grain, (c.amt ?? 0.25) * c.env(frame, defaultShape: "span"))
+ case "halo":
+ s.halo = max(s.halo, (c.amt ?? 1.2) * c.env(frame, defaultShape: "span"))
+ s.haloRadius = c.radius ?? 12
default:
continue
}
@@ -172,7 +179,8 @@ final class Effects {
e.ev = Float(0.85 * s.flash)
img = over(solid(s.flashColor, alpha: min(0.7, 0.36 * s.flash)), e.outputImage!)
}
- if let lights {
+ if var lights {
+ if s.halo > 0.01 { lights = halo(lights, amount: s.halo, radius: s.haloRadius) }
let f = CIFilter.screenBlendMode()
f.inputImage = lights
f.backgroundImage = img
@@ -190,6 +198,32 @@ final class Effects {
// MARK: effects
+ // Bloom on the light layer only: the layer itself, plus a tight and a wide gaussian blur of it scaled by `amount`,
+ // added together and clamped to 0...1 (screen blend misbehaves above 1). Transparent pixels stay transparent.
+ func halo(_ light: CIImage, amount a: Double, radius r: Double) -> CIImage {
+ let base = light.cropped(to: extent)
+ func blurred(_ sigma: Double, _ gain: Double) -> CIImage {
+ let b = CIFilter.gaussianBlur()
+ b.inputImage = base.clampedToExtent()
+ b.radius = Float(sigma)
+ let m = CIFilter.colorMatrix()
+ m.inputImage = b.outputImage!.cropped(to: extent)
+ let g = CGFloat(gain)
+ m.rVector = CIVector(x: g, y: 0, z: 0, w: 0)
+ m.gVector = CIVector(x: 0, y: g, z: 0, w: 0)
+ m.bVector = CIVector(x: 0, y: 0, z: g, w: 0)
+ m.aVector = CIVector(x: 0, y: 0, z: 0, w: g)
+ return m.outputImage!.cropped(to: extent)
+ }
+ let sum = blurred(r, a).applyingFilter("CIAdditionCompositing", parameters: [kCIInputBackgroundImageKey: base])
+ .applyingFilter("CIAdditionCompositing", parameters: [kCIInputBackgroundImageKey: blurred(r * 3.5, a * 0.6)])
+ let clamp = CIFilter.colorClamp()
+ clamp.inputImage = sum.cropped(to: extent)
+ clamp.minComponents = CIVector(x: 0, y: 0, z: 0, w: 0)
+ clamp.maxComponents = CIVector(x: 1, y: 1, z: 1, w: 1)
+ return clamp.outputImage!.cropped(to: extent)
+ }
+
// Sharp centre, blur growing toward the edges and corners (lens edge / dreamy focus).
func edgeBlur(_ img: CIImage, radius: Double) -> CIImage {
let g = CIFilter.radialGradient()