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.

chore: resync Codex mirror

Alex Greenshpun7dd43f726e60
diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/refs/PROVENANCE.json b/plugins/anidoodle/skills/anidoodle/engine/assets/refs/PROVENANCE.json
new file mode 100644
index 0000000..90f5a4d
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/refs/PROVENANCE.json
@@ -0,0 +1,12 @@
+{
+ "vangogh-almond-blossom.jpg": {
+ "work": "Vincent van Gogh, Almond Blossom (1890), Van Gogh Museum, Amsterdam",
+ "title": "File:Vincent van Gogh - Almond blossom - Google Art Project.jpg",
+ "page": "https://commons.wikimedia.org/wiki/File:Vincent_van_Gogh_-_Almond_blossom_-_Google_Art_Project.jpg",
+ "license": "Public domain (author died 1890; faithful reproduction of a 2D public-domain work)",
+ "sha256": "6f640dcd79def4223bf16569fd29ca5e37ee9d6cde2670958636e259e2a1c9d0",
+ "bytes": 1046465,
+ "usedBy": "the launch films (launch.ts, launch2.ts, launch3.ts) and typeOptions.ts show it only as the picture the user attaches in the chat; adaptAlmond.ts borrows its hand, never its pixels",
+ "note": "the one image in the repo that is not drawn by code; kept byte-identical to the download so renders stay reproducible"
+ }
+}
diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/refs/vangogh-almond-blossom.jpg b/plugins/anidoodle/skills/anidoodle/engine/assets/refs/vangogh-almond-blossom.jpg
new file mode 100644
index 0000000..bfb1848
Binary files /dev/null and b/plugins/anidoodle/skills/anidoodle/engine/assets/refs/vangogh-almond-blossom.jpg differ
diff --git a/plugins/anidoodle/skills/anidoodle/engine/package-lock.json b/plugins/anidoodle/skills/anidoodle/engine/package-lock.json
index f7bea03..1ef53d7 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/package-lock.json
+++ b/plugins/anidoodle/skills/anidoodle/engine/package-lock.json
@@ -1713,6 +1713,29 @@
"win32"
]
},
+ "node_modules/@rspack/core": {
+ "version": "1.7.11",
+ "resolved": "https://registry.npmjs.org/@rspack/core/-/core-1.7.11.tgz",
+ "integrity": "sha512-rsD9b+Khmot5DwCMiB3cqTQo53ioPG3M/A7BySu8+0+RS7GCxKm+Z+mtsjtG/vsu4Tn2tcqCdZtA3pgLoJB+ew==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@module-federation/runtime-tools": "0.22.0",
+ "@rspack/binding": "1.7.11",
+ "@rspack/lite-tapable": "1.1.0"
+ },
+ "engines": {
+ "node": ">=18.12.0"
+ },
+ "peerDependencies": {
+ "@swc/helpers": ">=0.5.1"
+ },
+ "peerDependenciesMeta": {
+ "@swc/helpers": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@rspack/lite-tapable": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@rspack/lite-tapable/-/lite-tapable-1.1.0.tgz",
@@ -2017,6 +2040,19 @@
"license": "Apache-2.0",
"optional": true
},
+ "node_modules/acorn": {
+ "version": "8.18.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
+ "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
+ "license": "MIT",
+ "optional": true,
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/acorn-import-phases": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz",
@@ -2030,6 +2066,23 @@
"acorn": "^8.14.0"
}
},
+ "node_modules/ajv": {
+ "version": "8.20.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
"node_modules/ajv-formats": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
@@ -2087,6 +2140,40 @@
"node": ">=6.0.0"
}
},
+ "node_modules/browserslist": {
+ "version": "4.29.0",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.0.tgz",
+ "integrity": "sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "baseline-browser-mapping": "^2.11.23",
+ "caniuse-lite": "^1.0.30001810",
+ "electron-to-chromium": "^1.5.427",
+ "node-releases": "^2.0.55",
+ "update-browserslist-db": "^1.3.3"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -2410,6 +2497,23 @@
"license": "MIT",
"optional": true
},
+ "node_modules/fast-uri": {
+ "version": "3.1.8",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
+ "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause",
+ "optional": true
+ },
"node_modules/fs-monkey": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.0.3.tgz",
@@ -2565,6 +2669,13 @@
"license": "MIT",
"optional": true
},
+ "node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT",
+ "optional": true
+ },
"node_modules/loader-runner": {
"version": "4.3.2",
"resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.2.tgz",
@@ -2592,6 +2703,26 @@
"node": ">=10"
}
},
+ "node_modules/mediabunny": {
+ "version": "1.58.1",
+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.58.1.tgz",
+ "integrity": "sha512-edscMXOwBgUlMT+45wpAHdiXTGukCQb1nOJPE2D+fM4esNhAvGyB2yGGgnEer2VSwhEg+7gMliZDDQQqLaR7nA==",
+ "license": "MPL-2.0",
+ "optional": true,
+ "peer": true,
+ "workspaces": [
+ ".",
+ "packages/*"
+ ],
+ "dependencies": {
+ "@types/dom-mediacapture-transform": "^0.1.11",
+ "@types/dom-webcodecs": "0.1.13"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/Vanilagy"
+ }
+ },
"node_modules/memfs": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/memfs/-/memfs-3.4.3.tgz",
@@ -2758,6 +2889,35 @@
"node": ">=20"
}
},
+ "node_modules/postcss": {
+ "version": "8.5.28",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "nanoid": "^3.3.18",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
"node_modules/postcss-modules-extract-imports": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.1.0.tgz",
@@ -2842,6 +3002,40 @@
"license": "MIT",
"optional": true
},
+ "node_modules/react": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",
+ "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
+ "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "scheduler": "^0.28.0"
+ },
+ "peerDependencies": {
+ "react": "^19.3.0"
+ }
+ },
+ "node_modules/react-refresh": {
+ "version": "0.18.0",
+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
+ "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/recast": {
"version": "0.23.21",
"resolved": "https://registry.npmjs.org/recast/-/recast-0.23.21.tgz",
@@ -2880,12 +3074,23 @@
"react-dom": ">=16.8.0"
}
},
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/scheduler": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
"integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
"license": "MIT",
- "optional": true
+ "optional": true,
+ "peer": true
},
"node_modules/schema-utils": {
"version": "4.5.0",
@@ -3234,6 +3439,55 @@
"node": ">=10.13.0"
}
},
+ "node_modules/webpack": {
+ "version": "5.105.0",
+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.105.0.tgz",
+ "integrity": "sha512-gX/dMkRQc7QOMzgTe6KsYFM7DxeIONQSui1s0n/0xht36HvrgbxtM1xBlgx596NbpHuQU8P7QpKwrZYwUX48nw==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@types/eslint-scope": "^3.7.7",
+ "@types/estree": "^1.0.8",
+ "@types/json-schema": "^7.0.15",
+ "@webassemblyjs/ast": "^1.14.1",
+ "@webassemblyjs/wasm-edit": "^1.14.1",
+ "@webassemblyjs/wasm-parser": "^1.14.1",
+ "acorn": "^8.15.0",
+ "acorn-import-phases": "^1.0.3",
+ "browserslist": "^4.28.1",
+ "chrome-trace-event": "^1.0.2",
+ "enhanced-resolve": "^5.19.0",
+ "es-module-lexer": "^2.0.0",
+ "eslint-scope": "5.1.1",
+ "events": "^3.2.0",
+ "glob-to-regexp": "^0.4.1",
+ "graceful-fs": "^4.2.11",
+ "json-parse-even-better-errors": "^2.3.1",
+ "loader-runner": "^4.3.1",
+ "mime-types": "^2.1.27",
+ "neo-async": "^2.6.2",
+ "schema-utils": "^4.3.3",
+ "tapable": "^2.3.0",
+ "terser-webpack-plugin": "^5.3.16",
+ "watchpack": "^2.5.1",
+ "webpack-sources": "^3.3.3"
+ },
+ "bin": {
+ "webpack": "bin/webpack.js"
+ },
+ "engines": {
+ "node": ">=10.13.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/webpack"
+ },
+ "peerDependenciesMeta": {
+ "webpack-cli": {
+ "optional": true
+ }
+ }
+ },
"node_modules/webpack-sources": {
"version": "3.5.1",
"resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.5.1.tgz",
diff --git a/plugins/anidoodle/skills/anidoodle/engine/package.json b/plugins/anidoodle/skills/anidoodle/engine/package.json
index debac11..3ed9c90 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/package.json
+++ b/plugins/anidoodle/skills/anidoodle/engine/package.json
@@ -8,7 +8,8 @@
"still": "node tools/still.mjs",
"gate": "node tools/gate.mjs",
"emit": "node tools/emit.mjs",
- "render": "node tools/render.mjs"
+ "render": "node tools/render.mjs",
+ "test": "node tools/test.mjs"
},
"dependencies": {
"esbuild": "^0.25.0"
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/adaptAlmond.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/adaptAlmond.ts
new file mode 100644
index 0000000..a5d7e64
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/adaptAlmond.ts
@@ -0,0 +1,181 @@
+import { rng, fractal, type Medium, type P } from "./core";
+import type { Film } from "./film";
+import { bounds, clamp, inside, mix, smooth } from "./gallery";
+import { fit, runProcess, timeline, type Proc } from "./sumiEKit";
+import { fill, oilStroke, weave, type OStroke } from "./paintedOilKit";
+import { KOI_HI, koiBody, koiFins, padShape, tail } from "./koi";
+
+// A KOI IN THE ALMOND-BLOSSOM HAND · adapted from a picture the user brought.
+//
+// REFERENCE: Vincent van Gogh, Almond Blossom (1890), public domain (Wikimedia Commons; sha256 and
+// source in engine/assets/refs/PROVENANCE.json). What is borrowed is the HAND.
+// The subject (a flowering branch against the sky), the composition (branches crossing the whole
+// field from the lower edge) and the blossoms themselves are not taken. The subject here is the
+// launch film's own koi, in its own pond, laid out as in koi.ts, so the same fish can be seen
+// changing hands.
+//
+// MEDIUM RECIPE, written from the painting at full size and at a 3x crop:
+// MARK: opaque oil, a loaded bristle brush, short strokes about a finger long. The ground (his
+// sky, our water) is laid in small patches of strokes that share a direction, the patches
+// turning against each other, so the flat colour shimmers without ever breaking into dabs.
+// Forms are painted ALONG their length (a branch in strokes that run with it), so the form's
+// own grain reads. Lights are thick: the blossoms stand off the canvas, ridged.
+// EDGE: hard and outlined. The Japanese-print line: a dark blue-green contour laid last with a
+// small round brush, broken, heavier on the shadow side, sometimes skipping a stretch
+// entirely. Ground strokes butt up to the forms; nothing is blended across an edge.
+// ORDER: the ground first, everywhere; the forms over it in their mid tone; their lights; the
+// contour; the last thick whites.
+// PAPER: canvas, the weave showing through the thinner ground strokes.
+// PALETTE: turquoise to cerulean for the ground (value range narrow and high, L 0.68-0.84); a
+// cool sage and grey-green for the woody forms; cream and lead white warmed with a yellow-green
+// heart; a whisper of pink and rust; the contour a deep blue-green, never black.
+// WHAT IT IS NOT: nearest by eye is paintedOil (the same bristle mark and impasto). It differs in
+// three things: a high-key flat decorative ground instead of a lit room, a drawn dark contour
+// (paintedOil has none: its edges are found and lost), and no modelling in depth beyond one
+// step of shadow. The analyzer's nearest (charcoalErasure, storybook) are wrong by eye.
+
+const W = 1080, H = 1080, N = 450; // 15 s; the last 30 frames are the finished picture
+const OIL: Medium = { nib: 1, taper: 1, pressure: 1, retrace: false, wobble: 0, rough: 0 };
+
+// ---------------------------------------------------------------- colour
+const WATER = ["#6aa4b2", "#79b1bb", "#88bcc1", "#97c6c6", "#a9d1cc"];
+const SHADE_W = "#5a92a1";
+const SAGE = ["#6f8f74", "#88a684", "#a2bb96", "#bccdaa"];
+const CREAM = "#f1eedc", CREAM_S = "#c7d3c1", LEAD = "#fbf8ea";
+const RED = "#dc5f30", RED_S = "#ad4429", RED_L = "#ec8a55";
+const CONTOUR = "#27413c", CONTOUR_2 = "#34524a";
+const pick = (stops: string[], t: number) => { const f = clamp(t) * (stops.length - 1), i = Math.min(stops.length - 2, Math.floor(f)); return mix(stops[i], stops[i + 1], f - i); };
+
+// ---------------------------------------------------------------- the forms (koi.ts's own)
+const b = koiBody(), fins = koiFins(b), cau = tail(b);
+const PADS: [number, number, number, number, number][] = [[905, 205, 168, 2.3, 3100], [890, 905, 120, 3.6, 3300], [120, 640, 88, 0.2, 3400]];
+const padShapes = PADS.map(([x, y, r, n, s]) => padShape(x, y, r, n, s));
+const patches = KOI_HI.map(([t, s, dt, ds, seed]) => { const r = rng(seed * 17), pts: P[] = []; for (let i = 0; i < 16; i++) { const a = (i / 16) * Math.PI * 2, kk = 0.8 + r() * 0.35; pts.push(b.at(t + Math.cos(a) * dt * kk, s + Math.sin(a) * ds * kk)); } return smooth(pts, true, 6); });
+
+// the body's own frame, inverted by lookup: where along the fish (t) and across it (s) a point is
+const TS: { p: P; t: number; s: number }[] = [];
+for (let t = 0; t <= 1.0001; t += 0.01) for (let s = -1; s <= 1.0001; s += 0.1) TS.push({ p: b.at(t, s), t, s });
+const frameOf = (x: number, y: number) => { let best = TS[0], d = 1e9; for (const q of TS) { const e = (q.p[0] - x) ** 2 + (q.p[1] - y) ** 2; if (e < d) { d = e; best = q; } } return best; };
+const alongBody = (x: number, y: number) => { const q = frameOf(x, y), a = b.at(Math.min(1, q.t + 0.01), q.s), c = b.at(Math.max(0, q.t - 0.01), q.s); return Math.atan2(a[1] - c[1], a[0] - c[0]); };
+// the fish's cast shadow on the pond floor, down and right, as in the marker plate
+const castShadow = [b.outline, cau.shape].map((s) => s.map(([x, y]) => [x + 30, y + 40] as P));
+const inCast = (x: number, y: number) => castShadow.some((s) => inside(s, x, y));
+const onForm = (x: number, y: number) => inside(b.outline, x, y) || padShapes.some((s) => inside(s, x, y));
+
+// ---------------------------------------------------------------- the passes
+type Stage = { name: string; per: number; strokes: OStroke[]; clip?: P[][]; out?: P[][]; within?: P[] }; // out: kept clear, e.g. a fin's line where the fin runs under the body
+const st = (ctrl: P[], w: number, c0: string, seed: number, c1 = c0, imp = 0.4, dry = 0.3, load = 1.05): OStroke => ({ ctrl, w, c0, c1, load, dry, impasto: imp, jit: 0.06, seed });
+// a broken contour: the outline walked in short strokes of the small brush, a gap now and then,
+// heavier on the side away from the light (upper left)
+const contour = (path: P[], closed: boolean, w: number, seed: number, skip = 0.16): OStroke[] => {
+ const r = rng(seed), pts = closed ? [...path, path[0]] : path, out: OStroke[] = [];
+ let i = 0;
+ while (i < pts.length - 2) {
+ const n = 12 + Math.floor(r() * 16), seg = pts.slice(i, Math.min(pts.length, i + n + 2)); i += n;
+ if (seg.length < 2 || r() < skip) continue;
+ const m = seg[Math.floor(seg.length / 2)], prev = seg[0], next = seg[seg.length - 1], nx = -(next[1] - prev[1]), ny = next[0] - prev[0], shade = clamp(0.5 + 0.5 * ((nx * 0.62 + ny * 0.78) / (Math.hypot(nx, ny) || 1)));
+ out.push(st(seg, w * (0.6 + 0.7 * shade) * (0.85 + 0.3 * r()), r() < 0.3 ? CONTOUR_2 : CONTOUR, seed * 100 + out.length, CONTOUR, 0.25, 0.35, 1.1));
+ void m;
+ }
+ return out;
+};
+
+const stages = (): Stage[] => {
+ const S: Stage[] = [];
+ const FRAME: P[] = [[-30, -30], [W + 30, -30], [W + 30, H + 30], [-30, H + 30]];
+ // 1. the ground: the whole pond in patches of like-directed strokes, darker in the fish's cast shadow
+ const patchDir = (x: number, y: number) => (fractal(401, x, y, 0.006, 0.006, 2) - 0.5) * 5.2 + 0.25;
+ S.push({ name: "water", per: 0.18, strokes: fill({
+ region: FRAME, step: 19, len: 58, w: 20, dir: patchDir, seed: 410, dry: 0.2, load: 1.15, impasto: 0.42, jit: 0.08, soft: 0.2, bend: 0.5, sweep: 0.9,
+ color: (x, y) => (onForm(x, y) && !inCast(x, y) ? null : inCast(x, y) ? mix(SHADE_W, pick(WATER, fractal(402, x, y, 0.01, 0.01, 2)), 0.25) : pick(WATER, fractal(402, x, y, 0.006, 0.006, 3) * 1.25 - 0.12)),
+ }) });
+ S.push({ name: "water lights", per: 0.3, strokes: fill({
+ region: FRAME, step: 34, len: 46, w: 14, dir: patchDir, seed: 415, dry: 0.35, impasto: 0.4, jit: 0.06, soft: 0.2, bend: 0.5, sweep: 0.9,
+ color: (x, y) => (onForm(x, y) || inCast(x, y) || fractal(416, x, y, 0.012, 0.012, 2) < 0.58 ? null : fractal(417, x, y, 0.02, 0.02, 1) > 0.5 ? mix(WATER[3], WATER[4], 0.5) : "#6fa7b8"),
+ }) });
+ // 2. the pads: sage, painted from the stalk outward like a leaf's own veins
+ padShapes.forEach((pad, i) => {
+ const [cx, cy, rr] = PADS[i];
+ S.push({ name: `pad${i}`, per: 0.5, clip: [pad], strokes: fill({
+ region: pad, step: 11, len: 30, w: 11, seed: 420 + i, dry: 0.3, impasto: 0.35, jit: 0.06, soft: 0.2,
+ dir: (x, y) => Math.atan2(y - cy, x - cx),
+ color: (x, y) => { const d = Math.hypot(x - cx, y - cy) / rr, lit = clamp(0.5 - 0.35 * ((x - cx) * 0.62 + (y - cy) * 0.78) / rr); return pick(SAGE, clamp(0.25 + 0.5 * lit + 0.2 * d + (fractal(430 + i, x, y, 0.03, 0.03, 2) - 0.5) * 0.3)); },
+ }) });
+ });
+ // 3. the body in cream, strokes running nose to tail; one step of cool shadow on the far flank
+ S.push({ name: "body", per: 0.6, clip: [b.outline], strokes: fill({
+ region: b.outline, step: 10, len: 34, w: 12, seed: 440, dry: 0.25, impasto: 0.45, jit: 0.05, soft: 0.2, dir: alongBody,
+ color: (x, y) => { const q = frameOf(x, y); return q.s > 0.45 ? mix(CREAM_S, CREAM, clamp((0.9 - q.s) * 1.5)) : CREAM; },
+ }) });
+ // 4. fins and tail: long strokes laid down each ray, cream going cool toward the edge, sage between
+ const rayStrokes = (rays: P[][], seed: number, w: number) => rays.map((ray, k) => st(ray, w, CREAM, seed + k, CREAM_S, 0.3, 0.45, 1));
+ fins.forEach((f, i) => S.push({ name: `fin${i}`, per: 1.2, clip: [f.shape], strokes: [...fill({ region: f.shape, step: 9, len: 22, w: 9, seed: 450 + i, dry: 0.4, impasto: 0.2, jit: 0.05, dir: (x, y) => Math.atan2(y - f.rays[0][0][1], x - f.rays[0][0][0]), color: () => mix(SAGE[3], CREAM_S, 0.5) }), ...rayStrokes(f.rays, 460 + i * 20, 8)] }));
+ S.push({ name: "tail", per: 1, clip: [cau.shape], strokes: [...fill({ region: cau.shape, step: 10, len: 28, w: 10, seed: 470, dry: 0.4, impasto: 0.2, jit: 0.05, dir: (x, y) => Math.atan2(y - b.at(0.955, 0)[1], x - b.at(0.955, 0)[0]), color: () => mix(SAGE[3], CREAM_S, 0.5) }), ...rayStrokes(cau.rays, 480, 9)] });
+ // 5. the red: vermilion laid along the body, rust on the shadow flank, a lighter pull on the back
+ patches.forEach((pt, i) => S.push({ name: `red${i}`, per: 0.9, clip: [pt], within: b.outline, strokes: fill({
+ region: pt, step: 8, len: 26, w: 10, seed: 500 + i, dry: 0.22, impasto: 0.5, jit: 0.05, soft: 0.15, dir: alongBody,
+ color: (x, y) => { const q = frameOf(x, y); return q.s > 0.4 ? RED_S : q.s < -0.35 ? mix(RED, RED_L, 0.6) : RED; },
+ }) }));
+ // 6. the water lily on the big pad: thick white petals pulled from the heart outward, a yellow-green heart
+ const LC: P = [880, 195], petals: OStroke[] = [];
+ for (let k = 0; k < 11; k++) { const a = (k / 11) * Math.PI * 2 + 0.3, L = 46 + (k % 3) * 10; petals.push(st([[LC[0] + Math.cos(a) * 10, LC[1] + Math.sin(a) * 10], [LC[0] + Math.cos(a + 0.08) * L * 0.6, LC[1] + Math.sin(a + 0.08) * L * 0.6], [LC[0] + Math.cos(a) * L, LC[1] + Math.sin(a) * L]], 20, LEAD, 540 + k, k % 4 === 0 ? "#efc9c0" : CREAM, 0.85, 0.2, 1.3)); }
+ for (let k = 0; k < 6; k++) { const a = (k / 6) * Math.PI * 2, L = 26; petals.push(st([[LC[0], LC[1]], [LC[0] + Math.cos(a) * L, LC[1] + Math.sin(a) * L]], 16, "#f7f2de", 560 + k, "#f3dcd0", 0.9, 0.15, 1.3)); }
+ petals.push(st([[LC[0] - 6, LC[1] - 2], [LC[0] + 2, LC[1] + 3], [LC[0] + 8, LC[1] - 1]], 13, "#d8d676", 570, "#c9c85a", 0.9, 0.1, 1.4));
+ S.push({ name: "lily", per: 2, strokes: petals });
+ // 7. the contour: the dark blue-green line, laid last, broken
+ const n = b.outline.length / 2, Lside = b.outline.slice(0, n), Rside = b.outline.slice(n).reverse(), cut = Math.round(n * 0.965);
+ S.push({ name: "fin lines", per: 1.4, out: [b.outline], strokes: [...fins.flatMap((f, i) => contour(f.shape, true, 4, 610 + i, 0.08)), ...contour(cau.shape.slice(3, cau.shape.length - 3), false, 5, 620, 0.06)] });
+ S.push({ name: "contour", per: 1.4, strokes: [
+ ...contour([...Lside.slice(0, cut).reverse(), ...Rside.slice(0, cut)], false, 6.5, 600, 0.05),
+ ...padShapes.flatMap((p, i) => contour(p, true, 5, 630 + i, 0.1)),
+ ...patches.flatMap((p, i) => contour(p, true, 2.4, 640 + i, 0.55)),
+ ] });
+ // 8. the head: gill arcs and eyes in the contour colour, a glint of lead white
+ const head: OStroke[] = [];
+ [-1, 1].forEach((sd, hi) => {
+ const gill: P[] = []; for (let i = 0; i <= 6; i++) gill.push(b.at(0.155 - Math.sin((i / 6) * Math.PI) * 0.03, sd * (0.98 - i * 0.1)));
+ head.push(st(gill, 4, CONTOUR, 700 + hi, CONTOUR, 0.25, 0.4, 1.1));
+ const e = b.at(0.085, sd * 0.8), ring = (r: number) => [0, 1, 2, 3, 4, 5, 6].map((k) => [e[0] + Math.cos(k * 1.05) * r, e[1] + Math.sin(k * 1.05) * r] as P);
+ head.push(st(ring(6), 7, "#e3d48f", 710 + hi, "#e3d48f", 0.5, 0.1, 1.3), st(ring(2.5), 6, "#1e2a2a", 712 + hi, "#1e2a2a", 0.5, 0.05, 1.4), st([[e[0] - 3, e[1] - 3], [e[0] - 1, e[1] - 4]], 3, LEAD, 714 + hi, LEAD, 0.9, 0, 1.4));
+ });
+ S.push({ name: "head", per: 2, strokes: head });
+ // 9. the last thick whites: light along the back and on the head, a few pulled ripples in the water
+ const back: OStroke[] = [[0.2, 0.3, -0.6, 8], [0.335, 0.43, -0.64, 7], [0.47, 0.52, -0.66, 5.5], [0.06, 0.1, -0.4, 7]].map(([t0, t1, sv, w], k) => st([b.at(t0, sv), b.at((t0 + t1) / 2, sv - 0.03), b.at(t1, sv)], w, LEAD, 800 + k, "#f4f1df", 1, 0.2, 1.4));
+ const rip: OStroke[] = [];
+ [[300, 196, 34], [300, 196, 58], [300, 196, 84]].forEach(([x, y, r], k) => { const a0 = -2.4 + k * 0.2, a1 = a0 + 1.3; rip.push(st([0, 0.5, 1].map((u) => [x + Math.cos(a0 + (a1 - a0) * u) * r, y + Math.sin(a0 + (a1 - a0) * u) * r * 0.62] as P), 6, WATER[4], 820 + k, "#c3e0d8", 0.45, 0.5, 1.1)); });
+ S.push({ name: "lights", per: 2, strokes: [...back, ...rip] });
+ return S;
+};
+
+// ---------------------------------------------------------------- the process
+const ground = (g: import("./core").Gfx) => { const c = g.cur, e = g.env; c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.fillStyle = "#e9e6d8"; c.fillRect(0, 0, e.W, e.H); weave(g, 0.5); };
+const finish = (g: import("./core").Gfx) => weave(g, 0.22);
+const withClip = (g: import("./core").Gfx, s: Stage, fn: () => void) => {
+ if (!s.clip && !s.out) return fn();
+ const c = g.cur, ring = (p: P[]) => { c.moveTo(p[0][0], p[0][1]); p.forEach(([x, y]) => c.lineTo(x, y)); c.closePath(); };
+ c.save(); c.beginPath();
+ if (s.clip) { s.clip.forEach(ring); c.clip("nonzero"); if (s.within) { c.beginPath(); ring(s.within); c.clip(); } } else { c.rect(-50, -50, W + 100, H + 100); s.out!.forEach(ring); c.clip("evenodd"); }
+ fn(); c.restore();
+};
+const build = (k: number): Proc => {
+ const tl = timeline(8, k, true);
+ stages().forEach((s, si) => {
+ const B = Math.max(1, Math.round(2 / s.per));
+ for (let a = 0; a < s.strokes.length; a += B) {
+ const batch = s.strokes.slice(a, a + B);
+ tl.add(batch.length * s.per, (g, p) => withClip(g, s, () => { const f = p * batch.length; batch.forEach((x, i) => { if (p >= 1 || i < Math.floor(f)) oilStroke(g, x, 1); else if (i === Math.floor(f)) oilStroke(g, x, f - i); }); }));
+ }
+ tl.wait(si === 0 ? 10 : 4);
+ });
+ return { id: "adaptAlmond", medium: OIL, ground, ops: tl.ops, finish };
+};
+let PROC: Proc | null = null;
+const proc = () => (PROC ??= fit(build, N - 31));
+
+export const STYLE = { id: "adaptAlmond", name: "Almond-blossom hand, adapted", family: "paint", medium: "opaque oil in short patterned strokes on canvas, a broken dark blue-green contour, thick lead-white lights", nearest: "paintedOil", hero: "the launch film's koi, repainted in a hand borrowed from a public-domain painting", house: "styles/house/almond-blossom.json" };
+
+export const adaptAlmond: Film = {
+ meta: { title: "Koi · the almond-blossom hand (adapted)", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },
+ assets: { images: {} },
+ shots: [{ id: "paint", start: 0, end: N, draw: (ctx, f, env) => { const p = proc(); runProcess(p, ctx, Math.min(f, p.ops[p.ops.length - 1].t1), env); } }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/brickBalloon.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/brickBalloon.ts
new file mode 100644
index 0000000..f3a7de1
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/brickBalloon.ts
@@ -0,0 +1,356 @@
+// BRICK BALLOON · the crayon balloon turns into toy bricks, builds itself, and flies.
+//
+// STORY (13.3 s, 90 bpm, a beat is 20 frames):
+// 0-30 the crayon balloon plate, exactly as balloon.ts draws it.
+// 30-72 a wave climbs the picture bottom to top; behind it the crayon becomes a brick mosaic,
+// one 1x1 plate per cell, each popping up with a press-fit, coloured from the crayon
+// beneath it snapped to the real toy-brick colour table.
+// 80-126 the mosaic lets go: tiles fall away bottom rows first and the studio shows through,
+// where a baseplate drops in and the balloon is rebuilt in 3D, instruction-booklet
+// style: hills, a tree, a house, the path, the basket, the burner, then the envelope
+// course by course, bottom up, each part falling down its insertion axis, ghosted in
+// flight, seating with a one-frame press-fit.
+// 200-228 the burner lights (a trans-orange flame that flickers); the world assembles around
+// the launch plate, tile by tile outward, and the camera pulls back into the sky.
+// 228-400 lift-off: the balloon rises and travels, the camera follows a beat behind, the brick
+// country scrolls beneath (hills, woods, houses, a river), brick clouds pass behind and
+// in front at their own depths.
+//
+// MEDIUM: the toy-brick plate's (toyBrick.ts): moulded ABS in real toy-brick colours, orthographic
+// at azimuth 45 / elevation 30, the cube rule for face tones, bevels, seams and real studs, one key
+// light from the upper left. Every brick is drawn by toyBrickKit.
+// THE ENVELOPE is a surface of revolution (the balloon plate's own profile: a narrow mouth, widest
+// a little above the middle, a rounded crown) built as 13 one-brick courses. Each course is a
+// 24-sided ring cut into 12 gores that run the full height in rainbow order, joints staggered
+// course to course like a running bond; studs show only on the terraces the next course leaves
+// bare. The basket hangs from the mouth by four black bars; the burner sits between them.
+import { fractal, rng, type Ctx, type Env, type Layer, type P } from "./core";
+import type { Film } from "./film";
+import { renderFrame } from "./film";
+import { balloon } from "./balloon";
+import { aabb, BRICK, Cam, drawPart, LIGHT, order, PLATE, shade, STUD, STUD_H, stud, type Part } from "./toyBrickKit";
+
+const W = 1080, H = 1080, N = 400, FPS = 30;
+// real toy-brick colours (LDraw / BrickLink names in the comments)
+const K = {
+ red: "#B40000", orange: "#D67923", yellow: "#FAC80A", bgreen: "#4B9F4A" /* Bright Green */, green: "#237841" /* Green */, dgreen: "#184632" /* Dark Green */,
+ blue: "#1E5AA8", azure: "#68C3E2" /* Medium Azure */, lblue: "#9FC3E9" /* Bright Light Blue */, lav: "#AC78BA" /* Medium Lavender */,
+ white: "#F4F4F4", lbg: "#969696", dbg: "#646464", black: "#1B2A34", brown: "#5F3109" /* Reddish Brown */, tan: "#D7BA8C", dtan: "#958A73",
+ tOrange: "#F08F1C" /* Trans-Orange */, tYellow: "#F5CD2F" /* Trans-Yellow */, byellow: "#FFF03A" /* Bright Light Yellow */,
+};
+const BACKDROP = "#E7E4DE", SKY = "#CFE7F2", HAIR = 0.7;
+const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+const ramp = (f: number, a: number, b: number) => clamp((f - a) / (b - a));
+const smooth = (t: number) => { const c = clamp(t); return c * c * (3 - 2 * c); };
+const out3 = (t: number) => 1 - Math.pow(1 - clamp(t), 3);
+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+const mixHex = (a: string, b: string, t: number) => { const h = (s: string) => [1, 3, 5].map((i) => parseInt(s.slice(i, i + 2), 16)); const x = h(a), y = h(b); return `rgb(${x.map((v, i) => Math.round(lerp(v, y[i], clamp(t)))).join(",")})`; };
+
+// ---------------------------------------------------------------- the cue table (frames)
+const T = { waveA: 30, waveB: 72, fallA: 80, fallB: 126, base: 96, build0: 104, env0: 146, envStep: 3, ropes: 140, settle: 192, fire: 200, world0: 200, lift: 228 };
+const FALL = 10, DROP = 190;
+
+// ---------------------------------------------------------------- the launch plate (tile 0,0)
+type Placed = Part & { land: number };
+const rect = (x0: number, z0: number, x1: number, z1: number): [number, number][] => [[x0, z0], [x1, z0], [x1, z1], [x0, z1]];
+const TILE = 16;
+// what stands on one 16x16 baseplate. `ox, oz` put it in the world; `launch` is the balloon's own plate
+const tileParts = (i: number, j: number, launch: boolean): Part[] => {
+ const P: Part[] = [], r = rng(9001 + i * 131 + j * 7919), ox = i * TILE, oz = j * TILE;
+ const add = (foot: [number, number][], y0: number, h: number, color: string, studs = true, kind: Part["kind"] = "prism") => P.push({ id: P.length, color, kind, foot: foot.map(([x, z]) => [x + ox, z + oz] as [number, number]), y0, h, studs, step: 0 });
+ // the river runs the whole length of the world along Z, at i = 2
+ const river = i === 2;
+ if (river) { add(rect(0, 0, 6, 16), -0.4, 0.4, K.bgreen); add(rect(6, 0, 10, 16), -0.4, 0.4, K.blue); add(rect(10, 0, 16, 16), -0.4, 0.4, K.bgreen); }
+ else add(rect(0, 0, 16, 16), -0.4, 0.4, K.bgreen);
+ const hill = (x0: number, z0: number, x1: number, z1: number, tiers: number) => { for (let k = 0; k < tiers; k++) add(rect(x0 + k, z0 + k, x1 - k, z1 - k), k * 3, 3, [K.green, K.bgreen, K.green, K.dgreen][k % 4]); };
+ const tree = (x: number, z: number, kind: number) => {
+ add(rect(x, z, x + 1, z + 1), 0, 3, K.brown, false, "round"); add(rect(x, z, x + 1, z + 1), 3, 3, K.brown, false, "round");
+ if (kind === 0) { add(rect(x - 1, z - 1, x + 2, z + 2), 6, 3, K.green); add(rect(x - 0.5, z - 0.5, x + 1.5, z + 1.5), 9, 3, K.green); add(rect(x, z, x + 1, z + 1), 12, 3, K.bgreen, true, "round"); }
+ else { add(rect(x - 1, z - 1, x + 2, z + 2), 6, 3, K.dgreen); add(rect(x - 1, z - 1, x + 2, z + 2), 9, 3, K.dgreen); add(rect(x, z, x + 1, z + 1), 12, 3, K.dgreen, true, "round"); }
+ };
+ const house = (x: number, z: number, roof: string) => {
+ add(rect(x, z, x + 4, z + 3), 0, 3, K.white); add(rect(x, z, x + 4, z + 3), 3, 3, K.white);
+ add(rect(x + 4 - 0.01, z + 1, x + 4, z + 2), 1, 3, K.azure, false); // a window in the lit face
+ add(rect(x - 0.5, z - 0.5, x + 4.5, z + 3.5), 6, 1, roof); add(rect(x, z, x + 4, z + 3), 7, 1, roof); add(rect(x + 0.5, z + 0.5, x + 3.5, z + 2.5), 8, 1, roof); add(rect(x + 1, z + 1, x + 3, z + 2), 9, 1, roof);
+ add(rect(x + 3, z + 0.5, x + 4, z + 1.5), 7, 5, K.dbg, true, "round");
+ };
+ if (launch) {
+ hill(0, 0, 7, 6, 3); house(10, 1, K.red); tree(3, 11, 1); tree(14, 7, 0); // nothing stands in front of the basket
+ add(rect(10, 8, 16, 9), 0, 1, K.tan, false); add(rect(8, 7, 10, 9), 0, 1, K.tan, false);
+ return P;
+ }
+ if (river) { add(rect(7, 3, 9, 4), 0, 0.4, K.azure, false); add(rect(6.5, 11, 8, 12), 0, 0.4, K.azure, false); if (j % 2 === 0) { add(rect(3, 6, 6, 10), 0, 3, K.green); tree(12, 4, 1); } else { tree(2, 3, 0); tree(12, 10, 0); } return P; }
+ // the countryside: a hill, a wood or a farm, chosen by the tile's own seed
+ const kind = Math.floor(r() * 5);
+ if (kind === 0) { hill(1 + Math.floor(r() * 3), 1 + Math.floor(r() * 3), 13 - Math.floor(r() * 2), 12 - Math.floor(r() * 2), 2 + Math.floor(r() * 2)); if (r() < 0.5) tree(13, 13, 1); }
+ else if (kind === 1) { const n = 2 + Math.floor(r() * 2); for (let k = 0; k < n; k++) tree(2 + Math.floor(r() * 11), 2 + Math.floor(r() * 11), k % 2); }
+ else if (kind === 2) { house(3 + Math.floor(r() * 4), 3 + Math.floor(r() * 3), r() < 0.5 ? K.red : K.blue); tree(12, 12, 0); }
+ else if (kind === 3) { const x0 = 1 + Math.floor(r() * 3), z0 = 1 + Math.floor(r() * 3), col = r() < 0.5 ? K.yellow : K.tan; for (let k = 0; k < 5; k++) add(rect(x0, z0 + k * 2, x0 + 9, z0 + k * 2 + 1), 0, 1, col, true); } // a field in rows
+ else { add(rect(4, 4, 11, 10), 0, 0.4, K.blue, false); add(rect(5, 5, 7, 6), 0, 0.4, K.azure, false); add(rect(8, 8, 10, 9), 0, 0.4, K.azure, false); tree(12, 3, 1); } // a pond
+ return P;
+};
+
+// ---------------------------------------------------------------- the balloon, in LDU
+const AXIS: [number, number] = [8.5 * STUD, 8.5 * STUD]; // on the launch plate
+const COURSES = 15, R_MAX = 6.5, R_MOUTH = 1.6, MOUTH_Y = 17 * PLATE, SEGS = 24;
+const GORE = [K.red, K.orange, K.yellow, K.bgreen, K.blue, K.lav];
+// the balloon plate's profile: a long cone out of the mouth that swells into the shoulder,
+// widest at 60% of the height, then a round crown
+const courseR = (i: number) => { const u = (i + 0.5) / COURSES; return u < 0.6 ? R_MOUTH + (R_MAX - R_MOUTH) * Math.pow(Math.sin((Math.PI / 2) * (u / 0.6)), 1.35) : R_MAX * Math.sqrt(Math.max(0, 1 - Math.pow((u - 0.6) / 0.43, 2))); };
+const sideTone = (nx: number, nz: number) => -0.11 - 0.11 * (nx - nz);
+const goreAt = (a: number) => GORE[Math.floor((((a / (Math.PI * 2)) % 1) + 1) % 1 * 12) % 6];
+const basketParts = (): Part[] => {
+ const P: Part[] = []; let id = 1000;
+ const add = (foot: [number, number][], y0: number, h: number, color: string, studs = true, kind: Part["kind"] = "prism") => P.push({ id: id++, color, kind, foot, y0, h, studs, step: 0 });
+ add(rect(7, 7, 10, 10), 0, 3, K.brown, false); add(rect(7, 7, 10, 10), 3, 3, K.brown, false); add(rect(7, 7, 10, 10), 6, 1, K.tan, false);
+ add(rect(8, 8, 9, 9), 7, 2, K.dbg, true, "round");
+ return P;
+};
+
+// one course of the envelope: camera-facing faces, the top, the bare terrace's studs
+const drawCourse = (c: Ctx, cam: Cam, i: number, lift: number, dy: number, alpha: number, hair: number) => {
+ const r = courseR(i) * STUD, rn = i + 1 < COURSES ? courseR(i + 1) : 0, Y0 = MOUTH_Y + i * BRICK + lift + dy, Y1 = Y0 + BRICK, [cx, cz] = AXIS, s = cam.s;
+ const off = (i % 2) * (Math.PI / SEGS), A = (k: number) => (k / SEGS) * Math.PI * 2 + off, pt = (k: number): [number, number] => [cx + Math.cos(A(k)) * r, cz + Math.sin(A(k)) * r];
+ c.globalAlpha = alpha;
+ // tops first (they are behind the faces), one fan per segment in its gore colour
+ for (let k = 0; k < SEGS; k++) { const a = pt(k), b = pt(k + 1), col = goreAt((A(k) + A(k + 1)) / 2 - off); const q = [cam.p(cx, Y1, cz), cam.p(a[0], Y1, a[1]), cam.p(b[0], Y1, b[1])]; c.beginPath(); q.forEach(([x, y], n) => (n ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fillStyle = shade(col, 0.1); c.fill(); c.strokeStyle = shade(col, 0.1); c.lineWidth = 0.6; c.stroke(); }
+ const faces: { q: [number, number][]; col: string; k: number }[] = [];
+ for (let k = 0; k < SEGS; k++) {
+ const am = (A(k) + A(k + 1)) / 2, nx = Math.cos(am), nz = Math.sin(am); if (nx + nz <= 0) continue;
+ const a = pt(k), b = pt(k + 1), col = goreAt(am - off);
+ const q: [number, number][] = [cam.p(a[0], Y0, a[1]), cam.p(b[0], Y0, b[1]), cam.p(b[0], Y1, b[1]), cam.p(a[0], Y1, a[1])];
+ c.beginPath(); q.forEach(([x, y], n) => (n ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fillStyle = shade(col, sideTone(nx, nz)); c.fill(); c.strokeStyle = shade(col, sideTone(nx, nz)); c.lineWidth = 0.6; c.stroke();
+ faces.push({ q, col, k });
+ }
+ // bevel along the lit top edge, seams along the bottom, and a vertical joint where the gore
+ // changes colour or where the running bond puts one
+ c.lineCap = "round";
+ faces.forEach(({ q, col, k }) => {
+ c.strokeStyle = shade(col, 0.32); c.lineWidth = Math.max(1, 0.9 * s); c.beginPath(); c.moveTo(q[3][0], q[3][1] + 0.5 * s); c.lineTo(q[2][0], q[2][1] + 0.5 * s); c.stroke();
+ c.strokeStyle = shade(col, -0.45); c.lineWidth = hair; c.beginPath(); c.moveTo(q[0][0], q[0][1]); c.lineTo(q[1][0], q[1][1]); c.stroke();
+ const prev = goreAt((A(k - 1) + A(k)) / 2 - off), joint = prev !== col || (k + i) % 2 === 0;
+ if (joint) { c.beginPath(); c.moveTo(q[0][0], q[0][1]); c.lineTo(q[3][0], q[3][1]); c.stroke(); }
+ });
+ // studs on the terrace the next course leaves bare, back to front
+ const cells: [number, number][] = [];
+ const R = Math.ceil(courseR(i)) + 1;
+ for (let x = -R; x < R; x++) for (let z = -R; z < R; z++) { const d = Math.hypot(x + 0.5, z + 0.5); if (d < courseR(i) - 0.5 && d > rn + 0.15) cells.push([x + 0.5, z + 0.5]); }
+ cells.sort((a, b) => a[0] + a[1] - (b[0] + b[1])).forEach(([x, z]) => stud(c, cam, cx + x * STUD, Y1, cz + z * STUD, goreAt(Math.atan2(z, x) - off), hair));
+ c.globalAlpha = 1;
+};
+// the four bars from the basket rim to the mouth; `front` picks the pair nearer the camera
+const drawBars = (c: Ctx, cam: Cam, lift: number, front: boolean, grow: number) => {
+ if (grow <= 0) return;
+ const [cx, cz] = AXIS, y0 = 7 * PLATE + lift, y1 = MOUTH_Y + lift, r0 = 1.5 * STUD, r1 = R_MOUTH * STUD * 0.9;
+ [Math.PI / 4, (3 * Math.PI) / 4, (5 * Math.PI) / 4, (7 * Math.PI) / 4].forEach((a) => {
+ const isFront = Math.cos(a) + Math.sin(a) > -0.1; if (isFront !== front) return;
+ const b = cam.p(cx + Math.cos(a) * r0 * 1.41, y0, cz + Math.sin(a) * r0 * 1.41), t = cam.p(cx + Math.cos(a) * r1, y1, cz + Math.sin(a) * r1), e: P = [lerp(b[0], t[0], grow), lerp(b[1], t[1], grow)];
+ c.lineCap = "round"; c.strokeStyle = K.black; c.lineWidth = Math.max(1.4, 2.2 * cam.s); c.beginPath(); c.moveTo(b[0], b[1]); c.lineTo(e[0], e[1]); c.stroke();
+ c.strokeStyle = shade(K.black, 0.35); c.lineWidth = Math.max(0.6, 0.7 * cam.s); c.beginPath(); c.moveTo(b[0] - 0.8 * cam.s, b[1]); c.lineTo(e[0] - 0.8 * cam.s, e[1]); c.stroke();
+ });
+};
+// the burner's flame: trans-orange outside, trans-yellow core, flickering on noise, into the mouth
+const drawFlame = (c: Ctx, cam: Cam, lift: number, f: number, power: number) => {
+ if (power <= 0) return;
+ const [cx, cz] = AXIS, base = cam.p(cx, 9 * PLATE + lift, cz), n = fractal(77, f * 0.35, 0.5, 1, 1, 2), h = (18 + 34 * n) * power * cam.s, w = (7 + 2 * n) * cam.s * Math.min(1, power * 1.5);
+ const tongue = (hh: number, ww: number, col: string, a: number) => { c.globalAlpha = a; c.fillStyle = col; c.beginPath(); c.moveTo(base[0] - ww, base[1]); c.quadraticCurveTo(base[0] - ww * 0.9, base[1] - hh * 0.55, base[0] + ww * 0.25 * Math.sin(f * 0.9), base[1] - hh); c.quadraticCurveTo(base[0] + ww * 0.9, base[1] - hh * 0.55, base[0] + ww, base[1]); c.closePath(); c.fill(); };
+ tongue(h, w, K.tOrange, 0.82); tongue(h * 0.62, w * 0.55, K.tYellow, 0.9); c.globalAlpha = 1;
+ // the glow the flame throws up into the mouth
+ const m = cam.p(cx, MOUTH_Y + lift, cz); c.globalAlpha = 0.28 * power * (0.8 + 0.2 * n); c.fillStyle = K.tYellow; c.beginPath(); c.ellipse(m[0], m[1], R_MOUTH * STUD * 0.95 * cam.s * 0.707 * 2, R_MOUTH * STUD * 0.95 * cam.s * 0.707, 0, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1;
+};
+
+// ---------------------------------------------------------------- the camera
+// q = the unit projection (Cam(1,0,0)); screen = (q - F) * z + centre
+const U = new Cam(1, 0, 0);
+type View = { F: P; z: number };
+const camOf = (v: View, sc: number) => new Cam(v.z * sc, (W / 2 - v.F[0] * v.z) * sc, (H * 0.56 - v.F[1] * v.z) * sc);
+const BUILD: View = { F: U.p(AXIS[0], 150, AXIS[1]) as P, z: 1.25 };
+const lift = (f: number) => (f < T.lift ? 0 : 820 * smooth((f - T.lift) / 130) + 1.8 * Math.max(0, f - T.lift - 70) + 5 * Math.sin(((f - T.lift) / 40) * Math.PI) * ramp(f, T.lift, T.lift + 40));
+const travel = (f: number) => (f < T.lift + 12 ? 0 : 40 * Math.pow((f - T.lift - 12) / (N - T.lift - 12), 1.5)) * STUD; // along +X -Z: screen right
+const balloonAt = (f: number) => ({ dx: travel(f), dz: -travel(f), y: lift(f) });
+const view = (f: number): View => {
+ const b = balloonAt(Math.max(0, f - 16)), follow: P = U.p(AXIS[0] + b.dx, 230 + b.y * 0.55, AXIS[1] + b.dz) as P;
+ const pull = smooth(ramp(f, T.world0, T.lift + 30));
+ return { F: [lerp(BUILD.F[0], follow[0], pull), lerp(BUILD.F[1], follow[1], pull)], z: lerp(BUILD.z, 0.86, pull) * (1 - 0.2 * smooth(ramp(f, T.lift + 20, N))) }; // ortho has no perspective: pulling back is the altitude cue
+};
+
+// ---------------------------------------------------------------- sprites (the world is static: draw it once)
+type Sprite = { L: Layer; q0: P; k: number }; // canvas origin in unit-projection coords; k = px per unit
+const SPRITE_K = 1.25;
+const spriteOf = (env: Env, key: string, parts: Part[], shadow = true): Sprite => {
+ const ck = `bb/sprite/${key}/${env.scale}`; let s = env.cache.get(ck) as Sprite | undefined; if (s) return s;
+ const k = SPRITE_K * env.scale; let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
+ parts.forEach((p) => { const b = aabb(p); for (const X of [b.x0, b.x1]) for (const Y of [b.y0, b.y1]) for (const Z of [b.z0, b.z1]) { const q = U.p(X, Y, Z); x0 = Math.min(x0, q[0]); x1 = Math.max(x1, q[0]); y0 = Math.min(y0, q[1]); y1 = Math.max(y1, q[1]); } });
+ const pad = 30, L = env.canvas(Math.ceil((x1 - x0) * k + pad * 2), Math.ceil((y1 - y0) * k + pad * 2)), cam = new Cam(k, -x0 * k + pad, -y0 * k + pad);
+ const base = parts.filter((p) => p.y0 < 0), rest = parts.filter((p) => p.y0 >= 0);
+ order(base.map((p) => ({ p, dy: 0 })), cam).forEach((i) => drawPart(L.ctx, cam, base[i], 0, HAIR * env.scale));
+ if (shadow) groundShadow(env, L.ctx, cam, rest, 0.3);
+ order(rest.map((p) => ({ p, dy: 0 })), cam).forEach((i) => drawPart(L.ctx, cam, rest[i], 0, HAIR * env.scale));
+ s = { L, q0: [x0 - pad / k, y0 - pad / k], k }; env.cache.set(ck, s); return s;
+};
+const blit = (ctx: Ctx, s: Sprite, v: View, sc: number, dyScreen = 0, alpha = 1) => {
+ const z = v.z * sc, x = (W / 2 + (s.q0[0] - v.F[0]) * v.z) * sc, y = (H * 0.56 + (s.q0[1] - v.F[1]) * v.z) * sc - dyScreen * sc;
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = alpha; ctx.drawImage(s.L.canvas as CanvasImageSource, x, y, (s.L.canvas.width * z) / s.k, (s.L.canvas.height * z) / s.k); ctx.globalAlpha = 1;
+};
+// soft ground shadows, swept along the light onto Y = 0, drawn small and scaled back up (no filter)
+const hull = (pts: P[]) => { const q = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]), cr = (o: P, a: P, b: P) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); const lo: P[] = [], up: P[] = []; for (const p of q) { while (lo.length >= 2 && cr(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); } for (let i = q.length - 1; i >= 0; i--) { const p = q[i]; while (up.length >= 2 && cr(up[up.length - 2], up[up.length - 1], p) <= 0) up.pop(); up.push(p); } return [...lo.slice(0, -1), ...up.slice(0, -1)]; };
+const groundShadow = (env: Env, c: Ctx, cam: Cam, parts: Part[], a: number, lifted = 0) => {
+ if (!parts.length) return;
+ const sx = -LIGHT[0] / LIGHT[1], sz = -LIGHT[2] / LIGHT[1], k = 0.2, w = Math.ceil(c.canvas.width * k) + 2, h = Math.ceil(c.canvas.height * k) + 2;
+ const key = `bb/soft/${w}x${h}`; let S = env.cache.get(key) as Layer | undefined; if (!S) { S = env.canvas(w, h); env.cache.set(key, S); }
+ const s = S.ctx; s.setTransform(1, 0, 0, 1, 0, 0); s.clearRect(0, 0, w, h); s.fillStyle = "#000";
+ const tr = c.getTransform();
+ parts.forEach((p) => { const b = aabb(p, lifted), pts: P[] = []; for (const Y of [b.y0, b.y1 - (p.studs ? STUD_H : 0)]) for (const X of [b.x0, b.x1]) for (const Z of [b.z0, b.z1]) { const q = cam.p(X + sx * Y, 0, Z + sz * Y); pts.push([(tr.a * q[0] + tr.e) * k, (tr.d * q[1] + tr.f) * k]); } const hh = hull(pts); s.beginPath(); hh.forEach(([x, y], i) => (i ? s.lineTo(x, y) : s.moveTo(x, y))); s.closePath(); s.fill(); });
+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.imageSmoothingEnabled = true; c.globalAlpha = a; c.drawImage(S.canvas as CanvasImageSource, 0, 0, w, h, 0, 0, w / k, h / k); c.restore();
+};
+
+// ---------------------------------------------------------------- the world
+type WTile = { i: number; j: number; d: number; parts: Part[] };
+const WORLD: WTile[] = (() => {
+ const out: WTile[] = [];
+ for (let i = -8; i <= 9; i++) for (let j = -13; j <= 4; j++) {
+ if (i === 0 && j === 0) continue;
+ // keep a tile only if some frame of the flight shows it (checked at the zoom and centre of every 8th frame)
+ const c = U.p((i + 0.5) * TILE * STUD, 0, (j + 0.5) * TILE * STUD); let seen = false;
+ for (let f = T.world0; f < N && !seen; f += 8) { const v = view(f), x = W / 2 + (c[0] - v.F[0]) * v.z, y = H * 0.56 + (c[1] - v.F[1]) * v.z; seen = x > -380 * v.z && x < W + 380 * v.z && y > -260 * v.z && y < H + 520 * v.z; }
+ if (!seen) continue;
+ const d = Math.max(Math.abs(i), Math.abs(j)) + 0.35 * (Math.abs(i) + Math.abs(j)); out.push({ i, j, d, parts: tileParts(i, j, false) });
+ }
+ return out.sort((a, b) => a.i + a.j - (b.i + b.j)); // back to front
+})();
+const LAUNCH = tileParts(0, 0, true);
+// the launch plate's build: the plate, then the hills bottom-up, the trees, the house, the path
+const LAUNCH_LAND: number[] = (() => { const land: number[] = []; let t = T.build0; LAUNCH.forEach((p, n) => { land.push(n === 0 ? T.base : t); if (n > 0) t += 2; }); return land; })();
+const BASKET = basketParts(), BASKET_LAND = [136, 139, 142, 145];
+
+// ---------------------------------------------------------------- clouds: white bricks, grey undersides
+const cloudParts = (seed: number): Part[] => {
+ const r = rng(seed), P: Part[] = []; let id = 2000;
+ const add = (x0: number, z0: number, x1: number, z1: number, y0: number, h: number, col: string, kind: Part["kind"] = "prism") => P.push({ id: id++, color: col, kind, foot: rect(x0, z0, x1, z1), y0, h, studs: true, step: 0 });
+ // two or three puffs side by side, each a dome: a wide grey-bottomed plate, then white courses
+ // stepping in, a round on top
+ const puffs = 2 + Math.floor(r() * 2);
+ for (let k = 0; k < puffs; k++) {
+ const w = 6 - (k % 2) * 2 + Math.floor(r() * 2), x = k * 4.5, z = (k % 2) * 1.5, y = (k % 2) * 3;
+ add(x, z, x + w, z + w * 0.6 + 1, y, 1, K.lbg); add(x, z, x + w, z + w * 0.6 + 1, y + 1, 3, K.white);
+ add(x + 1, z + 0.5, x + w - 1, z + w * 0.6 + 0.5, y + 4, 3, K.white); add(x + 2, z + 1, x + w - 2, z + w * 0.6, y + 7, 3, K.white);
+ add(x + w / 2 - 0.5, z + w * 0.3, x + w / 2 + 0.5, z + w * 0.3 + 1, y + 10, 2, K.white, "round");
+ }
+ return P;
+};
+type Cloud = { seed: number; X: number; Z: number; Y: number; par: number; front: boolean };
+const CLOUDS: Cloud[] = [
+ { seed: 1, X: 280, Z: -520, Y: 620, par: 0.7, front: false }, { seed: 2, X: 620, Z: -760, Y: 880, par: 0.75, front: false },
+ { seed: 3, X: 980, Z: -1180, Y: 700, par: 0.7, front: false }, { seed: 4, X: 470, Z: -980, Y: 980, par: 1.3, front: true },
+ { seed: 5, X: 860, Z: -1560, Y: 1180, par: 1.35, front: true }, { seed: 6, X: 150, Z: -220, Y: 1020, par: 0.65, front: false },
+];
+const drawCloud = (ctx: Ctx, env: Env, cl: Cloud, v: View, f: number) => {
+ const s = spriteOf(env, `cloud${cl.seed}`, cloudParts(cl.seed), false), sc = env.scale;
+ const q = U.p(cl.X, cl.Y, cl.Z), view0 = view(T.lift), par: View = { F: [lerp(view0.F[0], v.F[0], cl.par), lerp(view0.F[1], v.F[1], cl.par)], z: v.z };
+ const a = ramp(f, T.world0 + 10, T.lift + 20) * (cl.front ? 0.92 : 1);
+ if (a <= 0) return;
+ const shifted: Sprite = { ...s, q0: [s.q0[0] + q[0], s.q0[1] + q[1]] };
+ blit(ctx, shifted, par, sc, 0, a);
+};
+
+// ---------------------------------------------------------------- the crayon, and its mosaic
+const CELL = 27, NC = W / CELL; // 40 x 40 one-by-one plates
+const PAL = [K.white, K.lblue, K.azure, K.blue, K.red, K.orange, K.yellow, K.byellow, K.bgreen, K.green, K.dgreen, K.brown, K.tan, K.black, K.lav];
+const crayonLayer = (env: Env): Layer => {
+ const key = `bb/crayon/${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;
+ L = env.canvas(Math.round(W * env.scale), Math.round(H * env.scale));
+ renderFrame(balloon, L.ctx, 0, { W, H, scale: env.scale, cache: new Map(), canvas: env.canvas, image: env.image });
+ env.cache.set(key, L); return L;
+};
+const mosaic = (env: Env): string[] => {
+ const key = "bb/mosaic"; let m = env.cache.get(key) as string[] | undefined; if (m) return m;
+ const Ls = env.canvas(NC * 4, NC * 4); renderFrame(balloon, Ls.ctx, 0, { W, H, scale: (NC * 4) / W, cache: new Map(), canvas: env.canvas, image: env.image });
+ const d = Ls.ctx.getImageData(0, 0, NC * 4, NC * 4).data, rgb = PAL.map((h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)));
+ m = [];
+ for (let cy = 0; cy < NC; cy++) for (let cx = 0; cx < NC; cx++) {
+ let R = 0, G = 0, B = 0; for (let y = 0; y < 4; y++) for (let x = 0; x < 4; x++) { const o = ((cy * 4 + y) * NC * 4 + cx * 4 + x) * 4; R += d[o]; G += d[o + 1]; B += d[o + 2]; }
+ R /= 16; G /= 16; B /= 16;
+ // crayon hatching is colour over paper: find the most saturated sample and lean the cell toward it
+ let sat = -1, sr = R, sg = G, sb = B; for (let y = 0; y < 4; y++) for (let x = 0; x < 4; x++) { const o = ((cy * 4 + y) * NC * 4 + cx * 4 + x) * 4, mx = Math.max(d[o], d[o + 1], d[o + 2]), mn = Math.min(d[o], d[o + 1], d[o + 2]), c = mx - mn; if (c > sat) { sat = c; sr = d[o]; sg = d[o + 1]; sb = d[o + 2]; } }
+ if (sat > 60) { R = 0.25 * R + 0.75 * sr; G = 0.25 * G + 0.75 * sg; B = 0.25 * B + 0.75 * sb; }
+ let best = 0, bd = 1e9; rgb.forEach(([r, g, b], k) => { const e = 0.3 * (r - R) ** 2 + 0.59 * (g - G) ** 2 + 0.11 * (b - B) ** 2; if (e < bd) { bd = e; best = k; } }); m.push(PAL[best]);
+ }
+ env.cache.set(key, m); return m;
+};
+// a 1x1 plate seen from above: the top, a darker lip right and below, the stud with its crescents
+const tile2d = (c: Ctx, x: number, y: number, s: number, col: string) => {
+ const g = s * 0.06;
+ c.fillStyle = shade(col, -0.25); c.fillRect(x + g, y + g, s - g, s - g);
+ c.fillStyle = col; c.fillRect(x, y, s - g * 1.6, s - g * 1.6);
+ const cx = x + s * 0.46, cy = y + s * 0.46, r = s * 0.3;
+ c.fillStyle = shade(col, -0.22); c.beginPath(); c.arc(cx + r * 0.16, cy + r * 0.2, r, 0, Math.PI * 2); c.fill();
+ c.fillStyle = shade(col, 0.12); c.beginPath(); c.arc(cx, cy, r, 0, Math.PI * 2); c.fill();
+ c.strokeStyle = shade(col, 0.5); c.lineWidth = Math.max(1, s * 0.05); c.beginPath(); c.arc(cx, cy, r * 0.72, Math.PI * 1.02, Math.PI * 1.55); c.stroke();
+};
+const popAt = (cx: number, cy: number) => T.waveA + (1 - (cy + 0.5) / NC) * (T.waveB - T.waveA - 10) + fractal(31, cx * 0.4, cy * 0.4, 1, 1, 2) * 8;
+const fallAt = (cx: number, cy: number) => T.fallA + (1 - (cy + 0.5) / NC) * 26 + fractal(32, cx * 0.5, cy * 0.5, 1, 1, 2) * 10;
+const drawMosaic = (ctx: Ctx, env: Env, f: number) => {
+ const m = mosaic(env), sc = env.scale; ctx.setTransform(sc, 0, 0, sc, 0, 0);
+ for (let cy = 0; cy < NC; cy++) for (let cx = 0; cx < NC; cx++) {
+ const t0 = popAt(cx, cy); if (f < t0) continue;
+ const u = (f - t0) / 7, pop = u >= 1 ? 1 : 1 + 0.35 * Math.sin(Math.PI * u) * (1 - u) - (1 - out3(u)) * 0.6;
+ const tf = fallAt(cx, cy), fall = f > tf ? f - tf : 0, drop = 0.9 * fall * fall, spin = fractal(33, cx, cy, 1, 1, 1) - 0.5;
+ if (drop > H + 60) continue;
+ const s = CELL * clamp(pop, 0, 1.3), x = cx * CELL + (CELL - s) / 2 + spin * fall * 2.2, y = cy * CELL + (CELL - s) / 2 + drop;
+ tile2d(ctx, x, y, s, m[cy * NC + cx]);
+ }
+};
+
+// ---------------------------------------------------------------- one frame
+const drawFrame = (ctx: Ctx, fr: number, env: Env) => {
+ const f = Math.min(fr, N - 1), sc = env.scale;
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1;
+ if (f < T.waveA) { ctx.drawImage(crayonLayer(env).canvas as CanvasImageSource, 0, 0); return; }
+ if (f < T.fallA) { ctx.drawImage(crayonLayer(env).canvas as CanvasImageSource, 0, 0); drawMosaic(ctx, env, f); return; }
+ const v = view(f), cam = camOf(v, sc), sky = ramp(f, T.world0, T.lift + 40);
+ ctx.fillStyle = sky > 0 ? mixHex(BACKDROP, SKY, smooth(sky)) : BACKDROP; ctx.fillRect(0, 0, W * sc, H * sc);
+ // the world tiles drop in around the launch plate, nearest first
+ WORLD.forEach((t) => { const L = T.world0 + t.d * 3.2; if (f < L - FALL) return; const u = clamp((f - (L - FALL)) / FALL), dyS = (1 - out3(u)) * 260 * v.z; blit(ctx, spriteOf(env, `t${t.i},${t.j}`, t.parts), v, sc, dyS, 0.35 + 0.65 * Math.min(1, u / 0.6)); });
+ // the launch plate: built part by part, then one sprite
+ if (f >= LAUNCH_LAND[LAUNCH_LAND.length - 1] + 2) blit(ctx, spriteOf(env, "launch", LAUNCH), v, sc);
+ else {
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ const live = LAUNCH.map((p, n) => { const L = LAUNCH_LAND[n]; if (f < L - FALL) return null; if (f >= L) return { p, dy: f === L ? -0.5 : 0, a: 1 }; const u = (f - (L - FALL)) / FALL; return { p, dy: DROP * (1 - out3(u)) * (n === 0 ? 2 : 1), a: 0.35 + 0.65 * Math.min(1, u / 0.6) }; }).filter((x): x is NonNullable<typeof x> => !!x);
+ const base = live.filter((s) => s.p.y0 < 0), rest = live.filter((s) => s.p.y0 >= 0);
+ base.forEach((s) => { ctx.globalAlpha = s.a; drawPart(ctx, cam, s.p, s.dy, HAIR * sc); ctx.globalAlpha = 1; });
+ if (base.length && rest.length) groundShadow(env, ctx, cam, rest.filter((s) => s.dy === 0).map((s) => s.p), 0.3);
+ order(rest.map((s) => ({ p: s.p, dy: s.dy })), cam).forEach((i) => { ctx.globalAlpha = rest[i].a; drawPart(ctx, cam, rest[i].p, rest[i].dy, HAIR * sc); ctx.globalAlpha = 1; });
+ }
+ // the balloon: its shadow on the ground, then back bars, basket, burner, flame, front bars, envelope
+ const b = balloonAt(f), bc = new Cam(cam.s, cam.ox + ((b.dx - b.dz) * 0.70711) * cam.s, cam.oy + ((b.dx + b.dz) * 0.35355) * cam.s), up = b.y;
+ if (f >= T.lift) {
+ // a high midday sun for the balloon's own shadow, so it stays in frame and grows apart from the
+ // basket as it climbs: the ground point slides down-light a fifth of the height
+ const R = R_MAX * 0.85, sh = up / STUD, gx = 8.5 + 0.08 * sh, gz = 8.5 - 0.17 * sh, disc: [number, number][] = Array.from({ length: 12 }, (_, k) => [gx + Math.cos((k / 12) * Math.PI * 2) * R, gz + Math.sin((k / 12) * Math.PI * 2) * R * 0.9]);
+ const shp: Part = { id: 0, color: "#000", kind: "prism", foot: disc, y0: 0, h: 0.1, studs: false, step: 0 };
+ groundShadow(env, ctx, bc, [shp], 0.46 - 0.16 * ramp(up, 0, 1100));
+ }
+ CLOUDS.filter((c) => !c.front).forEach((c) => drawCloud(ctx, env, c, v, f));
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ const bars = ramp(f, T.ropes, T.ropes + 6);
+ drawBars(ctx, bc, up, false, bars);
+ BASKET.forEach((p, n) => { const L = BASKET_LAND[n]; if (f < L - FALL) return; const u = f >= L ? 1 : (f - (L - FALL)) / FALL, dy = (f >= L ? (f === L ? -0.5 : 0) : DROP * (1 - out3(u))) + up; ctx.globalAlpha = f >= L ? 1 : 0.35 + 0.65 * Math.min(1, u / 0.6); drawPart(ctx, bc, p, dy, HAIR * sc); ctx.globalAlpha = 1; });
+ drawFlame(ctx, bc, up, f, ramp(f, T.fire, T.fire + 6) * (f < T.fire + 14 ? 0.6 + 0.4 * Math.sin((f - T.fire) * 1.3) ** 2 : 1));
+ drawBars(ctx, bc, up, true, bars);
+ for (let i = 0; i < COURSES; i++) {
+ const L = T.env0 + i * T.envStep; if (f < L - FALL) break;
+ const u = f >= L ? 1 : (f - (L - FALL)) / FALL, dy = f >= L ? (f === L ? -0.5 : 0) : DROP * (1 - out3(u));
+ drawCourse(ctx, bc, i, up, dy, f >= L ? 1 : 0.35 + 0.65 * Math.min(1, u / 0.6), HAIR * sc);
+ }
+ CLOUDS.filter((c) => c.front).forEach((c) => drawCloud(ctx, env, c, v, f));
+ // the mosaic's last tiles falling away over the build
+ if (f < T.fallB) drawMosaic(ctx, env, f);
+};
+
+export const STYLE = { id: "brickBalloon", name: "Toy brick, from crayon, flying", family: "rendered", medium: "the crayon balloon turned into a toy-brick mosaic, rebuilt in moulded ABS bricks, then flown over a brick world", nearest: "toyBrick", hero: "the crayon hot-air balloon rebuilt in bricks, lifting off", sceneOf: "toyBrick" };
+
+export const brickBalloon: Film = {
+ meta: { title: "Balloon · crayon to bricks, and away", W, H, fps: FPS, bpm: 90, durationFrames: N, raster: "cpu" },
+ assets: { images: {} },
+ shots: [{ id: "flight", start: 0, end: N, draw: drawFrame }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/camera.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/camera.ts
index e974309..0fad116 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/camera.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/camera.ts
@@ -11,7 +11,7 @@
// 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
+// 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).
// - A CLOSE SHOT MUST NOT FATTEN THE LINE. Ink is authored at some view; at zoom S the same nib
@@ -80,6 +80,7 @@ export class Camera {
private keys: CamKey[];
private path?: (f: number) => Cam;
private monoZoom: boolean;
+ private zoomPath?: (f: number) => number; // the monotone zoom path, built once from the keys (they never change)
// 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
@@ -100,7 +101,7 @@ export class Camera {
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 (log2 && this.monoZoom && ks.length > 1) return (this.zoomPath ??= 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++;
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 805e2b7..bc0e712 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts
+++ b/plugins/anidoodle/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/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/drafting.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/drafting.ts
index cc81018..4febd92 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/drafting.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/drafting.ts
@@ -4,9 +4,9 @@
// pen's smoothing cannot round a vertex); `c` strokes are curves.
import { Gfx, P, rng } from "./core";
-type Glyph = { l?: P[][]; c?: P[][]; w?: number };
+export type Glyph = { l?: P[][]; c?: P[][]; w?: number };
const O: P[] = [[1.3, 0.1], [0.2, 1.3], [0.2, 4.7], [1.3, 5.9], [2.7, 5.9], [3.8, 4.7], [3.8, 1.3], [2.7, 0.1], [1.3, 0.1]];
-const G: Record<string, Glyph> = {
+export const G: Record<string, Glyph> = {
A: { l: [[[0, 6], [2, 0], [4, 6]], [[0.9, 3.9], [3.1, 3.9]]] }, B: { l: [[[0, 0], [0, 6]]], c: [[[0, 0], [2.6, 0], [3.5, 0.8], [3.5, 2.2], [2.6, 3], [0, 3]], [[2.6, 3], [3.8, 3.8], [3.8, 5.1], [2.8, 6], [0, 6]]] },
C: { c: [[[3.8, 1.2], [2.8, 0.1], [1.3, 0.1], [0.2, 1.3], [0.2, 4.7], [1.3, 5.9], [2.8, 5.9], [3.8, 4.8]]] }, D: { l: [[[0, 0], [0, 6]]], c: [[[0, 0], [2.3, 0], [3.8, 1.5], [3.8, 4.5], [2.3, 6], [0, 6]]] },
E: { l: [[[3.6, 0], [0, 0], [0, 6], [3.7, 6]], [[0, 3], [2.8, 3]]] }, F: { l: [[[3.6, 0], [0, 0], [0, 6]], [[0, 3], [2.8, 3]]] },
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/embroidery.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/embroidery.ts
index f2f7ef2..95783bb 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/embroidery.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/embroidery.ts
@@ -37,28 +37,28 @@ import { LIGHT, drawShadows, drawThreads, fishbone, headOf, knot, knots, linenLa
// line with a direction, and tone comes from the direction of the stitches, not from colour fills.
const W = 1080, H = 1080, N = 540, HOLD = 30;
-const EMB_M: Medium = { nib: 1, taper: 0, pressure: 0, retrace: false, wobble: 0, rough: 0 };
-const HC: P = [540, 548], RO = 470, RI = 446; // the hoop
-const C: P = [540, 584], R = 294; // the wreath
-const G = { dark: "#4d6636", olive: "#6c7f3e", sage: "#8ea46a", light: "#b3c690", stem: "#5b6f3b", grey: "#8c9a79" };
-const WHITE = "#f7f3eb", SHELL = "#dcd4c3", BUTTER = "#f1c33d", OCHRE = "#cf8a1e";
+export const EMB_M: Medium = { nib: 1, taper: 0, pressure: 0, retrace: false, wobble: 0, rough: 0 };
+export const HC: P = [540, 548], RO = 470, RI = 446; // the hoop
+export const C: P = [540, 584], R = 294; // the wreath
+export const G = { dark: "#4d6636", olive: "#6c7f3e", sage: "#8ea46a", light: "#b3c690", stem: "#5b6f3b", grey: "#8c9a79" };
+export const WHITE = "#f7f3eb", SHELL = "#dcd4c3", BUTTER = "#f1c33d", OCHRE = "#cf8a1e";
const BLUE = "#6f98d2", BLUE2 = "#a2bfe6", LAV = "#8f7bc0", LAV2 = "#66529a";
-const POPPY = ["#f08566", "#e2553b", "#c43b2d", "#8b211c"];
-const GOLD = "#e4a62c", UMBER = "#2e231c", FUZZ = "#b0782f", SILVER = "#cfd6db";
+export const POPPY = ["#f08566", "#e2553b", "#c43b2d", "#8b211c"];
+export const GOLD = "#e4a62c", UMBER = "#2e231c", FUZZ = "#b0782f", SILVER = "#cfd6db";
-const rad = (d: number) => (d * Math.PI) / 180;
-const polar = (deg: number, r = R): P => [C[0] + Math.cos(rad(deg)) * r, C[1] + Math.sin(rad(deg)) * r];
-const unit = (x: number, y: number): P => { const l = Math.hypot(x, y) || 1; return [x / l, y / l]; };
-const rot = (p: P, a: number): P => [p[0] * Math.cos(a) - p[1] * Math.sin(a), p[0] * Math.sin(a) + p[1] * Math.cos(a)];
-const add = (a: P, b: P, k = 1): P => [a[0] + b[0] * k, a[1] + b[1] * k];
+export const rad = (d: number) => (d * Math.PI) / 180;
+export const polar = (deg: number, r = R): P => [C[0] + Math.cos(rad(deg)) * r, C[1] + Math.sin(rad(deg)) * r];
+export const unit = (x: number, y: number): P => { const l = Math.hypot(x, y) || 1; return [x / l, y / l]; };
+export const rot = (p: P, a: number): P => [p[0] * Math.cos(a) - p[1] * Math.sin(a), p[0] * Math.sin(a) + p[1] * Math.cos(a)];
+export const add = (a: P, b: P, k = 1): P => [a[0] + b[0] * k, a[1] + b[1] * k];
// the wreath line: a gentle wave on the circle. dir = +1 grows with increasing angle (left branch)
const wreathR = (deg: number) => R + 7 * Math.sin(rad(deg) * 3);
-const onWreath = (deg: number): P => polar(deg, wreathR(deg));
-const grow = (deg: number, dir: 1 | -1): P => { const a = onWreath(deg), b = onWreath(deg + dir * 1); return unit(b[0] - a[0], b[1] - a[1]); };
-const outward = (deg: number): P => [Math.cos(rad(deg)), Math.sin(rad(deg))];
+export const onWreath = (deg: number): P => polar(deg, wreathR(deg));
+export const grow = (deg: number, dir: 1 | -1): P => { const a = onWreath(deg), b = onWreath(deg + dir * 1); return unit(b[0] - a[0], b[1] - a[1]); };
+export const outward = (deg: number): P => [Math.cos(rad(deg)), Math.sin(rad(deg))];
// ---------------------------------------------------------------- plants
-type Section = { id: string; a: number; b: number; sts: St[] };
+export type Section = { id: string; a: number; b: number; sts: St[] };
const LEFT = { from: 102, to: 262, dir: 1 as const }, RIGHT = { from: 78, to: -30, dir: -1 as const };
const branchPath = (b: typeof LEFT | typeof RIGHT): P[] => { const out: P[] = []; for (let d = b.from; b.dir > 0 ? d <= b.to : d >= b.to; d += b.dir * 2) out.push(onWreath(d)); return out; };
// the two stems cross at the bottom, where they were tied
@@ -92,18 +92,18 @@ const outlineOf = (l: Leaf): P[] => {
const litSide = (l: Leaf): number => { const a = l.mid[0], b = l.mid[l.mid.length - 1], u = unit(b[0] - a[0], b[1] - a[1]); return -u[1] * LIGHT[0] + u[0] * LIGHT[1] > 0 ? -1 : 1; };
// POPPY: four petals seen three-quarter from above, the back pair larger, the front pair overlapping
-const PC: P = add(polar(127, R + 8), [0, 0]);
+export const PC: P = add(polar(127, R + 8), [0, 0]);
const petal = (cDeg: number, half: number, rad0: number, seed: number) => {
const arc: P[] = [], r = rng(seed), ph = r() * 6;
for (let k = 0; k <= 18; k++) { const f = k / 18, a = rad(cDeg - half + f * 2 * half), rr = rad0 * (1 + 0.07 * Math.sin(a * 7 + ph) - 0.2 * Math.pow(Math.abs(f - 0.5) * 2, 2.4)); const v = rot([Math.cos(a) * rr, Math.sin(a) * rr * 0.8], rad(-12)); arc.push(add(PC, v)); }
const inner = (a: number): P => add(PC, rot([Math.cos(rad(a)) * 11, Math.sin(rad(a)) * 9], rad(-12)));
return { arc, outline: [inner(cDeg - half * 0.5), ...arc, inner(cDeg + half * 0.5)], target: (p: P): P => lerpP(PC, p, 0.2) };
};
-const PETALS = [petal(-128, 62, 80, 1), petal(-42, 58, 76, 2), petal(150, 60, 70, 3), petal(48, 62, 72, 4)];
+export const PETALS = [petal(-128, 62, 80, 1), petal(-42, 58, 76, 2), petal(150, 60, 70, 3), petal(48, 62, 72, 4)];
// DAISY: rays from an inner to an outer radius, satin across each ray, then a knotted disc.
// `T` maps the flower's own disc into the page, which is how the three-quarter view is authored.
-const daisy = (T: (p: P) => P, n: number, r0: number, r1: number, seed: number, face = 1): St[] => {
+export const daisy = (T: (p: P) => P, n: number, r0: number, r1: number, seed: number, face = 1): St[] => {
const out: St[] = [], r = rng(seed);
for (let i = 0; i < n; i++) {
const a = (i / n) * Math.PI * 2 + r() * 0.12, len = (r1 - r0) * (0.86 + r() * 0.2), dir: P = [Math.cos(a), Math.sin(a)], bend = (r() - 0.5) * 0.3;
@@ -113,8 +113,8 @@ const daisy = (T: (p: P) => P, n: number, r0: number, r1: number, seed: number,
}
return out;
};
-const disc = (T: (p: P) => P, r: number, seed: number): St[] => knots(0, 0, r, r, 2.3, (u, v) => (u * 0.6 + v * 0.8 > 0.25 ? OCHRE : BUTTER), seed).map((k) => ({ ...k, a: T(k.a) }));
-const faceOn = (c: P, k = 1, squash = 1, tilt = 0) => (p: P): P => add(c, rot([p[0] * k, p[1] * k * squash], rad(tilt)));
+export const disc = (T: (p: P) => P, r: number, seed: number): St[] => knots(0, 0, r, r, 2.3, (u, v) => (u * 0.6 + v * 0.8 > 0.25 ? OCHRE : BUTTER), seed).map((k) => ({ ...k, a: T(k.a) }));
+export const faceOn = (c: P, k = 1, squash = 1, tilt = 0) => (p: P): P => add(c, rot([p[0] * k, p[1] * k * squash], rad(tilt)));
// FORGET-ME-NOTS: five round petals, a yellow eye, clustered on short stalks
const forgetMeNots = (deg: number, side: number, seed: number): { stems: St[]; petals: St[]; eyes: St[] } => {
@@ -131,7 +131,7 @@ const forgetMeNots = (deg: number, side: number, seed: number): { stems: St[]; p
return { stems, petals, eyes };
};
// LAVENDER: a bare stem, then a spike of knots in whorls, tighter to the tip
-const lavender = (deg: number, seed: number): { stem: St[]; spike: St[] } => {
+export const lavender = (deg: number, seed: number): { stem: St[]; spike: St[] } => {
const r = rng(seed), base = onWreath(deg), o = outward(deg), g = grow(deg, deg >= 90 ? 1 : -1), d = unit(o[0] * 0.8 + g[0] * 0.6, o[1] * 0.8 + g[1] * 0.6), n: P = [-d[1], d[0]], len = 96 + r() * 16, bend = (r() - 0.5) * 0.3;
const path = [base, add(add(base, d, len * 0.5), n, bend * 10), add(add(base, d, len), n, bend * 22)], spine = resample(smooth(path, false, 6), 40);
const spike: St[] = [];
@@ -141,9 +141,9 @@ const lavender = (deg: number, seed: number): { stem: St[]; spike: St[] } => {
};
// ---------------------------------------------------------------- the bee
-const BEE: P = [650, 300], HEAD = rad(33), BS = 1.42;
+export const BEE: P = [650, 300], HEAD = rad(33), BS = 1.42;
const B = (x: number, y: number): P => add(BEE, rot([x * BS, y * BS], HEAD));
-const bee = () => {
+export const bee = () => {
const abdomen: St[] = [], thorax: St[] = [], head: St[] = [], legs: St[] = [], wings: St[] = [], r = rng(77);
// abdomen: six bands, satin across the body, the band edges bowing toward the tail with the roundness
const x0 = 1, x1 = -66, hw = (u: number) => 21 * Math.pow(Math.sin(Math.PI * clamp(0.1 + u * 0.88)), 0.6) * (1 - 0.25 * u);
@@ -175,7 +175,7 @@ const bee = () => {
const FLIGHT: P[] = [[262, 300], [290, 226], [352, 186], [398, 222], [372, 262], [334, 232], [366, 176], [436, 146], [500, 160], [542, 196], [566, 226]];
// ---------------------------------------------------------------- the timeline: one cue table
-const build = (): Section[] => {
+export const build = (): Section[] => {
const leaves = LEAVES.map(leafOf), bigLeaves = leaves.filter((l) => l.big), small = leaves.filter((l) => !l.big);
const fmn = [forgetMeNots(150, 1, 11), forgetMeNots(213, -1, 12), forgetMeNots(47, 1, 13), forgetMeNots(-3, -1, 14)];
const lav = [lavender(167, 21), lavender(233, 22), lavender(63, 23), lavender(8, 24)];
@@ -224,10 +224,10 @@ const timeline = (secs: Section[]): Timed[] => secs.flatMap((s) => {
((): void => { let t = 5; for (const s of build()) { if (s.a !== t || s.b <= s.a) throw new Error(`embroidery: section ${s.id} ${s.a}-${s.b} does not follow ${t}`); t = s.b; } if (t !== 505 || N % 15 || N - HOLD !== 510) throw new Error("embroidery: timeline does not end at 505 before the park and hold"); })();
// ---------------------------------------------------------------- the sheet in the hoop
-const cached = <T,>(env: Env, key: string, fn: () => T): T => { let v = env.cache.get(key) as T | undefined; if (v === undefined) { v = fn(); env.cache.set(key, v); } return v; };
-const DWH = (env: Env): [number, number] => [Math.round(env.W * env.scale), Math.round(env.H * env.scale)];
+export const cached = <T,>(env: Env, key: string, fn: () => T): T => { let v = env.cache.get(key) as T | undefined; if (v === undefined) { v = fn(); env.cache.set(key, v); } return v; };
+export const DWH = (env: Env): [number, number] => [Math.round(env.W * env.scale), Math.round(env.H * env.scale)];
const STRIDE = 180; // stitches per cached checkpoint
-const drawRun = (L: Layer, env: Env, sts: St[], lastP = 1) => {
+export const drawRun = (L: Layer, env: Env, sts: St[], lastP = 1) => {
if (!sts.length) return;
const g = new Gfx(L.ctx, env, 0, EMB_M); let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const s of sts) { x0 = Math.min(x0, s.a[0], s.b[0]); y0 = Math.min(y0, s.a[1], s.b[1]); x1 = Math.max(x1, s.a[0], s.b[0]); y1 = Math.max(y1, s.a[1], s.b[1]); }
g.group("plain", () => { g.touch(x0 - 8, y0 - 8, x1 + 10, y1 + 10); drawShadows(g.cur, sts, lastP); }, { blur: 0.9 });
@@ -243,13 +243,13 @@ const checkpoint = (env: Env, all: Timed[], k: number): Layer | null => {
return L;
};
-const ground = (env: Env): Layer => linenLayer(env, "hoop", 4.2, [224, 211, 186], (x, y) => {
+export const ground = (env: Env): Layer => linenLayer(env, "hoop", 4.2, [224, 211, 186], (x, y) => {
const d = Math.hypot(x - HC[0], y - HC[1]);
if (d < RI) return 1.03 - 0.05 * (d / RI) ** 2; // drum-tight inside the hoop
const fold = Math.sin((x * 0.8 + y * 0.35) * 0.012 + Math.sin(y * 0.01) * 1.6); // slack cloth outside it, in soft folds
return 0.84 + 0.07 * fold;
});
-const hoop = (env: Env): Layer => cached(env, `emb:hoop:${env.scale}:${env.W}x${env.H}`, () => {
+export const hoop = (env: Env): Layer => cached(env, `emb:hoop:${env.scale}:${env.W}x${env.H}`, () => {
const [dw, dh] = DWH(env), L = env.canvas(dw, dh), c = L.ctx, s = env.scale; c.setTransform(s, 0, 0, s, 0, 0);
const ring = (dx: number, dy: number, r0: number, r1: number) => { c.beginPath(); c.arc(HC[0] + dx, HC[1] + dy, r1, 0, Math.PI * 2); c.arc(HC[0] + dx, HC[1] + dy, r0, 0, Math.PI * 2, true); };
// the ring's shadow: inside at upper left, outside at lower right; soft by stacking offset copies
@@ -274,7 +274,7 @@ const hoop = (env: Env): Layer => cached(env, `emb:hoop:${env.scale}:${env.W}x${
});
// the needle, and the working thread from its eye
-const needle = (c: Ctx, tip: P, dir: P, colour: string, parked: boolean) => {
+export const needle = (c: Ctx, tip: P, dir: P, colour: string, parked: boolean) => {
const len = 52, back = add(tip, dir, -len), n: P = [-dir[1], dir[0]], tail = add(back, dir, -4);
c.save(); c.lineCap = "round";
const thread = parked ? [tail, add(tail, [-40, 30]), add(tail, [-10, 76]), add(tail, [-62, 96])] : [tail, add(add(tail, dir, -30), n, 18), add(add(tail, dir, -58), n, 8), add(add(tail, dir, -84), n, 30)];
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/embroideryAlive.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/embroideryAlive.ts
new file mode 100644
index 0000000..c469658
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/embroideryAlive.ts
@@ -0,0 +1,224 @@
+import { Gfx, rng, type Ctx, type Env, type Layer, type P } from "./core";
+import type { Film } from "./film";
+import { clamp, lerp, lerpP, resample, smooth } from "./gallery";
+import { drawShadows, drawThreads, knot, longShort, satin, splitStitch, stemStitch, straight, type St } from "./embroideryKit";
+import { BEE, BS, BUTTER, C, EMB_M, G, GOLD, HEAD, OCHRE, PC, PETALS, POPPY, R, SILVER, add, bee, build, cached, daisy, disc, DWH, drawRun, faceOn, ground, hoop, lavender, onWreath, polar, rad, rot } from "./embroidery";
+
+// THE WREATH, ALIVE · a seamless 8 s loop of the embroidery plate.
+//
+// Everything stays thread. Nothing here warps pixels: every frame the stitches themselves are
+// re-posed (a stitch is two holes and a colour, so bending a stem means moving its holes along the
+// bend) and drawn again with the plate's own thread renderer, so each one keeps its twist, its sheen
+// toward the window at upper left, and its hair of shadow down and right.
+//
+// THE STORY OF THE LOOP (240 frames, 90 bpm: a beat is 20 frames):
+// 0-36 the bee sits on the poppy, wings folded, one flick of the wings.
+// 36-56 it lifts off the linen: its shadow slides away and softens as it rises.
+// 36-206 it flies once round the wreath (up the left side past the daisy and the lavender, a
+// loop-the-loop in the gap at the top, down the right side past two more daisies, back
+// along the bottom). Behind it the needle sews its flight line in gold running stitch,
+// and the oldest stitches unpick themselves, so the line stays one length.
+// Every flower it passes nods in its wake (a damped swing about the stem's base, the stem
+// bending with it), daisy rays flutter, the lavender keeps a slow sway of its own.
+// 206 it lands back on the poppy: the head dips under its weight and springs back, and a puff
+// of pollen pops out as French knots that rise, drift and unpick.
+// 206-240 the rest of the line unpicks; the frame after 239 is frame 0.
+// WINGS: straight stitches, re-stitched at two angles on twos (the embroiderer's motion blur), the
+// other angle ghosted in fainter thread.
+// DEPTH: the bee's shadow is its own stitches' shadow, pushed further away and softened by height.
+
+const W = 1080, H = 1080, N = 240, TAKE = 36, LAND = 206, UNPICKED = 236;
+
+// ---------------------------------------------------------------- the moving flowers, as groups
+type Group = { id: string; base: P; head: P; sts: St[]; flutter?: { c: P; r: number }; sway: number; phase: number };
+const flowerStem = (deg: number, to: P, seed: number) => stemStitch([onWreath(deg), lerpP(onWreath(deg), to, 0.5), to], 8, 2.2, G.stem, seed);
+const groups = (): Group[] => {
+ const D1 = faceOn(polar(189, R + 20), 1.22), D2 = faceOn(polar(27, R + 16), 1.18, 0.52, -24), D3 = faceOn(polar(-21, R + 8), 0.92, 0.92, 8);
+ const daisyGroup = (id: string, T: (p: P) => P, deg: number, stemSeed: number, rays: St[], d: St[], r1: number): Group => ({ id, base: onWreath(deg), head: T([0, 0]), sts: [...flowerStem(deg, T([0, 0]), stemSeed), ...rays, ...d], flutter: { c: T([0, 0]), r: r1 }, sway: 0, phase: deg * 0.05 });
+ const poppy: St[] = [
+ ...flowerStem(122, PC, 34), ...PETALS.flatMap((p) => splitStitch(p.arc, 5, 2, POPPY[3])), ...PETALS.flatMap((p, i) => longShort(p.arc, p.target, 4, 2.3, 2.2, POPPY, 300 + i)),
+ ...satin([add(PC, [-9, 0]), PC, add(PC, [9, 0])], (t) => 8 * Math.sin(Math.PI * clamp(t * 0.85 + 0.08)), 2.1, 2, () => "#7d8f4b"),
+ ...Array.from({ length: 8 }, (_, k) => straight(PC, add(PC, rot([7, 0], (k / 8) * Math.PI * 2)), 1.3, "#2d2723")),
+ ...Array.from({ length: 16 }, (_, k) => knot(add(PC, rot([15 + (k % 2) * 3, 0], (k / 16) * Math.PI * 2 + 0.2)), 2.2, "#221d1a")),
+ ];
+ const lav = ([[167, 21], [233, 22], [63, 23], [8, 24]] as const).map(([deg, seed], i): Group => {
+ const l = lavender(deg, seed), all = [...l.stem, ...l.spike], base = onWreath(deg);
+ let head = base, far = 0; for (const s of all) for (const p of [s.a, s.b]) { const d = Math.hypot(p[0] - base[0], p[1] - base[1]); if (d > far) { far = d; head = p; } }
+ return { id: `lav${i}`, base, head, sts: all, sway: 0.05, phase: i * 1.7 };
+ });
+ return [
+ daisyGroup("d1", D1, 186, 30, daisy(D1, 19, 11, 48, 40), disc(D1, 11, 50), 48 * 1.22),
+ daisyGroup("d2", D2, 30, 31, daisy(D2, 17, 11, 46, 41, 0.6), disc(D2, 11, 51), 46 * 1.18),
+ daisyGroup("d3", D3, -16, 32, daisy(D3, 15, 9, 38, 42), disc(D3, 9, 52), 38 * 0.92),
+ { id: "poppy", base: onWreath(122), head: PC, sts: poppy, sway: 0, phase: 2.2 },
+ ...lav,
+ ];
+};
+// the plate minus the bee, its flight line and everything that moves: stitched once into the linen
+const key = (s: St) => `${s.k}|${s.a[0].toFixed(3)},${s.a[1].toFixed(3)}|${s.b[0].toFixed(3)},${s.b[1].toFixed(3)}|${s.w}|${s.c}`;
+const staticStitches = (gs: Group[]): St[] => {
+ const moving = new Map<string, number>(); for (const g of gs) for (const s of g.sts) moving.set(key(s), (moving.get(key(s)) ?? 0) + 1);
+ const bees = new Set(["flight", "abdomen", "thorax", "head", "legs", "wings"]), out: St[] = [];
+ for (const sec of build()) { if (bees.has(sec.id)) continue; for (const s of sec.sts) { const k = key(s), n = moving.get(k) ?? 0; if (n > 0) moving.set(k, n - 1); else out.push(s); } }
+ const left = [...moving.values()].reduce((a, b) => a + b, 0); if (left) throw new Error(`embroideryAlive: ${left} moving stitches not found in the plate`); // a group that drifted from the plate would draw twice
+ return out;
+};
+
+// ---------------------------------------------------------------- the flight
+// the bee sits with its head on the poppy's seed pod, its body lying back across the petals
+const REST_HEADING = rad(-118), SIZE = 0.82;
+const PERCH: P = add(PC, [Math.cos(REST_HEADING) * -56, Math.sin(REST_HEADING) * -56]);
+// the round: kept well inside the hoop (the bee is 120 px long), past every flower worth nodding
+const FLIGHT: P[] = [PERCH, [352, 790], [306, 660], [288, 536], [318, 424], [378, 338], [448, 288], [502, 250], [560, 262], [568, 322], [522, 340], [494, 296], [542, 248], [630, 250], [718, 298], [780, 398], [800, 520], [782, 640], [720, 758], [640, 838], [548, 884], [470, 906], [428, 900], PERCH];
+type Path = { pts: P[]; step: number; len: number };
+const path = (): Path => { const sm = smooth(FLIGHT, false, 18); let len = 0; for (let i = 1; i < sm.length; i++) len += Math.hypot(sm[i][0] - sm[i - 1][0], sm[i][1] - sm[i - 1][1]); const n = Math.round(len / 1.5), pts = resample(sm, n); return { pts, step: len / (n - 1), len }; };
+const at = (pa: Path, s: number): P => { const x = clamp(s / pa.step, 0, pa.pts.length - 1), i = Math.min(pa.pts.length - 2, Math.floor(x)); return lerpP(pa.pts[i], pa.pts[i + 1], x - i); };
+const tangent = (pa: Path, s: number): number => { const a = at(pa, s - 9), b = at(pa, s + 9); return Math.atan2(b[1] - a[1], b[0] - a[0]); };
+const ease = (t: number) => { const c = clamp(t); return c * c * (3 - 2 * c); };
+// where along the line the bee is: still until take-off, a soft start, cruising, a soft landing
+const RAMP = 16; // frames of speeding up and of slowing down: a trapezoid of speed, cruising between
+const travel = (t: number) => { const T = LAND - TAKE, v = 1 / (T - RAMP), c = clamp(t, 0, T); return c < RAMP ? (0.5 * v * c * c) / RAMP : c > T - RAMP ? 1 - (0.5 * v * (T - c) ** 2) / RAMP : v * (c - RAMP / 2); };
+const sAt = (pa: Path, f: number) => (f < TAKE ? 0 : f >= LAND ? pa.len : pa.len * travel(f - TAKE));
+const height = (f: number) => 30 * ease((f - TAKE) / 20) * (1 - ease((f - (LAND - 16)) / 16)) + (f > TAKE && f < LAND ? 3 * Math.sin(((f - TAKE) / 20) * Math.PI) * ease((f - TAKE) / 20) * (1 - ease((f - (LAND - 16)) / 16)) : 0);
+const perched = (f: number) => 1 - ease((f - TAKE) / 14) + ease((f - (LAND - 12)) / 12); // 1 on the poppy, 0 in the air
+const angDiff = (a: number, b: number) => { let d = b - a; while (d > Math.PI) d -= Math.PI * 2; while (d < -Math.PI) d += Math.PI * 2; return d; };
+
+// a damped swing started at frame fp, periodic over the loop (it has died away long before it comes round)
+const swing = (f: number, fp: number, tau = 18, period = 24) => { const d = (((f - fp) % N) + N) % N; return Math.exp(-d / tau) * Math.sin((d / period) * Math.PI * 2); };
+
+type Plan = { pa: Path; gs: Group[]; pass: { fp: number; amp: number; sign: number }[]; bodyLocal: St[] };
+const plan = (): Plan => {
+ const pa = path(), gs = groups();
+ const pass = gs.map((g) => {
+ if (g.id === "poppy") return { fp: LAND, amp: 0, sign: 1 };
+ let best = 1e9, fp = 0;
+ for (let f = TAKE; f < LAND; f++) { const p = at(pa, sAt(pa, f)), d = Math.hypot(p[0] - g.head[0], p[1] - g.head[1]); if (d < best) { best = d; fp = f; } }
+ const v = [Math.cos(tangent(pa, sAt(pa, fp))), Math.sin(tangent(pa, sAt(pa, fp)))], arm = [g.head[0] - g.base[0], g.head[1] - g.base[1]];
+ return { fp, amp: 0.3 * Math.exp(-((best / 120) ** 2)) + 0.04, sign: Math.sign(arm[0] * v[1] - arm[1] * v[0]) || 1 }; // the draft pushes the head the way the bee flew
+ });
+ // the bee's body in its own frame (x toward the head, scaled as authored), wings made fresh per frame
+ const b = bee(), bodyLocal = [...b.abdomen, ...b.thorax, ...b.head, ...b.legs].map((s) => ({ ...s, a: rot([s.a[0] - BEE[0], s.a[1] - BEE[1]], -HEAD), b: rot([s.b[0] - BEE[0], s.b[1] - BEE[1]], -HEAD) }));
+ return { pa, gs, pass, bodyLocal };
+};
+
+// ---------------------------------------------------------------- posing
+// bend a flower: each hole turns about the stem's base by the swing times how far up the stem it is
+const bend = (g: Group, theta: number, dip: number, flutter: number, f: number) => (s: St): St => {
+ const ax = g.head[0] - g.base[0], ay = g.head[1] - g.base[1], L2 = ax * ax + ay * ay;
+ const mv = (p: P): P => {
+ let q = p;
+ if (g.flutter && flutter) { const dx = p[0] - g.flutter.c[0], dy = p[1] - g.flutter.c[1], r = Math.hypot(dx, dy); if (r > g.flutter.r * 0.22) { const a = Math.atan2(dy, dx), phi = flutter * Math.sin(a * 3 + f * 0.9) * clamp(r / g.flutter.r); q = add(g.flutter.c, rot([dx, dy], phi)); } }
+ const u = clamp(((q[0] - g.base[0]) * ax + (q[1] - g.base[1]) * ay) / L2, 0, 1.3), k = Math.pow(u, 1.6), th = theta * k;
+ q = add(g.base, rot([q[0] - g.base[0], q[1] - g.base[1]], th));
+ if (dip && u > 0.8) { const hc = add(g.base, rot([ax, ay], theta)), sc = 1 - 0.06 * dip; q = [hc[0] + (q[0] - hc[0]) * sc + 3 * dip, hc[1] + (q[1] - hc[1]) * sc + 4 * dip]; }
+ return q;
+ };
+ return { ...s, a: mv(s.a), b: s.k === "knot" ? mv(s.a) : mv(s.b) };
+};
+
+// the wings, re-stitched: forewing larger over the hindwing's leading edge, swept back by `back`
+const WING_EDGE = "#a9b3ba";
+const wings = (sweep: number, spread: number, col = 1): St[] => {
+ const out: St[] = [];
+ const wing = (s: number, len: number, wd: number, back: number, rootX: number) => {
+ const root: P = [rootX * BS, s * 9 * BS], dir: P = [-Math.cos(rad(back)), s * Math.sin(rad(back))], nrm: P = [-dir[1] * s, dir[0] * s];
+ const pt = (fq: number, gq: number): P => add(add(root, dir, len * BS * fq / 1.42), nrm, wd * spread * BS * gq / 1.42);
+ const edge = smooth([pt(0, 0), pt(0.3, 0.55), pt(0.7, 0.62), pt(0.98, 0.25), pt(0.95, -0.15), pt(0.6, -0.32), pt(0.25, -0.22), pt(0, 0)], false, 6);
+ const c = (x: string) => (col < 1 ? "#dde2e4" : x);
+ out.push(...splitStitch(edge, 6, 1.5, c(WING_EDGE)));
+ out.push(straight(pt(0.05, 0.05), pt(0.7, 0.3), 1.2, c(SILVER)), straight(pt(0.1, 0), pt(0.85, 0.02), 1.2, c(SILVER)), straight(pt(0.3, 0.15), pt(0.55, -0.2), 1.1, c(SILVER)));
+ for (let k = 0; k < 7; k++) { const fq = 0.2 + k * 0.1, g0 = -0.25 + (k % 2) * 0.1; out.push(straight(pt(fq, g0), pt(fq + 0.12, 0.5 - (k % 3) * 0.08), 1.1, c(k % 2 ? "#eef1f2" : SILVER))); }
+ };
+ for (const s of [-1, 1]) { wing(s, 58, 26, 64 + sweep, 12); wing(s, 82, 34, 40 + sweep, 16); }
+ return out;
+};
+const place = (sts: St[], pos: P, heading: number, sc: number): St[] => sts.map((s) => ({ ...s, a: add(pos, rot([s.a[0] * sc, s.a[1] * sc], heading)), b: add(pos, rot([s.b[0] * sc, s.b[1] * sc], heading)), w: s.k === "knot" ? s.w * sc : s.w * Math.sqrt(sc) }));
+
+// ---------------------------------------------------------------- drawing helpers
+// the needle, as the plate draws it (steel, a lit edge, the eye), with its gold thread running from
+// the eye straight down into the newest stitch's hole, which is what a needle mid-sew looks like
+const drawNeedle = (c: Ctx, tip: P, dir: P, thread: P[]) => {
+ const back = add(tip, dir, -52), n: P = [-dir[1], dir[0]];
+ c.save(); c.lineCap = "round";
+ const th = smooth(thread, false, 8);
+ c.globalAlpha = 0.3; c.strokeStyle = "#3b2c1c"; c.lineWidth = 2.6; c.beginPath(); th.forEach(([x, y], i) => (i ? c.lineTo(x + 2, y + 3) : c.moveTo(x + 2, y + 3))); c.stroke();
+ c.globalAlpha = 1; c.strokeStyle = GOLD; c.lineWidth = 2.2; c.beginPath(); th.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke();
+ c.globalAlpha = 0.35; c.strokeStyle = "#2b1d10"; c.lineWidth = 3; c.beginPath(); c.moveTo(back[0] + 5, back[1] + 7); c.lineTo(tip[0] + 5, tip[1] + 7); c.stroke(); // it rides a little off the cloth
+ c.globalAlpha = 1; c.strokeStyle = "#8d949a"; c.lineWidth = 2.6; c.beginPath(); c.moveTo(back[0], back[1]); c.lineTo(tip[0], tip[1]); c.stroke();
+ c.strokeStyle = "#f5f7f8"; c.lineWidth = 0.9; c.beginPath(); c.moveTo(back[0] + n[0] * 0.6, back[1] + n[1] * 0.6); c.lineTo(tip[0] + n[0] * 0.6, tip[1] + n[1] * 0.6); c.stroke();
+ c.fillStyle = "#3b3f42"; c.beginPath(); c.ellipse(back[0] + dir[0] * 4, back[1] + dir[1] * 4, 2.6, 0.7, Math.atan2(dir[1], dir[0]), 0, Math.PI * 2); c.fill();
+ c.restore();
+};
+const box = (sts: St[]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const s of sts) { x0 = Math.min(x0, s.a[0], s.b[0]); y0 = Math.min(y0, s.a[1], s.b[1]); x1 = Math.max(x1, s.a[0], s.b[0]); y1 = Math.max(y1, s.a[1], s.b[1]); } return [x0, y0, x1, y1]; };
+// stitches standing `h` off the cloth: their shadow further away and softer, the thread itself unchanged
+const aloft = (g: Gfx, sts: St[], h: number, alpha = 1) => {
+ if (!sts.length) return; const [x0, y0, x1, y1] = box(sts), o: P = [h * 0.55, h * 0.8];
+ g.group("plain", () => { g.touch(x0 - 10, y0 - 10, x1 + 12, y1 + 12); drawShadows(g.cur, sts); }, { blur: 0.9 + h * 0.07, alpha: alpha * (1 - h * 0.011), off: o });
+ g.group("plain", () => { g.touch(x0 - 6, y0 - 6, x1 + 6, y1 + 6); drawThreads(g.cur, sts); }, { alpha });
+};
+// the gold flight line: stitch holes fixed along the path (they never slide), shown between the
+// unpicking tail and the needle; the newest stitch is still being pulled, the oldest being pulled out
+const DASH = 10, GAP = 6;
+const flightLine = (pa: Path, s0: number, s1: number): St[] => {
+ const out: St[] = []; if (s1 - s0 < 0.5) return out;
+ for (let k = Math.floor(s0 / (DASH + GAP)); k * (DASH + GAP) < s1; k++) { const a = Math.max(s0, k * (DASH + GAP)), b = Math.min(s1, k * (DASH + GAP) + DASH); if (b - a > 0.6) out.push({ k: "flat", a: at(pa, a), b: at(pa, b), w: 2.8, c: GOLD, t: 0.8 }); }
+ return out;
+};
+
+export const drawEmbroideryAlive = (ctx: Ctx, fr: number, env: Env) => {
+ const f = ((fr % N) + N) % N, pl = cached(env, "embA:plan", plan), [dw, dh] = DWH(env);
+ const still = cached(env, `embA:static:${env.scale}:${env.W}x${env.H}`, (): Layer => { const L = env.canvas(dw, dh); L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.drawImage(ground(env).canvas as CanvasImageSource, 0, 0); drawRun(L, env, staticStitches(pl.gs)); return L; });
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
+ ctx.drawImage(still.canvas as CanvasImageSource, 0, 0);
+ const me: Layer = { canvas: ctx.canvas as unknown as Layer["canvas"], ctx };
+
+ // the flowers, each on its swing
+ const land = swing(f, LAND, 16, 26), lift = swing(f, TAKE + 2, 14, 22);
+ // a flower at rest is blitted from its own cached stitching; only the ones swinging are re-stitched
+ const posed = pl.gs.flatMap((g, i) => {
+ const p = pl.pass[i], amb = g.sway * Math.sin((f / N) * Math.PI * 2 * (i % 2 ? 2 : 1) + g.phase);
+ let th: number, dip = 0, fl = 0;
+ if (g.id === "poppy") { dip = Math.max(0, land) * 1.0 + Math.max(0, -lift) * 0.35; th = amb + 0.05 * land - 0.03 * lift; }
+ else { th = amb + p.amp * p.sign * swing(f, p.fp - 3, 20, 26); fl = g.flutter ? 0.1 * Math.exp(-(((((f - p.fp) % N) + N) % N) / 16)) * p.amp * 5 : 0; }
+ if (Math.abs(th) < 0.0015 && dip < 0.01 && fl < 0.001) { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(cached(env, `embA:rest:${g.id}:${env.scale}:${env.W}x${env.H}`, () => { const L = env.canvas(dw, dh); drawRun(L, env, g.sts); return L; }).canvas as CanvasImageSource, 0, 0); return []; }
+ return g.sts.map(bend(g, th, dip, fl, f));
+ });
+ drawRun(me, env, posed);
+
+ // the flight line, then the pollen (on and just off the cloth)
+ const sB = sAt(pl.pa, f), BACK = 152, head = f < TAKE ? 0 : f >= LAND ? pl.pa.len - BACK : Math.max(0, sB - BACK), LT = 360;
+ const tail = f < TAKE ? 0 : f < LAND ? Math.max(0, head - LT) : lerp(Math.max(0, pl.pa.len - BACK - LT), pl.pa.len - BACK, ease((f - LAND) / (UNPICKED - LAND)));
+ const g = new Gfx(ctx, env, 0, EMB_M);
+ drawRun(me, env, flightLine(pl.pa, tail, f < TAKE ? 0 : head));
+ const dP = (((f - LAND) % N) + N) % N;
+ if (dP < 50) {
+ const r = rng(612), pollen: St[] = [], rise = 26 * Math.sin(Math.PI * clamp(dP / 50));
+ for (let i = 0; i < 22; i++) { const a = (i / 22) * Math.PI * 2 + r() * 0.35, dist = 8 + (40 + r() * 38) * (1 - Math.pow(1 - clamp(dP / 22), 3)), drift: P = [-dP * 0.3, -dP * 0.55], rad0 = (3 + r() * 1.6) * clamp(dP / 4) * (1 - ease((dP - 24 - r() * 10) / 16)); if (rad0 > 0.2) pollen.push(knot(add(add(PC, [Math.cos(a) * dist, Math.sin(a) * dist * 0.85]), drift), rad0, [BUTTER, OCHRE, "#f5d36a"][i % 3])); }
+ aloft(g, pollen, rise);
+ }
+
+ // the needle, sewing just behind the bee; on the poppy it rests on the linen beside it
+ const perch = clamp(perched(f)), sN = clamp(sB - 94, 0, pl.pa.len), rest: P = add(PERCH, [58, 30]), fly = at(pl.pa, sN);
+ const tip = lerpP(fly, rest, perch), tn = tangent(pl.pa, sN), ang = tn + angDiff(tn, REST_HEADING + 0.35) * perch;
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ const nd: P = [Math.cos(ang), Math.sin(ang)], eye = add(tip, nd, -52), last = f >= TAKE && head > 0 ? at(pl.pa, head) : add(eye, [-14, 10]);
+ drawNeedle(ctx, tip, nd, [eye, lerpP(eye, last, 0.5), last]);
+
+ // the bee
+ const h = height(f), hd0 = tangent(pl.pa, sB), heading = REST_HEADING + angDiff(REST_HEADING, hd0) * (1 - perch);
+ const dipOff: P = [3 * Math.max(0, land) * perch, 4 * Math.max(0, land) * perch];
+ const pos = add(at(pl.pa, sB), dipOff), sc = SIZE * (1 + h * 0.0045);
+ const flying = h > 1.5, flick = (f >= 8 && f < 16) || (f >= 222 && f < 230), twos = Math.floor(f / 2) % 2;
+ const up = flying || flick ? (twos ? { sweep: -26, spread: 0.55 } : { sweep: 10, spread: 1.05 }) : { sweep: 30, spread: 0.72 }, other = twos ? { sweep: 10, spread: 1.05 } : { sweep: -26, spread: 0.55 };
+ const body = place(pl.bodyLocal, pos, heading, sc), wing = place(wings(up.sweep, up.spread), pos, heading, sc);
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(hoop(env).canvas as CanvasImageSource, 0, 0);
+ if (flying || flick) aloft(g, place(wings(other.sweep, other.spread, 0.5), pos, heading, sc), h + 2, 0.4);
+ aloft(g, body, h); aloft(g, wing, h + 2);
+ void C; void H; void W;
+};
+
+export const embroideryAlive: Film = {
+ meta: { title: "A wreath and a bee · embroidery, alive", W, H, fps: 30, bpm: 90, durationFrames: N, kind: "loop" },
+ assets: { images: {} },
+ shots: [{ id: "alive", start: 0, end: N, draw: drawEmbroideryAlive }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts
index 9fb1575..64a8602 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts
@@ -41,10 +41,22 @@ export const validate = (film: Film): string[] => {
};
export const shotAt = (film: Film, frame: number): Shot | undefined => film.shots.find((s) => frame >= s.start && frame < s.end);
+// Every frame starts from a DEFAULT context, whatever the last frame left behind: a lineJoin, a dash,
+// a font or an unmatched save() leaking from frame 86 into frame 109 makes 109 depend on the order
+// frames were asked for (measured on brickBalloon inside the launch film). reset() is the whole
+// state in one call; the fallback names every property a 2D context carries.
+const freshState = (ctx: Ctx) => {
+ const c = ctx as Ctx & { reset?: () => void };
+ if (typeof c.reset === "function") { c.reset(); return; }
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
+ ctx.fillStyle = "#000"; ctx.strokeStyle = "#000"; ctx.lineWidth = 1; ctx.lineCap = "butt"; ctx.lineJoin = "miter"; ctx.miterLimit = 10;
+ ctx.setLineDash([]); ctx.lineDashOffset = 0; ctx.font = "10px sans-serif"; ctx.textAlign = "start"; ctx.textBaseline = "alphabetic"; ctx.direction = "inherit";
+ ctx.shadowBlur = 0; ctx.shadowColor = "rgba(0, 0, 0, 0)"; ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 0; ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "low";
+};
export const renderFrame = (film: Film, ctx: Ctx, frame: number, env: Env): string | null => {
const s = shotAt(film, Math.max(0, Math.min(film.meta.durationFrames - 1, Math.round(frame))));
if (!s) return null;
- ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; ctx.clearRect(0, 0, env.W * env.scale, env.H * env.scale);
+ freshState(ctx); ctx.clearRect(0, 0, env.W * env.scale, env.H * env.scale);
s.draw(ctx, frame - s.start, env);
return s.id;
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kinetic.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kinetic.ts
new file mode 100644
index 0000000..0275fec
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kinetic.ts
@@ -0,0 +1,387 @@
+// KINETIC. Illustrated, animated display lettering for the launch film: every word is written, a
+// stroke at a time, by a visible tool in one of anidoodle's own media, and every letter lands with
+// a little life (a pop as it completes, its own tilt and baseline). No font draws the display type:
+// the skeletons are drafting.ts's single-stroke capitals (G), the medium is all here.
+//
+// All functions draw in SCREEN (logical) coordinates: they set the transform to env.scale themselves
+// and leave it there. Pure functions of their arguments; randomness only from rng(seed).
+//
+// writeOn(ctx, env, text, x, y, size, p, style, opts) size = cap height, (x, y) = baseline anchor
+// sentence(ctx, env, words, frame, t0, opts) the finale, one medium per word, one per beat
+// logo(ctx, env, x, y, em, p, opts) the anidoodle wordmark, written by a dip pen
+// logoBug(ctx, env, frame, x, y, scale, opts) the wordmark as a corner mark that lives
+// caption(ctx, env, text, x, y, size, p, kind, opts) a small hand-lettered callout, underline or arrow
+import { fractal, rng, sample, type Ctx, type Env, type Layer, type P } from "./core";
+import { G, type Glyph } from "./drafting";
+import { DOT, TAIL, WORD, inkStroke, outlineOf, type Nib } from "./lettering";
+
+export type KStyle = "ink" | "crayon" | "thread" | "chalk" | "brick" | "marker";
+export type WriteOpts = { color?: string; align?: "left" | "center" | "right"; slant?: number; track?: number; seed?: number; tool?: boolean; weight?: number; pop?: number };
+
+const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+const ease = (t: number) => { const c = clamp(t); return c * c * (3 - 2 * c); };
+const out3 = (t: number) => 1 - Math.pow(1 - clamp(t), 3);
+const hx = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
+const shade = (h: string, k: number) => { const c = hx(h).map((v) => Math.round(k >= 0 ? v + (255 - v) * k : v * (1 + k))); return `rgb(${c[0]},${c[1]},${c[2]})`; };
+const rgba = (h: string, a: number) => { const c = hx(h); return `rgba(${c[0]},${c[1]},${c[2]},${a})`; };
+// a spring that settles to 0 from a kick of 1: the pop a letter makes as it lands
+const pop = (t: number, omega = 0.55, zeta = 0.42) => (t <= 0 ? 0 : Math.exp(-zeta * omega * t) * Math.sin(omega * Math.sqrt(1 - zeta * zeta) * t));
+const screen = (ctx: Ctx, env: Env) => ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+
+// ---------------------------------------------------------------- glyph geometry
+// A line of text as strokes in screen space, in writing order, each densified to ~2 px steps and
+// tagged with its glyph, plus the glyph boxes (for the pop) and the total width.
+type KStroke = { pts: P[]; len: number[]; L: number; glyph: number };
+type Layout = { strokes: KStroke[]; boxes: { c: P; w: number; firstS: number; lastS: number }[]; W: number; total: number };
+const GAP = 14; // px of "pen lift" between strokes: the nib travels, nothing is drawn
+const glyphOf = (ch: string): Glyph => G[ch.toUpperCase()] ?? G[ch] ?? G["-"];
+const densify = (pts: P[], step: number): P[] => { const out: P[] = [pts[0]]; for (let i = 1; i < pts.length; i++) { const a = pts[i - 1], b = pts[i], n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step)); for (let k = 1; k <= n; k++) out.push([a[0] + ((b[0] - a[0]) * k) / n, a[1] + ((b[1] - a[1]) * k) / n]); } return out; };
+const cum = (pts: P[]) => { const l = [0]; for (let i = 1; i < pts.length; i++) l.push(l[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1])); return l; };
+export const measure = (text: string, size: number, o: WriteOpts = {}) => { const s = size / 6, tr = o.track ?? 1.5; return [...text].reduce((a, ch) => a + ((glyphOf(ch).w ?? 4) + tr) * s, 0) - tr * s + 6 * (o.slant ?? 0.12) * s; }; // + the slant's overhang at the cap line
+const layout = (env: Env, text: string, x: number, y: number, size: number, o: WriteOpts): Layout => {
+ const key = `kin:${text}|${x}|${y}|${size}|${o.align}|${o.slant}|${o.track}|${o.seed}`; const hit = env.cache.get(key) as Layout | undefined; if (hit) return hit;
+ const s = size / 6, tr = o.track ?? 1.5, sl = o.slant ?? 0.12, r = rng((o.seed ?? 1) * 977 + 3), W = measure(text, size, o);
+ let cx = o.align === "center" ? x - W / 2 : o.align === "right" ? x - W : x;
+ const strokes: KStroke[] = [], boxes: Layout["boxes"] = [];
+ [...text].forEach((ch) => {
+ const gl = glyphOf(ch), gw = (gl.w ?? 4) * s, dy = (r() - 0.5) * size * 0.06, rot = (r() - 0.5) * 0.07, k = 1 + (r() - 0.5) * 0.06, gc: P = [cx + gw / 2, y - size / 2 + dy];
+ // glyph units -> screen: scale, the forward slant, a per-letter tilt and baseline wander about its centre
+ const T = ([px, py]: P): P => { const X = cx + (px + (6 - py) * sl) * s * k, Y = y - size + dy + py * s * k, ax = X - gc[0], ay = Y - gc[1]; return [gc[0] + ax * Math.cos(rot) - ay * Math.sin(rot), gc[1] + ax * Math.sin(rot) + ay * Math.cos(rot)]; };
+ const first = strokes.length;
+ (gl.l ?? []).forEach((st) => { const pts = densify(st.map(T), 2); strokes.push({ pts, len: cum(pts), L: 0, glyph: boxes.length }); });
+ (gl.c ?? []).forEach((st) => { const pts = densify(sample(st, false, 10).map(T), 2); strokes.push({ pts, len: cum(pts), L: 0, glyph: boxes.length }); });
+ strokes.slice(first).forEach((k2) => (k2.L = k2.len[k2.len.length - 1]));
+ boxes.push({ c: gc, w: gw, firstS: first, lastS: strokes.length - 1 });
+ cx += gw + tr * s;
+ });
+ const total = strokes.reduce((a, k2) => a + k2.L + GAP, 0);
+ const L: Layout = { strokes, boxes, W, total }; env.cache.set(key, L); return L;
+};
+// how much of each stroke is laid at progress p (a constant-speed hand, pen lifts between)
+const reach = (lay: Layout, p: number) => { let d = clamp(p) * lay.total; return lay.strokes.map((k) => { const u = clamp(d / k.L); d -= k.L + GAP; return u; }); };
+const cut = (k: KStroke, u: number): P[] => { if (u >= 1) return k.pts; const want = u * k.L, out: P[] = [k.pts[0]]; for (let i = 1; i < k.pts.length; i++) { if (k.len[i] <= want) out.push(k.pts[i]); else { const f = (want - k.len[i - 1]) / (k.len[i] - k.len[i - 1] || 1); out.push([k.pts[i - 1][0] + (k.pts[i][0] - k.pts[i - 1][0]) * f, k.pts[i - 1][1] + (k.pts[i][1] - k.pts[i - 1][1]) * f]); break; } } return out.length > 1 ? out : [k.pts[0], k.pts[0]]; };
+const tipOf = (lay: Layout, us: number[]): { p: P; ang: number } | null => {
+ for (let i = 0; i < lay.strokes.length; i++) if (us[i] > 0 && us[i] < 1) { const c = cut(lay.strokes[i], us[i]), a = c[Math.max(0, c.length - 4)], b = c[c.length - 1]; return { p: b, ang: Math.atan2(b[1] - a[1], b[0] - a[0]) }; }
+ // between strokes: the tool hovers over the start of the next one
+ for (let i = 0; i < lay.strokes.length; i++) if (us[i] <= 0) return { p: lay.strokes[i].pts[0], ang: 0 };
+ return null;
+};
+// the pop: each glyph kicks a little bigger when its last stroke lands, then settles
+const glyphScale = (lay: Layout, us: number[], g: number, p: number, strength: number) => {
+ const b = lay.boxes[g], done = us[b.lastS] >= 1; if (!done) return 1;
+ // time since completion, in "progress frames": estimate by how far the hand has gone past it
+ let d = 0; for (let i = b.lastS + 1; i < lay.strokes.length; i++) d += lay.strokes[i].L * us[i];
+ const since = p >= 1 ? 1e9 : d / 18 + 1; return 1 + strength * 0.18 * pop(since);
+};
+const withGlyph = (ctx: Ctx, lay: Layout, g: number, k: number, fn: () => void) => { if (k === 1) return fn(); const c = lay.boxes[g].c; ctx.save(); ctx.translate(c[0], c[1]); ctx.scale(k, k); ctx.translate(-c[0], -c[1]); fn(); ctx.restore(); };
+
+// ---------------------------------------------------------------- textures (tiled, cached per scale)
+const tile = (env: Env, key: string, n: number, fn: (x: number, y: number) => number): Layer => {
+ const k = `kin:tile:${key}:${env.scale}`; let L = env.cache.get(k) as Layer | undefined; if (L) return L;
+ const N = Math.round(n * env.scale); L = env.canvas(N, N); const img = L.ctx.createImageData(N, N);
+ for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) { const a = clamp(fn(x / env.scale, y / env.scale)), i = (y * N + x) * 4; img.data[i] = img.data[i + 1] = img.data[i + 2] = 255; img.data[i + 3] = Math.round(a * 255); }
+ L.ctx.putImageData(img, 0, 0); env.cache.set(k, L); return L;
+};
+// wax: holes where the crayon skipped the paper's tooth (alpha 1 = a hole)
+const waxHoles = (env: Env) => tile(env, "wax", 96, (x, y) => { const t = fractal(71, x, y, 0.35, 0.12, 2, 96), g = fractal(72, x, y, 0.08, 0.08, 2, 96); return (t + 0.25 * g - 0.74) * 7; });
+const chalkHoles = (env: Env) => tile(env, "chalk", 96, (x, y) => { const t = fractal(81, x, y, 0.5, 0.5, 2, 96), g = fractal(82, x, y, 0.06, 0.06, 2, 96); return (t * 0.8 + 0.35 * g - 0.6) * 5; });
+// draw fn into a scratch layer, punch the texture out of it, composite it back: a textured medium
+const textured = (ctx: Ctx, env: Env, key: string, holes: Layer | null, alpha: number, fn: (c: Ctx) => void) => {
+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), k = `kin:scratch:${key}:${DW}`;
+ let L = env.cache.get(k) as Layer | undefined; if (!L) { L = env.canvas(DW, DH); env.cache.set(k, L); }
+ const c = L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "source-over"; c.globalAlpha = 1; c.clearRect(0, 0, DW, DH);
+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); fn(c);
+ if (holes) { c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "destination-out"; c.fillStyle = c.createPattern(holes.canvas as CanvasImageSource, "repeat")!; c.fillRect(0, 0, DW, DH); c.globalCompositeOperation = "source-over"; }
+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = alpha; ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore(); screen(ctx, env);
+};
+
+// ---------------------------------------------------------------- the tools (drawn at the nib)
+const toolPen = (ctx: Ctx, tip: P, size: number) => {
+ const a = -2.25, L = size * 2.6, back: P = [tip[0] - Math.cos(a) * -L, tip[1] - Math.sin(a) * -L], dx = Math.cos(a + Math.PI), dy = Math.sin(a + Math.PI);
+ const at = (t: number, w: number): P => [tip[0] + dx * L * t - dy * w, tip[1] + dy * L * t + dx * w]; void back;
+ ctx.save(); ctx.lineCap = "round";
+ ctx.strokeStyle = "rgba(40,25,15,0.18)"; ctx.lineWidth = size * 0.09; ctx.beginPath(); ctx.moveTo(...at(0.3, size * 0.06)); ctx.lineTo(...at(1.05, size * 0.12)); ctx.stroke(); // its shadow
+ ctx.strokeStyle = "#4a2f26"; ctx.lineWidth = size * 0.085; ctx.beginPath(); ctx.moveTo(...at(0.34, 0)); ctx.lineTo(...at(1, 0)); ctx.stroke();
+ ctx.strokeStyle = "#c2a063"; ctx.lineWidth = size * 0.1; ctx.beginPath(); ctx.moveTo(...at(0.22, 0)); ctx.lineTo(...at(0.34, 0)); ctx.stroke();
+ const nib: P[] = [at(0, 0), at(0.12, size * 0.035), at(0.23, size * 0.045), at(0.23, -size * 0.045), at(0.12, -size * 0.035)];
+ const gr = ctx.createLinearGradient(...at(0.15, size * 0.05), ...at(0.15, -size * 0.05)); gr.addColorStop(0, "#f4f1ea"); gr.addColorStop(0.5, "#a6a098"); gr.addColorStop(1, "#5d5953");
+ ctx.fillStyle = gr; ctx.beginPath(); nib.forEach((p, i) => (i ? ctx.lineTo(...p) : ctx.moveTo(...p))); ctx.closePath(); ctx.fill();
+ ctx.strokeStyle = "#34302a"; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(...at(0, 0)); ctx.lineTo(...at(0.13, 0)); ctx.stroke();
+ ctx.fillStyle = "#34302a"; ctx.beginPath(); ctx.arc(...at(0.14, 0), size * 0.012, 0, Math.PI * 2); ctx.fill();
+ ctx.restore();
+};
+const toolStick = (ctx: Ctx, tip: P, size: number, body: string, wrap: string | null, len = 1.3, wid = 0.16) => {
+ const a = -2.05, dx = Math.cos(a + Math.PI), dy = Math.sin(a + Math.PI), L = size * len, w = size * wid;
+ const at = (t: number, s: number): P => [tip[0] + dx * L * t - dy * s, tip[1] + dy * L * t + dx * s];
+ ctx.save();
+ ctx.fillStyle = "rgba(40,25,15,0.14)"; ctx.beginPath(); [at(0.15, w * 0.7), at(1.05, w * 0.9), at(1.05, -w * 0.3), at(0.15, -w * 0.2)].forEach((p, i) => (i ? ctx.lineTo(p[0] + size * 0.05, p[1] + size * 0.07) : ctx.moveTo(p[0] + size * 0.05, p[1] + size * 0.07))); ctx.closePath(); ctx.fill();
+ const g = ctx.createLinearGradient(...at(0.5, w / 2), ...at(0.5, -w / 2)); g.addColorStop(0, shade(body, 0.25)); g.addColorStop(0.5, body); g.addColorStop(1, shade(body, -0.35));
+ ctx.fillStyle = g; ctx.beginPath(); [at(0.02, w * 0.12), at(0.16, w / 2), at(1, w / 2), at(1, -w / 2), at(0.16, -w / 2), at(0.02, -w * 0.12)].forEach((p, i) => (i ? ctx.lineTo(...p) : ctx.moveTo(...p))); ctx.closePath(); ctx.fill();
+ if (wrap) { ctx.fillStyle = wrap; ctx.globalAlpha = 0.92; ctx.beginPath(); [at(0.34, w / 2 + 0.6), at(0.9, w / 2 + 0.6), at(0.9, -w / 2 - 0.6), at(0.34, -w / 2 - 0.6)].forEach((p, i) => (i ? ctx.lineTo(...p) : ctx.moveTo(...p))); ctx.closePath(); ctx.fill(); ctx.globalAlpha = 1; ctx.strokeStyle = shade(body, -0.3); ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(...at(0.5, w / 2)); ctx.lineTo(...at(0.5, -w / 2)); ctx.moveTo(...at(0.74, w / 2)); ctx.lineTo(...at(0.74, -w / 2)); ctx.stroke(); }
+ ctx.restore();
+};
+const toolMarker = (ctx: Ctx, tip: P, size: number, color: string) => {
+ toolStick(ctx, tip, size, "#f3f1ec", null, 1.5, 0.22);
+ const a = -2.05, dx = Math.cos(a + Math.PI), dy = Math.sin(a + Math.PI), L = size * 1.5, w = size * 0.22;
+ const at = (t: number, s: number): P => [tip[0] + dx * L * t - dy * s, tip[1] + dy * L * t + dx * s];
+ ctx.fillStyle = color; ctx.beginPath(); [at(0, -w * 0.18), at(0.02, w * 0.2), at(0.1, w * 0.28), at(0.1, -w * 0.28)].forEach((p, i) => (i ? ctx.lineTo(...p) : ctx.moveTo(...p))); ctx.closePath(); ctx.fill();
+ ctx.fillStyle = color; ctx.fillRect(0, 0, 0, 0); ctx.beginPath(); [at(0.6, w / 2), at(0.72, w / 2), at(0.72, -w / 2), at(0.6, -w / 2)].forEach((p, i) => (i ? ctx.lineTo(...p) : ctx.moveTo(...p))); ctx.closePath(); ctx.fill();
+};
+const toolNeedle = (ctx: Ctx, tip: P, ang: number, size: number, thread: string, from: P | null) => {
+ const L = size * 1.25, dx = Math.cos(ang), dy = Math.sin(ang), eye: P = [tip[0] - dx * L, tip[1] - dy * L];
+ ctx.save(); ctx.lineCap = "round";
+ if (from) { ctx.strokeStyle = thread; ctx.lineWidth = size * 0.022; ctx.beginPath(); ctx.moveTo(...eye); ctx.quadraticCurveTo(eye[0] - dx * size * 0.4 + size * 0.2, eye[1] - dy * size * 0.4 + size * 0.3, from[0], from[1]); ctx.stroke(); }
+ ctx.strokeStyle = "rgba(40,25,15,0.2)"; ctx.lineWidth = size * 0.035; ctx.beginPath(); ctx.moveTo(tip[0] + 3, tip[1] + 4); ctx.lineTo(eye[0] + 3, eye[1] + 4); ctx.stroke();
+ const g = ctx.createLinearGradient(tip[0], tip[1] - 3, tip[0], tip[1] + 3); g.addColorStop(0, "#fbfbfa"); g.addColorStop(1, "#8d918f");
+ ctx.strokeStyle = g; ctx.lineWidth = size * 0.042; ctx.beginPath(); ctx.moveTo(...tip); ctx.lineTo(...eye); ctx.stroke();
+ ctx.strokeStyle = "#6c706e"; ctx.lineWidth = 1; ctx.beginPath(); ctx.ellipse(eye[0] + dx * size * 0.06, eye[1] + dy * size * 0.06, size * 0.045, size * 0.012, ang, 0, Math.PI * 2); ctx.stroke();
+ ctx.restore();
+};
+
+// ---------------------------------------------------------------- the media
+const PALETTE: Record<KStyle, string> = { ink: "#1b1510", crayon: "#d9412f", thread: "#2f7f86", chalk: "#f3efe2", brick: "#B40000", marker: "#1f6fd1" };
+// pointed-pen width along a stroke: only the downstrokes (the pen pulled toward the writer) swell
+const penWidths = (pts: P[], hair: number, shadeW: number) => {
+ const raw = pts.map((_, i) => { const a = pts[Math.max(0, i - 2)], b = pts[Math.min(pts.length - 1, i + 2)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1; return Math.pow(clamp(dy / l), 1.5); });
+ const K = 4, n = pts.length; return raw.map((_, i) => { let t = 0, c = 0; for (let j = -K; j <= K; j++) { const v = raw[i + j]; if (v !== undefined) { t += v; c++; } } const taper = Math.min(1, i / 3, (n - 1 - i) / 4); return (hair + (shadeW - hair) * (t / c)) * (0.45 + 0.55 * clamp(taper)); });
+};
+const ribbon = (pts: P[], ws: number[]): P[] => { const L: P[] = [], R: P[] = []; for (let i = 0; i < pts.length; i++) { const a = pts[Math.max(0, i - 1)], b = pts[Math.min(pts.length - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l; L.push([pts[i][0] + nx * ws[i], pts[i][1] + ny * ws[i]]); R.push([pts[i][0] - nx * ws[i], pts[i][1] - ny * ws[i]]); } return [...L, ...R.reverse()]; };
+const fillPoly = (c: Ctx, pts: P[]) => { c.beginPath(); pts.forEach((p, i) => (i ? c.lineTo(...p) : c.moveTo(...p))); c.closePath(); c.fill(); };
+const polyline = (c: Ctx, pts: P[]) => { c.beginPath(); pts.forEach((p, i) => (i ? c.lineTo(...p) : c.moveTo(...p))); c.stroke(); };
+
+const drawInk = (c: Ctx, lay: Layout, us: number[], size: number, color: string, p: number, popK: number) => {
+ const hair = size * 0.024, sh = size * 0.115;
+ lay.strokes.forEach((k, i) => {
+ if (us[i] <= 0) return;
+ withGlyph(c, lay, k.glyph, glyphScale(lay, us, k.glyph, p, popK), () => {
+ const full = penWidths(k.pts, hair, sh), pts = cut(k, us[i]), ws = full.slice(0, pts.length);
+ c.fillStyle = color; fillPoly(c, ribbon(pts, ws));
+ // a bead where the nib stopped and the ink pooled, and the wet sheen on the fresh stroke
+ if (us[i] >= 1) { const e = k.pts[k.pts.length - 1]; c.beginPath(); c.arc(e[0], e[1], Math.max(hair * 1.4, ws[ws.length - 1] * 1.05), 0, Math.PI * 2); c.fill(); }
+ else { c.fillStyle = "rgba(255,255,255,0.18)"; fillPoly(c, ribbon(pts.slice(-Math.min(pts.length, 14)), ws.slice(-Math.min(pts.length, 14)).map((w) => w * 0.35))); }
+ });
+ });
+};
+const drawMarker = (c: Ctx, lay: Layout, us: number[], size: number, color: string, p: number, popK: number) => {
+ const W = size * 0.16, chisel = -0.78;
+ lay.strokes.forEach((k, i) => {
+ if (us[i] <= 0) return;
+ withGlyph(c, lay, k.glyph, glyphScale(lay, us, k.glyph, p, popK), () => {
+ const pts = cut(k, us[i]), ws = pts.map((_, j) => { const a = pts[Math.max(0, j - 2)], b = pts[Math.min(pts.length - 1, j + 2)], ang = Math.atan2(b[1] - a[1], b[0] - a[0]); return (W / 2) * (0.4 + 0.6 * Math.abs(Math.sin(ang - chisel))); });
+ c.globalAlpha = 0.86; c.fillStyle = color; fillPoly(c, ribbon(pts, ws)); // translucent alcohol ink: overlaps go darker
+ c.globalAlpha = 0.35; c.fillStyle = shade(color, 0.35); fillPoly(c, ribbon(pts.map(([x, y]) => [x - W * 0.08, y - W * 0.1] as P), ws.map((w) => w * 0.3))); // the streak of the chisel's lighter edge
+ c.globalAlpha = 1;
+ });
+ });
+};
+const drawCrayon = (c: Ctx, lay: Layout, us: number[], size: number, color: string, p: number, popK: number, seed: number) => {
+ const W = size * 0.13, r = rng(seed);
+ lay.strokes.forEach((k, i) => {
+ if (us[i] <= 0) return;
+ withGlyph(c, lay, k.glyph, glyphScale(lay, us, k.glyph, p, popK), () => {
+ const pts = cut(k, us[i]);
+ c.lineCap = "round"; c.lineJoin = "round";
+ // the wax goes down in a few passes: a body stroke, then the crayon gone over again a hair off
+ for (let pass = 0; pass < 3; pass++) {
+ const ox = (r() - 0.5) * W * (pass ? 0.22 : 0), oy = (r() - 0.5) * W * (pass ? 0.22 : 0);
+ c.strokeStyle = pass === 2 ? shade(color, -0.2) : color; c.globalAlpha = pass === 0 ? 0.95 : 0.55; c.lineWidth = W * (pass === 0 ? 1.15 : 0.6);
+ polyline(c, pts.map(([x, y], j) => [x + ox + Math.sin(j * 0.7 + pass) * W * 0.06, y + oy + Math.cos(j * 0.5 + pass) * W * 0.06] as P));
+ }
+ c.globalAlpha = 1;
+ });
+ });
+};
+const drawChalk = (c: Ctx, lay: Layout, us: number[], size: number, color: string, p: number, popK: number, seed: number) => {
+ const W = size * 0.11, r = rng(seed);
+ lay.strokes.forEach((k, i) => {
+ if (us[i] <= 0) return;
+ withGlyph(c, lay, k.glyph, glyphScale(lay, us, k.glyph, p, popK), () => {
+ const pts = cut(k, us[i]); c.lineCap = "round"; c.lineJoin = "round";
+ c.strokeStyle = color; c.globalAlpha = 0.85; c.lineWidth = W; polyline(c, pts);
+ c.globalAlpha = 0.5; c.lineWidth = W * 0.45; polyline(c, pts.map(([x, y]) => [x + W * 0.25, y - W * 0.2] as P));
+ // dust: fine grains knocked off either side of the line
+ c.fillStyle = color; for (let j = 0; j < pts.length; j += 3) { const [x, y] = pts[j]; for (let q = 0; q < 2; q++) { const a = r() * Math.PI * 2, d = W * (0.6 + r() * 1.1); c.globalAlpha = 0.25 * r(); c.fillRect(x + Math.cos(a) * d, y + Math.sin(a) * d, 1.4, 1.4); } }
+ c.globalAlpha = 1;
+ });
+ });
+};
+// satin stitch laid ACROSS the stroke: each stitch a short twisted thread with a lit side and a shade side
+const drawThread = (c: Ctx, lay: Layout, us: number[], size: number, color: string, p: number, popK: number) => {
+ const W = size * 0.075, step = size * 0.022, lit = shade(color, 0.35), dark = shade(color, -0.35);
+ lay.strokes.forEach((k, i) => {
+ if (us[i] <= 0) return;
+ withGlyph(c, lay, k.glyph, glyphScale(lay, us, k.glyph, p, popK), () => {
+ const pts = cut(k, us[i]), lens = cum(pts), Lh = lens[lens.length - 1]; c.lineCap = "round";
+ for (let d = 0, j = 0; d <= Lh; d += step) {
+ while (j < lens.length - 2 && lens[j + 1] < d) j++;
+ const a = pts[j], b = pts[Math.min(pts.length - 1, j + 1)], tx = b[0] - a[0], ty = b[1] - a[1], l = Math.hypot(tx, ty) || 1, ux = tx / l, uy = ty / l, f = (d - lens[j]) / ((lens[j + 1] ?? lens[j]) - lens[j] || 1);
+ const m: P = [a[0] + tx * f, a[1] + ty * f], nx = -uy, ny = ux, sl = 0.45; // stitches slant across the line
+ const p0: P = [m[0] + (nx - ux * sl) * W, m[1] + (ny - uy * sl) * W], p1: P = [m[0] - (nx - ux * sl) * W, m[1] - (ny - uy * sl) * W];
+ c.strokeStyle = "rgba(40,30,20,0.22)"; c.lineWidth = step * 1.25; c.beginPath(); c.moveTo(p0[0] + 1.5, p0[1] + 2); c.lineTo(p1[0] + 1.5, p1[1] + 2); c.stroke();
+ const g = c.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); g.addColorStop(0, lit); g.addColorStop(0.45, color); g.addColorStop(1, dark);
+ c.strokeStyle = g; c.lineWidth = step * 1.15; c.beginPath(); c.moveTo(...p0); c.lineTo(...p1); c.stroke();
+ }
+ });
+ });
+};
+// toy bricks: the letter rasterised onto a stud grid, each 1x1 plate popping in as the "nib" passes
+type Cell = { x: number; y: number; t: number; g: number; col: string };
+const BRICK_COLS = ["#B40000", "#FAC80A", "#1E5AA8", "#00852B", "#D67923"];
+const cellsOf = (env: Env, lay: Layout, size: number, key: string): { cells: Cell[]; s: number } => {
+ const k = `kin:cells:${key}`; const hit = env.cache.get(k) as { cells: Cell[]; s: number } | undefined; if (hit) return hit;
+ const s = size / 6.5, cells: Cell[] = [];
+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; lay.strokes.forEach((st) => st.pts.forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }));
+ let acc = 0; const starts = lay.strokes.map((st) => { const a = acc; acc += st.L + GAP; return a; });
+ for (let gy = Math.floor((y0 - s) / s); gy <= Math.ceil((y1 + s) / s); gy++) for (let gx = Math.floor((x0 - s) / s); gx <= Math.ceil((x1 + s) / s); gx++) {
+ const cx = (gx + 0.5) * s, cy = (gy + 0.5) * s; let best = 1e9, bt = 0, bg = 0;
+ lay.strokes.forEach((st, si) => { for (let j = 0; j < st.pts.length; j += 2) { const d = Math.hypot(st.pts[j][0] - cx, st.pts[j][1] - cy); if (d < best) { best = d; bt = (starts[si] + st.len[j]) / lay.total; bg = st.glyph; } } });
+ if (best < s * 0.7) cells.push({ x: gx * s, y: gy * s, t: bt, g: bg, col: BRICK_COLS[bg % BRICK_COLS.length] });
+ }
+ const out = { cells: cells.sort((a, b) => a.t - b.t), s }; env.cache.set(k, out); return out;
+};
+const drawBricks = (c: Ctx, env: Env, lay: Layout, p: number, size: number, key: string, fixed?: string) => {
+ const { cells, s } = cellsOf(env, lay, size, key), span = 0.06; // a plate takes 6% of the write to fall and seat
+ for (const cl of cells) {
+ const u = clamp((p - cl.t + span) / span); if (u <= 0) continue;
+ const fall = 1 - out3(u), seat = u >= 1 ? 0 : 0, lift = fall * s * 1.4; void seat;
+ const col = fixed ?? cl.col, x = cl.x, y = cl.y - lift, a = u < 1 ? 0.45 + 0.55 * u : 1;
+ c.globalAlpha = a * 0.25 * (1 - fall); c.fillStyle = "#000"; c.fillRect(x + s * 0.12, cl.y + s * 0.16, s, s); // its shadow on the ground, sharper as it seats
+ c.globalAlpha = a; c.fillStyle = shade(col, -0.22); c.fillRect(x, y, s, s);
+ c.fillStyle = col; c.fillRect(x + 1, y + 1, s - 3, s - 3.5);
+ c.fillStyle = shade(col, 0.28); c.fillRect(x + 1, y + 1, s - 3, 1.4); c.fillRect(x + 1, y + 1, 1.4, s - 3.5);
+ const r = s * 0.3, sx = x + s / 2 - 0.8, sy = y + s / 2 - 1; // the stud: a cylinder seen from above, lit upper left
+ c.fillStyle = shade(col, -0.28); c.beginPath(); c.arc(sx + 1, sy + 1.4, r, 0, Math.PI * 2); c.fill();
+ c.fillStyle = col; c.beginPath(); c.arc(sx, sy, r, 0, Math.PI * 2); c.fill();
+ c.strokeStyle = shade(col, 0.45); c.lineWidth = 1.1; c.beginPath(); c.arc(sx, sy, r * 0.8, Math.PI * 0.95, Math.PI * 1.6); c.stroke();
+ }
+ c.globalAlpha = 1;
+};
+
+// ---------------------------------------------------------------- writeOn
+export const writeOn = (ctx: Ctx, env: Env, text: string, x: number, y: number, size: number, p: number, style: KStyle, o: WriteOpts = {}) => {
+ if (p <= 0) return;
+ screen(ctx, env);
+ if (style === "brick" && o.track === undefined) o = { ...o, track: 2.6, slant: o.slant ?? 0 };
+ const lay = layout(env, text, x, y, size, o), us = reach(lay, p), color = o.color ?? PALETTE[style], popK = o.pop ?? 1, seed = o.seed ?? 1;
+ ctx.save();
+ if (style === "ink") drawInk(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);
+ else if (style === "marker") drawMarker(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);
+ else if (style === "crayon") textured(ctx, env, "crayon", waxHoles(env), 1, (c) => drawCrayon(c, lay, us, size * (o.weight ?? 1), color, p, popK, seed));
+ else if (style === "chalk") textured(ctx, env, "chalk", chalkHoles(env), 1, (c) => drawChalk(c, lay, us, size * (o.weight ?? 1), color, p, popK, seed));
+ else if (style === "thread") drawThread(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);
+ else if (style === "brick") drawBricks(ctx, env, lay, p, size, `${text}|${x}|${y}|${size}|${o.seed}|${o.align}|${o.track}`, o.color);
+ ctx.restore();
+ // the tool, while the hand is still writing
+ if (o.tool === false || p >= 1 || style === "brick") return;
+ const tp = tipOf(lay, us); if (!tp) return;
+ if (style === "ink") toolPen(ctx, tp.p, size);
+ else if (style === "marker") toolMarker(ctx, tp.p, size, color);
+ else if (style === "crayon") toolStick(ctx, tp.p, size, color, "#efe6cf", 1.15, 0.24);
+ else if (style === "chalk") toolStick(ctx, tp.p, size, "#f6f3ea", null, 0.8, 0.12);
+ else if (style === "thread") { const lastDone = [...us.keys()].reverse().find((i) => us[i] > 0); const from = lastDone !== undefined ? cut(lay.strokes[lastDone], us[lastDone]).slice(-1)[0] : null; toolNeedle(ctx, [tp.p[0] + 6, tp.p[1] - 6], -0.9, size, color, from); }
+};
+
+// ---------------------------------------------------------------- the finale sentence
+// Each word in its own medium, one per beat, then the claim in pen with a swash that swings in.
+export type SentenceOpts = { beat?: number; styles?: KStyle[]; colors?: string[]; cx?: number; top?: number; size?: number; claim?: string; claimSize?: number };
+export const SENTENCE_STYLES: KStyle[] = ["marker", "ink", "thread", "crayon", "brick"];
+export const sentence = (ctx: Ctx, env: Env, words: string[], frame: number, t0: number, o: SentenceOpts = {}) => {
+ const beat = o.beat ?? 20, cx = o.cx ?? env.W / 2, size = o.size ?? 74, top = o.top ?? env.H * 0.3, styles = o.styles ?? SENTENCE_STYLES;
+ const colors = o.colors ?? ["#1f6fd1", "#1b1510", "#2f7f86", "#d9412f", ""];
+ const labels = words.map((w, i) => w + (i < words.length - 1 ? "," : "."));
+ // two lines, balanced by measured width
+ const wAt = (i: number) => measure(labels[i], size) + size * 0.55, split = Math.ceil(words.length / 2) - (words.length % 2 ? 1 : 0) || 1;
+ const lines = [labels.map((_, i) => i).slice(0, split), labels.map((_, i) => i).slice(split)];
+ lines.forEach((ids, li) => {
+ const total = ids.reduce((a, i) => a + wAt(i), 0) - size * 0.55; let x = cx - total / 2; const y = top + li * size * 1.75;
+ ids.forEach((i) => {
+ const p = ease((frame - t0 - i * beat) / (beat * 1.35));
+ writeOn(ctx, env, labels[i], x, y, size, p, styles[i % styles.length], { color: colors[i] || undefined, seed: 40 + i });
+ x += wAt(i);
+ });
+ });
+ const claim = o.claim ?? "All in pure code.", cs = o.claimSize ?? 118, cy = top + 2 * size * 1.75 + cs * 1.25, c0 = t0 + words.length * beat + beat * 0.5;
+ const pc = ease((frame - c0) / (beat * 2.2)), W = measure(claim, cs);
+ writeOn(ctx, env, claim, cx, cy, cs, pc, "ink", { align: "center", seed: 90, color: o.colors?.[5] ?? "#1b1510" });
+ // the swash: one long pointed-pen hairline swelling through its middle, swung in under the claim
+ const ps = out3((frame - c0 - beat * 2) / (beat * 0.9)); if (ps > 0) {
+ screen(ctx, env); const x0 = cx - W / 2 - cs * 0.1, x1 = cx + W / 2 + cs * 0.2, yy = cy + cs * 0.3, n = 60, pts: P[] = [], ws: number[] = [];
+ for (let i = 0; i <= n * ps; i++) { const t = i / n; pts.push([lerp(x0, x1, t), yy + Math.sin(t * Math.PI * 1.1 - 0.2) * cs * 0.12 - t * cs * 0.05]); ws.push(cs * (0.008 + 0.045 * Math.sin(Math.PI * t) ** 2)); }
+ if (pts.length > 1) { ctx.fillStyle = "#d4622b"; fillPoly(ctx, ribbon(pts, ws)); }
+ }
+};
+
+// ---------------------------------------------------------------- the logo
+// The anidoodle wordmark from lettering.ts, inked stroke by stroke with thick-thin pressure, the
+// i's dot last, and a dip pen riding the nib. Idle: a glint travels the dot and the word breathes.
+export type LogoOpts = { color?: string; pen?: boolean; seed?: number; glint?: number };
+const inkedWord = (env: Env, em: number, x: number, y: number) => {
+ const k = `kin:logo:${em}:${x}:${y}`; const hit = env.cache.get(k) as ReturnType<typeof build> | undefined; if (hit) return hit;
+ const b = build(em, x, y); env.cache.set(k, b); return b;
+};
+const build = (em: number, x: number, y: number) => {
+ const nib: Nib = { em, slant: 0.28, origin: [x, y], hair: em * 0.012, shade: em * 0.085 };
+ const strokes = WORD.map((s, i) => inkStroke(nib, s, TAIL[i])), total = strokes.reduce((a, k) => a + k.len[k.len.length - 1], 0);
+ const dot: P = [x + (DOT[0] + DOT[1] * Math.tan(nib.slant)) * em, y - DOT[1] * em];
+ return { strokes, total, dot, nib };
+};
+export const logoBox = (env: Env, em: number) => {
+ const k = `kin:logobox:${em}`; const hit = env.cache.get(k) as { x0: number; x1: number; y0: number; y1: number } | undefined; if (hit) return hit;
+ const W = inkedWord(env, em, 0, 0); let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
+ W.strokes.forEach((st) => st.spine.forEach(([x, y]) => { x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); }));
+ const b = { x0, x1, y0, y1 }; env.cache.set(k, b); return b;
+};
+export const logoWidth = (em: number) => em * 5.9; // the letters only; logoBox() includes the swash
+// the wordmark centred on (cx, cy), swash and all
+export const logoCentred = (ctx: Ctx, env: Env, cx: number, cy: number, em: number, p: number, o: LogoOpts = {}) => { const b = logoBox(env, em); logo(ctx, env, cx - (b.x0 + b.x1) / 2, cy - (b.y0 + b.y1) / 2, em, p, o); };
+export const logo = (ctx: Ctx, env: Env, x: number, y: number, em: number, p: number, o: LogoOpts = {}) => {
+ if (p <= 0) return;
+ screen(ctx, env);
+ const W = inkedWord(env, em, x, y), color = o.color ?? "#1b1510", pw = clamp(p / 0.9), pd = clamp((p - 0.9) / 0.1);
+ let d = pw * W.total, tip: P | null = null;
+ ctx.fillStyle = color;
+ for (const k of W.strokes) {
+ const L = k.len[k.len.length - 1]; if (d <= 0) break;
+ const upto = Math.min(L, d), poly = outlineOf(k, upto); fillPoly(ctx, poly);
+ if (d < L) { const i = k.len.findIndex((v) => v >= upto); tip = k.spine[Math.max(0, i)]; }
+ d -= L;
+ }
+ if (pd > 0) { ctx.beginPath(); ctx.arc(W.dot[0], W.dot[1], em * 0.07 * out3(pd), 0, Math.PI * 2); ctx.fill(); }
+ if (o.glint && o.glint > 0) { const g = ctx.createRadialGradient(W.dot[0] - em * 0.02, W.dot[1] - em * 0.02, 0, W.dot[0], W.dot[1], em * 0.16); g.addColorStop(0, `rgba(255,253,245,${0.85 * o.glint})`); g.addColorStop(1, "rgba(255,253,245,0)"); ctx.fillStyle = g; ctx.beginPath(); ctx.arc(W.dot[0], W.dot[1], em * 0.16, 0, Math.PI * 2); ctx.fill(); }
+ if (o.pen !== false && p < 1) toolPen(ctx, tip ?? W.dot, em * 1.25);
+};
+// the corner mark: writes on in ~1 s from t0, then lives (a glint every 4 s, a slow breath)
+export type BugOpts = { t0?: number; color?: string; fps?: number; pen?: boolean; alpha?: number };
+export const logoBug = (ctx: Ctx, env: Env, frame: number, x: number, y: number, scale: number, o: BugOpts = {}) => {
+ const fps = o.fps ?? 30, t = frame - (o.t0 ?? 0); if (t < 0) return;
+ const p = ease(t / fps), em = 26 * scale, breath = 1 + 0.006 * Math.sin((2 * Math.PI * t) / (fps * 3.2)), gl = (t % (fps * 4)) / (fps * 4), glint = t > fps ? Math.max(0, Math.sin(Math.PI * clamp((gl - 0.8) / 0.2))) : 0;
+ // the breath scales the word about its baseline origin: logo() draws in screen space from (x, y), so a scaled em is the whole move
+ ctx.save(); ctx.globalAlpha = o.alpha ?? 1;
+ logo(ctx, env, x, y, em * breath, p, { color: o.color, pen: o.pen ?? p < 1, glint });
+ ctx.restore();
+};
+
+// ---------------------------------------------------------------- captions
+// A small hand-lettered callout in pen, with a hand-drawn underline or an arrow that swings toward
+// `to` (screen point) once the words are down.
+export type CaptionOpts = { color?: string; to?: P; align?: "left" | "center" | "right"; style?: KStyle; accent?: string };
+export const caption = (ctx: Ctx, env: Env, text: string, x: number, y: number, size: number, p: number, kind: "plain" | "underline" | "arrow" = "underline", o: CaptionOpts = {}) => {
+ if (p <= 0) return;
+ const pw = clamp(p / 0.75), pl = out3((p - 0.7) / 0.3), W = measure(text, size), color = o.color ?? "#1b1510", accent = o.accent ?? "#d4622b";
+ const x0 = o.align === "center" ? x - W / 2 : o.align === "right" ? x - W : x;
+ writeOn(ctx, env, text, x, y, size, pw, o.style ?? "ink", { color, align: o.align, seed: 7, weight: 1.15, pop: 0.7 });
+ if (kind === "plain" || pl <= 0) return;
+ screen(ctx, env); ctx.save(); ctx.lineCap = "round"; ctx.strokeStyle = accent; ctx.fillStyle = accent;
+ if (kind === "underline") {
+ const n = 40, pts: P[] = [], ws: number[] = [];
+ for (let i = 0; i <= n * pl; i++) { const t = i / n; pts.push([x0 - size * 0.1 + (W + size * 0.3) * t, y + size * 0.32 + Math.sin(t * 5.2) * size * 0.035 - t * size * 0.05]); ws.push(size * (0.02 + 0.03 * Math.sin(Math.PI * t))); }
+ if (pts.length > 1) fillPoly(ctx, ribbon(pts, ws));
+ } else if (o.to) {
+ const e = o.to, s: P = e[1] < y - size * 1.2 ? [x0 + W * 0.75, y - size * 1.35] : e[1] > y + size * 0.3 ? [x0 + W * 0.75, y + size * 0.55] : e[0] < x0 ? [x0 - size * 0.4, y - size * 0.5] : [x0 + W + size * 0.4, y - size * 0.5], m: P = [(s[0] + e[0]) / 2 + (e[1] - s[1]) * 0.25, (s[1] + e[1]) / 2 - (e[0] - s[0]) * 0.25];
+ const n = 40, pts: P[] = []; for (let i = 0; i <= n * pl; i++) { const t = i / n; pts.push([(1 - t) ** 2 * s[0] + 2 * (1 - t) * t * m[0] + t * t * e[0], (1 - t) ** 2 * s[1] + 2 * (1 - t) * t * m[1] + t * t * e[1]]); }
+ if (pts.length > 1) { ctx.lineWidth = size * 0.06; polyline(ctx, pts); }
+ if (pl >= 1) { const a = pts[pts.length - 4], b = pts[pts.length - 1], ang = Math.atan2(b[1] - a[1], b[0] - a[0]), h = size * 0.3; ctx.lineWidth = size * 0.06; polyline(ctx, [[b[0] - Math.cos(ang - 0.5) * h, b[1] - Math.sin(ang - 0.5) * h], b, [b[0] - Math.cos(ang + 0.5) * h, b[1] - Math.sin(ang + 0.5) * h]]); }
+ }
+ ctx.restore();
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kineticDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kineticDemo.ts
new file mode 100644
index 0000000..68abe1e
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kineticDemo.ts
@@ -0,0 +1,44 @@
+// KINETIC DEMO. Every treatment in kinetic.ts, on the launch film's grid (90 bpm: a beat is 20 frames).
+// 0-60 the wordmark written large by the dip pen, then the corner mark writes itself in
+// 60-160 six words, six media: ink, crayon, thread, chalk (on a board), toy bricks, marker; a callout with an arrow
+// 160-280 the finale: one medium per word, then "All in pure code." with its swash
+import type { Ctx, Env } from "./core";
+import type { Film } from "./film";
+import { caption, logoBug, logoCentred, measure, sentence, writeOn, type KStyle } from "./kinetic";
+
+const W = 1920, H = 1080, PAPER = "#f4efe6";
+const ground = (ctx: Ctx, env: Env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H); };
+const ease = (t: number) => { const c = Math.max(0, Math.min(1, t)); return c * c * (3 - 2 * c); };
+const bug = (ctx: Ctx, env: Env, f: number) => logoBug(ctx, env, f, 1640, 1030, 1, { t0: 40 });
+
+const opening = (ctx: Ctx, f: number, env: Env) => {
+ ground(ctx, env);
+ logoCentred(ctx, env, W / 2, H / 2, 150, ease(f / 44));
+ bug(ctx, env, f);
+};
+// two rows of three, each row laid out by measured width and centred
+const SZ = 100, ROWS: [string, KStyle][][] = [[["INK", "ink"], ["CRAYON", "crayon"], ["THREAD", "thread"]], [["CHALK", "chalk"], ["BRICKS", "brick"], ["MARKER", "marker"]]];
+const WORDS: [string, KStyle, number, number][] = ROWS.flatMap((row, r) => { const gap = 90, tot = row.reduce((a, [t]) => a + measure(t, SZ), 0) + gap * (row.length - 1); let x = W / 2 - tot / 2; return row.map(([t, st]) => { const o: [string, KStyle, number, number] = [t, st, x, r ? 700 : 360]; x += measure(t, SZ, st === "brick" ? { track: 2.6, slant: 0 } : {}) + gap; return o; }); });
+const styles = (ctx: Ctx, f: number, env: Env) => {
+ ground(ctx, env);
+ const [, , cx, cy] = WORDS[3], cw = measure("CHALK", SZ); // the chalkboard behind the chalk word
+ ctx.fillStyle = "#2c3a33"; ctx.fillRect(cx - 50, cy - SZ - 55, cw + 100, SZ + 110); ctx.strokeStyle = "#6b4a2b"; ctx.lineWidth = 14; ctx.strokeRect(cx - 50, cy - SZ - 55, cw + 100, SZ + 110);
+ WORDS.forEach(([t, st, x, y], i) => writeOn(ctx, env, t, x, y, SZ, ease((f - i * 10) / 38), st, { seed: 3 + i }));
+ caption(ctx, env, "drawn live, no fonts", W / 2 + 180, 960, 40, ease((f - 60) / 30), "arrow", { to: [WORDS[5][2] + 60, 790] });
+ bug(ctx, env, f + 60);
+};
+const finale = (ctx: Ctx, f: number, env: Env) => {
+ ground(ctx, env);
+ sentence(ctx, env, ["Images", "Illustrations", "Loops", "Animations", "Films"], f, 0, { beat: 14 });
+ bug(ctx, env, f + 160);
+};
+
+export const kineticDemo: Film = {
+ meta: { title: "kinetic lettering · demo", W, H, fps: 30, bpm: 90, durationFrames: 280, raster: "cpu" },
+ assets: { images: {} },
+ shots: [
+ { id: "logo", start: 0, end: 60, draw: opening },
+ { id: "styles", start: 60, end: 160, draw: styles },
+ { id: "finale", start: 160, end: 280, draw: finale },
+ ],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koi.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koi.ts
index 30fb4fe..1c291c4 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koi.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koi.ts
@@ -14,7 +14,7 @@ import { cut, part, stagger, streakClip, streaks } from "./koiDrawKit";
// so they bend with it. Light from the upper left.
const INK = "#15122a", LIGHT: P = [-0.62, -0.78];
-const WATER = "#137582", WATER_D = "#0c5360", WATER_L = "#3aa6ad";
+export const WATER = "#137582", WATER_D = "#0c5360", WATER_L = "#3aa6ad";
const WHITE = "#fdf8ee", WHITE_S = "#c9d6e0", HI = "#ec4a22", HI_S = "#b72c1a", SUMI = "#1b1830";
const FIN = "#f7efe4", FIN_S = "#d5dde2";
@@ -30,19 +30,45 @@ const lay = (g: Gfx, p: number, shapes: P[][], fn: () => void, seed: number, w =
const c = g.cur; c.save(); streakClip(c, streaks(shapes, w, ang, seed, reach), p); fn(); c.restore();
};
// the contour grows along its centreline; a closed one is drawn open until it closes
-const inkP = (g: Gfx, center: P[], color: string, o: InkOpts, alpha: number | undefined, q: number) => {
+export const inkP = (g: Gfx, center: P[], color: string, o: InkOpts, alpha: number | undefined, q: number) => {
if (q >= 1) return alpha === undefined ? ink(g, center, color, o) : ink(g, center, color, o, alpha); if (q <= 0) return;
const path = o.closed ? [...center, center[0]] : center, side = o.closed ? (area(center) > 0 ? -1 : 1) : o.side;
ink(g, cut(path, q), color, { ...o, closed: false, side, taper: [o.closed ? 0.04 : (o.taper?.[0] ?? 0.12), 0.08] }, alpha ?? 1);
};
-const koiBody = (): Body => body(
- [[300, 222], [404, 292], [502, 408], [556, 556], [534, 694], [468, 792]],
+// ALIVE. The same koi, swimming: t in seconds. A carangiform swimmer: the wave travels nose to
+// tail, its amplitude growing toward the tail (the head barely yaws, the peduncle swings wide),
+// one tail beat every 2 s, the way a koi cruises. Everything hung on the body (fins, tail,
+// markings, scales, shadow) follows it for free. Undefined = the still plate, pixel for pixel.
+export type KoiLive = { t: number; amp?: number; beat?: number; pose?: KoiPose }; // amp 0..1 eases the swim in from the still pose; beat = seconds per tail beat
+// where the fish is: its spine's centroid placed at (x, y), turned by rot, scaled by k. koiWorld swims it along a path.
+export type KoiPose = { x: number; y: number; rot: number; k: number; straight?: number; bend?: number }; // straight 0..1: the plate's turning curve relaxed toward a straight cruise; bend: into a turn (+ = tail swings right of travel)
+const SPINE: P[] = [[300, 222], [404, 292], [502, 408], [556, 556], [534, 694], [468, 792]];
+export const KOI_BEAT = 2; // seconds per tail beat: every live motion's period divides 2 s, so 2 s loops
+export const SPINE_C: P = [SPINE.reduce((a, p) => a + p[0], 0) / SPINE.length, SPINE.reduce((a, p) => a + p[1], 0) / SPINE.length];
+export const SPINE_HEADING = Math.atan2(SPINE[0][1] - SPINE_C[1], SPINE[0][0] - SPINE_C[0]); // the way the plate's koi is facing
+const swim = (live: KoiLive): P[] => {
+ const ph = (2 * Math.PI * live.t) / (live.beat ?? KOI_BEAT), q = live.pose;
+ const place = (p: P): P => { if (!q) return p; const c = Math.cos(q.rot), s = Math.sin(q.rot), dx = p[0] - SPINE_C[0], dy = p[1] - SPINE_C[1]; return [q.x + (dx * c - dy * s) * q.k, q.y + (dx * s + dy * c) * q.k]; };
+ // a cruising fish is nearly straight: relax the authored curve toward a straight spine of the same
+ // length (laid back from the head along the plate's facing), then bend it into the current turn
+ const st = q?.straight ?? 0, bd = q?.bend ?? 0, ax: P = [Math.cos(SPINE_HEADING), Math.sin(SPINE_HEADING)];
+ let acc = 0; const seg = SPINE.map((p, i) => (i ? (acc += Math.hypot(p[0] - SPINE[i - 1][0], p[1] - SPINE[i - 1][1])) : 0));
+ const line = seg.map((d) => [-ax[0] * d, -ax[1] * d] as P), lc: P = [line.reduce((a, p) => a + p[0], 0) / line.length, line.reduce((a, p) => a + p[1], 0) / line.length];
+ const base = SPINE.map((p, i) => { const u = i / (SPINE.length - 1), sp: P = [SPINE_C[0] + line[i][0] - lc[0], SPINE_C[1] + line[i][1] - lc[1]], m: P = [p[0] + (sp[0] - p[0]) * st, p[1] + (sp[1] - p[1]) * st], side = bd * 70 * u * u; return [m[0] - ax[1] * side, m[1] + ax[0] * side] as P; });
+ return base.map((p, i) => {
+ const a = base[Math.max(0, i - 1)], c = base[Math.min(base.length - 1, i + 1)], dx = c[0] - a[0], dy = c[1] - a[1], l = Math.hypot(dx, dy) || 1, u = i / (base.length - 1);
+ const amp = (4 + 30 * Math.pow(u, 1.7)) * (live.amp ?? 1), off = amp * Math.sin(ph - u * 2.6);
+ return place([p[0] - (dy / l) * off, p[1] + (dx / l) * off]);
+ });
+};
+export const koiBody = (live?: KoiLive): Body => body(
+ live ? swim(live) : SPINE,
profile([[0, 0], [0.012, 27], [0.035, 46], [0.08, 64], [0.16, 80], [0.27, 90], [0.4, 88], [0.55, 78], [0.7, 60], [0.82, 40], [0.92, 26], [1, 22]]),
);
// a fin in the body's frame: rays fan from a root between two edge points out to a rounded paddle
-const fin = (root0: P, root1: P, tip: P, spread: number, bulge: number, seed: number, rays = 8): { shape: P[]; rays: P[][] } => {
+export const fin = (root0: P, root1: P, tip: P, spread: number, bulge: number, seed: number, rays = 8): { shape: P[]; rays: P[][] } => {
const r = rng(seed), mid = lerpP(root0, root1, 0.5), dx = tip[0] - mid[0], dy = tip[1] - mid[1], len = Math.hypot(dx, dy), ux = dx / len, uy = dy / len, nx = -uy, ny = ux;
const tipAt = (a: number): P => { const k = len * (1 - a * a * 0.34) * (0.985 + r() * 0.03); return [mid[0] + ux * k + nx * (a * spread + bulge * (1 - a * a)), mid[1] + uy * k + ny * (a * spread + bulge * (1 - a * a))]; };
const tips = Array.from({ length: rays }, (_, i) => tipAt(-1 + (2 * i) / (rays - 1)));
@@ -55,7 +81,7 @@ const fin = (root0: P, root1: P, tip: P, spread: number, bulge: number, seed: nu
// the caudal fin: a centreline that keeps turning at the body's own curvature, two long lobes
// either side of it that open out, wave, and part at a notch
-const tail = (b: Body): { shape: P[]; rays: P[][] } => {
+export const tail = (b: Body): { shape: P[]; rays: P[][] } => {
const t1 = b.tan(1), t0 = b.tan(0.9), th0 = Math.atan2(t1[1], t1[0]), dTh = Math.atan2(t0[1] * t1[0] - t0[0] * t1[1], t0[0] * t1[0] + t0[1] * t1[1]);
const kappa = (-dTh / 60) * 2.6, root = b.at(0.955, 0), line: P[] = [root], heads: number[] = [th0];
for (let i = 1; i <= 26; i++) { const th = th0 + kappa * i * 10; heads.push(th); const q = line[i - 1]; line.push([q[0] + Math.cos(th) * 10, q[1] + Math.sin(th) * 10]); }
@@ -88,7 +114,7 @@ export const padShape = (cx: number, cy: number, rr: number, notch: number, seed
for (let i = 0; i <= 40; i++) { const a = notch + 0.2 + (i / 40) * (Math.PI * 2 - 0.4); rim.push([cx + Math.cos(a) * rr * (1 + (r() - 0.5) * 0.03), cy + Math.sin(a) * rr * 0.93 * (1 + (r() - 0.5) * 0.03)]); }
return [[cx, cy], ...rim];
};
-const lilyPad = (g: Gfx, cx: number, cy: number, rr: number, notch: number, seed: number, k: KoiClock = ALL, el = "pad") => {
+export const lilyPad = (g: Gfx, cx: number, cy: number, rr: number, notch: number, seed: number, k: KoiClock = ALL, el = "pad") => {
const pad = padShape(cx, cy, rr, notch, seed), rim = pad.slice(1);
const fl = k(el, "flat"), sh = k(el, "shade"), dt = k(el, "detail"), ln = k(el, "line");
g.group("plain", () => {
@@ -102,7 +128,7 @@ const lilyPad = (g: Gfx, cx: number, cy: number, rr: number, notch: number, seed
});
};
-const waterLily = (g: Gfx, cx: number, cy: number, s: number, seed: number, kc: KoiClock = ALL, el = "lily") => {
+export const waterLily = (g: Gfx, cx: number, cy: number, s: number, seed: number, kc: KoiClock = ALL, el = "lily") => {
const r = rng(seed), fl = kc(el, "flat"), shd = kc(el, "shade"), dt = kc(el, "detail"), ln = kc(el, "line");
let j = 0; // petals are laid in the order they stack: back row first
const petal = (a: number, len: number, wid: number, col: string, sh: string, k: number) => {
@@ -124,13 +150,13 @@ const waterLily = (g: Gfx, cx: number, cy: number, s: number, seed: number, kc:
});
};
-const ripples = (g: Gfx, cx: number, cy: number, seed: number, kc: KoiClock = ALL) => {
+export const ripples = (g: Gfx, cx: number, cy: number, seed: number, kc: KoiClock = ALL, drift = 0, scale = 1) => {
// surface rings, broken where the light catches them: the one place the water shows its skin
const r = rng(seed), dt = kc("ripples", "detail");
g.group("plain", () => {
- [58, 104, 156].forEach((rad, k) => {
- let a = r() * 6;
- for (let s = 0; s < 5; s++) { const span = 0.55 + r() * 0.6, pts: P[] = []; for (let i = 0; i <= 12; i++) { const t = a + (i / 12) * span; pts.push([cx + Math.cos(t) * rad * 1.35, cy + Math.sin(t) * rad * 0.62]); } inkP(g, pts, "#d9fbf6", { w: 4.4 - k * 1.1, shadow: 0, taper: [0.3, 0.3], seed: seed + k * 10 + s }, 0.85 - k * 0.18, part(dt, k * 5 + s, 15)); a += span + 0.35 + r() * 0.5; }
+ [58, 104, 156].forEach((rad0, k) => {
+ let a = r() * 6; const rad = rad0 + 48 * drift, fade = drift ? Math.max(0, Math.min(1, (rad - 58) / 30, (212 - rad) / 50)) : 1; if (fade <= 0) { for (let s = 0; s < 5; s++) r(), r(), r(); return; }
+ for (let s = 0; s < 5; s++) { const span = 0.55 + r() * 0.6, pts: P[] = []; for (let i = 0; i <= 12; i++) { const t = a + (i / 12) * span; pts.push([cx + Math.cos(t) * rad * 1.35 * scale, cy + Math.sin(t) * rad * 0.62 * scale]); } inkP(g, pts, "#d9fbf6", { w: (4.4 - k * 1.1) * Math.sqrt(scale), shadow: 0, taper: [0.3, 0.3], seed: seed + k * 10 + s }, (0.85 - k * 0.18) * fade, part(dt, k * 5 + s, 15)); a += span + 0.35 + r() * 0.5; }
});
});
};
@@ -150,23 +176,19 @@ const pencilLayIn = (g: Gfx, k: KoiClock, b: Body, fins: { shape: P[] }[], cau:
});
};
-export const drawKoi = (ctx: Ctx, _frame: number, env: Env, clock?: KoiClock) => {
- const g = new Gfx(ctx, env, 0, PENCIL), k = clock ?? ALL;
- ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
- const b = koiBody();
- // pectorals on the outside of the curve spread wide; the inside one is tucked and foreshortened
- const pecR = fin(b.at(0.17, 0.9), b.at(0.285, 0.9), b.at(0.33, 2.85), 70, 16, 71, 9);
- const pecL = fin(b.at(0.18, -0.9), b.at(0.27, -0.9), b.at(0.35, -2.25), 44, -10, 72, 8);
- const pelR = fin(b.at(0.53, 0.9), b.at(0.6, 0.9), b.at(0.66, 1.95), 30, 6, 73, 6);
- const pelL = fin(b.at(0.54, -0.9), b.at(0.6, -0.9), b.at(0.67, -1.8), 26, -5, 74, 6);
- const cau = tail(b);
- const fins = [pecR, pecL, pelR, pelL];
- if (clock) { // the process only: a bare sheet of marker paper, and the lay-in on it
- ctx.fillStyle = "#fbf9f3"; ctx.fillRect(0, 0, 1080, 1080);
- pencilLayIn(g, k, b, fins, cau, [padShape(905, 205, 168, 2.3, 3100), padShape(890, 905, 120, 3.6, 3300), padShape(120, 640, 88, 0.2, 3400)], [880, 195, 1.15]);
- }
- water(g, k);
-
+// pectorals on the outside of the curve spread wide; the inside one is tucked and foreshortened
+// live: the pectorals scull, out of phase with each other, a half beat behind the tail
+export const koiFins = (b: Body, live?: KoiLive) => { const sc = live ? Math.sin((2 * Math.PI * live.t) / KOI_BEAT - 1.4) * (live.amp ?? 1) : 0; return [
+ fin(b.at(0.17, 0.9), b.at(0.285, 0.9), b.at(0.33 - 0.03 * sc, 2.85 + 0.35 * sc), 70, 16, 71, 9),
+ fin(b.at(0.18, -0.9), b.at(0.27, -0.9), b.at(0.35 + 0.03 * sc, -2.25 + 0.3 * sc), 44, -10, 72, 8),
+ fin(b.at(0.53, 0.9), b.at(0.6, 0.9), b.at(0.66, 1.95), 30, 6, 73, 6),
+ fin(b.at(0.54, -0.9), b.at(0.6, -0.9), b.at(0.67, -1.8), 26, -5, 74, 6),
+]; };
+// the red hi markings, in the body's (t, s) frame: [t, s, half-length, half-width, seed]
+export const KOI_HI: [number, number, number, number, number][] = [[0.105, -0.05, 0.075, 0.95, 11], [0.36, -0.25, 0.1, 1.2, 12], [0.47, 0.35, 0.07, 0.9, 13], [0.66, -0.1, 0.085, 1.15, 14], [0.82, 0.3, 0.05, 0.9, 15]];
+// THE FISH: its floor shadow, fins, body and markings, dorsal, head and tail, on whatever b is.
+// Split out of drawKoi so the same fish can be posed anywhere (koiWorld swims it through a pond).
+export const drawFish = (g: Gfx, k: KoiClock, b: Body, fins: ReturnType<typeof koiFins>, cau: ReturnType<typeof tail>) => {
// the fish's shadow on the pond floor, flat and hard, down-right away from the light
const floor = [b.outline, cau.shape, ...fins.map((f) => f.shape)].map((s) => s.map(([x, y]) => [x + 30, y + 40] as P));
g.group("plain", () => lay(g, k("floor", "shade"), floor, () => floor.forEach((s) => fillShape(g, s, "#083b45", 0.5)), 5001, 34, 0.9));
@@ -194,7 +216,7 @@ export const drawKoi = (ctx: Ctx, _frame: number, env: Env, clock?: KoiClock) =>
if (bsh >= 1) fillShape(g, bsL, WHITE);
// red hi: head crown, a saddle across the back, a patch toward the tail. Crisp back edges.
const hf = k("hi", "flat"), hs = k("hi", "shade");
- const patches: [number, number, number, number, number][] = [[0.105, -0.05, 0.075, 0.95, 11], [0.36, -0.25, 0.1, 1.2, 12], [0.47, 0.35, 0.07, 0.9, 13], [0.66, -0.1, 0.085, 1.15, 14], [0.82, 0.3, 0.05, 0.9, 15]];
+ const patches = KOI_HI;
patches.forEach(([t, s, dt, ds, seed], pi) => {
const r = rng(seed * 17), pts: P[] = [];
for (let i = 0; i < 16; i++) { const a = (i / 16) * Math.PI * 2, kk = 0.8 + r() * 0.35; pts.push(b.at(t + Math.cos(a) * dt * kk, s + Math.sin(a) * ds * kk)); }
@@ -264,11 +286,30 @@ export const drawKoi = (ctx: Ctx, _frame: number, env: Env, clock?: KoiClock) =>
inkP(g, tailEdge, INK, { w: 4.4, light: LIGHT, shadow: 0.85, seed: 1710, side: -1, taper: [0.04, 0.04], min: 0.3 }, undefined, tln);
});
- ripples(g, 300, 196, 2100, k);
- lilyPad(g, 905, 205, 168, 2.3, 3100, k, "pad0");
- waterLily(g, 880, 195, 1.15, 3200, k);
- lilyPad(g, 890, 905, 120, 3.6, 3300, k, "pad1");
- lilyPad(g, 120, 640, 88, 0.2, 3400, k, "pad2");
+};
+
+export const drawKoi = (ctx: Ctx, _frame: number, env: Env, clock?: KoiClock, live?: KoiLive) => {
+ const g = new Gfx(ctx, env, 0, PENCIL), k = clock ?? ALL;
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ const b = koiBody(live);
+ const fins = koiFins(b, live), cau = tail(b);
+ if (clock) { // the process only: a bare sheet of marker paper, and the lay-in on it
+ ctx.fillStyle = "#fbf9f3"; ctx.fillRect(0, 0, 1080, 1080);
+ pencilLayIn(g, k, b, fins, cau, [padShape(905, 205, 168, 2.3, 3100), padShape(890, 905, 120, 3.6, 3300), padShape(120, 640, 88, 0.2, 3400)], [880, 195, 1.15]);
+ }
+ water(g, k);
+
+ drawFish(g, k, b, fins, cau);
+
+ // live: the pads ride the swell the fish leaves, each on its own phase; the rings drift out from the nose
+ const bob = (i: number): P => (live ? [(live.amp ?? 1) * 3 * Math.sin((2 * Math.PI * live.t) / (2 * KOI_BEAT) + i * 2.1), (live.amp ?? 1) * 4 * Math.sin((2 * Math.PI * live.t) / (2 * KOI_BEAT) + i * 2.1 + 1.2)] : [0, 0]);
+ if (live) { const nose = b.at(0, 0); ripples(g, nose[0], nose[1] - 26, 2100, k, (live.t / KOI_BEAT) % 1); }
+ else ripples(g, 300, 196, 2100, k);
+ const [p0, p1, p2] = [bob(0), bob(1), bob(2)];
+ lilyPad(g, 905 + p0[0], 205 + p0[1], 168, 2.3, 3100, k, "pad0");
+ waterLily(g, 880 + p0[0], 195 + p0[1], 1.15, 3200, k);
+ lilyPad(g, 890 + p1[0], 905 + p1[1], 120, 3.6, 3300, k, "pad1");
+ lilyPad(g, 120 + p2[0], 640 + p2[1], 88, 0.2, 3400, k, "pad2");
g.paper("paper", 0.05);
};
@@ -277,3 +318,10 @@ export const koi: Film = {
assets: { images: {} },
shots: [{ id: "koi", start: 0, end: 1, draw: drawKoi }],
};
+
+// the koi, alive: a 4 s loop (two tail beats; the pads' swell is one period), for the launch film and loops
+export const koiAlive: Film = {
+ meta: { title: "Koi · marker comic, alive", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: 120, kind: "loop" },
+ assets: { images: {} },
+ shots: [{ id: "swim", start: 0, end: 120, draw: (ctx, f, env) => drawKoi(ctx, f, env, undefined, { t: f / 30 }) }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koiAlive.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koiAlive.ts
new file mode 100644
index 0000000..fffa973
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koiAlive.ts
@@ -0,0 +1 @@
+export { koiAlive } from "./koi";
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koiWorld.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koiWorld.ts
new file mode 100644
index 0000000..12f3c77
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/koiWorld.ts
@@ -0,0 +1,123 @@
+// KOI WORLD. The marker-comic koi, swimming for real: it leaves the plate's pose, turns, picks up
+// speed and travels through a pond much bigger than the frame while the camera follows. The pads,
+// lilies, lit water, current streaks and drifting petals are placed in the WORLD, so the scenery
+// changes as the fish moves; it slides under pads (they are drawn over it and throw their shadows
+// on it); its wake rings spread from its nose.
+//
+// At t = 0 the world is framed exactly like the koi plate (the same pads, the same lit water, the
+// fish in the plate's pose), so the launch film can hand over from the still card without a seam.
+// World units are the plate's pixels, 1:1 (the fish's widths and fins are authored in pixels).
+import { Gfx, PENCIL, rng, type Ctx, type Env, type P } from "./core";
+import type { Film } from "./film";
+import { blob, fillShape, mix, smooth } from "./gallery";
+import { drawFish, inkP, koiBody, koiFins, lilyPad, ripples, SPINE_C, SPINE_HEADING, tail, waterLily, WATER, WATER_D, WATER_L, type KoiClock } from "./koi";
+
+const ALL: KoiClock = () => 1;
+const FPS = 30, DT = 1 / FPS;
+
+// ---------------------------------------------------------------- the swim path
+// Heading: the plate's koi faces up-left; it turns clockwise through 135 degrees in its first
+// 1.8 s (clear of the plate's big lily pad), then weaves gently. Speed builds from rest over 1.2 s: a cruising koi, not a dart.
+const CRUISE = 235; // world px per second
+const headingAt = (t: number) => {
+ const turn = (Math.PI * 135) / 180, u = Math.min(1, t / 1.8), e = u * u * (3 - 2 * u);
+ return SPINE_HEADING + turn * e + (t > 2.5 ? 0.3 * Math.sin((2 * Math.PI * (t - 2.5)) / 3.4) * Math.min(1, (t - 2.5) / 1.5) : 0);
+};
+const speedAt = (t: number) => CRUISE * Math.min(1, (t / 1.2) ** 1.6);
+let PATH: { p: P; h: number }[] | null = null;
+const path = () => {
+ if (PATH) return PATH;
+ PATH = [{ p: SPINE_C, h: SPINE_HEADING }];
+ for (let i = 1; i <= 30 * FPS; i++) { const t = i * DT, h = headingAt(t), v = speedAt(t), q = PATH[i - 1].p; PATH.push({ p: [q[0] + Math.cos(h) * v * DT, q[1] + Math.sin(h) * v * DT], h }); }
+ return PATH;
+};
+export const fishAt = (t: number) => { const P = path(), f = Math.max(0, Math.min(P.length - 1.001, t * FPS)), i = Math.floor(f), a = P[i], b = P[i + 1], u = f - i; return { p: [a.p[0] + (b.p[0] - a.p[0]) * u, a.p[1] + (b.p[1] - a.p[1]) * u] as P, h: a.h + (b.h - a.h) * u }; };
+
+// the camera: held on the plate's framing, then it eases into following the fish with a little
+// lag and lead room ahead of it (the frame looks where the fish is going)
+export const camAt = (t: number): P => {
+ const f = fishAt(Math.max(0, t - 0.35)), lead = 170 * Math.min(1, t / 2), want: P = [f.p[0] + Math.cos(f.h) * lead, f.p[1] + Math.sin(f.h) * lead];
+ const u = Math.min(1, Math.max(0, (t - 0.3) / 1.6)), e = u * u * (3 - 2 * u), home: P = [540, 540];
+ return [home[0] + (want[0] - home[0]) * e, home[1] + (want[1] - home[1]) * e];
+};
+
+// ---------------------------------------------------------------- the pond, placed in the world
+type Pad = { c: P; r: number; notch: number; seed: number; lily?: number };
+const PLATE_PADS: Pad[] = [{ c: [905, 205], r: 168, notch: 2.3, seed: 3100, lily: 1.15 }, { c: [890, 905], r: 120, notch: 3.6, seed: 3300 }, { c: [120, 640], r: 88, notch: 0.2, seed: 3400 }];
+let WORLD: { pads: Pad[]; lit: { c: P; rx: number; ry: number; seed: number; rot: number }[]; streaks: { p: P; l: number; a: number; w: number; seed: number }[]; petals: { p: P; seed: number }[] } | null = null;
+const world = () => {
+ if (WORLD) return WORLD;
+ const r = rng(8123), P = path(), pads: Pad[] = [...PLATE_PADS], lit = [{ c: [560, 540] as P, rx: 610, ry: 470, seed: 401, rot: -0.75 }, { c: [520, 520] as P, rx: 400, ry: 290, seed: 402, rot: -0.9 }];
+ const clear = (c: P, r0: number) => pads.every((q) => Math.hypot(q.c[0] - c[0], q.c[1] - c[1]) > q.r + r0 + 60);
+ const lane = (c: P, r0: number) => P.every((q, j) => j % 6 !== 0 || Math.hypot(q.p[0] - c[0], q.p[1] - c[1]) > r0 + 230);
+ for (let i = 45; i < P.length; i += 9) {
+ const { p, h } = P[i];
+ for (const side of [-1, 1]) {
+ if (r() < 0.5) continue;
+ const d = 330 + r() * 420, c: P = [p[0] - Math.sin(h) * d * side + (r() - 0.5) * 120, p[1] + Math.cos(h) * d * side + (r() - 0.5) * 120], rad = 70 + r() * 110;
+ if (clear(c, rad) && lane(c, rad)) pads.push({ c, r: rad, notch: r() * Math.PI * 2, seed: 5000 + pads.length * 17, lily: r() < 0.3 ? 0.75 + r() * 0.35 : undefined });
+ }
+ // the one pad it swims under is the plate's own lily pad, early on; the lane stays clear after that
+ if (i % 18 === 0) lit.push({ c: [p[0] + (r() - 0.5) * 700, p[1] + (r() - 0.5) * 700], rx: 420 + r() * 300, ry: 280 + r() * 200, seed: 600 + i, rot: -0.7 + (r() - 0.5) * 0.4 });
+ }
+ const streaks = Array.from({ length: 140 }, (_, i) => { const q = P[Math.floor(r() * (P.length - 1))].p; return { p: [q[0] + (r() - 0.5) * 1900, q[1] + (r() - 0.5) * 1300] as P, l: 70 + r() * 150, a: -0.42 + (r() - 0.5) * 0.12, w: 5 + r() * 5, seed: 500 + i }; });
+ const petals = Array.from({ length: 40 }, (_, i) => { const q = P[Math.floor(r() * (P.length - 1))].p; return { p: [q[0] + (r() - 0.5) * 1700, q[1] + (r() - 0.5) * 1100] as P, seed: 9000 + i }; });
+ return (WORLD = { pads, lit, streaks, petals });
+};
+
+// ---------------------------------------------------------------- drawing
+export type KoiWorldView = { t: number; amp?: number };
+export const drawKoiWorld = (ctx: Ctx, env: Env, v: KoiWorldView) => {
+ const W = env.W, H = env.H, t = v.t, cam = camAt(t), V = (p: P): P => [p[0] - cam[0] + W / 2, p[1] - cam[1] + H / 2];
+ const onScreen = (p: P, pad: number) => { const q = V(p); return q[0] > -pad && q[0] < W + pad && q[1] > -pad && q[1] < H + pad; };
+ const g = new Gfx(ctx, env, 0, PENCIL), w = world(), flow = 9 * t; // the current carries the surface slowly down-right
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ // water: deep everywhere, the lit bodies of water where the sun gets in, the current's streaks
+ g.group("plain", () => {
+ const sq: P[] = [[-10, -10], [W + 10, -10], [W + 10, H + 10], [-10, H + 10]];
+ fillShape(g, sq, WATER_D);
+ w.lit.forEach((l, i) => { if (!onScreen(l.c, Math.max(l.rx, l.ry) + 60)) return; const c = V(l.c); fillShape(g, blob(c[0], c[1], l.rx, l.ry, l.seed, 0.1, 20, l.rot), i === 1 ? mix(WATER, WATER_L, 0.22) : WATER); });
+ w.streaks.forEach((s) => {
+ const p: P = [s.p[0] + flow, s.p[1] + flow * 0.45]; if (!onScreen(p, 240)) return;
+ const q = V(p), ln = smooth([q, [q[0] + Math.cos(s.a) * s.l * 0.5, q[1] + Math.sin(s.a) * s.l * 0.5 + 3], [q[0] + Math.cos(s.a) * s.l, q[1] + Math.sin(s.a) * s.l]], false, 6);
+ inkP(g, ln, WATER_L, { w: s.w, shadow: 0, taper: [0.4, 0.4], seed: s.seed }, 0.45, 1);
+ });
+ });
+ // the fish, posed on the path, beating its tail faster as it cruises
+ const f = fishAt(t), sp = speedAt(t) / CRUISE, amp = v.amp ?? 1;
+ const turn = (fishAt(t + 0.1).h - fishAt(t - 0.1).h) / 0.2; // rad/s: the body bends into the turn
+ const live = { t, amp: amp * (0.55 + 0.45 * sp), beat: 2 - 0.9 * sp, pose: { x: V(f.p)[0], y: V(f.p)[1], rot: f.h - SPINE_HEADING, k: 1, straight: 0.8 * sp * amp, bend: -Math.max(-1, Math.min(1, turn * 1.1)) * amp } };
+ const b = koiBody(live), fins = koiFins(b, live), cau = tail(b);
+ drawFish(g, ALL, b, fins, cau);
+ const nose = b.at(0, 0);
+ ripples(g, nose[0], nose[1], 2100, ALL, (t / 1.2) % 1, 0.8);
+ // petals riding the current, turning slowly
+ g.group("plain", () => w.petals.forEach((pt) => {
+ const r = rng(pt.seed), p: P = [pt.p[0] + flow * (1.4 + r()), pt.p[1] + flow * 0.6 + 10 * Math.sin(t * 0.8 + pt.seed)]; if (!onScreen(p, 30)) return;
+ const q = V(p), a = pt.seed * 0.7 + t * (0.4 + r() * 0.5) * (r() < 0.5 ? -1 : 1), s = 9 + r() * 5;
+ const shape = blob(q[0], q[1], s * 1.25, s * 0.7, pt.seed, 0.08, 10, a);
+ fillShape(g, shape, r() < 0.5 ? "#ffd3e0" : "#fff0f4"); inkP(g, shape, "#15122a", { w: 2, closed: true, shadow: 0, seed: pt.seed }, 0.9, 1);
+ }));
+ // pads over everything in the water: the fish slides under them; each rides the swell on its own phase
+ w.pads.forEach((pd, i) => {
+ if (!onScreen(pd.c, pd.r + 60)) return;
+ const bob: P = [3 * Math.sin(t * 1.6 + i * 2.1), 4 * Math.sin(t * 1.6 + i * 2.1 + 1.2)], c = V([pd.c[0] + bob[0], pd.c[1] + bob[1]]);
+ lilyPad(g, c[0], c[1], pd.r, pd.notch, pd.seed, ALL, "pad");
+ if (pd.lily) waterLily(g, c[0] - pd.r * 0.15, c[1] - pd.r * 0.06, pd.lily, pd.seed + 100, ALL);
+ });
+ g.paper("paper", 0.05);
+};
+
+const film = (W: number, H: number, N: number, title: string): Film => ({
+ meta: { title, W, H, fps: FPS, bpm: 90, durationFrames: N },
+ assets: { images: {} },
+ shots: [{ id: "swim", start: 0, end: N, draw: (ctx, fr, env) => drawKoiWorld(ctx, env, { t: fr / FPS, amp: Math.min(1, fr / 20) }) }],
+});
+export const koiWorld = film(1920, 1080, 300, "Koi · marker comic, swimming through the pond");
+export const koiWorldSquare = film(1080, 1080, 300, "Koi · marker comic, swimming (square)");
+
+// where the lily-flower pads are on screen at time t, for a camera move that dives into one
+export const padsOnScreen = (t: number, W: number, H: number) => {
+ const cam = camAt(t), w = world();
+ return w.pads.map((pd, i) => { const bob: P = [3 * Math.sin(t * 1.6 + i * 2.1), 4 * Math.sin(t * 1.6 + i * 2.1 + 1.2)]; return { i, x: pd.c[0] + bob[0] - cam[0] + W / 2, y: pd.c[1] + bob[1] - cam[1] + H / 2, r: pd.r, lily: !!pd.lily }; });
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch.ts
new file mode 100644
index 0000000..16f6dfd
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch.ts
@@ -0,0 +1,440 @@
+// LAUNCH. The anidoodle launch film, 1920x1080, 30 fps, 104 s on the 90 bpm grid of its own score
+// (a beat is 20 frames, a bar 80: every scene starts on a bar the music changes on).
+//
+// THE STORY is one sentence, told from the user's chair: you can make images, illustrations,
+// loops, animations and films, in pure code. A person types into a chat and presses Generate; the
+// Generate button becomes a drop of ink that blooms into the answer. Each request opens a chapter,
+// and the chapter's word writes itself onto a rail at the left as it is delivered:
+// Illustrations the koi draws itself, stroke by stroke
+// Animations "now make it swim": the card breaks out to the full frame and the koi swims
+// through a pond bigger than the screen, the camera following
+// Images the camera dives into a lily pad and the plates bloom out of shared circles
+// (watch face, full moon, crayon balloon); then a painter's hand, borrowed
+// Animations the crayon balloon rebuilds itself in toy bricks and flies over a brick world
+// Loops an embroidery that stitches itself, on a seamless loop
+// Animations a live page: Bit watches the real pointer
+// Films the butterfly film with its own score
+// then the words gather in the order of the sentence and "All in pure code." lands on the
+// score's home chord, the film pulls back into the editor that draws it, and the name writes itself.
+//
+// Every plate on screen is that plate's own code drawing live (launchKit.plateLayer): no recordings.
+// The one image is a public-domain painting the user "brings" (Van Gogh, Almond Blossom, 1890),
+// pinned in assets and shown only as the attachment; the answer is adaptAlmond. The sound is code
+// too: the score (music/pieces/launch.ts) plus the UI's clicks, thocks, plips and whooshes below.
+import { rng, type Ctx, type Env, type P } from "./core";
+import type { Film } from "./film";
+import {
+ C, CHAT, GEN, HOME, INPUT, MONO, REPLY, SANS, TEXT, artCard, blot, camLerp, caretAt, clamp, drawChatFrame, expo, inOut, lerp, lerpP,
+ out3, pathOf, plateLayer, pointer, press, ramp, rr, selfLayer, softShadow, spring, useCam, type Cam, type ChatState,
+} from "./launchKit";
+import { koiDraw } from "./koiDraw";
+import { koi } from "./koi";
+import { koiWorld, padsOnScreen } from "./koiWorld";
+import { pocketWatch } from "./pocketWatch";
+import { moonPhases } from "./moonPhases";
+import { balloon } from "./balloon";
+import { brickBalloon } from "./brickBalloon";
+import { adaptAlmond } from "./adaptAlmond";
+import { embroideryAlive } from "./embroideryAlive";
+import { mascotHero } from "./mascotHero";
+import { stateAt, type InputLog } from "./input";
+import { mechanicalLepidoptera } from "./mechanicalLepidoptera";
+import { banner as bannerFilm } from "./banner";
+import { launchLofi } from "./music/pieces/launch";
+import { renderPiece } from "./music/render";
+
+const W = 1920, H = 1080, FPS = 30, BEAT = 20;
+
+// THE TIMELINE, in frames. Every boundary is on a bar of the score (80 frames).
+export const T = {
+ type: [0, 160], gen: [160, 240], draw: [240, 560], swim: [560, 880],
+ run: [880, 1120], brick: [1120, 1520], ref: [1520, 1840], emb: [1840, 2080],
+ web: [2080, 2400], film: [2400, 2720], reveal: [2720, 2960], end: [2960, 3120],
+} as const;
+const N = T.end[1];
+
+// ---------------------------------------------------------------- typing
+// when each character lands: a typist's rhythm, seeded, never mechanical. Later requests type
+// faster: the viewer has learned the move, the film should not make them wait for it.
+const charTimes = (text: string, t0: number, rate: number, seed: number) => {
+ const out: number[] = []; let t = t0;
+ for (let i = 0; i < text.length; i++) { const h = Math.sin((i + 1) * 12.9898 + seed * 78.233) * 43758.5453, j = h - Math.floor(h); t += rate * (0.55 + j * 0.9) + (text[i] === " " ? 0.8 * rate : 0); out.push(t); }
+ return out;
+};
+const typedAt = (text: string, f: number, t0: number, rate: number, seed: number) => text.slice(0, charTimes(text, t0, rate, seed).filter((t) => f >= t).length);
+
+// ---------------------------------------------------------------- cameras
+const CARD_C: P = [REPLY.x + REPLY.s / 2, REPLY.y + REPLY.s / 2];
+const CARD_CAM: Cam = { c: CARD_C, z: 1000 / REPLY.s }; // the reply card at 1000 px, centred
+const GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];
+
+// ---------------------------------------------------------------- 1 + 2: the first request, Generate, ink
+const KOI_PROMPT = "a koi turning under lily pads, marker comic";
+const KOI_TYPE = { t0: 14, rate: 2.0, seed: 7 };
+const PRESS = { down: T.gen[0], up: T.gen[0] + 6 };
+const DROP = { t0: PRESS.up + 6, land: PRESS.up + 22, full: PRESS.up + 60 };
+const KOI_SPEED = 1.5, KOI_DONE = DROP.land + (koiDraw.meta.durationFrames - 30) / KOI_SPEED;
+const koiLayer = (env: Env, f: number) => (f < KOI_DONE ? plateLayer(env, "koiDraw", koiDraw, (f - DROP.land) * KOI_SPEED, 1080) : plateLayer(env, "koi", koi, 0, 1080));
+
+const typeCam = (ctx: Ctx, f: number): Cam => {
+ const typed = typedAt(KOI_PROMPT, f, KOI_TYPE.t0, KOI_TYPE.rate, KOI_TYPE.seed), [cx] = caretAt(ctx, typed);
+ const macro: Cam = { c: [Math.max(TEXT.x + 330, cx - 110), 934], z: 2.7 };
+ return f < 112 ? macro : camLerp(macro, HOME, expo(ramp(f, 112, 150)));
+};
+const leanCam = (f: number): Cam => { const lean = expo(ramp(f, DROP.land - 4, DROP.full + 20)) * 0.09; return { c: lerpP(HOME.c, CARD_C, lean * 1.6), z: 1 + lean }; };
+
+// the ink: the button's ink wells up, lets go, arcs into the reply with a drawn smear, and blooms
+const drawInk = (ctx: Ctx, env: Env, f: number, D: typeof DROP, art: CanvasImageSource, card = REPLY) => {
+ if (f < PRESS.up && D === DROP) return;
+ const land: P = [card.x + card.s / 2, card.y + card.s / 2], R0 = 30;
+ if (f < D.t0) { const w = out3(ramp(f, D.t0 - 6, D.t0)); ctx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(GEN_C[0], GEN.y + 6 - w * 22, R0 * (0.3 + 0.7 * w), 0, Math.PI * 2); ctx.fill(); return; }
+ if (f < D.land) {
+ const at = (g: number): P => { const u = ramp(g, D.t0, D.land), e = inOut(u); return [lerp(GEN_C[0], land[0], e), lerp(GEN.y - 16, land[1], e) - Math.sin(Math.PI * u) * 170]; };
+ for (let k = 30; k >= 0; k--) { const p = at(f - k * 0.1), r = R0 * (1 - k * 0.022) * (1 - 0.25 * Math.sin(Math.PI * ramp(f, D.t0, D.land))); ctx.fillStyle = C.ink; ctx.globalAlpha = k === 0 ? 1 : 0.22 * (1 - k / 31); ctx.beginPath(); ctx.arc(p[0], p[1], r, 0, Math.PI * 2); ctx.fill(); }
+ ctx.globalAlpha = 1; return;
+ }
+ const u = ramp(f, D.land, D.full), R = lerp(18, card.s * 0.8, out3(u)), rim = lerp(40, 0, ramp(u, 0.55, 1));
+ ctx.save(); rr(ctx, card.x, card.y, card.s, card.s, 22); ctx.clip();
+ pathOf(ctx, blot(land, R + rim, 311)); ctx.fillStyle = C.ink; ctx.fill();
+ pathOf(ctx, blot(land, Math.max(0, R - 6), 311)); ctx.clip();
+ ctx.fillStyle = C.paper; ctx.fillRect(card.x, card.y, card.s, card.s); ctx.drawImage(art, card.x, card.y, card.s, card.s);
+ ctx.restore();
+ for (let i = 0; i < 9; i++) { const a = i * 2.39 + 0.4, d = 30 + (i % 3) * 22 + 160 * out3(ramp(u, 0, 0.3)), s = (1 - ramp(u, 0.12, 0.34)) * (4 + (i % 4) * 2.5); if (s <= 0.2) continue; ctx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(land[0] + Math.cos(a) * d, land[1] + Math.sin(a) * d, s, 0, Math.PI * 2); ctx.fill(); }
+};
+
+const sceneOpen = (ctx: Ctx, env: Env, f: number) => {
+ useCam(ctx, env, f < T.gen[0] ? typeCam(ctx, f) : leanCam(f));
+ const typed = typedAt(KOI_PROMPT, f, KOI_TYPE.t0, KOI_TYPE.rate, KOI_TYPE.seed);
+ const s: ChatState = {
+ typed: f < PRESS.up ? typed : "", caret: f < PRESS.up && (Math.floor(f / 8) % 2 === 0 || typed.length < KOI_PROMPT.length),
+ placeholder: "Describe what you want drawn…",
+ sent: f >= PRESS.up ? KOI_PROMPT : undefined, sentAlpha: ramp(f, PRESS.up, PRESS.up + 10),
+ genPress: press(f, PRESS.down, PRESS.up), genHot: ramp(f, 150, 158),
+ label: f >= DROP.land ? "marker comic" : undefined, labelAlpha: ramp(f, DROP.land, DROP.land + 10),
+ };
+ drawChatFrame(ctx, s);
+ if (f >= DROP.land) softShadow(ctx, REPLY.x, REPLY.y, REPLY.s, REPLY.s, 22, ramp(f, DROP.land, DROP.full));
+ drawInk(ctx, env, f, DROP, koiLayer(env, f).canvas);
+ if (f >= 112) pointer(ctx, lerpP([1760, 1130], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, 116, 158))), press(f, PRESS.down, PRESS.up) * 0.8);
+};
+const sceneDraw = (ctx: Ctx, env: Env, f: number) => {
+ useCam(ctx, env, camLerp(leanCam(f), CARD_CAM, expo(ramp(f, T.draw[0] + 8, T.draw[0] + 80))));
+ drawChatFrame(ctx, { typed: "", caret: false, placeholder: "Describe what you want drawn…", sent: KOI_PROMPT, label: "marker comic" });
+ artCard(ctx, REPLY.x, REPLY.y, REPLY.s, koiLayer(env, f));
+};
+
+// ---------------------------------------------------------------- a request (the rest of the chat)
+// The previous answer rides back into the thread and away, the user types, presses Generate, the
+// button's ink flies into the reply and the answer blooms and plays. `push` leans into the card.
+type Art = { L: CanvasImageSource; w: number; h: number; crop?: [number, number, number, number] };
+type Turn = { prompt: string; label: string; t0: number; attach?: string; rate?: number; seed: number };
+const turnState = (tn: Turn) => {
+ const times = charTimes(tn.prompt, tn.t0 + 10, tn.rate ?? 0.9, tn.seed), end = times[times.length - 1], down = Math.ceil(end + 6), up = down + 5;
+ return { times, typeFrom: tn.t0 + 10, end, down, up, drop: { t0: up + 6, land: up + 22, full: up + 60 }, landAt: up + 22, fullAt: up + 60 };
+};
+const fitCard = (a: Art) => { const hMax = INPUT.y - 40 - REPLY.y, k = Math.min(1, hMax / ((REPLY.s * a.h) / a.w)), s = Math.round(REPLY.s * k); return { s, h: Math.round((s * a.h) / a.w) }; };
+const drawArt = (ctx: Ctx, a: Art, x: number, y: number, w: number, h: number) => { if (a.crop) ctx.drawImage(a.L, ...a.crop, x, y, w, h); else ctx.drawImage(a.L, x, y, w, h); };
+const sceneTurn = (ctx: Ctx, env: Env, f: number, tn: Turn, art: (f: number) => Art | null, o: { prev?: Art | null; push?: boolean } = {}) => {
+ const k = turnState(tn), pushU = o.push ? expo(ramp(f, k.fullAt + 10, k.fullAt + 50)) : 0;
+ useCam(ctx, env, camLerp(HOME, CARD_CAM, pushU));
+ const typed = typedAt(tn.prompt, f, k.typeFrom, tn.rate ?? 0.9, tn.seed), img = tn.attach ? env.image?.(tn.attach) : undefined;
+ drawChatFrame(ctx, {
+ typed: f < k.up ? typed : "", caret: f < k.up, placeholder: "Describe what you want drawn…",
+ sent: f >= k.up ? tn.prompt : undefined, sentAlpha: ramp(f, k.up, k.up + 10),
+ attach: f >= k.up && img ? { img, label: "" } : null,
+ genPress: press(f, k.down, k.up), genHot: ramp(f, k.down - 8, k.down),
+ label: f >= k.landAt ? tn.label : undefined, labelAlpha: ramp(f, k.landAt, k.landAt + 10),
+ });
+ // the previous answer rides up out of the thread as the new request starts
+ if (o.prev && f < k.landAt) { const u = inOut(ramp(f, tn.t0, tn.t0 + 16)), c = fitCard(o.prev); ctx.globalAlpha = 1 - u; ctx.save(); ctx.translate(0, -120 * u); artCard(ctx, REPLY.x, REPLY.y, c.s, null); rr(ctx, REPLY.x, REPLY.y, c.s, c.h, 22); ctx.clip(); drawArt(ctx, o.prev, REPLY.x, REPLY.y, c.s, c.h); ctx.restore(); ctx.globalAlpha = 1; }
+ if (img && f < k.up) { const u = out3(ramp(f, tn.t0, tn.t0 + 12)); ctx.globalAlpha = u; ctx.save(); rr(ctx, INPUT.x + INPUT.w - 420, INPUT.y + 16, 104, 72, 12); ctx.clip(); ctx.drawImage(img, INPUT.x + INPUT.w - 420, INPUT.y + 16, 104, 72); ctx.restore(); ctx.globalAlpha = 1; }
+ const a = f >= k.drop.t0 - 6 ? art(f) : null;
+ if (a && f < k.landAt) drawInk(ctx, env, f, k.drop, a.L); // the drop in flight (the bloom below takes over at landing)
+ if (a && f >= k.landAt) {
+ const { s, h } = fitCard(a), grow = out3(ramp(f, k.landAt, k.fullAt)), R = lerp(18, Math.hypot(s, h), grow), c: P = [REPLY.x + s / 2, REPLY.y + h / 2];
+ softShadow(ctx, REPLY.x, REPLY.y, s, h, 22, grow);
+ ctx.save(); rr(ctx, REPLY.x, REPLY.y, s, h, 22); ctx.clip();
+ if (grow < 1) { pathOf(ctx, blot(c, R + 30 * (1 - grow), 77)); ctx.fillStyle = C.ink; ctx.fill(); pathOf(ctx, blot(c, Math.max(0, R - 5), 77)); ctx.clip(); }
+ ctx.fillStyle = C.paper; ctx.fillRect(REPLY.x, REPLY.y, s, h); drawArt(ctx, a, REPLY.x, REPLY.y, s, h); ctx.restore();
+ }
+ pointer(ctx, lerpP([GEN_C[0] + 240, GEN_C[1] + 160], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, k.end - 14, k.down))), press(f, k.down, k.up) * 0.8);
+ return k;
+};
+// the previous answer, still: the chat pulls back from it before the next request
+const pullBack = (ctx: Ctx, env: Env, f: number, from: number, to: number, prev: Art) => {
+ useCam(ctx, env, camLerp(CARD_CAM, HOME, expo(ramp(f, from, to))));
+ drawChatFrame(ctx, { typed: "", caret: false, placeholder: "Describe what you want drawn…" });
+ const c = fitCard(prev); softShadow(ctx, REPLY.x, REPLY.y, c.s, c.h, 22, 1.4);
+ ctx.save(); rr(ctx, REPLY.x, REPLY.y, c.s, c.h, 22); ctx.clip(); ctx.fillStyle = C.paper; ctx.fillRect(REPLY.x, REPLY.y, c.s, c.h); drawArt(ctx, prev, REPLY.x, REPLY.y, c.s, c.h); ctx.restore();
+};
+
+// ---------------------------------------------------------------- 3: "now make it swim"
+const SWIM: Turn = { prompt: "now make it swim", label: "animation · swimming through the pond", t0: T.swim[0] + 30, seed: 11 };
+const SW = turnState(SWIM), SWIM_OPEN = SW.fullAt, SWIM_FULL = SW.fullAt + 30; // the card breaks out to the full frame
+const swimFrame = (f: number) => Math.max(0, f - SWIM_OPEN);
+const worldLayer = (env: Env, f: number, px = 1920) => plateLayer(env, `world${px}`, koiWorld, swimFrame(f), px);
+const SQUARE: [number, number, number, number] = [420, 0, 1080, 1080]; // at t = 0 the world is framed like the plate: this square IS the koi plate
+const sceneSwim = (ctx: Ctx, env: Env, f: number) => {
+ const koiArt: Art = { L: plateLayer(env, "koi", koi, 0, 1080).canvas, w: 1080, h: 1080 };
+ if (f < SWIM.t0) return pullBack(ctx, env, f, T.swim[0], SWIM.t0, koiArt);
+ if (f < SWIM_OPEN) { sceneTurn(ctx, env, f, SWIM, () => ({ L: worldLayer(env, f).canvas, w: 1080, h: 1080, crop: SQUARE }), { prev: koiArt }); return; }
+ // the break-out: the card's frame opens to the whole screen while the fish starts to move
+ const u = expo(ramp(f, SWIM_OPEN, SWIM_FULL)), L = worldLayer(env, f).canvas;
+ useCam(ctx, env, HOME);
+ if (u < 1) { ctx.globalAlpha = 1 - u; drawChatFrame(ctx, { typed: "", caret: false, placeholder: "Describe what you want drawn…", sent: SWIM.prompt, label: SWIM.label }); ctx.globalAlpha = 1; }
+ const x = lerp(REPLY.x, 0, u), y = lerp(REPLY.y, 0, u), w = lerp(REPLY.s, W, u), h = lerp(REPLY.s, H, u), sx = lerp(SQUARE[0], 0, u), sw = lerp(1080, 1920, u);
+ ctx.save(); rr(ctx, x, y, w, h, 22 * (1 - u)); ctx.clip(); ctx.drawImage(L, sx, 0, sw, 1080, x, y, w, h); ctx.restore();
+};
+
+// ---------------------------------------------------------------- 4: the circle run (Images)
+// The camera dives into a lily pad in the swim, and the plates bloom out of shared circles:
+// lily pad -> watch face -> full moon -> balloon. Each handover: zoom into circle A, bloom B out of
+// it in ink with B's own circle exactly where A's was, zoom out on B.
+type Link = { film: Film; key: string; c: P; r: number };
+const RUN: Link[] = [
+ { film: pocketWatch, key: "watch", c: [468, 590], r: 256 },
+ { film: moonPhases, key: "moon", c: [539, 390], r: 70 },
+ { film: balloon, key: "balloon", c: [540, 352], r: 236 },
+];
+const RUN_T0 = T.run[0], STEP = 3 * BEAT, XF = 2 * BEAT;
+const O: P = [460, 40], SB = 1000 / 1080;
+// the pad the camera dives into: the lily pad nearest the right third of the frame as the run begins
+const DIVE = (() => { const t = swimFrame(RUN_T0) / FPS, pads = padsOnScreen(t, W, H).filter((p) => p.x > 200 && p.x < W - 200 && p.y > 150 && p.y < H - 150); const pick = [...pads].sort((a, b) => Number(b.lily) - Number(a.lily) || Math.hypot(a.x - 1300, a.y - 540) - Math.hypot(b.x - 1300, b.y - 540))[0]; return pick.i; })();
+const diveCircle = (f: number) => { const p = padsOnScreen(swimFrame(f) / FPS, W, H)[DIVE]; return { c: [p.x, p.y] as P, r: p.r * 0.9 }; };
+const bigR = (ra: number, rb: number) => Math.min(560, ra * 3.2, rb * 3.2 * 1.6);
+const mapOf = (L: Link, z01: number, R1: number) => {
+ const kb = R1 / L.r, fit = (c: number, span: number, side: number) => (kb * span < side ? side / 2 - kb * (span / 2 - c) : clamp(side / 2, side - kb * (span - c), kb * c));
+ const base = { at: [O[0] + SB * L.c[0], O[1] + SB * L.c[1]] as P, k: SB }, big = { at: [fit(L.c[0], 1080, W), fit(L.c[1], 1080, H)] as P, k: kb };
+ return { k: Math.exp(lerp(Math.log(base.k), Math.log(big.k), z01)), at: lerpP(base.at, big.at, z01) };
+};
+const drawPlateMapped = (ctx: Ctx, env: Env, L: Link, m: { k: number; at: P }) => {
+ const px = m.k > 1.4 ? 2160 : 1080, lay = plateLayer(env, L.key, L.film, 0, px), s = env.scale, x = m.at[0] - m.k * L.c[0], y = m.at[1] - m.k * L.c[1], size = 1080 * m.k;
+ ctx.setTransform(s, 0, 0, s, 0, 0);
+ softShadow(ctx, x, y, size, size, (22 * m.k) / SB, 1.3);
+ ctx.save(); rr(ctx, x, y, size, size, (22 * m.k) / SB); ctx.clip(); ctx.drawImage(lay.canvas, x, y, size, size); ctx.restore();
+};
+const shiftTo = (m: { k: number; at: P }, from: P, to: P, z01: number) => ({ k: m.k, at: [m.at[0] + (from[0] - to[0]) * z01, m.at[1] + (from[1] - to[1]) * z01] as P });
+const in3ish = (t: number) => { const c = clamp(t); return c * c * (2.2 - 1.2 * c); };
+const bloomInto = (ctx: Ctx, env: Env, at: P, grow: number, seed: number, drawB: () => void) => {
+ const R = lerp(0, 1500, in3ish(grow));
+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ pathOf(ctx, blot(at, R + 26 * (1 - grow), seed)); ctx.fillStyle = C.ink; ctx.fill();
+ pathOf(ctx, blot(at, Math.max(0, R - 4), seed)); ctx.clip();
+ ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H); drawB(); ctx.restore();
+};
+const sceneRun = (ctx: Ctx, env: Env, f: number) => {
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ const i = Math.min(RUN.length - 1, Math.floor((f - RUN_T0) / STEP)), u = (f - (RUN_T0 + i * STEP)) / XF;
+ const zin = expo(ramp(u, 0, 0.42)), zout = 1 - expo(ramp(u, 0.6, 1)), grow = ramp(u, 0.34, 0.66);
+ if (u >= 1) return drawPlateMapped(ctx, env, RUN[i], mapOf(RUN[i], 0, 1));
+ if (i === 0) { // A is the swim: zoom the full frame about the pad
+ const d = diveCircle(f), R1 = bigR(d.r, RUN[0].r), k = Math.exp(lerp(0, Math.log(R1 / d.r), zin)), at = lerpP(d.c, [W / 2, H / 2], zin);
+ const L = worldLayer(env, f, k > 1.8 ? 3840 : 1920).canvas;
+ ctx.drawImage(L, at[0] - k * d.c[0], at[1] - k * d.c[1], W * k, H * k);
+ if (grow > 0) { const mB0 = mapOf(RUN[0], 1, R1), mB = u < 0.6 ? { k: mB0.k, at } : shiftTo(mapOf(RUN[0], zout, R1), at, mB0.at, zout); bloomInto(ctx, env, mB.at, grow, 900, () => drawPlateMapped(ctx, env, RUN[0], mB)); }
+ return;
+ }
+ const A = RUN[i - 1], B = RUN[i], R1 = bigR(A.r, B.r);
+ drawPlateMapped(ctx, env, A, mapOf(A, zin, R1));
+ if (grow > 0) { const mA = mapOf(A, 1, R1), mB0 = mapOf(B, 1, R1), mB = u < 0.6 ? { k: mB0.k, at: mA.at } : shiftTo(mapOf(B, zout, R1), mA.at, mB0.at, zout); bloomInto(ctx, env, mB.at, grow, 900 + i, () => drawPlateMapped(ctx, env, B, mB)); }
+};
+
+// ---------------------------------------------------------------- 5: "now in toy bricks, and let it fly"
+const BRICK: Turn = { prompt: "now build it in toy bricks, and let it fly", label: "animation · toy bricks", t0: T.brick[0] + 30, seed: 13 };
+const BK = turnState(BRICK), BRICK_SPEED = (brickBalloon.meta.durationFrames - 1) / (T.brick[1] - 12 - BK.landAt);
+const brickArt = (env: Env, f: number): Art => ({ L: plateLayer(env, "brick", brickBalloon, (f - BK.landAt) * BRICK_SPEED, 1080).canvas, w: 1080, h: 1080 });
+const sceneBrick = (ctx: Ctx, env: Env, f: number) => {
+ const prev: Art = { L: plateLayer(env, "balloon", balloon, 0, 1080).canvas, w: 1080, h: 1080 };
+ if (f < BRICK.t0) return pullBack(ctx, env, f, T.brick[0], BRICK.t0, prev);
+ sceneTurn(ctx, env, f, BRICK, (g) => brickArt(env, Math.max(g, BK.landAt)), { prev, push: true });
+};
+
+// ---------------------------------------------------------------- 6: a painter's hand, borrowed
+const REF: Turn = { prompt: "my koi again, painted in this hand", label: "adapted · the almond-blossom hand", t0: T.ref[0] + 30, attach: "almond", seed: 17 };
+const RF = turnState(REF), ALMOND_SPEED = (adaptAlmond.meta.durationFrames - 40) / (T.ref[1] - 16 - RF.landAt);
+const sceneRef = (ctx: Ctx, env: Env, f: number) => {
+ const prev = brickArt(env, T.brick[1] - 1);
+ if (f < REF.t0) return pullBack(ctx, env, f, T.ref[0], REF.t0, prev);
+ sceneTurn(ctx, env, f, REF, (g) => ({ L: plateLayer(env, "almond", adaptAlmond, 8 + Math.max(0, g - RF.landAt) * ALMOND_SPEED, 1080).canvas, w: 1080, h: 1080 }), { prev });
+};
+
+// ---------------------------------------------------------------- 7: a loop (embroidery)
+const EMB: Turn = { prompt: "and one in embroidery, on a loop", label: "loop · seamless", t0: T.emb[0] + 20, seed: 19 };
+const EM = turnState(EMB), embArt = (env: Env, f: number): Art => ({ L: plateLayer(env, "emb", embroideryAlive, Math.max(0, f - EM.landAt) % embroideryAlive.meta.durationFrames, 1080).canvas, w: 1080, h: 1080 });
+const sceneEmb = (ctx: Ctx, env: Env, f: number) => {
+ const prev: Art = { L: plateLayer(env, "almond", adaptAlmond, adaptAlmond.meta.durationFrames - 1, 1080).canvas, w: 1080, h: 1080 };
+ sceneTurn(ctx, env, f, EMB, (g) => embArt(env, g), { prev, push: true });
+};
+
+// ---------------------------------------------------------------- 8: a live page (Bit)
+const WEB: Turn = { prompt: "a robot for my landing page who watches the visitor", label: "interactive · watches the pointer", t0: T.web[0] + 20, rate: 0.8, seed: 23 };
+const WB = turnState(WEB);
+const BROWSER = { x: 330, y: 70, w: 1460, h: 940 }, HERO = { x: 1090, y: 230, s: 620 }, START = { x: 450, y: 610, w: 250, h: 72 };
+const webPointer = (g: number): P => { const pts: P[] = [[1580, 900], [1380, 420], [840, 330], [START.x + 140, START.y + 40]], u = clamp(g / 60) * (pts.length - 1), i = Math.min(pts.length - 2, Math.floor(u)); return lerpP(pts[i], pts[i + 1], inOut(u - i)); };
+let LOG: InputLog | null = null;
+const webLog = (): InputLog => {
+ const toPiece = (x: number, y: number): P => [((x - HERO.x) * 560) / HERO.s, ((y - HERO.y) * 560) / HERO.s];
+ const [sx, sy] = toPiece(START.x, START.y), log: InputLog = [{ tick: 0, type: "rect", target: "start", x: sx, y: sy, w: (START.w * 560) / HERO.s, h: (START.h * 560) / HERO.s }];
+ for (let t = 0; t <= 240; t += 2) { const [x, y] = webPointer(t / 2), [px, py] = toPiece(x, y); log.push({ tick: t, type: "move", x: px, y: py, value: "mouse" }); }
+ log.push({ tick: 118, type: "enter", target: "start" }, { tick: 170, type: "down", target: "start" }, { tick: 178, type: "up", target: "start" });
+ return log.sort((a, b) => a.tick - b.tick);
+};
+const subEnvOf = (env: Env, key: string, size: number, scale: number): Env => { const k = `sub:${key}:${scale}`; let e = env.cache.get(k) as Env | undefined; if (!e) { e = { W: size, H: size, scale, cache: new Map(), canvas: env.canvas, image: env.image }; env.cache.set(k, e); } return e; };
+const webPage = (ctx: Ctx, env: Env, open: number, tick: number) => {
+ useCam(ctx, env, HOME); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ const e = expo(open), bx = lerp(CHAT.x, BROWSER.x, e), by = lerp(CHAT.y, BROWSER.y, e), bw = lerp(CHAT.w, BROWSER.w, e), bh = lerp(CHAT.h, BROWSER.h, e);
+ softShadow(ctx, bx, by, bw, bh, 26, 1.4); ctx.fillStyle = "#fff"; rr(ctx, bx, by, bw, bh, 26); ctx.fill();
+ ctx.save(); rr(ctx, bx, by, bw, bh, 26); ctx.clip();
+ ctx.fillStyle = "#f4f1ea"; ctx.fillRect(bx, by, bw, 64); ["#e8715a", "#e9b949", "#7cbf6b"].forEach((c, i) => { ctx.fillStyle = c; ctx.beginPath(); ctx.arc(bx + 34 + i * 26, by + 32, 8, 0, Math.PI * 2); ctx.fill(); });
+ ctx.fillStyle = "#fff"; rr(ctx, bx + 150, by + 14, Math.min(560, bw - 300), 36, 18); ctx.fill(); ctx.fillStyle = C.soft; ctx.font = SANS(500, 19); ctx.textBaseline = "middle"; ctx.fillText("your-site.com", bx + 176, by + 33);
+ ctx.globalAlpha = ramp(open, 0.5, 1);
+ ctx.fillStyle = C.ink; ctx.font = SANS(700, 76); ctx.textBaseline = "alphabetic"; ctx.fillText("Meet Bit.", START.x, 420);
+ ctx.font = SANS(500, 30); ctx.fillStyle = C.soft; ctx.fillText("He reads along with you.", START.x, 480); ctx.fillText("Try the button.", START.x, 522);
+ ctx.fillStyle = tick >= 118 ? C.accentDeep : C.ink; rr(ctx, START.x, START.y, START.w, START.h, 36); ctx.fill(); ctx.fillStyle = "#fff"; ctx.font = SANS(600, 28); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText("Get started", START.x + START.w / 2, START.y + START.h / 2 + 1); ctx.textAlign = "left";
+ LOG ??= webLog();
+ const st = stateAt(tick, LOG, mascotHero.input), px = Math.round(HERO.s * env.scale), L = selfLayer(env, "bit", px, px), sub = subEnvOf(env, "bit", 560, px / 560);
+ mascotHero.draw(L.ctx, tick, sub, st);
+ ctx.save(); rr(ctx, HERO.x, HERO.y, HERO.s, HERO.s, 28); ctx.clip(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas, HERO.x * env.scale, HERO.y * env.scale); ctx.restore(); useCam(ctx, env, HOME);
+ ctx.globalAlpha = 1; ctx.restore();
+ pointer(ctx, webPointer(tick / 2), tick >= 170 && tick < 178 ? 1 : 0);
+};
+const webTick = (f: number) => Math.max(0, (f - WB.landAt - 10) * 2);
+const sceneWeb = (ctx: Ctx, env: Env, f: number) => {
+ if (f < WB.landAt) { sceneTurn(ctx, env, f, WEB, () => null, { prev: embArt(env, T.emb[1] - 1) }); return; }
+ webPage(ctx, env, ramp(f, WB.landAt, WB.landAt + 24), webTick(f));
+};
+
+// ---------------------------------------------------------------- 9: a film, with its own score
+const FILMT: Turn = { prompt: "now a short film, with its own music", label: "film · with its own score", t0: T.film[0] + 26, seed: 29 };
+const FM = turnState(FILMT);
+const sceneFilm = (ctx: Ctx, env: Env, f: number) => {
+ if (f < FILMT.t0) { webPage(ctx, env, 1 - ramp(f, T.film[0], FILMT.t0), webTick(T.web[1] - 1)); return; } // the page folds back into the chat
+ sceneTurn(ctx, env, f, FILMT, (g) => ({ L: plateLayer(env, "lep", mechanicalLepidoptera, 1040 + Math.max(0, g - FM.landAt) * 1.5, 1080).canvas, w: 1080, h: 1080 }));
+ if (f >= FM.fullAt) {
+ const wave = waveform(env), x0 = REPLY.x + REPLY.s + 60, x1 = CHAT.x + CHAT.w - 70, y = REPLY.y + REPLY.s / 2, head = (f - FM.landAt) * 1.5 + 1040;
+ ctx.globalAlpha = ramp(f, FM.fullAt, FM.fullAt + 12);
+ for (let i = 0; i < 90; i++) { const a = wave[Math.max(0, Math.min(wave.length - 1, Math.floor(head - 45 + i)))] ?? 0, x = lerp(x0, x1, i / 89), h = 8 + a * 260; ctx.fillStyle = i < 45 ? C.accent : C.line; rr(ctx, x - 2.5, y - h / 2, 5, h, 2.5); ctx.fill(); }
+ ctx.fillStyle = C.soft; ctx.font = SANS(500, 18); ctx.textBaseline = "alphabetic"; ctx.fillText("its score: a music box, drawn in code too", x0, y + 180);
+ ctx.globalAlpha = 1;
+ }
+};
+const waveform = (env: Env): number[] => {
+ let w = env.cache.get("wave") as number[] | undefined; if (w) return w;
+ const sr = 6000, [L] = mechanicalLepidoptera.audio!(sr), per = sr / FPS; w = []; let peak = 1e-6;
+ for (let i = 0; i < L.length / per; i++) { let s = 0; for (let j = 0; j < per; j++) { const v = L[Math.floor(i * per + j)] ?? 0; s += v * v; } const r = Math.sqrt(s / per); w.push(r); peak = Math.max(peak, r); }
+ w = w.map((v) => Math.pow(v / peak, 0.6)); env.cache.set("wave", w); return w;
+};
+
+// ---------------------------------------------------------------- the chapter rail
+// The story's words, written onto the left edge as each is delivered; the live one in ink with an
+// accent dot, the delivered ones quiet. At the reveal they gather in the sentence's own order.
+const CH = [
+ { word: "Illustrations", at: [300] },
+ { word: "Animations", at: [SWIM_OPEN, BK.landAt, WB.landAt] },
+ { word: "Images", at: [T.run[0] + 20, RF.landAt] },
+ { word: "Loops", at: [EM.landAt] },
+ { word: "Films", at: [FM.landAt] },
+];
+const SENTENCE = ["Images", "Illustrations", "Loops", "Animations", "Films"];
+const railPos = (i: number): P => [56, 540 - (CH.length * 64) / 2 + i * 64 + 40];
+const drawRail = (ctx: Ctx, env: Env, f: number) => {
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.textBaseline = "alphabetic";
+ const live = CH.map((c, i) => ({ i, t: Math.max(...c.at.filter((a) => a <= f), -1) })).sort((a, b) => b.t - a.t)[0];
+ CH.forEach((c, i) => {
+ const a = spring(f, c.at[0], 0.3, 0.72); if (a <= 0) return;
+ const [x, y] = railPos(i), on = live.t >= 0 && live.i === i, pulse = on ? 1 - clamp((f - live.t) / 20) : 0;
+ ctx.globalAlpha = clamp(a); ctx.font = SANS(700, 34 + 4 * pulse);
+ ctx.fillStyle = "rgba(255,253,248,0.55)"; ctx.fillText(c.word, x + 1.5 - 24 * (1 - a), y + 2); // a soft lift off whatever is behind
+ ctx.fillStyle = on ? C.ink : C.mute; ctx.fillText(c.word, x - 24 * (1 - a), y);
+ if (on) { ctx.fillStyle = C.accent; ctx.beginPath(); ctx.arc(x - 22, y - 12, 6 + 3 * pulse, 0, Math.PI * 2); ctx.fill(); }
+ });
+ ctx.globalAlpha = 1;
+};
+
+// ---------------------------------------------------------------- 10: all in pure code
+const kw = /\b(export|const|type|as)\b/g;
+const CODE = ["// THE TIMELINE, in frames. Every boundary is on a bar of the score.", "export const T = {", ...Object.entries(T).map(([k, v]) => ` ${k}: [${v[0]}, ${v[1]}],`), "} as const;"];
+const sceneReveal = (ctx: Ctx, env: Env, f: number) => {
+ const r0 = T.reveal[0], u = expo(ramp(f, r0, r0 + 40)), lines = ramp(f, r0 + 16, r0 + 90);
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = "#1b1916"; ctx.fillRect(0, 0, W, H);
+ const ed = { x: 60, y: 70, w: 900, h: 940 };
+ ctx.globalAlpha = u; ctx.fillStyle = "#23201c"; rr(ctx, ed.x, ed.y, ed.w, ed.h, 20); ctx.fill();
+ ctx.fillStyle = "#8f8676"; ctx.font = MONO(18); ctx.textBaseline = "middle"; ctx.fillText("launch.ts", ed.x + 28, ed.y + 34);
+ let left = Math.floor(lines * CODE.join("").length);
+ CODE.forEach((ln, i) => {
+ const n = Math.max(0, Math.min(ln.length, left)); left -= ln.length; if (n <= 0) return;
+ const y = ed.y + 90 + i * 44, text = ln.slice(0, n);
+ ctx.fillStyle = "#5d564b"; ctx.font = MONO(18); ctx.fillText(String(i + 1).padStart(2, " "), ed.x + 24, y);
+ ctx.font = MONO(22); ctx.fillStyle = text.trim().startsWith("//") ? "#7e9a6c" : "#e9e1d3"; ctx.fillText(text, ed.x + 74, y);
+ if (!text.trim().startsWith("//")) { ctx.fillStyle = C.accent; for (const m of text.matchAll(kw)) ctx.fillText(m[0], ed.x + 74 + ctx.measureText(text.slice(0, m.index)).width, y); }
+ });
+ ctx.globalAlpha = 1;
+ // the film, shrunk into its canvas pane, still playing its last scene
+ const pane = { x: lerp(0, 1010, u), y: lerp(0, 150, u), w: lerp(W, 850, u), h: lerp(H, 478, u) };
+ const L = selfLayer(env, "inner", Math.round(W * env.scale * 0.5), Math.round(H * env.scale * 0.5)), sub: Env = { ...env, scale: env.scale * 0.5 };
+ sceneFilm(L.ctx, sub, T.film[1] - 40 + (f - r0) * 0.25);
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ ctx.save(); rr(ctx, pane.x, pane.y, pane.w, pane.h, 18 * u); ctx.clip(); ctx.drawImage(L.canvas, pane.x, pane.y, pane.w, pane.h); ctx.restore();
+ ctx.globalAlpha = u; ctx.fillStyle = "#8f8676"; ctx.font = MONO(18); ctx.textBaseline = "middle"; ctx.fillText("canvas · 1920×1080 · 30 fps · every frame and every sound computed", 1010, 122); ctx.globalAlpha = 1;
+ // the chapter words fly from the rail to the sentence, one a beat, then the line lands on the downbeat
+ // the slots are laid out by measured width, as a line of type: two lines under the pane
+ const g0 = r0 + 40, gap = 16, maxX = 1860; ctx.font = SANS(700, 44); ctx.textBaseline = "alphabetic";
+ const slots: P[] = []; let sx = 1010, sy = 720;
+ SENTENCE.forEach((w, j) => { const wd = ctx.measureText(w + (j < 4 ? "," : "")).width; if (sx + wd > maxX) { sx = 1010; sy += 70; } slots.push([sx, sy]); sx += wd + gap; });
+ SENTENCE.forEach((word, j) => {
+ const ci = CH.findIndex((c) => c.word === word), from = railPos(ci), q = inOut(ramp(f, g0 + j * 10, g0 + j * 10 + 30)), p = lerpP(from, slots[j], q);
+ ctx.font = SANS(700, lerp(34, 44, q)); ctx.fillStyle = mixTo("#8a8173", "#f4efe6", q); ctx.fillText(word + (j < 4 ? "," : ""), p[0], p[1]);
+ });
+ const hit = spring(f, 2880, 0.32, 0.62); // bar 36 of the score: the home chord
+ if (hit > 0) { ctx.globalAlpha = clamp(hit); ctx.font = SANS(800, 84); ctx.fillStyle = C.accent; ctx.fillText("All in pure code.", 1010, 920 + (1 - hit) * 26); ctx.globalAlpha = 1; }
+};
+const mixTo = (a: string, b: string, t: number) => { const h = (s: string) => [1, 3, 5].map((i) => parseInt(s.slice(i, i + 2), 16)); const x = h(a), y = h(b); return `rgb(${x.map((v, i) => Math.round(lerp(v, y[i], clamp(t)))).join(",")})`; };
+
+const sceneEnd = (ctx: Ctx, env: Env, f: number) => {
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = "#f4efe6"; ctx.fillRect(0, 0, W, H);
+ const L = plateLayer(env, "banner", bannerFilm, Math.min(200, 12 + (f - T.end[0]) * 1.6), 2000);
+ ctx.drawImage(L.canvas, 0, 230, 1920, (1920 * 620) / 2000);
+ ctx.fillStyle = C.ink; ctx.font = MONO(30); ctx.textAlign = "center"; ctx.textBaseline = "middle";
+ ctx.globalAlpha = ramp(f, T.end[0] + 40, T.end[0] + 56); ctx.fillText("/plugin install anidoodle@alexgreensh-anidoodle", 960, 910);
+ ctx.fillStyle = C.soft; ctx.font = SANS(500, 26); ctx.fillText("Images · Illustrations · Loops · Animations · Films · Claude Code and Codex · github.com/alexgreensh/anidoodle", 960, 972); ctx.textAlign = "left"; ctx.globalAlpha = 1;
+};
+
+// ---------------------------------------------------------------- the sound
+// The score, cut to the film's length, plus the interface: a key click per character, the Generate
+// thock, the ink's plip as it lands, a whoosh for every dive and break-out. All synthesized.
+const launchAudio = (sr: number): [Float32Array, Float32Array] => {
+ const n = Math.round((N / FPS) * sr), L = new Float32Array(n), R = new Float32Array(n);
+ const m = renderPiece(launchLofi(), sr); for (let i = 0; i < n && i < m.L.length; i++) { L[i] = m.L[i]; R[i] = m.R[i]; }
+ const fade = Math.round(1.5 * sr); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }
+ const r = rng(4242), add = (t: number, len: number, fn: (s: number) => number, gain: number, pan = 0) => { const i0 = Math.round(t * sr); for (let i = 0; i < len * sr && i0 + i < n; i++) { if (i0 + i < 0) continue; const v = fn(i / sr) * gain; L[i0 + i] += v * (1 - Math.max(0, pan)); R[i0 + i] += v * (1 + Math.min(0, pan)); } };
+ const click = (fr: number) => { const f0 = 2600 + r() * 1400, ph = r() * 6; add(fr / FPS, 0.03, (s) => Math.sin(2 * Math.PI * f0 * s + ph) * Math.exp(-s / 0.004) + (r() - 0.5) * Math.exp(-s / 0.002) * 0.6, 0.05, (r() - 0.5) * 0.4); };
+ const thock = (fr: number) => add(fr / FPS, 0.14, (s) => Math.sin(2 * Math.PI * (70 + 90 * Math.exp(-s / 0.02)) * s) * Math.exp(-s / 0.05), 0.2);
+ const plip = (fr: number) => add(fr / FPS, 0.16, (s) => Math.sin(2 * Math.PI * (320 + 700 * Math.exp(-s / 0.03)) * s) * Math.exp(-s / 0.06), 0.12);
+ const whoosh = (fr: number, len = 0.7) => { let z = 0; add(fr / FPS, len, (s) => { z += 0.12 * ((r() - 0.5) - z); return z * Math.sin((Math.PI * s) / len) ** 2; }, 0.55); };
+ charTimes(KOI_PROMPT, KOI_TYPE.t0, KOI_TYPE.rate, KOI_TYPE.seed).forEach(click); thock(PRESS.down); plip(DROP.land);
+ [SWIM, BRICK, REF, EMB, WEB, FILMT].forEach((tn) => { const k = turnState(tn); k.times.forEach(click); thock(k.down); plip(k.landAt); });
+ whoosh(SWIM_OPEN, 0.9); [0, 1, 2].forEach((i) => whoosh(RUN_T0 + i * STEP, 0.9)); whoosh(T.reveal[0], 1.2);
+ return [L, R];
+};
+
+// ---------------------------------------------------------------- the film
+const withRail = (draw: (ctx: Ctx, env: Env, f: number) => void) => (ctx: Ctx, env: Env, f: number) => { draw(ctx, env, f); drawRail(ctx, env, f); };
+const shot = (id: keyof typeof T, draw: (ctx: Ctx, env: Env, f: number) => void) => ({ id, start: T[id][0], end: T[id][1], draw: (ctx: Ctx, local: number, env: Env) => draw(ctx, env, T[id][0] + local) });
+export const launch: Film = {
+ meta: { title: "anidoodle · launch", W, H, fps: FPS, bpm: 90, durationFrames: N, raster: "cpu", kind: "launch" },
+ assets: { images: { almond: "assets/refs/vangogh-almond-blossom.jpg" } }, // public domain; provenance in engine/assets/refs/PROVENANCE.json
+ shots: [
+ shot("type", withRail(sceneOpen)), shot("gen", withRail(sceneOpen)), shot("draw", withRail(sceneDraw)), shot("swim", withRail(sceneSwim)),
+ shot("run", withRail(sceneRun)), shot("brick", withRail(sceneBrick)), shot("ref", withRail(sceneRef)), shot("emb", withRail(sceneEmb)),
+ shot("web", withRail(sceneWeb)), shot("film", withRail(sceneFilm)), shot("reveal", sceneReveal), shot("end", sceneEnd),
+ ],
+ audio: launchAudio,
+};
+
+// THE MOTION TEST: the Generate press, the drop and the bloom, on their own.
+export const launchClip: Film = {
+ meta: { ...launch.meta, title: "anidoodle · launch, the ink test", durationFrames: 120 },
+ assets: launch.assets,
+ shots: [{ id: "ink", start: 0, end: 120, draw: (ctx, local, env) => { const f = 140 + local, sh = launch.shots.find((x) => f >= x.start && f < x.end)!; sh.draw(ctx, f - sh.start, env); } }],
+};
+export const KEYS = () => ({ SWIM: SW, BRICK: BK, REF: RF, EMB: EM, WEB: WB, FILM: FM, KOI_DONE, SWIM_OPEN, DIVE });
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch2.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch2.ts
new file mode 100644
index 0000000..ca7cda9
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch2.ts
@@ -0,0 +1,342 @@
+// LAUNCH, CUT 2. 69 s on the 26-bar score (music/pieces/launch.ts, launchLofi2): 90 bpm, a bar is
+// 80 frames. Alex's notes on cut 1 are the brief: it read as a slide deck; nobody could tell it
+// was code; the drawings were slow; the waits were long; the styles came one at a time; the site
+// was barely shown; the type was set, not drawn; the logo appeared once; the end card was cut out.
+// So: the logo writes itself first; the koi draws beside its own code streaming ("no image model,
+// just code"); a real chat thread that keeps every answer and scrolls; every drawing 3-6x faster;
+// every change of scene a move (break-outs, whip pans, punch-ins, card flips), never a cut; the 31
+// styles as a rolling wall the camera punches into; the full website tour; the words drawn in their
+// media; the corner logo throughout; an end card composed for the frame, with both install lines.
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import {
+ C, GEN, HOME, INPUT, MONO, REPLY, SANS, TEXT, blot, camLerp, caretAt, clamp, drawChatFrame, expo, inOut, lerp, lerpP,
+ out3, pathOf, plateLayer, pointer, press, ramp, rr, selfLayer, softShadow, useCam, type Cam,
+} from "./launchKit";
+import { koiDraw } from "./koiDraw";
+import { koi } from "./koi";
+import { koiWorld } from "./koiWorld";
+import { brickBalloon } from "./brickBalloon";
+import { adaptAlmond } from "./adaptAlmond";
+import { embroideryAlive } from "./embroideryAlive";
+import { webTour } from "./webTour";
+import { mechanicalLepidoptera } from "./mechanicalLepidoptera";
+import { drawWall, wallCam, cardOf, PUNCH, PUNCH_IN, type Punch } from "./launchGallery";
+import { caption, logo, logoBox, logoBug, logoCentred, sentence, writeOn, measure } from "./kinetic";
+import { KOI_CODE } from "./launchCode";
+import { launchLofi2 } from "./music/pieces/launch";
+import { renderPiece } from "./music/render";
+import { rng } from "./core";
+
+const W = 1920, H = 1080, FPS = 30, BEAT = 20;
+export const T2 = {
+ open: [0, 80], ask: [80, 200], code: [200, 360], swim: [360, 560], wall: [560, 800], brick: [800, 1040],
+ hand: [1040, 1200], loop: [1200, 1360], web: [1360, 1760], film: [1760, 1840], words: [1840, 2040], end: [2040, 2160],
+} as const;
+const N = T2.end[1];
+
+// ---------------------------------------------------------------- small helpers
+const charTimes = (text: string, t0: number, rate: number, seed: number) => { const out: number[] = []; let t = t0; for (let i = 0; i < text.length; i++) { const h = Math.sin((i + 1) * 12.9898 + seed * 78.233) * 43758.5453, j = h - Math.floor(h); t += rate * (0.55 + j * 0.9) + (text[i] === " " ? 0.6 * rate : 0); out.push(t); } return out; };
+const typedAt = (text: string, f: number, times: number[]) => text.slice(0, times.filter((t) => f >= t).length);
+const screen = (ctx: Ctx, env: Env) => ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+const GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];
+// a whip: the outgoing frame smeared along the move (drawn several times, fading), the incoming following it in
+const smear = (ctx: Ctx, env: Env, L: CanvasImageSource, dx: number, dy: number, blur: number) => { screen(ctx, env); for (let k = 5; k >= 0; k--) { ctx.globalAlpha = k === 0 ? 1 : 0.16; ctx.drawImage(L, dx - blur * k * Math.sign(dx || 1) * (dx ? 1 : 0), dy - blur * k * Math.sign(dy || 1) * (dy ? 1 : 0), W, H); } ctx.globalAlpha = 1; };
+
+// ---------------------------------------------------------------- the conversation
+// One thread for the whole film. Every answer stays in it; the thread scrolls as it grows, eased.
+type Art = { src: (env: Env, f: number) => CanvasImageSource; crop?: [number, number, number, number] };
+type Item = { kind: "user"; at: number; text: string; attach?: string } | { kind: "card"; at: number; art: Art; label: string; s: number; land: { t0: number; land: number; full: number } };
+const KOI_PROMPT = "a koi turning under lily pads, marker comic";
+const ASK = { times: charTimes(KOI_PROMPT, 84, 1.0, 7), down: 160, up: 166 };
+const DROP0 = { t0: 172, land: 188, full: 222 };
+const KOI_SPEED = 3.6, KOI_DONE = DROP0.land + (koiDraw.meta.durationFrames - 30) / KOI_SPEED;
+const SWIM_PROMPT = "now make it swim";
+const SW = (() => { const times = charTimes(SWIM_PROMPT, 378, 0.55, 11), down = Math.ceil(times[times.length - 1] + 4), up = down + 5; return { times, down, up, drop: { t0: up + 5, land: up + 19, full: up + 40 } }; })();
+const SWIM_START = SW.up + 6, SWIM_OUT = SWIM_START + 22, SWIM_FULL = SWIM_OUT + 34; // the koi in the thread starts to swim in its card, then the card opens to the full frame
+const swimArt: Art = { src: (env, f) => plateLayer(env, "world1920", koiWorld, Math.max(0, f - SWIM_START), 1920).canvas, crop: [420, 0, 1080, 1080] };
+// the koi's card: it draws itself, holds, and when asked to swim, swims right there in the thread (the pond world framed exactly like the plate)
+const koiArt: Art = { src: (env, f) => {
+ if (f < KOI_DONE) return plateLayer(env, "koiDraw", koiDraw, (f - DROP0.land) * KOI_SPEED, 1080).canvas;
+ if (f < SWIM_START) return plateLayer(env, "koi", koi, 0, 1080).canvas;
+ const Lw = plateLayer(env, "world1920", koiWorld, f - SWIM_START, 1920).canvas, sq = selfLayer(env, "koiswim", 1080, 1080); sq.ctx.drawImage(Lw, 420, 0, 1080, 1080, 0, 0, 1080, 1080); return sq.canvas;
+} };
+const HAND_PROMPT = "my koi, painted in this hand";
+const HD = (() => { const times = charTimes(HAND_PROMPT, 1068, 0.5, 17), down = Math.ceil(times[times.length - 1] + 4), up = down + 5; return { times, down, up, drop: { t0: up + 5, land: up + 19, full: up + 40 } }; })();
+const ALMOND_SPEED = (adaptAlmond.meta.durationFrames - 40) / (T2.hand[1] - 8 - HD.drop.land);
+const FLIP = T2.loop[0] + 2; // the Van Gogh card turns over and the embroidery is on its back
+const almondArt: Art = { src: (env, f) => (f < FLIP + 6 ? plateLayer(env, "almond", adaptAlmond, 8 + Math.max(0, f - HD.drop.land) * ALMOND_SPEED, 1080) : plateLayer(env, "emb", embroideryAlive, (f - FLIP) % embroideryAlive.meta.durationFrames, 1080)).canvas };
+const THREAD: Item[] = [
+ { kind: "user", at: ASK.up, text: KOI_PROMPT },
+ { kind: "card", at: DROP0.land, art: koiArt, label: "marker comic", s: 560, land: DROP0 },
+ { kind: "user", at: SW.up, text: SWIM_PROMPT },
+ { kind: "user", at: HD.up, text: HAND_PROMPT, attach: "almond" },
+ { kind: "card", at: HD.drop.land, art: almondArt, label: "adapted · the almond-blossom hand", s: 460, land: HD.drop },
+];
+const TOP = 170, VIEW_BOTTOM = INPUT.y - 26, BUBBLE = 58, ATTACH = 150;
+const layout = () => { let y = TOP; return THREAD.map((it) => { const h = it.kind === "user" ? BUBBLE + (it.attach ? ATTACH + 10 : 0) : it.s + 34; const r = { it, y, h }; y += h + 26; return r; }); };
+const LAYOUT = layout();
+// the scroll: each new item eases the thread up so the newest thing sits just above the composer
+const scrollAt = (f: number) => { let s = 0; LAYOUT.forEach((L) => { const want = Math.max(0, L.y + L.h - VIEW_BOTTOM); const prev = s; if (want > prev) s += (want - prev) * expo(ramp(f, L.it.at - 2, L.it.at + 16)); }); return s; };
+export const cardRect = (i: number, f: number) => { const L = LAYOUT[i], it = L.it as Extract<Item, { kind: "card" }>; return { x: REPLY.x, y: L.y + 34 - scrollAt(f), s: it.s }; };
+
+const drawUser = (ctx: Ctx, env: Env, it: Extract<Item, { kind: "user" }>, y: number, a: number) => {
+ ctx.globalAlpha = a; ctx.font = SANS(500, 26);
+ const tw = ctx.measureText(it.text).width, bw = tw + 52, bx = 1560 - bw; let yy = y;
+ const img = it.attach ? env.image?.(it.attach) : undefined;
+ if (img) { ctx.save(); rr(ctx, 1560 - 240, yy, 240, ATTACH, 16); ctx.clip(); ctx.drawImage(img, 1560 - 240, yy, 240, ATTACH); ctx.restore(); yy += ATTACH + 10; }
+ ctx.fillStyle = C.chip; rr(ctx, bx, yy, bw, BUBBLE - 2, 22); ctx.fill(); ctx.fillStyle = C.ink; ctx.textBaseline = "middle"; ctx.fillText(it.text, bx + 26, yy + 29); ctx.globalAlpha = 1;
+};
+const drawCard = (ctx: Ctx, env: Env, it: Extract<Item, { kind: "card" }>, x: number, y: number, f: number, flip = 1) => {
+ ctx.fillStyle = C.ink; ctx.globalAlpha = ramp(f, it.land.land, it.land.land + 10); ctx.beginPath(); ctx.arc(x + 9, y - 16, 7, 0, Math.PI * 2); ctx.fill();
+ ctx.font = SANS(600, 20); ctx.textBaseline = "middle"; ctx.fillText(f >= FLIP + 6 && it.art === almondArt ? "loop · embroidery, seamless" : it.label, x + 26, y - 15); ctx.globalAlpha = 1;
+ const s = it.s, grow = out3(ramp(f, it.land.land, it.land.full)), c: P = [x + s / 2, y + s / 2], L = it.art.src(env, f);
+ ctx.save(); ctx.translate(c[0], c[1]); ctx.scale(flip, 1); ctx.translate(-c[0], -c[1]);
+ softShadow(ctx, x, y, s, s, 20, grow * 1.3);
+ ctx.save(); rr(ctx, x, y, s, s, 20); ctx.clip();
+ if (grow < 1) { pathOf(ctx, blot(c, lerp(16, s * 0.8, grow) + 28 * (1 - grow), 77)); ctx.fillStyle = C.ink; ctx.fill(); pathOf(ctx, blot(c, Math.max(0, lerp(16, s * 0.8, grow) - 5), 77)); ctx.clip(); }
+ ctx.fillStyle = C.paper; ctx.fillRect(x, y, s, s);
+ if (it.art.crop) ctx.drawImage(L, ...it.art.crop, x, y, s, s); else ctx.drawImage(L, x, y, s, s);
+ ctx.restore(); ctx.restore();
+};
+// the drop in flight from Generate to where the new card will land
+const drawDrop = (ctx: Ctx, f: number, d: { t0: number; land: number }, to: P) => {
+ if (f < d.t0 - 6 || f >= d.land) return;
+ if (f < d.t0) { const w = out3(ramp(f, d.t0 - 6, d.t0)); ctx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(GEN_C[0], GEN.y + 6 - w * 22, 30 * (0.3 + 0.7 * w), 0, Math.PI * 2); ctx.fill(); return; }
+ const at = (g: number): P => { const u = ramp(g, d.t0, d.land), e = inOut(u); return [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16, to[1], e) - Math.sin(Math.PI * u) * 150]; };
+ for (let k = 24; k >= 0; k--) { const p = at(f - k * 0.1); ctx.fillStyle = C.ink; ctx.globalAlpha = k === 0 ? 1 : 0.22 * (1 - k / 25); ctx.beginPath(); ctx.arc(p[0], p[1], 30 * (1 - k * 0.022), 0, Math.PI * 2); ctx.fill(); }
+ ctx.globalAlpha = 1;
+};
+type ChatO = { typed: string; caret: boolean; press: number; hot: number; flip?: number; hideCard?: number };
+const drawChat = (ctx: Ctx, env: Env, f: number, o: ChatO) => {
+ drawChatFrame(ctx, { typed: o.typed, caret: o.caret, placeholder: "Describe what you want drawn…", genPress: o.press, genHot: o.hot });
+ const sc = scrollAt(f);
+ ctx.save(); ctx.beginPath(); ctx.rect(300, 158, 1320, VIEW_BOTTOM - 158); ctx.clip();
+ LAYOUT.forEach((L, i) => {
+ if (f < L.it.at) return;
+ const y = L.y - sc; if (y > VIEW_BOTTOM || y + L.h < 100) return;
+ if (L.it.kind === "user") drawUser(ctx, env, L.it, y, ramp(f, L.it.at, L.it.at + 8));
+ else if (o.hideCard !== i) drawCard(ctx, env, L.it, REPLY.x, y + 34, f, i === 4 ? (o.flip ?? 1) : 1);
+ });
+ ctx.restore();
+ // drops in flight land on the card's place in the thread
+ LAYOUT.forEach((L, i) => { if (L.it.kind !== "card") return; const r = cardRect(i, f); drawDrop(ctx, f, L.it.land, [r.x + r.s / 2, r.y + r.s / 2]); });
+};
+
+// ---------------------------------------------------------------- the corner logo
+const BUG: P = [1700, 1040];
+const bug = (ctx: Ctx, env: Env, f: number) => logoBug(ctx, env, f, BUG[0], BUG[1], 0.9, { t0: 70, fps: FPS });
+
+// ---------------------------------------------------------------- 0: the logo writes itself
+const sceneOpen = (ctx: Ctx, env: Env, f: number) => {
+ const u = expo(ramp(f, 58, 80));
+ useCam(ctx, env, HOME);
+ drawChatFrame(ctx, { typed: "", caret: false, placeholder: "Describe what you want drawn…" });
+ screen(ctx, env); ctx.globalAlpha = 1 - u; ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H); ctx.globalAlpha = 1;
+ // the wordmark, big, then it shrinks away toward its corner as the chat comes up under it
+ const em = lerp(150, 26, u), cx = lerp(W / 2, BUG[0], u), cy = lerp(H / 2 - 10, BUG[1] - 20, u);
+ ctx.globalAlpha = 1 - ramp(f, 72, 80); logoCentred(ctx, env, cx, cy, em, ramp(f, 2, 50), { pen: f < 56 }); ctx.globalAlpha = 1;
+ if (f < 58) caption(ctx, env, "hand-drawn art, written as code", W / 2, H / 2 + 210, 28, ramp(f, 30, 52), "plain", { align: "center" });
+};
+
+// ---------------------------------------------------------------- 1: the ask
+const askCam = (ctx: Ctx, f: number): Cam => {
+ const typed = typedAt(KOI_PROMPT, f, ASK.times), [cx] = caretAt(ctx, typed), macro: Cam = { c: [Math.max(TEXT.x + 330, cx - 110), 934], z: 2.4 };
+ return f < 136 ? macro : camLerp(macro, HOME, expo(ramp(f, 136, 158)));
+};
+// the code composition: the koi card at left of centre, its code streaming on the right
+const CODE_CAM = (): Cam => { const r = cardRect(1, 230), z = 1.25; return { c: [r.x + r.s / 2 + (W / 2 - 520) / z, r.y + r.s / 2 - (620 - H / 2) / z], z }; }; // the card lands at (520, 620), the words above it, the code at right
+const sceneAsk = (ctx: Ctx, env: Env, f: number) => {
+ const cam = f < T2.ask[1] ? (f < 160 ? askCam(ctx, f) : camLerp(HOME, CODE_CAM(), expo(ramp(f, 186, 226)))) : HOME;
+ useCam(ctx, env, cam);
+ const typed = typedAt(KOI_PROMPT, f, ASK.times);
+ drawChat(ctx, env, f, { typed: f < ASK.up ? typed : "", caret: f < ASK.up, press: press(f, ASK.down, ASK.up), hot: ramp(f, 150, 158) });
+ if (f >= 136) pointer(ctx, lerpP([1760, 1130], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, 138, 158))), press(f, ASK.down, ASK.up) * 0.8);
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 2: it's code
+const sceneCode = (ctx: Ctx, env: Env, f: number) => {
+ const back = expo(ramp(f, 328, 359));
+ useCam(ctx, env, camLerp(CODE_CAM(), HOME, back));
+ drawChat(ctx, env, f, { typed: "", caret: false, press: 0, hot: 0 });
+ // the editor slides in from the right, the lines stream in time with the drawing
+ screen(ctx, env);
+ const inU = expo(ramp(f, 200, 222)) * (1 - back), ex = lerp(W + 40, 1010, inU), ey = 110, ew = 830, eh = 860;
+ if (inU > 0.001) {
+ softShadow(ctx, ex, ey, ew, eh, 22, 1.6); ctx.fillStyle = "#1f1c18"; rr(ctx, ex, ey, ew, eh, 22); ctx.fill();
+ ctx.fillStyle = "#8f8676"; ctx.font = MONO(16); ctx.textBaseline = "middle"; ctx.fillText("koi.ts · drawFish() · running", ex + 26, ey + 30);
+ const prog = clamp((f - DROP0.land) / (KOI_DONE - DROP0.land)), shown = Math.floor(prog * KOI_CODE.length), first = Math.max(0, shown - 24);
+ ctx.save(); ctx.beginPath(); ctx.rect(ex, ey + 56, ew, eh - 70); ctx.clip();
+ for (let i = first; i < Math.min(KOI_CODE.length, shown + 1); i++) {
+ const y = ey + 80 + (i - first) * 32, ln = KOI_CODE[i], partial = i === shown ? ln.slice(0, Math.floor(((prog * KOI_CODE.length) % 1) * ln.length)) : ln;
+ ctx.fillStyle = "#5d564b"; ctx.font = MONO(13); ctx.fillText(String(i + 1).padStart(3, " "), ex + 16, y);
+ ctx.font = MONO(15); ctx.fillStyle = partial.trim().startsWith("//") ? "#8faa7c" : "#ece4d6"; ctx.fillText(partial, ex + 56, y);
+ }
+ ctx.restore();
+ }
+ // the point, drawn: no image model
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 3: now make it swim
+const sceneSwim = (ctx: Ctx, env: Env, f: number) => {
+ if (f < SWIM_OUT) {
+ useCam(ctx, env, HOME);
+ const typed = typedAt(SWIM_PROMPT, f, SW.times);
+ drawChat(ctx, env, f, { typed: f < SW.up ? typed : "", caret: f < SW.up && f >= 372, press: press(f, SW.down, SW.up), hot: ramp(f, SW.down - 6, SW.down) });
+ pointer(ctx, lerpP([GEN_C[0] + 200, GEN_C[1] + 150], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, SW.down - 12, SW.down))), press(f, SW.down, SW.up) * 0.8);
+ bug(ctx, env, f); return;
+ }
+ // the break-out: the card opens to the whole frame and the koi swims off
+ const u = inOut(ramp(f, SWIM_OUT, SWIM_FULL)), r = cardRect(1, SWIM_OUT), L = swimArt.src(env, f);
+ useCam(ctx, env, HOME);
+ if (u < 1) { ctx.globalAlpha = 1 - u * 0.8; drawChat(ctx, env, f, { typed: "", caret: false, press: 0, hot: 0, hideCard: 1 }); ctx.globalAlpha = 1; }
+ const x = lerp(r.x, 0, u), y = lerp(r.y, 0, u), w = lerp(r.s, W, u), h = lerp(r.s, H, u), sx = lerp(420, 0, u), sw = lerp(1080, 1920, u);
+ screen(ctx, env); ctx.save(); rr(ctx, x, y, w, h, 20 * (1 - u)); ctx.clip(); ctx.drawImage(L, sx, 0, sw, 1080, x, y, w, h); ctx.restore();
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 4: the wall of 31 styles
+// the punches are chosen by style, found on the wall where their row has carried them
+const PUNCH_STYLES = ["scratchboard", "pixelArt", "toyBrick", "balloon"], PUNCH_TIMES = [0.4, 2.53, 4.67, 6.3];
+const WALL_T0 = T2.wall[0] + 10, PUNCH_T0 = 0.9, PUNCH_GAP = PUNCH / FPS; // seconds into the wall
+const PUNCHES: Punch[] = (() => {
+ const out: Punch[] = [];
+ PUNCH_STYLES.forEach((id, j) => {
+ const t = PUNCH_TIMES[j], camx = lerp(-240, 240, clamp(t / 8));
+ let best: Punch | null = null, bd = 1e9;
+ for (let row = 0; row < 4; row++) for (let k = -12; k < 20; k++) { if (cardOf(row, k).id !== id) continue; const speed = [52, -64, 58, -48][row], x = k * 364 + speed * (t + 12 / FPS) + (row % 2) * 182, d = Math.abs(x - camx) + Math.abs(row - 1.5) * 80; if (d < bd) { bd = d; best = { row, k, t0: t }; } }
+ if (best) out.push(best);
+ });
+ return out;
+})();
+const wallT = (f: number) => (f - WALL_T0) / FPS;
+const drawWallAt = (ctx: Ctx, env: Env, f: number) => { const t = wallT(f), w = wallCam(t, PUNCHES, FPS, W, H, true); drawWall(ctx, env, t, w.cam, w.focus); return w; };
+const sceneWall = (ctx: Ctx, env: Env, f: number) => {
+ if (f < WALL_T0) { // a whip pan off the swim onto the wall
+ const u = inOut(ramp(f, T2.wall[0], WALL_T0)), Ls = swimArt.src(env, f);
+ screen(ctx, env); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ smear(ctx, env, Ls, -W * u, 0, 40 * Math.sin(Math.PI * u));
+ const Lw = selfLayer(env, "wallwhip", Math.round(W * env.scale), Math.round(H * env.scale)); drawWallAt(Lw.ctx, env, WALL_T0);
+ screen(ctx, env); ctx.drawImage(Lw.canvas, W * (1 - u), 0, W, H); bug(ctx, env, f); return;
+ }
+ const w = drawWallAt(ctx, env, f), t = wallT(f);
+ void w; void t;
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 5: crayon to bricks, and it flies
+const BRICK_SPEED = (brickBalloon.meta.durationFrames - 1) / (T2.brick[1] - 6 - T2.brick[0]);
+const brickFrame = (f: number) => Math.max(0, (f - T2.brick[0]) * BRICK_SPEED);
+const sceneBrick = (ctx: Ctx, env: Env, f: number) => {
+ screen(ctx, env); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ // the balloon card fills the frame's height; as it takes flight it opens to the full width
+ const open = expo(ramp(f, T2.brick[0] + 120, T2.brick[0] + 160)), size = lerp(H, W, open), x = (W - size) / 2, y = (H - size) / 2;
+ const L = plateLayer(env, "brick", brickBalloon, brickFrame(f), 1080).canvas;
+ softShadow(ctx, x, y, size, size, 14 * (1 - open), 1.3); ctx.save(); rr(ctx, x, y, size, size, 14 * (1 - open)); ctx.clip(); ctx.drawImage(L, x, y, size, size); ctx.restore();
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 6: a painter's hand, then 7: the card flips to a loop
+const sceneHand = (ctx: Ctx, env: Env, f: number) => {
+ // the flight shrinks away as the chat comes back, scrolled to its newest message
+ const back = expo(ramp(f, T2.hand[0], T2.hand[0] + 24));
+ useCam(ctx, env, HOME);
+ const typed = typedAt(HAND_PROMPT, f, HD.times), chip = out3(ramp(f, 1058, 1066));
+ drawChat(ctx, env, f, { typed: f < HD.up ? typed : "", caret: f < HD.up && f >= 1066, press: press(f, HD.down, HD.up), hot: ramp(f, HD.down - 6, HD.down) });
+ const img = env.image?.("almond");
+ if (img && f < HD.up && chip > 0) { ctx.globalAlpha = chip; ctx.save(); rr(ctx, INPUT.x + INPUT.w - 420, INPUT.y + 16, 104, 72, 12); ctx.clip(); ctx.drawImage(img, INPUT.x + INPUT.w - 420, INPUT.y + 16, 104, 72); ctx.restore(); ctx.globalAlpha = 1; }
+ if (f >= HD.down - 14) pointer(ctx, lerpP([GEN_C[0] + 200, GEN_C[1] + 150], [GEN_C[0] + 18, GEN_C[1] + 6], out3(ramp(f, HD.down - 14, HD.down))), press(f, HD.down, HD.up) * 0.8);
+ if (back < 1) { screen(ctx, env); const s = lerp(1, 0.2, back), L = plateLayer(env, "brick", brickBalloon, brickFrame(T2.brick[1] - 1), 1080).canvas; ctx.globalAlpha = 1 - back; ctx.drawImage(L, 0, (1080 - 1920) / 2, 1920, 1920); ctx.globalAlpha = 1; void s; }
+ bug(ctx, env, f);
+};
+const sceneLoop = (ctx: Ctx, env: Env, f: number) => {
+ const flip = Math.cos(Math.PI * inOut(ramp(f, FLIP - 8, FLIP + 8))), r = cardRect(4, f), push = inOut(ramp(f, FLIP + 12, FLIP + 52));
+ useCam(ctx, env, camLerp(HOME, { c: [r.x + r.s / 2, r.y + r.s / 2], z: 1040 / r.s }, push));
+ drawChat(ctx, env, f, { typed: "", caret: false, press: 0, hot: 0, flip: Math.abs(flip) < 0.02 ? 0.02 : Math.abs(flip) });
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 8: the website
+export const WEB_SKIP = 118; // the webTour frame where Bit's hero is in view: the scroll-drawn hero is cut, nobody could tell what it was
+const WEB0 = T2.web[0] + 10, webFrame = (f: number) => Math.max(0, Math.min(webTour.meta.durationFrames - 1, f - WEB0 + WEB_SKIP));
+const sceneWeb = (ctx: Ctx, env: Env, f: number) => {
+ const L = plateLayer(env, "web", webTour, webFrame(f), 1920).canvas;
+ if (f < WEB0) { // a whip up off the embroidery onto the site
+ const u = inOut(ramp(f, T2.web[0], WEB0)), r = cardRect(4, f), Le = plateLayer(env, "emb", embroideryAlive, (f - FLIP) % embroideryAlive.meta.durationFrames, 1080).canvas;
+ screen(ctx, env); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ ctx.save(); ctx.translate(0, -H * u); ctx.drawImage(Le, (W - H) / 2, 0, H, H); ctx.restore(); void r;
+ ctx.drawImage(L, 0, H * (1 - u), W, H); bug(ctx, env, f); return;
+ }
+ screen(ctx, env); ctx.drawImage(L, 0, 0, W, H);
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 9: a film
+// the film's own arc as a trailer: its blueprint drawn, the butterfly coming alive in colour, flying off through the flowers
+export const lepAt = (u: number) => (u < 0.36 ? lerp(60, 520, u / 0.36) : u < 0.62 ? lerp(560, 820, (u - 0.36) / 0.26) : lerp(900, 1420, (u - 0.62) / 0.38));
+const sceneFilm = (ctx: Ctx, env: Env, f: number) => {
+ const L = plateLayer(env, "lep", mechanicalLepidoptera, lepAt(clamp((f - T2.film[0]) / (T2.film[1] - T2.film[0]))), 1080).canvas, u = expo(ramp(f, T2.film[0], T2.film[0] + 16));
+ screen(ctx, env); ctx.fillStyle = "#101010"; ctx.fillRect(0, 0, W, H);
+ const s = lerp(0.6, 1, u) * W; ctx.drawImage(L, (W - s) / 2, (H - s) / 2, s, s);
+ bug(ctx, env, f);
+};
+
+// ---------------------------------------------------------------- 10: the sentence, and 11: the end
+const WORDS = ["Images", "Illustrations", "Loops", "Animations", "Films"]; // the kit adds the commas and the full stop
+const sceneWords = (ctx: Ctx, env: Env, f: number) => {
+ screen(ctx, env); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ if (f < T2.words[0] + 30) { const u = expo(ramp(f, T2.words[0], T2.words[0] + 30)), L = plateLayer(env, "lep", mechanicalLepidoptera, lepAt(1), 1080).canvas; ctx.globalAlpha = 1 - u; const s = W * (1 - 0.3 * u); ctx.drawImage(L, (W - s) / 2, (H - s) / 2, s, s); ctx.globalAlpha = 1; }
+ sentence(ctx, env, WORDS, f, T2.words[0] + 30, { beat: BEAT, styles: ["marker", "ink", "thread", "crayon", "marker"], colors: ["#2f6fd6", C.ink, "#2e7d6e", "#d8452f", "#7a3fb0"], size: 70, top: 230 });
+ bug(ctx, env, f);
+};
+const sceneEnd = (ctx: Ctx, env: Env, f: number) => {
+ screen(ctx, env); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ const em = 120, b = logoBox(env, em), cx = W / 2, cy = 360;
+ logoCentred(ctx, env, cx, cy, em, ramp(f, T2.end[0], T2.end[0] + 36), { pen: f < T2.end[0] + 40 }); void b; void logo;
+ const a = ramp(f, T2.end[0] + 30, T2.end[0] + 44);
+ ctx.globalAlpha = a; ctx.textAlign = "center"; ctx.textBaseline = "middle";
+ ctx.fillStyle = C.soft; ctx.font = SANS(500, 28); ctx.fillText("Images · Illustrations · Loops · Animations · Films, all in pure code", cx, 560);
+ ctx.fillStyle = "#1f1c18"; rr(ctx, cx - 520, 640, 1040, 170, 22); ctx.fill();
+ ctx.fillStyle = "#ece4d6"; ctx.font = MONO(30); ctx.fillText("/plugin marketplace add alexgreensh/anidoodle", cx, 695); ctx.fillText("/plugin install anidoodle@alexgreensh-anidoodle", cx, 755);
+ ctx.fillStyle = C.soft; ctx.font = SANS(500, 24); ctx.fillText("Claude Code and Codex · github.com/alexgreensh/anidoodle", cx, 880);
+ ctx.textAlign = "left"; ctx.globalAlpha = 1;
+};
+
+// ---------------------------------------------------------------- the sound
+const audio2 = (sr: number): [Float32Array, Float32Array] => {
+ const n = Math.round((N / FPS) * sr), L = new Float32Array(n), R = new Float32Array(n), m = renderPiece(launchLofi2(), sr);
+ for (let i = 0; i < n && i < m.L.length; i++) { L[i] = m.L[i]; R[i] = m.R[i]; }
+ const fade = Math.round(1.2 * sr); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }
+ const r = rng(4242), add = (t: number, len: number, fn: (s: number) => number, gain: number, pan = 0) => { const i0 = Math.round(t * sr); for (let i = 0; i < len * sr && i0 + i < n; i++) { if (i0 + i < 0) continue; const v = fn(i / sr) * gain; L[i0 + i] += v * (1 - Math.max(0, pan)); R[i0 + i] += v * (1 + Math.min(0, pan)); } };
+ const click = (fr: number) => { const f0 = 2600 + r() * 1400, ph = r() * 6; add(fr / FPS, 0.03, (s) => Math.sin(2 * Math.PI * f0 * s + ph) * Math.exp(-s / 0.004) + (r() - 0.5) * Math.exp(-s / 0.002) * 0.6, 0.05, (r() - 0.5) * 0.4); };
+ const thock = (fr: number) => add(fr / FPS, 0.14, (s) => Math.sin(2 * Math.PI * (70 + 90 * Math.exp(-s / 0.02)) * s) * Math.exp(-s / 0.05), 0.2);
+ const plip = (fr: number) => add(fr / FPS, 0.16, (s) => Math.sin(2 * Math.PI * (320 + 700 * Math.exp(-s / 0.03)) * s) * Math.exp(-s / 0.06), 0.12);
+ const whoosh = (fr: number, len = 0.5, g = 0.5) => { let z = 0; add(fr / FPS, len, (s) => { z += 0.14 * ((r() - 0.5) - z); return z * Math.sin((Math.PI * s) / len) ** 2; }, g); };
+ const scratch = (fr: number, len: number) => { let z = 0; add(fr / FPS, len, (s) => { z += 0.5 * ((r() - 0.5) - z); return z * (0.6 + 0.4 * Math.sin(s * 70)) * Math.min(1, s * 20) * Math.min(1, (len - s) * 20); }, 0.05); };
+ ASK.times.forEach(click); thock(ASK.down); plip(DROP0.land); scratch(2, 1.6);
+ SW.times.forEach(click); thock(SW.down); plip(SW.drop.land); whoosh(SWIM_OUT, 0.8);
+ HD.times.forEach(click); thock(HD.down); plip(HD.drop.land);
+ whoosh(T2.wall[0], 0.45); PUNCHES.forEach((p) => whoosh(WALL_T0 + p.t0 * FPS, 0.35, 0.4)); whoosh(T2.brick[0] + 120, 0.9);
+ whoosh(T2.hand[0], 0.5); whoosh(FLIP - 6, 0.35, 0.4); whoosh(T2.web[0], 0.45); whoosh(T2.film[0], 0.5); whoosh(T2.words[0], 0.6);
+ return [L, R];
+};
+
+// ---------------------------------------------------------------- the film
+const shot = (id: keyof typeof T2, draw: (ctx: Ctx, env: Env, f: number) => void) => ({ id, start: T2[id][0], end: T2[id][1], draw: (ctx: Ctx, local: number, env: Env) => draw(ctx, env, T2[id][0] + local) });
+export const launch2: Film = {
+ meta: { title: "anidoodle · launch, cut 2", W, H, fps: FPS, bpm: 90, durationFrames: N, raster: "cpu", kind: "launch" },
+ assets: { images: { almond: "assets/refs/vangogh-almond-blossom.jpg" } }, // public domain; provenance in engine/assets/refs/PROVENANCE.json
+ shots: [
+ shot("open", sceneOpen), shot("ask", sceneAsk), shot("code", sceneCode), shot("swim", sceneSwim), shot("wall", sceneWall), shot("brick", sceneBrick),
+ shot("hand", sceneHand), shot("loop", sceneLoop), shot("web", sceneWeb), shot("film", sceneFilm), shot("words", sceneWords), shot("end", sceneEnd),
+ ],
+ audio: audio2,
+};
+export const KEYS2 = () => ({ SW, HD, KOI_DONE, SWIM_OUT, PUNCHES, LAYOUT: LAYOUT.map((l) => [l.it.kind, l.y, l.h]) });
+
+// the picture alone, at content frame f (launch3.ts cuts it together with the type frames)
+export const content2 = (ctx: Ctx, env: Env, f: number) => { const g = Math.max(0, Math.min(N - 1, Math.round(f))), sh = launch2.shots.find((x) => g >= x.start && g < x.end)!; sh.draw(ctx, g - sh.start, env); };
+// the interface's sound events in content frames (launch3.ts maps them onto the cut)
+export const SFX2 = () => ({ clicks: [...ASK.times, ...SW.times, ...HD.times], thocks: [ASK.down, SW.down, HD.down], plips: [DROP0.land, HD.drop.land], punches: PUNCHES.map((p) => WALL_T0 + p.t0 * FPS), flip: FLIP - 6 });
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch3.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch3.ts
new file mode 100644
index 0000000..25ac91e
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch3.ts
@@ -0,0 +1,96 @@
+// LAUNCH, CUT 3. Alex on cut 2: "every frame has ugly text overlaying visual elements... text must be
+// a frame: white, big animated text, then the show." So the words never sit on the art. Cut 3 is
+// cut 2's pictures (launch2.content2, all type removed) spliced with TYPE FRAMES: a sheet of paper
+// sweeps in over the picture, one big word letters itself on in its own medium, and the paper sweeps
+// off to reveal the next scene. (Chosen: the ink bloom, and every word in ink.) 29 bars of the score (launchLofi3), 77 s.
+import type { Ctx, Env } from "./core";
+import type { Film } from "./film";
+import { C, blot, expo, pathOf, ramp, selfLayer } from "./launchKit";
+import { content2, SFX2, T2, WEB_SKIP } from "./launch2";
+import { logoBug, measure, writeOn, type KStyle } from "./kinetic";
+import { launchLofi3 } from "./music/pieces/launch";
+import { renderPiece } from "./music/render";
+import { rng } from "./core";
+
+const W = 1920, H = 1080, FPS = 30;
+type Line = { text: string; style: KStyle; color: string };
+type Seg = { kind: "pic"; from: number; to: number; len: number } | { kind: "type"; lines: Line[]; len: number; before: number; after: number };
+const pic = (from: number, to: number, len = to - from): Seg => ({ kind: "pic", from, to, len });
+const type = (lines: Line[], len: number, before: number, after = before): Seg => ({ kind: "type", lines, len, before, after });
+// Alex on cut 3: gentler pacing; ANIMATIONS before the swim request; the koi-and-code beat much
+// shorter; the embroidery long enough to see; the site from Bit's hero on. The film beat's length is
+// solved so "All in pure code." (content T2.words[0] + 140) lands on bar 26, the score's home chord.
+const WEB_FROM = T2.web[0] + 10, WEB_LEN = 360 - WEB_SKIP;
+const HEAD: Seg[] = [
+ pic(0, 200),
+ pic(200, 360, 90), // the koi and its code, twice as fast
+ type([{ text: "NO IMAGE MODEL.", style: "ink", color: C.ink }, { text: "JUST CODE.", style: "ink", color: C.accent }], 64, 359, 360),
+ pic(360, 372),
+ type([{ text: "ANIMATIONS", style: "ink", color: C.ink }], 50, 371, 372),
+ pic(372, 560),
+ type([{ text: "31 STYLES", style: "ink", color: C.ink }], 50, 559, 570),
+ pic(570, 800),
+ pic(800, 1040, 200),
+ pic(1040, 1200),
+ type([{ text: "LOOPS", style: "ink", color: C.ink }], 50, 1199, 1200),
+ pic(1200, 1360),
+ type([{ text: "INTERACTIVE", style: "ink", color: C.ink }], 50, 1359, WEB_FROM),
+ pic(WEB_FROM, WEB_FROM + WEB_LEN),
+ type([{ text: "FILMS", style: "ink", color: C.ink }], 60, WEB_FROM + WEB_LEN - 1, T2.film[0]),
+];
+const headLen = HEAD.reduce((a, s) => a + s.len, 0), CLAIM = 26 * 80, FILM_LEN = CLAIM - 140 - headLen;
+if (FILM_LEN < 90) throw new Error(`launch3: the film beat would be ${FILM_LEN} frames; the cut before it is too long for the claim to land on bar 26`);
+const SEGS: Seg[] = [...HEAD, pic(T2.film[0], T2.film[1], FILM_LEN), pic(T2.words[0], T2.words[1]), pic(T2.end[0], T2.end[1]), pic(T2.end[1] - 1, T2.end[1], 60)];
+const STARTS = (() => { let t = 0; return SEGS.map((s) => { const a = t; t += s.len; return a; }); })();
+export const N3 = STARTS[STARTS.length - 1] + SEGS[SEGS.length - 1].len;
+const at = (F: number) => { let i = SEGS.length - 1; while (i > 0 && STARTS[i] > F) i--; return { s: SEGS[i], local: F - STARTS[i] }; };
+const contentOf = (s: Extract<Seg, { kind: "pic" }>, local: number) => s.from + ((s.to - s.from) * local) / s.len;
+// a content frame, mapped to the cut (for the sound events); events inside a cut-away go to its start
+export const cutOf = (c: number) => { for (let i = 0; i < SEGS.length; i++) { const s = SEGS[i]; if (s.kind === "pic" && c >= s.from && c < s.to) return STARTS[i] + ((c - s.from) * s.len) / (s.to - s.from); } return -1; };
+
+// ---------------------------------------------------------------- a type frame
+const IN = 14, OUT = 14; // gentle: the bloom opens and closes over half a second
+// Alex's pick: B, the ink bloom. The Generate drop's own ink blooms from the centre over the picture,
+// the page is inside the bloom, the word is written on it in ink by the pointed pen, and the ink
+// shrinks back to a point to show the next scene.
+const drawType = (ctx: Ctx, env: Env, s: Extract<Seg, { kind: "type" }>, local: number, F: number) => {
+ const u = expo(ramp(local, 0, IN + 2)), v = expo(ramp(local, s.len - OUT, s.len)), R = 1250 * (v > 0 ? 1 - v : u);
+ content2(ctx, env, local < s.len / 2 ? s.before : s.after);
+ if (R < 2) return;
+ const L = selfLayer(env, "sheet", Math.round(W * env.scale), Math.round(H * env.scale)), c = L.ctx;
+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = C.bg; c.fillRect(0, 0, W, H);
+ const n = s.lines.length, size = Math.min(n === 1 ? 190 : 130, ...s.lines.map((l) => (1560 / measure(l.text, 100)) * 100)), gap = size * 1.45, y0 = H / 2 - ((n - 1) * gap) / 2 + size * 0.5;
+ s.lines.forEach((l, i) => writeOn(c, env, l.text, W / 2, y0 + i * gap, size, ramp(local, IN - 2 + i * 20, IN + 16 + i * 20), l.style, { color: l.color, align: "center", seed: 7 + i }));
+ logoBug(c, env, F, 1700, 1040, 0.9, { t0: -100, fps: FPS });
+ const ctr: [number, number] = [W / 2, H / 2];
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.save();
+ pathOf(ctx, blot(ctr, R + 26, 88)); ctx.fillStyle = C.ink; ctx.fill(); pathOf(ctx, blot(ctr, Math.max(0, R - 4), 88)); ctx.clip();
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas, 0, 0); ctx.restore();
+};
+
+// ---------------------------------------------------------------- the sound
+const audio3 = (sr: number): [Float32Array, Float32Array] => {
+ const n = Math.round((N3 / FPS) * sr), L = new Float32Array(n), R = new Float32Array(n), m = renderPiece(launchLofi3(), sr);
+ for (let i = 0; i < n && i < m.L.length; i++) { L[i] = m.L[i]; R[i] = m.R[i]; }
+ const fade = Math.round(1.2 * sr); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }
+ const r = rng(4242), add = (fr: number, len: number, fn: (s: number) => number, gain: number, pan = 0) => { if (fr < 0) return; const i0 = Math.round((fr / FPS) * sr); for (let i = 0; i < len * sr && i0 + i < n; i++) { const v = fn(i / sr) * gain; L[i0 + i] += v * (1 - Math.max(0, pan)); R[i0 + i] += v * (1 + Math.min(0, pan)); } };
+ const click = (fr: number) => { const f0 = 2600 + r() * 1400, ph = r() * 6; add(fr, 0.03, (s) => Math.sin(2 * Math.PI * f0 * s + ph) * Math.exp(-s / 0.004) + (r() - 0.5) * Math.exp(-s / 0.002) * 0.6, 0.05, (r() - 0.5) * 0.4); };
+ const thock = (fr: number) => add(fr, 0.14, (s) => Math.sin(2 * Math.PI * (70 + 90 * Math.exp(-s / 0.02)) * s) * Math.exp(-s / 0.05), 0.2);
+ const plip = (fr: number) => add(fr, 0.16, (s) => Math.sin(2 * Math.PI * (320 + 700 * Math.exp(-s / 0.03)) * s) * Math.exp(-s / 0.06), 0.12);
+ const whoosh = (fr: number, len = 0.4, g = 0.5) => { let z = 0; add(fr, len, (s) => { z += 0.14 * ((r() - 0.5) - z); return z * Math.sin((Math.PI * s) / len) ** 2; }, g); };
+ const scratch = (fr: number, len: number, g = 0.05) => { let z = 0; add(fr, len, (s) => { z += 0.5 * ((r() - 0.5) - z); return z * (0.6 + 0.4 * Math.sin(s * 70)) * Math.min(1, s * 20) * Math.min(1, (len - s) * 20); }, g); };
+ const e = SFX2();
+ e.clicks.forEach((c) => click(cutOf(c))); e.thocks.forEach((c) => thock(cutOf(c))); e.plips.forEach((c) => plip(cutOf(c)));
+ e.punches.forEach((c) => whoosh(cutOf(c), 0.3, 0.4)); whoosh(cutOf(e.flip), 0.3, 0.4); whoosh(cutOf(T2.brick[0] + 120), 0.9); whoosh(cutOf(T2.hand[0]), 0.5);
+ scratch(2, 1.6);
+ SEGS.forEach((s, i) => { if (s.kind !== "type") return; whoosh(STARTS[i], 0.32, 0.55); s.lines.forEach((_, k) => scratch(STARTS[i] + IN - 2 + k * 10, 0.6, 0.07)); whoosh(STARTS[i] + s.len - OUT, 0.32, 0.55); });
+ return [L, R];
+};
+
+export const launch3: Film = {
+ meta: { title: "anidoodle · launch, cut 3", W, H, fps: FPS, bpm: 90, durationFrames: N3, raster: "cpu", kind: "launch" },
+ assets: { images: { almond: "assets/refs/vangogh-almond-blossom.jpg" } }, // public domain; provenance in engine/assets/refs/PROVENANCE.json
+ shots: [{ id: "cut", start: 0, end: N3, draw: (ctx, F, env) => { const { s, local } = at(F); if (s.kind === "pic") content2(ctx, env, contentOf(s, local)); else drawType(ctx, env, s, local, F); } }],
+ audio: audio3,
+};
+export const SEGS3 = () => SEGS.map((s, i) => [s.kind, STARTS[i], s.len, s.kind === "type" ? s.lines.map((l) => l.text).join(" / ") : `${s.from}-${s.to}`]);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchClip.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchClip.ts
new file mode 100644
index 0000000..3afd440
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchClip.ts
@@ -0,0 +1 @@
+export { launchClip } from "./launch";
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCode.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCode.ts
new file mode 100644
index 0000000..1d55653
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCode.ts
@@ -0,0 +1,64 @@
+// GENERATED from koi.ts (drawFish, verbatim, long lines cut at 78 chars): the code the launch
+// film shows streaming beside the koi as it draws. Regenerate if drawFish changes.
+export const KOI_CODE: string[] = [
+"export const drawFish = (g: Gfx, k: KoiClock, b: Body, fins: ReturnType<typeo…",
+" // the fish's shadow on the pond floor, flat and hard, down-right away from…",
+" const floor = [b.outline, cau.shape, ...fins.map((f) => f.shape)].map((s) =…",
+" g.group(\"plain\", () => lay(g, k(\"floor\", \"shade\"), floor, () => floor.forEa…",
+"",
+" // fins under the body: translucent, cel-shaded, a black base on the pector…",
+" g.group(\"plain\", () => {",
+" fins.forEach((f, i) => {",
+" const el = `fin${i}`, fl = k(el, \"flat\"), sh = k(el, \"shade\"), dt = k(e…",
+" const moto = () => { if (i < 2) fillShape(g, blob(...(i === 0 ? b.at(0.…",
+" const cel = () => { fillShape(g, f.shape, FIN_S, 0.88); clipped(g, f.sh…",
+" if (sh >= 1) cel();",
+" else { lay(g, part(fl, 0, 2), [f.shape], () => fillShape(g, f.shape, FI…",
+" f.rays.forEach((ray, kk) => inkP(g, ray, mix(INK, FIN_S, 0.35), { w: 1.…",
+" inkP(g, f.shape, INK, { w: 4.2, closed: true, light: LIGHT, shadow: 0.8…",
+" });",
+" });",
+"",
+" // the body: shade cel underneath, the lit white pushed toward the light, t…",
+" const bs = b.outline, bsL = bs.map(([x, y]) => [x + LIGHT[0] * 22, y + LIGH…",
+" const bfl = k(\"body\", \"flat\"), bsh = k(\"body\", \"shade\");",
+" g.group(\"plain\", () => {",
+" if (bsh >= 1) fillShape(g, bs, WHITE_S);",
+" else { lay(g, bfl, [bs], () => fillShape(g, bs, WHITE), 5201, 34, -0.35);…",
+" clipped(g, bs, () => {",
+" if (bsh >= 1) fillShape(g, bsL, WHITE);",
+" // red hi: head crown, a saddle across the back, a patch toward the tai…",
+" const hf = k(\"hi\", \"flat\"), hs = k(\"hi\", \"shade\");",
+" const patches = KOI_HI;",
+" patches.forEach(([t, s, dt, ds, seed], pi) => {",
+" const r = rng(seed * 17), pts: P[] = [];",
+" for (let i = 0; i < 16; i++) { const a = (i / 16) * Math.PI * 2, kk =…",
+" const sh = smooth(pts, true, 6), ps = part(hs, pi, 5);",
+" const cel = () => { fillShape(g, sh, HI_S); clipped(g, sh, () => fill…",
+" if (ps >= 1) cel(); else { lay(g, part(hf, pi, 5), [sh], () => fillSh…",
+" });",
+" // sumi: a few black spots, never on the head",
+" const sf = k(\"sumi\", \"flat\");",
+" ([[0.3, 0.55, 0.028, 0.32, 31], [0.55, -0.55, 0.03, 0.3, 32], [0.61, 0.…",
+" const r = rng(seed), pts: P[] = []; for (let i = 0; i < 12; i++) { co…",
+" const sp = smooth(pts, true, 5); lay(g, part(sf, si, 5), [sp], () => …",
+" });",
+" // scales: a loose lattice of arcs, strongest on the lit back, gone int…",
+" const r = rng(55), sc = k(\"scales\", \"detail\");",
+" for (let t = 0.2; t < 0.93; t += 0.034) for (let s = -0.75; s <= 0.8; s…",
+" const tt = t + (Math.round(s / 0.3) % 2 ? 0.017 : 0), ss = s + (r() -…",
+" const lit = ss < 0.35 && !(r() < 0.3);",
+" if (lit) inkP(g, smooth([q, m, u], false, 5), \"#2a1f3a\", { w: 1.5, sh…",
+" void p;",
+" }",
+" // the wet highlight along the back, and a glint on the head",
+" const hl = k(\"gloss\", \"detail\");",
+" [[0.2, 0.3, -0.6, 7], [0.335, 0.42, -0.64, 6], [0.46, 0.5, -0.66, 4.5],…",
+" const glint = blob(...b.at(0.075, -0.35), 22, 9, 91, 0.1, 10, -0.7);",
+" lay(g, part(hl, 4, 5), [glint], () => fillShape(g, blob(...b.at(0.075, …",
+" });",
+" // dorsal fin down the spine: a narrow flutter of translucent fin with ra…",
+" const df: P[] = [], dfr: P[] = [];",
+" for (let i = 0; i <= 16; i++) { const f = i / 16, t = 0.36 + f * 0.3, h =…",
+" const dorsal = [...smooth(df, false, 3), ...smooth(dfr, false, 3).reverse…"
+];
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchGallery.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchGallery.ts
new file mode 100644
index 0000000..465bc51
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchGallery.ts
@@ -0,0 +1,135 @@
+// THE GALLERY WALL. All 31 anidoodle styles as cards on a tilted wall of rows that never stop
+// rolling (alternate rows in opposite directions, like a marquee), each card drawn by that style's
+// own plate code, once, at the size it is shown. The camera flies over the wall and punches into
+// cards one after another: a fast expo zoom that tracks the card as its row keeps moving, a beat of
+// hold while the style's name is on screen, and out again. The last punch doesn't come back out:
+// it fills the frame and hands over to the next scene.
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { C, SANS, clamp, expo, lerp, lerpP, plateLayer, ramp, rr, softShadow } from "./launchKit";
+import { balloon } from "./balloon";
+import { blueprint } from "./blueprint";
+import { brokenColour } from "./brokenColour";
+import { charcoalErasure } from "./charcoalErasure";
+import { colouredPencil } from "./colouredPencil";
+import { embroidery } from "./embroidery";
+import { flatVector } from "./flatVector";
+import { folkTale } from "./folkTale";
+import { fox } from "./fox";
+import { halftone } from "./halftone";
+import { isometric } from "./isometric";
+import { koi } from "./koi";
+import { lighthouse } from "./lighthouse";
+import { lowPoly } from "./lowPoly";
+import { mellan } from "./mellan";
+import { midCentury } from "./midCentury";
+import { moonPhases } from "./moonPhases";
+import { paintedOil } from "./paintedOil";
+import { paperCraft } from "./paperCraft";
+import { pixelArt } from "./pixelArt";
+import { pocketWatch } from "./pocketWatch";
+import { ranunculus } from "./ranunculus";
+import { rubberHose } from "./rubberHose";
+import { scrapbook } from "./scrapbook";
+import { scratchboard } from "./scratchboard";
+import { stipple } from "./stipple";
+import { storybookDraw } from "./storybookDraw";
+import { sumiE } from "./sumiE";
+import { toyBrick } from "./toyBrick";
+import { woodcut } from "./woodcut";
+import { wren } from "./wren";
+
+type Card = { id: string; name: string; film: Film };
+// the wall's order is a hang: neighbours contrast in value and palette
+export const CARDS: Card[] = [
+ { id: "scratchboard", name: "Scratchboard", film: scratchboard }, { id: "balloon", name: "Crayon", film: balloon }, { id: "sumiE", name: "Sumi-e", film: sumiE },
+ { id: "pixelArt", name: "Pixel art", film: pixelArt }, { id: "woodcut", name: "Ukiyo-e woodblock", film: woodcut }, { id: "stipple", name: "Stipple", film: stipple },
+ { id: "halftone", name: "Newsprint halftone", film: halftone }, { id: "koi", name: "Marker comic", film: koi }, { id: "blueprint", name: "Cyanotype", film: blueprint },
+ { id: "paintedOil", name: "Oil on canvas", film: paintedOil }, { id: "toyBrick", name: "Toy brick", film: toyBrick }, { id: "mellan", name: "Single-line engraving", film: mellan },
+ { id: "lighthouse", name: "Risograph", film: lighthouse }, { id: "embroidery", name: "Embroidery", film: embroidery }, { id: "lowPoly", name: "Low-poly", film: lowPoly },
+ { id: "rubberHose", name: "Rubber hose", film: rubberHose }, { id: "fox", name: "Cut paper", film: fox }, { id: "colouredPencil", name: "Coloured pencil", film: colouredPencil },
+ { id: "moonPhases", name: "Chalkboard", film: moonPhases }, { id: "flatVector", name: "Flat vector", film: flatVector }, { id: "folkTale", name: "Folk-tale storybook", film: folkTale },
+ { id: "charcoalErasure", name: "Charcoal", film: charcoalErasure }, { id: "ranunculus", name: "Pencil & watercolour", film: ranunculus }, { id: "isometric", name: "Isometric", film: isometric },
+ { id: "pocketWatch", name: "Ballpoint", film: pocketWatch }, { id: "paperCraft", name: "Paper theatre", film: paperCraft }, { id: "midCentury", name: "Mid-century gouache", film: midCentury },
+ { id: "brokenColour", name: "Broken colour", film: brokenColour }, { id: "wren", name: "Ink & line-wash", film: wren }, { id: "scrapbook", name: "Scrapbook", film: scrapbook },
+ { id: "storybook", name: "Storybook", film: storybookDraw },
+];
+
+// ---------------------------------------------------------------- the wall
+const ROWS = 4, CARD = 330, GAP = 34, PITCH = CARD + GAP, TILT = -0.12; // radians: the wall is hung at a slant, for motion
+const ROW_SPEED = [52, -64, 58, -48]; // world px per second, alternate directions
+const PER_ROW = Math.ceil(CARDS.length / ROWS);
+const cardAt = (row: number, k: number) => CARDS[(row * PER_ROW + (((k % PER_ROW) + PER_ROW) % PER_ROW)) % CARDS.length];
+// where card k of a row is at time t, in wall coordinates (wall origin = frame centre)
+const slot = (row: number, k: number, t: number): P => [k * PITCH + ROW_SPEED[row] * t + (row % 2) * PITCH * 0.5, (row - (ROWS - 1) / 2) * PITCH];
+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, 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 };
+const toScreen = (cam: WallCam, p: P, W: number, H: number): P => {
+ const x = (p[0] - cam.c[0]) * cam.z, y = (p[1] - cam.c[1]) * cam.z, co = Math.cos(cam.rot), si = Math.sin(cam.rot);
+ return [W / 2 + x * co - y * si, H / 2 + x * si + y * co];
+};
+
+// focus: the featured card, drawn last, grown by `grow` (0..1) toward `size` px on screen and
+// eased toward `toward` (a screen point); the rest of the wall eases back under a soft veil
+export type WallFocus = { row: number; k: number; grow: number; size: number; toward: P };
+export const drawWall = (ctx: Ctx, env: Env, t: number, cam: WallCam, focus?: WallFocus) => {
+ const W = env.W, H = env.H, s = env.scale;
+ ctx.setTransform(s, 0, 0, s, 0, 0); ctx.fillStyle = C.bg; ctx.fillRect(0, 0, W, H);
+ const reach = (Math.hypot(W, H) / 2 / cam.z) + PITCH * 1.5;
+ const card = (row: number, k: number, q: P, scale: number, rot: number, px: number) => {
+ ctx.save(); ctx.setTransform(s, 0, 0, s, 0, 0); ctx.translate(q[0], q[1]); ctx.rotate(rot); ctx.scale(scale, scale);
+ softShadow(ctx, -CARD / 2, -CARD / 2, CARD, CARD, 14, 1.2 + (scale > cam.z * 1.05 ? 1.2 : 0));
+ rr(ctx, -CARD / 2, -CARD / 2, CARD, CARD, 14); ctx.clip(); ctx.drawImage(thumb(env, cardAt(row, k), px).canvas, -CARD / 2, -CARD / 2, CARD, CARD);
+ ctx.restore();
+ };
+ for (let row = 0; row < ROWS; row++) {
+ const off = ROW_SPEED[row] * t + (row % 2) * PITCH * 0.5, k0 = Math.floor((cam.c[0] - reach - off) / PITCH), k1 = Math.ceil((cam.c[0] + reach - off) / PITCH);
+ for (let k = k0; k <= k1; k++) {
+ if (focus && focus.row === row && focus.k === k && focus.grow > 0) continue;
+ const p = slot(row, k, t); if (Math.abs(p[1] - cam.c[1]) > reach) continue;
+ card(row, k, toScreen(cam, p, W, H), cam.z, cam.rot, CARD * cam.z > 360 ? 540 : 360);
+ }
+ }
+ if (focus && focus.grow > 0) {
+ const g = focus.grow, q0 = toScreen(cam, slot(focus.row, focus.k, t), W, H), q: P = lerpP(q0, focus.toward, g), sc = Math.exp(lerp(Math.log(cam.z), Math.log(focus.size / CARD), g));
+ ctx.setTransform(s, 0, 0, s, 0, 0); ctx.fillStyle = `rgba(236,230,218,${0.55 * g})`; ctx.fillRect(0, 0, W, H); // the wall eases back
+ card(focus.row, focus.k, q, sc, lerp(cam.rot, 0, g), 1080);
+ }
+};
+void rowSpan;
+
+// ---------------------------------------------------------------- the choreography
+// Alex: no swooshing camera. The camera rides the wall gently and never zooms; the featured card
+// itself grows out of its row, holds, and settles back. The last one grows to fill the frame.
+export const PUNCH_IN = 18, PUNCH_HOLD = 30, PUNCH_OUT = 16, PUNCH = PUNCH_IN + PUNCH_HOLD + PUNCH_OUT;
+const soft = (u: number) => { const c = clamp(u); return c * c * (3 - 2 * c); };
+export const wallCam = (t: number, punches: Punch[], fps: number, W: number, H: number, finalHold = false): { cam: WallCam; focus?: WallFocus; card?: Card } => {
+ const cam: WallCam = { c: [lerp(-240, 240, clamp(t / 8)), 0], z: 0.72, rot: TILT };
+ for (let i = 0; i < punches.length; i++) {
+ const p = punches[i], f = t * fps - p.t0 * fps, last = i === punches.length - 1 && finalHold;
+ if (f < 0 || (!last && f >= PUNCH)) continue;
+ const grow = soft(f / (last ? PUNCH_IN + 12 : PUNCH_IN)) * (last ? 1 : 1 - soft((f - PUNCH_IN - PUNCH_HOLD) / PUNCH_OUT));
+ return { cam, focus: { row: p.row, k: p.k, grow, size: last ? H : 620, toward: last ? [W / 2, H / 2] : [W / 2, H / 2] }, card: cardAt(p.row, p.k) };
+ }
+ return { cam };
+};
+export const cardOf = (row: number, k: number) => cardAt(row, k);
+
+// a gallery-only test film: the wall with five punches, the last one holding
+const TEST_PUNCHES: Punch[] = [{ row: 1, k: 1, t0: 1.2 }, { row: 2, k: 3, t0: 2.8 }, { row: 0, k: 2, t0: 4.4 }, { row: 3, k: 2, t0: 6.0 }, { row: 1, k: 3, t0: 7.6 }];
+export const styleWall: Film = {
+ meta: { title: "anidoodle · the 31-style wall", W: 1920, H: 1080, fps: 30, bpm: 90, durationFrames: 300 },
+ assets: { images: {} },
+ shots: [{ id: "wall", start: 0, end: 300, draw: (ctx, f, env) => {
+ const t = f / 30, w = wallCam(t, TEST_PUNCHES, 30, env.W, env.H, true);
+ drawWall(ctx, env, t, w.cam, w.focus);
+ } }],
+};
+void ramp; void rr;
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts
new file mode 100644
index 0000000..da01741
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts
@@ -0,0 +1,171 @@
+// LAUNCH KIT. The pieces of the launch film that are not artwork: timing curves, a camera, a
+// chat surface, a pointer, an ink blot, and the one bridge that matters, `plateLayer`, which
+// draws any existing film of this engine into an offscreen surface at any frame so the launch
+// film can place it, zoom it and cut out of it. Every plate shown in the launch film is the real
+// plate drawn live by its own code, never a recording of it.
+import { fractal, type Ctx, type Env, type Layer, type P } from "./core";
+import { renderFrame, type Film } from "./film";
+
+// ---------------------------------------------------------------- palette and type
+export const C = {
+ bg: "#ece6da", card: "#fffdf8", ink: "#1d1a16", soft: "#6f675c", mute: "#a39a8c", line: "#e0d8c8",
+ chip: "#f3ede1", accent: "#d4622b", accentDeep: "#a9471a", paper: "#fbf9f3", shadow: "rgba(60,40,20,0.10)",
+};
+export const SANS = (w: number, px: number) => `${w} ${px}px "Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;
+export const MONO = (px: number) => `${px}px "SF Mono", Menlo, Monaco, monospace`;
+
+// ---------------------------------------------------------------- time
+export const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+export const ramp = (f: number, a: number, b: number) => clamp((f - a) / (b - a));
+export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+export const lerpP = (a: P, b: P, t: number): P => [lerp(a[0], b[0], t), lerp(a[1], b[1], t)];
+export const inOut = (t: number) => { const c = clamp(t); return c < 0.5 ? 4 * c * c * c : 1 - Math.pow(-2 * c + 2, 3) / 2; };
+export const out3 = (t: number) => 1 - Math.pow(1 - clamp(t), 3);
+export const in3 = (t: number) => Math.pow(clamp(t), 3);
+// expo in/out: the camera move of motion design, slow off the mark, fast through, slow landing
+export const expo = (t: number) => { const c = clamp(t); return c === 0 ? 0 : c === 1 ? 1 : c < 0.5 ? Math.pow(2, 20 * c - 10) / 2 : (2 - Math.pow(2, -20 * c + 10)) / 2; };
+// a closed-form damped spring step: 0 before t0, settles to 1. zeta < 1 overshoots a little.
+export const spring = (f: number, t0: number, omega = 0.45, zeta = 0.72) => {
+ const t = f - t0; if (t <= 0) return 0;
+ const wd = omega * Math.sqrt(1 - zeta * zeta);
+ return 1 - Math.exp(-zeta * omega * t) * (Math.cos(wd * t) + ((zeta * omega) / wd) * Math.sin(wd * t));
+};
+// a press: 0 -> dips toward 1 -> springs back past 0 and settles
+export const press = (f: number, down: number, up: number) => (f < down ? 0 : f < up ? out3((f - down) / (up - down)) : 1 - spring(f, up, 0.55, 0.45));
+
+// ---------------------------------------------------------------- camera
+// world coordinates are the 1920x1080 frame; the camera looks at `c` with magnification `z`
+export type Cam = { c: P; z: number };
+export const HOME: Cam = { c: [960, 540], z: 1 };
+export const camLerp = (a: Cam, b: Cam, t: number): Cam => {
+ const z = Math.exp(lerp(Math.log(a.z), Math.log(b.z), t)); // zoom travels in log space or it lurches
+ // keep the path of the centre steady on screen, not in world: weight it by the zoom
+ const w = (z - a.z) / (b.z - a.z || 1);
+ return { z, c: lerpP(a.c, b.c, Math.abs(b.z - a.z) < 1e-6 ? t : clamp(w)) };
+};
+export const useCam = (ctx: Ctx, env: Env, cam: Cam) => {
+ const s = env.scale * cam.z;
+ ctx.setTransform(s, 0, 0, s, env.scale * (env.W / 2 - cam.c[0] * cam.z), env.scale * (env.H / 2 - cam.c[1] * cam.z));
+};
+export const toScreen = (cam: Cam, p: P, W = 1920, H = 1080): P => [W / 2 + (p[0] - cam.c[0]) * cam.z, H / 2 + (p[1] - cam.c[1]) * cam.z];
+
+// ---------------------------------------------------------------- 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.
+// `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) {
+ const L = env.canvas(Math.round(film.meta.W * scale), Math.round(film.meta.H * scale));
+ rec = { L, sub: { W: film.meta.W, H: film.meta.H, scale, cache: new Map(), canvas: env.canvas, image: env.image }, last: NaN };
+ env.cache.set(lk, rec);
+ }
+ const f = Math.max(0, Math.min(film.meta.durationFrames - 1, Math.round(frame)));
+ 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
+export const selfLayer = (env: Env, key: string, w: number, h: number): Layer => {
+ const lk = `self:${key}:${w}x${h}`; let L = env.cache.get(lk) as Layer | undefined;
+ if (!L) { L = env.canvas(w, h); env.cache.set(lk, L); }
+ L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.clearRect(0, 0, w, h); return L;
+};
+
+// ---------------------------------------------------------------- shapes
+export const rr = (ctx: Ctx, x: number, y: number, w: number, h: number, r: number) => {
+ const q = Math.min(r, w / 2, h / 2); ctx.beginPath(); ctx.moveTo(x + q, y); ctx.arcTo(x + w, y, x + w, y + h, q); ctx.arcTo(x + w, y + h, x, y + h, q); ctx.arcTo(x, y + h, x, y, q); ctx.arcTo(x, y, x + w, y, q); ctx.closePath();
+};
+export const softShadow = (ctx: Ctx, x: number, y: number, w: number, h: number, r: number, depth = 1) => {
+ for (let i = 5; i >= 1; i--) { ctx.fillStyle = `rgba(70,45,20,${0.018 * depth})`; rr(ctx, x - i * 2, y - i * 1 + i * 3, w + i * 4, h + i * 4, r + i * 2); ctx.fill(); }
+};
+// an ink blot of radius R about c: a wobbling rim, seeded; `grow` 0..1 lets the lobes lead
+export const blot = (c: P, R: number, seed: number, n = 96): P[] => {
+ const pts: P[] = [];
+ for (let i = 0; i < n; i++) {
+ const a = (i / n) * Math.PI * 2, k = fractal(seed, Math.cos(a) * 1.6 + 5, Math.sin(a) * 1.6 + 5, 1, 1, 3);
+ const r = R * (0.9 + 0.22 * k);
+ pts.push([c[0] + Math.cos(a) * r, c[1] + Math.sin(a) * r]);
+ }
+ return pts;
+};
+export const pathOf = (ctx: Ctx, pts: P[]) => { ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); };
+
+// ---------------------------------------------------------------- pointer
+export const pointer = (ctx: Ctx, p: P, down = 0, s = 1.35) => {
+ const k = s * (1 - 0.12 * down);
+ const shape: P[] = [[0, 0], [0, 25], [6.4, 19.2], [10.6, 29], [14.8, 27.2], [10.8, 17.8], [19, 17.8]];
+ ctx.save(); ctx.translate(p[0], p[1]); ctx.scale(k, k);
+ ctx.fillStyle = "rgba(0,0,0,0.18)"; pathOf(ctx, shape.map(([x, y]) => [x + 1.2, y + 2] as P)); ctx.fill();
+ pathOf(ctx, shape); ctx.fillStyle = "#111"; ctx.fill(); ctx.lineWidth = 1.6; ctx.strokeStyle = "#fff"; ctx.lineJoin = "round"; ctx.stroke();
+ ctx.restore();
+};
+
+// ---------------------------------------------------------------- the chat
+// The layout of the one conversation the film lives in (world coordinates).
+export const CHAT = { x: 300, y: 56, w: 1320, h: 968, r: 34 };
+export const INPUT = { x: 360, y: 884, w: 1200, h: 104, r: 30 };
+export const GEN = { x: 1370, y: 906, w: 166, h: 60, r: 30 };
+export const REPLY = { x: 400, y: 214, s: 600 }; // the art card: a square the plate lands in
+export const TEXT = { x: 404, base: 948, px: 34 };
+
+export type ChatState = {
+ typed: string; caret: boolean; placeholder?: string;
+ sent?: string; sentAlpha?: number; // the user's message once it has gone up
+ attach?: { img: CanvasImageSource; label: string } | null;
+ genPress?: number; genHot?: number; // the button: press depth 0..1, hover glow 0..1
+ label?: string; labelAlpha?: number; // the reply's byline
+};
+
+export const drawChatFrame = (ctx: Ctx, s: ChatState) => {
+ ctx.fillStyle = C.bg; ctx.fillRect(-2000, -2000, 6000, 6000);
+ softShadow(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, CHAT.r, 1.2);
+ ctx.fillStyle = C.card; rr(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, CHAT.r); ctx.fill();
+ // the thread's head: a small ink dot and a name, nothing that belongs to anyone else
+ ctx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(CHAT.x + 58, CHAT.y + 52, 9, 0, Math.PI * 2); ctx.fill();
+ ctx.font = SANS(600, 22); ctx.fillStyle = C.ink; ctx.textBaseline = "middle"; ctx.fillText("anidoodle", CHAT.x + 80, CHAT.y + 53);
+ ctx.font = SANS(500, 18); ctx.fillStyle = C.mute; ctx.fillText("drawn in code", CHAT.x + 196, CHAT.y + 54);
+ ctx.fillStyle = C.line; ctx.fillRect(CHAT.x + 32, CHAT.y + 98, CHAT.w - 64, 1.5);
+ // the sent message, right aligned
+ if (s.sent) {
+ ctx.globalAlpha = s.sentAlpha ?? 1; ctx.font = SANS(500, 26);
+ const tw = ctx.measureText(s.sent).width, pad = 26, bw = tw + pad * 2, bx = CHAT.x + CHAT.w - 60 - bw, by = CHAT.y + 124;
+ let ay = by;
+ if (s.attach) { const iw = 240, ih = 150; ay = by; ctx.save(); rr(ctx, CHAT.x + CHAT.w - 60 - iw, ay, iw, ih, 16); ctx.clip(); ctx.drawImage(s.attach.img, CHAT.x + CHAT.w - 60 - iw, ay, iw, ih); ctx.restore(); ay += ih + 10; }
+ ctx.fillStyle = C.chip; rr(ctx, bx, ay, bw, 56, 22); ctx.fill();
+ ctx.fillStyle = C.ink; ctx.textBaseline = "middle"; ctx.fillText(s.sent, bx + pad, ay + 29);
+ ctx.globalAlpha = 1;
+ }
+ if (s.label) { ctx.globalAlpha = s.labelAlpha ?? 1; ctx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(REPLY.x + 9, REPLY.y - 26, 7, 0, Math.PI * 2); ctx.fill(); ctx.font = SANS(600, 20); ctx.textBaseline = "middle"; ctx.fillText(s.label, REPLY.x + 26, REPLY.y - 25); ctx.globalAlpha = 1; }
+ // the composer
+ ctx.fillStyle = C.paper; rr(ctx, INPUT.x, INPUT.y, INPUT.w, INPUT.h, INPUT.r); ctx.fill();
+ ctx.lineWidth = 2; ctx.strokeStyle = C.line; ctx.stroke();
+ ctx.font = SANS(500, TEXT.px); ctx.textBaseline = "alphabetic";
+ if (!s.typed && s.placeholder) { ctx.fillStyle = C.mute; ctx.fillText(s.placeholder, TEXT.x, TEXT.base); }
+ ctx.fillStyle = C.ink; ctx.fillText(s.typed, TEXT.x, TEXT.base);
+ if (s.caret) { const x = TEXT.x + ctx.measureText(s.typed).width + 3; ctx.fillStyle = C.accent; ctx.fillRect(x, TEXT.base - 32, 3, 40); }
+ // Generate
+ const pr = s.genPress ?? 0, hot = s.genHot ?? 0, k = 1 - 0.07 * pr, gx = GEN.x + (GEN.w * (1 - k)) / 2, gy = GEN.y + (GEN.h * (1 - k)) / 2;
+ ctx.fillStyle = hot > 0 ? mixHex(C.accent, C.accentDeep, 0.35 * hot + 0.4 * pr) : C.accent; rr(ctx, gx, gy, GEN.w * k, GEN.h * k, GEN.r * k); ctx.fill();
+ ctx.fillStyle = "#fff"; ctx.font = SANS(600, 24 * k); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText("Generate", GEN.x + GEN.w / 2, GEN.y + GEN.h / 2 + 1); ctx.textAlign = "left";
+};
+export const caretAt = (ctx: Ctx, typed: string): P => { ctx.font = SANS(500, TEXT.px); return [TEXT.x + ctx.measureText(typed).width, TEXT.base - 12]; };
+
+const hx = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
+export const mixHex = (a: string, b: string, t: number) => { const x = hx(a), y = hx(b); return `rgb(${x.map((v, i) => Math.round(lerp(v, y[i], clamp(t)))).join(",")})`; };
+
+// the art card: paper, a hairline, and whatever layer is inside, clipped to the rounded square
+export const artCard = (ctx: Ctx, x: number, y: number, s: number, L: Layer | null, r = 22) => {
+ softShadow(ctx, x, y, s, s, r, 1.4);
+ ctx.save(); rr(ctx, x, y, s, s, r); ctx.clip(); ctx.fillStyle = C.paper; ctx.fillRect(x, y, s, s);
+ if (L) ctx.drawImage(L.canvas, x, y, s, s);
+ ctx.restore();
+ ctx.lineWidth = 1.5; ctx.strokeStyle = "rgba(0,0,0,0.08)"; rr(ctx, x, y, s, s, r); ctx.stroke();
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
index 8d02f52..b3a437a 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts
@@ -10,9 +10,10 @@ export * from "./guards";
export * from "./score-text";
export * as instruments from "./instruments";
import { nocturne, pianoPhrase8 } from "./pieces/nocturne";
+import { launchLofi, launchLofi2, launchLofi3 } from "./pieces/launch";
import { musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic } from "./pieces/samplers";
import { marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm } from "./pieces/families";
import { ghostFixture } from "./pieces/fixtures";
-export { nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };
+export { launchLofi, launchLofi2, launchLofi3, nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };
/** Named pieces a film (or the tool) can ask for. ghostFixture is a test fixture, never a score. */
-export const PIECES = { nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };
+export const PIECES = { launchLofi, launchLofi2, launchLofi3, nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts
index d7dccf2..e2d2e43 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/instruments.ts
@@ -214,7 +214,7 @@ export const snare = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): O
export const hat = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
const out = { L: new Float32Array(n), R: new Float32Array(n) }, [gl, gr] = pan(num(o, "pan", 0.3));
for (const k of keys) { const i0 = Math.round(k.t * sr), dec = k.kind === "o" ? 0.2 : 0.03, len = Math.min(n - i0, Math.ceil(dec * 6 * sr)), hp = new SVF(sr, 7200, 0.7);
- for (let i = 0; i < len; i++) { const t = i / sr; hp.tick(gauss(r)); const y = hp.hp * Math.exp(-t / dec) * k.v * 0.09; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; } }
+ for (let i = 0; i < len; i++) { const t = i / sr; hp.tick(gauss(r)); let y = hp.hp * Math.exp(-t / dec) * k.v * 0.09; if (typeof o.crush === "number") { const q = Math.pow(2, (o.crush as number) - 1) * 4; y = Math.round(y * q) / q; } out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; } }
return out;
};
/** Warm bass: sine + harmonics, a pluck envelope, and a little saturation so phones hear the line (phone rule). */
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/lofiKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/lofiKit.ts
new file mode 100644
index 0000000..cb30a03
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/lofiKit.ts
@@ -0,0 +1,103 @@
+// LO-FI ELECTRONIC KIT. The voices and the bus moves chill lo-fi electronic music is made of, each
+// from the numbers producers publish for it (Unison "Making LoFi Beats 101", MODE Audio "5 LoFi
+// essentials"): a detuned saw pad low-passed near 2 kHz with a slow attack and chorus, a soft
+// pluck through a dotted-eighth ping-pong delay, a sine sub filtered near 120-150 Hz, the kick
+// ducking the pad (the pump that makes it breathe), and tape: 5-10 cents of slow wow, a little
+// flutter, and saturation. Pure functions of (keys, sr, n, opts, rng): deterministic like the rest.
+import { type Rng, TAU, clamp, pan, SVF, blep } from "./dsp";
+import type { Played } from "./perform";
+
+type Out = { L: Float32Array; R: Float32Array };
+type Opts = Record<string, number | boolean | string>;
+const num = (o: Opts, k: string, d: number) => (typeof o[k] === "number" ? (o[k] as number) : d);
+const f0 = (m: number) => 440 * Math.pow(2, (m - 69) / 12);
+
+/** Warm pad: 7 PolyBLEP saws spread +-14 cents, each drifting on its own slow LFO (the chorus),
+ * a 12 dB low-pass that opens a little with the attack, slow attack and long release. */
+export const warmPad = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {
+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, atk = num(o, "attack", 0.9), rel = num(o, "release", 1.8), cut = num(o, "cut", 1900), w = num(o, "width", 0.85);
+ for (const k of keys) {
+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + rel * 2) * sr));
+ const spread = num(o, "spread", 1), V = 7, dets = [-14, -9, -4, 0, 4.5, 9.5, 13.5].map((d) => d * spread), phs = dets.map(() => r()), pans = dets.map((_, i) => pan(((i / (V - 1)) * 2 - 1) * w));
+ const lfo = dets.map(() => ({ rate: 0.25 + r() * 0.5, ph: r() * TAU })), g = Math.pow(k.v, 1.1) * 0.075, lp = [new SVF(sr, cut, 0.55), new SVF(sr, cut, 0.55)];
+ for (let i = 0; i < len; i++) {
+ const t = i / sr, env = t < dur ? 1 - Math.exp(-t / (atk / 3)) : (1 - Math.exp(-dur / (atk / 3))) * Math.exp(-(t - dur) / (rel / 3));
+ if (env < 1e-5 && t > dur) break;
+ let sl = 0, sr_ = 0;
+ for (let v = 0; v < V; v++) {
+ const cents = dets[v] + 3 * spread * Math.sin(TAU * lfo[v].rate * t + lfo[v].ph), inc = (f * Math.pow(2, cents / 1200)) / sr;
+ let ph = phs[v] + inc; if (ph >= 1) ph -= 1; phs[v] = ph;
+ const s = 2 * ph - 1 - blep(ph, inc); sl += s * pans[v][0]; sr_ += s * pans[v][1];
+ }
+ if ((i & 63) === 0) { const c = clamp(cut * (0.7 + 0.3 * env), 200, 8000); lp[0].set(c, 0.55); lp[1].set(c, 0.55); }
+ const j = i0 + i; out.L[j] += lp[0].tick(sl) * env * g; out.R[j] += lp[1].tick(sr_) * env * g;
+ }
+ }
+ return out;
+};
+
+/** Soft pluck: triangle plus a quiet square an octave down, through a low-pass whose cutoff snaps
+ * open and falls back (the pluck), a short amp decay, then a dotted-eighth ping-pong delay. */
+export const softPluck = (keys: Played[], sr: number, n: number, o: Opts): Out => {
+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, dec = num(o, "decay", 0.55), bright = num(o, "bright", 3200), p = num(o, "pan", 0);
+ const [gl, gr] = pan(p);
+ for (const k of keys) {
+ const f = f0(k.p), i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil((dec * 6) * sr)), lp = new SVF(sr, bright, 0.9);
+ let ph = 0, ph2 = 0;
+ for (let i = 0; i < len; i++) {
+ const t = i / sr; ph += f / sr; if (ph >= 1) ph -= 1; ph2 += f / 2 / sr; if (ph2 >= 1) ph2 -= 1;
+ const tri = 1 - 4 * Math.abs(ph - 0.5), sq = ph2 < 0.5 ? 0.25 : -0.25;
+ if ((i & 15) === 0) lp.set(clamp(500 + bright * k.v * Math.exp(-t / 0.09), 200, 9000), 0.9);
+ const env = Math.min(1, t * 400) * Math.exp(-t / dec), y = lp.tick(tri + sq) * env * k.v * 0.32;
+ out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr;
+ }
+ }
+ const d = num(o, "delay", 0), fb = num(o, "feedback", 0.32), mix = num(o, "delayMix", 0.3);
+ if (d > 0) { // ping-pong: left echoes into right and back, each repeat darker
+ const D = Math.round(d * sr), bL = new Float32Array(n), bR = new Float32Array(n), toneL = new SVF(sr, 2600, 0.7), toneR = new SVF(sr, 2600, 0.7);
+ for (let i = 0; i < n; i++) {
+ const eL = i >= D ? bR[i - D] * fb + (out.L[i - D] + out.R[i - D]) * 0.5 : 0, eR = i >= D ? bL[i - D] : 0;
+ bL[i] = toneL.tick(eL); bR[i] = toneR.tick(eR);
+ }
+ for (let i = 0; i < n; i++) { out.L[i] += bL[i] * mix; out.R[i] += bR[i] * mix; }
+ }
+ return out;
+};
+
+/** Sine sub: the fundamental and a whisper of the 2nd so phones still hear it, low-passed at 150 Hz. */
+export const sub = (keys: Played[], sr: number, n: number, o: Opts): Out => {
+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, cut = num(o, "cut", 150);
+ for (const k of keys) {
+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.12) * sr)), lp = new SVF(sr, cut, 0.7);
+ for (let i = 0; i < len; i++) {
+ const t = i / sr, env = Math.min(1, t * 120) * (t < dur ? 0.8 + 0.2 * Math.exp(-t / 0.3) : Math.exp(-(t - dur) / 0.04));
+ const y = lp.tick(Math.sin(TAU * f * t) + 0.18 * Math.sin(TAU * 2 * f * t)) * env * k.v * 0.42; out.L[i0 + i] += y; out.R[i0 + i] += y;
+ }
+ }
+ return out;
+};
+
+// ---------------------------------------------------------------- bus moves
+/** The kick pump: a gain curve that dips by `depth` at every kick and recovers over `release` s. */
+export const duckCurve = (kicks: number[], sr: number, n: number, depth = 0.4, release = 0.28, attack = 0.008): Float32Array => {
+ const g = new Float32Array(n).fill(1);
+ for (const t of kicks) {
+ const i0 = Math.round(t * sr), len = Math.min(n - i0, Math.ceil(release * 5 * sr));
+ for (let i = 0; i < len; i++) { const s = i / sr, a = s < attack ? s / attack : Math.exp(-(s - attack) / (release / 2.5)); const v = 1 - depth * a; if (v < g[i0 + i]) g[i0 + i] = v; }
+ }
+ return g;
+};
+/** Tape: wow (slow pitch drift) and flutter as a modulated fractional delay, then soft saturation. */
+export const tape = (L: Float32Array, R: Float32Array, sr: number, o: { wowCents?: number; wowHz?: number; flutterCents?: number; flutterHz?: number; drive?: number } = {}) => {
+ const n = L.length, wc = o.wowCents ?? 7, wf = o.wowHz ?? 0.45, fc = o.flutterCents ?? 1.2, ff = o.flutterHz ?? 6.2, drive = o.drive ?? 1.25;
+ // a delay swinging by A seconds at f Hz shifts pitch by 2*pi*f*A: solve A from the cents wanted
+ const A1 = (Math.pow(2, wc / 1200) - 1) / (TAU * wf), A2 = (Math.pow(2, fc / 1200) - 1) / (TAU * ff), base = A1 + A2 + 0.002;
+ for (const c of [L, R]) {
+ const src = Float32Array.from(c);
+ for (let i = 0; i < n; i++) {
+ const t = i / sr, d = (base + A1 * Math.sin(TAU * wf * t) + A2 * Math.sin(TAU * ff * t)) * sr, x = i - d, j = Math.floor(x), fr = x - j;
+ const a = j >= 0 && j < n ? src[j] : 0, b = j + 1 >= 0 && j + 1 < n ? src[j + 1] : 0;
+ c[i] = Math.tanh((a + (b - a) * fr) * drive) / drive;
+ }
+ }
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
new file mode 100644
index 0000000..7168799
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
@@ -0,0 +1,114 @@
+// THE LAUNCH TRACK, v4: the v3 sound (Alex: "more upbeat, clearer, less noisy") laid out bar for
+// bar against the launch film. 90 bpm, so a bar is 80 frames at 30 fps and every section change
+// below lands on a scene change in launch.ts. Upbeat chill electronic on the lo-fi electronic kit
+// (lofiKit.ts): no electric piano, no vinyl, no bit-crush, a clean master, a tight detuned-saw pad
+// pumping under the kick, a bright pluck lead through a dotted-eighth ping-pong delay, high sparkle
+// plucks, a sine sub, a bouncy kick, a snare on 2 and 4 with rim ghosts, 16th hats. Levels were set
+// by measuring each part (anidoodle-research/launch-film/tools/stems.mjs) against published targets.
+// Harmony: the ii-V-I-vi loop Dm9 G13 Cmaj9 Am9 from bar 2, every 4 bars, so bar 36 (the film's
+// "All in pure code.") lands on Cmaj9, home, and the last bar holds it.
+//
+// BARS [film scene]: 0-1 intro pad [typing] · 2-6 groove [Generate, the koi draws] · 7-10 hook
+// [it swims] · 11-13 hook + sparkle [the circle run] · 14-18 groove + hook [bricks, it flies] ·
+// 19-22 B: half-time drums, no hook [Van Gogh] · 23-25 sparkle [the embroidery loop] · 26-29 groove
+// [the live page] · 30-33 hook + sparkle [the film] · 34-35 breakdown, drums out [the reveal] ·
+// 36 everything back [All in pure code.] · 37-38 outro, Cmaj9 held [the end card].
+import { line, type Note, type Piece, type Role } from "../plan";
+
+export const LAUNCH_BPM = 90, LAUNCH_BARS = 39;
+const L = (t: number, s: string, role: Role, v = 0.7, extra: { roll?: number } = {}) => line(t, s, { role, v, bpb: 4, ...extra });
+const DOTTED_EIGHTH = (60 / LAUNCH_BPM) * 0.75;
+const inRanges = (b: number, rs: [number, number][]) => rs.some(([a, z]) => b >= a && b <= z);
+// one part written a bar at a time: fn(bar, chord index in the loop, -1 in the intro) -> notation or null
+const byBar = (role: Role, v: number, fn: (b: number, ci: number) => string | null, extra: { roll?: number } = {}): Note[] => {
+ const out: Note[] = [];
+ for (let b = 0; b < LAUNCH_BARS; b++) { const s = fn(b, b < 2 ? -1 : (b - 2) % 4); if (s) out.push(...L(b * 4, s, role, v, extra)); }
+ return out;
+};
+
+const PAD = ["[F3 A3 C4 E4]", "[F3 B3 E4]", "[E3 G3 B3 D4]", "[E3 G3 B3 C4]"], PAD_INTRO = ["[E3 G3 B3 D4]", "[E3 G3 B3 C4]"];
+const SUB = ["D2:3 r:.5 A1:.5", "G1:3 r:.5 D2:.5", "C2:3 r:.5 G1:.5", "A1:3 r:.5 E2:.5"], SUB_HOLD = ["D2:4", "G1:4", "C2:4", "A1:4"];
+const HOOK = ["r:.5 A4:.5 C5:.5 E5:1 D5:.5 C5:1", "r:.5 B4:.5 D5:.5 E5:.5 D5:1 B4:1", "r:.5 G4:.5 B4:.5 D5:1 E5:.5 G5:1", "E5:1.5 D5:.5 C5:1 r:1"];
+const SPARK = ["r:1 E6:.5 D6:.5 C6:2", "r:1 B5:.5 D6:.5 E6:2", "r:1 G5:.5 B5:.5 D6:2", "E6:1 D6:1 C6:2"];
+const HATS = Array.from({ length: 16 }, (_, i) => `C4:.25@${[0.85, 0.35, 0.6, 0.4][i % 4]}`).join(" ");
+
+// v5: cut 2 (Alex: "very slow... it can be pretty much around a minute"). 26 bars, 69.3 s.
+// BARS [scene]: 0-1 intro pad [the logo, typing] · 2-3 groove [Generate, the koi draws] · 4-6 hook
+// [make it swim] · 7-9 hook + sparkle [the 31-style wall] · 10-12 hook [bricks, it flies] · 13-14
+// half-time [Van Gogh] · 15 sparkle [the embroidery loop] · 16-20 groove, hook from 18 [the website] ·
+// 21 sparkle [the film] · 22-23 breakdown, drums out [the five words] · 24 everything back, Cmaj9
+// [All in pure code.] · 25 held home [the end card].
+export const LAUNCH2_BARS = 26;
+export const launchLofi2 = (): Piece => {
+ const B = LAUNCH2_BARS, last = B - 1, ci = (b: number) => (b < 2 ? -1 : (b - 2) % 4);
+ const bars = (fn: (b: number, c: number) => string | null, role: Role, v: number, extra: { roll?: number } = {}): Note[] => { const out: Note[] = []; for (let b = 0; b < B; b++) { const x = fn(b, ci(b)); if (x) out.push(...L(b * 4, x, role, v, extra)); } return out; };
+ const full: [number, number][] = [[2, 12], [15, 21], [24, 24]], half: [number, number][] = [[13, 14]];
+ const pad = bars((b, c) => (b === last ? `${PAD[2]}:[email protected]` : c < 0 ? `${PAD_INTRO[b]}:[email protected]` : `${PAD[c]}:4`), "accomp", 0.62, { roll: 0.03 });
+ const sub = bars((b, c) => (c < 0 || inRanges(b, [[22, 23]]) ? null : b === last ? "C2:4" : SUB[c]), "bass", 0.85);
+ const kick = bars((b) => (inRanges(b, full) ? KICK[b % 2] : inRanges(b, half) ? "C4:2 r:2" : null), "drum", 0.85);
+ const snare = bars((b) => (inRanges(b, full) ? "r:1 C4:2 C4:1" : inRanges(b, half) ? "r:2 C4:2" : null), "drum", 0.7);
+ const ghost = bars((b) => (inRanges(b, full) ? (b % 2 ? "r:1.75 C4:[email protected] r:2" : "r:3.75 C4:[email protected]") : null), "drum", 0.5);
+ const hats = bars((b) => (inRanges(b, full) ? HATS : inRanges(b, half) ? "C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]" : null), "drum", 0.5);
+ const lead = bars((b, c) => (inRanges(b, [[4, 12], [18, 20], [24, 24]]) ? HOOK[c] : b === last ? "C5:4" : null), "melody", 0.72);
+ const sparkle = bars((b, c) => (inRanges(b, [[7, 9], [15, 15], [21, 23]]) ? SPARK[c] : null), "color", 0.5);
+ const harmony = Array.from({ length: B }, (_, b) => ({ t: b * 4, name: b < 2 ? ["Cmaj9", "Am9"][b] : b === last ? "Cmaj9" : ["Dm9", "G13", "Cmaj9", "Am9"][(b - 2) % 4] }));
+ const base = launchLofi();
+ return { ...base, title: "anidoodle launch, cut 2", harmony, plan: { ...base.plan, sections: [{ ...base.plan.sections[0], bars: B }] },
+ parts: base.parts.map((pt) => ({ ...pt, notes: ({ pad, lead, sparkle, sub, kick, snare, ghost, hat: hats } as Record<string, Note[]>)[pt.id] })) };
+};
+
+
+// v6: cut 3, the words in their own frames (Alex: "text must be a frame: white, big animated text,
+// then the show"). 29 bars, 77.3 s. The loop is re-phased so bar 26, the claim, is Cmaj9.
+// BARS [scene]: 0-1 intro [logo, typing] · 2-5 groove [Generate, the koi and its code] · 6-7 hook
+// [NO IMAGE MODEL, make it swim, ANIMATIONS, it swims] · 8-10 hook + sparkle [31 STYLES, the wall] ·
+// 11-13 hook [bricks] · 14-15 half-time [Van Gogh] · 16 sparkle [LOOPS] · 17-21 groove, hook from
+// 19 [INTERACTIVE, the site] · 22-23 sparkle [FILMS, the film] · 24-25 breakdown [the five words] ·
+// 26 everything back [All in pure code.] · 27-28 home [the end card].
+export const LAUNCH3_BARS = 29;
+export const launchLofi3 = (): Piece => {
+ const B = LAUNCH3_BARS, last = B - 1, ci = (b: number) => (b < 2 ? -1 : b % 4);
+ const bars = (fn: (b: number, c: number) => string | null, role: Role, v: number, extra: { roll?: number } = {}): Note[] => { const out: Note[] = []; for (let b = 0; b < B; b++) { const x = fn(b, ci(b)); if (x) out.push(...L(b * 4, x, role, v, extra)); } return out; };
+ const full: [number, number][] = [[2, 13], [16, 23], [26, 26]], half: [number, number][] = [[14, 15]];
+ const pad = bars((b, c) => (b >= 27 ? `${PAD[2]}:[email protected]` : c < 0 ? `${PAD_INTRO[b]}:[email protected]` : `${PAD[c]}:4`), "accomp", 0.62, { roll: 0.03 });
+ const sub = bars((b, c) => (c < 0 || inRanges(b, [[24, 25]]) ? null : b >= 27 ? "C2:4" : SUB[c]), "bass", 0.85);
+ const kick = bars((b) => (inRanges(b, full) ? KICK[b % 2] : inRanges(b, half) ? "C4:2 r:2" : null), "drum", 0.85);
+ const snare = bars((b) => (inRanges(b, full) ? "r:1 C4:2 C4:1" : inRanges(b, half) ? "r:2 C4:2" : null), "drum", 0.7);
+ const ghost = bars((b) => (inRanges(b, full) ? (b % 2 ? "r:1.75 C4:[email protected] r:2" : "r:3.75 C4:[email protected]") : null), "drum", 0.5);
+ const hats = bars((b) => (inRanges(b, full) ? HATS : inRanges(b, half) ? "C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]" : null), "drum", 0.5);
+ const lead = bars((b, c) => (inRanges(b, [[6, 13], [19, 21], [26, 26]]) ? HOOK[c] : b === last ? "C5:4" : null), "melody", 0.72);
+ const sparkle = bars((b, c) => (inRanges(b, [[8, 10], [16, 16], [22, 25]]) ? SPARK[c] : null), "color", 0.5);
+ const harmony = Array.from({ length: B }, (_, b) => ({ t: b * 4, name: b < 2 ? ["Cmaj9", "Am9"][b] : b >= 27 ? "Cmaj9" : ["Dm9", "G13", "Cmaj9", "Am9"][b % 4] }));
+ const base = launchLofi();
+ return { ...base, title: "anidoodle launch, cut 3", harmony, plan: { ...base.plan, sections: [{ ...base.plan.sections[0], bars: B }] },
+ parts: base.parts.map((pt) => ({ ...pt, notes: ({ pad, lead, sparkle, sub, kick, snare, ghost, hat: hats } as Record<string, Note[]>)[pt.id] })) };
+};
+
+export const launchLofi = (): Piece => {
+ const full: [number, number][] = [[2, 18], [23, 33], [36, 36]], half: [number, number][] = [[19, 22]], last = LAUNCH_BARS - 1;
+ const pad = byBar("accomp", 0.62, (b, ci) => (b === last ? `${PAD[2]}:[email protected]` : ci < 0 ? `${PAD_INTRO[b]}:[email protected]` : `${PAD[ci]}:4`), { roll: 0.03 });
+ const sub = byBar("bass", 0.85, (b, ci) => (ci < 0 || inRanges(b, [[34, 35]]) ? null : b === last ? "C2:4" : b >= 37 ? SUB_HOLD[ci] : SUB[ci]));
+ const kick = byBar("drum", 0.85, (b) => (inRanges(b, full) ? KICK[b % 2] : inRanges(b, half) ? "C4:2 r:2" : null));
+ const snare = byBar("drum", 0.7, (b) => (inRanges(b, full) ? "r:1 C4:2 C4:1" : inRanges(b, half) ? "r:2 C4:2" : null));
+ const ghost = byBar("drum", 0.5, (b) => (inRanges(b, full) ? (b % 2 ? "r:1.75 C4:[email protected] r:2" : "r:3.75 C4:[email protected]") : null));
+ const hats = byBar("drum", 0.5, (b) => (inRanges(b, full) ? HATS : inRanges(b, half) ? "C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]" : null));
+ const lead = byBar("melody", 0.72, (b, ci) => (inRanges(b, [[7, 18], [30, 33], [36, 36]]) ? HOOK[ci] : b === last ? "C5:4" : b === 37 ? "E5:2 D5:2" : null));
+ const sparkle = byBar("color", 0.5, (b, ci) => (inRanges(b, [[11, 13], [23, 25], [30, 35]]) ? SPARK[ci] : null));
+ const harmony = Array.from({ length: LAUNCH_BARS }, (_, b) => ({ t: b * 4, name: b < 2 ? ["Cmaj9", "Am9"][b] : b === last ? "Cmaj9" : ["Dm9", "G13", "Cmaj9", "Am9"][(b - 2) % 4] }));
+ return {
+ title: "anidoodle launch, upbeat chill electronic", seed: 2027, tail: 3.2, harmony,
+ plan: { style: "lofi", tempo: LAUNCH_BPM, meter: "4/4", swing: 0.54, ritard: 0.92, sections: [{ id: "a", bars: LAUNCH_BARS, mood: "calm", key: "C", mode: "major", melody: ["stepwise", "hook"], dyn: [0.62, 0.66], ending: "tail", repeatable: false }] },
+ parts: [
+ { id: "pad", inst: "warmPad", role: "accomp", notes: pad, gainDb: -3, opts: { cut: 2600, attack: 0.5, release: 1.4, spread: 0.55 }, send: 0.35 },
+ { id: "lead", inst: "softPluck", role: "melody", notes: lead, gainDb: 6, opts: { decay: 0.42, bright: 6000, delay: DOTTED_EIGHTH, feedback: 0.28, delayMix: 0.24 }, send: 0.25 },
+ { id: "sparkle", inst: "softPluck", role: "color", notes: sparkle, gainDb: 8, opts: { decay: 0.35, bright: 5200, pan: 0.35, delay: DOTTED_EIGHTH, feedback: 0.3, delayMix: 0.35 }, send: 0.6 },
+ { id: "sub", inst: "sub", role: "bass", notes: sub, gainDb: -6, opts: { cut: 150 } },
+ { id: "kick", inst: "kick", role: "drum", notes: kick, gainDb: 0.5, send: 0.1 },
+ { id: "snare", inst: "snare", role: "drum", notes: snare, gainDb: 8, send: 0.3 },
+ { id: "ghost", inst: "snare", role: "drum", notes: ghost, opts: { rim: true }, gainDb: 4, send: 0.2 },
+ { id: "hat", inst: "hat", role: "drum", notes: hats, opts: { pan: 0.25 }, gainDb: 20, send: 0.1 },
+ ],
+ fx: { clean: true, duck: { by: "kick", parts: ["pad", "sparkle"], depth: 0.38, release: 0.24 }, tape: { wowCents: 2.5, wowHz: 0.4, flutterCents: 0, flutterHz: 6, drive: 1.02 } },
+ };
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts
index f0f9153..a1148a6 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts
@@ -10,7 +10,7 @@ export const beatsPerBar = (m: Meter) => (m === "3/4" ? 3 : m === "4/4" ? 4 : m
export type Role = "melody" | "inner" | "bass" | "accomp" | "color" | "drum";
/** t, d in beats from the piece start; p = MIDI; v = written velocity 0..1 (performance shapes it). */
export type Note = { t: number; d: number; p: number; v: number; role: Role; roll?: number; kind?: string };
-export type InstId = "piano" | "musicBox" | "bell" | "celesta" | "marimba" | "vibes" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "pulse" | "triangle" | "noiseDrum" | "kick" | "snare" | "hat" | "bass" | "vinyl";
+export type InstId = "piano" | "musicBox" | "bell" | "celesta" | "marimba" | "vibes" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "pulse" | "triangle" | "noiseDrum" | "kick" | "snare" | "hat" | "bass" | "vinyl" | "warmPad" | "softPluck" | "sub";
export type Part = { id: string; inst: InstId; role: Role; notes: Note[]; gainDb?: number; pan?: number; opts?: Record<string, number | boolean | string>; send?: number };
export type Section = {
id: string; bars: number; mood: MoodId | [MoodId, MoodId, number]; key: string; mode: ModeId; melody: MelodyType[];
@@ -23,7 +23,9 @@ export type MusicPlan = { style: StyleId; tempo: number; meter: Meter; sections:
/** tempo-arch depth per phrase (1 = +-2.5 %); final ritard end-tempo ratio (1 = none) */ rubato?: number; ritard?: number;
/** room override (the guards' bad fixture uses it; films normally take the style's room) */ space?: { er?: number; late?: number; rt60?: number; hp?: number } };
export type Chord = { t: number; name: string };
-export type Piece = { title: string; plan: MusicPlan; parts: Part[]; harmony: Chord[]; tail: number; seed: number;
+/** Bus moves (lofiKit): `duck` pumps the named parts on every onset of the `by` part; `tape` wobbles and saturates the master. */
+export type PieceFx = { clean?: boolean /* skip the lo-fi master tone (low-pass, shelf, saturation) */; duck?: { by: string; parts: string[]; depth?: number; release?: number }; tape?: { wowCents?: number; wowHz?: number; flutterCents?: number; flutterHz?: number; drive?: number } };
+export type Piece = { title: string; plan: MusicPlan; parts: Part[]; harmony: Chord[]; tail: number; seed: number; fx?: PieceFx;
/** a shorter complete form of the same music, chosen automatically when the film is too short for this one */ shortForm?: () => Piece };
// ---------------------------------------------------------------- notation
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
index ee0cdec..20a9b6e 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts
@@ -7,6 +7,7 @@ import { perform, type Performance, type Played } from "./perform";
import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";
import * as I from "./instruments";
import { room, Biquad, db } from "./dsp";
+import { warmPad, softPluck, sub, duckCurve, tape } from "./lofiKit";
import { loudness, truePeak } from "./meter";
import { STYLES } from "./tables";
import { rng as mkRng } from "../core";
@@ -36,6 +37,9 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) =>
case "hat": return I.hat(keys, sr, n, o, r);
case "bass": return I.bass(keys, sr, n, o);
case "vinyl": return I.vinyl(keys, sr, n, o, r);
+ case "warmPad": return warmPad(keys, sr, n, o, r);
+ case "softPluck": return softPluck(keys, sr, n, o);
+ case "sub": return sub(keys, sr, n, o);
default: throw new Error(`no instrument ${pt.inst}`);
}
};
@@ -46,12 +50,16 @@ export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rende
const n = o.seconds ? Math.round(o.seconds * sr) : Math.ceil((perf.lastOnset + piece.tail) * sr);
const L = new Float32Array(n), R = new Float32Array(n), haloL = new Float32Array(n), stems: Record<string, [Float32Array, Float32Array]> = {};
const sends: [Float32Array, Float32Array, number][] = [];
+ // the pump: one gain curve from the ducking part's onsets, applied to every ducked part before the mix
+ const dk = piece.fx?.duck, byIdx = dk ? piece.parts.findIndex((p) => p.id === dk.by) : -1;
+ const pump = dk && byIdx >= 0 ? duckCurve(perf.parts[byIdx].keys.map((k) => k.t), sr, n, dk.depth ?? 0.4, dk.release ?? 0.28) : null;
piece.parts.forEach((pt, pi) => {
if (o.only && !o.only(pt)) return;
const keys = perf.parts[pi].keys; if (!keys.length) return;
let sL: Float32Array, sR: Float32Array;
if (pt.inst === "piano") { const r = renderPiano(keys, perf.pedal, sr, n, o.piano ?? PIANO_REAL, piece.seed + pi); sL = r.L; sR = r.R; if ((o.piano ?? PIANO_REAL).pedal) for (let i = 0; i < n; i++) haloL[i] += r.halo[i] * db(pt.gainDb ?? 0); }
else { const r = voice(pt, keys, sr, n, piece.seed * 101 + pi); sL = r.L; sR = r.R; }
+ if (pump && dk!.parts.includes(pt.id)) for (let i = 0; i < n; i++) { sL[i] *= pump[i]; sR[i] *= pump[i]; }
const g = db(pt.gainDb ?? 0);
if (pt.pan) { const a = Math.max(0, pt.pan), b = Math.max(0, -pt.pan); for (let i = 0; i < n; i++) { sL[i] *= 1 - a * 0.6; sR[i] *= 1 - b * 0.6; } }
for (let i = 0; i < n; i++) { sL[i] *= g; sR[i] *= g; L[i] += sL[i]; R[i] += sR[i]; }
@@ -75,7 +83,8 @@ export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rende
}
// ---- master: DC/rumble high-pass (4th-order Butterworth at 30 Hz), lo-fi tone, end fade
for (const q of [0.5412, 1.3066]) { Biquad.make(sr, "hp", 30, q).run(L); Biquad.make(sr, "hp", 30, q).run(R); }
- if (style.id === "lofi") { for (const c of [L, R]) { Biquad.make(sr, "lp", 8500, 0.6).run(c); Biquad.make(sr, "highshelf", 5000, 0.7, -3).run(c); for (let i = 0; i < n; i++) c[i] = Math.tanh(c[i] * 1.2) / 1.2; } }
+ if (style.id === "lofi" && !piece.fx?.clean) { for (const c of [L, R]) { Biquad.make(sr, "lp", 8500, 0.6).run(c); Biquad.make(sr, "highshelf", 5000, 0.7, -3).run(c); for (let i = 0; i < n; i++) c[i] = Math.tanh(c[i] * 1.2) / 1.2; } }
+ if (piece.fx?.tape) tape(L, R, sr, piece.fx.tape);
const fade = Math.min(n, Math.round(0.25 * sr)); for (let i = 0; i < fade; i++) { const g = 0.5 - 0.5 * Math.cos((Math.PI * i) / fade); L[n - 1 - i] *= g; R[n - 1 - i] *= g; }
let gainDb = 0, masterMode = o.master ?? "auto";
if (masterMode === "auto") masterMode = style.master;
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/styleWall.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/styleWall.ts
new file mode 100644
index 0000000..7775a57
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/styleWall.ts
@@ -0,0 +1 @@
+export { styleWall } from "./launchGallery";
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/typeOptions.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/typeOptions.ts
new file mode 100644
index 0000000..6ccc213
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/typeOptions.ts
@@ -0,0 +1,78 @@
+// TYPE FRAME OPTIONS, for Alex to choose from before cut 3 renders: four ways a word gets its own
+// frame between two scenes (A paper sweep, B ink bloom, C card flip, D push), each 2 s, and the same
+// word in every lettering medium (typeStyles, one still per style).
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { C, blot, expo, inOut, pathOf, ramp, selfLayer } from "./launchKit";
+import { content2 } from "./launch2";
+import { logoBug, measure, writeOn, type KStyle } from "./kinetic";
+
+const W = 1920, H = 1080, LEN = 60, IN = 10, OUT = 10;
+const BEFORE = 520, AFTER = 1600; // the swim going out, the website coming in
+const WORD = "ANIMATIONS";
+
+const sheet = (env: Env, local: number, style: KStyle, color: string, word = WORD) => {
+ const L = selfLayer(env, "sheet", Math.round(W * env.scale), Math.round(H * env.scale)), c = L.ctx;
+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = C.bg; c.fillRect(0, 0, W, H);
+ const size = Math.min(200, (1560 / measure(word, 100)) * 100);
+ writeOn(c, env, word, W / 2, H / 2 + size * 0.5, size, ramp(local, IN - 2, IN + 18), style, { color, align: "center" });
+ logoBug(c, env, 200, 1700, 1040, 0.9, { t0: -100 });
+ return L.canvas;
+};
+const pic = (ctx: Ctx, env: Env, local: number) => content2(ctx, env, local < LEN / 2 ? BEFORE : AFTER);
+type Tr = (ctx: Ctx, env: Env, local: number) => void;
+const S = (env: Env) => env.scale;
+
+// A: a sheet of paper sweeps in from the right, sweeps off to the left
+const sweep: Tr = (ctx, env, l) => {
+ pic(ctx, env, l); const u = expo(ramp(l, 0, IN)), v = expo(ramp(l, LEN - OUT, LEN)), x = v > 0 ? -W * v : W * (1 - u);
+ const Lc = sheet(env, l, "crayon", "#d8452f"); ctx.setTransform(1, 0, 0, 1, 0, 0);
+ const edge = (v > 0 ? x + W : x) * S(env), g = ctx.createLinearGradient(edge, 0, edge + (v > 0 ? 40 : -40) * S(env), 0); g.addColorStop(0, "rgba(40,25,10,0.22)"); g.addColorStop(1, "rgba(40,25,10,0)");
+ ctx.fillStyle = g; ctx.fillRect(v > 0 ? edge : edge - 40 * S(env), 0, 40 * S(env), H * S(env)); ctx.drawImage(Lc, x * S(env), 0);
+};
+// B: an ink blot blooms from the centre (the Generate drop's own ink), the page inside it
+const bloom: Tr = (ctx, env, l) => {
+ pic(ctx, env, l); const u = expo(ramp(l, 0, IN + 2)), v = expo(ramp(l, LEN - OUT, LEN)), R = 1250 * (v > 0 ? 1 - v : u), c: P = [W / 2, H / 2];
+ if (R < 2) return;
+ const Lc = sheet(env, l, "ink", C.ink);
+ ctx.setTransform(S(env), 0, 0, S(env), 0, 0); ctx.save(); pathOf(ctx, blot(c, R + 26, 88)); ctx.fillStyle = C.ink; ctx.fill(); pathOf(ctx, blot(c, Math.max(0, R - 4), 88)); ctx.clip();
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(Lc, 0, 0); ctx.restore();
+};
+// C: the picture flips over like a card; the word is on its back; it flips again to the next scene
+const flip: Tr = (ctx, env, l) => {
+ ctx.setTransform(S(env), 0, 0, S(env), 0, 0); ctx.fillStyle = "#1b1916"; ctx.fillRect(0, 0, W, H);
+ const a = l < LEN / 2 ? Math.PI * inOut(ramp(l, 0, IN + 4)) : Math.PI + Math.PI * inOut(ramp(l, LEN - OUT - 4, LEN)), k = Math.cos(a), face = Math.abs(k) < 1e-3 ? 1e-3 : Math.abs(k), back = Math.cos(a) < 0;
+ const tmp = selfLayer(env, "flipface", Math.round(W * S(env)), Math.round(H * S(env)));
+ if (back) tmp.ctx.drawImage(sheet(env, l, "thread", "#2e7d6e"), 0, 0); else pic(tmp.ctx, env, l);
+ const sc = 1 - 0.12 * Math.sin(Math.min(Math.PI, Math.abs(a % Math.PI) * 1.0 + (a > Math.PI ? 0 : 0)));
+ ctx.setTransform(S(env) * face * sc, 0, 0, S(env) * sc, (W / 2) * S(env) * (1 - face * sc), (H / 2) * S(env) * (1 - sc));
+ ctx.drawImage(tmp.canvas, 0, 0, W, H);
+ ctx.setTransform(S(env), 0, 0, S(env), 0, 0); ctx.fillStyle = `rgba(0,0,0,${0.35 * (1 - face)})`; ctx.fillRect(W / 2 - (W / 2) * face * sc, H / 2 - (H / 2) * sc, W * face * sc, H * sc);
+};
+// D: a paper panel pushes the picture up out of frame, then pushes on to reveal the next
+const push: Tr = (ctx, env, l) => {
+ const u = expo(ramp(l, 0, IN)), v = expo(ramp(l, LEN - OUT, LEN)), Lc = sheet(env, l, "marker", "#2f6fd6");
+ const tmp = selfLayer(env, "pushpic", Math.round(W * S(env)), Math.round(H * S(env))); pic(tmp.ctx, env, l);
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = "#000"; ctx.fillRect(0, 0, W * S(env), H * S(env));
+ if (v === 0) { ctx.drawImage(tmp.canvas, 0, -H * u * S(env)); ctx.drawImage(Lc, 0, H * (1 - u) * S(env)); }
+ else { ctx.drawImage(Lc, 0, -H * v * S(env)); ctx.drawImage(tmp.canvas, 0, H * (1 - v) * S(env)); }
+};
+
+const TR: [string, Tr][] = [["sweep", sweep], ["bloom", bloom], ["flip", flip], ["push", push]];
+export const typeOptions: Film = {
+ meta: { title: "type frame options", W, H, fps: 30, bpm: 90, durationFrames: LEN * TR.length, raster: "cpu" },
+ assets: { images: { almond: "assets/refs/vangogh-almond-blossom.jpg" } }, // public domain; provenance in engine/assets/refs/PROVENANCE.json
+ shots: TR.map(([id, fn], i) => ({ id, start: i * LEN, end: (i + 1) * LEN, draw: (ctx: Ctx, l: number, env: Env) => fn(ctx, env, l) })),
+};
+
+// the same word, finished, in every medium: one shot per style (20 frames each, stills are taken from them)
+const STYLES: [KStyle, string][] = [["ink", C.ink], ["crayon", "#d8452f"], ["thread", "#2e7d6e"], ["marker", "#2f6fd6"], ["brick", ""], ["chalk", "#f4f1e6"]];
+export const typeStyles: Film = {
+ meta: { title: "type styles", W, H, fps: 30, bpm: 90, durationFrames: 20 * STYLES.length },
+ assets: { images: {} },
+ shots: STYLES.map(([st, col], i) => ({ id: st, start: i * 20, end: (i + 1) * 20, draw: (ctx: Ctx, _l: number, env: Env) => {
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = st === "chalk" ? "#2d3a33" : C.bg; ctx.fillRect(0, 0, W, H);
+ const size = Math.min(200, (1560 / measure(WORD, 100)) * 100);
+ writeOn(ctx, env, WORD, W / 2, H / 2 + size * 0.5, size, 1, st, { color: col || undefined, align: "center" });
+ } })),
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/typeStyles.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/typeStyles.ts
new file mode 100644
index 0000000..b007c95
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/typeStyles.ts
@@ -0,0 +1 @@
+export { typeStyles } from "./typeOptions";
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/webTour.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/webTour.ts
new file mode 100644
index 0000000..1e091c0
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/webTour.ts
@@ -0,0 +1,174 @@
+// WEB TOUR. A 12 s walk through a real-feeling website built with anidoodle's interactive pieces,
+// driven by a visible cursor, for the launch film. Three sections on one long page:
+// 1 a scroll hero: the storybook plate draws itself as the page scrolls (it is pinned, sticky,
+// while it draws), the scrollHero piece fed the page's own scroll progress;
+// 2 Bit's hero: he watches the cursor, points at "Get started" on hover, cheers on the click;
+// 3 a sign-up form: Bit reads along as each field is typed, covers his eyes for the password,
+// thinks, and cheers when the form goes through.
+// The pieces are the REAL pieces (mascotHero, formMascot, scrollHero), each driven through a
+// synthetic input log in its own coordinates, exactly what a browser host would log (the form logs
+// only lengths and caret positions, never text). The camera punches in on every click and every
+// field so the viewer always sees what was done. Everything is a pure function of the frame.
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { C, SANS, camLerp, clamp, inOut, lerp, lerpP, out3, pointer, rr, selfLayer, softShadow, useCam, type Cam } from "./launchKit";
+import { stateAt, type InputLog, type Piece } from "./input";
+import { scrollHero } from "./scrollHero";
+import { mascotHero } from "./mascotHero";
+import { formMascot } from "./formMascot";
+
+const W = 1920, H = 1080, N = 360, TICK = 2; // input ticks are 60 Hz: two per frame
+
+// ---------------------------------------------------------------- the page
+const VP = { x: 120, y: 104, w: 1680, h: 936 }; // the browser's viewport on screen
+const NAV = 76; // the sticky nav bar's height
+const S2 = 1500, S3 = 2500; // section tops, page px
+const HERO_STICK = 900; // the hero stays pinned while the page scrolls this far
+const PIECE = 640;
+const heroTop = (scroll: number) => 150 + Math.min(scroll, HERO_STICK); // page y of the pinned hero
+const BIT = { x: 930, y: S2 + 120, s: 640 }, START = { x: 120, y: S2 + 470, w: 270, h: 78 };
+const FORM = { x: 930, y: S3 + 120, s: 640 };
+const FIELD = (i: number) => ({ x: 120, y: S3 + 270 + i * 112, w: 580, h: 74 });
+const SUBMIT = { x: 120, y: S3 + 270 + 3 * 112 + 12, w: 580, h: 80 };
+const TYPED = ["Sam Rivera", "[email protected]", "*********"];
+
+// ---------------------------------------------------------------- keyframes
+type Key<T> = [number, T];
+const track = <T>(keys: Key<T>[], mix: (a: T, b: T, u: number) => T) => (f: number): T => {
+ if (f <= keys[0][0]) return keys[0][1];
+ for (let i = 1; i < keys.length; i++) if (f <= keys[i][0]) { const [f0, a] = keys[i - 1], [f1, b] = keys[i]; return mix(a, b, inOut((f - f0) / (f1 - f0))); }
+ return keys[keys.length - 1][1];
+};
+// the page's scroll: a wheel's flicks, eased by the browser
+const scrollAt = track<number>([[0, 60], [92, HERO_STICK + 40], [104, HERO_STICK + 40], [124, S2], [196, S2], [214, S3], [N, S3]], (a, b, u) => lerp(a, b, u));
+const click = { start: 170, name: 222, email: 256, password: 290, submit: 320 };
+const screenOf = (px: number, py: number, scroll: number): P => [VP.x + px, VP.y + py - scroll];
+const centerOf = (r: { x: number; y: number; w: number; h: number }, page: number): P => [VP.x + r.x + r.w / 2, VP.y + r.y + r.h / 2 - page];
+// the cursor, on screen: it rests while the wheel turns, then travels to each target
+const cursorAt = track<P>([
+ [0, [1560, 720]], [100, [1520, 780]], [128, [1640, 860]], [150, [1300, 470]], [166, centerOf(START, S2)], [180, centerOf(START, S2)],
+ [200, [860, 820]], [218, centerOf(FIELD(0), S3)], [248, centerOf(FIELD(0), S3)], [254, centerOf(FIELD(1), S3)], [284, centerOf(FIELD(1), S3)],
+ [288, centerOf(FIELD(2), S3)], [314, centerOf(FIELD(2), S3)], [319, centerOf(SUBMIT, S3)], [340, centerOf(SUBMIT, S3)], [N, [900, 900]],
+], (a, b, u) => lerpP(a, b, u));
+// the camera: close on the drawing hero, wide for the scroll, punching in on every click and field
+const HOMEC: P = [W / 2, H / 2];
+const camKeys: Key<Cam>[] = [
+ [0, { c: [1060, 590], z: 1.1 }], [92, { c: [1200, 560], z: 1.16 }], [118, { c: HOMEC, z: 1.0 }], [150, { c: [1080, 560], z: 1.12 }],
+ [168, { c: [560, 620], z: 1.85 }], [186, { c: [980, 560], z: 1.18 }], [206, { c: HOMEC, z: 1.0 }], [222, { c: [560, 420], z: 1.75 }],
+ [250, { c: [580, 470], z: 1.6 }], [286, { c: [640, 560], z: 1.45 }], [298, { c: [1330, 480], z: 1.85 }], [314, { c: [1150, 520], z: 1.3 }],
+ [322, { c: [620, 720], z: 1.7 }], [334, { c: [1150, 540], z: 1.2 }], [352, { c: HOMEC, z: 0.94 }], [N, { c: HOMEC, z: 0.94 }],
+];
+const camTrack = track<Cam>(camKeys, (a, b, u) => camLerp(a, b, u));
+// never still: a breath of drift on top of the moves
+const camAt = (f: number): Cam => { const c = camTrack(f), d = Math.sin(f / 23) * 4; return { c: [c.c[0] + d, c.c[1] + Math.cos(f / 29) * 3], z: c.z * (1 + 0.006 * Math.sin(f / 17)) }; };
+const charsAt = (f: number, i: number) => { const t0 = [click.name, click.email, click.password][i] + 5, t1 = [250, 284, 312][i]; return Math.max(0, Math.min(TYPED[i].length, Math.floor(((f - t0) / (t1 - t0)) * TYPED[i].length))); };
+
+// ---------------------------------------------------------------- input logs, in each piece's own coordinates
+type Box = { x: number; y: number; s: number };
+const toPiece = (b: Box, screen: P, scroll: number): P => { const px = screen[0] - VP.x, py = screen[1] - VP.y + scroll; return [((px - b.x) * 560) / b.s, ((py - b.y) * 560) / b.s]; };
+const rectIn = (b: Box, r: { x: number; y: number; w: number; h: number }) => ({ x: ((r.x - b.x) * 560) / b.s, y: ((r.y - b.y) * 560) / b.s, w: (r.w * 560) / b.s, h: (r.h * 560) / b.s });
+const moves = (b: Box): InputLog => Array.from({ length: N }, (_, f) => { const [x, y] = toPiece(b, cursorAt(f), scrollAt(f)); return { tick: f * TICK, type: "move" as const, x, y, value: "mouse" }; });
+let LOGS: { hero: InputLog; bit: InputLog; form: InputLog } | null = null;
+const logs = () => {
+ if (LOGS) return LOGS;
+ const hero: InputLog = Array.from({ length: N }, (_, f) => ({ tick: f * TICK, type: "scroll" as const, value: clamp(scrollAt(f) / HERO_STICK) }));
+ const bit: InputLog = [{ tick: 0, type: "rect", target: "start", ...rectIn(BIT, START) }, ...moves(BIT),
+ { tick: 160 * TICK, type: "enter", target: "start" }, { tick: click.start * TICK, type: "down", target: "start" }, { tick: (click.start + 4) * TICK, type: "up", target: "start" }, { tick: 196 * TICK, type: "exit", target: "start" }];
+ const ids = ["name", "email", "password"], form: InputLog = [...ids.map((id, i) => ({ tick: 0, type: "rect" as const, target: id, ...rectIn(FORM, FIELD(i)) })), { tick: 0, type: "rect", target: "submit", ...rectIn(FORM, SUBMIT) }, ...moves(FORM)];
+ ids.forEach((id, i) => {
+ const at = [click.name, click.email, click.password][i];
+ form.push({ tick: at * TICK, type: "focus", target: id });
+ let last = 0;
+ for (let f = at; f <= at + 34; f++) { const n = charsAt(f, i); if (n !== last) { last = n; const r = FIELD(i), [x, y] = toPiece(FORM, [VP.x + r.x + 22 + n * 17, VP.y + r.y + r.h / 2 - S3], S3); form.push({ tick: f * TICK, type: "key", target: id, value: n, x, y }); } }
+ });
+ form.push({ tick: click.submit * TICK, type: "focus", target: "submit" }, { tick: click.submit * TICK, type: "down", target: "submit" }, { tick: (click.submit + 4) * TICK, type: "up", target: "submit" },
+ { tick: (click.submit + 5) * TICK, type: "state", value: "busy" }, { tick: (click.submit + 14) * TICK, type: "state", value: "success" });
+ const bytick = (a: { tick: number }, b: { tick: number }) => a.tick - b.tick;
+ return (LOGS = { hero: hero.sort(bytick), bit: bit.sort(bytick), form: form.sort(bytick) });
+};
+
+// ---------------------------------------------------------------- drawing a piece into the page
+const subEnv = (env: Env, key: string, px: number): Env => { const k = `tour:${key}:${px}`; let e = env.cache.get(k) as Env | undefined; if (!e) { e = { W: 560, H: 560, scale: px / 560, cache: new Map(), canvas: env.canvas, image: env.image }; env.cache.set(k, e); } return e; };
+const drawPiece = (ctx: Ctx, env: Env, key: string, piece: Piece, log: InputLog, f: number, x: number, y: number, s: number) => {
+ if (y > VP.y + VP.h || y + s < VP.y) return; // off the viewport
+ const px = Math.round(s * 2), L = selfLayer(env, `tour:${key}`, px, px), e = subEnv(env, key, px), t = f * TICK;
+ piece.draw(L.ctx, t, e, stateAt(t, log, piece.input));
+ softShadow(ctx, x, y, s, s, 26, 1.1);
+ ctx.save(); rr(ctx, x, y, s, s, 26); ctx.clip(); ctx.drawImage(L.canvas, x, y, s, s); ctx.restore();
+};
+
+// ---------------------------------------------------------------- the frame
+const text = (ctx: Ctx, s: string, x: number, y: number, w: number, px: number, col: string) => { ctx.font = SANS(w, px); ctx.fillStyle = col; ctx.textBaseline = "alphabetic"; ctx.fillText(s, x, y); };
+const bodyLines = (ctx: Ctx, x: number, y: number, widths: number[]) => widths.forEach((w, i) => { ctx.fillStyle = C.line; rr(ctx, x, y + i * 30, w, 12, 6); ctx.fill(); });
+const button = (ctx: Ctx, r: { x: number; y: number; w: number; h: number }, label: string, hot: number, down: number) => {
+ const k = 1 - 0.05 * down, cx = r.x + r.w / 2, cy = r.y + r.h / 2, w = r.w * k, h = r.h * k;
+ ctx.fillStyle = hot > 0 ? C.accentDeep : C.accent; rr(ctx, cx - w / 2, cy - h / 2, w, h, h / 2); ctx.fill();
+ ctx.fillStyle = "#fff"; ctx.font = SANS(600, 28 * k); ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(label, cx, cy + 1); ctx.textAlign = "left";
+};
+const pressAt = (f: number, at: number) => (f < at ? 0 : f < at + 4 ? out3((f - at) / 4) : Math.max(0, 1 - (f - at - 4) / 6));
+const ripple = (ctx: Ctx, p: P, f: number, at: number) => { const u = (f - at) / 16; if (u < 0 || u > 1) return; ctx.strokeStyle = C.accent; ctx.globalAlpha = 1 - u; ctx.lineWidth = 5 * (1 - u) + 1; ctx.beginPath(); ctx.arc(p[0], p[1], 14 + 70 * out3(u), 0, Math.PI * 2); ctx.stroke(); ctx.globalAlpha = 1; };
+
+const drawTour = (ctx: Ctx, env: Env, f: number) => {
+ useCam(ctx, env, camAt(f));
+ ctx.fillStyle = C.bg; ctx.fillRect(-1000, -1000, W + 2000, H + 2000);
+ const sc = scrollAt(f), L = logs();
+ // the browser
+ softShadow(ctx, VP.x, VP.y - 64, VP.w, VP.h + 64, 26, 1.5);
+ ctx.fillStyle = "#fff"; rr(ctx, VP.x, VP.y - 64, VP.w, VP.h + 64, 26); ctx.fill();
+ ctx.save(); rr(ctx, VP.x, VP.y - 64, VP.w, VP.h + 64, 26); ctx.clip();
+ ctx.fillStyle = "#f4f1ea"; ctx.fillRect(VP.x, VP.y - 64, VP.w, 64);
+ ["#e8715a", "#e9b949", "#7cbf6b"].forEach((c, i) => { ctx.fillStyle = c; ctx.beginPath(); ctx.arc(VP.x + 34 + i * 26, VP.y - 32, 8, 0, Math.PI * 2); ctx.fill(); });
+ ctx.fillStyle = "#fff"; rr(ctx, VP.x + 150, VP.y - 50, 560, 36, 18); ctx.fill(); text(ctx, "your-site.com", VP.x + 176, VP.y - 24, 500, 19, C.soft);
+ // the page, scrolled
+ ctx.save(); ctx.beginPath(); ctx.rect(VP.x, VP.y, VP.w, VP.h); ctx.clip();
+ ctx.fillStyle = C.card; ctx.fillRect(VP.x, VP.y, VP.w, VP.h);
+ const X = VP.x, Y = (py: number) => VP.y + py - sc;
+ // 1: the scroll hero
+ text(ctx, "Stories that draw", X + 120, Y(360), 800, 78, C.ink); text(ctx, "themselves.", X + 120, Y(448), 800, 78, C.accent);
+ bodyLines(ctx, X + 120, Y(500), [520, 560, 430]);
+ text(ctx, "Scroll, and watch the page being made.", X + 120, Y(640), 500, 26, C.soft);
+ const ht = heroTop(sc);
+ drawPiece(ctx, env, "hero", scrollHero, L.hero, f, X + 930, Y(ht), PIECE);
+ text(ctx, "pencil · paint · line", X + 930, Y(ht + PIECE + 44), 500, 20, C.mute);
+ // 2: Bit's hero
+ ctx.fillStyle = "#f7f2e8"; ctx.fillRect(X, Y(S2 - 40), VP.w, 1000);
+ text(ctx, "A mascot that", X + 120, Y(S2 + 250), 800, 66, C.ink); text(ctx, "watches your visitors.", X + 120, Y(S2 + 326), 800, 66, C.accent);
+ text(ctx, "Drawn in code. It follows the cursor,", X + 120, Y(S2 + 390), 500, 28, C.soft); text(ctx, "points at buttons, and cheers on a click.", X + 120, Y(S2 + 428), 500, 28, C.soft);
+ button(ctx, { x: X + START.x, y: Y(START.y), w: START.w, h: START.h }, "Click me", f >= 160 && f < 196 ? 1 : 0, pressAt(f, click.start));
+ drawPiece(ctx, env, "bit", mascotHero, L.bit, f, X + BIT.x, Y(BIT.y), BIT.s);
+ // 3: the form
+ ctx.fillStyle = C.card; ctx.fillRect(X, Y(S3 - 40), VP.w, 1200);
+ text(ctx, "It reads along as you type", X + 120, Y(S3 + 150), 800, 56, C.ink); text(ctx, "…and looks away for your password.", X + 120, Y(S3 + 205), 500, 30, C.soft);
+ ["Name", "Email", "Password"].forEach((lab, i) => {
+ const r = FIELD(i), at = [click.name, click.email, click.password][i], focused = f >= at && f < ([click.email, click.password, click.submit][i]), n = charsAt(f, i);
+ text(ctx, lab, X + r.x, Y(r.y - 10), 600, 20, C.soft);
+ ctx.fillStyle = C.paper; rr(ctx, X + r.x, Y(r.y), r.w, r.h, 16); ctx.fill(); ctx.lineWidth = focused ? 3 : 2; ctx.strokeStyle = focused ? C.accent : C.line; ctx.stroke();
+ const shown = i === 2 ? "•".repeat(n) : TYPED[i].slice(0, n); text(ctx, shown, X + r.x + 22, Y(r.y + r.h / 2 + 11), 500, 30, C.ink);
+ if (focused && Math.floor(f / 6) % 2 === 0) { ctx.font = SANS(500, 30); ctx.fillStyle = C.accent; ctx.fillRect(X + r.x + 24 + ctx.measureText(shown).width, Y(r.y + 18), 3, 38); }
+ });
+ const done = f >= click.submit + 14;
+ button(ctx, { x: X + SUBMIT.x, y: Y(SUBMIT.y), w: SUBMIT.w, h: SUBMIT.h }, done ? "You're in!" : f >= click.submit + 5 ? "Signing up…" : "Sign up", f >= 316 ? 1 : 0, pressAt(f, click.submit));
+ drawPiece(ctx, env, "form", formMascot, L.form, f, X + FORM.x, Y(FORM.y), FORM.s);
+ // the sticky nav, over the page
+ ctx.fillStyle = "rgba(255,253,248,0.94)"; ctx.fillRect(VP.x, VP.y, VP.w, NAV); ctx.fillStyle = C.line; ctx.fillRect(VP.x, VP.y + NAV - 1.5, VP.w, 1.5);
+ ctx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(X + 60, VP.y + NAV / 2, 10, 0, Math.PI * 2); ctx.fill(); text(ctx, "your site", X + 82, VP.y + NAV / 2 + 9, 700, 26, C.ink);
+ ["Home", "Mascot", "Form"].forEach((s, i) => text(ctx, s, X + VP.w - 420 + i * 130, VP.y + NAV / 2 + 8, 500, 22, i === Math.min(2, Math.floor(sc / 1000)) ? C.ink : C.soft));
+ // the scroll bar
+ const trackH = VP.h - NAV - 20, thumb = trackH * (VP.h / 3500), ty = VP.y + NAV + 10 + (trackH - thumb) * clamp(sc / (3500 - VP.h));
+ ctx.fillStyle = "rgba(0,0,0,0.18)"; rr(ctx, VP.x + VP.w - 14, ty, 7, thumb, 4); ctx.fill();
+ ctx.restore(); ctx.restore();
+ // the cursor and the click it makes
+ const cur = cursorAt(f);
+ [click.start, click.name, click.email, click.password, click.submit].forEach((a) => ripple(ctx, cur, f, a));
+ const down = [click.start, click.name, click.email, click.password, click.submit].some((a) => f >= a && f < a + 4) ? 1 : 0;
+ pointer(ctx, cur, down, 1.5);
+ // the wheel: while the page scrolls under a still cursor, a small scroll glyph shows the hand is on the wheel
+ const v = Math.abs(scrollAt(f + 1) - scrollAt(f - 1));
+ if (v > 4) { ctx.globalAlpha = clamp(v / 40); ctx.strokeStyle = C.ink; ctx.lineWidth = 3; rr(ctx, cur[0] + 30, cur[1] + 24, 22, 34, 11); ctx.stroke(); ctx.fillStyle = C.ink; rr(ctx, cur[0] + 39, cur[1] + 30 + ((f * 3) % 12), 4, 8, 2); ctx.fill(); ctx.globalAlpha = 1; }
+};
+
+export const webTour: Film = {
+ meta: { title: "Web tour · a page built with anidoodle's interactive pieces", W, H, fps: 30, bpm: 90, durationFrames: N, kind: "interactive" },
+ assets: { images: {} },
+ shots: [{ id: "tour", start: 0, end: N, draw: (ctx, f, env) => drawTour(ctx, env, f) }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAlmond.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAlmond.ts
new file mode 100644
index 0000000..d4c3719
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAlmond.ts
@@ -0,0 +1,4 @@
+import { adaptAlmond } from "../canvas-core/adaptAlmond";
+import { mountFilm } from "./page";
+
+mountFilm(adaptAlmond);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brickBalloon.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brickBalloon.ts
new file mode 100644
index 0000000..695fb2b
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brickBalloon.ts
@@ -0,0 +1,4 @@
+import { brickBalloon } from "../canvas-core/brickBalloon";
+import { mountFilm } from "./page";
+
+mountFilm(brickBalloon);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroideryAlive.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroideryAlive.ts
new file mode 100644
index 0000000..cf6de0a
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroideryAlive.ts
@@ -0,0 +1,4 @@
+import { embroideryAlive } from "../canvas-core/embroideryAlive";
+import { mountFilm } from "./page";
+
+mountFilm(embroideryAlive);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-kineticDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-kineticDemo.ts
new file mode 100644
index 0000000..a63e3a0
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-kineticDemo.ts
@@ -0,0 +1,4 @@
+import { kineticDemo } from "../canvas-core/kineticDemo";
+import { mountFilm } from "./page";
+
+mountFilm(kineticDemo);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiAlive.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiAlive.ts
new file mode 100644
index 0000000..3a707ef
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiAlive.ts
@@ -0,0 +1,4 @@
+import { koiAlive } from "../canvas-core/koiAlive";
+import { mountFilm } from "./page";
+
+mountFilm(koiAlive);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiWorld.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiWorld.ts
new file mode 100644
index 0000000..f1bd8ee
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiWorld.ts
@@ -0,0 +1,4 @@
+import { koiWorld } from "../canvas-core/koiWorld";
+import { mountFilm } from "./page";
+
+mountFilm(koiWorld);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch.ts
new file mode 100644
index 0000000..396a2ea
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch.ts
@@ -0,0 +1,4 @@
+import { launch } from "../canvas-core/launch";
+import { mountFilm } from "./page";
+
+mountFilm(launch);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch2.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch2.ts
new file mode 100644
index 0000000..1185b47
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch2.ts
@@ -0,0 +1,4 @@
+import { launch2 } from "../canvas-core/launch2";
+import { mountFilm } from "./page";
+
+mountFilm(launch2);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch3.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch3.ts
new file mode 100644
index 0000000..d85f8e0
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launch3.ts
@@ -0,0 +1,4 @@
+import { launch3 } from "../canvas-core/launch3";
+import { mountFilm } from "./page";
+
+mountFilm(launch3);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchClip.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchClip.ts
new file mode 100644
index 0000000..976f94c
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchClip.ts
@@ -0,0 +1,4 @@
+import { launchClip } from "../canvas-core/launch";
+import { mountFilm } from "./page";
+
+mountFilm(launchClip);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleWall.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleWall.ts
new file mode 100644
index 0000000..9beba4b
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleWall.ts
@@ -0,0 +1,4 @@
+import { styleWall } from "../canvas-core/styleWall";
+import { mountFilm } from "./page";
+
+mountFilm(styleWall);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-typeOptions.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-typeOptions.ts
new file mode 100644
index 0000000..c791c5f
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-typeOptions.ts
@@ -0,0 +1,4 @@
+import { typeOptions } from "../canvas-core/typeOptions";
+import { mountFilm } from "./page";
+
+mountFilm(typeOptions);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-typeStyles.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-typeStyles.ts
new file mode 100644
index 0000000..fcdbe3e
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-typeStyles.ts
@@ -0,0 +1,4 @@
+import { typeStyles } from "../canvas-core/typeStyles";
+import { mountFilm } from "./page";
+
+mountFilm(typeStyles);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-webTour.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-webTour.ts
new file mode 100644
index 0000000..f834909
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-webTour.ts
@@ -0,0 +1,4 @@
+import { webTour } from "../canvas-core/webTour";
+import { mountFilm } from "./page";
+
+mountFilm(webTour);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts
index 9eaf499..628409e 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts
@@ -4,7 +4,32 @@
import type { Ctx, Env, Layer } from "../canvas-core/core";
import { Film, renderFrame, validate } from "../canvas-core/film";
-declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string> } }
+declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string>; __BAKE_SRC__?: Record<string, string>; __ANIDOODLE_SRC__?: WeakMap<object, string> } }
+
+// THE BAKE STORE (Env.bake). A finished plate frame, keyed by the hash of the source that draws it
+// (build-page.mjs hashes each film module's whole import closure, plus the engine's own renderer),
+// the frame and the pixel size. The adapter loads matching PNGs from disk before frame 0 and saves
+// the fresh ones after; the page never touches a file. Only fully opaque frames are kept, because
+// only those survive a PNG round trip bit for bit.
+const bakeStore = (surface: (w: number, h: number) => Layer) => {
+ const loaded = new Map<string, ImageBitmap>(), fresh = new Map<string, Layer>(), stats = { hits: 0, misses: 0, kept: 0, skipped: 0 };
+ let on = false; // off until an adapter loads the store: a shipped player keeps no copies
+ const keyOf = (film: object, frame: number, w: number, h: number) => { const mod = window.__ANIDOODLE_SRC__?.get(film), hash = mod ? window.__BAKE_SRC__?.[mod] : undefined; return hash ? `${hash}.${frame}.${w}x${h}` : null; };
+ const bake: NonNullable<Env["bake"]> = {
+ get: (film, frame, w, h) => { if (!on) return undefined; const k = keyOf(film, frame, w, h), img = k ? loaded.get(k) : undefined; if (img) stats.hits++; else stats.misses++; return img; },
+ put: (film, frame, layer) => {
+ if (!on) return;
+ const { width: w, height: h } = layer.canvas, k = keyOf(film, frame, w, h); if (!k || loaded.has(k) || fresh.has(k)) return;
+ const d = layer.ctx.getImageData(0, 0, w, h).data; for (let i = 3; i < d.length; i += 4) if (d[i] !== 255) { stats.skipped++; return; }
+ const c = surface(w, h); c.ctx.drawImage(layer.canvas, 0, 0); fresh.set(k, c); stats.kept++; // same surface kind as the art: never mix raster paths
+ },
+ };
+ const load = async (entries: Record<string, string>) => { on = true; await Promise.all(Object.entries(entries).map(async ([k, b64]) => { try { const bin = atob(b64), u8 = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i); const img = await createImageBitmap(new Blob([u8], { type: "image/png" }), { premultiplyAlpha: "none", colorSpaceConversion: "none" }); if (`${img.width}x${img.height}` === k.split(".").pop()) loaded.set(k, img); } catch { /* unreadable: draw it cold */ } })); return loaded.size; }; // decoded in memory: no URL, no request
+ const png64 = async (c: Layer["canvas"]) => { const blob = "convertToBlob" in c ? await (c as OffscreenCanvas).convertToBlob({ type: "image/png" }) : await new Promise<Blob>((ok) => (c as HTMLCanvasElement).toBlob((b) => ok(b!), "image/png")); const u8 = new Uint8Array(await blob.arrayBuffer()); let s = ""; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode(...u8.subarray(i, i + 0x8000)); return btoa(s); };
+ const take = async () => { const out: Record<string, string> = {}; for (const [k, c] of fresh) out[k] = await png64(c.canvas); fresh.clear(); return out; };
+ const hashes = () => [...new Set(Object.values(window.__BAKE_SRC__ ?? {}))];
+ return { bake, load, take, hashes, stats };
+};
export const mountFilm = (film: Film) => {
const canvas = document.getElementById("film") as HTMLCanvasElement, images = new Map<string, CanvasImageSource>();
@@ -12,7 +37,8 @@ export const mountFilm = (film: Film) => {
// Safari before 16.4 has no 2D OffscreenCanvas: fall back to a detached <canvas>. The core cannot tell the difference.
const opts = film.meta.raster === "cpu" ? { willReadFrequently: true } : undefined; // see Film.meta.raster
const surface = (w: number, h: number): Layer => { const c = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(w, h) : Object.assign(document.createElement("canvas"), { width: w, height: h }); return { canvas: c, ctx: c.getContext("2d", opts) as unknown as Ctx } as Layer; };
- const mount = (scale = 1) => { canvas.width = Math.round(film.meta.W * scale); canvas.height = Math.round(film.meta.H * scale); ctx = canvas.getContext("2d", opts) as CanvasRenderingContext2D; env = { W: film.meta.W, H: film.meta.H, scale, cache: new Map(), canvas: surface, image: (n) => images.get(n) }; return film.meta; };
+ const bakes = bakeStore(surface);
+ const mount = (scale = 1) => { canvas.width = Math.round(film.meta.W * scale); canvas.height = Math.round(film.meta.H * scale); ctx = canvas.getContext("2d", opts) as CanvasRenderingContext2D; env = { W: film.meta.W, H: film.meta.H, scale, cache: new Map(), canvas: surface, image: (n) => images.get(n), bake: bakes.bake }; return film.meta; };
// contract rule 4: every asset is loaded AND decoded before frame 0, or the film refuses to start
const ready = (async () => {
const problems = validate(film); if (problems.length) throw new Error("timeline: " + problems.join("; "));
@@ -25,28 +51,55 @@ export const mountFilm = (film: Film) => {
// 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.
+ // It is also ALPHA-WEIGHTED (premultiplied): a transparent subframe carries no colour, so a
+ // sticker's moving edge fades out instead of picking up a dark fringe from the zero RGB that
+ // canvas keeps under alpha 0. Opaque pixels take exactly the unweighted path.
+ // STEPPED ART (meta.step > 1, or onTwos) holds each drawing for `step` frames, so the shutter
+ // would straddle two drawings and smear a pose into its neighbour: such films are not blurred.
// 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 };
+ if (!shot || samples < 2 || (film.meta.step ?? (film.meta.onTwos ? 2 : 1)) > 1) { const r = seek(n); return { shot: r.shot, ms: r.ms }; }
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]; }
+ for (let p = 0; p < d.length; p += 4) { const a = d[p + 3], k = a / 255; acc[p] += toLin[d[p]] * k; acc[p + 1] += toLin[d[p + 1]] * k; acc[p + 2] += toLin[d[p + 2]] * k; acc[p + 3] += a; }
+ }
+ const img = ctx.createImageData(w, h), o = img.data, inv = 1 / samples, full = 255 * samples;
+ for (let p = 0; p < o.length; p += 4) {
+ const A = acc[p + 3]; if (A === 0) continue; // nothing was ever drawn here: stays transparent black
+ const c = A === full ? inv : 255 / A; // premultiplied average, un-premultiplied by the mean alpha
+ o[p] = fromLin(acc[p] * c); o[p + 1] = fromLin(acc[p + 1] * c); o[p + 2] = fromLin(acc[p + 2] * c); o[p + 3] = Math.round(A * inv);
}
- 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, blur, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
+ // POSTER. Platforms show frame 0 as the thumbnail, so a delivery may open on a chosen frame (the
+ // wall of styles, the logo) and dissolve into the film's real opening over `fade` frames. The
+ // poster frame is drawn once into its own surface; frame n < fade is the real frame n with the
+ // poster laid over it at 1 - n/fade. Frame 0 IS the poster. Nothing else changes, not the score.
+ let posterOf: { key: string; img: CanvasImageSource } | null = null;
+ const poster = (frame: number, posterFrame: number, fade: number, samples = 1) => {
+ const n = Math.round(frame), u = fade > 0 ? 1 - n / fade : n === 0 ? 1 : 0, key = `${posterFrame}/${samples}/${canvas.width}x${canvas.height}`;
+ if (u > 0 && posterOf?.key !== key) {
+ samples > 1 ? blur(posterFrame, samples) : seek(posterFrame);
+ // the copy lives on the same kind of surface the art uses (surface(): same raster opts). A plain
+ // GPU <canvas> drawn onto a meta.raster "cpu" canvas flips Chrome's raster path for the rest
+ // of the session and every later frame comes out different: measured, not guessed.
+ const c = surface(canvas.width, canvas.height); c.ctx.drawImage(canvas, 0, 0); posterOf = { key, img: c.canvas };
+ }
+ const r = samples > 1 ? blur(n, samples) : seek(n);
+ if (u > 0 && posterOf) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = Math.min(1, u); ctx.globalCompositeOperation = "source-over"; if (u >= 1) ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(posterOf.img, 0, 0); ctx.restore(); }
+ current = n; return r;
+ };
+ window.FILM = { meta: { ...film.meta, hasAudio: typeof film.audio === "function", shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, poster, bakes: { load: bakes.load, take: bakes.take, hashes: bakes.hashes, stats: () => bakes.stats }, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };
// ---- the 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/test/camera.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/camera.test.ts
new file mode 100644
index 0000000..230bcd9
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/camera.test.ts
@@ -0,0 +1,78 @@
+// CAMERA TESTS. The engine camera (src/canvas-core/camera.ts) is pure arithmetic, so it is held to
+// exact numbers here, with no browser: node tools/test.mjs
+import { Camera, EASE, monoPath, planeScale, projectCam, strokeWeight, unprojectCam, type Cam } from "../src/canvas-core/camera";
+import { Gfx, type P } from "../src/canvas-core/core";
+
+export const name = "camera";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const cam = new Camera([540, 540], [{ f: 0, look: [400, 300], zoom: 1 }, { f: 90, look: [900, 300], zoom: 2 }, { f: 150, look: [900, 300], zoom: 2 }, { f: 240, look: [400, 300], zoom: 0.5 }]);
+ cam.shake({ from: 96, to: 126, amp: 14, seed: 7, rot: 0.05 });
+
+ // a fake context that records the transform the Gfx stack sets
+ let T: number[] = [];
+ const ctx = { setTransform: (...a: number[]) => { T = a; } } as unknown as ConstructorParameters<typeof Gfx>[0];
+ const env = { W: 1080, H: 1080, scale: 1, canvas: () => ({ ctx }), cache: new Map() } as unknown as ConstructorParameters<typeof Gfx>[1];
+ const g = new (Gfx as unknown as new (...a: unknown[]) => Gfx)(ctx, env, 0, "screen");
+
+ // 1. the transform path and the projector path are one camera
+ let maxErr = 0, roundTrip = 0;
+ for (const f of [0, 45, 97, 100, 110, 125, 200]) for (const z of [0, 0.7, -0.3]) {
+ cam.begin(g, f, z); const [a, b, c, d, e, ff] = T; cam.end(g);
+ for (const p of [[0, 0], [400, 300], [1234, -77]] as P[]) {
+ const s = cam.toScreen(p, f, z), m = [a * p[0] + c * p[1] + e, b * p[0] + d * p[1] + ff];
+ maxErr = Math.max(maxErr, Math.hypot(s[0] - m[0], s[1] - m[1]));
+ const w = cam.toWorld(s, f, z); roundTrip = Math.max(roundTrip, Math.hypot(w[0] - p[0], w[1] - p[1]));
+ }
+ }
+ ok(maxErr < 1e-6, `begin() transform and toScreen() agree (max ${maxErr.toExponential(1)} px)`);
+ ok(roundTrip < 1e-6, `toWorld(toScreen(p)) = p at every depth, shake and rotation included (max ${roundTrip.toExponential(1)})`);
+
+ // 2. zoom is eased in stops: the middle of a 1 -> 2 inout segment is sqrt(2), not 1.5
+ ok(near(cam.at(45).zoom, Math.SQRT2), "log2 midpoint of zoom 1 -> 2 is sqrt 2");
+ ok(near(cam.at(45).look[0], 650), "look is eased linearly in world units (midpoint 650)");
+ ok(near(cam.at(0).zoom, 1) && near(cam.at(90).zoom, 2) && near(cam.at(120).zoom, 2) && near(cam.at(999).zoom, 0.5), "keys are hit exactly; held between equal keys; clamped past the last");
+
+ // 3. eases: ends pinned, inout symmetric
+ for (const [n, e] of Object.entries(EASE)) ok(near(e(0), 0) && near(e(1), 1), `ease ${n} runs 0 -> 1`);
+ ok(near(EASE.inout(0.5), 0.5) && near(EASE.inout(0.25) + EASE.inout(0.75), 1), "inout is symmetric");
+
+ // 4. the dolly model
+ const c2: Cam = { look: [0, 0], zoom: 2 };
+ ok(near(planeScale(c2, 0), 2), "hero plane scales by zoom exactly");
+ ok(near(planeScale(c2, 1), 1 / (0.5 + 1)), "a plane at depth z scales by 1/(D + z)");
+ ok(planeScale(c2, 1) < planeScale(c2, 0) && planeScale(c2, -0.2) > planeScale(c2, 0), "far planes shrink, near planes grow");
+ const p: P = [123, -45], s = projectCam([540, 540], c2, 0.4, p, 0.2), back = unprojectCam([540, 540], c2, 0.4, s, 0.2);
+ ok(near(back[0], p[0], 1e-9) && near(back[1], p[1], 1e-9), "projectCam / unprojectCam invert each other");
+ ok(near(strokeWeight({ look: [0, 0], zoom: 8 }), Math.pow(8, 0.35)), "stroke weight is zoom^0.35");
+
+ // 5. shake: confined to its window, deterministic, rings down
+ ok(cam.shakeAt(95).every((v) => v === 0) && cam.shakeAt(126).every((v) => v === 0), "no shake outside [from, to)");
+ ok(JSON.stringify(cam.shakeAt(100)) === JSON.stringify(new Camera([540, 540], [{ f: 0, look: [0, 0], zoom: 1 }]).shake({ from: 96, to: 126, amp: 14, seed: 7, rot: 0.05 }).shakeAt(100)), "shake is a pure function of (seed, frame)");
+ const early = Math.max(...[98, 99, 100, 101].map((f) => Math.hypot(...cam.shakeAt(f).slice(0, 2) as [number, number]))), late = Math.max(...[121, 122, 123, 124, 125].map((f) => Math.hypot(...cam.shakeAt(f).slice(0, 2) as [number, number])));
+ ok(early > late, `shake decays (${early.toFixed(2)} px early vs ${late.toFixed(2)} px late)`);
+ ok(Math.hypot(...cam.shakeAt(96).slice(0, 2) as [number, number]) <= 14 * 0.5 + 1e-9, "shake attacks over its ramp instead of starting at full amplitude");
+
+ // 6. monotone path: never overshoots, never reverses, hits its keys
+ const keys = [[0, 1], [30, 4], [60, 4.2], [90, 0.5]] as const, path = monoPath(keys, { log2: true });
+ let prev = path(0), dir = 0, reversed = false, lo = Infinity, hi = -Infinity;
+ for (let f = 0; f <= 90; f += 0.5) { const v = path(f); lo = Math.min(lo, v); hi = Math.max(hi, v); const d = Math.sign(v - prev); if (d && dir && d !== dir && f < 60) reversed = true; if (d) dir = d; prev = v; }
+ ok(keys.every(([f, v]) => near(path(f), v, 1e-9)), "monoPath passes through every key");
+ ok(lo >= 0.5 - 1e-9 && hi <= 4.2 + 1e-9, "monoPath never overshoots its keys");
+ ok(!reversed, "monoPath never reverses inside a rising run");
+ const mono = new Camera([540, 540], [{ f: 0, look: [0, 0], zoom: 1 }, { f: 30, zoom: 4 }, { f: 60, zoom: 4.2 }, { f: 90, zoom: 0.5 }], { monoZoom: true });
+ ok([0, 13, 30, 47, 75, 90].every((f) => near(mono.at(f).zoom, path(f), 1e-12)), "Camera monoZoom uses the same path (built once, same answers every call)");
+
+ // 7. the Gfx transform stack composes rotation into child translation
+ g.push(10, 20, 2, 0.3); g.push(5, 0, 1, 0); const T1 = T; g.pop(); g.pop();
+ ok(near(T1[4], 10 + 2 * Math.cos(0.3) * 5) && near(T1[5], 20 + 2 * Math.sin(0.3) * 5), "nested push: child translation is rotated and scaled by the parent");
+
+ // 8. bad input is refused, loudly
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ ok(throws(() => new Camera([0, 0], [{ f: 5, zoom: 1 }, { f: 5, zoom: 2 }])), "rejects duplicate key frames");
+ ok(throws(() => new Camera([0, 0], [{ f: 1.5, zoom: 1 }])), "rejects a fractional key frame");
+ ok(throws(() => new Camera([0, 0], [{ f: 0, zoom: 0 }])), "rejects zoom <= 0");
+ ok(throws(() => new Camera([0, 0], [])), "rejects a camera with neither keys nor path");
+ ok(throws(() => cam.shake({ from: 10, to: 10, amp: 1, seed: 1 })), "rejects an empty shake window");
+ ok(throws(() => monoPath([[0, 1], [0, 2]])), "monoPath rejects non-increasing keys");
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/html-player.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/html-player.mjs
index 6aefff7..a6ec3d8 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/html-player.mjs
+++ b/plugins/anidoodle/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";
@@ -24,23 +25,26 @@ export const probe = () => {
};
// what makes a self-contained page worth shipping: nothing in it may reach outside itself
-export const pageChecks = (html) => {
- const has = (re) => { const m = html.match(re); return m ? m.length : 0; };
- const assets = html.match(/window\.__ASSETS__=([^;]*);/);
+// A film may declare assets (a photo the user brought): build-page inlines exactly those into the
+// manifest, and that is the ONLY place a binary may sit. `declared` = the film's asset names.
+export const pageChecks = (html, declared = []) => {
+ const assets = html.match(/window\.__ASSETS__=(\{.*?\});(?=window\.|<\/script>)/), rest = assets ? html.replace(assets[0], "") : html;
+ const has = (re) => { const m = rest.match(re); return m ? m.length : 0; };
+ let names = null; try { names = assets ? Object.keys(JSON.parse(assets[1])) : null; } catch { names = null; }
return [
{ ok: has(/https?:\/\//g) === 0, label: "no http(s) reference of any kind", detail: `${has(/https?:\/\//g)} found` },
{ ok: has(/<(img|audio|video|source|link|iframe)\b/gi) === 0, label: "no external element (img, audio, video, link)", detail: `${has(/<(img|audio|video|source|link|iframe)\b/gi)} found` },
{ ok: has(/@font-face/gi) === 0, label: "no web font", detail: `${has(/@font-face/gi)} found` },
- { ok: has(/data:[a-z]+\/[a-z0-9.+-]+;base64/gi) === 0, label: "no embedded binary asset", detail: `${has(/data:[a-z]+\/[a-z0-9.+-]+;base64/gi)} found` },
+ { ok: has(/data:[a-z]+\/[a-z0-9.+-]+;base64/gi) === 0, label: "no embedded binary outside the asset manifest", detail: `${has(/data:[a-z]+\/[a-z0-9.+-]+;base64/gi)} found` },
{ ok: has(/fetch\(|XMLHttpRequest|importScripts/g) === 0, label: "no network call in the bundle", detail: `${has(/fetch\(|XMLHttpRequest|importScripts/g)} found` },
- { ok: assets ? assets[1].trim() === "{}" : false, label: "the asset manifest is empty", detail: assets ? assets[1].trim() : "manifest absent" },
+ { ok: !!names && names.length === declared.length && declared.every((n) => names.includes(n)), label: declared.length ? `the asset manifest holds exactly the film's ${declared.length} declared asset(s)` : "the asset manifest is empty", detail: names ? (names.join(", ") || "{}") : "manifest absent or unreadable" },
{ ok: /window\.FILM\s*=/.test(html), label: "exposes window.FILM so any host can drive it", detail: "" },
{ ok: /audio\s*[:(]/.test(html), label: "any score is synthesized in the page, never loaded", detail: "" },
];
};
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 +53,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);
+ if (opts.warm !== false) await page.evaluate(() => window.FILM.warm()); // warm:false = truly cold, nothing drawn before the first ask
if (errors.length) throw new Error("page failed: " + errors.join("; "));
pages.push(page);
}
@@ -66,7 +72,7 @@ export const open = async (film, opts = {}) => {
frame: async (n, w = 0) => { const r = await pick(w).evaluate((f) => { const s = window.FILM.seek(f); return { ...s, png: window.FILM.png() }; }, n); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms }; },
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(),
+ artifact: () => ({ path: out, kind: "self-contained HTML player", bytes: statSync(out).size, meta: built.meta, checks: pageChecks(html, built.assets ?? []) }),
+ close: async () => { if (useBakes) for (const p of pages) await saveBakes(p, bv).catch(() => 0); await browser.close(); },
};
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs
index 60e6d35..be46717 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs
@@ -2,23 +2,33 @@
// canvas pixels. Frame accuracy comes from the pull model (frame N is a pure function of N),
// not from anything Playwright does.
import { pathToFileURL } from "node:url";
+import { bakeCacheOn, loadBakes, saveBakes } from "../bake-cache.mjs";
export const name = "playwright";
-export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workers = 1 } = {}) => {
+// bakeCache (default on): finished plate frames come from and go to .cache/bakes (see bake-cache.mjs)
+export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workers = 1, bakeCache } = {}) => {
const browser = await pw.lib.chromium.launch({ executablePath: found.executablePath, args: ["--disable-background-timer-throttling"] });
+ const useBakes = bakeCacheOn(bakeCache), bv = browser.version(); let loadedBakes = 0;
const context = await browser.newContext({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 1 });
const pages = [];
- for (let i = 0; i < workers; i++) { const page = await context.newPage(); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.goto(pathToFileURL(pagePath).href + "?adapter=playwright"); await page.evaluate(async (s) => { await window.FILM.ready; window.FILM.mount(s); window.FILM.warm(); }, scale); /* warm = build texture tiles once, outside the timed frames */ if (errors.length) throw new Error("page failed: " + errors.join("; ")); pages.push(page); }
+ for (let i = 0; i < workers; i++) { const page = await context.newPage(); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); await page.goto(pathToFileURL(pagePath).href + "?adapter=playwright"); await page.evaluate(async (s) => { await window.FILM.ready; window.FILM.mount(s); }, scale); if (useBakes) loadedBakes = await loadBakes(page, bv); await page.evaluate(() => window.FILM.warm()); /* warm = build texture tiles once, outside the timed frames */ if (errors.length) throw new Error("page failed: " + errors.join("; ")); pages.push(page); }
const pick = (n) => pages[n % pages.length];
return {
workers: pages.length,
+ bakes: () => ({ on: useBakes, loaded: loadedBakes }),
info: () => pages[0].evaluate(() => window.FILM.meta),
// -> { 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 }; },
+ // a frame of the poster dissolve (see hosts/page.ts poster): frame n with poster frame p over it
+ poster: async (n, p, fade, samples = 1, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, pf, fd, s]) => { const r = window.FILM.poster(f, pf, fd, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, p, fade, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },
+ posterHash: (n, p, fade, samples = 1, w = 0) => pick(w).evaluate(([f, pf, fd, s]) => { window.FILM.poster(f, pf, fd, s); return window.FILM.hash(); }, [n, p, fade, samples]),
+ // hash of the motion-blurred frame: what a --blur render actually writes, so the probe checks THAT
+ blurHash: (n, samples, w = 0) => pick(w).evaluate(([f, s]) => { window.FILM.blur(f, s); return window.FILM.hash(); }, [n, samples]),
audio: (sr) => pages[0].evaluate((s) => window.FILM.audio(s), sr),
- close: () => browser.close(),
+ // keeps the fresh bakes, then closes; returns how many plate frames were stored
+ close: async () => { let saved = 0; if (useBakes) for (const p of pages) saved += await saveBakes(p, bv).catch(() => 0); await browser.close(); return saved; },
};
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjs
index 5779d5d..dc4b261 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/remotion.mjs
@@ -13,6 +13,7 @@ import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { join, resolve } from "node:path";
+import { overlay } from "../overlay.mjs";
const require = createRequire(import.meta.url);
const tryRequire = (id) => { try { return require(id); } catch { return null; } };
@@ -35,7 +36,7 @@ export const probe = () => {
// build-page.mjs reads it: bundled on its own, with no host attached, so nothing can disagree.
const loadFilm = async (film) => {
const { build } = await import("esbuild");
- const out = (await 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" })).outputFiles[0].text;
+ const out = (await 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;
return (await import("data:text/javascript;base64," + Buffer.from(out).toString("base64"))).film;
};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/bake-cache.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/bake-cache.mjs
new file mode 100644
index 0000000..c1fe9da
--- /dev/null
+++ b/plugins/anidoodle/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/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs
index 0ca66c3..cd772be 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs
@@ -1,20 +1,61 @@
// Build ONE self-contained HTML file: the art core + film, bundled, with every asset in the
// manifest inlined as a data URI. No network, no server, no sibling files.
import { build } from "esbuild";
-import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
-import { extname, join } from "node:path";
+import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { extname, join, relative, resolve } from "node:path";
+import { overlay, resolveOverlay } from "./overlay.mjs";
+
+// 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 = [] }) => {
- const js = (await build({ entryPoints: [entry], bundle: true, format: "iife", target: "es2020", minify: true, write: false, legalComments: "none", plugins })).outputFiles[0].text;
+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 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 };
+ return { out, bytes: html.length, meta: film.meta, assets: Object.keys(film.assets.images) };
};
if (import.meta.url === `file://${process.argv[1]}`) { const title = process.argv[2] ?? "fixtures"; const r = await buildPage({ entry: `src/hosts/page-${title}.ts`, out: `dist/${title}.html`, title }); console.log(`built ${r.out} (${(r.bytes / 1024).toFixed(0)} KB, self-contained)`); }
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/emit-interactive.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/emit-interactive.mjs
index 5d270b3..8503526 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/emit-interactive.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/emit-interactive.mjs
@@ -22,6 +22,7 @@ import { dirname, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { gzipSync } from "node:zlib";
import { detect } from "./detect.mjs";
+import { overlay } from "./overlay.mjs";
const VAL = new Set(["out", "module", "page", "title", "shot"]);
const pos = [], opt = {};
@@ -35,7 +36,7 @@ const out = resolve(opt.out ?? `out/${kebab}.html`), modOut = resolve(opt.module
// ---------------------------------------------------------------- build
const buildModule = async (piece, tag = piece.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase()) => (await build({
stdin: { contents: `import { mount, define } from "./src/hosts/interactive"; import { ${piece} } from "./src/canvas-core/${piece}"; export const piece = ${piece}; export { mount, define }; define({ ${JSON.stringify(tag)}: ${piece} });`, resolveDir: process.cwd(), loader: "ts" },
- bundle: true, format: "esm", target: "es2020", minify: true, write: false, legalComments: "none",
+ bundle: true, format: "esm", target: "es2020", minify: true, write: false, legalComments: "none", plugins: [overlay],
})).outputFiles[0].text;
const js = await buildModule(name, kebab);
const defaultPage = () => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${opt.title ?? name}</title>
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs
index 2c2cc3d..ec4dd10 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs
@@ -50,7 +50,7 @@ console.log(` ${out} (${(ship.bytes / 1024).toFixed(0)} KB, self-containe
// ---------------------------------------------------------------- 1. static
head(1, "SHIP-WORTHY the file reaches outside itself for nothing");
const html = readFileSync(out, "utf8");
-pageChecks(html).forEach((c) => say(c.ok, c.label, c.detail));
+pageChecks(html, ship.assets).forEach((c) => say(c.ok, c.label, c.detail));
say(statSync(out).size === ship.bytes, "the file on disk is the file that was built", `${statSync(out).size} bytes`);
// ---------------------------------------------------------------- 2 & 3. run it
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/gallery.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/gallery.mjs
index 90073dc..ee3f956 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/gallery.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/gallery.mjs
@@ -12,6 +12,7 @@ import { buildPage } from "./build-page.mjs";
import { detect } from "./detect.mjs";
import * as playwright from "./adapters/playwright.mjs";
import { loadRegistry, ENGINE, ROOT } from "./registry.mjs";
+import { overlay } from "./overlay.mjs";
process.chdir(ENGINE); // buildPage and the host pages resolve src/ against cwd, like every tool here
const GALLERY = resolve(ROOT, "assets/gallery");
@@ -40,7 +41,7 @@ const findFont = (ff) => {
// A still.mjs-style probe: bundle the film, read meta, no browser. Enough for --dry to say which
// frame is the last.
-const metaOf = async (film) => (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" })).outputFiles[0].text).toString("base64"))).film.meta;
+const metaOf = async (film) => (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.meta;
const cols = Math.ceil(Math.sqrt(tiles.length)), rows = Math.ceil(tiles.length / cols);
const plan = (font) => `grid ${cols}x${rows} of ${CELL}px tiles, ${font.ok ? `labels in ${font.font}` : `no labels (${font.why}) -> LEGEND.md`}`;
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs
index f9372b5..98902cf 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs
@@ -11,6 +11,7 @@
// The gate NEVER writes to out/. It renders into .tmp/gate/ and it only ever READS the MP4 it is
// pointed at, so running it can never damage a finished film.
import { execFileSync, spawnSync } from "node:child_process";
+import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { readdirSync } from "node:fs";
@@ -60,7 +61,8 @@ const walk = (dir, out = []) => { for (const e of execFileSync("find", [dir, "-n
const contractScan = () => {
head(2, "CONTRACT the art core cannot reach a clock, the network or a file");
- const files = [...walk("src/canvas-core"), `src/hosts/page-${film}.ts`].filter((f) => existsSync(f));
+ // the worked example is part of the same tree at build time (tools/overlay.mjs): scan it too
+ const files = [...walk("src/canvas-core"), ...(existsSync("../example/src/canvas-core") ? walk("../example/src/canvas-core") : []), `src/hosts/page-${film}.ts`].filter((f) => existsSync(f));
const hits = [];
for (const f of files) { const src = stripComments(readFileSync(f, "utf8")); FORBIDDEN.forEach(([re, label]) => { const m = src.match(new RegExp(re.source, "g")); if (m) hits.push(`${f}: ${label} x${m.length}`); }); }
say(hits.length === 0, `no forbidden call in ${files.length} art-core modules`, hits.length ? hits.slice(0, 6).join(" | ") : "Math.random, Date, performance.now, ctx.filter, network, image/font loads: none");
@@ -102,14 +104,19 @@ const run = async () => {
if (!p.ok) { console.log("\nGATE: CANNOT RUN"); process.exit(2); }
head(1, "DETERMINISM the same frame, drawn two different ways, is the same frame");
- const s1 = await mod.open(film, { scale: SCALE, workers: 1 });
+ // session 1 is COLD (no warm-up draws) and forward; session 2 is warmed and reversed. A frame that
+ // depends on what was drawn before it (leaked context state, a cache key missing a term) differs.
+ const s1 = await mod.open(film, { scale: SCALE, workers: 1, warm: false });
const meta = await s1.info();
const N = meta.durationFrames;
const bounds = [...new Set([0, N - 1, ...(meta.shots ?? []).flatMap((s) => [s.start, s.end - 1])])];
const extra = Math.max(0, SAMPLES - bounds.length);
const spread = Array.from({ length: extra }, (_, i) => Math.round(((i + 1) * (N - 1)) / (extra + 1)));
const frames = [...new Set([...bounds, ...spread])].sort((a, b) => a - b);
- const h1 = []; for (const f of frames) h1.push(await s1.hash(f, 0)); // forward, one page
+ // the PNGs themselves are kept: if two hashes disagree, the pixels compared are THOSE pixels, not
+ // a fresh redraw that may not reproduce the history that made them differ
+ const md5 = (b) => createHash("md5").update(b).digest("hex"), p1 = [], p2 = new Array(frames.length);
+ const h1 = []; for (const f of frames) { const png = (await s1.frame(f, 0)).png; p1.push(png); h1.push(md5(png)); } // forward, one cold page
const art = s1.artifact?.() ?? null;
const aud1 = await s1.audio(48000);
await s1.close();
@@ -117,7 +124,7 @@ const run = async () => {
const W2 = 3;
const s2 = await mod.open(film, { scale: SCALE, workers: W2 });
const h2 = new Array(frames.length);
- for (let i = frames.length - 1; i >= 0; i--) h2[i] = await s2.hash(frames[i], i); // reversed, spread over 3 pages
+ for (let i = frames.length - 1; i >= 0; i--) { const png = (await s2.frame(frames[i], i)).png; p2[i] = png; h2[i] = md5(png); } // reversed, spread over 3 warmed pages
const aud2 = await s2.audio(48000);
const same = frames.filter((_, i) => h1[i] === h2[i]).length;
@@ -127,9 +134,7 @@ const run = async () => {
for (let i = 0; i < frames.length; i++) {
if (h1[i] === h2[i]) continue;
const a = resolve(TMP, `a${frames[i]}.png`), b = resolve(TMP, `b${frames[i]}.png`);
- const sA = await mod.open(film, { scale: SCALE, workers: 1 });
- writeFileSync(a, (await sA.frame(frames[i], 0)).png); await sA.close();
- writeFileSync(b, (await s2.frame(frames[i], i)).png);
+ writeFileSync(a, p1[i]); writeFileSync(b, p2[i]);
const v = psnr(a, b); worst = Math.min(worst, v);
console.log(` frame ${frames[i]}: PSNR ${v === Infinity ? "inf" : v.toFixed(2)} dB`);
}
@@ -139,15 +144,15 @@ const run = async () => {
// of a cache key that does not name everything its pixels depend on.
const bad = frames.find((_, i) => h1[i] !== h2[i]);
if (bad !== undefined) {
- const c0 = await mod.open(film, { scale: SCALE, workers: 1 }); const cold = await c0.hash(bad, 0); await c0.close();
+ const c0 = await mod.open(film, { scale: SCALE, workers: 1, warm: false }); const cold = await c0.hash(bad, 0); await c0.close();
const culprits = [];
for (const pre of frames.filter((f) => f !== bad)) {
- const c = await mod.open(film, { scale: SCALE, workers: 1 });
+ const c = await mod.open(film, { scale: SCALE, workers: 1, warm: false });
await c.hash(pre, 0); const h = await c.hash(bad, 0); await c.close();
if (h !== cold) culprits.push(pre);
}
console.log(culprits.length
- ? ` DIAGNOSIS: frame ${bad} is ORDER-DEPENDENT. Drawing frame(s) ${culprits.join(", ")} first changes it.\n That is a cache key that does not name everything its pixels depend on.`
+ ? ` DIAGNOSIS: frame ${bad} is ORDER-DEPENDENT. Drawing frame(s) ${culprits.join(", ")} first changes it.\n That is a cache key that does not name everything its pixels depend on,\n or state one frame leaves behind for the next.`
: ` DIAGNOSIS: frame ${bad} is stable within a session; the difference is between sessions.`);
}
}
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/lesson.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/lesson.mjs
index 632d0fd..436dff6 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/lesson.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/lesson.mjs
@@ -18,6 +18,7 @@ import { pathToFileURL } from "node:url";
import { build } from "esbuild";
import { buildPage } from "./build-page.mjs";
import { detect } from "./detect.mjs";
+import { overlay } from "./overlay.mjs";
const VAL = new Set(["out", "ref", "ref-crop", "workers"]);
const pos = [], opt = {};
@@ -28,7 +29,7 @@ const outDir = resolve(opt.out ?? `out/${name}`); mkdirSync(outDir, { recursive:
const log = []; const say = (s = "") => { console.log(s); log.push(s); };
// ---------------------------------------------------------------- 1. the score, in node
-const probe = (await build({ stdin: { contents: `export { LESSON, ${name} as film } from "./src/canvas-core/${name}"; export { validate, PHASE_NAME } from "./src/canvas-core/drawingScore";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral" })).outputFiles[0].text;
+const probe = (await build({ stdin: { contents: `export { LESSON, ${name} as film } from "./src/canvas-core/${name}"; export { validate, PHASE_NAME } from "./src/canvas-core/drawingScore";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral", plugins: [overlay] })).outputFiles[0].text;
const M = await import("data:text/javascript;base64," + Buffer.from(probe).toString("base64"));
const S = M.LESSON.score(), V = M.validate(S), plan = M.film.plan(), fps = M.film.meta.fps, N = M.film.meta.durationFrames;
say(`LESSON ${S.title} (${S.medium})`);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/overlay.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/overlay.mjs
new file mode 100644
index 0000000..14ba363
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/overlay.mjs
@@ -0,0 +1,36 @@
+// OVERLAY. The engine's src/ and the worked example's example/src/ are ONE tree at build time,
+// exactly as scaffold.mjs --example lays them out on disk: a relative import that is not found
+// next to its importer is looked for at the same relative place under the other root. The
+// example keeps importing "../core"; a launch film can import "./mechanicalLepidoptera" and get
+// the committed example. Order matters: engine/src first, so the engine always wins a name clash.
+// tsconfig.json says the same thing to tsc with "rootDirs", so the checker and the bundler agree.
+import { existsSync, statSync } from "node:fs";
+import { dirname, join, relative, resolve, sep } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const ENGINE = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+export const ROOTS = [join(ENGINE, "src"), resolve(ENGINE, "../example/src")];
+const EXT = ["", ".ts", ".tsx", ".js", ".mjs", "/index.ts", "/index.js"];
+const file = (p) => { for (const e of EXT) { const f = p + e; if (existsSync(f) && statSync(f).isFile()) return f; } return null; };
+const rootOf = (p) => ROOTS.find((r) => p === r || p.startsWith(r + sep));
+
+// Resolve a relative specifier asked from directory `dir` across the roots; null when it is not
+// ours to answer. `dir` may sit outside the roots (a probe's stdin resolves from engine/).
+export const resolveOverlay = (spec, dir) => {
+ const want = resolve(dir, spec), root = rootOf(want); if (!root) return null;
+ if (file(want)) return null; // found where it was asked for: esbuild's own resolver handles it
+ const rel = relative(root, want);
+ if (rel.startsWith("..")) return null; // left the tree: not an overlay question
+ for (const r of ROOTS) { if (r === root) continue; const f = file(join(r, rel)); if (f) return f; }
+ return null;
+};
+
+export const overlay = {
+ name: "anidoodle-overlay",
+ setup(b) {
+ b.onResolve({ filter: /^\.\.?\// }, (a) => {
+ const f = resolveOverlay(a.path, a.resolveDir);
+ return f ? { path: f } : undefined;
+ });
+ },
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/registry.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/registry.mjs
index ef578cd..f4027bb 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/registry.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/registry.mjs
@@ -29,8 +29,9 @@ export const loadRegistry = () => {
const byId = new Map(), shadowed = [];
for (const s of legacy) byId.set(s.id, s);
- // A house style (a hand matched from someone's image) or a recreation/study USES a hand; it is not a new one.
- scanned.splice(0, scanned.length, ...scanned.filter((s) => !s.house && !s.recreationOf && !s.study));
+ // A house style (a hand matched from someone's image), a recreation/study, or a scene drawn in an
+ // existing hand (`sceneOf: "<hand id>"`) USES a hand; it is not a new one.
+ scanned.splice(0, scanned.length, ...scanned.filter((s) => !s.house && !s.recreationOf && !s.study && !s.sceneOf));
// "<plate>Draw" is the drawing film of an existing hand, not a new hand: fold it into its parent.
const drawOf = (s) => (s.id.endsWith("Draw") && byId.has(s.id.slice(0, -4)) ? s.id.slice(0, -4) : null);
for (const s of scanned.filter(drawOf)) byId.set(drawOf(s), { ...byId.get(drawOf(s)), drawFilm: s.id });
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs
index ca27bd3..8122217 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs
@@ -1,11 +1,19 @@
// 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.
+// --blur N motion blur (N an integer >= 1): every output frame is the average of N subframes over
+// a one-frame shutter, integrated in linear light and weighted by alpha inside the page.
+// Fast pans and dolly moves stop juddering; held frames come out unchanged because their
+// subframes are identical. Stepped art (meta.step > 1 or onTwos) is NOT blurred: the
+// shutter would straddle two drawings. Costs N times the draw time. --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.
+// render is silent (the score would not line up), says so, and by default writes
+// out/<film>.<from>-<to>.<ext> so it can never overwrite the finished film.
+// --hashes file also write "frame md5" of every PNG handed to the encoder: two renders compared
+// frame by frame, before any codec can blur the difference.
+// --poster-frame N [--poster-fade 6] platforms show frame 0 as the thumbnail: open on frame N (the
+// wall of styles, the logo) and dissolve into the real opening by frame 6. The frame
+// count and the score are unchanged. A delivery whose frame 0 is near-blank gets a
+// warning after the encode (verify-export --delivery makes it a failure).
// 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
@@ -15,6 +23,7 @@
// .apng animated PNG, alpha kept, loops forever, plays in every browser
// --width only applies to the silent formats; the MP4 is always the film's own size.
import { spawn, execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
import { mkdirSync, writeFileSync } from "node:fs";
import { cpus } from "node:os";
import { join, resolve } from "node:path";
@@ -23,11 +32,18 @@ import { detect } from "./detect.mjs";
import * as playwright from "./adapters/playwright.mjs";
import { defaultOutput } from "./names.mjs";
import { float32Wav } from "./audio.mjs";
+import { firstFrameBlank } from "./thumb.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 BLUR = Number(arg("blur", 1));
+if (!Number.isInteger(BLUR) || BLUR < 1) { console.error(`--blur wants a whole number of subframes >= 1, got '${arg("blur")}'`); process.exit(2); }
+const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2)))));
+const HASHES = arg("hashes", null) ? new Map() : null;
+const RANGE_ASKED = process.argv.includes("--from") || process.argv.includes("--to");
+const POSTER = arg("poster-frame", null) === null ? null : Number(arg("poster-frame")), FADE = Number(arg("poster-fade", 6));
+if (POSTER !== null && (!Number.isInteger(POSTER) || POSTER < 0)) { console.error(`--poster-frame wants a frame number >= 0, got '${arg("poster-frame")}'`); process.exit(2); }
+if (!Number.isInteger(FADE) || FADE < 0) { console.error(`--poster-fade wants a whole number of frames >= 0, got '${arg("poster-fade")}'`); process.exit(2); }
const env = detect();
console.log("backends found:"); for (const [k, v] of Object.entries(env.report)) console.log(` ${k.padEnd(11)} ${v}`);
@@ -40,6 +56,15 @@ const t0 = Date.now(), session = await playwright.open(env, page.out, { scale, w
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;
+// a passage never lands on the finished film's path: default to out/<film>.<from>-<to>.<ext>, and refuse an explicit --out that IS the film
+const full = resolve(defaultOutput(film).replace(/\.mp4$/, `.${fmt}`));
+const out = resolve(arg("out", ranged ? `out/${film}.${FROM}-${TO}.${fmt}` : full));
+if (ranged && out === resolve(defaultOutput(film))) { console.error(`refusing to write a range render over the finished film ${out}; pick another --out or drop --from/--to`); process.exit(2); }
+if (RANGE_ASKED && !ranged) console.log("range covers the whole film: rendering it complete, with its score");
+if (POSTER !== null && POSTER >= N) { console.error(`--poster-frame ${POSTER} is past the film's last frame ${N - 1}`); process.exit(2); }
+if (POSTER !== null) console.log(`poster: frame 0 is frame ${POSTER}, dissolving into the opening by frame ${Math.max(1, FADE)}`);
+const posterAt = (n) => POSTER !== null && n < Math.max(1, FADE); // frames the poster dissolve touches
+const drawAt = (n, w) => (posterAt(n) ? session.poster(n, POSTER, FADE, BLUR, w) : BLUR > 1 ? session.blur(n, BLUR, w) : session.frame(n, w));
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`);
@@ -65,9 +90,10 @@ const done = new Promise((res, rej) => ff.on("close", (c) => (c ? rej(new Error(
const cost = [], pending = new Map(); let next, write;
const pump = async () => { while (pending.has(write)) { const b = pending.get(write); pending.delete(write); if (!ff.stdin.write(b)) await new Promise((r) => ff.stdin.once("drain", r)); write++; } };
next = FROM; write = FROM;
-await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = 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 Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await drawAt(n, w); if (HASHES) HASHES.set(n, createHash("md5").update(f.png).digest("hex")); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs }); pending.set(n, f.png); await pump(); } }));
await pump(); ff.stdin.end(); await done;
const wall = (Date.now() - t0) / 1000;
+if (HASHES) { const hf = resolve(arg("hashes")); mkdirSync(join(hf, ".."), { recursive: true }); writeFileSync(hf, [...HASHES].sort((a, b) => a[0] - b[0]).map(([n, h]) => `${n} ${h}`).join("\n") + "\n"); console.log(`frame hashes -> ${hf}`); }
// ---- frame cost
const stat = (xs) => { const s = [...xs].sort((a, b) => a - b); return { med: s[s.length >> 1], p95: s[Math.floor(s.length * 0.95)], max: s[s.length - 1] }; };
@@ -80,9 +106,11 @@ console.log(` wall clock: ${wall.toFixed(1)} s for ${TO - FROM} frames = ${((TO
// ---- 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])].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 hashOf = (n, w) => (posterAt(n) ? session.posterHash(n, POSTER, FADE, BLUR, w) : BLUR > 1 ? session.blurHash(n, BLUR, w) : session.hash(n, w)); // probe what was WRITTEN: poster dissolve, blurred frame
+for (const n of probe) fwd.push(await hashOf(n, 0)); for (const n of [...probe].reverse()) rev.unshift(await hashOf(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"}`);
+console.log(`\ndeterminism: ${same}/${probe.length} probe frames${BLUR > 1 ? ` (blurred, ${BLUR} subframes)` : ""} hash-identical (forward on page 0 vs reversed on page ${session.workers - 1})${same === probe.length ? "" : " -> fall back to PSNR > 45 dB in the Phase 2 gate"}`);
await session.close();
const pr = execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height,nb_frames,duration", "-of", "csv=p=0", out]).toString().trim().split("\n");
console.log(`\noutput: ${out}`); pr.forEach((l) => console.log(` ${l}`));
+if (fmt === "mp4" && !ranged) { const t = firstFrameBlank(out); if (t.blank) console.log(`\nWARNING frame 0 is near-blank (${t.detail}). Platforms use frame 0 as the thumbnail: re-render with --poster-frame N (a legible frame: the wall, the logo).`); }
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/snap.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/snap.mjs
index e2232a8..c0fe9e8 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/snap.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/snap.mjs
@@ -10,6 +10,7 @@ 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", "samples", "scale", "out"]);
const pos = [], opt = {};
@@ -40,7 +41,7 @@ const onlyPlugin = opt.only ? (() => {
})() : [];
// the film's own shots and meta, read through the same shim in --only mode
-const probe = (await 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: onlyPlugin })).outputFiles[0].text;
+const probe = (await 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: [...onlyPlugin, overlay] })).outputFiles[0].text;
const f = (await import("data:text/javascript;base64," + Buffer.from(probe).toString("base64"))).film;
const targets = shotId ? [f.shots.find((s) => s.id === shotId) ?? die(`film '${film}' has no shot '${shotId}' (has: ${f.shots.map((s) => s.id).join(", ")})`)] : f.shots;
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjs
index fc5f5b3..89df523 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjs
@@ -1,39 +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";
-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" })).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();
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/test.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/test.mjs
new file mode 100644
index 0000000..a345dfe
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/test.mjs
@@ -0,0 +1,21 @@
+// UNIT TESTS. Every test/*.test.ts module exports { name, run(ok) }; this bundles each with esbuild
+// (the same resolver the films use) and runs it in node. No browser, no framework, exit 1 on any
+// failure. node tools/test.mjs [name ...]
+import { build } from "esbuild";
+import { readdirSync } from "node:fs";
+import { overlay } from "./overlay.mjs";
+
+const only = process.argv.slice(2);
+const files = readdirSync("test").filter((f) => f.endsWith(".test.ts")).sort().filter((f) => !only.length || only.includes(f.replace(/\.test\.ts$/, "")));
+if (!files.length) { console.error(`test: nothing to run${only.length ? ` for ${only.join(", ")}` : ""}`); process.exit(2); }
+let pass = 0, fail = 0;
+for (const f of files) {
+ const js = (await build({ entryPoints: [`test/${f}`], bundle: true, format: "esm", write: false, platform: "neutral", plugins: [overlay], logLevel: "error" })).outputFiles[0].text;
+ const mod = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));
+ console.log(`\n${mod.name ?? f}`);
+ try {
+ mod.run((cond, label) => { if (cond) pass++; else fail++; console.log(` ${cond ? "PASS" : "FAIL"} ${label}`); });
+ } catch (e) { fail++; console.log(` FAIL crashed: ${e.stack ?? e}`); }
+}
+console.log(`\nTESTS: ${fail ? "FAIL" : "PASS"} ${pass} passed, ${fail} failed`);
+process.exit(fail ? 1 : 0);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/thumb.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/thumb.mjs
new file mode 100644
index 0000000..9814699
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/thumb.mjs
@@ -0,0 +1,17 @@
+// THUMBNAIL GUARD. Platforms show a video's first frame as its thumbnail, so a delivery that opens
+// on a blank page, a flat colour or a fade from black shows up as an empty rectangle in the feed.
+// This reads decoded frame 0 of a file (what the platform will actually show) at thumbnail size
+// and calls it near-blank when it is one flat tone: tiny spread of luma, or almost every pixel
+// within a few levels of the median. A small logo or a line of text on a blank ground still
+// counts as blank on purpose: that is not a thumbnail anyone can read at feed size.
+import { spawnSync } from "node:child_process";
+
+const W = 96, H = 54;
+export const firstFrameBlank = (file, { frame = 0 } = {}) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select=eq(n\\,${frame}),scale=${W}:${H}:flags=area`, "-vsync", "0", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"], { maxBuffer: 1 << 20 });
+ if (r.status !== 0 || r.stdout.length !== W * H) return { blank: false, unknown: true, detail: `could not decode frame ${frame}: ${r.stderr?.toString().trim() || "short read"}` };
+ const px = [...r.stdout], n = px.length, mean = px.reduce((a, b) => a + b, 0) / n;
+ const sd = Math.sqrt(px.reduce((a, b) => a + (b - mean) ** 2, 0) / n), med = [...px].sort((a, b) => a - b)[n >> 1];
+ const flat = px.filter((v) => Math.abs(v - med) <= 6).length / n;
+ return { blank: sd < 3 || flat >= 0.985, sd, flat, mean, detail: `luma spread ${sd.toFixed(1)}, ${(flat * 100).toFixed(1)}% of pixels within 6 levels of ${med}` };
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs
index c797e5a..8c46e2a 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs
@@ -5,19 +5,27 @@
// 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)
+// [--width W] expected pixel width of a .gif/.webm/.apng made with render --width
+// (default: the film's own; height follows the aspect). Not for .mp4:
+// render always writes the MP4 at the film's size (x --scale), so
+// --width on an MP4 is refused rather than silently ignored
// [--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)
+// [--fidelity-psnr N] a decoded frame must sit within N dB of the source frame (renders it once)
+// [--frame N] which frame --fidelity-psnr compares (default 0)
+// [--delivery] this file ships: a near-blank frame 0 (the platform thumbnail) FAILS
+// instead of warning; fix with render --poster-frame N
//
-// 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.
+// Always checked: the file decodes, its pixel size, its exact frame count, its duration against
+// the film's meta, and for an MP4 the score: an audio stream exactly when the film has a score,
+// as long as the picture, and not silent. 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";
+import { firstFrameBlank } from "./thumb.mjs";
-const VAL = new Set(["file", "adapter", "width", "first-frame", "tol", "fidelity-psnr", "scale"]);
+const VAL = new Set(["file", "adapter", "width", "first-frame", "tol", "fidelity-psnr", "scale", "frame"]);
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";
@@ -51,6 +59,10 @@ const N = meta.durationFrames, FW = Math.round(meta.W * SCALE), FH = Math.round(
const file = resolve(opt.file ?? defaultOutput(film));
console.log(`VERIFY-EXPORT film "${meta.title}" file ${file}`);
if (!existsSync(file)) die(`${file} not found`);
+const isMp4 = /\.(mp4|m4v|mov)$/i.test(file);
+if (opt.width && isMp4) die(`--width does not apply to an MP4: render writes it at the film's own size (x --scale); use --scale to check a scaled render`);
+const FRAME = opt.frame === undefined ? 0 : Number(opt.frame);
+if (!Number.isInteger(FRAME) || FRAME < 0 || FRAME >= N) die(`--frame wants a frame number in [0, ${N - 1}], got '${opt.frame}'`);
// ---------------------------------------------------------------- 1. the container
head(1, "CONTAINER the file is the film's size, length and duration");
@@ -64,8 +76,30 @@ const dur = Number(ffprobe(["-show_entries", "format=duration", "-of", "csv=p=0"
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)`);
+// ---------------------------------------------------------------- 1b. the score, in an MP4
+if (isMp4) {
+ head("1b", "SOUND the score is in the file, as long as the picture, and audible");
+ const a = ffprobe(["-select_streams", "a", "-show_entries", "stream=codec_name,duration,sample_rate,channels", "-of", "csv=p=0", file]).split("\n").filter(Boolean);
+ const hasAudio = meta.hasAudio ?? Boolean(await s.audio?.(48000)); // older pages / other adapters: ask the score itself
+ if (!hasAudio) say(a.length === 0, "no audio stream (the film has no score)", a.length ? `found ${a.length}: ${a.join(" | ")}` : "");
+ else if (!a.length) say(false, "an audio stream (the film has a score)", "none found: was it a range render?");
+ else {
+ const [acodec, rate, ch, adur] = a[0].split(","), ad = Number(adur);
+ say(a.length === 1, `one audio stream (${acodec}, ${rate} Hz, ${ch} ch)`, a.length > 1 ? `found ${a.length}` : "");
+ say(Math.abs(ad - wantDur) <= slack + 0.05, `audio duration ${ad.toFixed(3)} s`, `picture is ${wantDur.toFixed(3)} s +/- ${(slack + 0.05).toFixed(3)} (AAC priming)`);
+ const vd = spawnSync("ffmpeg", ["-v", "info", "-i", file, "-map", "0:a:0", "-af", "volumedetect", "-f", "null", "-"], { encoding: "utf8" });
+ const mx = Number(((vd.stdout + vd.stderr).match(/max_volume:\s*(-?[0-9.]+|-inf) dB/) ?? [])[1]);
+ say(Number.isFinite(mx) && mx > -40 && mx <= 0, `audio peak ${Number.isFinite(mx) ? mx.toFixed(1) : "-inf"} dBFS`, "audible (> -40 dBFS) and not clipped past 0");
+ }
+}
+
// ---------------------------------------------------------------- 2. the first frame's colour
head(2, "FIRST FRAME what the audience's first instant actually looks like");
+const thumb = firstFrameBlank(file);
+if (thumb.unknown) note("thumbnail check skipped", thumb.detail);
+else if (opt.delivery) say(!thumb.blank, "frame 0 (the platform thumbnail) is legible, not near-blank", thumb.detail + (thumb.blank ? " -> render --poster-frame N" : ""));
+else if (thumb.blank) note("WARNING frame 0 is near-blank", `${thumb.detail}; platforms show frame 0 as the thumbnail: render --poster-frame N (pass --delivery to fail on this)`);
+else note("frame 0 is not blank", thumb.detail);
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("")}`;
@@ -80,13 +114,13 @@ if (opt["first-frame"]) {
// ---------------------------------------------------------------- 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 src = resolve(TMP, `source-${FRAME}.png`), dec = resolve(TMP, `decoded-${FRAME}.png`);
+ writeFileSync(src, (await s.frame(FRAME, 0)).png);
+ const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `select=eq(n\\,${FRAME})`, "-vsync", "0", "-frames:v", "1", "-y", dec], { encoding: "utf8" });
+ if (r.status !== 0) die(`ffmpeg could not lift frame ${FRAME}: ${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`);
+ say(v >= +opt["fidelity-psnr"], `decoded frame ${FRAME} vs source frame ${FRAME}: ${v === Infinity ? "inf" : v.toFixed(2)} dB`, `bar ${opt["fidelity-psnr"]} dB`);
}
// ---------------------------------------------------------------- 4. the seam, if it loops
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tsconfig.json b/plugins/anidoodle/skills/anidoodle/engine/tsconfig.json
index 1fe1ad9..25da5d9 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tsconfig.json
+++ b/plugins/anidoodle/skills/anidoodle/engine/tsconfig.json
@@ -1,7 +1,8 @@
{
"compilerOptions": {
"target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx",
- "strict": true, "noEmit": true, "skipLibCheck": true, "esModuleInterop": true, "lib": ["DOM", "ES2022"]
+ "strict": true, "noEmit": true, "skipLibCheck": true, "esModuleInterop": true, "lib": ["DOM", "ES2022"],
+ "rootDirs": ["src", "../example/src"]
},
- "include": ["src"]
+ "include": ["src", "test", "../example/src"]
}
diff --git a/plugins/anidoodle/skills/anidoodle/styles/house/almond-blossom.json b/plugins/anidoodle/skills/anidoodle/styles/house/almond-blossom.json
new file mode 100644
index 0000000..e361050
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/styles/house/almond-blossom.json
@@ -0,0 +1,25 @@
+{
+ "name": "almond-blossom",
+ "title": "Almond-blossom hand",
+ "plate": "engine/src/canvas-core/adaptAlmond.ts",
+ "nearest": "paintedOil",
+ "recipe": {
+ "mark": "opaque oil, a loaded bristle brush, short strokes about a finger long; the ground laid in patches of like-directed strokes that turn against each other; forms painted along their length; lights thick and ridged",
+ "edge": "hard: a broken dark blue-green contour laid last with a small round brush, heavier on the shadow side, long runs that break rarely; nothing blended across an edge",
+ "order": "the ground everywhere first (forms left as bare priming, cast shadows laid darker); forms in their mid tone; lights; the contour; the last thick whites",
+ "paper": "primed linen (#e9e6d8), weave at 0.5 under, 0.22 over",
+ "palette": ["#6aa4b2", "#79b1bb", "#88bcc1", "#97c6c6", "#a9d1cc", "#6f8f74", "#a2bb96", "#f1eedc", "#fbf8ea", "#dc5f30", "#27413c"],
+ "subject rule": "high-key flat decorative ground, one step of shadow on forms, no modelling in depth; no black anywhere: the darkest note is the blue-green contour"
+ },
+ "params": { "groundStep": 19, "groundLen": 58, "groundW": 20, "patchNoise": 0.006, "contourW": 6.5, "contourSkip": 0.05 },
+ "profile": { "file": "anidoodle-research/launch-film/refs/vangogh-almond-blossom.profile.json", "summary": "analyzer's nearest (charcoalErasure, storybook) wrong by eye; nearest by eye paintedOil" },
+ "provenance": {
+ "reference": "Vincent van Gogh, Almond Blossom (1890), Wikimedia Commons, public domain (File:Vincent van Gogh - Almond blossom - Google Art Project.jpg)",
+ "sha256": "6f640dcd79def4223bf16569fd29ca5e37ee9d6cde2670958636e259e2a1c9d0",
+ "broughtBy": "Alex Greenshpun (owner), chosen for the launch film",
+ "date": "2026-09-27",
+ "embedded": false,
+ "copied": "nothing but the hand: no branch, no blossom, no composition; the subject is the launch film's own koi and pond from koi.ts"
+ },
+ "proof": ["anidoodle-research/samples/adapt-teach/almond/adaptAlmond-still.png", "anidoodle-research/samples/adapt-teach/almond/compare-almond.jpg"]
+}