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.

test(camera): commit the camera unit suite (node tools/test.mjs, 30 checks); cache the monotone zoom path; parallax comment in the code's 1/(D + z) form

Alex Greenshpun683702183a13
diff --git a/skills/anidoodle/engine/package.json b/skills/anidoodle/engine/package.json
index debac11..3ed9c90 100644
--- a/skills/anidoodle/engine/package.json
+++ b/skills/anidoodle/engine/package.json
@@ -8,7 +8,8 @@
"still": "node tools/still.mjs",
"gate": "node tools/gate.mjs",
"emit": "node tools/emit.mjs",
- "render": "node tools/render.mjs"
+ "render": "node tools/render.mjs",
+ "test": "node tools/test.mjs"
},
"dependencies": {
"esbuild": "^0.25.0"
diff --git a/skills/anidoodle/engine/src/canvas-core/camera.ts b/skills/anidoodle/engine/src/canvas-core/camera.ts
index e974309..0fad116 100644
--- a/skills/anidoodle/engine/src/canvas-core/camera.ts
+++ b/skills/anidoodle/engine/src/canvas-core/camera.ts
@@ -11,7 +11,7 @@
// accelerate gently and arrive gently; linear reads as mechanical, ease-out alone reads as
// interrupted. The ease lives on the key the segment LEAVES.
// - PARALLAX IS ONE NUMBER. The camera sits at distance D = 1/zoom from the hero plane (z = 0);
-// a plane at depth z scales by zoom/(1 + z*zoom) and moves with it. Near planes swing wide, far
+// a plane at depth z scales by 1/(D + z) and moves with it. Near planes swing wide, far
// ones barely stir, and every element at a depth agrees with every other, because there is only
// one camera. Positive z recedes; a negative z crosses the lens (grass across the glass).
// - A CLOSE SHOT MUST NOT FATTEN THE LINE. Ink is authored at some view; at zoom S the same nib
@@ -80,6 +80,7 @@ export class Camera {
private keys: CamKey[];
private path?: (f: number) => Cam;
private monoZoom: boolean;
+ private zoomPath?: (f: number) => number; // the monotone zoom path, built once from the keys (they never change)
// centre: the frame's centre in logical px (usually [W/2, H/2]); every projection goes through it
constructor(readonly centre: P, keys: CamKey[] = [], opts: { monoZoom?: boolean; path?: (f: number) => Cam } = {}) {
this.keys = [...keys]; // authored order, strictly increasing: a camera path is a cue table
@@ -100,7 +101,7 @@ export class Camera {
private channel(f: number, get: (k: CamKey) => number | undefined, log2: boolean): number {
const ks = this.keys.map((k, i) => ({ k, v: get(k), i })).filter((e) => e.v !== undefined) as { k: CamKey; v: number; i: number }[];
if (!ks.length) throw new Error("camera keys never set this channel");
- if (log2 && this.monoZoom && ks.length > 1) return monoPath(ks.map((e) => [e.k.f, e.v] as const), { log2: true })(f);
+ if (log2 && this.monoZoom && ks.length > 1) return (this.zoomPath ??= monoPath(ks.map((e) => [e.k.f, e.v] as const), { log2: true }))(f);
if (f <= ks[0].k.f) return ks[0].v;
if (f >= ks[ks.length - 1].k.f) return ks[ks.length - 1].v;
let i = 0; while (f >= ks[i + 1].k.f) i++;
diff --git a/skills/anidoodle/engine/test/camera.test.ts b/skills/anidoodle/engine/test/camera.test.ts
new file mode 100644
index 0000000..230bcd9
--- /dev/null
+++ b/skills/anidoodle/engine/test/camera.test.ts
@@ -0,0 +1,78 @@
+// CAMERA TESTS. The engine camera (src/canvas-core/camera.ts) is pure arithmetic, so it is held to
+// exact numbers here, with no browser: node tools/test.mjs
+import { Camera, EASE, monoPath, planeScale, projectCam, strokeWeight, unprojectCam, type Cam } from "../src/canvas-core/camera";
+import { Gfx, type P } from "../src/canvas-core/core";
+
+export const name = "camera";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const cam = new Camera([540, 540], [{ f: 0, look: [400, 300], zoom: 1 }, { f: 90, look: [900, 300], zoom: 2 }, { f: 150, look: [900, 300], zoom: 2 }, { f: 240, look: [400, 300], zoom: 0.5 }]);
+ cam.shake({ from: 96, to: 126, amp: 14, seed: 7, rot: 0.05 });
+
+ // a fake context that records the transform the Gfx stack sets
+ let T: number[] = [];
+ const ctx = { setTransform: (...a: number[]) => { T = a; } } as unknown as ConstructorParameters<typeof Gfx>[0];
+ const env = { W: 1080, H: 1080, scale: 1, canvas: () => ({ ctx }), cache: new Map() } as unknown as ConstructorParameters<typeof Gfx>[1];
+ const g = new (Gfx as unknown as new (...a: unknown[]) => Gfx)(ctx, env, 0, "screen");
+
+ // 1. the transform path and the projector path are one camera
+ let maxErr = 0, roundTrip = 0;
+ for (const f of [0, 45, 97, 100, 110, 125, 200]) for (const z of [0, 0.7, -0.3]) {
+ cam.begin(g, f, z); const [a, b, c, d, e, ff] = T; cam.end(g);
+ for (const p of [[0, 0], [400, 300], [1234, -77]] as P[]) {
+ const s = cam.toScreen(p, f, z), m = [a * p[0] + c * p[1] + e, b * p[0] + d * p[1] + ff];
+ maxErr = Math.max(maxErr, Math.hypot(s[0] - m[0], s[1] - m[1]));
+ const w = cam.toWorld(s, f, z); roundTrip = Math.max(roundTrip, Math.hypot(w[0] - p[0], w[1] - p[1]));
+ }
+ }
+ ok(maxErr < 1e-6, `begin() transform and toScreen() agree (max ${maxErr.toExponential(1)} px)`);
+ ok(roundTrip < 1e-6, `toWorld(toScreen(p)) = p at every depth, shake and rotation included (max ${roundTrip.toExponential(1)})`);
+
+ // 2. zoom is eased in stops: the middle of a 1 -> 2 inout segment is sqrt(2), not 1.5
+ ok(near(cam.at(45).zoom, Math.SQRT2), "log2 midpoint of zoom 1 -> 2 is sqrt 2");
+ ok(near(cam.at(45).look[0], 650), "look is eased linearly in world units (midpoint 650)");
+ ok(near(cam.at(0).zoom, 1) && near(cam.at(90).zoom, 2) && near(cam.at(120).zoom, 2) && near(cam.at(999).zoom, 0.5), "keys are hit exactly; held between equal keys; clamped past the last");
+
+ // 3. eases: ends pinned, inout symmetric
+ for (const [n, e] of Object.entries(EASE)) ok(near(e(0), 0) && near(e(1), 1), `ease ${n} runs 0 -> 1`);
+ ok(near(EASE.inout(0.5), 0.5) && near(EASE.inout(0.25) + EASE.inout(0.75), 1), "inout is symmetric");
+
+ // 4. the dolly model
+ const c2: Cam = { look: [0, 0], zoom: 2 };
+ ok(near(planeScale(c2, 0), 2), "hero plane scales by zoom exactly");
+ ok(near(planeScale(c2, 1), 1 / (0.5 + 1)), "a plane at depth z scales by 1/(D + z)");
+ ok(planeScale(c2, 1) < planeScale(c2, 0) && planeScale(c2, -0.2) > planeScale(c2, 0), "far planes shrink, near planes grow");
+ const p: P = [123, -45], s = projectCam([540, 540], c2, 0.4, p, 0.2), back = unprojectCam([540, 540], c2, 0.4, s, 0.2);
+ ok(near(back[0], p[0], 1e-9) && near(back[1], p[1], 1e-9), "projectCam / unprojectCam invert each other");
+ ok(near(strokeWeight({ look: [0, 0], zoom: 8 }), Math.pow(8, 0.35)), "stroke weight is zoom^0.35");
+
+ // 5. shake: confined to its window, deterministic, rings down
+ ok(cam.shakeAt(95).every((v) => v === 0) && cam.shakeAt(126).every((v) => v === 0), "no shake outside [from, to)");
+ ok(JSON.stringify(cam.shakeAt(100)) === JSON.stringify(new Camera([540, 540], [{ f: 0, look: [0, 0], zoom: 1 }]).shake({ from: 96, to: 126, amp: 14, seed: 7, rot: 0.05 }).shakeAt(100)), "shake is a pure function of (seed, frame)");
+ const early = Math.max(...[98, 99, 100, 101].map((f) => Math.hypot(...cam.shakeAt(f).slice(0, 2) as [number, number]))), late = Math.max(...[121, 122, 123, 124, 125].map((f) => Math.hypot(...cam.shakeAt(f).slice(0, 2) as [number, number])));
+ ok(early > late, `shake decays (${early.toFixed(2)} px early vs ${late.toFixed(2)} px late)`);
+ ok(Math.hypot(...cam.shakeAt(96).slice(0, 2) as [number, number]) <= 14 * 0.5 + 1e-9, "shake attacks over its ramp instead of starting at full amplitude");
+
+ // 6. monotone path: never overshoots, never reverses, hits its keys
+ const keys = [[0, 1], [30, 4], [60, 4.2], [90, 0.5]] as const, path = monoPath(keys, { log2: true });
+ let prev = path(0), dir = 0, reversed = false, lo = Infinity, hi = -Infinity;
+ for (let f = 0; f <= 90; f += 0.5) { const v = path(f); lo = Math.min(lo, v); hi = Math.max(hi, v); const d = Math.sign(v - prev); if (d && dir && d !== dir && f < 60) reversed = true; if (d) dir = d; prev = v; }
+ ok(keys.every(([f, v]) => near(path(f), v, 1e-9)), "monoPath passes through every key");
+ ok(lo >= 0.5 - 1e-9 && hi <= 4.2 + 1e-9, "monoPath never overshoots its keys");
+ ok(!reversed, "monoPath never reverses inside a rising run");
+ const mono = new Camera([540, 540], [{ f: 0, look: [0, 0], zoom: 1 }, { f: 30, zoom: 4 }, { f: 60, zoom: 4.2 }, { f: 90, zoom: 0.5 }], { monoZoom: true });
+ ok([0, 13, 30, 47, 75, 90].every((f) => near(mono.at(f).zoom, path(f), 1e-12)), "Camera monoZoom uses the same path (built once, same answers every call)");
+
+ // 7. the Gfx transform stack composes rotation into child translation
+ g.push(10, 20, 2, 0.3); g.push(5, 0, 1, 0); const T1 = T; g.pop(); g.pop();
+ ok(near(T1[4], 10 + 2 * Math.cos(0.3) * 5) && near(T1[5], 20 + 2 * Math.sin(0.3) * 5), "nested push: child translation is rotated and scaled by the parent");
+
+ // 8. bad input is refused, loudly
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ ok(throws(() => new Camera([0, 0], [{ f: 5, zoom: 1 }, { f: 5, zoom: 2 }])), "rejects duplicate key frames");
+ ok(throws(() => new Camera([0, 0], [{ f: 1.5, zoom: 1 }])), "rejects a fractional key frame");
+ ok(throws(() => new Camera([0, 0], [{ f: 0, zoom: 0 }])), "rejects zoom <= 0");
+ ok(throws(() => new Camera([0, 0], [])), "rejects a camera with neither keys nor path");
+ ok(throws(() => cam.shake({ from: 10, to: 10, amp: 1, seed: 1 })), "rejects an empty shake window");
+ ok(throws(() => monoPath([[0, 1], [0, 2]])), "monoPath rejects non-increasing keys");
+};
diff --git a/skills/anidoodle/engine/tools/test.mjs b/skills/anidoodle/engine/tools/test.mjs
new file mode 100644
index 0000000..a345dfe
--- /dev/null
+++ b/skills/anidoodle/engine/tools/test.mjs
@@ -0,0 +1,21 @@
+// UNIT TESTS. Every test/*.test.ts module exports { name, run(ok) }; this bundles each with esbuild
+// (the same resolver the films use) and runs it in node. No browser, no framework, exit 1 on any
+// failure. node tools/test.mjs [name ...]
+import { build } from "esbuild";
+import { readdirSync } from "node:fs";
+import { overlay } from "./overlay.mjs";
+
+const only = process.argv.slice(2);
+const files = readdirSync("test").filter((f) => f.endsWith(".test.ts")).sort().filter((f) => !only.length || only.includes(f.replace(/\.test\.ts$/, "")));
+if (!files.length) { console.error(`test: nothing to run${only.length ? ` for ${only.join(", ")}` : ""}`); process.exit(2); }
+let pass = 0, fail = 0;
+for (const f of files) {
+ const js = (await build({ entryPoints: [`test/${f}`], bundle: true, format: "esm", write: false, platform: "neutral", plugins: [overlay], logLevel: "error" })).outputFiles[0].text;
+ const mod = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));
+ console.log(`\n${mod.name ?? f}`);
+ try {
+ mod.run((cond, label) => { if (cond) pass++; else fail++; console.log(` ${cond ? "PASS" : "FAIL"} ${label}`); });
+ } catch (e) { fail++; console.log(` FAIL crashed: ${e.stack ?? e}`); }
+}
+console.log(`\nTESTS: ${fail ? "FAIL" : "PASS"} ${pass} passed, ${fail} failed`);
+process.exit(fail ? 1 : 0);
diff --git a/skills/anidoodle/engine/tsconfig.json b/skills/anidoodle/engine/tsconfig.json
index d85c7e5..25da5d9 100644
--- a/skills/anidoodle/engine/tsconfig.json
+++ b/skills/anidoodle/engine/tsconfig.json
@@ -4,5 +4,5 @@
"strict": true, "noEmit": true, "skipLibCheck": true, "esModuleInterop": true, "lib": ["DOM", "ES2022"],
"rootDirs": ["src", "../example/src"]
},
- "include": ["src", "../example/src"]
+ "include": ["src", "test", "../example/src"]
}