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.

plugin folder under the directory's 512-file hold: engine tests and the worked example stay in the repo, tools say where to get them, sync guards file count and size; 0.9.5

Alex Greenshpun7e0d072e4011
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index bbe2658..5e9a2d2 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -13,7 +13,7 @@
"name": "anidoodle",
"source": "./",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",
- "version": "0.9.4",
+ "version": "0.9.5",
"author": {
"name": "Alex Greenshpun",
"url": "https://linkedin.com/in/alexgreensh"
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index d0a5a4e..47585be 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -2,7 +2,7 @@
"name": "anidoodle",
"displayName": "anidoodle",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",
- "version": "0.9.4",
+ "version": "0.9.5",
"icon": "./assets/icon.png",
"author": {
"name": "Alex Greenshpun",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index dd09e93..21859bb 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle",
- "version": "0.9.4",
+ "version": "0.9.5",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",
"skills": "./skills/",
"interface": {
diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.json
index 30f51b9..6a2080f 100644
--- a/.grok-plugin/marketplace.json
+++ b/.grok-plugin/marketplace.json
@@ -10,7 +10,7 @@
"name": "anidoodle",
"source": "./plugins/anidoodle",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",
- "version": "0.9.4",
+ "version": "0.9.5",
"author": {
"name": "Alex Greenshpun",
"url": "https://linkedin.com/in/alexgreensh"
diff --git a/plugins/anidoodle/.claude-plugin/plugin.json b/plugins/anidoodle/.claude-plugin/plugin.json
index d0a5a4e..47585be 100644
--- a/plugins/anidoodle/.claude-plugin/plugin.json
+++ b/plugins/anidoodle/.claude-plugin/plugin.json
@@ -2,7 +2,7 @@
"name": "anidoodle",
"displayName": "anidoodle",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",
- "version": "0.9.4",
+ "version": "0.9.5",
"icon": "./assets/icon.png",
"author": {
"name": "Alex Greenshpun",
diff --git a/plugins/anidoodle/.codex-plugin/plugin.json b/plugins/anidoodle/.codex-plugin/plugin.json
index dd09e93..21859bb 100644
--- a/plugins/anidoodle/.codex-plugin/plugin.json
+++ b/plugins/anidoodle/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle",
- "version": "0.9.4",
+ "version": "0.9.5",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",
"skills": "./skills/",
"interface": {
diff --git a/plugins/anidoodle/README.md b/plugins/anidoodle/README.md
index 76858a4..4bab377 100644
--- a/plugins/anidoodle/README.md
+++ b/plugins/anidoodle/README.md
@@ -14,18 +14,21 @@ Works in Claude Code, Codex and Grok Build, and in any agent that reads skills.
- The skill writes and runs local Node.js scripts from its `engine/` folder (Node 20 or newer).
- The first render in a new project runs `npm install` for the engine's open-source dependencies (esbuild, playwright-core, typescript, and Remotion for some video work) and downloads a Chromium build with `npx playwright-core install chromium`. Moving pictures also use your local `ffmpeg`.
+- The optional sound pack downloads only when you run `node engine/tools/soundfetch.mjs get <instrument>`. It comes from this project's GitHub release, and every file is checked against a pinned sha256 before it unpacks into `~/.anidoodle/sounds`.
- Nothing else leaves your machine: no telemetry, no accounts, no API keys, and the rendered pages and bundles are checked for network calls.
## Links
- Source, gallery and full docs: https://github.com/alexgreensh/anidoodle
+- The worked example film and the engine's unit tests live in the repository, not in this plugin, to keep it small: clone it to use `scaffold.mjs --example` or `npm test`
- License: Apache-2.0, by Alex Greenshpun
## Notes for directory reviewers
-The directory scan holds one finding, "Uses a credential from the user's machine". It pairs two false matches:
+"Uses a credential from the user's machine" points at `engine/tools/soundfetch.mjs`. It reads three settings, none of them a credential:
-- `engine/src/canvas-core/bake.ts` calls `env.cache.set(...)`. `env` is the renderer's own object and `cache` is its in-memory drawing cache. Nothing reads environment variables or runs `env` or `set` in a shell.
-- `engine/src/canvas-core/adaptAlmond.ts` builds a cache label for lily pad `i` as `pad${i}`. It is a string key, not a command.
+- `ANIDOODLE_SOUNDS`: the folder to install the sound pack into (default `~/.anidoodle/sounds`)
+- `ANIDOODLE_SOUNDS_URL`: where to download the pack from (default this project's GitHub release)
+- `ANIDOODLE_SOUNDS_INDEX_SHA256`: the expected hash of the pack index, for testing a new pack
-anidoodle reads no credentials and sends nothing off the machine. It renders locally with Node, Chromium and ffmpeg, as described above.
+It sends nothing. It only downloads when the user runs `soundfetch.mjs get`, and it refuses any file whose sha256 doesn't match the pinned value. anidoodle reads no tokens or keys and renders locally with Node, Chromium and ffmpeg, as described above.
diff --git a/plugins/anidoodle/skills/anidoodle/engine/package.json b/plugins/anidoodle/skills/anidoodle/engine/package.json
index b7e1a10..a4c3c7c 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/package.json
+++ b/plugins/anidoodle/skills/anidoodle/engine/package.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle-engine",
- "version": "0.9.4",
+ "version": "0.9.5",
"private": true,
"type": "module",
"description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/arc.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/arc.test.ts
deleted file mode 100644
index b6a22d3..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/arc.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-// ARC TESTS. src/canvas-core/music/arc.ts reads the shape of a finished score from its loudness
-// over time. Built signals with a known shape go in; the numbers and the findings must say so.
-// node tools/test.mjs arc
-import { arcReport, arcText } from "../src/canvas-core/music/arc";
-
-export const name = "arc";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const SR = 48000;
- // a steady tone whose level follows `db(t)`: loudness then tracks the envelope and nothing else
- const tone = (seconds: number, db: (t: number) => number) => { const n = Math.round(seconds * SR), x = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / SR; x[i] = Math.pow(10, db(t) / 20) * Math.sin(2 * Math.PI * 997 * t); } return [x, x]; };
- const has = (r: { findings: { msg: string }[] }, s: string) => r.findings.some((f) => f.msg.includes(s));
-
- // 1. a shaped piece: soft way in, a body, one high point on the payoff, an ending that drops away
- const shaped = arcReport(tone(24, (t) => (t < 2.5 ? -30 : t < 9 ? -22 : t < 12 ? -16 : t < 20 ? -22 : t < 22 ? -26 : -40)), SR, { payoffS: 10.5 });
- ok(shaped.peakS > 9 && shaped.peakS < 12, `the loudest moment is found inside the loud section (${shaped.peakS.toFixed(1)} s)`);
- ok(Math.abs(shaped.peakOverMedian - 6) < 0.6 && Math.abs(shaped.introUnderBody - 8) < 1, `the peak reads 6 LU over the body and the way in 8 LU under it (${shaped.peakOverMedian.toFixed(1)}, ${shaped.introUnderBody.toFixed(1)})`);
- ok(shaped.endUnderPeak > 20 && shaped.findings.length === 0, `a shaped piece has nothing to answer (the end sits ${shaped.endUnderPeak.toFixed(0)} LU under the peak)`);
- ok(arcText(shaped).includes("the shape holds") && arcText(shaped).startsWith("ARC"), "the report says so in one line");
-
- // 2. each way a score wanders is named
- const flat = arcReport(tone(24, () => -20), SR);
- ok(has(flat, "nothing is the high point") && has(flat, "little contrast"), "one level from start to finish: no high point, no contrast");
- ok(has(arcReport(tone(24, (t) => (t < 20 ? -24 : -14)), SR), "the ending out-shouts"), "the loudest moment in the last fifth is flagged");
- ok(has(arcReport(tone(24, (t) => (t < 2.5 ? -14 : t < 12 ? -22 : t < 14 ? -17 : t < 22 ? -22 : -40)), SR), "nothing left to build to"), "opening over the body's level is flagged");
- ok(has(arcReport(tone(24, (t) => (t < 2.5 ? -50 : t < 12 ? -22 : t < 14 ? -16 : t < 22 ? -22 : -40)), SR), "nothing happening yet"), "a first 2.5 s far under the rest is flagged");
- ok(has(arcReport(tone(24, (t) => (t < 2.5 ? -30 : t < 9 ? -22 : t < 12 ? -16 : -19)), SR), "only 3.0 LU under"), "an ending that barely comes down is flagged");
- ok(has(arcReport(tone(24, (t) => (t < 2.5 ? -30 : t < 9 ? -22 : t < 12 ? -16 : t < 22 ? -22 : -40)), SR, { payoffS: 18 }), "the picture pays off at 18.0 s"), "a high point away from the picture's payoff is flagged");
-
- // 3. a loop has no beginning and no end: only its seam and its contrast are read
- const loop = arcReport(tone(12, (t) => (t < 6 ? -24 : -18)), SR, { loop: true });
- ok(has(loop, "where the loop comes round") && !has(loop, "out-shouts") && !has(loop, "build to"), `a loop that ends 6 LU over where it starts is flagged at the seam only (${loop.seamJump.toFixed(1)} LU)`);
- ok(arcReport(tone(12, (t) => (t < 4 ? -24 : t < 8 ? -18 : -24)), SR, { loop: true }).findings.length === 0, "a loop that swells in the middle and returns has nothing to answer");
- // a phrase that ends into a quiet bar: the join is no bigger a step than the piece makes inside itself
- const breath = arcReport(tone(12, (t) => (t < 3 ? -30 : t < 6 ? -18 : t < 9 ? -30 : -21)), SR, { loop: true }); ok(breath.seamJump > 3 && breath.insideJump >= breath.seamJump && !has(breath, "comes round"), `a loop whose join steps ${breath.seamJump.toFixed(1)} LU is left alone when it steps ${breath.insideJump.toFixed(1)} LU inside too`);
-
- // 4. short pieces and silence do not crash or nag
- ok(arcReport(tone(3, () => -20), SR).findings.length === 0, "a three-second sting is not asked for an arc");
- const quiet = arcReport([new Float32Array(SR * 2), new Float32Array(SR * 2)], SR); ok(Number.isFinite(quiet.peakS) && quiet.findings.length === 0 && !arcText(quiet).includes("NaN"), "two seconds of silence give finite numbers and no findings");
- const long = arcReport([new Float32Array(SR * 24), new Float32Array(SR * 24)], SR), longLoop = arcReport([new Float32Array(SR * 24)], SR, { loop: true }); ok(long.findings.length === 0 && longLoop.findings.length === 0 && !arcText(long).includes("NaN"), "24 seconds of silence are not told they lack a high point");
- let threw = false; try { arcReport([], SR); } catch { threw = true; } ok(threw, "no channels at all is refused with a message");
- ok(!arcText(arcReport(tone(2, () => -20), SR)).includes("NaN"), "a two-second piece prints no NaN");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/assetKit.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/assetKit.test.ts
deleted file mode 100644
index 0741e77..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/assetKit.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-// ASSET KIT TESTS. Site art's claims: the colour maths round-trips, a brand ramp steps light to dark in
-// its own hue, a page palette keeps every material's light order on a light page and on a dark one, the
-// brand lands only on the part to watch, and a placement's art region never overlaps its headline zone.
-// node tools/test.mjs assetKit
-import { toLab, fromLab, rampFrom, pagePalette, isDark, PLACEMENTS, fitBox, strongPoint } from "../src/canvas-core/assetKit";
-import type { Material } from "../src/canvas-core/mechanismKit";
-
-export const name = "assetKit";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const L = (h: string) => toLab(h)[0], hue = (h: string) => { const [, a, b] = toLab(h); return Math.atan2(b, a); };
- const near = (a: string, b: string) => { const x = parseInt(a.slice(1), 16), y = parseInt(b.slice(1), 16); return [16, 8, 0].every((s) => Math.abs(((x >> s) & 255) - ((y >> s) & 255)) <= 1); };
-
- // 1. colour maths
- ok(["#000000", "#ffffff", "#e4572e", "#3d7bff", "#12151f", "#faf7f2"].every((h) => near(fromLab(toLab(h)), h)), "OKLab round-trips to the same hex");
- ok(Math.abs(L("#ffffff") - 1) < 1e-3 && L("#000000") < 1e-3, "white is lightness 1, black 0");
- ok(/^#[0-9a-f]{6}$/.test(fromLab([0.7, 0.4, 0.4])), "a colour outside sRGB gives up chroma and still comes back as a hex");
- ok(isDark("#12151f") && !isDark("#faf7f2"), "a navy page is dark, an off-white page is light");
-
- // 2. a brand ramp: five tones, dark to light, in the brand's own hue, in either theme
- for (const dark of [false, true]) for (const hex of ["#e4572e", "#3d7bff", "#2a9d5c"]) {
- const r = rampFrom(hex, dark), ls = r.ramp.map(L);
- ok(ls.every((v, i) => !i || v > ls[i - 1] + 0.03), `${hex} ${dark ? "dark" : "light"}: the ramp steps up in lightness (${ls.map((v) => v.toFixed(2)).join(" ")})`);
- ok(r.ramp.every((c) => Math.abs(hue(c) - hue(hex)) < 0.12), `${hex} ${dark ? "dark" : "light"}: every tone keeps the brand's hue`);
- }
- ok(L(rampFrom("#e4572e", true).ramp[4]) < 0.85, "on a dark page the brand's lit top does not glare");
-
- // 3. a page palette keeps light order and puts the brand only on the part to watch
- const zinc: Material = { name: "zinc", ramp: ["#a9a69f", "#bdbab3", "#cfccc4", "#dedbd3", "#f4f1ea"], ink: "#232227", seam: "#8a877f", pigment: "#8d8b86" };
- const watch: Material = { ...zinc, name: "accent", accent: true, pigment: "#d0502a" };
- for (const paper of ["#faf7f2", "#12151f", "#f0f4ff"]) {
- const p = pagePalette({ paper, accent: "#3d7bff" }), z = p(zinc), ls = z.ramp.map(L);
- ok(ls.every((v, i) => !i || v >= ls[i - 1]), `on ${paper}: zinc keeps its light order`);
- ok(isDark(paper) ? ls[0] > L(paper) : ls[4] <= L(paper) + 0.06, `on ${paper}: parts sit ${isDark(paper) ? "above" : "at or below"} the page`);
- ok(!near(p(watch).pigment!, z.pigment!) && Math.abs(hue(p(watch).pigment!) - hue("#3d7bff")) < 0.12, `on ${paper}: the part to watch takes the brand`);
- ok(near(p({ ...zinc }).ramp[2], z.ramp[2]), `on ${paper}: a plain part does not`);
- }
- const ink = pagePalette({ paper: "#faf7f2", colours: { zinc: { hex: "#e4572e", mode: "lines" } } })(zinc);
- ok(Math.abs(hue(ink.ink) - hue("#e4572e")) < 0.12 && near(ink.ramp[2], pagePalette({ paper: "#faf7f2" })(zinc).ramp[2]), "lines mode colours the lines and leaves the part neutral");
- ok(near(pagePalette({ paper: "#f3f0e8" })(zinc).ramp[2], zinc.ramp[2]), "on the kit's own paper nothing moves");
-
- // 4. placements
- for (const [id, p] of Object.entries(PLACEMENTS)) {
- const [x0, y0, x1, y1] = fitBox(p), s = p.safe;
- ok(x0 >= 0 && y0 >= 0 && x1 <= p.W && y1 <= p.H && x1 > x0 && y1 > y0, `${id}: the fit box lies inside the canvas`);
- if (s) ok(x1 <= s.x || x0 >= s.x + s.w || y1 <= s.y || y0 >= s.y + s.h, `${id}: the art never overlaps the headline zone`);
- }
- const st = PLACEMENTS.heroStack, [sx] = strongPoint(st), side = PLACEMENTS.heroSide, [hx] = strongPoint(side);
- ok(Math.abs(sx - (st.art.x + st.art.w / 2)) < 1e-9, "words above: the moment sits on the centre line");
- ok(Math.abs(hx - (side.art.x + side.art.w / 3)) < 1e-9, "words on the left: the moment leans a third toward them");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/avsync.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/avsync.test.ts
deleted file mode 100644
index 05a12a1..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/avsync.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-// AV SYNC TESTS. verify-export measures a delivered file's sound against its master mix and against
-// the picture's own sync frames; these hold the measurements to known answers on synthetic signals.
-// @ts-ignore: a plain ES module shared with the tools
-import { xcorrOffset, onsetNear, toSrt, toVtt } from "../tools/avsync.mjs";
-
-export const name = "avsync";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 48000, n = sr * 3, ref = new Float32Array(n);
- let s = 12345; const rnd = () => ((s = (s * 1103515245 + 12345) >>> 0) / 4294967296) * 2 - 1;
- for (let i = 0; i < n; i++) ref[i] = 0.05 * rnd(); // a noise bed
- const click = (x: Float32Array, at: number) => { for (let k = 0; k < 480; k++) x[at + k] += 0.8 * Math.exp(-k / 60) * Math.sin(k * 0.9); };
- click(ref, sr * 1); click(ref, Math.round(sr * 2.2));
- for (const shift of [0, 7, -13, 96]) {
- const dec = new Float32Array(n); for (let i = 0; i < n; i++) { const j = i - shift; dec[i] = j >= 0 && j < n ? ref[j] : 0; }
- const r = xcorrOffset(ref, dec, 1.0, sr);
- ok(Math.abs(r.lag - shift) < 0.05, `a ${shift}-sample shift (${((shift / sr) * 1000).toFixed(2)} ms) is measured as ${r.lag.toFixed(2)} samples (corr ${r.corr.toFixed(3)})`);
- }
- // a half-sample shift (linear interpolation) is found to a fraction of a sample
- const half = new Float32Array(n); for (let i = 1; i < n; i++) half[i] = 0.5 * (ref[i] + ref[i - 1]);
- ok(Math.abs(xcorrOffset(ref, half, 1.0, sr).lag - 0.5) < 0.2, `a half-sample delay reads as ${xcorrOffset(ref, half, 1.0, sr).lag.toFixed(2)} samples (sub-sample)`);
- ok(Number.isNaN(xcorrOffset(new Float32Array(n), ref, 1.0, sr).ms), "silence has no offset to measure (NaN, never a fake zero)");
- // onsets: the click at 1.000 s is found within a millisecond, and on the decoded copy 7 samples late
- const t1 = onsetNear(ref, 1.0, sr), late = new Float32Array(n); for (let i = 480; i < n; i++) late[i] = ref[i - 480];
- ok(Math.abs(t1 - 1.0) <= 0.001, `the onset of a cue at 1.000 s is found at ${t1.toFixed(4)} s`);
- ok(Math.abs(onsetNear(late, 1.0, sr) - 1.01) <= 0.001, `a cue 10 ms late reads as ${((onsetNear(late, 1.0, sr) - 1) * 1000).toFixed(1)} ms late`);
- ok(Number.isNaN(onsetNear(ref, 1.6, sr)), "no cue near a frame: NaN, not the nearest noise");
- // captions
- const caps = [{ from: 0, to: 45, text: "a lighthouse at sunset, as a print" }, { from: 3600 * 30 + 15, to: 3600 * 30 + 90, text: "One sentence that says what it is, and then a second sentence that wraps" }];
- const srt = toSrt(caps, 30), vtt = toVtt(caps, 30);
- ok(srt.startsWith("1\n00:00:00,000 --> 00:00:01,500\na lighthouse at sunset, as a print\n"), "SubRip: numbered cues, comma milliseconds");
- ok(/01:00:00,500 --> 01:00:03,000\n.{1,42}\n.+\n/.test(srt), "an hour in, and a long line wraps to two");
- ok(vtt.startsWith("WEBVTT\n\n00:00:00.000 --> 00:00:01.500\n"), "WebVTT: the header and dot milliseconds");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/callout.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/callout.test.ts
deleted file mode 100644
index 9142425..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/callout.test.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-// CALLOUT TESTS. calloutPose, calloutReady, leaderPath and checkHandoff in
-// src/canvas-core/callout.ts are pure and are held to numbers here. drawCallout and drawLabel
-// draw through kinetic.ts (writeOn / setType) and are not covered. node tools/test.mjs
-import { CALLOUT_T, calloutPose, calloutReady, checkHandoff, leaderPath, type Callout, type LabelPose } from "../src/canvas-core/callout";
-import type { P } from "../src/canvas-core/core";
-
-export const name = "callout";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
- const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
- const dist = (a: P, b: P) => Math.hypot(a[0] - b[0], a[1] - b[1]);
- const anchor = (): P => [500, 600];
- const base: Callout = { text: "LIVE PREVIEW", anchor, label: { p: [1000, 300], size: 40 }, t0: 60 };
- const same = (a: LabelPose | null, b: LabelPose) => !!a && near(a.p[0], b.p[0]) && near(a.p[1], b.p[1]) && near(a.size, b.size);
-
- // 1. calloutPose: null before t0, the label's own pose until a handoff leaves, exactly the
- // destination pose on `at`
- ok(calloutPose(base, 0) === null && calloutPose(base, 59) === null, "calloutPose is null before t0");
- ok(same(calloutPose(base, 60), base.label) && same(calloutPose({ ...base, out: 100 }, 500), base.label), "without a handoff the pose is the label's, leaving included");
- const hc: Callout = { ...base, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 80 }, arc: 60 } };
- ok(same(calloutPose(hc, 120), base.label), "until leave the pose is still the label's");
- const landed = calloutPose(hc, 150)!;
- ok(near(landed.p[0], 200) && near(landed.p[1], 800) && near(landed.size, 80), "on the handoff frame the pose is exactly the next scene's heading");
- const mid = calloutPose(hc, 135)!; // u = 0.5 -> e = 0.5
- ok(near(mid.p[0], 600) && near(mid.p[1], 550 - 60, 1e-6), "mid-handoff the label sits on the eased midpoint, lifted by the arc");
- ok(near(mid.size, Math.sqrt(40 * 80)), `size is eased as a ratio (${mid.size.toFixed(1)} = the geometric mean, not 60)`);
-
- // 2. calloutReady: the frame the label is fully written
- ok(calloutReady(base) === 60 + CALLOUT_T.text[1] && calloutReady(base) === 90, "calloutReady is t0 + the text's write-on time");
-
- // 3. leaderPath, both registers, label to the right and to the left of the anchor
- const pose: LabelPose = { p: [1000, 300], size: 40 }, w = 300, dot = pose.size * 0.16;
- const drawn = leaderPath(anchor(), pose, w, "drawn");
- ok(drawn.length === 25, "a drawn leader is a 25-point bowed stroke");
- ok(near(dist(drawn[0], anchor()), dot * 2.2), "the drawn line starts off the anchor by the dot gap");
- ok(near(drawn[24][0], 1000 - 40 * 0.35) && near(drawn[24][1], 300 - 40 * 0.42), "the drawn line ends at the label");
- const chord: P = [(drawn[0][0] + drawn[24][0]) / 2, (drawn[0][1] + drawn[24][1]) / 2];
- ok(dist(chord, drawn[12]) > 2, `the drawn line bows off its chord (${dist(chord, drawn[12]).toFixed(1)} px)`);
- const drawnL = leaderPath([1500, 600], pose, w, "drawn");
- ok(near(drawnL[24][0], 1000 + w + 40 * 0.35), "label left of the thing: the drawn line lands on its right edge");
-
- const clean = leaderPath(anchor(), pose, w, "clean");
- ok(clean.length === 3, "a clean leader is an elbow and an underline");
- ok(near(dist(clean[0], anchor()), dot * 2), "the clean line starts off the anchor by the dot gap");
- ok(clean[1][1] === clean[2][1] && near(clean[1][1], 300 + 40 * 0.34), "the underline is horizontal, just under the baseline");
- ok(clean[1][0] <= 1000 && clean[2][0] >= 1300, "the underline spans the label's whole width");
- const cleanL = leaderPath([1500, 600], pose, w, "clean");
- ok(near(cleanL[1][0], 1000 + w + 40 * 0.1) && near(cleanL[2][0], 1000 - 40 * 0.1), "label left of the thing: the elbow meets its right edge and the underline runs left");
-
- // 4. checkHandoff: a matching pose passes; a 5 px miss, an early leave, or a backwards
- // window all throw
- ok(checkHandoff(hc, hc.handoff!.pose).every((g) => g.dp < 1e-6 && g.dr < 1e-6), "a matching pose passes within tolerance");
- ok(throws(() => checkHandoff(hc, { p: [205, 800], size: 80 })), "a 5 px miss throws");
- ok(throws(() => checkHandoff(hc, { p: [200, 800], size: 84 })), "a 4 px size miss throws");
- const early: Callout = { ...base, handoff: { leave: 80, at: 150, pose: { p: [200, 800], size: 80 } } };
- ok(throws(() => checkHandoff(early, { p: [200, 800], size: 80 })), "leaving at 80, before the label is readable at 90, throws");
- const back: Callout = { ...base, handoff: { leave: 160, at: 150, pose: { p: [200, 800], size: 80 } } };
- ok(throws(() => checkHandoff(back, { p: [200, 800], size: 80 })), "landing before it leaves throws");
- ok(throws(() => checkHandoff(base, { p: [0, 0], size: 10 })), "a callout with no handoff has nothing to check: throws");
-
- // 5. checkHandoff needs the dot and line's CALLOUT_T.leave frames to retract: a shorter
- // trip throws even when the pose matches, exactly CALLOUT_T.leave frames is legal
- const tight: Callout = { ...base, handoff: { leave: 130, at: 141, pose: { p: [200, 800], size: 80 } } };
- ok(throws(() => checkHandoff(tight, { p: [200, 800], size: 80 })), `a handoff trip under ${CALLOUT_T.leave} frames throws even with a matching pose`);
- const just: Callout = { ...base, handoff: { leave: 130, at: 130 + CALLOUT_T.leave, pose: { p: [200, 800], size: 80 } } };
- ok(!throws(() => checkHandoff(just, { p: [200, 800], size: 80 })), `a trip of exactly ${CALLOUT_T.leave} frames is legal`);
-
- // 6. calloutPose with a size of 0 on either side falls back to a linear ease: finite numbers
- const zeroA: Callout = { ...base, label: { p: [1000, 300], size: 0 }, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 80 } } };
- const zeroB: Callout = { ...base, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 0 } } };
- for (const c of [zeroA, zeroB]) for (const f of [120, 135, 149, 150]) {
- const p = calloutPose(c, f)!;
- ok(Number.isFinite(p.p[0]) && Number.isFinite(p.p[1]) && Number.isFinite(p.size), `a size of 0 gives finite numbers through the handoff (f=${f})`);
- }
- ok(near(calloutPose(zeroA, 135)!.size, 40), "0 -> 80 eases linearly through 40 at the midpoint");
-
- // 7. leaderPath's `side` pins which edge the line meets, wherever the anchor sits
- ok(near(leaderPath([500, 600], pose, w, "drawn", undefined, false)[24][0], 1000 + w + 40 * 0.35), "side=false: the drawn line meets the label's right edge though the anchor is left of it");
- ok(near(leaderPath([1500, 600], pose, w, "drawn", undefined, true)[24][0], 1000 - 40 * 0.35), "side=true: the drawn line meets the label's left edge though the anchor is right of it");
- const pinned = leaderPath([500, 600], pose, w, "clean", undefined, false);
- ok(near(pinned[1][0], 1000 + w + 40 * 0.1) && near(pinned[2][0], 1000 - 40 * 0.1), "side=false pins the clean elbow and underline the same way");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/camera.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/camera.test.ts
deleted file mode 100644
index 8fe8a50..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/camera.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-// 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, dollyZoom, EASE, heroScale, 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. lens zoom is not a dolly: the lens scales every plane by one factor, the dolly changes parallax
- const base: Cam = { look: [0, 0], zoom: 1.5 }, lensed: Cam = { ...base, lens: 2 }, dollied: Cam = { look: [0, 0], zoom: 3 };
- ok(near(heroScale(lensed), 3) && near(heroScale(dollied), 3) && near(heroScale(base), 1.5), "hero-plane scale is dolly x lens (a lens of 2 and a dolly to 3 frame the hero the same)");
- ok([0.5, 1, 3, -0.2].every((z) => near(planeScale(lensed, z) / planeScale(base, z), 2)), "a lens zoom grows every depth by the same factor: the depth relationships do not change");
- ok(planeScale(dollied, 3) / planeScale(dollied, 0) < planeScale(base, 3) / planeScale(base, 0), "a dolly in to the same hero size shrinks the far plane relative to the hero: parallax changes");
- ok(near(strokeWeight(lensed), Math.pow(3, 0.35)), "stroke weight follows the screen scale, lens included");
- const lc = new Camera([540, 540], [{ f: 0, look: [0, 0], zoom: 1 }, { f: 60, lens: 1 }, { f: 120, lens: 4 }]);
- ok(near(lc.at(90).lens!, 2) && near(lc.at(90).zoom, 1) && near(lc.at(0).lens!, 1), "lens keys ease in log2 like the dolly (midpoint of 1 -> 4 is 2) and hold before their first key");
- ok(JSON.stringify(Object.keys(cam.at(45))) === JSON.stringify(["look", "zoom"]), "a camera that never sets a lens answers exactly as before (no lens field)");
- lc.shake({ from: 80, to: 110, amp: 10, seed: 3 }); // inside the lens move, so the lens is not 1 where the shake is measured
- let lensErr = 0, lensTrip = 0, shakePx = 0;
- for (const f of [5, 70, 85, 100]) for (const z of [0, 1.5, -0.25]) {
- lc.begin(g, f, z); const [a, b, c, d, e, ff] = T; lc.end(g);
- for (const q of [[0, 0], [300, -120]] as P[]) { const s = lc.toScreen(q, f, z), m = [a * q[0] + c * q[1] + e, b * q[0] + d * q[1] + ff]; lensErr = Math.max(lensErr, Math.hypot(s[0] - m[0], s[1] - m[1])); const w = lc.toWorld(s, f, z); lensTrip = Math.max(lensTrip, Math.hypot(w[0] - q[0], w[1] - q[1])); }
- }
- { const sh = lc.shaken(85), cl = lc.at(85), [dx, dy] = lc.shakeAt(85); shakePx = Math.hypot((cl.look[0] - sh.look[0]) * heroScale(sh) - dx, (cl.look[1] - sh.look[1]) * heroScale(sh) - dy); }
- ok(lensErr < 1e-6 && lensTrip < 1e-6, "with a lens, begin() and toScreen() still agree and toWorld inverts them");
- ok(lc.at(85).lens! > 1.2 && Math.hypot(...lc.shakeAt(85).slice(0, 2) as [number, number]) > 0.5 && shakePx < 1e-9 && lc.shaken(70).lens !== undefined, "shake stays in screen px under a lens, and the shaken camera keeps its lens");
-
- // 9. the dolly zoom: the hero plane holds its size while the depth stretches
- const dolly = new Camera([540, 540], [{ f: 0, look: [0, 0], zoom: 1 }, { f: 60, zoom: 3 }]), vz = dollyZoom((f) => dolly.at(f));
- ok([0, 15, 30, 45, 60].every((f) => near(heroScale(vz(f)), 1, 1e-12)), "dollyZoom holds the hero plane's screen scale on every frame");
- ok(planeScale(vz(60), 2) < planeScale(vz(0), 2) * 0.6, `dollying in, the far plane falls away behind the subject (${planeScale(vz(0), 2).toFixed(3)} -> ${planeScale(vz(60), 2).toFixed(3)})`);
- const out = new Camera([540, 540], [{ f: 0, look: [0, 0], zoom: 2 }, { f: 60, zoom: 0.8 }]), vo = dollyZoom((f) => out.at(f), { at: 0 });
- ok(near(heroScale(vo(60)), 2) && planeScale(vo(60), 2) > planeScale(vo(0), 2), "dollying out, the hero holds and the background looms");
- ok(near(heroScale(dollyZoom((f) => dolly.at(f), { hold: 2.5 })(30)), 2.5), "hold sets the size to keep");
- const asPath = new Camera([540, 540], [], { path: vz });
- ok(near(heroScale(asPath.shaken(40)), 1) && asPath.toScreen([0, 0], 40)[0] === 540, "a dolly zoom drives a Camera as a path, with shake and projections intact");
-
- // 10. 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");
- { const extra = new Camera([0, 0], [], { path: () => ({ look: [0, 0], zoom: 1, extra: 1 } as unknown as Cam) }); ok(JSON.stringify(Object.keys(extra.shaken(0))) === JSON.stringify(["look", "zoom", "rot"]), "shaken() returns only the camera's own fields"); }
- ok(throws(() => new Camera([0, 0], [{ f: 0, zoom: Infinity }])), "rejects an endless zoom");
- ok(throws(() => new Camera([0, 0], [{ f: 0, zoom: 1, lens: 0 }])) && throws(() => new Camera([0, 0], [{ f: 0, zoom: 1, lens: NaN }])) && throws(() => new Camera([0, 0], [{ f: 0, zoom: NaN }])), "rejects a lens <= 0, or a lens or zoom that is not a number");
- ok(throws(() => dollyZoom((f) => dolly.at(f), { hold: 0 })) && throws(() => dollyZoom(() => ({ look: [0, 0], zoom: 0 }))), "dollyZoom refuses a size of 0 to hold, or a dolly at zoom 0");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/delivery.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/delivery.test.ts
deleted file mode 100644
index 655753a..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/delivery.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-// DELIVERY TESTS. The whole film mix lands on its loudness target under the -1 dBTP ceiling, a quiet
-// effects-only film is brought to the target, the limiter's work is capped (the gain gives way and says
-// so), and "none" leaves the mix alone.
-// node tools/test.mjs delivery
-import { deliver, targetOf } from "../src/canvas-core/music/delivery";
-import { loudness, truePeak } from "../src/canvas-core/music/meter";
-import { mixSfx } from "../src/canvas-core/music/sfxMix";
-// @ts-ignore: a plain ES module shared with the tools
-import { filmShape } from "../tools/filmshape.mjs";
-
-export const name = "delivery";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 48000, n = sr * 4;
- const tone = (amp: number, hits = false) => { const L = new Float32Array(n), R = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr, h = hits ? (i % (sr / 2) < 200 ? 0.9 : 0) : 0, v = amp * Math.sin(2 * Math.PI * 220 * t) * (0.6 + 0.4 * Math.sin(2 * Math.PI * 0.5 * t)) + h * Math.sin(2 * Math.PI * 3000 * t); L[i] = v; R[i] = v * 0.95; } return [L, R] as [Float32Array, Float32Array]; };
-
- for (const mode of ["gentle", "dense"] as const) {
- const [L, R] = tone(0.01), d = deliver(L, R, sr, mode);
- ok(Math.abs(d.lufs - targetOf(mode)) <= 0.5 && d.dbtp <= -1 + 1e-6, `${mode}: a quiet mix lands on ${targetOf(mode)} LUFS (${d.lufs.toFixed(2)}) under -1 dBTP (${d.dbtp.toFixed(2)})`);
- }
- const [L2, R2] = tone(0.002, true), d2 = deliver(L2, R2, sr, "gentle");
- ok(d2.limitDb <= 4 + 0.1 && d2.dbtp <= -1 + 1e-6, `sharp hits over near silence: the limiter takes at most 4 dB (${d2.limitDb.toFixed(2)})`);
- ok(d2.shortLu < 0.1 || d2.limitDb > 3.8, `and uses its allowance before falling short (${d2.limitDb.toFixed(2)} dB limited, ${d2.shortLu.toFixed(2)} LU short)`);
- ok(Math.abs(d2.shortLu - Math.max(0, -16 - d2.lufs)) < 1e-9, `and any shortfall is reported (${d2.shortLu.toFixed(2)} LU short)`);
- const [L3, R3] = tone(0.3), before = L3.slice(), d3 = deliver(L3, R3, sr, "none");
- ok(d3.gainDb === 0 && L3.every((v, i) => v === before[i]), "none leaves the mix untouched");
- ok(Math.abs(loudness(tone(0.01), sr).integrated - loudness(tone(0.01), sr).integrated) < 1e-12, "the master is deterministic in, deterministic out");
-
- // an effects-only film is delivered at the gentle target
- const fx = mixSfx(null, { fps: 30, frames: 120, cues: [{ frame: 10, kind: "tick" }, { frame: 40, kind: "pop" }, { frame: 80, kind: "impact" }] } as never, sr);
- ok(fx.delivered !== undefined && fx.dbtp <= -1 + 1e-6, `effects-only mix: delivered (${fx.lufs.toFixed(1)} LUFS, ${fx.dbtp.toFixed(2)} dBTP, limiter ${fx.limiterDb.toFixed(1)} dB)`);
- const old = mixSfx(null, { fps: 30, frames: 120, master: "none", cues: [{ frame: 10, kind: "tick" }, { frame: 40, kind: "pop" }, { frame: 80, kind: "impact" }] } as never, sr);
- ok(Math.abs(fx.lufs + 16) <= 0.5, `on target (the peak-only master gives ${old.lufs.toFixed(1)} LUFS)`);
- void truePeak;
-
- // between its cues an effects-only film sits on room tone, never on digital silence
- const sparse = { fps: 30, frames: 240, cues: [{ frame: 6, kind: "tick" }, { frame: 150, kind: "impact" }] } as never;
- const bedded = mixSfx(null, sparse, sr), bare = mixSfx(null, { ...(sparse as object), bed: false } as never, sr);
- ok(filmShape(bare.L, bare.R, sr).problems.some((p: { kind: string }) => p.kind === "hole"), "without a bed, two cues 5 s apart leave a hole");
- ok(!filmShape(bedded.L, bedded.R, sr).problems.some((p: { kind: string }) => p.kind === "hole"), "with room tone the hole is gone");
- let c = 0, l2 = 0, r2 = 0; for (let i = sr; i < 3 * sr; i++) { c += bedded.L[i] * bedded.R[i]; l2 += bedded.L[i] ** 2; r2 += bedded.R[i] ** 2; }
- ok(c / Math.sqrt(l2 * r2) > 0.7, `room tone is nearly mono, so a phone keeps it (correlation ${(c / Math.sqrt(l2 * r2)).toFixed(2)})`);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/drums.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/drums.test.ts
deleted file mode 100644
index 71a28cd..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/drums.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-// DRUM KIT TESTS (music/drums.ts): the anti-MIDI checks from the music research (section 9) that a
-// kit can fail on its own, with no human: determinism, no two hits alike, velocity changes the
-// timbre (not just the level), open hats choke, pieces sit where the stage puts them, the low end
-// stays mono, GM notes and lane kinds pick the right piece, and the legacy kit is untouched.
-import { kitVoice, timpani, pieceOf, chokeTimes, KITS, type KitId } from "../src/canvas-core/music/drums";
-import { drumVoice, kick as legacyKick } from "../src/canvas-core/music/instruments";
-import { laneKind } from "../src/canvas-core/music/grooves";
-import type { Played } from "../src/canvas-core/music/perform";
-import { rng } from "../src/canvas-core/core";
-
-export const name = "drums";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const SR = 24000, hit = (t: number, v: number, p = 60, kind?: string): Played => ({ t, off: t + 0.2, p, v, role: "drum", kind, w: v });
- const render = (inst: string, keys: Played[], kit: KitId, seed = 1, secs = 3, extra: Record<string, number | boolean | string> = {}) => kitVoice(inst, keys, SR, Math.round(secs * SR), { kit, grid: true, ...extra }, rng(seed), { choke: chokeTimes([{ inst, opts: { kit, ...extra }, keys }]) });
- const seg = (x: Float32Array, t: number, ms: number) => x.subarray(Math.round(t * SR), Math.round(t * SR) + Math.round((ms / 1000) * SR));
- const corr = (a: Float32Array, b: Float32Array) => { let ab = 0, aa = 0, bb = 0; for (let i = 0; i < a.length; i++) { ab += a[i] * b[i]; aa += a[i] * a[i]; bb += b[i] * b[i]; } return ab / Math.sqrt(aa * bb + 1e-30); };
- const rms = (x: Float32Array) => { let s = 0; for (const v of x) s += v * v; return Math.sqrt(s / Math.max(1, x.length)); };
- // spectral centroid by zero-crossing-free proxy: the share of energy in the first difference (a tilt meter)
- const bright = (x: Float32Array) => { let d = 0, e = 0; for (let i = 1; i < x.length; i++) { d += (x[i] - x[i - 1]) ** 2; e += x[i] ** 2; } return d / (e + 1e-30); };
- const finite = (o: { L: Float32Array; R: Float32Array }) => { let m = 0; for (const x of [o.L, o.R]) for (const v of x) { if (!Number.isFinite(v)) return false; m = Math.max(m, Math.abs(v)); } return m < 4; };
-
- // 1. determinism, finite output, every piece of every kit sounds
- const GM = [36, 38, 37, 40, 39, 42, 44, 46, 41, 45, 48, 49, 51, 53, 54, 56, 70, 61, 62, 64];
- let silent: string[] = [], same = true, sane = true;
- for (const kit of KITS) {
- const keys = GM.map((p, i) => hit(i * 0.35, 0.8, p)), a = render("snare", keys, kit, 7, GM.length * 0.35 + 2), b = render("snare", keys, kit, 7, GM.length * 0.35 + 2);
- same &&= a.L.every((v, i) => v === b.L[i]) && a.R.every((v, i) => v === b.R[i]); sane &&= finite(a);
- GM.forEach((p, i) => { if (rms(seg(a.L, i * 0.35 + 0.02, 60)) + rms(seg(a.R, i * 0.35 + 0.02, 60)) < 1e-5) silent.push(`${kit}:${p}`); });
- }
- ok(same, "same keys + seed = identical samples, every kit");
- ok(sane, "every kit renders finite, bounded output");
- ok(silent.length === 0, `every GM piece of every kit sounds${silent.length ? ` (silent: ${silent.join(", ")})` : ""}`);
-
- // 2. no clones: the same piece at the same velocity, eight times, never repeats a waveform. Clone score (research sec. 9):
- // the mean correlation of a repeat with the first hit < 0.98 per piece, and no pair ever near-identical (< 0.998)
- let worstMean = 0, worstMax = 0, worstAt = "";
- for (const kit of KITS) for (const [inst, p] of [["kick", 60], ["snare", 60], ["hat", 60], ["hat", 46], ["snare", 39], ["snare", 45], ["hat", 51], ["hat", 70]] as [string, number][]) {
- const keys = Array.from({ length: 8 }, (_, i) => hit(i * 0.5, 0.75, p)), o = render(inst, keys, kit, 3, 4.6), cs: number[] = [];
- for (let i = 1; i < 8; i++) cs.push(corr(seg(o.L, 0, 80), seg(o.L, i * 0.5, 80)));
- const mean = cs.reduce((a, b) => a + b, 0) / cs.length; if (mean > worstMean) { worstMean = mean; worstAt = `${kit} ${inst}/${p}`; } worstMax = Math.max(worstMax, ...cs);
- }
- ok(worstMean < 0.98 && worstMax < 0.998, `repeated hits never clone: worst mean correlation ${worstMean.toFixed(3)} (${worstAt}) < 0.98, closest pair ${worstMax.toFixed(3)} < 0.998`);
-
- // 3. velocity changes the timbre: a hard snare / hat is brighter than a soft one (level-independent measure)
- const vb = (inst: string, kit: KitId) => { const S = 48000, o = kitVoice(inst, [hit(0, 0.25), hit(1, 1)], S, S * 2, { kit, grid: true }, rng(5)), at = (t: number) => o.L.subarray(t * S, t * S + 0.12 * S); return [bright(at(0)), bright(at(1))]; };
- const vbad = KITS.flatMap((kit) => (["snare", "hat", "kick"] as const).filter((i) => { const [s, h] = vb(i, kit); return !(h > s * 1.03); }).map((i) => `${kit} ${i}`));
- ok(vbad.length === 0, `velocity -> brightness on kick, snare, hat of every kit${vbad.length ? ` (flat: ${vbad.join(", ")})` : ""}`);
-
- // 4. choke: a closed hat stops an open hat
- { const open = render("hat", [hit(0, 0.8, 46)], "acoustic", 2, 1.5), choked = render("hat", [hit(0, 0.8, 46), hit(0.3, 0.05, 44)], "acoustic", 2, 1.5);
- const tail = (o: { L: Float32Array }) => rms(seg(o.L, 0.4, 300));
- ok(tail(choked) < tail(open) * 0.05, `an open hat is choked by the pedal hat (tail ${(20 * Math.log10(tail(choked) / tail(open))).toFixed(0)} dB)`); }
-
- // 5. the stage: hats right, ride and floor tom left, kick centred and mono in the lows
- { const side = (inst: string, p: number) => { const o = render(inst, [hit(0, 0.8, p)], "acoustic", 4, 1.2); return 20 * Math.log10(rms(o.R) / rms(o.L)); };
- const hr = side("hat", 42), rd = side("hat", 51), ft = side("snare", 41), kk = side("kick", 36);
- ok(hr > 2 && rd < -2 && ft < -2 && Math.abs(kk) < 1, `stage: hat R ${hr.toFixed(1)} dB, ride ${rd.toFixed(1)}, floor tom ${ft.toFixed(1)}, kick ${kk.toFixed(1)}`);
- const k = render("kick", [hit(0, 0.9, 36)], "acoustic", 4, 1), lo = (x: Float32Array) => { const y = new Float32Array(x.length); let z = 0; const a = 1 - Math.exp((-2 * Math.PI * 120) / SR); for (let i = 0; i < x.length; i++) { z += a * (x[i] - z); y[i] = z; } return y; };
- const icc = corr(lo(k.L), lo(k.R)); ok(icc > 0.95, `kick below 120 Hz stays mono (ICC ${icc.toFixed(3)})`);
- const cr = render("hat", [hit(0, 0.9, 49)], "acoustic", 4, 2.5), hi = corr(seg(cr.L, 0.05, 800), seg(cr.R, 0.05, 800)); ok(hi < 0.9, `a crash is wide (L/R correlation ${hi.toFixed(2)} < 0.9)`); }
-
- // 6. notes pick pieces: GM pitch > the part's piece > the lane kind > the inst's own piece
- ok(pieceOf({ p: 60 }, "hat", {}) === "hat" && pieceOf({ p: 60 }, "snare", { rim: true }) === "cross" && pieceOf({ p: 60, kind: "o" }, "hat", {}) === "open" && pieceOf({ p: 49 }, "snare", {}) === "crash" && pieceOf({ p: 60, kind: "ride" }, "hat", { piece: "shaker" }) === "shaker", "pieceOf: GM notes, part piece, kinds, inst defaults");
- ok(laneKind({ family: "fourFloor" }, "snare") === "clap" && laneKind({ family: "swing" }, "hat") === "ride" && laneKind({ kick: ["C4:4"] }, "hat") === "hat", "lane kinds: a fourFloor snare lane is a clap, a swing hat lane a ride, written grooves keep their lanes");
-
- // 7. timpani: pitched (energy peaks near the written note), a roll is many strokes, deterministic
- { const t = timpani([hit(0, 0.8, 43)], SR, SR * 3, {}, rng(1)), f = 440 * Math.pow(2, (43 - 69) / 12), x = seg(t.L, 0.1, 500);
- const mag = (hz: number) => { let c = 0, s = 0; for (let i = 0; i < x.length; i++) { c += x[i] * Math.cos((2 * Math.PI * hz * i) / SR); s += x[i] * Math.sin((2 * Math.PI * hz * i) / SR); } return Math.hypot(c, s); };
- ok(mag(f) > 3 * mag(f * 1.25) && mag(f) > 3 * mag(f * 0.8), `timpani rings at its note (${f.toFixed(0)} Hz)`);
- const a = timpani([{ ...hit(0, 0.8, 43), off: 2, kind: "roll" }], SR, SR * 3, {}, rng(1)), b = timpani([{ ...hit(0, 0.8, 43), off: 2, kind: "roll" }], SR, SR * 3, {}, rng(1));
- ok(a.L.every((v, i) => v === b.L[i]) && rms(seg(a.L, 1.5, 200)) > 4 * rms(seg(t.L, 1.5, 200)), "a timpani roll sustains (many strokes), deterministically"); }
-
- // 8. legacy: the frozen launch film's kit is the old voice, bit for bit
- { const keys = [hit(0, 0.8), hit(0.5, 0.6)], a = drumVoice("kick", keys, SR, SR, { legacy: true }, rng(1)), b = legacyKick(keys, SR, SR, {});
- ok(a.L.every((v, i) => v === b.L[i]), "legacy: true renders the original soft kit"); }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/facts.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/facts.test.ts
deleted file mode 100644
index adde572..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/facts.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-// FACTS TESTS. Every claim a film declares must be listed in facts.json with its source, or labelled
-// generated; nothing invented. Held to known answers, with the failing cases.
-// @ts-ignore: a plain ES module shared with the tools
-import { checkFacts, entryProblems, normClaim, EMPTY_FACTS } from "../tools/factsrules.mjs";
-import { makeLaunchFilm } from "../src/canvas-core/launchTemplate";
-import type { Film } from "../src/canvas-core/film";
-import exampleLedger from "../facts/launchExample.json";
-import cleanLedger from "../facts/launchExampleClean.json";
-import { launchExample } from "../src/canvas-core/launchExample";
-import { launchExampleClean } from "../src/canvas-core/launchExampleClean";
-
-export const name = "facts";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const src = { sentence: "Setup takes about 40 minutes.", url: "https://example.com/docs" };
- const good = { claim: "Ships in 40 minutes.", where: "on-screen", source: src };
- const slogan = { claim: "IDEA IN.", where: "on-screen", generated: true, note: "slogan written for this film" };
- const facts = { version: 1, claims: [good, slogan] };
- ok(normClaim(" Ships IN 40 minutes! ") === normClaim("ships in 40 minutes."), "claims match ignoring case, spacing and end punctuation");
- ok(checkFacts(["Ships in 40 minutes.", "IDEA IN."], facts).status === "PASS", "every claim listed with a source or labelled generated passes");
- ok(checkFacts([], facts).status === "N/A" && checkFacts(undefined, facts).status === "N/A", "a film that declares no claims is N/A, never a pass");
-
- const missing = checkFacts(["Ships in 40 minutes.", "Loved by 10,000 teams."], facts);
- ok(missing.status === "FAIL" && missing.problems.length === 1 && /not listed/.test(missing.problems[0].why), "NEGATIVE: a claim missing from facts.json fails");
- ok(checkFacts(["IDEA IN."], null).status === "FAIL", "NEGATIVE: claims with no facts.json fail");
- ok(checkFacts(["IDEA IN."], EMPTY_FACTS).status === "FAIL", "NEGATIVE: the empty scaffold fails until the claims are listed");
- ok(checkFacts(["TODO CLAIM."], { claims: [{ claim: "TODO CLAIM.", generated: true, note: "x" }] }).status === "FAIL", "NEGATIVE: a TODO is not a claim");
-
- const bad = (e: object) => entryProblems(e).join("; ");
- ok(/source.sentence/.test(bad({ claim: "c", source: { url: "https://a.b" } })), "NEGATIVE: a sourced claim needs the exact sentence");
- ok(/source.url or source.file/.test(bad({ claim: "c", source: { sentence: "c" } })), "NEGATIVE: a sourced claim needs a URL or a file");
- ok(bad({ claim: "c", source: { sentence: "c", file: "notes/brief.md#2" } }) === "", "a file is a source too");
- ok(/not an http/.test(bad({ claim: "c", source: { sentence: "c", url: "ftp://x" } })), "NEGATIVE: a source URL is http(s)");
- ok(/no note/.test(bad({ claim: "c", generated: true })), "NEGATIVE: generated content must say what it is");
- ok(/states a number/.test(bad({ claim: "5 stars", generated: true, note: "n" })), "NEGATIVE: a generated claim cannot state a number (no invented ratings or prices)");
- ok(/states 99/.test(bad({ claim: "Saves 99% of time", source: src })), "NEGATIVE: a number the source sentence does not contain is caught");
- ok(bad({ claim: "Takes 40 minutes", source: src }) === "", "a number that is in the source passes");
- ok(checkFacts(["Ships in 40 minutes."], { claims: [{ ...good, source: { ...src, sentence: "" } }] }).status === "FAIL", "an entry with an empty sentence fails");
- ok(checkFacts(["IDEA IN."], { claims: [slogan, { claim: "Narrated: best in class", where: "narration" }] }).status === "FAIL", "NEGATIVE: a narrated claim listed with no source fails too");
-
- // the launch template declares its claims: the type-frame words, the split words and the tagline
- const plate: Film = { meta: { title: "plate", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: 60 }, assets: { images: {} }, shots: [{ id: "p", start: 0, end: 60, draw: () => {} }] };
- const film = makeLaunchFilm({ title: "Tally", asks: [{ prompt: "draw it", plate, label: "l" }, { prompt: "again", plate, label: "l" }], words: [[{ text: "ONE.", style: "ink", color: "#111" }, { text: "TWO.", style: "ink", color: "#111" }]], tagline: "Counts things.", install: ["npm i tally"], bpm: 120, askBeats: 8, endBeats: 12, sfx: false, score: null, claims: ["Fast.", "ONE."] });
- ok(film.claims.join("|") === "ONE.|TWO.|Counts things.|Fast.", `a launch film declares its words, tagline and extra claims once each (${film.claims.join("|")})`);
- ok(film.reshape("9x16").claims.join("|") === film.claims.join("|"), "the claims are the same in every shape");
- ok(!film.claims.includes("draw it") && !film.claims.includes("npm i tally"), "prompts and install lines are not claims");
- // the shipped examples carry their own ledgers (facts/<film>.json), so launch.mjs ship passes for them
- for (const [nm, f, ledger] of [["launchExample", launchExample, exampleLedger], ["launchExampleClean", launchExampleClean, cleanLedger]] as const) {
- const r = checkFacts(f.claims, ledger);
- ok(r.status === "PASS" && ledger.claims.every((e: { generated?: boolean }) => e.generated === true), `${nm}: its ${r.checked} claims are all in facts/${nm}.json, labelled generated (${r.problems.map((p: { why: string }) => p.why).join("; ") || "no problems"})`);
- }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/filmshape.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/filmshape.test.ts
deleted file mode 100644
index 0a3c069..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/filmshape.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-// FILM SHAPE TESTS. A finished film's sound starts with the picture, never drops out, and ends with it;
-// a silence the film declares in meta.quiet is not a fault.
-// node tools/test.mjs filmshape
-// @ts-ignore: a plain ES module shared with the tools
-import { filmShape } from "../tools/filmshape.mjs";
-
-export const name = "filmshape";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 8000, film = (secs: number, on: (t: number) => boolean) => { const n = sr * secs, L = new Float32Array(n), R = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr, v = on(t) ? 0.2 * Math.sin(2 * Math.PI * 330 * t) : 0; L[i] = v; R[i] = v; } return [L, R] as const; };
- const kinds = (r: ReturnType<typeof filmShape>) => r.problems.map((p: { kind: string }) => p.kind).join(",");
- ok(kinds(filmShape(...film(6, () => true), sr)) === "", "sound from start to end: a finished shape");
- ok(kinds(filmShape(...film(6, (t) => t > 1.2), sr)) === "late start", "a film that starts 1.2 s late is caught");
- const dead = filmShape(...film(16, (t) => t < 5.4), sr);
- ok(kinds(dead) === "dead end" && Math.abs(dead.endS - 10.6) < 0.15, `sound that stops at 5.4 s of 16 is a dead end (${dead.endS.toFixed(1)} s)`);
- const hole = filmShape(...film(8, (t) => t < 3.1 || t > 6.4), sr);
- ok(kinds(hole) === "hole" && Math.abs(hole.holeS - 3.3) < 0.15, `a 3.3 s hole in the middle is caught (${hole.holeS.toFixed(1)} s)`);
- ok(kinds(filmShape(...film(8, (t) => t < 3.1 || t > 3.3), sr)) === "", "a 0.2 s breath is not a hole");
- ok(kinds(filmShape(...film(8, (t) => t < 3.1 || t > 4.0), sr, { fps: 30, quiet: [[90, 123, "a held breath before the reveal"]] })) === "", "a declared held breath is not a fault");
- ok(kinds(filmShape(...film(4, () => false), sr)) === "silent", "a silent film is caught");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/ctx-filter.mjs b/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/ctx-filter.mjs
deleted file mode 100644
index ec731ba..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/ctx-filter.mjs
+++ /dev/null
@@ -1 +0,0 @@
-export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: (frame) => { const ctx = {}; ctx.filter = "blur(1px)"; return frame; } };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/dead-loop.mjs b/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/dead-loop.mjs
deleted file mode 100644
index 798895e..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/dead-loop.mjs
+++ /dev/null
@@ -1 +0,0 @@
-export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: () => "same" };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/declared-hold.mjs b/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/declared-hold.mjs
deleted file mode 100644
index 8e34913..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/declared-hold.mjs
+++ /dev/null
@@ -1 +0,0 @@
-export default { expected: "PASS", meta: { fps: 4, durationFrames: 8, holds: [[6, 8]] }, render: (frame) => Math.min(frame, 5) };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/math-random.mjs b/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/math-random.mjs
deleted file mode 100644
index 199700d..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/math-random.mjs
+++ /dev/null
@@ -1 +0,0 @@
-export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: (frame) => `${frame}-${Math.random()}` };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/on-twos.mjs b/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/on-twos.mjs
deleted file mode 100644
index ceab668..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/on-twos.mjs
+++ /dev/null
@@ -1 +0,0 @@
-export default { expected: "PASS", meta: { fps: 4, durationFrames: 8, onTwos: true }, render: (frame) => Math.floor(frame / 2) };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/order-cache.mjs b/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/order-cache.mjs
deleted file mode 100644
index 105aacf..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/fixtures/order-cache.mjs
+++ /dev/null
@@ -1 +0,0 @@
-export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: (frame, cache) => { if (!cache.has("first")) cache.set("first", frame); return `${frame}:${cache.get("first")}`; } };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/guards.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/guards.test.ts
deleted file mode 100644
index efc54d5..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/guards.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-// GUARD TESTS. A declared breath section is authored silence: the ghost guard must not judge it, and
-// guardReport must actually hand those spans to ghostCheck (it once did not, so every score with a
-// breath failed on its own silence).
-// node tools/test.mjs guards
-import { breathSpans, ghostCheck } from "../src/canvas-core/music/guards";
-import type { Rendered } from "../src/canvas-core/music/render";
-
-export const name = "guards";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const SR = 8000, bpm = 120, spb = 0.5;
- // 1. breathSpans reads breath sections only, in seconds at the piece's tempo
- const r = { piece: { arrangement: [{ kind: "groove", from: 0, bars: 2 }, { kind: "breath", from: 2, bars: 2 }, { kind: "drop", from: 4, bars: 1 }] }, perf: { sec: (beat: number) => beat * spb } } as unknown as Pick<Rendered, "piece" | "perf">;
- const sp = breathSpans(r, 4);
- ok(sp.length === 1 && Math.abs(sp[0][0] - 3.999) < 1e-9 && Math.abs(sp[0][1] - 8.001) < 1e-9, `one breath, bars 2-4 = 4 s to 8 s, padded 1 ms (${JSON.stringify(sp)})`);
- // 2. a held, onset-free pad is formless; inside a declared breath it is not judged
- const n = SR * 8, x = new Float32Array(n); for (let i = 0; i < n; i++) x[i] = 0.2 * Math.sin((2 * Math.PI * 220 * i) / SR);
- const bare = ghostCheck([x, x], SR, { bpm, beatsPerBar: 4 }), exempt = ghostCheck([x, x], SR, { bpm, beatsPerBar: 4, breaths: [[-0.001, 8.001]] });
- ok(!bare.pass, `a held pad with no onsets fails the ghost guard (${bare.failures} windows)`);
- ok(exempt.pass, "the same pad inside a declared breath passes");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/hostAudio.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/hostAudio.test.ts
deleted file mode 100644
index 8b54044..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/hostAudio.test.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { embeddedAudio } from '../src/hosts/audio';
-export const name = 'embedded film track';
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 48000, n = sr / 10, bytes = new Uint8Array(n * 8), view = new DataView(bytes.buffer);
- for (let i = 0; i < n; i++) { view.setFloat32(i * 8, 1.4 * Math.sin(2 * Math.PI * 18000 * i / sr), true); view.setFloat32(i * 8 + 4, -0.25, true); }
- const audio = embeddedAudio({ sampleRate: sr, frames: n, float32: btoa(String.fromCharCode(...bytes)) }), [L, R] = audio(sr);
- ok(L.every((v, i) => v === view.getFloat32(i * 8, true)) && R.every(v => v === -0.25), 'embedded stereo keeps every Float32 sample, including unclipped values');
- const [down] = audio(24000), [up] = audio(96000), [device] = audio(44100);
- ok(down.length === n / 2 && up.length === n * 2 && device.length === 4410, 'alternate sample rates keep the complete track duration');
- ok(down.slice(100).reduce((e, x) => e + x * x, 0) / down.length < 0.01, 'downsampling removes tones above the new Nyquist frequency');
- ok(audio(sr)[0].every((v, i) => v === view.getFloat32(i * 8, true)), 'sample-rate conversion leaves the pinned 48 kHz master untouched');
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/kinetic.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/kinetic.test.ts
deleted file mode 100644
index 6453a83..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/kinetic.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-// KINETIC SPACING TESTS. The drawn lettering is spaced by its ink: the mean gap between two letters is
-// the same across the cap height (track + AIR), no ink comes closer than MIN_GAP, and measure() is the
-// width the layout writes.
-import { advance, measure, profileOf, SPACING } from "../src/canvas-core/kinetic";
-
-export const name = "kinetic";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const tr = 1.5, box = 4 + tr, { BANDS, MIN_GAP, AIR } = SPACING;
- const minGap = (a: string, b: string) => { const pa = profileOf(a)!, pb = profileOf(b)!, o = advance(a, b, tr); let m = Infinity; for (let i = 0; i < BANDS; i++) if (pa.ink[i] && pb.ink[i]) m = Math.min(m, o + pb.L[i] - pa.R[i]); return m; };
- const meanGap = (a: string, b: string) => advance(a, b, tr) - profileOf(a)!.mR + profileOf(b)!.mL;
- ok(advance("C", "T", tr) < box - 0.5, `C then T sits closer than the box spacing (${advance("C", "T", tr).toFixed(2)} vs ${box}): no hole before the T`);
- ok(advance("E", "A", tr) < box - 0.5, `E then A closes up the same way (${advance("E", "A", tr).toFixed(2)})`);
- ok(minGap("I", "D") >= tr + AIR - 1e-9, `a narrow I is as far from its neighbour's stem as any two stems (${minGap("I", "D").toFixed(2)} units)`);
- const pairs = "YOUR PRODUCT IDEA IN ART OUT".split(" ").flatMap((w) => [...w].slice(1).map((ch, i) => [w[i], ch] as [string, string]));
- ok(pairs.every(([a, b]) => minGap(a, b) >= MIN_GAP - 1e-9), `no two letters' ink comes closer than ${MIN_GAP} units (${pairs.map(([a, b]) => `${a}${b} ${minGap(a, b).toFixed(2)}`).join(", ")})`);
- const free = pairs.filter(([a, b]) => minGap(a, b) > MIN_GAP + 1e-6);
- ok(free.length > 5 && free.every(([a, b]) => Math.abs(meanGap(a, b) - (tr + AIR)) < 1e-9), `where ink does not bind, every pair's mean gap is the track plus AIR (${free.map(([a, b]) => `${a}${b}`).join(" ")})`);
- ok(Math.abs(measure("CT", 60, { slant: 0 }) - (advance("C", "T", 1.5) + 4) * 10) < 1e-9 && Math.abs(measure("A B", 60, { slant: 0 }) - (advance("A", " ", 1.5) + advance(" ", "B", 1.5) + 4) * 10) < 1e-9, "measure() is the advances plus the last letter's box (a space keeps its box)");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/launchLayout.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/launchLayout.test.ts
deleted file mode 100644
index 8cbbc94..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/launchLayout.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-// LAUNCH LAYOUT TESTS. One timeline, four frame shapes: each shape is a composition of its own (the
-// chat, the cards, the word pages, the split beat, the end card), every line a viewer reads is at
-// least the phone-safe size, nothing sits over anything else, and 16x9 is the desktop film exactly.
-import { CHAT_GEOM, chatGeom, CHAT } from "../src/canvas-core/launchKit";
-import { launchLayout, SHAPES, MIN_PX, PHONE_SAFE, estWidth, installRows, monoWidth, parseShapes, type Shape } from "../src/canvas-core/launchLayout";
-import { makeLaunchFilm, fitWords } from "../src/canvas-core/launchTemplate";
-import type { Film } from "../src/canvas-core/film";
-
-type R = { x: number; y: number; w: number; h: number };
-const inside = (a: R, b: R, tol = 0.5) => a.x >= b.x - tol && a.y >= b.y - tol && a.x + a.w <= b.x + b.w + tol && a.y + a.h <= b.y + b.h + tol;
-const overlap = (a: R, b: R) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
-
-export const name = "launchLayout";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const g = chatGeom(CHAT, 1, CHAT_GEOM.px, 34, 0);
- ok(JSON.stringify([g.CHAT, g.INPUT, g.GEN, g.REPLY.x, g.REPLY.y, g.TEXT]) === JSON.stringify([CHAT_GEOM.CHAT, CHAT_GEOM.INPUT, CHAT_GEOM.GEN, CHAT_GEOM.REPLY.x, CHAT_GEOM.REPLY.y, CHAT_GEOM.TEXT]), "the chat derivation at k = 1 IS the desktop chat (one component, not two)");
- const content0 = { prompts: ["a lighthouse at sunset, as a print", "now a fox at dusk"], install: ["/plugin marketplace add alexgreensh/anidoodle", "/plugin install anidoodle@alexgreensh-anidoodle"], tagline: "Illustrations, loops and films, drawn in code" };
- for (const shape of Object.keys(SHAPES) as Shape[]) {
- const content = content0;
- const L = launchLayout(shape, content), frame = { x: 0, y: 0, w: L.W, h: L.H }, c = L.chat;
- ok(L.W === SHAPES[shape].W && L.H === SHAPES[shape].H, `${shape}: the frame is ${L.W}x${L.H}`);
- const small = L.roles.filter((r) => r.px < r.min);
- ok(!small.length, `${shape}: every text role is at or over its minimum (${L.roles.map((r) => `${r.role} ${r.px.toFixed(0)}`).join(", ")})`);
- if (L.phone) ok(L.roles.filter((r) => ["prompt", "bubble", "card label", "tagline", "install lines"].includes(r.role)).every((r) => r.px >= MIN_PX.phone.read), `${shape}: the lines a viewer must read are phone-safe (>= ${MIN_PX.phone.read} px)`);
- ok(inside(c.CHAT, frame) && inside(c.INPUT, c.CHAT) && inside(c.GEN, c.INPUT), `${shape}: window in frame, composer in window, button in composer`);
- ok(L.thread.cardX >= c.CHAT.x && L.thread.cardX + L.thread.card <= c.CHAT.x + c.CHAT.w && L.thread.card > 0, `${shape}: the answer card (${L.thread.card} px) sits inside the thread`);
- ok(L.thread.bubbles.every((ls) => ls.length <= 3), `${shape}: prompts wrap to at most 3 bubble lines (${L.thread.bubbles.map((b) => b.length).join(", ")})`);
- ok(L.bug.y > c.CHAT.y + c.CHAT.h, `${shape}: the corner mark sits below the chat window, never on it`);
- const pw = Math.max(...L.end.rows.map((r) => monoWidth(r.text, L.end.monoPx) + r.indent * L.end.monoPx * 0.61)) + 2 * L.end.padX;
- ok(pw <= L.W, `${shape}: the install panel (${pw.toFixed(0)} px at ${L.end.monoPx.toFixed(1)} px mono) fits the frame's width`);
- ok(L.end.titleY < L.end.taglineY && L.end.taglineY < L.end.panelY && L.end.footerY < L.stage.h, `${shape}: the end card stacks title, line, panel, footer, all in frame`);
- ok(!overlap(L.split.words, L.split.ui) && inside(L.split.words, L.stage) && inside(L.split.ui, L.stage), `${shape}: a split beat's words and live UI have their own areas (${L.split.vertical ? "stacked" : "side by side"})`);
- if (L.phone) { const B = launchLayout(shape, { ...content, band: true }); ok(!!B.band && !overlap(B.band, B.stage) && B.band.y + B.band.h === (B.zones ? B.safe.y + B.safe.h : B.H), `${shape}: burned-in captions get their own band under the picture (${B.band?.h} px${B.zones ? ", at the safe rectangle's bottom" : ""})`); }
- // the 9:16 platform safe zones: every rectangle that holds text sits inside the safe rectangle; other shapes have none
- if (shape !== "9x16") { ok(!L.zones && JSON.stringify(L.safe) === JSON.stringify(frame), `${shape}: no safe zones (the whole frame is free for text)`); continue; }
- const S = L.safe, E = L.end, pushed = (r: R, z: number) => ({ x: r.x + r.w / 2 - (r.w * z) / 2, y: r.y + r.h / 2 - (r.h * z) / 2, w: r.w * z, h: r.h * z });
- ok(L.zones && Math.abs(S.y - L.H * PHONE_SAFE.top) < 1e-9 && Math.abs(S.x + S.w - L.W * (1 - PHONE_SAFE.right)) < 1e-9 && Math.abs(S.y + S.h - L.H * (1 - PHONE_SAFE.bottom)) < 1e-9, `9x16: the safe rectangle is the frame less the top ${Math.round(PHONE_SAFE.top * 100)} %, bottom ${Math.round(PHONE_SAFE.bottom * 100)} % and right ${Math.round(PHONE_SAFE.right * 100)} %`);
- ok(inside(c.CHAT, S), `9x16: the chat window, and every line in it, sits inside the safe rectangle (${[c.CHAT.x, c.CHAT.y, c.CHAT.x + c.CHAT.w, c.CHAT.y + c.CHAT.h].map((v) => v.toFixed(0)).join(",")})`);
- ok(inside(L.split.words, S) && inside(pushed(L.split.ui, 1.12), S), "9x16: the split beat's words and its live UI, pushed in to its fullest 12 %, sit inside the safe rectangle");
- ok(inside(pushed(L.uiFull, 1.06), S), "9x16: a UI ask on its own leaves its camera room to creep without leaving the safe rectangle");
- const bugW = estWidth("Your Product", L.bug.px) * 1.2;
- ok(inside({ x: L.bug.x - bugW, y: L.bug.y - L.bug.px, w: bugW, h: L.bug.px * 1.3 }, S), "9x16: the corner mark sits inside the safe rectangle");
- const at = L.type.at!; ok(!!at && inside({ x: at[0] - L.type.maxW / 2, y: at[1] - 10, w: L.type.maxW, h: 20 }, S), "9x16: a word page's lines are centred in the safe rectangle and no wider than it");
- const pw0 = pw;
- ok(inside({ x: E.cx - Math.max(E.titleW, pw0) / 2, y: E.titleY - E.titleMax, w: Math.max(E.titleW, pw0), h: E.footerY + E.footerPx - (E.titleY - E.titleMax) }, S), "9x16: the end card (name, line, install panel, footer) sits inside the safe rectangle");
- }
- let err = ""; try { launchLayout("16x9", { ...content0, band: true }); } catch (e) { err = (e as Error).message; } ok(/sidecar/.test(err), "16x9 refuses a burned-in band: its captions ship as .srt/.vtt");
- // install lines too long for the mono minimum wrap at a natural break, the continuation indented; short ones stay whole
- const T = launchLayout("9x16", content0).end, rowsOf = (r: { text: string; indent: number }[]) => r.map((x) => `${" ".repeat(x.indent)}${x.text}`).join(" | ");
- ok(T.wrapped && rowsOf(T.rows) === "/plugin marketplace add | alexgreensh/anidoodle | /plugin install | anidoodle@alexgreensh-anidoodle" && T.monoPx >= MIN_PX.phone.read, `9x16: anidoodle's own install lines wrap after the command word at ${T.monoPx.toFixed(1)} px: ${rowsOf(T.rows)}`);
- const one = installRows(["npm install tally"], 824.8, 32, 41), mixed = installRows(["npm i tally", "/plugin install anidoodle@alexgreensh-anidoodle"], 824.8, 32, 41);
- ok(!one.wrapped && one.rows.length === 1 && one.rows[0].text === "npm install tally" && one.rows[0].indent === 0, "a short install line stays on one row");
- ok(mixed.wrapped && rowsOf(mixed.rows) === "npm i tally | /plugin install | anidoodle@alexgreensh-anidoodle", `only the line that cannot fit wraps: ${rowsOf(mixed.rows)}`);
- const at = installRows(["npx anidoodle-package@alexgreensh-anidoodle-latest"], 700, 32, 41);
- ok(at.wrapped && rowsOf(at.rows) === "npx anidoodle-package | @alexgreensh-anidoodle-latest", `two rows when one break gives two: before "@" when no space does (${rowsOf(at.rows)})`);
- const mark = installRows(["alexgreensh-anidoodle@alexgreensh-anidoodle-x"], 600, 32, 41);
- ok(mark.wrapped && rowsOf(mark.rows) === "alexgreensh-anidoodle | @alexgreensh-anidoodle-x", `with no space it wraps before "@", the next row opening with it: ${rowsOf(mark.rows)}`);
- const slash = installRows(["alexgreensh-anidoodle/alexgreensh-anidoodle-x"], 600, 32, 41);
- ok(slash.wrapped && rowsOf(slash.rows) === "alexgreensh-anidoodle/ | alexgreensh-anidoodle-x", `or after "/", the row closing with it: ${rowsOf(slash.rows)}`);
- ok(JSON.stringify(installRows(["npm i a", "b init"], 944, 32, 33.6)) === JSON.stringify({ rows: [{ text: "npm i a", indent: 0 }, { text: "b init", indent: 0 }], px: 33.6, wrapped: false }), "lines that fit keep their size and rows exactly");
- err = ""; try { launchLayout("9x16", { ...content0, install: ["npx a-single-package-name-that-is-far-too-long-for-any-phone-frame-at-all"] }); } catch (e) { err = (e as Error).message; } ok(/install lines would be/.test(err), `an install line that cannot be phone-safe is an error: ${err.slice(0, 80)}`);
- ok(parseShapes("16x9, 9x16").join() === "16x9,9x16", "parseShapes reads a --shapes list");
- err = ""; try { parseShapes("16x10"); } catch (e) { err = (e as Error).message; } ok(/not a shape/.test(err), "parseShapes refuses an unknown shape");
-
- // one timeline, every shape: the same cut and length, a different composition
- const plate: Film = { meta: { title: "plate", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 60 }, assets: { images: {} }, shots: [{ id: "p", start: 0, end: 60, draw: () => {} }] };
- const f = makeLaunchFilm({ title: "Tally", asks: [{ prompt: content0.prompts[0], plate, label: "l" }, { prompt: content0.prompts[1], plate, label: "l" }], words: [[{ text: "EVERY NUMBER, COUNTED.", style: "ink", color: "#000" }]], tagline: content0.tagline, install: ["npm i tally"], bpm: 90, claimBar: 4, score: null });
- const shapes = (Object.keys(SHAPES) as Shape[]).map((s) => f.reshape(s));
- ok(shapes.every((x) => x.meta.durationFrames === f.meta.durationFrames && JSON.stringify(x.cut.STARTS) === JSON.stringify(f.cut.STARTS)), `every shape is the same cut (${f.meta.durationFrames} frames, cuts at ${f.cut.STARTS.join(", ")})`);
- ok(shapes.every((x, i) => x.meta.W === SHAPES[(Object.keys(SHAPES) as Shape[])[i]].W && x.meta.H === SHAPES[(Object.keys(SHAPES) as Shape[])[i]].H), "each shape renders at its own frame size");
- ok(f.reshape("16x9") === f && f.reshape("9x16") === f.reshape("9x16"), "reshape returns the film itself for its own shape, and one film per shape");
- const tall = fitWords([{ text: "EVERY NUMBER, COUNTED.", style: "ink", color: "#000" }], f.reshape("9x16").layout), wide = fitWords([{ text: "EVERY NUMBER, COUNTED.", style: "ink", color: "#000" }], f.layout);
- // a film ask (any film in a card) with its words beside it builds in every shape, its seam into the end card matched
- const fa = makeLaunchFilm({ title: "Tally", asks: [{ prompt: content0.prompts[0], plate, label: "l" }, { kind: "film", film: plate, split: [{ text: "Any film.", style: "ink", color: "#000" }] }], tagline: "t", install: ["npm i tally"], bpm: 90, score: null });
- ok((Object.keys(SHAPES) as Shape[]).every((sh) => fa.reshape(sh).seams.every((q) => Math.hypot(q.out.p[0] - q.into.p[0], q.out.p[1] - q.into.p[1]) < 2)), "a film ask builds in every shape, the motif's seam matched");
- // the hook: the first prompt is the hero, large enough to read muted in the first 2 s, in every shape
- ok((Object.keys(SHAPES) as Shape[]).every((sh) => { const x = f.reshape(sh); return (x.heroPx ?? 0) >= (x.layout.phone ? 64 : 56); }), `the first prompt is the hero: ${(Object.keys(SHAPES) as Shape[]).map((sh) => `${sh} ${f.reshape(sh).heroPx} px`).join(", ")} (>= 64 on a phone frame, 56 on 16x9)`);
- let long = ""; try { makeLaunchFilm({ title: "Tally", shape: "9x16", asks: [{ prompt: "a very long first prompt that goes on and on about everything it could possibly want drawn today", plate, label: "l" }], tagline: "t", install: ["npm i tally"], bpm: 90, score: null }); } catch (e) { long = (e as Error).message; }
- ok(/shorten it/.test(long), "a first prompt too long for a readable hook is an error, never tiny type");
- ok(wide.length === 1 && tall.length === 2, `a word page re-sets its lines for a narrow frame (16x9: ${wide.length} line, 9x16: ${tall.map((l) => l.text).join(" / ")})`);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/launchSound.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/launchSound.test.ts
deleted file mode 100644
index 6f4e4ac..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/launchSound.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// LAUNCH SOUND TESTS. The template's sound cues come from the picture's own timing: a key per typed
-// character, the press on the frame Generate goes down, the drop and its bloom, the card landing on
-// its spring's first arrival, each panned to where it happens on screen; one riser and one impact at
-// the big reveal and nothing on the other cuts; every cue heard over a real score.
-import { makeLaunchFilm } from "../src/canvas-core/launchTemplate";
-import { mixLaunch, panOf } from "../src/canvas-core/launchSound";
-import { springLand } from "../src/canvas-core/productUI";
-import type { Material } from "../src/canvas-core/music";
-import type { Film } from "../src/canvas-core/film";
-
-export const name = "launchSound";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const plate: Film = { meta: { title: "plate", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 60 }, assets: { images: {} }, shots: [{ id: "p", start: 0, end: 60, draw: () => {} }] };
- const mine = (): Material => ({
- style: "playful", title: "Tally, counted", seed: 5, mood: "curious", bpm: 90, key: "G", mode: "mixolydian",
- chords: { G: { voicing: "[D4 G4 B4]", bass: "G2:1.5 D3:.5 G2:1 F2:1" }, F: { voicing: "[C4 F4 A4]", bass: "F2:1.5 C3:.5 F2:1 E2:1" } },
- motifs: { a: "B4:.5 D5:.5 G5:1 r:.5 F5:.25 E5:.25 D5:1", b: "r:1 A4:.5 C5:.5 F5:1 E5:.5 C5:.5" },
- grooves: { main: { family: "shuffle", density: 0.45, variation: 0.35 } },
- sections: [{ kind: "groove", bars: 4, harmony: ["G", "F"], lead: ["a", "b", "a", "b"], groove: "main", stretch: true }, { kind: "outro", bars: 1, harmony: ["G"], lead: ["a"] }],
- });
- const prompts = ["a lighthouse at sunset", "now a fox at dusk"];
- const spec = { title: "Tally", asks: prompts.map((p) => ({ prompt: p, plate, label: "l" })), words: [[{ text: "IDEA IN.", style: "ink" as const, color: "#000" }]], tagline: "t", install: ["npm i tally"], bpm: 90, askBeats: 6, endBeats: 8, claimBar: 5, score: mine };
- const f = makeLaunchFilm(spec), cues = f.cues, at = (c: number) => Math.round(f.cut.cutOf(c));
- const by = (r: string) => cues.filter((c) => c.role === r);
-
- // keys: one per character typed on screen (the first prompt is under way at frame 0: only what is typed after it)
- const typed = f.timing.reduce((a, t) => a + t.times.filter((x) => x >= Math.max(0, t.tin)).length, 0);
- ok(by("key").length === typed, `a key cue for every character typed on screen (${by("key").length} of ${typed})`);
- const spaces = prompts.join("").split("").filter((c) => c === " ").length;
- ok(by("key").filter((c) => c.variant === "space").length <= spaces && by("key").some((c) => c.variant === "space"), "the space bar has its own sound");
- ok(f.timing.every((t, i) => by("key").filter((c) => c.frame >= at(t.base) && c.frame < at(t.base + t.len)).every((c, j, a) => j === 0 || c.frame >= a[j - 1].frame)), "keys land in typing order");
- // the press, the drop, the bloom, the landing: on the frames the picture does them
- f.timing.forEach((t, i) => {
- ok(by("press")[i]?.frame === at(t.base + t.down), `ask ${i}: the press is on the frame Generate goes down (${by("press")[i]?.frame})`);
- ok(by("drop")[i]?.frame === at(t.base + t.drop.t0) && by("bloom")[i]?.frame === at(t.base + t.drop.land), `ask ${i}: the drop lifts and blooms on its frames (${by("drop")[i]?.frame}, ${by("bloom")[i]?.frame})`);
- ok(by("land")[i]?.frame === at(springLand(t.base + t.drop.land, 4.163 / 21, 0.8)), `ask ${i}: the card lands on its spring's first arrival (${by("land")[i]?.frame})`);
- });
- // pan by screen x: Generate is right of centre, the answer card left of it (16x9)
- ok(by("press").every((c) => panOf(c.x, 1920) > 0.1) && by("bloom").every((c) => panOf(c.x, 1920) < -0.1), `panned to where it happens: press ${by("press").map((c) => panOf(c.x, 1920).toFixed(2)).join(", ")}, bloom ${by("bloom").map((c) => panOf(c.x, 1920).toFixed(2)).join(", ")}`);
- ok(cues.every((c) => c.x === undefined || (c.x >= 0 && c.x <= 1920)), "every cue's screen x is on screen");
- // restraint: one riser and one impact, at the big reveal only; no whoosh or swish at all; nothing on a type frame's cuts
- const reveal = f.cut.STARTS[f.cut.SEGS.length - 1];
- ok(by("riser").length === 1 && by("impact").length === 1 && by("riser")[0].frame === reveal && by("impact")[0].frame === reveal, `one riser and one impact, both at the reveal (frame ${reveal})`);
- ok(!cues.some((c) => c.kind === "whoosh" || c.kind === "swish"), "no whoosh or swish anywhere");
- const typeCuts = f.cut.SEGS.flatMap((s, k) => (s.kind === "type" ? [f.cut.STARTS[k], f.cut.STARTS[k] + s.len] : []));
- ok(typeCuts.length > 0 && !cues.some((c) => typeCuts.some((x) => Math.abs(c.frame - x) <= 2)), `nothing on the cuts into or out of a word page (${typeCuts.join(", ")})`);
- ok(!cues.some((c) => f.cut.SEGS.some((s, k) => s.kind === "type" && c.frame > f.cut.STARTS[k] && c.frame < f.cut.STARTS[k] + s.len)), "word pages are silent (no cue inside a type frame)");
-
- // every cue heard over a real score, the mix under -1 dBTP
- const [L, R] = f.audio!(48000);
- ok(L.length === Math.round((f.meta.durationFrames / 30) * 48000) && L.length === R.length, `the mix is the film's length (${(L.length / 48000).toFixed(2)} s)`);
- const bed = makeLaunchFilm({ ...spec, sfx: false }).audio!(48000);
- const mix = mixLaunch(bed, { fps: 30, frames: f.meta.durationFrames, W: 1920, cues, bpm: 90, seed: 7, key: "G" }, 48000);
- ok(mix.ok, `every cue audible over the score (${mix.audibility.length} cues, worst margin ${Math.min(...mix.audibility.map((a) => a.marginDb)).toFixed(1)} dB vs floor -6; ${mix.raised.length} raised)`);
- ok(mix.dbtp <= -1, `the mix's true peak is under the ceiling (${mix.dbtp.toFixed(2)} dBTP)`);
- const quiet = mixLaunch(bed, { fps: 30, frames: f.meta.durationFrames, W: 1920, cues: cues.map((c) => ({ ...c, gainDb: -30 })), bpm: 90, seed: 7, key: "G" }, 48000, 0);
- ok(!quiet.ok, "a cue buried 30 dB under the score is caught, not shipped");
-
- // one timeline at 60 fps: the same cues on the same instants, twice the frames
- const f60 = makeLaunchFilm({ ...spec, fps: 60 });
- ok(f60.meta.durationFrames === 2 * f.meta.durationFrames && f60.cues.length === cues.length && f60.cues.every((c, i) => Math.abs(c.frame - 2 * cues[i].frame) <= 1), `60 fps: ${f60.meta.durationFrames} frames, every cue on the same instant (within one 60 fps frame)`);
- // sync markers: the presses and the impact, for verify-export's audio-to-video check
- ok(f.meta.sync!.length === 3 && f.meta.sync!.every((s) => cues.some((c) => c.frame === s.frame && (c.role === "press" || c.role === "impact"))), `sync markers are the presses and the impact (${f.meta.sync!.map((s) => s.frame).join(", ")})`);
- // sfx: false leaves the score alone; a silent film still gets its cues (sound design without music)
- ok(makeLaunchFilm({ ...spec, sfx: false }).cues.length === 0, "sfx: false emits no cues");
- const silent = makeLaunchFilm({ ...spec, score: null });
- ok(silent.cues.some((c) => c.role === "riser" && c.variant === "air") && typeof silent.audio === "function", "a film with no score still has its cues (the riser untuned: air)");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/launchTemplate.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/launchTemplate.test.ts
deleted file mode 100644
index 497cf7d..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/launchTemplate.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-// LAUNCH TEMPLATE TESTS. makeLaunchFilm takes a score composed for the product: a Material (what
-// compose.md writes) or a Piece. anidoodle's own pieces are refused by identity, by title and by
-// content, so a retitled or transposed copy of our launch score cannot ship as a user's film.
-import { gridScore, makeLaunchFilm } from "../src/canvas-core/launchTemplate";
-import { chiptunePlayful, composePiece, daylightCopy, renderPiece, launchLofi3, launchLofi3Material, loudness, perform, truePeak, type Material } from "../src/canvas-core/music";
-import type { Film } from "../src/canvas-core/film";
-
-export const name = "launchTemplate";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const plate: Film = { meta: { title: "plate", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: 60 }, assets: { images: {} }, shots: [{ id: "p", start: 0, end: 60, draw: () => {} }] };
- // sfx: false: these check the score bed alone (the sound cues are launchSound.test.ts)
- const base = { title: "Tally", asks: [{ prompt: "draw it", plate, label: "l" }], tagline: "t", install: ["npm i tally"], bpm: 120, askBeats: 8, endBeats: 12, sfx: false };
- const refused = (score: unknown, re = /anidoodle's own/) => { try { makeLaunchFilm({ ...base, score } as never); return false; } catch (e) { return re.test(String((e as Error).message)); } };
- const mine = (): Material => ({
- style: "playful", title: "Tally, counted", seed: 5, mood: "curious", bpm: 120, key: "G", mode: "mixolydian",
- chords: { G: { voicing: "[D4 G4 B4]", bass: "G2:1.5 D3:.5 G2:1 F2:1" }, F: { voicing: "[C4 F4 A4]", bass: "F2:1.5 C3:.5 F2:1 E2:1" } },
- motifs: { a: "B4:.5 D5:.5 G5:1 r:.5 F5:.25 E5:.25 D5:1", b: "r:1 A4:.5 C5:.5 F5:1 E5:.5 C5:.5" },
- grooves: { main: { family: "shuffle", density: 0.45, variation: 0.35 } },
- sections: [{ kind: "groove", bars: 4, harmony: ["G", "F"], lead: ["a", "b", "a", "b"], groove: "main", stretch: true }, { kind: "outro", bars: 1, harmony: ["G"], lead: ["a"] }],
- });
- let film: Film | null = null; try { film = makeLaunchFilm({ ...base, score: mine }); } catch (e) { ok(false, `a composed Material is accepted: ${(e as Error).message}`); }
- ok(!!film && typeof film.audio === "function", "a composed Material is accepted as the score");
- ok(film?.audio?.scores?.length === 1, "film audio exposes its fitted score so hosts load only its recorded instruments");
- ok(refused(launchLofi3), "refuses our launch score by identity");
- ok(refused(launchLofi3Material), "refuses our launch score's material by identity");
- ok(refused(chiptunePlayful), "refuses a demo");
- ok(refused(() => ({ ...launchLofi3(), title: "Mine" })), "refuses a retitled copy of our launch score");
- ok(refused(() => ({ ...launchLofi3Material(), title: "Mine" })), "refuses retitled launch material");
- ok(refused(daylightCopy), "refuses the transposed copy of our launch score (the Daylight fixture)");
- ok(refused(undefined, /required/), "a missing score is an error, never a default");
-
- // Sync wins over length: a 120 bpm film with a score whose stretch section is 4 bars plays the
- // score at EXACTLY 120 bpm, and the film is made whole bars of it by the end-card hold. The bed is
- // that render at one gain (never cut and faded, never re-tempoed), every downbeat on the grid.
- const two = { ...base, asks: [base.asks[0], { prompt: "again", plate, label: "l" }], askBeats: 16, endBeats: 12, score: mine };
- const bedFilm = makeLaunchFilm(two), N = bedFilm.meta.durationFrames, secs = N / bedFilm.meta.fps, SR = 16000, sc = bedFilm.meta.score;
- ok(!!sc && sc.tempo === 120 && sc.grid === true, `the score plays at the film's bpm exactly (${sc?.tempo} bpm, ${sc?.form})`);
- ok(N % 60 === 0, `the film is whole bars of the score (${N} frames = ${N / 60} bars of 60 frames)`);
- const endAt = bedFilm.cut.STARTS[bedFilm.cut.SEGS.length - 1];
- ok(bedFilm.cut.STARTS.every((f) => f % 60 === 0) && endAt === 2 * 16 * 15, `every cut sits on a downbeat (${bedFilm.cut.STARTS.join(", ")}; end card at ${endAt})`);
- const played = gridScore(mine, 120, 30, endAt, 12 * 15), perf = perform(played.piece, 120, { expressive: true });
- let worst = 0; for (let b = 0; 4 * b * 0.5 < perf.lastOnset - 3; b++) worst = Math.max(worst, Math.abs(perf.sec(4 * b) - 2 * b));
- ok(worst < 1e-6, `every downbeat before the final ritard lands on its bar, worst ${(worst * 1000).toFixed(3)} ms`);
- ok(played.bars * 60 < N && played.piece.plan.sections.length >= 1, `the score (${played.bars} bars) ends inside the film and rings out on its last frame`);
- const [L, R] = bedFilm.audio!(SR), r = renderPiece(played.piece, SR, { seconds: secs, tempo: 120 });
- let k = 0; for (let i = 0; i < r.L.length; i++) if (Math.abs(r.L[i]) > Math.abs(r.L[k])) k = i;
- const g = L[k] / r.L[k]; let dev = 0; for (let i = 0; i < L.length; i++) dev = Math.max(dev, Math.abs(L[i] - g * r.L[i]));
- ok(L.length === Math.round(secs * SR) && dev < 1e-5, `the bed is that 120 bpm render at one gain, exactly the film's ${secs} s (max deviation ${dev.toExponential(1)})`);
- // no form of a fixed score fits: an error that says what to do, never a tempo change
- let msg = ""; try { makeLaunchFilm({ ...two, score: () => composePiece({ ...mine(), sections: mine().sections.map((x) => ({ ...x, stretch: false, kind: x.kind === "groove" ? "intro" : x.kind })) }) }); } catch (e) { msg = (e as Error).message; }
- ok(/cannot end on a bar.*1-bar stretch section/.test(msg), `a score that cannot fit throws with the fix: ${msg.slice(0, 90)}...`);
- const lu = loudness([L, R], SR).integrated, tp = truePeak([L, R]).dbtp;
- ok(tp <= -0.99 && (Math.abs(lu + 14) < 0.3 || tp > -1.05), `bed at -14 LUFS or held by the -1 dBTP ceiling (${lu.toFixed(2)} LUFS, ${tp.toFixed(2)} dBTP)`);
- // a dynamic bed stops at the peak ceiling; limit: true lets the limiter take those peaks instead
- const long = { ...two, askBeats: 24, endBeats: 16 }, [cL, cR] = makeLaunchFilm(long).audio!(SR), [lL, lR] = makeLaunchFilm({ ...long, limit: true }).audio!(SR);
- const cu = loudness([cL, cR], SR).integrated, lu2 = loudness([lL, lR], SR).integrated, tp2 = truePeak([lL, lR]).dbtp;
- ok(cu < -14.2 && truePeak([cL, cR]).dbtp > -1.05, `without limit the ceiling wins and says so in the loudness (${cu.toFixed(2)} LUFS)`);
- ok(Math.abs(lu2 + 14) < 0.3 && tp2 <= -1, `limit: true reaches -14 LUFS under -1 dBTP (${lu2.toFixed(2)} LUFS, ${tp2.toFixed(2)} dBTP)`);
- // a claimBar that needs a longer last ask gets a really longer ask, never the same ask slowed down
- // (content played at half speed repeats frames and fails the gate's identical-frame check)
- const solvedFilm = makeLaunchFilm({ ...base, asks: [base.asks[0], { ...base.asks[0], prompt: "and again" }], words: [[{ text: "ONE.", style: "ink" }]], claimBar: 7, score: null } as never) as ReturnType<typeof makeLaunchFilm>;
- const slowed = solvedFilm.cut.SEGS.filter((sg) => sg.kind === "pic" && sg.len > sg.to - sg.from);
- ok(slowed.length === 0 && solvedFilm.cut.STARTS[solvedFilm.cut.STARTS.length - 1] === 7 * 60, `a solved ask is longer, not slower (end card on bar 7 at frame ${solvedFilm.cut.STARTS[solvedFilm.cut.STARTS.length - 1]}, ${slowed.length} slowed segments)`);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts
deleted file mode 100644
index 47f7cdc..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-// MECHANISM KIT TESTS. The kit's claims are arithmetic: the camera is the house dimetric at 45/30, the
-// light ladder is monotone, the springs are exact closed forms, an exploded view staggers out and folds
-// back last-out-first-home, hatching stays inside its shape, and the music box's words come from its pins.
-// node tools/test.mjs mechanism
-import { Cam, level, springAt, sharesAt, type ExplodePlan, hand, flatHand, spin } from "../src/canvas-core/mechanismKit";
-import { Iso } from "../src/canvas-core/isometricKit";
-import { hatchSegs } from "../src/canvas-core/mechanismHands";
-import { play, PLAN, REV } from "../src/canvas-core/mechanism";
-
-export const name = "mechanism";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
-
- // 1. the camera at 45/30 is exactly the house 2:1 dimetric
- const k = 20, c = new Cam(45, 30, k, 300, 200), iso = new Iso(null as unknown as CanvasRenderingContext2D, (k * Math.SQRT2) / 2, 300, 200);
- const pts: [number, number, number][] = [[0, 0, 0], [3, -2, 5], [-4, 7, 1.5]];
- ok(pts.every((q) => { const a = c.p(q), b = iso.p(...q); return near(a[0], b[0], 1e-3) && near(a[1], b[1], 1e-2); }), "Cam(45, 30) projects like Iso.p (Iso rounds cos 30 to 4 places)");
- ok(c.depth(c.V) > c.depth([0, 0, 0]), "depth grows toward the viewer");
- const off = c.dv([2, -1, 3]), a0 = c.p([1, 1, 1]), a1 = c.p([3, 0, 4]);
- ok(near(a1[0] - a0[0], off[0], 1e-9) && near(a1[1] - a0[1], off[1], 1e-9), "dv is the screen offset of a world move");
-
- // 2. the light ladder: 0 to 4, monotone, whole numbers away from the thresholds
- const xs = Array.from({ length: 201 }, (_, i) => -1 + i / 100), ls = xs.map((x) => level(x));
- ok(ls.every((v, i) => !i || v >= ls[i - 1]), "level never falls as the light score rises");
- ok(near(level(-1), 0) && near(level(1), 4) && near(level(0.1), 1) && near(level(0.3), 2) && near(level(0.5), 3), "level is 0..4 and an integer between thresholds");
- ok(level(0.2) > 1.4 && level(0.2) < 1.6, "level crossfades across a threshold instead of flipping");
-
- // 3. springs: exact, continuous, and the damping ratio means what it says
- const step = (z: number) => Array.from({ length: 400 }, (_, i) => springAt(8, z, 0, 0, 1, i / 100).x);
- const crit = step(1), under = step(0.89), over = step(1.6);
- ok(crit.every((x) => x <= 1 + 1e-12), "critically damped: never overshoots");
- ok(Math.max(...under) > 1.0005 && Math.max(...under) < 1.05, `z 0.89: one faint overshoot (peak ${Math.max(...under).toFixed(4)})`);
- ok(over.every((x) => x <= 1 + 1e-12) && over[50] < crit[50], "overdamped: slower, no overshoot");
- ok([crit, under, over].every((s) => Math.abs(s[399] - 1) < 2e-3), "every spring arrives");
- for (const z of [0.6, 1, 1.4]) { const t = 0.37, h = 1e-6, v = springAt(8, z, 0.2, -0.5, 1, t).v, num = (springAt(8, z, 0.2, -0.5, 1, t + h).x - springAt(8, z, 0.2, -0.5, 1, t - h).x) / (2 * h); ok(Math.abs(v - num) < 1e-4, `z ${z}: velocity is the derivative of position`); }
- ok(springAt(8, 0.89, 0.3, 2, 1, 0).x === 0.3, "at tau 0 a spring is where it starts");
-
- // 4. the exploded view
- const P: ExplodePlan = { order: ["a", "b", "c", "d"], stagger: 0.1, w: 8, z: 0.89 };
- const open = [{ t: 1, apart: true }];
- ok(Object.values(sharesAt(P, open, 0.99)).every((v) => v === 0), "nothing moves before the cue");
- const early = sharesAt(P, open, 1.15); ok(early.a > early.b && early.b > 0 && early.c === 0 && early.d === 0, "it opens in order, one stagger apart");
- ok(Object.values(sharesAt(P, open, 5)).every((v) => Math.abs(v - 1) < 1e-3), "and arrives apart");
- const cycle = [{ t: 1, apart: true }, { t: 4, apart: false }], back = sharesAt(P, cycle, 4.12);
- ok(back.d < back.a && back.c < back.a, "it folds back last-out first-home");
- ok(Object.values(sharesAt(P, cycle, 9)).every((v) => Math.abs(v) < 1e-3), "and comes all the way home");
- const rev = [{ t: 1, apart: true }, { t: 1.15, apart: false }], r = sharesAt(P, rev, 1.2);
- ok(r.c === 0 && r.d === 0, "a reversal mid-stagger cancels the moves still pending");
- ok(Object.values(sharesAt(P, rev, 8)).every((v) => Math.abs(v) < 1e-3), "and what had left comes home");
- ok(JSON.stringify(sharesAt(P, cycle, 2.5)) === JSON.stringify(sharesAt(P, [...cycle].reverse(), 2.5)), "cue order in the list does not matter");
-
- // 5. hatching stays inside its shape and is anchored, not screen-locked
- const sq: [number, number][] = [[0, 0], [40, 0], [40, 30], [0, 30]], segs = hatchSegs(sq, Math.PI / 4, 4);
- ok(segs.length > 10 && segs.every(([a, b]) => [a, b].every(([x, y]) => x >= -1e-6 && x <= 40 + 1e-6 && y >= -1e-6 && y <= 30 + 1e-6)), `hatching: ${segs.length} lines, all inside the square`);
- const moved = hatchSegs(sq.map(([x, y]) => [x + 7, y + 3] as [number, number]), Math.PI / 4, 4, [7, 3]);
- ok(moved.length === segs.length && moved.every(([a], i) => near(a[0], segs[i][0][0] + 7, 1e-6) && near(a[1], segs[i][0][1] + 3, 1e-6)), "anchored hatching travels with its part");
-
- // 6. the music box: one model for pins, teeth and words
- ok(PLAN.order.length === 8, "eight assemblies");
- const quiet = play(0.0001);
- ok(/^PIN [12] · TOOTH \d+ · [A-G]#?\d \d+ HZ$/.test(quiet.read), `at the start the first chord speaks (its top note): ${quiet.read}`);
- const a4 = play(2 * Math.PI * (16 / 32) + 1e-6).read; ok(a4.includes("A4 440 HZ") || a4.includes("F3"), `at step 16 the readout names that step's pin: ${a4}`);
- const loop = play(2 * Math.PI * 3 + 0.4), first = play(0.4);
- ok(loop.read === first.read && loop.bend.every((v, i) => near(v, first.bend[i], 0.05)), "the drum's story repeats every turn");
- ok(REV > 0 && hand().id === "flat", "the kit's default hand is the plain reference hand");
- void flatHand;
-
- // 7. spin: a slow turn draws the blades once; a fast one first paints fainter echoes, each further back along the turn
- const calls = (sweep: number) => { const a: number[] = []; spin(1, sweep, (ang) => a.push(ang)); return a; };
- ok(calls(0).length === 1 && calls(0)[0] === 1, "a slow turn draws only the blades");
- const fast = calls(1.2); ok(fast.length === 5 && fast[fast.length - 1] === 1 && fast.slice(0, -1).every((v) => v < 1), `a fast turn paints ${fast.length - 1} fainter echoes before the blades`);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/morph.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/morph.test.ts
deleted file mode 100644
index 0df43cf..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/morph.test.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-// MORPH TESTS. resample, centreOf, handoff, coverShape, shapeGap and checkShapes in
-// src/canvas-core/morph.ts are pure and are held to numbers here. pathShape / fillShape get a
-// tiny recording ctx; nothing else draws. node tools/test.mjs
-import { blotShape, centreOf, checkShapes, circleShape, coverShape, fillShape, handoff, pathShape, rectShape, resample, shapeGap, type Shape } from "../src/canvas-core/morph";
-import type { Ctx, Env, P } from "../src/canvas-core/core";
-
-export const name = "morph";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
- const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
- const inside = (p: P, s: Shape) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
- const area = (s: Shape) => s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2;
- const centred = (s: Shape, c: P): Shape => { const m = centreOf(s); return s.map(([x, y]): P => [x - m[0] + c[0], y - m[1] + c[1]]); };
- const sq = rectShape(0, 0, 100, 50);
-
- // 1. resample: exactly n points, clockwise on screen whatever the input winding, evenly
- // spaced along the outline; degenerate shapes are refused
- const r60 = resample(sq, 60);
- ok(r60.length === 60 && resample(sq, 160).length === 160, "resample returns exactly n points");
- ok(area(r60) > 0 && area(resample([...sq].reverse(), 60)) > 0, "resampled outlines run clockwise on screen, either input winding");
- const circ = resample(circleShape([0, 0], 30, 72), 60), step = (2 * Math.PI * 30) / 60;
- const gaps = circ.map((p, i) => Math.hypot(p[0] - circ[(i + 59) % 60][0], p[1] - circ[(i + 59) % 60][1]));
- ok(gaps.every((g) => g > step * 0.98 && g <= step * 1.000001), `resample spaces points evenly along the outline (step ${step.toFixed(2)} px)`);
- ok(JSON.stringify(resample(sq, 60)) === JSON.stringify(r60), "resample is deterministic");
- ok(throws(() => resample([[0, 0], [1, 1]], 60)) && throws(() => resample([[5, 5], [5, 5], [5, 5]], 60)), "resample refuses fewer than 3 points or a zero-size shape");
-
- // 2. the shape builders and centreOf
- ok(circleShape([10, 20], 5).every((p) => near(Math.hypot(p[0] - 10, p[1] - 20), 5)), "circleShape's points sit on the circle");
- ok(JSON.stringify(rectShape(0, 0, 100, 50)) === JSON.stringify([[100, 0], [100, 50], [0, 50], [0, 0]]), "a sharp rect is its four corners, clockwise");
- const rr = rectShape(0, 0, 100, 50, 10, 4);
- ok(rr.length === 20 && rr.every(([x, y]) => x >= -1e-9 && x <= 100 + 1e-9 && y >= -1e-9 && y <= 50 + 1e-9), "a rounded rect is perCorner points a corner, inside the box");
- ok(blotShape([0, 0], 40, 7).every((p) => { const d = Math.hypot(p[0], p[1]); return d >= 40 * 0.9 - 1e-9 && d <= 40 * 1.12 + 1e-9; }), "blotShape's rim wobbles inside [0.9, 1.12] R");
- ok(centreOf(sq)[0] === 50 && centreOf(sq)[1] === 25, "centreOf is the middle of the bounding box");
- ok(centreOf([[0, 0], [10, 0], [0, 40]])[0] === 5 && centreOf([[0, 0], [10, 0], [0, 40]])[1] === 20, "centreOf uses the box, not the centroid");
-
- // 3. handoff: exact at both ends, the centre rides the arc, stretch is zero at the ends
- ok(throws(() => handoff({ from: circleShape([0, 0], 10), to: circleShape([100, 0], 10), t0: 50, t1: 50 })) && throws(() => handoff({ from: sq, to: sq, t0: 50, t1: 40 })), "t1 <= t0 throws");
- const from = circleShape([820, 300], 16), to = rectShape(240, 420, 600, 380, 28);
- const h = handoff({ from, to, t0: 45, t1: 80, arc: 90 });
- ok(h.at(0) === from && h.at(45) === from && h.at(80) === to && h.at(200) === to, "handoff returns exactly the source until t0 and exactly the target from t1");
- const ca = centreOf(resample(from, 160)), cb = centreOf(resample(to, 160));
- ok(near(h.centre(45)[0], ca[0]) && near(h.centre(45)[1], ca[1]) && near(h.centre(80)[0], cb[0], 1e-6) && near(h.centre(80)[1], cb[1], 1e-6), "the centre starts and lands on the two shapes' centres");
- const cm = h.centre(62.5); // u = 0.5 -> e = 0.5
- ok(near(cm[0], (ca[0] + cb[0]) / 2, 1e-6) && near(cm[1], (ca[1] + cb[1]) / 2 - 90, 1e-6), "mid-flight the centre is the eased midpoint, lifted by the arc");
- const long = handoff({ from, to, t0: 0, t1: 200, arc: 90 });
- ok(shapeGap(long.at(1), centred(resample(from, 160), long.centre(1))) < 0.5, "just after t0 the outline is the un-stretched source at its centre");
- ok(shapeGap(long.at(199), centred(resample(to, 160), long.centre(199))) < 0.5, "just before t1 the outline is the un-stretched target at its centre");
- const spec = { from, to, t0: 45, t1: 80, arc: 90 };
- ok(JSON.stringify(handoff(spec).at(60)) === JSON.stringify(h.at(60)), "a handoff is a pure function of its spec");
-
- // 4. coverShape: a uniform scale about the frame's centre until every corner is inside
- for (const s of [circleShape([820, 300], 16), sq, blotShape([500, 300], 40, 3)]) {
- const cov = coverShape(s, 1920, 1080, 24), cs: P[] = [[-24, -24], [1944, -24], [1944, 1104], [-24, 1104]];
- ok(cs.every((q) => inside(q, cov)), "coverShape puts every padded frame corner inside");
- }
- const wide = rectShape(300, 300, 100, 40), cov = coverShape(wide, 1920, 1080, 24);
- const box = (s: Shape) => { const xs = s.map((p) => p[0]), ys = s.map((p) => p[1]); return [Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)]; };
- const [w0, h0] = box(wide), [w1, h1] = box(cov);
- ok(near(w1 / h1, w0 / h0), `coverShape keeps the shape's proportions (aspect ${(w1 / h1).toFixed(3)} = the source's)`);
- ok(near(centreOf(cov)[0], 960, 1e-6) && near(centreOf(cov)[1], 540, 1e-6), "the shape's centre lands on the frame's centre");
- // a shape whose bounding-box centre sits in its own hole can never cover the frame
- const ring: Shape = [];
- for (let i = 0; i <= 40; i++) { const a = -2.97 + (i * 5.94) / 40; ring.push([400 + Math.cos(a) * 60, 300 + Math.sin(a) * 60]); }
- for (let i = 40; i >= 0; i--) { const a = -2.97 + (i * 5.94) / 40; ring.push([400 + Math.cos(a) * 40, 300 + Math.sin(a) * 40]); }
- ok(!inside(centreOf(ring), ring), "the test ring's centre is in its hole");
- ok(throws(() => coverShape(ring, 1920, 1080)), "coverShape throws when no scale can cover");
-
- // 5. shapeGap and checkShapes: 0 for identical outlines, a real offset measured, tol enforced
- const selfGap = shapeGap(sq, sq);
- ok(selfGap < 1e-9, `a shape has zero gap to itself (${selfGap.toExponential(1)} of resample noise)`);
- const c0 = circleShape([0, 0], 30), drift: Shape = c0.map(([x, y]): P => [x + 10, y]);
- const g = shapeGap(c0, drift);
- ok(Math.abs(g - 10) <= 0.5, `a 10 px offset is measured as ${g.toFixed(2)} px`);
- ok(near(shapeGap(drift, c0), g), "shapeGap is symmetric");
- ok(near(checkShapes(sq, sq), selfGap) && !throws(() => checkShapes(sq, sq, "self")), "checkShapes passes on a matching outline");
- ok(throws(() => checkShapes(c0, drift, "probe", 2)), "checkShapes throws past tol");
- ok(near(checkShapes(c0, drift, "probe", 20), g), "checkShapes returns the measured gap inside tol");
-
- // 6. pathShape / fillShape on a recording ctx
- const calls: string[] = [];
- const fx = { beginPath() { calls.push("begin"); }, moveTo() { calls.push("m"); }, lineTo() { calls.push("l"); }, closePath() { calls.push("close"); }, setTransform(...a: number[]) { calls.push(`t${a.join("/")}`); }, fill() { calls.push("fill"); }, fillStyle: "", globalAlpha: 0 };
- pathShape(fx as unknown as Ctx, sq);
- ok(calls.join(",") === "begin,m,l,l,l,close", "pathShape traces the outline and closes it");
- calls.length = 0;
- fillShape(fx as unknown as Ctx, { scale: 2 } as unknown as Env, sq, "#123456");
- ok(calls.includes("fill") && fx.fillStyle === "#123456" && calls.includes("t2/0/0/2/0/0"), "fillShape fills the outline in the film's scale");
-
- // 7. the checks refuse bad input: NaN in a shape, a turn that ends where it starts, a NaN
- // landing frame; a points: 2 ask still gets a usable outline (the floor is 8)
- const nanShape: Shape = [[NaN, 0], [0, 10], [10, 0]];
- ok(throws(() => checkShapes(nanShape, sq, "nan-out")) && throws(() => checkShapes(sq, nanShape, "nan-into")), "checkShapes throws when a shape contains NaN");
- ok(throws(() => handoff({ from, to, t0: 45, t1: 80, turn: [0.5, 0.5] })) && throws(() => handoff({ from, to, t0: 45, t1: 80, turn: [1, 0.2] })), "a turn that does not end after it starts throws");
- ok(throws(() => handoff({ from, to, t0: 45, t1: NaN })) && throws(() => handoff({ from, to, t0: NaN, t1: 80 })), "a NaN t0 or t1 throws");
- const coarse = handoff({ from, to, t0: 45, t1: 80, points: 2 }).at(60);
- ok(coarse.length === 8 && coarse.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y)), "points: 2 still yields a valid outline (8 finite points)");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/pianoTone.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/pianoTone.test.ts
deleted file mode 100644
index 10b014c..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/pianoTone.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-// The piano ruler's measures, tone colour between recorded layers and keys, and the two-band release, on synthetic takes.
-import { bandEnvelope, envelopeGap, ruled, bandDecay, centroidHz, onsetOf } from "../src/canvas-core/music/pianoRuler";
-import { registerBank, clearBanks, samplerVoice, sampleZones, toneColour, colourFilters, releaseLow, measuredTone, trebleFix, TREBLE_LEVEL, RELEASE_SPLIT, type SampleBank, type SampleZone } from "../src/canvas-core/music/sampler";
-import { PIANO_BANDS } from "../src/canvas-core/music/keysTables";
-import { hz } from "../src/canvas-core/music/theory";
-import type { Played } from "../src/canvas-core/music/perform";
-
-export const name = "piano tone";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const SR = 48000;
- // a take whose upper partials grow with the layer: brightness b sets partial n to b^(n-1)
- const tone = (f: number, b: number, secs = 2, tau = 1.2) => { const a = new Float32Array(Math.round(secs * SR)); for (let i = 0; i < a.length; i++) { let s = 0; for (let n = 1; n <= 24 && n * f < 20000; n++) s += Math.pow(b, n - 1) * Math.sin((2 * Math.PI * n * f * i) / SR); a[i] = 0.2 * s * Math.exp(-i / (SR * tau)); } return a; };
- const BRIGHT = [0.45, 0.65, 0.85];
- const bank = (id: string, pitches: number[], layers = 3, damped = true): SampleBank & { id?: string } => {
- const zones: SampleBank["zones"] = [];
- for (const midi of pitches) for (let layer = 1; layer <= layers; layer++) {
- const a = tone(hz(midi), BRIGHT[layer - 1]);
- const zone: SampleZone = { file: `${id}_${midi}_${layer}.flac`, midi, layer, rr: 1, frames: a.length, channels: 1, peakDb: -6, rmsDb: -14, sha256: (midi * 100 + layer * 10).toString(16).padStart(64, "0") };
- zones.push({ zone, channels: [a] });
- }
- return { entry: { title: id, source: "synthetic", license: "CC0-1.0", kind: "struck", range: [21, 108], layers, damped, normalized: true, zones: zones.map((z) => z.zone) }, zones };
- };
- const key = (p: number, v: number, off = 1.8): Played => ({ p, v, tone: v, t: 0, off, role: "melody", w: v });
- const centroidOf = (x: Float32Array) => centroidHz(x, SR, 0, 0.3);
-
- // ruler measures
- const dark = tone(220, 0.4), bright = tone(220, 0.85), mid = tone(220, 0.65);
- const eD = bandEnvelope(dark, SR, 0, 0.15), eB = bandEnvelope(bright, SR, 0, 0.15), eM = bandEnvelope(mid, SR, 0, 0.15);
- ok(eD.length === PIANO_BANDS.length, "one envelope value per piano band");
- ok(envelopeGap(eD, eD) === 0 && envelopeGap(eD, eB) > 3, `envelope gap: zero for the same take, large dark vs bright (${envelopeGap(eD, eB).toFixed(1)} dB)`);
- ok(Math.abs(envelopeGap(eD, eB.map((x) => x - 20)) - envelopeGap(eD, eB)) < 1e-9, "envelope gap ignores level");
- ok(ruled(eD, eD, eD, eB) === 0 && Math.abs(ruled(eB, eD, eD, eB) - 1) < 1e-9, "ruled: 0 on the truth, 1.0 a whole soft-to-loud step off");
- ok(ruled(eM, eD, eD, eB) > 0.2 && ruled(eM, eD, eD, eB) < 0.9, `ruled: a middle take sits between (${ruled(eM, eD, eD, eB).toFixed(2)})`);
- ok(centroidOf(bright) > centroidOf(dark) * 1.3, "centroid rises with brightness");
- const lead = new Float32Array(SR); lead.set(tone(220, 0.5, 0.5), 4800); ok(Math.abs(onsetOf(lead) - 4800) < 50, "onset found after a silent lead-in");
- const falling = tone(440, 0.5, 2, 0.5), rate = bandDecay(falling, SR, 0, 0.1, 1.5, [[300, 600]])[0];
- ok(Math.abs(rate - 20 * Math.log10(Math.E) / 0.5) < 2, `band decay reads an exponential's rate (${rate.toFixed(1)} dB/s, want 17.4)`);
- ok(Number.isNaN(bandDecay(falling, SR, 0, 0.1, 1.5, [[300, 600], [12000, 16000]])[1]), "band decay: an empty band is NaN, not a number");
-
- // tone colour
- clearBanks();
- try {
- const grand = registerBank("piano", bank("piano", [56, 60, 64]));
- const other = registerBank("vibes", bank("vibes", [56, 60, 64]));
- ok(measuredTone(grand, {}) && !measuredTone(other, {}) && !measuredTone(grand, { velocityTone: "lowpass" }) && !measuredTone(grand, { sampleFilter: "off" }), "tone colour: on for the piano banks, off elsewhere, and off on request");
- const ks = [key(60, 0.3)], picked = sampleZones(grand, ks, 1, [], undefined, true)[0].zone.layer, nearest = sampleZones(grand, ks, 1)[0].zone.layer;
- ok(picked === 2 && nearest === 1, `a blow between layers takes the louder layer to soften (louder ${picked}, nearest ${nearest})`);
- const loud = grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 3)!, soft = grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 1)!;
- ok(toneColour(grand, loud, 60, 0.9) === null && toneColour(grand, soft, 60, 0.9) === null, "never brightens: at or above the take's own layer of an even keyboard there is nothing to do");
- const d = toneColour(grand, loud, 60, 0.5)!;
- ok(d.length === PIANO_BANDS.length && d[16] < d[6] - 3, `softening cuts the top more than the body (7.7 kHz ${d[16].toFixed(1)} dB vs 240 Hz ${d[6].toFixed(1)} dB)`);
- ok(d.every((x) => x <= 6 + 12 && x >= -18 - 12), "colour stays inside its caps (plus the level shift)");
- const truth = soft.channels[0].length ? grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 2)!.channels[0] : new Float32Array(0);
- const asIs = samplerVoice(grand, [key(60, 0.5)], [], SR, SR * 2, { velocityTone: "lowpass", release: "flat" }, 1).L;
- const held = { ...grand, zones: grand.zones.filter((z) => !(z.zone.midi === 60 && z.zone.layer === 2)) };
- const fromLoud = samplerVoice(held, [key(60, 0.5)], [], SR, SR * 2, { release: "flat" }, 1).L, fromLoudPlain = samplerVoice(held, [key(60, 0.5)], [], SR, SR * 2, { velocityTone: "lowpass", release: "flat" }, 1).L;
- const tE = bandEnvelope(truth, SR, 0, 0.15), sE = bandEnvelope(soft.channels[0], SR, 0, 0.15), lE = bandEnvelope(loud.channels[0], SR, 0, 0.15);
- const gOn = ruled(bandEnvelope(fromLoud, SR, 0, 0.15), tE, sE, lE), gOff = ruled(bandEnvelope(fromLoudPlain, SR, 0, 0.15), tE, sE, lE);
- ok(gOn < gOff * 0.6, `held-out middle layer: the softened loud take lands nearer the real one (${gOn.toFixed(2)} vs ${gOff.toFixed(2)})`);
- ok(ruled(bandEnvelope(asIs, SR, 0, 0.15), tE, sE, lE) < 0.05, "a blow at a recorded layer plays that take untouched");
- // a key between recorded pitches: the colour is read between its neighbours
- const shifted = toneColour(grand, grand.zones.find((z) => z.zone.midi === 60 && z.zone.layer === 2)!, 62, 0.5)!;
- ok(Array.isArray(shifted) && shifted.length === PIANO_BANDS.length, "a moved take gets a colour from the keys either side");
- ok(toneColour(grand, grand.zones.find((z) => z.zone.midi === 64 && z.zone.layer === 2)!, 66, 0.5) === null, "past the last recorded key there is no neighbour to read, so nothing changes");
- // filters land on the colour asked for
- let seed = 12345; const noise = Float32Array.from({ length: SR }, () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 2 ** 32) - 0.5);
- const want = PIANO_BANDS.map((f) => (f > 1000 ? -9 : 0)), fs = colourFilters(want, SR), shaped = Float32Array.from(noise); for (const f of fs) f.run(shaped);
- const resp = bandEnvelope(shaped, SR, 0, 1), ref = bandEnvelope(noise, SR, 0, 1);
- const err = [8, 10, 12, 14].map((j) => Math.abs(resp[j] - ref[j] - want[j]));
- ok(Math.max(...err) < 2, `octave filters land within 2 dB of the colour at the octave centres (worst ${Math.max(...err).toFixed(2)} dB)`);
- ok(colourFilters(PIANO_BANDS.map(() => 0), SR).length === 0, "a flat colour builds no filters");
-
- // treble level: one dull take among bright neighbours is lifted inside the cap and its neighbours come down
- const keysOf = (id: string, dull?: number) => { const b = bank(id, [48, 52, 56, 60, 64, 68, 72], 1); b.zones.forEach((z) => { z.channels = [tone(hz(z.zone.midi), z.zone.midi === dull ? 0.55 : 0.85)]; }); return b; };
- const lev = registerBank("piano", keysOf("piano", 60)), fx = trebleFix(lev), at = (m: number) => { const f = fx.get(lev.zones.find((z) => z.zone.midi === m)!); return f ? Math.max(...f.map(Math.abs)) * Math.sign(f.find((x) => x !== 0)!) : 0; };
- ok(at(60) > 0 && at(60) <= TREBLE_LEVEL.liftDb + 1e-9, `a dull take is lifted, never past the cap (${at(60).toFixed(1)} dB, cap ${TREBLE_LEVEL.liftDb})`);
- ok(at(56) < 0 && at(64) < 0, `its brighter neighbours come down to split the rest (${at(56).toFixed(1)}, ${at(64).toFixed(1)} dB)`);
- const flat = trebleFix(registerBank("piano", keysOf("piano"))), most = Math.max(0, ...[...flat.values()].map((f) => Math.max(...f.map(Math.abs))));
- ok(most <= 1.5, `an even keyboard gets at most a small touch (${most.toFixed(1)} dB)`);
- ok(trebleFix(registerBank("piano.upright", keysOf("piano.upright", 60))).size === 0, "the upright is left as recorded");
- const lifted = toneColour(lev, lev.zones.find((z) => z.zone.midi === 60)!, 60, 0.9);
- ok(!!lifted && lifted[16] > lifted[6], "a take at its own key and layer still gets its fixed treble shelf");
-
- // two-band release
- ok(releaseLow(24, 0.5) === 0.5 * RELEASE_SPLIT.lowMul && releaseLow(60, 0.1) === 0.1 && releaseLow(84, 0.08) === 0.08, "the low band lingers longest at the bottom and not at all from middle C up");
- const lowKey = registerBank("piano", bank("piano", [36, 40], 1)), keyUp = 0.6;
- const twoBand = samplerVoice(lowKey, [key(36, 0.8, keyUp)], [], SR, SR * 2, {}, 1).L, flatRel = samplerVoice(lowKey, [key(36, 0.8, keyUp)], [], SR, SR * 2, { release: "flat" }, 1).L;
- const bands: [number, number][] = [[30, 250], [500, 1000]], r2 = bandDecay(twoBand, SR, keyUp, 0.02, 0.2, bands), r1 = bandDecay(flatRel, SR, keyUp, 0.02, 0.2, bands);
- ok(r2[0] < r1[0] * 0.6, `two-band: the bass hum falls slower after key-up (${r2[0].toFixed(0)} vs ${r1[0].toFixed(0)} dB/s)`);
- ok(Math.abs(r2[1] - r1[1]) < r1[1] * 0.25, `two-band: the upper partials still stop as fast (${r2[1].toFixed(0)} vs ${r1[1].toFixed(0)} dB/s)`);
- const before = Math.round(0.5 * SR); ok(twoBand.slice(0, before).every((x, i) => Math.abs(x - flatRel[i]) < 1e-6), "before key-up the split sums back to the take exactly");
- const up = registerBank("piano.upright", bank("piano.upright", [36, 40], 1)), u2 = samplerVoice(up, [key(36, 0.8, keyUp)], [], SR, SR * 2, {}, 1).L, u1 = samplerVoice(up, [key(36, 0.8, keyUp)], [], SR, SR * 2, { release: "flat" }, 1).L;
- ok(u2.every((x, i) => x === u1[i]), "the upright keeps its single-rate release unless asked");
- } finally { clearBanks(); }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/recordedMix.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/recordedMix.test.ts
deleted file mode 100644
index eb06294..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/recordedMix.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { registerBank, clearBanks, type SampleBank } from '../src/canvas-core/music/sampler';
-import { calibrateBank, renderPiece } from '../src/canvas-core/music/render';
-import { maskingPlan, roleBandDb } from '../src/canvas-core/music/guards';
-import { perform } from '../src/canvas-core/music/perform';
-import { Biquad } from '../src/canvas-core/music/dsp';
-import { hz } from '../src/canvas-core/music/theory';
-import { marimbaCurious } from '../src/canvas-core/music/pieces/families';
-import type { Piece, Role } from '../src/canvas-core/music/plan';
-
-export const name = 'recorded support mix';
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 24000, frames = 48000, pitches = [48, 60, 72];
- const zones = pitches.map((midi, i) => {
- const pcm = Float32Array.from({ length: frames }, (_, n) => {
- const t = n / 48000, f = hz(midi);
- return 0.2 * Math.exp(-t * 3) * (Math.sin(2 * Math.PI * f * t) + (i < 2 ? 0.8 * Math.sin(2 * Math.PI * f * 5 * t) : 0));
- });
- return { zone: { file: `${midi}.flac`, midi, layer: 1, rr: 1, frames, channels: 1, peakDb: -6, rmsDb: -18, sha256: String(i + 1).repeat(64) }, channels: [pcm] };
- });
- const bank: SampleBank = { entry: { title: 'spectral fixture', source: 'synthetic', license: 'CC0-1.0', kind: 'struck', range: [48, 72], layers: 1, damped: false, normalized: false, zones: zones.map(z => z.zone) }, zones };
- const source = marimbaCurious();
- const part = source.parts[0];
- const piece = (role: Role, mixed = false): Piece => ({ ...source, tail: 0.2,
- plan: { ...source.plan, space: undefined }, mix: { ...source.mix, eq: 0, transient: null, space: null, drumRoom: null, tilt: 0, busDrive: 0, glue: null, width: { mid: 1, high: 1, monoHz: 0, splitHz: 800 } },
- parts: [{ ...part, inst: 'marimba', role, pan: 0, gainDb: 0, notes: mixed
- ? [{ t: 0, d: 0.4, p: 48, v: 0.5, role: 'bass' }, { t: 0.5, d: 0.4, p: 72, v: 0.5, role: 'accomp' }, { t: 1, d: 0.4, p: 72, v: 0.5, role: 'accomp' }]
- : [{ t: 0, d: 0.4, p: role === 'bass' ? 48 : 60, v: 0.5, role }] }] });
- const fraction = (a: Float32Array) => {
- const x = Biquad.make(sr, 'hp', 40, Math.SQRT1_2).run(Float32Array.from(a));
- const total = x.reduce((s, v) => s + v * v, 0);
- Biquad.make(sr, 'hp', 500, Math.SQRT1_2).run(x); Biquad.make(sr, 'lp', 4000, Math.SQRT1_2).run(x);
- return 10 * Math.log10(x.reduce((s, v) => s + v * v, 0) / total);
- };
- const rms = (a: Float32Array) => Math.sqrt(a.reduce((s, v) => s + v * v, 0) / a.length);
- clearBanks();
- try {
- registerBank('marimba', bank); const calibrated = calibrateBank('marimba');
- const neutral = { ...calibrated, trim: calibrated.trim!.map(t => ({ ...t, bandFractionDb: -40, bandExcessDb: 0 })) };
- const render = (role: Role) => renderPiece(piece(role), sr, { seconds: 2, master: 'none', expressive: false }).dry[0];
- registerBank('marimba', neutral); const unchanged = render('melody'), bassBefore = render('bass'), accompBefore = render('accomp');
- registerBank('marimba', calibrated); const lead = render('melody'), bass = render('bass'), accomp = render('accomp');
- ok(lead.every((v, i) => v === unchanged[i]), 'recorded melody keeps every sample when support EQ measurements change');
- ok(fraction(bass) < fraction(bassBefore) - 2 && fraction(accomp) < fraction(accompBefore) - 1, 'load-measured recorded bass and accompaniment lose masking-band energy');
- ok(Math.abs(20 * Math.log10(rms(bass) / rms(bassBefore))) < 2.5 && Math.abs(20 * Math.log10(rms(accomp) / rms(accompBefore))) < 2.5, 'support EQ retains broadband balance through the existing makeup stage');
- // Keep this fixture below the EQ cap so a wrong role-only selection is audible.
- registerBank('marimba', { ...calibrated, trim: calibrated.trim!.map(t => ({ ...t,
- bandExcessDb: 0, bandFractionDb: t.midi === 48 ? -10 : -6 })) });
- const p = piece('accomp', true);
- // Include one melody note so the guard has a melody role; keep the complete accompaniment context.
- p.parts[0].notes[2].role = 'melody';
- const complete = perform(p, p.plan.tempo, { expressive: false }), plan = maskingPlan(p, { seconds: 2, perf: complete })!;
- const isolated = { ...complete, parts: complete.parts.map(q => ({ ...q, keys: q.keys.filter(k => k.role === 'bass') })) };
- const expected = roleBandDb(p, sr, { seconds: 2, master: 'none', perf: isolated, mixKeys: complete.parts.map(q => q.keys) }, plan.spans);
- const actual = roleBandDb(p, sr, plan.opts('bass'), plan.spans);
- ok(actual.every((v, i) => Math.abs(v - expected[i]) < 1e-8), 'role-isolated guard uses the complete part spectral choice, including mixed-role parts');
- } finally { clearBanks(); }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/recordingWidth.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/recordingWidth.test.ts
deleted file mode 100644
index 7027800..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/recordingWidth.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-// RECORDING WIDTH TESTS. A stereo recording whose sides are out of phase in the body of the sound is
-// narrowed when its bank is registered, so a mono fold keeps it; the air above 2 kHz stays wide; a mono
-// recording and a second registration are left alone.
-// node tools/test.mjs recordingWidth
-import { registerBank, clearBanks, type SampleBank } from "../src/canvas-core/music/sampler";
-
-export const name = "recordingWidth";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 48000, n = sr, tone = (f: number, ph: number) => Float32Array.from({ length: n }, (_, i) => 0.3 * Math.sin(2 * Math.PI * f * (i / sr) + ph));
- const corr = (a: Float32Array, b: Float32Array) => { let c = 0, x = 0, y = 0; for (let i = sr / 4; i < n; i++) { c += a[i] * b[i]; x += a[i] ** 2; y += b[i] ** 2; } return c / Math.sqrt(x * y); };
- const zone = (ch: number) => ({ file: `z${ch}.flac`, midi: 60, layer: 1, rr: 1, frames: n, channels: ch, peakDb: -10, rmsDb: -20, sha256: "a".repeat(64) });
- const bank = (chs: Float32Array[]): SampleBank => ({ entry: { title: "t", source: "s", license: "CC0", kind: "struck", range: [48, 72], layers: 1, damped: false, zones: [zone(chs.length)] }, zones: [{ zone: zone(chs.length), channels: chs }] });
- clearBanks();
- const low = registerBank("t.low", bank([tone(500, 0), tone(500, Math.PI * 0.85)])).zones[0].channels;
- ok(corr(tone(500, 0), tone(500, Math.PI * 0.85)) < -0.8 && corr(low[0], low[1]) > 0.3, `a 500 Hz body recorded out of phase (${corr(tone(500, 0), tone(500, Math.PI * 0.85)).toFixed(2)}) is narrowed until a mono fold keeps it (${corr(low[0], low[1]).toFixed(2)})`);
- const high = registerBank("t.high", bank([tone(6000, 0), tone(6000, Math.PI / 2)])).zones[0].channels;
- ok(Math.abs(corr(high[0], high[1])) < 0.1, `the air above 2 kHz keeps its width (${corr(high[0], high[1]).toFixed(2)})`);
- const mono = tone(500, 0), m = registerBank("t.mono", bank([mono])).zones[0].channels;
- ok(m.length === 1 && m[0] === mono, "a mono recording is left alone");
- const again = registerBank("t.again", { ...bank([low[0], low[1]]) }).zones[0].channels;
- ok(again[0] === low[0], "a recording already narrowed is not narrowed twice");
- clearBanks();
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/rooms.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/rooms.test.ts
deleted file mode 100644
index aee11cb..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/rooms.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-// Recorded responses change the room, never the dry mix. Missing packs retain the old spaces.
-import { registerRoom, roomFor, clearRooms, reverb, type Space } from "../src/canvas-core/music/mixReverb";
-import { renderPiece, voiceJobs, voiceJobKey, runVoiceJob } from "../src/canvas-core/music/render";
-import { nocturne } from "../src/canvas-core/music/pieces/nocturne";
-import { rng } from "../src/canvas-core/core";
-import { MIX_PROFILES } from '../src/canvas-core/music/mixProfiles';
-import { musicBoxJoy, chiptunePlayful } from '../src/canvas-core/music/pieces/samplers';
-import { Biquad } from '../src/canvas-core/music/dsp';
-const fsModule = 'node:fs', { readFileSync } = await import(fsModule);
-export const name = "recorded rooms";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const same = (a: Float32Array, b: Float32Array) => a.length === b.length && a.every((v, i) => v === b[i]);
- const throws = (f: () => unknown) => { try { f(); return false; } catch { return true; } };
- clearRooms();
- try {
- const builder = readFileSync('tools/soundpack.mjs', 'utf8').match(/const ROOMS = \[([\s\S]*?)\n\];/)[1];
- const roomIds = new Set([...builder.matchAll(/id: "([^"]+)"/g)].map((m: any) => m[1]));
- ok(Object.values(MIX_PROFILES).every(p => [p.space?.room, p.drumRoom?.room].every(id => !id || roomIds.has(id))), 'every profile room is present in the pack builder room list');
- const L = new Float32Array(9600), R = new Float32Array(9600); L[0] = 0.6; R[0] = 0.5; L[3840] = 0.4; R[4320] = -0.4;
- const p = nocturne(), roomPiece = { ...p, plan: { ...p.plan, space: { ...p.plan.space, room: "test" } } }, o = { seconds: 0.7, master: "none" as const, stems: true }, before = renderPiece(p, 48000, o), missing = renderPiece(roomPiece, 48000, o), jobs = voiceJobs(roomPiece, 48000, o);
- ok(same(before.L, missing.L) && same(before.R, missing.R), "unregistered room falls back bit for bit");
- registerRoom("test", { L, R, rt60: 0.2, sha256: "a".repeat(64) });
- const recorded = renderPiece(roomPiece, 48000, o), again = renderPiece(roomPiece, 48000, o);
- ok(same(before.dry[0], recorded.dry[0]) && same(before.dry[1], recorded.dry[1]) && Object.keys(before.stems).every((id) => same(before.stems[id][0], recorded.stems[id][0])), "registered room leaves dry mix and stems untouched");
- ok(!same(before.wet[0], recorded.wet[0]) && same(recorded.L, again.L) && same(recorded.R, again.R), "recorded wet signal changes and is deterministic");
- const registeredJobs = voiceJobs(roomPiece, 48000, o);
- ok(registeredJobs.every((j, i) => voiceJobKey(j) !== voiceJobKey(jobs[i]) && j.roomHashes?.[0][1] === "a".repeat(64)), "room sha256 pins voice and guard job keys");
- const cache = new Map(), cached = renderPiece(roomPiece, 48000, { ...o, cache });
- ok(same(cached.L, recorded.L) && same(renderPiece(roomPiece, 48000, { ...o, cache }).L, recorded.L), "room renders are identical through cache hits");
- const low = renderPiece(roomPiece, 24000, o);
- ok(low.L.length === 16800 && low.L.every(Number.isFinite) && low.R.every(Number.isFinite) && same(low.L, renderPiece(roomPiece, 24000, o).L), "24 kHz recorded room renders finite and deterministically");
- const s: Space = { kind: "conv", room: "test", rt60: 1, er: 0.4, late: 0.2, hp: 100, lp: 7000, predelayMs: 20 }, impulse = new Float32Array(24000); impulse[0] = 1;
- const wet = reverb(impulse, impulse, 48000, s, rng(1)), lateOnly = reverb(impulse, impulse, 48000, { ...s, er: 0 }, rng(1)), earlyOnly = reverb(impulse, impulse, 48000, { ...s, late: 0 }, rng(1));
- ok(wet[0].slice(0, 960).every((x) => Math.abs(x) < 1e-7) && wet[2].slice(0, 960 + 1920).every((x) => Math.abs(x) < 1e-7), "predelay and 40 ms early/late split keep their timing");
- ok(same(wet[2], lateOnly[2]) && earlyOnly[2].every((x) => x === 0) && !same(earlyOnly[0], wet[0]), "er and late independently control the recorded reflections and tail");
- registerRoom("test", { L: Float32Array.from(L, (x) => -x), R, rt60: 0.2, sha256: "b".repeat(64) });
- ok(voiceJobKey(voiceJobs(roomPiece, 48000, o)[0]) !== voiceJobKey(registeredJobs[0]) && throws(() => runVoiceJob(registeredJobs[0])) && !same(renderPiece(roomPiece, 48000, { ...o, cache }).L, cached.L), "replacing a room invalidates jobs and cache identity");
- ok(throws(() => registerRoom("bad", { L, R: new Float32Array(1), rt60: 0.2, sha256: "c".repeat(64) })) && !roomFor("bad"), "invalid room PCM is rejected before registration");
- clearRooms();
- for (const kind of ["conv", "plate", "fdn"] as const) {
- const a = reverb(impulse, impulse, 48000, { ...s, kind, room: undefined }, rng(3)), b = reverb(impulse, impulse, 48000, { ...s, kind }, rng(3));
- ok(a.every((c, i) => same(c, b[i])), `${kind}: missing room preserves every wet channel bit for bit`);
- }
- for (const make of [musicBoxJoy, chiptunePlayful]) {
- const p = make(), before = renderPiece(p, 24000, o), unknown = renderPiece({ ...p, plan: { ...p.plan, space: { room: 'not-installed' } } }, 24000, o);
- ok(same(before.L, unknown.L) && same(before.R, unknown.R), `${make.name}: an unavailable room-only override retains the original no-pack recipe`);
- }
- const ir = new Float32Array(4800); ir[0] = 0.8; ir[119] = 0.2; ir[240] = 0.1; ir[2400] = 0.01;
- const recordedRoom = { L: ir, R: Float32Array.from(ir), rt60: 0.1, sha256: 'd'.repeat(64), directFrames: 120 };
- registerRoom('trimmed', recordedRoom);
- const roomSpace = { ...s, room: 'trimmed', predelayMs: 0, er: 1, late: 1 };
- for (const rate of [48000, 24000]) {
- const input = new Float32Array(rate / 2); input[0] = 1;
- const a = reverb(input, input, rate, roomSpace, rng(1));
- ok(a[0].slice(0, Math.round(120 * rate / 48000)).every(x => Math.abs(x) < 1e-7), `${rate} Hz: directFrames is removed before the wet reflections`);
- }
- const a = reverb(impulse, impulse, 48000, roomSpace, rng(1));
- const filtered = Float32Array.from(impulse); Biquad.make(48000, 'hp', s.hp, 0.7071).run(filtered); Biquad.make(48000, 'lp', s.lp, 0.7071).run(filtered);
- const energy = (x: Float32Array) => x.reduce((sum, v) => sum + v * v, 0);
- const early = reverb(impulse, impulse, 48000, { ...roomSpace, late: 0 }, rng(1));
- ok(Math.abs(energy(a[2]) / energy(filtered) - (1.5 * 0.36) ** 2) < 1e-6 && Math.abs(energy(early[0]) / energy(filtered) - 0.51 ** 2) < 1e-6, 'recorded early and late each use synthIR unit-per-channel energy');
- registerRoom('trimmed', { ...recordedRoom, directFrames: 121 });
- const named = { ...p, plan: { ...p.plan, space: { room: 'trimmed' } } }, oldJobs = voiceJobs(named, 48000, o);
- registerRoom('trimmed', { ...recordedRoom, directFrames: 122 });
- ok(voiceJobKey(oldJobs[0]) !== voiceJobKey(voiceJobs(named, 48000, o)[0]) && throws(() => runVoiceJob(oldJobs[0])), 'directFrames participates in room cache identity and stale-job rejection');
- ok(throws(() => registerRoom('bad-direct', { ...recordedRoom, directFrames: -1 })), 'invalid directFrames is rejected');
- } finally { clearRooms(); }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sampler.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sampler.test.ts
deleted file mode 100644
index 91eb8d6..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/sampler.test.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-// Tiny synthetic recordings: pitch, dynamics, dampers, bank routing and cache identity, no files.
-import { registerBank, bankFor, clearBanks, samplerVoice, sampleZones, sampleCutoff, sampleGain, bankIdentity, type SampleBank, type SampleZone, pinnedPitch } from "../src/canvas-core/music/sampler";
-import { renderPiece, voiceJobs, runVoiceJob, voiceJobKey, calibrateBank } from "../src/canvas-core/music/render";
-import { nocturne } from "../src/canvas-core/music/pieces/nocturne";
-import { marimbaCurious } from "../src/canvas-core/music/pieces/families";
-import { hz } from "../src/canvas-core/music/theory";
-import { centroid, stemRms } from "../src/canvas-core/music/meter";
-import { pianoVelocity } from "../src/canvas-core/music/keysPiano";
-import { Biquad } from "../src/canvas-core/music/dsp";
-import { ampSim, transientGain } from "../src/canvas-core/music/mixDsp";
-import { lofiStem, LOFI_DUSTY } from "../src/canvas-core/music/lofiFx";
-import type { Played } from "../src/canvas-core/music/perform";
-const cryptoModule = "node:crypto", { createHash } = await import(cryptoModule);
-
-export const name = "sampler";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const SR = 48000, key = (p = 60, v = 1, t = 0, off = 0.2): Played => ({ p, v, t, off, role: "melody", w: v });
- const bank = (pitches = [60], layers = 1, rrs = 1, damped = false, rich = false): SampleBank => {
- const zones: SampleBank["zones"] = [];
- for (const midi of pitches) for (let layer = 1; layer <= layers; layer++) for (let rr = 1; rr <= rrs; rr++) {
- const a = new Float32Array(SR * 3), f = hz(midi);
- for (let i = 0; i < a.length; i++) a[i] = 0.3 * Math.exp(-i / (SR * 2)) * (Math.sin(2 * Math.PI * f * i / SR + (rr - 1) * 0.3) + (rich ? 0.7 * Math.sin(2 * Math.PI * 6500 * i / SR) : 0));
- const zone: SampleZone = { file: `${midi}_${layer}_${rr}.flac`, midi, layer, rr, frames: a.length, channels: 1, peakDb: -6, rmsDb: -14, sha256: (midi * 100 + layer * 10 + rr).toString(16).padStart(64, "0") };
- zones.push({ zone, channels: [a] });
- }
- return { entry: { title: "Test", source: "synthetic", license: "CC0-1.0", kind: "struck", range: [21, 108], layers, damped, normalized: true, zones: zones.map((z) => z.zone) }, zones };
- };
- const render = (b: SampleBank, ks = [key()], sr = SR, pedal: [number, number][] = [], opts = {}, seed = 1) => samplerVoice(b, ks, pedal, sr, sr * 3, opts, seed);
- const same = (a: Float32Array, b: Float32Array) => a.length === b.length && a.every((v, i) => v === b[i]);
- const rms = (a: Float32Array) => Math.sqrt(a.reduce((s, v) => s + v * v, 0) / Math.max(1, a.length));
- const throws = (f: () => unknown, re: RegExp) => { try { f(); return false; } catch (e) { return re.test(String(e)); } };
- const pitch = (a: Float32Array, sr: number) => {
- const ts = []; for (let i = Math.round(sr * 0.1); i < sr * 0.6; i++) if (a[i - 1] <= 0 && a[i] > 0) ts.push(i - 1 - a[i - 1] / (a[i] - a[i - 1]));
- return sr * (ts.length - 1) / (ts[ts.length - 1] - ts[0]);
- };
- const cents = (f: number, m: number) => Math.abs(1200 * Math.log2(f / hz(m)));
- clearBanks();
- try {
- const b = bank(), a = render(b), up = render(b, [key(62)]), lowRate = render(b, [key(62)], 24000);
- ok(cents(pitch(up.L, SR), 62) < 3, "two-semitone repitch is within 3 cents");
- ok(cents(pitch(lowRate.L, 24000), 62) < 3 && lowRate.L.every(Number.isFinite), "24 kHz stems render finite and in tune");
- // Unity playback still has the velocity low-pass, but the source reader must use integer frames.
- const expected = Float32Array.from(b.zones[0].channels[0], (v) => v * sampleGain(b.entry, b.zones[0].zone, 1));
- ok(same(a.L, expected) && same(a.L, a.R), "in-tune 48 kHz mono keeps original attack frames above the layer centre");
- const rich = bank([60], 1, 1, false, true), soft = render(rich, [key(60, 0.2)]), loud = render(rich, [key()]);
- ok(rms(loud.L) > rms(soft.L) * 3 && centroid([soft.L, soft.R], SR).energyWeighted > centroid([loud.L, loud.R], SR).energyWeighted * 0.85, "normalized dynamics stay expressive and soft notes retain their attack spectrum");
- const natural = bank([60], 2); natural.entry.normalized = false; natural.zones[1].channels[0] = Float32Array.from(natural.zones[0].channels[0], (v) => v * 2);
- const softLayer = render(natural, [{ ...key(60, 0.25), tone: 0.25 }]), hardLayer = render(natural, [{ ...key(60, 0.75), tone: 0.75 }]);
- ok(rms(hardLayer.L) > rms(softLayer.L) * 1.9, "unnormalized layers retain the source's level relationship");
- const damped = bank([60], 1, 1, true), dry = render(damped), held = render(damped, [key()], SR, [[0, 2]]), noPedal = render(damped, [key()], SR, [[0, 2]], { pedal: false });
- const tail = (o: { L: Float32Array }) => rms(o.L.subarray(Math.round(SR * 1.2), Math.round(SR * 1.4)));
- ok(tail(dry) === 0 && tail(noPedal) === 0 && tail(held) > 0.01 && tail(a) > 0.01, "middle-register damper is silent 1 s after lift; pedal holds; undamped rings");
- ok(rms(held.halo!) > 0 && rms(noPedal.halo!) === 0, "the pedal feeds a room halo and pedal:false disables it");
- const caught = render(damped, [key()], SR, [[0.2, 1.5]]), boundary = render(damped, [key()], SR, [[0, 0.2]]);
- ok(tail(caught) > 0.01 && tail(boundary) === 0, "pedal spans use the piano's inclusive down, exclusive up boundary");
- const registers = bank([36, 90], 1, 1, true), bass = render(registers, [key(36)]), treble = render(registerBank("piano", registers), [key(90)]);
- ok(rms(bass.L.subarray(SR * 0.3, SR * 0.4)) > 0 && tail(treble) > 0.01, "bass dampers close slowly; top grand keys have no dampers");
- ok(tail(render(registerBank("vibes", registers), [key(90)])) === 0 && tail(render(registerBank("piano.upright", registers), [key(90)])) === 0, "vibes and upright top keys still have dampers");
- clearBanks();
- ok(throws(() => render(b, [key(20)]), /Ab0.*A0.*C8/), "out-of-range note throws with note name and playable range");
- const varied = { ...key(), vary: { cents: 12, db: -6, bright: 1, decay: 1, phase: 0, seed: 17 } }, detuned = render(b, [varied]);
- ok(Math.abs(1200 * Math.log2(pitch(detuned.L, SR) / hz(60)) - 12) < 3 && rms(detuned.L) < rms(a.L) * 0.6, "per-note cents and dB are applied");
- const unpitched = bank(); unpitched.zones[0].zone.unpitched = true;
- ok(cents(pitch(render(unpitched, [varied]).L, SR), 60) < 3 && same(render(unpitched, [key(62)]).L, a.L), "unpitched zones never transpose, including cents variation");
- ok(same(render(b).L, a.L) && same(render(b, [key()], SR, [], {}, 99).L, a.L), "deterministic output; changing seed cannot change a single recording");
-
- const rb = bank([60, 63], 3, 3), repeated = Array.from({ length: 8 }, (_, i) => ({ ...key(61, 0.65, i * 0.3), vary: { cents: 0, db: 0, bright: 1, decay: 1, phase: 0, seed: 42 } }));
- const picks = sampleZones(rb, repeated, 1);
- ok(picks.every((z) => z.zone.midi === 60 && z.zone.layer === 2), "nearest pitch is chosen before the nearest velocity layer");
- ok(picks.every((z, i) => !i || z !== picks[i - 1]), "round robins never repeat back to back, even with identical note seeds");
- ok(sampleZones(rb, repeated, 1).every((z, i) => z === picks[i]) && sampleZones(rb, repeated, 99).every((z, i) => z === picks[i]), "each note's own seed owns its round robin");
- const fallback = repeated.map(({ vary, ...k }) => k), p1 = sampleZones(rb, fallback, 1), p2 = sampleZones(rb, fallback, 2);
- ok(p1.some((z, i) => z !== p2[i]) && p2.every((z) => z.zone.midi === 60 && z.zone.layer === 2), "a changed fallback seed changes round robins only");
- const rrA = render(rb, repeated), rrB = render(rb, repeated);
- ok(same(rrA.L, rrB.L) && same(rrA.R, rrB.R) && same(rrA.halo!, rrB.halo!), "repeated-note renders are bit-identical");
- const sparse = bank([60, 63], 3); sparse.zones = sparse.zones.filter((z) => z.zone.midi !== 60 || z.zone.layer === 1); sparse.entry.zones = sparse.zones.map((z) => z.zone);
- ok(sampleZones(sparse, [key(61, 1)], 1)[0].zone.midi === 60, "a missing layer never pulls a note to a farther pitch");
- ok(sampleZones(rb, [key(60, 0.332), key(60, 1 / 3), key(60, 0.666), key(60, 2 / 3)], 1).map((z) => z.zone.layer).join() === "1,2,2,3", "default centres split layers at 1/3 and 2/3, boundaries choose the harder layer");
- const custom = bank([60], 3); custom.entry.layerVelocity = [0.1, 0.35, 0.6];
- ok(sampleZones(custom, [key(60, 0.55), { ...key(60, 1), tone: 0.2 }], 1).map((z) => z.zone.layer).join() === "3,3", "manifest centres override defaults; played velocity owns the layer, tone only shapes the filter");
- const arts = bank([60], 2, 2, true), add = (art: "sus" | "rel") => {
- for (const z of arts.zones.slice().filter((z) => !z.zone.art)) { const zone = { ...z.zone, art, file: `${art}_${z.zone.file}`, sha256: (art === "sus" ? "a" : "b").repeat(64) }, channels = [art === "rel" ? new Float32Array(480).fill(0.25) : Float32Array.from(z.channels[0], (v) => v * 0.5)]; zone.frames = channels[0].length; arts.zones.push({ zone, channels }); }
- arts.entry.zones = arts.zones.map((z) => z.zone);
- };
- add("sus"); add("rel");
- const strikes = [key(60, 0.2, 0), key(60, 0.2, 0.2), key(60, 0.8, 0.5), key(60, 0.2, 1)];
- ok(sampleZones(arts, strikes, 7, [[0.2, 1]]).map((z) => z.zone.art ?? "ordinary").join() === "ordinary,sus,sus,ordinary", "sus only for strikes under the pedal, including both boundaries");
- const missingSus = { ...arts, zones: arts.zones.filter((z) => z.zone.art !== "sus" || z.zone.layer === 1) };
- ok(!sampleZones(missingSus, [key(60, 0.8)], 1, [[0, 1]])[0].zone.art, "missing sus at the ordinary pitch/layer falls back to ordinary");
- const ordinary = { ...arts, zones: arts.zones.filter((z) => !z.zone.art) }, withoutRel = { ...arts, zones: arts.zones.filter((z) => z.zone.art !== "rel") };
- ok(same(render(arts, [key()], SR, [[0, 2]], { pedal: false }).L.subarray(0, SR * 0.2), render(ordinary, [key()]).L.subarray(0, SR * 0.2)), "pedal:false never selects a sus recording");
- const release = (off: number, pedal: [number, number][] = []) => { const ks = [key(60, 0.5, 0, off)], a = render(arts, ks, SR, pedal), b = render(withoutRel, ks, SR, pedal); return Float32Array.from(a.L, (v, i) => v - b.L[i]); };
- const relEarly = release(0.1), relLate = release(1), relHeld = release(0.1, [[0.05, 1.2]]);
- ok(relEarly.slice(0, SR * 0.1).every((x) => x === 0) && rms(relEarly.subarray(SR * 0.1, SR * 0.11)) > 0 && relEarly.slice(SR * 0.11).every((x) => x === 0), "rel fires once at key-up for its exact recorded duration");
- ok(relHeld.slice(0, SR * 1.2).every((x) => x === 0) && rms(relHeld.subarray(SR * 1.2, SR * 1.21)) > 0 && relHeld.slice(SR * 1.21).every((x) => x === 0), "a caught note fires rel at pedal-up, once");
- const overlapping = [key(60, 0.5, 0, 0.12), key(60, 0.5, 0.1, 0.3)], overlapWith = render(arts, overlapping), overlapDry = render(withoutRel, overlapping), overlapRel = Float32Array.from(overlapWith.L, (x, i) => x - overlapDry.L[i]);
- ok(overlapRel.subarray(0, SR * 0.12).every((x) => x === 0) && rms(overlapRel.subarray(SR * 0.12, SR * 0.13)) > 0 && overlapRel.subarray(SR * 0.13, SR * 0.3).every((x) => x === 0) && rms(overlapRel.subarray(SR * 0.3, SR * 0.31)) > 0, "restruck notes release at each actual key-up, never at the artificial string choke");
- const ownLevel = rms(render(withoutRel, [key(60, 0.5, 0, 0.1)]).L.subarray(SR * 0.08, SR * 0.1));
- ok(Math.abs(20 * Math.log10(rms(relEarly.subarray(SR * 0.1, SR * 0.11)) / ownLevel) + 15) < 0.01 && rms(relEarly) > rms(relLate) * 1.4, "rel is 15 dB below the remaining string level, later releases are quieter");
- const undamped = { ...arts, entry: { ...arts.entry, damped: false } };
- ok(same(render(undamped).L, render({ ...undamped, zones: undamped.zones.filter((z) => z.zone.art !== "rel") }).L), "undamped instruments never add rel");
- const top = bank([90], 1, 1, true), relTop = { ...top.zones[0], zone: { ...top.zones[0].zone, art: "rel" as const }, channels: [new Float32Array(SR * 3).fill(0.25)] }; top.zones.push(relTop); top.entry.zones.push(relTop.zone);
- ok(same(render(registerBank("piano", top), [key(90)]).L, render({ ...top, entry: { ...top.entry, damped: false } }, [key(90)]).L), "undamped grand treble never adds rel"); clearBanks();
- ok(same(render(arts, strikes, SR, [[0.2, 1]], {}, 7).L, render(arts, strikes, SR, [[0.2, 1]], {}, 7).L), "sus and rel round robins render deterministically");
- ok(same(render(arts, [key(64)]).L, render(withoutRel, [key(64)]).L), "rel outside the two-semitone allowance is skipped");
- const ordinaryHash = bankIdentity(arts.entry), changedArt = { ...arts.entry, zones: arts.entry.zones.map((z) => z.art === "sus" ? { ...z, art: "rel" as const } : z) };
- ok(bankIdentity(changedArt) !== ordinaryHash, "articulations belong in the bank identity");
- ok(Math.abs(sampleCutoff(custom.entry, custom.zones[1].zone, { ...key(), tone: 0.2 }, SR, "relative") - (350 + 17650 * 0.85 ** 2)) < 1e-8 && sampleCutoff(custom.entry, custom.zones[1].zone, { ...key(), tone: 0.35 }, SR, "relative") === Infinity, "relative filter uses the chosen centre, bypassing at and above it");
- ok(same(render(b, [key()], SR, [], { sampleFilter: "off" }).L, expected), "filter-off plays unity-rate PCM with only its dynamic gain");
- ok(sampleGain(natural.entry, natural.zones[0].zone, 0.25) === 1 && Math.abs(20 * Math.log10(sampleGain(natural.entry, natural.zones[0].zone, 0.35)) - 1.6) < 1e-10 && sampleGain(natural.entry, natural.zones[0].zone, 0) === 0, "non-normalized gain is unity at the layer centre, gently relative below and above, silent at zero");
- ok([0.1, 0.3, 0.6, 0.8, 1].every((v) => sampleGain(b.entry, b.zones[0].zone, v) === pianoVelocity(v) * Math.pow(10, -8 * Math.max(0, 0.6 - v) / 20)), "normalized banks use exactly the modeled piano velocity law, including its soft-register level compensation");
- const calibration = bank([60], 3, 2); calibration.entry.normalized = false;
- for (const z of calibration.zones) { const v = (z.zone.layer - 0.5) / 3, dynamic = pianoVelocity(v) * Math.pow(10, -8 * Math.max(0, 0.6 - v) / 20); z.channels[0] = Float32Array.from(z.channels[0], (x) => x * dynamic); }
- const original = calibration.zones.map((z) => Float32Array.from(z.channels[0])); registerBank("piano", calibration);
- const calibrated = calibrateBank("piano"), redo = calibrateBank("piano");
- ok(calibrated.hash === redo.hash && JSON.stringify(calibrated.trim) === JSON.stringify(redo.trim), "pitch/layer calibration is deterministic from PCM and fixed modeled references");
- ok(calibrated.trim!.every(t => Number.isFinite(t.bandFractionDb) && Number.isFinite(t.bandExcessDb)), "load calibration measures every zone's masking-band fraction and excess over its modeled reference");
- ok(calibrated.zones.every((z, i) => same(z.channels[0], original[i])), "calibration never changes recording PCM or tone");
- const measured = (x: Float32Array, y: Float32Array) => { const mid = Float32Array.from(x, (v, i) => (v + y[i]) * 0.5); Biquad.make(SR, "hp", 30, 0.7071).run(mid); let energy = 0; for (const v of mid) energy += v * v; return 10 * Math.log10(energy / (SR * 12)); };
- const levels = [1, 2, 3].map((layer) => { const v = (layer - 0.5) / 3, r = render(calibrated, [{ ...key(60, v, 0, 1), tone: v }], SR, [], { pedal: false }); return measured(r.L, r.R); });
- const refs = [1, 2, 3].map((layer) => calibrated.trim!.find((t) => t.layer === layer)!.modeledDb);
- ok(calibrated.trim!.every((t) => !t.boostLimited && Math.abs(t.correctionDb - t.requestedDb!) < 1e-9) && levels.every((v, i) => Math.abs(v - refs[i]) <= 0.15) && levels.slice(1).every((v, i) => v - levels[i] >= refs[i + 1] - refs[i] - 0.15), "healthy calibrated layers meet fixed references and preserve at least the modeled dynamic range");
- ok([0.05, 0.25, 0.65, 1].every((v) => Math.abs(20 * Math.log10(sampleGain(calibration.entry, calibration.zones[2].zone, v))) <= 6.000001), "calibrated non-normalized notes add only a bounded relative adjustment");
- const noisy = bank([60], 3, 2); noisy.entry.normalized = false;
- for (const z of noisy.zones) { const v = (z.zone.layer - 0.5) / 3, dynamic = pianoVelocity(v) * Math.pow(10, -8 * Math.max(0, 0.6 - v) / 20), scale = z.zone.layer === 1 ? 1e-4 : z.zone.layer === 3 ? 1e3 : 1; z.channels[0] = Float32Array.from(z.channels[0], (x) => x * dynamic * 0.001 * scale); }
- registerBank("piano", noisy); const capped = calibrateBank("piano");
- ok(capped.trim!.every((t) => Math.abs(t.correctionDb - t.medianDb!) <= 9.000001) && capped.trim![0].medianDb! > 40, "zone corrections stay within 9 dB of the instrument median, while the whole-instrument trim is unlimited");
- ok(capped.trim!.filter((t) => t.boostLimited).every((t) => t.layer === 1) && capped.trim!.filter((t) => t.boostLimited).length === 2, "only zones needing excessive upward correction trigger louder-layer fallback");
- ok(capped.trim!.filter((t) => t.layer === 3).every((t) => t.requestedDb! < t.medianDb! - 9 && t.correctionDb === t.medianDb! - 9 && !t.boostLimited), "excessive downward corrections are capped too, without promoting an already-loud zone");
- const quietKeys = Array.from({ length: 8 }, (_, i) => key(60, 0.1, i * 0.1));
- const safePicks = sampleZones(capped, quietKeys, 42);
- ok(safePicks.every((z) => z.zone.midi === 60 && z.zone.layer === 2) && safePicks.every((z, i) => !i || z !== safePicks[i - 1]) && sampleZones(capped, quietKeys, 42).every((z, i) => z === safePicks[i]), "quiet zones use the next louder layer at the same pitch, with deterministic non-repeating round robin");
- ok(sampleGain(capped.entry, safePicks[0].zone, 0.1) < 1 && sampleGain(capped.entry, safePicks[0].zone, 0.1) >= Math.pow(10, -6 / 20), "louder-layer fallback is brought down only by the gentle bounded relative gain");
- const noHigher = { ...capped, zones: capped.zones.filter((z) => z.zone.layer === 1) };
- ok(sampleZones(noHigher, [key(60, 0.1)], 1)[0].zone.layer === 1, "a quiet zone without a louder layer keeps its capped correction, never changes pitch or disappears");
- const stillQuiet = { ...capped, trim: capped.trim!.map((t) => t.layer === 2 ? { ...t, boostLimited: true } : t) };
- ok(sampleZones(stillQuiet, [key(60, 0.1)], 1)[0].zone.layer === 3 && sampleZones({ ...capped, zones: capped.zones.filter((z) => z.zone.layer !== 2) }, [key(60, 0.1)], 1)[0].zone.layer === 3, "protection skips still-quiet and missing layers, staying at the selected pitch");
- const protectedArts = { ...arts, trim: arts.zones.filter((z) => z.zone.art !== "rel").map(({ zone: z }) => ({ file: z.file, midi: z.midi, layer: z.layer, measuredDb: -40, modeledDb: -20, correctionDb: z.layer === 1 ? 9 : 0, requestedDb: z.layer === 1 ? 20 : 0, medianDb: 0, boostLimited: z.layer === 1 })) };
- ok(sampleZones(protectedArts, [key(60, 0.1)], 1, [[0, 1]])[0].zone.art === "sus" && sampleZones(protectedArts, [key(60, 0.1)], 1)[0].zone.art === undefined && sampleZones(protectedArts, [key(60, 0.1)], 1)[0].zone.layer === 2, "louder-layer protection keeps sus tied to pedal-at-strike and ordinary playback otherwise");
- clearBanks();
- const invalid = bank([60], 3); invalid.entry.layerVelocity = [0.1, 0.5];
- ok(throws(() => registerBank("piano", invalid), /layerVelocity/), "invalid layerVelocity is rejected");
- const stereo = bank(); stereo.zones[0].zone.channels = 2; stereo.zones[0].channels.push(Float32Array.from(stereo.zones[0].channels[0], (v) => v * -0.25));
- const wide = render(stereo); ok(wide.R.every((v, i) => Math.abs(v + wide.L[i] * 0.25) < 1e-7), "stereo channel phase and level survive playback");
- const high = bank(); for (let i = 0; i < high.zones[0].channels[0].length; i++) high.zones[0].channels[0][i] = 0.3 * Math.sin(2 * Math.PI * 23000 * i / SR);
- const upHigh = render(high, [key(62)]), downHigh = render(high, [key()], 24000), center = (x: Float32Array, sr: number) => rms(x.subarray(sr * 0.1, sr * 0.6));
- ok(center(upHigh.L, SR) < 0.001 && center(downHigh.L, 24000) < 0.001, "sinc removes above-Nyquist energy before pitch-up and 24 kHz downsampling");
- const imagesDb = (x: Float32Array, f: number) => {
- let cc = 0, ss = 0, cs = 0, xc = 0, xs = 0;
- for (let i = 0; i < x.length; i++) { const c = Math.cos(2 * Math.PI * f * i / SR), s = Math.sin(2 * Math.PI * f * i / SR); cc += c*c; ss += s*s; cs += c*s; xc += x[i]*c; xs += x[i]*s; }
- const d = cc*ss-cs*cs, a = (xc*ss-xs*cs)/d, b = (xs*cc-xc*cs)/d;
- let residual = 0, signal = 0;
- for (let i = 0; i < x.length; i++) { const fit = a*Math.cos(2*Math.PI*f*i/SR)+b*Math.sin(2*Math.PI*f*i/SR); residual += (x[i]-fit)**2; signal += fit*fit; }
- return 10*Math.log10(residual/signal);
- };
- const tone = bank([60]); tone.zones[0].channels[0] = Float32Array.from({ length: SR*3 }, (_, i) => 0.3*Math.sin(2*Math.PI*15000*i/SR));
- for (const shift of [-3, -200]) {
- const k = { ...key(), vary: { cents: shift, db: 0, bright: 1, decay: 1, phase: 0, seed: 4 } }, f = 15000*2**(shift/1200);
- const played = render(tone, [k]);
- ok(imagesDb(played.L.slice(SR*0.1, SR*0.3), f) < -65, `${shift} cents: downward humanisation has no audible interpolation images`);
- const relZone = { ...tone.zones[0].zone, art: 'rel' as const, file: 'release.flac' }, withRel = { ...tone, entry: { ...tone.entry, damped: true, zones: [...tone.entry.zones, relZone] }, zones: [...tone.zones, { zone: relZone, channels: tone.zones[0].channels }] };
- const release = render(withRel, [k]), without = render({ ...tone, entry: { ...tone.entry, damped: true } }, [k]);
- const isolated = Float32Array.from(release.L.slice(SR*0.22, SR*0.32), (v, i) => v - without.L[SR*0.22+i]);
- ok(imagesDb(isolated, f) < -65, `${shift} cents: pitch-down release noise uses the same clean sinc path`);
- }
- const canonical = JSON.stringify([b.entry.kind, b.entry.range, b.entry.layers, null, b.entry.damped, true, b.entry.zones.map((z) => [z.sha256, z.midi, z.layer, z.rr, z.frames, z.channels, false, null])]);
- ok(bankIdentity(b.entry) === createHash("sha256").update(canonical).digest("hex"), "browser-safe bank identity agrees with SHA-256");
- const wideGaps = bank([60, 72]); wideGaps.entry.sparse = true; wideGaps.entry.maxShift = 6; wideGaps.zones[0].zone.measuredHz = 260;
- const shifted = render(wideGaps, [key(66)]);
- ok(cents(pitch(shifted.L, SR), 66) < 3 && shifted.L.every(Number.isFinite), "sparse banks allow wide shifts; measuredHz does not retune the recording");
-
- for (const [make, want] of [[nocturne, "acd240c8adffd25d00ee5279f2c72d3e"], [marimbaCurious, "d787a58c5704cf940a4404281e33d07a"]] as const) {
- const r = renderPiece(make(), SR), h = createHash("md5"); h.update(new Uint8Array(r.L.buffer)); h.update(new Uint8Array(r.R.buffer));
- ok(h.digest("hex") === want, `${make.name}: no-bank audio matches the pre-change md5`);
- }
- const piece = nocturne(), model = voiceJobs(piece, 24000, { seconds: 0.5 });
- const reg = registerBank("piano", b), sampled = voiceJobs(piece, 24000, { seconds: 0.5 });
- ok(sampled.every((j) => j.kind === "sampled" && j.bankHash === reg.hash) && voiceJobKey(model[0]) !== voiceJobKey(sampled[0]), "sampled jobs carry the bank hash and cannot hit modeled cache entries");
- const processed = { ...sampled[0], post: { id: "probe", seed: 1, lofi: LOFI_DUSTY, amp: 0.3, transient: { maxDb: 3, thrDb: -18, ratio: 2 } } }, { post, ...bare } = processed;
- const full = runVoiceJob(processed), manual = runVoiceJob(bare);
- lofiStem(post.lofi, post.id, manual.L, manual.R, bare.sr, bare.keys.map((k) => k.t), post.seed);
- ampSim(manual.L, manual.R, bare.sr, post.amp); const gr = transientGain(manual.L, manual.R, bare.sr, post.transient);
- ok(same(full.L, manual.L) && same(full.R, manual.R) && full.transientGr === gr, "sampled stems run the existing lo-fi, amp and transient chain in order");
- const disabled = { ...piece, parts: piece.parts.map((p) => ({ ...p, opts: { ...p.opts, sampled: false } })) };
- ok(voiceJobs(disabled, 24000, { seconds: 0.5 }).every((j, i) => { const a = runVoiceJob(j), b = runVoiceJob(model[i]); return j.kind === "piano" && same(a.L, b.L) && same(a.R, b.R); }), "sampled:false retains exact modeled audio");
- ok(voiceJobs({ ...piece, legacy: true }, 24000, { seconds: 0.5 }).every((j) => j.kind !== "sampled"), "legacy pieces never use a registered bank");
- registerBank("piano.upright", bank([63]));
- ok(bankFor("piano", "upright")?.id === "piano.upright" && !bankFor("piano", "felt"), "variants are exact bank ids, with no bare-id fallback");
- const job = sampled[0], replacement = bank(); replacement.zones[0].zone.sha256 = "f".repeat(64); registerBank("piano", replacement);
- ok(bankIdentity(replacement.entry) !== reg.hash && throws(() => runVoiceJob(job), /missing or changed/), "replaced banks invalidate jobs instead of silently serving another voice");
- const sustained = bank(); sustained.entry.kind = "sustained";
- ok(throws(() => registerBank("strings", sustained), /sustained zone without a loop/), "sustained zones without loops are rejected");
- } finally { clearBanks(); }
-
- // a drum pinned to a note lands inside what was recorded, on the same note name
- ok(pinnedPitch(31, [37, 59]) === 43 && pinnedPitch(60, [37, 59]) === 48 && pinnedPitch(43, [37, 59]) === 43, "a pinned pitch moves by octaves into the recorded range (G1 to G2, C4 to C3) and stays put when it is inside");
- ok([24, 31, 38, 60, 72, 90].every((p) => { const q = pinnedPitch(p, [37, 59]); return q >= 37 && q <= 59 && (q - p) % 12 === 0; }), "every pinned pitch stays in range and keeps its note name");
- { let threw = 0; for (const bad of [NaN, Infinity, -Infinity]) try { pinnedPitch(bad, [37, 59]); } catch { threw++; } ok(threw === 3, "a pinned pitch that is not a number is refused, never looped on"); }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/seams.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/seams.test.ts
deleted file mode 100644
index 35396a4..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/seams.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-// SEAM TESTS. src/canvas-core/seams.ts is arithmetic, so the claim it makes (motion carries across
-// the cut at one speed, in one direction, and comes to rest exactly) is held to numbers here.
-// node tools/test.mjs seams
-import { checkSeam, checkSeamPlan, easeIn, easeOut, entryDistance, exitSpeed, matchedMove, matchedZoom, MIN_ZOOM_FROM, speedCeiling, velocityAt } from "../src/canvas-core/seams";
-import type { P } from "../src/canvas-core/core";
-
-export const name = "seams";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
- const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
- const CUT = 100;
-
- // 1. the two curves are mirror images, and the helpers invert each other
- ok([0, 0.2, 0.5, 0.9, 1].every((t) => near(easeOut(t), 1 - easeIn(1 - t))) && easeIn(0) === 0 && easeOut(1) === 1, "easeOut is easeIn mirrored; both run 0 to 1");
- ok(near(entryDistance(exitSpeed(300, 24), 24), 300), "an entry as long as its exit travels the same distance");
- ok(exitSpeed(300, 12) > exitSpeed(300, 24), "a shorter exit over the same distance leaves faster");
-
- // 2. a matched move: one speed on both sides of the cut, in one direction, at rest at both ends
- for (const dir of [0, Math.PI, 0.6, -Math.PI / 2]) {
- const m = matchedMove({ dir, exitDist: 260, exitF: 12, entryF: 40 });
- // what is on screen: the outgoing shot up to CUT - 1, the incoming one from CUT. Each side's own step, as a viewer sees it
- const a = velocityAt((f) => m.out(f, CUT), CUT - 1), b = velocityAt((f) => m.in(f, CUT), CUT + 1), va = Math.hypot(a[0], a[1]), vb = Math.hypot(b[0], b[1]);
- ok(near(va, m.speed, 1e-6) && near(vb, m.speed, 1e-6), `dir ${dir.toFixed(2)}: ${va.toFixed(2)} px a frame into the cut, ${vb.toFixed(2)} out of it`);
- ok(near(Math.atan2(a[1], a[0]), Math.atan2(b[1], b[0]), 1e-6), `dir ${dir.toFixed(2)}: the direction of travel is the same on both sides`);
- ok(checkSeam(a, b, { W: 1920, fps: 30 }).length === 0, `dir ${dir.toFixed(2)}: checkSeam has nothing to say`);
- const s = m.out(CUT - 13, CUT), e = m.in(CUT + 40, CUT), late = m.in(CUT + 400, CUT), early = m.out(0, CUT), end = m.out(CUT - 1, CUT);
- ok(near(Math.hypot(s[0], s[1]), 0) && near(Math.hypot(early[0], early[1]), 0) && near(Math.hypot(e[0], e[1]), 0) && near(Math.hypot(late[0], late[1]), 0), `dir ${dir.toFixed(2)}: at rest before the exit and from the end of the entry on`);
- ok(near(Math.hypot(end[0], end[1]), 260, 1e-9), `dir ${dir.toFixed(2)}: the whole exit is travelled by the outgoing shot's last frame on screen, CUT - 1`);
- const last = velocityAt((f) => m.in(f, CUT), CUT + 40); ok(Math.hypot(last[0], last[1]) < m.speed * 0.01, `dir ${dir.toFixed(2)}: it lands with no speed left`);
- }
- let mono = true; { const m = matchedMove({ exitDist: 260, exitF: 12, entryF: 40 }); for (let f = CUT - 13; f < CUT + 40; f++) if (f !== CUT - 1 && (f < CUT - 1 ? m.out(f + 1, CUT)[0] < m.out(f, CUT)[0] : m.in(f + 1, CUT)[0] < m.in(f, CUT)[0])) mono = false; }
- ok(mono, "neither side ever travels backwards");
- ok(throws(() => matchedMove({ exitDist: 100, exitF: 1, entryF: 20 })) && throws(() => matchedMove({ exitDist: 100, exitF: 10, entryF: 0 })) && throws(() => matchedMove({ exitDist: NaN, exitF: 10, entryF: 20 })) && throws(() => matchedMove({ exitDist: 100, exitF: Infinity, entryF: 20 })), "a one-frame exit, a zero-frame entry, an endless exit or a distance that is not a number is refused");
- // the card's own numbers at 30 fps: a 0.2 s exit and a 0.5 s entry, measured on the frames a viewer sees
- { const m = matchedMove({ exitDist: 260, exitF: 6, entryF: 15 }), a = velocityAt((f) => m.out(f, CUT), CUT - 1), b = velocityAt((f) => m.in(f, CUT), CUT + 1); ok(near(a[0], b[0], 1e-6) && checkSeam(a, b, { W: 1920, fps: 30 }).some((x) => x.msg.includes("past what blur")) === (a[0] > speedCeiling(1920, 30)), `a 6-frame exit and a 15-frame entry: ${a[0].toFixed(1)} px a frame on both displayed sides`); }
-
- // 3. a matched zoom: the same rate of growth on both sides, in log space, landing on 1
- const z = matchedZoom({ push: 1.2, exitF: 6, entryF: 15 });
- ok(near(z.out(CUT - 7, CUT), 1) && near(z.out(CUT - 1, CUT), 1.2) && near(z.in(CUT, CUT), z.from) && near(z.in(CUT + 15, CUT), 1) && near(z.in(CUT + 99, CUT), 1), "zoom: 1 before, the push at the cut, `from` after it, 1 at rest");
- const rOut = Math.log(z.out(CUT - 1, CUT) / z.out(CUT - 2, CUT)), rIn = Math.log(z.in(CUT + 1, CUT) / z.in(CUT, CUT));
- ok(near(rOut, z.rate, 1e-9) && near(rIn, z.rate, 1e-9), `zoom: growing ${(100 * (Math.exp(rOut) - 1)).toFixed(1)}% a frame into the cut and ${(100 * (Math.exp(rIn) - 1)).toFixed(1)}% out of it`);
- ok(z.from > 0.4 && z.from < 1, `zoom: the incoming shot opens at ${z.from.toFixed(2)} of its size, inside what a scene can be drawn at`);
- ok(throws(() => matchedZoom({ push: 0.9, exitF: 6, entryF: 15 })) && throws(() => matchedZoom({ exitF: 1, entryF: 15 })), "a push of 1 or less, or a one-frame exit, is refused");
- ok(throws(() => matchedZoom({ push: 2, exitF: 6, entryF: 30 })) && throws(() => matchedZoom({ push: 4, exitF: 2, entryF: 60 })) && matchedZoom({ push: 1.2, exitF: 6, entryF: 15 }).from >= MIN_ZOOM_FROM, `a zoom whose incoming shot would open under ${MIN_ZOOM_FROM} of its size is refused`);
-
- // 4. checkSeam names each way a cut between moving shots goes wrong
- const o = { W: 1920, fps: 30 }, has = (f: { msg: string }[], s: string) => f.some((x) => x.msg.includes(s));
- ok(checkSeam([0, 0], [0.2, 0], o).length === 0, "two shots at rest: nothing to match");
- ok(has(checkSeam([40, 0], [0, 0], o), "at rest") && has(checkSeam([0, 0], [40, 0], o), "at rest"), "one side at rest, one moving: flagged");
- ok(has(checkSeam([40, 0], [-40, 0], o), "turns") && has(checkSeam([40, 0], [0, 40], o), "turns") && has(checkSeam([40, 0], [30, 26], o), "turns") && !has(checkSeam([40, 0], [39, 9], o), "turns"), "a reversal, a right angle and a 41 degree turn are flagged; 13 degrees is not");
- ok(throws(() => checkSeam([NaN, 0], [40, 0], o)) && throws(() => checkSeam([40, 0], [40, 0], { W: 1920, fps: 0 })) && throws(() => checkSeam([40, 0], [40, 0], { W: undefined as unknown as number, fps: 30 })), "a velocity that is not a number, or a missing size or frame rate, is refused, never passed");
- ok(has(checkSeam([40, 0], [20, 0], o), "drops") && has(checkSeam([40, 0], [80, 0], o), "jumps") && checkSeam([40, 0], [46, 0], o).length === 0, "half or double the speed is flagged; 15% off is not");
- ok(near(speedCeiling(1920, 60), 80) && has(checkSeam([200, 0], [200, 0], o), "past what blur"), "the ceiling is 2.5 widths a second (80 px a frame at 1920 and 60 fps), and a move past it is flagged");
-
- // 5. the seam plan: a designed seam twice, the signature three times, cuts as often as wanted
- const p = (type: string, n: number, x: object = {}) => Array.from({ length: n }, () => ({ type, ...x }));
- ok(checkSeamPlan([...p("iris", 2), ...p("matched cut", 6, { cut: true }), ...p("ink bloom", 3, { signature: true })]).length === 0, "two irises, six cuts and the signature three times pass");
- ok(has(checkSeamPlan(p("iris", 3)), '"iris" is used 3 times') && has(checkSeamPlan(p("ink bloom", 4, { signature: true })), "4 times"), "a third iris and a fourth signature are flagged");
- ok(has(checkSeamPlan([...p("bloom", 1, { signature: true }), ...p("wipe", 1, { signature: true })]), "2 signature moves"), "two signature moves are flagged");
- ok(has(checkSeamPlan([{ type: "Iris" }, { type: "iris" }, { type: " iris " }]), "3 times"), "a seam is counted whatever its capitals and spaces");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sfxFrozenPlans.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sfxFrozenPlans.ts
deleted file mode 100644
index 552b9d1..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/sfxFrozenPlans.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-// Launch-template cue sequences (launchTemplate.ts): typing, Generate/drop/card, reveal.
-import { launchLofi3 } from "../src/canvas-core/music/index";
-import { renderPiece } from "../src/canvas-core/music/render";
-import type { SfxPlan } from "../src/canvas-core/music/sfxMix";
-export const frozenPlans = (sr: number) => {
- const piece = launchLofi3(), r = renderPiece(piece, sr), music: [Float32Array, Float32Array] = [r.L, r.R];
- const base = { fps: 30, frames: 240, seed: 7, score: { piece } };
- const plans: SfxPlan[] = [
- { ...base, cues: [
- { frame: 12, kind: "tick", variant: "key", gainDb: 1.5, label: 'key "m"' },
- { frame: 16, kind: "tick", variant: "key" }, { frame: 19, kind: "tick", variant: "space" },
- { frame: 24, kind: "tick", variant: "key" }, { frame: 28, kind: "tick", variant: "key" },
- ] },
- { ...base, cues: [
- { frame: 30, kind: "press", variant: "thock", label: "Generate" },
- { frame: 37, kind: "ink", variant: "plip", label: "the drop lifts" },
- { frame: 48, kind: "ink", variant: "bloom", label: "it blooms into the card" },
- { frame: 54, kind: "pop", variant: "cork", label: "the card lands (spring)" },
- ] },
- { ...base, cues: [
- { frame: 120, kind: "riser", variant: "soft", beats: 4, label: "into the reveal" },
- { frame: 120, kind: "impact", variant: "bloom", label: "the reveal" },
- ] },
- ];
- return { plans, music };
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts
deleted file mode 100644
index d8e50d4..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { mixSfx, filmSfx, sfxHarshness, type PlacedCue, type SfxPlan, type SfxHarshOptions } from "../src/canvas-core/music/sfxMix";
-import { frozenPlans } from "./sfxFrozenPlans";
-import { survey } from "./sfxKitSurvey";
-const cryptoModule = "node:crypto", { createHash } = await import(cryptoModule);
-const hash = (L: Float32Array, R: Float32Array) => createHash("sha256").update(new Uint8Array(L.buffer)).update(new Uint8Array(R.buffer)).digest("hex");
-export const name = "sfx harshness";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 48000, n = sr * 2;
- const music: [Float32Array, Float32Array] = [Float32Array.from({ length: n }, (_, i) => 0.04 * Math.sin(2 * Math.PI * 220 * i / sr) + 0.006 * Math.sin(2 * Math.PI * 4000 * i / sr)), new Float32Array(n)];
- music[1].set(music[0]);
- const synth = (f: number): PlacedCue => {
- const L = Float32Array.from({ length: sr / 4 }, (_, i) => i < sr * 0.02 ? 0.5 * Math.sin(2 * Math.PI * f * i / sr) : 0), R = L.slice();
- return { i: 0, cue: { frame: 15, kind: "tick", label: `${f} Hz` }, sound: { L, R, sr, kind: "tick", variant: "ui", seed: 1, hit: 0, window: [0, sr * 0.02], lufs: 0 }, hitS: 0.5, snappedFromS: 0.5, start: sr / 2, window: [sr / 2, sr * 0.52] };
- };
- const piercing = synth(4000), dull = synth(100), before = hash(piercing.sound.L, piercing.sound.R);
- const high = sfxHarshness([piercing], music, sr, {})[0], low = sfxHarshness([dull], music, sr, {})[0];
- ok(!high.ok && high.violations?.some((v) => v.metric === "liftDb"), "a loud 4 kHz burst exceeds the default lift cap");
- ok(low.ok && Math.abs(low.cueRmsDb - high.cueRmsDb) < 1e-6, "a 100 Hz thump at the same RMS passes");
- ok(high.peakDb > high.bodyDb + 10 && high.crestDb === high.peakDb - high.bodyDb, "a short peak with little following body has a large peak-body gap");
- ok(hash(piercing.sound.L, piercing.sound.R) === before, "measurement never changes the cue samples");
- const silence: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)], silent = sfxHarshness([piercing], silence, sr, {})[0];
- ok(silent.liftDb === null && silent.peakMarginDb === null && silent.violations.every((v) => v.metric !== "liftDb"), "silence-relative fields are null and lift is skipped");
- const click = synth(4000); click.sound.L.fill(0); click.sound.R.fill(0); click.sound.L[0] = click.sound.R[0] = 0.5;
- const impulse = sfxHarshness([click], silence, sr, {})[0];
- ok(impulse.bodyDb === -200 && impulse.peakAtS === 0.5 && Math.abs(impulse.peakDb + 6.020599913) < 1e-8, "body starts after the first peak: a single sample has no body");
- const tail = synth(4000); tail.sound.L.fill(0); tail.sound.R.fill(0); tail.sound.L[0] = tail.sound.R[0] = 0.5;
- tail.sound.L.fill(0.1, 1, 1 + sr * 0.15); tail.sound.R.set(tail.sound.L);
- const body = sfxHarshness([tail], silence, sr, {})[0];
- ok(Math.abs(body.bodyDb + 20) < 1e-6, "the 150 ms body uses stereo mean-power RMS without a +3 dB boost");
- const plan: SfxPlan = { fps: 30, frames: 60, cues: [{ frame: 15, kind: "tick", variant: "ui", label: "piercing key" }] };
- const report = mixSfx(music, plan, sr), cap = report.harshness[0].peakDb - 3, options: SfxHarshOptions = { maxPeakDb: cap, maxTiltDb: 0, maxLiftDb: 100 };
- const explicit = mixSfx(music, { ...plan, harsh: { ...options, mode: "report" } }, sr);
- ok(hash(report.L, report.R) === hash(explicit.L, explicit.R) && explicit.ok && !explicit.harshness[0].ok, "report flags a peak breach and keeps samples and audibility verdict unchanged");
- let message = "";
- try { mixSfx(music, { ...plan, harsh: { ...options, mode: "throw" } }, sr); } catch (e) { message = (e as Error).message; }
- ok(/piercing key/.test(message) && /peakDb/.test(message) && /cap/.test(message), `throw names the cue, metric, measured value and cap: ${message.replace(/\n/g, " ")}`);
- const tame = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame" } }, sr), tameAgain = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame" } }, sr);
- ok(tame.harshness[0].ok && tame.harshness[0].peakDb <= cap && tame.ok && tame.harshness[0].reductionDb >= 3, "tame lowers the peak under the cap and keeps the cue audible");
- ok(hash(tame.L, tame.R) === hash(tameAgain.L, tameAgain.R) && plan.cues[0].gainDb === undefined, "tame is deterministic and leaves the caller's plan alone");
- const liftCap = report.harshness[0].liftDb! - 2, lifted = mixSfx(music, { ...plan, harsh: { mode: "tame", maxLiftDb: liftCap, maxTiltDb: 0 } }, sr);
- ok(lifted.harshness[0].ok && lifted.harshness[0].liftDb! <= liftCap && lifted.ok, "tame lowers a lift breach under the cap while audible");
- const conflict = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame", maxPeakDb: cap - 60 } }, sr);
- ok(!conflict.harshness[0].ok && conflict.harshness[0].conflict === "audibility floor" && conflict.ok && conflict.audibility[0].marginDb >= conflict.audibility[0].minDb, "an impossible cap reports an audibility conflict and stays audible");
- const tiltCap = report.harshness[0].tiltDb - 1, tilt = mixSfx(music, { ...plan, harsh: { mode: "tame", maxTiltDb: tiltCap, maxPeakDb: cap } }, sr);
- ok(hash(tilt.L, tilt.R) === hash(report.L, report.R) && tilt.harshness[0].conflict === "tilt cannot be fixed by gain" && tilt.harshness[0].reductionDb === 0, "a tilt breach leaves the cue unchanged and explains that gain cannot fix it");
- message = ""; try { mixSfx(null, { ...plan, harsh: { mode: "throw", maxTiltDb: tiltCap } }, sr); } catch (e) { message = (e as Error).message; }
- ok(/tiltDb/.test(message) && /piercing key/.test(message), "throw still rejects a tilt breach over silence");
- const override = mixSfx(music, { ...plan, harsh: { ...options, mode: "throw" }, cues: [{ ...plan.cues[0], harsh: { maxPeakDb: 0 } }] }, sr);
- ok(override.harshness[0].ok, "a per-cue cap overrides the plan cap");
- const floor = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame", maxPeakDb: cap - 60 }, cues: [{ ...plan.cues[0], minDb: 0 }] }, sr);
- ok(floor.ok && floor.audibility[0].marginDb >= 0, "tame respects the per-cue audibility floor");
- const buriedPlan: SfxPlan = { ...plan, cues: [{ ...plan.cues[0], gainDb: -40 }], harsh: { mode: "tame", maxPeakDb: -100 } }, buried = mixSfx(music, buriedPlan, sr);
- ok(!buried.ok && buried.harshness[0].conflict === "audibility floor" && buried.harshness[0].reductionDb === 0, "tame never lowers an already buried cue");
- const overSilence = mixSfx(null, { ...plan, harsh: { ...options, mode: "tame" } }, sr);
- ok(overSilence.ok && overSilence.harshness[0].ok && overSilence.harshness[0].liftDb === null, "over silence, tame still enforces the absolute peak cap");
- for (const harsh of [{ mode: "unknown" }, { maxLiftDb: NaN }, { maxTiltDb: Infinity }, { maxPeakDb: "hot" }]) {
- message = ""; try { mixSfx(null, { ...plan, harsh: harsh as SfxHarshOptions }, sr); } catch (e) { message = (e as Error).message; }
- ok(/harsh\./.test(message), `invalid harsh option rejected: ${JSON.stringify(harsh)}`);
- }
- // Plan 2's hash covers the impact boom's shorter low tail (0.38 s decay).
- // Captured from production sources at c1beddfe4264a34d12531dbe931acef611fb0a02,
- // loaded by git show and bundled with these fixtures before the mixer was edited.
- const hashes = ["5db7c646b1e61b0016c5dd8a114e875f6cedbaed17f6b702a225ba2dcc187a85", "3064c924f76acb857c509a5c294cf043380451d544fda0b5372ce06d33ef133a", "f2fb798441ecf453b18de3ee2c849810e6fd56f4eaa14fd2002600985fb189f6"];
- const frozen = frozenPlans(sr);
- // the old peak-only master stays bit-identical when asked for; the loudness master is tested in delivery.test.ts
- frozen.plans.forEach((p0, i) => { const p = { ...p0, master: "none" as const }, m = mixSfx(frozen.music, p, sr), f = filmSfx(() => frozen.music, p)(sr);
- ok(hash(m.L, m.R) === hashes[i] && hash(...f) === hashes[i], `launch cue plan ${i}: mixSfx and filmSfx match base SHA-256 ${hashes[i]}`);
- });
- for (const row of survey()) ok(row.ok, `${row.kind}:${row.variant} over ${row.context}: default gain passes the measured default caps`);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sfxKitSurvey.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sfxKitSurvey.ts
deleted file mode 100644
index af4fe38..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/sfxKitSurvey.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-// Fixed calibration context: default gain, C major / 90 bpm, seed 1, 48 kHz.
-// A steady -22.36 dBFS score (220 Hz + 440 Hz + a quiet 4 kHz partial), no modulation.
-import { SFX_KINDS, sfxVariants, renderSfx } from "../src/canvas-core/music/sfxKit";
-import { sfxDuck, sfxHarshness, type PlacedCue } from "../src/canvas-core/music/sfxMix";
-export const survey = () => {
- const sr = 48000, n = sr * 12, L = Float32Array.from({ length: n }, (_, i) => 0.1 * Math.sin(2 * Math.PI * 220 * i / sr) + 0.035 * Math.sin(2 * Math.PI * 440 * i / sr) + 0.02 * Math.sin(2 * Math.PI * 4000 * i / sr));
- const silence: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)];
- return SFX_KINDS.flatMap((kind) => sfxVariants(kind).flatMap((variant) => {
- const sound = renderSfx(kind, { variant, key: "C", bpm: 90 }, sr), start = 4 * sr - sound.hit;
- const pc: PlacedCue = { i: 0, cue: { kind, variant, frame: 120 }, sound, hitS: 4, snappedFromS: 4, start, window: [start + sound.window[0], start + sound.window[1]] };
- const duck = sfxDuck([pc], n, sr), bed = Float32Array.from(L, (x, i) => x * duck[i]);
- return ([["silence", silence], ["score", [bed, bed]]] as [string, [Float32Array, Float32Array]][]).map(([context, music]) => ({ context, ...sfxHarshness([pc], music, sr, {})[0] }));
- }));
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/soundcheck.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/soundcheck.test.ts
deleted file mode 100644
index 51627b8..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/soundcheck.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-// SOUNDCHECK TESTS. Each fault the scorecard exists to catch, built on purpose in code (a hole, a
-// dead tail, a late start, a decorrelated pair, a rumble-heavy mix, a crowded body, a quiet master, a cut
-// ending), and each must show up in its own metric, with a fix that names the time or the band.
-import { analyze, evaluate, startHere, visualEvents, visualSync, buildProfile, profileFrom, grade, DEFAULT_PROFILE } from "../src/canvas-core/music/soundcheck";
-import { loudness } from "../src/canvas-core/music/meter";
-
-export const name = "soundcheck";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const sr = 48000;
- // mulberry32, never a plain LCG: an LCG's interleaved left/right outputs are correlated per band and fake a near -1 low-band correlation
- let seed = 9; const rnd = () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return (((t ^ (t >>> 14)) >>> 0) / 4294967296) * 2 - 1; };
- /** A plucked chord every 0.25 s over a soft pad: music-like, steady, correlated (the same in both ears). */
- const music = (secs: number, { from = 0, to = secs, amp = 0.2 } = {}) => {
- const n = Math.round(secs * sr), L = new Float32Array(n), R = new Float32Array(n);
- for (let i = Math.round(from * sr); i < Math.min(n, Math.round(to * sr)); i++) {
- const t = i / sr, ph = t % 0.25, env = Math.exp(-ph * 10);
- const v = amp * (0.5 * Math.sin(2 * Math.PI * 330 * t) + 0.3 * Math.sin(2 * Math.PI * 495 * t) * env + 0.3 * Math.sin(2 * Math.PI * 1320 * t) * env + 0.15 * Math.sin(2 * Math.PI * 110 * t) + 0.05 * rnd());
- L[i] = v; R[i] = v;
- }
- return [L, R] as [Float32Array, Float32Array];
- };
- const at = (L: Float32Array, R: Float32Array, opts?: { allow?: [number, number][] }) => analyze(L, R, sr, opts).measures;
- const row = (m: ReturnType<typeof at>, k: string) => evaluate(m).find((r) => r.key === k)!;
-
- // a clean, steady, centred mix: no holes, no tail, sound from frame 0, nothing lost in mono
- const clean = at(...music(6));
- ok(clean.firstSound === 0 && clean.insideGap === 0 && clean.endSilence < 0.06, `clean mix: first sound ${clean.firstSound} s, longest hole ${clean.insideGap} s, end silence ${clean.endSilence.toFixed(2)} s`);
- ok(Math.abs(clean.monoLoss) < 0.1 && clean.bodyCorr > 0.99 && clean.corr > 0.99, `identical channels fold to mono with ${clean.monoLoss.toFixed(2)} dB extra loss, 150-2k correlation ${clean.bodyCorr.toFixed(2)}`);
- ok(["insideGap", "endSilence", "firstSound", "bodyCorr", "monoLoss", "rumble"].every((k) => row(clean, k).status === "PASS"), "clean mix passes the shape, stereo and rumble checks");
-
- // the loudness number agrees with the meter, and a -27 LUFS master fails with the gain it needs
- const [qL, qR] = music(6, { amp: 0.02 }), q = at(qL, qR), ref = loudness([qL, qR], sr).integrated;
- ok(Math.abs(q.lufs - ref) < 1e-9, `integrated loudness is meter.ts's own (${q.lufs.toFixed(2)} LUFS)`);
- ok(row(q, "lufs").status === "FAIL" && /LU under the web target/.test(row(q, "lufs").fix ?? ""), `a ${q.lufs.toFixed(1)} LUFS master fails: "${row(q, "lufs").fix?.slice(0, 60)}..."`);
- const gain = Math.pow(10, (-14 - ref) / 20), [tL, tR] = [qL.map((x) => x * gain), qR.map((x) => x * gain)], tgt = at(tL, tR);
- ok(Math.abs(tgt.lufs + 14) < 0.05 && row(tgt, "lufs").status === "PASS", `mastered to ${tgt.lufs.toFixed(2)} LUFS: PASS`);
-
- // a 1 s hole at 2.0 s: caught, timed, and its fix names the time; --allow over it clears it
- const [hL, hR] = music(6); for (let i = 2 * sr; i < 3 * sr; i++) { hL[i] = 0; hR[i] = 0; }
- const hole = at(hL, hR);
- ok(Math.abs(hole.insideGap - 1) <= 0.06 && Math.abs((hole.insideGapAt ?? 0) - 2) <= 0.06, `a 1 s hole at 2.0 s reads ${hole.insideGap.toFixed(2)} s at ${hole.insideGapAt?.toFixed(2)} s`);
- const hf = startHere(evaluate(hole)).find((r) => r.key === "insideGap");
- ok(row(hole, "insideGap").status === "FAIL" && /1\.0 s hole at 0:02\.0/.test(hf?.fix ?? ""), `the fix says where: "${hf?.fix?.slice(0, 40)}..."`);
- ok(!startHere(evaluate(hole)).some((r) => r.key === "arcDip"), "the arc dip inside that hole is the same fault: one fix, not two");
- ok(at(hL, hR, { allow: [[1.9, 3.1]] }).insideGap === 0, "a declared held breath (--allow 1.9:3.1) is not a hole");
- const [sL, sR] = music(6); for (let i = 2 * sr; i < 2.15 * sr; i++) { sL[i] = 0; sR[i] = 0; }
- ok(row(at(sL, sR), "insideGap").status === "PASS", `a 0.15 s breath is not a hole (${at(sL, sR).insideGap.toFixed(2)} s)`);
-
- // a dead tail and a late start
- const tail = at(...music(6, { to: 3 }));
- ok(Math.abs(tail.endSilence - 3) <= 0.06 && row(tail, "endSilence").status === "FAIL" && /from 0:03\.0/.test(row(tail, "endSilence").fix ?? ""), `3 s of dead tail: ${tail.endSilence.toFixed(2)} s from ${tail.endSilenceFrom.toFixed(2)} s, FAIL`);
- const late = at(...music(6, { from: 1.5 }));
- ok(Math.abs((late.firstSound ?? 0) - 1.5) <= 0.06 && row(late, "firstSound").status === "FAIL", `sound starting at 1.5 s: first sound ${late.firstSound} s, FAIL`);
-
- // a cut ending against a faded one
- const cut = at(...music(4));
- const [fL, fR] = music(4); for (let i = 3.5 * sr; i < 4 * sr; i++) { const g = Math.max(0, 1 - (i - 3.5 * sr) / (0.45 * sr)); fL[i] *= g; fR[i] *= g; }
- ok(row(cut, "tailLu").status === "FAIL" && row(at(fL, fR), "tailLu").status === "PASS", `a film that stops mid-note fails the tail (${cut.tailLu.toFixed(1)} LU); faded, it passes`);
-
- // a decorrelated pair: independent noise in each ear
- const n = 4 * sr, dL = new Float32Array(n), dR = new Float32Array(n); for (let i = 0; i < n; i++) { dL[i] = 0.1 * rnd(); dR[i] = 0.1 * rnd(); }
- const dec = at(dL, dR), df = startHere(evaluate(dec));
- ok(Math.abs(dec.bodyCorr) < 0.1 && Math.abs(dec.monoLoss - 3) < 0.3, `decorrelated pair: 150-2k correlation ${dec.bodyCorr.toFixed(2)}, mono loses ${dec.monoLoss.toFixed(2)} dB past the expected 3`);
- ok(row(dec, "bodyCorr").status === "FAIL" && row(dec, "monoLoss").status === "FAIL" && df.filter((r) => ["bodyCorr", "monoLoss", "corr", "sideMid"].includes(r.key)).length === 1 && /below 2 kHz/.test(df.find((r) => r.key === "bodyCorr")?.fix ?? ""), "it fails, and the four stereo numbers make one fix: narrow the width below 2 kHz");
- // decorrelated only in the body: a 600 Hz tone a quarter-turn apart, a centred 5 kHz tone
- const bL = new Float32Array(n), bR = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr, c = 0.1 * Math.sin(2 * Math.PI * 5000 * t); bL[i] = 0.2 * Math.sin(2 * Math.PI * 600 * t) + c; bR[i] = 0.2 * Math.cos(2 * Math.PI * 600 * t) + c; }
- const body = at(bL, bR);
- ok(Math.abs(body.bodyCorr) < 0.1 && body.bandCorr.sparkle > 0.95, `body-only decorrelation is seen per band (150-2k ${body.bodyCorr.toFixed(2)}, sparkle ${body.bandCorr.sparkle.toFixed(2)})`);
-
- // a rumble-heavy mix and a crowded body, each with a band-specific fix
- const [uL, uR] = music(4, { amp: 0.05 }); for (let i = 0; i < uL.length; i++) { const v = 0.4 * Math.sin(2 * Math.PI * 40 * (i / sr)); uL[i] += v; uR[i] += v; }
- const sub = at(uL, uR);
- ok(sub.bands.rumble > -3 && row(sub, "rumble").status === "FAIL" && /under 40 Hz/.test(row(sub, "rumble").fix ?? ""), `rumble-heavy: ${sub.bands.rumble.toFixed(1)} dB of the energy under 80 Hz, FAIL, "roll off under 40 Hz"`);
- ok(clean.bands.rumble < -20, `the clean mix keeps ${clean.bands.rumble.toFixed(1)} dB under 80 Hz`);
- const [xL, xR] = music(4, { amp: 0.03 }); for (let i = 0; i < xL.length; i++) { const v = 0.3 * Math.sin(2 * Math.PI * 630 * (i / sr)); xL[i] += v; xR[i] += v; }
- const box = at(xL, xR);
- ok(row(box, "body").status === "FAIL" && box.peakHz.body === 630 && /630 Hz/.test(row(box, "body").fix ?? ""), `crowded body: ${box.bands.body.toFixed(1)} dB, strongest third-octave ${box.peakHz.body} Hz named in the fix`);
-
- // a held breath: a steady bed that dips 15 dB for 0.4 s and snaps back
- const [pL, pR] = music(6); for (let i = 3 * sr; i < 3.4 * sr; i++) { pL[i] *= 0.18; pR[i] *= 0.18; }
- const sd = at(pL, pR);
- ok(sd.heldBreaths.length === 1 && Math.abs(sd.heldBreaths[0].at - 3) < 0.1, `a 0.4 s, 15 dB dip reads as one held breath at ${sd.heldBreaths[0]?.at.toFixed(2)} s`);
-
- // the profile: ranges grade PASS / WARN / FAIL, and a built profile moves taste ranges but never the delivery limits
- ok(grade(-14, { min: -16, max: -13, tol: 1 }) === "PASS" && grade(-16.5, { min: -16, max: -13, tol: 1 }) === "WARN" && grade(-18, { min: -16, max: -13, tol: 1 }) === "FAIL" && grade(5, undefined) === "INFO", "grade: inside PASS, within tolerance WARN, beyond FAIL, no range INFO");
- const built = buildProfile("test", [{ file: "a", measures: clean }, { file: "b", measures: tgt }]), prof = profileFrom(built);
- ok(built.metrics.lufs.min <= built.metrics.lufs.median && built.metrics.lufs.median <= built.metrics.lufs.max && built.from.length === 2, `built profile: lufs ${built.metrics.lufs.min}..${built.metrics.lufs.max}, median ${built.metrics.lufs.median}`);
- ok(JSON.stringify(prof.ranges.endSilence) === JSON.stringify(DEFAULT_PROFILE.ranges.endSilence) && prof.ranges.lufs.min !== DEFAULT_PROFILE.ranges.lufs.min && prof.ranges.sparkle !== undefined, "a built profile sets the taste ranges (loudness, bands) and keeps the hard ones (end silence)");
-
- // picture against sound
- const changed = Array.from({ length: 300 }, (_, i) => (i === 30 || i === 120 || i === 210 ? 0.5 : 0.01));
- const ev = visualEvents(changed, 30);
- ok(ev.length === 3 && Math.abs(ev[0] - 1) < 1e-9, `three cuts in a slow-changing picture read as events at ${ev.map((e) => e.toFixed(2)).join(", ")} s`);
- const vs = visualSync([1, 4, 7], [1.03, 5.5, 6.95], 10);
- ok(Math.abs(vs.share - 2 / 3) < 1e-9 && vs.unanswered.length === 1 && vs.unanswered[0] === 4 && vs.medianOffsetMs === -10, `2 of 3 events have an onset within 100 ms (+30 and -50 ms, median ${vs.medianOffsetMs}); the one at 4 s has none`);
- ok(Number.isFinite(vs.chance) && vs.chance <= 2 / 3, `chance baseline from shifted events: ${Math.round(vs.chance * 100)} %`);
-
- // silence: everything fails cleanly, never NaN-passes
- const z = at(new Float32Array(sr * 2), new Float32Array(sr * 2)), zr = evaluate(z);
- ok(z.silent && zr.find((r) => r.key === "lufs")!.status === "FAIL" && zr.every((r) => r.status !== "PASS" || r.value !== null), "a silent file fails loudness and passes nothing it could not measure");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/textrules.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/textrules.test.ts
deleted file mode 100644
index 310f139..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/textrules.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-// TEXT RULES TESTS. The reading-time rule and the 9:16 phone safe zones, held to known answers,
-// including the failing cases: a cue that is too short, text under the platforms' buttons.
-// @ts-ignore: a plain ES module shared with the tools
-import { SAFE_ZONES, isPortrait916, readingNeed, readingTime, safeZoneHits, zoneRects } from "../tools/textrules.mjs";
-import { PHONE_SAFE } from "../src/canvas-core/launchLayout";
-
-export const name = "textrules";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- // one set of numbers: the layout composes inside PHONE_SAFE, framecheck checks against SAFE_ZONES
- ok(JSON.stringify(SAFE_ZONES) === JSON.stringify(PHONE_SAFE), `the checked safe zones are the ones the launch layout composes for (${JSON.stringify(SAFE_ZONES)})`);
- // ---- reading time: max(0.7 s, 0.3 s per word)
- ok(readingNeed("Hi") === 0.7 && readingNeed("one two") === 0.7, "one or two words need the 0.7 s floor");
- ok(Math.abs(readingNeed("one two three four five six") - 1.8) < 1e-9, "six words need 1.8 s (0.3 s each)");
- const fps = 30, cue = (text: string, s: number) => ({ from: 100, to: 100 + Math.round(s * fps), text });
- ok(readingTime([cue("IDEA IN.", 0.7), cue("one two three four five six", 1.8)], fps).status === "PASS", "cues exactly at their reading time pass");
- const short = readingTime([cue("IDEA IN.", 0.7), cue("one two three four five six", 1.5)], fps);
- ok(short.status === "FAIL" && short.bad.length === 1 && short.bad[0].need === 1.8 && short.bad[0].seconds === 1.5, `NEGATIVE: a 6-word cue up for 1.5 s fails (${JSON.stringify(short.bad[0])})`);
- ok(readingTime([cue("Yes", 0.6)], fps).status === "FAIL", "NEGATIVE: one word up for 0.6 s fails the 0.7 s floor");
- ok(readingTime([{ from: 0, to: 20, text: "Yes" }], 30).status === "FAIL" && readingTime([{ from: 0, to: 21, text: "Yes" }], 30).status === "PASS", "the floor is 21 frames at 30 fps, 20 fails");
- ok(readingTime([], fps).status === "N/A" && readingTime(undefined, fps).status === "N/A", "no declared cues is N/A, never a pass");
- ok(readingTime([{ from: 0, to: 5, text: " " }], fps).status === "N/A", "a blank cue is not text: N/A");
- ok(readingTime([cue("IDEA IN.", 0.7)], fps).status !== "N/A", "declared text is judged");
-
- // ---- the 9:16 frame and its zones
- ok(isPortrait916(1080, 1920) && isPortrait916(720, 1280) && !isPortrait916(1920, 1080) && !isPortrait916(1080, 1350) && !isPortrait916(1080, 1080), "9:16 is detected by shape, not by name");
- const z = zoneRects(1080, 1920);
- ok(z.length === 3 && z[0].y1 === 1920 * SAFE_ZONES.top && z[1].y0 === 1920 * (1 - SAFE_ZONES.bottom) && z[2].x0 === 1080 * (1 - SAFE_ZONES.right), "three zones: top band, bottom band, right button column");
- ok(SAFE_ZONES.top >= 0.12 && SAFE_ZONES.bottom >= 0.2 && SAFE_ZONES.right >= 0.1, "the shares are the conservative ones, not the minimum");
- const text = (label: string, x0: number, y0: number, x1: number, y1: number, frame = 0) => ({ kind: "text", label, x0, y0, x1, y1, frame });
- const inside = text("whole", 200, 600, 800, 700), W = 1080, H = 1920;
- ok(safeZoneHits([inside], W, H).status === "PASS", "text in the middle of the frame passes");
- const top = safeZoneHits([text("TITLE", 100, 40, 900, 120)], W, H);
- ok(top.status === "FAIL" && top.hits[0].zone === "top band", "NEGATIVE: text in the top band fails");
- const bottom = safeZoneHits([text("npm i x", 100, 1600, 900, 1700)], W, H);
- ok(bottom.status === "FAIL" && bottom.hits[0].zone === "bottom band", "NEGATIVE: text in the bottom band fails");
- const right = safeZoneHits([text("CLAIM", 700, 800, 1060, 900)], W, H);
- ok(right.status === "FAIL" && right.hits[0].zone === "right button column", "NEGATIVE: text running into the right button column fails");
- ok(safeZoneHits([text("edge", 100, 270, 900, 280)], W, H).status === "PASS", "text that only touches a zone's border passes");
- const many = safeZoneHits([text("TITLE", 100, 40, 900, 120, 0), text("TITLE", 100, 40, 900, 120, 5), text("TITLE", 100, 40, 900, 120, 9)], W, H);
- ok(many.hits.length === 1 && many.hits[0].frames.join() === "0,5,9", "one row per text and zone, with every frame it was seen on");
- ok(safeZoneHits([{ kind: "box", label: "card", x0: 0, y0: 0, x1: 1080, y1: 1920, frame: 0 }], W, H).status === "PASS", "content boxes are not judged here, only text");
- ok(safeZoneHits([text("TITLE", 100, 40, 900, 120)], 1920, 1080).status === "N/A", "a 16:9 frame is N/A, never judged against phone zones");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/timeRemap.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/timeRemap.test.ts
deleted file mode 100644
index 3293528..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/timeRemap.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-// TIME REMAP TESTS. src/canvas-core/timeRemap.ts is arithmetic, so its claims (time is continuous and
-// never runs backwards, a ramp has no kick, a freeze says what keeps moving, a sound can be cued on a
-// remapped event) are held to numbers here. node tools/test.mjs timeRemap
-import { timeRemap, type TimeKey } from "../src/canvas-core/timeRemap";
-
-export const name = "timeRemap";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
- const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
-
- // 1. no keys is real time; a key at speed 1 changes nothing
- const id = timeRemap([]);
- ok([-5, 0, 0.5, 37, 900].every((f) => id.at(f) === f && id.speedAt(f) === 1), "no keys: scene frame = film frame, speed 1");
- ok([0, 12, 300].every((f) => timeRemap([{ f: 10, speed: 1 }]).at(f) === f), "a key at speed 1 is real time");
-
- // 2. exact numbers: a hard change to slow motion, then a smooth ramp back
- const slow = timeRemap([{ f: 30, speed: 0.25 }, { f: 70, speed: 1, ramp: 10 }]);
- ok(near(slow.at(30), 30) && near(slow.at(70), 40) && near(slow.at(50), 35), "speed 0.25 from frame 30: 40 film frames show 10 scene frames");
- ok(near(slow.at(80), 40 + 10 * (0.25 + 1) / 2) && near(slow.at(100), 46.25 + 20), "a ramp covers the mean of its two speeds, then real time resumes");
- ok(near(slow.speedAt(75), 0.25 + 0.75 * 0.5) && near(slow.speedAt(70), 0.25) && near(slow.speedAt(80), 1), "the speed glides from 0.25 to 1 over the ramp, half way at its middle");
-
- // 3. a full ramp-freeze-release: continuous, never backwards, speed continuous, no kick at the ramp ends
- const keys: TimeKey[] = [{ f: 60, speed: 0.3, ramp: 8 }, { f: 90, speed: 0, ramp: 4, keepsMoving: "the name writes itself" }, { f: 126, speed: 1, ramp: 12 }];
- const t = timeRemap(keys);
- let back = false, jump = 0, sjump = 0;
- for (let f = -10; f <= 300; f += 0.125) { const a = t.at(f), b = t.at(f + 0.125); if (b < a - 1e-12) back = true; jump = Math.max(jump, b - a); sjump = Math.max(sjump, Math.abs(t.speedAt(f + 0.125) - t.speedAt(f))); }
- ok(!back, "scene time never runs backwards");
- ok(jump <= 0.125 + 1e-9, `scene time never jumps (largest step ${jump.toFixed(4)} for 0.125 film frames, at most real time here)`);
- ok(sjump < 0.1, `the speed never steps on a smooth ramp (largest change ${sjump.toFixed(4)} per eighth of a frame)`);
- const e = 1e-4, kick = (f: number) => Math.abs(t.speedAt(f + e) - t.speedAt(f)) / e;
- ok([60, 68, 90, 94, 126, 138].every((f) => kick(f) < 1e-2), "smoothstep ramps start and end with no kick (speed flat at both ends)");
- ok(t.freezes.length === 1 && t.freezes[0].from === 94 && t.freezes[0].to === 126 && t.freezes[0].keepsMoving === "the name writes itself", "the freeze is listed from where the speed reaches 0 to the next key, with what keeps moving");
- ok([94, 100, 110.5, 125.99].every((f) => near(t.at(f), t.at(94))), "inside the freeze the scene stands still");
- ok(t.at(127) > t.at(126), "it releases at the next key");
-
- // 4. a linear ramp covers the same area as a smooth one; fast motion runs ahead of real time
- const lin = timeRemap([{ f: 0, speed: 0.5, ramp: 10, curve: "linear" }]), smo = timeRemap([{ f: 0, speed: 0.5, ramp: 10 }]);
- ok(near(lin.at(10), smo.at(10)) && near(lin.at(10), 7.5) && near(lin.speedAt(2.5), 0.875), "linear and smooth ramps cover the same area by their end; linear glides in a straight line");
- ok(near(timeRemap([{ f: 20, speed: 2 }]).at(50), 80), "speed 2 shows two scene frames per film frame");
-
- // 5. cueing a sound on a remapped event: the first film frame that shows it
- for (const target of [10, 61.3, 75, t.at(94), t.at(94) + 0.5, 140, 400]) {
- const f = t.filmFrameOf(target);
- ok(Number.isInteger(f) && t.at(f) >= target - 1e-9 && t.at(f - 1) < target, `scene frame ${target.toFixed(2)} is first shown on film frame ${f}`);
- }
- ok(t.filmFrameOf(t.at(100)) <= 94, "an event at the frozen moment is cued where the freeze begins, not later");
- ok(throws(() => timeRemap([{ f: 10, speed: 0, keepsMoving: "camera creeps" }]).filmFrameOf(50)), "a scene frame past a freeze that never releases is never shown, and says so");
- ok(timeRemap([{ f: 0, speed: 0.01 }]).filmFrameOf(5) === 500, "a very slow remap still finds its frame");
-
- // 6. pure: the same keys give the same numbers in any order of asking
- const a = timeRemap(keys), b = timeRemap(keys), order1 = [200, 5, 100, 61].map((f) => a.at(f)), order2 = [61, 100, 5, 200].map((f) => b.at(f)).reverse();
- ok(JSON.stringify(order1) === JSON.stringify(order2), "the same keys answer the same, whatever order frames are asked in");
-
- // 7. bad input is refused, loudly
- ok(throws(() => timeRemap([{ f: 30, speed: 0 }])) && throws(() => timeRemap([{ f: 30, speed: 0, keepsMoving: " " }])), "a freeze that does not say what keeps moving is refused (dead air)");
- ok(throws(() => timeRemap([{ f: 30, speed: -1 }])) && throws(() => timeRemap([{ f: 30, speed: NaN }])), "a negative or non-number speed is refused: time never runs backwards");
- ok(throws(() => timeRemap([{ f: 30, speed: 1 }, { f: 30, speed: 2 }])) && throws(() => timeRemap([{ f: 3.5, speed: 1 }])) && throws(() => timeRemap([{ f: -1, speed: 1 }])), "keys on repeated, fractional or negative frames are refused");
- ok(throws(() => timeRemap([{ f: 30, speed: 0.5, ramp: 20 }, { f: 40, speed: 1 }])) && throws(() => timeRemap([{ f: 30, speed: 0.5, ramp: -2 }])), "a ramp that runs past the next key, or a negative ramp, is refused");
- ok(throws(() => timeRemap([{ f: 30, speed: 0.5, curve: "bounce" as "smooth" }])), "an unknown ramp curve is refused");
- ok(throws(() => timeRemap([{ f: 30, speed: 1e-9 }])) && throws(() => timeRemap([{ f: 30, speed: 0.005 }])), "a speed so slow it looks frozen is refused: declare a freeze instead");
- ok(timeRemap([{ f: 0, speed: 0, ramp: 10, keepsMoving: "dust" }, { f: 10, speed: 1 }]).freezes.length === 0, "a ramp that fills the gap to the next key lists no empty freeze");
- { let msg = ""; try { timeRemap([{ f: 5, speed: 1 }, { f: 3, speed: 2 }]); } catch (e) { msg = String(e); } ok(msg.includes("must increase"), "keys out of order are reported as out of order"); }
- ok(throws(() => t.at(Infinity)) && throws(() => t.at(NaN)) && throws(() => t.speedAt(NaN)), "a frame that is not a number is refused");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/transitions.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/transitions.test.ts
deleted file mode 100644
index d081895..0000000
--- a/plugins/anidoodle/skills/anidoodle/engine/test/transitions.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// TRANSITION TESTS. The seam math in src/canvas-core/transitions.ts is pure (wipeFront,
-// irisRadius, flashAlpha, checkFlashes, seam), so it is held to numbers here with no browser.
-// brushWipe / iris / flashCut draw through layers and are not covered; flash gets a tiny
-// recording ctx. node tools/test.mjs
-import { checkFlashes, flash, flashAlpha, irisRadius, irisRim, seam, wipeFront } from "../src/canvas-core/transitions";
-import { blot } from "../src/canvas-core/launchKit";
-import type { Ctx, Env, P } from "../src/canvas-core/core";
-
-export const name = "transitions";
-export const run = (ok: (cond: boolean, label: string) => void) => {
- const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
- const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
- // the same point-in-polygon ray cast morph.ts uses (it is private there)
- const inside = (p: P, s: P[]) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
- const W = 1920, H = 1080, corners: P[] = [[0, 0], [W, 0], [W, H], [0, H]];
-
- // 1. seam: a clamped ramp over [at, at + len]
- ok(seam(100, 120, 22) === 0 && seam(119.9, 120, 22) === 0, "seam is 0 before its window");
- ok(seam(131, 120, 22) === 0.5 && seam(142, 120, 22) === 1 && seam(500, 120, 22) === 1, "seam is 0.5 mid-window and 1 from at+len on");
-
- // 2. wipeFront: at p = 0 nothing of the frame is inside the picture polygon, at p = 1 all
- // four corners are - for a straight, a diagonal, a vertical and a backwards stroke
- const mid: P[] = [[W / 2, H / 2], [W * 0.25, H * 0.75], [W * 0.8, H * 0.2]];
- for (const angle of [0, 0.22, Math.PI / 2, Math.PI]) for (const ink of [undefined, "#1d1a16"] as (string | undefined)[]) {
- const o = { angle, ink, seed: 11 };
- ok([...corners, ...mid].every((c) => !inside(c, wipeFront(0, W, H, o))), `wipeFront p=0 angle ${angle.toFixed(2)} ink ${!!ink}: nothing of the frame is inside`);
- ok(corners.every((c) => inside(c, wipeFront(1, W, H, o))), `wipeFront p=1 angle ${angle.toFixed(2)} ink ${!!ink}: all four corners are inside`);
- }
-
- // 3. the ink edge never trails the picture edge: a point inside the picture polygon is
- // inside the ink polygon too, at any progress and any angle
- for (const angle of [0, 0.22, Math.PI / 2, Math.PI]) for (const p of [0.15, 0.5, 0.85]) {
- const pic = wipeFront(p, W, H, { angle, ink: "#1d1a16", seed: 5 }), inked = wipeFront(p, W, H, { angle, ink: "#1d1a16", seed: 5 }, "ink");
- let lead = true;
- for (let y = 0; y <= 20 && lead; y++) for (let x = 0; x <= 36 && lead; x++) { const q: P = [(x * W) / 36, (y * H) / 20]; if (inside(q, pic) && !inside(q, inked)) lead = false; }
- ok(lead, `wipeFront angle ${angle.toFixed(2)} p ${p}: the ink edge is ahead of or equal to the picture edge`);
- }
-
- // 4. the stroke is a pure function of its arguments: same seed, same points
- const w1 = wipeFront(0.5, W, H, { angle: 0.3, seed: 7 });
- ok(JSON.stringify(w1) === JSON.stringify(wipeFront(0.5, W, H, { angle: 0.3, seed: 7 })), "wipeFront: same seed gives identical points");
- ok(JSON.stringify(w1) !== JSON.stringify(wipeFront(0.5, W, H, { angle: 0.3, seed: 8 })), "wipeFront: a different seed is a different brush");
-
- // 5. irisRadius: 0 at p = 0, past the farthest corner at p = 1 even off-centre, reversed
- // with close; a blot's wobbling rim needs more radius than a clean circle
- ok(irisRadius(0, W, H) === 0, "irisRadius is 0 at p = 0");
- const c: P = [120, 90], far = Math.max(...corners.map(([x, y]) => Math.hypot(x - c[0], y - c[1])));
- ok(irisRadius(1, W, H, { center: c }) >= far, `irisRadius at p = 1 covers the farthest corner (${far.toFixed(0)} px from an off-centre centre)`);
- ok(irisRadius(0, W, H, { center: c, close: true }) >= far && near(irisRadius(1, W, H, { close: true }), 0), "close: full radius at p = 0, 0 at p = 1");
- const rb = irisRadius(1, W, H, { shape: "blot", center: [300, 200] }), rc = irisRadius(1, W, H, { center: [300, 200] });
- ok(rb > rc, `a blot needs more radius than a circle (${rb.toFixed(0)} > ${rc.toFixed(0)})`);
- ok([1, 42, 99].every((seed) => corners.every((q) => inside(q, blot([300, 200], rb, seed)))), "the blot's deepest rim dip still covers every corner at p = 1");
-
- // 6. flashAlpha: peak on the cut frame, 0 outside [cut - inF, cut + outF), and the legal
- // minimum still lights four frames - a one-frame flash cannot be built
- ok(near(flashAlpha(100, 100), 0.86), "flashAlpha peaks on the cut frame");
- const lit = Array.from({ length: 30 }, (_, i) => i + 90).filter((f) => flashAlpha(f, 100) > 0);
- ok(lit.length === 11 && lit[0] === 98 && lit[10] === 108, `flashAlpha is > 0 on exactly the inF + outF frames around the cut (${lit.length})`);
- ok(flashAlpha(97, 100) === 0 && flashAlpha(109, 100) === 0, "flashAlpha is 0 outside its window");
- ok(flashAlpha(98, 100) < flashAlpha(99, 100) && flashAlpha(99, 100) < flashAlpha(100, 100), "the light rises into the cut");
- ok(Array.from({ length: 10 }, (_, i) => i + 95).filter((f) => flashAlpha(f, 100, { inF: 1, outF: 3 }) > 0).length === 4, "the tightest legal flash lights 4 frames: never a one-frame flash");
- ok(throws(() => flashAlpha(50, 100, { outF: 2 })) && throws(() => flashAlpha(50, 100, { inF: 0 })), "flashAlpha throws for outF < 3 or inF < 1");
-
- // 7. checkFlashes: one rule - any two flashes closer than half a second throw; the
- // boundary is strict, and however many flashes there are, only the nearest pair matters
- ok(throws(() => checkFlashes([0, 14], 30)), "two flashes 0.47 s apart throw");
- ok(!throws(() => checkFlashes([0, 15], 30)), "two flashes exactly 0.5 s apart pass");
- ok(!throws(() => checkFlashes([0, 15, 30, 45], 30)), "four flashes, all at least half a second apart, pass: the only rule is the pair rule");
- ok(throws(() => checkFlashes([0, 29, 14], 30)), "a close pair throws however the cuts were listed");
- const cuts = [400, 240];
- ok(checkFlashes(cuts, 30) === cuts, "checkFlashes sorts a copy and returns the argument");
-
- // 8. flash() on a recording ctx: one full-frame fill at the computed alpha
- let seen: { a: number; r: number[] } | undefined;
- const rec = { setTransform() {}, globalCompositeOperation: "", globalAlpha: 0, fillStyle: "", fillRect: (...r: number[]) => { seen = { a: rec.globalAlpha, r }; } };
- flash(rec as unknown as Ctx, { W, H, scale: 2 } as unknown as Env, 100, 100);
- ok(near(seen?.a ?? -1, 0.86) && JSON.stringify(seen?.r) === JSON.stringify([0, 0, W, H]), "flash paints the whole frame at the computed alpha");
-
- // 9. seam with len 0 is a hard cut that still answers 0 or 1, never NaN
- ok(seam(119.9, 120, 0) === 0 && seam(120, 120, 0) === 1 && seam(500, 120, 0) === 1, "seam(local, at, 0): 0 before at, 1 from at");
- ok(seam(119.9, 120, -3) === 0 && seam(120, 120, -3) === 1, "a negative len behaves the same");
- ok([seam(NaN, 120, 0), seam(-1e9, 120, 0), seam(1e9, 120, 0)].every((v) => v === 0 || v === 1), "seam is never NaN");
-
- // 10. irisRim: 0 at R = 0, grows without a step bigger than rim/20 per px, full width by
- // R = 70 - so the ink rim never appears or vanishes in one frame
- for (const [o, rim] of [[{ shape: "blot" }, 22], [{ rim: 10 }, 10]] as const) {
- ok(irisRim(0, o) === 0 && irisRim(70, o) === rim && irisRim(200, o) === rim, `irisRim (rim ${rim}): 0 at R = 0, full ${rim} px from R = 70`);
- let prev = 0, stepOk = true;
- for (let R = 0.5; R <= 100; R += 0.5) { const v = irisRim(R, o); if (v - prev > rim / 20 + 1e-12 || v < prev - 1e-12) stepOk = false; prev = v; }
- ok(stepOk, `irisRim (rim ${rim}) grows continuously, no step over ${(rim / 20).toFixed(2)} px`);
- }
- ok(irisRim(50, {}) === 0 && irisRim(50, { shape: "circle" }) === 0, "a clean circle has no rim");
-
- // 11. wipeFront stays finite on degenerate input: no bristles, an ease that overshoots
- const finite = (s: P[]) => s.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y));
- ok(finite(wipeFront(0.5, W, H, { bristles: 0 })), "wipeFront with bristles: 0 still gives finite points");
- ok(finite(wipeFront(0.5, W, H, { ease: () => 1.7 })) && finite(wipeFront(0.5, W, H, { ease: () => -0.4 })), "wipeFront with an ease returning 1.7 or -0.4 still gives finite points");
-};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs
index 68852b4..7a30284 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs
@@ -183,6 +183,7 @@ const run = async () => {
};
const selfTest = async () => {
let wrong = 0;
+ if (!existsSync("test/fixtures")) { console.error("gate --self-test: the fixtures are not in this install (the directory copy leaves them out). Clone https://github.com/alexgreensh/anidoodle to run it."); process.exit(2); }
for (const file of readdirSync("test/fixtures").filter((f) => f.endsWith(".mjs")).sort()) {
const fixture = (await import(`../test/fixtures/${file}`)).default;
const { meta, render, expected } = fixture;
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjs
index c71d816..2085e7f 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjs
@@ -72,7 +72,7 @@ for (const f of ["package.json", "package-lock.json", "tsconfig.json"]) if (exis
if (opt.example) {
const ex = join(SKILL, "example", "src");
- if (!existsSync(ex)) die(`--example asked for, but ${ex} is not there`);
+ if (!existsSync(ex)) die(`--example: the worked film is not in this install (the directory copy leaves it out to stay small). Clone https://github.com/alexgreensh/anidoodle and run its skills/anidoodle/engine/tools/scaffold.mjs with --example.`);
cpSync(ex, join(target, "src"), { recursive: true });
}
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/test.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/test.mjs
index a345dfe..e881881 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/test.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/test.mjs
@@ -2,10 +2,11 @@
// (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 { existsSync, readdirSync } from "node:fs";
import { overlay } from "./overlay.mjs";
const only = process.argv.slice(2);
+if (!existsSync("test")) { console.error("test: the unit suites are not in this install (the directory copy leaves them out to stay small). Clone https://github.com/alexgreensh/anidoodle to run them."); process.exit(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;
diff --git a/plugins/anidoodle/skills/anidoodle/example/README.md b/plugins/anidoodle/skills/anidoodle/example/README.md
deleted file mode 100644
index 6096b4d..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/README.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# MECHANICAL LEPIDOPTERA — the worked example
-
-1410 frames, 47.0 s at 30 fps, 1080x1080. A clockwork butterfly is drawn on a blueprint sheet,
-comes alive, and leaves its blueprint behind in the grass. Every pixel and every audio sample is
-drawn by code. No images, no fonts, no samples.
-
-`butterfly-film-spec.md` is the spec it was built from — the story, the shot list, the cue grid,
-the realism section, the music. Read that first; it is what a good spec looks like.
-
-## Study it. Do not copy it.
-
-This is here as proof of craft, not as a template. Copying it gets you somebody else's film with
-your title on it, and none of the craft bar in `SKILL.md` is satisfied by inheritance.
-
-What is worth opening, and why:
-
-| File | What it shows |
-|---|---|
-| `src/canvas-core/mechanicalLepidoptera.ts` | a whole film as data: meta, shots tiling `[0, duration)`, the score attached |
-| `src/canvas-core/butterfly/act1cues.ts` | ONE cue table holding every frame number, with a checker that runs at load |
-| `src/canvas-core/butterfly/alive/anatomy.ts` | realism as code: a closed discal cell, veins that fork and never cross, a scalloped margin — and a header naming the four reference images actually opened |
-| `src/canvas-core/butterfly/alive/lateral.ts` | the second AUTHORED view. A closed wing is the same wing stood up, not a folded one |
-| `src/canvas-core/butterfly/surface.ts` | a cache key that names everything its pixels depend on |
-| `src/canvas-core/butterfly/plate.ts` | `live()` vs `still()`: two kits, so a surface drawn at some boil cannot be given a key that omits it |
-| `src/canvas-core/butterfly/alive/score.ts` | the music recipe as arithmetic, with every onset asserted onto the frame grid |
-| `src/canvas-core/butterfly/kit.ts` | the draftsman's marks: a ruling pen that is never quite straight |
-
-## Running it
-
-The example is not a project on its own — its modules import `../core`, which lives in the
-engine. Put the two together:
-
-```bash
-node <skill>/engine/tools/scaffold.mjs ~/study --example
-cd ~/study && npm install
-node tools/still.mjs mechanicalLepidoptera --out out/look.png
-node tools/gate.mjs mechanicalLepidoptera --mp4 out/mechanical-lepidoptera.mp4
-node tools/emit.mjs mechanicalLepidoptera --out out/mechanical-lepidoptera.html
-```
-
-The dead-air check needs a rendered MP4 to measure; without one it reports that and the other two
-bars still run. `node tools/render.mjs mechanicalLepidoptera` makes it (it takes a while: 1410
-frames).
-
-## One honest note about Act 1
-
-Act 1 (frames 0-540) is LOCKED on the original film and it fails the dead-air bar at its open —
-there are 49 identical consecutive frames in it, all inside that act. The gate reports them
-separately rather than laundering them. That is the right behaviour to copy: a gate that hides a
-known failure to keep a green light is worth nothing.
diff --git a/plugins/anidoodle/skills/anidoodle/example/butterfly-film-spec.md b/plugins/anidoodle/skills/anidoodle/example/butterfly-film-spec.md
deleted file mode 100644
index b28342a..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/butterfly-film-spec.md
+++ /dev/null
@@ -1,273 +0,0 @@
-# MECHANICAL LEPIDOPTERA: film spec, Revision 4 (BUILT, then ALIVE)
-
-Roles: an art director authors and reviews this spec, a builder implements it, a client approves.
-Project: this skill's `example/` (a worked reference to study, not a template).
-Read before building, in this order: this file, whole; `../references/determinism-and-contract.md` for the rules every frame obeys; then the modules beside this spec in `src/canvas-core/butterfly/` (geom, kit, parts, plate, surface, linkage, act1cues, and the finale world in act4*). Render the approved destination still yourself before you change anything that reaches it.
-
-This revision REPLACES Revision 3. Lines marked DIRECTOR are the art director's own calls, vetoable by the client in one line.
-
----
-
-## 0. The story (the client)
-
-A mechanical butterfly is BUILT on a blueprint. Then it comes ALIVE, leaves the blueprint, and the world opens around it.
-
-| # | Movement | Medium | Frames | Beats | Bars | Status |
-|---|---|---|---|---|---|---|
-| 1 | BLUEPRINT: the plate drafts itself, with camera | cyanotype, ruling pen | 540 | 36 | 9 | DONE, APPROVED, LOCKED |
-| 2 | ALIVE: one continuous coming-to-life, macro to wide | pencil + watercolour | 1260 | 84 | 21 | this spec |
-| | **Film** | | **1800** | **120** | **30** | **60.0 s** |
-
-1080x1080, 30 fps, 120 bpm.
-
-**Cut from the film (the client):** the editorial cutaway. **Cut (DIRECTOR, my call on the question the client left open):** the riso wake. Reason: the story is two states, a drawing and a living thing. A third medium in the middle is a detour, and there is no honest device that turns printer's ink into watercolour. There IS one that turns a cyanotype into watercolour: water. Cyanotypes are developed in water and the blue lifts when wet. So the bridge is a single drop of water landing on the blueprint (section 5, beat 1). The cut acts are not part of this film and do not ship with it. What survives from them: `linkage.ts` (flap driven by the crank), the stir vocabulary (gears catch, antennae quiver, first twitch), `tools/deadair.mjs`, the camera/view engine, per-part cached surfaces.
-
-**The one idea that makes it one story (DIRECTOR):** the blueprint of Act 1 and the ghost blueprint lying in the grass on the approved finale still are THE SAME SHEET. Movement 2 starts pressed against that sheet in macro and never cuts again: one stepped pull-back carries us from a wing panel, to the whole creature, to the sheet it leaves behind, to the ranunculus, to the meadow, and the last thing to come back into frame is the sheet, with a butterfly-shaped blank where the drawing used to be and the key it no longer needs. The ending's meaning is set up by the first frame.
-
-### 0.1 Hard rules
-
-1. **NO DEAD AIR.** Something visibly moves in every second. No blank starts, no static holds. Checked by `tools/deadair.mjs` (gate G-AIR). "Hold" in this document always means the camera slows to a creep while the subject keeps moving.
-2. **EVERY ELEMENT MEANS SOMETHING.** Decoration is the machine tell.
-3. **ONE SHOT.** Movement 2 contains no cuts. Every change of scale is a camera move, and every big move is MOTIVATED BY A TAKE-OFF (the client).
-
----
-
-## 1. The grid (binding)
-
-One beat = 15 frames. Bars = 60. Movement boundaries on bar lines.
-- **Events** (a drop lands, a panel floods, a landing, a take-off, a stroke begins): multiples of **5**.
-- **Landings and take-offs: on BEATS** (multiples of 15). Take-offs that trigger a camera step: on BAR lines where the table says so.
-- Motion inside a move is continuous; its start and arrival are on the grid.
-- Every frame number lives in `act2cues.ts` (new file for this movement; retire the riso table to `legacy/`) and nowhere else. `gridProblems()` at module load.
-
-## 2. Craft bar (binding)
-
-The client's test: would a proud human illustrator ship this. Never mechanical shape-assembly.
-
-| The tell (rejected) | What passes |
-|---|---|
-| Things fade or scale in | Marks are MADE: water spreads, a wash floods out from where the brush touched, a line is drawn on |
-| Symmetry in time | One side leads. Always lopsided |
-| Mechanical easing on a living thing | After it wakes: ease in AND out, overlap, follow-through, the body bobbing against the wings |
-| Canvas-scaled parts | Transform CONTROL POINTS, then paint. Never scale a bitmap up |
-| Even scatter | Hand-placed DRIFTS with bare rests between |
-| One flower stamped many times | 5 hand-authored views per species (section 6), seeded petal variation, no view above 25 percent of a clump |
-| Concentric scalloped circles for a ranunculus | Petals painted from the centre out as overlapping C-strokes with paper left between them (6.1) |
-| Grass swaying in unison | Wind as a GUST FRONT crossing the field; blades lean on arrival, spring back lopsided |
-| Flat bands of one green | Three greens by temperature, wet-in-wet, dry-brush on top, cast shadows, cloud shadows |
-| Gradient sky, disc sun | Graded granulating wash; the sun is where the paper was left lightest |
-| Outline round everything | Lost-and-found pencil on near planes only. Far planes are paint alone |
-| A sheet of paper that looks like a sticker | A rectangle in perspective, one corner curled, grass blades OVER its edges, a cast shadow under the curl, flattened grass round it |
-
-## 3. Contract (unchanged)
-
-`renderFrame` pure in `(frame, env)`. Randomness only from `rng(seed)`. No `Math.random`, `Date`, `performance.now`, `ctx.filter`, `document`, `window`, `new OffscreenCanvas`, `new Image`, or imports of `react`, `remotion` or any host/component module in the core. Surfaces from `env.canvas()`. Seeded tile textures. `g.touch()` for raw drawing in groups. Cache keys name everything the pixels depend on. `/* */` when patching one-liners. Never touch the locked deliverables (the finished film and Act 1's source and MP4). Install nothing without your own security gate. Budget 150 ms draw per frame, one page, warm.
-
-## 4. Camera model (binding)
-
-A true DOLLY over depth planes (already built for the finale world): camera distance `D`, plane depth `z_i`, plane scale `s_i = 1 / (D + z_i)`. The HERO plane is `z = 0`, so hero scale `S = 1 / D`. **S is "screen px per sheet unit"**: at S = 1 the creature (wingspan 780 units) is 780 px wide.
-
-- `S(frame)` is a monotone cubic through `log2(S)` keys (table 5.1). It never increases. After frame 0 its velocity is never zero: between steps it CREEPS.
-- The camera centre follows the creature with critically damped lag (about 25 frames) in stages M to R, then hands over to an authored path keyed on bars that ends on the approved still's composition.
-- Never scale a bitmap UP. Static washes per plane are cached at LOD steps of sqrt 2 and only downscaled, by at most 1.41x. Everything that moves is drawn live from control points, culled to frame, LOD-reduced by screen size.
-- Line weight `w = w_authored * S^0.35`. All texture anchored to the world. Finer tile octave comes up with S. Max S = 4.0 (raised from 3.4 for the macro; watercolour has no hairlines to fatten).
-
----
-
-## 5. MOVEMENT 2, ALIVE (1260 frames). The client's six beats, on the grid.
-
-Local frames `[start, end)`. Film frame = local + 540.
-
-### 5.1 Camera scale at each stage
-
-| Stage | Frames | S (hero scale) | D | Creature wingspan on screen | What the frame holds |
-|---|---|---|---|---|---|
-| **M, macro wings** | 0-120 | 4.0 creeping to 3.4 | 0.25-0.29 | 3100 px, far bigger than frame | One forewing root, panel 2, the edge of the thorax window. Extreme close |
-| M2, still macro | 120-240 | 3.4 to 1.6 | 0.29-0.63 | 2650 to 1250 px | Thorax and all four wing roots; by 240 most of the creature |
-| **T1, take-off pull** | 240-345 | 1.6 to 0.55 | 0.63-1.82 | 1250 to 430 px | The whole creature, then the whole SHEET with its blank, then grass over the sheet's edges, then stems |
-| **R, close ranunculus** | 345-720 | 0.55 stepping down to 0.45 | 1.82-2.22 | 430 to 350 px | Three to five ranunculus heads fill the frame; each head about 385 to 315 px. THE HOLD: 6 bars, 12.5 s |
-| **F, mid flight** | 720-870 | 0.45 to 0.18 | 2.22-5.56 | 350 to 140 px | Drifts of flowers, grass, the footpath, the first hills at the top of frame by about 800 |
-| **W, wide meadow** | 870-1080 | 0.18 to 0.118 | 5.56-8.47 | see 5.7 (it flies TOWARD us) | Field, hills, sky, sun, clouds. The sheet comes back into frame lower left |
-| Settle + signature | 1080-1260 | 0.118 to 0.115 | 8.47-8.70 | 290 px (as the approved still) | The approved still's composition, alive, signed |
-
-`S` keys for the cubic: f0 4.0 · f120 3.4 · f240 1.6 · f345 0.55 · f420 0.545 · f450 0.52 · f525 0.515 · f555 0.49 · f630 0.485 · f660 0.47 · f720 0.45 · f810 0.24 · f870 0.18 · f1080 0.118 · f1260 0.115. Between steps the camera creeps (about 1 percent per bar); the drops that start at 420, 525 and 630 are the "steps": each is released by a take-off and takes 30 frames. The big moves start on the take-offs at 240, 720 and 855.
-
-### 5.2 BEAT 1. It turns into a real butterfly (0-240, bars 1-4). Stage M.
-
-The join to Act 1 is a CUT on the bar line (the only cut in the film after Act 1's own match cut): from Act 1's held wide plate to a macro of the SAME plate, same state, same ticking train. View M0: centred on the starboard forewing root so that lifted PANEL 2 on its projection lines sits right of centre and the edge of the thorax window, wheels stepping, sits in the left third. Gate: frame 0 must equal Act 1's final state drawn at view M0 (hash or above 45 dB).
-
-| Frames | Camera | What happens |
-|---|---|---|
-| 0-5 | M0, S 4.0, creeping | Blueprint macro. White line on Prussian ground. The train steps on 0. The tick continues from Act 1 |
-| **5** | | **A drop of water lands** on panel 2. A clear bead: darker blue under it, one paper-white highlight, a tiny crown splash of 4 droplets |
-| 5-60 | creep | **The water runs, and a REAL WING comes up behind it.** It does not spread as a circle: it follows the drawing by capillary, along the spars toward the hinge, one spar per 5 frames (water does not care about the draftsman's order). Behind the wet front, on the creature only, every mechanical part becomes the piece of anatomy it always stood for (mapping in 5.7): the ruled SPAR softens, tapers and forks into a VEIN; the membrane PANEL becomes a wing CELL, first a pale warm wash, then scale colour and markings dropped in wet-on-damp (basal dusting, the dark apical patch with its pale spots, the marginal band); each RIVET becomes a submarginal SPOT; the ruled margin becomes a scalloped edge with a fine fringe. The Prussian ground lifts to bare cold-press under the wing only. The front itself is a dark blue rim of displaced pigment. By 60 the starboard forewing in frame is unmistakably a butterfly's wing, of naturalist-plate quality, and the sheet AROUND the creature is still a blueprint, for ever. **Rejected: a frame that reads as gears on one side and colour on the other. At every frame the painted part must already be anatomy, never an abstract colour field** |
-| 45-60 | creep | **Panel 2 comes home.** It floods CORNFLOWER blue (it keeps the blueprint's colour, with a ghost of the ruled grid lifted in it) and slides down its projection lines, dashes shrinking, seating on 60 with the last mechanical overshoot in the film. The flaw is healed, and it becomes the mark of the individual: that blue panel is on the approved still |
-| 60-120 | slow drift left across the thorax to the port wing roots, S to 3.4 | **Water crosses the body, and the body becomes an insect.** The housing takes a warm umber-grey wash turned as a form (light upper right, core shadow, reflected light below). The wheels in the window keep stepping on the tick while thoracic FUR is dry-brushed in from the window's edge, stroke by stroke, 75-120, closing over them: the mechanism is not removed, it is grown over. Abdomen rings become true segments with paler bands and fine hair. The stippled eyes become compound eyes with one lifted highlight each. Port wings come up 75-120, vein by vein, as the starboard did. Dimension lines, leaders and balloons that cross the frame stay hard white on blue: furniture does not change |
-| 120-180 | ease back, S 3.4 to 2.4 | **First movement, and it is the movement of a newly emerged butterfly.** 120: the last of the mechanism, felt not seen: one stall, a recoil held for 2 ticks, a double step on 130, as a shudder through the thorax. 125: port antenna (now a finely ringed shaft with a true club) quivers, starboard answers on 130. 135-150: the six LEGS unfold from under the thorax, one pair per 5 frames, thin and jointed, and take the weight; the body lifts a hair off the sheet. 150-180: a BREATH, flap 1 to 0.86 and back, port first, starboard a triplet later. Motion is still STEPPED on the tick: it moves like a mechanism wearing a butterfly |
-| 180-240 | S 2.4 to 1.6 | **It softens into a living thing: the slow fanning of wet wings.** Real butterflies do exactly this after emerging, pumping and fanning until the wings are dry enough to fly, so the wet paint IS the wet wings. Three fans, wider each time: down-strokes at 180 (30 frames, to flap 0.6), 210 (20 frames, to 0.5), 230 (10 frames). As the wings rise we see, for the first time, the paler UNDERSIDE pattern (5.7). Across this bar the motion blends from tick-stepped to continuous (`motion = lerp(stepped, smooth, u)`, u 0 to 1 over 180-240), easing changes from hard-out to in-and-out, the body bobs against the wings, the abdomen curls, the antennae trail, the proboscis uncoils once and recoils (200-220). A soft painted SHADOW separates beneath it on the blue sheet, offset 0 to (14, 20). From 180 the paint lags the pencil by up to 9 px on fast strokes. **By 240 nothing mechanical is visible. What takes off is a real butterfly.** Sound: the tick thins across this bar and a felt wing-flutter takes each down-stroke (section 8) |
-
-### 5.3 BEAT 2. It takes off; the camera begins to zoom out (240-345, bars 5-6). Stage T1.
-
-| Frames | Camera | What happens |
-|---|---|---|
-| **240** | the pull-back STARTS here, motivated by the take-off | **Take-off on the bar line.** Wing cycle drops to 10 frames. It rises off the sheet; its shadow slides away down-left and shrinks |
-| 240-285 | S 1.6 to 0.95 | **What it leaves behind:** a butterfly-shaped BLANK in the blueprint, bare unexposed paper where the drawing was, because the drawing went with it. The furniture is all still there, now dimensioning nothing: WINGSPAN 184 across an empty shape, leaders pointing at paper. The KEY stays on the sheet. At about 270 the whole sheet is in frame: border, cartouche, MECHANICAL LEPIDOPTERA, and the hole |
-| 285-345 | S 0.95 to 0.55, centre following the creature up and right | **Scenery appears.** Grass blades lie OVER the sheet's edges; one corner is curled with a shadow under it. The camera rises and tilts with the creature: the sheet foreshortens (control points, y-scale 1 to 0.45 about its centre, slight keystone) as it slides out lower left, gone by 335. Stems rise through frame: tall, slender, curving. Out-of-focus colour behind them resolves into petals. Big soft foreground blades (plane z -0.2) whip out of frame |
-| **345** | arrives S 0.55 | It is hovering over a clump of RANUNCULUS |
-
-### 5.4 BEATS 3 and 4. The ranunculus close-up; flower to flower, sipping (345-720, bars 6-12). Stage R.
-
-This is the heart of the film and it is held long enough to read: six bars. The camera only creeps and drifts sideways with the creature, stepping back slightly on each take-off.
-
-| Frames | Beat | Action |
-|---|---|---|
-| **360** | 24 | **Lands on R1** (coral, facing us). The head DIPS (stem bends 6 degrees, one settle). Wings open flat, then fan slowly (30-frame cycle, amp 0.35): it is never still |
-| 375-410 | | **Sips.** The proboscis, the blueprint's hairspring, uncoils into the tight centre (375-385). Abdomen pulses once per beat: the tick has become a heartbeat. Recoils 405-410 |
-| **420** | 28 | Take-off. R1 rebounds. Camera step 0.55 to 0.52 over 420-450 |
-| 420-450 | | Short hop right, a bob on every down-stroke (6 to 10 units), one playful overshoot past R2 and back |
-| **450** | 30 | **Lands on R2** (blush white with a pink picotee edge, three-quarter view). Sips 465-510 |
-| **525** | 35 | Take-off. Step to 0.49 over 525-555 |
-| 525-555 | | Crosses LEFT behind a stem (it passes BEHIND: overlap sells depth), first gust of wind arrives 540 and pushes it sideways; it recovers |
-| **555** | 37 | **Lands on R3** (butter yellow, profile cup, lower in frame, with a nodding bud on the same stem). Sips 570-615. A petal it disturbs falls (585-630, tumbling) |
-| **630** | 42 | Take-off. Step to 0.47 over 630-660 |
-| **660** | 44 | **Lands on R4** (deep magenta, half-open, highest in frame). Sips 675-705 |
-| **720** | 48 | **Take-off on the bar line.** This one does not hop: it climbs. It releases BEAT 5 |
-
-Through the whole stage: every head nods on its own period (50 to 80 frames, never shared), leaves turn, the gust front at 540 crosses in 60 frames, sunlight flickers as a cloud shadow slides over the clump (600-690), two seed-fluffs drift through the foreground.
-
-### 5.5 BEAT 5. The camera zooms out more; it takes off again (720-870, bars 13-15). Stage F.
-
-| Frames | Camera | Action |
-|---|---|---|
-| 720-810 | S 0.45 to 0.24 | Mid flight: up and away over the ranunculus, a loop at 750, low over a daisy drift, then right along the footpath. The ranunculus clump shrinks into one drift among many. Hills enter the top of frame at about 800 |
-| **810** | S 0.24, creeping | **Touch-down on a field poppy**, far right, deeper in the field (plane z 2.2). A short sip, 820-845. Two small WHITE butterflies lift out of the grass nearby at 825 (DIRECTOR): real ones |
-| **855** | beat 57 | **Take-off again.** Second gust arrives 855. This take-off releases the final pull-back |
-| 855-870 | S to 0.18 | It climbs with the two whites spiralling round it |
-
-### 5.6 BEAT 6. Final wide: the meadow (870-1260, bars 15-21). Stage W, settle, signature.
-
-| Frames | Camera | Action |
-|---|---|---|
-| 870-1080 | S 0.18 to 0.118, authored path, horizon settling at y 410 | The meadow opens: far field in bands, two ridges with a hedgerow and one lone tree, the big warm sky, the sun upper right, three lifted clouds drifting left, cloud shadows sliding over the far field from 900. **At about 930 the blueprint sheet re-enters, lower left**: small, in perspective, its corner lifting in the gust (on 945 and 1005), the butterfly-shaped blank and the key on it. It is never pointed at |
-| 900-1080 | | **It flies TOWARD us.** From the poppy it turns and comes up the field to the foreground, growing as the world shrinks (its depth goes z 2.2 to z -5.8, so its scale goes 0.13 to 0.37). The whites peel away at 990. It arrives at the approved still's position (440, 590), wingspan about 290 px, on 1080, and HOVERS: a slow figure of eight, 60-frame period, wings on a 10-frame beat |
-| 1080-1140 | S creeping 0.118 to 0.116 | The picture is the approved still, alive: grass idling, heads nodding, clouds, the creature hovering |
-| 1140-1155 | | A clean damp brush LIFTS the lower right corner: one soft swipe about 250 x 60 px (see 7) |
-| 1155-1185 | | **The signature is written**, last stroke finishing on **1185 with the DING** (film frame 1725) |
-| 1185-1260 | creep to 0.115 | Five beats to read it. Ink dries 0.75 to 0.60. The creature drifts a little higher. Last frame: the approved still's composition. THE END |
-
-### 5.7 The creature, painted
-
-**The client's note: MORE REALISTIC, less abstract. A naturalist watercolour plate, NOT colour fields.** The medium, the warmth and the ranunculus stay. My earlier "wings as stained glass" direction is withdrawn: it produced flat panels and it was wrong.
-
-**The bar:** a plate from a natural-history folio (Merian, the 19th-century lepidoptera atlases) painted by someone who has had the specimen under a lens. A lepidopterist should be able to name every part. It stays an ORIGINAL species (borrow the medium, never the content): no copying a real butterfly's pattern, but every structure is true. Look at real reference for anatomy and venation before moving a point, and say which you used.
-
-**What each mechanical part becomes (this mapping IS the transform beat, 5.2):**
-
-| Blueprint | Living butterfly |
-|---|---|
-| Wing spars radiating from the hinge | VEINS. They keep their positions, so the silhouette and rhythm carry over, but they become true venation: a closed DISCAL CELL from the base to about half the wing, veins leaving the cell and running to the margin, forking, never crossing, thinning toward the edge |
-| Membrane panels | Wing CELLS between veins, covered in scales |
-| Rivets along the spars | The row of SUBMARGINAL SPOTS |
-| Ruled wing margin | A margin gently SCALLOPED between vein ends, with a fine pale/dark FRINGE |
-| Thorax housing and its window | A furred THORAX (the fur grows over the window) |
-| Abdomen rings | 7 to 8 visible abdominal SEGMENTS, tapering, paler bands at the joints, fine hair |
-| Stippled eyes | Two large COMPOUND EYES, one lifted highlight each, and a pair of small furry PALPS between them |
-| Coiled-wire antennae | Slender, finely ringed ANTENNAE ending in true CLUBS |
-| Proboscis hairspring | The PROBOSCIS, coiled at rest between the palps, a fine double tube when extended |
-| (not on the blueprint) | SIX LEGS, thin and jointed: femur, tibia, a tarsus with a tiny claw. They unfold at 135-150, grip the petal when perched, tuck back in flight |
-| Lifted panel 2 | The one mark no real butterfly has: a CORNFLOWER BLUE cell in the starboard forewing, painted as an iridescent scale patch. The blueprint it carries with it |
-
-**Wings, two true pairs.** Forewing roughly triangular (leading edge, apex, outer margin, inner margin), hindwing rounder with the short TAIL the geometry already has. The forewing OVERLAPS the hindwing's leading third, and that double layer is darker. Left and right are never mirror images (keep the seeded asymmetry).
-- **Pattern (original, plausible, warm):** ground of rose running to peach toward the margin. Warm grey-umber DUSTING at the base, hairy near the body. A dark umber APICAL PATCH on the forewing holding three pale spots. A dark MARGINAL BAND, narrowing toward the rear corner, carrying the row of pale submarginal spots. A small dark DISCAL SPOT at the end of the cell. On the hindwing, the marginal spot row again and, at the base of the tail, a small blue-and-orange EYESPOT.
-- **Underside (seen whenever the wings rise or close):** different and quieter, as in life: pale cream-peach with soft grey-olive marbling, the spot row repeated small, veins a touch darker. A butterfly with the same pattern on both faces reads as a cut-out.
-- **How to paint it:** a pale first wash over the whole wing; pattern dropped in WET-ON-DAMP so its edges soften the way scales do (no hard-edged shapes except the eyespot's pupil); veins LAST with a fine rigger in umber, broken, tapering, heavier near the base, never a uniform line; the fringe as tiny alternating ticks; a lifted paper-white rim on the sunward margins.
-- **Volume and translucency:** the wing is not flat: a slight camber, so a soft shadow runs behind each main vein and the cell between catches light. The body casts a shadow onto the wing bases; the wings cast a shadow onto the flower. Wings are TRANSLUCENT: where a wing overlaps a petal or the sky, 15 to 20 percent of that colour warms through it; backlit (wings raised against the sun, upper right) the ground glows and the veins read darker.
-- **Body:** painted as a form, not a capsule: light upper right, core shadow, reflected light from below, fur dry-brushed along the thorax in the direction it grows, the segment bands wrapping round the cylinder.
-
-**Two authored views (DIRECTOR, needed for realism at the ranunculus):**
-- **DORSAL** (existing control points): the transform beat, basking with wings flat, all flight.
-- **LATERAL, wings closed or half open over the back** (new hand-authored control points: body in profile, six legs gripping, forewing and hindwing undersides overlapped). This is how most butterflies actually sip, and it is what a plate shows beside the dorsal figure. Used at stage R, where the creature is 350 to 430 px and realism matters most: at least two of the four ranunculus visits are lateral. The switch between views happens inside the landing flutter, at the instant the wings pass through closed. Below about 150 px on screen, dorsal with the pose transform is enough.
-
-**Pose and flight.** `Pose = { flap, sweep, heading, pitch, bank }`, all on control points: `heading` rotates about the thorax, `pitch` foreshortens along the body axis (1 to 0.55), `bank` offsets port against starboard flap by up to 0.2. `flap` comes from `linkage.ts`; after frame 240 the crank runs free and smooth. Flight is a butterfly's: hand-authored paths with detours, a bob on every down-stroke, never a straight line or a clean sine. It is the most saturated thing in every frame, with the wash behind its path kept a value lighter. Never under 46 px wingspan. LOD: above 300 px everything above; 120 to 300 px veins, main markings, legs when perched; 46 to 120 px silhouette, two-tone wings, dark margin, the blue cell.
-
-**Rejected on sight:** wings as flat colour fields or stained-glass panels; spars left as straight ruled lines; mirror-image wings; one pattern on both faces; a capsule body; antennae as a line with a dot; no legs; uniform-weight veins; any frame of the transform that reads as "gears here, colour there".
-
----
-
-## 6. The world
-
-Light from the upper right, always: lit side, shadow side, a cast-shadow dab to the lower left of every plant and of the creature when it is low. Paper white is the brightest value and is LEFT: highlights, cloud tops, the rim of petals. Three greens by temperature. Aerial perspective: farther is paler, bluer, softer, no pencil.
-
-### 6.1 RANUNCULUS, rendered true (the client)
-
-Persian buttercup, *Ranunculus asiaticus*. Study real photographs before moving a point, and say which you used.
-
-- **The head:** dozens of tissue-thin petals in tight, overlapping, concentric layers: a cupped rosette, rose-like but flatter and more orderly than a rose, never a pompom. Petals are smallest and most upright at the centre, largest, palest and slightly ruffled at the rim. Layers are OFFSET from each other, so no petal sits directly behind another.
-- **The centre:** a tight green-yellow button. In a half-open bloom it is green and clasped; fully open it shows a small dark eye ringed with yellow.
-- **How to paint it (this is the craft):** from the centre OUT, as short overlapping C-strokes circling the button, each ring larger and looser than the last. LEAVE SLIVERS OF BARE PAPER between strokes: those slivers are the petal edges, and they are what makes it read as layered tissue instead of a disc. Drop darker pigment into the gaps near the centre while wet (depth), let the outer petals stay pale with a hard dried rim, add one cool shadow wash over the side away from the sun. No outline round the head.
-- **Rejected on sight:** concentric circles with regular scallops; a mathematical spiral; identical heads; petals as separate ovals arranged on a ring; straight stems.
-- **Five views, hand-authored:** facing; three-quarter (an oval cup, inner layers seen as stacked crescents); profile (a cup on its stem, green sepals reflexed beneath); half-open; tight round BUD, nodding, clasped by sepals.
-- **Stems:** tall, slender, faintly hairy, each with its own S-curve and thickness, often one main bloom plus a side bud. **Leaves:** low and basal, deeply cut, parsley-like, painted as a dark ferny mass at the foot of the clump.
-- **Colours:** coral, blush white with a pink picotee edge, butter yellow, deep magenta, peach. They are the creature's own wing colours, which is why it goes to them (DIRECTOR).
-- **The clump:** 9 heads and 5 buds, hand-placed at three heights and three depths, R1 to R4 chosen so the flight zig-zags right, left-behind-a-stem, down, up. Size: a full head is 700 units across, a little smaller than the creature.
-- **LOD:** above 120 px everything above; 40 to 120 px three rings of strokes and the button; 14 to 40 px two tones and a centre dab; under 14 px one dab.
-
-### 6.2 Everything else (as the approved still, with its open craft fixes)
-
-Planes: P0 foreground fringe z -0.2 · P1 hero z 0 (the sheet, the ranunculus clump) · P2 z 1.0 (daisy drift) · P3 z 2.2 (poppies, cosmos, the touch-down poppy) · P4 z 3.5 (buttercups along the footpath) · P5 far field z 8 · P6 hills z 20 · P7 sky.
-
-Supporting flowers, each with 4 views and LOD as above: oxeye daisy (paper white), field poppy, cosmos, buttercup (the ranunculus's wild cousin). About 14 hand-placed drift centres, seeded scatter inside each with falloff, three bare rests of plain grass.
-
-**Changes to the approved still, flagged for the client:** the near flowers at about (540, 700), (440, 790), (815, 680), (920, 750) become RANUNCULUS so the clump we spent six bars on is recognisably in the last frame. Everything else in the still's composition stands: creature (440, 590), sheet lower left, sun upper right, signature lower right, horizon about y 410.
-
-**Craft fixes already listed against the still, all still owed before motion:** (1) value range: the greens sit in one narrow band, push the hollows darker and the sunlit crests lighter; (2) drifts read as dot clouds, give near drifts real flower forms; (3) the sheet reads as a sticker or a lily pad: make it a rectangle in perspective with a curled corner, grass over its edges, a shadow under the curl; (4) the foreground is empty flat colour: P0/P1 grass clumps with thickness and cast shadows; (5) the signature letterforms (section 7).
-
-**What moves, always:** gust fronts enter left on 540 and 855 and cross in 60 to 90 frames; idle sway between, per-clump periods 50 to 80 frames; clouds drift left; cloud shadows over the clump 600-690 and over the far field from 900; seed fluff from 345; the two whites 825-990; every visited flower dips and rebounds; wet paint spreading 5-120.
-
----
-
-## 7. The signature (the client)
-
-`alexgreenshpun.com`, signed like a watercolourist signs a corner. A signature, never a caption.
-- Hand-authored brush strokes in `butterfly/finale/signature.ts` (control points, about 8 strokes), lowercase, connected, slight forward slant, baseline rising 2 degrees, uneven letter widths, loose descenders on g and p. LEGIBLE FIRST: it is a URL, the dot must read as a dot. The still's current letterforms do not pass this.
-- Rigger brush, dilute warm grey-brown about `#5b5148`, width 1.3 to 2.2 px with pressure, pigment pooled at stroke ends, opacity 0.75 wet drying to 0.60.
-- SCREEN space. Right edge of the last letter x = 1036, baseline y = 1034 at its left end, width 190 px, x-height 12 px, ascenders 19 px.
-- Damp-brush lift 1140-1155 to make room (about 250 x 60 px, lightens the wash about 45 percent, faint backrun at its end). Written on, never faded: `alex` 1155-1160, `green` 1160-1170, `shpun` 1170-1175, the dot on 1175, `com` 1175-1185. Last stroke ends on **1185, with the DING**. Then 75 frames to read it.
-- Check: readable at 100 percent, vanishes into the painting at thumbnail size. No underline, no flourish, no glow.
-
-## 8. Score (pure JS, same shape as `score.ts`)
-
-12/8. Act 1: music box, asks the question, ends unresolved on the fifth. Movement 2: the drop on local 5 is a single water-note; the motif returns slowed and warm under 5-240; from 240 (take-off) a bowed pad and a second voice; the answer resolves to the root as the meadow opens at 870; DING on local 1185.
-**The tick becomes a pulse:** tick every 5 frames through 0-180, thinning across 180-240 as a felt wing-flutter takes each down-stroke; gone by 240. While it sips, one soft low pulse per beat (the heartbeat). Landings get a pluck on their beat. Every onset is a cue; assert sample index = `round(frame / 30 * 48000)`.
-
-## 9. Engine work
-
-1. `act2cues.ts` for this movement; riso/editorial tables retired to `legacy/`, nothing imports them.
-2. **The water front:** progress along spars (arc length, reuse `nib()`), per-panel flood on arrival, ground lift clipped to the creature's silhouette plus a 6 px bleed, blue pigment rim at the front. Drop and crown splash.
-3. **The sheet as a world object:** the Act 1 plate drawn into plane P1 via the existing view engine, cached at LOD steps, downscale only; a `blank` state that knocks the creature's silhouette out to bare paper; foreshortening on control points.
-4. **Stepped-to-smooth motion blend** on the crank (5.2, 180-240).
-5. Ranunculus: 5 views x colour variants, LOD, stems, leaves, dip and rebound.
-6. Pose extension, flight paths, landing/sip/take-off states, proboscis.
-7. Reuse as built: dolly planes, flora LOD, gusts, clouds, creature paint, signature, `deadair.mjs`.
-If the macro (huge wet washes) or the last bars break 150 ms, cut blade and stroke counts before touching the look, and tell me.
-
-## 10. Gates (stills first, I review each; under the no-collision protocol I review COPIES and return numbered fix lists through the client)
-
-| Gate | Deliverable | Pass |
-|---|---|---|
-| **G-R ranunculus** (FIRST) | One sheet: the 5 views in 3 colours at full LOD, plus the clump composed at stage R with the creature perched on R1 | Craft review against 6.1. No motion before this passes |
-| **G-M metamorphosis** | 6 stills: local 0, 5, 30, 60, 120, 210 | Frame 0 equals Act 1's final state at view M0. The water reads as water. Panel 2 home and blue. Realism per 5.7: every painted part is nameable anatomy at every sampled frame, never "gears here, colour there"; by 210 it is a complete, recognizable real butterfly with legs, clubbed antennae, venation, markings and an underside. Plus one PLATE still: the finished creature, dorsal and lateral side by side, as a naturalist plate |
-| **G-S sheet** | 3 stills: local 270 (whole sheet with the blank), 320 (grass over its edges, foreshortening), 1080 (in the wide) | It is a sheet of paper, not a sticker. The blank reads as the absence of THIS butterfly |
-| G-W wide | The approved still re-rendered with the five fixes and the ranunculus swap | The client re-approves the destination |
-| G-MOTION | Contact sheet at one tile per beat (84) + MP4 | Tables 5.1 to 5.6 on the frame; landings and take-offs on their beats; camera keys within 2 percent |
-| G-AIR | `tools/deadair.mjs` on the movement and the film | No identical consecutive frames; no 15-frame window under 0.5 percent changed area |
-| G-FILM | `out/butterfly.mp4`, `dist/butterfly.html` | h264 + aac, 1800 frames, clean decode, draw median under 150 ms and p95 under 200 on one page, determinism on probe frames (hash, else above 45 dB) |
-
-## 11. Open for the client (none blocks the build)
-
-- O1. No riso wake (section 0). If you want one back, it costs a second bridge device and I would argue against it.
-- O2. The join from Act 1 is a CUT to macro on the bar line. The alternative is a 30-frame push-in over the finished plate, which costs a full-plate redraw per frame.
-- O3. Four near flowers on the approved still become ranunculus (6.2).
-- O4. The two white butterflies, and the creature flying toward us at the end so it lands at the still's size.
-- Act 1 is locked and approved, and it fails the dead-air check at its open (43 identical frames in the first seconds, per the gate). Two cue changes would fix it. The client's call whether to unlock it for that.
-- O6. Length: 42 s for the coming-to-life, 60 s film. If it must be shorter, trim stage F and one ranunculus landing, never the macro or the ending.
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act1cues.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act1cues.ts
deleted file mode 100644
index 8f768ca..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act1cues.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-// ACT 1, THE BLUEPRINT: 540 frames, 18 s, 36 beats at 120 bpm. A bare cyanotype sheet draws
-// itself into PLATE I, the key goes in, the train starts, and for two beats the drawing is
-// alive. Every frame number in the act is in this table and nowhere else: cuts on multiples of
-// 15, events on multiples of 5 (triplet eighths, which is what an escapement sounds like).
-import { EMPTY, Parts, PlateState } from "./plate";
-import { BUBBLE } from "./parts";
-import { View } from "./surface";
-import { Train } from "./parts";
-
-export type Ease = "linear" | "out" | "outBack" | "flick" | "inout";
-export type Cue = { at: number; dur: number; id: string; ease?: Ease; amp?: number };
-
-export const DURATION = 540, TICK0 = 240, TICK = 5;
-export const SHOTS: [string, number, number][] = [
- ["sheet", 0, 60], /* the ground, the printed grid, the border rules itself */
- ["layout", 60, 120], /* construction: centre line, wing envelopes, thorax ellipse, then the title block is RULED */
- ["thorax", 120, 180], /* the housing, the broken-out window, the head and its coiled antennae */
- ["push", 180, 240], /* the camera moves in on the thorax while the going train seats inside it */
- ["detail", 240, 270], /* MATCH CUT: the bubble on the thorax becomes Detail B, full frame, and it ticks */
- ["pull", 270, 315], /* back out to the sheet */
- ["spars", 315, 360], /* four wing frames radiate from their hinges, port leading */
- ["skin", 360, 405], /* membrane panels fly home along their projection lines and are veined */
- ["notes", 405, 420], /* dimensions, balloons, notes, and MECHANICAL LEPIDOPTERA written last */
- ["wind", 420, 495], /* the key rides up the centre line and winds seven turns, then comes out */
- ["alive", 495, 525], /* it moves, and lifts off its own paper */
- ["plate", 525, 540], /* the finished plate, held */
-];
-
-// THE CAMERA. Keyframes of (frame, centre, zoom); two keys on the same frame are a CUT. The view
-// is applied to control points through the transform stack, and line weight is compensated for
-// the zoom in plate.ts, so a close shot is redrawn at size, never a magnified bitmap.
-type Key = { at: number; cx: number; cy: number; z: number; ease: Ease };
-const [BX, BY, BR] = BUBBLE(), DBX = 392, DBY = 898, DBR = 100, SCREEN = 330; /* the bubble and the Detail B circle land on the SAME screen circle: that is the cut */
-export const CAM: Key[] = [
- { at: 0, cx: 540, cy: 540, z: 1, ease: "linear" },
- { at: 195, cx: 540, cy: 540, z: 1, ease: "inout" },
- { at: 240, cx: BX, cy: BY, z: SCREEN / BR, ease: "linear" }, /* slow push in on the thorax as the wheels seat */
- { at: 240, cx: DBX, cy: DBY, z: SCREEN / DBR, ease: "linear" }, /* CUT */
- { at: 270, cx: DBX, cy: DBY, z: (SCREEN / DBR) * 1.045, ease: "out" }, /* it breathes in while the train runs */
- { at: 315, cx: 540, cy: 500, z: 1.12, ease: "linear" }, /* held here while the wings and the body are drawn: a still camera lets the drawing work */
- { at: 405, cx: 540, cy: 500, z: 1.12, ease: "inout" },
- { at: 420, cx: 540, cy: 540, z: 1, ease: "linear" }, /* wide again, on the frame the key starts to rise */
- { at: 540, cx: 540, cy: 540, z: 1, ease: "linear" },
-];
-
-export const CUES: Cue[] = [
- { at: 15, dur: 30, id: "grid", ease: "out" }, /* printed paper, so it may fade: the only fade in the act */
- { at: 30, dur: 30, id: "border" },
- { at: 60, dur: 45, id: "construct" }, { at: 300, dur: 30, id: "erase" }, /* construction is UN-drawn, because a construction line is erased and never faded */
- { at: 105, dur: 45, id: "cartouche" }, { at: 355, dur: 65, id: "lettering" }, /* the box is ruled early, the lettering is the last job: MECHANICAL LEPIDOPTERA is written just before the key goes in */
- { at: 120, dur: 45, id: "shell" }, { at: 160, dur: 40, id: "head" },
- { at: 165, dur: 60, id: "detailPlate" }, { at: 180, dur: 45, id: "detail" }, { at: 200, dur: 35, id: "window" }, { at: 185, dur: 30, id: "bubble" }, /* the bubble is rung on the thorax before the camera goes in, and it is the circle the cut matches */ { at: 385, dur: 25, id: "detail.notes" }, /* the tooth counts are notes, so they wait for the notes phase */
- { at: 300, dur: 45, id: "wing.LF" }, { at: 315, dur: 45, id: "wing.LH" }, { at: 330, dur: 45, id: "wing.RF" }, { at: 345, dur: 45, id: "wing.RH" }, /* port leads, starboard follows: a right-handed draftsman works left to right */
- { at: 340, dur: 40, id: "skin.LF" }, { at: 355, dur: 40, id: "skin.LH" }, { at: 370, dur: 40, id: "skin.RF" },
- { at: 350, dur: 50, id: "abdomen" },
- { at: 365, dur: 45, id: "key.draw" }, { at: 360, dur: 20, id: "axis" }, { at: 370, dur: 50, id: "furniture" }, { at: 365, dur: 30, id: "section" }, { at: 375, dur: 20, id: "scale" }, { at: 380, dur: 15, id: "note" }, { at: 380, dur: 30, id: "list" },
- { at: 420, dur: 15, id: "key.rise", ease: "outBack" }, { at: 435, dur: 35, id: "key.wind", ease: "linear" }, { at: 475, dur: 10, id: "key.out", ease: "out" },
- { at: 485, dur: 10, id: "twitch", ease: "flick", amp: 0.14 },
- { at: 495, dur: 15, id: "flap1", ease: "flick", amp: 0.55 }, { at: 510, dur: 10, id: "flap2", ease: "flick", amp: 0.62 }, { at: 520, dur: 5, id: "flap3", ease: "flick", amp: 0.45 },
- { at: 495, dur: 15, id: "shadow.out", ease: "out" }, { at: 510, dur: 15, id: "shadow.in", ease: "out" },
- { at: 495, dur: 30, id: "boil" },
-];
-
-const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
-const ease = (p: number, e: Ease = "linear") => (e === "inout" ? (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2) : e === "out" ? 1 - (1 - p) ** 3 : e === "outBack" ? 1 + 1.7 * (p - 1) ** 3 + 0.7 * (p - 1) ** 2 : e === "flick" ? (p < 0.35 ? Math.sin((p / 0.35) * Math.PI / 2) : Math.cos(((p - 0.35) / 0.65) * Math.PI / 2)) : p);
-const byId = new Map(CUES.map((c) => [c.id, c]));
-const cue = (id: string) => { const c = byId.get(id); if (!c) throw new Error(`no cue '${id}'`); return c; };
-export const at = (frame: number, id: string): number => { const c = cue(id); return ease(clamp((frame - c.at) / c.dur), c.ease); };
-export const raw = (frame: number, id: string): number => { const c = cue(id); return clamp((frame - c.at) / c.dur); };
-
-// the going train: one tooth of the escape wheel per tick, snapped over two frames with a
-// one-frame recoil, and every other wheel geared off it by its tooth count
-const STEP = [14 / 24, 26 / 24, 1, 1, 1];
-export const advance = (frame: number): number => { if (frame < TICK0 + TICK) return 0; const t = Math.floor((frame - TICK0) / TICK), s = (frame - TICK0) % TICK; return t - 1 + STEP[s]; };
-export const trainAt = (frame: number): Train => {
- const a = advance(frame), w = (Math.PI * 2) / 96, t = Math.floor((frame - TICK0) / TICK), s = (frame - TICK0) % TICK;
- const rocking = frame >= TICK0 + TICK && s === 0 ? 0 : 0.085 * (t % 2 ? 1 : -1); /* the fork passes through centre on the tick frame */
- return { centre: a * w, third: -a * w * (24 / 14), pinion: a * w * (24 / 8), escape: a * ((Math.PI * 2) / 15), fork: frame < TICK0 + TICK ? 0 : rocking };
-};
-
-// the camera at a frame: the last key at or before it, eased into the next
-export const viewAt = (frame: number): View => {
- let i = 0; for (let j = 0; j < CAM.length; j++) if (CAM[j].at <= frame) i = j;
- const a = CAM[i], b = CAM[Math.min(CAM.length - 1, i + 1)];
- if (b.at <= a.at) return { cx: a.cx, cy: a.cy, zoom: a.z };
- const t = ease(clamp((frame - a.at) / (b.at - a.at)), a.ease), lz = Math.exp(Math.log(a.z) + (Math.log(b.z) - Math.log(a.z)) * t); /* zoom moves geometrically, or a push looks like it stalls at the end */
- const cx = a.cx + (b.cx - a.cx) * t, cy = a.cy + (b.cy - a.cy) * t;
- if (Math.abs(lz - 1) < 0.004 && Math.abs(cx - 540) < 2 && Math.abs(cy - 540) < 2) return { cx: 540, cy: 540, zoom: 1 }; /* snap the last hair of the move to true wide, or every finished part redraws for nothing */
- return { cx, cy, zoom: lz };
-};
-
-export const stateAt = (frame: number): PlateState => {
- const flap = ["twitch", "flap1", "flap2", "flap3"].reduce((f, id) => f - (cue(id).amp ?? 0) * at(frame, id), 1);
- const sh = 1 - at(frame, "shadow.in"), out = at(frame, "shadow.out") * sh, wind = raw(frame, "key.wind");
- const p: Parts = {
- ...EMPTY,
- grid: at(frame, "grid"), border: at(frame, "border"), construct: at(frame, "construct") * (1 - at(frame, "erase")),
- shell: at(frame, "shell"), head: at(frame, "head"), window: at(frame, "window"),
- detail: at(frame, "detail"), detailPlate: at(frame, "detailPlate"),
- wing: [at(frame, "wing.LH"), at(frame, "wing.RH"), at(frame, "wing.LF"), at(frame, "wing.RF")],
- skin: [at(frame, "skin.LH"), 0, at(frame, "skin.LF"), at(frame, "skin.RF")], /* starboard hindwing keeps its membrane omitted */
- abdomen: at(frame, "abdomen"), axis: at(frame, "axis"), key: at(frame, "key.draw"), note: at(frame, "note"), bubble: at(frame, "bubble"),
- furniture: at(frame, "furniture"), section: at(frame, "section"), scale: at(frame, "scale"), list: at(frame, "list"), cartouche: at(frame, "cartouche"), lettering: at(frame, "lettering"), detailNotes: at(frame, "detail.notes"),
- };
- return {
- wings: { flap, sweep: -0.2 * (1 - flap) }, /* a raised wing also rakes forward: the 57o sweep the plate dimensions */
- lift: 1, /* the starboard forewing panel that never comes home: the act ends on the approved plate */
- keyY: at(frame, "key.rise") * (1 - at(frame, "key.out")),
- keyTurn: wind >= 1 || wind <= 0 ? 0 : wind * 7 * Math.PI * 2, /* seven turns, one every five frames */
- train: trainAt(frame),
- shadow: [out * 10, out * 14],
- boil: at(frame, "boil") > 0 && raw(frame, "boil") < 1 ? 0.25 : 0,
- inkedBoil: 0, /* at the desk the finished furniture is dead still (spec 4): only the hero line breathes */
- boilIndex: Math.floor(frame / 5) % 4,
- p,
- view: viewAt(frame),
- };
-};
-
-// The grid is a rule, so it is checked, not trusted (spec 9, G1).
-export const gridProblems = (): string[] => {
- const p: string[] = [];
- CUES.forEach((c) => { if (c.at % 5) p.push(`cue '${c.id}' starts on frame ${c.at}, not a multiple of 5`); if ((c.at + c.dur) % 5) p.push(`cue '${c.id}' ends on frame ${c.at + c.dur}, not a multiple of 5`); if (c.at + c.dur > DURATION) p.push(`cue '${c.id}' ends after the act`); });
- SHOTS.forEach(([id, a, b]) => { if (a % 15 || b % 15) p.push(`shot '${id}' cuts off the beat grid (${a}..${b})`); });
- if (TICK0 % 5) p.push(`the train starts on frame ${TICK0}, not a multiple of 5`);
- return p;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2art.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2art.ts
deleted file mode 100644
index fb19d92..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2art.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-// ACT 2, RISOGRAPH. The same creature, built a completely different way: no ruling pen, no
-// section lines, no drafting furniture. Three spot inks on cream stock, each laid by its own
-// drum pass. Volume is a halftone SCREEN whose dots change size with a tone function, edges are
-// torn rather than ruled, and the plates never quite register, which is the charm of the machine.
-//
-// BLUE plate = the machine: body segments, head, wing ribs, rivets, the key, the imprint.
-// PINK plate = the wings as screen gradients, the going train through the body, antennae, eyes.
-// YELLOW plate = the sun behind it, and the lit side of the body. Overprints multiply.
-import { Ctx, Gfx, P, oval, rng, tube } from "../core";
-import { letter } from "../drafting";
-import { INK, PAPER, cut, screen, smooth } from "../riso";
-import { CX, CY, HEAD, K, KC, THORAX, Wing, cen, lerp } from "./geom";
-import { Train } from "./parts";
-import { inside } from "../riso";
-
-const BLUE = INK.blue, PINK = INK.pink, YELLOW = INK.yellow;
-export const SUN: [number, number, number] = [700, 290, 210]; // upper right, behind it, and it agrees with the finale's sun
-
-// each abdominal segment is its own printed shape, with paper showing in the joints; `flex`
-// is the ripple that runs down the body when it wakes
-const seg = (i: number, flex = 0): P[] => { const segs = 7, y0 = 70, y1 = 238, hw = (t: number) => 23 * (1 - t) ** 0.8 + 6.5, t0 = i / segs, t1 = (i + 1) / segs, g = 2.4, s = 1 + flex * 0.16, dy = flex * 5; /* FABLE review: 0.06 and 2.2 were invisible at viewing size, the wake second read as a still */
- return [[-hw(t0) * s + g, y0 + (y1 - y0) * t0 + g + dy], [hw(t0) * s - g, y0 + (y1 - y0) * t0 + g + dy], [hw(t1) * s - g, y0 + (y1 - y0) * t1 - g + dy], [-hw(t1) * s + g, y0 + (y1 - y0) * t1 - g + dy]].map(([x, y]) => [CX + x * K, CY + y * K] as P); };
-const gearDisc = (cx: number, cy: number, r: number, teeth: number, ph: number, seed: number): P[] => { const rn = rng(seed), out: P[] = []; for (let i = 0; i < teeth * 2; i++) { const a = ph + (i / (teeth * 2)) * Math.PI * 2, rr = (i % 2 ? r * 0.82 : r) * (0.985 + rn() * 0.03); out.push([cx + Math.cos(a) * rr, cy + Math.sin(a) * rr]); } return out; };
-const BODY: P[] = (() => { const segs = 7, y0 = 70, y1 = 238, hw = (t: number) => 23 * (1 - t) ** 0.8 + 6.5, L: P[] = [], R: P[] = [];
- for (let i = 0; i <= 14; i++) { const t = i / 14, y = y0 + (y1 - y0) * t; L.push([CX - hw(t) * K, CY + y * K]); R.push([CX + hw(t) * K, CY + y * K]); }
- return [...THORAX.slice(0, 7), ...R, ...L.reverse(), ...THORAX.slice(7)]; })();
-const antenna = (sd: number, q: number): P[] => { const a0: P = [CX + sd * 8 * K, CY - 127 * K], c = Math.cos(sd * q), s = Math.sin(sd * q), R = (p: P): P => [a0[0] + (p[0] - a0[0]) * c - (p[1] - a0[1]) * s, a0[1] + (p[0] - a0[0]) * s + (p[1] - a0[1]) * c];
- const a1 = R([CX + sd * 56 * K, CY - 206 * K]), a2 = R([CX + sd * 124 * K, CY - 246 * K]);
- return Array.from({ length: 9 }, (_, i) => { const t = i / 8; return lerp(lerp(a0, a1, t), lerp(a1, a2, t), t); }); };
-
-export type BlueS = { key: number; flex: number[]; imprint: number };
-export const bluePlate = (g: Gfx, w: Wing[], s: BlueS) => {
- const c = g.cur, fill = (pts: P[], col = BLUE, a = 1) => { g.mark(pts, 3); c.globalAlpha = a; c.fillStyle = col; g.path(c, pts); c.fill(); c.globalAlpha = 1; };
- w.forEach((wg) => { /* the wing frame: three ribs carry it, and they stay inside the membrane */
- const n = wg.ends.length, inset = smooth(wg.out.map((p) => lerp(p, cen(wg.out), 0.045))), ribs = [0, Math.max(1, (n - 1) >> 1), n - 2].filter((v, i, a) => a.indexOf(v) === i);
- c.save(); g.path(c, inset); c.clip();
- ribs.forEach((j, r) => { const a0 = r === 0 ? 0.04 : 0.1, a1 = r === 0 ? 0.95 : 0.82, line = Array.from({ length: 7 }, (_, q) => wg.spar(j, a0 + (q / 6) * (a1 - a0))); fill(cut(tube(line, r === 0 ? 6.5 : 5, 1.5))); });
- ribs.forEach((j, r) => { for (let q = 1; q <= (r === 0 ? 4 : 2); q++) { const t = r === 0 ? 0.16 + q * 0.19 : 0.3 + q * 0.2, p = wg.spar(j, t); fill(oval(p[0], p[1], r === 0 ? 3.6 : 2.8, r === 0 ? 3.6 : 2.8, 9), PAPER); } }); /* rivets are holes in the ink: riso cannot print white, it leaves the sheet */
- c.restore();
- fill(cut(oval(wg.h[0], wg.h[1], 13, 13, 12))); fill(oval(wg.h[0], wg.h[1], 4.5, 4.5, 9), PAPER);
- });
- for (let i = 0; i < 7; i++) fill(cut(seg(i, s.flex[i] ?? 0)));
- fill(cut(THORAX.map((p) => lerp(p, cen(THORAX), -0.06))));
- fill(cut(HEAD.map((p) => lerp(p, cen(HEAD), -0.08))));
- const sp: P = [CX, CY + 244 * K], sq: P = [CX, CY + 272 * K]; fill(cut(tube([sp, sq], 5, 5)));
- const dy = -38 * s.key; fill(cut(tube([[KC[0], KC[1] - 36 + dy], [KC[0], KC[1] + dy]], 4.6, 4.6))); [-1, 1].forEach((sd) => { fill(cut(oval(KC[0] + sd * 21, KC[1] + 3 + dy, 16, 21, 12))); fill(oval(KC[0] + sd * 21, KC[1] + 3 + dy, 7, 10, 10), PAPER); });
- if (s.imprint > 0) { letter(g, "MECHANICAL LEPIDOPTERA", 92, 966, { cap: 15, seed: 900, color: BLUE, w: 2.2, opacity: 0.92, progress: Math.min(1, s.imprint * 1.6) }); letter(g, "PLATE II - RISOGRAPH, THREE PASSES ON CREAM", 92, 992, { cap: 8.4, seed: 901, color: BLUE, w: 1.1, opacity: 0.8, progress: Math.max(0, s.imprint * 1.6 - 0.6) }); }
- c.save(); g.path(c, smooth(BODY)); c.clip(); /* the shadow lives INSIDE the body, or it is a smear */
- screen(g, { x0: CX - 70, y0: CY - 150, x1: CX + 70, y1: CY + 250 }, 5.2, 22, (x, y) => 0.9 * Math.max(0, (CX + 4 - x) / 34) * Math.max(0, 1 - Math.abs(y - CY - 30) / 260), BLUE); /* the sun is upper right, so the body's shadow side is to port */
- c.restore();
-};
-
-export type PinkS = { train: Train; wheels: number; panel2: number; quiver: [number, number]; proboscis: number; vel: number[] };
-export const pinkPlate = (g: Gfx, w: Wing[], s: PinkS) => {
- const c = g.cur, fill = (pts: P[], col = PINK, a = 1) => { g.mark(pts, 3); c.globalAlpha = a; c.fillStyle = col; g.path(c, pts); c.fill(); c.globalAlpha = 1; };
- w.forEach((wg, i) => {
- const b = { x0: Math.min(...wg.out.map((p) => p[0])) - 6, y0: Math.min(...wg.out.map((p) => p[1])) - 6, x1: Math.max(...wg.out.map((p) => p[0])) + 6, y1: Math.max(...wg.out.map((p) => p[1])) + 6 };
- const R = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) * 0.66, spars = wg.ends.map((_, j) => Array.from({ length: 7 }, (_, q) => wg.spar(j, q / 6)));
- const near = (x: number, y: number) => { let d = 1e9; for (const line of spars) for (const p of line) { const q = (p[0] - x) * (p[0] - x) + (p[1] - y) * (p[1] - y); if (q < d) d = q; } return Math.sqrt(d); };
- const swell = 1 + Math.min(0.55, (s.vel[i] ?? 0) * 3.2); /* dots SWELL with wing velocity: the riso answer to a smear frame */
- const hole = i === 3 && s.panel2 < 1 ? wg.panels[2] : null; /* panel 2 does not print with this pass */
- screen(g, b, 5.6, i < 2 ? 75 : 15, (x, y) => { if (hole && inside(hole, x, y)) return 0; const t = Math.min(1, Math.hypot(x - wg.h[0], y - wg.h[1]) / R), lead = Math.min(1, Math.max(0, (near(x, y) - 6) / 26)); return Math.min(1, (1 - t * 0.97) ** 1.25 * 1.15 * swell) * (0.4 + 0.6 * lead); }, PINK, smooth(wg.out));
- fill(cut(tube([...wg.out, wg.out[0]], 5.5, 5.5, false))); /* the margin: one heavy printed band */
- if (hole) { c.save(); c.globalCompositeOperation = "destination-out"; g.path(c, smooth(hole.map((q) => lerp(q, cen(hole), -0.06)))); c.fill(); c.globalCompositeOperation = "source-over"; c.restore(); } /* the sheet shows through where panel 2 has not printed yet */
- if (i === 3 && s.panel2 > 0) { const pn = wg.panels[2], pb = { x0: Math.min(...pn.map((p) => p[0])) - 4, y0: Math.min(...pn.map((p) => p[1])) - 4, x1: Math.max(...pn.map((p) => p[0])) + 4, y1: Math.max(...pn.map((p) => p[1])) + 4 };
- c.save(); g.path(c, smooth(pn)); c.clip(); screen(g, pb, 5.6, 15, (x, y) => 0.8 * s.panel2 * Math.min(1, Math.max(0, (near(x, y) - 6) / 22)), PINK); c.restore(); fill(cut(tube([...pn, pn[0]], 3.4, 3.4, false)), PINK, s.panel2); } /* it prints alone, a beat late, with no blue under it */
- });
- c.save(); c.globalCompositeOperation = "destination-out"; g.path(c, smooth(BODY)); c.fill(); g.path(c, smooth(HEAD)); c.fill(); c.globalCompositeOperation = "source-over"; c.restore(); /* knock the body out of the wing screens so the inks stay clean */
- if (s.wheels > 0) { const o = cen(THORAX), t = s.train; /* the going train printed straight through the body: two inks, so you can see inside the machine */
- ([[o[0] + 1, o[1] + 10, 27, 14, 0.2 + t.centre], [o[0] - 19, o[1] - 34, 16, 10, 0.5 + t.third], [o[0] + 22, o[1] - 24, 11, 8, 0.1 + t.pinion]] as number[][]).forEach(([x, y, r, teeth, ph], i) => { const q = Math.min(1, Math.max(0, s.wheels * 3 - i)); if (q <= 0) return; fill(gearDisc(x, y, r * q, teeth, ph, 700 + i)); fill(oval(x, y, r * q * 0.3, r * q * 0.3, 10), PAPER); fill(oval(x, y, r * q * 0.1, r * q * 0.1, 8)); }); }
- [-1, 1].forEach((sd, i) => { const a = antenna(sd, s.quiver[i]); fill(cut(tube(a, 3.6, 1.6))); fill(cut(oval(a[8][0], a[8][1], 9, 9, 10))); });
- if (s.proboscis > 0) { const pr: P = [CX, CY - 150 * K], turns = 3.2 - s.proboscis * 1.4, pts: P[] = []; for (let i = 0; i <= 40; i++) { const t = i / 40, a = 1.4 + t * turns * Math.PI * 2, rr = 1.5 + 10 * t * (1 + s.proboscis * 0.6); pts.push([pr[0] + Math.cos(a) * rr, pr[1] + Math.sin(a) * rr * 0.97]); } fill(cut(tube(pts, 2.6, 1.4, false))); } /* the hairspring uncoils to taste the air */
- [-1, 1].forEach((sd) => { fill(cut(oval(CX + sd * 17 * K, CY - 112 * K, 8, 10.5, 10))); fill(oval(CX + sd * 17 * K, CY - 113 * K, 3.4, 4.2, 9), PAPER); });
-};
-
-export const yellowPlate = (g: Gfx, w: Wing[], s: { sun: number; lit: number }) => {
- const c = g.cur, fill = (pts: P[], a = 1) => { g.mark(pts, 3); c.globalAlpha = a; c.fillStyle = YELLOW; g.path(c, pts); c.fill(); c.globalAlpha = 1; };
- if (s.sun > 0) { const [sx, sy, sr] = SUN, r = sr * (0.35 + 0.65 * s.sun); fill(cut(oval(sx, sy, r, r, 22)), 0.78); c.globalCompositeOperation = "destination-out"; c.fillStyle = "#000"; [smooth(BODY), smooth(HEAD)].forEach((k) => { g.path(c, k); c.fill(); }); c.globalCompositeOperation = "source-over"; } /* hand-cut sun disc, behind the creature, transparent ink so it prints last and reads first. FABLE review: the disc is KNOCKED OUT under the body, or blue x yellow turns the whole machine green and the pink train goes black */
- if (s.lit <= 0) return;
- c.save(); g.path(c, smooth(BODY)); c.clip();
- screen(g, { x0: CX - 70, y0: CY - 160, x1: CX + 70, y1: CY + 250 }, 5.2, 68, (x, y) => s.lit * 0.85 * Math.max(0, 1 - Math.abs(x - (CX + 14)) / 15) * Math.max(0, 1 - Math.abs(y - CY - 20) / 250), YELLOW); /* the sun is upper right, so the lit edge is a band, and the body stays the machine's colour */
- c.restore();
- c.save(); g.path(c, smooth(HEAD)); c.clip(); screen(g, { x0: CX - 40, y0: CY - 140, x1: CX + 40, y1: CY - 80 }, 5, 68, (x) => s.lit * 0.8 * Math.max(0, 1 - Math.abs(x - (CX + 12)) / 13), YELLOW); c.restore();
-};
-
-export const stock = (g: Gfx, W: number, H: number) => { const c = g.main, e = g.env, dw = Math.round(W * e.scale), dh = Math.round(H * e.scale); c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.fillStyle = PAPER; c.fillRect(0, 0, dw, dh); c.restore(); g.paper("coldpress", 0.3); };
-export const marks = (g: Gfx, W: number, H: number, p: number, bars: number) => {
- if (p > 0) g.group("plain", () => { const c = g.cur, n = 4; g.touch(0, 0, W, H); c.strokeStyle = "#2a2a2a"; c.lineWidth = 1.1; [[30, 30], [W - 30, 30], [30, H - 30], [W - 30, H - 30]].forEach(([x, y], i) => { if (p * n < i) return; const q = Math.min(1, p * n - i); c.beginPath(); c.arc(x, y, 7 * q, 0, Math.PI * 2); c.moveTo(x - 13 * q, y); c.lineTo(x + 13 * q, y); c.moveTo(x, y - 13 * q); c.lineTo(x, y + 13 * q); c.stroke(); }); }, { alpha: 0.85 });
- [BLUE, PINK, YELLOW].forEach((col, i) => { const q = Math.min(1, Math.max(0, bars * 3 - i)); if (q <= 0) return; g.group("plain", () => { const c = g.cur, x = W / 2 - 52 + i * 36, y = H - 42; g.touch(x, y, x + 28, y + 16); c.fillStyle = col; c.fillRect(x, y, 28 * q, 16); }, { blend: "multiply", textures: ["risoSpeck"] }); });
-};
-export const grain = (g: Gfx) => { g.paper("paper", 0.3); g.paper("coldpress", 0.18); };
-// the drum sweeps the sheet: everything above the roller line has been printed
-export const rollerPath = (c: Ctx, W: number, H: number, r: number) => { const y = -50 + r * (H + 100); c.beginPath(); c.moveTo(-10, -10); c.lineTo(W + 10, -10); c.lineTo(W + 10, y); for (let x = W + 10; x >= -10; x -= 30) c.lineTo(x, y + Math.sin(x * 0.021 + 1.3) * 3.5 + Math.sin(x * 0.006) * 2.5); c.closePath(); return y; };
-export const wetEdge = (c: Ctx, W: number, H: number, r: number, col: string) => { if (r <= 0 || r >= 1) return; const y = -50 + r * (H + 100); c.save(); c.globalAlpha = 0.5; c.strokeStyle = col; c.lineWidth = 6; c.beginPath(); for (let x = -10; x <= W + 10; x += 30) { const yy = y + Math.sin(x * 0.021 + 1.3) * 3.5 + Math.sin(x * 0.006) * 2.5; x === -10 ? c.moveTo(x, yy) : c.lineTo(x, yy); } c.stroke(); c.restore(); }; /* the ink is still wet at the roller line */
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2cues.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2cues.ts
deleted file mode 100644
index c231001..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2cues.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-// ACT 2, RISOGRAPH: 360 frames, 12 s, 24 beats. It STIRS. Frame 0 is Act 1's last frame; the
-// first drum pass wipes the blueprint off the sheet and replaces it with ink. Then three passes,
-// a train that stalls and catches, a first twitch, a body that wakes, and full flutter.
-// Nothing is ever still: there is no blank stock and no end hold.
-import { P } from "../core";
-import { RisoState } from "./act2plate";
-import { Pose } from "./geom";
-import { Train } from "./parts";
-import { View } from "./surface";
-
-export type Ease = "linear" | "out" | "inout" | "flick";
-export type Cue = { at: number; dur: number; id: string; ease?: Ease; amp?: number };
-export const DURATION = 360, TICK = 5, TRAIN0 = 60; // the train takes its first step when the pink plate lands
-export const SHOTS: [string, number, number][] = [
- ["blue", 0, 30], /* the blue drum wipes the blueprint off the sheet */
- ["pink", 30, 60], /* the second pass lands badly out of register */
- ["jog", 60, 90], /* the operator nudges the sheet twice, and panel 2 prints alone and late */
- ["yellow", 90, 120], /* the sun, and the lit side of the body */
- ["catch", 120, 150], /* the gears stall, hang for two ticks, and catch with a double step */
- ["twitch", 150, 180], /* first wing twitch, port alone, starboard answering */
- ["wake", 180, 210], /* the body wakes: a ripple down the abdomen, both antennae sweeping */
- ["flaps", 210, 270], /* first real flaps, all four wings */
- ["lift", 270, 330], /* sustained flutter, and it lifts off the stock leaving a ghost */
- ["flutter", 330, 360],/* full amplitude, cut on the top of an up-stroke */
-];
-
-export const CUES: Cue[] = [
- { at: 0, dur: 25, id: "pass.blue", ease: "linear" }, { at: 0, dur: 25, id: "marks" }, { at: 10, dur: 25, id: "imprint" }, { at: 5, dur: 10, id: "bar1" },
- { at: 30, dur: 25, id: "pass.pink", ease: "linear" }, { at: 45, dur: 10, id: "wheels" }, { at: 45, dur: 10, id: "bar2" },
- { at: 60, dur: 15, id: "jog1", ease: "out" }, { at: 80, dur: 10, id: "jog2", ease: "out" }, { at: 75, dur: 10, id: "panel2", ease: "out" },
- { at: 90, dur: 25, id: "pass.yellow", ease: "linear" }, { at: 90, dur: 20, id: "sun", ease: "out" }, { at: 95, dur: 20, id: "lit" }, { at: 110, dur: 10, id: "bar3" },
- { at: 135, dur: 10, id: "quiver.port", ease: "flick", amp: 1 }, { at: 140, dur: 10, id: "quiver.star", ease: "flick", amp: 1 },
- { at: 150, dur: 10, id: "twitch.port", ease: "flick", amp: 0.14 }, { at: 165, dur: 10, id: "twitch.star", ease: "flick", amp: 0.14 },
- { at: 170, dur: 10, id: "proboscis", ease: "out" },
- { at: 180, dur: 35, id: "ripple" }, { at: 180, dur: 35, id: "sweep", ease: "flick", amp: 1 },
- { at: 210, dur: 15, id: "flap1", ease: "flick", amp: 0.4 }, { at: 225, dur: 15, id: "flap2", ease: "flick", amp: 0.55 }, { at: 240, dur: 10, id: "flap3", ease: "flick", amp: 0.62 },
- { at: 250, dur: 10, id: "flap4", ease: "flick", amp: 0.62 }, { at: 260, dur: 10, id: "flap5", ease: "flick", amp: 0.62 },
- { at: 270, dur: 10, id: "f1", ease: "flick", amp: 0.55 }, { at: 280, dur: 10, id: "f2", ease: "flick", amp: 0.55 }, { at: 290, dur: 10, id: "f3", ease: "flick", amp: 0.55 },
- { at: 300, dur: 10, id: "f4", ease: "flick", amp: 0.55 }, { at: 310, dur: 10, id: "f5", ease: "flick", amp: 0.55 }, { at: 320, dur: 10, id: "f6", ease: "flick", amp: 0.55 },
- { at: 330, dur: 10, id: "f7", ease: "flick", amp: 0.62 }, { at: 340, dur: 10, id: "f8", ease: "flick", amp: 0.62 }, { at: 350, dur: 10, id: "f9", ease: "inout", amp: 0.55 }, /* the last up-stroke, still rising when we cut */
- { at: 285, dur: 20, id: "lift", ease: "inout" }, { at: 285, dur: 15, id: "ghost" }, { at: 330, dur: 30, id: "ghost.shrink", ease: "out" },
-];
-
-const CAM: { at: number; cx: number; cy: number; z: number; ease: Ease }[] = [
- { at: 0, cx: 540, cy: 540, z: 1, ease: "linear" }, { at: 25, cx: 540, cy: 540, z: 1, ease: "linear" }, { at: 30, cx: 540, cy: 537, z: 1.012, ease: "inout" },
- { at: 60, cx: 540, cy: 470, z: 1.15, ease: "linear" }, { at: 120, cx: 540, cy: 466, z: 1.18, ease: "inout" }, /* creep */
- { at: 150, cx: 540, cy: 440, z: 1.22, ease: "linear" }, { at: 240, cx: 540, cy: 436, z: 1.25, ease: "inout" }, /* FABLE review: at 1.3 the resting wingtips kissed the frame edge (my spec's number, corrected there too) */
- { at: 270, cx: 540, cy: 420, z: 1.45, ease: "linear" }, { at: 330, cx: 540, cy: 416, z: 1.48, ease: "inout" },
- { at: 360, cx: 540, cy: 400, z: 1.6, ease: "linear" },
-];
-
-const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
-const ease = (p: number, e: Ease = "linear") => (e === "inout" ? (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2) : e === "out" ? 1 - (1 - p) ** 3 : e === "flick" ? (p < 0.35 ? Math.sin((p / 0.35) * Math.PI / 2) : Math.cos(((p - 0.35) / 0.65) * Math.PI / 2)) : p);
-const byId = new Map(CUES.map((c) => [c.id, c]));
-const cue = (id: string) => { const c = byId.get(id); if (!c) throw new Error(`no cue '${id}'`); return c; };
-export const at = (frame: number, id: string) => { const c = cue(id); return ease(clamp((frame - c.at) / c.dur), c.ease); };
-
-// THE TRAIN. It steps on the tick from 60, stalls at 120 with a 3 degree recoil, hangs for two
-// ticks, and catches up with a double step at 130.
-const STEP = [14 / 24, 26 / 24, 1, 1, 1];
-const teeth = (f: number): number => { if (f < TRAIN0 + TICK) return 0; const g = f >= 120 && f < 130 ? 119 : f, t = Math.floor((g - TRAIN0) / TICK), s = (g - TRAIN0) % TICK; return t - 1 + STEP[s]; };
-export const trainAt = (f: number): Train => {
- const a = teeth(f), w = (Math.PI * 2) / 96, stalled = f >= 120 && f < 130, recoil = stalled ? -(3 * Math.PI) / 180 : 0;
- const t = Math.floor((f - TRAIN0) / TICK), s = (f - TRAIN0) % TICK, tremble = stalled ? ((f % 2) - 0.5) * 0.02 : 0;
- const rocking = f >= TRAIN0 + TICK && s === 0 ? 0 : 0.085 * (t % 2 ? 1 : -1);
- return { centre: a * w, third: -a * w * (24 / 14), pinion: a * w * (24 / 8), escape: a * ((Math.PI * 2) / 15) + recoil, fork: (f < TRAIN0 + TICK ? 0 : rocking) + tremble };
-};
-
-const viewAt = (frame: number): View => {
- let i = 0; for (let j = 0; j < CAM.length; j++) if (CAM[j].at <= frame) i = j;
- const a = CAM[i], b = CAM[Math.min(CAM.length - 1, i + 1)];
- if (b.at <= a.at) return { cx: a.cx, cy: a.cy, zoom: a.z };
- const t = ease(clamp((frame - a.at) / (b.at - a.at)), a.ease);
- return { cx: a.cx + (b.cx - a.cx) * t, cy: a.cy + (b.cy - a.cy) * t, zoom: Math.exp(Math.log(a.z) + (Math.log(b.z) - Math.log(a.z)) * t) };
-};
-
-// per-wing flap. Port leads starboard by 5 frames, and only the forewings twitch at first.
-const FLAPS = ["flap1", "flap2", "flap3", "flap4", "flap5", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9"];
-const flapOf = (frame: number, wing: number): number => {
- const star = wing === 1 || wing === 3, f = frame - (star ? 2 : 0), fore = wing >= 2; /* FABLE review: a 5-frame lag on a 10-frame beat is ANTIPHASE, one side folded while the other is spread. 2 frames keeps it lopsided and together */
- let v = 1;
- if (fore) v -= (cue(star ? "twitch.star" : "twitch.port").amp ?? 0) * at(frame, star ? "twitch.star" : "twitch.port");
- FLAPS.forEach((id) => { v -= (cue(id).amp ?? 0) * at(f, id); });
- return clamp(v, 0.25, 1);
-};
-export const poseAt = (frame: number, wing: number): Pose => { const flap = flapOf(frame, wing); return { flap, sweep: -0.2 * (1 - flap) }; };
-
-export const stateAt = (frame: number): RisoState => {
- const poses = [0, 1, 2, 3].map((i) => poseAt(frame, i));
- const vel = [0, 1, 2, 3].map((i) => Math.abs(flapOf(frame, i) - flapOf(frame - 1, i)));
- const j1 = at(frame, "jog1"), j2 = at(frame, "jog2");
- const OFF0: P = [17, -12], OFF1: P = [9.5, -6.5], OFF2: P = [4.5, -3];
- const lagN = Math.max(...vel) * 60; /* misregistration as follow-through: the pink plate lags a fast move and catches up */
- const reg: P = [OFF0[0] + (OFF1[0] - OFF0[0]) * j1 + (OFF2[0] - OFF1[0]) * j2 + lagN * 0.6, OFF0[1] + (OFF1[1] - OFF0[1]) * j1 + (OFF2[1] - OFF1[1]) * j2 + lagN * 0.4];
- const lift = at(frame, "lift"), sway = ((frame - 285) / 60) * Math.PI * 2;
- const L: P = lift > 0 ? [Math.sin(sway) * 7 * lift, -14 * lift + Math.sin(sway * 2) * 4 * lift] : [0, 0]; /* a slow figure of eight, the way a thing that has just learned to fly holds itself */
- const rip = at(frame, "ripple"), flex = Array.from({ length: 7 }, (_, i) => { const t = clamp((rip * 7 - i) * 1.6); return Math.sin(t * Math.PI) * (1 - i * 0.06); });
- const q = at(frame, "quiver.port"), qs = at(frame, "quiver.star"), sw = at(frame, "sweep");
- return {
- poses, view: viewAt(frame),
- blue: at(frame, "pass.blue"), pink: at(frame, "pass.pink"), yellow: at(frame, "pass.yellow"),
- reg, lift: L, ghost: at(frame, "ghost") * (1 - 0.6 * at(frame, "ghost.shrink")),
- marks: at(frame, "marks"), bars: (at(frame, "bar1") + at(frame, "bar2") + at(frame, "bar3")) / 3, imprint: at(frame, "imprint"),
- train: trainAt(frame), wheels: at(frame, "wheels"), panel2: at(frame, "panel2"),
- quiver: [q * 0.1 + sw * 0.26, qs * 0.1 + sw * 0.2], /* FABLE review: 3 to 5 degrees did not read; antennae are the first thing that says alive */ proboscis: at(frame, "proboscis"), key: 0,
- flex, vel, sun: at(frame, "sun"), lit: at(frame, "lit"),
- };
-};
-export const END_POSE = (): Pose[] => [0, 1, 2, 3].map((i) => poseAt(DURATION - 1, i)); // Act 3 opens on exactly this
-export const gridProblems = (): string[] => {
- const p: string[] = [];
- CUES.forEach((c) => { if (c.at % 5) p.push(`cue '${c.id}' starts on frame ${c.at}, not a multiple of 5`); if ((c.at + c.dur) % 5) p.push(`cue '${c.id}' ends on frame ${c.at + c.dur}, not a multiple of 5`); if (c.at + c.dur > DURATION) p.push(`cue '${c.id}' ends after the act`); });
- CAM.forEach((k) => { if (k.at % 5) p.push(`camera key at frame ${k.at} is not a multiple of 5`); });
- SHOTS.forEach(([id, a, b]) => { if (a % 15 || b % 15) p.push(`shot '${id}' cuts off the beat grid (${a}..${b})`); });
- return p;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2plate.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2plate.ts
deleted file mode 100644
index 1588627..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act2plate.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// THE PRESS. Three plates, one sheet, and the sheet underneath is still Act 1. Each plate is
-// drawn on its own surface and printed with MULTIPLY at its own registration offset, so the
-// offset can lag, jog and be corrected without redrawing a dot, and each drum pass is revealed
-// by its own roller line at composite time.
-import { Ctx, Env, Gfx, Medium, P } from "../core";
-import { INK, LITHO } from "../riso";
-import { FW, FW_H, FW_T, HW, HW_H, HW_T, Pose, REST, Wing, wingGeom } from "./geom";
-import { BlueS, PinkS, bluePlate, grain, marks, pinkPlate, rollerPath, stock, wetEdge, yellowPlate } from "./act2art";
-import { Train } from "./parts";
-import { View, WIDE, blit, kk, part, slotOf } from "./surface";
-import { stateAt as act1StateAt } from "./act1cues";
-import { drawPlate } from "./plate";
-
-export type RisoState = {
- poses: Pose[]; view: View;
- blue: number; pink: number; yellow: number; /* roller pass progress, 0 = not printed */
- reg: P; lift: P; ghost: number; marks: number; bars: number; imprint: number;
- train: Train; wheels: number; panel2: number; quiver: [number, number]; proboscis: number; key: number;
- flex: number[]; vel: number[]; sun: number; lit: number;
-};
-const nibFor = (z: number): Medium => (z === 1 ? LITHO : { ...LITHO, nib: (LITHO.nib * Math.pow(z, 0.35)) / z }); // weight tracks zoom^0.35, never the transform
-
-export const drawRiso = (ctx: Ctx, env: Env, s: RisoState) => {
- const W = env.W, H = env.H, v = s.view, vk = kk(v.cx, v.cy, v.zoom), med = nibFor(v.zoom);
- const P4 = (p: Pose[]): Wing[] => [wingGeom(-1, HW, HW_H, HW_T, 2000, p[0]), wingGeom(1, HW, HW_H, HW_T, 2600, p[1]), wingGeom(-1, FW, FW_H, FW_T, 1000, p[2]), wingGeom(1, FW, FW_H, FW_T, 1600, p[3])];
- const w = P4(s.poses), pk = kk(...s.poses.flatMap((p) => [p.flap, p.sweep]));
- const pt = (name: string, key: string, fn: (g: Gfx) => void) => part(env, med, name, key + "|" + vk, 0, fn, v);
-
- const sheet = pt("stock", "stock", (g) => stock(g, W, H));
- const blueS: BlueS = { key: s.key, flex: s.flex, imprint: s.imprint };
- const blue = s.blue > 0 ? pt("blue", kk("b", pk, s.key, s.imprint, ...s.flex), (g) => bluePlate(g, w, blueS)) : null;
- const pinkS: PinkS = { train: s.train, wheels: s.wheels, panel2: s.panel2, quiver: s.quiver, proboscis: s.proboscis, vel: s.vel };
- const pink = s.pink > 0 ? pt("pink", kk("p", pk, s.wheels, s.panel2, s.train.centre, s.train.escape, s.quiver[0], s.quiver[1], s.proboscis, ...s.vel.map((x) => Math.round(x * 40) / 40)), (g) => pinkPlate(g, w, pinkS)) : null;
- const yellow = s.yellow > 0 ? pt("yellow", kk("y", s.sun, s.lit), (g) => yellowPlate(g, w, { sun: s.sun, lit: s.lit })) : null;
- const furn = pt("marks", kk(s.marks, s.bars), (g) => marks(g, W, H, s.marks, s.bars));
- /* the sheet underneath is Act 1's last frame: the transition is a drum pass over the blueprint */
- const under = s.blue < 1 ? part(env, med, "blueprint", "act1-539", 0, (g) => drawPlate(g.main, env, act1StateAt(539)), WIDE) : null;
-
- const pass = (r: number, draw: () => void) => { if (r <= 0) return; ctx.save(); if (r < 1) { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); rollerPath(ctx, W, H, r); ctx.clip(); } draw(); ctx.restore(); };
- const L: P = s.lift, sc = env.scale;
- blit(ctx, under);
- pass(s.blue, () => { blit(ctx, sheet); if (s.ghost > 0 && blue) blit(ctx, blue, 0, 0, 0.3 * s.ghost, "multiply"); blit(ctx, blue, Math.round(L[0] * sc), Math.round(L[1] * sc), 1, "multiply"); }); /* the ghost is the print it left on the stock where it sat */
- pass(s.pink, () => blit(ctx, pink, Math.round((L[0] + s.reg[0]) * sc), Math.round((L[1] + s.reg[1]) * sc), 1, "multiply"));
- pass(s.yellow, () => blit(ctx, yellow, Math.round(L[0] * sc), Math.round(L[1] * sc), 1, "multiply"));
- ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); wetEdge(ctx, W, H, s.blue, INK.blue); wetEdge(ctx, W, H, s.pink, INK.pink); wetEdge(ctx, W, H, s.yellow, INK.yellow); ctx.restore();
- blit(ctx, furn); /* register crosses and colour bars stay exactly where they were struck */
- if (s.blue > 0) { ctx.save(); if (s.blue < 1) { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); rollerPath(ctx, W, H, s.blue); ctx.clip(); } grain(new Gfx(ctx, env, 0, LITHO)); ctx.restore(); } /* the cream stock only has tooth where the cream stock is: frame 0 must still be Act 1 exactly */
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3art.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3art.ts
deleted file mode 100644
index 9f17d15..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3art.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-// ACT 3, EDITORIAL CUTAWAY. The fourth construction: a page from a technical magazine. One
-// confident thick-thin contour, flat limited colour laid with a swipe, paper cut faces with a
-// hard section edge, and ONE accent, vermilion, on every part that MOVES and on nothing else.
-// Force arrows and the travelling pulse are in the riso yellow, so the colour carries over.
-import { Ctx, Gfx, P, arc, oval, rng, tube } from "../core";
-import { letter, width } from "../drafting";
-import { CX, CY, HEAD, K, THORAX, Wing, cen, lerp } from "./geom";
-import { ARBOR, RC, armEnd, bellAngle, crankPin, outEnd, pivot } from "./linkage";
-import { Train } from "./parts";
-
-export const PAGE = "#f6f1e7", INK = "#2b2a28", HOUSE = "#8ca0a2", HOUSE2 = "#7a9092", FACE = "#e7e0d2", ACCENT = "#e2452b", PULSE = "#f2b705";
-const swipeClip = (c: Ctx, g: Gfx, pts: P[], t: number, axis: "x" | "y" = "x") => { /* flat colour is LAID along the shape's long axis, never faded up */
- const xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1]), x0 = Math.min(...xs) - 6, x1 = Math.max(...xs) + 6, y0 = Math.min(...ys) - 6, y1 = Math.max(...ys) + 6;
- c.beginPath(); if (axis === "x") c.rect(x0, y0, (x1 - x0) * t, y1 - y0); else c.rect(x0, y0, x1 - x0, (y1 - y0) * t); c.clip(); g.touch(x0, y0, x1, y1);
-};
-const flat = (g: Gfx, pts: P[], col: string, t = 1, axis: "x" | "y" = "x", alpha = 1) => { if (t <= 0) return; const c = g.cur; c.save(); swipeClip(c, g, pts, t, axis); c.globalAlpha = alpha; c.fillStyle = col; g.path(c, pts); c.fill(); c.restore(); };
-// one brush-pen contour: thick where the form turns away from the light, thin on the lit side
-export const contour = (g: Gfx, pts: P[], w0: number, w1: number, seed: number, t = 1, col = INK) => { if (t <= 0) return; const n = Math.max(2, Math.round(pts.length * Math.min(1, t))), s = pts.slice(0, n); if (s.length < 2) return; g.fill(tube(s, w0, w1, false), col, 0.96); };
-export const hatchFace = (g: Gfx, pts: P[], seed: number, t = 1) => { /* a cut face is paper, with sparse section lines so it reads as CUT and not as a hole */
- if (t <= 0) return; const c = g.cur, r = rng(seed), b = { x0: Math.min(...pts.map((p) => p[0])), y0: Math.min(...pts.map((p) => p[1])), x1: Math.max(...pts.map((p) => p[0])), y1: Math.max(...pts.map((p) => p[1])) };
- c.save(); g.path(c, pts); c.clip(); g.touch(b.x0, b.y0, b.x1, b.y1);
- c.strokeStyle = INK; c.globalAlpha = 0.33; c.lineWidth = 1.1; const span = b.x1 - b.x0 + (b.y1 - b.y0), n = Math.floor((span / 13) * t);
- for (let i = 0; i < n; i++) { const o = b.x0 - (b.y1 - b.y0) + i * 13 + r() * 2; c.beginPath(); c.moveTo(o, b.y1 + 4); c.lineTo(o + (b.y1 - b.y0) + 8, b.y0 - 4); c.stroke(); }
- c.globalAlpha = 1; c.restore();
-};
-export const page = (g: Gfx, W: number, H: number) => { const c = g.main, e = g.env, dw = Math.round(W * e.scale), dh = Math.round(H * e.scale); c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.fillStyle = PAGE; c.fillRect(0, 0, dw, dh); c.restore(); g.paper("paper", 0.1); };
-
-// ---------------------------------------------------------------- the creature, in section
-export type A3 = { th: number; shell: number; faces: number; accent: number; wings: number; lift: P; bleed: number; ghostRod: number; arc: number; ghostSpar: number };
-export const creature = (g: Gfx, w: Wing[], s: A3) => {
- const c = g.cur, acc = (i: number) => Math.min(1, Math.max(0, s.accent * 6 - i)); /* vermilion is laid part by part, in the order the force travels */
- w.forEach((wg, i) => { /* wings: flat pale colour, then the contour, then the leading spar in accent because it MOVES */
- flat(g, wg.out, "#dfe4e2", s.wings, i % 2 ? "x" : "x", 0.95);
- contour(g, [...wg.out, wg.out[0]], 3.4, 2.2, 400 + i, s.wings);
- const ribs = [0, Math.max(1, (wg.ends.length - 1) >> 1)];
- c.save(); g.path(c, wg.out); c.clip(); /* the frame belongs to the wing: never a ray across the page */
- ribs.forEach((j, r) => { const line = Array.from({ length: 7 }, (_, q) => wg.spar(j, 0.05 + (q / 6) * 0.9)), driven = r === 0 && i >= 2; g.fill(tube(line, driven ? 4.2 : 3, 1.3), driven ? ACCENT : INK, driven ? Math.max(0.15, acc(5)) : 0.85); }); /* the bell-crank drives the FOREWING leading spar: that is the part that moves */
- c.restore();
- });
- if (s.ghostSpar > 0) { const wg = w[2], gq = (t: number) => Array.from({ length: 7 }, (_, q) => wg.spar(0, 0.05 + (q / 6) * 0.9)).map((p) => [p[0], p[1] + t] as P); [-46, 0, 46].forEach((dy, i) => { if (s.ghostSpar * 3 < i) return; const pts = gq(dy); c.save(); c.setLineDash([7, 5]); c.strokeStyle = ACCENT; c.globalAlpha = 0.45; c.lineWidth = 1.6; c.beginPath(); pts.forEach(([x, y], k) => (k ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke(); c.setLineDash([]); c.globalAlpha = 1; c.restore(); g.touch(pts[0][0] - 10, pts[0][1] - 10, pts[6][0] + 10, pts[6][1] + 10); }); } /* where the spar is at the top, the middle and the bottom of its stroke */
- /* body: the housing slides off up-left on two projection dashes, leaving the section open */
- const off: P = [-72 * s.shell, -58 * s.shell], shell = THORAX.map(([x, y]) => [x + off[0], y + off[1]] as P);
- if (s.shell > 0.02) [2, 8].forEach((k, i) => { const a = THORAX[k], b: P = [a[0] + off[0], a[1] + off[1]]; c.save(); c.setLineDash([6, 5]); c.strokeStyle = INK; c.globalAlpha = 0.5; c.lineWidth = 1.2; c.beginPath(); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); c.stroke(); c.setLineDash([]); c.globalAlpha = 1; c.restore(); g.touch(Math.min(a[0], b[0]) - 4, Math.min(a[1], b[1]) - 4, Math.max(a[0], b[0]) + 4, Math.max(a[1], b[1]) + 4); });
- flat(g, shell, HOUSE, 1, "y"); contour(g, [...shell, shell[0]], 3.2, 2.4, 410);
- const inner = THORAX.map((p) => lerp(p, cen(THORAX), 0.1));
- flat(g, inner, FACE, s.faces, "x"); hatchFace(g, inner, 411, s.faces); contour(g, [...inner, inner[0]], 2.6, 1.8, 412, s.faces); /* the cut face, hard-edged */
- const abd: P[] = [];
- for (let i = 0; i <= 10; i++) { const t = i / 10, y = 70 + 168 * t, hw = 23 * (1 - t) ** 0.8 + 6.5; abd.push([CX + hw * K, CY + y * K]); }
- for (let i = 10; i >= 0; i--) { const t = i / 10, y = 70 + 168 * t, hw = 23 * (1 - t) ** 0.8 + 6.5; abd.push([CX - hw * K, CY + y * K]); }
- flat(g, abd, HOUSE2, 1, "y"); contour(g, [...abd, abd[0]], 3, 2.2, 413);
- flat(g, HEAD, HOUSE, 1, "x"); contour(g, [...HEAD, HEAD[0]], 3, 2.2, 414);
-};
-
-// ---------------------------------------------------------------- the mechanism, all of it true
-export const mechanism = (g: Gfx, s: A3, t: Train, show: number) => {
- if (show <= 0) return;
- const c = g.cur, acc = (i: number) => Math.min(1, Math.max(0, s.accent * 6 - i));
- const wheel = (cx: number, cy: number, r: number, teeth: number, ph: number, seed: number, a: number) => { if (a <= 0) return; const pts: P[] = []; for (let i = 0; i < teeth * 2; i++) { const an = ph + (i / (teeth * 2)) * Math.PI * 2, rr = i % 2 ? r * 0.84 : r; pts.push([cx + Math.cos(an) * rr, cy + Math.sin(an) * rr]); } g.fill(pts, ACCENT, a); g.fill(oval(cx, cy, r * 0.68, r * 0.68, 14), PAGE, a); g.fill(tube([...oval(cx, cy, r * 0.68, r * 0.68, 14), [cx + r * 0.68, cy]], 1.5, 1.5, false), INK, a * 0.8); for (let k = 0; k < 4; k++) { const an = ph + (k / 4) * Math.PI * 2; g.fill(tube([[cx + Math.cos(an) * r * 0.12, cy + Math.sin(an) * r * 0.12], [cx + Math.cos(an) * r * 0.64, cy + Math.sin(an) * r * 0.64]], 2.4, 1.8), ACCENT, a); } g.fill(oval(cx, cy, r * 0.13, r * 0.13, 9), INK, a); }; /* a wheel is a rim, a web and four spokes, not a red disc */
- const br: P = [ARBOR[0] - 44, ARBOR[1] - 10];
- g.fill(oval(br[0], br[1], 26, 26, 18), ACCENT, acc(0) * 0.92); g.fill(oval(br[0], br[1], 21, 21, 16), PAGE, acc(0)); /* mainspring barrel */
- { const pts: P[] = []; for (let i = 0; i <= 56; i++) { const q = i / 56, a = 0.6 - t.centre * 0.25 + q * 4.2 * Math.PI * 2, rr = 3 + 17 * q; pts.push([br[0] + Math.cos(a) * rr, br[1] + Math.sin(a) * rr]); } g.fill(tube(pts, 1.9, 1.3, false), ACCENT, acc(0)); }
- wheel(ARBOR[0], ARBOR[1], 25, 16, 0.2 + t.centre, 420, acc(1)); /* centre wheel */
- wheel(ARBOR[0] + 34, ARBOR[1] - 30, 13, 10, 0.5 + t.third, 421, acc(1) * 0.9);
- wheel(ARBOR[0] + 52, ARBOR[1] + 4, 10, 8, 0.1 + t.pinion, 422, acc(1) * 0.9); /* escapement end of the train */
- const P0 = crankPin(s.th);
- g.fill(tube([ARBOR, P0], 3.6, 3.6), ACCENT, acc(2)); g.fill(oval(P0[0], P0[1], 4.6, 4.6, 10), ACCENT, acc(2)); /* the crank */
- [-1, 1].forEach((side) => {
- const Q = pivot(side), R = armEnd(side, s.th), S = outEnd(side, s.th), i = side < 0 ? 4 : 5;
- if (s.ghostRod > 0 && side < 0) [0, Math.PI / 2, Math.PI].forEach((ph, k) => { if (s.ghostRod * 3 < k) return; const gp = crankPin(ph), gr = armEnd(side, ph); c.save(); c.setLineDash([6, 4]); c.strokeStyle = ACCENT; c.globalAlpha = 0.4; c.lineWidth = 1.5; c.beginPath(); c.moveTo(gp[0], gp[1]); c.lineTo(gr[0], gr[1]); c.stroke(); c.setLineDash([]); c.globalAlpha = 1; c.restore(); g.touch(Math.min(gp[0], gr[0]) - 6, Math.min(gp[1], gr[1]) - 6, Math.max(gp[0], gr[0]) + 6, Math.max(gp[1], gr[1]) + 6); }); /* onion skin: the rod at three crank angles */
- g.fill(tube([P0, R], 3.2, 3.2), ACCENT, acc(3)); /* connecting rod */
- g.fill(tube([R, Q, S], 4.2, 4.2), ACCENT, acc(i)); g.fill(oval(Q[0], Q[1], 4.2, 4.2, 10), PAGE, acc(i)); /* bell-crank, pivot left as paper */
- });
- if (s.arc > 0) { const Q = pivot(-1), a0 = bellAngle(-1, 0), a1 = bellAngle(-1, Math.PI), pts = arc(Q[0], Q[1], 54, 54, a0, a0 + (a1 - a0) * s.arc, 12); g.fill(tube(pts, 1.8, 1.8, false), PULSE, 0.9); for (let i = 0; i <= 4; i++) { const a = a0 + (a1 - a0) * s.arc * (i / 4), p: P = [Q[0] + Math.cos(a) * 54, Q[1] + Math.sin(a) * 54], q: P = [Q[0] + Math.cos(a) * 61, Q[1] + Math.sin(a) * 61]; g.fill(tube([p, q], 1.5, 1.5), PULSE, 0.9); } } /* the stroke, measured */
-};
-
-// the pulse hops along the train, one wheel per tick: the force, made visible
-export const pulse = (g: Gfx, s: { at: number; on: number }) => {
- if (s.on <= 0) return;
- const stops: P[] = [[ARBOR[0] - 44, ARBOR[1] - 10], ARBOR, crankPin(0), [ARBOR[0] + 34, ARBOR[1] - 30]];
- const i = Math.floor(s.at) % stops.length, j = (i + 1) % stops.length, f = s.at - Math.floor(s.at), p = lerp(stops[i], stops[j], f * f * (3 - 2 * f));
- g.fill(oval(p[0], p[1], 7.5, 7.5, 12), PULSE, 0.95 * s.on); g.fill(oval(p[0], p[1], 3.4, 3.4, 10), "#fff6d8", 0.9 * s.on);
-};
-
-// ---------------------------------------------------------------- the annotation
-export type Label = { n: string; text: string; at: P; to: P; p: number };
-export const labels = (g: Gfx, ls: Label[]) => ls.forEach((l, i) => {
- if (l.p <= 0) return;
- const q = (k: number) => Math.min(1, Math.max(0, l.p * 3 - k)), x0 = l.at[0];
- g.fill(oval(x0 - 11, l.at[1] - 4, 8.6, 8.6, 12), ACCENT, q(0)); letter(g, l.n, x0 - 11, l.at[1] - 0.4, { cap: 8.4, align: "center", seed: 470 + i, color: PAGE, w: 1.3, progress: q(0) });
- letter(g, l.text, x0 + 2, l.at[1] - 4.5, { cap: 9.5, seed: 480 + i, color: INK, w: 1.25, progress: q(1) });
- const a: P = [x0 + 2, l.at[1] + 5], b = l.to, t = q(2); if (t <= 0) return;
- g.fill(tube([a, lerp(a, b, t)], 1.1, 1.1), INK, 0.7); if (t >= 1) g.fill([b, [b[0] - 7, b[1] - 3], [b[0] - 6, b[1]], [b[0] - 7, b[1] + 3]], INK, 0.8);
-});
-export const caption = (g: Gfx, text: string, v: { cx: number; cy: number; zoom: number }, p: number) => { if (p <= 0) return; letter(g, text, v.cx, v.cy + 430 / v.zoom, { cap: 19 / v.zoom, align: "center", seed: 495, color: INK, w: 2.4 / v.zoom, progress: p }); }; /* written across the foot of the FRAME, at whatever zoom the camera is */
-// a force arrow in the riso yellow: where the push goes next
-export const force = (g: Gfx, a: P, b: P, p: number) => { if (p <= 0) return; const e = lerp(a, b, p), d = Math.atan2(e[1] - a[1], e[0] - a[0]); g.fill(tube([a, e], 3.4, 3.4), PULSE, 0.9); if (p >= 1) g.fill([b, [b[0] - Math.cos(d - 0.4) * 15, b[1] - Math.sin(d - 0.4) * 15], [b[0] - Math.cos(d) * 11, b[1] - Math.sin(d) * 11], [b[0] - Math.cos(d + 0.4) * 15, b[1] - Math.sin(d + 0.4) * 15]], PULSE, 0.95); };
-// the explainer's one intervention: panel 2, pressed home, in an inset
-export const inset = (g: Gfx, wg: Wing, p: number, seat: number, v: { cx: number; cy: number; zoom: number }) => {
- if (p <= 0) return;
- const c = g.cur, C: P = [v.cx + 330 / v.zoom, v.cy - 330 / v.zoom], R = (90 * Math.min(1, p * 1.4)) / v.zoom;
- g.fill(oval(C[0], C[1], R, R, 22), PAGE, 1); g.fill(tube([...oval(C[0], C[1], R, R, 22), [C[0] + R, C[1]]], 2.6 / v.zoom, 2.6 / v.zoom, false), INK, 0.9);
- if (p < 0.5) return;
- const pn = wg.panels[2], pc = cen(pn), k = R / 150, T = (q: P): P => [C[0] + (q[0] - pc[0]) * k, C[1] + (q[1] - pc[1]) * k];
- c.save(); g.path(c, oval(C[0], C[1], R - 3, R - 3, 22)); c.clip();
- const lift = 1 - seat, up = pn.map(([x, y]) => T([x + 58 * lift, y - 60 * lift]));
- if (lift > 0.02) [0, 2, 4, 6].forEach((j) => { const a = T(pn[j]), b = up[j]; c.save(); c.setLineDash([5, 4]); c.strokeStyle = ACCENT; c.globalAlpha = 0.6; c.lineWidth = 1.3; c.beginPath(); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); c.stroke(); c.setLineDash([]); c.globalAlpha = 1; c.restore(); });
- g.fill(up, "#dfe4e2", 0.95); g.fill(tube([...up, up[0]], 2.2 / v.zoom, 2.2 / v.zoom, false), ACCENT, 0.9);
- c.restore(); g.touch(C[0] - R - 6, C[1] - R - 6, C[0] + R + 6, C[1] + R + 6);
-};
-export const cutLine = (g: Gfx, p: number) => { /* the dashed cut, struck across the body with a scissor mark */
- if (p <= 0) return; const c = g.cur, y = CY - 40, x0 = CX - 210, x1 = CX + 210, x = x0 + (x1 - x0) * p;
- c.save(); c.setLineDash([12, 7]); c.strokeStyle = INK; c.lineWidth = 1.8; c.globalAlpha = 0.8; c.beginPath(); c.moveTo(x0, y); c.lineTo(x, y); c.stroke(); c.setLineDash([]); c.globalAlpha = 1; c.restore(); g.touch(x0 - 6, y - 22, x1 + 6, y + 22);
- const sx = x; g.fill(tube([[sx - 9, y - 7], [sx + 7, y + 5]], 1.8, 1.8), INK, 0.9); g.fill(tube([[sx - 9, y + 7], [sx + 7, y - 5]], 1.8, 1.8), INK, 0.9); g.fill(oval(sx - 11, y - 9, 3.4, 3.4, 9), INK, 0.9); g.fill(oval(sx - 11, y + 9, 3.4, 3.4, 9), INK, 0.9);
-};
-// the accent starts to run wet at its edges: the watercolour arriving
-export const bleed = (g: Gfx, w: Wing[], s: A3) => {
- if (s.bleed <= 0) return;
- const c = g.cur, r = 6 * s.bleed;
- [-1, 1].forEach((side) => { const Q = pivot(side), R = armEnd(side, s.th); c.globalAlpha = 0.3 * s.bleed; g.fill(tube([crankPin(s.th), R], 3.2 + r, 3.2 + r), ACCENT, 0.3 * s.bleed); g.fill(oval(Q[0], Q[1], 10 + r, 10 + r, 12), ACCENT, 0.22 * s.bleed); c.globalAlpha = 1; });
- g.fill(oval(ARBOR[0], ARBOR[1], 27 + r, 27 + r, 18), ACCENT, 0.2 * s.bleed);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3cues.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3cues.ts
deleted file mode 100644
index 04c4925..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3cues.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-// ACT 3, EDITORIAL CUTAWAY: 360 frames, 12 s, 24 beats. UNDERSTOOD. The flight stops, the
-// housing comes off, and the mechanism is run in slow motion, one crank step per tick, while
-// the camera follows the force from the spring to the wing. Then it speeds back up and leaves.
-import { P } from "../core";
-import { EditState } from "./act3plate";
-import { Pose, THORAX, cen } from "./geom";
-import { ARBOR, crankFor, crankPin, flapOf, pivot } from "./linkage";
-import { Train } from "./parts";
-import { View } from "./surface";
-import { END_POSE } from "./act2cues";
-
-export type Ease = "linear" | "out" | "inout" | "outBack";
-export type Cue = { at: number; dur: number; id: string; ease?: Ease };
-export const DURATION = 360, TICK = 5, CRANK0 = 30;
-export const SHOTS: [string, number, number][] = [
- ["freeze", 0, 30], /* the only silence in the film, and the housing comes off */
- ["spring", 30, 120], /* station A: mainspring and going train */
- ["crank", 120, 210], /* station B: round becomes back-and-forth */
- ["wing", 210, 285], /* station C: the wing answers, and panel 2 is pressed home */
- ["whole", 285, 315], /* cause and effect in one frame */
- ["speed", 315, 345], /* it speeds back up and lifts off its own diagram */
- ["leave", 345, 360], /* pushed in on the thorax, the accent bleeding wet: the watercolour arriving */
-];
-export const CUES: Cue[] = [
- { at: 0, dur: 10, id: "cut" }, { at: 10, dur: 20, id: "shell", ease: "outBack" }, { at: 10, dur: 20, id: "faces" }, { at: 15, dur: 30, id: "accent" },
- { at: 45, dur: 10, id: "l1" }, { at: 50, dur: 10, id: "rot" }, { at: 75, dur: 10, id: "l2" }, { at: 90, dur: 10, id: "l3" }, { at: 105, dur: 10, id: "l4" },
- { at: 150, dur: 30, id: "ghostRod" }, { at: 165, dur: 10, id: "l5" }, { at: 180, dur: 10, id: "l6" }, { at: 190, dur: 10, id: "cap" },
- { at: 240, dur: 20, id: "arc" }, { at: 240, dur: 20, id: "ghostSpar" }, { at: 255, dur: 10, id: "l7" }, { at: 265, dur: 10, id: "l8" },
- { at: 270, dur: 15, id: "inset" }, { at: 275, dur: 10, id: "seat", ease: "outBack" },
- { at: 300, dur: 15, id: "shellBack", ease: "out" },
- { at: 330, dur: 15, id: "lift", ease: "out" }, { at: 330, dur: 15, id: "shadow", ease: "out" }, { at: 350, dur: 10, id: "bleed" },
- { at: 60, dur: 60, id: "pulse" }, { at: 120, dur: 90, id: "pulse2" },
-];
-const ARB = ARBOR, PV = pivot(-1), TC = cen(THORAX);
-const CAM: { at: number; cx: number; cy: number; z: number; ease: Ease }[] = [
- { at: 0, cx: 540, cy: 400, z: 1.6, ease: "inout" }, { at: 30, cx: 540, cy: 400, z: 1.68, ease: "inout" }, /* the freeze still creeps: nothing in this film is nailed down */
- { at: 60, cx: ARB[0], cy: ARB[1] + 8, z: 3.2, ease: "inout" }, { at: 120, cx: ARB[0] + 4, cy: ARB[1] + 10, z: 3.4, ease: "inout" },
- { at: 135, cx: (ARB[0] + PV[0]) / 2, cy: (ARB[1] + PV[1]) / 2 + 6, z: 3.2, ease: "inout" }, { at: 210, cx: (ARB[0] + PV[0]) / 2 - 4, cy: (ARB[1] + PV[1]) / 2 + 8, z: 3.32, ease: "inout" },
- { at: 225, cx: PV[0] - 6, cy: PV[1] + 4, z: 3.0, ease: "inout" }, { at: 285, cx: PV[0] - 10, cy: PV[1] + 2, z: 3.1, ease: "inout" },
- { at: 315, cx: 540, cy: 440, z: 1.15, ease: "out" }, { at: 345, cx: 540, cy: 434, z: 1.19, ease: "inout" },
- { at: 360, cx: TC[0], cy: TC[1] - 6, z: 3.2, ease: "inout" }, /* the thorax again, the film's rhyme with Act 1 */
-];
-const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
-const ease = (p: number, e: Ease = "linear") => (e === "inout" ? (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2) : e === "out" ? 1 - (1 - p) ** 3 : e === "outBack" ? 1 + 1.7 * (p - 1) ** 3 + 0.7 * (p - 1) ** 2 : p);
-const byId = new Map(CUES.map((c) => [c.id, c]));
-const cue = (id: string) => { const c = byId.get(id); if (!c) throw new Error(`no cue '${id}'`); return c; };
-export const at = (frame: number, id: string) => { const c = cue(id); return ease(clamp((frame - c.at) / c.dur), c.ease); };
-
-// THE CRANK. Slow motion is one twenty-fourth of a revolution per tick, snapped over two frames
-// like the escapement that drives it. It doubles at 315, again at 325, and runs free from 335.
-const STEP = [14 / 24, 26 / 24, 1, 1, 1], TH0 = crankFor(END_POSE()[2].flap);
-const REV = Math.PI * 2, TH: number[] = (() => {
- const out: number[] = []; let th = TH0;
- const stepped = (f: number, from: number, per: number) => { const t = Math.floor((f - from) / TICK), s = (f - from) % TICK; return t < 1 ? 0 : (t - 1 + STEP[s]) * per; };
- let base = TH0, b315 = 0, b325 = 0, b335 = 0;
- for (let f = 0; f < DURATION; f++) {
- if (f < CRANK0) th = TH0;
- else if (f < 315) th = base + stepped(f, CRANK0, REV / 24);
- else if (f < 325) { if (!b315) b315 = base + stepped(315, CRANK0, REV / 24); th = b315 + stepped(f, 315, REV / 12); }
- else if (f < 335) { if (!b325) b325 = b315 + stepped(325, 315, REV / 12); th = b325 + stepped(f, 325, REV / 6); }
- else { if (!b335) b335 = b325 + stepped(335, 325, REV / 6); th = b335 + ((f - 335) * REV) / 10; } /* life speed: a beat every ten frames */
- out.push(th);
- }
- return out;
-})();
-export const thAt = (f: number) => TH[Math.max(0, Math.min(DURATION - 1, f))];
-const trainAt = (f: number): Train => { const th = thAt(f) - TH0, a = th / REV; return { centre: th, third: -a * REV * (24 / 14) * 0.25, pinion: a * REV * (24 / 8) * 0.25, escape: a * REV * 1.2, fork: 0.085 * (Math.floor(f / TICK) % 2 ? 1 : -1) }; };
-
-const viewAt = (frame: number): View => {
- let i = 0; for (let j = 0; j < CAM.length; j++) if (CAM[j].at <= frame) i = j;
- const a = CAM[i], b = CAM[Math.min(CAM.length - 1, i + 1)];
- if (b.at <= a.at) return { cx: a.cx, cy: a.cy, zoom: a.z };
- const t = ease(clamp((frame - a.at) / (b.at - a.at)), a.ease);
- return { cx: a.cx + (b.cx - a.cx) * t, cy: a.cy + (b.cy - a.cy) * t, zoom: Math.exp(Math.log(a.z) + (Math.log(b.z) - Math.log(a.z)) * t) };
-};
-const poseAt = (frame: number): Pose[] => {
- if (frame < CRANK0) return END_POSE(); /* the freeze holds Act 2's last frame exactly */
- const th = thAt(frame), fp = flapOf(-1, th), fs = flapOf(1, th);
- return [-1, 1, -1, 1].map((side, i) => { const f = side < 0 ? fp : fs; return { flap: f, sweep: -0.2 * (1 - f) }; });
-};
-export const stateAt = (frame: number): EditState => {
- const th = thAt(frame), P0 = crankPin(th), R = pivot(-1);
- const L = (n: string, text: string, at: P, to: P, id: string): { n: string; text: string; at: P; to: P; p: number } => ({ n, text, at, to, p: at2(frame, id) });
- const shell = at(frame, "shell") * (1 - at(frame, "shellBack"));
- const lift = at(frame, "lift"), sh = at(frame, "shadow");
- return {
- view: viewAt(frame), poses: poseAt(frame), th, train: trainAt(frame), mech: at(frame, "accent") > 0 ? 1 : 0,
- art: { th, shell, faces: at(frame, "faces") * (1 - at(frame, "shellBack")), accent: at(frame, "accent"), wings: 1, lift: [0, 0], bleed: at(frame, "bleed"), ghostRod: at(frame, "ghostRod"), arc: at(frame, "arc"), ghostSpar: at(frame, "ghostSpar") },
- cut: at(frame, "cut"),
- labels: [
- L("1", "MAINSPRING", [ARB[0] - 158, ARB[1] - 22], [ARB[0] - 62, ARB[1] - 16], "l1"),
- L("2", "GOING TRAIN", [ARB[0] + 72, ARB[1] - 102], [ARB[0] + 32, ARB[1] - 34], "l2"),
- L("3", "ESCAPEMENT", [ARB[0] + 88, ARB[1] + 74], [ARB[0] + 54, ARB[1] + 8], "l3"),
- L("4", "24 : 8", [ARB[0] + 112, ARB[1] + 10], [ARB[0] + 40, ARB[1] - 6], "l4"),
- L("5", "CRANK", [ARB[0] - 152, ARB[1] + 74], [P0[0], P0[1]], "l5"),
- L("6", "CONN. ROD", [ARB[0] - 44, ARB[1] + 136], [(P0[0] + R[0]) / 2, (P0[1] + R[1]) / 2 + 6], "l6"),
- L("7", "BELL-CRANK", [R[0] - 152, R[1] - 84], [R[0] - 14, R[1] - 8], "l7"),
- L("8", "WING ROOT", [R[0] + 34, R[1] + 100], [R[0] + 14, R[1] + 18], "l8"),
- ],
- caption: ["ROUND BECOMES BACK-AND-FORTH", at(frame, "cap")],
- pulseAt: (at(frame, "pulse") * 4 + at(frame, "pulse2") * 12) % 4, pulseOn: frame >= 60 && frame < 215 ? 1 : 0,
- forceP: at(frame, "rot"), inset: at(frame, "inset"), seat: at(frame, "seat"),
- lift: [0, -30 * lift], shadow: [10 * sh, 14 * sh],
- };
-};
-const at2 = (frame: number, id: string) => at(frame, id);
-export const gridProblems = (): string[] => {
- const p: string[] = [];
- CUES.forEach((c) => { if (c.at % 5) p.push(`cue '${c.id}' starts on frame ${c.at}, not a multiple of 5`); if ((c.at + c.dur) % 5) p.push(`cue '${c.id}' ends on frame ${c.at + c.dur}, not a multiple of 5`); if (c.at + c.dur > DURATION) p.push(`cue '${c.id}' ends after the act`); });
- CAM.forEach((k) => { if (k.at % 5) p.push(`camera key at frame ${k.at} is not a multiple of 5`); });
- SHOTS.forEach(([id, a, b]) => { if (a % 15 || b % 15) p.push(`shot '${id}' cuts off the beat grid (${a}..${b})`); });
- return p;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3plate.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3plate.ts
deleted file mode 100644
index 900c858..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act3plate.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-// THE PAGE. Editorial cutaway: the art on one surface, the annotation on another, so labels can
-// be written while the mechanism runs without redrawing the mechanism, and the camera can push
-// in on either without a bitmap ever being scaled up.
-import { Ctx, Env, Gfx, Medium, P, PENCIL } from "../core";
-import { FW, FW_H, FW_T, HW, HW_H, HW_T, Pose, Wing, wingGeom } from "./geom";
-import { A3, Label, bleed, caption, creature, cutLine, force, inset, labels, mechanism, page, pulse } from "./act3art";
-import { Train } from "./parts";
-import { View, blit, kk, part } from "./surface";
-
-export type EditState = {
- view: View; poses: Pose[]; th: number; train: Train; art: A3;
- cut: number; labels: Label[]; caption: [string, number]; pulseAt: number; pulseOn: number;
- forceP: number; inset: number; seat: number; lift: P; shadow: [number, number]; mech: number;
-};
-const BRUSH: Medium = { nib: 1, taper: 0.5, pressure: 0.5, retrace: false, wobble: 0.35, rough: 0.5 }; // a brush pen: it swells, it does not scratch
-const nibFor = (z: number): Medium => (z === 1 ? BRUSH : { ...BRUSH, nib: (BRUSH.nib * Math.pow(z, 0.35)) / z });
-
-export const drawEdit = (ctx: Ctx, env: Env, s: EditState) => {
- const W = env.W, H = env.H, v = s.view, vk = kk(v.cx, v.cy, v.zoom), med = nibFor(v.zoom), a = s.art;
- const w: Wing[] = [wingGeom(-1, HW, HW_H, HW_T, 2000, s.poses[0]), wingGeom(1, HW, HW_H, HW_T, 2600, s.poses[1]), wingGeom(-1, FW, FW_H, FW_T, 1000, s.poses[2]), wingGeom(1, FW, FW_H, FW_T, 1600, s.poses[3])];
- const pk = kk(...s.poses.flatMap((p) => [p.flap, p.sweep]));
- const pt = (name: string, key: string, fn: (g: Gfx) => void) => part(env, med, name, key + "|" + vk, 0, fn, v);
-
- const sheet = pt("page3", "page3", (g) => page(g, W, H));
- const art = pt("edit", kk(pk, a.th, a.shell, a.faces, a.accent, a.wings, a.bleed, a.ghostRod, a.arc, a.ghostSpar, s.mech, s.train.centre), (g) => { creature(g, w, a); mechanism(g, a, s.train, s.mech); bleed(g, w, a); });
- const note = pt("notes3", kk(s.cut, s.caption[1], s.inset, s.seat, s.forceP, s.pulseAt, s.pulseOn, a.th, pk, ...s.labels.map((l) => l.p), ...s.labels.flatMap((l) => l.to)), (g) => { /* two leaders point AT the crank, so the crank angle is part of what this surface is */
- cutLine(g, s.cut); labels(g, s.labels); if (s.caption[1] > 0) caption(g, s.caption[0], v, s.caption[1]);
- if (s.forceP > 0) { const from: P = [540 + 6, 380], to: P = [540 + 96, 330]; force(g, from, to, s.forceP); }
- pulse(g, { at: s.pulseAt, on: s.pulseOn }); inset(g, w[3], s.inset, s.seat, v);
- });
-
- blit(ctx, sheet);
- const sc = env.scale, L = s.lift;
- if (s.shadow[0] || s.shadow[1]) blit(ctx, art, Math.round((L[0] + s.shadow[0]) * sc), Math.round((L[1] + s.shadow[1]) * sc), 0.16); /* it lifts off the page, and the page keeps its diagram */
- blit(ctx, art, Math.round(L[0] * sc), Math.round(L[1] * sc));
- blit(ctx, note); /* every label and leader stays exactly where it was put, pointing at paper */
- const g = new Gfx(ctx, env, 0, PENCIL); g.paper("paper", 0.12);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4art.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4art.ts
deleted file mode 100644
index a39d2da..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4art.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// ACT 3, WATERCOLOUR. The third construction: nothing is ruled and nothing is printed. A soft
-// pencil underdrawing goes down FIRST and stays visible under the paint, then washes are laid
-// wet-in-wet and allowed to misbehave: they bloom out from where the brush touched, they pool
-// darker at the wet edge, they granulate as they dry, and they never stay inside the pencil.
-// The medium is the motion. Water spreads on the beat, pigment settles after it.
-import { Ctx, Env, GRAPHITE, Gfx, P, TINT, jitter, oval, rng } from "../core";
-import { CX, CY, HEAD, K, KC, THORAX, Wing, cen, lerp } from "./geom";
-
-export const PAPER3 = "#fbf7ee";
-const ROSE = TINT.rose, BLUSH = TINT.blush, BUTTER = TINT.butter, SKY = TINT.sky, DENIM = TINT.denim, PEACH = TINT.peach;
-
-// a wash does not appear, it SPREADS: every point of the shape reaches its edge at its own
-// moment, out from the point the brush was put down
-const spread = (pts: P[], from: P, t: number, seed: number): P[] => { const r = rng(seed); return pts.map((p) => { const lag = 0.55 + r() * 0.45, u = Math.max(0, Math.min(1, (t * 1.5 - (1 - lag)) / lag)); return lerp(from, p, u * u * (3 - 2 * u)); }); };
-const bodyShape = (): P[] => { const segs = 7, y0 = 70, y1 = 250, hw = (t: number) => 23 * (1 - t) ** 0.8 + 6.5, L: P[] = [], R: P[] = [];
- for (let i = 0; i <= 12; i++) { const t = i / 12, y = y0 + (y1 - y0) * t; L.push([CX - hw(t) * K, CY + y * K]); R.push([CX + hw(t) * K, CY + y * K]); }
- return [...THORAX.slice(0, 7), ...R, ...L.reverse(), ...THORAX.slice(7)]; };
-
-// ---------------------------------------------------------------- the pencil under the paint
-export const pencil = (g: Gfx, w: Wing[], p: number) => {
- if (p <= 0) return;
- const st = (i: number, n: number, dur = 0.45) => (p >= 1 ? 1 : Math.max(0, Math.min(1, (p - (i * (1 - dur)) / Math.max(1, n - 1)) / dur)));
- g.group("ink", () => {
- w.forEach((wg, i) => {
- g.pen(wg.out, { w: 2.2, color: GRAPHITE, seed: 1200 + i, closed: true, wobble: 1.4, boil: 0, opacity: 0.72, progress: st(i, 9) });
- [0, 2, 4].forEach((j, r) => { if (j >= wg.ends.length) return; const line = Array.from({ length: 6 }, (_, q) => wg.spar(j, 0.05 + (q / 5) * 0.88)); g.pen(line, { w: 1.5, color: GRAPHITE, seed: 1220 + i * 4 + r, wobble: 1.1, boil: 0, opacity: 0.55, progress: st(4 + i, 9) }); });
- });
- g.pen(bodyShape(), { w: 2.4, color: GRAPHITE, seed: 1240, closed: true, wobble: 1.2, boil: 0, opacity: 0.75, progress: st(8, 9) });
- g.pen(HEAD, { w: 2, color: GRAPHITE, seed: 1241, closed: true, wobble: 1, boil: 0, opacity: 0.75, progress: st(8, 9) });
- const o = cen(THORAX); ([[o[0] + 2, o[1] + 8, 26], [o[0] - 18, o[1] - 32, 15], [o[0] + 22, o[1] - 24, 11]] as number[][]).forEach(([x, y, r], i) => g.pen(jitter(oval(x, y, r, r, 12), 1.4, 1260 + i), { w: 1.4, color: GRAPHITE, seed: 1260 + i, closed: true, wobble: 0.8, boil: 0, opacity: 0.8, progress: st(8, 9) })); /* it is still a clockwork butterfly: the train is drawn, then painted */
- g.pen(jitter(oval(KC[0], KC[1], 7, 7, 10), 0.8, 1270), { w: 1.6, color: GRAPHITE, seed: 1270, closed: true, wobble: 0.7, boil: 0, opacity: 0.6, progress: st(8, 9) });
- [-1, 1].forEach((sd) => g.pen(jitter(oval(KC[0] + sd * 21, KC[1] + 3, 16, 21, 11), 1.1, 1272 + sd), { w: 1.5, color: GRAPHITE, seed: 1272 + sd, closed: true, wobble: 0.9, boil: 0, opacity: 0.55, progress: st(8, 9) }));
- g.pen([[KC[0], KC[1] - 36], [KC[0], KC[1] - 4]], { w: 1.6, color: GRAPHITE, seed: 1274, wobble: 0.6, boil: 0, opacity: 0.6, progress: st(8, 9) });
- [-1, 1].forEach((sd) => { const a0: P = [CX + sd * 8 * K, CY - 127 * K], a1: P = [CX + sd * 56 * K, CY - 206 * K], a2: P = [CX + sd * 124 * K, CY - 246 * K]; g.pen(Array.from({ length: 9 }, (_, i) => { const t = i / 8; return lerp(lerp(a0, a1, t), lerp(a1, a2, t), t); }), { w: 1.6, color: GRAPHITE, seed: 1250 + sd, wobble: 0.9, boil: 0, opacity: 0.65, progress: st(8, 9) }); });
- }, { alpha: 0.9 });
-};
-
-// ---------------------------------------------------------------- the washes
-export const washes = (g: Gfx, w: Wing[], s: { wet: number; settle: number; slip: P }) => {
- if (s.wet <= 0) return;
- const st = (i: number, n: number, dur = 0.5) => Math.max(0, Math.min(1, (s.wet - (i * (1 - dur)) / Math.max(1, n - 1)) / dur));
- const off = (pts: P[]): P[] => pts.map(([x, y]) => [x + s.slip[0], y + s.slip[1]] as P); /* the paint slides off its own drawing */
- const shrunk = (pts: P[], k: number): P[] => { const c = cen(pts); return pts.map((q) => lerp(q, c, k)); };
- // pigment does not dry flat: it pools where the water sat longest and lifts where it ran out
- const pools = (pts: P[], col: string, seed: number, n: number, a: number) => {
- const c0 = cen(pts), r = rng(seed);
- for (let i = 0; i < n; i++) { const k = 0.3 + r() * 0.45, dx = (r() - 0.5) * 46, dy = (r() - 0.5) * 40; g.wash(shrunk(pts, k).map(([x, y]) => [x + dx, y + dy] as P), col, { alpha: a * (0.55 + r() * 0.6), seed: seed + i * 3, dx: (r() - 0.5) * 8, dy: (r() - 0.5) * 8, shrink: 0.86 + r() * 0.2, rim: r() > 0.45 }); }
- };
- g.group("paint", () => {
- const c = g.cur;
- w.forEach((wg, i) => {
- const t = st(i, 6), root = wg.h, tip = wg.ends[Math.max(0, wg.ends.length - 3)];
- if (t <= 0) return;
- const shape = off(wg.out.map((p) => lerp(p, cen(wg.out), -0.02))), pig = i < 2 ? BLUSH : ROSE;
- c.globalCompositeOperation = "source-over";
- g.wash(spread(shape, root, t, 1300 + i), pig, { alpha: 0.3, seed: 1300 + i, dx: 3, dy: 2, shrink: 0.97, rim: t > 0.55 }); /* the first pass is thin: watercolour is built, never filled */
- if (t > 0.35) { c.globalCompositeOperation = "multiply";
- const q = Math.min(1, (t - 0.35) / 0.4);
- pools(spread(shape, root, t, 1300 + i), pig, 1310 + i * 7, 4, 0.22 * q); /* uneven drying, the whole charm of the medium */
- g.wash(spread(shrunk(shape, 0.1), lerp(root, tip, 0.3), q, 1316 + i), pig, { alpha: 0.2 * q, seed: 1316 + i, dx: -3, dy: 4, shrink: 0.9, rim: true });
- }
- if (t > 0.45) { c.globalCompositeOperation = "multiply"; /* a second pigment dropped into the first while it is still wet */
- const second = shrunk(off(wg.out.map((p) => lerp(p, wg.h, 0.22))), 0.12); /* the drop runs toward the root, it does not fill a panel */
- g.wash(spread(second, lerp(root, tip, 0.45), (t - 0.45) / 0.55, 1320 + i), i < 2 ? BUTTER : PEACH, { alpha: 0.26, seed: 1320 + i, dx: -4, dy: 3, shrink: 0.88 });
- pools(second, i < 2 ? BUTTER : PEACH, 1330 + i * 5, 2, 0.14);
- }
- if (t > 0.7 && s.settle > 0.2) { c.globalCompositeOperation = "multiply"; /* pigment walks to the wet edge and dries as a dark rim */
- g.wash(spread(off(wg.out.map((p) => lerp(p, cen(wg.out), 0.04))), lerp(root, tip, 0.6), 1, 1340 + i), SKY, { alpha: 0.1 * s.settle, seed: 1340 + i, dx: 2, dy: -3, shrink: 0.995, rim: true });
- g.wash(spread(off(wg.out.map((p) => lerp(p, cen(wg.out), 0.02))), lerp(root, tip, 0.8), 1, 1350 + i), pig, { alpha: 0.16 * s.settle, seed: 1350 + i, dx: 1, dy: 5, shrink: 1.0, rim: true });
- const edge = off(wg.out), inner = shrunk(edge, 0.055); g.mark(edge, 4); c.globalAlpha = 0.3 * s.settle; c.fillStyle = pig; c.beginPath(); edge.forEach(([x, y], q) => (q ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); [...inner].reverse().forEach(([x, y], q) => (q ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill("evenodd"); c.globalAlpha = 1; /* the hard wet edge: pigment stranded at the rim as the water left */
- }
- c.globalCompositeOperation = "source-over";
- });
- }, { alpha: 0.95 });
- const b = st(5, 6);
- if (b > 0) g.group("paint", () => {
- const c = g.cur, body = off(bodyShape());
- g.wash(spread(body, [CX, CY], b, 1360), DENIM, { alpha: 0.34, seed: 1360, dx: 2, dy: 3, shrink: 0.96 });
- c.globalCompositeOperation = "multiply";
- pools(body, DENIM, 1364, 3, 0.2);
- g.wash(spread(shrunk(body, 0.18), [CX + 9, CY + 30], b, 1366), DENIM, { alpha: 0.24, seed: 1366, dx: 5, dy: 2, shrink: 0.9, rim: true }); /* the shadow side of the body, wet into wet */
- g.wash(spread(off(HEAD.map((p) => lerp(p, cen(HEAD), -0.05))), [CX, CY - 110 * K], b, 1362), DENIM, { alpha: 0.4, seed: 1362, dx: -2, dy: 2, shrink: 0.94 });
- { const kb = [-1, 1].map((sd) => off(jitter(oval(KC[0] + sd * 21, KC[1] + 3, 16, 21, 11), 1.1, 1380 + sd))); kb.forEach((sh, i) => g.wash(spread(sh, KC, b, 1380 + i), DENIM, { alpha: 0.3, seed: 1380 + i, dx: 2, dy: 2, shrink: 0.9, rim: true })); } /* the key, painted where it lies */
- if (s.settle > 0.3) { const o = cen(THORAX), wheels: number[][] = [[o[0] + 2, o[1] + 8, 26], [o[0] - 18, o[1] - 32, 15], [o[0] + 22, o[1] - 24, 11]];
- c.globalCompositeOperation = "destination-out"; /* lift the pigment off the wheels with a damp brush, the way you would */
- wheels.forEach(([x, y, r], i) => g.wash(off(jitter(oval(x, y, r * 0.96, r * 0.96, 12), 1.4, 1366 + i)), "#000000", { alpha: 0.5 * s.settle, seed: 1366 + i, dx: 0, dy: 0, shrink: 0.98, rim: false }));
- c.globalCompositeOperation = "multiply";
- wheels.forEach(([x, y, r], i) => g.wash(off(jitter(oval(x, y, r, r, 12), 1.6, 1370 + i)), SKY, { alpha: 0.4 * s.settle, seed: 1370 + i, dx: 1, dy: 2, shrink: 0.92, rim: true })); } /* then drop a cooler pigment into the hollow: the train, seen through the body */
- c.globalCompositeOperation = "source-over";
- }, { alpha: 0.95 });
-};
-
-// a drop of clean water dropped into a drying wash pushes the pigment out in a ring
-export const backrun = (g: Gfx, at: P, r: number, t: number, seed: number) => {
- if (t <= 0) return;
- const e = t * t * (3 - 2 * t), R = r * (0.25 + 0.75 * e), c = g.cur;
- c.globalCompositeOperation = "destination-out"; /* straight onto the paint: a group of its own would have nothing to lift */
- g.wash(jitter(oval(at[0], at[1], R, R * 0.86, 18), R * 0.2, seed), "#000000", { alpha: 0.6 * (1 - e * 0.2), seed, dx: 0, dy: 0, shrink: 1, rim: false });
- g.wash(jitter(oval(at[0] - R * 0.34, at[1] + R * 0.26, R * 0.44, R * 0.36, 14), R * 0.12, seed + 3), "#000000", { alpha: 0.5, seed: seed + 3, dx: 0, dy: 0, shrink: 1, rim: false });
- c.globalCompositeOperation = "multiply";
- g.wash(jitter(oval(at[0], at[1], R * 1.07, R * 0.94, 18), R * 0.24, seed + 7), TINT.rose, { alpha: 0.3 * e, seed: seed + 7, dx: 0, dy: 0, shrink: 1.02, rim: true }); /* and piles the pigment into a hard ring at the edge of the bloom */
- c.globalCompositeOperation = "source-over";
-};
-
-export const sheet3 = (g: Gfx, W: number, H: number) => { const c = g.main, e = g.env; c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.fillStyle = PAPER3; c.fillRect(0, 0, W, H); g.paper("coldpress", 0.17); };
-export const dry = (g: Gfx) => { g.paper("washGran", 0.05); g.paper("coldpress", 0.11); g.vignette("rgba(120,96,64,0.055)"); }; /* the sheet keeps its light: three multiplies turned white paper into cardboard */
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4cues.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4cues.ts
deleted file mode 100644
index c34bd98..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4cues.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-// ACT 3, WATERCOLOUR: 360 frames, 12 s, 24 beats. Pencil, water, pigment, and a drop of clean
-// water in the middle of it. The motion is what the water does.
-import { P } from "../core";
-import { WaterState } from "./act4plate";
-
-export type Ease = "linear" | "out" | "flick";
-export type Cue = { at: number; dur: number; id: string; ease?: Ease; amp?: number };
-export const DURATION = 360;
-export const SHOTS: [string, number, number][] = [
- ["paper", 0, 45], /* cold-press stock, nothing on it yet */
- ["pencil", 45, 135], /* the underdrawing, loose and fast, and it stays visible for ever */
- ["wet", 135, 225], /* the washes go down wet-in-wet and spread out from the brush */
- ["settle", 225, 270], /* a drop of clean water blooms a backrun, pigment granulates and dries */
- ["alive", 270, 345], /* five flaps, and the paint lags behind the drawing */
- ["dry", 345, 360], /* the finished painting, held */
-];
-export const CUES: Cue[] = [
- { at: 45, dur: 80, id: "pencil", ease: "linear" },
- { at: 135, dur: 85, id: "wet", ease: "linear" },
- { at: 195, dur: 75, id: "settle", ease: "out" },
- { at: 225, dur: 40, id: "bloom", ease: "out" },
- { at: 270, dur: 10, id: "twitch", ease: "flick", amp: 0.14 },
- { at: 285, dur: 15, id: "flap1", ease: "flick", amp: 0.55 }, { at: 300, dur: 10, id: "flap2", ease: "flick", amp: 0.62 },
- { at: 310, dur: 10, id: "flap3", ease: "flick", amp: 0.5 }, { at: 320, dur: 10, id: "flap4", ease: "flick", amp: 0.32 }, { at: 330, dur: 10, id: "flap5", ease: "flick", amp: 0.16 },
- { at: 285, dur: 30, id: "slip.out", ease: "out" }, { at: 325, dur: 20, id: "slip.in", ease: "out" },
-];
-const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
-const ease = (p: number, e: Ease = "linear") => (e === "out" ? 1 - (1 - p) ** 3 : e === "flick" ? (p < 0.35 ? Math.sin((p / 0.35) * Math.PI / 2) : Math.cos(((p - 0.35) / 0.65) * Math.PI / 2)) : p);
-const byId = new Map(CUES.map((c) => [c.id, c]));
-const cue = (id: string) => { const c = byId.get(id); if (!c) throw new Error(`no cue '${id}'`); return c; };
-export const at = (frame: number, id: string) => { const c = cue(id); return ease(clamp((frame - c.at) / c.dur), c.ease); };
-
-export const stateAt = (frame: number): WaterState => {
- const flap = ["twitch", "flap1", "flap2", "flap3", "flap4", "flap5"].reduce((f, id) => f - (cue(id).amp ?? 0) * at(frame, id), 1);
- const slip = at(frame, "slip.out") * (1 - at(frame, "slip.in"));
- return { pose: { flap, sweep: -0.2 * (1 - flap) }, pencil: at(frame, "pencil"), wet: at(frame, "wet"), settle: at(frame, "settle"), slip: [slip * 9, slip * 6], bloom: at(frame, "bloom") };
-};
-export const gridProblems = (): string[] => {
- const p: string[] = [];
- CUES.forEach((c) => { if (c.at % 5) p.push(`cue '${c.id}' starts on frame ${c.at}, not a multiple of 5`); if ((c.at + c.dur) % 5) p.push(`cue '${c.id}' ends on frame ${c.at + c.dur}, not a multiple of 5`); if (c.at + c.dur > DURATION) p.push(`cue '${c.id}' ends after the act`); });
- SHOTS.forEach(([id, a, b]) => { if (a % 15 || b % 15) p.push(`shot '${id}' cuts off the beat grid (${a}..${b})`); });
- return p;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4plate.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4plate.ts
deleted file mode 100644
index 3a2e743..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/act4plate.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// THE SHEET OF PAPER. Pencil first, washes over it, blooms and settling on top, and the paper's
-// own tooth over everything. The washes are their own surface, so the paint can slide off the
-// drawing while it flies without either being redrawn.
-import { Ctx, Env, Gfx, P, PENCIL } from "../core";
-import { FW, FW_H, FW_T, HW, HW_H, HW_T, Pose, REST, Wing, wingGeom } from "./geom";
-import { backrun, dry, pencil, sheet3, washes } from "./act4art";
-import { blit, kk, part } from "./surface";
-
-export type WaterState = { pose: Pose; pencil: number; wet: number; settle: number; slip: P; bloom: number };
-export const WATER_REST: WaterState = { pose: REST, pencil: 1, wet: 1, settle: 1, slip: [0, 0], bloom: 1 };
-
-export const drawWater = (ctx: Ctx, env: Env, s: WaterState) => {
- const W = env.W, H = env.H;
- const wings = (pose: Pose): Wing[] => [wingGeom(-1, HW, HW_H, HW_T, 2000, pose), wingGeom(1, HW, HW_H, HW_T, 2600, pose), wingGeom(-1, FW, FW_H, FW_T, 1000, pose), wingGeom(1, FW, FW_H, FW_T, 1600, pose)];
- const w = wings(s.pose), pk = kk(s.pose.flap, s.pose.sweep);
- const paper = part(env, PENCIL, "sheet3", "sheet3", 0, (g) => sheet3(g, W, H));
- const draw = s.pencil > 0 ? part(env, PENCIL, "pencil", kk(pk, s.pencil), 0, (g) => pencil(g, w, s.pencil)) : null;
- const paint = s.wet > 0 ? part(env, PENCIL, "wash", kk(pk, s.wet, s.settle, s.slip[0], s.slip[1], s.bloom), 0, (g) => {
- washes(g, w, { wet: s.wet, settle: s.settle, slip: s.slip });
- if (s.bloom > 0) { const b = w[2], at: P = [b.spar(2, 0.55)[0] + s.slip[0], b.spar(2, 0.55)[1] + s.slip[1]]; backrun(g, at, 78, s.bloom, 1400); } /* one drop of clean water, into the port forewing */
- }) : null;
-
- blit(ctx, paper); blit(ctx, paint); blit(ctx, draw, 0, 0, 0.95); /* graphite reads THROUGH the paint, so it goes on top at low opacity */
- dry(new Gfx(ctx, env, 0, PENCIL));
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/anatomy.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/anatomy.ts
deleted file mode 100644
index 410484c..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/anatomy.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-// LEPIDOPTERAN ANATOMY, built on the plate's own control points. Spec 5.7:
-// the stained-glass direction is withdrawn. A spar is no longer a ruled line between two panels,
-// it is a VEIN, and the panel between two veins is a wing CELL covered in scales. The spars keep
-// their positions, so Act 1's silhouette and rhythm carry over exactly; what changes is that the
-// structure hanging off them is now true.
-//
-// REFERENCE ACTUALLY OPENED before a point was moved (5.7 asks which; these are the four):
-// 1. "Veinspaces1" (butterfly-ID venation plate, forewing above, hindwing below, CELL labelled,
-// veins v1a-v12 and spaces s1a-s12). It settles the topology this file implements: a closed
-// DISCAL CELL running from the base to about half the wing; veins leaving the END of that
-// cell and fanning to the outer margin; further veins branching off the cell's LOWER edge at
-// intervals rather than from its end; above the cell a costal trunk that forks two or three
-// times toward the apex; and one unbranched anal vein along the inner margin. Around twelve
-// veins reach the forewing margin and around eight the hindwing.
-// 2. bobs-bugs "Wing venation" (generic insect wing, trunks coloured by system). It settles the
-// two rules that matter more than the count: veins BRANCH outward and NEVER cross, and every
-// vein is thickest at the base and thins toward the margin.
-// 3. Alamy monarch on a crown flower, lateral, wings closed. It settles what the underside does
-// graphically: the venation is the dominant mark, the margin carries a dark band with a
-// DOUBLE row of pale spots, and a fine alternating fringe sits outside that.
-// 4. Shutterstock macro of a butterfly's head at a flower. It settles the head: the compound eye
-// is a large dark dome with one soft highlight, the head and thorax are densely furred, the
-// antenna is thick and finely ringed at its base, the PALPS are two furry forward projections
-// below the eyes, and the proboscis leaves from BELOW the palps as a fine dark tube.
-import { P, jitter, rng } from "../../core";
-import { Wing, cen, lerp } from "../geom";
-
-export type Vein = { pts: P[]; w: number; main: boolean }; // w is relative weight at the base; every vein thins to a point at the margin
-export type Anatomy = { out: P[]; veins: Vein[]; cell: P[]; ends: P[]; span: number };
-
-const push = (p: P, c: P, k: number): P => [p[0] + (p[0] - c[0]) * k, p[1] + (p[1] - c[1]) * k];
-const bow = (a: P, b: P, k: number): P[] => { const nx = -(b[1] - a[1]), ny = b[0] - a[0], l = Math.hypot(nx, ny) || 1; return [a, [a[0] + (b[0] - a[0]) * 0.34 + (nx / l) * k * 0.7, a[1] + (b[1] - a[1]) * 0.34 + (ny / l) * k * 0.7], [a[0] + (b[0] - a[0]) * 0.7 + (nx / l) * k, a[1] + (b[1] - a[1]) * 0.7 + (ny / l) * k], b]; };
-
-// The margin between two vein ends is gently SCALLOPED: the veins hold the margin out and the
-// membrane between them falls away. A ruled or a smoothly swept margin is the tell.
-export const scallop = (out: P[], ends: P[], c: P, depth: number): P[] => {
- const near = (q: P) => ends.reduce((best, e) => (Math.hypot(e[0] - q[0], e[1] - q[1]) < Math.hypot(best[0] - q[0], best[1] - q[1]) ? e : best), ends[0]);
- return out.map((q) => { const e = near(q), d = Math.hypot(e[0] - q[0], e[1] - q[1]), sp = Math.hypot(q[0] - c[0], q[1] - c[1]); return d < sp * 0.34 ? push(q, c, -depth * Math.sin((d / (sp * 0.34)) * Math.PI) ) : q; });
-};
-
-// One wing's venation. `fore` picks the forewing plan (a long cell, a forked costal trunk, twelve
-// veins) from the hindwing's (a short cell near the base, eight veins, no apical fork).
-export const venation = (wg: Wing, fore: boolean, seed: number): Anatomy => {
- const r = rng(seed), E = wg.ends, n = E.length, h = wg.h, c = cen(wg.out);
- const span = Math.max(...wg.out.map((q) => Math.hypot(q[0] - h[0], q[1] - h[1])));
- const veins: Vein[] = [];
- // a margin target: along the chord between two tips, pushed out onto the margin itself
- const M = (i: number, f: number): P => push(lerp(E[Math.min(i, n - 1)], E[Math.min(i + 1, n - 1)], f), c, 0.03);
-
- // ---- the CELL. Closed, from the base to about half the wing, bounded above by the subcostal
- // trunk and below by the cubital, and shut at its outer end by the DISCOCELLULAR vein.
- const up = fore ? 1 : 1, lo = fore ? 4 : Math.max(2, n - 3), tU = fore ? 0.5 : 0.42, tL = fore ? 0.43 : 0.36;
- const cellU = [0, 0.25, 0.5, 0.75, 1].map((t) => wg.spar(up, t * tU)), cellL = [0, 0.25, 0.5, 0.75, 1].map((t) => wg.spar(lo, t * tL));
- const C1 = cellU[4], C2 = cellL[4];
- const disco = bow(C1, C2, span * 0.012); /* the discocellular is a little concave: it was pulled in when the wing dried */
- const cell = [...cellU, ...disco.slice(1, 3), ...cellL.slice().reverse()];
- veins.push({ pts: cellU, w: 1, main: true }, { pts: cellL, w: 0.95, main: true }, { pts: disco, w: 0.5, main: false });
-
- // ---- above the cell: the costal trunk to the leading margin, forking toward the apex
- const costa = [0, 0.3, 0.62, 1].map((t) => wg.spar(0, 0.04 + t * 0.94));
- veins.push({ pts: costa, w: 1, main: true });
- if (fore) [0.5, 0.72].forEach((t, k) => { const from = wg.spar(0, t), to = lerp(wg.spar(0, 1), wg.spar(1, 1), 0.3 + k * 0.45); veins.push({ pts: bow(from, to, span * 0.008 * (r() - 0.5)), w: 0.58 - k * 0.1, main: false }); }); /* radial branches: they leave one trunk in sequence, toward the apex, and never cross */ /* radial branches: they leave one trunk in sequence and never cross */
-
- // ---- the fan that fills the outer half of the wing. These veins ARE the plate's spars, which
- // is what "they keep their positions" has to mean: a vein that leaves the cell and then strikes
- // off on a bearing of its own is a ruled line with a new colour. Each one starts where the cell
- // ends and runs out to the margin the spar already reaches.
- for (let k = 1; k < n - 1; k++) {
- if (k === up || k === lo) continue;
- const inCell = k > up && k < lo, t0 = inCell ? (tU + tL) / 2 : 0.05;
- veins.push({ pts: [0, 0.26, 0.56, 0.8, 1].map((t) => wg.spar(k, t0 + t * (0.99 - t0))), w: 0.9 - Math.abs(k - (up + lo) / 2) * 0.06, main: true });
- }
- // ---- and off the cell's LOWER edge, at intervals: the one piece of structure the blueprint
- // never had, and the detail that separates a real plan from a fan of spokes, because these
- // start part way along a trunk instead of at its end
- [0.58, 0.88].forEach((t, k) => { const from = wg.spar(lo, t * tL), to = M(n - 3 + k, 0.35 + r() * 0.3); veins.push({ pts: bow(from, to, span * 0.012), w: 0.6 - k * 0.08, main: false }); });
- // ---- the anal vein: unbranched, along the inner margin
- veins.push({ pts: [0, 0.4, 0.75, 1].map((t) => wg.spar(n - 1, 0.04 + t * 0.86)), w: 0.66, main: true });
- if (!fore) veins.push({ pts: bow(wg.spar(n - 1, 0.3), M(n - 2, 0.7), span * 0.01), w: 0.5, main: false }); /* the hindwing carries a second anal vein */
-
- const ends = veins.filter((v) => v.main).map((v) => v.pts[v.pts.length - 1]);
- return { out: scallop(jitter(wg.out, span * 0.004, seed + 3), ends, c, 0.018), veins, cell, ends, span };
-};
-
-// The membrane between two adjacent veins: a wing CELL. These are what carry the scales, the
-// ground colour and the markings, and they are bounded by real veins rather than ruled apart.
-export const cells = (a: Anatomy): P[][] => {
- const main = a.veins.filter((v) => v.main), c = cen(a.out), out: P[][] = [];
- const byAngle = main.slice().sort((p, q) => Math.atan2(p.pts[p.pts.length - 1][1] - c[1], p.pts[p.pts.length - 1][0] - c[0]) - Math.atan2(q.pts[q.pts.length - 1][1] - c[1], q.pts[q.pts.length - 1][0] - c[0]));
- for (let i = 0; i < byAngle.length - 1; i++) {
- const A = byAngle[i].pts, B = byAngle[i + 1].pts;
- const mid = lerp(A[A.length - 1], B[B.length - 1], 0.5);
- out.push([...A, push(mid, c, 0.015), ...B.slice().reverse()]);
- }
- return out;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/cues.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/cues.ts
deleted file mode 100644
index 115edf6..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/cues.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// MOVEMENT 2, "ALIVE": every frame number in the movement, and nothing else. Spec section 1 is
-// binding: one beat = 15 frames, one bar = 60, events on multiples of 5, landings and take-offs
-// on BEATS. gridProblems() runs at module load in every host that draws this movement, so a
-// number that drifts off the grid is a build error and never something a reviewer catches by eye.
-//
-// FABLE, one deviation to veto in a line: the spec asks for this table in `butterfly/act2cues.ts`.
-// That filename is taken by the CUT riso act, which is still on disk as the record you asked to
-// keep and still compiles; moving it to legacy/ breaks `act2.ts` and `act3.ts` with it. The
-// movement's table lives here instead. Nothing imports the riso tables from this movement.
-
-export const LOCAL = 870; // frames in movement 2. Retimed from 1260 on review: the macro and the
-// ending are untouched, stage F loses its poppy touch-down and stage R loses the fourth landing,
-// which is exactly the trim spec O6 nominates. The whole film is now 1410 frames, 47.0 s.
-export const FILM_OFFSET = 540; // film frame = local + 540 (Act 1 is frames 0-539)
-export const BEAT = 15, BAR = 60;
-export const filmFrame = (local: number) => local + FILM_OFFSET;
-
-// ---------------------------------------------------------------- 5.1 the camera
-// S is screen px per sheet unit. Monotone, never increasing, never at rest after frame 0.
-export const S_KEYS: [number, number][] = [
- [0, 4.0], [120, 3.4], [240, 1.6], [345, 0.55],
- [420, 0.545], [450, 0.52], [525, 0.515], [555, 0.49], [585, 0.485],
- [660, 0.24], [720, 0.15], [780, 0.118], [870, 0.115],
-];
-// The three STEPS: a take-off releases each one and it takes 30 frames. The big moves start on
-// the take-offs at 240, 720 and 855.
-export const STEPS: [number, number][] = [[420, 450], [525, 555]];
-
-// The camera spine: where the lens is pointed, in sheet units, keyed on bars. Stages M to R are
-// authored here; once the flight paths land these become the TARGET of a critically damped
-// follow (about 25 frames of lag, spec 4) rather than the centre itself.
-export const M0: [number, number] = [665, 372]; // beat 1's view: starboard forewing root, panel 2 right of centre, thorax window and its wheels in the left third
-
-// ---------------------------------------------------------------- 5.2 the water
-// The drop lands on the LIFTED panel 2 and runs down its projection lines onto the wing; from
-// there it follows the spars by capillary, one spar per 5 frames, and the draftsman's port-to-
-// starboard order is abandoned because water does not care about the draftsman.
-// Wing order everywhere in this movement: 0 port hind, 1 starboard hind, 2 port fore, 3 starboard fore.
-export const DROP = 5; // a clear bead lands on panel 2
-export const SPAR_WET: number[][] = [
- [85, 90, 95, 100, 105, 110, 115], // 0 port hind
- [40, 45, 50, 55, 60, 65, 70], // 1 starboard hind
- [75, 80, 85, 90, 95, 100], // 2 port fore
- [40, 25, 15, 10, 30, 50], // 3 starboard fore: the drop arrives at spar 3 and works outward and back, and the trailing spar is the LAST to take it, so at 60 the front is still crossing the wing in the middle of the frame
-];
-export const PANEL2_FLOOD = 45, PANEL2_HOME = 60; // it keeps the blueprint's cornflower and slides home on its projection lines
-export const BODY_WET = { shell: 65, head: 75, window: 80, abdomen: 85 }; // water crosses the body 60-120
-
-// ---------------------------------------------------------------- 5.2 to 5.6 the beats
-export const STIR = { gears: 120, portAntenna: 125, starAntenna: 130, doubleStep: 130, breath: 135, breathStar: 140, breathEnd: 165 };
-export const FANS: [number, number, number][] = [[180, 30, 0.6], [210, 20, 0.5], [230, 10, 0.45]]; // start, length, flap floor
-export const SMOOTH = [180, 240] as const; // stepped motion blends to continuous across this bar
-export const TAKEOFFS = [240, 420, 525, 585];
-export const LANDINGS: { at: number; flower: string }[] = [
- { at: 360, flower: "R1" }, { at: 450, flower: "R2" }, { at: 540, flower: "R3" },
-];
-export const SIPS: [number, number][] = [[375, 410], [465, 510], [555, 575]];
-export const PROBOSCIS = [375, 385] as const; // the hairspring uncoils into the tight centre
-export const GUSTS = [480, 600]; // a gust FRONT enters left and crosses in 60 to 90 frames
-export const CLOUD_SHADOW: [number, number][] = [[480, 540], [660, 870]];
-export const PETAL_FALL = [555, 585] as const;
-export const WHITES = [630, 750] as const; // two real white butterflies
-export const SHEET_RETURNS = 700, SHEET_CORNER_LIFTS = [715, 745];
-export const HOVER = 750, CORNER_LIFT = [780, 795] as const, SIGNATURE = [795, 825] as const, DING = 825;
-// 5.6: from the poppy it turns and comes UP the field to the foreground, growing as the world
-// shrinks. These are the keys of that approach, and the last one is the arrival at the approved
-// still's position. Without them bar 18 owns no event, which is exactly what G-AIR would find.
-export const APPROACH: [number, number][] = [[660, 2.2], [700, 0.9], [730, -2.1], [750, -5.8]]; // frame, the creature's depth z
-// 1185-1260: five beats to read the signature. The ink is still drying and the creature is still
-// drifting, so the last bar is authored too and is not a held frame.
-export const INK_DRY: [number, number] = [825, 865];
-export const SEED_FLUFF = 345;
-
-// ---------------------------------------------------------------- the gate
-export const gridProblems = (): string[] => {
- const p: string[] = [], ev = (n: number, what: string) => { if (n % 5) p.push(`${what} at ${n} is off the 5-frame event grid`); if (n < 0 || n > LOCAL) p.push(`${what} at ${n} is outside [0, ${LOCAL}]`); };
- const beat = (n: number, what: string) => { if (n % BEAT) p.push(`${what} at ${n} is not on a beat (${BEAT} frames)`); };
- ev(DROP, "the drop"); ev(PANEL2_FLOOD, "panel 2 flood"); ev(PANEL2_HOME, "panel 2 home");
- SPAR_WET.forEach((w, i) => w.forEach((n, j) => ev(n, `wing ${i} spar ${j}`)));
- Object.entries(BODY_WET).forEach(([k, n]) => ev(n, `body ${k}`));
- Object.entries(STIR).forEach(([k, n]) => ev(n, `stir ${k}`));
- FANS.forEach(([n], i) => ev(n, `fan ${i}`));
- TAKEOFFS.forEach((n) => { ev(n, `take-off ${n}`); beat(n, `take-off ${n}`); });
- LANDINGS.forEach((l) => { ev(l.at, `landing on ${l.flower}`); beat(l.at, `landing on ${l.flower}`); });
- SIPS.forEach(([a, b], i) => { ev(a, `sip ${i} start`); ev(b, `sip ${i} end`); if (b <= a) p.push(`sip ${i} ends before it starts`); });
- [...GUSTS, SEED_FLUFF, SHEET_RETURNS, ...SHEET_CORNER_LIFTS, HOVER, DING, ...INK_DRY].forEach((n) => ev(n, `event ${n}`));
- APPROACH.forEach(([n], i) => { ev(n, `approach key ${i}`); if (i && n <= APPROACH[i - 1][0]) p.push(`approach key ${i} at ${n} is out of order`); if (i && APPROACH[i][1] >= APPROACH[i - 1][1]) p.push(`approach key ${i} does not come toward the camera`); });
- [...CORNER_LIFT, ...SIGNATURE, ...PETAL_FALL, ...WHITES, ...PROBOSCIS].forEach((n) => ev(n, `event ${n}`));
- CLOUD_SHADOW.forEach(([a, b], i) => { ev(a, `cloud shadow ${i}`); ev(b, `cloud shadow ${i} end`); });
- STEPS.forEach(([a, b], i) => { if (!TAKEOFFS.includes(a)) p.push(`camera step ${i} at ${a} is not released by a take-off`); if (b - a !== 30) p.push(`camera step ${i} takes ${b - a} frames, the spec says 30`); });
- S_KEYS.forEach(([f], i) => { if (i && f <= S_KEYS[i - 1][0]) p.push(`S key ${i} at frame ${f} is out of order`); });
- S_KEYS.forEach(([, s], i) => { if (i && s > S_KEYS[i - 1][1]) p.push(`S rises at key ${i} (${S_KEYS[i - 1][1]} to ${s}): the camera never moves in`); });
- if (S_KEYS[S_KEYS.length - 1][0] !== LOCAL) p.push(`the last S key is at ${S_KEYS[S_KEYS.length - 1][0]}, the movement is ${LOCAL}`);
- // every bar of the movement must own at least one authored event, or something is holding still
- const all = [DROP, PANEL2_FLOOD, PANEL2_HOME, ...SPAR_WET.flat(), ...Object.values(BODY_WET), ...Object.values(STIR), ...FANS.map((f) => f[0]), ...TAKEOFFS, ...LANDINGS.map((l) => l.at), ...SIPS.flat(), ...GUSTS, SEED_FLUFF, SHEET_RETURNS, ...SHEET_CORNER_LIFTS, HOVER, ...CORNER_LIFT, ...SIGNATURE, DING, ...PETAL_FALL, ...WHITES, ...CLOUD_SHADOW.flat(), ...APPROACH.map((a) => a[0]), ...INK_DRY];
- for (let b = 0; b * BAR < LOCAL; b++) if (!all.some((n) => n >= b * BAR && n < (b + 1) * BAR)) p.push(`bar ${b + 1} (frames ${b * BAR}-${(b + 1) * BAR}) has no authored event: check it against section 5 before trusting G-AIR`);
- return p;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/lateral.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/lateral.ts
deleted file mode 100644
index 83fcbb0..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/lateral.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-// THE LATERAL FIGURE (spec 5.7, FABLE): wings closed or half open over the back, body in profile,
-// six legs gripping. This is how most butterflies actually sip, and it is the figure a natural
-// history plate draws BESIDE the dorsal one. It is used at stage R, where the creature is 350 to
-// 430 px across and realism matters most.
-//
-// It uses the SAME control points as the dorsal figure, which is the project's rule and also the
-// honest thing: a closed wing is not a different wing, it is the same wing stood up over the back
-// and seen from the side. So the forewing and hindwing outlines are posed rather than redrawn, the
-// venation code runs on them unchanged, and what is genuinely new here is the profile body, the
-// legs and the head, none of which the blueprint ever drew.
-//
-// From the Alamy monarch (reference 3 in `anatomy.ts`): the hindwing sits BEHIND and its rounded
-// margin projects below and behind the forewing; the forewing's inner margin tucks down out of
-// sight; the underside is quieter than the upperside and its VENATION is the dominant mark; the
-// margin carries a dark band with a double row of pale spots; the legs reach forward and down to
-// grip; and the antennae splay into a shallow V with the clubs at the top.
-import { Gfx, P, oval, rng, tube } from "../../core";
-import { CX, CY, FW, FW_H, FW_T, HW, HW_H, HW_T, REST, Wing, cen, lerp, wingGeom } from "../geom";
-import { PAPER_W } from "../finale/world";
-const PEACH = "#ef9a5c", ROSE = "#d96e80";
-import { lift } from "../finale/paint";
-import { venation } from "./anatomy";
-import { BAND, DUST, EYE, EYE_HI, FUR, FUR_D, LEG, SPOT, UMBER, damp, dilate, mixc, ps, rigger } from "./wingpaint";
-
-// The UNDERSIDE is a different picture from the upperside, as it is in life. A butterfly with the
-// same pattern on both faces reads as a cut-out, so this is quieter, cooler and more marbled.
-// richer than a pale underside would be in life, because the brief wants pigment depth: still
-// quieter than the upperside, but with real weight in the marbling and the margin
-const U_GROUND = "#f0b389", U_MARBLE = "#a8734f", U_VEIN = "#6b3b2a", U_SHADE = "#d98a6d";
-
-export type Perch = {
- at: P; // the thorax, on screen
- scale: number; // px per plate unit, as everywhere in this movement
- face: number; // -1 the head points left, +1 right
- lean: number; // radians: the body's tilt, nose down into the flower
- open: number; // 0 wings shut over the back, 1 held half open
- proboscis: number; probTo?: P;
- grip: P[]; // where the feet are, on the petal
- seed?: number;
-};
-
-// Wings closed over the back. A closed wing is not a folded wing: you see its whole FACE, the
-// underside, standing up over the body. So the outline is used exactly as authored and simply
-// ROTATED about its own hinge until its long axis points up and back, with a little cross-wing
-// foreshortening because the pair is not quite edge on to us. Folding the outline about its own
-// midline instead (which is what an `abs()` in here would do) turns one wing into a symmetrical
-// moth and is why the first attempt looked like a mosquito.
-const stand = (wg: Wing, at: P, scale: number, face: number, lean: number, tipUp: number, off: P): ((p: P) => P) => {
- const a = -Math.PI / 2 - tipUp + lean, c = Math.cos(a), s = Math.sin(a);
- return (p: P): P => {
- const dx = (p[0] - wg.h[0]) * scale, dy = (p[1] - wg.h[1]) * scale * 0.84;
- return [at[0] + face * (dx * c - dy * s) + face * off[0] * scale, at[1] + (dx * s + dy * c) + off[1] * scale];
- };
-};
-
-export const drawLateral = (g: Gfx, pe: Perch) => {
- const { at, scale, face, lean, open } = pe, seed = pe.seed ?? 900, sc = scale * 90, r = rng(seed + 31);
- const lod = scale * 780;
- const HW_G = wingGeom(1, HW, HW_H, HW_T, 2600, REST), FW_G = wingGeom(1, FW, FW_H, FW_T, 1600, REST);
-
- // ---- the shadow it throws on the petal, before anything else
- g.fill(oval(at[0] - sc * 0.5 * face, at[1] + sc * 0.9, sc * 1.1, sc * 0.26, 10), "#6d7f55", 0.2);
-
- // ---- the far legs, then the wings, then the body, then the near legs: the stacking order is
- // the whole reason a lateral figure reads as a solid animal and not a sticker
- perchLegs(g, pe, sc, false);
- profileBody(g, pe, sc, lod, r); /* the body goes UNDER the wings: a closed pair covers most of the abdomen, and an abdomen left sticking out behind is a mosquito */
- wingFace(g, HW_G, false, stand(HW_G, at, scale, face, lean, -0.72 - open * 0.26, [-104, 16]), sc, lod, seed + 7, 0.9); /* the hindwing sits BEHIND, and its rounded margin projects below and behind the forewing */
- wingFace(g, FW_G, true, stand(FW_G, at, scale, face, lean, -0.42 + open * 0.3, [-66, -10]), sc, lod, seed + 11, 1);
- perchLegs(g, pe, sc, true);
- profileHead(g, pe, sc, lod);
-};
-
-// one wing, seen from UNDERNEATH, standing over the back
-const wingFace = (g: Gfx, wg: Wing, fore: boolean, T: (p: P) => P, sc: number, lod: number, seed: number, front: number) => {
- const A = venation(wg, fore, seed), c0 = cen(wg.out), out = A.out.map(T);
- g.fill(dilate(A.out, 2).map(T), PAPER_W, 0.7); /* the paper is kept lighter under it */
- ps(g, out, U_GROUND, 0.92, seed + 1, sc * 1.3);
- ps(g, out.map((q) => lerp(q, cen(out), 0.2)), mixc(U_GROUND, PEACH, 0.5), 0.7, seed + 2, sc, false);
- ps(g, out.map((q) => lerp(q, T(wg.h), 0.3)), ROSE, 0.36, seed + 3, sc * 0.8, false); /* the rose of the upperside bleeds through at the wing root: one animal, two faces */
- // soft grey-olive marbling: the underside's whole character, and nothing on it has a hard edge
- for (let k = 0; k < 5; k++) { const rr = rng(seed + 20 + k), kk = 0.3 + rr() * 0.45, off: P = [(rr() - 0.5) * sc * 0.5, (rr() - 0.5) * sc * 0.5]; ps(g, out.map((z) => [cen(out)[0] + (z[0] - cen(out)[0]) * kk + off[0], cen(out)[1] + (z[1] - cen(out)[1]) * kk + off[1]] as P), rr() > 0.55 ? U_MARBLE : U_SHADE, 0.3 + rr() * 0.24, seed + 30 + k, sc * 0.7, false); }
- if (fore) { const apex = A.ends[Math.min(1, A.ends.length - 1)]; damp(g, [apex, lerp(apex, A.ends[0], 0.5), lerp(apex, c0, 0.34)].map(T), mixc(UMBER, U_MARBLE, 0.5), 0.3, seed + 40, sc * 0.5); }
- // the dark margin and the DOUBLE row of pale spots the reference shows on the underside
- if (lod > 120) {
- const inner = A.out.map((q) => lerp(q, c0, 0.11));
- damp(g, [...A.out, ...inner.slice().reverse()].map(T), mixc(BAND, U_SHADE, 0.05), 0.74, seed + 50, sc * 1.1);
- [0.14, 0.26].forEach((d, row) => A.ends.forEach((e, k) => { const q = T(lerp(e, c0, d)); ps(g, oval(q[0], q[1], sc * (0.026 - row * 0.006), sc * (0.022 - row * 0.005), 8), SPOT, 0.7 - row * 0.16, seed + 60 + row * 9 + k, sc * 0.09, false); }));
- }
- // the venation, which on an underside is the loudest thing on the wing
- A.veins.forEach((v, k) => rigger(g, v.pts.map(T), sc * 0.026 * v.w, U_VEIN, v.main ? 0.95 : 0.7, seed + 80 + k));
- if (lod > 120) A.out.forEach((q, k) => { const nx = q[0] - c0[0], ny = q[1] - c0[1], L = Math.hypot(nx, ny) || 1; g.fill(tube([T(q), T([q[0] + (nx / L) * A.span * 0.02, q[1] + (ny / L) * A.span * 0.02])], sc * 0.007, sc * 0.003, false), k % 2 ? SPOT : BAND, 0.55); }); /* the fringe */
- if (front > 0.95) lift(g, tube(out.slice(0, Math.ceil(out.length * 0.3)), sc * 0.045, sc * 0.025, false), seed + 90, 0.5);
-};
-
-// the body in profile: a furred thorax, a tapering segmented abdomen tucked down behind the wings
-const profileBody = (g: Gfx, pe: Perch, sc: number, lod: number, r: () => number) => {
- const { at, face, lean, scale } = pe, c = Math.cos(lean), s = Math.sin(lean);
- const L = (x: number, y: number): P => [at[0] + face * (x * c - y * s) * scale, at[1] + (x * s + y * c) * scale];
- const thorax = [L(-34, -40), L(6, -46), L(38, -26), L(46, 8), L(30, 36), L(-4, 46), L(-38, 32), L(-52, -8)];
- ps(g, thorax, mixc(UMBER, "#4a3a2c", 0.3), 0.9, 421, sc * 0.5);
- ps(g, thorax.map((q) => lerp(q, L(14, -22), 0.5)), mixc(DUST, SPOT, 0.34), 0.42, 423, sc * 0.35, false); /* lit from the upper right */
- ps(g, thorax.map((q) => lerp(q, L(-12, 28), 0.55)), "#3b2f24", 0.34, 425, sc * 0.35, false); /* core shadow */
- ps(g, thorax.map((q) => lerp(q, L(-14, 38), 0.66)), mixc(DUST, "#8c7a63", 0.5), 0.24, 427, sc * 0.3, false); /* light bounced back up off the petal */
- const abd: P[] = []; for (let i = 0; i <= 6; i++) { const t = i / 6; abd.push(L(-36 - t * 104, 4 + t * 56)); } for (let i = 6; i >= 0; i--) { const t = i / 6; abd.push(L(-36 - t * 104, 58 + t * 26)); }
- ps(g, abd, mixc(UMBER, DUST, 0.26), 0.86, 430, sc * 0.4);
- for (let i = 1; i < 7; i++) { const t = i / 7; g.fill(tube([L(-36 - t * 104, 5 + t * 56), L(-36 - t * 104, 57 + t * 26)], sc * 0.012, sc * 0.012, false), mixc(DUST, SPOT, 0.45), 0.42); } /* the paler band at each joint, wrapping round the cylinder */
- ps(g, abd.map((q) => lerp(q, L(-110, 60), 0.42)), "#463628", 0.26, 432, sc * 0.35, false);
- if (lod > 120) for (let i = 0; i < 26; i++) { const t = r(), a = -1.5 + (r() - 0.5) * 1.4, p = L(-10 + (r() - 0.5) * 80, -40 + t * 84), len = sc * (0.09 + r() * 0.11); g.fill(tube([p, [p[0] + Math.cos(a) * len, p[1] + Math.sin(a) * len] as P], sc * 0.011, sc * 0.003, false), r() > 0.45 ? FUR : FUR_D, 0.4 + r() * 0.3); }
-};
-
-// the head in profile: one big compound eye, the palps in front of it, the antenna and the tube
-const profileHead = (g: Gfx, pe: Perch, sc: number, lod: number) => {
- const { at, face, lean, scale } = pe, c = Math.cos(lean), s = Math.sin(lean);
- const L = (x: number, y: number): P => [at[0] + face * (x * c - y * s) * scale, at[1] + (x * s + y * c) * scale];
- ps(g, [L(40, -44), L(76, -34), L(86, -8), L(76, 16), L(46, 20), L(34, -14)], mixc(UMBER, "#493928", 0.35), 0.9, 440, sc * 0.3);
- if (lod > 120) {
- const e = L(66, -16);
- ps(g, oval(e[0], e[1], sc * 0.105, sc * 0.115, 13), EYE, 0.92, 442, sc * 0.22, false); /* one large compound eye, filling most of the head */
- ps(g, oval(e[0] - sc * 0.02, e[1] + sc * 0.025, sc * 0.072, sc * 0.078, 11), mixc(EYE, "#6a5a45", 0.42), 0.42, 444, sc * 0.16, false);
- g.fill(oval(e[0] + sc * 0.035, e[1] - sc * 0.04, sc * 0.024, sc * 0.02, 8), EYE_HI, 0.88);
- g.fill(tube([L(58, 14), L(84, 30), L(98, 50)], sc * 0.036, sc * 0.012, false), FUR, 0.9); /* the palps, forward and down, furry */
- g.fill(tube([L(74, 30), L(94, 46)], sc * 0.02, sc * 0.008, false), FUR_D, 0.7);
- }
- [0, 1].forEach((k) => { /* the antennae splay into a shallow V, finely ringed, clubbed */
- const a0 = L(64, -44), a1 = L(122, -116 - k * 18), a2 = L(196, -160 - k * 34);
- const pts = Array.from({ length: 9 }, (_, i) => { const t = i / 8; return lerp(lerp(a0, a1, t), lerp(a1, a2, t), t); });
- g.fill(tube(pts, sc * 0.024, sc * 0.01, false), mixc(EYE, UMBER, 0.3), 0.84);
- if (lod > 120) for (let i = 1; i < 8; i++) g.fill(tube([pts[i], lerp(pts[i], pts[i + 1], 0.45)], sc * 0.015, sc * 0.013, false), FUR, 0.4);
- const cl = pts[8], cb = pts[7];
- ps(g, oval(cl[0] + (cl[0] - cb[0]) * 0.3, cl[1] + (cl[1] - cb[1]) * 0.3, sc * 0.044, sc * 0.028, 9), mixc(EYE, UMBER, 0.2), 0.9, 450 + k, sc * 0.1, false);
- });
- // the proboscis: it leaves from BELOW the palps, and when it is out it is a fine curved tube
- const base = L(88, 38), tip: P = pe.probTo ?? [base[0], base[1] + sc * 0.9], p = pe.proboscis, spir: P[] = [];
- for (let i = 0; i <= 24; i++) {
- const t = i / 24, a = 1.2 + t * 2.4 * Math.PI * 2, rr = sc * (0.016 + 0.07 * t);
- const coiled: P = [base[0] + Math.cos(a) * rr, base[1] + Math.sin(a) * rr];
- const bw = Math.sin(t * Math.PI) * sc * 0.26;
- const straight: P = [base[0] + (tip[0] - base[0]) * t + face * bw * 0.5, base[1] + (tip[1] - base[1]) * t + bw * 0.5];
- spir.push([coiled[0] + (straight[0] - coiled[0]) * p, coiled[1] + (straight[1] - coiled[1]) * p]);
- }
- g.fill(tube(spir, sc * 0.02, sc * 0.01, false), mixc(EYE, UMBER, 0.25), 0.78);
- if (p > 0.4) g.fill(tube(spir.map((q) => [q[0] + sc * 0.011, q[1] + sc * 0.005] as P), sc * 0.008, sc * 0.004, false), FUR, 0.3 * p);
-};
-
-// Six legs, reaching forward and down to GRIP. The far three are drawn before the wings and the
-// near three after, which is what makes the figure sit on the flower rather than in front of it.
-const perchLegs = (g: Gfx, pe: Perch, sc: number, near: boolean) => {
- const { at, face, lean, grip, scale } = pe, c = Math.cos(lean), s = Math.sin(lean), r = rng((pe.seed ?? 900) + (near ? 3 : 5));
- const L = (x: number, y: number): P => [at[0] + face * (x * c - y * s) * scale, at[1] + (x * s + y * c) * scale];
- ([[34, 30], [2, 42], [-34, 46]] as number[][]).forEach(([hx, hy], k) => {
- const hip = L(hx, hy), foot = grip[k % grip.length] ?? [hip[0] + sc * 0.3, hip[1] + sc * 0.7];
- const off = near ? sc * 0.06 : -sc * 0.08, fo: P = [foot[0] + off + (r() - 0.5) * sc * 0.12, foot[1] + (r() - 0.5) * sc * 0.08];
- const knee: P = [lerp(hip, fo, 0.45)[0] + face * sc * 0.16, lerp(hip, fo, 0.45)[1] - sc * 0.2]; /* the femur goes forward and UP, the tibia comes back down: that kink is the leg */
- const col = near ? LEG : mixc(LEG, "#3b2f24", 0.45);
- g.fill(tube([hip, knee], sc * 0.021, sc * 0.014, false), col, near ? 0.84 : 0.6);
- g.fill(tube([knee, fo], sc * 0.015, sc * 0.008, false), col, near ? 0.82 : 0.58);
- g.fill(tube([fo, [fo[0] + face * sc * 0.07, fo[1] + sc * 0.03] as P], sc * 0.009, sc * 0.004, false), mixc(col, EYE, 0.5), near ? 0.85 : 0.6); /* tarsus and its claw, bent over the petal */
- for (let i = 0; i < 3; i++) { const p = lerp(hip, knee, 0.3 + i * 0.25); g.fill(tube([p, [p[0] + (r() - 0.5) * sc * 0.05, p[1] - sc * 0.028] as P], sc * 0.0045, sc * 0.002, false), FUR_D, near ? 0.5 : 0.3); }
- });
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/meadow2.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/meadow2.ts
deleted file mode 100644
index fcfbd5d..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/meadow2.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-// THE CLUMP, AND WHAT IS BEHIND IT. Stage R holds for six bars, so this is the part of the film
-// the eye has time to disbelieve. Nine heads and five buds, hand-placed at three heights and
-// three depths, chosen so the flight zig-zags right, then left behind a stem, then down, then up
-// (spec 6.1). Nothing is stamped: every plant has its own view, colour, size, nod and seed, and
-// no view is used for more than a quarter of the clump. Nine heads over five views is two of
-// each and one over, so every view sits at 22 percent and none of them reaches the 25 the spec
-// allows: facing R1 and F3, three-quarter R2 and F1, profile R3 and F4, half-open R4 and F2, and
-// one bud standing among them on its own tall stem.
-//
-// Behind them there is no sky yet. At S around 0.5 the camera is down among the stems, so the
-// backdrop is the meadow itself thrown out of focus: a graded wash that runs cool and green at
-// the bottom to warm and pale at the top where the light comes through, drifts of colour with no
-// drawing in them at all, and two planes of grass that are only silhouette and value.
-import { Gfx, P, jitter, oval, rng, tube } from "../../core";
-import { GRASS_LIT, GRASS_MID, GRASS_SHADE } from "../finale/world";
-import { Plant, Variety, View, basalLeaves, head, plant } from "./ranunculus";
-import { Cam, projector } from "./view";
-
-// world units, the same units as the plate: the ground the clump grows out of is at y = 1080
-export const GROUND = 1080;
-export const R_LOOK: P = [1760, 250]; // where the lens sits through stage R
-
-// R1 to R4 are the four the creature visits, in order. The rest are the clump it visits them in.
-export const CLUMP: (Plant & { id: string; z: number })[] = [
- { id: "R4", z: 0, at: [1965, -130], R: 310, v: "magenta", view: "half", tilt: -0.12, stemLen: 1180, seed: 2101 },
- { id: "R2", z: 0, at: [2210, 170], R: 330, v: "blush", view: "three", tilt: 0.16, stemLen: 980, seed: 2102, sideBud: -0.7 },
- { id: "F1", z: 0, at: [1145, 255], R: 300, v: "peach", view: "three", tilt: -0.22, stemLen: 900, seed: 2103 },
- { id: "R1", z: 0, at: [1720, 300], R: 350, v: "coral", view: "facing", tilt: 0.05, stemLen: 900, seed: 2104 },
- { id: "F2", z: 0, at: [2470, 520], R: 290, v: "coral", view: "half", tilt: 0.3, stemLen: 700, seed: 2105 },
- { id: "R3", z: 0, at: [1330, 640], R: 300, v: "butter", view: "profile", tilt: -0.3, stemLen: 620, seed: 2106, sideBud: 0.6 },
- { id: "F4", z: 0, at: [2345, 790], R: 260, v: "blush", view: "profile", tilt: 0.42, stemLen: 420, seed: 2107 },
- { id: "F3", z: 0, at: [1575, 810], R: 270, v: "butter", view: "facing", tilt: 0.1, stemLen: 400, seed: 2108 },
- { id: "F5", z: 0.3, at: [1380, 430], R: 150, v: "magenta", view: "bud", tilt: -0.08, stemLen: 760, seed: 2109 },
-];
-export const BUDS: (Plant & { z: number })[] = [
- { z: 0, at: [1450, 120], R: 90, v: "coral", view: "bud", tilt: -0.5, stemLen: 1100, seed: 2201 },
- { z: 0, at: [2120, 700], R: 80, v: "blush", view: "bud", tilt: 0.55, stemLen: 520, seed: 2202 },
- { z: 0.3, at: [1250, -60], R: 85, v: "magenta", view: "bud", tilt: -0.3, stemLen: 1300, seed: 2203 },
- { z: 0, at: [2600, 200], R: 75, v: "peach", view: "bud", tilt: 0.7, stemLen: 980, seed: 2204 },
- { z: 0, at: [1700, 900], R: 70, v: "butter", view: "bud", tilt: -0.62, stemLen: 300, seed: 2205 },
-];
-// Every head nods on its OWN period, 50 to 80 frames, never shared. A visited head also dips on
-// the landing and rebounds on the take-off, which is the only synchronised motion in the clump.
-export const nod = (seed: number, f: number) => { const per = 50 + (seed % 31); return Math.sin((f / per) * Math.PI * 2 + seed) * 0.12; };
-
-// ---------------------------------------------------------------- the backdrop
-const mixc = (a: string, b: string, t: number) => { const h = (x: string) => [parseInt(x.slice(1, 3), 16), parseInt(x.slice(3, 5), 16), parseInt(x.slice(5, 7), 16)]; const A = h(a), B = h(b); return "#" + A.map((v, i) => Math.round(v + (B[i] - v) * t).toString(16).padStart(2, "0")).join(""); };
-
-export const backdrop = (g: Gfx, cam: Cam, W: number, H: number) => {
- const c = g.cur, gr = c.createLinearGradient(0, 0, 0, H);
- gr.addColorStop(0, "#eee9cd"); gr.addColorStop(0.34, "#cfd8a2"); gr.addColorStop(0.72, "#9cb375"); gr.addColorStop(1, "#6e8b5d");
- g.touch(-20, -20, W + 20, H + 20); c.fillStyle = gr; c.fillRect(-20, -20, W + 40, H + 40);
- const r = rng(4400); /* drifts of colour with no drawing in them: other flowers, far too far back to be flowers */
- ([["#e8b8c8", 260, 300, 190, 6], ["#f2dc9a", 760, 210, 220, 7], ["#d9a0b4", 900, 620, 170, 5], ["#eae2c2", 420, 120, 150, 5]] as [string, number, number, number, number][]).forEach(([col, cx, cy, rad, n], i) => {
- for (let j = 0; j < n; j++) { const a = r() * 6.283, d = Math.sqrt(r()) * rad; g.wash(oval(cx + Math.cos(a) * d, cy + Math.sin(a) * d * 0.7, 18 + r() * 26, 14 + r() * 20, 9), col, { alpha: 0.2 + r() * 0.18, seed: 4410 + i * 20 + j, shrink: 0.95, rim: false }); }
- });
-};
-
-// a plane of grass that is only silhouette and value: no blade is drawn sharply this far back
-export const backGrass = (g: Gfx, cam: Cam, z: number, seed: number, n: number, fade: number, lean: number) => {
- const { at, k } = projector(cam, z), r = rng(seed);
- const air = (col: string) => mixc(col, "#dfe4d0", fade);
- for (let i = 0; i < n; i++) {
- const wx = R_LOOK[0] - 2600 + r() * 5200, wy = GROUND - 200 + r() * 900, p = at([wx, wy]), h = (260 + r() * 520) * k;
- if (p[0] < -160 || p[0] > 1240) continue;
- const ang = (r() - 0.5) * 0.5 + lean * 0.4, pts: P[] = [];
- for (let q = 0; q <= 5; q++) { const t = q / 5, a = ang + lean * t * t * 1.4; pts.push([p[0] + Math.sin(a) * h * t, p[1] - Math.cos(a) * h * t]); }
- g.fill(tube(pts, Math.max(0.8, h * 0.022), h * 0.004, false), air([GRASS_SHADE, GRASS_MID, GRASS_LIT][Math.floor(r() * 3)]), (0.2 + r() * 0.24) * (1 - fade * 0.4));
- }
-};
-
-// ---------------------------------------------------------------- the clump, composed
-export const drawClump = (g: Gfx, cam: Cam, f: number, o: { dip?: Record<string, number>; lean?: number } = {}) => {
- const lean = o.lean ?? 0, dips = o.dip ?? {};
- const items = [...CLUMP.map((p) => ({ p, bud: false })), ...BUDS.map((p) => ({ p: p as typeof CLUMP[0], bud: true }))];
- const drawn = items.map((it) => { const pr = projector(cam, it.p.z), s = pr.at(it.p.at); return { ...it, s, k: pr.k, y: s[1] }; });
- const p0 = projector(cam, 0);
- g.group("plain", () => basalLeaves(g, p0.at([1780, GROUND + 130]), 1250 * p0.k, 2300, 11), { alpha: 0.9 }); /* the dark ferny mass at the foot of the clump */
- drawn.sort((a, b) => a.y - b.y).forEach((it) => {
- const dip = dips[(it.p as { id?: string }).id ?? ""] ?? 0, n = nod(it.p.seed, f);
- g.group("paint", () => plant(g, { ...it.p, at: it.s, R: it.p.R }, it.k, dip + n, lean + n * 0.4), { alpha: 0.99 }); /* a paint group softens the margin a hair and granulates it: the difference between cellophane and wet pigment */
- });
-};
-
-// ---------------------------------------------------------------- the near air
-export const fringe = (g: Gfx, cam: Cam, lean: number) => {
- const { at, k } = projector(cam, -0.2), r = rng(4500);
- g.group("plain", () => {
- for (let i = 0; i < 7; i++) {
- const p = at([R_LOOK[0] - 1400 + r() * 2800, GROUND + 400 + r() * 300]), h = (900 + r() * 700) * k, a = (r() - 0.5) * 0.7;
- const pts: P[] = []; for (let q = 0; q <= 5; q++) { const t = q / 5, ang = a + (lean + 0.1) * t * t * 1.6; pts.push([p[0] + Math.sin(ang) * h * t, p[1] - Math.cos(ang) * h * t]); }
- g.fill(tube(pts, Math.max(2, h * 0.04), h * 0.006, false), [GRASS_SHADE, GRASS_MID, GRASS_LIT][i % 3], 0.34);
- }
- }, { alpha: 0.55, blur: 4.2 }); /* across the lens, huge and with no edge at all */
-};
-// seed fluff, from local 345: two of them, drifting, never crossing the creature's face
-export const seedFluff = (g: Gfx, cam: Cam, f: number) => {
- const { k } = projector(cam, -0.05);
- ([[345, 120, 980, -0.9, 3110], [420, 860, 1120, -1.25, 3120]] as number[][]).forEach(([from, x0, y0, rise, seed]) => {
- if (f < from) return; const t = (f - from) / 300, r = rng(seed);
- const p: P = [x0 + t * 620 + Math.sin(t * 7 + seed) * 46, y0 + t * 560 * rise + Math.cos(t * 5.5) * 30], R = 17 * Math.max(0.6, k * 1.6);
- if (p[1] < -40 || p[0] > 1140) return;
- for (let i = 0; i < 11; i++) { const a = (i / 11) * Math.PI * 2 + t * 1.6; g.fill(tube([p, [p[0] + Math.cos(a) * R, p[1] + Math.sin(a) * R]], R * 0.09, R * 0.03, false), "#f6f1e2", 0.5); }
- g.fill(oval(p[0], p[1], R * 0.14, R * 0.14, 6), "#cdbfa2", 0.7);
- });
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/movement2.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/movement2.ts
deleted file mode 100644
index 29ab81b..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/movement2.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-// MOVEMENT 2, "ALIVE", all 1260 frames. One shot, no cuts: every change of scale is a camera
-// move and every big move is released by a take-off. The whole movement is a pure function of the
-// local frame, and every frame number it uses comes from `cues.ts`.
-//
-// The movement crosses two camera conventions. Stages M to R live in the NEAR world, in plate
-// units, where the sheet is 1080 units across and the ranunculus clump grows beside it. Stages F
-// and W live in the FINALE world, which is the approved destination's own coordinate system and
-// carries the sky, the hills, the far field, the footpath and the signature. The handover is a
-// 60-frame DISSOLVE under the climb out of the clump, which is the only place in the movement
-// where two renderings of the same meadow are on screen at once. It is not a cut: nothing jumps,
-// the camera keeps pulling back through it, and it is over before the hills arrive.
-import { Ctx, Env, Gfx, Layer, P, PENCIL } from "../../core";
-import { CX, CY, HEAD, THORAX, cen, lerp } from "../geom";
-import { FULL, PlateState, drawPlate } from "../plate";
-import { PAPER_F } from "../finale/compose";
-import { Cam as FCam, projector as fprojector } from "../finale/world";
-import { farField, footpath, grassBlades, grassWash, hills, sky } from "../finale/scene";
-import { Drift, drift, flower } from "../finale/flora";
-import { blueprintSheet } from "../finale/sheet";
-import { clearCorner, signature } from "./sign";
-import { clump as grassClump } from "../finale/paint";
-import { GRASS_LIT, GRASS_MID, GRASS_SHADE } from "../finale/world";
-import { APPROACH, CORNER_LIFT, DING, FANS, GUSTS, HOVER, LANDINGS, M0, PANEL2_HOME, SEED_FLUFF, SIGNATURE, SIPS, STIR, TAKEOFFS, WHITES } from "./cues";
-import { Cam, projector, scaleOf } from "./view";
-import { drop, frontRim, wetnessAt } from "./water";
-import { ALL_WET, Flight, dilate, mapper, paintCreature, wingsOf } from "./wingpaint";
-import { CLUMP, GROUND, R_LOOK, backGrass, backdrop, drawClump, fringe, nod, seedFluff } from "./meadow2";
-import { PAINTS } from "./ranunculus";
-
-const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
-const ease = (t: number) => t * t * (3 - 2 * t);
-const ramp = (f: number, a: number, b: number) => ease(clamp((f - a) / (b - a)));
-const HANDOVER: [number, number] = [575, 630]; // the dissolve out of the near world, under the climb
-
-// ---------------------------------------------------------------- the camera spine (near world)
-// Authored on bars. Stages M to R: it starts on the wing root, drifts across the thorax, then
-// follows the creature off the sheet and over to the clump, where it settles and only creeps.
-const LOOK: [number, P][] = [
- [0, M0], [120, [626, 382]], [200, [590, 440]], [240, [560, 500]], [270, [545, 535]],
- [285, [600, 520]], [320, [1080, 420]], [345, R_LOOK], [450, [1820, 262]], [540, [1700, 300]],
- [585, [1800, 220]], [640, [2400, 60]], [700, [3100, -140]],
-];
-const lookAt = (f: number): P => {
- let i = 0; while (i < LOOK.length - 2 && f > LOOK[i + 1][0]) i++;
- const [f0, a] = LOOK[i], [f1, b] = LOOK[i + 1], t = ease(clamp((f - f0) / (f1 - f0)));
- return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
-};
-export const camAt = (f: number): Cam => ({ S: scaleOf(f), look: lookAt(f) });
-
-// ---------------------------------------------------------------- the creature, beat by beat
-// Stepped on the tick until 180, blending to continuous across the bar to 240, then free.
-const poseAt = (f: number): Flight => {
- if (f < STIR.gears) return { pose: { flap: 1, sweep: 0 }, heading: 0, pitch: 1, bank: 0 };
- if (f < 180) { /* the gears catch, the antennae quiver, then a BREATH: one side leads */
- const n = Math.floor(f / 5), step = (n % 2 ? 0.012 : -0.008);
- const br = f >= STIR.breath ? Math.sin(((f - STIR.breath) / 30) * Math.PI) * 0.14 : 0;
- return { pose: { flap: 1 - br + step, sweep: step * 0.4 }, heading: 0, pitch: 1, bank: 0.03 + br * 0.4 };
- }
- if (f < 240) { /* three fans, opening wider each time, easing from hard-out to in and out */
- let flap = 1;
- FANS.forEach(([at, len, floor]) => { if (f >= at && f < at + len * 2) { const u = (f - at) / (len * 2); flap = Math.min(flap, 1 - (1 - floor) * Math.sin(u * Math.PI)); } });
- const u = clamp((f - 180) / 60), stepped = Math.floor(f / 5) % 2 ? 0.01 : -0.01;
- return { pose: { flap: flap + stepped * (1 - u), sweep: -0.02 * (1 - flap) }, heading: 0, pitch: 1 - 0.04 * (1 - flap), bank: 0.06 + 0.1 * (1 - flap) };
- }
- const cyc = f < 345 ? 10 : 30, ph = ((f - 240) % cyc) / cyc, flap = 0.62 + 0.38 * Math.cos(ph * Math.PI * 2);
- return { pose: { flap, sweep: -0.03 * (1 - flap) }, heading: 0, pitch: 0.92, bank: 0.07 + 0.05 * Math.sin(f * 0.11) };
-};
-
-// Where it is, in NEAR-WORLD units, from the take-off to the climb out of the clump. Hand-authored
-// with detours: a butterfly never flies a straight line and never a clean sine.
-const hostOf = (id: string) => CLUMP.find((c) => c.id === id)!;
-const perchPoint = (id: string): P => { const h = hostOf(id); return [h.at[0] + h.R * 0.42, h.at[1] - h.R * 0.52]; };
-const bob = (f: number, amp: number): number => Math.sin(f * 0.42) * amp;
-export const whereAt = (f: number): { at: P; perched: boolean; on: string } => {
- if (f < 240) return { at: [CX, CY], perched: false, on: "" };
- if (f < 360) { /* off the sheet, up and right, with a detour: it is not going anywhere in particular yet */
- const t = ease(clamp((f - 240) / 120)), a: P = [CX, CY], b = perchPoint("R1");
- return { at: [a[0] + (b[0] - a[0]) * t + Math.sin(t * Math.PI * 1.6) * 210, a[1] + (b[1] - a[1]) * t - Math.sin(t * Math.PI) * 420 + bob(f, 12)], perched: false, on: "" };
- }
- const legs: [number, number, string, string][] = [[360, 420, "R1", "R1"], [420, 450, "R1", "R2"], [450, 525, "R2", "R2"], [525, 540, "R2", "R3"], [540, 585, "R3", "R3"], [585, 645, "R3", ""]];
- for (const [a, b, from, to] of legs) {
- if (f < a || f >= b) continue;
- if (from === to) return { at: perchPoint(from), perched: true, on: from };
- const t = ease(clamp((f - a) / (b - a))), p = perchPoint(from), q = to ? perchPoint(to) : [p[0] + 900, p[1] - 1400] as P;
- const detour = Math.sin(t * Math.PI) * (to === "R2" ? 180 : to === "R3" ? -260 : 150);
- return { at: [p[0] + (q[0] - p[0]) * t + detour, p[1] + (q[1] - p[1]) * t - Math.sin(t * Math.PI) * 170 + bob(f, 9)], perched: false, on: "" };
- }
- const t = clamp((f - 645) / 90), p = perchPoint("R3");
- return { at: [p[0] + 1400 * t, p[1] - 2100 * t], perched: false, on: "" };
-};
-
-// ---------------------------------------------------------------- the sheet, as a world object
-// The plate is drawn ONCE at 1:1 into its own surface with the butterfly-shaped BLANK knocked out
-// of it, and from then on it is only ever downscaled and foreshortened onto the frame. Never
-// scaled up: that is the rule, and it is also why the blank keeps the drawing's own edge.
-const BLANK = "#e8e3d2";
-const sheetLayer = (env: Env, blank: boolean): Layer => {
- const key = `alive:sheet:${blank}`, dw = Math.round(env.W * env.scale), dh = Math.round(env.H * env.scale);
- let L = env.cache.get(key) as Layer | undefined;
- if (L) return L;
- L = env.canvas(dw, dh);
- const st: PlateState = { wings: { flap: 1, sweep: 0 }, lift: 0, keyY: 0, keyTurn: 0, train: { centre: 0, third: 0, pinion: 0, escape: 0, fork: 0 }, shadow: [0, 0], boil: 0, inkedBoil: 0, boilIndex: 0, p: FULL, view: { cx: 540, cy: 540, zoom: 1 } };
- drawPlate(L.ctx, env, st);
- if (blank) knockOut(new Gfx(L.ctx, env, 0, PENCIL), (p: P) => p);
- env.cache.set(key, L);
- return L;
-};
-// the creature's own silhouette, lifted clean out of the plate: the drawing went with it
-export const knockOut = (g: Gfx, T: (p: P) => P) => {
- const W = wingsOf({ pose: { flap: 1, sweep: 0 }, heading: 0, pitch: 1, bank: 0 });
- W.forEach((wg) => g.fill(dilate(wg.out, 4).map(T), BLANK, 0.97));
- g.fill(dilate(THORAX, 5).map(T), BLANK, 0.97);
- g.fill(dilate(HEAD, 4).map(T), BLANK, 0.97);
- const abd: P[] = [];
- for (let i = 0; i <= 6; i++) { const t = i / 6, hw = 23 * (1 - t) ** 0.8 + 6.5; abd.push(T([CX + hw * 0.9, CY + (70 + 170 * t) * 0.9])); }
- for (let i = 6; i >= 0; i--) { const t = i / 6, hw = 23 * (1 - t) ** 0.8 + 6.5; abd.push(T([CX - hw * 0.9, CY + (70 + 170 * t) * 0.9])); }
- g.fill(abd, BLANK, 0.97);
-};
-// y-scale 1 to 0.45 about its centre with a slight keystone: the sheet is lying in the grass now
-const sheetOnto = (ctx: Ctx, env: Env, cam: Cam, f: number) => {
- const L = sheetLayer(env, f >= TAKEOFFS[0]), pr = projector(cam, 0), c = pr.at([540, 540]);
- const yk = 1 - 0.55 * ramp(f, 285, 335), sk = 0.18 * ramp(f, 290, 340), k = cam.S * env.scale;
- ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0);
- ctx.translate(c[0] * env.scale, c[1] * env.scale); ctx.transform(k, sk * k * 0.35, -sk * k, k * yk, 0, 0);
- ctx.globalAlpha = 1; ctx.imageSmoothingEnabled = true;
- ctx.drawImage(L.canvas as CanvasImageSource, -540 * env.scale, -540 * env.scale, env.W * env.scale, env.H * env.scale);
- ctx.restore();
-};
-
-// ---------------------------------------------------------------- the NEAR world, stages M to R
-const nearFrame = (ctx: Ctx, env: Env, f: number) => {
- const cam = camAt(f), W = env.W, H = env.H, g = new Gfx(ctx, env, f, PENCIL);
- ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER_F; ctx.fillRect(0, 0, W, H);
- g.paper("coldpress", 0.16);
- const meadow = ramp(f, 262, 330); /* the scenery arrives from behind the sheet as the camera rises */
- if (meadow > 0) {
- g.group("plain", () => backdrop(g, cam, W, H), { alpha: meadow });
- g.group("plain", () => backGrass(g, cam, 3.5, 4601, 26, 0.55, 0.06), { alpha: 0.9 * meadow, blur: 3.4 });
- g.group("plain", () => backGrass(g, cam, 2.2, 4602, 24, 0.34, 0.08), { alpha: 0.92 * meadow, blur: 2.2 });
- g.group("plain", () => backGrass(g, cam, 1.0, 4603, 20, 0.14, 0.1), { alpha: 0.95 * meadow, blur: 1.1 });
- const dips: Record<string, number> = {};
- LANDINGS.forEach((l) => { const off = TAKEOFFS.find((t) => t > l.at) ?? 1e9; if (f >= l.at && f <= off + 30) { const t = f - l.at, s = t < 12 ? 1.35 * (1 - Math.pow(1 - t / 12, 2)) : 1 + 0.35 * Math.cos((t - 12) * 0.34) * Math.exp(-(t - 12) / 14); dips[l.flower] = f <= off ? s : s * Math.max(0, 1 - (f - off) / 24); } });
- const gust = GUSTS.reduce((a, gt) => (f >= gt && f < gt + 70 ? a + 0.12 * Math.sin(((f - gt) / 70) * Math.PI) : a), 0);
- g.group("plain", () => drawClump(g, cam, f, { dip: dips, lean: 0.05 + gust }), { alpha: 0.99 * meadow });
- }
- // ---- the sheet: live at the macro, then its own cached surface, only ever downscaled
- if (f < 285) {
- const st: PlateState = { wings: { flap: 1, sweep: 0 }, lift: liftAt(f), keyY: 0, keyTurn: 0, train: trainAt(f), shadow: f > 180 && f < 240 ? [((f - 180) / 60) * 14, ((f - 180) / 60) * 20] : [0, 0], boil: 1, inkedBoil: 1, boilIndex: Math.floor(f / 4), p: FULL, view: { cx: cam.look[0], cy: cam.look[1], zoom: cam.S } };
- drawPlate(ctx, env, st);
- if (f >= TAKEOFFS[0]) { const pr = projector(cam, 0); g.group("plain", () => knockOut(g, pr.at), { alpha: 1 }); }
- } else if (f < 345) sheetOnto(ctx, env, cam, f);
- // ---- the water, only while it is still making the creature
- const wt = f < 130 ? wetnessAt(f) : ALL_WET;
- const w = whereAt(f), pose = poseAt(f), pr = projector(cam, 0), at = pr.at(w.at);
- if (w.perched && f >= 345) {
- const host = hostOf(w.on), hp = projector(cam, host.z), hs = hp.at(host.at), R = host.R * hp.k;
- const n = nod(host.seed, f), well: P = [hs[0] - R * 0.02, hs[1] + R * 0.11 + n * R * 0.1];
- const sip = SIPS.find(([a, b]) => f >= a - 20 && f <= b + 10), land = LANDINGS.find((l) => l.flower === w.on)!;
- const p = sip ? clamp((f - sip[0] + 10) / 10) : 0, beat = 0.5 - 0.5 * Math.cos(((f - land.at) / 15) * Math.PI * 2);
- /* TOP / three-quarter, wings OPEN. The head is turned down toward the throat so the proboscis
- reaches it without crossing the body, and the body's form shading is computed in SCREEN space,
- so turning the creature never moves the sun off the upper right. */
- const fan = 0.5 - 0.5 * Math.cos(((f - land.at) / 30) * Math.PI * 2);
- const head: Flight = { pose: { flap: 0.96 - 0.16 * fan, sweep: -0.02 - 0.02 * fan }, heading: 2.78 + 0.05 * Math.sin((f - land.at) * 0.06), pitch: 0.9, bank: 0.06 + 0.04 * Math.sin((f - land.at) * 0.19) };
- const sit: P = [well[0] - 58 * cam.S, well[1] - 168 * cam.S];
- g.group("plain", () => paintCreature(g, sit, cam.S * (1 + beat * 0.008), head, { proboscis: p, probTo: well, shadow: 1, shadowOff: [-0.55, 0.85], legs: 1, behind: PAINTS[host.v].mid, seed: 900 }), { alpha: 0.99 });
- } else {
- g.group("plain", () => paintCreature(g, at, cam.S, pose, { wetness: wt, groundLift: f < 130, shadow: f > 180 && f < 300 ? ramp(f, 180, 240) * (1 - ramp(f, 260, 300)) : 0, shadowOff: [-0.35, 0.45], legs: f >= 135 ? ramp(f, 135, 150) * (f > 240 ? 0.25 : 1) : 0, seed: 900 }), { alpha: 0.98 });
- if (f < 130) { const T = mapper(at, cam.S, pose), Wg = wingsOf(pose); g.group("plain", () => frontRim(g, T, cam.S * 90, Wg, f, wt), { alpha: 0.9 }); if (f < 60) { const c = cen(Wg[3].panels[2]), lp = liftAt(f); g.group("plain", () => drop(g, T([c[0] + 58 * lp, c[1] - 60 * lp]), cam.S * 26, f), { alpha: 1 }); } }
- }
- if (f >= SEED_FLUFF) g.group("plain", () => seedFluff(g, cam, f), { alpha: 0.7, blur: 1.4 });
- if (meadow > 0.4) fringe(g, cam, 0.05);
- g.paper("washGran", 0.05); g.paper("coldpress", 0.07);
-};
-const liftAt = (f: number): number => { if (f <= 45) return 1; if (f >= PANEL2_HOME + 6) return 0; const u = clamp((f - 45) / 15), e = 1 - Math.pow(1 - u, 3); return Math.max(-0.06, 1 - e) + (f > PANEL2_HOME ? -0.06 * Math.sin(((f - PANEL2_HOME) / 6) * Math.PI) : 0); };
-const trainAt = (f: number) => { const n = Math.floor(f / 5) + (f >= 130 ? 1 : 0), th = n * 0.42; return { centre: th, third: th * 2.1, pinion: th * 4.4, escape: -th * 3.2, fork: Math.sin(n * 1.7) * 0.22 }; };
-
-// ---------------------------------------------------------------- the FINALE world, stages F and W
-const DRIFTS: [number, Drift][] = [
- [3.5, { sp: "buttercup", at: [470, 545], r: 150, n: 26, size: 5.5, seed: 7101 }],
- [3.5, { sp: "buttercup", at: [700, 560], r: 120, n: 16, size: 5, seed: 7102 }],
- [3.5, { sp: "daisy", at: [200, 560], r: 130, n: 12, size: 5, seed: 7103 }],
- [2.2, { sp: "poppy", at: [780, 655], r: 170, n: 20, size: 9, seed: 7201 }],
- [2.2, { sp: "cosmos", at: [640, 640], r: 90, n: 9, size: 11, seed: 7202 }],
- [2.2, { sp: "daisy", at: [250, 660], r: 120, n: 14, size: 8, seed: 7203 }],
- [1.0, { sp: "cornflower", at: [250, 690], r: 95, n: 13, size: 13, seed: 7301 }],
- [1.0, { sp: "daisy", at: [430, 720], r: 150, n: 16, size: 12, seed: 7302 }],
- [1.0, { sp: "cosmos", at: [760, 700], r: 110, n: 8, size: 13, seed: 7303 }],
-];
-// D runs from the clump out to the approved still's 0.8, and the look-at lands on its composition
-const fcamAt = (f: number): FCam => {
- const t = ease(clamp((f - 575) / 175)), t2 = ease(clamp((f - 750) / 120));
- return { D: 0.26 + (0.8 - 0.26) * t + 0.012 * t2, look: [520 - 190 * t + 0 * t2, 800 - 190 * t] };
-};
-const POPPY: P = [800, 640]; // the field poppy it touches down on at 810, deeper in the field
-const wideFrame = (ctx: Ctx, env: Env, f: number) => {
- const W = env.W, H = env.H, g = new Gfx(ctx, env, f, PENCIL), cam = fcamAt(f);
- ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER_F; ctx.fillRect(0, 0, W, H);
- g.paper("coldpress", 0.16);
- const open = ramp(f, 570, 660); /* the sky and the hills arrive as the camera clears the stems */
- if (open > 0) { g.group("plain", () => sky(g, cam, W, H), { alpha: open }); g.group("plain", () => hills(g, cam), { alpha: open }); g.group("plain", () => farField(g, cam), { alpha: open }); }
- const gust = GUSTS.reduce((a, gt) => (f >= gt && f < gt + 90 ? a + 0.1 * Math.sin(((f - gt) / 90) * Math.PI) : a), 0);
- const lean = 0.05 + gust + 0.02 * Math.sin(f * 0.03);
- ([[3.5, 545, 61, 26, 0.06, 0.3], [2.2, 640, 67, 34, 0.08, 0.12], [1.0, 706, 71, 46, 0.1, 0]] as number[][]).forEach(([z, y0, seed, n, ln, fade]) => {
- g.group("plain", () => { grassWash(g, cam, z, y0, seed, { lean: ln + gust, fade, cool: z === 1 }); if (z === 3.5) footpath(g, cam); }, { alpha: 1 });
- g.group("plain", () => grassBlades(g, cam, z, y0, seed, { blades: n, lean: ln + gust, fade }), { alpha: 0.95 });
- const pr = fprojector(cam, z);
- g.group("plain", () => DRIFTS.filter(([dz]) => dz === z).forEach(([, d]) => drift(g, d, pr.at, pr.k, lean)), { alpha: 0.97 });
- });
- const h0 = fprojector(cam, 0), h1 = fprojector(cam, 0.3);
- g.group("plain", () => {
- if (f >= 700) blueprintSheet(g, h0.at([150, 965]), 150 * h0.k); /* what it left behind, back in frame lower left, never pointed at */
- ([[330, 830, 34, 7401, 0], [250, 880, 26, 7402, 1]] as number[][]).forEach(([x, y, s, sd, v]) => flower(g, "daisy", h0.at([x, y]), s * h0.k, sd, { variant: v, lean }));
- ([[560, 800, 30, 7403, 0], [650, 840, 22, 7404, 3]] as number[][]).forEach(([x, y, s, sd, v]) => flower(g, "poppy", h1.at([x, y]), s * h1.k, sd, { variant: v, lean }));
- }, { alpha: 0.98 });
- // ---- the creature: along the path, down on a poppy at 810, then up the field toward us
- const cr = creatureWide(f, cam);
- if (cr) g.group("plain", () => paintCreature(g, cr.at, cr.scale, cr.flight, { shadow: cr.low, shadowOff: [-0.5, 0.6], legs: cr.perched ? 1 : 0.2, proboscis: cr.sip, probTo: cr.probTo, seed: 900 }), { alpha: 0.99 });
- whites(g, f, cam);
- const fr = fprojector(cam, -0.2);
- if (f < 700) g.group("plain", () => { ([[-40, 1120], [180, 1160], [900, 1150], [1120, 1090], [620, 1180]] as P[]).forEach((w0, i) => grassClump(g, fr.at(w0), (240 + i * 34) * fr.k, 60 * fr.k, [GRASS_SHADE, GRASS_MID, GRASS_LIT][i % 3], 7500 + i, 0.06 + i * 0.02, 6, 0.3)); }, { alpha: 0.5 * (1 - ramp(f, 620, 700)), blur: 2.2 });
- if (f >= CORNER_LIFT[0]) g.group("plain", () => { clearCorner(g, ramp(f, CORNER_LIFT[0], CORNER_LIFT[1])); signature(g, clamp((f - SIGNATURE[0]) / (SIGNATURE[1] - SIGNATURE[0])), 0.75 - 0.15 * ramp(f, DING, 1245)); }, { alpha: 1 });
- g.paper("washGran", 0.05); g.paper("coldpress", 0.07);
-};
-
-// its flight through the last three stages, in finale-world coordinates
-const creatureWide = (f: number, cam: FCam) => {
- const off = 620, arrive = HOVER, end: P = [246, 648];
- let world: P, z: number, k: number;
- if (f < off) { /* the climb out of the clump, along the field: stage F keeps its move and loses its stop */
- const t = ease(clamp((f - 575) / 45));
- world = [540 + (POPPY[0] - 540) * t + Math.sin(t * Math.PI * 1.7) * 90, 760 + (POPPY[1] - 760) * t - Math.sin(t * Math.PI) * 120];
- z = 1.2 + 1.0 * t; k = 0.2 - 0.06 * t;
- } else { /* it turns and comes UP the field to the foreground, GROWING as the world shrinks */
- const t = ease(clamp((f - off) / (arrive - off)));
- z = 2.2 + (1.0 - 2.2) * t; /* the depth the spec asks for, kept short of the camera plane: the
- finale projector divides by (D + z) and turns inside out at z = -D, so the approach is carried
- by the creature's own scale rather than by flying it through the lens */
- k = 0.14 + (0.36 - 0.14) * t;
- world = [POPPY[0] + (end[0] - POPPY[0]) * t + Math.sin(t * Math.PI * 2.3) * 60, POPPY[1] + (end[1] - POPPY[1]) * t - Math.sin(t * Math.PI) * 70];
- if (f >= arrive) { const u = (f - arrive) / 60; world = [end[0] + Math.sin(u * Math.PI * 2) * 16, end[1] + Math.sin(u * Math.PI * 4) * 9 - (f - arrive) * 0.05]; k = 0.36; z = 1.0; } /* the approved still's position, hovering */
- }
- const pr = fprojector(cam, z), ph = (f % 10) / 10, flap = 0.6 + 0.4 * Math.cos(ph * Math.PI * 2);
- const scale = Math.max(0.105, k * pr.k); /* readability floor: below about 80 px of wingspan it stops being a butterfly and becomes a speck */
- return { at: pr.at(world), scale, perched: false, low: 0, sip: 0, probTo: undefined as P | undefined, flight: { pose: { flap, sweep: -0.03 }, heading: 0.1 * Math.sin(f * 0.05), pitch: 0.94, bank: 0.08 * Math.sin(f * 0.09) } as Flight };
-};
-// two REAL white butterflies lift out of the grass and spiral round it, then peel away
-const whites = (g: Gfx, f: number, cam: FCam) => {
- if (f < WHITES[0] || f > WHITES[1]) return;
- const pr = fprojector(cam, 1.6);
- for (let k = 0; k < 2; k++) {
- const t = (f - WHITES[0]) / (WHITES[1] - WHITES[0]), a = f * 0.08 + k * Math.PI;
- const w: P = [820 - t * 420 + Math.cos(a) * 60, 700 - t * 300 + Math.sin(a) * 40 - t * t * 260];
- const p = pr.at(w), s = 26 * pr.k * (1 - t * 0.3), fl = 0.4 + 0.6 * Math.abs(Math.cos(f * 0.32 + k));
- g.fill([[p[0] - s * fl, p[1] - s * 0.7], [p[0] - s * 0.1, p[1] - s * 0.2], [p[0] - s * 0.8 * fl, p[1] + s * 0.5]], "#fbf8ef", 0.85);
- g.fill([[p[0] + s * fl, p[1] - s * 0.7], [p[0] + s * 0.1, p[1] - s * 0.2], [p[0] + s * 0.8 * fl, p[1] + s * 0.5]], "#f4efe2", 0.8);
- g.fill([[p[0] - s * 0.09, p[1] - s * 0.34], [p[0] + s * 0.09, p[1] - s * 0.3], [p[0] + s * 0.06, p[1] + s * 0.3], [p[0] - s * 0.06, p[1] + s * 0.3]], "#6b6250", 0.7);
- }
-};
-
-// ---------------------------------------------------------------- the movement
-export const drawAlive = (ctx: Ctx, env: Env, f: number) => {
- if (f < HANDOVER[0]) return nearFrame(ctx, env, f);
- if (f >= HANDOVER[1]) return wideFrame(ctx, env, f);
- const t = ease((f - HANDOVER[0]) / (HANDOVER[1] - HANDOVER[0]));
- nearFrame(ctx, env, f);
- const dw = Math.round(env.W * env.scale), dh = Math.round(env.H * env.scale);
- let L = env.cache.get("alive:dissolve") as Layer | undefined;
- if (!L) { L = env.canvas(dw, dh); env.cache.set("alive:dissolve", L); }
- L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.globalAlpha = 1; L.ctx.globalCompositeOperation = "source-over"; L.ctx.clearRect(0, 0, dw, dh);
- wideFrame(L.ctx, env, f);
- ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = t; ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore();
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/perch.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/perch.ts
deleted file mode 100644
index b3a8983..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/perch.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-// BEATS 3 AND 4, THE RANUNCULUS CLOSE-UP. The heart of the film, held for six bars so it has
-// time to be believed. The camera only creeps and drifts sideways with the creature, stepping
-// back a little on each take-off; the creature lands, sips, and goes on to the next head.
-//
-// This composes stage R for any frame. The approval still is local 390: thirty frames after the
-// landing on R1, with the proboscis down in the tight green centre and the head still carrying
-// the dip it took when the creature arrived on it.
-import { Ctx, Env, Gfx, P, PENCIL } from "../../core";
-import { PAPER_F } from "../finale/compose";
-import { LANDINGS, SIPS, PROBOSCIS, TAKEOFFS } from "./cues";
-import { PAINTS, head } from "./ranunculus";
-
-export const LATERAL = ["R1", "R3"]; // spec 5.7: at least two of the four visits are the lateral figure
-import { CLUMP, R_LOOK, backGrass, backdrop, drawClump, fringe, nod, seedFluff } from "./meadow2";
-import { Cam, projector, scaleOf } from "./view";
-import { Flight, paintCreature } from "./wingpaint";
-import { drawLateral } from "./lateral";
-
-export const camAt = (f: number): Cam => ({ S: scaleOf(f), look: R_LOOK });
-
-// A visited head dips when the creature lands on it and rebounds when it leaves: stem bends about
-// six degrees, one settle, and nothing else in the clump moves with it.
-const dipOf = (f: number) => {
- const out: Record<string, number> = {};
- LANDINGS.forEach((l, i) => {
- const off = TAKEOFFS.find((t) => t > l.at) ?? 1e9;
- if (f < l.at || f > off + 30) return;
- const t = f - l.at;
- const settle = t < 12 ? 1.35 * (1 - Math.pow(1 - t / 12, 2)) : 1 + 0.35 * Math.cos((t - 12) * 0.34) * Math.exp(-(t - 12) / 14);
- out[l.flower] = f <= off ? settle : settle * Math.max(0, 1 - (f - off) / 24);
- });
- return out;
-};
-// It is never still. Wings fan on a 30-frame cycle at an amplitude of about a third, one side
-// leads the other, and the abdomen pulses once a beat: the tick has become a heartbeat.
-const perched = (f: number, landed: number): Flight => {
- const t = f - landed, fan = 0.5 - 0.5 * Math.cos((t / 30) * Math.PI * 2);
- return { pose: { flap: 1 - 0.35 * fan, sweep: -0.02 - 0.03 * fan }, heading: -2.35 + 0.05 * Math.sin(t * 0.08), pitch: 0.9, bank: 0.07 + 0.03 * Math.sin(t * 0.21) };
-};
-
-export type PerchState = { f: number; on: string };
-export const drawPerch = (ctx: Ctx, env: Env, f: number, on = "R1") => {
- const W = env.W, H = env.H, g = new Gfx(ctx, env, f, PENCIL), cam = camAt(f), c = ctx;
- c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = PAPER_F; c.fillRect(0, 0, W, H);
- g.paper("coldpress", 0.16);
- g.group("plain", () => backdrop(g, cam, W, H), { alpha: 1 });
- g.group("plain", () => backGrass(g, cam, 3.5, 4601, 46, 0.55, 0.06), { alpha: 0.9, blur: 3.4 }); /* aerial perspective is the only way distance reads in paint: paler, bluer, softer, no drawing */
- g.group("plain", () => backGrass(g, cam, 2.2, 4602, 40, 0.34, 0.08), { alpha: 0.92, blur: 2.2 });
- g.group("plain", () => backGrass(g, cam, 1.0, 4603, 32, 0.14, 0.1), { alpha: 0.95, blur: 1.1 });
-
- const land = LANDINGS.find((l) => l.flower === on), dips = dipOf(f);
- g.group("plain", () => drawClump(g, cam, f, { dip: dips, lean: 0.05 }), { alpha: 0.99 });
-
- // ---- the creature, perched on the head it landed on. Spec 5.7: at least two of the four
- // ranunculus visits are LATERAL, wings closed over the back, which is how a butterfly actually
- // sips and what a plate shows beside the dorsal figure. R1 and R3 are the two.
- const host = CLUMP.find((p) => p.id === on);
- if (host && land && f >= land.at) {
- const pr = projector(cam, host.z), hs = pr.at(host.at), R = host.R * pr.k;
- const dip = dips[on] ?? 0, n = nod(host.seed, f);
- const well: P = [hs[0] + (dip + n) * R * 0.12 - R * 0.02, hs[1] + (dip + n) * R * 0.1 + R * 0.11];
- const sip = SIPS.find(([a, b]) => f >= a - 20 && f <= b + 10);
- const p = sip ? Math.max(0, Math.min(1, (f - PROBOSCIS[0]) / (PROBOSCIS[1] - PROBOSCIS[0]))) : 0;
- const beat = 0.5 - 0.5 * Math.cos(((f - land.at) / 15) * Math.PI * 2); /* one soft pulse per beat while it sips: the heartbeat */
- if (LATERAL.includes(on)) {
- const at: P = [well[0] + R * 0.5, well[1] - R * 0.5];
- const grip: P[] = [[well[0] + R * 0.16, well[1] - R * 0.04], [well[0] + R * 0.42, well[1] + R * 0.06], [well[0] + R * 0.68, well[1] + R * 0.1]];
- g.group("plain", () => drawLateral(g, { at, scale: cam.S * (1 + beat * 0.008), face: -1, lean: 0.52 + 0.03 * Math.sin((f - land.at) * 0.07), open: 0.16 + 0.1 * (0.5 - 0.5 * Math.cos(((f - land.at) / 30) * Math.PI * 2)), proboscis: p, probTo: well, grip, seed: 900 }), { alpha: 0.98 });
- } else {
- const at: P = [well[0] + R * 0.42, well[1] - R * 0.56];
- g.group("plain", () => paintCreature(g, at, cam.S * (1 + beat * 0.008), perched(f, land.at), { proboscis: p, probTo: well, shadow: 1, shadowOff: [-0.8, 0.95], legs: 1, behind: PAINTS[host.v].mid, seed: 900 }), { alpha: 0.98 });
- }
- }
-
- g.group("plain", () => seedFluff(g, cam, f), { alpha: 0.7, blur: 1.4 });
- fringe(g, cam, 0.05);
- g.paper("washGran", 0.05); g.paper("coldpress", 0.07);
-};
-
-// ---------------------------------------------------------------- G-R, the study sheet
-// The five hand-authored views in three colours at full level of detail, which is the sheet a
-// painter would put on the wall before starting the picture. Nothing here is in the film.
-export const drawViews = (ctx: Ctx, env: Env) => {
- const W = env.W, H = env.H, g = new Gfx(ctx, env, 0, PENCIL), c = ctx;
- c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = PAPER_F; c.fillRect(0, 0, W, H);
- g.paper("coldpress", 0.18);
- const views = ["facing", "three", "profile", "half", "bud"] as const, cols = ["coral", "blush", "butter"] as const;
- const x0 = 118, y0 = 190, dx = 202, dy = 300;
- cols.forEach((v, row) => views.forEach((view, col) => {
- const at: P = [x0 + col * dx, y0 + row * dy], R = view === "bud" ? 52 : 86;
- g.group("paint", () => head(g, at, R, v, { view, tilt: (col - 2) * 0.09 + (row - 1) * 0.05, seed: 3000 + row * 41 + col * 7, reserve: false }), { alpha: 0.99 });
- }));
- g.paper("coldpress", 0.07);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/ranunculus.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/ranunculus.ts
deleted file mode 100644
index 74086d9..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/ranunculus.ts
+++ /dev/null
@@ -1,288 +0,0 @@
-// RANUNCULUS ASIATICUS, the Persian buttercup. Spec 6.1 is binding and it is a craft brief, not
-// a shape brief: the head is painted FROM THE CENTRE OUT as short overlapping C-strokes circling
-// a tight green button, each ring larger and looser than the last, with slivers of bare paper
-// LEFT between the strokes. Those slivers are the petal edges. There is no concentric scallop,
-// no mathematical spiral, and no ring of separate ovals anywhere in this file.
-//
-// PHOTOGRAPHS STUDIED before a point was moved (spec 6.1 asks which; these are the three I
-// actually opened, not a list from memory):
-// 1. Alamy HX5F8J, "close up of Ranunculus asiaticus petals opening": a macro straight into the
-// centre of a red-on-yellow bloom. What it settles: the centre is NOT a flat yellow button.
-// It is a dark green-black domed receptacle, finely stippled, with a pale green star at its
-// apex, sitting at the bottom of a WELL. The innermost whorl stands almost vertical around
-// that well as narrow creased strips; petals widen and flatten ring by ring outward; every
-// ring sits in the gaps of the one inside it; each petal carries a darker edge, and the
-// overlap between two petals reads as a bright hairline.
-// 2. TopTropicals `ranunculus_asiaticus3857`, a white bloom from above and slightly in front.
-// What it settles: the head is TWO ZONES, and this is the whole read. A broad outer SKIRT of
-// a few large, pale, nearly flat petals that reflex downward, and a much smaller, tighter,
-// GREEN-hearted inner cup raised inside it. Also: the foliage is dark, deeply cut and
-// parsley-like, and a bud on the same plant is a clasped green ball.
-// 3. BigCommerce "Wholesale Coral Ranunculus", one whole cut stem. What it settles: the
-// proportions. The stem runs about three and a half head-widths long, has its own S-curve,
-// thickens toward the base, swells green at the neck, carries its deeply cut leaves around
-// the middle of its length with a side bud on a short branch, and the head NODS a few
-// degrees off the stem's axis rather than sitting square on it.
-//
-// The head is built as real cup geometry, not as a flat pattern: a petal knows its radius, its
-// angle and its HEIGHT in the bowl, and the view is that bowl seen at an elevation. Which is why
-// the three-quarter view gets its stacked crescents and the profile gets its cup for free.
-import { Gfx, P, displace, jitter, oval, rng, sample, tube } from "../../core";
-import { lift } from "../finale/paint";
-
-export type View = "facing" | "three" | "profile" | "half" | "bud";
-export type Variety = "coral" | "blush" | "butter" | "magenta" | "peach";
-
-// Colour sets read off the references: a mid, a dark for the wells and the shadow side, a pale
-// for the lit rim of the skirt, and the edge tint that rides the outer margin (the picotee).
-type Paints = { mid: string; dark: string; pale: string; edge: string; heart: string };
-export const PAINTS: Record<Variety, Paints> = {
- coral: { mid: "#ee8a70", dark: "#cf5a3f", pale: "#f9c6b0", edge: "#d9603f", heart: "#dfa86a" },
- blush: { mid: "#f6ece4", dark: "#c9b4ac", pale: "#fffbf5", edge: "#e0819a", heart: "#e6dcab" }, // blush white with a pink picotee edge
- butter: { mid: "#f3d577", dark: "#d8a83c", pale: "#fbeeb6", edge: "#dfae3f", heart: "#c9c657" },
- magenta: { mid: "#b8417e", dark: "#7c2154", pale: "#d98cb0", edge: "#8d2a63", heart: "#c98f6a" },
- peach: { mid: "#f5b98a", dark: "#dd8a5f", pale: "#fbdcc0", edge: "#e0906a", heart: "#e2c37e" },
-};
-export const SEPAL = "#7d9a52", STEM_G = "#88a457", STEM_SHADE = "#5e7a42", LEAF = "#55713f", LEAF_LIT = "#7b9455";
-const BUTTON = "#b7c150", BUTTON_DARK = "#3f4a28", BUTTON_STAR = "#e6e6a6", WELL = "#6d7a42", PAPER = "#fbf7ee", COOL = "#8ea3c4";
-
-// Elevation of the camera above the flower's own plane, per view. 1 = straight down the throat,
-// 0 = edge on. Everything else about a view follows from this one number, the ring set and the
-// sepals: there is no per-view special casing of shape anywhere below.
-const ELEV: Record<View, number> = { facing: 0.95, three: 0.6, profile: 0.16, half: 0.82, bud: 0.5 };
-
-// The bowl, in units of the head radius: height above the rim plane at radius t. A deep dark well
-// at the centre, a crest about three quarters out where the skirt is widest, and only a SLIGHT
-// reflex past it. This one curve is what makes the three-quarter view stack its crescents and
-// the profile view sit up as a cup, so it is the shape of the flower and not a lighting trick.
-const bowl = (t: number): number => (t < 0.74 ? -0.70 + 0.80 * Math.pow(t / 0.74, 1.5) : 0.10 - 0.20 * Math.pow((t - 0.74) / 0.26, 1.7));
-
-// The rings, centre out. `r` is the fraction of the head radius the petal's MARGIN reaches, `n`
-// the count, `w` its tangential half-width as a multiple of the even spacing, `into` how far back
-// toward the centre it is attached, and `lift` how far it curls up out of the bowl.
-// The two zones are the whole read (reference 2): a HEART of many small tight greener petals, and
-// a SKIRT of a few big pale ones. A ranunculus with one uniform zone is a pompom.
-type Ring = { r: number; n: number; w: number; into: number; lift: number; heart: boolean };
-const RINGS: Ring[] = [
- { r: 0.62, n: 5, w: 1.38, into: 0.50, lift: 0.09, heart: false },
- { r: 0.76, n: 6, w: 1.34, into: 0.54, lift: 0.07, heart: false },
- { r: 0.89, n: 6, w: 1.34, into: 0.58, lift: 0.05, heart: false },
- { r: 1.00, n: 7, w: 1.32, into: 0.60, lift: 0.04, heart: false },
-];
-// A petal is a BLADE, not a fan: its inner edge is nearly as wide as its margin, because what
-// narrows a real petal toward its base is hidden behind the ring inside it. Fans that all
-// converge on the centre make a pinwheel, and a pinwheel is a mathematical spiral with extra
-// steps. What breaks the four rings up instead is that no petal is the same size as its
-// neighbour and none of them sits at quite the radius its ring says.
-// The HEART is not rings. Concentric annuli of petals nest into a moulded shell, which is the
-// scalloped-circle failure the spec rejects on sight. A real heart is a ROLLED WHORL: broad
-// crescents that each wrap a third of the way round the centre, overlapping like a rose, laid
-// biggest and lowest first and finishing on the small upright ones standing over the button.
-// These twelve turn offsets are HAND PLACED, not a golden angle and not a step: no two gaps
-// between consecutive petals are the same, which is what stops the eye finding the rule.
-const TURNS = [0, 0.41, 0.77, 0.19, 0.6, 0.93, 0.33, 0.7, 0.08, 0.52, 0.86, 0.26];
-// A half-open bloom has not let its skirt down yet: the outer rings are still drawn in and stood
-// up round the green heart, so what you see is a cup closing rather than a disc.
-const halfOpen = (rg: Ring): Ring => (rg.heart ? { ...rg, lift: rg.lift + 0.06 } : { ...rg, r: rg.r * 0.66, lift: rg.lift + 0.34, w: rg.w * 0.96, into: rg.into * 0.8 });
-
-const mix = (a: string, b: string, t: number) => { const h = (x: string) => [parseInt(x.slice(1, 3), 16), parseInt(x.slice(3, 5), 16), parseInt(x.slice(5, 7), 16)]; const A = h(a), B = h(b); return "#" + A.map((v, i) => Math.round(v + (B[i] - v) * Math.max(0, Math.min(1, t))).toString(16).padStart(2, "0")).join(""); };
-
-// A C-STROKE. The core's `wash` wobbles every outline by an ABSOLUTE thirteen units, which is
-// right for a wing panel three hundred units across and turns a twenty-pixel petal into porridge.
-// A petal therefore gets its own wash, wobbled in proportion to its own width, so a small one
-// keeps the crisp dried edge that makes the stack of tissue read.
-const cstroke = (g: Gfx, pts: P[], col: string, alpha: number, seed: number, w: number) => {
- const s = displace(sample(jitter(pts, w * 0.035, seed), true, 4), w * 0.07, 1.7 / Math.max(3, w), 2, (seed % 89) + 3);
- g.fill(s, col, alpha);
- return s;
-};
-
-// One head. `R` is its radius ON SCREEN, `tilt` the nod off the stem's axis in radians, and the
-// sun is upper right, so the lit side of every petal is the side facing about -0.9 rad.
-export type HeadOpts = { view?: View; tilt?: number; seed?: number; reserve?: boolean; dip?: number };
-export const head = (g: Gfx, at: P, R: number, v: Variety, o: HeadOpts = {}) => {
- const view = o.view ?? "facing", seed = o.seed ?? 1, r = rng(seed), C = PAINTS[v], tilt = (o.tilt ?? 0) + (o.dip ?? 0) * 0.16;
- if (view === "bud") return budHead(g, at, R, v, seed, tilt);
- // ---- level of detail, spec 6.1. Below these sizes a painter stops drawing the flower and
- // starts putting down what the flower does to the picture: two tones, then one dab.
- if (R < 7) { g.fill(oval(at[0], at[1], R * 1.15, R * 0.95, 8), C.mid, 0.8); return; }
- if (R < 20) { g.fill(oval(at[0] - R * 0.22, at[1] + R * 0.24, R * 1.05, R * 0.86, 9), C.dark, 0.5); g.fill(oval(at[0], at[1], R * 1.1, R * 0.92, 9), C.mid, 0.9); g.fill(oval(at[0], at[1], R * 0.28, R * 0.24, 7), mix(BUTTON, WELL, 0.4), 0.85); return; }
- const set = (R < 60 ? [RINGS[0], RINGS[2], RINGS[3]] : RINGS).map((rg) => (view === "half" ? halfOpen(rg) : rg)); // 40 to 120 px: three rings of strokes and the button
-
- const e = ELEV[view], ce = Math.sqrt(Math.max(0, 1 - e * e)), ct = Math.cos(tilt), st = Math.sin(tilt);
- // bowl point -> screen. X across, Y away from the camera, Z up out of the cup, then the nod.
- const T = (ang: number, rad: number, z: number): P => {
- const X = Math.cos(ang) * rad, Y = Math.sin(ang) * rad, sy = -(Y * e + z * ce);
- return [at[0] + (X * ct - sy * st) * R, at[1] + (X * st + sy * ct) * R];
- };
- if (view === "profile" || view === "half") sepals(g, T, R, seed, view === "profile" ? 1 : 0.5);
- const edgeR = set[set.length - 1].r;
- if (o.reserve !== false) { const sil: P[] = []; for (let i = 0; i < 20; i++) { const a = (i / 20) * Math.PI * 2; sil.push(T(a, edgeR * 0.93, bowl(edgeR) + 0.02)); } g.fill(jitter(sil, R * 0.03, seed + 1), PAPER, 0.5); } /* the paper is LEFT for it: a wash over white glows, a wash over green does not */
-
- const ring = (rg: Ring, i: number) => {
- const t = rg.r, phase = r() * Math.PI * 2, step = (Math.PI * 2) / rg.n, half = step * 0.5 * rg.w;
- const zIn = bowl(t * rg.into), zOut = bowl(t) + rg.lift, outermost = i === set.length - 1;
- const pw = 2 * half * t * R; /* the petal's own width on screen: everything wobbles in proportion to this */
- const petals = Array.from({ length: rg.n }, (_, k) => phase + k * step + (r() - 0.5) * step * 0.22);
- petals.sort((a, b) => T(a, t, zOut)[1] - T(b, t, zOut)[1]); /* the far side of the bowl is behind the near side */
- petals.forEach((a, k) => {
- const lit = 0.5 + 0.5 * Math.cos(a + 0.9 - tilt), s2 = seed + i * 31 + k * 7, rr = rng(s2);
- const ruf = 0.03 + rr() * 0.045, skew = (rr() - 0.5) * 0.3, notch = outermost ? 0.045 + rr() * 0.04 : 0, size = 0.82 + rr() * 0.38, shove = (rr() - 0.5) * 0.13; /* hand-placed: no two petals in a ring reach the same distance, so the margin is never a circle */ /* one side always leads, and the big outer petals are notched at the top */
- const N = 9, outer: P[] = [], band: P[] = [];
- for (let q = 0; q < N; q++) {
- const u = q / (N - 1), ang = a + (u - 0.5) * 2 * half * (1 + skew * (u - 0.5));
- const rad = t * size + t * shove + t * size * (ruf * Math.sin(u * Math.PI * 2.2 + s2) - notch * Math.exp(-Math.pow((u - 0.5) * 4, 2)));
- outer.push(T(ang, rad, zOut)); band.push(T(ang, rad * 0.86, zOut * 0.95));
- }
- const inner: P[] = []; for (let q = 3; q >= 0; q--) { const u = q / 3, ang = a + (u - 0.5) * 2 * half * 0.84; inner.push(T(ang, (t * size + t * shove) * rg.into, zIn)); }
- // Value. The heart is CREAM AND GREEN, lighter than the throat it stands in, which is the
- // only way the tight inner whorl reads as petals instead of one dark mass; the dark in the
- // heart is the throat showing between the strokes, never paint on the strokes themselves.
- const vary = (rr() - 0.5) * 0.2; /* no two petals in a ring are the same value: that is what stops a ring reading as one moulded shell */
- const base = rg.heart ? mix(mix(C.pale, C.heart, 0.5 + vary), BUTTON_STAR, 0.24 - t * 0.35) : mix(C.mid, C.pale, (t - 0.5) * 0.95 + lit * 0.42 + vary);
- const col = mix(base, C.dark, (1 - lit) * (rg.heart ? 0.3 : 0.38) + Math.max(0, vary));
- cstroke(g, [...outer, ...inner], col, rg.heart ? 0.93 : 0.9, s2, pw);
- /* a petal is darker where it folds down into the cup and paler at the margin the light hits:
- one more stroke on the inner half, not a gradient */
- const half2: P[] = []; for (let q = 0; q < N; q++) { const u = q / (N - 1), ang = a + (u - 0.5) * 2 * half * 0.9; half2.push(T(ang, (t * size + t * shove) * (rg.into + (1 - rg.into) * 0.42), (zIn + zOut) / 2)); }
- cstroke(g, [...half2, ...inner], mix(col, rg.heart ? WELL : C.dark, rg.heart ? 0.4 : 0.3), rg.heart ? 0.72 : 0.5, s2 + 2, pw * 0.7);
- /* pigment settles where the water stopped: a darker rim along the outer margin only, which
- is a dried edge and not an outline, because it never goes round the sides */
- g.fill(tube(outer.slice(1, N - 1), pw * 0.025, pw * 0.012, false), mix(col, C.dark, 0.55), 0.34 + (1 - lit) * 0.2);
- /* and the shadow the petal in front throws on it: this is what opens the stack up */
- g.fill(tube([T(a + (skew > 0 ? -half : half) * 0.92, t * 0.62, (zIn + zOut) / 2), outer[skew > 0 ? 0 : N - 1]], pw * 0.045, pw * 0.014, false), mix(col, WELL, 0.38), 0.26);
- if (R > 50 && !rg.heart) { const crease = [T(a, t * rg.into, zIn), T(a + skew * 0.12, t * 0.82, (zIn + zOut) / 2), T(a, t * 0.96, zOut)]; g.fill(tube(crease, pw * 0.012, pw * 0.005, false), mix(col, C.dark, 0.4), 0.2); }
- /* the picotee: a BAND of colour along the outer margin, which is what a picotee is. Every
- other variety gets the same band, quieter, as the colour its own margin dries to. */
- if (outermost && R > 40) cstroke(g, [...outer, ...band.slice().reverse()], C.edge, v === "blush" ? 0.55 : 0.25, s2 + 11, pw);
- });
- };
-
- for (let i = set.length - 1; i >= 0; i--) ring(set[i], i); /* the skirt was laid first and let dry */
- // the THROAT: the darkest value in the picture of this flower, and it goes UNDER the heart so
- // that what shows between the tight inner petals is depth rather than paper
- const cz = bowl(0), c0 = T(0, 0.001, cz), well: P[] = []; for (let i = 0; i < 14; i++) { const a = (i / 14) * Math.PI * 2; well.push(T(a, 0.42, bowl(0.42))); }
- cstroke(g, well, mix(C.dark, WELL, 0.22), 0.6, seed + 600, R * 0.75);
- cstroke(g, well.map((p) => [at[0] + (p[0] - at[0]) * 0.6, at[1] + (p[1] - at[1]) * 0.6] as P), mix(C.dark, "#4a4426", 0.45), 0.55, seed + 602, R * 0.45);
- whorl(g, T, R, C, seed, tilt, R >= 60 ? 9 : 5, view === "half" ? 0.78 : 1);
-
- // ---- the centre. A domed receptacle at the bottom of the well, finely stippled, with a pale
- // star at its apex and a ring of stamens round its foot (reference 1). Never a flat button.
- const cr = R * 0.08;
- if (R > 30 && view !== "profile") {
- const green = view === "half" ? mix(BUTTON, WELL, 0.68) : mix(BUTTON, WELL, 0.3);
- cstroke(g, oval(c0[0], c0[1], cr * 1.3, cr * (0.36 + e * 0.8), 11), green, 0.94, seed + 610, cr * 2);
- cstroke(g, oval(c0[0] - cr * 0.3, c0[1] + cr * 0.38, cr * 0.9, cr * 0.46 * (0.36 + e * 0.7), 10), mix(BUTTON_DARK, WELL, 0.45), 0.5, seed + 615, cr * 1.6);
- if (R > 60) {
- g.fill(oval(c0[0] + cr * 0.06, c0[1] - cr * 0.14, cr * 0.32, cr * 0.26 * (0.4 + e * 0.6), 9), BUTTON_STAR, 0.78);
- const rs = rng(seed + 620), n = view === "half" ? 8 : 18;
- for (let k = 0; k < n; k++) { const a = rs() * Math.PI * 2, d = cr * (1.4 + rs() * 0.55), p: P = [c0[0] + Math.cos(a) * d, c0[1] + Math.sin(a) * d * (0.3 + e * 0.65)]; g.fill(oval(p[0], p[1], R * 0.0075, R * 0.006, 6), BUTTON_DARK, 0.5 + rs() * 0.34); }
- }
- }
- // ---- one cool wash over the side away from the sun, laid as an annulus that hugs the rim, so
- // it never puts a chord across the middle of the flower. No outline anywhere on the head.
- for (let pass = 0; pass < 2; pass++) {
- const a0 = 1.15 + pass * 0.3, a1 = a0 + Math.PI * (0.95 - pass * 0.18), out: P[] = [], inn: P[] = [];
- for (let i = 0; i <= 8; i++) { const a = a0 + (i / 8) * (a1 - a0); out.push(T(a, edgeR * 0.98, bowl(edgeR))); inn.push(T(a, edgeR * (0.44 + pass * 0.2), bowl(0.55))); }
- cstroke(g, [...out, ...inn.reverse()], COOL, 0.09, seed + 700 + pass, R * 1.2);
- }
- g.fill(oval(at[0] - R * 0.5, at[1] + R * (0.38 + 0.4 * e), R * 0.62, R * 0.13, 9), "#6d7f55", 0.11); /* the dab of shadow it throws below itself */
-};
-
-// The rolled heart. Each crescent knows its radius, how far round it wraps, and how high it
-// stands, so the three-quarter view stacks it into the overlapping arcs the reference shows and
-// the facing view rolls it into a cone. The darkness between them is the throat, not paint.
-const whorl = (g: Gfx, T: (a: number, r: number, z: number) => P, R: number, C: Paints, seed: number, tilt: number, n: number, squeeze: number) => {
- const r0 = rng(seed + 900), phase = r0();
- for (let k = n - 1; k >= 0; k--) {
- const u = n > 1 ? k / (n - 1) : 1, rr = rng(seed + 910 + k * 13);
- const t = (0.26 + 0.2 * Math.pow(u, 0.7) + (rr() - 0.5) * 0.09) * squeeze; /* a tight rosette of crescents at nearly one radius, each with its own reach: a monotone radius against a turning angle is a nautilus */
- const a = (TURNS[k % TURNS.length] + phase) * Math.PI * 2 + (rr() - 0.5) * 0.34;
- const half = 0.78 + 0.28 * u + (rr() - 0.5) * 0.26; /* it wraps between a third and a half of the way round */
- const zOut = bowl(t) + 0.3 * (1 - u) + 0.06, zIn = bowl(t * 0.5) + 0.34 * (1 - u);
- const lit = 0.5 + 0.5 * Math.cos(a + 0.9 - tilt), vary = (rr() - 0.5) * 0.22;
- const N = 11, outer: P[] = [], free: P[] = [], inner: P[] = [];
- for (let q = 0; q < N; q++) { const w = q / (N - 1), ang = a + (w - 0.5) * 2 * half, rad = t * (1 + 0.05 * Math.sin(w * 5.1 + k) - 0.07 * Math.pow(Math.abs(w - 0.5) * 2, 3)); outer.push(T(ang, rad, zOut)); free.push(T(ang, rad * 0.9, zOut * 0.99)); }
- for (let q = 4; q >= 0; q--) { const w = q / 4, ang = a + (w - 0.5) * 2 * half * 0.86; inner.push(T(ang, t * 0.5, zIn)); }
- const pw = 2 * half * t * R;
- const body = mix(mix(C.pale, C.mid, 0.46 + vary), BUTTON_STAR, Math.max(0, 0.38 * (1 - t / 0.22))); /* it keeps the flower's own hue and only goes green in the last few petals over the button */
- const col = mix(body, C.dark, (1 - lit) * 0.26 + Math.max(0, vary * 0.8));
- cstroke(g, [...outer, ...inner], col, 0.94, seed + 920 + k, pw);
- cstroke(g, [...inner, ...inner.map((p) => p).reverse().slice(0, 1), ...free.slice(2, N - 2).reverse()], mix(col, WELL, 0.42), 0.6, seed + 930 + k, pw * 0.8); /* the shade where it folds down into the throat */
- g.fill(tube(outer.slice(1, N - 1), pw * 0.022, pw * 0.01, false), mix(col, C.dark, 0.5), 0.3); /* pigment dried along the free edge */
- lift(g, tube(free.slice(2, N - 2), pw * 0.02, pw * 0.009, false), seed + 940 + k, 0.34); /* and the light sitting on the fold just inside it */
- }
-};
-
-// the green sepals a cup sits in, reflexed beneath it: only ever seen from the side
-const sepals = (g: Gfx, T: (a: number, r: number, z: number) => P, R: number, seed: number, amt: number) => {
- const r = rng(seed + 77);
- for (let i = 0; i < 3; i++) {
- const a = -0.35 + (i / 2) * (Math.PI + 0.7) + (r() - 0.5) * 0.18;
- const base = T(a, 0.2, bowl(0.2) - 0.14), mid = T(a, 0.66, bowl(0.66) - 0.22 * amt), tip = T(a, 0.94, bowl(0.94) - 0.34 * amt);
- g.fill(tube([base, mid, tip], R * 0.075, R * 0.025, false), i === 1 ? SEPAL : STEM_SHADE, 0.88); /* broad straps that lie under the cup, not legs */
- }
-};
-
-// A BUD: a tight green ovoid clasped by sepals that hug it and flick out at their tips, nodding
-// on its own stalk, with the first sliver of the petal colour showing at the crown. Every
-// reference carries one on the plant, so the clump does too.
-const budHead = (g: Gfx, at: P, R: number, v: Variety, seed: number, tilt: number) => {
- const C = PAINTS[v], r = rng(seed), ct = Math.cos(tilt), st = Math.sin(tilt);
- const T = (x: number, y: number): P => [at[0] + (x * ct - y * st) * R, at[1] + (x * st + y * ct) * R];
- if (R < 6) { g.fill(oval(at[0], at[1], R, R * 1.1, 7), SEPAL, 0.85); return; }
- const ball = jitter([...Array(13)].map((_, i) => { const a = (i / 13) * Math.PI * 2; return T(Math.cos(a) * 0.8, Math.sin(a) * 1.0 - 0.08); }), R * 0.045, seed);
- g.fill(ball, PAPER, 0.92);
- g.wash(ball, mix(C.pale, SEPAL, 0.5), { alpha: 0.8, seed, shrink: 0.95, rim: true });
- g.wash(ball.map((p) => [p[0] - R * 0.22, p[1] + R * 0.2] as P), STEM_SHADE, { alpha: 0.32, seed: seed + 4, shrink: 0.8, rim: false });
- /* the sepals do not radiate: they lie ON the bud from its foot and only their points leave it */
- for (let i = 0; i < 5; i++) {
- const a = -2.5 + i * 0.78 + (r() - 0.5) * 0.22, w = Math.cos(a), h = Math.sin(a);
- const foot = T(w * 0.18, 0.86), mid = T(w * 0.62, 0.86 - Math.abs(h) * 0.7), tip = T(w * 1.02, 0.5 - h * 0.66);
- g.fill(tube([foot, mid, tip], R * 0.15, R * 0.025, false), i % 2 ? SEPAL : STEM_SHADE, 0.88);
- }
- if (R > 16) { g.wash([T(-0.34, -0.86), T(0.1, -1.02), T(0.4, -0.78), T(0.0, -0.66)], C.mid, { alpha: 0.5, seed: seed + 8, shrink: 0.9, rim: true }); } /* the first sliver of colour, breaking out at the crown */
-};
-
-// ---------------------------------------------------------------- stem, leaves, the whole plant
-// Every stem gets its OWN S-curve and thickness. Nothing here is straight (rejected on sight).
-export const stem = (g: Gfx, root: P, neck: P, w: number, seed: number, lean = 0) => {
- const r = rng(seed), dx = neck[0] - root[0], dy = neck[1] - root[1], len = Math.hypot(dx, dy) || 1, nx = -dy / len, ny = dx / len;
- const bow = (0.05 + r() * 0.07) * len * (r() > 0.5 ? 1 : -1) + lean * len * 0.1, bow2 = -bow * (0.3 + r() * 0.4);
- const spine: P[] = [root, [root[0] + dx * 0.32 + nx * bow, root[1] + dy * 0.32 + ny * bow], [root[0] + dx * 0.7 + nx * bow2, root[1] + dy * 0.7 + ny * bow2], neck];
- g.fill(tube(spine, w * 1.2, w * 0.7, false), STEM_SHADE, 0.62);
- g.fill(tube(spine.map((p) => [p[0] - w * 0.34, p[1]] as P), w * 0.8, w * 0.44, false), STEM_G, 0.82); /* a stem is a cylinder: a shadow side, a lit side and the paper between them */
- for (let i = 0; i < 5; i++) { const t = 0.15 + i * 0.18, p: P = [root[0] + dx * t + nx * bow * Math.sin(t * Math.PI), root[1] + dy * t + ny * bow * Math.sin(t * Math.PI)]; g.fill(oval(p[0] + w * 0.5, p[1], w * 0.16, w * 0.5, 6), mix(STEM_G, PAPER, 0.5), 0.3); } /* faintly hairy: the light catches down one side */
- g.fill(tube([[neck[0] - w * 0.8, neck[1] + w * 1.6], [neck[0], neck[1] + w * 0.2]], w * 1.5, w * 1.1, false), SEPAL, 0.8); /* the green swell at the neck */
- return spine;
-};
-// A leaf: basal, deeply cut, parsley-like. Three lobes, each lobe notched twice, never a blob.
-export const leaf = (g: Gfx, at: P, len: number, ang: number, seed: number, alpha = 0.9) => {
- const r = rng(seed), pts: P[] = [], lobes = 3;
- const put = (d: number, off: number) => { const a = ang + off; pts.push([at[0] + Math.cos(a) * d, at[1] + Math.sin(a) * d]); };
- put(len * 0.1, -0.1);
- for (let i = 0; i < lobes; i++) { const o = (i / (lobes - 1) - 0.5) * 1.5; put(len * (0.42 + r() * 0.12), o * 1.25); put(len * (0.86 + r() * 0.2), o * 0.95); put(len * (0.6 + r() * 0.12), o * 0.72); put(len * (0.92 + r() * 0.14), o * 0.5); put(len * (0.52 + r() * 0.1), o * 0.3); }
- put(len * 0.12, 0.1);
- g.wash(pts, LEAF, { alpha: alpha * 0.85, seed, dx: 1, dy: 1, shrink: 0.94, rim: true });
- g.wash(pts.map((p) => [at[0] + (p[0] - at[0]) * 0.72 - len * 0.05, at[1] + (p[1] - at[1]) * 0.72 - len * 0.04] as P), LEAF_LIT, { alpha: alpha * 0.4, seed: seed + 5, shrink: 0.9, rim: false });
- g.fill(tube([at, [at[0] + Math.cos(ang) * len * 0.5, at[1] + Math.sin(ang) * len * 0.5]], len * 0.03, len * 0.015, false), LEAF_LIT, 0.5);
-};
-// the dark ferny mass a clump sits in: leaves at the foot, smaller and cooler as they go back
-export const basalLeaves = (g: Gfx, at: P, spread: number, seed: number, n = 7) => {
- const r = rng(seed), set: { p: P; L: number; a: number; s: number }[] = [];
- for (let i = 0; i < n; i++) { const t = (i / (n - 1) - 0.5) * 2; set.push({ p: [at[0] + t * spread * 0.55 + (r() - 0.5) * spread * 0.14, at[1] + (r() - 0.5) * spread * 0.1], L: spread * (0.2 + r() * 0.2), a: -Math.PI / 2 + t * 0.95 + (r() - 0.5) * 0.3, s: seed + i * 13 }); }
- set.sort((a, b) => a.p[1] - b.p[1]).forEach((s, i) => leaf(g, s.p, s.L, s.a, s.s, 0.55 + (i / n) * 0.4));
-};
-
-// ---------------------------------------------------------------- a whole plant at one position
-export type Plant = { at: P; R: number; v: Variety; view: View; tilt: number; stemLen: number; seed: number; sideBud?: number };
-export const plant = (g: Gfx, pl: Plant, k: number, dip = 0, lean = 0) => {
- const R = pl.R * k, w = Math.max(0.7, R * 0.05), neck: P = [pl.at[0], pl.at[1] + R * 0.86];
- const root: P = [neck[0] - pl.stemLen * k * lean * 0.5, neck[1] + pl.stemLen * k];
- if (R > 5) {
- stem(g, root, [neck[0] + dip * R * 0.2, neck[1] + dip * R * 0.1], w, pl.seed + 3, lean);
- if (R > 22) { const r = rng(pl.seed + 9), ly = 0.45 + r() * 0.2, at: P = [root[0] + (neck[0] - root[0]) * ly, root[1] + (neck[1] - root[1]) * ly]; leaf(g, at, R * 0.62, r() > 0.5 ? -0.5 : Math.PI + 0.5, pl.seed + 11, 0.85); }
- if (pl.sideBud !== undefined && R > 18) { const b: P = [neck[0] + Math.cos(pl.sideBud) * R * 1.35, neck[1] + R * 0.5 + Math.sin(pl.sideBud) * R * 0.7]; g.fill(tube([[neck[0], neck[1] + R * 0.5], b], w * 0.9, w * 0.5, false), STEM_G, 0.85); head(g, b, R * 0.3, pl.v, { view: "bud", seed: pl.seed + 17, tilt: pl.sideBud * 0.4 }); }
- }
- head(g, [pl.at[0] + dip * R * 0.12, pl.at[1] + dip * R * 0.1], R, pl.v, { view: pl.view, tilt: pl.tilt + dip * 0.1 + lean * 0.3, seed: pl.seed, dip });
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/score.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/score.ts
deleted file mode 100644
index 82bec78..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/score.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-// THE SCORE (spec section 8, rewritten on note: a real piece, not a sound design pass).
-// Pure maths into two Float32Arrays. No Web Audio, no samples, no Node: as deterministic as the
-// picture, and it runs under any backend.
-//
-// ONE THEME carries the whole film, and the whole film is in a MAJOR key. The note was: it was
-// reading sad and eerie, which was the minor mode doing exactly what the minor mode does. Act 1 is
-// curious and mechanical but SUNNY: a music box in C major, sparse and bright, which ends on the
-// dominant so the question is still open without ever being mournful. The come-alive warms it with
-// a harp and a low pad; the bloom opens it out; the meadow answers it home. Nothing anywhere is
-// minor except two passing chords that make the major ones taste sweeter.
-//
-// frames 0-540 C major Act 1. Music box and a clockwork ostinato, ending open on G
-// frames 540-1200 C major the come-alive and the bloom: harp, warm pad, a counter-line
-// frame 1200 C MAJOR the meadow. Plagal turn, perfect cadence, DING on 1365
-import { DING, LANDINGS, SIPS, TAKEOFFS } from "./cues";
-
-const OFF = 540, FPS = 30, BEAT = 15, BAR = 60;
-export const atFrame = (filmFrame: number, sr: number) => Math.round((filmFrame / FPS) * sr);
-
-const HZ: Record<string, number> = {
- C2: 65.41, G2: 98.0, Ab2: 103.83, Bb2: 116.54, C3: 130.81, D3: 146.83, Eb3: 155.56, E3: 164.81, F3: 174.61, G3: 196.0, Ab3: 207.65, A3: 220.0, Bb3: 233.08,
- C4: 261.63, D4: 293.66, Eb4: 311.13, E4: 329.63, F4: 349.23, G4: 392.0, Ab4: 415.3, A4: 440.0, Bb4: 466.16, B4: 493.88,
- C5: 523.25, D5: 587.33, Eb5: 622.25, E5: 659.25, F5: 698.46, G5: 784.0, Ab5: 830.61, A5: 880.0, Bb5: 932.33, C6: 1046.5, Eb6: 1244.51, G6: 1568.0,
-};
-// root, and the triad over it. The harmony is a real progression, not a drone.
-const CHORD: Record<string, [string, string[]]> = {
- C: ["C3", ["C4", "E4", "G4"]], F: ["F3", ["F4", "A4", "C5"]], G: ["G3", ["G4", "B4", "D5"]],
- Am: ["A3", ["A4", "C5", "E5"]], Dm: ["D3", ["D4", "F4", "A4"]], C2nd: ["C3", ["D4", "E4", "G4"]],
-};
-// film frame -> chord. The meadow lands on C MAJOR exactly on 1410, which is local 870.
-const PROG: [number, string][] = [
- [0, "C"], [120, "F"], [180, "G"], [240, "C"], [300, "Am"], [360, "F"], [420, "G"],
- [540, "C"], [600, "F"], [660, "C2nd"], [720, "G"], [780, "C"], [840, "F"], [900, "Dm"],
- [960, "G"], [1020, "C"], [1080, "F"], [1140, "G"],
- [1200, "C"], [1260, "F"], [1320, "Am"], [1350, "G"], [1365, "C"],
-];
-const chordAt = (f: number) => { let c = PROG[0][1]; for (const [s, ch] of PROG) if (f >= s) c = ch; return c; };
-
-// THE THEME: eight notes, in semitones above the tonic, with its rhythm in beats. The only
-// difference between the minor statement and the major answer is the third.
-const THEME_MAJ = [0, 4, 7, 5, 4, 0, 2, 4]; // the only mode this film is in
-const RHYTHM = [1, 1, 2, 1, 1, 2, 1, 3];
-
-export const aliveScore = (frames: number) => (sr: number): [Float32Array, Float32Array] => {
- const n = Math.ceil((frames / FPS) * sr), L = new Float32Array(n), R = new Float32Array(n);
- const put = (i0: number, len: number, fn: (t: number) => number, pan: number, gain: number) => {
- for (let i = 0; i < len; i++) { const j = i0 + i; if (j < 0 || j >= n) continue; const v = fn(i / sr) * gain; L[j] += v * (1 - pan); R[j] += v * pan; }
- };
- // ---- the instruments. Each one is a different way of making a note start and stop, which is
- // all an instrument is once you have the harmony right.
- const box = (fr: number, hz: number, g = 0.3, pan = 0.5, ring = 2.2) => put(atFrame(fr, sr), Math.floor(ring * sr), (t) => {
- const e = Math.exp(-t * 2.8) * Math.min(1, t * 900);
- return (Math.sin(6.283 * hz * t) + 0.4 * Math.sin(6.283 * hz * 2.76 * t) * Math.exp(-t * 6) + 0.18 * Math.sin(6.283 * hz * 5.4 * t) * Math.exp(-t * 11)) * e * 0.5;
- }, pan, g);
- const harp = (fr: number, hz: number, g = 0.22, pan = 0.5, ring = 2.6) => put(atFrame(fr, sr), Math.floor(ring * sr), (t) => {
- const e = Math.exp(-t * 1.9) * Math.min(1, t * 500);
- return (Math.sin(6.283 * hz * t) + 0.34 * Math.sin(6.283 * hz * 2 * t) * Math.exp(-t * 3) + 0.14 * Math.sin(6.283 * hz * 3 * t) * Math.exp(-t * 5)) * e * 0.5;
- }, pan, g);
- const pad = (fr: number, hz: number, lenFr: number, g = 0.1, pan = 0.5) => { const len = Math.floor((lenFr / FPS) * sr); put(atFrame(fr, sr), len, (t) => {
- const u = t / (len / sr), e = Math.min(1, u * 5) * Math.min(1, (1 - u) * 4), vib = 1 + 0.0016 * Math.sin(6.283 * 4.2 * t);
- let v = Math.sin(6.283 * hz * t * vib) * 1.5; for (let k = 2; k <= 4; k++) v += Math.sin(6.283 * hz * k * t * vib) / (k * k * 0.85);
- return v * e * 0.26;
- }, pan, g); };
- const bass = (fr: number, hz: number, lenFr: number, g = 0.16) => { const len = Math.floor((lenFr / FPS) * sr); put(atFrame(fr, sr), len, (t) => {
- const u = t / (len / sr), e = Math.min(1, u * 8) * Math.min(1, (1 - u) * 3);
- return (Math.sin(6.283 * hz * t) + 0.3 * Math.sin(6.283 * hz * 2 * t) + 0.12 * Math.sin(6.283 * hz * 3 * t)) * e * 0.42;
- }, 0.5, g); };
- const bell = (fr: number, hz: number, g = 0.3) => put(atFrame(fr, sr), Math.floor(4.5 * sr), (t) => {
- const e = Math.exp(-t * 1.0) * Math.min(1, t * 700);
- return (Math.sin(6.283 * hz * t) + 0.5 * Math.sin(6.283 * hz * 2.0 * t) * Math.exp(-t * 1.6) + 0.3 * Math.sin(6.283 * hz * 2.76 * t) * Math.exp(-t * 2.4) + 0.16 * Math.sin(6.283 * hz * 5.4 * t) * Math.exp(-t * 4)) * e * 0.5;
- }, 0.5, g);
- const tick = (fr: number, g: number) => put(atFrame(fr, sr), Math.floor(0.04 * sr), (t) => (Math.sin(6.283 * 2100 * t) * 0.55 + Math.sin(6.283 * 3300 * t) * 0.45) * Math.exp(-t * 170), 0.46, g);
- const flutter = (fr: number, g: number, sd: number) => { let s = (sd * 2654435761) >>> 0; put(atFrame(fr, sr), Math.floor(0.15 * sr), (t) => { s = (s * 1664525 + 1013904223) >>> 0; return ((s / 4294967296) * 2 - 1) * Math.exp(-t * 24) * (0.35 + 0.65 * Math.sin(6.283 * 95 * t)); }, 0.5, g); };
- const water = (fr: number, g: number) => put(atFrame(fr, sr), Math.floor(0.6 * sr), (t) => Math.sin(6.283 * (600 + 850 * t) * t) * Math.exp(-t * 6.5) * Math.min(1, t * 500), 0.52, g);
- const heart = (fr: number, g: number) => put(atFrame(fr, sr), Math.floor(0.36 * sr), (t) => (Math.sin(6.283 * 56 * t) + 0.4 * Math.sin(6.283 * 112 * t)) * Math.exp(-t * 8.5) * Math.min(1, t * 180), 0.5, g);
-
- const semis = (hz: number, s: number) => hz * Math.pow(2, s / 12);
- // one statement of the theme, on whatever instrument and in whichever mode
- const theme = (start: number, tonic: number, major: boolean, voice: (fr: number, hz: number, g: number, pan: number) => void, g: number, stretch = 1, pan = 0.5) => {
- const T = THEME_MAJ; let fr = start;
- T.forEach((s, i) => { voice(fr, semis(tonic, s), g * (i === 0 || i === 2 ? 1 : 0.82), pan + (i % 2 ? 0.06 : -0.06)); fr += RHYTHM[i] * BEAT * stretch; });
- return fr;
- };
-
- // ================================================================ ACT 1: curious, mechanical
- // A clockwork ostinato under a music box, and the theme stated twice in C minor. The act ends
- // on the DOMINANT and stays there: the question the whole rest of the film answers.
- for (let f = 0; f < 540; f += BEAT / 2) { const ch = CHORD[chordAt(f)][1], k = (f / (BEAT / 2)) % 3; box(f, HZ[ch[k]] * 2, 0.07, 0.3 + 0.4 * ((f / BEAT) % 2), 0.9); } /* the escapement, ticking through the harmony */
- for (let f = 0; f < 540; f += BAR) { const c = chordAt(f); bass(f, HZ[CHORD[c][0]], BAR, 0.14); pad(f, HZ[CHORD[c][1][1]], BAR, 0.045, 0.62); }
- theme(30, HZ.C5, true, (fr, hz, g, pan) => box(fr, hz, g, pan), 0.28);
- theme(240, HZ.C5, true, (fr, hz, g, pan) => box(fr, hz, g, pan), 0.26);
- box(420, HZ.G5, 0.24, 0.42, 3); box(450, HZ.D5, 0.2, 0.58, 3); box(480, HZ.B4, 0.24, 0.5, 4); box(480, HZ.G4, 0.2, 0.5, 4); /* it asks, and leaves it open */
- pad(420, HZ.G3, 120, 0.075, 0.5); pad(420, HZ.D4, 120, 0.05, 0.36); pad(420, HZ.B4, 120, 0.035, 0.66);
-
- // ================================================================ MOVEMENT 2
- water(OFF + 5, 0.3);
- for (let fr = 0; fr < 240; fr += 5) { const thin = fr < 180 ? 1 : 1 - (fr - 180) / 60; if (thin > 0) tick(OFF + fr, 0.16 * thin); } /* the tick thins to a wing-flutter and is gone by 240 */
- [180, 210, 230].forEach((a, k) => { for (let j = 0; j < 3; j++) flutter(OFF + a + j * (30 - k * 10), 0.085 + k * 0.02, a + j); });
-
- // the come-alive: the theme returns at HALF SPEED and warm, on a harp, over a real bass line
- for (let f = 540; f < 1200; f += BAR) { const c = chordAt(f); bass(f, HZ[CHORD[c][0]], BAR, 0.155); CHORD[c][1].forEach((nm, k) => pad(f, HZ[nm], BAR, 0.05 - k * 0.008, 0.28 + k * 0.22)); }
- theme(OFF + 15, HZ.C4, true, (fr, hz, g, pan) => harp(fr, hz, g, pan, 3.2), 0.2, 2, 0.44);
- theme(OFF + 255, HZ.C5, true, (fr, hz, g, pan) => harp(fr, hz, g, pan, 2.8), 0.18, 1.5, 0.56); /* it lifts an octave as the creature does */
-
- // the BLOOM: E flat major, the relative major. Same theme, opened out, with a counter-line
- // moving against it in thirds, which is the sound of a world arriving.
- theme(1020, HZ.F4, true, (fr, hz, g, pan) => harp(fr, hz, g, pan, 3.4), 0.2, 1.5, 0.4);
- theme(1020 + 8, HZ.A4, true, (fr, hz, g, pan) => harp(fr, hz, g * 0.6, pan, 3), 0.17, 1.5, 0.64);
- [1110, 1125, 1140, 1170].forEach((f, k) => harp(f, [HZ.G5, HZ.F5, HZ.E5, HZ.D5][k], 0.15, 0.3 + k * 0.12, 2.4));
- pad(1140, HZ.G3, 60, 0.09, 0.5); pad(1140, HZ.D4, 60, 0.06, 0.4); /* the dominant, gathering */
-
- // the MEADOW at 1410: C MAJOR. The answer to Act 1's question, the same eight notes with the
- // third raised, then a plagal turn and a perfect cadence to close.
- for (let f = 1200; f < 1410; f += BAR) { const c = chordAt(f); bass(f, HZ[CHORD[c][0]], BAR, 0.17); CHORD[c][1].forEach((nm, k) => pad(f, HZ[nm], BAR, 0.055 - k * 0.008, 0.26 + k * 0.24)); }
- theme(1200, HZ.C5, true, (fr, hz, g, pan) => box(fr, hz, g, pan, 3.4), 0.3, 1, 0.46);
- theme(1206, HZ.E4, true, (fr, hz, g, pan) => harp(fr, hz, g * 0.72, pan, 3), 0.2, 1, 0.66);
- theme(1200, HZ.C3, true, (fr, hz, g, pan) => pad(fr, hz, 45, g * 0.4, pan), 0.1, 1, 0.5);
- [1290, 1320, 1335, 1350].forEach((f, k) => harp(f, [HZ.A4, HZ.C5, HZ.F5, HZ.G5][k], 0.17, 0.36 + k * 0.1, 3));
- bell(OFF + DING, HZ.C6, 0.3); bell(OFF + DING, HZ.C5, 0.16); box(OFF + DING, HZ.G5, 0.12, 0.5, 3.4); /* the DING, on the last stroke of the signature */
- bass(OFF + DING, HZ.C2, 75, 0.17); pad(OFF + DING, HZ.C4, 75, 0.07, 0.5); pad(OFF + DING, HZ.E4, 75, 0.05, 0.36); pad(OFF + DING, HZ.G4, 75, 0.04, 0.64);
- [1380, 1390, 1400].forEach((f, k) => harp(f, [HZ.E5, HZ.G5, HZ.C6][k], 0.11 - k * 0.02, 0.4 + k * 0.1, 3));
-
- // ---- the events the picture makes, sitting inside the harmony rather than on top of it
- LANDINGS.forEach((l, i) => { const c = CHORD[chordAt(OFF + l.at)][1]; harp(OFF + l.at, HZ[c[i % 3]] * 2, 0.16, 0.3 + i * 0.12, 2.2); });
- TAKEOFFS.forEach((t, i) => { flutter(OFF + t, 0.1, t); if (i > 0) { const c = CHORD[chordAt(OFF + t)][1]; harp(OFF + t, HZ[c[1]], 0.1, 0.62, 1.8); } });
- SIPS.forEach(([a, b]) => { for (let fr = a; fr < b; fr += BEAT) heart(OFF + fr, 0.17); }); /* the tick has become a heartbeat */
-
- // ---- a little room. Three taps is not a reverb, but it is the difference between a score and
- // a row of beeps: nothing in this film happens in an anechoic chamber.
- const taps: [number, number][] = [[0.085, 0.3], [0.168, 0.19], [0.287, 0.11]];
- const dl = L.slice(), dr = R.slice();
- taps.forEach(([sec, g]) => { const d = Math.floor(sec * sr); for (let i = d; i < n; i++) { L[i] += dr[i - d] * g; R[i] += dl[i - d] * g; } });
- for (let i = 0; i < n; i++) { const w = i < 1200 ? i / 1200 : i > n - 18000 ? Math.max(0, (n - i) / 18000) : 1; L[i] = Math.tanh(L[i] * 2.15) * w; R[i] = Math.tanh(R[i] * 2.15) * w; }
- return [L, R];
-};
-
-// every onset must sit exactly on its frame, which is what makes a cue a cue
-export const scoreProblems = (sr = 48000): string[] => {
- const p: string[] = [];
- [5, ...TAKEOFFS, ...LANDINGS.map((l) => l.at), DING, 660, 750].forEach((fr) => { const want = Math.round(((fr + OFF) / FPS) * sr); if (atFrame(fr + OFF, sr) !== want) p.push(`cue at local ${fr} lands on sample ${atFrame(fr + OFF, sr)}, not ${want}`); });
- if (atFrame(OFF + DING, 48000) !== 2184000) p.push(`the DING is at sample ${atFrame(OFF + DING, 48000)}, expected 2184000 (film frame ${OFF + DING})`);
- if (chordAt(1200) !== "C") p.push(`the meadow does not land on C major at 1200, it lands on ${chordAt(1200)}`);
- if (chordAt(480) !== "G") p.push(`Act 1 does not end on the dominant, it ends on ${chordAt(480)}`);
- return p;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/sign.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/sign.ts
deleted file mode 100644
index a40354f..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/sign.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-// THE SIGNATURE, REDRAWN FOR READABILITY (spec 7: "LEGIBLE FIRST: it is a URL, the dot must read
-// as a dot"). The approved still's signature is a run of control points that reads as a scribble
-// at any size, which the spec itself flags as not passing. This is a proper hand: every letter is
-// authored from its own strokes, in em units with the x-height at 1, so it can be set at whatever
-// size the frame needs and still be a word rather than a gesture.
-//
-// It stays a SIGNATURE and not a caption: one warm grey-brown rigger line, a forward slant, a
-// baseline that rises the couple of degrees a hand rises, uneven letter widths, real descenders on
-// g and p. It is just large enough to read, which at 1080 means about 410 px across.
-//
-// `finale/signature.ts` is left exactly as it was, so the approved finale still keeps re-rendering
-// byte for byte. This is the one the film uses.
-import { Gfx, P, jitter, rng, tube } from "../../core";
-
-const SIG = "#574d43";
-type Glyph = { w: number; s: P[][] };
-const arc = (cx: number, cy: number, rx: number, ry: number, a0: number, a1: number, n = 11): P[] =>
- Array.from({ length: n }, (_, i) => { const a = a0 + ((a1 - a0) * i) / (n - 1); return [cx + Math.cos(a) * rx, cy + Math.sin(a) * ry] as P; });
-
-// x-height 1, ascenders to about 1.75, descenders to about -0.55. Widths are deliberately uneven.
-const G: Record<string, Glyph> = {
- a: { w: 0.94, s: [arc(0.46, 0.47, 0.4, 0.45, -0.35, 4.3), [[0.86, 0.9], [0.84, 0.14], [0.97, 0.03]]] },
- l: { w: 0.5, s: [[[0.2, 1.72], [0.23, 0.2], [0.38, 0.03]]] },
- e: { w: 0.88, s: [[[0.08, 0.5], [0.78, 0.54]], arc(0.44, 0.47, 0.38, 0.45, -0.12, 4.0)] },
- x: { w: 0.92, s: [[[0.07, 0.9], [0.82, 0.05]], [[0.09, 0.05], [0.84, 0.9]]] },
- g: { w: 0.98, s: [arc(0.46, 0.55, 0.4, 0.4, -0.35, 4.3), [[0.86, 0.94], [0.85, 0.1], [0.74, -0.42], [0.36, -0.54], [0.18, -0.34]]] },
- r: { w: 0.7, s: [[[0.17, 0.9], [0.2, 0.04]], [[0.2, 0.58], [0.42, 0.92], [0.68, 0.84]]] },
- n: { w: 0.9, s: [[[0.14, 0.9], [0.17, 0.04]], [[0.17, 0.56], [0.44, 0.93], [0.76, 0.72], [0.79, 0.04]]] },
- s: { w: 0.82, s: [[[0.76, 0.82], [0.42, 0.95], [0.16, 0.74], [0.48, 0.52], [0.76, 0.36], [0.58, 0.04], [0.16, 0.14]]] },
- h: { w: 0.9, s: [[[0.14, 1.74], [0.17, 0.04]], [[0.17, 0.56], [0.44, 0.93], [0.76, 0.72], [0.79, 0.04]]] },
- p: { w: 0.94, s: [[[0.15, 0.92], [0.11, -0.52]], [[0.14, 0.78], [0.48, 0.92], [0.78, 0.62], [0.64, 0.24], [0.17, 0.18]]] },
- u: { w: 0.94, s: [[[0.14, 0.9], [0.16, 0.28], [0.4, 0.03], [0.68, 0.2], [0.78, 0.64], [0.8, 0.08], [0.95, 0.04]]] },
- c: { w: 0.86, s: [arc(0.52, 0.47, 0.4, 0.45, 0.85, 5.45)] }, /* a c has to be OPEN on the right or it is an o */
- o: { w: 0.9, s: [arc(0.46, 0.47, 0.4, 0.45, 0, 6.35, 13)] },
- m: { w: 1.24, s: [[[0.1, 0.9], [0.13, 0.04]], [[0.13, 0.56], [0.35, 0.93], [0.58, 0.72], [0.6, 0.04]], [[0.6, 0.56], [0.84, 0.93], [1.08, 0.72], [1.11, 0.04]]] },
- ".": { w: 0.4, s: [] },
-};
-const WORD = "alexgreenshpun.com";
-
-// `p` writes it on, stroke by stroke, in the order a hand would. `alpha` is the ink drying.
-export const signature = (g: Gfx, p = 1, alpha = 0.8) => {
- if (p <= 0) return;
- const em = 27, right = 1042, base = 1032, slant = 0.1, rise = Math.tan((-2 * Math.PI) / 180);
- const total = [...WORD].reduce((a, ch) => a + (G[ch]?.w ?? 0.5) + 0.045, 0);
- const x0 = right - total * em;
- const strokes: { pts: P[]; dot?: boolean }[] = [];
- let pen = 0;
- for (const ch of WORD) {
- const gl = G[ch]; if (!gl) { pen += 0.5; continue; }
- const T = ([gx, gy]: P): P => { const X = x0 + (pen + gx + gy * slant) * em; return [X, base - gy * em + (X - x0) * rise]; };
- if (ch === ".") strokes.push({ pts: [T([0.16, 0.05])], dot: true });
- else gl.s.forEach((st) => strokes.push({ pts: st.map(T) }));
- pen += gl.w + 0.045;
- }
- const r = rng(5901), each = 1 / strokes.length;
- strokes.forEach((st, i) => {
- const q = Math.max(0, Math.min(1, (p - i * each) / each)); if (q <= 0) return;
- if (st.dot) { const [x, y] = st.pts[0], d = em * 0.1; g.fill([[x - d, y - d], [x + d * 1.1, y - d * 0.85], [x + d * 0.95, y + d * 1.1], [x - d * 1.05, y + d * 0.95]], SIG, alpha); return; } /* the dot reads as a dot, which is the whole point of a URL */
- const n = Math.max(2, Math.ceil(st.pts.length * q)), s = jitter(st.pts.slice(0, n), em * 0.016, 5910 + i);
- const w = em * (0.1 + r() * 0.03); /* a rigger: loaded at the start of a stroke, thinner as it runs */
- g.fill(tube(s, w, w * 0.62, false), SIG, alpha);
- if (q >= 1) { const e = s[s.length - 1], d = w * 0.85; g.fill([[e[0] - d, e[1] - d], [e[0] + d, e[1] - d * 0.8], [e[0] + d * 0.9, e[1] + d], [e[0] - d * 0.95, e[1] + d * 0.9]], SIG, alpha * 0.9); } /* pigment pools where the brush left the paper */
- });
-};
-// a clean damp brush lifts the corner before anyone signs over a dark passage
-export const clearCorner = (g: Gfx, p = 1) => {
- if (p <= 0) return;
- const c = g.cur;
- c.globalCompositeOperation = "destination-out";
- g.wash([[560, 992], [1062, 986], [1066, 1058], [556, 1064]], "#000000", { alpha: 0.5 * p, seed: 5900, dx: 0, dy: 0, shrink: 1, rim: false });
- c.globalCompositeOperation = "source-over";
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/transform.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/transform.ts
deleted file mode 100644
index fc468b4..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/transform.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// BEAT 1, THE MACRO: the mechanical creature turns into a real watercolour butterfly. One shot,
-// no cut, at S = 4.0 creeping to 3.4, so the frame holds one forewing root, panel 2 on its
-// projection lines, and the edge of the thorax window with its wheels still stepping on the tick.
-//
-// The order of the picture is the order of the event. The BLUEPRINT is drawn first, in full, by
-// Act 1's own composer at a close view, so what the water is lifting is genuinely the same
-// drawing. Then the water takes the creature, panel by panel, and only the creature: the sheet
-// around it stays a blueprint for ever, which is the line the whole film turns on.
-import { Ctx, Env, Gfx, P, PENCIL } from "../../core";
-import { CX, CY } from "../geom";
-import { FULL, PlateState } from "../plate";
-import { drawPlate } from "../plate";
-import { IDLE } from "../parts";
-import { M0, PANEL2_HOME, DROP } from "./cues";
-import { Cam, projector, scaleOf } from "./view";
-import { drop, frontRim, wetnessAt } from "./water";
-import { paintCreature, wingsOf, REST_FLIGHT, mapper } from "./wingpaint";
-
-// The lifted panel seats on 60 with the last mechanical overshoot in the film, and the flaw
-// becomes the mark of the individual: that blue panel is the one on the approved finale still.
-const liftAt = (f: number): number => {
- if (f <= 45) return 1;
- if (f >= PANEL2_HOME + 6) return 0;
- const u = Math.min(1, (f - 45) / 15), e = 1 - Math.pow(1 - u, 3);
- return Math.max(-0.06, 1 - e) + (f > PANEL2_HOME ? -0.06 * Math.sin(((f - PANEL2_HOME) / 6) * Math.PI) : 0);
-};
-// the train steps on the tick, one notch per five frames, all the way through the macro
-const trainAt = (f: number) => { const n = Math.floor(f / 5) + (f >= 130 ? 1 : 0), th = n * 0.42; return { centre: th, third: th * 2.1, pinion: th * 4.4, escape: -th * 3.2, fork: Math.sin(n * 1.7) * 0.22 }; };
-
-export const camAt = (f: number): Cam => {
- const S = scaleOf(f), u = Math.max(0, Math.min(1, (f - 60) / 60)); /* 60-120: a slow drift left across the thorax to the port wing roots */
- return { S, look: [M0[0] - 78 * u * u * (3 - 2 * u) * 0.5, M0[1] + 10 * u] as P };
-};
-
-export const drawTransform = (ctx: Ctx, env: Env, f: number) => {
- const cam = camAt(f), pr = projector(cam, 0);
- // ---- the blueprint, at this view, by Act 1's composer
- const st: PlateState = { wings: { flap: 1, sweep: 0 }, lift: liftAt(f), keyY: 0, keyTurn: 0, train: trainAt(f), shadow: f > 180 ? [((f - 180) / 60) * 14, ((f - 180) / 60) * 20] : [0, 0], boil: 1, inkedBoil: 1, boilIndex: Math.floor(f / 4), p: FULL, view: { cx: cam.look[0], cy: cam.look[1], zoom: cam.S } };
- drawPlate(ctx, env, st);
-
- // ---- the water, and what it leaves behind
- const g = new Gfx(ctx, env, f, PENCIL), wt = wetnessAt(f), at = pr.at([CX, CY]);
- g.group("plain", () => paintCreature(g, at, cam.S, REST_FLIGHT, { wetness: wt, groundLift: true, shadow: f > 180 ? (f - 180) / 60 : 0, shadowOff: [-0.35, 0.45], seed: 900 }), { alpha: 0.98 });
- const T = mapper(at, cam.S, REST_FLIGHT), W = wingsOf(REST_FLIGHT);
- g.group("plain", () => frontRim(g, T, cam.S * 90, W, f, wt), { alpha: 0.9 });
- if (f >= DROP && f < DROP + 55) { const liftedPanel = W[3].panels[2], c = liftedPanel.reduce((a, p) => [a[0] + p[0] / liftedPanel.length, a[1] + p[1] / liftedPanel.length] as P, [0, 0] as P); const lp = liftAt(f); g.group("plain", () => drop(g, T([c[0] + 58 * lp, c[1] - 60 * lp]), cam.S * 26, f), { alpha: 1 }); }
- g.paper("coldpress", 0.07); /* the tooth of the sheet, over the paint as well as over the ink */
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
deleted file mode 100644
index 8aefbfe..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/view.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// THE CAMERA, spec section 4. A true dolly over depth planes: camera distance D, plane depth z,
-// plane scale 1/(D + z). The hero plane is z = 0, so the hero scale S is 1/D, and S is SCREEN
-// PIXELS PER SHEET UNIT: at S = 1 the creature (wingspan 780 units) is 780 px across.
-//
-// The machinery lives in the engine now (canvas-core/camera.ts): the dolly math, the monotone
-// log2 zoom path, the stroke-weight rule. What stays here is this film's own choreography: the
-// zoom path keyed on the bars, and the units the shots were written in.
-//
-// NOTE, one engine item: the finale world's projector (butterfly/finale/world.ts) normalises
-// every plane by (1 + z) so that all planes are 1:1 on the last frame. That convention inverts
-// parallax for D > 1, and movement 2 spends almost all of its time there (D runs 0.25 to 8.7).
-// It is an authored end-frame framing, not the dolly model, and it stays with the finale.
-import { type P } from "../../core";
-import { monoPath, planeScale, projectCam, strokeWeight } from "../../camera";
-import { S_KEYS } from "./cues";
-
-export type Cam = { S: number; look: P };
-export const distance = (S: number) => 1 / S;
-const asEngine = (c: Cam) => ({ look: c.look, zoom: c.S });
-export const scaleAt = (c: Cam, z: number) => planeScale(asEngine(c), z);
-export const projector = (c: Cam, z: number) => { const k = scaleAt(c, z); return { k, at: (p: P) => projectCam([540, 540], asEngine(c), z, p) }; };
-// A close shot must not fatten the line by the zoom: w = w_authored * S^0.35 (spec 4).
-export const weight = (S: number) => strokeWeight({ look: [0, 0], zoom: S });
-// The zoom path, keyed on the bars and read in stops: S is interpolated in log2, which is what
-// "one stop of zoom" means, and the cubic is monotone so the dolly never overshoots into a scale
-// it was not given, and never reverses.
-export const scaleOf = monoPath(S_KEYS, { log2: true });
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/water.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/water.ts
deleted file mode 100644
index 625e22f..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/water.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// THE WATER FRONT. A cyanotype is developed in water and its blue lifts when the sheet is wet,
-// which is the only honest device that turns this drawing into a painting, and it is why a single
-// drop is the whole bridge between the two movements of the film (spec section 0).
-//
-// The water does not spread as a circle. It lands on the lifted panel, runs down its projection
-// lines onto the wing, and from there it follows the DRAWING by capillary, one spar per five
-// frames, in an order the draftsman would never have chosen. Behind the front the Prussian ground
-// is gone and there is paint; in front of it there is still a blueprint; and the front itself is
-// a dark rim of the pigment it pushed along in front of it.
-import { Gfx, P, jitter, oval, rng, tube } from "../../core";
-import { Wing, cen, lerp } from "../geom";
-import { BODY_WET, DROP, PANEL2_FLOOD, SPAR_WET } from "./cues";
-import { Wetness, frontLine } from "./wingpaint";
-
-const FRONT = "#1e4f7e", DROP_DARK = "#0f3558", HIGHLIGHT = "#fdfdfb";
-const ramp = (f: number, at: number, len: number) => Math.max(0, Math.min(1, (f - at) / len));
-
-// when a panel starts to flood: both its spars have to be running before it fills
-export const panelAt = (i: number, j: number): number => (i === 3 && j === 2 ? PANEL2_FLOOD : Math.max(SPAR_WET[i][j], SPAR_WET[i][j + 1] ?? SPAR_WET[i][j]) + 5);
-export const panelFrom = (i: number, j: number): number => ((SPAR_WET[i][j] ?? 0) <= (SPAR_WET[i][j + 1] ?? 1e9) ? j : j + 1); // the spar the water arrived on
-
-export const wetnessAt = (f: number): Wetness => ({
- panel: (i, j) => ramp(f, panelAt(i, j), i === 3 && j === 2 ? 15 : 10),
- spar: (i, j) => ramp(f, SPAR_WET[i][j] ?? 1e9, 8),
- body: (part) => ramp(f, BODY_WET[part], 20),
- from: (i, j) => panelFrom(i, j) === j,
-});
-
-// The front itself, drawn after the paint: wherever a panel is half taken, a wet edge is crossing
-// it, and a wet edge in watercolour is a dark line because the pigment piles up at the water's rim.
-export const frontRim = (g: Gfx, T: (p: P) => P, sc: number, W: Wing[], f: number, wt: Wetness) => {
- W.forEach((wg, i) => wg.panels.forEach((pn, j) => {
- const u = wt.panel(i, j); if (u <= 0.02 || u >= 0.98) return;
- const p = pn.map((q) => lerp(q, cen(pn), 0.09)), line = frontLine(p, panelFrom(i, j) === j, u).map(T);
- /* a wet edge in watercolour is DARK, because the water carries the pigment to its own rim and
- leaves it there when it stops. That dark line is the only thing that says this is liquid. */
- g.fill(jitter(tube(line, sc * 0.03, sc * 0.02, false), sc * 0.012, 4100 + i * 9 + j), FRONT, 0.62);
- g.fill(jitter(tube(line.map((q) => [q[0] - sc * 0.035, q[1] + sc * 0.02] as P), sc * 0.05, sc * 0.03, false), sc * 0.02, 4150 + i * 9 + j), "#8fb1cb", 0.28); /* the damp sheen just behind it */
- }));
-};
-
-// The drop. A clear bead on a blue sheet: darker blue under it because it magnifies the ground,
-// one paper-white highlight up and left of centre, and a crown of four droplets thrown off the
-// impact that are gone again within a beat.
-export const drop = (g: Gfx, at: P, r: number, f: number) => {
- const t = f - DROP; if (t < 0 || t > 55) return;
- const spread = Math.min(1, t / 30), R = r * (0.55 + spread * 0.75), fade = 1 - Math.max(0, (t - 34) / 21);
- g.wash(jitter(oval(at[0], at[1], R * 1.05, R * 0.92, 14), R * 0.08, 4300), DROP_DARK, { alpha: 0.42 * fade, seed: 4300, shrink: 0.97, rim: true, dx: 1, dy: 2 });
- if (t < 26) { /* while it is still a bead it has a lens in it */
- g.fill(oval(at[0] - R * 0.28, at[1] - R * 0.3, R * 0.2, R * 0.14, 9), HIGHLIGHT, 0.8 * (1 - t / 26));
- g.wash(oval(at[0] + R * 0.2, at[1] + R * 0.24, R * 0.5, R * 0.34, 10), "#5f8fb4", { alpha: 0.3, seed: 4310, shrink: 0.9, rim: false });
- }
- if (t <= 10) { const rr = rng(4320); for (let i = 0; i < 4; i++) { const a = rr() * Math.PI * 2, d = R * (0.9 + t * 0.14 + rr() * 0.4), s = R * 0.12 * (1 - t / 10); g.fill(oval(at[0] + Math.cos(a) * d, at[1] + Math.sin(a) * d * 0.7 - t * R * 0.04, s, s * 0.85, 7), "#bfd8e8", 0.75 * (1 - t / 10)); } } /* the crown */
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/wingpaint.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/wingpaint.ts
deleted file mode 100644
index 74bf419..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/alive/wingpaint.ts
+++ /dev/null
@@ -1,269 +0,0 @@
-// THE CREATURE AS A NATURALIST PLATE (spec 5.7: more realistic, less abstract).
-// The stained-glass direction is withdrawn and this file is rebuilt to it. A lepidopterist should
-// be able to name every part: a closed discal cell, veins forking to a scalloped margin, the
-// submarginal spot row, the apical patch, the discal spot, a furred thorax, seven abdominal
-// segments, compound eyes with palps between them, clubbed antennae, a proboscis that is a tube
-// and not a spring, and six jointed legs. The species stays ORIGINAL: the medium and the anatomy
-// are borrowed, the pattern is not. The reference actually opened is named atop `anatomy.ts`.
-//
-// It still carries a WETNESS per part, because this is also the creature the water is making in
-// beat 1. At 0 the blueprint shows through untouched; between 0 and 1 the paint reaches only as
-// far as the water has, clipped to the front, never faded in over the whole shape.
-import { Gfx, P, displace, jitter, oval, rng, sample, tube } from "../../core";
-import { CX, CY, FW, FW_H, FW_T, HEAD, HW, HW_H, HW_T, Pose, THORAX, Wing, cen, lerp, wingGeom } from "../geom";
-import { GRASS_SHADE, PAPER_W } from "../finale/world";
-
-// RICHER PIGMENT (not washed out, real pigment depth). The finale's ROSE and
-// PEACH are a value or two too weak to carry a naturalist plate, so the creature gets its own,
-// deeper set here rather than an edit to `finale/world.ts`: that file feeds the approved finale
-// still, which keeps re-rendering byte-identical, and this way the film gets the stronger paint
-// without moving anything anyone has already signed off.
-const ROSE = "#d96e80", ROSE_D = "#b04a5e", PEACH = "#ef9a5c", PEACH_L = "#f8c48c", CORNFLOWER = "#3f6fc4";
-import { lift } from "../finale/paint";
-import { venation } from "./anatomy";
-
-export type Flight = { pose: Pose; heading: number; pitch: number; bank: number };
-export const REST_FLIGHT: Flight = { pose: { flap: 1, sweep: 0 }, heading: 0, pitch: 1, bank: 0 };
-// Wing order everywhere in movement 2: 0 port hind, 1 starboard hind, 2 port fore, 3 starboard fore.
-export const wingsOf = (f: Flight): Wing[] => {
- const port = { ...f.pose, flap: Math.min(1, f.pose.flap + f.bank) }, star = { ...f.pose, flap: Math.max(0.2, f.pose.flap - f.bank) };
- return [wingGeom(-1, HW, HW_H, HW_T, 2000, port), wingGeom(1, HW, HW_H, HW_T, 2600, star), wingGeom(-1, FW, FW_H, FW_T, 1000, port), wingGeom(1, FW, FW_H, FW_T, 1600, star)];
-};
-export const mapper = (at: P, scale: number, f: Flight) => {
- const c = Math.cos(f.heading), s = Math.sin(f.heading);
- return (p: P): P => { const dx = (p[0] - CX) * scale, dy = (p[1] - CY) * scale * f.pitch; return [at[0] + dx * c - dy * s, at[1] + dx * s + dy * c]; };
-};
-
-export type Wetness = { panel: (wing: number, panel: number) => number; spar: (wing: number, spar: number) => number; body: (part: "shell" | "head" | "window" | "abdomen") => number; from: (wing: number, panel: number) => boolean };
-export const ALL_WET: Wetness = { panel: () => 1, spar: () => 1, body: () => 1, from: () => true };
-
-// The wet part of a panel. A half-taken panel is not a whole panel at half strength: it is paint
-// up to the water's edge and blueprint past it.
-export const wetPart = (p: P[], fromLow: boolean, t: number): P[] => {
- if (t >= 0.995) return p;
- const A = fromLow ? [p[0], p[1], p[2]] : [p[6], p[5], p[4]], B = fromLow ? [p[6], p[5], p[4]] : [p[0], p[1], p[2]];
- const f = A.map((q, i) => lerp(q, B[i], t));
- return [...A, ...(t > 0.55 ? [p[3]] : []), ...f.slice().reverse()];
-};
-export const frontLine = (p: P[], fromLow: boolean, t: number): P[] => {
- const A = fromLow ? [p[0], p[1], p[2]] : [p[6], p[5], p[4]], B = fromLow ? [p[6], p[5], p[4]] : [p[0], p[1], p[2]];
- return A.map((q, i) => lerp(q, B[i], t));
-};
-
-// ---------------------------------------------------------------- the paint box
-export const UMBER = "#6d4a33", BAND = "#57402f", DUST = "#a08a70", SPOT = "#fcf5e7", FUR = "#c8a98c", FUR_D = "#7d6249";
-export const EYE = "#3a3026", EYE_HI = "#fdfbf4", IRIS_B = "#4d72ae", IRIS_O = "#df8a3d", LEG = "#5e4b3a";
-export const mixc = (a: string, b: string, t: number) => { const h = (x: string) => [parseInt(x.slice(1, 3), 16), parseInt(x.slice(3, 5), 16), parseInt(x.slice(5, 7), 16)]; const A = h(a), B = h(b); return "#" + A.map((v, i) => Math.round(v + (B[i] - v) * Math.max(0, Math.min(1, t))).toString(16).padStart(2, "0")).join(""); };
-
-// A wash that wobbles in proportion to the thing it is painting. The core's `wash` displaces every
-// outline by an ABSOLUTE thirteen units: right for a wing, porridge for a palp and a flat
-// airbrushed ribbon for a macro cell. Everything here therefore carries its own scale.
-export const ps = (g: Gfx, pts: P[], col: string, alpha: number, seed: number, s: number, rim = true): P[] => {
- const q = displace(sample(jitter(pts, s * 0.012, seed), true, 5), s * 0.035, 1.9 / Math.max(6, s), 2, (seed % 83) + 5);
- g.fill(q, col, alpha);
- if (rim) { const c = g.cur; c.globalAlpha = alpha * 0.5; c.strokeStyle = col; c.lineWidth = Math.max(1.1, s * 0.016); c.lineJoin = "round"; g.path(c, q); c.stroke(); c.globalAlpha = 1; }
- return q;
-};
-// WET ON DAMP. A marking dropped into a wash that has not dried has no edge of its own: it creeps
-// a little and stops soft. Three passes, each smaller and stronger, is what that looks like.
-export const damp = (g: Gfx, pts: P[], col: string, alpha: number, seed: number, s: number) => {
- const c = cen(pts);
- for (let k = 0; k < 3; k++) ps(g, pts.map((q) => lerp(q, c, k * 0.11)), col, alpha * (0.42 + k * 0.26), seed + k * 7, s * (1 - k * 0.12), false);
-};
-export const dilate = (pts: P[], d: number): P[] => { const c = cen(pts); return pts.map(([x, y]) => { const dx = x - c[0], dy = y - c[1], l = Math.hypot(dx, dy) || 1; return [x + (dx / l) * d, y + (dy / l) * d] as P; }); };
-// a vein: heavier at the base, thinning to nothing, and BROKEN, because a rigger runs out of paint
-export const rigger = (g: Gfx, pts: P[], w0: number, col: string, alpha: number, seed: number) => {
- const s = sample(pts, false, 11), r = rng(seed);
- for (let i = 0; i < s.length - 1; i++) {
- const t = i / (s.length - 1); if (r() < 0.035 + t * 0.13) continue; /* a rigger runs dry here and there; it does not draw a dash-dot rule */
- const w = w0 * (1 - t * 0.94) ** 1.7;
- g.fill(tube([s[i], s[i + 1]], Math.max(0.28, w), Math.max(0.24, w * 0.92), false), col, alpha * (0.55 + 0.45 * (1 - t)));
- }
-};
-
-export type PaintOpts = {
- wetness?: Wetness;
- groundLift?: boolean;
- shadow?: number; shadowOff?: P;
- proboscis?: number; probTo?: P;
- legs?: number; // 0 tucked in flight, 1 unfolded and gripping
- seed?: number;
- behind?: string; // what the wings are over, for the fifth of it that warms through them
-};
-
-export const paintCreature = (g: Gfx, at: P, scale: number, f: Flight, o: PaintOpts = {}) => {
- const T = mapper(at, scale, f), seed = o.seed ?? 900, W = wingsOf(f), sc = scale * 90;
- const wt = o.wetness ?? ALL_WET, gl = o.groundLift === true, lod = scale * 780; // wingspan on screen
-
- if ((o.shadow ?? 0) > 0) { const d = o.shadowOff ?? [-0.5, 0.55]; g.fill(oval(at[0] + sc * d[0], at[1] + sc * d[1], sc * 1.5, sc * 0.35, 10), GRASS_SHADE, 0.16 * (o.shadow ?? 0)); }
- if ((o.legs ?? 0) > 0 && lod > 120) legs(g, T, sc, o.legs ?? 1, seed, false);
- // hindwings first: the forewing OVERLAPS the hindwing's leading third, and the double layer is darker
- [0, 1, 2, 3].forEach((i) => paintWing(g, T, W[i], i, sc, lod, wt, gl, seed, o.behind));
- body(g, T, sc, lod, wt, seed);
- if ((o.legs ?? 0) > 0 && lod > 120) legs(g, T, sc, o.legs ?? 1, seed, true);
- headParts(g, T, sc, lod, wt, o.proboscis ?? 0, o.probTo, seed);
-};
-
-// ---------------------------------------------------------------- one wing
-const paintWing = (g: Gfx, T: (p: P) => P, wg: Wing, i: number, sc: number, lod: number, wt: Wetness, gl: boolean, seed: number, behind?: string) => {
- const fore = i >= 2, star = i % 2 === 1, A = venation(wg, fore, seed + i * 77), r = rng(seed + i * 11);
- const c0 = cen(wg.out);
- // how wet a point of the wing is: which panel it falls in, and how far the front has crossed it
- const cents = wg.panels.map(cen);
- const wetAt = (q: P): number => {
- let bi = 0, bd = 1e18; cents.forEach((c, j) => { const d = (c[0] - q[0]) ** 2 + (c[1] - q[1]) ** 2; if (d < bd) { bd = d; bi = j; } });
- const u = wt.panel(i, bi); if (u <= 0 || u >= 1) return u;
- const p = wg.panels[bi], low = wt.from(i, bi);
- const Am = low ? lerp(p[0], p[2], 0.5) : lerp(p[6], p[4], 0.5), Bm = low ? lerp(p[6], p[4], 0.5) : lerp(p[0], p[2], 0.5);
- const vx = Bm[0] - Am[0], vy = Bm[1] - Am[1], L = vx * vx + vy * vy || 1;
- return ((q[0] - Am[0]) * vx + (q[1] - Am[1]) * vy) / L <= u ? 1 : 0;
- };
- if (!wg.panels.some((_, j) => wt.panel(i, j) > 0)) return;
-
- // ---- the paper. Either the ground LIFTED panel by panel as the water arrives, or one reserve.
- if (gl) wg.panels.forEach((pn, j) => { const u = wt.panel(i, j); if (u <= 0) return; const part = wetPart(pn, wt.from(i, j), u); ps(g, dilate(part, 15).map(T), PAPER_W, 0.93, seed + 800 + i * 9 + j, sc * 0.8, false); ps(g, jitter(dilate(part, 12).map(T), sc * 0.04, seed + 810 + i * 9 + j), "#6f8ea8", 0.1, seed + 820 + i * 9 + j, sc * 0.5, false); });
- else g.fill(dilate(A.out, 1.5).map(T), PAPER_W, 0.62);
-
- // ---- 1. the pale first wash, laid PANEL BY PANEL so the water's edge stays the edge of the
- // paint. Filtering an outline point by point instead tears the polygon into a rag: a shape has
- // to keep all of its vertices, so what gets clipped is the region, never the point list.
- let anyPaint = false;
- wg.panels.forEach((pn, j) => {
- const u = wt.panel(i, j); if (u <= 0) return;
- anyPaint = true;
- const q = dilate(wetPart(pn, wt.from(i, j), u), 4), p = q.map(T), pc = cen(p), root = T(wg.h);
- const far = Math.min(1, Math.hypot(pc[0] - root[0], pc[1] - root[1]) / (sc * 3.2));
- ps(g, p, ROSE, 0.62 + (1 - far) * 0.28, seed + i * 20 + j, sc);
- ps(g, p.map((z) => lerp(z, T(wg.h), 0.24)), ROSE_D, 0.3 * (1 - far), seed + 40 + i * 20 + j, sc * 0.9, false); /* the pigment pools deepest at the wing root */
- ps(g, p.map((z) => lerp(z, pc, 0.16)), PEACH, 0.4 + far * 0.38, seed + 60 + i * 20 + j, sc * 0.8, false);
- ps(g, p.map((z) => lerp(z, pc, 0.42)), PEACH_L, 0.24 + far * 0.2, seed + 70 + i * 20 + j, sc * 0.6, false);
- if (behind) ps(g, p.map((z) => lerp(z, pc, 0.3)), behind, 0.17, seed + 90 + i * 20 + j, sc * 0.7, false); /* a wing is TRANSLUCENT: a fifth of what is behind it warms through */
- for (let k = 0; k < 2; k++) { const rr = rng(seed + 700 + i * 30 + j * 5 + k), k2 = 0.3 + rr() * 0.4, off: P = [(rr() - 0.5) * sc * 0.45, (rr() - 0.5) * sc * 0.35]; ps(g, p.map((z) => [pc[0] + (z[0] - pc[0]) * k2 + off[0], pc[1] + (z[1] - pc[1]) * k2 + off[1]] as P), rr() > 0.5 ? mixc(ROSE_D, "#8f3a50", 0.4) : mixc(PEACH, "#e8843f", 0.45), 0.2 + rr() * 0.22, seed + 710 + i * 30 + j * 5 + k, sc * 0.6, false); }
- /* the marginal band lives on the OUTER edge of each panel, so it narrows toward the rear
- corner on its own, because the panels do */
- if (lod > 46 && wetAt(pn[3]) > 0.5) { const outerEdge = [pn[2], pn[3], pn[4]].map(T), innerEdge = outerEdge.map((z) => lerp(z, pc, 0.3)); damp(g, [...outerEdge, ...innerEdge.slice().reverse()], BAND, 0.5, seed + 160 + i * 9 + j, sc * 0.7); }
- });
- if (!anyPaint) return;
-
- // ---- 2. the pattern, dropped in WET ON DAMP so nothing but the eyespot's pupil has a hard edge
- const dustPts = wg.panels.filter((_, j) => wt.panel(i, j) > 0.5).map((pn) => lerp(cen(pn), wg.h, 0.62));
- if (dustPts.length > 2) damp(g, [...dustPts, wg.h].map(T), DUST, 0.46, seed + 120 + i, sc * 0.8); /* the warm grey-umber dusting at the base, where the wing is hairy */
- const disc = lerp(A.cell[4], A.cell[5], 0.5);
- if (lod > 120 && wetAt(disc) > 0.5) { const d = T(disc); damp(g, oval(d[0], d[1], sc * 0.085, sc * 0.065, 9), UMBER, 0.66, seed + 130 + i, sc * 0.22); } /* the discal spot, at the end of the cell */
- if (fore && lod > 120) {
- const apex = A.ends[Math.min(1, A.ends.length - 1)], apx = lerp(apex, c0, 0.22), second = A.ends[Math.min(2, A.ends.length - 1)];
- if (wetAt(apx) > 0.5) { /* the dark umber apical patch, holding three pale spots */
- damp(g, [apex, lerp(apex, A.ends[0], 0.55), lerp(apx, c0, 0.34), lerp(apex, second, 0.6)].map(T), UMBER, 0.56, seed + 140 + i, sc * 0.6);
- for (let k = 0; k < 3; k++) { const q = T(lerp(apx, lerp(A.ends[0], second, 0.15 + k * 0.3), 0.42)); ps(g, oval(q[0], q[1], sc * 0.034, sc * 0.028, 8), SPOT, 0.7, seed + 150 + i * 5 + k, sc * 0.1, false); }
- }
- }
- // the row of pale submarginal spots that the blueprint's rivets became
- if (lod > 120) A.ends.forEach((e, k) => { const p = lerp(e, c0, 0.19); if (wetAt(p) < 0.5) return; const q = T(p); ps(g, oval(q[0], q[1], sc * 0.03, sc * 0.025, 8), SPOT, 0.66, seed + 170 + i * 7 + k, sc * 0.1, false); });
- // the one mark no real butterfly has: an iridescent cornflower scale patch in the starboard forewing
- if (i === 3) { const u = wt.panel(3, 2); if (u > 0) { const q = dilate(wetPart(wg.panels[2], wt.from(3, 2), u), 4).map(T), qc = cen(q); ps(g, q, CORNFLOWER, 0.92, seed + 300, sc); ps(g, q.map((z) => lerp(z, qc, 0.34)), mixc(CORNFLOWER, "#8fb6e8", 0.5), 0.4, seed + 302, sc * 0.6, false); lift(g, q.map((z) => lerp(z, qc, 0.52)), seed + 304, 0.3); } }
- // the hindwing's eyespot at the base of the tail: the only hard edge on the whole creature
- if (!fore && lod > 120) {
- const tail = A.ends[Math.max(0, A.ends.length - 2)], e = lerp(tail, c0, 0.26);
- if (wetAt(e) > 0.5) { const q = T(e); damp(g, oval(q[0], q[1], sc * 0.105, sc * 0.09, 10), IRIS_O, 0.76, seed + 180 + i, sc * 0.24); ps(g, oval(q[0], q[1], sc * 0.066, sc * 0.056, 9), IRIS_B, 0.86, seed + 182 + i, sc * 0.16, false); g.fill(oval(q[0], q[1], sc * 0.028, sc * 0.024, 8), EYE, 0.86); g.fill(oval(q[0] + sc * 0.011, q[1] - sc * 0.011, sc * 0.009, sc * 0.007, 6), EYE_HI, 0.8); }
- }
- // ---- 3. VOLUME. The wing has a camber, so a soft shadow lies behind every main vein.
- if (lod > 120) A.veins.filter((v) => v.main).forEach((v) => { const sh = v.pts.map((q) => [q[0] + 2.6, q[1] + 2.8] as P).map(T); g.fill(tube(sh, sc * 0.021 * v.w, sc * 0.006, false), mixc(UMBER, ROSE, 0.55), 0.18); });
- // ---- 4. the VEINS, last, with a fine rigger: broken, tapering, heavier at the base
- A.veins.forEach((v, k) => {
- const n = 7; let cut = 0;
- for (let q = n - 1; q >= 0; q--) { const p = v.pts[Math.min(v.pts.length - 1, Math.round((q / (n - 1)) * (v.pts.length - 1)))]; if (wetAt(p) > 0.5) { cut = (q + 1) / n; break; } }
- if (cut <= 0) return;
- rigger(g, v.pts.slice(0, Math.max(2, Math.ceil(v.pts.length * cut))).map(T), sc * 0.021 * v.w, mixc(UMBER, ROSE_D, 0.3), (v.main ? 0.72 : 0.48) * (lod > 120 ? 1 : 0.7), seed + 400 + i * 20 + k);
- });
- // ---- 5. the fringe: tiny alternating ticks, pale then dark, outside the margin
- if (lod > 120) A.out.forEach((q, k) => {
- if (wetAt(q) < 0.5) return;
- const nx = q[0] - c0[0], ny = q[1] - c0[1], L = Math.hypot(nx, ny) || 1;
- g.fill(tube([T(q), T([q[0] + (nx / L) * A.span * 0.022, q[1] + (ny / L) * A.span * 0.022])], sc * 0.008, sc * 0.003, false), k % 2 ? SPOT : BAND, 0.6);
- });
- // ---- 6. the rim light on the sunward margin: paper LIFTED, never white paint
- if (star) { const rim = A.out.slice(0, Math.ceil(A.out.length * 0.36)).filter((q) => wetAt(q) > 0.5); if (rim.length > 2) lift(g, tube(rim.map(T), sc * 0.05, sc * 0.03, false), seed + 260 + i, 0.6); }
-};
-
-// ---------------------------------------------------------------- the body, painted as a FORM
-const body = (g: Gfx, T: (p: P) => P, sc: number, lod: number, wt: Wetness, seed: number) => {
- const r = rng(seed + 5), ua = wt.body("abdomen");
- if (ua > 0) for (let i = 0; i < 7; i++) { /* seven visible segments, tapering, a paler band at each joint */
- const t0 = i / 7, t1 = (i + 1) / 7, hw = (t: number) => 23 * (1 - t) ** 0.8 + 6.5;
- const u = Math.min(1, ua * (1.4 - i * 0.06)); if (u <= 0) continue;
- const q: P[] = [T([CX - hw(t0) * 0.9, CY + (70 + 170 * t0) * 0.9]), T([CX + hw(t0) * 0.9, CY + (70 + 170 * t0) * 0.9]), T([CX + hw(t1) * 0.9, CY + (70 + 170 * t1) * 0.9]), T([CX - hw(t1) * 0.9, CY + (70 + 170 * t1) * 0.9])];
- ps(g, q, mixc(UMBER, DUST, 0.16 + i * 0.05), (0.8 - i * 0.02) * u, seed + 400 + i, sc * 0.4);
- ps(g, [q[0], q[1], lerp(q[1], q[2], 0.3), lerp(q[0], q[3], 0.3)], mixc(DUST, SPOT, 0.42), 0.4 * u, seed + 410 + i, sc * 0.3, false); /* the paler band at the joint, wrapping round the cylinder */
- ps(g, [lerp(q[0], q[3], 0.1), lerp(q[1], q[2], 0.1), lerp(q[1], q[2], 0.9), lerp(q[0], q[3], 0.9)].map((z) => lerp(z, cen(q), 0.45)), "#43352a", 0.16 * u, seed + 412 + i, sc * 0.3, false); /* the core shadow, so a segment is a cylinder and not a tile */
- }
- const us = wt.body("shell");
- if (us > 0) {
- const th = THORAX.map(T), c = cen(th);
- ps(g, th, mixc(UMBER, "#4a3a2c", 0.3), 0.84 * us, seed + 420, sc * 0.7);
- ps(g, th.map((q) => lerp(q, [c[0] + sc * 0.16, c[1] - sc * 0.14] as P, 0.42)), mixc(DUST, SPOT, 0.3), 0.44 * us, seed + 422, sc * 0.5, false); /* lit upper right */
- ps(g, th.map((q) => lerp(q, [c[0] - sc * 0.2, c[1] + sc * 0.2] as P, 0.5)), "#3b2f24", 0.3 * us, seed + 424, sc * 0.5, false); /* core shadow */
- ps(g, th.map((q) => lerp(q, [c[0] - sc * 0.26, c[1] + sc * 0.28] as P, 0.64)), mixc(DUST, "#8c7a63", 0.5), 0.24 * us, seed + 426, sc * 0.4, false); /* reflected light coming back up off the petal */
- if (lod > 120) for (let i = 0; i < 30; i++) { /* the fur, dry-brushed ALONG the thorax in the direction it grows, and over the old window */
- const t = r(), a = -1.62 + (r() - 0.5) * 1.5, p = T([CX + (r() - 0.5) * 88, CY - 88 + t * 156]), L = sc * (0.1 + r() * 0.13);
- g.fill(tube([p, [p[0] + Math.cos(a) * L, p[1] + Math.sin(a) * L]], sc * 0.012, sc * 0.003, false), r() > 0.45 ? FUR : FUR_D, 0.38 + r() * 0.3);
- }
- }
-};
-
-// ---------------------------------------------------------------- head: eyes, palps, antennae
-const headParts = (g: Gfx, T: (p: P) => P, sc: number, lod: number, wt: Wetness, prob: number, probTo: P | undefined, seed: number) => {
- if (wt.body("head") <= 0) return;
- ps(g, HEAD.map(T), mixc(UMBER, "#493928", 0.35), 0.86, seed + 424, sc * 0.35);
- if (lod > 120) {
- [-1, 1].forEach((sd) => { /* two large compound eyes, one soft highlight each */
- const e = T([CX + sd * 20, CY - 112]);
- ps(g, oval(e[0], e[1], sc * 0.085, sc * 0.095, 12), EYE, 0.9, seed + 430 + sd, sc * 0.2, false);
- ps(g, oval(e[0] - sc * 0.02, e[1] + sc * 0.02, sc * 0.058, sc * 0.064, 10), mixc(EYE, "#6a5a45", 0.4), 0.42, seed + 432 + sd, sc * 0.14, false);
- g.fill(oval(e[0] + sc * 0.03, e[1] - sc * 0.035, sc * 0.021, sc * 0.017, 8), EYE_HI, 0.85);
- });
- [-1, 1].forEach((sd) => { /* the furry palps, between and below the eyes, pointing forward */
- const b = T([CX + sd * 9, CY - 116]), t = T([CX + sd * 15, CY - 154]);
- g.fill(tube([b, lerp(b, t, 0.55), t], sc * 0.033, sc * 0.012, false), FUR, 0.88);
- g.fill(tube([lerp(b, t, 0.62), t], sc * 0.018, sc * 0.007, false), FUR_D, 0.7);
- });
- }
- [-1, 1].forEach((sd) => { /* the antennae: slender, finely RINGED, ending in a true club */
- const a0 = T([CX + sd * 10, CY - 124]), a1 = T([CX + sd * 52, CY - 190]), a2 = T([CX + sd * 116, CY - 226]);
- const pts = Array.from({ length: 9 }, (_, i) => { const t = i / 8; return lerp(lerp(a0, a1, t), lerp(a1, a2, t), t); });
- g.fill(tube(pts, sc * 0.026, sc * 0.011, false), mixc(EYE, UMBER, 0.3), 0.82);
- if (lod > 120) for (let i = 1; i < 8; i++) g.fill(tube([pts[i], lerp(pts[i], pts[i + 1], 0.45)], sc * 0.016, sc * 0.014, false), FUR, 0.4);
- const cl = pts[8], cb = pts[7];
- ps(g, oval(cl[0] + (cl[0] - cb[0]) * 0.3, cl[1] + (cl[1] - cb[1]) * 0.3, sc * 0.046, sc * 0.03, 9), mixc(EYE, UMBER, 0.2), 0.88, seed + 440 + sd, sc * 0.1, false);
- });
- proboscis(g, T, sc, prob, probTo);
-};
-
-// coiled between the palps at rest, a fine double tube when it is out
-export const proboscis = (g: Gfx, T: (p: P) => P, sc: number, p: number, to?: P) => {
- const base = T([CX, CY - 132]), tip: P = to ?? [base[0], base[1] + sc * 1.2], spir: P[] = [];
- for (let i = 0; i <= 26; i++) {
- const t = i / 26, a = 1.4 + t * 2.6 * Math.PI * 2, rr = sc * (0.018 + 0.085 * t);
- const coiled: P = [base[0] + Math.cos(a) * rr, base[1] + Math.sin(a) * rr];
- const bw = Math.sin(t * Math.PI) * sc * 0.3;
- const straight: P = [base[0] + (tip[0] - base[0]) * t - bw * 0.45, base[1] + (tip[1] - base[1]) * t + bw];
- spir.push([coiled[0] + (straight[0] - coiled[0]) * p, coiled[1] + (straight[1] - coiled[1]) * p]);
- }
- g.fill(tube(spir, sc * 0.022, sc * 0.012, false), mixc(EYE, UMBER, 0.25), 0.72);
- if (p > 0.4) g.fill(tube(spir.map((q) => [q[0] + sc * 0.013, q[1] + sc * 0.006] as P), sc * 0.009, sc * 0.005, false), FUR, 0.3 * p); /* it is a DOUBLE tube: two galeae zipped together */
-};
-
-// ---------------------------------------------------------------- six legs: femur, tibia, tarsus
-export const legs = (g: Gfx, T: (p: P) => P, sc: number, open: number, seed: number, front: boolean) => {
- const r = rng(seed + 77);
- ([[-1, -46, 0.95], [1, -46, 0.95], [-1, 4, 1.05], [1, 4, 1.05], [-1, 52, 1.15], [1, 52, 1.15]] as number[][]).forEach(([sd, y, len], k) => {
- if ((k % 2 === 0) === front) return; /* half of them are on the far side of the body and go under the wings */
- const hip = T([CX + sd * 26, CY + y]), a0 = sd * (0.5 + 0.55 * open) + (r() - 0.5) * 0.18, L = sc * 0.34 * len;
- const knee: P = [hip[0] + Math.cos(a0) * L * (0.5 + 0.5 * open), hip[1] + Math.abs(Math.sin(a0)) * L * 0.42 + L * 0.1];
- const a1 = a0 + sd * (0.9 - 0.4 * open);
- const foot: P = [knee[0] + Math.cos(a1) * L * 0.9 * (0.4 + 0.6 * open), knee[1] + L * (0.5 + 0.5 * open)];
- g.fill(tube([hip, knee], sc * 0.022, sc * 0.015, false), LEG, 0.8); /* femur */
- g.fill(tube([knee, foot], sc * 0.016, sc * 0.009, false), LEG, 0.78); /* tibia */
- g.fill(tube([foot, [foot[0] + Math.cos(a1) * L * 0.2, foot[1] + L * 0.1] as P], sc * 0.01, sc * 0.004, false), mixc(LEG, EYE, 0.5), 0.8); /* tarsus, ending in a claw */
- for (let i = 0; i < 3; i++) { const p = lerp(hip, knee, 0.3 + i * 0.25); g.fill(tube([p, [p[0] + (r() - 0.5) * sc * 0.05, p[1] - sc * 0.03] as P], sc * 0.005, sc * 0.002, false), FUR_D, 0.5); }
- });
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/cues.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/cues.ts
deleted file mode 100644
index d476bf3..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/cues.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-// THE TIMELINE. Every frame number in the film lives in this table and nowhere else. 120 bpm at
-// 30 fps: one beat = 15 frames, cuts on multiples of 15, events on multiples of 5 (triplet
-// eighths, which is what an escapement sounds like anyway). State is a pure function of frame.
-import { FULL, PlateState } from "./plate";
-import { WIDE } from "./surface";
-import { Train } from "./parts";
-
-export type Ease = "linear" | "out" | "outBack" | "flick";
-export type Cue = { at: number; dur: number; id: string; ease?: Ease; amp?: number };
-
-// The motion test: four shots, eight beats. It starts on the approved plate and ends on it.
-export const SHOTS: [string, number, number][] = [["still", 0, 30], ["wind", 30, 60], ["hush", 60, 90], ["alive", 90, 120]];
-export const CUES: Cue[] = [
- { at: 15, dur: 20, id: "key.rise", ease: "outBack" }, /* the key rides up its own centre line and seats with a small overshoot */
- { at: 35, dur: 20, id: "key.wind", ease: "linear" }, /* four turns of 5 frames: in plan view the bows foreshorten to a line and back */
- { at: 55, dur: 10, id: "key.out", ease: "out" },
- { at: 65, dur: 10, id: "twitch", ease: "flick", amp: 0.14 }, /* it moves once before anyone expects it */
- { at: 75, dur: 15, id: "flap1", ease: "flick", amp: 0.55 },
- { at: 90, dur: 10, id: "flap2", ease: "flick", amp: 0.62 },
- { at: 100, dur: 5, id: "flap3", ease: "flick", amp: 0.45 },
- { at: 105, dur: 5, id: "flap4", ease: "flick", amp: 0.3 },
- { at: 110, dur: 5, id: "flap5", ease: "flick", amp: 0.14 },
- { at: 85, dur: 15, id: "shadow.out", ease: "out" }, /* the drawing separates from its own paper */
- { at: 105, dur: 10, id: "shadow.in", ease: "out" },
- { at: 85, dur: 30, id: "boil" }, /* hero linework breathes only while it is alive */
-];
-export const TICK0 = 35, TICK = 5; // the train starts on the first turn of the key and never stops
-export const DURATION = 120;
-
-const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
-const ease = (p: number, e: Ease = "linear") => e === "out" ? 1 - (1 - p) ** 3 : e === "outBack" ? 1 + 1.7 * (p - 1) ** 3 + 0.7 * (p - 1) ** 2 : e === "flick" ? (p < 0.35 ? Math.sin((p / 0.35) * Math.PI / 2) : Math.cos(((p - 0.35) / 0.65) * Math.PI / 2)) : p;
-const cue = (id: string) => { const c = CUES.find((x) => x.id === id); if (!c) throw new Error(`no cue '${id}'`); return c; };
-export const at = (frame: number, id: string): number => { const c = cue(id); return ease(clamp((frame - c.at) / c.dur), c.ease); }; // 0 before, 1 after
-export const raw = (frame: number, id: string): number => { const c = cue(id); return clamp((frame - c.at) / c.dur); };
-
-// the going train: one tooth of the escape wheel per tick, snapped over two frames with a
-// one-frame recoil, and every other wheel geared off it by its tooth count
-const STEP = [14 / 24, 26 / 24, 1, 1, 1];
-export const advance = (frame: number): number => { if (frame < TICK0 + TICK) return 0; const t = Math.floor((frame - TICK0) / TICK), s = (frame - TICK0) % TICK; return t - 1 + STEP[s]; };
-export const trainAt = (frame: number): Train => {
- const a = advance(frame), w = (Math.PI * 2) / 96, t = Math.floor((frame - TICK0) / TICK), s = (frame - TICK0) % TICK;
- const rocking = frame >= TICK0 + TICK && s === 0 ? 0 : 0.085 * (t % 2 ? 1 : -1); /* the fork passes through centre on the tick frame */
- return { centre: a * w, third: -a * w * (24 / 14), pinion: a * w * (24 / 8), escape: a * ((Math.PI * 2) / 15), fork: frame < TICK0 + TICK ? 0 : rocking };
-};
-
-export const stateAt = (frame: number): PlateState => {
- const flap = ["twitch", "flap1", "flap2", "flap3", "flap4", "flap5"].reduce((f, id) => f - (cue(id).amp ?? 0) * at(frame, id), 1);
- const sh = 1 - at(frame, "shadow.in"), out = at(frame, "shadow.out") * sh, wind = raw(frame, "key.wind");
- return {
- wings: { flap, sweep: -0.2 * (1 - flap) }, /* a raised wing also rakes forward: the 57o sweep the plate dimensions */
- lift: 1, /* the starboard panel stays off the wing: the film ends on the approved plate */
- keyY: at(frame, "key.rise") * (1 - at(frame, "key.out")),
- keyTurn: wind >= 1 || wind <= 0 ? 0 : wind * 4 * Math.PI * 2,
- train: trainAt(frame),
- shadow: [out * 10, out * 14],
- boil: at(frame, "boil") > 0 && raw(frame, "boil") < 1 ? 0.25 : 0,
- inkedBoil: 0, /* the motion test is the same desk: the furniture does not move (spec 4) */
- boilIndex: Math.floor(frame / 5) % 4,
- p: FULL, /* the motion test starts from the finished plate */
- view: WIDE,
- };
-};
-
-// The grid is a rule, so it is checked, not trusted (spec 9, G1).
-export const gridProblems = (): string[] => {
- const p: string[] = [];
- CUES.forEach((c) => { if (c.at % 5) p.push(`cue '${c.id}' starts on frame ${c.at}, not a multiple of 5`); if ((c.at + c.dur) % 5) p.push(`cue '${c.id}' ends on frame ${c.at + c.dur}, not a multiple of 5`); if (c.at + c.dur > DURATION) p.push(`cue '${c.id}' ends after the film`); });
- SHOTS.forEach(([id, a, b]) => { if (a % 15 || b % 15) p.push(`shot '${id}' cuts off the beat grid (${a}..${b})`); });
- if (TICK0 % 5) p.push(`the train starts on frame ${TICK0}, not a multiple of 5`);
- return p;
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/compose.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/compose.ts
deleted file mode 100644
index 78eaa89..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/compose.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-// THE FINALE FRAME. One sheet of cold-press, painted back to front: sky, hills, far field, the
-// path, the grass planes with their flower drifts, the hero flowers, what it left behind, the
-// creature, the fringe across the lens, and the signature in the corner. The camera is one
-// number, so the same function paints the opening close-up and the last wide shot.
-import { Ctx, Env, Gfx, P, PENCIL } from "../../core";
-import { Cam, GRASS_LIT, GRASS_MID, GRASS_SHADE, projector } from "./world";
-import { farField, footpath, grassBlades, grassWash, hills, sky } from "./scene";
-import { Drift, drift, flower } from "./flora";
-import { Flight, drawCreature } from "./creature";
-import { blueprintSheet } from "./sheet";
-import { clearCorner, signature } from "./signature";
-import { clump } from "./paint";
-
-export type FinaleState = { cam: Cam; creature: { at: P; scale: number; flight: Flight } | null; sig: number; lean: number };
-export const PAPER_F = "#fbf7ee";
-
-// hand-placed drifts: a centre, a radius, a species, and seeded scatter that thins outward.
-// Three bare rests of plain grass are left on purpose, at world x 380-520 on P3, left of F3,
-// and right of the path on P4.
-const DRIFTS: [number, Drift][] = [
- [3.5, { sp: "buttercup", at: [470, 545], r: 150, n: 26, size: 5.5, seed: 7101 }],
- [3.5, { sp: "buttercup", at: [700, 560], r: 120, n: 16, size: 5, seed: 7102 }],
- [3.5, { sp: "daisy", at: [200, 560], r: 130, n: 12, size: 5, seed: 7103 }],
- [2.2, { sp: "poppy", at: [780, 655], r: 170, n: 20, size: 9, seed: 7201 }],
- [2.2, { sp: "cosmos", at: [640, 640], r: 90, n: 9, size: 11, seed: 7202 }],
- [2.2, { sp: "daisy", at: [250, 660], r: 120, n: 14, size: 8, seed: 7203 }],
- [1.0, { sp: "cornflower", at: [250, 690], r: 95, n: 13, size: 13, seed: 7301 }],
- [1.0, { sp: "daisy", at: [430, 720], r: 150, n: 16, size: 12, seed: 7302 }],
- [1.0, { sp: "cosmos", at: [760, 700], r: 110, n: 8, size: 13, seed: 7303 }],
-];
-
-export const drawFinale = (ctx: Ctx, env: Env, s: FinaleState) => {
- const W = env.W, H = env.H, g = new Gfx(ctx, env, 0, PENCIL), c = ctx, cam = s.cam;
- c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = PAPER_F; c.fillRect(0, 0, W, H);
- g.paper("coldpress", 0.16); /* the sheet, before anything is on it */
- g.group("plain", () => { sky(g, cam, W, H); }, { alpha: 1 }); /* a paint group softens and granulates every plane, which put a grey veil over the whole meadow: the washes carry their own edge */
- g.group("plain", () => { hills(g, cam); }, { alpha: 1 });
- g.group("plain", () => { farField(g, cam); }, { alpha: 1 });
- ([[3.5, 545, 61, 26, 0.06, 0.42], [2.2, 640, 67, 34, 0.08, 0.22], [1.0, 706, 71, 46, 0.1, 0]] as number[][]).forEach(([z, y0, seed, n, lean, fade]) => {
- g.group("plain", () => { grassWash(g, cam, z, y0, seed, { lean, fade, cool: z === 1 }); if (z === 3.5) footpath(g, cam); }, { alpha: 1 }); /* the path is worn INTO the plane it crosses */
- g.group("plain", () => grassBlades(g, cam, z, y0, seed, { blades: n, lean, fade }), { alpha: 0.95 }); /* blades on dry paint keep their edge */
- const pr = projector(cam, z);
- g.group("plain", () => DRIFTS.filter(([dz]) => dz === z).forEach(([, d]) => drift(g, d, pr.at, pr.k, s.lean)), { alpha: 0.97 });
- });
- /* the hero plane: what it left behind, and the two flowers it has already visited */
- const h0 = projector(cam, 0), h1 = projector(cam, 0.3);
- g.group("plain", () => {
- blueprintSheet(g, h0.at([150, 965]), 150 * h0.k);
- flower(g, "daisy", h0.at([330, 830]), 34 * h0.k, 7401, { variant: 0, lean: s.lean });
- flower(g, "daisy", h0.at([250, 880]), 26 * h0.k, 7402, { variant: 1, lean: s.lean });
- flower(g, "poppy", h1.at([560, 800]), 30 * h1.k, 7403, { variant: 0, lean: s.lean });
- flower(g, "poppy", h1.at([650, 840]), 22 * h1.k, 7404, { variant: 3, lean: s.lean });
- }, { alpha: 0.98 });
- if (s.creature) g.group("plain", () => drawCreature(g, s.creature!.at, s.creature!.scale, s.creature!.flight), { alpha: 0.98 });
- /* the fringe across the lens: huge, soft, no edge, and gone by the third second */
- const fr = projector(cam, -0.2);
- g.group("plain", () => { const roots: P[] = [[-40, 1120], [180, 1160], [900, 1150], [1120, 1090], [620, 1180]];
- roots.forEach((w0, i) => clump(g, fr.at(w0), (240 + i * 34) * fr.k, 60 * fr.k, [GRASS_SHADE, GRASS_MID, GRASS_LIT][i % 3], 7500 + i, 0.06 + i * 0.02, 6, 0.3)); }, { alpha: 0.5, blur: 2.2 });
- g.group("plain", () => { clearCorner(g, s.sig > 0 ? 1 : 0); signature(g, s.sig); }, { alpha: 1 });
- g.paper("washGran", 0.05); g.paper("coldpress", 0.07); /* the tooth of the sheet, over everything */
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/creature.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/creature.ts
deleted file mode 100644
index 792300c..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/creature.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-// THE CREATURE, REPAINTED. Same control points, new paint. Each membrane panel between the
-// spars is its own small wet-in-wet wash, rose at the root running to peach at the margin with
-// a butter drop near the tip. The spars are denim line, the rivets are lifted dots, the rim
-// light on the sunward margins is paper left unpainted, and starboard forewing panel 2 is
-// cornflower blue with a ruled grid lifted in it: a piece of the blueprint it carries with it.
-import { Gfx, P, jitter, oval, rng, tube } from "../../core";
-import { CX, CY, FW, FW_H, FW_T, HEAD, HW, HW_H, HW_T, Pose, THORAX, Wing, cen, lerp, wingGeom } from "../geom";
-import { BUTTER, CORNFLOWER, DENIM, GRASS_SHADE, INK_P, PAPER_W, PEACH, ROSE } from "./world";
-import { lift, mottle, wet } from "./paint";
-
-export type Flight = { pose: Pose; heading: number; pitch: number; bank: number };
-export const REST_FLIGHT: Flight = { pose: { flap: 1, sweep: 0 }, heading: 0, pitch: 1, bank: 0 };
-
-// world -> screen for the creature: pose on the control points first, then heading, pitch, scale
-const mapper = (at: P, scale: number, f: Flight) => {
- const c = Math.cos(f.heading), s = Math.sin(f.heading);
- return (p: P): P => {
- const dx = (p[0] - CX) * scale, dy = (p[1] - CY) * scale * f.pitch; /* pitch foreshortens along the body axis as it climbs away */
- return [at[0] + dx * c - dy * s, at[1] + dx * s + dy * c];
- };
-};
-export const drawCreature = (g: Gfx, at: P, scale: number, f: Flight, seed = 900) => {
- const T = mapper(at, scale, f), r = rng(seed);
- const pose = f.pose, port = { ...pose, flap: Math.min(1, pose.flap + f.bank) }, star = { ...pose, flap: Math.max(0.2, pose.flap - f.bank) };
- const w: Wing[] = [wingGeom(-1, HW, HW_H, HW_T, 2000, port), wingGeom(1, HW, HW_H, HW_T, 2600, star), wingGeom(-1, FW, FW_H, FW_T, 1000, port), wingGeom(1, FW, FW_H, FW_T, 1600, star)];
- const sc = scale * 90; /* one "unit" of paint at this size */
- g.fill(oval(at[0] - sc * 0.5, at[1] + sc * 0.55, sc * 1.5, sc * 0.35, 10), GRASS_SHADE, 0.16); /* the shadow it throws on the grass, lower left */
- /* the paper was LEFT for it. A watercolourist paints the field around the subject and keeps
- the sheet clean underneath, which is why a wash over white glows and a wash over green does not */
- const reserve: P[] = [];
- w.forEach((wg) => wg.out.forEach((q) => reserve.push(T(q))));
- const rc = cen(reserve);
- w.forEach((wg) => { g.fill(wg.out.map((q) => { const p = T(q); return lerp(p, rc, -0.03) as P; }), PAPER_W, 0.93); });
- g.fill(THORAX.map((q) => lerp(T(q), rc, -0.08)), PAPER_W, 0.95);
- w.forEach((wg, i) => {
- const star2 = i % 2 === 1, out = wg.out.map(T), root = T(wg.h), margin = out.map((q) => lerp(q, cen(out), 0.055));
- /* the margin band: the darkest pigment on the wing, laid first and let dry */
- wet(g, out, ROSE, { alpha: 0.62, seed: seed + i * 40, shrink: 0.985, rim: true, dx: 2, dy: 2 });
- wg.panels.forEach((pn, j) => {
- const p = pn.map((q) => lerp(q, cen(pn), 0.12)).map(T), c0 = cen(p), d = Math.hypot(c0[0] - root[0], c0[1] - root[1]), far = Math.min(1, d / (sc * 3.2));
- if (i === 3 && j === 2) { /* the panel that never came home, painted the colour of the plate it came from */
- wet(g, p, CORNFLOWER, { alpha: 0.8, seed: seed + 300, shrink: 0.95, rim: true });
- const gr = 3; for (let q = 1; q < gr; q++) { const a = lerp(p[0], p[6], q / gr), b = lerp(p[2], p[4], q / gr); lift(g, tube([a, b], sc * 0.03, sc * 0.03, false), seed + 310 + q, 0.5); }
- return;
- }
- /* each panel is its OWN small wash: rose at the root, peach running out to the margin,
- with a paper gap between panels so the wing reads like stained glass */
- wet(g, p, ROSE, { alpha: 0.5 + (1 - far) * 0.34, seed: seed + i * 20 + j, shrink: 0.93, rim: true, dx: 1.5, dy: 1.5 });
- wet(g, p.map((q) => lerp(q, lerp(c0, T(wg.ends[Math.min(j + 1, wg.ends.length - 1)]), 0.45), 0.3)), PEACH, { alpha: 0.3 + far * 0.34, seed: seed + 60 + i * 20 + j, dx: 2, dy: -2, shrink: 0.86, rim: false });
- if (far > 0.5 && r() > 0.4) { const tip = lerp(c0, T(wg.ends[Math.min(j + 1, wg.ends.length - 1)]), 0.55); wet(g, oval(tip[0], tip[1], sc * 0.2, sc * 0.16, 9), BUTTER, { alpha: 0.5, seed: seed + 120 + i * 9 + j, shrink: 0.88, rim: false }); } /* a drop of butter near the tip, dropped in while it is wet */
- });
- wg.ends.forEach((_, j) => { const line = Array.from({ length: 6 }, (_, q) => T(wg.spar(j, 0.05 + (q / 5) * 0.9))); g.fill(tube(line, sc * (j === 0 ? 0.05 : 0.03), sc * 0.01, false), DENIM, j === 0 ? 0.78 : 0.56); });
- for (let j = 1; j <= 4; j++) { const p = T(wg.spar(0, 0.16 + j * 0.18)); lift(g, oval(p[0], p[1], sc * 0.03, sc * 0.03, 8), seed + 200 + i * 9 + j, 0.6); }
- if (star2) { const rim = out.slice(0, Math.ceil(out.length * 0.4)); lift(g, tube(rim, sc * 0.07, sc * 0.04, false), seed + 260 + i, 0.72); } /* rim light on the sunward margin: paper left, never white paint */
- /* lost-and-found pencil: it follows the margin for a while, then leaves it alone */
- const seg = Math.ceil(out.length * 0.45); g.fill(tube([...out.slice(0, seg)], sc * 0.024, sc * 0.014, false), INK_P, 0.5);
- g.fill(tube([...out.slice(seg + 2, out.length)], sc * 0.02, sc * 0.012, false), INK_P, 0.3);
- });
- const body = THORAX.map(T), head = HEAD.map(T);
- for (let i = 0; i < 6; i++) { /* the abdomen is six printed segments with the paper showing in the joints */
- const t0 = i / 6, t1 = (i + 1) / 6, hw = (t: number) => 23 * (1 - t) ** 0.8 + 6.5, g0 = 1.6;
- const q: P[] = [T([CX - hw(t0) * 0.9 + g0, CY + (70 + 170 * t0) * 0.9 + g0]), T([CX + hw(t0) * 0.9 - g0, CY + (70 + 170 * t0) * 0.9 + g0]), T([CX + hw(t1) * 0.9 - g0, CY + (70 + 170 * t1) * 0.9 - g0]), T([CX - hw(t1) * 0.9 + g0, CY + (70 + 170 * t1) * 0.9 - g0])];
- wet(g, q, DENIM, { alpha: 0.72 - i * 0.03, seed: seed + 400 + i, shrink: 0.94, rim: true, dx: 1, dy: 1 });
- }
- wet(g, body, DENIM, { alpha: 0.8, seed: seed + 420, shrink: 0.94, rim: true });
- wet(g, head, DENIM, { alpha: 0.84, seed: seed + 424, shrink: 0.92, rim: true });
- wet(g, body.map((q) => lerp(q, [cen(body)[0] - sc * 0.12, cen(body)[1]] as P, 0.3)), "#4f6f9e", { alpha: 0.34, seed: seed + 426, shrink: 0.9, rim: false }); /* the shadow side: the sun is upper right */
- lift(g, oval(T([CX + 14, CY - 30])[0], T([CX + 14, CY - 30])[1], sc * 0.13, sc * 0.3, 10), seed + 410, 0.45); /* the lit side of the body, taken back off */
- const o = cen(THORAX); ([[o[0] + 2, o[1] + 8, 24], [o[0] - 18, o[1] - 32, 14], [o[0] + 22, o[1] - 24, 10]] as number[][]).forEach(([x, y, rr], i) => { const p = T([x, y]); lift(g, oval(p[0], p[1], rr * scale * 0.95, rr * scale * 0.95, 12), seed + 420 + i, 0.5); wet(g, jitter(oval(p[0], p[1], rr * scale, rr * scale, 12), rr * scale * 0.12, seed + 430 + i), "#8fb3d8", { alpha: 0.42, seed: seed + 430 + i, shrink: 0.9, rim: true }); }); /* the train, lifted out and dropped in cool sky: still clockwork */
- [-1, 1].forEach((sd) => { const a0 = T([CX + sd * 8, CY - 114]), a1 = T([CX + sd * 50, CY - 186]), a2 = T([CX + sd * 112, CY - 222]); const pts = Array.from({ length: 7 }, (_, i) => { const t = i / 6; return lerp(lerp(a0, a1, t), lerp(a1, a2, t), t); }); g.fill(tube(pts, sc * 0.035, sc * 0.012, false), INK_P, 0.7); g.fill(oval(a2[0], a2[1], sc * 0.055, sc * 0.055, 8), INK_P, 0.7); });
- const pr = T([CX, CY - 135]), spir: P[] = []; for (let i = 0; i <= 26; i++) { const t = i / 26, a = 1.4 + t * 2.6 * Math.PI * 2, rr = sc * (0.02 + 0.1 * t); spir.push([pr[0] + Math.cos(a) * rr, pr[1] + Math.sin(a) * rr]); }
- g.fill(tube(spir, sc * 0.026, sc * 0.014, false), INK_P, 0.45); /* the proboscis is still a hairspring */
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/flora.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/flora.ts
deleted file mode 100644
index de224ec..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/flora.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// FIVE SPECIES, FOUR VARIANTS EACH, and a level of detail that follows the painter's own rule:
-// close up you draw the flower, further off you put down the petals as single strokes, further
-// still it is two dabs, colour and shadow, and at the back of the field it is one dab.
-// Every species is a colour the film has already used.
-import { Gfx, P, oval, rng, tube } from "../../core";
-import { BUTTERCUP, CORNFLOWER, COSMOS, DAISY, DAISY_SHADE, GRASS_SHADE, POPPY, POPPY_DARK, PAPER_W, STEM } from "./world";
-
-export type Sp = "daisy" | "poppy" | "cornflower" | "cosmos" | "buttercup";
-const COL: Record<Sp, [string, string]> = { daisy: [DAISY, DAISY_SHADE], poppy: [POPPY, POPPY_DARK], cornflower: [CORNFLOWER, "#3f5e9e"], cosmos: [COSMOS, "#d druck"], buttercup: [BUTTERCUP, "#d9a323"] };
-COL.cosmos = [COSMOS, "#d2789a"];
-
-const stem = (g: Gfx, root: P, head: P, w: number, seed: number, lean: number) => {
- const r = rng(seed), mid: P = [(root[0] + head[0]) / 2 + (r() - 0.5) * 8 * w + lean * 10, (root[1] + head[1]) / 2];
- g.fill(tube([root, mid, head], w * 1.25, w * 0.6, false), STEM, 0.8);
- if (w > 1.2) { const lp = 0.45 + r() * 0.25, at: P = [root[0] + (head[0] - root[0]) * lp, root[1] + (head[1] - root[1]) * lp], dir = r() < 0.5 ? -1 : 1; g.fill(tube([at, [at[0] + dir * w * 7, at[1] - w * 3], [at[0] + dir * w * 11, at[1] - w * 9]], w * 1.1, w * 0.4, false), STEM, 0.75); }
-};
-// one flower. `size` is its head radius on screen; everything else follows from that.
-export const flower = (g: Gfx, sp: Sp, at: P, size: number, seed: number, o: { variant?: number; lean?: number; dip?: number; light?: number } = {}) => {
- const r = rng(seed), v = o.variant ?? Math.floor(r() * 4), [col, dark] = COL[sp], lean = (o.lean ?? 0) + (o.dip ?? 0) * 0.5;
- const head: P = [at[0] + lean * size * 1.6, at[1] - size * (sp === "daisy" ? 2.6 : sp === "poppy" ? 2.4 : sp === "cosmos" ? 3 : 2.2) * (1 - (o.dip ?? 0) * 0.12)];
- if (size < 3) { g.fill(oval(head[0], head[1], size * 1.2, size, 7), col, 0.75); return; }
- if (size < 7) { g.fill(oval(head[0] + size * 0.3, head[1] + size * 0.3, size * 1.1, size * 0.9, 8), dark, 0.4); g.fill(oval(head[0], head[1], size * 1.15, size * 0.95, 8), col, 0.85); return; } /* two dabs: colour and its shadow */
- stem(g, at, head, Math.max(0.7, size * 0.11), seed + 1, lean);
- const petals = sp === "daisy" ? 13 : sp === "poppy" ? 4 : sp === "cornflower" ? 11 : sp === "cosmos" ? 8 : 5;
- const bud = v === 3, profile = v === 2, tilt = v === 1 ? 0.55 : 1;
- if (bud) { g.fill(oval(head[0], head[1], size * 0.5, size * 0.78, 9), col, 0.85); g.fill(tube([[head[0], head[1] + size * 0.6], [head[0], head[1] - size * 0.2]], size * 0.36, size * 0.2, false), STEM, 0.8); return; }
- const open = profile ? Math.PI * 0.55 : Math.PI * 2, a0 = profile ? -Math.PI * 0.78 : 0;
- if (size < 16) { for (let i = 0; i < petals; i++) { const a = a0 + (i / petals) * open, e: P = [head[0] + Math.cos(a) * size * (profile ? 0.8 : 1), head[1] + Math.sin(a) * size * tilt]; g.fill(tube([head, e], size * 0.3, size * 0.14, false), i % 3 === 0 ? dark : col, 0.85); } g.fill(oval(head[0], head[1], size * 0.3, size * 0.3 * tilt, 8), sp === "daisy" ? BUTTERCUP : dark, 0.9); return; } /* petals as single strokes */
- for (let i = 0; i < petals; i++) {
- const a = a0 + (i / petals) * open + (r() - 0.5) * 0.12, L = size * (0.85 + r() * 0.3), lit = Math.cos(a + 0.9) * 0.5 + 0.5; /* the sun is upper right, so petals facing it are paler */
- const tip: P = [head[0] + Math.cos(a) * L, head[1] + Math.sin(a) * L * tilt], mid: P = [head[0] + Math.cos(a + 0.18) * L * 0.55, head[1] + Math.sin(a + 0.18) * L * 0.55 * tilt];
- const pet = [head, mid, tip, [head[0] + Math.cos(a - 0.2) * L * 0.5, head[1] + Math.sin(a - 0.2) * L * 0.5 * tilt] as P];
- g.wash(pet, lit > 0.55 ? col : dark, { alpha: sp === "daisy" ? 0.5 : 0.62, seed: seed + i * 3, dx: 1, dy: 1, shrink: 0.94, rim: r() > 0.5 });
- if (sp === "daisy" && lit > 0.6) g.fill(tube([head, tip], L * 0.16, L * 0.1, false), PAPER_W, 0.5); /* paper white left for the lit petals */
- }
- const cr = size * (sp === "poppy" ? 0.34 : 0.28);
- g.wash(oval(head[0], head[1], cr, cr * tilt, 10), sp === "daisy" || sp === "cosmos" ? BUTTERCUP : sp === "poppy" ? POPPY_DARK : dark, { alpha: 0.85, seed: seed + 40, dx: 0, dy: 0, shrink: 0.95, rim: true });
- if (sp === "poppy") { const r2 = rng(seed + 9); for (let i = 0; i < 7; i++) { const a = r2() * 6.283; g.fill(oval(head[0] + Math.cos(a) * cr * 1.5, head[1] + Math.sin(a) * cr * 1.5 * tilt, size * 0.05, size * 0.05, 6), POPPY_DARK, 0.7); } }
- g.fill(oval(at[0] - size * 0.5, at[1] + size * 0.12, size * 0.85, size * 0.22, 9), GRASS_SHADE, 0.18); /* the dab of shadow it throws on the grass */
-};
-
-// a DRIFT: a hand-placed centre, a radius, a species, and seeded scatter that thins toward its
-// edge. No even scatter anywhere, and no variant more than a quarter of the drift.
-export type Drift = { sp: Sp; at: P; r: number; n: number; size: number; seed: number };
-export const drift = (g: Gfx, d: Drift, project: (p: P) => P, k: number, lean = 0, lod = 1) => {
- const r = rng(d.seed);
- const items: { p: P; s: number; v: number; seed: number }[] = [];
- for (let i = 0; i < d.n; i++) {
- const a = r() * 6.283, rad = Math.pow(r(), 0.7) * d.r, w: P = [d.at[0] + Math.cos(a) * rad, d.at[1] + Math.sin(a) * rad * 0.42];
- items.push({ p: project(w), s: d.size * k * (0.75 + r() * 0.5), v: Math.floor(r() * 4), seed: d.seed + i * 17 });
- }
- items.sort((a, b) => a.p[1] - b.p[1]); /* back to front, so nearer flowers overlap the ones behind */
- items.forEach((it) => { if (it.s * lod < 1.4) return; flower(g, d.sp, it.p, it.s, it.seed, { variant: it.v, lean }); });
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/paint.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/paint.ts
deleted file mode 100644
index 5b611ec..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/paint.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// WATERCOLOUR, THE VERBS. Every mark in the finale is one of these: a graded wash, a wet band
-// that spreads and pools, a lifted highlight (paper left, or pigment taken back off), dry-brush
-// texture dragged over dry paint, and a backrun where clean water hit a drying wash.
-import { Ctx, Gfx, P, displace, jitter, oval, rng, sample, tube } from "../../core";
-
-export const wet = (g: Gfx, pts: P[], col: string, o: { alpha?: number; seed?: number; shrink?: number; rim?: boolean; dx?: number; dy?: number } = {}) =>
- g.wash(pts, col, { alpha: o.alpha ?? 0.42, seed: o.seed ?? 1, dx: o.dx ?? 2, dy: o.dy ?? 2, shrink: o.shrink ?? 0.97, rim: o.rim ?? true });
-
-// pigment never dries flat: it pools where the water sat and lifts where it ran out
-export const mottle = (g: Gfx, pts: P[], col: string, seed: number, n: number, a: number) => {
- const r = rng(seed), c = pts.reduce((s, p) => [s[0] + p[0] / pts.length, s[1] + p[1] / pts.length] as P, [0, 0] as P);
- for (let i = 0; i < n; i++) { const k = 0.3 + r() * 0.45, dx = (r() - 0.5) * 60, dy = (r() - 0.5) * 50; g.wash(pts.map((p) => [c[0] + (p[0] - c[0]) * k + dx, c[1] + (p[1] - c[1]) * k + dy] as P), col, { alpha: a * (0.5 + r() * 0.7), seed: seed + i * 3, dx: (r() - 0.5) * 8, dy: (r() - 0.5) * 8, shrink: 0.88 + r() * 0.2, rim: r() > 0.5 }); }
-};
-// a graded sky: cream at the horizon, blue at the top, and the sun is simply where the paper was left alone
-export const graded = (g: Gfx, x0: number, y0: number, x1: number, y1: number, top: string, low: string) => {
- const c = g.cur, gr = c.createLinearGradient(0, y0, 0, y1); gr.addColorStop(0, top); gr.addColorStop(0.72, low); gr.addColorStop(1, low);
- g.touch(x0, y0, x1, y1); c.fillStyle = gr; c.fillRect(x0, y0, x1 - x0, y1 - y0);
-};
-export const sunBloom = (g: Gfx, at: P, r: number, col: string, a = 0.9) => {
- const c = g.cur, gr = c.createRadialGradient(at[0], at[1], 0, at[0], at[1], r);
- gr.addColorStop(0, col + "ff"); gr.addColorStop(0.45, col + "aa"); gr.addColorStop(0.8, col + "33"); gr.addColorStop(1, col + "00");
- g.touch(at[0] - r, at[1] - r, at[0] + r, at[1] + r); c.save(); c.globalAlpha = a; c.fillStyle = gr; c.fillRect(at[0] - r, at[1] - r, r * 2, r * 2); c.restore();
-};
-// clean water into a drying wash: it pushes pigment out and strands it in a hard ring
-export const backrun = (g: Gfx, at: P, r: number, seed: number, col: string, strength = 0.55) => {
- const c = g.cur;
- c.globalCompositeOperation = "destination-out";
- g.wash(jitter(oval(at[0], at[1], r, r * 0.86, 18), r * 0.2, seed), "#000000", { alpha: strength, seed, dx: 0, dy: 0, shrink: 1, rim: false });
- c.globalCompositeOperation = "multiply";
- g.wash(jitter(oval(at[0], at[1], r * 1.06, r * 0.93, 18), r * 0.22, seed + 7), col, { alpha: 0.24, seed: seed + 7, dx: 0, dy: 0, shrink: 1.02, rim: true });
- c.globalCompositeOperation = "source-over";
-};
-// take pigment back off with a damp brush: the only way to get light back in watercolour
-export const lift = (g: Gfx, pts: P[], seed: number, strength = 0.5) => { const c = g.cur; c.globalCompositeOperation = "destination-out"; g.wash(pts, "#000000", { alpha: strength, seed, dx: 0, dy: 0, shrink: 1, rim: false }); c.globalCompositeOperation = "source-over"; };
-// dry brush: a loaded brush dragged over dry paper skips, and only the tooth takes colour
-export const dryBrush = (g: Gfx, a: P, b: P, w: number, col: string, seed: number, alpha = 0.5) => {
- const r = rng(seed), n = 5 + Math.floor(r() * 4), c = g.cur;
- for (let i = 0; i < n; i++) { const t0 = r() * 0.5, t1 = t0 + 0.2 + r() * 0.5, p0: P = [a[0] + (b[0] - a[0]) * t0, a[1] + (b[1] - a[1]) * t0], p1: P = [a[0] + (b[0] - a[0]) * t1, a[1] + (b[1] - a[1]) * t1]; g.fill(tube([p0, p1], w * (0.5 + r() * 0.8), w * 0.3, false), col, alpha * (0.5 + r() * 0.6)); }
-};
-// a blade of grass: it leaves the ground thick and ends in a point, and it bends with the wind
-export const blade = (g: Gfx, root: P, len: number, ang: number, lean: number, w: number, col: string, seed: number, alpha = 0.9) => {
- const pts: P[] = []; for (let i = 0; i <= 5; i++) { const t = i / 5, a = ang + lean * t * t, r = len * t; pts.push([root[0] + Math.sin(a) * r, root[1] - Math.cos(a) * r]); }
- g.fill(tube(pts, w, w * 0.12, false), col, alpha);
-};
-export const clump = (g: Gfx, root: P, h: number, spread: number, col: string, seed: number, lean = 0, n = 7, alpha = 0.9) => {
- const r = rng(seed);
- for (let i = 0; i < n; i++) { const t = n > 1 ? i / (n - 1) - 0.5 : 0; blade(g, [root[0] + t * spread * 0.4 + (r() - 0.5) * 4, root[1] + (r() - 0.5) * 3], h * (0.6 + r() * 0.65), t * spread * 0.014 + (r() - 0.5) * 0.12, lean * (0.7 + r() * 0.6), Math.max(0.8, h * 0.028), col, seed + i, alpha * (0.7 + r() * 0.35)); }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/scene.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/scene.ts
deleted file mode 100644
index 88cf2ac..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/scene.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-// THE WORLD, PAINTED. Sky, hills, far field, the path, and the grass planes. Everything is laid
-// as a wash first and worked into while it is wet; nothing is outlined. Farther planes are
-// paler, bluer, softer and lower in contrast, which is the only way distance reads in paint.
-import { Gfx, P, jitter, oval, rng } from "../../core";
-import { Cam, CLOUD_SHADE, FIELD_COOL, FIELD_LIT, FIELD_MID, GRASS_LIT, GRASS_MID, GRASS_SHADE, HILL_FAR, HILL_NEAR, HORIZON, PATH, SKY_LOW, SKY_TOP, SUN, SUN_AT, TREE, projector } from "./world";
-import { backrun, clump, dryBrush, graded, lift, mottle, sunBloom, wet } from "./paint";
-
-// a band of ground: the top contour, then enough points down the sides and along the bottom that
-// the wash's own smoothing cannot bulge the corners out into the sky
-const slab = (top: P[], bottom: number): P[] => {
- const out = [...top], right = top[top.length - 1][0], left = top[0][0];
- for (let i = 1; i <= 6; i++) out.push([right, top[top.length - 1][1] + ((bottom - top[top.length - 1][1]) * i) / 6]);
- for (let i = 1; i <= 8; i++) out.push([right + ((left - right) * i) / 8, bottom]);
- for (let i = 1; i < 6; i++) out.push([left, bottom + ((top[0][1] - bottom) * i) / 6]);
- return out;
-};
-const ridge = (y: number, amp: number, seed: number, from = -200, to = 1300): P[] => {
- const r = rng(seed), out: P[] = [];
- for (let x = from; x <= to; x += 60) out.push([x, y + Math.sin(x * 0.0042 + seed) * amp + Math.sin(x * 0.0011 + seed * 2) * amp * 1.6 + (r() - 0.5) * 6]);
- return out;
-};
-
-export const sky = (g: Gfx, c: Cam, W: number, H: number) => {
- const { at } = projector(c, 1e6), hor = projector(c, 20).at([0, HORIZON])[1];
- graded(g, -20, -20, W + 20, hor + 40, SKY_TOP, SKY_LOW);
- sunBloom(g, SUN_AT, 330, "#f8e6bd", 0.34); /* the sun is where the paper was left lightest, never a disc of paint */
- sunBloom(g, SUN_AT, 150, "#fdf4de", 0.6); sunBloom(g, SUN_AT, 62, "#fffdf7", 0.9);
- /* three cumulus, lifted: white tops, a blue-violet wash underneath */
- ([[250, 150, 140, 46], [620, 96, 92, 30], [900, 250, 110, 34]] as number[][]).forEach(([x, y, rx, ry], i) => {
- const top = jitter([...Array(9)].map((_, k) => { const a = Math.PI + (k / 8) * Math.PI; return [x + Math.cos(a) * rx, y + Math.sin(a) * ry * (0.7 + 0.5 * Math.sin(k * 2.1 + i)) ] as P; }), 6, 5200 + i);
- const base: P[] = [...top, [x + rx, y + ry * 0.35], [x - rx, y + ry * 0.35]];
- wet(g, base, CLOUD_SHADE, { alpha: 0.3, seed: 5210 + i, shrink: 0.98, dx: 2, dy: 4 });
- lift(g, jitter([...Array(9)].map((_, k) => { const a = Math.PI + (k / 8) * Math.PI; return [x + Math.cos(a) * rx * 0.94, y - 4 + Math.sin(a) * ry * 0.9] as P; }), 5, 5220 + i), 5230 + i, 0.62);
- });
-};
-
-export const hills = (g: Gfx, c: Cam) => {
- const { at, k } = projector(c, 20);
- const far = ridge(HORIZON + 6, 16, 3.1).map(at), near = ridge(HORIZON + 34, 22, 5.7, -200, 1300).map(at);
- const floor = 540 + (760 - c.look[1]) * k + 900;
- wet(g, slab(far, floor), HILL_FAR, { alpha: 0.5, seed: 5300, shrink: 0.995, rim: false, dx: 1, dy: 3 });
- wet(g, slab(near, floor), HILL_NEAR, { alpha: 0.46, seed: 5310, shrink: 0.995, rim: false, dx: -2, dy: 3 });
- mottle(g, [...near.slice(6, 14), ...far.slice(6, 14).reverse()], HILL_NEAR, 5320, 3, 0.1);
- /* a hedgerow of six rounded trees on the right ridge, and one lone tree on the left */
- const r = rng(5330);
- for (let i = 0; i < 6; i++) { const x = 760 + i * 52 + r() * 14, p = at([x, HORIZON + 30 + Math.sin(x * 0.0042 + 5.7) * 22 + Math.sin(x * 0.0011 + 11.4) * 35]); wet(g, jitter(oval(p[0], p[1] - 9 * k, 15 * k * (0.8 + r() * 0.5), 11 * k * (0.8 + r() * 0.4), 11), 2.5, 5340 + i), TREE, { alpha: 0.42, seed: 5340 + i, shrink: 0.96, rim: false }); }
- const lone = at([210, HORIZON + 26 + Math.sin(210 * 0.0042 + 5.7) * 22 + Math.sin(210 * 0.0011 + 11.4) * 35]), th = 26 * k;
- g.fill([[lone[0] - 1.6, lone[1] + 2], [lone[0] + 1.6, lone[1] + 2], [lone[0] + 1.1, lone[1] - th], [lone[0] - 1.1, lone[1] - th]], TREE, 0.55);
- wet(g, jitter(oval(lone[0], lone[1] - th - 9 * k, 15 * k, 13 * k, 13), 2.5, 5360), TREE, { alpha: 0.52, seed: 5360, shrink: 0.94, rim: true }); /* one lone tree on the left ridge, the thing your eye goes to */
-};
-
-// the far field: colour only, no plants, and the cloud shadows that sell the sunlight
-export const farField = (g: Gfx, c: Cam) => {
- const { at, k } = projector(c, 8), bottom = 540 + (900 - c.look[1]) * k;
- ([[HORIZON + 44, FIELD_COOL, 0.4, 5400], [HORIZON + 96, FIELD_MID, 0.42, 5410], [HORIZON + 168, FIELD_LIT, 0.44, 5420]] as [number, string, number, number][]).forEach(([y, col, a, seed], i) => {
- const band = ridge(y, 9, seed * 0.001 + i).map(at);
- wet(g, slab(band, bottom), col, { alpha: a, seed, shrink: 0.996, rim: i > 0, dx: i ? 3 : -3, dy: 2 });
- });
- const r = rng(5430); /* drifts of flower colour, as dabs of pure pigment, nothing drawn */
- ([["#e2452b", 700, HORIZON + 70, 150, 26], ["#f5c93f", 330, HORIZON + 110, 170, 30], ["#ef9ab8", 880, HORIZON + 140, 120, 18]] as [string, number, number, number, number][]).forEach(([col, cx, cy, rad, n], i) => {
- for (let j = 0; j < n; j++) { const a = r() * 6.283, d = Math.sqrt(r()) * rad, p = at([cx + Math.cos(a) * d, cy + Math.sin(a) * d * 0.45]); g.fill(oval(p[0], p[1], (1.6 + r() * 1.8) * k, (1.2 + r() * 1.1) * k, 7), col, 0.32 + r() * 0.3); }
- });
- ([[420, HORIZON + 120, 260, 60, 5440], [860, HORIZON + 190, 200, 44, 5450]] as number[][]).forEach(([cx, cy, rx, ry, seed]) => { const p = at([cx, cy]); wet(g, jitter(oval(p[0], p[1], rx * k, ry * k, 14), 8, seed), CLOUD_SHADE, { alpha: 0.1, seed, shrink: 0.98, rim: false }); }); /* cloud shadows crossing the field */
-};
-
-// the footpath: someone walked out here, and the eye follows them to the gap in the ridges
-export const footpath = (g: Gfx, c: Cam) => {
- const { at, k } = projector(c, 3.5);
- const spine: P[] = [[980, 1140], [860, 980], [740, 830], [640, 690], [560, 560], [520, 470], [512, 424]];
- const w = (t: number) => (62 - 56 * t) * k;
- const L: P[] = [], R: P[] = [];
- spine.forEach((p, i) => { const t = i / (spine.length - 1), q = at(p); L.push([q[0] - w(t), q[1]]); R.push([q[0] + w(t), q[1]]); });
- wet(g, [...L, ...R.reverse()], PATH, { alpha: 0.42, seed: 5500, shrink: 0.985, rim: false, dx: 2, dy: 2 });
- mottle(g, [...L.slice(0, 4), ...R.slice(0, 4).reverse()], PATH, 5510, 3, 0.1);
-};
-
-// a grass plane: three wash bands on an S contour, then dry-brush and blades on top of dry paint
-export const grassWash = (g: Gfx, c: Cam, z: number, y0: number, seed: number, o: { blades?: number; lean?: number; cool?: boolean; fade?: number } = {}) => {
- const { at, k } = projector(c, z), bottom = 540 + (1500 - c.look[1]) * k, r = rng(seed), fade = o.fade ?? 0;
- const mix = (a: string, b: string, t: number) => { const h = (x: string) => [parseInt(x.slice(1, 3), 16), parseInt(x.slice(3, 5), 16), parseInt(x.slice(5, 7), 16)]; const A = h(a), B = h(b); return "#" + A.map((v, i) => Math.round(v + (B[i] - v) * t).toString(16).padStart(2, "0")).join(""); };
- const air = (col: string) => mix(col, "#cfd9dd", fade); /* farther is paler, bluer, lower in contrast: that is all distance is */
- const cols = (o.cool ? [GRASS_SHADE, GRASS_MID, GRASS_LIT] : [GRASS_MID, GRASS_LIT, GRASS_MID]).map(air);
- cols.forEach((col, i) => {
- const band = ridge(y0 + i * 44, 13, seed * 0.01 + i * 3).map(at);
- wet(g, slab(band, bottom), col, { alpha: (0.34 + i * 0.05) * (1 + (1 - fade) * 1.1), seed: seed + i, shrink: 0.996, rim: i === 1, dx: i % 2 ? 3 : -3, dy: 2 }); /* the near planes carry enough pigment to hide what is behind them, or the picture goes milky */
- const hollow = ridge(y0 + i * 44 + 6, 13, seed * 0.01 + i * 3).map(at), lipY = 540 + (y0 + i * 44 + 30 - c.look[1]) * k;
- wet(g, slab(hollow, lipY), air(GRASS_SHADE), { alpha: 0.16 + (1 - fade) * 0.1, seed: seed + 40 + i, shrink: 0.995, rim: false, dx: -2, dy: 1 }); /* the shaded lip where the ground dips away */
- });
- mottle(g, [[-300, 540 + (y0 - c.look[1]) * k] as P, [1400, 540 + (y0 - c.look[1]) * k] as P, [1400, bottom] as P, [-300, bottom] as P], air(GRASS_MID), seed + 90, 4, 0.05);
-};
-
-// the blades go on DRY paint, so they are their own pass and they keep their edges
-export const grassBlades = (g: Gfx, c: Cam, z: number, y0: number, seed: number, o: { blades?: number; lean?: number; fade?: number } = {}) => {
- const { at, k } = projector(c, z), r = rng(seed + 7), fade = o.fade ?? 0;
- const mix = (a: string, b: string, t: number) => { const h = (x: string) => [parseInt(x.slice(1, 3), 16), parseInt(x.slice(3, 5), 16), parseInt(x.slice(5, 7), 16)]; const A = h(a), B = h(b); return "#" + A.map((v, i) => Math.round(v + (B[i] - v) * t).toString(16).padStart(2, "0")).join(""); };
- const air = (col: string) => mix(col, "#cfd9dd", fade), n = o.blades ?? 26, palette = [GRASS_SHADE, GRASS_MID, GRASS_LIT].map(air);
- for (let i = 0; i < n; i++) {
- const wx = -260 + r() * 1620, wy = y0 + 16 + r() * 200, p = at([wx, wy]), h = (30 + r() * 62) * k, lean = (o.lean ?? 0) + (r() - 0.5) * 0.12;
- g.fill(oval(p[0] - h * 0.22, p[1] + 2 * k, h * 0.3, h * 0.09, 9), air(GRASS_SHADE), 0.2 * (1 - fade)); /* the shadow the clump throws to its lower left: this is what says SUN */
- clump(g, p, h, 22 * k, palette[Math.floor(r() * 3)], seed * 7 + i * 13, lean, 5 + Math.floor(r() * 5), (0.62 + r() * 0.33) * (1 - fade * 0.45));
- if (r() < 0.24) { const tip: P = [p[0] + Math.sin(lean * 1.6) * h * 0.6, p[1] - h * 0.95]; g.fill(oval(tip[0], tip[1], 2.6 * k, 5.6 * k, 9), air(GRASS_SHADE), 0.5 * (1 - fade)); }
- }
- for (let i = 0; i < n * 0.7; i++) { const wx = -260 + r() * 1620, wy = y0 + 50 + r() * 170, p = at([wx, wy]); dryBrush(g, p, [p[0] + (r() - 0.5) * 80 * k, p[1] - (18 + r() * 34) * k], 2.6 * k, air(GRASS_SHADE), seed * 11 + i, 0.3 * (1 - fade * 0.6)); }
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/sheet.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/sheet.ts
deleted file mode 100644
index dbde46e..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/sheet.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-// WHAT IT LEFT BEHIND. A sheet of blueprint lying in the grass with a butterfly-shaped BLANK in
-// it, and the winding key on top of it. The plate is still here; the creature is not in it.
-import { Gfx, P, jitter, oval, rng, tube } from "../../core";
-import { CX, CY, FW, FW_H, FW_T, HW, HW_H, HW_T, REST, THORAX, cen, lerp, wingGeom } from "../geom";
-import { PAPER_W } from "./world";
-import { lift, mottle, wet } from "./paint";
-
-const GROUND_BLUE = "#2e5f86";
-export const blueprintSheet = (g: Gfx, at: P, w: number, seed = 6000) => {
- const c = g.cur, h = w * 0.72, r = rng(seed);
- /* the sheet lies in the grass, so it is a parallelogram with a lifted near corner */
- const quad: P[] = [[at[0] - w * 0.5, at[1] - h * 0.34], [at[0] + w * 0.52, at[1] - h * 0.46], [at[0] + w * 0.46, at[1] + h * 0.4], [at[0] - w * 0.56, at[1] + h * 0.5]];
- wet(g, jitter(quad, w * 0.012, seed), GROUND_BLUE, { alpha: 0.62, seed, shrink: 0.985, rim: true, dx: 2, dy: 2 });
- mottle(g, quad, GROUND_BLUE, seed + 3, 3, 0.12);
- const grid = 5; c.save(); g.path(c, quad); c.clip();
- for (let i = 1; i < grid; i++) { const a = lerp(quad[0], quad[3], i / grid), b = lerp(quad[1], quad[2], i / grid); g.fill(tube([a, b], w * 0.004, w * 0.004, false), "#9fc4dd", 0.3); const p = lerp(quad[0], quad[1], i / grid), q = lerp(quad[3], quad[2], i / grid); g.fill(tube([p, q], w * 0.004, w * 0.004, false), "#9fc4dd", 0.3); }
- c.restore();
- /* the blank: the creature's own silhouette, lifted clean out of the plate */
- const sc = (w / 1080) * 1.5, T = (p: P): P => [at[0] + (p[0] - CX) * sc * 0.92, at[1] + (p[1] - CY) * sc * 0.5];
- const wings = [wingGeom(-1, HW, HW_H, HW_T, 2000, REST), wingGeom(1, HW, HW_H, HW_T, 2600, REST), wingGeom(-1, FW, FW_H, FW_T, 1000, REST), wingGeom(1, FW, FW_H, FW_T, 1600, REST)];
- wings.forEach((wg, i) => lift(g, wg.out.map(T), seed + 20 + i, 0.92));
- lift(g, THORAX.map(T), seed + 30, 0.92);
- const abd: P[] = []; for (let i = 0; i <= 6; i++) { const t = i / 6, y = 70 + 170 * t, hw = 23 * (1 - t) ** 0.8 + 6.5; abd.push(T([CX + hw, CY + y])); } for (let i = 6; i >= 0; i--) { const t = i / 6, y = 70 + 170 * t, hw = 23 * (1 - t) ** 0.8 + 6.5; abd.push(T([CX - hw, CY + y])); }
- lift(g, abd, seed + 32, 0.92);
- /* the key, lying on top of it: it does not need winding any more */
- const k: P = [at[0] + w * 0.3, at[1] + h * 0.16], kw = w * 0.055;
- g.fill(tube([[k[0] - kw * 2.2, k[1] + kw * 0.6], [k[0] + kw * 1.4, k[1] - kw * 0.4]], kw * 0.42, kw * 0.42, false), "#d8dfe4", 0.9);
- [-1, 1].forEach((sd) => { const b = jitter(oval(k[0] + kw * (1.9 + sd * 0.9), k[1] - kw * (0.5 + sd * 0.25), kw * 0.8, kw * 0.58, 10), kw * 0.06, seed + 40 + sd); g.fill(b, "#d8dfe4", 0.9); g.fill(oval(k[0] + kw * (1.9 + sd * 0.9), k[1] - kw * (0.5 + sd * 0.25), kw * 0.34, kw * 0.24, 8), "#8fa8b8", 0.8); });
- g.fill(oval(k[0] - kw * 0.4, k[1] + kw * 1.1, kw * 2.4, kw * 0.5, 10), "#5e7f52", 0.2); /* its shadow in the grass */
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/signature.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/signature.ts
deleted file mode 100644
index 596a12a..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/signature.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-// THE SIGNATURE. `alexgreenshpun.com`, written the way a watercolourist signs a corner: a rigger
-// brush in a dilute warm grey, five connected strokes and two marks, not a font and not the
-// drafting capitals. Control points only. It is a URL first, so it has to stay legible.
-import { Gfx, P, tube } from "../../core";
-import { SIG } from "./world";
-import { backrun, lift } from "./paint";
-
-// authored in em units: baseline y = 0, x-height = 1, ascenders about 1.7, descenders about -0.8
-const ALEX: P[] = [[0.62, 0.02], [0.34, 0.06], [0.12, 0.42], [0.2, 0.86], [0.46, 0.95], [0.63, 0.62], [0.6, 0.06], [0.72, 0.02], [0.86, 0.3],
- [0.98, 1.05], [1.06, 1.62], [1.12, 0.9], [1.1, 0.24], [1.22, 0.04], [1.4, 0.22],
- [1.52, 0.5], [1.72, 0.66], [1.78, 0.48], [1.62, 0.3], [1.46, 0.36], [1.44, 0.14], [1.6, 0.02], [1.8, 0.16],
- [2.02, 0.06], [2.38, 0.82], [2.5, 0.96], [2.62, 0.72], [2.78, 0.12]];
-const XBAR: P[] = [[2.06, 0.78], [2.3, 0.5], [2.56, 0.2], [2.8, 0.04]];
-const GREEN: P[] = [[3.0, 0.72], [2.88, 0.36], [3.0, 0.06], [3.22, 0.1], [3.3, 0.5], [3.28, 0.02], [3.24, -0.5], [3.06, -0.74], [2.92, -0.6],
- [3.42, 0.08], [3.5, 0.6], [3.54, 0.26], [3.7, 0.52], [3.86, 0.44],
- [3.98, 0.52], [4.14, 0.62], [4.2, 0.4], [4.04, 0.24], [3.94, 0.36], [3.98, 0.08], [4.2, 0.04], [4.36, 0.2],
- [4.46, 0.56], [4.62, 0.64], [4.68, 0.42], [4.52, 0.26], [4.42, 0.38], [4.46, 0.08], [4.68, 0.04], [4.86, 0.22],
- [4.94, 0.66], [4.96, 0.1], [5.02, 0.48], [5.2, 0.66], [5.36, 0.5], [5.38, 0.06]];
-const SHPUN: P[] = [[5.66, 0.58], [5.56, 0.7], [5.4, 0.6], [5.5, 0.4], [5.7, 0.3], [5.76, 0.12], [5.6, 0.02], [5.46, 0.12],
- [5.96, 0.1], [6.0, 0.9], [6.04, 1.66], [6.06, 0.72], [6.1, 0.1], [6.22, 0.5], [6.4, 0.66], [6.54, 0.48], [6.56, 0.06],
- [6.86, 0.66], [6.8, 0.1], [6.76, -0.46], [6.72, -0.76], [6.88, 0.52], [7.06, 0.66], [7.22, 0.5], [7.24, 0.2], [7.1, 0.04], [6.94, 0.14],
- [7.5, 0.64], [7.46, 0.2], [7.56, 0.06], [7.74, 0.16], [7.82, 0.62], [7.86, 0.08],
- [8.02, 0.62], [8.04, 0.08], [8.1, 0.46], [8.28, 0.64], [8.44, 0.48], [8.46, 0.06]];
-const COM: P[] = [[9.06, 0.54], [8.92, 0.66], [8.74, 0.56], [8.7, 0.26], [8.82, 0.06], [9.0, 0.12],
- [9.2, 0.5], [9.36, 0.64], [9.52, 0.5], [9.54, 0.22], [9.4, 0.06], [9.22, 0.16], [9.2, 0.46],
- [9.72, 0.62], [9.74, 0.08], [9.8, 0.46], [9.96, 0.62], [10.08, 0.46], [10.1, 0.08], [10.16, 0.46], [10.32, 0.62], [10.44, 0.46], [10.46, 0.06]];
-const DOT: P = [8.62, 0.06];
-const STROKES: [P[], number][] = [[ALEX, 0], [XBAR, 1], [GREEN, 2], [SHPUN, 3], [COM, 4]];
-
-// right edge of the last letter at x = 1036, baseline at y = 1034, x-height 12 px, and the
-// baseline rises two degrees to the right the way a hand does
-export const signature = (g: Gfx, p = 1, alpha = 0.75) => {
- if (p <= 0) return;
- const em = 15.5, W = 212, k = W / 10.5, x0 = 1036 - W, y0 = 1032, rise = Math.tan((-2 * Math.PI) / 180);
- const T = ([x, y]: P): P => [x0 + x * k, y0 - y * em + (x * k) * rise];
- const each = 1 / STROKES.length;
- STROKES.forEach(([pts, i]) => {
- const q = Math.max(0, Math.min(1, (p - i * each) / each)); if (q <= 0) return;
- const n = Math.max(2, Math.round(pts.length * q)), s = pts.slice(0, n).map(T);
- g.fill(tube(s, 2.7, 1.5, false), SIG, alpha); /* a rigger: it starts loaded and runs thin */
- if (q >= 1) g.fill([[s[s.length - 1][0] - 1.4, s[s.length - 1][1] - 1.4], [s[s.length - 1][0] + 1.6, s[s.length - 1][1] - 1], [s[s.length - 1][0] + 1.2, s[s.length - 1][1] + 1.6], [s[s.length - 1][0] - 1.6, s[s.length - 1][1] + 1.2]], SIG, alpha * 0.9); /* pigment pools where the brush leaves the paper */
- });
- if (p > 0.72) { const d = T(DOT); g.fill([[d[0] - 1.6, d[1] - 1.6], [d[0] + 1.8, d[1] - 1.3], [d[0] + 1.5, d[1] + 1.7], [d[0] - 1.7, d[1] + 1.4]], SIG, alpha); }
-};
-// before signing over a dark passage a painter lifts the corner with a clean damp brush
-export const clearCorner = (g: Gfx, p = 1) => {
- if (p <= 0) return;
- const pts: P[] = [[836, 1000], [1060, 994], [1064, 1052], [832, 1058]];
- lift(g, pts, 5900, 0.45 * p);
- if (p >= 1) backrun(g, [1046, 1044], 26, 5910, "#b8ab96", 0.16);
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/world.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/world.ts
deleted file mode 100644
index 4f9da9c..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/finale/world.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-// THE MEADOW, AS A WORLD. Positions are written as they appear on the LAST frame of the film,
-// which makes the spec's table readable, and everything earlier is that world seen from closer
-// in. A plane at depth z is magnified about the camera's look-at point by (Dend + z)/(D + z):
-// near things swell fast as the camera comes in, the hills hardly move at all. One dolly, one
-// number, and the parallax is true for every element at once.
-import { P } from "../../core";
-
-export const DEND = 1; // the dolly distance on the last frame; the hero plane is 1:1 there
-export type Plane = { id: string; z: number };
-export const PLANES: Plane[] = [
- { id: "fringe", z: -0.2 }, /* grass across the lens, huge and soft at the open */
- { id: "hero", z: 0 }, /* the flower it is on, and the blueprint sheet */
- { id: "hero2", z: 0.3 },
- { id: "p2", z: 1.0 }, { id: "p3", z: 2.2 }, { id: "p4", z: 3.5 },
- { id: "far", z: 8 }, /* the far field: colour, no plants */
- { id: "hills", z: 20 },
- { id: "sky", z: 1e6 }, /* no parallax at all */
-];
-export const zOf = (id: string) => PLANES.find((p) => p.id === id)?.z ?? 0;
-
-export type Cam = { D: number; look: P };
-export const scaleAt = (c: Cam, z: number) => (DEND + z) / (c.D + z);
-export const project = (c: Cam, z: number, p: P): P => { const k = scaleAt(c, z); return [540 + (p[0] - c.look[0]) * k, 540 + (p[1] - c.look[1]) * k]; };
-export const projector = (c: Cam, z: number) => { const k = scaleAt(c, z); return { k, at: (p: P): P => [540 + (p[0] - c.look[0]) * k, 540 + (p[1] - c.look[1]) * k] }; };
-
-// ---------------------------------------------------------------- the paint box
-export const SKY_TOP = "#a6c6e4", SKY_LOW = "#f4e7d0", SUN = "#f7dd9a", CLOUD_SHADE = "#c8c9dd";
-export const HILL_FAR = "#aec2c4", HILL_NEAR = "#94ad9b", TREE = "#5f7e69";
-export const FIELD_LIT = "#cbd485", FIELD_MID = "#a8bd6f", FIELD_COOL = "#7f9d78";
-export const GRASS_LIT = "#ccd677", GRASS_MID = "#94b155", GRASS_SHADE = "#5e7f52", PATH = "#e9dfc2";
-export const DAISY = "#fbf7ee", DAISY_SHADE = "#e8ddc4", POPPY = "#e2452b", POPPY_DARK = "#8d2a20";
-export const CORNFLOWER = "#5b7fc7", COSMOS = "#ef9ab8", BUTTERCUP = "#f5c93f", STEM = "#8aa35f";
-export const ROSE = "#e9a3ad", PEACH = "#f5b98a", BUTTER = "#f3d577", DENIM = "#6f93c4", INK_P = "#4a4a52";
-export const PAPER_W = "#fbf7ee", SIG = "#5b5148";
-
-// where the light is: upper right, so everything has a lit side and a shadow to its lower left
-export const SUN_AT: P = [830, 150];
-export const HORIZON = 410; // world y where hills meet sky on the last frame
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/geom.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/geom.ts
deleted file mode 100644
index 816cb1e..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/geom.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-// PLATE GEOMETRY. The authored control points of MECHANICAL LEPIDOPTERA, and the pose that
-// moves them. Nothing here draws. A pose transforms CONTROL POINTS only (spec 6.4), so line
-// weight never changes when a wing foreshortens.
-import { P, jitter } from "../core";
-
-export const WHITE = "#f1f7fb", CYAN = "#a7d8ec", DIM = "#7fbcd8", GROUND = "#123a63";
-export const CX = 540, CY = 418, K = 0.9;
-export const FW: P[] = [[26, -52], [120, -132], [232, -216], [332, -272], [402, -286], [430, -250], [434, -190], [412, -120], [374, -60], [300, -18], [200, 2], [100, -6], [30, -20]];
-export const HW: P[] = [[24, 2], [100, 22], [220, 30], [322, 62], [362, 122], [352, 192], [304, 252], [236, 292], [204, 342], [172, 302], [122, 262], [72, 182], [36, 92]];
-export const FW_H: P = [28, -38], HW_H: P = [26, 14];
-export const FW_T: P[] = [[402, -286], [433, -222], [424, -150], [392, -86], [318, -26], [208, 1]], HW_T: P[] = [[322, 62], [362, 150], [330, 226], [236, 292], [204, 342], [122, 262], [60, 150]];
-export const lerp = (a: P, b: P, t: number): P => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
-export const cen = (pts: P[]): P => [pts.reduce((a, p) => a + p[0], 0) / pts.length, pts.reduce((a, p) => a + p[1], 0) / pts.length];
-
-// A wing pose. flap 1 = spread flat on the sheet (the approved plate), 0.35 = raised and
-// foreshortened; sweep = the in-plane rotation the plate dimensions as "57o SWEEP", radians.
-export type Pose = { flap: number; sweep: number };
-export const REST: Pose = { flap: 1, sweep: 0 };
-export const posed = (pose: Pose): boolean => pose.flap !== 1 || pose.sweep !== 0;
-const SPAN = 420 * K, RISE = 44; // a raised wing also rides UP the sheet a little: the tip is nearer the eye
-
-export type Wing = { h: P; ends: P[]; out: P[]; panels: P[][]; spar: (i: number, t: number) => P; sparLine: (i: number, a?: number, b?: number, n?: number) => P[] };
-export const wingGeom = (side: number, outline: P[], hinge: P, tips: P[], seed: number, pose: Pose = REST): Wing => {
- const place = (pts: P[]): P[] => jitter(pts, 1.6, seed).map(([x, y]) => [CX + side * x * K, CY + y * K] as P); /* each side is placed by hand, so the two never quite match */
- const h = place([hinge])[0];
- const move = (pts: P[]): P[] => {
- if (!posed(pose)) return pts;
- const c = Math.cos(side * pose.sweep), s = Math.sin(side * pose.sweep);
- return pts.map(([x0, y0]) => {
- const rx = pose.sweep ? h[0] + (x0 - h[0]) * c - (y0 - h[1]) * s : x0, ry = pose.sweep ? h[1] + (x0 - h[0]) * s + (y0 - h[1]) * c : y0;
- return [h[0] + (rx - h[0]) * pose.flap, ry - (1 - pose.flap) * RISE * Math.min(1, Math.abs(rx - h[0]) / SPAN)] as P; /* foreshorten about the hinge, lift with the tip */
- });
- };
- const out = move(place(outline)), ends = move(place(tips));
- const spar = (i: number, t: number): P => { const e = ends[i], m = lerp(h, e, 0.5), nx = -(e[1] - h[1]), ny = e[0] - h[0], l = Math.hypot(nx, ny) || 1, bow = (i === 0 ? -22 : 5 - i * 2.4) * side * K, b: P = [m[0] + (nx / l) * bow, m[1] + (ny / l) * bow]; return lerp(lerp(h, b, t), lerp(b, e, t), t); };
- const sparLine = (i: number, a = 0, b = 1, n = 7): P[] => Array.from({ length: n }, (_, k) => spar(i, a + ((b - a) * k) / (n - 1)));
- const panels = ends.slice(0, -1).map((_, i) => { const raw = [spar(i, 0.16), spar(i, 0.55), spar(i, 0.97), lerp(lerp(ends[i], ends[i + 1], 0.5), cen(out), -0.04), spar(i + 1, 0.97), spar(i + 1, 0.55), spar(i + 1, 0.16)], c0 = cen(raw); return raw.map((p) => lerp(p, c0, 0.075)); });
- return { h, ends, out, panels, spar, sparLine };
-};
-
-// the body, drawn in sheet space: thorax, head, the broken-out window, the key's centre
-export const B = (pts: P[], seed: number): P[] => jitter(pts, 1.1, seed).map(([x, y]) => [CX + x * K, CY + y * K] as P);
-export const THORAX = B([[0, -92], [30, -84], [48, -52], [52, -8], [44, 36], [24, 62], [0, 70], [-24, 62], [-45, 34], [-52, -10], [-47, -54], [-28, -85]], 31);
-export const HEAD = B([[0, -130], [16, -124], [23, -109], [15, -95], [0, -91], [-15, -96], [-23, -110], [-14, -125]], 32);
-export const WINDOW = B([[-30, -62], [-8, -72], [10, -66], [32, -50], [40, -8], [30, 30], [8, 36], [-6, 44], [-32, 26], [-40, -18]], 33);
-export const KC: P = [CX, CY + 322 * K]; // the key at rest, withdrawn on the centre line
-export const SPINDLE: P = [CX, CY + 262 * K]; // the squared end of the winding spindle it slides onto
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/kit.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/kit.ts
deleted file mode 100644
index 2de29d1..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/kit.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// THE DRAFTSMAN'S KIT. Every mark on the plate is made with one of these: a ruling pen that is
-// never quite straight, a swung ring, section lines that start and stop inside the part, stipple,
-// a gear, a leader with its arrow, a balloon. Bound to one Gfx target, so the same kit draws on
-// the main canvas or into a cached layer without knowing the difference.
-import { Ctx, Gfx, Medium, P, arc, jitter, line, oval, poly, rng } from "../core";
-import { letter, width } from "../drafting";
-import { bounds, inside } from "../riso";
-import { CYAN, DIM, WHITE, lerp } from "./geom";
-
-export const DRAFT: Medium = { nib: 1, taper: 0.6, pressure: 0.75, retrace: false, wobble: 0.5, rough: 0.55 }; // a ruling pen in a human hand
-export type PenO = { color?: string; seed?: number; opacity?: number; closed?: boolean; taper?: number; wobble?: number; progress?: number };
-export type Kit = ReturnType<typeof kit>;
-
-// boil: 0 for everything the draftsman has already inked (spec 4: furniture is dead still).
-// tint: the shadow pass paints the same linework in one flat colour (spec S11).
-export const kit = (g: Gfx, o: { boil?: number; tint?: string | null } = {}) => {
- const boil = o.boil ?? 0, tint = o.tint ?? null, col = (c?: string) => tint ?? c ?? WHITE;
- const ink = (fn: () => void) => g.inkGroup(fn, { blur: 1.8, alpha: 0.28, textures: ["draftTooth"] }); // a faint halo under the line: white ink on blue always blooms a little
- const pen = (pts: P[], w: number, p: PenO = {}) => g.pen(pts, { w, color: col(p.color), seed: p.seed ?? 1, opacity: p.opacity ?? 0.95, closed: p.closed, taper: p.taper ?? 0.6, wobble: p.wobble ?? 0.5, boil, progress: p.progress });
- const ln = (a: P, b: P, w: number, p: PenO = {}) => pen(line(a, b, ((p.seed ?? 1) % 3) - 1), w, p); // nobody rules a dead straight line freehand
- const dash = (a: P, b: P, on: number, off: number, w: number, p: PenO = {}) => { const L = Math.hypot(b[0] - a[0], b[1] - a[1]); for (let d = 0, i = 0; d < L; d += on + off, i++) ln(lerp(a, b, d / L), lerp(a, b, Math.min(1, (d + on) / L)), w, { ...p, seed: (p.seed ?? 1) + i, taper: 0.3 }); };
- const chain = (a: P, b: P, w: number, p: PenO = {}) => { const L = Math.hypot(b[0] - a[0], b[1] - a[1]); for (let d = 0, i = 0; d < L; d += 40, i++) { ln(lerp(a, b, d / L), lerp(a, b, Math.min(1, (d + 24) / L)), w, { ...p, seed: (p.seed ?? 1) + i * 2, taper: 0.3 }); if (d + 35 < L) ln(lerp(a, b, (d + 30) / L), lerp(a, b, (d + 35) / L), w, { ...p, seed: (p.seed ?? 1) + i * 2 + 1, taper: 0.2 }); } };
- const arrow = (tip: P, ang: number, size = 13, color = WHITE) => g.fill([tip, [tip[0] - Math.cos(ang - 0.17) * size, tip[1] - Math.sin(ang - 0.17) * size], [tip[0] - Math.cos(ang) * size * 0.82, tip[1] - Math.sin(ang) * size * 0.82], [tip[0] - Math.cos(ang + 0.17) * size, tip[1] - Math.sin(ang + 0.17) * size]], col(color), 0.95);
- const fill = (pts: P[], color: string, alpha = 1) => g.fill(pts, tint ?? color, alpha);
- const ring = (cx: number, cy: number, r: number, w: number, seed: number, p: PenO = {}) => pen(jitter(oval(cx, cy, r, r * (0.96 + (seed % 5) * 0.015), 12, -1.9 + seed), r * 0.035, seed), w, { ...p, seed, closed: true, taper: 0.4 }); // hand-swung, never a true circle
- // section lines / cross-hatch: parallel strokes that start and stop inside the part
- const hatch = (pts: P[], ang: number, gap: number, w: number, seed: number, p: { color?: string; opacity?: number; progress?: number } = {}) => {
- const c = Math.cos(ang), s = Math.sin(ang), r = rng(seed), proj = pts.map(([x, y]) => -s * x + c * y), lo = Math.min(...proj), hi = Math.max(...proj), segs: [P, P, number][] = [];
- for (let off = lo + gap * 0.5, n = 0; off < hi; off += gap * (0.86 + r() * 0.28), n++) {
- const ox = -s * off, oy = c * off, ts: number[] = [];
- for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[j], b = pts[i], ex = b[0] - a[0], ey = b[1] - a[1], den = c * ey - s * ex; if (Math.abs(den) < 1e-9) continue; const t = ((a[0] - ox) * ey - (a[1] - oy) * ex) / den, u = ((a[0] - ox) * s - (a[1] - oy) * c) / den; if (u >= 0 && u < 1) ts.push(t); }
- ts.sort((a, b) => a - b);
- for (let k = 0; k + 1 < ts.length; k += 2) { const t0 = ts[k] + r() * 2.5, t1 = ts[k + 1] - r() * 2.5; if (t1 - t0 < 3) continue; segs.push([[ox + c * t0, oy + s * t0], [ox + c * t1, oy + s * t1], seed + n * 7 + k]); }
- }
- const vis = (p.progress ?? 1) * segs.length; /* section lines run on one stroke at a time, the last one half made */
- segs.forEach(([a, b, sd], i) => { const q = Math.min(1, vis - i); if (q > 0) ln(a, b, w, { seed: sd, color: p.color ?? CYAN, opacity: p.opacity ?? 0.8, taper: 0.7, progress: q }); });
- };
- const stipple = (pts: P[], n: number, seed: number, dens: (x: number, y: number) => number, color = WHITE) => { const b = bounds(pts), r = rng(seed), c = g.cur; g.touch(b.x0, b.y0, b.x1, b.y1); c.fillStyle = col(color); for (let i = 0; i < n; i++) { const x = b.x0 + r() * (b.x1 - b.x0), y = b.y0 + r() * (b.y1 - b.y0); if (!inside(pts, x, y) || r() > dens(x, y)) continue; c.globalAlpha = 0.6 + r() * 0.35; c.beginPath(); c.ellipse(x, y, 0.7 + r() * 0.7, 0.6 + r() * 0.5, r() * 3, 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; };
- const gearPts = (cx: number, cy: number, rp: number, teeth: number, ph: number, seed: number, spike = false): P[] => { const r = rng(seed), out: P[] = [], add = rp * (spike ? 0.24 : 0.13), ded = rp * 0.13; for (let i = 0; i < teeth; i++) { const a = ph + (i / teeth) * Math.PI * 2, st = (Math.PI * 2) / teeth, q = (da: number, rr: number): P => [cx + Math.cos(a + da * st) * (rr + (r() - 0.5) * 0.7), cy + Math.sin(a + da * st) * (rr + (r() - 0.5) * 0.7)]; if (spike) out.push(q(0, rp - ded), q(0.62, rp - ded), q(0.92, rp + add)); else out.push(q(0, rp - ded), q(0.16, rp - ded), q(0.3, rp + add), q(0.56, rp + add), q(0.7, rp - ded)); } return out; };
- const gear = (cx: number, cy: number, rp: number, teeth: number, ph: number, seed: number, p: { spokes?: number; spike?: boolean; w?: number; progress?: number } = {}) => {
- const q = p.progress ?? 1; if (q <= 0) return;
- const n = 4 + (p.spokes ?? 5), st = (i: number) => (q >= 1 ? 1 : Math.max(0, Math.min(1, q * n - i))); /* rim, then the hub rings, then the spokes: a wheel is drawn from the outside in */
- pen(poly(gearPts(cx, cy, rp, teeth, ph, seed, p.spike), 2), p.w ?? 1.9, { seed, closed: true, taper: 0.3, wobble: 0.15, progress: st(0) });
- ring(cx, cy, rp * 0.74, 1.2, seed + 1, { color: CYAN, progress: st(1) }); ring(cx, cy, rp * 0.26, 1.6, seed + 2, { progress: st(2) }); ring(cx, cy, rp * 0.1, 1.3, seed + 3, { progress: st(3) });
- for (let i = 0; i < (p.spokes ?? 5); i++) { const a = ph + 0.3 + (i / (p.spokes ?? 5)) * Math.PI * 2, nn = a + Math.PI / 2, wv = rp * 0.06, sq = st(4 + i); [-1, 1].forEach((sd) => ln([cx + Math.cos(a) * rp * 0.27 + Math.cos(nn) * wv * sd, cy + Math.sin(a) * rp * 0.27 + Math.sin(nn) * wv * sd], [cx + Math.cos(a) * rp * 0.73 + Math.cos(nn) * wv * 0.7 * sd, cy + Math.sin(a) * rp * 0.73 + Math.sin(nn) * wv * 0.7 * sd], 1.2, { seed: seed + 10 + i * 2 + sd, progress: sq })); }
- if (q >= 1) { ln([cx - rp * 0.2, cy], [cx + rp * 0.2, cy], 0.9, { color: DIM, seed: seed + 30 }); ln([cx, cy - rp * 0.2], [cx, cy + rp * 0.2], 0.9, { color: DIM, seed: seed + 31 }); } /* centre marks go on when the wheel is finished */
- };
- const spiral = (cx: number, cy: number, r0: number, r1: number, turns: number, ph = 0): P[] => Array.from({ length: Math.ceil(turns * 14) + 1 }, (_, i) => { const t = i / (turns * 14), a = ph + t * turns * Math.PI * 2, rr = r0 + (r1 - r0) * t; return [cx + Math.cos(a) * rr, cy + Math.sin(a) * rr * 0.97] as P; });
- const text = (s: string, x: number, y: number, p: { cap?: number; color?: string; seed?: number; align?: "left" | "center" | "right"; w?: number; opacity?: number; progress?: number } = {}) => letter(g, s, x, y, { ...p, color: col(p.color ?? "#eef6fb") });
- const balloon = (n: string, at: P, to: P, seed: number, q = 1) => { if (q <= 0) return; const a = Math.atan2(to[1] - at[1], to[0] - at[0]), s3 = (i: number) => Math.min(1, Math.max(0, q * 3 - i)); ring(at[0], at[1], 13.5, 1.6, seed, { progress: s3(0) }); text(n, at[0] - 0.5, at[1] - 6.5, { cap: 13, align: "center", seed, w: 1.7, progress: s3(1) }); ln([at[0] + Math.cos(a) * 14, at[1] + Math.sin(a) * 14], to, 1.1, { seed: seed + 1, color: CYAN, progress: s3(2) }); if (q >= 1) fill(oval(to[0], to[1], 2.6, 2.6, 7), WHITE, 0.95); };
- const callout = (t: string, at: P, to: P, seed: number, align: "left" | "right" = "left", q = 1) => { if (q <= 0) return; const wd = width(t, 10.5), x0 = align === "left" ? at[0] : at[0] - wd, s3 = (i: number) => Math.min(1, Math.max(0, q * 3 - i)); /* the word first, then the rule under it, then the leader out to the part */ text(t, x0, at[1] - 11, { cap: 10.5, seed, color: WHITE, progress: s3(0) }); ln([x0 - 2, at[1] + 4], [x0 + wd + 2, at[1] + 4], 1, { seed: seed + 1, color: CYAN, progress: s3(1) }); ln(align === "left" ? [x0 - 2, at[1] + 4] : [x0 + wd + 2, at[1] + 4], to, 1, { seed: seed + 2, color: CYAN, progress: s3(2) }); if (q >= 1) arrow(to, Math.atan2(to[1] - at[1] - 4, to[0] - (align === "left" ? x0 - 2 : x0 + wd + 2)), 10, CYAN); };
- const raw = (): Ctx => g.cur;
- return { g, ink, pen, ln, dash, chain, arrow, fill, ring, hatch, stipple, gear, spiral, text, balloon, callout, raw, arc, poly, oval, jitter, rng, tint };
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/linkage.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/linkage.ts
deleted file mode 100644
index e04e0e2..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/linkage.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-// THE LINKAGE. What actually drives the wings, and the reason Act 3 can be honest: a CRANK on
-// the centre-wheel arbor, a CONNECTING ROD, and a rocking BELL-CRANK at each wing root that
-// lifts the leading spar. `flap` is computed FROM the bell-crank angle, which is computed from
-// the crank angle, so a rod and a wing can never disagree on screen.
-import { P } from "../core";
-import { CX, CY, THORAX, cen } from "./geom";
-
-const O = cen(THORAX);
-export const ARBOR: P = [O[0] + 2, O[1] + 4]; // the centre wheel's arbor, the same one Act 1 and 2 draw
-export const RC = 17, ARM = 26, ROD = 58, OUT = 21, LAG = (8 * Math.PI) / 180; // crank throw, input arm, rod, output arm, and the starboard side's lag in crank angle
-export const pivot = (side: number): P => [CX + side * 44, CY - 52]; // the bell-crank pivot, just inboard of the forewing hinge
-export const crankPin = (th: number): P => [ARBOR[0] + Math.cos(th) * RC, ARBOR[1] + Math.sin(th) * RC];
-
-// the bell-crank angle that puts the rod's far end exactly ROD from the crank pin
-export const bellAngle = (side: number, th: number): number => {
- const P0 = crankPin(th - (side > 0 ? LAG : 0)), Q = pivot(side), dx = P0[0] - Q[0], dy = P0[1] - Q[1], d = Math.hypot(dx, dy) || 1;
- const c = Math.max(-1, Math.min(1, (ARM * ARM + d * d - ROD * ROD) / (2 * ARM * d)));
- return Math.atan2(dy, dx) + side * Math.acos(c); /* one branch per side, so the two arms mirror */
-};
-export const armEnd = (side: number, th: number): P => { const a = bellAngle(side, th), Q = pivot(side); return [Q[0] + Math.cos(a) * ARM, Q[1] + Math.sin(a) * ARM]; };
-export const outEnd = (side: number, th: number): P => { const a = bellAngle(side, th) + side * Math.PI * 0.62, Q = pivot(side); return [Q[0] + Math.cos(a) * OUT, Q[1] + Math.sin(a) * OUT]; }; /* the arm that actually lifts the spar */
-
-// the swing of the bell-crank over one revolution, measured once, so flap can be mapped onto it
-const swing = (side: number) => { let lo = 1e9, hi = -1e9; for (let i = 0; i < 360; i++) { const a = bellAngle(side, (i / 360) * Math.PI * 2); lo = Math.min(lo, a); hi = Math.max(hi, a); } return [lo, hi] as const; };
-const SW = [swing(-1), swing(1)];
-export const flapOf = (side: number, th: number): number => { const [lo, hi] = SW[side > 0 ? 1 : 0], a = bellAngle(side, th), t = (a - lo) / (hi - lo || 1); return 1 - 0.62 * (side > 0 ? 1 - t : t); };
-// the crank angle whose flap is closest to a wanted one: how Act 3 starts on Act 2's last pose
-export const crankFor = (flap: number): number => { let best = 0, bd = 9; for (let i = 0; i < 720; i++) { const th = (i / 720) * Math.PI * 2, d = Math.abs(flapOf(-1, th) - flap); if (d < bd) { bd = d; best = th; } } return best; };
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/parts.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/parts.ts
deleted file mode 100644
index 39cd873..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/parts.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-// THE PARTS OF THE PLATE. Each one draws with a Kit onto whatever target that Kit is bound to,
-// and takes only the state it needs. Nothing here knows about caching, films or frames.
-import { P, oval, poly, sample } from "../core";
-import { width } from "../drafting";
-import { B, CX, CY, CYAN, DIM, GROUND, HEAD, K, KC, THORAX, WHITE, WINDOW, Wing, cen, lerp } from "./geom";
-import { Kit, PenO } from "./kit";
-
-// element i of a run of n, drawn in order, each taking `dur` of the whole: the hand works
-// down the part, it does not fade things up together.
-export const stagger = (p: number, n: number, dur = Math.min(1, 2 / n)) => { const step = n > 1 ? (1 - dur) / (n - 1) : 0; return (i: number) => (p >= 1 ? 1 : Math.max(0, Math.min(1, (p - i * step) / dur))); };
-// WHERE THE NIB IS. `progress` cuts a stroke on sample INDEX, and samples are not evenly
-// spaced in arc length, so a fitting gated on cue progress can appear on bare paper ahead of
-// the line it belongs to. This measures the drawn fraction of the actual stroke, and where a
-// point sits along it, both in arc length, so a knuckle or a rivet lands as the nib passes it.
-export const nib = (pts: P[]) => {
- const s = sample(pts), acc = [0]; let total = 0;
- for (let i = 1; i < s.length; i++) { total += Math.hypot(s[i][0] - s[i - 1][0], s[i][1] - s[i - 1][1]); acc.push(total); }
- const L = total || 1;
- return {
- drawn: (q: number) => { if (q >= 1) return 1; const n = (s.length - 1) * q, i = Math.max(0, Math.min(s.length - 1, Math.floor(n))), f = n - i; return (acc[i] + (i + 1 < s.length ? (acc[i + 1] - acc[i]) * f : 0)) / L; },
- where: (t: P) => { let best = 0, bd = 1e9; for (let i = 0; i < s.length; i++) { const d = (s[i][0] - t[0]) ** 2 + (s[i][1] - t[1]) ** 2; if (d < bd) { bd = d; best = i; } } return acc[best] / L; },
- };
-};
-export const cut = (p: number, a: number, b: number) => (p >= 1 ? 1 : Math.max(0, Math.min(1, (p - a) / (b - a))));
-
-export type Train = { centre: number; third: number; pinion: number; escape: number; fork: number }; // radians added to the plate's authored phases
-export const IDLE: Train = { centre: 0, third: 0, pinion: 0, escape: 0, fork: 0 };
-
-// ---------------------------------------------------------------- the sheet
-export const sheet = (k: Kit, W: number, H: number) => {
- const c = k.g.main, e = k.g.env, dw = Math.round(W * e.scale), dh = Math.round(H * e.scale);
- c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.fillStyle = GROUND; c.fillRect(0, 0, dw, dh); c.restore(); /* the ground fills the FRAME, whatever the camera is doing */
- const glow = c.createRadialGradient(W * 0.5, H * 0.44, 60, W * 0.5, H * 0.5, W * 0.78); glow.addColorStop(0, "rgba(58,120,178,0.34)"); glow.addColorStop(0.55, "rgba(30,84,140,0.1)"); glow.addColorStop(1, "rgba(4,16,36,0.5)"); c.fillStyle = glow; c.fillRect(-W, -H, W * 3, H * 3);
- k.g.paper("blueMottle", 0.55);
- /* two old fold lines: a plate that has lived in a drawer */
- [[W * 0.5 + 3, 0, W * 0.5 - 2, H], [0, H * 0.5 - 4, W, H * 0.5 + 2]].forEach(([x0, y0, x1, y1]) => { c.strokeStyle = "rgba(190,225,245,0.07)"; c.lineWidth = 2.4; c.beginPath(); c.moveTo(x0, y0); c.lineTo(x1, y1); c.stroke(); c.strokeStyle = "rgba(2,10,26,0.16)"; c.lineWidth = 1.2; c.beginPath(); c.moveTo(x0 + 2, y0 + 2); c.lineTo(x1 + 2, y1 + 2); c.stroke(); });
-};
-// The detail bubble goes on the thorax BEFORE the detail is drawn: a draftsman rings what he is
-// about to magnify, and it is the circle the cut to Detail B matches (spec 7).
-export const bubble = (k: Kit, p = 1) => { if (p <= 0) return; k.ink(() => { const tc = cen(THORAX); k.ring(tc[0], tc[1] - 6, 62, 1.5, 336, { color: CYAN, opacity: 0.95, progress: cut(p, 0, 0.7) }); /* the circle the cut matches: it has to carry the frame, so it is rung with a confident line */ k.text("B", tc[0] + 50, tc[1] - 70, { cap: 14, seed: 337, w: 1.8, progress: cut(p, 0.6, 1) }); }); };
-export const BUBBLE = (): [number, number, number] => { const tc = cen(THORAX); return [tc[0], tc[1] - 6, 62]; };
-
-export const grid = (k: Kit, W: number, H: number, alpha = 1) => k.g.group("plain", () => { const c = k.raw(); c.globalAlpha = alpha; k.g.touch(0, 0, W, H); for (let i = 40; i < W - 30; i += 20) { const major = (i - 40) % 100 === 0; c.strokeStyle = major ? "rgba(150,208,236,0.2)" : "rgba(150,208,236,0.085)"; c.lineWidth = major ? 1 : 0.7; c.beginPath(); c.moveTo(i, 40); c.lineTo(i, H - 40); c.moveTo(40, i); c.lineTo(W - 40, i); c.stroke(); } c.globalAlpha = 1; }, { textures: ["draftTooth"] });
-export const border = (k: Kit, W: number, H: number, p = 1) => { if (p <= 0) return; k.ink(() => {
- const q = stagger(cut(p, 0, 0.75), 8, 0.42); /* the sheet is ruled stroke by stroke, outer frame first, inner rule chasing it */
- [[22, 2.6], [34, 1.2]].forEach(([m, w], j) => [[[m, m], [W - m, m]], [[W - m, m], [W - m, H - m]], [[W - m, H - m], [m, H - m]], [[m, H - m], [m, m]]].forEach(([a, b], i) => k.ln(a as P, b as P, w, { seed: 900 + j * 4 + i, taper: 0.15, progress: q(i * 2 + j) })));
- const z = cut(p, 0.7, 1);
- ["A", "B", "C", "D"].forEach((t, i) => { const y = 34 + ((H - 68) * (i + 0.5)) / 4, qq = stagger(z, 8, 0.4)(i); k.text(t, 24.5, y - 4, { cap: 7, seed: 910 + i, color: CYAN, w: 1, progress: qq }); if (i) k.ln([22, 34 + ((H - 68) * i) / 4], [34, 34 + ((H - 68) * i) / 4], 1, { seed: 920 + i, progress: qq }); });
- ["1", "2", "3", "4"].forEach((t, i) => { const x = 34 + ((W - 68) * (i + 0.5)) / 4, qq = stagger(z, 8, 0.4)(i + 4); k.text(t, x, 24.5, { cap: 7, seed: 930 + i, color: CYAN, w: 1, align: "center", progress: qq }); if (i) k.ln([34 + ((W - 68) * i) / 4, 22], [34 + ((W - 68) * i) / 4, 34], 1, { seed: 940 + i, progress: qq }); });
-}); };
-
-// CONSTRUCTION. What the draftsman lays down before he inks: the centre line, the envelope each
-// wing has to fit, the thorax ellipse. It is drawn in DIM, and later it is taken away the same
-// way it arrived, by UN-drawing, because a construction line is erased and never faded.
-export const construction = (k: Kit, w: { LF: Wing; RF: Wing; LH: Wing; RH: Wing }, p: number) => { if (p <= 0) return; k.ink(() => {
- const q = stagger(p, 7, 0.4), o: PenO = { color: DIM, opacity: 0.8, seed: 0 };
- k.chain([CX, CY - 300], [CX, CY + 380], 1, { ...o, seed: 960, progress: q(0) });
- [w.LF, w.RF, w.LH, w.RH].forEach((wg, i) => k.pen(wg.out, 1.2, { ...o, seed: 961 + i, closed: true, wobble: 1.6, progress: q(1 + i) }));
- k.pen(k.oval(CX, CY - 10, 58, 92, 12), 1.2, { ...o, seed: 966, closed: true, progress: q(5) });
- k.pen(k.oval(CX, CY - 100, 26, 22, 10), 1.1, { ...o, seed: 967, closed: true, progress: q(6) });
-}); };
-
-// ---------------------------------------------------------------- the wings
-export type WingP = { skin: boolean; lift?: number; liftT?: number; line?: number; skinP?: number };
-export const drawWing = (k: Kit, w: Wing, side: number, seed: number, o: WingP) => {
- const { h, ends, out, panels, spar, sparLine } = w, line = o.line ?? 1, skinP = o.skinP ?? 1;
- if (line <= 0 && skinP <= 0) return;
- // a membrane panel is a MADE part: it arrives whole along its projection lines, seats, and is
- // veined and then shaded afterwards, in that order
- const drawPanel = (pn: P[], i: number, dx = 0, dy = 0, q = 1) => {
- if (q <= 0) return;
- const p = pn.map(([x, y]) => [x + dx, y + dy] as P), base = lerp(p[0], p[6], 0.5), tip = p[3], c0 = cen(p);
- const vein = cut(q, 0.45, 0.8), tone = cut(q, 0.8, 1);
- k.fill(p, CYAN, 0.085); k.pen(p, 1.15, { seed: seed + 300 + i, closed: true, color: CYAN, wobble: 0.3 });
- if (vein <= 0) return;
- /* veining: a midrib that forks, and cross-veins running out to the panel's edges */
- const mid = (t: number): P => lerp(lerp(base, c0, t), lerp(c0, tip, t), t), vq = stagger(vein, 9, 0.45);
- k.pen([0, 0.25, 0.5, 0.75, 0.96].map(mid), 1.05, { seed: seed + 320 + i, color: WHITE, opacity: 0.85, progress: vq(0) });
- [0.28, 0.46, 0.64, 0.8].forEach((t, j) => [1, 5].forEach((e, r) => { const from = mid(t), to = lerp(lerp(p[e], p[e === 1 ? 2 : 4], t), from, 0.12); k.pen([from, lerp(lerp(from, to, 0.5), c0, -0.1), to], 0.8, { seed: seed + 340 + i * 9 + j * 2 + r, color: CYAN, opacity: 0.78, taper: 0.9, progress: vq(1 + j * 2 + r) }); }));
- if (tone > 0) k.hatch([p[6], p[5], p[4], lerp(p[4], c0, 0.34), lerp(p[5], c0, 0.3), lerp(p[6], c0, 0.3)], Math.atan2(p[4][1] - p[6][1], p[4][0] - p[6][0]) + 0.9, 4.6, 0.75, seed + 360 + i, { opacity: 0.6, progress: tone });
- };
- if (o.skin && skinP > 0) { const sq = stagger(skinP, panels.length, 0.5); panels.forEach((pn, i) => { if (i === o.lift) return; const a = cut(sq(i), 0, 0.45), f = 1 - a * a * (3 - 2 * a); drawPanel(pn, i, side * 58 * f, -60 * f, sq(i)); }); }
- if (line <= 0) return;
- const mq = cut(line, 0, 0.3), sq = stagger(cut(line, 0.2, 0.92), ends.length, 0.45), bq = cut(line, 0.85, 1);
- k.pen(out, 2.7, { seed: seed + 1, closed: true, wobble: 0.6, progress: mq }); /* the wing margin: the heaviest line on the wing, and the first */
- ends.forEach((_, i) => {
- const q = sq(i); if (q <= 0) return;
- const nrm = (t: number): P => { const a = spar(i, t - 0.02), b = spar(i, t + 0.02), l = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1; return [-(b[1] - a[1]) / l, (b[0] - a[0]) / l]; }, tw = i === 0 ? 3.4 : 2.3;
- [-1, 1].forEach((sd) => k.pen(sparLine(i, 0.04, 0.985).map((p, j, arr) => { const t = 0.04 + (0.945 * j) / (arr.length - 1), n = nrm(Math.min(0.97, Math.max(0.03, t))), wv = tw * (1 - t * 0.55); return [p[0] + n[0] * wv * sd, p[1] + n[1] * wv * sd] as P; }), i === 0 ? 1.7 : 1.05, { seed: seed + 40 + i * 2 + sd, color: i === 0 ? WHITE : CYAN, opacity: i === 0 ? 0.95 : 0.85, progress: q })); /* a spar is a tapering TUBE: two lines, not one */
- const kn = spar(i, 0.44), n = nrm(0.44), nb = nib(sparLine(i, 0.04, 0.985)), tip = nb.drawn(q), hq = q >= 1 ? 1 : cut(tip - nb.where(kn), 0, 0.1); /* the knuckle rings on as the NIB passes it, not when the cue says so */
- if (hq > 0) { k.ring(kn[0], kn[1], 5.2, 1.5, seed + 60 + i, { progress: hq }); k.ring(kn[0], kn[1], 1.8, 1.1, seed + 70 + i, { progress: hq }); k.ln([kn[0] - n[0] * 8, kn[1] - n[1] * 8], [kn[0] + n[0] * 8, kn[1] + n[1] * 8], 1.1, { seed: seed + 80 + i, progress: hq }); }
- for (let j = 1; j <= (i === 0 ? 9 : 3); j++) { const t = i === 0 ? 0.08 + j * 0.095 : 0.2 + j * 0.2, p = spar(i, t), rq = q >= 1 ? 1 : cut(tip - nb.where(p), 0, 0.08); if (rq <= 0) continue; k.ring(p[0], p[1], 1.7, 0.9, seed + 100 + i * 12 + j, { color: WHITE, progress: rq }); } /* rivets, each one as the nib reaches it */
- if (i && bq > 0) [0.44, 0.74].forEach((t, j) => k.pen([spar(i - 1, t), lerp(lerp(spar(i - 1, t), spar(i, t), 0.5), h, -0.03), spar(i, t)], 1.15, { seed: seed + 200 + i * 2 + j, color: WHITE, opacity: 0.85, progress: stagger(bq, 2, 0.7)(j) })); /* cross-braces last */
- });
- const jq = cut(line, 0.1, 0.3);
- if (jq > 0) { k.ring(h[0], h[1], 8.5, 2, seed + 90, { progress: jq }); k.ring(h[0], h[1], 3.2, 1.4, seed + 91, { progress: jq }); if (jq >= 1) k.stipple(oval(h[0], h[1], 8, 8, 10), 60, seed + 92, () => 0.5); }
- if (o.skin && o.lift !== undefined && skinP > 0) { /* the lifted panel goes on last and is knocked out, so it reads as a plate floating above the wing */
- const t = o.liftT ?? 1, pn = panels[o.lift], dx = side * 58 * t, dy = -60 * t, up = pn.map(([x, y]) => [x + dx, y + dy] as P), lq = stagger(skinP, panels.length, 0.5)(o.lift);
- if (lq > 0) {
- if (t > 0.02) { k.pen(pn, 0.9, { seed: seed + 380, closed: true, color: DIM, opacity: 0.6, progress: lq }); k.fill(up.map((q) => lerp(q, cen(up), -0.04)), GROUND, 0.94); [0, 2, 4, 6].forEach((j) => k.dash(pn[j], up[j], 7, 5, 1, { seed: seed + 390 + j, color: CYAN, opacity: 0.9, progress: lq })); }
- drawPanel(pn, o.lift, dx, dy, lq); k.pen(up, 1.9, { seed: seed + 399, closed: true, wobble: 0.3, progress: lq });
- }
- }
-};
-
-// ---------------------------------------------------------------- body: abdomen, thorax, head
-export const bodyMask = (k: Kit, on = true) => { if (!on) return; k.g.group("plain", () => { k.fill(THORAX, GROUND, 1); k.fill(HEAD, GROUND, 1); }); }; // the body sits OVER the wing roots
-export const abdomen = (k: Kit, p = 1) => { if (p <= 0) return; k.ink(() => {
- const segs = 7, y0 = 70, y1 = 238, hw = (t: number) => 23 * (1 - t) ** 0.8 + 6.5;
- const edge = (sd: number): P[] => B(Array.from({ length: 15 }, (_, j) => { const t = j / 14; return [sd * (hw(t) + Math.sin(t * segs * Math.PI) * 1.6), y0 + (y1 - y0) * t] as P; }), 34 + sd);
- const L = edge(-1), R = edge(1), wq = cut(p, 0, 0.3), sq = stagger(cut(p, 0.22, 0.72), segs, 0.4), tq = cut(p, 0.6, 0.94), eq = cut(p, 0.9, 1);
- if (p >= 1) k.g.group("plain", () => k.fill([...L, ...[...R].reverse()], GROUND, 1)); else if (wq >= 1) k.g.group("plain", () => k.fill([...L, ...[...R].reverse()], GROUND, 1));
- k.pen(L, 2.4, { seed: 35, progress: wq }); k.pen(R, 2.8, { seed: 36, progress: wq }); /* both flanks run down from the thorax */
- for (let a = 1; a < segs; a++) { const q = sq(a - 1); if (q <= 0) continue; const t = a / segs, y = y0 + (y1 - y0) * t, w = hw(t); k.pen(B([[-w, y], [0, y + 5.5], [w, y]], 40 + a), 1.5, { seed: 40 + a, progress: q }); k.pen(B([[-w * 0.94, y + 4], [0, y + 9], [w * 0.94, y + 4]], 50 + a), 0.9, { seed: 50 + a, color: CYAN, opacity: 0.8, progress: q }); [-0.55, 0.55].forEach((r, j) => { const c0 = B([[w * r, y - 8]], 60 + a * 2 + j)[0]; k.ring(c0[0], c0[1], 1.8, 0.9, 60 + a * 2 + j, { progress: cut(q, 0.6, 1) }); }); } /* segments stack, rivets ripple after each */
- if (tq > 0) for (let a = 0; a < segs; a++) { const t0 = a / segs, t1 = (a + 1) / segs, ya = y0 + (y1 - y0) * t0 + 7, yb = y0 + (y1 - y0) * t1 + 1, q = stagger(tq, segs, 0.45)(a); if (q <= 0) continue; k.hatch(B([[hw(t0) * 0.34, ya], [hw(t0) * 0.98, ya], [hw(t1) * 0.98, yb], [hw(t1) * 0.34, yb + 3]], 70 + a), 0.78, 3.4, 0.75, 70 + a, { opacity: 0.7, progress: q }); if (a % 2 === 0) k.hatch(B([[hw(t0) * 0.62, ya], [hw(t0) * 0.98, ya], [hw(t1) * 0.98, yb], [hw(t1) * 0.62, yb + 3]], 80 + a), -0.78, 3.6, 0.7, 80 + a, { opacity: 0.6, progress: q }); }
- if (eq > 0) { const tip = B([[0, 238], [0, 262]], 90); [-1, 1].forEach((sd) => k.ln([tip[0][0] + sd * 3.4, tip[0][1] - 3], [tip[1][0] + sd * 2.6, tip[1][1]], 1.5, { seed: 91 + sd, progress: eq })); k.ln([tip[1][0] - 2.6, tip[1][1]], [tip[1][0] + 2.6, tip[1][1]], 1.4, { seed: 93, progress: cut(eq, 0.6, 1) }); } /* winding spindle, squared end */
-}); };
-
-// thorax housing, its opened window with the train running inside, head and antennae.
-// One ink block, exactly as the approved plate draws it, so the halo matches.
-export const thoraxShell = (k: Kit, p: { shell?: number; head?: number } = {}) => { const sp = p.shell ?? 1, hp = p.head ?? 1; if (sp <= 0 && hp <= 0) return; k.ink(() => {
- if (sp > 0) {
- const cq = cut(sp, 0, 0.28), wq = cut(sp, 0.22, 0.45), bq = cut(sp, 0.42, 0.66), tq = cut(sp, 0.62, 1);
- k.pen(THORAX, 3.1, { seed: 100, closed: true, progress: cq });
- const wall = THORAX.map((q, i) => lerp(q, cen(THORAX), 0.13 + (i % 3) * 0.006)); k.pen(wall, 1.2, { seed: 101, closed: true, color: CYAN, progress: wq });
- k.pen(WINDOW, 1.25, { seed: 102, closed: true, wobble: 2.4, progress: bq }); /* the break line is drawn freehand, on purpose, and slower than the rest */
- k.hatch([...THORAX.slice(2, 8), ...wall.slice(2, 8).reverse()], 0.78, 3.6, 0.85, 103, { opacity: 0.85, progress: stagger(tq, 2, 0.75)(0) }); k.hatch([...THORAX.slice(8), THORAX[0], wall[0], ...wall.slice(8).reverse()], 0.78, 3.6, 0.85, 104, { opacity: 0.6, progress: stagger(tq, 2, 0.75)(1) });
- }
- if (hp <= 0) return;
- /* head: compound eyes stippled, a hairspring proboscis, coiled-wire antennae ending in a flat spiral club */
- const hq = cut(hp, 0, 0.25), eq = cut(hp, 0.2, 0.45), pq = cut(hp, 0.4, 0.6), aq = cut(hp, 0.5, 1);
- k.pen(HEAD, 2.5, { seed: 150, closed: true, progress: hq });
- if (eq > 0) [-1, 1].forEach((sd) => { const e = B(k.oval(sd * 17, -112, 8.5, 12, 9), 151 + sd), q = stagger(eq, 2, 0.8)(sd < 0 ? 0 : 1); k.pen(e, 1.5, { seed: 152 + sd, closed: true, progress: q }); if (q >= 1) k.stipple(e, 150, 153 + sd, (x, y) => 0.25 + 0.6 * Math.max(0, (x - e[0][0]) / 20 + (y - e[0][1]) / 40)); });
- if (pq > 0) { const pr = B([[0, -146]], 155)[0]; k.pen(k.spiral(pr[0], pr[1], 1.5, 11.5, 3.2, 1.4), 1.2, { seed: 156, progress: pq }); k.ln([pr[0], pr[1] + 11], [pr[0], pr[1] + 17], 1.2, { seed: 157, progress: cut(pq, 0.7, 1) }); }
- if (aq > 0) [-1, 1].forEach((sd) => { const q = stagger(aq, 2, 0.85)(sd < 0 ? 0 : 1); if (q <= 0) return; const a0 = B([[sd * 8, -127]], 160)[0], a1 = B([[sd * 56, -206]], 161)[0], a2 = B([[sd * 124, -246]], 162)[0], qq = (u: number): P => lerp(lerp(a0, a1, u), lerp(a1, a2, u), u), pts: P[] = []; for (let j = 0; j <= 150; j++) { const u = (j / 150) * 0.9, pt = qq(u), p2 = qq(u + 0.01), dx = p2[0] - pt[0], dy = p2[1] - pt[1], l = Math.hypot(dx, dy) || 1, ph = j * 0.92, amp = 3.6 - u * 1.4; pts.push([pt[0] + (-dy / l) * Math.sin(ph) * amp + (dx / l) * Math.cos(ph) * amp * 0.55, pt[1] + (dx / l) * Math.sin(ph) * amp + (dy / l) * Math.cos(ph) * amp * 0.55]); } k.pen(pts.filter((_, j) => j % 2 === 0), 1.05, { seed: 163 + sd, wobble: 0.1, taper: 0.3, progress: cut(q, 0, 0.8) }); const e = qq(0.9), cl = qq(1); k.pen(k.spiral(cl[0], cl[1], 1.2, 9.5, 2.6, Math.atan2(e[1] - cl[1], e[0] - cl[0])).reverse(), 1.3, { seed: 165 + sd, progress: cut(q, 0.75, 1) }); }); /* the wire coils out from the base, the club winds on at the end */
-}); };
-
-// the three wheels seen through the broken-out window: the same train Detail B magnifies, so
-// they turn by the same angles. Its own layer, because the housing around it never moves.
-export const thoraxTrain = (k: Kit, t: Train, p = 1) => { if (p <= 0) return; k.ink(() => {
- const c = k.raw(), o = cen(THORAX), q = stagger(p, 4, 0.5); c.save(); k.g.path(c, WINDOW); c.clip();
- k.gear(o[0] + 2, o[1] + 4, 23, 16, 0.2 + t.centre, 110, { spokes: 4, w: 1.5, progress: q(1) }); k.gear(o[0] - 14, o[1] - 33, 13, 10, 0.5 + t.third, 120, { spokes: 3, w: 1.3, progress: q(2) }); k.gear(o[0] + 21, o[1] - 26, 9, 8, 0.1 + t.pinion, 130, { spokes: 3, w: 1.2, progress: q(3) }); k.pen(k.spiral(o[0] - 4, o[1] + 34, 2, 13, 3.4, -t.centre * 0.25), 1, { seed: 140, color: CYAN, progress: q(0) });
- c.restore(); k.g.touch(o[0] - 50, o[1] - 80, o[0] + 50, o[1] + 70);
-}); };
-
-// ---------------------------------------------------------------- the key, on its centre line
-// y: 0 withdrawn (the approved plate), 1 seated on the spindle. turn: radians about the spindle
-// axis, which in PLAN VIEW foreshortens the two bows to a line and back, never an in-plane spin.
-export const key = (k: Kit, s: { y: number; turn: number; axis?: number; body?: number; note?: number }) => {
- const dy = -38 * s.y, cs = Math.cos(s.turn), still = s.y === 0 && s.turn === 0, ax = s.axis ?? 1, bp = s.body ?? 1, np = s.note ?? 1;
- if (ax <= 0 && bp <= 0 && np <= 0) return;
- const T = (p: P): P => (still ? p : [KC[0] + (p[0] - KC[0]) * cs, p[1] + dy]);
- k.ink(() => {
- k.chain([CX, CY - 168 * K], [CX, CY + 372 * K], 0.9, { seed: 170, color: DIM, opacity: 0.85, progress: ax }); /* the axis of symmetry: long dash, short dash */
- if (bp > 0) {
- const kc: P = still ? KC : [KC[0], KC[1] + dy], sq = cut(bp, 0, 0.3), rq = cut(bp, 0.25, 0.45), wq = cut(bp, 0.4, 1);
- [-1, 1].forEach((sd) => k.ln([kc[0] + sd * 3.2, kc[1] - 34], [kc[0] + sd * 3.2, kc[1] - 6], 1.6, { seed: 171 + sd, progress: sq })); k.ln([kc[0] - 3.2, kc[1] - 34], [kc[0] + 3.2, kc[1] - 34], 1.4, { seed: 173, progress: sq }); k.ring(kc[0], kc[1], 6.5, 1.8, 174, { progress: rq });
- [-1, 1].forEach((sd) => { const q = stagger(wq, 2, 0.75)(sd < 0 ? 0 : 1); if (q <= 0) return; const bow = k.jitter(k.oval(KC[0] + sd * 21, KC[1] + 3, 16, 21, 11, 0.4), 0.9, 175 + sd).map(T); k.pen(bow, 2.2, { seed: 176 + sd, closed: true, progress: cut(q, 0, 0.5) }); k.pen(bow.map((pt) => lerp(pt, cen(bow), 0.42)), 1.3, { seed: 178 + sd, closed: true, progress: cut(q, 0.4, 0.75) }); k.hatch([...bow.slice(3, 9), ...bow.slice(3, 9).map((pt) => lerp(pt, cen(bow), 0.42)).reverse()], 0.78, 3.2, 0.75, 180 + sd, { opacity: 0.75, progress: cut(q, 0.7, 1) }); });
- }
- if (np > 0) { const a: P = [CX + 30, CY + 268 * K], b: P = [CX + 30, CY + 292 * K]; k.ln(b, a, 1.1, { seed: 182, color: CYAN, progress: np }); if (np >= 1) k.arrow(a, -Math.PI / 2, 10, CYAN); } /* INSERT: the note stays put while the key moves */
- });
-};
-
-// ---------------------------------------------------------------- drafting furniture on the view
-export const furniture = (k: Kit, w: { LF: Wing; RF: Wing; RH: Wing }, p = 1) => { if (p <= 0) return; k.ink(() => {
- const { LF, RF, RH } = w, N = 10, q = stagger(p, N, 0.32); /* the draftsman dimensions the drawing in the order he would: overall size, details, then the notes */
- const a0q = q(0), a1q = q(1), a2q = q(2), a3q = q(3), a4q = q(4);
- /* overall span, with witness lines that stand clear of the object */
- const la = LF.ends[0], ra = RF.ends[0], y = 102; k.ln([la[0], la[1] - 8], [la[0], y - 8], 0.95, { seed: 300, color: CYAN, progress: cut(a0q, 0, 0.4) }); k.ln([ra[0], ra[1] - 8], [ra[0], y - 8], 0.95, { seed: 301, color: CYAN, progress: cut(a0q, 0.2, 0.6) });
- const t = "WINGSPAN 184", tw = width(t, 12.5); k.ln([la[0], y], [CX - tw / 2 - 10, y], 0.95, { seed: 302, color: CYAN, progress: cut(a0q, 0.4, 0.8) }); k.ln([CX + tw / 2 + 10, y], [ra[0], y], 0.95, { seed: 303, color: CYAN, progress: cut(a0q, 0.4, 0.8) }); if (a0q >= 1) { k.arrow([la[0], y], Math.PI, 13); k.arrow([ra[0], y], 0, 13); } k.text(t, CX, y - 6.5, { cap: 12.5, align: "center", seed: 304, progress: cut(a0q, 0.7, 1) });
- /* key width, arrows outside the witness lines because the space between is too tight for them */
- const ky = KC[1] + 46, kx0 = KC[0] - 38, kx1 = KC[0] + 38; k.ln([kx0, KC[1] + 28], [kx0, ky + 6], 0.9, { seed: 310, color: CYAN, progress: cut(a1q, 0, 0.4) }); k.ln([kx1, KC[1] + 28], [kx1, ky + 6], 0.9, { seed: 311, color: CYAN, progress: cut(a1q, 0.2, 0.6) }); k.ln([kx0 - 30, ky], [kx1 + 30, ky], 0.95, { seed: 312, color: CYAN, progress: cut(a1q, 0.4, 0.8) }); if (a1q >= 1) { k.arrow([kx0, ky], 0, 11); k.arrow([kx1, ky], Math.PI, 11); } k.text("22", kx1 + 36, ky - 6, { cap: 11, seed: 314, progress: cut(a1q, 0.7, 1) });
- /* hinge sweep: the folded position in phantom line, and the arc between */
- const rh = RF.h, re = RF.ends[0], b0 = Math.atan2(re[1] - rh[1], re[0] - rh[0]), b1 = b0 - 1.0, R = 150; k.dash(rh, [rh[0] + Math.cos(b1) * 205, rh[1] + Math.sin(b1) * 205], 12, 6, 0.95, { seed: 320, color: DIM, opacity: 0.8, progress: cut(a2q, 0, 0.45) }); k.pen(k.arc(rh[0], rh[1], R, R, b1, b0, 9), 0.95, { seed: 321, color: CYAN, progress: cut(a2q, 0.35, 0.8) }); if (a2q >= 1) { k.arrow([rh[0] + Math.cos(b0) * R, rh[1] + Math.sin(b0) * R], b0 + Math.PI / 2, 10, CYAN); k.arrow([rh[0] + Math.cos(b1) * R, rh[1] + Math.sin(b1) * R], b1 - Math.PI / 2, 10, CYAN); } k.text("57o SWEEP", rh[0] + 12, rh[1] - 226, { cap: 10.5, seed: 322, progress: cut(a2q, 0.75, 1) });
- /* cutting plane A-A through the third abdominal segment, and the detail bubble on the thorax */
- const ya = CY + 146 * K; k.chain([CX - 92, ya], [CX + 92, ya], 1.7, { seed: 330, progress: cut(a3q, 0, 0.5) }); [-1, 1].forEach((sd) => { const qq = cut(a3q, 0.45, 0.85); k.ln([CX + sd * 92, ya], [CX + sd * 92, ya + 26], 2, { seed: 331 + sd, progress: qq }); if (a3q >= 1) k.arrow([CX + sd * 92, ya + 30], Math.PI / 2, 13); k.text("A", CX + sd * 92 + (sd < 0 ? -22 : 10), ya - 4, { cap: 15, seed: 333 + sd, w: 1.9, progress: cut(a3q, 0.8, 1) }); });
- const tc = cen(THORAX); /* the detail bubble is drawn earlier, with the thorax it rings */
- /* parts balloons, in number order */
- const bq = q(5), bs = stagger(bq, 6, 0.45);
- k.balloon("1", [118, 250], LF.spar(1, 0.62), 340, bs(0)); k.balloon("2", [92, 470], cen(LF.panels[3]), 342, bs(1)); k.balloon("3", [968, 128], RF.spar(0, 0.44), 344, bs(2)); k.balloon("4", [676, 700], [tc[0] + 16, tc[1] + 8], 346, bs(3)); k.balloon("5", [420, 742], [KC[0] - 24, KC[1] + 8], 348, bs(4)); k.balloon("6", [960, 640], RH.spar(2, 0.44), 350, bs(5));
- /* notes in the draftsman hand, one line at a time */
- const cq = stagger(Math.max(0, Math.min(1, (p - 0.6) / 0.4)), 6, 0.35);
- k.callout("ANTENNA - COILED WIRE, 2 OFF", [690, 140], [CX + 116 * K, CY - 236 * K], 360, "left", cq(0)); k.callout("PROBOSCIS HAIRSPRING", [468, 140], [CX - 10, CY - 150 * K], 362, "right", cq(1));
- k.callout("PANEL LIFTED", [930, 400], [cen(RF.panels[2])[0] + 84, cen(RF.panels[2])[1] - 30], 364, "left", cq(2)); k.callout("MEMBRANE OMITTED THIS SIDE", [776, 756], RH.spar(4, 0.78), 366, "left", cq(3)); k.callout("INSERT KEY & WIND 7 TURNS", [250, 700], [KC[0] - 40, KC[1] - 4], 368, "right", cq(4));
- k.callout("RIVETS x 96", [176, 140], LF.spar(0, 0.62), 370, "right", cq(5));
-}); };
-
-// ---------------------------------------------------------------- SECTION A-A
-export const sectionAA = (k: Kit, p = 1) => { if (p <= 0) return; k.ink(() => {
- const c: P = [142, 880], q = stagger(p, 7, 0.36);
- k.ring(c[0], c[1], 56, 2.6, 400, { progress: q(0) }); k.ring(c[0], c[1], 45, 1.5, 401, { progress: q(1) }); k.hatch([...k.oval(c[0], c[1], 56, 56, 28), ...k.oval(c[0], c[1], 45, 45, 28).reverse()], 0.78, 4.2, 0.85, 402, { opacity: 0.9, progress: q(2) }); /* the shell, cut: section-lined */
- k.ring(c[0], c[1], 13, 1.8, 403, { progress: q(3) }); k.hatch(k.oval(c[0], c[1], 13, 13, 16), -0.78, 3.4, 0.8, 404, { opacity: 0.9, progress: q(3) }); /* the shaft is a different part, so its lines run the other way */
- k.gear(c[0], c[1], 30, 14, 0.3, 405, { spokes: 0, w: 1.4, progress: q(4) }); [[-32, -32], [32, -32], [-32, 32], [32, 32]].forEach(([x, y], i) => { k.ring(c[0] + x * 1.13, c[1] + y * 1.13, 3, 1.1, 410 + i, { progress: stagger(q(5), 4, 0.6)(i) }); });
- k.ln([c[0] - 70, c[1]], [c[0] + 70, c[1]], 0.85, { seed: 415, color: DIM, progress: q(5) }); k.ln([c[0], c[1] - 70], [c[0], c[1] + 70], 0.85, { seed: 416, color: DIM, progress: q(5) });
- k.text("SECTION A-A", c[0], c[1] + 70, { cap: 12, align: "center", seed: 417, progress: q(6) }); k.text("SCALE 4 : 1", c[0], c[1] + 92, { cap: 9, align: "center", seed: 418, color: CYAN, progress: cut(q(6), 0.5, 1) });
- k.ln([c[0] - 54, c[1] + 87], [c[0] + 54, c[1] + 87], 1, { seed: 419, progress: cut(q(6), 0.4, 0.9) });
-}); };
-
-const DB: P = [392, 898], DR = 100;
-const wheels = (): { g1: P; g2: P; g3: P; ew: P; br: P } => { const g1: P = [DB[0] - 22, DB[1] + 16], a2 = -0.87, g2: P = [g1[0] + Math.cos(a2) * 72, g1[1] + Math.sin(a2) * 72]; return { g1, g2, g3: [g2[0] + Math.cos(0.35) * 40, g2[1] + Math.sin(0.35) * 40], ew: [DB[0] + 56, DB[1] + 50], br: [DB[0] - 56, DB[1] - 62] }; };
-
-// DETAIL B, the going train, at 8:1. Live: the four wheels, the mainspring coil and the fork.
-export const detailTrain = (k: Kit, t: Train, p = 1) => { if (p <= 0) return; k.ink(() => {
- const { g1, g2, g3, ew, br } = wheels(), cg = k.raw(), q = stagger(p, 6, 0.42); /* one part per beat, in the order a watchmaker lays a train down */
- cg.save(); k.g.path(cg, k.oval(DB[0], DB[1], DR - 3, DR - 3, 40)); cg.clip();
- k.pen(k.spiral(br[0], br[1], 3, 26, 5.2, 0.6 - t.centre * 0.25), 1.15, { seed: 442, progress: q(0) }); /* the mainspring unwinds as the train runs */
- k.gear(g1[0], g1[1], 46, 24, 0.12 + t.centre, 450, { spokes: 5, progress: q(1) }); k.gear(g2[0], g2[1], 26, 14, 0.36 + t.third, 460, { spokes: 4, progress: q(2) }); k.gear(g3[0], g3[1], 14, 8, 0.2 + t.pinion, 470, { spokes: 0, progress: q(3) }); k.gear(ew[0], ew[1], 23, 15, 0.1 + t.escape, 480, { spokes: 4, spike: true, progress: q(4) }); /* centre wheel, third wheel, pinion, escape wheel */
- /* pallet fork astride the escape wheel: it rocks to the opposite side on every tick */
- const fq = q(5); if (fq > 0) { const pv: P = [ew[0] + 4, ew[1] - 36], fc = Math.cos(t.fork), fs = Math.sin(t.fork), F = (x: number, y: number): P => (t.fork === 0 ? [pv[0] + x, pv[1] + y] : [pv[0] + x * fc - y * fs, pv[1] + x * fs + y * fc]);
- k.ring(pv[0], pv[1], 3.4, 1.4, 490, { progress: cut(fq, 0, 0.3) }); [[-25, 16, -21, 25], [24, 12, 27, 22]].forEach(([x, y, x2, y2], i) => { const aq = stagger(cut(fq, 0.25, 1), 2, 0.7)(i); k.pen([pv, F(x * 0.55, y * 0.2), F(x, y)], 1.9, { seed: 491 + i, progress: aq }); k.ln(F(x, y), F(x2, y2), 2.6, { seed: 493 + i, taper: 0.2, progress: cut(aq, 0.7, 1) }); }); }
- cg.restore(); k.g.touch(DB[0] - DR, DB[1] - DR, DB[0] + DR, DB[1] + DR);
-}); };
-
-// Static: the boundary, the barrel shell, the bridge over the arbors, the tone and the notes.
-export const detailPlate = (k: Kit, p = 1, notes = 1) => { if (p <= 0) return; k.ink(() => {
- const { g1, g2, br, ew } = wheels(), cg = k.raw(), q = stagger(p, 6, 0.4);
- k.pen(k.jitter(k.oval(DB[0], DB[1], DR, DR, 16), 1.2, 430), 1.5, { seed: 430, closed: true, wobble: 1.2, progress: q(0) });
- cg.save(); k.g.path(cg, k.oval(DB[0], DB[1], DR - 3, DR - 3, 40)); cg.clip();
- const bq = q(1); k.ring(br[0], br[1], 31, 2, 440, { progress: cut(bq, 0, 0.4) }); k.ring(br[0], br[1], 27, 1, 441, { color: CYAN, progress: cut(bq, 0.3, 0.6) }); k.ring(br[0], br[1], 3.4, 1.4, 443, { progress: cut(bq, 0.5, 0.7) }); k.hatch([...k.oval(br[0], br[1], 31, 31, 24), ...k.oval(br[0], br[1], 27, 27, 24).reverse()], 0.78, 3, 0.7, 444, { progress: cut(bq, 0.6, 1) }); /* mainspring barrel */
- const gq = q(2), bridge: P[] = [[g1[0] - 8, g1[1] - 9], [g2[0] - 6, g2[1] - 10], [g2[0] + 8, g2[1] + 6], [g1[0] + 9, g1[1] + 9]]; k.pen(poly(bridge, 3), 1.3, { seed: 496, closed: true, color: CYAN, wobble: 0.3, progress: cut(gq, 0, 0.6) }); [lerp(g1, g2, 0.33), lerp(g1, g2, 0.67)].forEach((pt, i) => { const sq = stagger(cut(gq, 0.5, 1), 2, 0.7)(i); k.ring(pt[0], pt[1], 3.6, 1.2, 497 + i, { progress: sq }); k.ln([pt[0] - 2.6, pt[1] - 1.4], [pt[0] + 2.6, pt[1] + 1.4], 1.1, { seed: 499 + i, progress: cut(sq, 0.6, 1) }); }); /* the bridge that carries the arbors, with its two screws */
- if (q(3) >= 1) { k.stipple(k.oval(g1[0], g1[1], 12, 12, 12), 120, 500, () => 0.55); k.stipple(k.oval(g2[0], g2[1], 7, 7, 10), 60, 501, () => 0.55); }
- cg.restore(); k.g.touch(DB[0] - DR, DB[1] - DR, DB[0] + DR, DB[1] + DR);
- const lq = q(4); k.text("DETAIL B", DB[0] + DR + 6, DB[1] - 100, { cap: 12, seed: 510, progress: cut(lq, 0, 0.5) }); k.text("SCALE 8 : 1", DB[0] + DR + 6, DB[1] - 79, { cap: 9, seed: 511, color: CYAN, progress: cut(lq, 0.4, 0.8) }); k.ln([DB[0] + DR + 4, DB[1] - 83.5], [DB[0] + DR + 92, DB[1] - 83.5], 1, { seed: 512, progress: cut(lq, 0.7, 1) });
- const cq = stagger(notes, 4, 0.5); /* the tooth counts are notes, and notes are written in the notes phase */
- k.callout("24 T", [DB[0] + DR + 14, DB[1] + 4], [g1[0] + 44, g1[1] + 14], 513, "left", cq(0)); k.callout("14 T", [DB[0] + DR + 14, DB[1] - 36], [g2[0] + 22, g2[1] + 4], 515, "left", cq(1)); k.callout("ESCAPE WHEEL 15 T", [DB[0] + DR - 4, DB[1] + 86], [ew[0] + 18, ew[1] + 14], 517, "left", cq(2)); k.callout("MAINSPRING", [DB[0] - DR - 6, DB[1] - 112], [br[0] - 8, br[1] - 24], 519, "left", cq(3));
-}); };
-
-// ---------------------------------------------------------------- scale bar, parts list, cartouche
-export const scaleBar = (k: Kit, p = 1) => { if (p <= 0) return; k.ink(() => { const x = 64, y = 1016, u = 26, q = stagger(p, 7, 0.4); for (let i = 0; i < 5; i++) { const a: P = [x + i * u, y], b: P = [x + (i + 1) * u, y], qq = q(i); if (qq <= 0) continue; if (i % 2 === 0 && qq >= 1) k.fill([[a[0], y - 7], [b[0], y - 7], [b[0], y], [a[0], y]], WHITE, 0.92); k.ln([a[0], y - 7], [b[0], y - 7], 1.2, { seed: 600 + i, progress: qq }); k.ln(a, b, 1.2, { seed: 610 + i, progress: qq }); k.ln([b[0], y - 11], [b[0], y], 1.2, { seed: 620 + i, progress: qq }); } k.ln([x, y - 11], [x, y], 1.2, { seed: 630, progress: q(0) }); ["0", "10", "20", "30", "40", "50"].forEach((t, i) => k.text(t, x + i * u, y - 26, { cap: 8, align: "center", seed: 640 + i, color: CYAN, w: 1, progress: stagger(q(5), 6, 0.5)(i) })); k.text("MM", x + 5 * u + 14, y - 9, { cap: 8.5, seed: 650, color: CYAN, w: 1, progress: q(6) }); }); };
-
-export const partsList = (k: Kit, p = 1) => { if (p <= 0) return; k.ink(() => {
- const x0 = 650, x1 = 1026, y0 = 772, rowH = 15.5, rows: [string, string, string][] = [["1", "WING SPAR, HINGED", "13"], ["2", "MEMBRANE PANEL", "11"], ["3", "KNUCKLE HINGE & PIN", "13"], ["4", "GOING TRAIN ASSY", "1"], ["5", "WINDING KEY", "1"], ["6", "SPAR, HINDWING", "7"]];
- const yb = y0 + rowH * (rows.length + 1), fq = cut(p, 0, 0.3), hq = cut(p, 0.25, 0.45), rq = cut(p, 0.4, 1);
- [[[x0, y0], [x1, y0]], [[x1, y0], [x1, yb]], [[x1, yb], [x0, yb]], [[x0, yb], [x0, y0]]].forEach(([a, b], i) => k.ln(a as P, b as P, 1.7, { seed: 700 + i, taper: 0.15, progress: stagger(fq, 4, 0.5)(i) })); k.ln([x0, y0 + rowH], [x1, y0 + rowH], 1.5, { seed: 705, progress: hq }); [x0 + 34, x1 - 48].forEach((x, i) => k.ln([x, y0], [x, yb], 1, { seed: 706 + i, color: CYAN, progress: hq }));
- [["NO.", x0 + 17], ["DESCRIPTION", (x0 + 34 + x1 - 48) / 2], ["QTY", x1 - 24]].forEach(([t, x], i) => k.text(t as string, x as number, y0 + 3.2, { cap: 8.5, align: "center", seed: 710 + i, color: CYAN, w: 1.05, progress: stagger(hq, 3, 0.6)(i) }));
- const rs = stagger(rq, rows.length, 0.4);
- rows.forEach(([n, d, q], i) => { const y = y0 + rowH * (i + 1), qq = rs(i); if (qq <= 0) return; if (i) k.ln([x0, y], [x1, y], 0.8, { seed: 720 + i, color: DIM, opacity: 0.7, progress: cut(qq, 0, 0.3) }); k.text(n, x0 + 17, y + 3.4, { cap: 8.5, align: "center", seed: 730 + i, w: 1.05, progress: cut(qq, 0.2, 0.45) }); k.text(d, x0 + 42, y + 3.4, { cap: 8.5, seed: 740 + i, w: 1.05, progress: cut(qq, 0.3, 0.85) }); k.text(q, x1 - 24, y + 3.4, { cap: 8.5, align: "center", seed: 750 + i, w: 1.05, progress: cut(qq, 0.8, 1) }); });
-}); };
-
-// A draftsman rules the title block early and letters it last of all, so the box and the
-// lettering are two different jobs on two different cues.
-export const cartouche = (k: Kit, box = 1, text = 1) => { if (box <= 0 && text <= 0) return; k.ink(() => {
- const x0 = 650, x1 = 1026, y0 = 890, y1 = 1026, bq = cut(box, 0, 0.55), lq = cut(box, 0.45, 1);
- [[0, 2.8], [5, 1.1]].forEach(([m, w], j) => [[[x0 + m, y0 + m], [x1 - m, y0 + m]], [[x1 - m, y0 + m], [x1 - m, y1 - m]], [[x1 - m, y1 - m], [x0 + m, y1 - m]], [[x0 + m, y1 - m], [x0 + m, y0 + m]]].forEach(([a, b], i) => k.ln(a as P, b as P, w, { seed: 800 + j * 4 + i, taper: 0.12, progress: stagger(bq, 8, 0.42)(i * 2 + j) })));
- k.ln([x0 + 5, y0 + 62], [x1 - 5, y0 + 62], 1.2, { seed: 812, progress: cut(lq, 0, 0.5) }); k.ln([x0 + 5, y0 + 99], [x1 - 5, y0 + 99], 1, { seed: 813, color: CYAN, progress: cut(lq, 0.3, 0.8) }); [x0 + 128, x0 + 252].forEach((x, i) => k.ln([x, y0 + 62], [x, y1 - 5], 1, { seed: 814 + i, color: CYAN, progress: cut(lq, 0.5, 1) }));
- if (text <= 0) return;
- /* fields first, then the strapline, and the plate's name last of all */
- const f1 = cut(text, 0, 0.3), f2 = cut(text, 0.25, 0.55), sq = cut(text, 0.5, 0.72), tq = cut(text, 0.68, 1);
- ([["PLATE", "I", x0 + 66], ["SCALE", "2 : 1", x0 + 190], ["SHEET", "1 OF 1", x0 + 314]] as [string, string, number][]).forEach(([a, v, x], i) => { const qq = stagger(f1, 3, 0.55)(i); k.text(a, x, y0 + 67, { cap: 7, align: "center", seed: 820 + i, color: CYAN, w: 0.95, progress: cut(qq, 0, 0.5) }); k.text(v, x, y0 + 79, { cap: 12.5, align: "center", seed: 823 + i, w: 1.6, progress: cut(qq, 0.4, 1) }); });
- ([["DRAWN", "F.B.", x0 + 66], ["DIMENSIONS", "MILLIMETRES", x0 + 190], ["DATE", "20 IX 2026", x0 + 314]] as [string, string, number][]).forEach(([a, v, x], i) => { const qq = stagger(f2, 3, 0.55)(i); k.text(a, x, y0 + 104, { cap: 7, align: "center", seed: 830 + i, color: CYAN, w: 0.95, progress: cut(qq, 0, 0.5) }); k.text(v, x, y0 + 116, { cap: 9.5, align: "center", seed: 833 + i, w: 1.2, progress: cut(qq, 0.4, 1) }); });
- k.text("CLOCKWORK BUTTERFLY - GENERAL ARRANGEMENT", (x0 + x1) / 2, y0 + 45, { cap: 8.6, align: "center", seed: 811, color: CYAN, w: 1.05, progress: sq });
- k.text("MECHANICAL LEPIDOPTERA", (x0 + x1) / 2, y0 + 16, { cap: 17, align: "center", seed: 810, w: 2.1, progress: tq });
-}); };
-
-// ---------------------------------------------------------------- the surface: dust, then tooth
-export const dust = (k: Kit, W: number, H: number) => k.g.group("plain", () => { const c = k.raw(), r = k.rng(77); k.g.touch(0, 0, W, H); for (let i = 0; i < 260; i++) { c.globalAlpha = 0.1 + r() * 0.3; c.fillStyle = r() < 0.75 ? "#dff1fb" : "#06142c"; c.beginPath(); c.arc(r() * W, r() * H, 0.4 + r() * r() * 1.8, 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; });
-export const tooth = (k: Kit) => { k.g.paper("paper", 0.34); k.g.paper("coldpress", 0.2); };
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/plate.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/plate.ts
deleted file mode 100644
index 376190d..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/plate.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-// THE COMPOSER. Draws PLATE I for one state, part by part, each part on its own surface so a
-// part that did not change is not redrawn (spec 6.3). A cache entry's key names everything its
-// pixels depend on, which is why caching stays inside the pure-function contract: a cold frame
-// and a cached frame of the same number are the same pixels.
-import { Ctx, Env, Gfx, Layer, Medium } from "../core";
-import { FW, FW_H, FW_T, HW, HW_H, HW_T, Pose, REST, Wing, posed, wingGeom } from "./geom";
-import { DRAFT, Kit, kit } from "./kit";
-import { IDLE, Train, abdomen, bodyMask, border, bubble, cartouche, construction, detailPlate, detailTrain, drawWing, dust, furniture, grid, key, partsList, scaleBar, sectionAA, sheet, thoraxShell, thoraxTrain, tooth } from "./parts";
-
-// How much of each part is on the sheet. 0 = the draftsman has not started it, 1 = finished.
-export type Parts = { grid: number; border: number; construct: number; shell: number; head: number; window: number; detail: number; detailPlate: number; detailNotes: number; bubble: number; wing: [number, number, number, number]; skin: [number, number, number, number]; abdomen: number; axis: number; key: number; note: number; furniture: number; section: number; scale: number; list: number; cartouche: number; lettering: number };
-export const FULL: Parts = { grid: 1, border: 1, construct: 0, shell: 1, head: 1, window: 1, detail: 1, detailPlate: 1, detailNotes: 1, bubble: 1, wing: [1, 1, 1, 1], skin: [1, 1, 1, 1], abdomen: 1, axis: 1, key: 1, note: 1, furniture: 1, section: 1, scale: 1, list: 1, cartouche: 1, lettering: 1 };
-export const EMPTY: Parts = { grid: 0, border: 0, construct: 0, shell: 0, head: 0, window: 0, detail: 0, detailPlate: 0, detailNotes: 0, bubble: 0, wing: [0, 0, 0, 0], skin: [0, 0, 0, 0], abdomen: 0, axis: 0, key: 0, note: 0, furniture: 0, section: 0, scale: 0, list: 0, cartouche: 0, lettering: 0 };
-
-// `boil` is the hero linework's breath. `inkedBoil` is the breath of everything the draftsman has
-// ALREADY inked: the sheet, the grid, the border, the furniture, the cartouche. At the desk that is
-// 0, because finished furniture is dead still (spec 4); once the drawing comes alive the whole sheet
-// breathes with it. It is a field rather than a constant because the two moments want opposite
-// answers, and a field is the only way a cache KEY can name it.
-export type PlateState = { wings: Pose; lift: number; keyY: number; keyTurn: number; train: Train; shadow: [number, number]; boil: number; inkedBoil: number; boilIndex: number; p: Parts; view: View };
-export const PLATE_REST: PlateState = { wings: REST, lift: 1, keyY: 0, keyTurn: 0, train: IDLE, shadow: [0, 0], boil: 0, inkedBoil: 0, boilIndex: 0, p: FULL, view: WIDE };
-const SHADOW = "#061a30";
-import { View, WIDE, blit as blitL, kk, part as partL, slotOf } from "./surface";
-// A close shot must not fatten the line. The canvas transform multiplies width by the zoom, so
-// the nib is divided back out and re-multiplied by zoom^0.35: a 3.3x push gets a line about
-// 1.5x heavier, which is what a draftsman's pen looks like magnified (spec 6.4).
-const nibFor = (z: number): Medium => (z === 1 ? DRAFT : { ...DRAFT, nib: (DRAFT.nib * Math.pow(z, 0.35)) / z });
-const blit = (ctx: Ctx, L: Layer | null, dx = 0, dy = 0, alpha = 1) => blitL(ctx, L, dx, dy, alpha);
-
-export const drawPlate = (ctx: Ctx, env: Env, s: PlateState) => {
- const W = env.W, H = env.H, dw = Math.round(W * env.scale), dh = Math.round(H * env.scale), p = s.p;
- // A surface drawn at some boil carries that boil in its PIXELS, so it must carry it in its KEY, or a
- // later frame at a different boil silently reuses the slot and the film stops being a function of the
- // frame number alone. Kit, boil frame and key term are all derived from the one number, together.
- const bfOf = (boil: number) => (boil > 0 ? s.boilIndex * 4 : 0);
- const keyOf = (boil: number) => kk(boil, boil > 0 ? s.boilIndex : 0);
- const bf = bfOf(s.boil), K = (g: Gfx, tint?: string) => kit(g, { boil: s.boil, tint });
- // The already-inked parts hold ONE boil phase rather than cycling: a sheet that has been drawn on
- // settles, it does not flutter. So their boil frame is always 0 and their key needs only the amount.
- const bf0 = 0, K0 = (g: Gfx, tint?: string) => kit(g, { boil: s.inkedBoil, tint });
- const v = s.view, vk = kk(v.cx, v.cy, v.zoom), med = nibFor(v.zoom);
- const part = (name: string, key: string, boilFrame: number, fn: (g: Gfx) => void): Layer => partL(env, med, name, key + "|" + vk, boilFrame, fn, v);
- const live = (name: string, key: string, fn: (g: Gfx) => void): Layer => part(name, key + "|" + b, bf, fn); /* draws with K, breathes */
- const still = (name: string, key: string, fn: (g: Gfx) => void): Layer => part(name, key + "|" + b0, bf0, fn); /* draws with K0, already inked */
- const b = keyOf(s.boil), b0 = kk(s.inkedBoil), t = kk(s.train.centre, s.train.escape, s.train.fork);
- const wings = (pose: Pose): Wing[] => [wingGeom(-1, HW, HW_H, HW_T, 2000, pose), wingGeom(1, HW, HW_H, HW_T, 2600, pose), wingGeom(-1, FW, FW_H, FW_T, 1000, pose), wingGeom(1, FW, FW_H, FW_T, 1600, pose)];
- const w = wings(s.wings), wr = posed(s.wings) ? wings(REST) : w, rest = { LH: wr[0], RH: wr[1], LF: wr[2], RF: wr[3] }; /* the furniture was inked on the resting drawing and stays where it was put */
- const on = (v: number) => v > 0;
-
- const drawWings = (g: Gfx, tint?: string) => {
- const k = K(g, tint);
- k.ink(() => { drawWing(k, w[0], -1, 2000, { skin: true, line: p.wing[0], skinP: p.skin[0] }); drawWing(k, w[1], 1, 2600, { skin: false, line: p.wing[1], skinP: p.skin[1] }); });
- k.ink(() => { drawWing(k, w[2], -1, 1000, { skin: true, line: p.wing[2], skinP: p.skin[2] }); drawWing(k, w[3], 1, 1600, { skin: true, lift: 2, liftT: s.lift, line: p.wing[3], skinP: p.skin[3] }); });
- };
- const anyWing = p.wing.some(on) || p.skin.some(on);
-
- const back = still("back", kk("back", p.grid, p.border), (g) => { const k = K0(g); sheet(k, W, H); grid(k, W, H, p.grid); border(k, W, H, p.border); });
- const constructL = on(p.construct) ? still("construct", kk(p.construct), (g) => construction(K0(g), { LF: rest.LF, RF: rest.RF, LH: rest.LH, RH: rest.RH }, p.construct)) : null;
- const wingL = anyWing ? live("wings", kk("w", p.wing.join(","), p.skin.join(","), s.lift, s.wings.flap, s.wings.sweep), drawWings) : null;
- const bodyL = on(p.abdomen) || on(p.shell) ? live("body", kk(p.abdomen, p.shell > 0 ? 1 : 0), (g) => { const k = K(g); bodyMask(k, on(p.shell)); abdomen(k, p.abdomen); }) : null;
- const shellL = on(p.shell) || on(p.head) ? live("shell", kk(p.shell, p.head), (g) => thoraxShell(K(g), { shell: p.shell, head: p.head })) : null;
- const windowL = on(p.window) ? live("window", kk(p.window, t), (g) => thoraxTrain(K(g), s.train, p.window)) : null;
- const keyL = on(p.axis) || on(p.key) || on(p.note) ? live("key", kk(p.axis, p.key, p.note, s.keyY, s.keyTurn), (g) => key(K(g), { y: s.keyY, turn: s.keyTurn, axis: p.axis, body: p.key, note: p.note })) : null;
- const frontOn = on(p.furniture) || on(p.section) || on(p.scale) || on(p.list) || on(p.cartouche) || on(p.lettering);
- const front = still("front", kk("f", p.furniture, p.section, p.scale, p.list, p.cartouche, p.lettering), (g) => { const k = K0(g); if (frontOn) { furniture(k, rest, p.furniture); sectionAA(k, p.section); scaleBar(k, p.scale); partsList(k, p.list); cartouche(k, p.cartouche, p.lettering); } dust(k, W, H); });
- const bubbleL = on(p.bubble) ? still("bubble", kk(p.bubble), (g) => bubble(K0(g), p.bubble)) : null;
- const detailL = on(p.detail) ? live("detail", kk(p.detail, t), (g) => detailTrain(K(g), s.train, p.detail)) : null;
- const detailFurn = on(p.detailPlate) ? still("detailPlate", kk(p.detailPlate, p.detailNotes), (g) => detailPlate(K0(g), p.detailPlate, p.detailNotes)) : null;
-
- blit(ctx, back); blit(ctx, constructL);
- if (s.shadow[0] || s.shadow[1]) { /* the drawing lifts off its own paper: one flat copy of the hero linework, offset */
- const sh = slotOf(env, "shadow", dw, dh).L, c = sh.ctx;
- c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; c.clearRect(0, 0, dw, dh);
- [wingL, bodyL, shellL, windowL, keyL].forEach((L) => L && c.drawImage(L.canvas as CanvasImageSource, 0, 0));
- c.globalCompositeOperation = "source-in"; c.fillStyle = SHADOW; c.fillRect(0, 0, dw, dh); c.globalCompositeOperation = "source-over";
- blit(ctx, sh, Math.round(s.shadow[0] * env.scale), Math.round(s.shadow[1] * env.scale), 0.7);
- }
- [wingL, bodyL, shellL, windowL, keyL, bubbleL, front, detailL, detailFurn].forEach((L) => blit(ctx, L));
- tooth(kit(new Gfx(ctx, env, 0, DRAFT))); /* the sheet's tooth is on the FRAME, so it neither swims nor blows up when the camera moves */
-};
-
-// The approved plate: every part finished, nothing running. Frame 0 of the motion test is this.
-export const drawStill = (ctx: Ctx, _frame: number, env: Env) => drawPlate(ctx, env, PLATE_REST);
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/surface.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/surface.ts
deleted file mode 100644
index 614fddb..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/butterfly/surface.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-// PART SURFACES. Every part of a plate draws onto its own persistent surface and is composited
-// in order. A surface is redrawn only when its KEY changes, and the key names everything the
-// pixels depend on, so a cached frame and a cold frame of the same number are identical.
-import { Ctx, Env, Gfx, Layer, Medium } from "../core";
-
-export const kk = (...v: (number | string)[]) => v.map((x) => (typeof x === "number" ? x.toFixed(4) : x)).join("|");
-export type Slot = { L: Layer; key: string | null };
-export const slotOf = (env: Env, name: string, dw: number, dh: number): Slot => {
- const id = `plate:${name}:${dw}x${dh}`; let s = env.cache.get(id) as Slot | undefined;
- if (!s) { s = { L: env.canvas(dw, dh), key: null }; env.cache.set(id, s); }
- return s;
-};
-export type View = { cx: number; cy: number; zoom: number };
-export const WIDE: View = { cx: 540, cy: 540, zoom: 1 };
-export const part = (env: Env, medium: Medium, name: string, key: string, boilFrame: number, fn: (g: Gfx) => void, view?: View): Layer => {
- const dw = Math.round(env.W * env.scale), dh = Math.round(env.H * env.scale), s = slotOf(env, name, dw, dh);
- if (s.key !== key) {
- s.L.ctx.setTransform(1, 0, 0, 1, 0, 0); s.L.ctx.globalAlpha = 1; s.L.ctx.globalCompositeOperation = "source-over"; s.L.ctx.clearRect(0, 0, dw, dh);
- const g = new Gfx(s.L.ctx, env, boilFrame, medium);
- if (view && view.zoom !== 1) g.push(env.W / 2 - view.zoom * view.cx, env.H / 2 - view.zoom * view.cy, view.zoom); /* the camera moves the CONTROL POINTS through the transform stack, never the finished pixels */
- fn(g); s.key = key;
- }
- return s.L;
-};
-export const blit = (ctx: Ctx, L: Layer | null, dx = 0, dy = 0, alpha = 1, op: GlobalCompositeOperation = "source-over") => { if (!L) return; ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = alpha; ctx.globalCompositeOperation = op; ctx.drawImage(L.canvas as CanvasImageSource, dx, dy); ctx.restore(); };
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/mechanicalLepidoptera.ts b/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/mechanicalLepidoptera.ts
deleted file mode 100644
index af42f04..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/canvas-core/mechanicalLepidoptera.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-// MECHANICAL LEPIDOPTERA. The whole film: 1800 frames, 60.0 s at 30 fps, 120 bpm, 1080x1080.
-//
-// ACT 1 frames 0- 540 BLUEPRINT: the plate drafts itself, with camera. LOCKED.
-// MOVEMENT 2 frames 540-1800 ALIVE: one continuous coming-to-life, macro to wide.
-//
-// Act 1 is reused exactly as it was approved: its own cue table, its own composer, not a line
-// changed. Movement 2 is one shot on top of it. The score is section 8, generated in pure JS on
-// the same beat grid, so every onset sits on the frame that caused it.
-import { DURATION as ACT1, SHOTS, gridProblems as act1Grid, stateAt } from "./butterfly/act1cues";
-import { drawPlate } from "./butterfly/plate";
-import { gridProblems as aliveGrid, LOCAL } from "./butterfly/alive/cues";
-import { drawAlive } from "./butterfly/alive/movement2";
-import { aliveScore, scoreProblems } from "./butterfly/alive/score";
-import type { Film } from "./film";
-
-const problems = [...act1Grid(), ...aliveGrid(), ...scoreProblems()];
-if (problems.length) throw new Error("the film is off the grid:\n " + problems.join("\n "));
-
-export const TOTAL = ACT1 + LOCAL; // 1800
-
-export const mechanicalLepidoptera: Film = {
- meta: { title: "mechanicalLepidoptera", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: TOTAL },
- assets: { images: {} },
- shots: [
- ...SHOTS.map(([id, start, end]) => ({ id, start, end, draw: (ctx: CanvasRenderingContext2D, local: number, env: Parameters<typeof drawPlate>[1]) => drawPlate(ctx, env, stateAt(start + local)) })),
- { id: "movement2", start: ACT1, end: TOTAL, draw: (ctx, local, env) => drawAlive(ctx, env, local) },
- ],
- audio: aliveScore(TOTAL),
-};
diff --git a/plugins/anidoodle/skills/anidoodle/example/src/hosts/page-mechanicalLepidoptera.ts b/plugins/anidoodle/skills/anidoodle/example/src/hosts/page-mechanicalLepidoptera.ts
deleted file mode 100644
index 34ed590..0000000
--- a/plugins/anidoodle/skills/anidoodle/example/src/hosts/page-mechanicalLepidoptera.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { mechanicalLepidoptera } from "../canvas-core/mechanicalLepidoptera";
-import { mountFilm } from "./page";
-mountFilm(mechanicalLepidoptera);
diff --git a/scripts/plugin-README.md b/scripts/plugin-README.md
index 76858a4..4bab377 100644
--- a/scripts/plugin-README.md
+++ b/scripts/plugin-README.md
@@ -14,18 +14,21 @@ Works in Claude Code, Codex and Grok Build, and in any agent that reads skills.
- The skill writes and runs local Node.js scripts from its `engine/` folder (Node 20 or newer).
- The first render in a new project runs `npm install` for the engine's open-source dependencies (esbuild, playwright-core, typescript, and Remotion for some video work) and downloads a Chromium build with `npx playwright-core install chromium`. Moving pictures also use your local `ffmpeg`.
+- The optional sound pack downloads only when you run `node engine/tools/soundfetch.mjs get <instrument>`. It comes from this project's GitHub release, and every file is checked against a pinned sha256 before it unpacks into `~/.anidoodle/sounds`.
- Nothing else leaves your machine: no telemetry, no accounts, no API keys, and the rendered pages and bundles are checked for network calls.
## Links
- Source, gallery and full docs: https://github.com/alexgreensh/anidoodle
+- The worked example film and the engine's unit tests live in the repository, not in this plugin, to keep it small: clone it to use `scaffold.mjs --example` or `npm test`
- License: Apache-2.0, by Alex Greenshpun
## Notes for directory reviewers
-The directory scan holds one finding, "Uses a credential from the user's machine". It pairs two false matches:
+"Uses a credential from the user's machine" points at `engine/tools/soundfetch.mjs`. It reads three settings, none of them a credential:
-- `engine/src/canvas-core/bake.ts` calls `env.cache.set(...)`. `env` is the renderer's own object and `cache` is its in-memory drawing cache. Nothing reads environment variables or runs `env` or `set` in a shell.
-- `engine/src/canvas-core/adaptAlmond.ts` builds a cache label for lily pad `i` as `pad${i}`. It is a string key, not a command.
+- `ANIDOODLE_SOUNDS`: the folder to install the sound pack into (default `~/.anidoodle/sounds`)
+- `ANIDOODLE_SOUNDS_URL`: where to download the pack from (default this project's GitHub release)
+- `ANIDOODLE_SOUNDS_INDEX_SHA256`: the expected hash of the pack index, for testing a new pack
-anidoodle reads no credentials and sends nothing off the machine. It renders locally with Node, Chromium and ffmpeg, as described above.
+It sends nothing. It only downloads when the user runs `soundfetch.mjs get`, and it refuses any file whose sha256 doesn't match the pinned value. anidoodle reads no tokens or keys and renders locally with Node, Chromium and ffmpeg, as described above.
diff --git a/scripts/sync-codex-marketplace-plugin.sh b/scripts/sync-codex-marketplace-plugin.sh
index c13d9c1..2a87e05 100755
--- a/scripts/sync-codex-marketplace-plugin.sh
+++ b/scripts/sync-codex-marketplace-plugin.sh
@@ -40,7 +40,10 @@ cd "${REPO_ROOT}"
# cheetah films, their scores, pages and rig test), the public-domain reference image they show,
# and the gallery sheet and the tool that rebuilds it (the docs link to it online).
# A test that needs a left-out file is left out with it (craft.test.ts reads the blind pieces).
-EXCLUDE='/canvas-core/(launch|launch2|launch3|launchClip|launchCode|typeOptions|typeStyles)\.ts$|/hosts/page-(launch|launch2|launch3|launchClip|typeOptions|typeStyles)\.ts$|/engine/assets/refs/|/engine/tools/gallery\.mjs$|^skills/anidoodle/assets/styles\.jpg$|/engine/package-lock\.json$|/music/blind/|/canvas-core/cheetah[A-Za-z]*\.ts$|/music/pieces/cheetah[A-Za-z]*\.ts$|/hosts/page-cheetah[A-Za-z]*\.ts$|/test/cheetahRig\.test\.ts$|/test/craft\.test\.ts$'
+# The engine's unit tests and the worked example film stay in the repository too: Anthropic's directory
+# holds any plugin over 512 files for a manual review, so every release waited days. The tools that
+# use them (npm test, gate --self-test, scaffold --example) say where to get them when they are absent.
+EXCLUDE='^skills/anidoodle/engine/test/|^skills/anidoodle/example/|/canvas-core/(launch|launch2|launch3|launchClip|launchCode|typeOptions|typeStyles)\.ts$|/hosts/page-(launch|launch2|launch3|launchClip|typeOptions|typeStyles)\.ts$|/engine/assets/refs/|/engine/tools/gallery\.mjs$|^skills/anidoodle/assets/styles\.jpg$|/engine/package-lock\.json$|/music/blind/|/canvas-core/cheetah[A-Za-z]*\.ts$|/music/pieces/cheetah[A-Za-z]*\.ts$|/hosts/page-cheetah[A-Za-z]*\.ts$|/test/cheetahRig\.test\.ts$|/test/craft\.test\.ts$'
count=0
while IFS= read -r f; do
mkdir -p "${STAGE}/$(dirname "$f")"; cp -p "$f" "${STAGE}/$f"; count=$((count + 1))
@@ -55,7 +58,7 @@ if command -v node >/dev/null 2>&1; then
node -e '
const fs = require("fs"), path = require("path"), root = process.argv[1], bad = [];
const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)]);
- for (const f of [path.join(root, "src"), path.join(root, "test")].flatMap(walk).filter((f) => /\.ts$/.test(f))) for (const m of fs.readFileSync(f, "utf8").matchAll(/^\s*(?:import|export)\b[^"\x27;]*?from\s+["\x27](\.{1,2}\/[^"\x27]+)["\x27]/gm)) {
+ for (const f of [path.join(root, "src"), path.join(root, "test")].filter((d) => fs.existsSync(d)).flatMap(walk).filter((f) => /\.ts$/.test(f))) for (const m of fs.readFileSync(f, "utf8").matchAll(/^\s*(?:import|export)\b[^"\x27;]*?from\s+["\x27](\.{1,2}\/[^"\x27]+)["\x27]/gm)) {
const t = path.resolve(path.dirname(f), m[1]);
if (![t, t + ".ts", t + ".mjs", t + ".json", path.join(t, "index.ts")].some((c) => fs.existsSync(c) && fs.statSync(c).isFile())) bad.push(path.relative(root, f) + " -> " + m[1]);
}
@@ -65,5 +68,13 @@ fi
[ -f "${STAGE}/skills/anidoodle/SKILL.md" ] || { echo "ERROR: SKILL.md missing after copy (is it committed?)" >&2; exit 4; }
[ "${count}" -ge 50 ] || { echo "ERROR: only ${count} files copied; expected the whole skill" >&2; exit 4; }
+# Anthropic's directory holds a plugin with more than 512 files, or any non-image file of 256 KiB or more,
+# for a manual review. Fail well before the line so a release never stalls there; warn as it gets close.
+total="$(cd "${STAGE}" && find . -type f | wc -l | tr -d ' ')"
+[ "${total}" -le 500 ] || { echo "ERROR: plugin folder has ${total} files; the directory holds anything over 512. Leave more out." >&2; exit 7; }
+[ "${total}" -le 490 ] || echo "WARNING: plugin folder has ${total} files, close to the directory's 512-file hold." >&2
+big="$(cd "${STAGE}" && find . -type f -size +255k ! -iname '*.png' ! -iname '*.jpg' ! -iname '*.jpeg' ! -iname '*.gif' ! -iname '*.webp' ! -iname '*.svg' | head -5)"
+[ -z "${big}" ] || { echo "ERROR: files of 256 KiB or more are held by the directory:" >&2; echo "${big}" >&2; exit 7; }
+
rm -rf "${NESTED}"; mv "${STAGE}" "${NESTED}"; trap - EXIT
-echo "Synced plugin folder -> plugins/anidoodle (${count} tracked files, $(grep -o '"version"[^,]*' "${NESTED}/.codex-plugin/plugin.json" | head -1))"
+echo "Synced plugin folder -> plugins/anidoodle (${total} files, $(grep -o '"version"[^,]*' "${NESTED}/.codex-plugin/plugin.json" | head -1))"
diff --git a/skills/anidoodle/engine/package-lock.json b/skills/anidoodle/engine/package-lock.json
index 22ecd07..5fe45c7 100644
--- a/skills/anidoodle/engine/package-lock.json
+++ b/skills/anidoodle/engine/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "anidoodle-engine",
- "version": "0.9.4",
+ "version": "0.9.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "anidoodle-engine",
- "version": "0.9.4",
+ "version": "0.9.5",
"dependencies": {
"esbuild": "0.25.12"
},
diff --git a/skills/anidoodle/engine/package.json b/skills/anidoodle/engine/package.json
index b7e1a10..a4c3c7c 100644
--- a/skills/anidoodle/engine/package.json
+++ b/skills/anidoodle/engine/package.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle-engine",
- "version": "0.9.4",
+ "version": "0.9.5",
"private": true,
"type": "module",
"description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",
diff --git a/skills/anidoodle/engine/tools/gate.mjs b/skills/anidoodle/engine/tools/gate.mjs
index 68852b4..7a30284 100644
--- a/skills/anidoodle/engine/tools/gate.mjs
+++ b/skills/anidoodle/engine/tools/gate.mjs
@@ -183,6 +183,7 @@ const run = async () => {
};
const selfTest = async () => {
let wrong = 0;
+ if (!existsSync("test/fixtures")) { console.error("gate --self-test: the fixtures are not in this install (the directory copy leaves them out). Clone https://github.com/alexgreensh/anidoodle to run it."); process.exit(2); }
for (const file of readdirSync("test/fixtures").filter((f) => f.endsWith(".mjs")).sort()) {
const fixture = (await import(`../test/fixtures/${file}`)).default;
const { meta, render, expected } = fixture;
diff --git a/skills/anidoodle/engine/tools/scaffold.mjs b/skills/anidoodle/engine/tools/scaffold.mjs
index c71d816..2085e7f 100644
--- a/skills/anidoodle/engine/tools/scaffold.mjs
+++ b/skills/anidoodle/engine/tools/scaffold.mjs
@@ -72,7 +72,7 @@ for (const f of ["package.json", "package-lock.json", "tsconfig.json"]) if (exis
if (opt.example) {
const ex = join(SKILL, "example", "src");
- if (!existsSync(ex)) die(`--example asked for, but ${ex} is not there`);
+ if (!existsSync(ex)) die(`--example: the worked film is not in this install (the directory copy leaves it out to stay small). Clone https://github.com/alexgreensh/anidoodle and run its skills/anidoodle/engine/tools/scaffold.mjs with --example.`);
cpSync(ex, join(target, "src"), { recursive: true });
}
diff --git a/skills/anidoodle/engine/tools/test.mjs b/skills/anidoodle/engine/tools/test.mjs
index a345dfe..e881881 100644
--- a/skills/anidoodle/engine/tools/test.mjs
+++ b/skills/anidoodle/engine/tools/test.mjs
@@ -2,10 +2,11 @@
// (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 { existsSync, readdirSync } from "node:fs";
import { overlay } from "./overlay.mjs";
const only = process.argv.slice(2);
+if (!existsSync("test")) { console.error("test: the unit suites are not in this install (the directory copy leaves them out to stay small). Clone https://github.com/alexgreensh/anidoodle to run them."); process.exit(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;