A Claude Code plugin that turns a story into a finished anime
Ruby
Add the p5, Python and Swift renderers
Francesco 'makevoid' Canessa8b6ca16047a6
diff --git a/skills/make-an-anime/scripts/tools/p5/examples/lights.js b/skills/make-an-anime/scripts/tools/p5/examples/lights.jsnew file mode 100644index 0000000..213c1d0--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/examples/lights.js@@ -0,0 +1,137 @@+// Reusable light layer: the post-processing effects that are drawn light rather than image processing: light leaks, a lens flare,+// sparkle glints. Rendered only on the frames where a light cue is live (rake vfx:*), then screen-blended over the finished video by+// vfx/ (mvfx --lights), so black / transparent adds nothing and colours only brighten, like real light on film.+//+// Anim.data("vfx") is the resolved cue list (the project VFX cues.yml -> cues.json); frame numbers are the whole+// song's 24fps grid, so frame i here is frame i of the preview. The envelope matches Cue.env in vfx/Sources/mvfx/Cues.swift.+//+// leak span amt 0.6, color #ff7a2f, x 1 (side it drifts in from: 0 left, 1 right), fade 8+// flare hit amt 1, x/y (0..1 from top-left), color #ffe2c4+// glints hit amt 1, x/y centre, radius 0.14 (of the width), seed, n 12, size 1; sustain: true = one steady glint on x/y that+// pops in, shimmers and is gone by the cue's end (mv2: the sticker corner on the last frame)++const INK = { orange: "#ff7a2f", pink: "#ff5fae", mustard: "#ffc24a", cream: "#fff3dc", white: "#ffffff" };+const W = 1928, H = 1076;++const env = (c, frame, shape = "hit", curve = 2.2) => {+ const pre = c.pre || 0;+ if (frame < c.f - pre || frame >= c.f + c.dur) return 0;+ if (frame < c.f) { const q = (frame - (c.f - pre) + 1) / (pre + 1); return q * q; }+ const t = frame - c.f;+ if ((c.shape || shape) === "span") {+ const fd = Math.max(c.fade ?? 8, 1);+ return Math.min(1, (t + 1) / fd, (c.dur - t) / fd);+ }+ return Math.pow(1 - t / Math.max(c.dur, 1), curve);+};++// rgba() of a hex colour at alpha a.+const rgba = (hex, a) => {+ const v = parseInt(hex.slice(1), 16);+ return `rgba(${(v >> 16) & 255},${(v >> 8) & 255},${v & 255},${Math.max(0, Math.min(1, a)).toFixed(4)})`;+};++// Soft radial blob of light (canvas gradient, additive).+const blob = (x, y, r, hex, a, { sx = 1, sy = 1 } = {}) => {+ if (a <= 0.002 || r <= 0) return;+ const g = drawingContext;+ g.save();+ g.translate(x, y);+ g.scale(sx, sy);+ const grad = g.createRadialGradient(0, 0, 0, 0, 0, r);+ grad.addColorStop(0, rgba(hex, a));+ grad.addColorStop(0.45, rgba(hex, a * 0.45));+ grad.addColorStop(1, rgba(hex, 0));+ g.fillStyle = grad;+ g.fillRect(-r, -r, 2 * r, 2 * r);+ g.restore();+};++const FX = {+ // Film light leak: warm blobs drifting in from one side, breathing slowly; a second tint and a faint vertical burn streak.+ leak(c, frame) {+ const e = env(c, frame, "span") * (c.amt ?? 0.6);+ if (e <= 0) return;+ const age = (frame - c.f) / 24;+ const side = c.x ?? 1;+ const dir = side > 0.5 ? -1 : 1;+ const x0 = side * W;+ const main = c.color || INK.orange;+ const breathe = 0.85 + 0.15 * Math.sin(age * 2.1 + c.f);+ blob(x0 + dir * (120 + age * 90), H * (0.35 + 0.08 * Math.sin(age * 0.9)), H * 0.95, main, 0.75 * e * breathe, { sx: 0.8, sy: 1.25 });+ blob(x0 + dir * (40 + age * 60), H * 0.85, H * 0.6, INK.pink, 0.45 * e, { sx: 1.2, sy: 0.8 });+ blob(x0 + dir * (260 + age * 140), H * 0.15, H * 0.45, INK.mustard, 0.35 * e * (1.1 - breathe * 0.3));+ blob(x0 + dir * (30 + age * 40), H * 0.5, H * 0.9, INK.cream, 0.3 * e, { sx: 0.12, sy: 1.1 });+ },++ // Lens flare on a bright point: hot core, a long anamorphic streak, a slow four-ray star, ghosts mirrored through the centre.+ flare(c, frame) {+ const e = env(c, frame, "hit", 1.6) * (c.amt ?? 1);+ if (e <= 0) return;+ const age = Math.max(0, frame - c.f);+ const x = (c.x ?? 0.5) * W, y = (c.y ?? 0.5) * H;+ const col = c.color || "#ffe2c4";+ const grow = 1 + 0.25 * Anim.ease.outCubic(Math.min(1, age / 8));+ blob(x, y, 150 * grow, col, 0.9 * e);+ blob(x, y, 45 * grow, INK.white, 1.0 * e);+ blob(x, y, W * 0.48 * grow, INK.cream, 0.55 * e, { sx: 1, sy: 0.018 }); // anamorphic streak+ blob(x, y, W * 0.3 * grow, INK.pink, 0.35 * e, { sx: 1, sy: 0.05 });+ push(); // four long rays, turning slowly+ translate(x, y);+ rotate(0.35 + age * 0.02);+ for (let i = 0; i < 4; i++) {+ rotate(HALF_PI);+ blob(0, 0, 320 * grow, INK.white, 0.5 * e, { sx: 1, sy: 0.03 });+ }+ pop();+ const cx = W / 2, cy = H / 2; // ghosts along the line through the centre+ [[-0.35, 38, INK.mustard], [-0.8, 70, INK.pink], [-1.25, 26, INK.cream], [0.45, 20, INK.orange]].forEach(([k, r, h]) => {+ blob(cx + (cx - x) * -k, cy + (cy - y) * -k, r * grow, h, 0.35 * e);+ });+ },++ // A burst of four-point twinkles around a spot, each popping in on its own frame and shrinking out.+ // n (12) twinkles, size (1) scales them. sustain: true makes one steady glint instead: the first twinkle sits exactly on x/y,+ // all of them pop in over 3 frames, shimmer, and shrink out over the cue's last frames, gone by its end (to end on a last frame).+ glints(c, frame) {+ const e = (c.amt ?? 1);+ if (frame < c.f || frame >= c.f + c.dur) return;+ const rnd = Anim.rng(c.seed ?? c.f);+ const x = (c.x ?? 0.5) * W, y = (c.y ?? 0.5) * H, R = (c.radius ?? 0.14) * W;+ const n = c.n ?? 12, k = c.size ?? 1;+ for (let i = 0; i < n; i++) {+ const a = rnd() * TWO_PI, d = c.sustain && i === 0 ? 0 : Math.sqrt(rnd()) * R;+ const start = Math.floor(rnd() * c.dur * 0.55), life = 6 + Math.floor(rnd() * 8);+ const size = (26 + rnd() * 44) * k;+ const pick = [INK.white, INK.cream, INK.pink, INK.mustard][Math.floor(rnd() * 4)];+ const col = c.sustain && i === 0 ? INK.white : pick;+ let s;+ if (c.sustain) {+ const age = frame - c.f;+ const env = Math.min(1, (age + 1) / 3) * Math.pow(Math.max(0, Math.min(1, (c.dur - age) / 5)), 2);+ s = size * (i === 0 ? 1 : 0.45) * env * (0.85 + 0.15 * Math.sin(age * 1.7 + i * 2)) * e;+ } else {+ const p = (frame - c.f - start) / life;+ if (p < 0 || p >= 1) continue;+ s = size * Math.sin(Math.PI * p) * e;+ }+ if (s <= 0) continue;+ const gx = x + Math.cos(a) * d, gy = y + Math.sin(a) * d * 0.7;+ blob(gx, gy, s * 2.6, col, 0.6 * e);+ Anim.twinkle(gx, gy, s, col);+ }+ }+};++Anim.sketch({+ load() {+ this.cues = Anim.data("vfx").cues.filter((c) => FX[c.fx]);+ },+ draw(t, frame) {+ push(); scale(width / W, height / H);+ drawingContext.globalCompositeOperation = "lighter";+ for (const c of this.cues) FX[c.fx](c, frame);+ drawingContext.globalCompositeOperation = "source-over";+ pop();+ }+});diff --git a/skills/make-an-anime/scripts/tools/p5/examples/smoke.js b/skills/make-an-anime/scripts/tools/p5/examples/smoke.jsnew file mode 100644index 0000000..9ccaecc--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/examples/smoke.js@@ -0,0 +1,36 @@+// Exercises typography, timing and graphics helpers with browser system fonts:+// ruby scripts/mv.rb 'anim:render[tools/p5/examples/smoke.js,tmp/anim_smoke,48]'+Anim.sketch({+ async load() {+ this.f = { big: "sans-serif", mono: "monospace", serif: "serif", sans: "sans-serif" };+ const w = (word, s, e) => ({ w: word, s, e });+ this.cue = Anim.cues([w("hello", 0.1, 0.5), w("print", 0.5, 0.9), w("world", 0.9, 1.4)]);+ },++ draw(t) {+ const { f, cue } = this;+ textFont(f.big);+ textSize(160);+ textAlign(LEFT, BASELINE);+ Anim.at(120, 260, Anim.pop(t, cue("hello").s), () =>+ Anim.knockout("HELLO", 0, 0, { weight: 18, ghost: { color: "rgba(43,58,122,0.6)" } }));++ Anim.at(1400, 300, Anim.slap(t, 0.4, { rot: -0.04 }), () => {+ Anim.slip(560, 150, { seed: 3, torn: ["right", "bottom"] });+ textFont(f.mono); textSize(26); fill("#e8488f"); noStroke();+ text("arXiv:0000.00000 [cs.CL]", -250, -20);+ textFont(f.serif); textSize(44); fill("#2b3a7a");+ text(Anim.typed("smoke test", Anim.progress(t, 0.5, 0.6)), -250, 40);+ });++ Anim.trace([[0, 700], [300, 700], [380, 620], [600, 620]], Anim.progress(t, 0.2, 0.8, Anim.ease.outCubic));+ const words = ["hello ", "print ", "world"].map((s, i) => ({ text: s.trim(), cue: cue(s.trim()) }));+ Anim.at(700, 900, {}, () => {+ Anim.slip(640, 110, { seed: 5, torn: [] });+ Anim.karaoke(t, words, -290, 16, { font: f.sans, size: 52 });+ });+ Anim.sparkle(1600, 700, 140, Anim.progress(t, 0.9, 0.9));+ Anim.twinkle(1750, 200, 30 * (0.6 + 0.4 * sin(t * 12)), "#e8488f");+ Anim.grain(0.2);+ }+});diff --git a/skills/make-an-anime/scripts/tools/p5/lib/battle.js b/skills/make-an-anime/scripts/tools/p5/lib/battle.jsnew file mode 100644index 0000000..3d9bad5--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/battle.js@@ -0,0 +1,132 @@+// Battle: title drops, speed lines, impacts and the virtual camera roll for layered action scenes. Everything is seeded+// or a pure function of time, so a frame renders the same way every time.+//+// Anim.titleSlam(local, { title: "EMBER × TEMPEST", tagline: "...", font, tagFont });+// Anim.withRoll(frame, () => sprite.draw(...)); // same roll as the shot's `roll: [from, to]` plate+// Anim.aura("#ff6a1f", 40, () => sprite.draw(...));+window.Anim = window.Anim || {};++(() => {+ // The shot under `frame` from Anim.data("shots"): { name, start_frame, frames, roll, local (seconds), p (0..1) }.+ Anim.shotAt = (frame, shots = Anim.data("shots")) => {+ const s = shots.find((x) => frame >= x.start_frame && frame < x.start_frame + x.frames);+ if (!s) return null;+ return { ...s, local: (frame - s.start_frame) / ANIM.fps, p: (frame - s.start_frame) / Math.max(s.frames - 1, 1) };+ };++ // The eased plate roll at `frame`, in degrees: must match Media::FFmpeg#roll_filter.+ Anim.rollAt = (frame, shots) => {+ const s = Anim.shotAt(frame, shots);+ if (!s?.roll) return 0;+ return s.roll[0] + (s.roll[1] - s.roll[0]) * (3 * s.p ** 2 - 2 * s.p ** 3);+ };++ // Draw fn in the camera's frame, turning with the plate around the middle of the canvas.+ Anim.withRoll = (frame, fn, shots) => {+ push();+ translate(width / 2, height / 2);+ rotate((Anim.rollAt(frame, shots) * Math.PI) / 180);+ translate(-width / 2, -height / 2);+ fn();+ pop();+ };++ // A glow that follows the alpha of whatever fn draws (a sprite's silhouette).+ Anim.aura = (color, blur, fn) => {+ const g = drawingContext;+ const prev = [g.shadowColor, g.shadowBlur];+ g.shadowColor = color; g.shadowBlur = blur;+ fn();+ [g.shadowColor, g.shadowBlur] = prev;+ };++ // Radial speed lines around (cx, cy), a new seed each `hold` frames so they flicker like hand-drawn ones.+ Anim.speedLines = (frame, cx, cy, { count = 70, inner = 340, outer = 1500, color = [255, 255, 255], alpha = 0.55, weight = 7, hold = 2, seed = 11 } = {}) => {+ const rng = Anim.rng(seed + Math.floor(frame / hold) * 97);+ const g = drawingContext;+ g.save();+ for (let i = 0; i < count; i++) {+ const a = rng() * Math.PI * 2, r0 = inner * (0.7 + rng() * 0.8), r1 = outer * (0.7 + rng() * 0.3), w = weight * (0.25 + rng());+ const c = Math.cos(a), s = Math.sin(a), nx = -s * w, ny = c * w;+ g.fillStyle = `rgba(${color[0]},${color[1]},${color[2]},${alpha * (0.35 + rng() * 0.65)})`;+ g.beginPath();+ g.moveTo(cx + c * r0, cy + s * r0);+ g.lineTo(cx + c * r1 + nx, cy + s * r1 + ny);+ g.lineTo(cx + c * r1 - nx, cy + s * r1 - ny);+ g.closePath();+ g.fill();+ }+ g.restore();+ };++ // An expanding shock ring: `p` 0..1 from the hit.+ Anim.shockRing = (x, y, p, { radius = 900, color = [255, 240, 210], weight = 44 } = {}) => {+ if (p <= 0 || p >= 1) return;+ const k = Anim.ease.outCubic(p);+ const g = drawingContext;+ g.save();+ g.strokeStyle = `rgba(${color[0]},${color[1]},${color[2]},${(1 - p) * 0.9})`;+ g.lineWidth = weight * (1 - p) + 1;+ g.shadowColor = `rgb(${color[0]},${color[1]},${color[2]})`; g.shadowBlur = 40;+ g.beginPath(); g.ellipse(x, y, radius * k, radius * k * 0.72, -0.2, 0, Math.PI * 2); g.stroke();+ g.restore();+ };++ // A hot centre that blooms and dies at a hit.+ Anim.impactBloom = (x, y, p, { radius = 520, core = "255,255,255", edge = "255,160,70" } = {}) => {+ if (p <= 0 || p >= 1) return;+ const g = drawingContext, a = 1 - p, r = radius * Anim.ease.outExpo(p);+ const grad = g.createRadialGradient(x, y, 0, x, y, r);+ grad.addColorStop(0, `rgba(${core},${a})`);+ grad.addColorStop(0.35, `rgba(${edge},${a * 0.7})`);+ grad.addColorStop(1, `rgba(${edge},0)`);+ g.fillStyle = grad;+ g.fillRect(x - r, y - r, r * 2, r * 2);+ };++ // Drifting sparks. `depth` scales speed and size, so a near layer passes faster than a far one.+ Anim.embers = (t, { count = 60, seed = 3, color = [255, 170, 80], depth = 1, wind = [-60, -120], size = 5 } = {}) => {+ const rng = Anim.rng(seed);+ const g = drawingContext;+ g.save();+ for (let i = 0; i < count; i++) {+ const x0 = rng() * width, y0 = rng() * height, phase = rng() * 6.28, s = (0.4 + rng()) * size * depth, speed = 0.6 + rng() * 0.8;+ const x = (((x0 + wind[0] * depth * speed * t + Math.sin(t * 2 + phase) * 18) % width) + width) % width;+ const y = (((y0 + wind[1] * depth * speed * t) % height) + height) % height;+ g.fillStyle = `rgba(${color[0]},${color[1]},${color[2]},${0.45 + 0.45 * Math.sin(t * 5 + phase) ** 2})`;+ g.shadowColor = `rgb(${color[0]},${color[1]},${color[2]})`; g.shadowBlur = 10;+ g.beginPath(); g.arc(x, y, s, 0, Math.PI * 2); g.fill();+ }+ g.restore();+ };++ // A full-frame colour: smash whites and fades.+ Anim.flash = (alpha, color = "255,255,255") => {+ if (alpha <= 0) return;+ drawingContext.fillStyle = `rgba(${color},${Math.min(alpha, 1)})`;+ drawingContext.fillRect(0, 0, width, height);+ };++ // Title drop: the title slams in oversized, the frame shakes, a tagline follows. `local`: seconds into the card.+ Anim.titleSlam = (local, { title, tagline = "", font, tagFont = font, size = 170, color = "#fff4e0", glow = "#ff6a1f", tagColor = "#ffd9a8", at = 0.1, tagAt = 0.75, y = height * 0.47, spacing = 8 } = {}) => {+ const slam = Anim.slam(local, at, { dur: 0.14, from: 2.1 });+ const shake = Anim.shake(local, at + 0.14, { dur: 0.4, amp: 18 });+ const g = drawingContext;+ Anim.at(width / 2 + shake.x, y + shake.y, slam, () => {+ textFont(font); textSize(size); textAlign(CENTER, CENTER);+ g.letterSpacing = `${spacing}px`;+ g.shadowColor = glow; g.shadowBlur = 46;+ fill(color); noStroke();+ text(title, 0, 0);+ g.shadowBlur = 0;+ g.letterSpacing = "0px";+ });+ if (tagline) {+ const a = Anim.tween(local, tagAt, 0.25, 0, 1);+ textFont(tagFont); textSize(size * 0.2); textAlign(CENTER, CENTER);+ g.letterSpacing = `${size * 0.05}px`;+ g.globalAlpha = a; fill(tagColor); text(tagline, width / 2, y + size * 0.82); g.globalAlpha = 1;+ g.letterSpacing = "0px";+ }+ };+})();diff --git a/skills/make-an-anime/scripts/tools/p5/lib/core.js b/skills/make-an-anime/scripts/tools/p5/lib/core.jsnew file mode 100644index 0000000..a0a443b--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/core.js@@ -0,0 +1,127 @@+// Anim core: owns the p5 lifecycle so a sketch only describes what to draw at time t.+//+// Anim.sketch({+// async load() { this.f = await Anim.fonts({ big: "title.ttf" }) },+// draw(t, frame) { ... } // canvas is already cleared (transparent) for every frame+// });+//+// ANIM (set by anim/render.mjs) holds width, height, fps, frames, data (from --data name=file.json).+window.Anim = window.Anim || {};++(() => {+ let current = null;++ Anim.sketch = (def) => { current = def; };++ window.setup = async () => {+ try {+ createCanvas(ANIM.width, ANIM.height);+ pixelDensity(1);+ noLoop();+ if (!current) throw new Error("the sketch never called Anim.sketch({ draw })");+ await current.load?.call(current);+ ANIM.ready = true;+ } catch (e) {+ ANIM.error = e.stack || String(e);+ throw e;+ }+ };++ window.draw = () => {+ if (!ANIM.ready) return;+ clear();+ randomSeed(1000 + ANIM.frame); // per-frame jitter that is identical on every render+ noiseSeed(7);+ // push/pop isolate every frame: p5 resets transforms per frame but not style (textAlign, fill, shadow,+ // letterSpacing), so a helper's state leaked into the next frame only in full renders.+ push();+ try { current.draw.call(current, ANIM.t, ANIM.frame); } finally { pop(); }+ };++ // Called by render.mjs: draw frame i and return it as a PNG data URL (alpha preserved).+ Anim.renderFrame = async (i) => {+ ANIM.frame = i;+ ANIM.t = i / ANIM.fps;+ await redraw();+ return document.querySelector("canvas").toDataURL("image/png");+ };++ // { name: "File.ttf" } -> { name: p5.Font }, copied into this project's tools/p5/fonts/.+ Anim.fonts = async (map) => {+ const out = {};+ for (const [name, file] of Object.entries(map)) out[name] = await loadFont(`/tools/p5/fonts/${encodeURIComponent(file)}`);+ return out;+ };++ Anim.data = (name) => {+ const d = ANIM.data[name];+ if (d === undefined) throw new Error(`missing --data ${name}=file.json`);+ return d;+ };++ // Character sprite cut out by the Clips step (Anim.data("clips")[name] = { dir, frames, w, h, audio_at }), every frame loaded:+ // const run = await Anim.clip("flower_run"); run.frame(i) -> p5.Image (clamped, or looped with { loop: true }).+ // run.at(t) -> the frame lip-synced to song time t (clips with audio_at); run.draw(i, x, y, h) draws it centred at x, y, h tall.+ // run.place(img, x, y, w) draws it where the character sat in its source frame, that frame drawn w wide with its top-left at (x, y):+ // sprites of one framing cut from different sources (an H3 clip and a still) then line up exactly.+ Anim.clip = async (name) => {+ const meta = Anim.data("clips")[name];+ if (!meta) throw new Error(`no clip "${name}" (${Object.keys(Anim.data("clips")).join(", ")})`);+ const images = await Promise.all(+ Array.from({ length: meta.frames }, (_, i) => loadImage(`/${meta.dir}/${String(i).padStart(4, "0")}.png`)));+ const frame = (i, { loop = false } = {}) => {+ const n = images.length;+ return images[loop ? ((Math.floor(i) % n) + n) % n : Math.min(n - 1, Math.max(0, Math.floor(i)))];+ };+ return {+ ...meta, images, frame,+ at: (t, opts) => frame((t - (meta.audio_at ?? 0)) * ANIM.fps, opts),+ draw: (img, x, y, h) => { imageMode(CENTER); image(img, x, y, (h * img.width) / img.height, h); },+ place: (img, x = 0, y = 0, w = ANIM.width) => {+ const k = w / meta.src[0], [bx, by, bw, bh] = meta.box;+ imageMode(CORNER);+ image(img, x + bx * k, y + by * k, bw * k, bh * k);+ }+ };+ };++ // Word cues from a transcript: [{ w: "sparks", s: 1.02, e: 1.4 }, ...] (Overlay step writes words.json).+ // cue("your", 2) -> the 2nd "your". Throws with the transcript when a word is missing so timing never silently drifts.+ Anim.cues = (words) => {+ const norm = (w) => w.toLowerCase().replace(/[^a-z0-9']/g, "");+ const list = words.map((x) => ({ ...x, w: norm(x.w) }));+ const cue = (word, nth = 1) => {+ const hits = list.filter((x) => x.w === norm(word));+ if (!hits[nth - 1]) throw new Error(`cue "${word}" #${nth} not in transcript: ${list.map((x) => x.w).join(" ")}`);+ return hits[nth - 1];+ };+ cue.list = list;+ return cue;+ };++ // Seeded PRNG (mulberry32) for shapes that must stay identical across frames (torn edges, trace jitter).+ Anim.rng = (seed) => {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+ };++ // Run fn inside push/pop, translated/rotated/scaled around (x, y); alpha 0..1 multiplies canvas alpha.+ Anim.at = (x, y, { scale: s = 1, rot = 0, alpha = 1 } = {}, fn) => {+ if (alpha <= 0) return;+ push();+ translate(x, y);+ if (rot) rotate(rot);+ if (s !== 1) scale(s);+ const prev = drawingContext.globalAlpha;+ drawingContext.globalAlpha = prev * alpha;+ fn();+ drawingContext.globalAlpha = prev;+ pop();+ };+})();diff --git a/skills/make-an-anime/scripts/tools/p5/lib/fx.js b/skills/make-an-anime/scripts/tools/p5/lib/fx.jsnew file mode 100644index 0000000..155cb91--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/fx.js@@ -0,0 +1,115 @@+// Anim fx: entrance transforms (slap, pop, slam), shake, sparkle bursts and circuit traces.+// Entrance helpers return { scale, rot, alpha } to pass straight into Anim.at().+window.Anim = window.Anim || {};++(() => {+ const { ease, clamp01 } = Anim;++ // Sticker "slapped" onto the page: starts big and rotated, snaps down with a small overshoot.+ Anim.slap = (t, start, { dur = 0.22, from = 1.18, rot = 0, spin = 0.08 } = {}) => {+ if (t < start) return { scale: 1, rot, alpha: 0 };+ const p = clamp01((t - start) / dur);+ return { scale: from + (1 - from) * ease.outBack(p), rot: rot + spin * (1 - ease.outCubic(p)), alpha: clamp01(p * 4) };+ };++ // Word pop: grows from `from` to 1 with an overshoot.+ Anim.pop = (t, start, { dur = 0.16, from = 0.55 } = {}) => {+ if (t < start) return { scale: 1, rot: 0, alpha: 0 };+ const p = clamp01((t - start) / dur);+ return { scale: from + (1 - from) * ease.outBack(p), rot: 0, alpha: clamp01(p * 3) };+ };++ // Heavy slam: enters oversized and hits its size fast (pair with Anim.shake for the impact).+ Anim.slam = (t, start, { dur = 0.12, from = 1.7 } = {}) => {+ if (t < start) return { scale: 1, rot: 0, alpha: 0 };+ const p = clamp01((t - start) / dur);+ return { scale: from + (1 - from) * ease.inCubic(p), rot: 0, alpha: clamp01(p * 2) };+ };++ // Decaying random offset {x, y} after `start` (camera-shake / impact jitter).+ Anim.shake = (t, start, { dur = 0.3, amp = 14 } = {}) => {+ const p = (t - start) / dur;+ if (p < 0 || p > 1) return { x: 0, y: 0 };+ const k = amp * Math.pow(1 - p, 2);+ return { x: random(-k, k), y: random(-k, k) };+ };++ // Starburst sparkle at (x, y): `progress` 0..1 blooms, spins and fades. Long + short rays and a hot core.+ Anim.sparkle = (x, y, r, progress, { color = "#ff3fa4", core = "#ffffff", rays = 8 } = {}) => {+ if (progress <= 0 || progress >= 1) return;+ const grow = ease.outBack(clamp01(progress * 2.2));+ const fade = 1 - clamp01((progress - 0.6) / 0.4);+ Anim.at(x, y, { rot: progress * 0.9, alpha: fade }, () => {+ noStroke();+ fill(color);+ for (let i = 0; i < rays; i++) {+ const len = r * grow * (i % 2 ? 0.55 : 1);+ const w = r * 0.09 * grow;+ push();+ rotate((i * TWO_PI) / rays);+ beginShape();+ vertex(0, -w);+ vertex(len, 0);+ vertex(0, w);+ vertex(-w * 0.5, 0);+ endShape(CLOSE);+ pop();+ }+ fill(core);+ circle(0, 0, r * 0.28 * grow);+ fill(color);+ circle(0, 0, r * 0.12 * grow);+ });+ };++ // Four-point twinkle star (small decoration), size scaled by `s`.+ Anim.twinkle = (x, y, s, color) => {+ if (s <= 0) return;+ push();+ translate(x, y);+ noStroke();+ fill(color);+ beginShape();+ for (let i = 0; i < 8; i++) {+ const r = i % 2 ? s * 0.22 : s;+ const a = (i * PI) / 4 - HALF_PI;+ vertex(cos(a) * r, sin(a) * r);+ }+ endShape(CLOSE);+ pop();+ };++ // Circuit trace: polyline `points` [[x,y],...] drawn on up to `progress` (0..1 of total length),+ // with a solder dot on every reached vertex and a bigger pad at the head.+ Anim.trace = (points, progress, { color = "#2b3a7a", weight = 4, dot = 13, pad = 20 } = {}) => {+ if (progress <= 0) return;+ const segs = [];+ let total = 0;+ for (let i = 1; i < points.length; i++) {+ const d = dist(...points[i - 1], ...points[i]);+ segs.push(d);+ total += d;+ }+ let left = total * clamp01(progress);+ push();+ stroke(color);+ strokeWeight(weight);+ strokeCap(ROUND);+ noFill();+ const reached = [points[0]];+ let head = points[0];+ for (let i = 0; i < segs.length && left > 0; i++) {+ const k = Math.min(1, left / segs[i]);+ const [ax, ay] = points[i], [bx, by] = points[i + 1];+ head = [ax + (bx - ax) * k, ay + (by - ay) * k];+ line(ax, ay, ...head);+ if (k === 1) reached.push(points[i + 1]);+ left -= segs[i];+ }+ noStroke();+ fill(color);+ reached.slice(1).forEach(([x, y]) => circle(x, y, dot));+ circle(...head, progress >= 1 ? pad : dot);+ pop();+ };+})();diff --git a/skills/make-an-anime/scripts/tools/p5/lib/paper.js b/skills/make-an-anime/scripts/tools/p5/lib/paper.jsnew file mode 100644index 0000000..228e301--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/paper.js@@ -0,0 +1,48 @@+// Anim paper: torn-edge paper slips (labels, stickers, caption cards) with a soft drop shadow.+window.Anim = window.Anim || {};++(() => {+ const cache = new Map();++ // Outline of a w×h slip centred on the origin. `torn` lists the ragged edges ("top", "right", "bottom", "left");+ // the rest get a faint cut-paper wobble. Seeded, so the same slip keeps its shape on every frame.+ Anim.slipPath = (w, h, { seed = 1, torn = ["right"], rough = 7, step = 9 } = {}) => {+ const key = [w, h, seed, torn, rough, step].join("|");+ if (cache.has(key)) return cache.get(key);+ const rnd = Anim.rng(seed);+ const pts = [];+ const edge = (name, ax, ay, bx, by, nx, ny) => {+ const len = Math.hypot(bx - ax, by - ay);+ const n = Math.max(2, Math.round(len / step));+ const amp = torn.includes(name) ? rough : 0.9;+ for (let i = 0; i < n; i++) {+ const k = i / n;+ const j = (rnd() - 0.5) * 2 * amp * (torn.includes(name) ? 1 : 0.6);+ pts.push([ax + (bx - ax) * k + nx * j, ay + (by - ay) * k + ny * j]);+ }+ };+ const x0 = -w / 2, y0 = -h / 2, x1 = w / 2, y1 = h / 2;+ edge("top", x0, y0, x1, y0, 0, 1);+ edge("right", x1, y0, x1, y1, -1, 0);+ edge("bottom", x1, y1, x0, y1, 0, -1);+ edge("left", x0, y1, x0, y0, 1, 0);+ cache.set(key, pts);+ return pts;+ };++ // Draw the slip at the current origin. Call inside Anim.at(x, y, transform, () => Anim.slip(...)).+ Anim.slip = (w, h, { fill: f = "#f1ead9", shadow = "rgba(40,30,20,0.28)", blur = 14, offset = [5, 7], ...pathOpts } = {}) => {+ const pts = Anim.slipPath(w, h, pathOpts);+ push();+ drawingContext.shadowColor = shadow;+ drawingContext.shadowBlur = blur;+ drawingContext.shadowOffsetX = offset[0];+ drawingContext.shadowOffsetY = offset[1];+ noStroke();+ fill(f);+ beginShape();+ pts.forEach(([x, y]) => vertex(x, y));+ endShape(CLOSE);+ pop();+ };+})();diff --git a/skills/make-an-anime/scripts/tools/p5/lib/riso.js b/skills/make-an-anime/scripts/tools/p5/lib/riso.jsnew file mode 100644index 0000000..5fa7abc--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/riso.js@@ -0,0 +1,34 @@+// Anim riso: print-look finishing so vector graphics sit in a risograph / screen-print plate.+window.Anim = window.Anim || {};++(() => {+ // Misregistered two-ink print: draws fn(ghostColor) offset by (dx, dy), then fn(color) on top.+ // fn receives the ink colour to use, e.g. (ink) => Anim.knockout("NERVOUS", 0, 0, { fill: ink }).+ Anim.misregister = (fn, { color, ghost = "rgba(43,58,122,0.55)", dx = 4, dy = 3 } = {}) => {+ push();+ translate(dx, dy);+ fn(ghost);+ pop();+ fn(color);+ };++ // Ink grain over everything drawn so far: knocks random speckles out of the alpha channel so fills look+ // printed instead of flat. `amount` 0..1 is the share of alpha removed at most; new pattern every frame.+ Anim.grain = (amount = 0.18, { cell = 2 } = {}) => {+ loadPixels();+ const W = width, H = height, px = pixels;+ const rnd = Anim.rng(9000 + ANIM.frame);+ for (let y = 0; y < H; y += cell) {+ for (let x = 0; x < W; x += cell) {+ const k = 1 - amount * rnd() * rnd() * 2;+ for (let yy = y; yy < Math.min(y + cell, H); yy++) {+ for (let xx = x; xx < Math.min(x + cell, W); xx++) {+ const i = (yy * W + xx) * 4 + 3;+ if (px[i]) px[i] = px[i] * k;+ }+ }+ }+ }+ updatePixels();+ };+})();diff --git a/skills/make-an-anime/scripts/tools/p5/lib/screens.js b/skills/make-an-anime/scripts/tools/p5/lib/screens.jsnew file mode 100644index 0000000..9549d28--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/screens.js@@ -0,0 +1,168 @@+// Screens: the readable parts of an anime scene that p5 draws over the H3 plate — code editors and terminals on a+// monitor insert, typing, subtitles, the monitor vignette. Generated images never contain text; everything readable+// comes from here.+//+// const typing = Anim.typing("life = Life.new(1987)", { seed: 1987 }); // deterministic key times (s)+// Anim.codeEditor(local, dur, { font, tokens: [["life", "#e6edf7"], [" = ", "#ff79c6"], ...], typing, zoom: [1.1, 1.16] });+// Anim.subtitles(t, Anim.data("dialogue"), { font, italic });+// Anim.vignette(0.6);+//+// Pitfalls these helpers avoid:+// - p5's textWidth() ignores leading/trailing spaces with a loaded font: code is laid out on a monospace grid instead.+// - A canvas radial gradient leaves the inside of a non-zero inner radius unpainted, and interpolates colours+// unpremultiplied (a tinted stop next to a black stop paints a bright ring): the vignette is black-only, alpha-only.+window.Anim = window.Anim || {};++(() => {+ // Monospace grid for a loaded font: one advance per glyph, so spaces count.+ Anim.mono = (font, size) => {+ textFont(font);+ textSize(size);+ const adv = textWidth("0");+ return {+ adv,+ size,+ // Draw coloured tokens [[str, colour], ...] from x, y (baseline); only the first `limit` glyphs. Returns glyphs drawn.+ tokens(tokens, x, y, limit = Infinity) {+ textFont(font); textSize(size); textAlign(LEFT, BASELINE);+ let col = 0;+ for (const [str, colour] of tokens) {+ for (const ch of str) {+ if (col >= limit) return col;+ if (ch !== " ") { fill(colour); text(ch, x + col * adv, y); }+ col++;+ }+ }+ return col;+ },+ };+ };++ // Deterministic typing rhythm: a key time per character plus an optional Enter, in seconds from `start`.+ // { chars: [t0, t1, ...], enter, count(t), last(t) } — use the same times for keyboard SFX cues.+ Anim.typing = (str, { seed = 1, start = 0.08, base = 0.038, jitter = 0.03, spacePause = 0.03, enterPause = 0.14, enter = true } = {}) => {+ const rng = Anim.rng(seed);+ const chars = [];+ let t = start;+ for (const ch of str) { chars.push(t); t += base + rng() * jitter + (ch === " " ? spacePause : 0); }+ const enterAt = enter ? t + enterPause : null;+ return {+ text: str,+ chars,+ enter: enterAt,+ count: (now) => chars.filter((c) => now >= c).length,+ entered: (now) => enterAt !== null && now >= enterAt,+ last: (now) => Math.max(-9, ...chars.filter((c) => now >= c), enterAt !== null && now >= enterAt ? enterAt : -9),+ };+ };++ // Cursor visibility: solid for `hold` s after the last key, then blinking at `hz`.+ Anim.cursorOn = (now, lastKey = -9, { hold = 0.4, hz = 1.9 } = {}) => now - lastKey <= hold || Math.floor(now * hz * 2) % 2 === 0;++ Anim.EDITOR_DARK = { bg: "#0b0f17", panel: "#0f1522", bar: "#141c2b", gutter: "#3a4660", text: "#e6edf7", dim: "#6b7894", cursor: "#7fd8ff", glow: "#7fd8ff" };++ // Full-screen code editor on a monitor insert. `local`/`dur`: seconds into / length of the insert.+ // font, size 64, tokens (the line being typed), typing (Anim.typing result; omit for an empty file with a blinking+ // cursor), above: earlier lines as token arrays, filename "main.rb", lang "Ruby", colors (EDITOR_DARK),+ // zoom [from, to] eased push toward the cursor (empty file) or the middle of the line (typing), vignette 0.6,+ // scanlines true, flash: brighten toward white after Enter (leads into a smash cut).+ Anim.codeEditor = (local, dur, { font, size = 64, tokens = [], typing = null, above = [], filename = "main.rb", lang = "",+ colors = Anim.EDITOR_DARK, zoom = [1, 1], vignette = 0.6, scanlines = true, flash = 0 } = {}) => {+ const C = colors, W = width, H = height;+ const grid = Anim.mono(font, size);+ const lh = size * 1.6;+ const lineText = tokens.map((p) => p[0]).join("");+ const cols = Math.max(lineText.length, ...above.map((l) => l.map((p) => p[0]).join("").length), 12);+ const x0 = Math.round((W - cols * grid.adv) / 2 + grid.adv * 1.5);+ const y0 = Math.round(H * 0.47 - (above.length * lh) / 2) + above.length * lh;+ const typed = typing ? typing.count(local) : 0;+ const entered = typing ? typing.entered(local) : false;+ const cx = entered ? x0 : x0 + typed * grid.adv, cy = entered ? y0 + lh : y0;+ const fx = typing ? x0 + (lineText.length * grid.adv) / 2 : cx, fy = y0 - size * 0.35;+ const k = Anim.tween(local, 0, dur, zoom[0], zoom[1], Anim.ease.inOutCubic);++ push();+ background(C.bg);+ translate(fx, fy); scale(k); translate(-fx, -fy);+ noStroke();+ fill(C.panel); rect(120, 120, W - 240, H - 240, 18);+ fill(C.bar); rect(120, 120, W - 240, 72, 18, 18, 0, 0);+ [["#ff5f57", 0], ["#febc2e", 1], ["#28c840", 2]].forEach(([c, i]) => { fill(c); circle(164 + i * 36, 156, 20); });+ textFont(font); textSize(28);+ const tabW = textWidth(filename) + 64;+ fill(C.panel); rect(260, 134, tabW, 58, 10, 10, 0, 0);+ fill(C.text); textAlign(LEFT, CENTER); text(filename, 292, 162);+ if (lang) { fill(C.dim); textAlign(RIGHT, CENTER); text(lang, W - 160, H - 150); }++ const first = y0 - above.length * lh;+ const nLines = above.length + 1 + (entered ? 1 : 0);+ textSize(size); textAlign(RIGHT, BASELINE);+ for (let i = 0; i < nLines; i++) { fill(i === nLines - 1 ? C.dim : C.gutter); text(String(i + 1), x0 - grid.adv * 2, first + i * lh); }+ fill(255, 255, 255, 10); rect(120, cy - size * 1.05, W - 240, lh);+ above.forEach((line, i) => grid.tokens(line, x0, first + i * lh));+ grid.tokens(tokens, x0, y0, typed);++ if (Anim.cursorOn(local, typing ? typing.last(local) : -9)) {+ drawingContext.shadowBlur = 28; drawingContext.shadowColor = C.glow;+ fill(C.cursor); rect(cx + 2, cy - size * 0.82, 6, size, 1);+ drawingContext.shadowBlur = 0;+ }+ pop();++ if (vignette) Anim.vignette(vignette);+ if (scanlines) Anim.scanlines();+ if (flash && entered) {+ drawingContext.fillStyle = `rgba(255,255,255,${Anim.tween(local, typing.enter, dur - typing.enter, 0, flash, (x) => x * x)})`;+ drawingContext.fillRect(0, 0, W, H);+ }+ return { cursor: [cx, cy], typed, entered };+ };++ // Darkened edges: black only, alpha only, inner radius 0 (see the pitfalls above).+ Anim.vignette = (strength = 0.6, { inner = 0.45 } = {}) => {+ const g = drawingContext, W = width, H = height;+ const grad = g.createRadialGradient(W / 2, H / 2, 0, W / 2, H / 2, H * 0.95);+ grad.addColorStop(0, "rgba(0,0,0,0)");+ grad.addColorStop(inner, `rgba(0,0,0,${(strength * 0.13).toFixed(3)})`);+ grad.addColorStop(1, `rgba(0,0,0,${strength})`);+ g.fillStyle = grad;+ g.fillRect(0, 0, W, H);+ };++ Anim.scanlines = (alpha = 0.07, step = 4) => {+ drawingContext.fillStyle = `rgba(0,0,0,${alpha})`;+ for (let y = 0; y < height; y += step) drawingContext.fillRect(0, y, width, 1);+ };++ // Subtitles from Anim.data("dialogue") lines ({ text, at, end, vo }): one at a time, lower third, white with a soft+ // shadow, narration in `italic`. Performed audio tags ([whispering]) are removed.+ // Lines start where the voice actually starts: `speech_at` is measured from each take's leading silence by the Dialogue+ // step (a take with a muted stumble at its head would otherwise show the subtitle early). Word-alignment times are+ // not used for this: after a long performance tag they placed a line's first word 1.1 s after the voice began.+ Anim.spoken = (lines) => lines.map((l) => (l.speech_at != null ? { ...l, at: Math.max(l.at, l.speech_at) } : l));+ const spokenCache = new WeakMap();++ Anim.subtitles = (t, lines, { font, italic = font, size = 46, y = height - 92, lead = 0.05, tail = 0.35, skip = () => false } = {}) => {+ if (!spokenCache.has(lines)) spokenCache.set(lines, Anim.spoken(lines));+ const l = spokenCache.get(lines).find((x) => t >= x.at - lead && t < x.end + tail && !skip(x));+ if (!l) return null;+ const str = (l.subtitle || l.text).replace(/\[[^\]]*\]\s*/g, "").trim();+ const a = Anim.envelope(t, l.at - lead, l.end + tail, 0.12, 0.2);+ textFont(l.vo ? italic : font); textSize(size); textAlign(CENTER, BASELINE);+ drawingContext.shadowBlur = 14; drawingContext.shadowColor = `rgba(0,0,0,${0.9 * a})`;+ fill(0, 0, 0, 150 * a); text(str, width / 2 + 2, y + 2);+ fill(255, 255, 255, 255 * a); text(str, width / 2, y);+ drawingContext.shadowBlur = 0;+ return l;+ };++ // Place/date card ("CITY · 1999"): letter-spaced, fading in.+ Anim.placeCard = (local, str, { font, size = 64, color = [40, 44, 52], alpha = 0.75, at = 0.05, fade = 0.3, spacing = 18, y = height / 2 } = {}) => {+ const a = Anim.tween(local, at, fade, 0, alpha);+ textFont(font); textSize(size); textAlign(CENTER, CENTER);+ fill(...color, 255 * a);+ drawingContext.letterSpacing = `${spacing}px`;+ text(str, width / 2, y);+ drawingContext.letterSpacing = "0px";+ };+})();diff --git a/skills/make-an-anime/scripts/tools/p5/lib/time.js b/skills/make-an-anime/scripts/tools/p5/lib/time.jsnew file mode 100644index 0000000..1a5a0eb--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/time.js@@ -0,0 +1,41 @@+// Anim time: easing curves and timeline helpers. All times are in seconds.+window.Anim = window.Anim || {};++(() => {+ const c1 = 1.70158, c3 = c1 + 1;++ Anim.ease = {+ linear: (x) => x,+ inCubic: (x) => x * x * x,+ outCubic: (x) => 1 - Math.pow(1 - x, 3),+ inOutCubic: (x) => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2),+ outExpo: (x) => (x >= 1 ? 1 : 1 - Math.pow(2, -10 * x)),+ outBack: (x) => 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2),+ outElastic: (x) => (x <= 0 ? 0 : x >= 1 ? 1 : Math.pow(2, -10 * x) * Math.sin((x * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1)+ };++ Anim.clamp01 = (x) => Math.min(1, Math.max(0, x));++ // 0..1 progress of t through [start, start + dur], eased.+ Anim.progress = (t, start, dur, ease = Anim.ease.linear) => ease(Anim.clamp01((t - start) / dur));++ // Value from `from` to `to` over [start, start + dur].+ Anim.tween = (t, start, dur, from, to, ease = Anim.ease.outCubic) => from + (to - from) * Anim.progress(t, start, dur, ease);++ // Is t inside [start, end)?+ Anim.live = (t, start, end = Infinity) => t >= start && t < end;++ // Visibility envelope 0..1: fades in over `fadeIn` after start, out over `fadeOut` before end (0 = hard cut).+ Anim.envelope = (t, start, end, fadeIn = 0, fadeOut = 0) => {+ if (t < start || t >= end) return 0;+ const a = fadeIn ? Anim.clamp01((t - start) / fadeIn) : 1;+ const b = fadeOut ? Anim.clamp01((end - t) / fadeOut) : 1;+ return Math.min(a, b);+ };++ // Step counter: how many `period`s have passed since start (for tickers / counters).+ Anim.steps = (t, start, period) => Math.max(0, Math.floor((t - start) / period));++ // Frames since the last step boundary — 0 on the frame a counter changes (for "just changed" jitter).+ Anim.sinceStep = (t, start, period) => Math.round((((t - start) % period) + period) % period * ANIM.fps);+})();diff --git a/skills/make-an-anime/scripts/tools/p5/lib/type.js b/skills/make-an-anime/scripts/tools/p5/lib/type.jsnew file mode 100644index 0000000..8e69673--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/lib/type.js@@ -0,0 +1,77 @@+// Anim type: typewriter reveals, knockout (outlined) text, word stacks and karaoke captions.+window.Anim = window.Anim || {};++(() => {+ const { clamp01 } = Anim;++ // Text with a thick outline drawn *under* the fill (a sticker / riso knockout that reads on busy plates).+ // ghost: { color, dx, dy } adds a misregistered second ink between the outline and the fill.+ Anim.knockout = (str, x, y, { fill: f = "#e8488f", outline = "#f1ead9", weight = 0, ghost = null } = {}) => {+ push();+ if (weight > 0) {+ stroke(outline);+ strokeWeight(weight);+ strokeJoin(ROUND);+ fill(outline);+ text(str, x, y);+ }+ noStroke();+ if (ghost) {+ fill(ghost.color);+ text(str, x + (ghost.dx ?? 5), y + (ghost.dy ?? 4));+ }+ fill(f);+ text(str, x, y);+ pop();+ };++ // Characters of `str` visible at progress 0..1 (typewriter).+ Anim.typed = (str, progress) => str.slice(0, Math.round(str.length * clamp01(progress)));++ // Typewriter synced to sung words: `parts` = [{ text: "in ", cue: {s, e} }, ...]; each part types+ // across its cue's duration (min `minDur`), so the text lands with the vocal. Returns the visible string.+ Anim.typedWords = (t, parts, { minDur = 0.12 } = {}) =>+ parts.map(({ text: str, cue }) => Anim.typed(str, (t - cue.s) / Math.max(minDur, cue.e - cue.s))).join("");++ // Karaoke caption: words laid out left to right from (x, y) (baseline). Words before the active one+ // are `done`, the active word is `active` with an underline growing over its duration, later words `todo`.+ // activeFont / activeWeight (variable fonts, p5 2.x textWeight) make the sung word heavier.+ Anim.karaoke = (t, words, x, y, { font, size, activeFont, weight, activeWeight, done = "#2b3a7a", todo = "rgba(43,58,122,0.45)",+ active = "#2b3a7a", underline = "#e8488f", gap = 0.28 } = {}) => {+ push();+ textSize(size);+ textAlign(LEFT, BASELINE);+ let cx = x;+ for (const { text: str, cue } of words) {+ const isActive = t >= cue.s && t < cue.e + 0.15;+ const isDone = t >= cue.e + 0.15;+ textFont(isActive && activeFont ? activeFont : font);+ if (weight || activeWeight) textWeight(isActive && activeWeight ? activeWeight : weight || 400);+ noStroke();+ fill(isActive ? active : isDone ? done : todo);+ text(str, cx, y);+ const w = textWidth(str);+ if (isActive || isDone) {+ const p = isDone ? 1 : clamp01((t - cue.s) / Math.max(0.15, cue.e - cue.s));+ stroke(underline);+ strokeWeight(size * 0.09);+ strokeCap(ROUND);+ line(cx, y + size * 0.2, cx + w * Anim.ease.outCubic(p), y + size * 0.2);+ }+ cx += w + size * gap;+ }+ pop();+ return cx - x;+ };++ // Width of a caption laid out by Anim.karaoke (to size its paper slip).+ Anim.karaokeWidth = (words, { font, size, weight, gap = 0.28 }) => {+ push();+ textFont(font);+ textSize(size);+ if (weight) textWeight(weight);+ const w = words.reduce((sum, { text: str }) => sum + textWidth(str) + size * gap, 0) - size * gap;+ pop();+ return w;+ };+})();diff --git a/skills/make-an-anime/scripts/tools/p5/render.mjs b/skills/make-an-anime/scripts/tools/p5/render.mjsnew file mode 100644index 0000000..1e20c14--- /dev/null+++ b/skills/make-an-anime/scripts/tools/p5/render.mjs@@ -0,0 +1,107 @@+#!/usr/bin/env node+// Render a p5.js sketch to a transparent PNG sequence, frame-exact, in headless Chrome.+//+// node anim/render.mjs <sketch.js> --out <dir> [--width 1928] [--height 1076] [--fps 24] [--frames 168]+// [--only 0,48,120] [--data name=file.json ...] [--chrome /path/to/chrome]+//+// The sketch registers itself with Anim.sketch({ load, draw }) (see anim/lib/core.js) and gets+// every anim/lib/*.js helper. Frame i is drawn at t = i / fps and written to <out>/<i:0000>.png.+// Prints a JSON summary ({ out, frames, width, height, fps, ms }) on stdout.+import http from "node:http";+import fs from "node:fs";+import path from "node:path";+import { parseArgs } from "node:util";+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 CHROME = [+ process.env.CHROME_PATH,+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "/Applications/Chromium.app/Contents/MacOS/Chromium",+ "/usr/bin/google-chrome",+ "/usr/bin/chromium"+].filter(Boolean);+const TYPES = { ".js": "text/javascript", ".mjs": "text/javascript", ".ttf": "font/ttf", ".otf": "font/otf",+ ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".html": "text/html" };++const { values: opts, positionals } = parseArgs({+ allowPositionals: true,+ options: {+ out: { type: "string" },+ width: { type: "string", default: "1928" },+ height: { type: "string", default: "1076" },+ fps: { type: "string", default: "24" },+ frames: { type: "string", default: "168" },+ only: { type: "string" },+ data: { type: "string", multiple: true, default: [] },+ chrome: { type: "string" }+ }+});+const sketch = positionals[0];+if (!sketch || !opts.out) {+ console.error("usage: node anim/render.mjs <sketch.js> --out <dir> [--width W --height H --fps N --frames N --only 0,12 --data name=file.json]");+ process.exit(2);+}++const cfg = {+ width: +opts.width, height: +opts.height, fps: +opts.fps, frames: +opts.frames,+ data: Object.fromEntries(opts.data.map((kv) => {+ const [name, file] = kv.split("=");+ return [name, JSON.parse(fs.readFileSync(file, "utf8"))];+ }))+};+const indices = opts.only ? opts.only.split(",").map(Number) : [...Array(cfg.frames).keys()];+const sketchUrl = "/" + path.relative(ROOT, path.resolve(sketch)).split(path.sep).join("/");+if (sketchUrl.startsWith("/..")) throw new Error(`sketch must live inside ${ROOT}`);++const page = `<!doctype html><html><head><meta charset="utf-8">+<style>html,body{margin:0;background:transparent}</style>+<script>window.ANIM = ${JSON.stringify({ ...cfg, frame: 0, t: 0, ready: false })};</script>+<script src="/node_modules/p5/lib/p5.min.js"></script>+${LIB.map((m) => `<script src="/tools/p5/lib/${m}.js"></script>`).join("\n")}+<script src="${sketchUrl}"></script>+</head><body></body></html>`;++// Static server rooted at the video project for p5, tools/p5/lib, selected tools/p5/fonts and sketches.+const server = http.createServer((req, res) => {+ const url = decodeURIComponent(new URL(req.url, "http://x").pathname);+ if (url === "/__anim__.html") return res.writeHead(200, { "content-type": "text/html" }).end(page);+ if (url === "/favicon.ico") return res.writeHead(204).end();+ const file = path.join(ROOT, url);+ if (!file.startsWith(ROOT) || !fs.existsSync(file)) return res.writeHead(404).end();+ res.writeHead(200, { "content-type": TYPES[path.extname(file)] || "application/octet-stream" });+ fs.createReadStream(file).pipe(res);+});+await new Promise((ok) => server.listen(0, "127.0.0.1", ok));++const executablePath = opts.chrome || CHROME.find((p) => fs.existsSync(p));+if (!executablePath) throw new Error("no Chrome found, pass --chrome or set CHROME_PATH");+const browser = await puppeteer.launch({ executablePath, headless: true, args: ["--force-color-profile=srgb"] });+const started = Date.now();+try {+ const tab = await browser.newPage();+ const errors = [];+ tab.on("pageerror", (e) => errors.push(e.message));+ tab.on("console", (m) => m.type() === "error" && !m.text().startsWith("Failed to load resource") && errors.push(m.text()));+ tab.on("response", (r) => r.status() >= 400 && errors.push(`${r.status()} ${r.url()}`));+ await tab.setViewport({ width: cfg.width, height: cfg.height, deviceScaleFactor: 1 });+ await tab.goto(`http://127.0.0.1:${server.address().port}/__anim__.html`);+ await tab.waitForFunction("window.ANIM.ready || window.ANIM.error", { timeout: 60_000 }).catch(() => {});+ const state = await tab.evaluate(() => ({ ready: ANIM.ready, error: ANIM.error }));+ if (!state.ready) throw new Error(`sketch did not start: ${state.error || errors.join("\n") || "timeout"}`);++ fs.mkdirSync(opts.out, { recursive: true });+ for (const i of indices) {+ const dataUrl = await tab.evaluate((i) => Anim.renderFrame(i), i);+ if (errors.length) throw new Error(`frame ${i}: ${errors.join("\n")}`);+ fs.writeFileSync(path.join(opts.out, `${String(i).padStart(4, "0")}.png`), Buffer.from(dataUrl.split(",")[1], "base64"));+ if (process.stderr.isTTY) process.stderr.write(`\rframe ${i + 1}/${cfg.frames}`);+ }+ if (process.stderr.isTTY) process.stderr.write("\n");+ console.log(JSON.stringify({ out: opts.out, frames: indices.length, width: cfg.width, height: cfg.height, fps: cfg.fps, ms: Date.now() - started }));+} finally {+ await browser.close();+ server.close();+}diff --git a/skills/make-an-anime/scripts/tools/python/audio_energy.py b/skills/make-an-anime/scripts/tools/python/audio_energy.pynew file mode 100644index 0000000..9a6c629--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/audio_energy.py@@ -0,0 +1,45 @@+#!/usr/bin/env python3+"""Loudness + vocal-band presence per window of a mono 16-bit wav.++usage: audio_energy.py file.wav [window_seconds]+prints JSON: {duration, rate, windows: [{t, rms_db, vocal_ratio}], silence_tail_s}+vocal_ratio = energy share in 300-3400 Hz (rough proxy for sung vocals).+"""+import json+import sys+import wave++import numpy as np+++def main():+ path = sys.argv[1]+ win_s = float(sys.argv[2]) if len(sys.argv) > 2 else 0.5+ with wave.open(path, "rb") as w:+ rate = w.getframerate()+ if w.getsampwidth() != 2:+ raise ValueError("audio_energy requires 16-bit PCM WAV")+ data = np.frombuffer(w.readframes(w.getnframes()), dtype=np.int16).astype(np.float32).reshape(-1, w.getnchannels()).mean(axis=1) / 32768.0+ n = int(rate * win_s)+ freqs = np.fft.rfftfreq(n, 1.0 / rate)+ band = (freqs >= 300) & (freqs <= 3400)+ windows = []+ for i in range(0, max(len(data) - n + 1, 1), n):+ chunk = data[i:i + n]+ if len(chunk) < n:+ chunk = np.pad(chunk, (0, n - len(chunk)))+ rms = float(np.sqrt(np.mean(chunk ** 2)) + 1e-9)+ spec = np.abs(np.fft.rfft(chunk * np.hanning(n))) ** 2+ ratio = float(spec[band].sum() / (spec.sum() + 1e-12))+ windows.append({"t": round(i / rate, 2), "rms_db": round(20 * np.log10(rms), 1), "vocal_ratio": round(ratio, 3)})+ tail = 0.0+ for wdw in reversed(windows):+ if wdw["rms_db"] < -45:+ tail += win_s+ else:+ break+ print(json.dumps({"duration": round(len(data) / rate, 3), "rate": rate, "windows": windows, "silence_tail_s": tail}))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/audio_seams.py b/skills/make-an-anime/scripts/tools/python/audio_seams.pynew file mode 100644index 0000000..093ab31--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/audio_seams.py@@ -0,0 +1,102 @@+"""Find abrupt audio in a film: every join between scenes, and hard changes inside a scene's score.++usage: audio_seams.py film.mp4 rows.json rows: [[run, seconds], ...] in film order; prints JSON.++seams: for each scene join, the level just before and just after it. A track that is still sounding in its last 30 ms was+ cut, not ended; one that is loud in its first 30 ms starts without a fade (fine for a hit, wrong for a bed).+joints: for each scene's score file, the biggest changes between the 0.4 s either side of a point, spectrum and level, with+ how far the point is from a composition-plan chunk boundary. A chunk boundary with sound on both sides and a big+ change is a hard change of music, the kind score_tool.py crossfade fixes.+"""+import glob+import json+import os+import re+import subprocess+import sys++import numpy as np++SR = 22050+++def pcm(path):+ cmd = ["ffmpeg", "-v", "error", "-i", path, "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"]+ return np.frombuffer(subprocess.run(cmd, capture_output=True).stdout, dtype=np.float32)+++def db(x):+ return float(20 * np.log10(np.sqrt(np.mean(x ** 2)) + 1e-6)) if len(x) else -120.0+++def spectrum(x):+ s = np.abs(np.fft.rfft(x * np.hanning(len(x))))+ s = np.add.reduceat(s, np.unique(np.geomspace(1, len(s) - 1, 40).astype(int)))+ return s / (np.linalg.norm(s) + 1e-9)+++def seams(a, rows):+ out, t = [], 0.0+ for i, (run, seconds) in enumerate(rows):+ if i:+ c = int(t * SR)+ n = int(0.03 * SR)+ out.append({"join": f"{rows[i - 1][0]}>{run}", "at": round(t, 2),+ "last_30ms": round(db(a[c - n:c]), 1), "first_30ms": round(db(a[c:c + n]), 1),+ "cut": bool(db(a[c - n:c]) > -45), "hard_start": bool(db(a[c:c + n]) > -30)})+ t += seconds+ return out+++def score_file(run):+ configs = glob.glob("config/generations/*.rb") + ["config/generations.rb"]+ text = next((open(p).read() for p in configs if os.path.exists(p) and f'"{run}" =>' in open(p).read()), "")+ m = re.search(r'music_from: "([^"]+)"', text)+ if m and os.path.exists(m.group(1)):+ return m.group(1)+ takes = glob.glob(f"output/{run}/03_music_*s.wav")+ return max(takes, key=os.path.getmtime) if takes else None+++def chunk_times(run):+ path = f"prompts/{run}/03_score.json"+ if not os.path.exists(path):+ return []+ return list(np.cumsum([c["duration_ms"] / 1000 for c in json.load(open(path)).get("chunks", [])]))+++def joints(run):+ path = score_file(run)+ if not path:+ return []+ a, w, step, found = pcm(path), int(0.4 * SR), int(0.05 * SR), []+ for c in range(w, len(a) - w, step):+ before, after = a[c - w:c], a[c:c + w]+ la, lb = db(before), db(after)+ if max(la, lb) < -40:+ continue+ found.append((float(1 - np.dot(spectrum(before), spectrum(after))), c / SR, la, lb))+ found.sort(reverse=True)+ picked, chunks = [], chunk_times(run)+ for jump, at, la, lb in found:+ if jump < 0.5:+ break+ if all(abs(at - p["at"]) > 1.0 for p in picked):+ near = min((abs(at - c) for c in chunks), default=None)+ picked.append({"run": run, "at": round(at, 2), "jump": round(jump, 2), "before_db": round(la, 1), "after_db": round(lb, 1),+ "kind": "stop" if lb < -60 else "start" if la < -60 else "change",+ "chunk_boundary": bool(near is not None and near < 0.5), "file": path})+ if len(picked) == 3:+ break+ return picked+++def main():+ film, rows = sys.argv[1], json.load(open(sys.argv[2]))+ report = {"seams": seams(pcm(film), rows), "joints": [j for run, _ in rows for j in joints(run)]}+ report["joints"].sort(key=lambda j: -j["jump"])+ print(json.dumps(report))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/beats.py b/skills/make-an-anime/scripts/tools/python/beats.pynew file mode 100644index 0000000..269c1e4--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/beats.py@@ -0,0 +1,117 @@+#!/usr/bin/env python3+"""Beat grid + onsets of a song (numpy only), for placing VFX on the music.++usage: beats.py song.wav [fps]+prints JSON: {duration, fps, bpm, period, phase, beats: [{t, f, n, bar_pos, strength, low}],+ onsets: [{t, f, strength, low}], loudness: [{t, db}] (per 0.25s)}+strength/low = spectral flux (full band / < 150 Hz kick band) at the beat, normalised to the song's 95th percentile.+bar_pos = beat index within a 4/4 bar (0 = downbeat, picked as the phase with the most low-band energy).+"""+import json+import sys+import wave++import numpy as np++HOP = 256+N_FFT = 2048+++def read_mono(path):+ with wave.open(path, "rb") as w:+ rate, ch, width = w.getframerate(), w.getnchannels(), w.getsampwidth()+ raw = w.readframes(w.getnframes())+ if width != 2:+ raise SystemExit("need 16-bit wav")+ data = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0+ return data.reshape(-1, ch).mean(axis=1), rate+++def flux(mag, lo, hi):+ band = np.log1p(100 * mag[lo:hi])+ d = np.diff(band, axis=1, prepend=band[:, :1])+ return np.maximum(d, 0).sum(axis=0)+++def norm(x):+ x = x - np.median(x)+ return np.clip(x / (np.percentile(x, 95) + 1e-9), 0, None)+++def main():+ path = sys.argv[1]+ fps = float(sys.argv[2]) if len(sys.argv) > 2 else 24.0+ y, rate = read_mono(path)+ win = np.hanning(N_FFT).astype(np.float32)+ n = 1 + (len(y) - N_FFT) // HOP+ frames = np.lib.stride_tricks.as_strided(y, shape=(n, N_FFT), strides=(y.strides[0] * HOP, y.strides[0]))+ mag = np.abs(np.fft.rfft(frames * win, axis=1)).T+ freqs = np.fft.rfftfreq(N_FFT, 1.0 / rate)+ t = (np.arange(n) * HOP + N_FFT / 2) / rate++ full = norm(flux(mag, 1, len(freqs)))+ low = norm(flux(mag, 1, int(np.searchsorted(freqs, 150))))+ env = full + low++ # Tempo + phase: the comb (period, offset) over the whole song that lands on the most onset energy, 80–180 BPM,+ # coarse then fine. (Autocorrelation was ~0.4% off, a beat and a half of drift over a 140s song.)+ frame_rate = rate / HOP++ def comb(period, ph):+ idx = np.round((np.arange(ph, t[-1], period) - t[0]) * frame_rate).astype(int)+ idx = idx[(idx >= 0) & (idx < len(env))]+ return env[idx].mean()++ def best(bpms, n_phase):+ cands = []+ for bpm in bpms:+ p = 60 / bpm+ phs = np.linspace(0, p, n_phase, endpoint=False)+ scores = [comb(p, ph) for ph in phs]+ k = int(np.argmax(scores))+ cands.append((scores[k], p, phs[k]))+ return max(cands)++ _, period, _ = best(np.arange(80, 180, 0.25), 48)+ _, period, phase = best(np.arange(60 / period - 0.3, 60 / period + 0.3, 0.02), 128)+ grid = np.arange(phase, t[-1], period)++ # Snap every grid beat to the strongest onset within ±40 ms (small tempo drift).+ beats = []+ for i, bt in enumerate(grid):+ k = int(round((bt - t[0]) * frame_rate))+ lo_k, hi_k = max(k - 6, 0), min(k + 7, len(env))+ if lo_k >= hi_k:+ continue+ j = lo_k + int(np.argmax(env[lo_k:hi_k]))+ beats.append({"t": round(float(t[j]), 3), "n": i, "strength": round(float(full[j]), 2), "low": round(float(low[j]), 2)})++ # Downbeat: the phase of 4 with the most kick energy.+ bar = int(np.argmax([sum(b["low"] for b in beats if b["n"] % 4 == p) for p in range(4)]))+ for b in beats:+ b["bar_pos"] = (b["n"] - bar) % 4+ b["f"] = int(round(b["t"] * fps))++ # Onsets: local maxima of the envelope above threshold, ≥ 90 ms apart.+ onsets = []+ thr = 1.2+ last = -1.0+ for j in range(1, len(env) - 1):+ if env[j] >= thr and env[j] >= env[j - 1] and env[j] > env[j + 1] and t[j] - last >= 0.09:+ onsets.append({"t": round(float(t[j]), 3), "f": int(round(t[j] * fps)),+ "strength": round(float(full[j]), 2), "low": round(float(low[j]), 2)})+ last = t[j]++ step = int(0.25 * rate)+ loud = []+ for i in range(0, len(y) - step + 1, step):+ rms = float(np.sqrt(np.mean(y[i:i + step] ** 2)) + 1e-9)+ loud.append({"t": round(i / rate, 2), "db": round(20 * np.log10(rms), 1)})++ print(json.dumps({"duration": round(len(y) / rate, 3), "fps": fps, "bpm": round(60 / period, 2),+ "period": round(period, 4), "phase": round(float(phase), 4),+ "beats": beats, "onsets": onsets, "loudness": loud}))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/camera_motion.py b/skills/make-an-anime/scripts/tools/python/camera_motion.pynew file mode 100644index 0000000..e18ea95--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/camera_motion.py@@ -0,0 +1,101 @@+#!/usr/bin/env python3+"""Estimate the camera move between two frames of a shot (numpy + Pillow only).++usage: camera_motion.py first.png last.png++Searches zoom factors and, for each, the best translation by phase correlation on downscaled grayscale frames,+then keeps the zoom/shift with the highest normalised cross-correlation. Prints JSON:+ {"zoom": 1.18, "shift_x": -0.03, "shift_y": 0.02, "score": 0.91, "camera": "push-in ×1.18, pan left 3%"}+zoom > 1: the last frame shows a smaller, magnified part of the first (push-in / zoom in); < 1: pull-out.+shift_x / shift_y: where the matched region's centre sits relative to frame centre, as a fraction of width/height+(content moving left = camera panning right). A low score means the picture changed too much to match (a morph,+a cut, or heavy character motion) — check the strip by eye.+"""+import json+import sys++import numpy as np+from PIL import Image++W, H = 192, 108+++def load(path):+ return np.asarray(Image.open(path).convert("L").resize((W, H), Image.BILINEAR), dtype=np.float64)+++def crop_zoom(img_path, zoom):+ """Centre crop of 1/zoom of the frame, resized back to W×H (what a push-in by `zoom` would show)."""+ im = Image.open(img_path).convert("L")+ w, h = im.size+ cw, ch = w / zoom, h / zoom+ box = ((w - cw) / 2, (h - ch) / 2, (w + cw) / 2, (h + ch) / 2)+ return np.asarray(im.crop(box).resize((W, H), Image.BILINEAR), dtype=np.float64)+++def phase_shift(a, b):+ """Integer (dy, dx) such that b ≈ a shifted by (dy, dx)."""+ win = np.outer(np.hanning(H), np.hanning(W))+ fa, fb = np.fft.fft2((a - a.mean()) * win), np.fft.fft2((b - b.mean()) * win)+ r = fb * np.conj(fa)+ r /= np.abs(r) + 1e-9+ corr = np.fft.ifft2(r).real+ dy, dx = np.unravel_index(np.argmax(corr), corr.shape)+ if dy > H // 2:+ dy -= H+ if dx > W // 2:+ dx -= W+ return int(dy), int(dx)+++def ncc(a, b, dy, dx):+ """Normalised cross-correlation of the overlap of a shifted by (dy, dx) with b."""+ ys, yd = (slice(0, H - dy), slice(dy, H)) if dy >= 0 else (slice(-dy, H), slice(0, H + dy))+ xs, xd = (slice(0, W - dx), slice(dx, W)) if dx >= 0 else (slice(-dx, W), slice(0, W + dx))+ pa, pb = a[ys, xs], b[yd, xd]+ if pa.size < (H * W) // 4:+ return -1.0+ pa, pb = pa - pa.mean(), pb - pb.mean()+ return float((pa * pb).sum() / (np.sqrt((pa ** 2).sum() * (pb ** 2).sum()) + 1e-9))+++def describe(zoom, sx, sy):+ parts = []+ if zoom > 1.03:+ parts.append(f"push-in ×{zoom:.2f}")+ elif zoom < 0.97:+ parts.append(f"pull-out ×{zoom:.2f}")+ # The region the camera ends on sits at (sx, sy) in the first frame: right of centre = the camera panned right.+ if abs(sx) >= 0.02:+ parts.append(f"pan {'right' if sx > 0 else 'left'} {abs(sx) * 100:.0f}%")+ if abs(sy) >= 0.02:+ parts.append(f"tilt/pedestal {'down' if sy > 0 else 'up'} {abs(sy) * 100:.0f}%")+ return ", ".join(parts) or "static (no measurable camera move)"+++def main(first, last):+ b = load(last)+ a_full = load(first)+ best = None+ for zoom in np.round(np.arange(0.55, 1.901, 0.01), 2):+ if zoom >= 1:+ a = crop_zoom(first, zoom) # the first frame magnified: compare with the last frame+ ref, cand = a, b+ else:+ ref, cand = a_full, crop_zoom(last, 1 / zoom) # the last frame magnified back: compare with the first+ dy, dx = phase_shift(ref, cand)+ score = ncc(ref, cand, dy, dx)+ if best is None or score > best[0]:+ best = (score, float(zoom), dy, dx)+ score, zoom, dy, dx = best+ # Shift of content between ref and cand -> where the end framing sits in the first frame (fractions of the frame).+ scale = zoom if zoom >= 1 else 1.0+ sx, sy = -dx / W / scale, -dy / H / scale+ print(json.dumps({"zoom": round(zoom, 3), "shift_x": round(sx, 3), "shift_y": round(sy, 3),+ "score": round(score, 3), "camera": describe(zoom, sx, sy)}))+++if __name__ == "__main__":+ if len(sys.argv) != 3:+ sys.exit(__doc__)+ main(sys.argv[1], sys.argv[2])diff --git a/skills/make-an-anime/scripts/tools/python/cutout.py b/skills/make-an-anime/scripts/tools/python/cutout.pynew file mode 100644index 0000000..7e0eb24--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/cutout.py@@ -0,0 +1,104 @@+#!/usr/bin/env python3+"""Cut a character out of a video (or still) into a transparent PNG sequence, for p5 sprites.++usage: cutout.py SOURCE OUT_DIR KEY [--box X Y W H] [--seed X Y] [--frames N] [--start N] [--scale S] [--tol T]+ SOURCE video or image; KEY is "green" (flat chroma-key background), "paper" (cream paper background) or "none"+ (no keying: the crop stays fully opaque, for full-frame scene clips that contain green, e.g. plants)+ --box crop in source pixels (default: the whole frame); --seed a point on the character (default: box centre)+ --frames / --start which frames of a video (default: all from 0); --scale resize the cut-outs (default 1)+ --tol paper colour tolerance (default 28, RGB distance after a median filter)+paper: the background is the paper connected to the crop border (flood fill on a median-filtered copy, so paper grain+does not stop it and the character's cream skin/face, enclosed by its outlines, stays opaque); then only the component+under --seed is kept (drops loose strokes such as speed lines). green: alpha from green dominance, with despill.+Writes OUT_DIR/0000.png … and prints JSON {"frames", "w", "h", "box", "src" (source frame size), "scale"}.+"""+import argparse+import json+import os+import subprocess++import numpy as np+from PIL import Image, ImageDraw, ImageFilter+++def frames(source, start, count):+ if os.path.splitext(source)[1].lower() in (".png", ".jpg", ".jpeg", ".webp"):+ yield Image.open(source).convert("RGB")+ return+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",+ "-of", "csv=p=0", source], capture_output=True, check=True, text=True).stdout+ w, h = map(int, out.strip().split(",")[:2])+ vf = f"select=gte(n\\,{start})" + (f"*lt(n\\,{start + count})" if count else "")+ proc = subprocess.Popen(["ffmpeg", "-v", "error", "-i", source, "-vf", vf, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],+ stdout=subprocess.PIPE)+ size = w * h * 3+ while (buf := proc.stdout.read(size)) and len(buf) == size:+ yield Image.frombuffer("RGB", (w, h), buf)+ proc.wait()+++def paper_alpha(img, seed, tol):+ small = img.resize((img.width // 4, img.height // 4), Image.BILINEAR).filter(ImageFilter.MedianFilter(5))+ w, h = small.size+ mark = (255, 0, 255)+ for x, y in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1), (w // 2, 0), (w // 2, h - 1), (0, h // 2), (w - 1, h // 2)]:+ if small.getpixel((x, y)) != mark:+ ImageDraw.floodfill(small, (x, y), mark, thresh=tol)+ # .copy(): PIL's floodfill is a silent no-op on the read-only images Image.fromarray makes+ fg = Image.fromarray(np.where((np.asarray(small) == mark).all(-1), 0, 255).astype(np.uint8)).copy()+ # keep the component under the seed (fill it grey, then keep grey)+ sx, sy = min(w - 1, seed[0] // 4), min(h - 1, seed[1] // 4)+ if fg.getpixel((sx, sy)) == 255:+ ImageDraw.floodfill(fg, (sx, sy), 128)+ fg = Image.fromarray(np.where(np.asarray(fg) == 128, 255, 0).astype(np.uint8))+ return fg.resize(img.size, Image.BILINEAR).filter(ImageFilter.GaussianBlur(1))+++def green_alpha(img, low=25):+ a = np.asarray(img).astype(np.int16)+ r, g, b = a[..., 0], a[..., 1], a[..., 2]+ dom = g - np.maximum(r, b) # how much greener than the other channels+ alpha = np.clip(255 - (dom - low) * 6, 0, 255)+ if low < 25:+ # A strict key also clears the dim olive where fire glow lit the green; bright flame and white cloth are untouched.+ olive = (g - b > 50) & (r < 205) & (dom > -35)+ alpha = np.where(olive, np.minimum(alpha, np.clip((-dom - 5) * 9, 0, 255)), alpha)+ alpha = alpha.astype(np.uint8)+ return Image.fromarray(alpha).filter(ImageFilter.MinFilter(3)).filter(ImageFilter.GaussianBlur(0.8))+++def despill(img, low=25):+ a = np.asarray(img).astype(np.int16)+ other = np.maximum(a[..., 0], a[..., 2])+ # A strict key is for warm glow on the green: what stays greener than red and blue turns back to the glow's own colour.+ a[..., 1] = np.minimum(a[..., 1], other + 10) if low >= 25 else np.where(a[..., 1] > other, other * 3 // 4, a[..., 1])+ return Image.fromarray(a.clip(0, 255).astype(np.uint8))+++def main():+ p = argparse.ArgumentParser()+ p.add_argument("source"); p.add_argument("out"); p.add_argument("key", choices=["green", "paper", "none"])+ p.add_argument("--low", type=int, default=25, help="green key: how much greener than red and blue a pixel may be and stay opaque; lower removes fire or glow cast on the green")+ p.add_argument("--box", type=int, nargs=4); p.add_argument("--seed", type=int, nargs=2)+ p.add_argument("--frames", type=int, default=0); p.add_argument("--start", type=int, default=0)+ p.add_argument("--scale", type=float, default=1.0); p.add_argument("--tol", type=int, default=28)+ o = p.parse_args()+ os.makedirs(o.out, exist_ok=True)+ n = 0+ for img in frames(o.source, o.start, o.frames):+ src = [img.width, img.height]+ box = o.box or [0, 0, img.width, img.height]+ img = img.crop((box[0], box[1], box[0] + box[2], box[1] + box[3]))+ seed = [o.seed[0] - box[0], o.seed[1] - box[1]] if o.seed else [box[2] // 2, box[3] // 2]+ rgba = (despill(img, o.low) if o.key == "green" else img).convert("RGBA")+ if o.key != "none":+ rgba.putalpha(green_alpha(img, o.low) if o.key == "green" else paper_alpha(img, seed, o.tol))+ if o.scale != 1:+ rgba = rgba.resize((round(rgba.width * o.scale), round(rgba.height * o.scale)), Image.LANCZOS)+ rgba.save(os.path.join(o.out, f"{n:04d}.png"))+ n += 1+ print(json.dumps({"frames": n, "w": rgba.width, "h": rgba.height, "box": box, "src": src, "scale": o.scale}))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/cuts.py b/skills/make-an-anime/scripts/tools/python/cuts.pynew file mode 100644index 0000000..b23ddc8--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/cuts.py@@ -0,0 +1,32 @@+#!/usr/bin/env python3+"""Hard cuts of a video: frames whose picture differs sharply from the previous one (mean abs diff of 96x54 grey thumbnails).++usage: cuts.py video.mp4 [threshold]+prints JSON: {frames, cuts: [{f, diff}], diff: [per-frame diff]} (cut = diff ≥ threshold and ≥ 3x the median of its ±6 neighbours)+"""+import json+import subprocess+import sys++import numpy as np++W, H = 96, 54+++def main():+ video = sys.argv[1]+ thr = float(sys.argv[2]) if len(sys.argv) > 2 else 18.0+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", video, "-vf", f"scale={W}:{H},format=gray", "-f", "rawvideo", "-"],+ capture_output=True, check=True).stdout+ frames = np.frombuffer(raw, dtype=np.uint8).reshape(-1, H, W).astype(np.float32)+ diff = np.concatenate([[0.0], np.abs(np.diff(frames, axis=0)).mean(axis=(1, 2))])+ cuts = []+ for i in range(1, len(diff)):+ near = np.concatenate([diff[max(i - 6, 1):i], diff[i + 1:i + 7]])+ if diff[i] >= thr and diff[i] >= 3 * (np.median(near) if len(near) else 0):+ cuts.append({"f": i, "diff": round(float(diff[i]), 1)})+ print(json.dumps({"frames": len(frames), "cuts": cuts, "diff": [round(float(d), 1) for d in diff]}))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/keep_component.py b/skills/make-an-anime/scripts/tools/python/keep_component.pynew file mode 100644index 0000000..319c3a0--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/keep_component.py@@ -0,0 +1,79 @@+"""Keep the four-connected nonzero-alpha component containing an explicit seed.++No erosion, dilation, resampling or synthesis: every selected RGBA pixel is exact.+Touching lettering is part of the same component and requires a separate mask.+Stage the complete sequence before publication so a missing seed cannot leave a+partially cleaned sequence that looks successful.+"""+import argparse+import json+import os+from pathlib import Path+import sys+import tempfile++import numpy as np+from PIL import Image, ImageDraw+++def clean_sequence(source, output, seed_x, seed_y):+ source, output = Path(source).resolve(), Path(output).resolve()+ if source == output:+ raise ValueError("source and output must be different directories")+ if not source.is_dir():+ raise ValueError("source must be a PNG sequence directory")+ if seed_x < 0 or seed_y < 0:+ raise ValueError("seed coordinates must be nonnegative")+ frames = sorted(source.glob("*.png"))+ if not frames:+ raise ValueError("source contains no PNG frames")+ if output.exists() and (not output.is_dir() or any(output.iterdir())):+ raise ValueError("output must be a new or empty directory; retain earlier takes")+ output.parent.mkdir(parents=True, exist_ok=True)+ metrics = []+ with tempfile.TemporaryDirectory(prefix=".component-", dir=output.parent) as temp:+ stage = Path(temp) / "frames"+ stage.mkdir()+ for path in frames:+ with Image.open(path) as original:+ if "A" not in original.getbands() and "transparency" not in original.info:+ raise ValueError(f"{path.name}: PNG has no alpha channel")+ image = original.convert("RGBA")+ if seed_x >= image.width or seed_y >= image.height:+ raise ValueError(f"{path.name}: seed is outside image bounds")+ rgba = np.array(image)+ alpha = rgba[:, :, 3]+ if alpha[seed_y, seed_x] == 0:+ raise ValueError(f"{path.name}: seed component is absent (transparent seed)")+ # Explicit copy makes Pillow's NumPy-backed image writable for floodfill.+ mask = Image.fromarray(np.where(alpha > 0, 255, 0).astype(np.uint8)).copy()+ ImageDraw.floodfill(mask, (seed_x, seed_y), 128)+ keep = np.asarray(mask) == 128+ removed = int(np.count_nonzero((alpha > 0) & ~keep))+ rgba[:, :, 3] = np.where(keep, alpha, 0)+ Image.fromarray(rgba).save(stage / path.name)+ metrics.append({"frame": path.name, "removed_pixels": removed,+ "remaining_pixels": int(np.count_nonzero(keep))})+ os.replace(stage, output)+ return {"out": str(output), "frames": len(metrics), "seed": [seed_x, seed_y],+ "connectivity": 4, "metrics": metrics}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("source")+ parser.add_argument("output")+ parser.add_argument("seed_x", type=int)+ parser.add_argument("seed_y", type=int)+ args = parser.parse_args()+ try:+ result = clean_sequence(args.source, args.output, args.seed_x, args.seed_y)+ except (ValueError, OSError) as error:+ print(f"keep_component: {error}", file=sys.stderr)+ return 1+ print(json.dumps(result))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/make-an-anime/scripts/tools/python/mouth_sync.py b/skills/make-an-anime/scripts/tools/python/mouth_sync.pynew file mode 100644index 0000000..4df9b69--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/mouth_sync.py@@ -0,0 +1,86 @@+#!/usr/bin/env python3+"""Measure a lip-synced sprite clip against a vocal stem.++ python3 scripts/mouth_sync.py <clip_dir> <vocals.wav> <song_start_s> X Y W H [--pauses 55.79-56.04,57.88-58.21]++<clip_dir> holds the cut-out frames 0000.png… (sprite frame i shows song time song_start_s + i/24). X Y W H is a box around the+mouth in sprite pixels. Per frame: openness = share of dark pixels in the box (an open mouth shows its dark inside) and the vocal's+level at that frame. Prints the correlation at lags -6..+6 frames (positive = the mouth comes late), the mouth's movement inside each+pause, and a per-frame table. The JSON summary goes to stdout's last line.+"""+import glob+import json+import sys+import wave++import numpy as np+from PIL import Image+++def vocal_db(path, start, n, fps=24):+ w = wave.open(path)+ sr, ch, sw = w.getframerate(), w.getnchannels(), w.getsampwidth()+ dtype = {2: np.int16, 4: np.int32}[sw]+ x = np.frombuffer(w.readframes(w.getnframes()), dtype=dtype).reshape(-1, ch).mean(1) / float(2 ** (8 * sw - 1))+ out = []+ for i in range(n):+ a, b = int((start + i / fps) * sr), int((start + (i + 1) / fps) * sr)+ seg = x[a:b]+ out.append(20 * np.log10(np.sqrt((seg ** 2).mean()) + 1e-9) if len(seg) else -120.0)+ return np.array(out)+++def openness(clip_dir, n, box):+ x, y, w, h = box+ vals = []+ for i in range(n):+ im = np.asarray(Image.open(f"{clip_dir}/{i:04d}.png").convert("RGBA")).astype(float)[y:y + h, x:x + w]+ rgb, a = im[..., :3], im[..., 3]+ lum = rgb @ [0.299, 0.587, 0.114]+ dark = (lum < 95) & (a > 128)+ vals.append(dark.mean())+ return np.array(vals)+++def main():+ args = sys.argv[1:]+ pauses = []+ if "--pauses" in args:+ k = args.index("--pauses")+ pauses = [tuple(map(float, p.split("-"))) for p in args[k + 1].split(",")]+ del args[k:k + 2]+ clip_dir, wav, start = args[0], args[1], float(args[2])+ box = tuple(int(v) for v in args[3:7])+ n = len(glob.glob(f"{clip_dir}/*.png"))+ mouth = openness(clip_dir, n, box)+ voc = vocal_db(wav, start, n)+ voiced = (voc > -36).astype(float)+ m = (mouth - mouth.mean()) / (mouth.std() + 1e-9)+ v = (np.clip(voc, -60, 0) - np.clip(voc, -60, 0).mean()) / (np.clip(voc, -60, 0).std() + 1e-9)+ corr = {}+ for lag in range(-6, 7): # mouth[i + lag] vs voice[i]+ a = m[max(0, lag):n + min(0, lag)]+ b = v[max(0, -lag):n - max(0, lag)]+ corr[lag] = float(np.corrcoef(a, b)[0, 1])+ best = max(corr, key=corr.get)+ print("lag (frames, + = mouth late): " + " ".join(f"{k:+d}:{c:+.2f}" for k, c in corr.items()))+ print(f"best lag {best:+d} frames (r = {corr[best]:+.2f})")+ talk = mouth[voiced > 0]+ rep = {"best_lag": best, "r": round(corr[best], 3), "mouth_voiced": round(float(talk.mean()), 4) if len(talk) else None,+ "pauses": []}+ for a, b in pauses:+ idx = [i for i in range(n) if a <= start + i / 24 < b]+ if not idx:+ continue+ seg = mouth[idx]+ info = {"pause": [a, b], "mean": round(float(seg.mean()), 4), "range": round(float(seg.max() - seg.min()), 4)}+ rep["pauses"].append(info)+ print(f"pause {a:.2f}-{b:.2f}: mouth mean {seg.mean():.4f} (voiced mean {talk.mean():.4f}), movement {seg.max() - seg.min():.4f}")+ for i in range(n):+ s = start + i / 24+ print(f"{i:3d} {s:6.2f} voice {voc[i]:6.1f} {'#' * max(0, int((voc[i] + 50) / 2)):<25s} mouth {mouth[i]:.3f} {'*' * int(mouth[i] * 150)}")+ print(json.dumps(rep))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/score_tool.py b/skills/make-an-anime/scripts/tools/python/score_tool.pynew file mode 100644index 0000000..768fb74--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/score_tool.py@@ -0,0 +1,136 @@+"""Small local edits of a shaped score wav, numpy only, no Fal calls.+Usage: .venv/bin/python3 -I tools/python/score_tool.py <cmd> IN OUT args...+ insert IN OUT T L [CF] rewind: at T jump back L seconds (inserts x[T-L:T] again), crossfade CF (default 0.06)+ remove IN OUT T L [CF] cut L seconds starting at T, crossfade CF+ freeze IN OUT T A B END DB0 DB1 from T add a spectral freeze of x[A:B] whose level goes DB0 -> DB1 (dBFS RMS) by+ END-0.4, faded out by END; the file is padded/trimmed to END seconds+ length IN OUT SECONDS [FADE] pad with silence / trim to SECONDS, optional fade-out FADE at the end+ crossfade IN OUT T L a hard change of music at T becomes a crossfade over L seconds: the last chord before T is+ held (spectral freeze) and fades out while the new section fades in; the length is unchanged+ soften IN OUT T L in|out an abrupt start or stop of the music at T gets a fade of L seconds, after T for in, before T for out+"""+import sys, wave+import numpy as np+++def load(p):+ w = wave.open(p)+ sr, ch = w.getframerate(), w.getnchannels()+ assert w.getsampwidth() == 2+ x = np.frombuffer(w.readframes(w.getnframes()), np.int16).reshape(-1, ch).astype(np.float64) / 32768+ return x, sr+++def save(p, x, sr):+ y = np.clip(np.round(x * 32768), -32768, 32767).astype(np.int16)+ w = wave.open(p, "wb")+ w.setnchannels(x.shape[1]); w.setsampwidth(2); w.setframerate(sr)+ w.writeframes(y.tobytes()); w.close()+++def xfade(a, b, n):+ """a then b, overlapping the last n samples of a with the first n of b (equal power)."""+ t = np.linspace(0, 1, n)[:, None]+ mid = a[-n:] * np.cos(t * np.pi / 2) + b[:n] * np.sin(t * np.pi / 2)+ return np.concatenate([a[:-n], mid, b[n:]])+++def insert(x, sr, T, L, cf):+ T, S, h = int(round(T * sr)), int(round((T - L) * sr)), int(cf * sr / 2)+ return xfade(x[:T + h], x[S - h:], 2 * h)+++def remove(x, sr, T, L, cf):+ T, E, h = int(round(T * sr)), int(round((T + L) * sr)), int(cf * sr / 2)+ return xfade(x[:T + h], x[E - h:], 2 * h)+++def hold(seg, n, sr, seed=39):+ """n samples sustaining seg's sound: its averaged spectrum resynthesised with new phases, at seg's level."""+ n_fft, hop = 4096, 1024+ win = np.hanning(n_fft)+ rng = np.random.default_rng(seed)+ out = np.zeros((n + n_fft, seg.shape[1]))+ for c in range(seg.shape[1]):+ frames = [np.abs(np.fft.rfft(seg[i:i + n_fft, c] * win)) for i in range(0, max(len(seg) - n_fft, 1), hop)]+ mag = np.mean(frames, axis=0)+ for i in range(0, n, hop):+ phase = rng.uniform(0, 2 * np.pi, len(mag))+ out[i:i + n_fft, c] += np.fft.irfft(mag * np.exp(1j * phase), n_fft) * win+ out = out[:n]+ rms = lambda a: np.sqrt(np.mean(a ** 2)) + 1e-9+ return out * (rms(seg) / rms(out))+++def crossfade(x, sr, T, L):+ t, n = int(T * sr), int(L * sr)+ x = x.copy()+ held = hold(x[max(t - int(0.6 * sr), 0):t], n, sr)+ ramp = np.linspace(0, 1, n)[:, None]+ x[t:t + n] = x[t:t + n] * np.sin(ramp * np.pi / 2) + held * np.cos(ramp * np.pi / 2)+ return x+++def soften(x, sr, T, L, kind):+ x = x.copy()+ t, n = int(T * sr), int(L * sr)+ ramp = np.linspace(0, 1, n)[:, None]+ if kind == "in":+ x[t:t + n] *= ramp+ else:+ x[t - n:t] *= ramp[::-1]+ return x+++def freeze(x, sr, T, A, B, END, db0, db1):+ n_fft, hop = 4096, 1024+ win = np.hanning(n_fft)+ seg = x[int(A * sr):int(B * sr)]+ total = int(round(END * sr))+ if len(x) < total:+ x = np.concatenate([x, np.zeros((total - len(x), x.shape[1]))])+ x = x[:total].copy()+ start = int(T * sr) - int(0.1 * sr)+ n = total - start+ rng = np.random.default_rng(38)+ out = np.zeros((n + n_fft, x.shape[1]))+ for c in range(x.shape[1]):+ frames = [np.abs(np.fft.rfft(seg[i:i + n_fft, c] * win)) for i in range(0, len(seg) - n_fft, hop // 2)]+ mag = np.mean(frames, axis=0)+ for i in range(0, n, hop):+ ph = np.exp(2j * np.pi * rng.random(len(mag)))+ out[i:i + n_fft, c] += np.fft.irfft(mag * ph) * win+ out = out[:n]+ rms = np.sqrt((out[int(0.3 * sr):] ** 2).mean()) + 1e-12+ t = np.arange(n) / sr+ dur = (total - start) / sr+ lvl = 10 ** ((db0 + (db1 - db0) * np.clip((t - 0.1) / max(0.1, dur - 0.5), 0, 1)) / 20)+ env = lvl / rms * np.clip(t / 0.3, 0, 1) # fade in over 0.3 s from T-0.1+ env *= np.clip((dur - t) / 0.4, 0, 1) # fade out by END+ x[start:] += out * env[:, None]+ return x+++def length(x, sr, secs, fade):+ total = int(round(secs * sr))+ x = np.concatenate([x, np.zeros((max(0, total - len(x)), x.shape[1]))])[:total].copy()+ if fade:+ n = int(fade * sr)+ x[-n:] *= np.linspace(1, 0, n)[:, None]+ return x+++if __name__ == "__main__":+ cmd, src, dst, *a = sys.argv[1:]+ x, sr = load(src)+ kind = a.pop() if cmd == "soften" else None+ a = [float(v) for v in a]+ if cmd == "insert": y = insert(x, sr, a[0], a[1], a[2] if len(a) > 2 else 0.06)+ elif cmd == "remove": y = remove(x, sr, a[0], a[1], a[2] if len(a) > 2 else 0.06)+ elif cmd == "freeze": y = freeze(x, sr, *a)+ elif cmd == "length": y = length(x, sr, a[0], a[1] if len(a) > 1 else 0)+ elif cmd == "crossfade": y = crossfade(x, sr, a[0], a[1])+ elif cmd == "soften": y = soften(x, sr, a[0], a[1], kind)+ else: raise SystemExit(__doc__)+ save(dst, y, sr)+ print(f"{cmd}: {len(x)/sr:.3f}s -> {len(y)/sr:.3f}s peak {np.abs(y).max():.3f}")diff --git a/skills/make-an-anime/scripts/tools/python/sfx_mix.py b/skills/make-an-anime/scripts/tools/python/sfx_mix.pynew file mode 100644index 0000000..53781e2--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/sfx_mix.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""Mix sound-effect cues over a music track (Media::Sfx, rake sfx:mix).++usage: sfx_mix.py music.wav cues.json out.wav [--floor-db -30] [--peak-db -6] [--max-gain-db 18]+ [--level-ref ref.wav] [--voice voice.wav --voice-dip-db 6]++cues.json: [{ "at": s, "wav": path, "sound": name, "rel_db": dB, "rate": 1.0, "len": s|null, "fade": s }, ...]++Each sound is decoded to 48 kHz stereo float, its leading silence trimmed (so it hits on the cue), optionally sped up / pitched by+`rate` and cut to `len` with a fade-out. Its level is set so that its loudness (RMS over its audible part, high-passed at 150 Hz as+a rough stand-in for perceived loudness) sits `rel_db` from the music's loudness in the same window, with the music floored at+`--floor-db` so a cue in a quiet passage stays audible, capped so the cue peaks at most at `--peak-db` and is never boosted by more+than `--max-gain-db`. The music is not changed; the sum goes through a peak limiter (-1 dBFS).+`--level-ref` measures that window in another file (the mix before a voice lift), so lifting a voice does not lift the cues with it.+`--voice` dips all the cues by `--voice-dip-db` while that track is speaking, so effects never sit on top of a line.+Prints a JSON report per cue: music dB, sfx gain, the cue's peak after gain and the limiter's deepest cut in its window.+"""+import argparse+import json+import subprocess++import numpy as np++SR = 48000+++def decode(path):+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "2", "-ar", str(SR), "-"],+ check=True, capture_output=True).stdout+ return np.frombuffer(raw, dtype=np.float32).reshape(-1, 2).astype(np.float64)+++def loudness_db(x, fc=150.0):+ """RMS in dB of the mono sum with everything under fc removed (FFT), a rough stand-in for perceived loudness."""+ if len(x) < 64:+ return -120.0+ m = x.mean(axis=1)+ spec = np.fft.rfft(m)+ spec[np.fft.rfftfreq(len(m), 1 / SR) < fc] = 0+ h = np.fft.irfft(spec, len(m))+ return 20 * np.log10(np.sqrt(np.mean(h ** 2)) + 1e-12)+++def trim_lead(x, thresh_db=-40.0):+ env = np.abs(x).max(axis=1)+ peak = env.max() + 1e-12+ on = np.nonzero(env > peak * 10 ** (thresh_db / 20))[0]+ if len(on) == 0:+ return x+ start = max(0, on[0] - int(0.003 * SR))+ end = on[-1] + int(0.02 * SR)+ return x[start:end]+++def active(x, thresh_db=-30.0):+ """The part of a sound above thresh (relative to its peak), for measuring its loudness."""+ env = np.abs(x).max(axis=1)+ peak = env.max() + 1e-12+ blk = int(0.01 * SR)+ n = len(env) // blk+ if n == 0:+ return x+ b = env[: n * blk].reshape(n, blk).max(axis=1)+ keep = np.repeat(b > peak * 10 ** (thresh_db / 20), blk)+ return x[: n * blk][keep]+++def resample(x, rate):+ if abs(rate - 1.0) < 1e-6:+ return x+ n = int(len(x) / rate)+ src = np.arange(n) * rate+ idx = np.arange(len(x))+ return np.stack([np.interp(src, idx, x[:, c]) for c in range(2)], axis=1)+++def voice_dip(voice, n, dip_db, attack=0.06, release=0.4, thresh_db=-45.0):+ """Per-sample gain for the cues: down by dip_db while the voice track is above thresh, smoothed so it never pumps."""+ blk = int(0.01 * SR)+ voice = np.vstack([voice, np.zeros((max(0, n - len(voice)), 2))])[:n]+ m = -(-n // blk)+ env = np.abs(np.vstack([voice, np.zeros((m * blk - n, 2))])).max(axis=1).reshape(m, blk).max(axis=1)+ want = np.where(env > 10 ** (thresh_db / 20), 10 ** (-dip_db / 20), 1.0)+ # Anticipate the line by the attack time: the dip is already there on its first syllable.+ lead = int(attack / 0.01)+ want = np.minimum(want, np.concatenate([want[lead:], np.ones(lead)]))+ att, rel = np.exp(-0.01 / attack), np.exp(-0.01 / release)+ out = np.empty(m)+ cur = 1.0+ for i, w in enumerate(want):+ k = att if w < cur else rel+ cur = w + (cur - w) * k+ out[i] = cur+ return np.repeat(out, blk)[:n]+++def limit(x, ceiling_db=-1.0, release=0.08):+ ceil = 10 ** (ceiling_db / 20)+ blk = int(0.0025 * SR)+ n = -(-len(x) // blk)+ pad = np.zeros((n * blk - len(x), 2))+ env = np.abs(np.vstack([x, pad])).max(axis=1).reshape(n, blk).max(axis=1)+ g = np.minimum(1.0, ceil / (env + 1e-12))+ # look ahead one block, then release smoothly (gain recovers at most by the release rate)+ g = np.minimum(g, np.concatenate([g[1:], [1.0]]))+ rel = np.exp(-blk / (release * SR))+ out = np.empty_like(g)+ cur = 1.0+ for i, gi in enumerate(g):+ cur = gi if gi < cur else gi + (cur - gi) * rel+ out[i] = cur+ gs = np.repeat(out, blk)[: len(x)]+ y = x * gs[:, None]+ return np.clip(y, -ceil, ceil), gs+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("music")+ ap.add_argument("cues")+ ap.add_argument("out")+ ap.add_argument("--floor-db", type=float, default=-30.0)+ ap.add_argument("--peak-db", type=float, default=-6.0)+ ap.add_argument("--max-gain-db", type=float, default=18.0)+ ap.add_argument("--level-ref")+ ap.add_argument("--voice")+ ap.add_argument("--voice-dip-db", type=float, default=0.0)+ a = ap.parse_args()++ music = decode(a.music)+ ref = decode(a.level_ref) if a.level_ref else music+ fx = np.zeros_like(music)+ cache = {}+ report = []+ for cue in json.load(open(a.cues)):+ if cue["wav"] not in cache:+ cache[cue["wav"]] = trim_lead(decode(cue["wav"]))+ s = resample(cache[cue["wav"]], cue.get("rate") or 1.0)+ if cue.get("len"):+ s = s[: int(cue["len"] * SR)].copy()+ fade = int((cue.get("fade") or 0.05) * SR)+ if fade and len(s) > fade:+ s[-fade:] *= np.linspace(1, 0, fade)[:, None]+ i0 = int(round(cue["at"] * SR))+ if i0 >= len(music):+ continue+ s = s[: len(music) - i0]+ m_db = max(loudness_db(ref[i0: i0 + len(s)]), a.floor_db)+ s_db = loudness_db(active(s))+ # loudness match, but never past the peak cap (the song is mastered near 0 dBFS, so hot transients would make the limiter+ # duck the music) or past max_gain (a near-silent generation would only bring its noise up)+ peak_raw = 20 * np.log10(np.abs(s).max() + 1e-12)+ gain_db = min(m_db + cue["rel_db"] - s_db, a.peak_db - peak_raw, a.max_gain_db)+ fx[i0: i0 + len(s)] += s * 10 ** (gain_db / 20)+ report.append({"at": cue["at"], "sound": cue.get("sound"), "music_db": round(m_db, 1), "gain_db": round(gain_db, 1),+ "peak_db": round(20 * np.log10(np.abs(s).max() + 1e-12) + gain_db, 1), "n": len(s)})++ if a.voice and a.voice_dip_db:+ fx = fx * voice_dip(decode(a.voice), len(fx), a.voice_dip_db)[:, None]+ mix, gs = limit(music + fx)+ for r in report:+ i0 = int(r["at"] * SR)+ w = gs[i0: i0 + r.pop("n")]+ r["limiter_db"] = round(20 * np.log10(w.min()), 1) if len(w) else 0.0+ pcm = (mix * 32767).astype(np.int16).tobytes()+ subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "s16le", "-ar", str(SR), "-ac", "2", "-i", "-", a.out], input=pcm, check=True)+ print(json.dumps({"cues": report, "limiter_db": round(20 * np.log10(gs.min()), 1)}))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/split_row.py b/skills/make-an-anime/scripts/tools/python/split_row.pynew file mode 100644index 0000000..a5f9308--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/split_row.py@@ -0,0 +1,76 @@+#!/usr/bin/env python3+"""Split a green-screen video of characters standing in a row into one video per character (gen4-anim17's dancers).++usage: split_row.py SOURCE OUT_PREFIX X1 X2 ... [--band 90]+ X1 X2 … the nominal x of each gap between neighbours (source pixels, left to right): N gaps -> N + 1 videos+ --band how far (px) a seam may wander from its gap's x+For every frame and every gap it finds the vertical seam (top to bottom, moving at most 1 px sideways per row) that crosses the+fewest character pixels within the band, so dancers whose raised hands touch or overlap are still cut apart along the cleanest line.+Writes OUT_PREFIX_0.mp4 … : the same frames with everything outside that character's strip painted flat chroma green (#00B140),+ready for Clips `source:` items with `key: green` (and a box around the strip).+"""+import argparse+import subprocess++import numpy as np++GREEN = np.array([0, 177, 64], np.uint8)+++def seam(cost):+ """Min-cost top-to-bottom path through cost (rows x cols), 8-connected; returns the column per row."""+ h, w = cost.shape+ acc = cost.astype(np.float64).copy()+ for y in range(1, h):+ prev = acc[y - 1]+ left = np.r_[np.inf, prev[:-1]]+ right = np.r_[prev[1:], np.inf]+ acc[y] += np.minimum(np.minimum(left, right) + 0.05, prev)+ path = np.empty(h, int)+ path[-1] = int(np.argmin(acc[-1]))+ for y in range(h - 2, -1, -1):+ x = path[y + 1]+ lo, hi = max(0, x - 1), min(w, x + 2)+ path[y] = lo + int(np.argmin(acc[y, lo:hi]))+ return path+++def main():+ p = argparse.ArgumentParser()+ p.add_argument("source"); p.add_argument("out_prefix"); p.add_argument("gaps", type=int, nargs="+")+ p.add_argument("--band", type=int, default=90)+ o = p.parse_args()+ probe = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",+ "-of", "csv=p=0", o.source], capture_output=True, check=True, text=True).stdout+ w, h = map(int, probe.strip().split(",")[:2])+ reader = subprocess.Popen(["ffmpeg", "-v", "error", "-i", o.source, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], stdout=subprocess.PIPE)+ n = len(o.gaps) + 1+ writers = [subprocess.Popen(["ffmpeg", "-y", "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", "24",+ "-i", "-", "-c:v", "libx264", "-crf", "12", "-pix_fmt", "yuv444p", f"{o.out_prefix}_{i}.mp4"],+ stdin=subprocess.PIPE) for i in range(n)]+ xs = np.arange(w)+ frames = 0+ while (buf := reader.stdout.read(w * h * 3)) and len(buf) == w * h * 3:+ img = np.frombuffer(buf, np.uint8).reshape(h, w, 3)+ a = img.astype(np.int16)+ fg = (a[..., 1] - np.maximum(a[..., 0], a[..., 2])) < 25+ cuts = []+ for g in o.gaps:+ lo, hi = max(0, g - o.band), min(w, g + o.band)+ # cost: character pixels, plus a gentle pull toward the nominal gap so empty rows don't wander+ cost = fg[:, lo:hi] * 10.0 + np.abs(np.arange(lo, hi) - g)[None, :] * 0.002+ cuts.append(lo + seam(cost))+ edges = [np.zeros(h, int)] + cuts + [np.full(h, w)]+ for i in range(n):+ inside = (xs[None, :] >= edges[i][:, None]) & (xs[None, :] < edges[i + 1][:, None])+ out = np.where(inside[..., None], img, GREEN)+ writers[i].stdin.write(out.astype(np.uint8).tobytes())+ frames += 1+ for wr in writers:+ wr.stdin.close(); wr.wait()+ reader.wait()+ print(f"{frames} frames -> {n} videos {o.out_prefix}_0..{n - 1}.mp4")+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/sprite_box.py b/skills/make-an-anime/scripts/tools/python/sprite_box.pynew file mode 100644index 0000000..8a4ae87--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/sprite_box.py@@ -0,0 +1,38 @@+#!/usr/bin/env python3+"""Measure where a character sits in a video or still, to fill `box:` / `seed:` in 04_clips.yml and size its sprite in the sketch.++usage: sprite_box.py SOURCE green|paper+ green: the character is everything that isn't chroma green; paper: everything far from the paper colour (sampled on the top/bottom rows).+ Videos are sampled every 6th frame and the boxes are unioned (plus a 24px margin), so the box holds the character through its motion.+ H3's extra marks (speed lines, impact ticks) widen the union; the cut-out keeps only the part connected to the seed anyway.+prints JSON (parsed by Media::Python#call): frames sampled, the character's extent [x0, y0, x1, y1], and `box` [x, y, w, h] / `seed` [x, y]+in source pixels, ready for 04_clips.yml.+"""+import json, subprocess, sys, numpy as np+from PIL import Image+src, key = sys.argv[1], sys.argv[2] # video or image, "green" | "paper"+if src.endswith((".png", ".jpg")):+ frames = [np.asarray(Image.open(src).convert("RGB")).astype(int)]+else:+ w, h = map(int, subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",+ "-of", "csv=p=0", src], capture_output=True, text=True).stdout.split(",")[:2])+ raw = subprocess.run(["ffmpeg", "-v", "error", "-i", src, "-vf", "select=not(mod(n\\,6))", "-fps_mode", "passthrough", "-f", "rawvideo",+ "-pix_fmt", "rgb24", "-"], capture_output=True).stdout+ frames = list(np.frombuffer(raw, np.uint8).reshape(-1, h, w, 3).astype(int))+boxes = []+for f in frames:+ r, g, b = f[..., 0], f[..., 1], f[..., 2]+ if key == "green":+ fg = (g - np.maximum(r, b)) < 25+ else:+ paper = np.median(np.concatenate([f[:8].reshape(-1, 3), f[-8:].reshape(-1, 3)]), axis=0)+ fg = np.abs(f - paper).sum(-1) > 150+ ys, xs = np.nonzero(fg)+ boxes.append([np.percentile(xs, 1), np.percentile(ys, 1), np.percentile(xs, 99), np.percentile(ys, 99)])+b = np.array(boxes)+x0, y0, x1, y1 = b[:, 0].min(), b[:, 1].min(), b[:, 2].max(), b[:, 3].max()+m = 24 # margin for motion / soft edges+H, W = frames[0].shape[:2]+box = [max(0, int(x0 - m)), max(0, int(y0 - m))]; box += [min(W, int(x1 + m)) - box[0], min(H, int(y1 + m)) - box[1]]+print(json.dumps({"frames_sampled": len(frames), "size": [W, H], "extent": [int(x0), int(y0), int(x1), int(y1)],+ "box": box, "seed": [int((x0 + x1) / 2), int((y0 + y1) / 2)]}))diff --git a/skills/make-an-anime/scripts/tools/python/style_split.py b/skills/make-an-anime/scripts/tools/python/style_split.pynew file mode 100644index 0000000..245fd1d--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/style_split.py@@ -0,0 +1,50 @@+#!/usr/bin/env python3+"""Measure how much of an image is monochrome line-art vs colored.++usage: style_split.py img1.png [img2.png ...]+prints JSON: {"images": [{path, mono_pct, color_pct, left_mono_pct, right_mono_pct,+ band_mono_pct: [top..bottom thirds]}], "mean_mono_pct": x}+"""+import json+import sys++import numpy as np+from PIL import Image++SAT_THRESHOLD = 0.12 # HSV saturation below this counts as monochrome+++def analyze(path):+ img = Image.open(path).convert("RGB")+ img.thumbnail((768, 768))+ hsv = np.asarray(img.convert("HSV"), dtype=np.float32) / 255.0+ sat, val = hsv[..., 1], hsv[..., 2]+ # ignore near-black pixels (saturation is meaningless there)+ valid = val > 0.15+ mono = (sat < SAT_THRESHOLD) & valid+ h, w = mono.shape++ def pct(mask, region=np.s_[:, :]):+ v = valid[region].sum()+ return round(100.0 * mask[region].sum() / v, 1) if v else 0.0++ thirds = [np.s_[i * h // 3:(i + 1) * h // 3, :] for i in range(3)]+ return {+ "path": path,+ "mono_pct": pct(mono),+ "color_pct": round(100.0 - pct(mono), 1),+ "left_mono_pct": pct(mono, np.s_[:, : w // 2]),+ "right_mono_pct": pct(mono, np.s_[:, w // 2:]),+ "band_mono_pct": [pct(mono, t) for t in thirds],+ "mean_saturation": round(float(sat[valid].mean()), 3),+ }+++def main():+ results = [analyze(p) for p in sys.argv[1:]]+ mean = round(sum(r["mono_pct"] for r in results) / len(results), 1) if results else 0+ print(json.dumps({"images": results, "mean_mono_pct": mean}))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/python/track_template.py b/skills/make-an-anime/scripts/tools/python/track_template.pynew file mode 100644index 0000000..2eb7bbe--- /dev/null+++ b/skills/make-an-anime/scripts/tools/python/track_template.py@@ -0,0 +1,91 @@+#!/usr/bin/env python3+"""Track a small feature (e.g. a hair clip) through a video by template matching.++usage: track_template.py video.mp4 X Y SIZE [SEARCH] [FROM]+ X Y centre of the feature in frame FROM (default 0, full-res pixels), SIZE its box side, SEARCH the max+ move per frame in px (default SIZE). Frames before FROM (e.g. earlier shots) repeat the seed with score 0.+prints JSON: {"fps", "width", "height", "points": [[x, y, score], ...]} — one point per frame, full-res,+lightly smoothed. score is the normalized cross-correlation (1 = identical to the frame-FROM patch).+Luminance NCC, computed with FFTs at half resolution; the template is the frame-FROM patch.+"""+import json+import subprocess+import sys++import numpy as np++SCALE = 2 # work at 1/SCALE resolution+++def probe(video):+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",+ "stream=width,height,r_frame_rate", "-of", "json", video],+ capture_output=True, check=True, text=True).stdout+ s = json.loads(out)["streams"][0]+ num, den = s["r_frame_rate"].split("/")+ return s["width"], s["height"], float(num) / float(den)+++def frames(video, w, h):+ proc = subprocess.Popen(["ffmpeg", "-v", "error", "-i", video, "-vf", f"scale={w}:{h}",+ "-f", "rawvideo", "-pix_fmt", "gray", "-"], stdout=subprocess.PIPE)+ size = w * h+ while chunk := proc.stdout.read(size):+ if len(chunk) < size:+ break+ yield np.frombuffer(chunk, np.uint8).reshape(h, w).astype(np.float64)+ proc.wait()+++def box_sum(a, k):+ """Sum over every k×k window (valid positions) via an integral image."""+ c = np.pad(a, ((1, 0), (1, 0))).cumsum(0).cumsum(1)+ return c[k:, k:] - c[:-k, k:] - c[k:, :-k] + c[:-k, :-k]+++def ncc(window, tmpl):+ k = tmpl.shape[0]+ t = tmpl - tmpl.mean()+ shape = [window.shape[0] + k - 1, window.shape[1] + k - 1]+ corr = np.fft.irfft2(np.fft.rfft2(window, shape) * np.fft.rfft2(t[::-1, ::-1], shape), shape)+ corr = corr[k - 1:window.shape[0], k - 1:window.shape[1]]+ n = k * k+ var = box_sum(window ** 2, k) - box_sum(window, k) ** 2 / n+ return corr / (np.sqrt(np.maximum(var, 1e-6)) * np.sqrt((t ** 2).sum()))+++def main():+ video, x, y, size = sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), int(sys.argv[4])+ search = int(sys.argv[5]) if len(sys.argv) > 5 else size+ start = int(sys.argv[6]) if len(sys.argv) > 6 else 0+ W, H, fps = probe(video)+ w, h = W // SCALE, H // SCALE+ k, r = size // SCALE, search // SCALE+ cx, cy = x / SCALE, y / SCALE+ tmpl, raw = None, []+ for n, img in enumerate(frames(video, w, h)):+ if n < start:+ raw.append([x, y, 0.0])+ continue+ if tmpl is None:+ x0, y0 = int(round(cx - k / 2)), int(round(cy - k / 2))+ tmpl = img[y0:y0 + k, x0:x0 + k]+ x0 = int(max(0, min(w - k, round(cx - k / 2 - r))))+ y0 = int(max(0, min(h - k, round(cy - k / 2 - r))))+ win = img[y0:min(h, y0 + k + 2 * r), x0:min(w, x0 + k + 2 * r)]+ score = ncc(win, tmpl)+ iy, ix = np.unravel_index(np.argmax(score), score.shape)+ cx, cy = x0 + ix + k / 2, y0 + iy + k / 2+ raw.append([cx * SCALE, cy * SCALE, float(score[iy, ix])])++ pts = np.array(raw)+ smooth = pts.copy()+ for i in range(start, len(pts)): # 3-frame centred moving average on x, y (within the tracked range)+ lo, hi = max(start, i - 1), min(len(pts), i + 2)+ smooth[i, :2] = pts[lo:hi, :2].mean(0)+ print(json.dumps({"fps": fps, "width": W, "height": H,+ "points": [[round(a, 1), round(b, 1), round(c, 3)] for a, b, c in smooth]}))+++if __name__ == "__main__":+ main()diff --git a/skills/make-an-anime/scripts/tools/vfx/Package.swift b/skills/make-an-anime/scripts/tools/vfx/Package.swiftnew file mode 100644index 0000000..8884500--- /dev/null+++ b/skills/make-an-anime/scripts/tools/vfx/Package.swift@@ -0,0 +1,12 @@+// swift-tools-version:5.9+// mvfx: post-processing VFX for the finished music video (zooms, glow, motion blur, edge blur, old TV, interference, flashes)+// with Core Image + AVFoundation, driven by a cue list (see prompts/run4-vfx/cues.yml and lib/media/vfx.rb).+import PackageDescription++let package = Package(+ name: "mvfx",+ platforms: [.macOS(.v14)],+ targets: [+ .executableTarget(name: "mvfx", path: "Sources/mvfx")+ ]+)diff --git a/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Cues.swift b/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Cues.swiftnew file mode 100644index 0000000..034f6eb--- /dev/null+++ b/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Cues.swift@@ -0,0 +1,65 @@+import Foundation++// One effect hit, from the cue list lib/media/vfx.rb writes (prompts/run4-vfx/cues.yml, frame numbers on the video's 24fps grid).+// f: the frame the effect hits (the beat), dur: frames it lasts from there, pre: frames of ramp-in before f.+// shape: "hit" (full at f, decays to 0 over dur) or "span" (fades in over `fade` frames from f, holds, fades out by f + dur).+// Every other field is a per-effect knob with a default in Effects.swift. Cues with an fx this tool doesn't know+// (the p5 light layer's leak/flare/glints) are skipped here; their frames reach the video through --lights.+struct Cue: Decodable {+ let fx: String+ let f: Int+ let dur: Int+ var pre: Int?+ var shape: String?+ var fade: Int?+ var amt: Double?+ var radius: Double?+ var x: Double?+ var y: Double?+ var angle: Double?+ var color: String?+ var hold: Int?+ var seed: Int?+ var grain: Double?++ var first: Int { f - (pre ?? 0) }+ var last: Int { f + dur }+ func active(_ frame: Int) -> Bool { frame >= first && frame < last }++ // 0...1 strength of the cue at `frame`.+ func env(_ frame: Int, defaultShape: String = "hit", curve: Double = 2.2) -> Double {+ guard active(frame) else { return 0 }+ if frame < f {+ let q = Double(frame - first + 1) / Double((pre ?? 0) + 1)+ return q * q+ }+ let t = Double(frame - f)+ switch shape ?? defaultShape {+ case "span":+ let fd = Double(max(fade ?? 4, 1))+ return min(1, (t + 1) / fd, (Double(dur) - t) / fd)+ default:+ return pow(1 - t / Double(max(dur, 1)), curve)+ }+ }+}++struct CueFile: Decodable {+ let cues: [Cue]+}++// Deterministic per-frame randomness (SplitMix64), so a re-render gives the same jitter and glitch bands.+struct Rand {+ private var state: UInt64+ init(_ a: Int, _ b: Int = 0) { state = UInt64(bitPattern: Int64(a &* 73_856_093 ^ b &* 19_349_663)) &+ 0x9E37_79B9_7F4A_7C15 }+ mutating func next() -> Double {+ state &+= 0x9E37_79B9_7F4A_7C15+ var z = state+ z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9+ z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB+ z ^= z >> 31+ return Double(z >> 11) / Double(1 << 53)+ }+ mutating func range(_ lo: Double, _ hi: Double) -> Double { lo + (hi - lo) * next() }+ mutating func sign() -> Double { next() < 0.5 ? -1 : 1 }+}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.swiftnew file mode 100644index 0000000..8909943--- /dev/null+++ b/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/Effects.swift@@ -0,0 +1,363 @@+import CoreImage+import CoreImage.CIFilterBuiltins+import Foundation++// The effect chain for one frame. Every active cue adds to a State (how much zoom, blur, glow… this frame), then the frame goes+// through the Core Image filters once, in a fixed order: camera (punch/zoom/shake/whip) -> blurs (zoom, motion, edge) -> light+// (glow, flash) -> the p5 light layer (screen blend) -> lens/signal damage (chromatic aberration, interference, old TV) -> dark flash.+//+// fx shape knobs (defaults)+// punch hit amt 0.06 (zoom-in fraction), radius 2 (zoom-blur amount; 10+ is a hard hit), x/y anchor 0.5/0.5 (0..1 from top-left)+// zoom ramp amt 0.08 (zoom reached at f + dur, from 0), x/y; hard reset after dur, so end it on a cut+// shake hit amt 14 (px)+// whip - around a cut at f: pre frames slide out, dur frames slide in; amt 0.12 (of width), radius 70, angle 0 (deg)+// mblur hit amt 30 (px), angle 0+// edgeblur span amt 10 (px), fade 6+// glow hit amt 1.0 (bloom intensity), radius 18+// flash hit amt 1.0, color #fffaf0+// dark hit amt 0.94 (black opacity), hold 2 (frames at full)+// rgb hit amt 0.006 (radial split, fraction of the frame)+// 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)+final class Effects {+ let extent: CGRect+ var w: CGFloat { extent.width }+ var h: CGFloat { extent.height }++ init(width: Int, height: Int) {+ extent = CGRect(x: 0, y: 0, width: width, height: height)+ }++ struct State {+ var scale = 1.0, anchor = CGPoint(x: 0.5, y: 0.5), dx = 0.0, dy = 0.0, rot = 0.0+ var zoomBlur = 0.0, motion = 0.0, motionAngle = 0.0, edge = 0.0+ 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 seed = 0+ }++ func state(frame: Int, cues: [Cue]) -> State {+ var s = State()+ s.seed = frame+ var anchorWeight = 0.0+ func anchor(_ c: Cue, _ e: Double) {+ guard e > anchorWeight else { return }+ anchorWeight = e+ s.anchor = CGPoint(x: c.x ?? 0.5, y: c.y ?? 0.5)+ }+ for c in cues where c.active(frame) {+ var r = Rand(frame, c.f)+ switch c.fx {+ case "punch":+ let e = c.env(frame, curve: 2.5)+ s.scale *= 1 + (c.amt ?? 0.06) * e+ s.zoomBlur += (c.radius ?? 2) * e * e * e+ s.rgb += 0.002 * e+ anchor(c, e)+ case "zoom":+ let p = Double(frame - c.f + 1) / Double(max(c.dur, 1))+ let e = p * p * (3 - 2 * p)+ s.scale *= 1 + (c.amt ?? 0.08) * max(0, e)+ anchor(c, 0.01)+ case "shake":+ let e = c.env(frame, curve: 2)+ let a = (c.amt ?? 14) * e+ s.dx += r.range(-a, a)+ s.dy += r.range(-a, a)+ s.rot += r.range(-0.006, 0.006) * e+ s.scale *= 1 + 2 * a / Double(h)+ case "whip":+ let rad = (c.angle ?? 0) * .pi / 180+ let dist = (c.amt ?? 0.12) * Double(w)+ var slide = 0.0, e = 0.0+ if frame < c.f {+ let q = Double(frame - c.first + 1) / Double((c.pre ?? 1) + 1)+ slide = dist * q * q * q+ e = q * q+ } else {+ let q = 1 - Double(frame - c.f) / Double(max(c.dur, 1))+ slide = -dist * q * q * q+ e = q * q+ }+ s.dx += cos(rad) * slide+ s.dy += sin(rad) * slide+ s.motion += (c.radius ?? 70) * e+ s.motionAngle = rad+ s.scale *= 1 + 0.03 * e+ case "mblur":+ s.motion += (c.amt ?? 30) * c.env(frame, curve: 2)+ s.motionAngle = (c.angle ?? 0) * .pi / 180+ case "edgeblur":+ s.edge += (c.amt ?? 10) * c.env(frame, defaultShape: "span")+ case "glow":+ s.bloom += (c.amt ?? 1) * c.env(frame, curve: 1.6)+ s.bloomRadius = c.radius ?? 18+ case "flash":+ s.flash += (c.amt ?? 1) * c.env(frame, curve: 2.8)+ if let hex = c.color { s.flashColor = Effects.color(hex) }+ case "dark":+ let hold = c.hold ?? 2+ let t = frame - c.f+ let e = t < 0 ? c.env(frame) : t < hold ? 1 : pow(1 - Double(t - hold) / Double(max(c.dur - hold, 1)), 2)+ s.dark = max(s.dark, (c.amt ?? 0.94) * e)+ case "rgb":+ s.rgb += (c.amt ?? 0.006) * c.env(frame, curve: 2)+ case "glitch":+ var e = (c.amt ?? 1) * c.env(frame, defaultShape: "span")+ if r.next() < 0.3 { e *= 0.15 } // flicker: some frames nearly clean+ s.glitch = max(s.glitch, e)+ s.seed = frame &* 31 &+ (c.seed ?? c.f)+ case "tv":+ s.tv = max(s.tv, (c.amt ?? 1) * c.env(frame, defaultShape: "span"))+ s.tvGrain = c.grain ?? 0.09+ case "grain":+ s.grain = max(s.grain, (c.amt ?? 0.25) * c.env(frame, defaultShape: "span"))+ default:+ continue+ }+ }+ if s.tv > 0 {+ var r = Rand(frame, 777)+ if r.next() < 0.18 { s.dy += r.sign() * 2 * s.tv } // line jitter+ }+ return s+ }++ func apply(_ src: CIImage, frame: Int, cues: [Cue], lights: CIImage?) -> CIImage {+ let s = state(frame: frame, cues: cues)+ var img = src++ // Camera + camera blurs on one edge-clamped, infinite image, cropped once: shakes and whips never show black, and no+ // crop -> clamp in between (Core Image folded a translated clamp, cropped and clamped again, into black edges on whips).+ if s.scale != 1 || s.dx != 0 || s.dy != 0 || s.rot != 0 || s.zoomBlur > 0.5 || s.motion > 0.5 {+ var inf = src.clampedToExtent()+ if s.scale != 1 || s.dx != 0 || s.dy != 0 || s.rot != 0 {+ let a = point(s.anchor)+ inf = inf.transformed(by: CGAffineTransform(translationX: -a.x, y: -a.y)+ .concatenating(CGAffineTransform(rotationAngle: s.rot))+ .concatenating(CGAffineTransform(scaleX: s.scale, y: s.scale))+ .concatenating(CGAffineTransform(translationX: a.x + s.dx, y: a.y - s.dy)))+ }+ if s.zoomBlur > 0.5 {+ let f = CIFilter.zoomBlur()+ f.inputImage = inf+ f.center = point(s.anchor)+ f.amount = Float(s.zoomBlur)+ inf = f.outputImage!+ }+ if s.motion > 0.5 {+ let f = CIFilter.motionBlur()+ f.inputImage = inf+ f.radius = Float(s.motion)+ f.angle = Float(s.motionAngle)+ inf = f.outputImage!+ }+ img = inf.cropped(to: extent)+ }+ if s.edge > 0.3 { img = edgeBlur(img, radius: s.edge) }++ // Light.+ if s.bloom > 0.01 {+ let f = CIFilter.bloom()+ f.inputImage = img.clampedToExtent()+ f.radius = Float(s.bloomRadius)+ f.intensity = Float(s.bloom)+ img = f.outputImage!.cropped(to: extent)+ }+ if s.flash > 0.01 {+ let e = CIFilter.exposureAdjust()+ e.inputImage = img+ 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 {+ let f = CIFilter.screenBlendMode()+ f.inputImage = lights+ f.backgroundImage = img+ img = f.outputImage!.cropped(to: extent)+ }++ // Lens / signal damage.+ if s.rgb > 0.0003 { img = chroma(img, radial: s.rgb, shift: 0) }+ if s.glitch > 0.02 { img = interference(img, amount: s.glitch, seed: s.seed) }+ if s.tv > 0.01 { img = oldTV(img, amount: s.tv, grain: s.tvGrain, frame: frame) }+ if s.grain > 0.005 { img = filmGrain(img, amount: s.grain, frame: frame) }+ if s.dark > 0.01 { img = over(solid(CIColor(red: 0.02, green: 0.02, blue: 0.05), alpha: s.dark), img) }+ return img.cropped(to: extent)+ }++ // MARK: effects++ // Sharp centre, blur growing toward the edges and corners (lens edge / dreamy focus).+ func edgeBlur(_ img: CIImage, radius: Double) -> CIImage {+ let g = CIFilter.radialGradient()+ g.center = CGPoint(x: w / 2, y: h / 2)+ g.radius0 = Float(h * 0.36)+ g.radius1 = Float(w * 0.62)+ g.color0 = CIColor.black+ g.color1 = CIColor.white+ let f = CIFilter.maskedVariableBlur()+ f.inputImage = img.clampedToExtent()+ f.mask = g.outputImage!.cropped(to: extent)+ f.radius = Float(radius)+ return f.outputImage!.cropped(to: extent)+ }++ // Split R and B: `radial` scales them apart around the centre (lens fringing), `shift` moves them sideways (px, signal error).+ func chroma(_ img: CIImage, radial: Double, shift: Double) -> CIImage {+ let c = CGPoint(x: w / 2, y: h / 2)+ func channel(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, scale: Double, dx: Double) -> CIImage {+ let m = CIFilter.colorMatrix()+ m.inputImage = img.clampedToExtent()+ m.rVector = CIVector(x: r, 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: b, w: 0)+ m.aVector = CIVector(x: 0, y: 0, z: 0, w: 1)+ let t = CGAffineTransform(translationX: -c.x, y: -c.y)+ .concatenating(CGAffineTransform(scaleX: scale, y: scale))+ .concatenating(CGAffineTransform(translationX: c.x + dx, y: c.y))+ return m.outputImage!.transformed(by: t)+ }+ let red = channel(1, 0, 0, scale: 1 + radial, dx: shift)+ let green = channel(0, 1, 0, scale: 1, dx: 0)+ let blue = channel(0, 0, 1, scale: 1 - radial, dx: -shift)+ return red.applyingFilter("CIMaximumCompositing", parameters: [kCIInputBackgroundImageKey: green])+ .applyingFilter("CIMaximumCompositing", parameters: [kCIInputBackgroundImageKey: blue])+ .cropped(to: extent)+ }++ // Analog interference: horizontal slices shoved sideways, an RGB split, a tinted band and white-noise bars.+ func interference(_ img: CIImage, amount a: Double, seed: Int) -> CIImage {+ var r = Rand(seed, 4242)+ var out = chroma(img, radial: 0, shift: (4 + 10 * r.next()) * a)+ let clamped = out.clampedToExtent()+ let bands = 2 + Int(r.next() * 5 * a)+ for _ in 0..<bands {+ let bh = r.range(6, 90) * (0.5 + a)+ let y = r.range(0, Double(h) - bh)+ let dx = r.sign() * r.range(12, 140) * a+ let rect = CGRect(x: 0, y: y, width: Double(w), height: bh)+ out = over(clamped.transformed(by: CGAffineTransform(translationX: dx, y: 0)).cropped(to: rect), out)+ }+ if r.next() < 0.6 * a { // one tinted band (magenta or cyan)+ let bh = r.range(20, 120)+ let rect = CGRect(x: 0, y: r.range(0, Double(h) - bh), width: Double(w), height: bh)+ let tint = r.next() < 0.5 ? CIColor(red: 1, green: 0.25, blue: 0.64) : CIColor(red: 0.2, green: 0.9, blue: 1)+ let band = solid(tint, alpha: 0.35 * a).cropped(to: rect)+ out = band.applyingFilter("CIScreenBlendMode", parameters: [kCIInputBackgroundImageKey: out])+ }+ let noise = grayNoise(seed: seed, alpha: 0.55 * a)+ for _ in 0..<(1 + Int(r.next() * 3 * a)) { // white-noise bars+ let bh = r.range(2, 18)+ let rect = CGRect(x: 0, y: r.range(0, Double(h) - bh), width: Double(w), height: bh)+ out = over(noise.cropped(to: rect), out)+ }+ return out.cropped(to: extent)+ }++ // A worn CRT: softer, faded colour, scanlines, grain, vignette and a slow bright bar rolling down.+ func oldTV(_ img: CIImage, amount a: Double, grain: Double, frame: Int) -> CIImage {+ var out = img+ let soft = CIFilter.gaussianBlur()+ soft.inputImage = out.clampedToExtent()+ soft.radius = Float(1.1 * a)+ out = soft.outputImage!.cropped(to: extent)+ out = chroma(out, radial: 0, shift: 2.5 * a)+ let cc = CIFilter.colorControls()+ cc.inputImage = out+ cc.saturation = Float(1 - 0.35 * a)+ cc.contrast = Float(1 + 0.1 * a)+ cc.brightness = Float(0.02 * a)+ out = cc.outputImage!+ let tint = CIFilter.colorMatrix() // a little green-warm phosphor cast+ tint.inputImage = out+ tint.rVector = CIVector(x: 1 - 0.02 * a, y: 0, z: 0, w: 0)+ tint.gVector = CIVector(x: 0, y: 1 + 0.02 * a, z: 0, w: 0)+ tint.bVector = CIVector(x: 0, y: 0, z: 1 - 0.08 * a, w: 0)+ out = tint.outputImage!.cropped(to: extent)++ let stripes = CIFilter.stripesGenerator() // vertical stripes, turned into scanlines+ stripes.color0 = CIColor(red: 0, green: 0, blue: 0, alpha: 0.26 * a)+ stripes.color1 = CIColor(red: 0, green: 0, blue: 0, alpha: 0)+ stripes.width = 1.5+ stripes.sharpness = 0.6+ let lines = stripes.outputImage!.transformed(by: CGAffineTransform(rotationAngle: .pi / 2)).cropped(to: extent)+ out = over(lines, out)+ if grain > 0 { out = over(grayNoise(seed: frame, alpha: grain * a), out) }++ let y = CGFloat((Double(frame) * 9).truncatingRemainder(dividingBy: Double(h + 400))) - 200+ let bar = CIFilter.gaussianGradient()+ bar.center = CGPoint(x: w / 2, y: h - y)+ bar.radius = 70+ bar.color0 = CIColor(red: 1, green: 1, blue: 1, alpha: 0.07 * a)+ bar.color1 = CIColor(red: 1, green: 1, blue: 1, alpha: 0)+ let band = bar.outputImage!+ .transformed(by: CGAffineTransform(translationX: -w / 2, y: 0).concatenating(CGAffineTransform(scaleX: 20, y: 1))+ .concatenating(CGAffineTransform(translationX: w / 2, y: 0))).cropped(to: extent)+ out = band.applyingFilter("CIScreenBlendMode", parameters: [kCIInputBackgroundImageKey: out])++ let v = CIFilter.vignetteEffect()+ v.inputImage = out+ v.center = CGPoint(x: w / 2, y: h / 2)+ v.radius = Float(w * 0.55)+ v.intensity = Float(0.55 * a)+ v.falloff = 0.55+ return v.outputImage!.cropped(to: extent)+ }++ // Film grain: soft, slightly clumped grey noise soft-light blended (strongest in midtones, faint on white paper and deep navy),+ // dissolved in by `amount` (0.1 barely there, 0.25 visible, 0.5 heavy).+ func filmGrain(_ img: CIImage, amount: Double, frame: Int) -> CIImage {+ var r = Rand(frame, 5150)+ let raw = CIFilter.randomGenerator().outputImage!+ .transformed(by: CGAffineTransform(translationX: r.range(-4000, 0), y: r.range(-4000, 0)))+ let m = CIFilter.colorMatrix() // opaque grey from the red channel+ m.inputImage = raw+ m.rVector = CIVector(x: 1, y: 0, z: 0, w: 0)+ m.gVector = CIVector(x: 1, y: 0, z: 0, w: 0)+ m.bVector = CIVector(x: 1, y: 0, z: 0, w: 0)+ m.aVector = CIVector(x: 0, y: 0, z: 0, w: 0)+ m.biasVector = CIVector(x: 0, y: 0, z: 0, w: 1)+ let soft = CIFilter.gaussianBlur()+ soft.inputImage = m.outputImage!+ soft.radius = 0.7+ let grained = soft.outputImage!.cropped(to: extent)+ .applyingFilter("CISoftLightBlendMode", parameters: [kCIInputBackgroundImageKey: img])+ let mix = CIFilter.dissolveTransition()+ mix.inputImage = img+ mix.targetImage = grained.cropped(to: extent)+ mix.time = Float(min(1, amount))+ return mix.outputImage!.cropped(to: extent)+ }++ // MARK: helpers++ func point(_ p: CGPoint) -> CGPoint { CGPoint(x: p.x * w, y: (1 - p.y) * h) }++ func solid(_ c: CIColor, alpha: Double) -> CIImage {+ CIImage(color: CIColor(red: c.red, green: c.green, blue: c.blue, alpha: alpha)).cropped(to: extent)+ }++ func over(_ top: CIImage, _ bottom: CIImage) -> CIImage { top.composited(over: bottom) }++ func grayNoise(seed: Int, alpha: Double) -> CIImage {+ var r = Rand(seed, 99)+ let n = CIFilter.randomGenerator().outputImage!+ .transformed(by: CGAffineTransform(translationX: r.range(-4000, 0), y: r.range(-4000, 0)))+ let m = CIFilter.colorMatrix()+ m.inputImage = n+ m.rVector = CIVector(x: 1, y: 0, z: 0, w: 0) // grey from the red channel, at a fixed opacity+ m.gVector = CIVector(x: 1, y: 0, z: 0, w: 0)+ m.bVector = CIVector(x: 1, y: 0, z: 0, w: 0)+ m.aVector = CIVector(x: 0, y: 0, z: 0, w: 0)+ m.biasVector = CIVector(x: 0, y: 0, z: 0, w: CGFloat(alpha))+ return m.outputImage!.cropped(to: extent)+ }++ static func color(_ hex: String) -> CIColor {+ let v = Int(hex.trimmingCharacters(in: CharacterSet(charactersIn: "#")), radix: 16) ?? 0xFFFFFF+ return CIColor(red: CGFloat((v >> 16) & 255) / 255, green: CGFloat((v >> 8) & 255) / 255, blue: CGFloat(v & 255) / 255)+ }+}diff --git a/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/main.swift b/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/main.swiftnew file mode 100644index 0000000..a044ee5--- /dev/null+++ b/skills/make-an-anime/scripts/tools/vfx/Sources/mvfx/main.swift@@ -0,0 +1,181 @@+import CoreImage+import Foundation+import ImageIO+import UniformTypeIdentifiers++// mvfx: post-processing VFX over a finished video, frame-exact on its 24fps grid.+//+// mvfx --in video.mp4 --cues cues.json --out out.mp4 [--lights dir] [--from N --to M]+// mvfx --in video.mp4 --cues cues.json --stills dir --only 120,503,1296 [--lights dir]+//+// Frames come from ffmpeg as raw BGRA and go back to ffmpeg (libx264 crf 16, the source's audio copied or cut to the range),+// with accurate swscale rounding both ways, so an empty cue list is a clean re-encode (same colour means as the source). The effects themselves are Core Image (Effects.swift) on the GPU. --lights: a dir of transparent PNGs named by+// frame (0503.png), screen-blended over the frame (the p5 light layer: leaks, flares, glints); missing files mean no light.+// --stills writes <dir>/<frame>.png for the --only frames instead of a video.++struct Options {+ var input = "", cues = "", out = "", lights: String?, stills: String?+ var only: [Int] = []+ var from = 0, to: Int?++ init(_ args: [String]) {+ var it = args.dropFirst().makeIterator()+ while let a = it.next() {+ let v = it.next() ?? ""+ switch a {+ case "--in": input = v+ case "--cues": cues = v+ case "--out": out = v+ case "--lights": lights = v+ case "--stills": stills = v+ case "--only": only = v.split(separator: ",").compactMap { Int($0) }.sorted()+ case "--from": from = Int(v) ?? 0+ case "--to": to = Int(v)+ default: fail("unknown option \(a)")+ }+ }+ if input.isEmpty || cues.isEmpty || (out.isEmpty && stills == nil) {+ fail("usage: mvfx --in video.mp4 --cues cues.json (--out out.mp4 [--from N --to M] | --stills dir --only 1,2) [--lights dir]")+ }+ }+}++func fail(_ msg: String) -> Never {+ FileHandle.standardError.write((msg + "\n").data(using: .utf8)!)+ exit(1)+}++func probe(_ path: String) -> (w: Int, h: Int, frames: Int) {+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/usr/bin/env")+ p.arguments = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets",+ "-show_entries", "stream=width,height,nb_read_packets", "-of", "csv=p=0", path]+ let pipe = Pipe()+ p.standardOutput = pipe+ try! p.run()+ p.waitUntilExit()+ let s = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)!+ let v = s.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ",").compactMap { Int($0) }+ guard v.count == 3 else { fail("ffprobe failed on \(path): \(s)") }+ return (v[0], v[1], v[2])+}++func ffmpeg(_ args: [String], stdin: Pipe? = nil, stdout: Pipe? = nil) -> Process {+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/usr/bin/env")+ p.arguments = ["ffmpeg", "-hide_banner", "-v", "error"] + args+ if let stdin { p.standardInput = stdin }+ if let stdout { p.standardOutput = stdout }+ do { try p.run() } catch { fail("ffmpeg: \(error)") }+ return p+}++// Fill `buf` with exactly `n` bytes from a pipe (false at EOF). POSIX read into one reused buffer: no per-frame Data.+func readFull(_ fd: Int32, _ buf: UnsafeMutableRawPointer, _ n: Int) -> Bool {+ var got = 0+ while got < n {+ let r = read(fd, buf + got, n - got)+ if r <= 0 { return false }+ got += r+ }+ return true+}++func writeFull(_ fd: Int32, _ buf: UnsafeRawPointer, _ n: Int) {+ var put = 0+ while put < n {+ let r = write(fd, buf + put, n - put)+ if r <= 0 { fail("encoder pipe closed") }+ put += r+ }+}++func writePNG(_ bytes: Data, w: Int, h: Int, to path: String) {+ let provider = CGDataProvider(data: bytes as CFData)!+ let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)+ let img = CGImage(width: w, height: h, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: w * 4,+ space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: info, provider: provider,+ decode: nil, shouldInterpolate: false, intent: .defaultIntent)!+ let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: path) as CFURL, UTType.png.identifier as CFString, 1, nil)!+ CGImageDestinationAddImage(dest, img, nil)+ CGImageDestinationFinalize(dest)+}++let opt = Options(CommandLine.arguments)+let cues: [Cue]+do {+ cues = try JSONDecoder().decode(CueFile.self, from: Data(contentsOf: URL(fileURLWithPath: opt.cues))).cues+} catch { fail("cues \(opt.cues): \(error)") }++let (W, H, total) = probe(opt.input)+let fps = 24.0+let last = min(opt.to ?? total, total)+let frameBytes = W * H * 4+let fx = Effects(width: W, height: H)+let ctx = CIContext(options: [.workingColorSpace: NSNull(), .outputColorSpace: NSNull(), .cacheIntermediates: false])++// Which source frames we need, in order.+let wanted: [Int] = opt.stills != nil ? opt.only.filter { $0 < total } : Array(opt.from..<last)+guard !wanted.isEmpty else { fail("no frames to render") }+let select = opt.stills != nil+ ? "select='\(wanted.map { "eq(n\\,\($0))" }.joined(separator: "+"))'"+ : "trim=start_frame=\(opt.from):end_frame=\(last),setpts=PTS-STARTPTS"++// swscale's default rounding darkens a yuv -> rgb -> yuv round trip by ~1.5 levels; these flags make it lossless on average.+let sws = "scale=flags=accurate_rnd+full_chroma_int+full_chroma_inp"+let decOut = Pipe()+let decoder = ffmpeg(["-i", opt.input, "-vf", "\(select),\(sws),format=bgra", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "bgra", "pipe:1"],+ stdout: decOut)++var encoder: Process?+let encIn = Pipe()+if opt.stills == nil {+ let t0 = Double(opt.from) / fps, len = Double(last - opt.from) / fps+ let whole = opt.from == 0 && last == total+ let audio = whole ? ["-i", opt.input] : ["-ss", String(format: "%.4f", t0), "-t", String(format: "%.4f", len), "-i", opt.input]+ encoder = ffmpeg(["-y", "-f", "rawvideo", "-pix_fmt", "bgra", "-s", "\(W)x\(H)", "-r", "24", "-i", "pipe:0"] + audio ++ ["-map", "0:v:0", "-map", "1:a:0?", "-vf", "\(sws),format=yuv420p", "-c:v", "libx264", "-crf", "16", "-preset", "medium",+ "-r", "24"] + (whole ? ["-c:a", "copy"] : ["-c:a", "aac", "-b:a", "256k"]) + [opt.out], stdin: encIn)+} else {+ try? FileManager.default.createDirectory(atPath: opt.stills!, withIntermediateDirectories: true)+}++// Memory stays flat (~1–2 GB): one input and one output frame buffer are reused, and each frame's Core Image graph, the lights PNG and+// every Foundation object it touches are released at the end of the frame (autoreleasepool). Without the pool a top-level loop+// never drains, and the full 3397-frame song grew to ~40 GB.+let started = Date()+let inBuf = UnsafeMutableRawPointer.allocate(byteCount: frameBytes, alignment: 64)+let outBuf = UnsafeMutableRawPointer.allocate(byteCount: frameBytes, alignment: 64)+let inFd = decOut.fileHandleForReading.fileDescriptor+let outFd = encIn.fileHandleForWriting.fileDescriptor+signal(SIGPIPE, SIG_IGN)+for (i, frame) in wanted.enumerated() {+ autoreleasepool {+ guard readFull(inFd, inBuf, frameBytes) else { fail("decoder ended at frame \(frame)") }+ let bytes = Data(bytesNoCopy: inBuf, count: frameBytes, deallocator: .none) // render is synchronous, so reusing inBuf is safe+ let src = CIImage(bitmapData: bytes, bytesPerRow: W * 4, size: CGSize(width: W, height: H), format: .BGRA8, colorSpace: nil)+ let name = String(format: "%04d.png", frame)+ var lights: CIImage?+ if let dir = opt.lights, FileManager.default.fileExists(atPath: "\(dir)/\(name)") {+ lights = CIImage(contentsOf: URL(fileURLWithPath: "\(dir)/\(name)"), options: [.colorSpace: NSNull()])+ }+ let img = fx.apply(src, frame: frame, cues: cues, lights: lights)+ ctx.render(img, toBitmap: outBuf, rowBytes: W * 4, bounds: fx.extent, format: .BGRA8, colorSpace: nil)+ if let dir = opt.stills {+ writePNG(Data(bytes: outBuf, count: frameBytes), w: W, h: H, to: "\(dir)/\(name)")+ } else {+ writeFull(outFd, outBuf, frameBytes)+ }+ if i % 240 == 239 { ctx.clearCaches() }+ if isatty(2) != 0, i % 24 == 0 {+ FileHandle.standardError.write("\rframe \(i + 1)/\(wanted.count)".data(using: .utf8)!)+ }+ }+}+try? encIn.fileHandleForWriting.close()+decoder.waitUntilExit()+encoder?.waitUntilExit()+if let e = encoder, e.terminationStatus != 0 { fail("encoder failed (\(e.terminationStatus))") }+if isatty(2) != 0 { FileHandle.standardError.write("\n".data(using: .utf8)!) }+let ms = Int(Date().timeIntervalSince(started) * 1000)+print("{\"out\":\"\(opt.stills ?? opt.out)\",\"frames\":\(wanted.count),\"width\":\(W),\"height\":\(H),\"ms\":\(ms)}")