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.

feat(tools): still.mjs --frames a,b,c (+ranges, --sheet contact sheet) in one browser session; disk bake cache for finished plates keyed by source-closure hash (wall still 70 s -> 0.6 s, same md5)

Alex Greenshpun0f73856e4725
diff --git a/.gitignore b/.gitignore
index 3a68cf4..2ada8c5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@ skills/anidoodle/engine/node_modules/
skills/anidoodle/engine/out/
skills/anidoodle/engine/dist/
skills/anidoodle/engine/.tmp/
+skills/anidoodle/engine/.cache/
**/*.log
.DS_Store
diff --git a/skills/anidoodle/engine/src/canvas-core/core.ts b/skills/anidoodle/engine/src/canvas-core/core.ts
index 805e2b7..bc0e712 100644
--- a/skills/anidoodle/engine/src/canvas-core/core.ts
+++ b/skills/anidoodle/engine/src/canvas-core/core.ts
@@ -13,6 +13,11 @@ export type Env = {
canvas(w: number, h: number): Layer; // the ONLY way the core obtains an offscreen surface
image?(name: string): CanvasImageSource | undefined; // assets are decoded by the ADAPTER before frame 0
cache: Map<string, unknown>;
+ // OPTIONAL, host-provided: a store of finished plate frames that outlives the page (the adapters
+ // keep it on disk, keyed by a hash of the plate's source, so it can never hand back stale art).
+ // get() returns the exact pixels renderFrame would draw for (film, frame) at w x h, or nothing;
+ // put() offers a freshly drawn one. A core that never calls it draws exactly the same frames.
+ bake?: { get(film: object, frame: number, w: number, h: number): CanvasImageSource | undefined; put(film: object, frame: number, layer: Layer): void };
};
// ---------------------------------------------------------------- deterministic randomness
diff --git a/skills/anidoodle/engine/src/canvas-core/launchGallery.ts b/skills/anidoodle/engine/src/canvas-core/launchGallery.ts
index 921cb99..465bc51 100644
--- a/skills/anidoodle/engine/src/canvas-core/launchGallery.ts
+++ b/skills/anidoodle/engine/src/canvas-core/launchGallery.ts
@@ -67,7 +67,7 @@ const rowSpan = PER_ROW * PITCH;
// the punch-ins: which card, when. A card is found by (row, k) at the moment the punch starts.
export type Punch = { row: number; k: number; t0: number };
const final = (film: Film) => Math.max(0, film.meta.durationFrames - 1);
-const thumb = (env: Env, c: Card, px: number) => plateLayer(env, `wall:${c.id}`, c.film, final(c.film), px);
+const thumb = (env: Env, c: Card, px: number) => plateLayer(env, `wall:${c.id}`, c.film, final(c.film), px, true); // a finished plate: persistable
// camera over the wall: centre (wall coords), zoom, and the wall's own rotation (it untilts as the camera arrives on a card)
export type WallCam = { c: P; z: number; rot: number };
diff --git a/skills/anidoodle/engine/src/canvas-core/launchKit.ts b/skills/anidoodle/engine/src/canvas-core/launchKit.ts
index 08efe06..da01741 100644
--- a/skills/anidoodle/engine/src/canvas-core/launchKit.ts
+++ b/skills/anidoodle/engine/src/canvas-core/launchKit.ts
@@ -52,7 +52,10 @@ export const toScreen = (cam: Cam, p: P, W = 1920, H = 1080): P => [W / 2 + (p[0
// ---------------------------------------------------------------- plates, live
// Draw frame `frame` of `film` into a surface sized for `px` device pixels across. Sub-films get
// their own cache (their bake keys must never meet the launch film's) and the surface is reused.
-export const plateLayer = (env: Env, key: string, film: Film, frame: number, px = 1080): Layer => {
+// `persist`: a frame that is drawn the same way in every session (a finished plate on the wall)
+// may be served from the host's disk store (env.bake) instead of being drawn again: the 31-card
+// wall costs a minute to draw cold. Same pixels either way; without a store it simply draws.
+export const plateLayer = (env: Env, key: string, film: Film, frame: number, px = 1080, persist = false): Layer => {
const res = px / film.meta.W, scale = res, lk = `plate:${key}:${px}`;
let rec = env.cache.get(lk) as { L: Layer; sub: Env; last: number } | undefined;
if (!rec) {
@@ -61,7 +64,12 @@ export const plateLayer = (env: Env, key: string, film: Film, frame: number, px
env.cache.set(lk, rec);
}
const f = Math.max(0, Math.min(film.meta.durationFrames - 1, Math.round(frame)));
- if (rec.last !== f) { renderFrame(film, rec.L.ctx, f, rec.sub); rec.last = f; }
+ if (rec.last !== f) {
+ const L = rec.L, hit = persist ? env.bake?.get(film, f, L.canvas.width, L.canvas.height) : undefined;
+ if (hit) { const c = L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "copy"; c.drawImage(hit, 0, 0); c.globalCompositeOperation = "source-over"; }
+ else { renderFrame(film, L.ctx, f, rec.sub); if (persist) env.bake?.put(film, f, L); }
+ rec.last = f;
+ }
return rec.L;
};
// a surface the launch film draws into itself (a scene inside a scene), same reuse rule
diff --git a/skills/anidoodle/engine/tools/adapters/html-player.mjs b/skills/anidoodle/engine/tools/adapters/html-player.mjs
index 6aefff7..1405f98 100644
--- a/skills/anidoodle/engine/tools/adapters/html-player.mjs
+++ b/skills/anidoodle/engine/tools/adapters/html-player.mjs
@@ -12,6 +12,7 @@ import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { buildPage } from "../build-page.mjs";
import { detect } from "../detect.mjs";
+import { loadBakes, saveBakes } from "../bake-cache.mjs";
export const name = "html-player";
export const describe = () => "a single self-contained HTML file that plays the film in any browser, offline";
@@ -40,7 +41,7 @@ export const pageChecks = (html) => {
};
export const open = async (film, opts = {}) => {
- const { scale = 1, workers = 1 } = opts;
+ const { scale = 1, workers = 1 } = opts, useBakes = opts.bakeCache === true && process.env.ANIDOODLE_BAKE_CACHE !== "0"; // OFF by default: the gate proves the source, not a cache
const p = probe();
if (!p.ok) throw new Error(`html-player: ${p.why}`);
const out = resolve(`dist/${film}.html`);
@@ -49,13 +50,15 @@ export const open = async (film, opts = {}) => {
const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling"] });
const context = await browser.newContext({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 1 });
- const pages = [];
+ const pages = [], bv = browser.version();
for (let i = 0; i < workers; i++) {
const page = await context.newPage(), errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("request", (r) => { if (!r.url().startsWith("file:") && !r.url().startsWith("data:")) errors.push(`page reached the network: ${r.url()}`); }); /* the page is supposed to be offline: prove it at run time, not just by reading it */
await page.goto(pathToFileURL(out).href + "?adapter=html-player");
- await page.evaluate(async (s) => { await window.FILM.ready; window.FILM.mount(s); window.FILM.warm(); }, scale);
+ await page.evaluate(async (s) => { await window.FILM.ready; window.FILM.mount(s); }, scale);
+ if (useBakes) await loadBakes(page, bv);
+ await page.evaluate(() => window.FILM.warm());
if (errors.length) throw new Error("page failed: " + errors.join("; "));
pages.push(page);
}
@@ -67,6 +70,6 @@ export const open = async (film, opts = {}) => {
hash: (n, w = 0) => pick(w).evaluate((f) => { window.FILM.seek(f); return window.FILM.hash(); }, n),
audio: (sr) => pages[0].evaluate((s) => window.FILM.audio(s), sr),
artifact: () => ({ path: out, kind: "self-contained HTML player", bytes: statSync(out).size, meta: built.meta, checks: pageChecks(html) }),
- close: () => browser.close(),
+ close: async () => { if (useBakes) for (const p of pages) await saveBakes(p, bv).catch(() => 0); await browser.close(); },
};
};
diff --git a/skills/anidoodle/engine/tools/bake-cache.mjs b/skills/anidoodle/engine/tools/bake-cache.mjs
new file mode 100644
index 0000000..c1fe9da
--- /dev/null
+++ b/skills/anidoodle/engine/tools/bake-cache.mjs
@@ -0,0 +1,32 @@
+// BAKE CACHE, the disk half of Env.bake (the page half is hosts/page.ts). Finished plate frames
+// live in .cache/bakes/<browser version>/<source hash>.<frame>.<w>x<h>.png. The source hash is
+// computed by build-page.mjs over the plate's whole import closure, so an edited plate simply
+// misses and is drawn again; a different browser build (which may rasterise differently) gets a
+// different folder. Nothing here is ever needed: delete .cache/ and every frame is drawn cold.
+// Off with ANIDOODLE_BAKE_CACHE=0 (or an adapter's { bakeCache: false }).
+import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+export const bakeCacheOn = (opt) => opt !== false && process.env.ANIDOODLE_BAKE_CACHE !== "0";
+const dirFor = (browserVersion) => resolve(".cache/bakes", String(browserVersion || "unknown").replace(/[^\w.-]/g, "_"));
+
+// before frame 0: hand the page every stored frame whose source hash it still has
+export const loadBakes = async (page, browserVersion) => {
+ const dir = dirFor(browserVersion), hashes = new Set(await page.evaluate(() => window.FILM.bakes.hashes())), entries = {};
+ if (existsSync(dir)) for (const f of readdirSync(dir)) { const m = f.match(/^([0-9a-f]+)\.(\d+)\.(\d+x\d+)\.png$/); if (m && hashes.has(m[1])) entries[f.slice(0, -4)] = readFileSync(join(dir, f)).toString("base64"); }
+ await page.evaluate((e) => window.FILM.bakes.load(e), entries);
+ return Object.keys(entries).length;
+};
+
+// after the last frame: keep what the page drew fresh
+export const saveBakes = async (page, browserVersion) => {
+ const fresh = await page.evaluate(() => window.FILM.bakes.take()), dir = dirFor(browserVersion);
+ const keys = Object.keys(fresh); if (!keys.length) return 0;
+ mkdirSync(dir, { recursive: true });
+ for (const k of keys) { const f = join(dir, `${k}.png`), t = `${f}.${process.pid}.tmp`; writeFileSync(t, Buffer.from(fresh[k], "base64")); renameSync(t, f); } // atomic: a crash never leaves half a PNG
+ // bounded: edits leave old hashes behind, so keep the newest KEEP files and let the rest go
+ const all = readdirSync(dir).filter((f) => f.endsWith(".png"));
+ if (all.length > KEEP) all.map((f) => [f, statSync(join(dir, f)).mtimeMs]).sort((a, b) => b[1] - a[1]).slice(KEEP).forEach(([f]) => { try { unlinkSync(join(dir, f)); } catch { /* another process got there */ } });
+ return keys.length;
+};
+const KEEP = 600;
diff --git a/skills/anidoodle/engine/tools/build-page.mjs b/skills/anidoodle/engine/tools/build-page.mjs
index 3ab0876..5662c01 100644
--- a/skills/anidoodle/engine/tools/build-page.mjs
+++ b/skills/anidoodle/engine/tools/build-page.mjs
@@ -2,21 +2,59 @@
// manifest inlined as a data URI. No network, no server, no sibling files.
import { build } from "esbuild";
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
-import { extname, join } from "node:path";
+import { createHash } from "node:crypto";
+import { extname, join, relative, resolve } from "node:path";
import { overlay, resolveOverlay } from "./overlay.mjs";
+// BAKE KEYS (see Env.bake and hosts/page.ts). Every module that exports `const X: Film` is tagged
+// in the bundle with its own path, and each tagged module gets a hash of its WHOLE import closure
+// (file contents, not timestamps) plus the renderer and this format's version. Change one line
+// anywhere a plate's pixels come from and its key changes, so a stale bake can never be served.
+const BAKE_FORMAT = "bake-1";
+const FILM_EXPORT = /export\s+const\s+([A-Za-z_$][\w$]*)\s*:\s*Film\b/g;
+const tagFilms = {
+ name: "anidoodle-film-tags",
+ setup(b) {
+ b.onLoad({ filter: /[\\/]canvas-core[\\/].*\.ts$/ }, (a) => {
+ const src = readFileSync(a.path, "utf8"), names = [...src.matchAll(FILM_EXPORT)].map((m) => m[1]);
+ if (!names.length) return undefined;
+ const rel = relative(process.cwd(), a.path).split("\\").join("/");
+ return { contents: `${src}\n;{ const t = ((globalThis as any).__ANIDOODLE_SRC__ ??= new WeakMap()); ${names.map((n) => `t.set(${n}, ${JSON.stringify(rel)});`).join(" ")} }\n`, loader: "ts" };
+ });
+ },
+};
+const bakeHashes = (metafile, salt) => {
+ const inputs = metafile.inputs, fileHash = new Map(), memo = new Map();
+ const h = (p) => { if (!fileHash.has(p)) fileHash.set(p, createHash("sha256").update(readFileSync(resolve(p))).digest("hex")); return fileHash.get(p); };
+ const closure = (p, seen = new Set()) => { if (seen.has(p) || !inputs[p]) return seen; seen.add(p); for (const i of inputs[p].imports ?? []) closure(i.path, seen); return seen; };
+ const out = {};
+ for (const p of Object.keys(inputs)) {
+ if (!/canvas-core\/.*\.ts$/.test(p)) continue;
+ const src = readFileSync(resolve(p), "utf8"); if (!src.match(FILM_EXPORT)) continue;
+ const all = [...closure(p)].sort(), d = createHash("sha256").update(salt);
+ for (const q of all) d.update(`${q}\0${h(q)}\0`);
+ if (!memo.has(p)) memo.set(p, d.digest("hex").slice(0, 24));
+ out[p.split("\\").join("/")] = memo.get(p);
+ }
+ return out;
+};
+
const MIME = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".woff2": "font/woff2" };
export const buildPage = async ({ entry, out, title, plugins: extra = [] }) => {
const plugins = [...extra, overlay]; // extra first: a caller's shim (snap --only) outranks the overlay
if (!existsSync(entry)) entry = resolveOverlay("./" + entry, process.cwd()) ?? entry; // e.g. the example's own host page
- const js = (await build({ entryPoints: [entry], bundle: true, format: "iife", target: "es2020", minify: true, write: false, legalComments: "none", plugins })).outputFiles[0].text;
+ const main = await build({ entryPoints: [entry], bundle: true, format: "iife", target: "es2020", minify: true, write: false, legalComments: "none", metafile: true, plugins: [...plugins, tagFilms] });
+ const js = main.outputFiles[0].text;
// read the manifest out of the film module itself, so the page and the film can never disagree
const probe = (await build({ stdin: { contents: `export { ${title} as film } from "./src/canvas-core/${title}";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral", plugins })).outputFiles[0].text;
const { film } = await import("data:text/javascript;base64," + Buffer.from(probe).toString("base64"));
const assets = Object.fromEntries(Object.entries(film.assets.images).map(([name, file]) => { const mime = MIME[extname(file).toLowerCase()]; if (!mime) throw new Error(`asset '${name}': unsupported type ${file}`); return [name, `data:${mime};base64,${readFileSync(join(process.cwd(), file)).toString("base64")}`]; }));
+ // the renderer that draws every plate frame, and the assets any plate may read, salt every key
+ const salt = [BAKE_FORMAT, ...["src/canvas-core/film.ts", "src/canvas-core/core.ts"].map((f) => readFileSync(resolve(f), "utf8")), JSON.stringify(assets)].join("\0");
+ const bakeSrc = bakeHashes(main.metafile, salt);
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${film.meta.title}</title>
<style>html,body{margin:0;height:100%;background:#1b1a1a;display:grid;place-items:center}canvas{max-width:100vw;max-height:100vh;aspect-ratio:${film.meta.W}/${film.meta.H};cursor:pointer;background:#fff}</style></head>
-<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;
+<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};window.__BAKE_SRC__=${JSON.stringify(bakeSrc)};</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;
mkdirSync(join(out, ".."), { recursive: true }); writeFileSync(out, html);
return { out, bytes: html.length, meta: film.meta };
};
diff --git a/skills/anidoodle/engine/tools/still.mjs b/skills/anidoodle/engine/tools/still.mjs
index 53affe1..89df523 100644
--- a/skills/anidoodle/engine/tools/still.mjs
+++ b/skills/anidoodle/engine/tools/still.mjs
@@ -1,40 +1,91 @@
-// STILL. One frame of one film, at full resolution, to a path a human can open.
+// STILL. Frames of one film, at full resolution, to paths a human can open.
// node tools/still.mjs <film> [--shot <id>] [--frame N] [--out out/x.png] [--scale 1]
-// The look still is rendered many times before a single frame of motion is, so
-// this does exactly that and nothing else: build the page, draw the frame, write the PNG, print
-// the draw cost and the frame's hash so a re-render can be proved identical.
+// node tools/still.mjs <film> --frames 0,700,1500 [--out out/dir/ | --out out/x-{frame}.png] [--sheet out/sheet.jpg]
+// The look still is rendered many times before a single frame of motion is, so this does exactly
+// that and nothing else: build the page, draw the frames, write the PNGs, print the draw cost and
+// each frame's hash so a re-render can be proved identical. Every frame is drawn twice, because a
+// still that is not reproducible is not a gate.
+// --frames a,b,c many frames in ONE browser session (one build, one launch, one warm-up, and
+// plates baked once): the cheap way to review a cut. Ranges work: 0-300:50.
+// --sheet file also lay the frames out as one contact sheet at --sheet-scale (default 0.4)
+// --no-bake-cache draw every finished plate cold instead of reading .cache/bakes
+// With no --frame/--frames, one still per shot, at the shot's first frame.
import { createHash } from "node:crypto";
-import { mkdirSync, writeFileSync } from "node:fs";
-import { dirname, resolve } from "node:path";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
import { buildPage } from "./build-page.mjs";
import { detect } from "./detect.mjs";
import * as playwright from "./adapters/playwright.mjs";
-import { overlay } from "./overlay.mjs";
-const VAL = new Set(["shot", "out", "scale", "frame"]);
+const VAL = new Set(["shot", "out", "scale", "frame", "frames", "sheet", "sheet-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 die = (m) => { console.error(`still: ${m}`); process.exit(1); };
-const film = pos[0] ?? die("usage: node tools/still.mjs <film> [--shot <id>] [--frame N] [--out out/x.png] [--scale 1]");
+const film = pos[0] ?? die("usage: node tools/still.mjs <film> [--shot <id>] [--frame N | --frames a,b,c] [--out out/x.png] [--scale 1] [--sheet out/sheet.jpg]");
const scale = Number(opt.scale ?? 1);
+if (!(scale > 0)) die(`--scale wants a number > 0, got '${opt.scale}'`);
+if (opt.frame !== undefined && opt.frames !== undefined) die("give --frame N or --frames a,b,c, not both");
+
+// "0,700,1500" or "0-300:50" (from-to inclusive, every 50) or a mix
+const parseFrames = (s) => String(s).split(",").map((t) => t.trim()).filter(Boolean).flatMap((t) => {
+ const m = t.match(/^(\d+)-(\d+)(?::(\d+))?$/);
+ if (m) { const [a, b, st] = [Number(m[1]), Number(m[2]), Number(m[3] ?? 1)]; if (b < a || st < 1) die(`bad range '${t}'`); return Array.from({ length: Math.floor((b - a) / st) + 1 }, (_, i) => a + i * st); }
+ if (!/^\d+$/.test(t)) die(`--frames wants frame numbers like 0,700,1500 or 0-300:50, got '${t}'`);
+ return [Number(t)];
+});
const env = detect();
// A still needs a browser and nothing else: ffmpeg only matters once there is motion to encode.
if (!env.pw.ok || !env.browser.ok) die(`no browser to draw in.\n playwright: ${env.report.playwright}\n browser: ${env.report.browser}\n fix: npm install, then npx playwright-core install chromium`);
const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });
-const session = await playwright.open(env, page.out, { scale, workers: 1 });
-const meta = await session.info();
-const probe = (await import("data:text/javascript;base64," + Buffer.from((await (await import("esbuild")).build({ stdin: { contents: `export { ${film} as film } from "./src/canvas-core/${film}";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral", plugins: [overlay] })).outputFiles[0].text).toString("base64"))).film;
-const shots = opt.shot ? [probe.shots.find((s) => s.id === opt.shot) ?? die(`no shot '${opt.shot}' (has: ${probe.shots.map((s) => s.id).join(", ")})`)] : probe.shots;
+const session = await playwright.open(env, page.out, { scale, workers: 1, bakeCache: opt["no-bake-cache"] ? false : undefined });
+const meta = await session.info(), N = meta.durationFrames;
+const shotOf = (n) => meta.shots.find((s) => n >= s.start && n < s.end) ?? meta.shots[meta.shots.length - 1];
+
+// the jobs: [frame, output path]
+let jobs;
+if (opt.frames !== undefined || opt.frame !== undefined) {
+ const list = [...new Set(opt.frames !== undefined ? parseFrames(opt.frames) : parseFrames(opt.frame))];
+ for (const n of list) if (n >= N) die(`frame ${n} is past the film's last frame ${N - 1}`);
+ const outFor = (n) => {
+ if (!opt.out) return list.length === 1 && opt.frame !== undefined ? `out/still-${film}-${shotOf(n).id}.png` : `out/still-${film}-${n}.png`;
+ if (String(opt.out).includes("{frame}")) return String(opt.out).replaceAll("{frame}", String(n));
+ if (String(opt.out).endsWith("/")) return join(opt.out, `${film}-${n}.png`);
+ if (list.length === 1) return opt.out;
+ die(`--out for ${list.length} frames must be a folder ending in / or contain {frame}`);
+ };
+ jobs = list.map((n) => [n, resolve(outFor(n)), shotOf(n).id]);
+} else {
+ const shots = opt.shot ? [meta.shots.find((s) => s.id === opt.shot) ?? die(`no shot '${opt.shot}' (has: ${meta.shots.map((s) => s.id).join(", ")})`)] : meta.shots;
+ jobs = shots.map((s) => [s.start, resolve(shots.length === 1 && opt.out ? opt.out : `out/still-${film}-${s.id}.png`), s.id]);
+}
-console.log(`film: "${meta.title}" ${meta.W}x${meta.H}, scale ${scale}`);
-for (const s of shots) {
- const n = opt.frame !== undefined ? Number(opt.frame) : s.start;
- const out = resolve(shots.length === 1 && opt.out ? opt.out : `out/still-${film}-${s.id}.png`);
+const b = session.bakes();
+console.log(`film: "${meta.title}" ${meta.W}x${meta.H}, scale ${scale}, ${jobs.length} still${jobs.length === 1 ? "" : "s"}${b.on ? `, bake cache: ${b.loaded} plate frame(s) loaded` : ", bake cache off"}`);
+const h = (p) => createHash("md5").update(p).digest("hex"), t0 = Date.now(), written = [];
+for (const [n, out, id] of jobs) {
const a = await session.frame(n, 0);
- const b = await session.frame(n, 0); // drawn twice: a still that is not reproducible is not a gate
- mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, a.png);
- const h = (p) => createHash("md5").update(p).digest("hex");
- console.log(` ${s.id.padEnd(12)} frame ${String(n).padEnd(5)} draw ${a.drawMs.toFixed(0)} ms md5 ${h(a.png)} ${h(a.png) === h(b.png) ? "reproducible" : "NOT REPRODUCIBLE"} -> ${out} (${(a.png.length / 1024).toFixed(0)} KB)`);
+ const c = await session.frame(n, 0); // drawn twice: a still that is not reproducible is not a gate
+ mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, a.png); written.push(out);
+ console.log(` ${id.padEnd(12)} frame ${String(n).padEnd(5)} draw ${a.drawMs.toFixed(0).padStart(5)} ms md5 ${h(a.png)} ${h(a.png) === h(c.png) ? "reproducible" : "NOT REPRODUCIBLE"} -> ${out} (${(a.png.length / 1024).toFixed(0)} KB)`);
+}
+const saved = await session.close();
+console.log(` ${jobs.length} frame(s) in ${((Date.now() - t0) / 1000).toFixed(1)} s${saved ? `; ${saved} finished plate frame(s) stored in .cache/bakes for next time` : ""}`);
+
+if (opt.sheet) {
+ const k = Number(opt["sheet-scale"] ?? 0.4), cols = Math.ceil(Math.sqrt(written.length)), rows = Math.ceil(written.length / cols), tmp = resolve(".tmp/sheet");
+ rmSync(tmp, { recursive: true, force: true }); mkdirSync(tmp, { recursive: true });
+ const args = ["-v", "error", "-y"]; written.forEach((f) => args.push("-i", f));
+ const w = Math.max(2, Math.round((meta.W * scale * k) / 2) * 2), hh = Math.max(2, Math.round((meta.H * scale * k) / 2) * 2);
+ const pads = Array.from({ length: cols * rows - written.length }, (_, i) => `color=c=white:s=${w}x${hh}:d=1[p${i}]`);
+ const labels = written.map((_, i) => `[${i}:v]scale=${w}:${hh}:flags=area,setsar=1[v${i}]`);
+ const padIds = pads.map((p) => p.match(/\[(p\w+)\]$/)[1]);
+ const all = [...written.map((_, i) => `[v${i}]`), ...padIds.map((p) => `[${p}]`)];
+ const layout = all.map((_, i) => `${(i % cols) * w}_${Math.floor(i / cols) * hh}`).join("|");
+ const graph = [...labels, ...pads, `${all.join("")}xstack=inputs=${all.length}:layout=${layout}:fill=white`].join(";");
+ const out = resolve(opt.sheet); mkdirSync(dirname(out), { recursive: true });
+ const r = spawnSync("ffmpeg", [...args, "-filter_complex", all.length === 1 ? `[0:v]scale=${w}:${hh}` : graph, "-frames:v", "1", "-q:v", "3", out], { encoding: "utf8" });
+ if (r.status !== 0) die(`contact sheet failed: ${r.stderr.trim()}`);
+ console.log(` contact sheet ${cols}x${rows} at ${k}x -> ${out}`);
}
-await session.close();