Skip to content

Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.

canvas-core: engine camera, decoded-export QA, motion blur render mode

alexgr-agenteb38182f8c95
diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.md
index 8c6206f..6a2b937 100644
--- a/plugins/anidoodle/skills/anidoodle/SKILL.md
+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md
@@ -97,6 +97,9 @@ draws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze
`engine/` is the portable art core plus the tooling. `engine/src/canvas-core` knows nothing
about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`.
+Camera moves (pans, zooms, parallax, shake) come from `engine/src/canvas-core/camera.ts`:
+`references/camera.md`. `render.mjs --blur N` renders with motion blur (N subframes averaged in
+linear light per frame); the default path is untouched.
```bash
node <skill>/engine/tools/scaffold.mjs ~/art --film intro --format 9x16 --duration 180
@@ -114,6 +117,7 @@ node tools/emit.mjs intro --out out/intro.html # one self-co
| `gate.mjs` | determinism, contract, dead air, artifact; `--self-test` proves it can fail |
| `registry.mjs` / `gallery.mjs` | the style list from the plates themselves / the gallery sheet |
| `docs-check.mjs` | fails when any doc's style count, length or path disagrees with the code |
+| `verify-export.mjs` | opt-in QA on the rendered file: frame count, duration, first-frame colour, loop seam |
| `music.mjs` | renders and meters a score (loudness, range, onsets, brightness) |
Four backends, one art core: `playwright`, `html-player`, `remotion`, `hyperframes`.
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/camera.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/camera.ts
new file mode 100644
index 0000000..e974309
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/camera.ts
@@ -0,0 +1,164 @@
+// THE CAMERA. One dolly over depth planes, keyed on the frame grid. A film either draws in world
+// coordinates inside begin()/end() (the transform path, dirty boxes stay right), or asks
+// toScreen() where a world point lands and draws there (the projector path). Both come from the
+// same state, so a caption pinned to the frame and the world it floats over can never disagree.
+//
+// CRAFT, and why the numbers work this way:
+// - ZOOM IS INTERPOLATED IN log2. A zoom is a ratio: halving the apparent size twice should take
+// twice as long as halving it once. Easing the zoom value itself makes a long push-in sprint at
+// the near end and crawl at the far one; easing log2(zoom) spends time evenly per stop.
+// - EASING PER SEGMENT, ease-in-out by default. A camera move with no live operator should
+// accelerate gently and arrive gently; linear reads as mechanical, ease-out alone reads as
+// interrupted. The ease lives on the key the segment LEAVES.
+// - PARALLAX IS ONE NUMBER. The camera sits at distance D = 1/zoom from the hero plane (z = 0);
+// a plane at depth z scales by zoom/(1 + z*zoom) and moves with it. Near planes swing wide, far
+// ones barely stir, and every element at a depth agrees with every other, because there is only
+// one camera. Positive z recedes; a negative z crosses the lens (grass across the glass).
+// - A CLOSE SHOT MUST NOT FATTEN THE LINE. Ink is authored at some view; at zoom S the same nib
+// reads S times heavier, so stroke widths divide by weight(S) = S^0.35 (not S: a little weight
+// gain is what makes a close-up feel close rather than enlarged).
+// - SHAKE IS DECAYING NOISE, NEVER RANDOM PER FRAME. An impact rings down: full amplitude at the
+// hit, gone a beat later, smooth in between. White noise per frame reads as static, not as a
+// camera; low-frequency gradient noise with an attack ramp and a squared decay reads as mass.
+// The shake is given in SCREEN pixels so it reads the same at any zoom, plus a small rotation
+// about the frame's centre, which is what actually sells handheld.
+import { fractal, Gfx, P } from "./core";
+
+export type Cam = { look: P; zoom: number }; // look: world point at the frame's centre; zoom: screen px per world unit on the hero plane
+export type EaseName = "linear" | "in" | "out" | "inout";
+export const EASE: Record<EaseName, (u: number) => number> = {
+ linear: (u) => u,
+ in: (u) => u * u * u,
+ out: (u) => 1 - Math.pow(1 - u, 3),
+ inout: (u) => (u < 0.5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2), // easeInOutCubic: the camera default
+};
+export type CamKey = { f: number; look?: P; zoom?: number; ease?: EaseName }; // ease governs the segment this key LEAVES
+export type Shake = { from: number; to: number; amp: number; seed: number; freq?: number; rot?: number; attack?: number };
+
+// Monotone cubic (Fritsch-Carlson): a smooth path through every key that never overshoots into a
+// value it was not given and never reverses. With log2 set, the values are read and returned in
+// stops: log2 in, linear out. Use it for a zoom path with several keys, where per-segment easing
+// would breathe at every key.
+export const monoPath = (keys: readonly (readonly [number, number])[], opts: { log2?: boolean } = {}): ((x: number) => number) => {
+ const xs = keys.map((k) => k[0]), ys = keys.map((k) => (opts.log2 ? Math.log2(k[1]) : k[1])), n = xs.length;
+ if (n === 0) throw new Error("monoPath needs at least one key");
+ for (let i = 1; i < n; i++) if (xs[i] <= xs[i - 1]) throw new Error(`monoPath keys must increase: ${xs[i - 1]} then ${xs[i]}`);
+ const mono = (x: number): number => {
+ if (x <= xs[0]) return ys[0];
+ if (x >= xs[n - 1]) return ys[n - 1];
+ const d: number[] = []; for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]));
+ const m: number[] = [d[0]]; for (let i = 1; i < n - 1; i++) m.push(d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2); m.push(d[n - 2]);
+ for (let i = 0; i < n - 1; i++) { if (d[i] === 0) { m[i] = 0; m[i + 1] = 0; continue; } const a = m[i] / d[i], b = m[i + 1] / d[i], s = a * a + b * b; if (s > 9) { const t = 3 / Math.sqrt(s); m[i] = t * a * d[i]; m[i + 1] = t * b * d[i]; } }
+ let i = 0; while (x > xs[i + 1]) i++;
+ const h = xs[i + 1] - xs[i], t = (x - xs[i]) / h, t2 = t * t, t3 = t2 * t;
+ return ys[i] * (2 * t3 - 3 * t2 + 1) + h * m[i] * (t3 - 2 * t2 + t) + ys[i + 1] * (-2 * t3 + 3 * t2) + h * m[i + 1] * (t3 - t2);
+ };
+ return opts.log2 ? (x) => Math.pow(2, mono(x)) : mono;
+};
+
+const clampF = (v: number, a: number, b: number) => Math.max(a, Math.min(b, v));
+
+// ---- explicit-state helpers, for films that hold their own Cam per frame. The Camera class
+// below delegates to these; there is one math, whether the film keys the camera or computes it.
+// The dolly model: camera distance D = 1/zoom from the hero plane (z = 0); a plane at depth z
+// scales by 1/(D + z) and moves with it. Positive z recedes; negative z crosses the lens.
+export const planeScale = (c: Cam, z = 0): number => 1 / (1 / c.zoom + z);
+export const projectCam = (centre: P, c: Cam, z: number, p: P, rot = 0): P => {
+ const k = planeScale(c, z), co = Math.cos(rot), si = Math.sin(rot), dx = p[0] - c.look[0], dy = p[1] - c.look[1];
+ return [centre[0] + k * (co * dx - si * dy), centre[1] + k * (si * dx + co * dy)];
+};
+export const unprojectCam = (centre: P, c: Cam, z: number, s: P, rot = 0): P => {
+ const k = planeScale(c, z), co = Math.cos(rot), si = Math.sin(rot), dx = (s[0] - centre[0]) / k, dy = (s[1] - centre[1]) / k;
+ return [c.look[0] + co * dx + si * dy, c.look[1] - si * dx + co * dy];
+};
+// ink authored at some view reads zoom times heavier at a close one; divide stroke widths by
+// this. 0.35, not 1: a little weight gain is what makes a close-up feel close, not enlarged.
+export const strokeWeight = (c: Cam, exp = 0.35): number => Math.pow(c.zoom, exp);
+
+export class Camera {
+ private shakes: Shake[] = [];
+ private keys: CamKey[];
+ private path?: (f: number) => Cam;
+ private monoZoom: boolean;
+ // centre: the frame's centre in logical px (usually [W/2, H/2]); every projection goes through it
+ constructor(readonly centre: P, keys: CamKey[] = [], opts: { monoZoom?: boolean; path?: (f: number) => Cam } = {}) {
+ this.keys = [...keys]; // authored order, strictly increasing: a camera path is a cue table
+ this.path = opts.path;
+ this.monoZoom = opts.monoZoom ?? false;
+ if (!this.path && this.keys.length === 0) throw new Error("camera needs keys or a path");
+ let last = -1;
+ for (const k of this.keys) {
+ if (!Number.isInteger(k.f) || k.f < 0) throw new Error(`camera key at non-integral or negative frame ${k.f}`);
+ if (k.f <= last) throw new Error(`camera keys must increase: ${last} then ${k.f}`);
+ if (k.zoom !== undefined && k.zoom <= 0) throw new Error(`camera zoom must be positive, got ${k.zoom} at frame ${k.f}`);
+ last = k.f;
+ }
+ }
+
+ // one channel of the keys, eased per segment. Missing values hold the nearest given one, so a
+ // key may set only look or only zoom.
+ private channel(f: number, get: (k: CamKey) => number | undefined, log2: boolean): number {
+ const ks = this.keys.map((k, i) => ({ k, v: get(k), i })).filter((e) => e.v !== undefined) as { k: CamKey; v: number; i: number }[];
+ if (!ks.length) throw new Error("camera keys never set this channel");
+ if (log2 && this.monoZoom && ks.length > 1) return monoPath(ks.map((e) => [e.k.f, e.v] as const), { log2: true })(f);
+ if (f <= ks[0].k.f) return ks[0].v;
+ if (f >= ks[ks.length - 1].k.f) return ks[ks.length - 1].v;
+ let i = 0; while (f >= ks[i + 1].k.f) i++;
+ const [a, b] = [ks[i], ks[i + 1]], u = (f - a.k.f) / (b.k.f - a.k.f), e = EASE[a.k.ease ?? "inout"](clampF(u, 0, 1));
+ if (log2) return Math.pow(2, Math.log2(a.v) + (Math.log2(b.v) - Math.log2(a.v)) * e);
+ return a.v + (b.v - a.v) * e;
+ }
+
+ // the clean move at frame f, before shake. Pure.
+ at(f: number): Cam {
+ if (this.path) return this.path(f);
+ return { look: [this.channel(f, (k) => k.look?.[0], false), this.channel(f, (k) => k.look?.[1], false)], zoom: this.channel(f, (k) => k.zoom, true) };
+ }
+
+ // register an impact or a handheld stretch. amp in SCREEN px; rot in radians at full strength.
+ shake(s: Shake): this {
+ if (!(s.to > s.from)) throw new Error(`shake window must have length: ${s.from}..${s.to}`);
+ if (s.amp < 0) throw new Error("shake amp must be >= 0");
+ this.shakes.push(s);
+ return this;
+ }
+
+ // screen-space shake at f: [dx, dy] px and dr radians about the frame's centre. Pure.
+ shakeAt(f: number): [number, number, number] {
+ let dx = 0, dy = 0, dr = 0;
+ for (const s of this.shakes) {
+ if (f < s.from || f >= s.to) continue;
+ const u = (f - s.from) / (s.to - s.from), ramp = clampF((f - s.from + 1) / (s.attack ?? 2), 0, 1), fall = (1 - u) * (1 - u);
+ const amp = s.amp * ramp * fall, fq = s.freq ?? 0.35;
+ dx += amp * (fractal(s.seed, f * fq, 0, 1, 1, 2) * 2 - 1);
+ dy += amp * (fractal(s.seed + 101, f * fq, 0, 1, 1, 2) * 2 - 1);
+ dr += (s.rot ?? 0) * ramp * fall * (fractal(s.seed + 211, f * fq, 0, 1, 1, 2) * 2 - 1);
+ }
+ return [dx, dy, dr];
+ }
+
+ // the move the audience sees: the clean path with its shake folded in. A screen-space nudge of
+ // [dx, dy] is the camera's look point stepping BACK by that much, in world units.
+ shaken(f: number): Cam & { rot: number } {
+ const c = this.at(f), [dx, dy, dr] = this.shakeAt(f), k = c.zoom;
+ return { look: [c.look[0] - dx / k, c.look[1] - dy / k], zoom: c.zoom, rot: dr };
+ }
+
+ // plane scale at depth z for a camera state: the hero plane (z = 0) scales by zoom exactly.
+ scaleAt(c: Cam, z = 0): number { return planeScale(c, z); }
+
+ // stroke-weight compensation for a close shot (see strokeWeight above)
+ weight(c: Cam, exp = 0.35): number { return strokeWeight(c, exp); }
+
+ // ---- the transform path: draw in world coordinates inside begin/end. Dirty boxes stay right
+ // because the camera rides the Gfx transform stack instead of touching the context.
+ begin(g: Gfx, f: number, z = 0) {
+ const c = this.shaken(f), k = this.scaleAt(c, z), co = Math.cos(c.rot), si = Math.sin(c.rot);
+ g.push(this.centre[0] - k * (co * c.look[0] - si * c.look[1]), this.centre[1] - k * (si * c.look[0] + co * c.look[1]), k, c.rot);
+ }
+ end(g: Gfx) { g.pop(); }
+
+ // ---- the projector path: ask where a world point lands, draw there yourself
+ toScreen(p: P, f: number, z = 0): P { const c = this.shaken(f); return projectCam(this.centre, c, z, p, c.rot); }
+ toWorld(s: P, f: number, z = 0): P { const c = this.shaken(f); return unprojectCam(this.centre, c, z, s, c.rot); }
+}
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts
index c8e52a1..805e2b7 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts
@@ -138,7 +138,7 @@ export class Gfx {
// `drawn`: union of every device box composited onto `main` since construction. Read-only for the
// art; the web profile (bake.ts) crops a part into a sprite by it. Setting it changes no pixel.
drawn: Rect | null = null;
- cur: Ctx; private pool: Tracked[] = []; private stack: [number, number, number][] = [[0, 0, 1]]; private box: Rect | null = null;
+ cur: Ctx; private pool: Tracked[] = []; private stack: [number, number, number, number][] = [[0, 0, 1, 0]]; private box: Rect | null = null;
constructor(public main: Ctx, public env: Env, public frame: number, public medium: Medium) {
this.cur = main; this.base(main);
// surfaces outlive the frame: allocating six full-size canvases per frame is pure churn
@@ -147,17 +147,17 @@ export class Gfx {
private get m() { return this.stack[this.stack.length - 1]; }
private get DW() { return Math.round(this.env.W * this.env.scale); }
private get DH() { return Math.round(this.env.H * this.env.scale); }
- private base(c: Ctx) { const [x, y, s] = this.m, k = this.env.scale; c.setTransform(k * s, 0, 0, k * s, k * x, k * y); }
+ private base(c: Ctx) { const [x, y, s, r] = this.m, k = this.env.scale; if (r === 0) { c.setTransform(k * s, 0, 0, k * s, k * x, k * y); return; } const co = Math.cos(r), si = Math.sin(r); c.setTransform(k * s * co, k * s * si, -k * s * si, k * s * co, k * x, k * y); }
private dev(c: Ctx) { c.setTransform(1, 0, 0, 1, 0, 0); }
private clip(r: Rect, pad = 0): Rect { return [Math.max(0, Math.floor(r[0] - pad)), Math.max(0, Math.floor(r[1] - pad)), Math.min(this.DW, Math.ceil(r[2] + pad)), Math.min(this.DH, Math.ceil(r[3] + pad))]; }
private join(a: Rect | null, b: Rect): Rect { return a ? [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])] : b; }
// local points -> device box, with `pad` local units of slack (line weight, displacement, blur)
- private boxOf(pts: P[], pad: number): Rect { const [tx, ty, s] = this.m, k = this.env.scale; let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } return this.clip([k * (tx + (x0 - pad) * s), k * (ty + (y0 - pad) * s), k * (tx + (x1 + pad) * s), k * (ty + (y1 + pad) * s)]); }
+ private boxOf(pts: P[], pad: number): Rect { const [tx, ty, s, r] = this.m, k = this.env.scale; let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } x0 -= pad; y0 -= pad; x1 += pad; y1 += pad; if (r === 0) return this.clip([k * (tx + x0 * s), k * (ty + y0 * s), k * (tx + x1 * s), k * (ty + y1 * s)]); const co = Math.cos(r), si = Math.sin(r), cs = [[x0, y0], [x1, y0], [x0, y1], [x1, y1]]; let a0 = 1e9, b0 = 1e9, a1 = -1e9, b1 = -1e9; for (const [x, y] of cs) { const ax = k * (tx + s * (co * x - si * y)), by = k * (ty + s * (si * x + co * y)); if (ax < a0) a0 = ax; if (by < b0) b0 = by; if (ax > a1) a1 = ax; if (by > b1) b1 = by; } return this.clip([a0, b0, a1, b1]); }
mark(pts: P[], pad = 4) { this.box = this.join(this.box, this.boxOf(pts, pad)); }
touch(x0: number, y0: number, x1: number, y1: number) { this.mark([[x0, y0], [x1, y1]], 0); } // for raw ctx drawing inside a group
layer(): Tracked { let L = this.pool.pop(); if (!L) { L = this.env.canvas(this.DW, this.DH) as Tracked; L.dirty = null; } this.dev(L.ctx); L.ctx.globalCompositeOperation = "source-over"; L.ctx.globalAlpha = 1; if (L.dirty) { const d = L.dirty; L.ctx.clearRect(d[0], d[1], d[2] - d[0], d[3] - d[1]); L.dirty = null; } return L; }
release(L: Tracked, dirty: Rect | null) { L.dirty = dirty ? this.join(L.dirty ?? null, dirty) : L.dirty; this.pool.push(L); }
- push(x: number, y: number, s: number) { const [px, py, ps] = this.m; this.stack.push([px + x * ps, py + y * ps, ps * s]); this.base(this.cur); }
+ push(x: number, y: number, s: number, r = 0) { const [px, py, ps, pr] = this.m; if (pr === 0) { this.stack.push([px + x * ps, py + y * ps, ps * s, r]); this.base(this.cur); return; } const co = Math.cos(pr), si = Math.sin(pr); this.stack.push([px + ps * (co * x - si * y), py + ps * (si * x + co * y), ps * s, pr + r]); this.base(this.cur); }
pop() { this.stack.pop(); this.base(this.cur); }
path(c: Ctx, pts: P[]) { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts
index f2924cf..9eaf499 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts
@@ -22,9 +22,31 @@ export const mountFilm = (film: Film) => {
const seek = (frame: number) => { const t0 = performance.now(); const shot = renderFrame(film, ctx, frame, env); ctx.getImageData(0, 0, 1, 1); current = frame; return { shot, ms: performance.now() - t0 }; }; // getImageData forces the deferred raster so the timing is real
const hash = () => { const d = ctx.getImageData(0, 0, canvas.width, canvas.height).data; let h = 0x811c9dc5; for (let i = 0; i < d.length; i++) { h ^= d[i]; h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(16); };
const b64 = (u8: Uint8Array) => { let s = ""; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode(...u8.subarray(i, i + 0x8000)); return btoa(s); };
+ // MOTION BLUR. One output frame as the average of subframes spread over a one-frame shutter
+ // centred on it, confined to its own shot so nothing bleeds across a cut. The average is taken
+ // in LINEAR light: blur is light integration, and averaging in sRGB darkens every moving edge.
+ // hosts may keep time; the core never does.
+ const toLin = new Float32Array(256);
+ for (let i = 0; i < 256; i++) { const s = i / 255; toLin[i] = s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4); }
+ const fromLin = (l: number) => { const v = l <= 0.0031308 ? l * 12.92 : 1.055 * Math.pow(l, 1 / 2.4) - 0.055; return Math.max(0, Math.min(255, Math.round(v * 255))); };
+ const blur = (frame: number, samples: number) => {
+ const n = Math.max(0, Math.min(film.meta.durationFrames - 1, Math.round(frame))), shot = film.shots.find((s) => n >= s.start && n < s.end);
+ if (!shot || samples < 2) return { shot: shot?.id ?? null, ms: 0 };
+ const t0 = performance.now(), w = canvas.width, h = canvas.height, acc = new Float64Array(w * h * 4);
+ for (let i = 0; i < samples; i++) {
+ const t = Math.min(shot.end - 1, Math.max(shot.start, n + (i + 0.5) / samples - 0.5));
+ renderFrame(film, ctx, t, env);
+ const d = ctx.getImageData(0, 0, w, h).data;
+ for (let p = 0; p < d.length; p += 4) { acc[p] += toLin[d[p]]; acc[p + 1] += toLin[d[p + 1]]; acc[p + 2] += toLin[d[p + 2]]; acc[p + 3] += d[p + 3]; }
+ }
+ const img = ctx.createImageData(w, h), o = img.data, inv = 1 / samples;
+ for (let p = 0; p < o.length; p += 4) { o[p] = fromLin(acc[p] * inv); o[p + 1] = fromLin(acc[p + 1] * inv); o[p + 2] = fromLin(acc[p + 2] * inv); o[p + 3] = Math.round(acc[p + 3] * inv); }
+ ctx.putImageData(img, 0, 0); current = n;
+ return { shot: shot.id, ms: performance.now() - t0 };
+ };
const audio = (sr: number) => { if (!film.audio) return null; const [L, R] = film.audio(sr); if (L.length !== R.length) throw new Error("audio channels have different lengths"); const pcm = new Float32Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; } return { sampleRate: sr, frames: L.length, float32: b64(new Uint8Array(pcm.buffer)) }; };
const warm = () => film.shots.forEach((s) => { seek(s.start); seek(s.start + ((s.end - s.start) >> 1)); }); // first + middle frame of every shot: builds tiles, pre-allocates the layer pool
- window.FILM = { meta: { ...film.meta, shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
+ window.FILM = { meta: { ...film.meta, shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
// ---- the player: click or space to play, arrows to step, ?frame=N to open on a frame
ready.then(() => {
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs
index b0c2f13..60e6d35 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs
@@ -16,6 +16,8 @@ export const open = async ({ pw, browser: found }, pagePath, { scale = 1, worker
// -> { png: Buffer, shot, drawMs, captureMs }
frame: async (n, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate((f) => { const s = window.FILM.seek(f); const t = performance.now(); const png = window.FILM.png(); return { ...s, png, enc: performance.now() - t }; }, n); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
hash: (n, w = 0) => pick(w).evaluate((f) => { window.FILM.seek(f); return window.FILM.hash(); }, n),
+ // motion-blurred frame: `samples` subframes averaged in the page (see hosts/page.ts blur)
+ blur: async (n, samples, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, s]) => { const r = window.FILM.blur(f, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
audio: (sr) => pages[0].evaluate((s) => window.FILM.audio(s), sr),
close: () => browser.close(),
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs
index 5d48fc8..ca27bd3 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs
@@ -1,4 +1,11 @@
// node tools/render.mjs [film] [--scale 1] [--workers 4] [--out out/x.mp4|.gif|.webm|.apng] [--gif-fps 15] [--width 640]
+// [--blur N] [--from F] [--to F]
+// --blur N motion blur: every output frame is the average of N subframes over a one-frame
+// shutter, integrated in linear light inside the page. Fast pans and dolly moves stop
+// juddering; stills and stepped (on-twos) art are unchanged because their subframes are
+// identical. Costs N times the draw time. The default path (--blur 1) is untouched.
+// --from/--to render only frames [from, to): for checking a passage, not for shipping. A range
+// render is silent (the score would not line up) and says so.
// Auto-detects a backend, renders every frame through it, encodes with ffmpeg, then VERIFIES.
// .mp4 the film, with its score
// .gif loops and README heroes: silent, loops forever, ONE palette built from the whole piece
@@ -19,6 +26,7 @@ import { float32Wav } from "./audio.mjs";
const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };
const film = process.argv[2] && !process.argv[2].startsWith("--") ? process.argv[2] : "fixtures";
+const BLUR = Math.max(1, Number(arg("blur", 1)));
const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2))))), out = resolve(arg("out", defaultOutput(film)));
const env = detect();
@@ -29,10 +37,15 @@ console.log(`using: ${env.chosen}\n`);
const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });
console.log(`page: ${page.out} (${(page.bytes / 1024).toFixed(0)} KB)`);
const t0 = Date.now(), session = await playwright.open(env, page.out, { scale, workers }), meta = await session.info(), N = meta.durationFrames;
+const FROM = Math.max(0, Number(arg("from", 0))), TO = Math.min(N, Number(arg("to", N)));
+if (!Number.isInteger(FROM) || !Number.isInteger(TO) || TO <= FROM) { console.error(`bad range: [${FROM}, ${TO}) of ${N}`); process.exit(2); }
+const ranged = FROM !== 0 || TO !== N;
console.log(`film: "${meta.title}" ${meta.W}x${meta.H} @ ${meta.fps} fps, ${N} frames, ${meta.bpm} bpm, scale ${scale}, ${session.workers} page(s)`);
+if (BLUR > 1) console.log(`motion blur: ${BLUR} subframes per frame, one-frame shutter, linear light`);
+if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent by design`);
-// audio: pure JS in the page -> WAV here
-mkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = await session.audio(48000);
+// audio: pure JS in the page -> WAV here (skipped for a range render: the score would not line up)
+mkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = ranged ? null : await session.audio(48000);
if (a) writeFileSync(wav, float32Wav(a));
mkdirSync(join(out, ".."), { recursive: true });
@@ -49,9 +62,10 @@ const ff = spawn(env.ffmpeg.bin, encode, { stdio: ["pipe", "inherit", "inherit"]
const done = new Promise((res, rej) => ff.on("close", (c) => (c ? rej(new Error(`ffmpeg exited ${c}`)) : res())));
// frames render in parallel across pages, and are fed to ffmpeg strictly in order
-const cost = [], pending = new Map(); let next = 0, write = 0;
+const cost = [], pending = new Map(); let next, write;
const pump = async () => { while (pending.has(write)) { const b = pending.get(write); pending.delete(write); if (!ff.stdin.write(b)) await new Promise((r) => ff.stdin.once("drain", r)); write++; } };
-await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < N) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await session.frame(n, w); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs }); pending.set(n, f.png); await pump(); } }));
+next = FROM; write = FROM;
+await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = BLUR > 1 ? await session.blur(n, BLUR, w) : await session.frame(n, w); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs }); pending.set(n, f.png); await pump(); } }));
await pump(); ff.stdin.end(); await done;
const wall = (Date.now() - t0) / 1000;
@@ -61,10 +75,11 @@ console.log("\nframe cost (ms), draw = art core only, png = canvas PNG encode in
for (const id of [...new Set(cost.map((c) => c.shot))]) { const c = cost.filter((x) => x.shot === id), d = stat(c.map((x) => x.draw)), e = stat(c.map((x) => x.enc)); console.log(` ${id.padEnd(12)} draw median ${d.med.toFixed(0)} p95 ${d.p95.toFixed(0)} max ${d.max.toFixed(0)} | png median ${e.med.toFixed(0)} (${c.length} frames)`); }
const slow = [...cost].sort((a, b) => b.draw - a.draw).slice(0, 3).map((c) => `#${c.n} ${c.shot} ${c.draw.toFixed(0)}ms`).join(", ");
console.log(` slowest: ${slow}\n budget: 150 ms draw per frame -> ${cost.every((c) => c.draw <= 150) ? "PASS" : "OVER on " + cost.filter((c) => c.draw > 150).length + " frames"}`);
-console.log(` wall clock: ${wall.toFixed(1)} s for ${N} frames = ${(N / wall).toFixed(1)} fps end to end (build + launch + render + encode)`);
+console.log(` wall clock: ${wall.toFixed(1)} s for ${TO - FROM} frames = ${((TO - FROM) / wall).toFixed(1)} fps end to end (build + launch + render + encode)`);
// ---- verify: same frame, different order, different page. Standard = visually identical; hash equality is the cheap first test.
-const probe = [...new Set([0, ...meta.shots.flatMap((s) => [s.start, s.end - 1]), ...((k) => Array.from({ length: k }, (_, i) => Math.round(i * (N - 1) / (k - 1 || 1))))(Math.min(6, N)), N - 1])].sort((a, b) => a - b), fwd = [], rev = [];
+const probe = [...new Set([0, ...meta.shots.flatMap((s) => [s.start, s.end - 1]), ...((k) => Array.from({ length: k }, (_, i) => Math.round(i * (N - 1) / (k - 1 || 1))))(Math.min(6, N)), N - 1])].filter((n) => n >= FROM && n < TO).sort((a, b) => a - b), fwd = [], rev = [];
+if (!probe.length) probe.push(FROM);
for (const n of probe) fwd.push(await session.hash(n, 0)); for (const n of [...probe].reverse()) rev.unshift(await session.hash(n, session.workers - 1));
const same = probe.filter((_, i) => fwd[i] === rev[i]).length;
console.log(`\ndeterminism: ${same}/${probe.length} probe frames hash-identical (forward on page 0 vs reversed on page ${session.workers - 1})${same === probe.length ? "" : " -> fall back to PSNR > 45 dB in the Phase 2 gate"}`);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs
new file mode 100644
index 0000000..c797e5a
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs
@@ -0,0 +1,110 @@
+// VERIFY-EXPORT. The gate proves the SOURCE draws the same frame every time; this proves the
+// FILE that came out of the encoder is that film. It never renders the film again except where
+// a check says so, it never writes near out/, and every check beyond the container facts is
+// opt-in, because the right bar depends on the piece: a transparent sticker has no background
+// colour to assert, and a one-shot film has no seam to hide.
+//
+// node tools/verify-export.mjs <film> [--file out/x.mp4] [--adapter html-player]
+// [--width W] expected pixel width (default: the film's own; height follows the aspect)
+// [--first-frame #rrggbb] the average colour the decoded first frame must have (tol: --tol N, default 8)
+// [--loop] the last-to-first seam must read like any other step of the loop
+// [--fidelity-psnr N] decoded frame 0 must sit within N dB of the source frame (renders it once)
+//
+// Always checked: the file decodes, its pixel size, its exact frame count, and its duration
+// against the film's meta. Everything else is asked for explicitly.
+import { execFileSync, spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { defaultOutput } from "./names.mjs";
+
+const VAL = new Set(["file", "adapter", "width", "first-frame", "tol", "fidelity-psnr", "scale"]);
+const pos = [], opt = {};
+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }
+const film = pos[0] ?? "fixtures";
+const adapterName = opt.adapter ?? "html-player";
+const SCALE = +(opt.scale ?? 1);
+const TMP = resolve(".tmp/verify"); mkdirSync(TMP, { recursive: true });
+
+let fails = 0, checks = 0;
+const say = (ok, label, detail = "") => { checks++; if (!ok) fails++; console.log(` ${ok ? "PASS" : "FAIL"} ${label}${detail ? " " + detail : ""}`); };
+const note = (label, detail = "") => console.log(` ---- ${label}${detail ? " " + detail : ""}`);
+const head = (n, t) => console.log(`\n${n}. ${t}\n${"-".repeat(58)}`);
+const die = (m) => { console.error(`verify-export: ${m}`); process.exit(2); };
+
+const ffprobe = (args) => { const r = spawnSync("ffprobe", ["-v", "error", ...args], { encoding: "utf8", maxBuffer: 1 << 24 }); if (r.status !== 0) die(`ffprobe: ${r.stderr.trim()}`); return r.stdout.trim(); };
+// decode one frame to grayscale pixels at `w` px wide. H is measured from the file itself.
+const grab = (file, n, w, h) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select=eq(n\\,${n}),scale=${w}:${h}`, "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"], { maxBuffer: 1 << 26 });
+ if (r.status !== 0) die(`ffmpeg could not decode frame ${n}: ${r.stderr.toString().trim()}`);
+ if (r.stdout.length !== w * h) die(`frame ${n} decoded to ${r.stdout.length} bytes, expected ${w * h}`);
+ return r.stdout;
+};
+const changed = (a, b, threshold = 4) => { let n = 0; for (let i = 0; i < a.length; i++) if (Math.abs(a[i] - b[i]) > threshold) n++; return n / a.length; };
+
+// ---------------------------------------------------------------- the film's own numbers
+const mod = await import(`./adapters/${adapterName}.mjs`);
+const p = mod.probe();
+if (!p.ok) die(`adapter "${adapterName}": ${p.why}`);
+const s = await mod.open(film, { scale: SCALE, workers: 1 });
+const meta = await s.info();
+const N = meta.durationFrames, FW = Math.round(meta.W * SCALE), FH = Math.round(meta.H * SCALE);
+const file = resolve(opt.file ?? defaultOutput(film));
+console.log(`VERIFY-EXPORT film "${meta.title}" file ${file}`);
+if (!existsSync(file)) die(`${file} not found`);
+
+// ---------------------------------------------------------------- 1. the container
+head(1, "CONTAINER the file is the film's size, length and duration");
+const stream = ffprobe(["-select_streams", "v:0", "-show_entries", "stream=codec_name,width,height,pix_fmt", "-of", "csv=p=0", file]).split("\n")[0].split(",");
+const [codec, sw, sh] = [stream[0], Number(stream[1]), Number(stream[2])];
+const wantW = opt.width ? Number(opt.width) : FW, wantH = Math.round((wantW * FH) / FW / 2) * 2; // encoders want even heights
+say(sw === wantW && Math.abs(sh - wantH) <= 2, `pixel size ${sw}x${sh}`, `expected ${wantW}x${wantH} (${codec}${stream[3] ? ", " + stream[3] : ""})`);
+const counted = Number(ffprobe(["-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]).split("\n")[0]);
+say(counted === N, `decoded frame count is ${counted}`, `the film is ${N}`);
+const dur = Number(ffprobe(["-show_entries", "format=duration", "-of", "csv=p=0", file]));
+const wantDur = N / meta.fps, slack = 1 / meta.fps + 0.05;
+say(Math.abs(dur - wantDur) <= slack, `duration ${dur.toFixed(3)} s`, `expected ${wantDur.toFixed(3)} s +/- ${slack.toFixed(3)} (container rounding)`);
+
+// ---------------------------------------------------------------- 2. the first frame's colour
+head(2, "FIRST FRAME what the audience's first instant actually looks like");
+const avg = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "select=eq(n\\,0),scale=1:1", "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 1 << 16 });
+if (avg.status !== 0 || avg.stdout.length < 3) die(`ffmpeg could not average frame 0: ${avg.stderr.toString().trim()}`);
+const hex = `#${[...avg.stdout.subarray(0, 3)].map((v) => v.toString(16).padStart(2, "0")).join("")}`;
+if (opt["first-frame"]) {
+ const want = opt["first-frame"].replace("#", "");
+ if (!/^[0-9a-fA-F]{6}$/.test(want)) die(`--first-frame wants #rrggbb, got '${opt["first-frame"]}'`);
+ const tol = +(opt.tol ?? 8), wr = parseInt(want.slice(0, 2), 16), wg = parseInt(want.slice(2, 4), 16), wb = parseInt(want.slice(4, 6), 16);
+ const off = [Math.abs(avg.stdout[0] - wr), Math.abs(avg.stdout[1] - wg), Math.abs(avg.stdout[2] - wb)];
+ say(off.every((v) => v <= tol), `decoded first frame averages ${hex}`, `expected ${opt["first-frame"]} +/- ${tol} per channel (off by ${off.join("/")})`);
+} else note("no --first-frame given", `decoded first frame averages ${hex}; nothing asserted (a transparent or non-uniform first frame has no single right colour)`);
+
+// ---------------------------------------------------------------- 3. fidelity to the source, if asked
+if (opt["fidelity-psnr"]) {
+ head(3, "FIDELITY the decoded frame is the frame the source drew");
+ const src = resolve(TMP, "source-0.png"), dec = resolve(TMP, "decoded-0.png");
+ writeFileSync(src, (await s.frame(0, 0)).png);
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "select=eq(n\\,0)", "-vsync", "0", "-frames:v", "1", "-y", dec], { encoding: "utf8" });
+ if (r.status !== 0) die(`ffmpeg could not lift frame 0: ${r.stderr.trim()}`);
+ const ps = spawnSync("ffmpeg", ["-v", "error", "-i", dec, "-i", src, "-lavfi", "psnr=stats_file=-", "-f", "null", "-"], { encoding: "utf8" });
+ const m = (ps.stdout + ps.stderr).match(/psnr_avg:([0-9.]+|inf)/), v = m ? (m[1] === "inf" ? Infinity : Number(m[1])) : NaN;
+ say(v >= +opt["fidelity-psnr"], `decoded frame 0 vs source frame 0: ${v === Infinity ? "inf" : v.toFixed(2)} dB`, `bar ${opt["fidelity-psnr"]} dB`);
+}
+
+// ---------------------------------------------------------------- 4. the seam, if it loops
+if (opt.loop) {
+ head(4, "LOOP SEAM the join reads like any other step of the loop");
+ if (N < 4) note("film too short to judge a seam", `${N} frames`);
+ else {
+ const W = 270, H = Math.max(2, Math.round((W * wantH) / wantW));
+ const first = grab(file, 0, W, H), last = grab(file, N - 1, W, H), seam = changed(last, first);
+ const samples = Math.min(11, N - 1), deltas = [];
+ for (let i = 0; i < samples; i++) { const f = 1 + Math.round((i * (N - 2)) / Math.max(1, samples - 1)); if (f >= N) continue; deltas.push(changed(grab(file, f - 1, W, H), grab(file, f, W, H))); }
+ deltas.sort((a, b) => a - b);
+ const med = deltas[deltas.length >> 1] ?? 0, ceiling = Math.max(2 * med, 0.005);
+ say(seam <= ceiling, `last-to-first step changes ${(seam * 100).toFixed(2)}% of the frame`, `mid-loop median ${(med * 100).toFixed(2)}%, ceiling ${(ceiling * 100).toFixed(2)}% (2x median, 0.5% floor)`);
+ }
+}
+
+await s.close();
+console.log(`\n${"=".repeat(58)}`);
+console.log(fails ? `VERIFY-EXPORT: FAIL ${fails} of ${checks} checks failed` : `VERIFY-EXPORT: PASS ${checks}/${checks} checks`);
+process.exit(fails ? 1 : 0);
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
index a680f8c..8aefbfe 100644
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
+++ b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
@@ -2,34 +2,26 @@
// plane scale 1/(D + z). The hero plane is z = 0, so the hero scale S is 1/D, and S is SCREEN
// PIXELS PER SHEET UNIT: at S = 1 the creature (wingspan 780 units) is 780 px across.
//
-// NOTE, one engine item, does not block the stills: the finale world's projector
-// (butterfly/finale/world.ts) normalises every plane by (1 + z) so that all planes are 1:1 on the
-// last frame. That convention inverts parallax for D > 1, and movement 2 spends almost all of its
-// time there (D runs 0.25 to 8.7). This movement uses the spec's model instead. The two have to
-// be reconciled once, at the wide end, by choosing world positions for the last bars; that is
-// G-W work, not stills work.
-import { P } from "../../core";
+// The machinery lives in the engine now (canvas-core/camera.ts): the dolly math, the monotone
+// log2 zoom path, the stroke-weight rule. What stays here is this film's own choreography: the
+// zoom path keyed on the bars, and the units the shots were written in.
+//
+// NOTE, one engine item: the finale world's projector (butterfly/finale/world.ts) normalises
+// every plane by (1 + z) so that all planes are 1:1 on the last frame. That convention inverts
+// parallax for D > 1, and movement 2 spends almost all of its time there (D runs 0.25 to 8.7).
+// It is an authored end-frame framing, not the dolly model, and it stays with the finale.
+import { type P } from "../../core";
+import { monoPath, planeScale, projectCam, strokeWeight } from "../../camera";
import { S_KEYS } from "./cues";
export type Cam = { S: number; look: P };
export const distance = (S: number) => 1 / S;
-export const scaleAt = (c: Cam, z: number) => 1 / (distance(c.S) + z);
-export const projector = (c: Cam, z: number) => { const k = scaleAt(c, z); return { k, at: (p: P): P => [540 + (p[0] - c.look[0]) * k, 540 + (p[1] - c.look[1]) * k] }; };
+const asEngine = (c: Cam) => ({ look: c.look, zoom: c.S });
+export const scaleAt = (c: Cam, z: number) => planeScale(asEngine(c), z);
+export const projector = (c: Cam, z: number) => { const k = scaleAt(c, z); return { k, at: (p: P) => projectCam([540, 540], asEngine(c), z, p) }; };
// A close shot must not fatten the line by the zoom: w = w_authored * S^0.35 (spec 4).
-export const weight = (S: number) => Math.pow(S, 0.35);
-
-// Monotone cubic (Fritsch-Carlson) so the dolly never overshoots into a scale it was not given,
-// and never reverses: S is interpolated in log2, which is what "one stop of zoom" means.
-const mono = (xs: number[], ys: number[], x: number): number => {
- const n = xs.length;
- if (x <= xs[0]) return ys[0];
- if (x >= xs[n - 1]) return ys[n - 1];
- const d: number[] = []; for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]));
- const m: number[] = [d[0]]; for (let i = 1; i < n - 1; i++) m.push(d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2); m.push(d[n - 2]);
- for (let i = 0; i < n - 1; i++) { if (d[i] === 0) { m[i] = 0; m[i + 1] = 0; continue; } const a = m[i] / d[i], b = m[i + 1] / d[i], s = a * a + b * b; if (s > 9) { const t = 3 / Math.sqrt(s); m[i] = t * a * d[i]; m[i + 1] = t * b * d[i]; } }
- let i = 0; while (x > xs[i + 1]) i++;
- const h = xs[i + 1] - xs[i], t = (x - xs[i]) / h, t2 = t * t, t3 = t2 * t;
- return ys[i] * (2 * t3 - 3 * t2 + 1) + h * m[i] * (t3 - 2 * t2 + t) + ys[i + 1] * (-2 * t3 + 3 * t2) + h * m[i + 1] * (t3 - t2);
-};
-const SX = S_KEYS.map((k) => k[0]), SY = S_KEYS.map((k) => Math.log2(k[1]));
-export const scaleOf = (local: number): number => Math.pow(2, mono(SX, SY, local));
+export const weight = (S: number) => strokeWeight({ look: [0, 0], zoom: S });
+// The zoom path, keyed on the bars and read in stops: S is interpolated in log2, which is what
+// "one stop of zoom" means, and the cubic is monotone so the dolly never overshoots into a scale
+// it was not given, and never reverses.
+export const scaleOf = monoPath(S_KEYS, { log2: true });
diff --git a/plugins/anidoodle/skills/anidoodle/references/camera.md b/plugins/anidoodle/skills/anidoodle/references/camera.md
new file mode 100644
index 0000000..8b3137c
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/camera.md
@@ -0,0 +1,84 @@
+# The camera: one dolly, keyed on the frame grid
+
+`engine/src/canvas-core/camera.ts` is the camera. A film either draws in world coordinates
+inside `begin()`/`end()` (the transform path: dirty boxes stay right because the camera rides
+the `Gfx` transform stack), or asks `toScreen()` where a world point lands and draws there (the
+projector path). Both come from the same state, so a caption pinned to the frame and the world
+it floats over can never disagree. Everything is a pure function of the frame: the same camera
+question gets the same answer on any machine, in any order.
+
+## The move
+
+```ts
+import { Camera } from "./camera";
+
+const cam = new Camera([W / 2, H / 2], [
+ { f: 0, look: [400, 300], zoom: 1, ease: "inout" }, // ease governs the segment this key LEAVES
+ { f: 90, look: [900, 300], zoom: 2 },
+ { f: 150, look: [900, 300], zoom: 2 }, // a hold: say it, don't imply it
+ { f: 240, look: [400, 300], zoom: 1 },
+]);
+cam.shake({ from: 96, to: 126, amp: 14, seed: 7, rot: 0.004 }); // an impact, ringing down
+```
+
+- **Zoom is interpolated in log2.** A zoom is a ratio: halving the apparent size twice should
+ take twice as long as halving it once. Ease the zoom value itself and a long push-in sprints
+ at the near end and crawls at the far one; easing log2(zoom) spends time evenly per stop.
+- **Easing per segment, `inout` (easeInOutCubic) by default.** A camera move with no live
+ operator should accelerate gently and arrive gently. `linear` reads as mechanical, `out`
+ alone reads as interrupted, `in` alone as a fall.
+- **A zoom path with several keys** breathes at every key under per-segment easing. Pass
+ `monoZoom: true` to run one monotone cubic through all the zoom keys in log2 instead: smooth,
+ never overshooting into a scale it was not given, never reversing.
+- **Authored paths**: for a camera that follows a creature or a curve, pass
+ `path: (f) => ({ look, zoom })` instead of keys. Same camera, same shake, same projections.
+
+## Depth planes (parallax)
+
+The camera sits at distance D = 1/zoom from the hero plane (z = 0). A plane at depth z scales
+by `1/(D + z)` and moves with it: near planes swing wide, far ones barely stir, and every
+element at a depth agrees with every other, because there is only one camera. Positive z
+recedes; a negative z crosses the lens (grass across the glass). Pass the plane's z to
+`begin(g, f, z)` or `toScreen(p, f, z)`. One dolly, one number, and the parallax is true for
+every element at once: do not hand-each-plane its own drift.
+
+## Shake
+
+`shake({ from, to, amp, seed, freq, rot, attack })` registers an impact or a handheld stretch:
+
+- **amp in SCREEN pixels**, so the shake reads the same at any zoom; **rot** in radians at full
+ strength, about the frame's centre. A small rotation is what actually sells handheld.
+- The envelope is an **attack ramp** (default 2 frames) into a **squared decay**: full strength
+ at the hit, gone a beat later. An impact rings down; it does not stop mid-air.
+- The motion is **low-frequency gradient noise**, seeded, never white noise per frame. Static
+ per frame reads as a faulty projector; smooth noise reads as mass. `freq` is cycles per frame
+ (default 0.35, about 10 Hz at 30 fps; drop it for a heavier camera).
+- Shake is folded into `shaken(f)`, which `begin` and `toScreen` read, so the drawn world and
+ any projected overlay shake together. `at(f)` stays clean for driving things that must not
+ shake (the score, a cue grid).
+
+## Line weight at close range
+
+Ink is authored at some view; at zoom S the same nib reads S times heavier. Divide stroke widths
+by `weight(cam)` = S^0.35. Not S: a little weight gain is what makes a close-up feel close
+rather than enlarged.
+
+## The two drawing paths
+
+```ts
+// transform path: the world moves, you draw in world units
+cam.begin(g, f); // hero plane
+meadow(g, f);
+cam.end(g);
+cam.begin(g, f, 2.2); // a farther plane
+hills(g, f);
+cam.end(g);
+
+// projector path: ask where things are, draw them there (cached surfaces, screen-space type)
+const at = cam.toScreen(flower.centre, f, flower.z);
+const k = cam.scaleAt(cam.at(f), flower.z);
+```
+
+`toWorld(s, f, z)` inverts `toScreen`, for hit-testing or for pinning world content to a screen
+point. The camera never touches the context itself, the clock, or `Math.random`: it is
+arithmetic over `(frame, keys, seed)`, which is what keeps the determinism contract intact.
diff --git a/plugins/anidoodle/skills/anidoodle/references/formats.md b/plugins/anidoodle/skills/anidoodle/references/formats.md
index c56fe15..d41ddf5 100644
--- a/plugins/anidoodle/skills/anidoodle/references/formats.md
+++ b/plugins/anidoodle/skills/anidoodle/references/formats.md
@@ -35,7 +35,9 @@ the craft table, then show it.
- **Seamless loop**: drive everything from `t = local / DURATION` through functions that repeat
a whole number of times over `[0, 1)` (`sin(2 * PI * k * t)`, integer `k`). Frame `DURATION`
then equals frame 0 and the seam disappears. Check it: render the last frame and frame 0 and
- compare them to a mid-loop neighbour pair.
+ compare them to a mid-loop neighbour pair, or run `node tools/verify-export.mjs <name> --loop`
+ on the rendered file, which judges the last-to-first step against the loop's own mid-loop
+ deltas.
- **Animated logo / sticker**: 2 to 4 seconds, the mark DRAWN on (`progress` on `g.pen`,
`letter`), a settle, a small idle. Leave the background unpainted for transparency.
- **Ambient / idle art** (a site header that breathes, a banner): the subject never stops; the
@@ -58,6 +60,11 @@ the craft table, then show it.
| APNG | `node tools/render.mjs <name> --out out/x.apng [--width 512]` | alpha loops that play in every browser |
| HTML | `node tools/emit.mjs <name> --out out/x.html` | the piece itself: one offline file that redraws it, with sound, on a double-click |
+After any encode, `node tools/verify-export.mjs <name> [--first-frame #hex] [--fidelity-psnr 40]`
+proves the file on disk is the film: size, exact frame count, duration, and optionally the first
+frame's average colour and its fidelity to the source frame. All of it is opt-in beyond the
+container facts, so transparent and non-uniform pieces pass cleanly.
+
A still needs a browser only (`npx playwright-core install chromium`). Anything that moves also needs
`ffmpeg`. `gate.mjs` runs on all of them and marks the checks that do not apply to the piece,
a silent loop's audio or a still's dead air, as `----` rather than passing them.
diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md
index 7bd8dcd..10b8335 100644
--- a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md
+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md
@@ -10,6 +10,30 @@ Product screenshots, a logo, UI captures, a repo link, a feature list. Images th
embedded (pinned by sha256, provenance recorded in the film's manifest); everything around them
is drawn in code. Never generate or fetch images.
+## Ground it in the real product first
+
+Before any storyboarding, write a short sourced brief and get ONE approval on it. A launch film
+that invents its subject draws a mascot of a product, not the product. Keep it light: one brief,
+one look approval, then build.
+
+1. **Read the real thing.** Open what exists: the screenshots and captures they brought, the
+ repo's README and UI components, the live page. Note the two or three REAL features a viewer
+ should recognise on screen, the exact product name and mark, and the brand colours as hex.
+2. **Collect approved claims.** The one-line promise and any numbers come from the person's own
+ materials (site copy, release notes, the README), each with its source written next to it.
+ Anything you cannot source becomes a question, not a line in the film. Write the claims the
+ film must NOT make while you are at it.
+3. **Ask the grounding questions**, one message: which real features to show (pick from the
+ list you found, recommend your three), which shapes to ship (`9x16`, `16x9`, `1x1`), text
+ treatment (drawn kinetic type, their UI captures, or both), and where it will run.
+4. **Write the brief** where the film's files will live: product and promise, the chosen
+ features with their sources, brand colours mapped onto the style's palette roles, the
+ approved claims and the banned ones, the shapes. The storyboard and every caption then quote
+ the brief, never memory.
+
+The film still opens with a drawn hook, not a feature list: the brief decides WHAT the film may
+claim and show, never how it moves.
+
## Shape of the film
1. **Hook in the first two seconds**: the problem, drawn being made (a tangle, a pile, a clock),
diff --git a/skills/anidoodle/SKILL.md b/skills/anidoodle/SKILL.md
index 8c6206f..6a2b937 100644
--- a/skills/anidoodle/SKILL.md
+++ b/skills/anidoodle/SKILL.md
@@ -97,6 +97,9 @@ draws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze
`engine/` is the portable art core plus the tooling. `engine/src/canvas-core` knows nothing
about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`.
+Camera moves (pans, zooms, parallax, shake) come from `engine/src/canvas-core/camera.ts`:
+`references/camera.md`. `render.mjs --blur N` renders with motion blur (N subframes averaged in
+linear light per frame); the default path is untouched.
```bash
node <skill>/engine/tools/scaffold.mjs ~/art --film intro --format 9x16 --duration 180
@@ -114,6 +117,7 @@ node tools/emit.mjs intro --out out/intro.html # one self-co
| `gate.mjs` | determinism, contract, dead air, artifact; `--self-test` proves it can fail |
| `registry.mjs` / `gallery.mjs` | the style list from the plates themselves / the gallery sheet |
| `docs-check.mjs` | fails when any doc's style count, length or path disagrees with the code |
+| `verify-export.mjs` | opt-in QA on the rendered file: frame count, duration, first-frame colour, loop seam |
| `music.mjs` | renders and meters a score (loudness, range, onsets, brightness) |
Four backends, one art core: `playwright`, `html-player`, `remotion`, `hyperframes`.
diff --git a/skills/anidoodle/engine/src/canvas-core/camera.ts b/skills/anidoodle/engine/src/canvas-core/camera.ts
new file mode 100644
index 0000000..e974309
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/camera.ts
@@ -0,0 +1,164 @@
+// THE CAMERA. One dolly over depth planes, keyed on the frame grid. A film either draws in world
+// coordinates inside begin()/end() (the transform path, dirty boxes stay right), or asks
+// toScreen() where a world point lands and draws there (the projector path). Both come from the
+// same state, so a caption pinned to the frame and the world it floats over can never disagree.
+//
+// CRAFT, and why the numbers work this way:
+// - ZOOM IS INTERPOLATED IN log2. A zoom is a ratio: halving the apparent size twice should take
+// twice as long as halving it once. Easing the zoom value itself makes a long push-in sprint at
+// the near end and crawl at the far one; easing log2(zoom) spends time evenly per stop.
+// - EASING PER SEGMENT, ease-in-out by default. A camera move with no live operator should
+// accelerate gently and arrive gently; linear reads as mechanical, ease-out alone reads as
+// interrupted. The ease lives on the key the segment LEAVES.
+// - PARALLAX IS ONE NUMBER. The camera sits at distance D = 1/zoom from the hero plane (z = 0);
+// a plane at depth z scales by zoom/(1 + z*zoom) and moves with it. Near planes swing wide, far
+// ones barely stir, and every element at a depth agrees with every other, because there is only
+// one camera. Positive z recedes; a negative z crosses the lens (grass across the glass).
+// - A CLOSE SHOT MUST NOT FATTEN THE LINE. Ink is authored at some view; at zoom S the same nib
+// reads S times heavier, so stroke widths divide by weight(S) = S^0.35 (not S: a little weight
+// gain is what makes a close-up feel close rather than enlarged).
+// - SHAKE IS DECAYING NOISE, NEVER RANDOM PER FRAME. An impact rings down: full amplitude at the
+// hit, gone a beat later, smooth in between. White noise per frame reads as static, not as a
+// camera; low-frequency gradient noise with an attack ramp and a squared decay reads as mass.
+// The shake is given in SCREEN pixels so it reads the same at any zoom, plus a small rotation
+// about the frame's centre, which is what actually sells handheld.
+import { fractal, Gfx, P } from "./core";
+
+export type Cam = { look: P; zoom: number }; // look: world point at the frame's centre; zoom: screen px per world unit on the hero plane
+export type EaseName = "linear" | "in" | "out" | "inout";
+export const EASE: Record<EaseName, (u: number) => number> = {
+ linear: (u) => u,
+ in: (u) => u * u * u,
+ out: (u) => 1 - Math.pow(1 - u, 3),
+ inout: (u) => (u < 0.5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2), // easeInOutCubic: the camera default
+};
+export type CamKey = { f: number; look?: P; zoom?: number; ease?: EaseName }; // ease governs the segment this key LEAVES
+export type Shake = { from: number; to: number; amp: number; seed: number; freq?: number; rot?: number; attack?: number };
+
+// Monotone cubic (Fritsch-Carlson): a smooth path through every key that never overshoots into a
+// value it was not given and never reverses. With log2 set, the values are read and returned in
+// stops: log2 in, linear out. Use it for a zoom path with several keys, where per-segment easing
+// would breathe at every key.
+export const monoPath = (keys: readonly (readonly [number, number])[], opts: { log2?: boolean } = {}): ((x: number) => number) => {
+ const xs = keys.map((k) => k[0]), ys = keys.map((k) => (opts.log2 ? Math.log2(k[1]) : k[1])), n = xs.length;
+ if (n === 0) throw new Error("monoPath needs at least one key");
+ for (let i = 1; i < n; i++) if (xs[i] <= xs[i - 1]) throw new Error(`monoPath keys must increase: ${xs[i - 1]} then ${xs[i]}`);
+ const mono = (x: number): number => {
+ if (x <= xs[0]) return ys[0];
+ if (x >= xs[n - 1]) return ys[n - 1];
+ const d: number[] = []; for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]));
+ const m: number[] = [d[0]]; for (let i = 1; i < n - 1; i++) m.push(d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2); m.push(d[n - 2]);
+ for (let i = 0; i < n - 1; i++) { if (d[i] === 0) { m[i] = 0; m[i + 1] = 0; continue; } const a = m[i] / d[i], b = m[i + 1] / d[i], s = a * a + b * b; if (s > 9) { const t = 3 / Math.sqrt(s); m[i] = t * a * d[i]; m[i + 1] = t * b * d[i]; } }
+ let i = 0; while (x > xs[i + 1]) i++;
+ const h = xs[i + 1] - xs[i], t = (x - xs[i]) / h, t2 = t * t, t3 = t2 * t;
+ return ys[i] * (2 * t3 - 3 * t2 + 1) + h * m[i] * (t3 - 2 * t2 + t) + ys[i + 1] * (-2 * t3 + 3 * t2) + h * m[i + 1] * (t3 - t2);
+ };
+ return opts.log2 ? (x) => Math.pow(2, mono(x)) : mono;
+};
+
+const clampF = (v: number, a: number, b: number) => Math.max(a, Math.min(b, v));
+
+// ---- explicit-state helpers, for films that hold their own Cam per frame. The Camera class
+// below delegates to these; there is one math, whether the film keys the camera or computes it.
+// The dolly model: camera distance D = 1/zoom from the hero plane (z = 0); a plane at depth z
+// scales by 1/(D + z) and moves with it. Positive z recedes; negative z crosses the lens.
+export const planeScale = (c: Cam, z = 0): number => 1 / (1 / c.zoom + z);
+export const projectCam = (centre: P, c: Cam, z: number, p: P, rot = 0): P => {
+ const k = planeScale(c, z), co = Math.cos(rot), si = Math.sin(rot), dx = p[0] - c.look[0], dy = p[1] - c.look[1];
+ return [centre[0] + k * (co * dx - si * dy), centre[1] + k * (si * dx + co * dy)];
+};
+export const unprojectCam = (centre: P, c: Cam, z: number, s: P, rot = 0): P => {
+ const k = planeScale(c, z), co = Math.cos(rot), si = Math.sin(rot), dx = (s[0] - centre[0]) / k, dy = (s[1] - centre[1]) / k;
+ return [c.look[0] + co * dx + si * dy, c.look[1] - si * dx + co * dy];
+};
+// ink authored at some view reads zoom times heavier at a close one; divide stroke widths by
+// this. 0.35, not 1: a little weight gain is what makes a close-up feel close, not enlarged.
+export const strokeWeight = (c: Cam, exp = 0.35): number => Math.pow(c.zoom, exp);
+
+export class Camera {
+ private shakes: Shake[] = [];
+ private keys: CamKey[];
+ private path?: (f: number) => Cam;
+ private monoZoom: boolean;
+ // centre: the frame's centre in logical px (usually [W/2, H/2]); every projection goes through it
+ constructor(readonly centre: P, keys: CamKey[] = [], opts: { monoZoom?: boolean; path?: (f: number) => Cam } = {}) {
+ this.keys = [...keys]; // authored order, strictly increasing: a camera path is a cue table
+ this.path = opts.path;
+ this.monoZoom = opts.monoZoom ?? false;
+ if (!this.path && this.keys.length === 0) throw new Error("camera needs keys or a path");
+ let last = -1;
+ for (const k of this.keys) {
+ if (!Number.isInteger(k.f) || k.f < 0) throw new Error(`camera key at non-integral or negative frame ${k.f}`);
+ if (k.f <= last) throw new Error(`camera keys must increase: ${last} then ${k.f}`);
+ if (k.zoom !== undefined && k.zoom <= 0) throw new Error(`camera zoom must be positive, got ${k.zoom} at frame ${k.f}`);
+ last = k.f;
+ }
+ }
+
+ // one channel of the keys, eased per segment. Missing values hold the nearest given one, so a
+ // key may set only look or only zoom.
+ private channel(f: number, get: (k: CamKey) => number | undefined, log2: boolean): number {
+ const ks = this.keys.map((k, i) => ({ k, v: get(k), i })).filter((e) => e.v !== undefined) as { k: CamKey; v: number; i: number }[];
+ if (!ks.length) throw new Error("camera keys never set this channel");
+ if (log2 && this.monoZoom && ks.length > 1) return monoPath(ks.map((e) => [e.k.f, e.v] as const), { log2: true })(f);
+ if (f <= ks[0].k.f) return ks[0].v;
+ if (f >= ks[ks.length - 1].k.f) return ks[ks.length - 1].v;
+ let i = 0; while (f >= ks[i + 1].k.f) i++;
+ const [a, b] = [ks[i], ks[i + 1]], u = (f - a.k.f) / (b.k.f - a.k.f), e = EASE[a.k.ease ?? "inout"](clampF(u, 0, 1));
+ if (log2) return Math.pow(2, Math.log2(a.v) + (Math.log2(b.v) - Math.log2(a.v)) * e);
+ return a.v + (b.v - a.v) * e;
+ }
+
+ // the clean move at frame f, before shake. Pure.
+ at(f: number): Cam {
+ if (this.path) return this.path(f);
+ return { look: [this.channel(f, (k) => k.look?.[0], false), this.channel(f, (k) => k.look?.[1], false)], zoom: this.channel(f, (k) => k.zoom, true) };
+ }
+
+ // register an impact or a handheld stretch. amp in SCREEN px; rot in radians at full strength.
+ shake(s: Shake): this {
+ if (!(s.to > s.from)) throw new Error(`shake window must have length: ${s.from}..${s.to}`);
+ if (s.amp < 0) throw new Error("shake amp must be >= 0");
+ this.shakes.push(s);
+ return this;
+ }
+
+ // screen-space shake at f: [dx, dy] px and dr radians about the frame's centre. Pure.
+ shakeAt(f: number): [number, number, number] {
+ let dx = 0, dy = 0, dr = 0;
+ for (const s of this.shakes) {
+ if (f < s.from || f >= s.to) continue;
+ const u = (f - s.from) / (s.to - s.from), ramp = clampF((f - s.from + 1) / (s.attack ?? 2), 0, 1), fall = (1 - u) * (1 - u);
+ const amp = s.amp * ramp * fall, fq = s.freq ?? 0.35;
+ dx += amp * (fractal(s.seed, f * fq, 0, 1, 1, 2) * 2 - 1);
+ dy += amp * (fractal(s.seed + 101, f * fq, 0, 1, 1, 2) * 2 - 1);
+ dr += (s.rot ?? 0) * ramp * fall * (fractal(s.seed + 211, f * fq, 0, 1, 1, 2) * 2 - 1);
+ }
+ return [dx, dy, dr];
+ }
+
+ // the move the audience sees: the clean path with its shake folded in. A screen-space nudge of
+ // [dx, dy] is the camera's look point stepping BACK by that much, in world units.
+ shaken(f: number): Cam & { rot: number } {
+ const c = this.at(f), [dx, dy, dr] = this.shakeAt(f), k = c.zoom;
+ return { look: [c.look[0] - dx / k, c.look[1] - dy / k], zoom: c.zoom, rot: dr };
+ }
+
+ // plane scale at depth z for a camera state: the hero plane (z = 0) scales by zoom exactly.
+ scaleAt(c: Cam, z = 0): number { return planeScale(c, z); }
+
+ // stroke-weight compensation for a close shot (see strokeWeight above)
+ weight(c: Cam, exp = 0.35): number { return strokeWeight(c, exp); }
+
+ // ---- the transform path: draw in world coordinates inside begin/end. Dirty boxes stay right
+ // because the camera rides the Gfx transform stack instead of touching the context.
+ begin(g: Gfx, f: number, z = 0) {
+ const c = this.shaken(f), k = this.scaleAt(c, z), co = Math.cos(c.rot), si = Math.sin(c.rot);
+ g.push(this.centre[0] - k * (co * c.look[0] - si * c.look[1]), this.centre[1] - k * (si * c.look[0] + co * c.look[1]), k, c.rot);
+ }
+ end(g: Gfx) { g.pop(); }
+
+ // ---- the projector path: ask where a world point lands, draw there yourself
+ toScreen(p: P, f: number, z = 0): P { const c = this.shaken(f); return projectCam(this.centre, c, z, p, c.rot); }
+ toWorld(s: P, f: number, z = 0): P { const c = this.shaken(f); return unprojectCam(this.centre, c, z, s, c.rot); }
+}
diff --git a/skills/anidoodle/engine/src/canvas-core/core.ts b/skills/anidoodle/engine/src/canvas-core/core.ts
index c8e52a1..805e2b7 100644
--- a/skills/anidoodle/engine/src/canvas-core/core.ts
+++ b/skills/anidoodle/engine/src/canvas-core/core.ts
@@ -138,7 +138,7 @@ export class Gfx {
// `drawn`: union of every device box composited onto `main` since construction. Read-only for the
// art; the web profile (bake.ts) crops a part into a sprite by it. Setting it changes no pixel.
drawn: Rect | null = null;
- cur: Ctx; private pool: Tracked[] = []; private stack: [number, number, number][] = [[0, 0, 1]]; private box: Rect | null = null;
+ cur: Ctx; private pool: Tracked[] = []; private stack: [number, number, number, number][] = [[0, 0, 1, 0]]; private box: Rect | null = null;
constructor(public main: Ctx, public env: Env, public frame: number, public medium: Medium) {
this.cur = main; this.base(main);
// surfaces outlive the frame: allocating six full-size canvases per frame is pure churn
@@ -147,17 +147,17 @@ export class Gfx {
private get m() { return this.stack[this.stack.length - 1]; }
private get DW() { return Math.round(this.env.W * this.env.scale); }
private get DH() { return Math.round(this.env.H * this.env.scale); }
- private base(c: Ctx) { const [x, y, s] = this.m, k = this.env.scale; c.setTransform(k * s, 0, 0, k * s, k * x, k * y); }
+ private base(c: Ctx) { const [x, y, s, r] = this.m, k = this.env.scale; if (r === 0) { c.setTransform(k * s, 0, 0, k * s, k * x, k * y); return; } const co = Math.cos(r), si = Math.sin(r); c.setTransform(k * s * co, k * s * si, -k * s * si, k * s * co, k * x, k * y); }
private dev(c: Ctx) { c.setTransform(1, 0, 0, 1, 0, 0); }
private clip(r: Rect, pad = 0): Rect { return [Math.max(0, Math.floor(r[0] - pad)), Math.max(0, Math.floor(r[1] - pad)), Math.min(this.DW, Math.ceil(r[2] + pad)), Math.min(this.DH, Math.ceil(r[3] + pad))]; }
private join(a: Rect | null, b: Rect): Rect { return a ? [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[2], b[2]), Math.max(a[3], b[3])] : b; }
// local points -> device box, with `pad` local units of slack (line weight, displacement, blur)
- private boxOf(pts: P[], pad: number): Rect { const [tx, ty, s] = this.m, k = this.env.scale; let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } return this.clip([k * (tx + (x0 - pad) * s), k * (ty + (y0 - pad) * s), k * (tx + (x1 + pad) * s), k * (ty + (y1 + pad) * s)]); }
+ private boxOf(pts: P[], pad: number): Rect { const [tx, ty, s, r] = this.m, k = this.env.scale; let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } x0 -= pad; y0 -= pad; x1 += pad; y1 += pad; if (r === 0) return this.clip([k * (tx + x0 * s), k * (ty + y0 * s), k * (tx + x1 * s), k * (ty + y1 * s)]); const co = Math.cos(r), si = Math.sin(r), cs = [[x0, y0], [x1, y0], [x0, y1], [x1, y1]]; let a0 = 1e9, b0 = 1e9, a1 = -1e9, b1 = -1e9; for (const [x, y] of cs) { const ax = k * (tx + s * (co * x - si * y)), by = k * (ty + s * (si * x + co * y)); if (ax < a0) a0 = ax; if (by < b0) b0 = by; if (ax > a1) a1 = ax; if (by > b1) b1 = by; } return this.clip([a0, b0, a1, b1]); }
mark(pts: P[], pad = 4) { this.box = this.join(this.box, this.boxOf(pts, pad)); }
touch(x0: number, y0: number, x1: number, y1: number) { this.mark([[x0, y0], [x1, y1]], 0); } // for raw ctx drawing inside a group
layer(): Tracked { let L = this.pool.pop(); if (!L) { L = this.env.canvas(this.DW, this.DH) as Tracked; L.dirty = null; } this.dev(L.ctx); L.ctx.globalCompositeOperation = "source-over"; L.ctx.globalAlpha = 1; if (L.dirty) { const d = L.dirty; L.ctx.clearRect(d[0], d[1], d[2] - d[0], d[3] - d[1]); L.dirty = null; } return L; }
release(L: Tracked, dirty: Rect | null) { L.dirty = dirty ? this.join(L.dirty ?? null, dirty) : L.dirty; this.pool.push(L); }
- push(x: number, y: number, s: number) { const [px, py, ps] = this.m; this.stack.push([px + x * ps, py + y * ps, ps * s]); this.base(this.cur); }
+ push(x: number, y: number, s: number, r = 0) { const [px, py, ps, pr] = this.m; if (pr === 0) { this.stack.push([px + x * ps, py + y * ps, ps * s, r]); this.base(this.cur); return; } const co = Math.cos(pr), si = Math.sin(pr); this.stack.push([px + ps * (co * x - si * y), py + ps * (si * x + co * y), ps * s, pr + r]); this.base(this.cur); }
pop() { this.stack.pop(); this.base(this.cur); }
path(c: Ctx, pts: P[]) { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }
diff --git a/skills/anidoodle/engine/src/hosts/page.ts b/skills/anidoodle/engine/src/hosts/page.ts
index f2924cf..9eaf499 100644
--- a/skills/anidoodle/engine/src/hosts/page.ts
+++ b/skills/anidoodle/engine/src/hosts/page.ts
@@ -22,9 +22,31 @@ export const mountFilm = (film: Film) => {
const seek = (frame: number) => { const t0 = performance.now(); const shot = renderFrame(film, ctx, frame, env); ctx.getImageData(0, 0, 1, 1); current = frame; return { shot, ms: performance.now() - t0 }; }; // getImageData forces the deferred raster so the timing is real
const hash = () => { const d = ctx.getImageData(0, 0, canvas.width, canvas.height).data; let h = 0x811c9dc5; for (let i = 0; i < d.length; i++) { h ^= d[i]; h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(16); };
const b64 = (u8: Uint8Array) => { let s = ""; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode(...u8.subarray(i, i + 0x8000)); return btoa(s); };
+ // MOTION BLUR. One output frame as the average of subframes spread over a one-frame shutter
+ // centred on it, confined to its own shot so nothing bleeds across a cut. The average is taken
+ // in LINEAR light: blur is light integration, and averaging in sRGB darkens every moving edge.
+ // hosts may keep time; the core never does.
+ const toLin = new Float32Array(256);
+ for (let i = 0; i < 256; i++) { const s = i / 255; toLin[i] = s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4); }
+ const fromLin = (l: number) => { const v = l <= 0.0031308 ? l * 12.92 : 1.055 * Math.pow(l, 1 / 2.4) - 0.055; return Math.max(0, Math.min(255, Math.round(v * 255))); };
+ const blur = (frame: number, samples: number) => {
+ const n = Math.max(0, Math.min(film.meta.durationFrames - 1, Math.round(frame))), shot = film.shots.find((s) => n >= s.start && n < s.end);
+ if (!shot || samples < 2) return { shot: shot?.id ?? null, ms: 0 };
+ const t0 = performance.now(), w = canvas.width, h = canvas.height, acc = new Float64Array(w * h * 4);
+ for (let i = 0; i < samples; i++) {
+ const t = Math.min(shot.end - 1, Math.max(shot.start, n + (i + 0.5) / samples - 0.5));
+ renderFrame(film, ctx, t, env);
+ const d = ctx.getImageData(0, 0, w, h).data;
+ for (let p = 0; p < d.length; p += 4) { acc[p] += toLin[d[p]]; acc[p + 1] += toLin[d[p + 1]]; acc[p + 2] += toLin[d[p + 2]]; acc[p + 3] += d[p + 3]; }
+ }
+ const img = ctx.createImageData(w, h), o = img.data, inv = 1 / samples;
+ for (let p = 0; p < o.length; p += 4) { o[p] = fromLin(acc[p] * inv); o[p + 1] = fromLin(acc[p + 1] * inv); o[p + 2] = fromLin(acc[p + 2] * inv); o[p + 3] = Math.round(acc[p + 3] * inv); }
+ ctx.putImageData(img, 0, 0); current = n;
+ return { shot: shot.id, ms: performance.now() - t0 };
+ };
const audio = (sr: number) => { if (!film.audio) return null; const [L, R] = film.audio(sr); if (L.length !== R.length) throw new Error("audio channels have different lengths"); const pcm = new Float32Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; } return { sampleRate: sr, frames: L.length, float32: b64(new Uint8Array(pcm.buffer)) }; };
const warm = () => film.shots.forEach((s) => { seek(s.start); seek(s.start + ((s.end - s.start) >> 1)); }); // first + middle frame of every shot: builds tiles, pre-allocates the layer pool
- window.FILM = { meta: { ...film.meta, shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
+ window.FILM = { meta: { ...film.meta, shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
// ---- the player: click or space to play, arrows to step, ?frame=N to open on a frame
ready.then(() => {
diff --git a/skills/anidoodle/engine/tools/adapters/playwright.mjs b/skills/anidoodle/engine/tools/adapters/playwright.mjs
index b0c2f13..60e6d35 100644
--- a/skills/anidoodle/engine/tools/adapters/playwright.mjs
+++ b/skills/anidoodle/engine/tools/adapters/playwright.mjs
@@ -16,6 +16,8 @@ export const open = async ({ pw, browser: found }, pagePath, { scale = 1, worker
// -> { png: Buffer, shot, drawMs, captureMs }
frame: async (n, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate((f) => { const s = window.FILM.seek(f); const t = performance.now(); const png = window.FILM.png(); return { ...s, png, enc: performance.now() - t }; }, n); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
hash: (n, w = 0) => pick(w).evaluate((f) => { window.FILM.seek(f); return window.FILM.hash(); }, n),
+ // motion-blurred frame: `samples` subframes averaged in the page (see hosts/page.ts blur)
+ blur: async (n, samples, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, s]) => { const r = window.FILM.blur(f, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
audio: (sr) => pages[0].evaluate((s) => window.FILM.audio(s), sr),
close: () => browser.close(),
};
diff --git a/skills/anidoodle/engine/tools/render.mjs b/skills/anidoodle/engine/tools/render.mjs
index 5d48fc8..ca27bd3 100644
--- a/skills/anidoodle/engine/tools/render.mjs
+++ b/skills/anidoodle/engine/tools/render.mjs
@@ -1,4 +1,11 @@
// node tools/render.mjs [film] [--scale 1] [--workers 4] [--out out/x.mp4|.gif|.webm|.apng] [--gif-fps 15] [--width 640]
+// [--blur N] [--from F] [--to F]
+// --blur N motion blur: every output frame is the average of N subframes over a one-frame
+// shutter, integrated in linear light inside the page. Fast pans and dolly moves stop
+// juddering; stills and stepped (on-twos) art are unchanged because their subframes are
+// identical. Costs N times the draw time. The default path (--blur 1) is untouched.
+// --from/--to render only frames [from, to): for checking a passage, not for shipping. A range
+// render is silent (the score would not line up) and says so.
// Auto-detects a backend, renders every frame through it, encodes with ffmpeg, then VERIFIES.
// .mp4 the film, with its score
// .gif loops and README heroes: silent, loops forever, ONE palette built from the whole piece
@@ -19,6 +26,7 @@ import { float32Wav } from "./audio.mjs";
const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };
const film = process.argv[2] && !process.argv[2].startsWith("--") ? process.argv[2] : "fixtures";
+const BLUR = Math.max(1, Number(arg("blur", 1)));
const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2))))), out = resolve(arg("out", defaultOutput(film)));
const env = detect();
@@ -29,10 +37,15 @@ console.log(`using: ${env.chosen}\n`);
const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });
console.log(`page: ${page.out} (${(page.bytes / 1024).toFixed(0)} KB)`);
const t0 = Date.now(), session = await playwright.open(env, page.out, { scale, workers }), meta = await session.info(), N = meta.durationFrames;
+const FROM = Math.max(0, Number(arg("from", 0))), TO = Math.min(N, Number(arg("to", N)));
+if (!Number.isInteger(FROM) || !Number.isInteger(TO) || TO <= FROM) { console.error(`bad range: [${FROM}, ${TO}) of ${N}`); process.exit(2); }
+const ranged = FROM !== 0 || TO !== N;
console.log(`film: "${meta.title}" ${meta.W}x${meta.H} @ ${meta.fps} fps, ${N} frames, ${meta.bpm} bpm, scale ${scale}, ${session.workers} page(s)`);
+if (BLUR > 1) console.log(`motion blur: ${BLUR} subframes per frame, one-frame shutter, linear light`);
+if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent by design`);
-// audio: pure JS in the page -> WAV here
-mkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = await session.audio(48000);
+// audio: pure JS in the page -> WAV here (skipped for a range render: the score would not line up)
+mkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = ranged ? null : await session.audio(48000);
if (a) writeFileSync(wav, float32Wav(a));
mkdirSync(join(out, ".."), { recursive: true });
@@ -49,9 +62,10 @@ const ff = spawn(env.ffmpeg.bin, encode, { stdio: ["pipe", "inherit", "inherit"]
const done = new Promise((res, rej) => ff.on("close", (c) => (c ? rej(new Error(`ffmpeg exited ${c}`)) : res())));
// frames render in parallel across pages, and are fed to ffmpeg strictly in order
-const cost = [], pending = new Map(); let next = 0, write = 0;
+const cost = [], pending = new Map(); let next, write;
const pump = async () => { while (pending.has(write)) { const b = pending.get(write); pending.delete(write); if (!ff.stdin.write(b)) await new Promise((r) => ff.stdin.once("drain", r)); write++; } };
-await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < N) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await session.frame(n, w); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs }); pending.set(n, f.png); await pump(); } }));
+next = FROM; write = FROM;
+await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = BLUR > 1 ? await session.blur(n, BLUR, w) : await session.frame(n, w); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs }); pending.set(n, f.png); await pump(); } }));
await pump(); ff.stdin.end(); await done;
const wall = (Date.now() - t0) / 1000;
@@ -61,10 +75,11 @@ console.log("\nframe cost (ms), draw = art core only, png = canvas PNG encode in
for (const id of [...new Set(cost.map((c) => c.shot))]) { const c = cost.filter((x) => x.shot === id), d = stat(c.map((x) => x.draw)), e = stat(c.map((x) => x.enc)); console.log(` ${id.padEnd(12)} draw median ${d.med.toFixed(0)} p95 ${d.p95.toFixed(0)} max ${d.max.toFixed(0)} | png median ${e.med.toFixed(0)} (${c.length} frames)`); }
const slow = [...cost].sort((a, b) => b.draw - a.draw).slice(0, 3).map((c) => `#${c.n} ${c.shot} ${c.draw.toFixed(0)}ms`).join(", ");
console.log(` slowest: ${slow}\n budget: 150 ms draw per frame -> ${cost.every((c) => c.draw <= 150) ? "PASS" : "OVER on " + cost.filter((c) => c.draw > 150).length + " frames"}`);
-console.log(` wall clock: ${wall.toFixed(1)} s for ${N} frames = ${(N / wall).toFixed(1)} fps end to end (build + launch + render + encode)`);
+console.log(` wall clock: ${wall.toFixed(1)} s for ${TO - FROM} frames = ${((TO - FROM) / wall).toFixed(1)} fps end to end (build + launch + render + encode)`);
// ---- verify: same frame, different order, different page. Standard = visually identical; hash equality is the cheap first test.
-const probe = [...new Set([0, ...meta.shots.flatMap((s) => [s.start, s.end - 1]), ...((k) => Array.from({ length: k }, (_, i) => Math.round(i * (N - 1) / (k - 1 || 1))))(Math.min(6, N)), N - 1])].sort((a, b) => a - b), fwd = [], rev = [];
+const probe = [...new Set([0, ...meta.shots.flatMap((s) => [s.start, s.end - 1]), ...((k) => Array.from({ length: k }, (_, i) => Math.round(i * (N - 1) / (k - 1 || 1))))(Math.min(6, N)), N - 1])].filter((n) => n >= FROM && n < TO).sort((a, b) => a - b), fwd = [], rev = [];
+if (!probe.length) probe.push(FROM);
for (const n of probe) fwd.push(await session.hash(n, 0)); for (const n of [...probe].reverse()) rev.unshift(await session.hash(n, session.workers - 1));
const same = probe.filter((_, i) => fwd[i] === rev[i]).length;
console.log(`\ndeterminism: ${same}/${probe.length} probe frames hash-identical (forward on page 0 vs reversed on page ${session.workers - 1})${same === probe.length ? "" : " -> fall back to PSNR > 45 dB in the Phase 2 gate"}`);
diff --git a/skills/anidoodle/engine/tools/verify-export.mjs b/skills/anidoodle/engine/tools/verify-export.mjs
new file mode 100644
index 0000000..c797e5a
--- /dev/null
+++ b/skills/anidoodle/engine/tools/verify-export.mjs
@@ -0,0 +1,110 @@
+// VERIFY-EXPORT. The gate proves the SOURCE draws the same frame every time; this proves the
+// FILE that came out of the encoder is that film. It never renders the film again except where
+// a check says so, it never writes near out/, and every check beyond the container facts is
+// opt-in, because the right bar depends on the piece: a transparent sticker has no background
+// colour to assert, and a one-shot film has no seam to hide.
+//
+// node tools/verify-export.mjs <film> [--file out/x.mp4] [--adapter html-player]
+// [--width W] expected pixel width (default: the film's own; height follows the aspect)
+// [--first-frame #rrggbb] the average colour the decoded first frame must have (tol: --tol N, default 8)
+// [--loop] the last-to-first seam must read like any other step of the loop
+// [--fidelity-psnr N] decoded frame 0 must sit within N dB of the source frame (renders it once)
+//
+// Always checked: the file decodes, its pixel size, its exact frame count, and its duration
+// against the film's meta. Everything else is asked for explicitly.
+import { execFileSync, spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { defaultOutput } from "./names.mjs";
+
+const VAL = new Set(["file", "adapter", "width", "first-frame", "tol", "fidelity-psnr", "scale"]);
+const pos = [], opt = {};
+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }
+const film = pos[0] ?? "fixtures";
+const adapterName = opt.adapter ?? "html-player";
+const SCALE = +(opt.scale ?? 1);
+const TMP = resolve(".tmp/verify"); mkdirSync(TMP, { recursive: true });
+
+let fails = 0, checks = 0;
+const say = (ok, label, detail = "") => { checks++; if (!ok) fails++; console.log(` ${ok ? "PASS" : "FAIL"} ${label}${detail ? " " + detail : ""}`); };
+const note = (label, detail = "") => console.log(` ---- ${label}${detail ? " " + detail : ""}`);
+const head = (n, t) => console.log(`\n${n}. ${t}\n${"-".repeat(58)}`);
+const die = (m) => { console.error(`verify-export: ${m}`); process.exit(2); };
+
+const ffprobe = (args) => { const r = spawnSync("ffprobe", ["-v", "error", ...args], { encoding: "utf8", maxBuffer: 1 << 24 }); if (r.status !== 0) die(`ffprobe: ${r.stderr.trim()}`); return r.stdout.trim(); };
+// decode one frame to grayscale pixels at `w` px wide. H is measured from the file itself.
+const grab = (file, n, w, h) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select=eq(n\\,${n}),scale=${w}:${h}`, "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"], { maxBuffer: 1 << 26 });
+ if (r.status !== 0) die(`ffmpeg could not decode frame ${n}: ${r.stderr.toString().trim()}`);
+ if (r.stdout.length !== w * h) die(`frame ${n} decoded to ${r.stdout.length} bytes, expected ${w * h}`);
+ return r.stdout;
+};
+const changed = (a, b, threshold = 4) => { let n = 0; for (let i = 0; i < a.length; i++) if (Math.abs(a[i] - b[i]) > threshold) n++; return n / a.length; };
+
+// ---------------------------------------------------------------- the film's own numbers
+const mod = await import(`./adapters/${adapterName}.mjs`);
+const p = mod.probe();
+if (!p.ok) die(`adapter "${adapterName}": ${p.why}`);
+const s = await mod.open(film, { scale: SCALE, workers: 1 });
+const meta = await s.info();
+const N = meta.durationFrames, FW = Math.round(meta.W * SCALE), FH = Math.round(meta.H * SCALE);
+const file = resolve(opt.file ?? defaultOutput(film));
+console.log(`VERIFY-EXPORT film "${meta.title}" file ${file}`);
+if (!existsSync(file)) die(`${file} not found`);
+
+// ---------------------------------------------------------------- 1. the container
+head(1, "CONTAINER the file is the film's size, length and duration");
+const stream = ffprobe(["-select_streams", "v:0", "-show_entries", "stream=codec_name,width,height,pix_fmt", "-of", "csv=p=0", file]).split("\n")[0].split(",");
+const [codec, sw, sh] = [stream[0], Number(stream[1]), Number(stream[2])];
+const wantW = opt.width ? Number(opt.width) : FW, wantH = Math.round((wantW * FH) / FW / 2) * 2; // encoders want even heights
+say(sw === wantW && Math.abs(sh - wantH) <= 2, `pixel size ${sw}x${sh}`, `expected ${wantW}x${wantH} (${codec}${stream[3] ? ", " + stream[3] : ""})`);
+const counted = Number(ffprobe(["-select_streams", "v:0", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", file]).split("\n")[0]);
+say(counted === N, `decoded frame count is ${counted}`, `the film is ${N}`);
+const dur = Number(ffprobe(["-show_entries", "format=duration", "-of", "csv=p=0", file]));
+const wantDur = N / meta.fps, slack = 1 / meta.fps + 0.05;
+say(Math.abs(dur - wantDur) <= slack, `duration ${dur.toFixed(3)} s`, `expected ${wantDur.toFixed(3)} s +/- ${slack.toFixed(3)} (container rounding)`);
+
+// ---------------------------------------------------------------- 2. the first frame's colour
+head(2, "FIRST FRAME what the audience's first instant actually looks like");
+const avg = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "select=eq(n\\,0),scale=1:1", "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 1 << 16 });
+if (avg.status !== 0 || avg.stdout.length < 3) die(`ffmpeg could not average frame 0: ${avg.stderr.toString().trim()}`);
+const hex = `#${[...avg.stdout.subarray(0, 3)].map((v) => v.toString(16).padStart(2, "0")).join("")}`;
+if (opt["first-frame"]) {
+ const want = opt["first-frame"].replace("#", "");
+ if (!/^[0-9a-fA-F]{6}$/.test(want)) die(`--first-frame wants #rrggbb, got '${opt["first-frame"]}'`);
+ const tol = +(opt.tol ?? 8), wr = parseInt(want.slice(0, 2), 16), wg = parseInt(want.slice(2, 4), 16), wb = parseInt(want.slice(4, 6), 16);
+ const off = [Math.abs(avg.stdout[0] - wr), Math.abs(avg.stdout[1] - wg), Math.abs(avg.stdout[2] - wb)];
+ say(off.every((v) => v <= tol), `decoded first frame averages ${hex}`, `expected ${opt["first-frame"]} +/- ${tol} per channel (off by ${off.join("/")})`);
+} else note("no --first-frame given", `decoded first frame averages ${hex}; nothing asserted (a transparent or non-uniform first frame has no single right colour)`);
+
+// ---------------------------------------------------------------- 3. fidelity to the source, if asked
+if (opt["fidelity-psnr"]) {
+ head(3, "FIDELITY the decoded frame is the frame the source drew");
+ const src = resolve(TMP, "source-0.png"), dec = resolve(TMP, "decoded-0.png");
+ writeFileSync(src, (await s.frame(0, 0)).png);
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", "select=eq(n\\,0)", "-vsync", "0", "-frames:v", "1", "-y", dec], { encoding: "utf8" });
+ if (r.status !== 0) die(`ffmpeg could not lift frame 0: ${r.stderr.trim()}`);
+ const ps = spawnSync("ffmpeg", ["-v", "error", "-i", dec, "-i", src, "-lavfi", "psnr=stats_file=-", "-f", "null", "-"], { encoding: "utf8" });
+ const m = (ps.stdout + ps.stderr).match(/psnr_avg:([0-9.]+|inf)/), v = m ? (m[1] === "inf" ? Infinity : Number(m[1])) : NaN;
+ say(v >= +opt["fidelity-psnr"], `decoded frame 0 vs source frame 0: ${v === Infinity ? "inf" : v.toFixed(2)} dB`, `bar ${opt["fidelity-psnr"]} dB`);
+}
+
+// ---------------------------------------------------------------- 4. the seam, if it loops
+if (opt.loop) {
+ head(4, "LOOP SEAM the join reads like any other step of the loop");
+ if (N < 4) note("film too short to judge a seam", `${N} frames`);
+ else {
+ const W = 270, H = Math.max(2, Math.round((W * wantH) / wantW));
+ const first = grab(file, 0, W, H), last = grab(file, N - 1, W, H), seam = changed(last, first);
+ const samples = Math.min(11, N - 1), deltas = [];
+ for (let i = 0; i < samples; i++) { const f = 1 + Math.round((i * (N - 2)) / Math.max(1, samples - 1)); if (f >= N) continue; deltas.push(changed(grab(file, f - 1, W, H), grab(file, f, W, H))); }
+ deltas.sort((a, b) => a - b);
+ const med = deltas[deltas.length >> 1] ?? 0, ceiling = Math.max(2 * med, 0.005);
+ say(seam <= ceiling, `last-to-first step changes ${(seam * 100).toFixed(2)}% of the frame`, `mid-loop median ${(med * 100).toFixed(2)}%, ceiling ${(ceiling * 100).toFixed(2)}% (2x median, 0.5% floor)`);
+ }
+}
+
+await s.close();
+console.log(`\n${"=".repeat(58)}`);
+console.log(fails ? `VERIFY-EXPORT: FAIL ${fails} of ${checks} checks failed` : `VERIFY-EXPORT: PASS ${checks}/${checks} checks`);
+process.exit(fails ? 1 : 0);
diff --git a/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts b/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
index a680f8c..8aefbfe 100644
--- a/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
+++ b/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
@@ -2,34 +2,26 @@
// plane scale 1/(D + z). The hero plane is z = 0, so the hero scale S is 1/D, and S is SCREEN
// PIXELS PER SHEET UNIT: at S = 1 the creature (wingspan 780 units) is 780 px across.
//
-// NOTE, one engine item, does not block the stills: the finale world's projector
-// (butterfly/finale/world.ts) normalises every plane by (1 + z) so that all planes are 1:1 on the
-// last frame. That convention inverts parallax for D > 1, and movement 2 spends almost all of its
-// time there (D runs 0.25 to 8.7). This movement uses the spec's model instead. The two have to
-// be reconciled once, at the wide end, by choosing world positions for the last bars; that is
-// G-W work, not stills work.
-import { P } from "../../core";
+// The machinery lives in the engine now (canvas-core/camera.ts): the dolly math, the monotone
+// log2 zoom path, the stroke-weight rule. What stays here is this film's own choreography: the
+// zoom path keyed on the bars, and the units the shots were written in.
+//
+// NOTE, one engine item: the finale world's projector (butterfly/finale/world.ts) normalises
+// every plane by (1 + z) so that all planes are 1:1 on the last frame. That convention inverts
+// parallax for D > 1, and movement 2 spends almost all of its time there (D runs 0.25 to 8.7).
+// It is an authored end-frame framing, not the dolly model, and it stays with the finale.
+import { type P } from "../../core";
+import { monoPath, planeScale, projectCam, strokeWeight } from "../../camera";
import { S_KEYS } from "./cues";
export type Cam = { S: number; look: P };
export const distance = (S: number) => 1 / S;
-export const scaleAt = (c: Cam, z: number) => 1 / (distance(c.S) + z);
-export const projector = (c: Cam, z: number) => { const k = scaleAt(c, z); return { k, at: (p: P): P => [540 + (p[0] - c.look[0]) * k, 540 + (p[1] - c.look[1]) * k] }; };
+const asEngine = (c: Cam) => ({ look: c.look, zoom: c.S });
+export const scaleAt = (c: Cam, z: number) => planeScale(asEngine(c), z);
+export const projector = (c: Cam, z: number) => { const k = scaleAt(c, z); return { k, at: (p: P) => projectCam([540, 540], asEngine(c), z, p) }; };
// A close shot must not fatten the line by the zoom: w = w_authored * S^0.35 (spec 4).
-export const weight = (S: number) => Math.pow(S, 0.35);
-
-// Monotone cubic (Fritsch-Carlson) so the dolly never overshoots into a scale it was not given,
-// and never reverses: S is interpolated in log2, which is what "one stop of zoom" means.
-const mono = (xs: number[], ys: number[], x: number): number => {
- const n = xs.length;
- if (x <= xs[0]) return ys[0];
- if (x >= xs[n - 1]) return ys[n - 1];
- const d: number[] = []; for (let i = 0; i < n - 1; i++) d.push((ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]));
- const m: number[] = [d[0]]; for (let i = 1; i < n - 1; i++) m.push(d[i - 1] * d[i] <= 0 ? 0 : (d[i - 1] + d[i]) / 2); m.push(d[n - 2]);
- for (let i = 0; i < n - 1; i++) { if (d[i] === 0) { m[i] = 0; m[i + 1] = 0; continue; } const a = m[i] / d[i], b = m[i + 1] / d[i], s = a * a + b * b; if (s > 9) { const t = 3 / Math.sqrt(s); m[i] = t * a * d[i]; m[i + 1] = t * b * d[i]; } }
- let i = 0; while (x > xs[i + 1]) i++;
- const h = xs[i + 1] - xs[i], t = (x - xs[i]) / h, t2 = t * t, t3 = t2 * t;
- return ys[i] * (2 * t3 - 3 * t2 + 1) + h * m[i] * (t3 - 2 * t2 + t) + ys[i + 1] * (-2 * t3 + 3 * t2) + h * m[i + 1] * (t3 - t2);
-};
-const SX = S_KEYS.map((k) => k[0]), SY = S_KEYS.map((k) => Math.log2(k[1]));
-export const scaleOf = (local: number): number => Math.pow(2, mono(SX, SY, local));
+export const weight = (S: number) => strokeWeight({ look: [0, 0], zoom: S });
+// The zoom path, keyed on the bars and read in stops: S is interpolated in log2, which is what
+// "one stop of zoom" means, and the cubic is monotone so the dolly never overshoots into a scale
+// it was not given, and never reverses.
+export const scaleOf = monoPath(S_KEYS, { log2: true });
diff --git a/skills/anidoodle/references/camera.md b/skills/anidoodle/references/camera.md
new file mode 100644
index 0000000..8b3137c
--- /dev/null
+++ b/skills/anidoodle/references/camera.md
@@ -0,0 +1,84 @@
+# The camera: one dolly, keyed on the frame grid
+
+`engine/src/canvas-core/camera.ts` is the camera. A film either draws in world coordinates
+inside `begin()`/`end()` (the transform path: dirty boxes stay right because the camera rides
+the `Gfx` transform stack), or asks `toScreen()` where a world point lands and draws there (the
+projector path). Both come from the same state, so a caption pinned to the frame and the world
+it floats over can never disagree. Everything is a pure function of the frame: the same camera
+question gets the same answer on any machine, in any order.
+
+## The move
+
+```ts
+import { Camera } from "./camera";
+
+const cam = new Camera([W / 2, H / 2], [
+ { f: 0, look: [400, 300], zoom: 1, ease: "inout" }, // ease governs the segment this key LEAVES
+ { f: 90, look: [900, 300], zoom: 2 },
+ { f: 150, look: [900, 300], zoom: 2 }, // a hold: say it, don't imply it
+ { f: 240, look: [400, 300], zoom: 1 },
+]);
+cam.shake({ from: 96, to: 126, amp: 14, seed: 7, rot: 0.004 }); // an impact, ringing down
+```
+
+- **Zoom is interpolated in log2.** A zoom is a ratio: halving the apparent size twice should
+ take twice as long as halving it once. Ease the zoom value itself and a long push-in sprints
+ at the near end and crawls at the far one; easing log2(zoom) spends time evenly per stop.
+- **Easing per segment, `inout` (easeInOutCubic) by default.** A camera move with no live
+ operator should accelerate gently and arrive gently. `linear` reads as mechanical, `out`
+ alone reads as interrupted, `in` alone as a fall.
+- **A zoom path with several keys** breathes at every key under per-segment easing. Pass
+ `monoZoom: true` to run one monotone cubic through all the zoom keys in log2 instead: smooth,
+ never overshooting into a scale it was not given, never reversing.
+- **Authored paths**: for a camera that follows a creature or a curve, pass
+ `path: (f) => ({ look, zoom })` instead of keys. Same camera, same shake, same projections.
+
+## Depth planes (parallax)
+
+The camera sits at distance D = 1/zoom from the hero plane (z = 0). A plane at depth z scales
+by `1/(D + z)` and moves with it: near planes swing wide, far ones barely stir, and every
+element at a depth agrees with every other, because there is only one camera. Positive z
+recedes; a negative z crosses the lens (grass across the glass). Pass the plane's z to
+`begin(g, f, z)` or `toScreen(p, f, z)`. One dolly, one number, and the parallax is true for
+every element at once: do not hand-each-plane its own drift.
+
+## Shake
+
+`shake({ from, to, amp, seed, freq, rot, attack })` registers an impact or a handheld stretch:
+
+- **amp in SCREEN pixels**, so the shake reads the same at any zoom; **rot** in radians at full
+ strength, about the frame's centre. A small rotation is what actually sells handheld.
+- The envelope is an **attack ramp** (default 2 frames) into a **squared decay**: full strength
+ at the hit, gone a beat later. An impact rings down; it does not stop mid-air.
+- The motion is **low-frequency gradient noise**, seeded, never white noise per frame. Static
+ per frame reads as a faulty projector; smooth noise reads as mass. `freq` is cycles per frame
+ (default 0.35, about 10 Hz at 30 fps; drop it for a heavier camera).
+- Shake is folded into `shaken(f)`, which `begin` and `toScreen` read, so the drawn world and
+ any projected overlay shake together. `at(f)` stays clean for driving things that must not
+ shake (the score, a cue grid).
+
+## Line weight at close range
+
+Ink is authored at some view; at zoom S the same nib reads S times heavier. Divide stroke widths
+by `weight(cam)` = S^0.35. Not S: a little weight gain is what makes a close-up feel close
+rather than enlarged.
+
+## The two drawing paths
+
+```ts
+// transform path: the world moves, you draw in world units
+cam.begin(g, f); // hero plane
+meadow(g, f);
+cam.end(g);
+cam.begin(g, f, 2.2); // a farther plane
+hills(g, f);
+cam.end(g);
+
+// projector path: ask where things are, draw them there (cached surfaces, screen-space type)
+const at = cam.toScreen(flower.centre, f, flower.z);
+const k = cam.scaleAt(cam.at(f), flower.z);
+```
+
+`toWorld(s, f, z)` inverts `toScreen`, for hit-testing or for pinning world content to a screen
+point. The camera never touches the context itself, the clock, or `Math.random`: it is
+arithmetic over `(frame, keys, seed)`, which is what keeps the determinism contract intact.
diff --git a/skills/anidoodle/references/formats.md b/skills/anidoodle/references/formats.md
index c56fe15..d41ddf5 100644
--- a/skills/anidoodle/references/formats.md
+++ b/skills/anidoodle/references/formats.md
@@ -35,7 +35,9 @@ the craft table, then show it.
- **Seamless loop**: drive everything from `t = local / DURATION` through functions that repeat
a whole number of times over `[0, 1)` (`sin(2 * PI * k * t)`, integer `k`). Frame `DURATION`
then equals frame 0 and the seam disappears. Check it: render the last frame and frame 0 and
- compare them to a mid-loop neighbour pair.
+ compare them to a mid-loop neighbour pair, or run `node tools/verify-export.mjs <name> --loop`
+ on the rendered file, which judges the last-to-first step against the loop's own mid-loop
+ deltas.
- **Animated logo / sticker**: 2 to 4 seconds, the mark DRAWN on (`progress` on `g.pen`,
`letter`), a settle, a small idle. Leave the background unpainted for transparency.
- **Ambient / idle art** (a site header that breathes, a banner): the subject never stops; the
@@ -58,6 +60,11 @@ the craft table, then show it.
| APNG | `node tools/render.mjs <name> --out out/x.apng [--width 512]` | alpha loops that play in every browser |
| HTML | `node tools/emit.mjs <name> --out out/x.html` | the piece itself: one offline file that redraws it, with sound, on a double-click |
+After any encode, `node tools/verify-export.mjs <name> [--first-frame #hex] [--fidelity-psnr 40]`
+proves the file on disk is the film: size, exact frame count, duration, and optionally the first
+frame's average colour and its fidelity to the source frame. All of it is opt-in beyond the
+container facts, so transparent and non-uniform pieces pass cleanly.
+
A still needs a browser only (`npx playwright-core install chromium`). Anything that moves also needs
`ffmpeg`. `gate.mjs` runs on all of them and marks the checks that do not apply to the piece,
a silent loop's audio or a still's dead air, as `----` rather than passing them.
diff --git a/skills/anidoodle/references/workflows/launch-video.md b/skills/anidoodle/references/workflows/launch-video.md
index 7bd8dcd..10b8335 100644
--- a/skills/anidoodle/references/workflows/launch-video.md
+++ b/skills/anidoodle/references/workflows/launch-video.md
@@ -10,6 +10,30 @@ Product screenshots, a logo, UI captures, a repo link, a feature list. Images th
embedded (pinned by sha256, provenance recorded in the film's manifest); everything around them
is drawn in code. Never generate or fetch images.
+## Ground it in the real product first
+
+Before any storyboarding, write a short sourced brief and get ONE approval on it. A launch film
+that invents its subject draws a mascot of a product, not the product. Keep it light: one brief,
+one look approval, then build.
+
+1. **Read the real thing.** Open what exists: the screenshots and captures they brought, the
+ repo's README and UI components, the live page. Note the two or three REAL features a viewer
+ should recognise on screen, the exact product name and mark, and the brand colours as hex.
+2. **Collect approved claims.** The one-line promise and any numbers come from the person's own
+ materials (site copy, release notes, the README), each with its source written next to it.
+ Anything you cannot source becomes a question, not a line in the film. Write the claims the
+ film must NOT make while you are at it.
+3. **Ask the grounding questions**, one message: which real features to show (pick from the
+ list you found, recommend your three), which shapes to ship (`9x16`, `16x9`, `1x1`), text
+ treatment (drawn kinetic type, their UI captures, or both), and where it will run.
+4. **Write the brief** where the film's files will live: product and promise, the chosen
+ features with their sources, brand colours mapped onto the style's palette roles, the
+ approved claims and the banned ones, the shapes. The storyboard and every caption then quote
+ the brief, never memory.
+
+The film still opens with a drawn hook, not a feature list: the brief decides WHAT the film may
+claim and show, never how it moves.
+
## Shape of the film
1. **Hook in the first two seconds**: the problem, drawn being made (a tangle, a pile, a clock),