Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.
TypeScript agent-skillsanimationcanvasclaude-codeclaude-pluginclaude-skillscodex-plugincreative-codecreative-codingcreative-toolsdeterministicgenerative-arthand-drawnillustrationlaunch-videomotion-designmotion-graphicspluginprocedural-generationskill
3D motion: seekable timeline, named camera moves, motion-graphics verbs, demo; gate scans three-core; WebGL flags in player and emit; contents lists on long references
Alex Greenshpun32890e7abf7f
diff --git a/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.ts b/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.tsnew file mode 100644index 0000000..cc7a6e8--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.ts@@ -0,0 +1,150 @@+// THREE MOTION DEMO. A 9.5 s tour of the 3D motion kit (three-core/timeline, camera, mograph) on+// simple bevelled shapes in one studio: four stations along x, one shot each, cuts on the beat.+// grid a 5x5 field of bevelled tiles pops in from the centre, then a wave rolls across it;+// push-in with a light handheld+// write a ribbon writes itself through the air with a glowing bead riding its tip; pillars rise+// from the floor; the camera dollies past on a constant-speed path+// morph a ring draws on, its beads pop in, and the ring morphs into a star while the camera+// orbits; a whip pan (held frames, no smear) carries us to the next station+// explode a 3x3x3 block flashes, blows apart and reassembles under a crane up with a dutch roll+// Everything moving is set from the frame: the scene is built once (memo) and every draw re-poses it.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import * as THREE from "three";+import { draw3d, memo } from "../three-core/stage";+import { ease, seg, tween } from "../three-core/time";+import { crane, dolly, dutch, handheld, hash01, look, orbit, path, place, pushIn, then, whipPan, withMods, type CamState, type Move, type V3 } from "../three-core/camera";+import { assemble, dropIn, explode, grid, indicate, lagged, morph, moveAlongPath, popIn, riseFromFloor, wave, writeOn, writeTube } from "../three-core/mograph";++const W = 1920, H = 1080, FPS = 24, BEAT = 12, N = 19 * BEAT; // 228 frames, 9.5 s+const BG = "#15122a", FLOOR = "#221d3d";+const PAL = { coral: "#ff6b5b", sun: "#ffc53d", teal: "#2ec4b6", lilac: "#8c7dff", cream: "#f3ece0" };+const CUT = { write: 4 * BEAT, morph: 9 * BEAT, explode: 14 * BEAT };+const ST = { grid: [0, 0, 0] as V3, write: [17, 0, 0] as V3, morph: [34, 0, 0] as V3, explode: [51, 0, 0] as V3 };++const mat = (color: string, o: { emissive?: string; ei?: number; rough?: number } = {}) =>+ new THREE.MeshPhysicalMaterial({ color, roughness: o.rough ?? 0.42, metalness: 0, clearcoat: 0.5, clearcoatRoughness: 0.35, emissive: o.emissive ?? "#000000", emissiveIntensity: o.ei ?? 1 });+// a rounded rectangle extruded with a soft bevel: the "designed object" look, never a raw box+const slab = (w: number, d: number, depth: number, r: number, bevel = 0.06) => {+ const s = new THREE.Shape(), x = -w / 2, y = -d / 2;+ s.moveTo(x + r, y); s.lineTo(x + w - r, y); s.quadraticCurveTo(x + w, y, x + w, y + r); s.lineTo(x + w, y + d - r); s.quadraticCurveTo(x + w, y + d, x + w - r, y + d);+ s.lineTo(x + r, y + d); s.quadraticCurveTo(x, y + d, x, y + d - r); s.lineTo(x, y + r); s.quadraticCurveTo(x, y, x + r, y);+ const g = new THREE.ExtrudeGeometry(s, { depth, bevelEnabled: true, bevelThickness: bevel, bevelSize: bevel, bevelSegments: 4, curveSegments: 6 });+ return g;+};+const shadowy = (m: THREE.Object3D) => { m.traverse((c) => { c.castShadow = true; c.receiveShadow = true; }); return m; };++const build = () => {+ const scene = new THREE.Scene();+ scene.background = new THREE.Color(BG);+ scene.fog = new THREE.Fog(BG, 22, 48);+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(400, 400), new THREE.MeshStandardMaterial({ color: FLOOR, roughness: 0.95 }));+ floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);+ const key = new THREE.DirectionalLight("#fff1dc", 2.4); key.castShadow = true;+ key.shadow.mapSize.set(2048, 2048); key.shadow.bias = -0.0004; key.shadow.normalBias = 0.02; key.shadow.radius = 4;+ Object.assign(key.shadow.camera, { left: -8, right: 8, top: 8, bottom: -8, near: 1, far: 40 });+ scene.add(key, key.target);+ const rim = new THREE.DirectionalLight("#9fb4ff", 1.2); scene.add(rim, rim.target);+ scene.add(new THREE.HemisphereLight("#c9d2ff", "#2a2240", 0.85));++ // grid: 5x5 tiles in three heights, in a palette that walks the colours diagonally+ const tiles = new THREE.Group(), heights = [0.25, 0.5, 0.8].map((h) => { const g = slab(0.8, 0.8, h, 0.16, 0.05); g.rotateX(-Math.PI / 2); g.translate(0, 0.05, 0); return g; });+ const tileCols = [PAL.coral, PAL.sun, PAL.teal, PAL.lilac, PAL.cream].map((c) => mat(c));+ for (let i = 0; i < 5; i++) for (let j = 0; j < 5; j++) {+ const h = Math.floor(hash01(11, i * 5 + j) * 3), m = new THREE.Mesh(heights[h], tileCols[(i + j) % 5]);+ m.position.set((i - 2) * 1.02, 0, (j - 2) * 1.02); tiles.add(m);+ }+ tiles.position.set(...ST.grid); scene.add(shadowy(tiles));++ // write: a ribbon swooping through the air, a bead at its tip, pillars around it+ const swoop = path([[-4, 0.4, 2.2], [-2.6, 1.8, 0.4], [-0.6, 3.0, -1.4], [1.6, 2.4, -0.6], [1.2, 1.0, 1.4], [-0.4, 1.4, 0.8], [0.4, 2.6, -0.2], [2.6, 3.2, 0.2], [4.2, 1.6, 1.6]].map((p) => [p[0] + ST.write[0], p[1], p[2]] as V3));+ const ribbon = new THREE.Mesh(new THREE.TubeGeometry(swoop, 480, 0.13, 20), mat(PAL.coral, { rough: 0.3 }));+ const bead = new THREE.Mesh(new THREE.SphereGeometry(0.24, 32, 20), mat(PAL.sun, { emissive: PAL.sun, ei: 0.9 }));+ const pillars = new THREE.Group();+ [[-3.0, -2.0, 1.6, PAL.lilac], [3.4, -2.4, 2.4, PAL.teal], [-0.8, -3.4, 1.1, PAL.cream], [4.6, 0.2, 0.8, PAL.sun]].forEach(([x, z, h, c]) => {+ const g = new THREE.CylinderGeometry(0.42, 0.42, h as number, 40); g.translate(0, (h as number) / 2, 0);+ const m = new THREE.Mesh(g, mat(c as string)); m.position.set(ST.write[0] + (x as number), 0, z as number); pillars.add(m);+ });+ bead.position.copy(swoop.getPointAt(0));+ scene.add(shadowy(ribbon), shadowy(bead), shadowy(pillars));++ // morph: a ring of beads and a tube laid through them, standing up; a circle becoming a star+ const M = 64, cy = 2.3, ringR = 1.9;+ const circle: V3[] = Array.from({ length: M }, (_, i) => { const a = (i / M) * Math.PI * 2 + Math.PI / 2; return [ST.morph[0] + Math.cos(a) * ringR, cy + Math.sin(a) * ringR, 0]; });+ const star: V3[] = Array.from({ length: 10 }, (_, i) => { const a = (i / 10) * Math.PI * 2 + Math.PI / 2, r = i % 2 ? 0.95 : 2.25; return [ST.morph[0] + Math.cos(a) * r, cy + Math.sin(a) * r, 0]; });+ const ringTube = new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(circle.map((p) => new THREE.Vector3(...p)), true), 256, 0.07, 12, true), mat(PAL.teal, { rough: 0.3 }));+ const beads = new THREE.Group(), beadGeo = new THREE.SphereGeometry(0.15, 24, 16), beadMat = mat(PAL.sun, { emissive: "#ff9a1f", ei: 0.35 });+ for (let i = 0; i < 20; i++) beads.add(new THREE.Mesh(beadGeo, beadMat));+ const plinth = new THREE.Mesh(slab(5.6, 1.4, 0.3, 0.3, 0.06).rotateX(-Math.PI / 2), mat(PAL.lilac)); plinth.position.set(ST.morph[0], 0.06, 0);+ scene.add(shadowy(ringTube), shadowy(beads), shadowy(plinth));++ // explode: a 3x3x3 block of soft cubes, sun on the corners, coral on the edges, cream elsewhere+ const block = new THREE.Group(), cubeGeo = slab(0.52, 0.52, 0.52, 0.12, 0.05); cubeGeo.center();+ const cubeMat = { sun: mat(PAL.sun), coral: mat(PAL.coral), cream: mat(PAL.cream) };+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) for (let k = 0; k < 3; k++) {+ const ends = [i, j, k].filter((v) => v !== 1).length, m = new THREE.Mesh(cubeGeo, ends === 3 ? cubeMat.sun : ends === 2 ? cubeMat.coral : cubeMat.cream);+ m.position.set((i - 1) * 0.68, 0.34 + j * 0.68, (k - 1) * 0.68); block.add(m);+ }+ const blockWrap = new THREE.Group(); blockWrap.add(block); blockWrap.position.set(...ST.explode);+ scene.add(shadowy(blockWrap));++ const cam = new THREE.PerspectiveCamera(35, W / H, 0.1, 200);+ return { scene, key, rim, tiles, swoop, ribbon, bead, pillars, circle, star, ringTube, beads, block, blockWrap, cam };+};++// ---- camera, one move per shot, in film frames+const shot1 = withMods(pushIn(look([3.6, 4.4, 7.2], [0, 0.1, 0.2], 36), 0.22, 0, CUT.write, ease.inOutSine), handheld(2, 0.6));+const shot2 = withMods(dolly(path([[ST.write[0] - 5.5, 1.3, 7.6], [ST.write[0] - 2.5, 2.3, 7.8], [ST.write[0] + 1.5, 2.8, 8.0], [ST.write[0] + 4.5, 2.1, 8.4]]), CUT.write, CUT.morph, { target: [ST.write[0], 1.7, 0], fov: 38, ease: ease.inOutSine }), handheld(3, 0.4));+const D0: CamState = look([ST.explode[0] + 4.6, 2.4, 6.6], [ST.explode[0], 1.0, 0], 36);+const WHIP = CUT.explode - BEAT;+const orbitC = orbit([ST.morph[0], 1.9, 0], -38, 22, 10.6, 0.8, CUT.morph, WHIP + 2, { fov: 36, ease: ease.inOutSine });+const shot3: Move = then(orbitC, WHIP, whipPan(orbitC(WHIP), D0, WHIP, CUT.explode, { hold: 2 }));+const shot4 = withMods(crane(D0, 2.2, CUT.explode, N, { follow: 0.25, ease: ease.inOutSine }), dutch((f) => -7 * tween(f, CUT.explode, N, ease.inOutSine)), handheld(5, 0.5));+const camAt = (f: number) => (f < CUT.write ? shot1(f) : f < CUT.morph ? shot2(f) : f < CUT.explode ? shot3(f) : shot4(f));++const draw = (ctx: Ctx, f: number, env: Env) => {+ const s = memo(env, "threeMotionDemo", build);++ // grid: pops from the centre outwards (begun just before frame 0 so the film opens on motion), then a wave+ grid(s.tiles, f, -14, 3, (c, ff, at) => popIn(c, ff, at, 12));+ wave(s.tiles, f, 20, 26, { height: 0.45, width: 4 });++ // write: pillars rise on the beat, the ribbon writes on with the bead on its tip+ lagged(s.pillars, f, CUT.write - 6, 6, (c, ff, at) => riseFromFloor(c, ff, at, 14, 2.6));+ const w0 = CUT.write + 2, w1 = CUT.morph - 10, wt = ease.inOutSine(seg(f, w0, w1));+ writeOn(s.ribbon, f, w0, w1 - w0, ease.inOutSine);+ // the bead drops onto the ribbon's start (its rest pose), then rides the tip; dropIn's squash rings on+ dropIn(s.bead, f, w0 - 10, 14, { height: 2.5 });+ if (f >= w0) moveAlongPath(s.bead, s.swoop, wt);++ // morph: ring draws on, beads pop in around it, circle becomes star, star pulses+ const m0 = CUT.morph, mt = ease.inOutCubic(seg(f, m0 + 14, m0 + 34));+ const shape = morph(s.circle, s.star, mt, { n: 120, closed: true });+ writeTube(s.ringTube.geometry as THREE.TubeGeometry, shape, true);+ writeOn(s.ringTube, f, m0 - 4, 14, ease.outCubic);+ const ring20 = morph(s.circle, s.star, mt, { n: 20, closed: true });+ // popIn owns scale and visibility only, so the beads ride the morph through position freely+ lagged(s.beads, f, m0 + 2, 1, (b, ff, at, i) => { b.position.set(...ring20[i]); popIn(b, ff, at, 10); });+ indicate(s.beads, f, m0 + 36, 12, { scale: 1.0, color: "#ffffff", strength: 0.5 });++ // explode: flash in the whip's tail, blow apart on the beat, home again two beats later+ indicate(s.blockWrap, f, CUT.explode - 6, 12, { scale: 1.08, color: "#ffe9b0", strength: 0.45 });+ if (f < CUT.explode + 24) explode(s.block, f, CUT.explode + 6, 18, { seed: 9, distance: 1.9, spin: 0.35, upward: true });+ else assemble(s.block, f, CUT.explode + 26, 22, { seed: 9, distance: 1.9, spin: 0.35, upward: true, ease: ease.inOutCubic });++ // lights follow the station the camera is at, so one 16-unit shadow map covers every shot+ const c = camAt(f), at = c.target;+ s.key.position.set(at[0] + 5, 9, at[2] + 6); s.key.target.position.set(at[0], 0, at[2]);+ s.rim.position.set(at[0] - 4, 5, at[2] - 8); s.rim.target.position.set(at[0], 1, at[2]);+ place(s.cam, c, env);+ draw3d(ctx, env, s.scene, s.cam, { clear: BG, shadows: true });+};++const shot = (id: string, start: number, end: number) => ({ id, start, end, draw: (ctx: Ctx, local: number, env: Env) => draw(ctx, start + local, env) });+export const threeMotionDemo: Film = {+ meta: { title: "three motion demo", W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "explainer", poster: 130,+ // the whip pan opens on posed held frames (no smear, lesson 46); the star has finished, so they are truly still+ holds: [[WHIP, WHIP + 3, "whip pan: held pose before the whip"]] },+ assets: { images: {} },+ shots: [shot("grid", 0, CUT.write), shot("write", CUT.write, CUT.morph), shot("morph", CUT.morph, CUT.explode), shot("explode", CUT.explode, N)],+};diff --git a/skills/anidoodle/engine/src/hosts/page-threeMotionDemo.ts b/skills/anidoodle/engine/src/hosts/page-threeMotionDemo.tsnew file mode 100644index 0000000..dea9a14--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-threeMotionDemo.ts@@ -0,0 +1,4 @@+import { threeMotionDemo } from "../canvas-core/threeMotionDemo";+import { mountFilm } from "./page";++mountFilm(threeMotionDemo);diff --git a/skills/anidoodle/engine/src/three-core/camera.ts b/skills/anidoodle/engine/src/three-core/camera.tsnew file mode 100644index 0000000..8c4e7f6--- /dev/null+++ b/skills/anidoodle/engine/src/three-core/camera.ts@@ -0,0 +1,202 @@+// CAMERA (3D). Named moves a director would call, each a pure function of the frame that returns a+// whole camera state: where it stands, what it looks at, the lens and the roll. place() writes a+// state onto a THREE.PerspectiveCamera. Nothing is stepped, so any frame can be drawn first.+//+// const base = look([0, 1.2, 8], [0, 0.6, 0], 35);+// const move = withMods(pushIn(base, 0.3, 0, 48), handheld(7, 0.6));+// place(cam, move(f), env);+//+// Same vocabulary as the 2D camera (canvas-core/camera.ts) and the same craft:+// - A PUSH IS EASED IN log(distance). Halving the distance twice should take twice as long as+// halving it once; easing the distance itself sprints at the near end.+// - A DOLLY ALONG A PATH RUNS AT CONSTANT SPEED BY ARC LENGTH (getPointAt), then the ease shapes+// it. Curve parameter u bunches up wherever the control points do, which reads as a stutter.+// - HANDHELD IS SMOOTH SEEDED NOISE, MOSTLY ROTATION. Per-frame random reads as static; a slow+// aim wander and a little roll is what sells an operator. Never Math.random.+// - A WHIP PAN HOLDS POSED FRAMES ON BOTH ENDS AND HAS NO SMEAR (lesson 46): sharp drawings at each+// end and a fast move between make the cut without a motion-blur bible break.+// - A MATCH CUT KEEPS SCREEN SIZE: on-screen size is worldSize * H / (2 * D * tan(fov / 2)), so+// across a lens change keep D * tan(fov / 2) fixed (matchDistance) and the subject holds its size.+// - LEGIBILITY IS MEASURED IN PIXELS (lessons 25, 27): a contact beat needs ~40 px at 1080p, a+// story-critical line ~2 px. screenSize() and worldForPx() turn a camera into those numbers.+import * as THREE from "three";+import { ease as E, seg, type Ease } from "./time";++export type V3 = [number, number, number];+/** a whole camera: position, the point it looks at, vertical fov in degrees, roll in degrees */+export type CamState = { pos: V3; target: V3; fov: number; roll: number };+/** a camera move: frame in, camera out */+export type Move = (f: number) => CamState;+/** something layered on top of a move (handheld, dutch): state and frame in, new state out */+export type Mod = (s: CamState, f: number) => CamState;+type Size = { W: number; H: number };++const D2R = Math.PI / 180;+const v = (a: V3) => new THREE.Vector3(a[0], a[1], a[2]);+const arr = (p: THREE.Vector3): V3 => [p.x, p.y, p.z];+const lerp3 = (a: V3, b: V3, t: number): V3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+const p = (f: number, f0: number, f1: number, e: Ease) => e(seg(f, f0, f1));++/** a camera state from where it stands and what it looks at */+export const look = (pos: V3, target: V3, fov = 35, roll = 0): CamState => ({ pos: [...pos], target: [...target], fov, roll });+/** a move that never moves (a locked-off shot; add handheld to keep it alive) */+export const hold = (s: CamState): Move => () => ({ ...s, pos: [...s.pos], target: [...s.target] });+/** layer modifiers over a move, in order */+export const withMods = (move: Move, ...mods: Mod[]): Move => (f) => mods.reduce((s, m) => m(s, f), move(f));+/** run one move until frame `at`, then another (a move that hands over without a cut) */+export const then = (a: Move, at: number, b: Move): Move => (f) => (f < at ? a(f) : b(f));++/** write a state onto a three camera: position, lookAt, roll about the view axis, fov (and aspect from env) */+export const place = (cam: THREE.PerspectiveCamera, s: CamState, env?: Size) => {+ cam.position.set(s.pos[0], s.pos[1], s.pos[2]);+ cam.up.set(0, 1, 0);+ cam.lookAt(s.target[0], s.target[1], s.target[2]);+ if (s.roll) cam.rotateZ(s.roll * D2R);+ cam.fov = s.fov;+ if (env) cam.aspect = env.W / env.H;+ cam.updateProjectionMatrix();+ cam.updateMatrixWorld(true);+ return cam;+};++// distance moved in log space: equal time per halving+const pushTo = (base: CamState, factor: number, f: number, f0: number, f1: number, e: Ease): CamState => {+ const k = Math.exp(Math.log(factor) * p(f, f0, f1, e)), t = base.target;+ return { ...base, pos: [t[0] + (base.pos[0] - t[0]) * k, t[1] + (base.pos[1] - t[1]) * k, t[2] + (base.pos[2] - t[2]) * k], target: [...t] };+};+/** move toward the target: amount 0.3 ends 30% closer */+export const pushIn = (base: CamState, amount: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => (f) => pushTo(base, 1 - amount, f, f0, f1, e);+/** move away from the target: amount 0.3 ends 30% farther */+export const pullBack = (base: CamState, amount: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => (f) => pushTo(base, 1 + amount, f, f0, f1, e);++/** a path for the camera through points (centripetal Catmull-Rom: no loops or overshoot at tight keys) */+export const path = (points: V3[], closed = false) => new THREE.CatmullRomCurve3(points.map(v), closed, "centripetal");+/** travel along a curve at constant speed by arc length; aim at a fixed point, along a second curve, or ahead along the path */+export const dolly = (curve: THREE.Curve<THREE.Vector3>, f0: number, f1: number, o: { target?: V3 | THREE.Curve<THREE.Vector3> | "ahead"; fov?: number; ease?: Ease; lead?: number } = {}): Move => {+ // arc-length table built once here, not on the first draw: getPointAt caches it on the curve+ curve.getLengths();+ return (f) => {+ const t = p(f, f0, f1, o.ease ?? E.inOutSine), pos = arr(curve.getPointAt(t));+ let target: V3;+ // "ahead": look along the travel direction, `lead` units out (the tangent, so it never stalls at the end)+ if (o.target === undefined || o.target === "ahead") target = arr(curve.getPointAt(t).add(curve.getTangentAt(t).multiplyScalar(o.lead ?? 3)));+ else if (Array.isArray(o.target)) target = [...o.target];+ else target = arr(o.target.getPointAt(t));+ return { pos, target, fov: o.fov ?? 35, roll: 0 };+ };+};+/** circle a point at a radius and height above it, fromDeg to toDeg (0 deg = on +z, looking toward -z) */+export const orbit = (center: V3, fromDeg: number, toDeg: number, radius: number, height: number, f0: number, f1: number, o: { fov?: number; ease?: Ease } = {}): Move => (f) => {+ const a = (fromDeg + (toDeg - fromDeg) * p(f, f0, f1, o.ease ?? E.inOutSine)) * D2R;+ return { pos: [center[0] + Math.sin(a) * radius, center[1] + height, center[2] + Math.cos(a) * radius], target: [...center], fov: o.fov ?? 35, roll: 0 };+};+/** rise (or sink, negative) by `rise`; follow 0 keeps the aim point (the camera tilts), 1 lifts it too */+export const crane = (base: CamState, rise: number, f0: number, f1: number, o: { follow?: number; ease?: Ease } = {}): Move => (f) => {+ const d = rise * p(f, f0, f1, o.ease ?? E.inOutCubic);+ return { ...base, pos: [base.pos[0], base.pos[1] + d, base.pos[2]], target: [base.target[0], base.target[1] + d * (o.follow ?? 0), base.target[2]] };+};+// the camera's right and up axes for a state (world up is +y)+const axes = (s: CamState) => {+ const fwd = v(s.target).sub(v(s.pos)).normalize(), right = new THREE.Vector3().crossVectors(fwd, new THREE.Vector3(0, 1, 0)).normalize();+ return { fwd, right, up: new THREE.Vector3().crossVectors(right, fwd) };+};+/** slide sideways (positive = camera right), aim point and all */+export const truck = (base: CamState, dx: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => {+ const r = arr(axes(base).right);+ return (f) => { const d = dx * p(f, f0, f1, e); return { ...base, pos: lerp3(base.pos, [base.pos[0] + r[0], base.pos[1] + r[1], base.pos[2] + r[2]], d), target: lerp3(base.target, [base.target[0] + r[0], base.target[1] + r[1], base.target[2] + r[2]], d) }; };+};+const turnAim = (s: CamState, axis: THREE.Vector3, deg: number): V3 => arr(v(s.target).sub(v(s.pos)).applyAxisAngle(axis, deg * D2R).add(v(s.pos)));+/** turn the camera on its head left or right (positive = left) */+export const pan = (base: CamState, deg: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => (f) => ({ ...base, pos: [...base.pos], target: turnAim(base, new THREE.Vector3(0, 1, 0), deg * p(f, f0, f1, e)) });+/** nod the camera up or down (positive = up) */+export const tilt = (base: CamState, deg: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => { const r = axes(base).right; return (f) => ({ ...base, pos: [...base.pos], target: turnAim(base, r, deg * p(f, f0, f1, e)) }); };+/**+ * A fast pan from one aim to another: the first `hold` frames sit on `from`, the last `hold` on `to`,+ * the move between is an expo in-out with no smear. Both states may differ in position too.+ */+export const whipPan = (from: CamState, to: CamState, f0: number, f1: number, o: { hold?: number } = {}): Move => {+ const h = o.hold ?? 2;+ if (f1 - f0 < 2 * h + 2) throw new Error(`whipPan: ${f1 - f0} frames is too short for ${h} held frames each end plus a move`);+ // aim swings on a sphere around the moving position, so the pan reads as a turn, not a slide+ return (f) => {+ const t = E.inOutExpo(seg(f, f0 + h, f1 - h)), pos = lerp3(from.pos, to.pos, t);+ const da = v(from.target).sub(v(from.pos)), db = v(to.target).sub(v(to.pos)), la = da.length(), lb = db.length();+ const q = new THREE.Quaternion().setFromUnitVectors(da.clone().normalize(), db.clone().normalize()), dir = da.clone().normalize().applyQuaternion(new THREE.Quaternion().slerp(q, t));+ return { pos, target: arr(dir.multiplyScalar(la + (lb - la) * t).add(v(pos))), fov: from.fov + (to.fov - from.fov) * t, roll: from.roll + (to.roll - from.roll) * t };+ };+};+/** roll the frame: a fixed angle, or a function of the frame for an eased dutch */+export const dutch = (roll: number | ((f: number) => number)): Mod => (s, f) => ({ ...s, roll: s.roll + (typeof roll === "number" ? roll : roll(f)) });+/** change the lens over time (deg): a zoom, which unlike a push keeps every depth's proportion */+export const zoom = (fromFov: number, toFov: number, f0: number, f1: number, e: Ease = E.inOutCubic): Mod => (s, f) => ({ ...s, fov: fromFov + (toFov - fromFov) * p(f, f0, f1, e) });++// ---- seeded smooth noise+/** a pure hash of (seed, i) to [0, 1): no sequence, so any i can be asked first */+export const hash01 = (seed: number, i: number) => {+ let h = Math.imul((seed | 0) ^ 0x9e3779b9, 0x85ebca6b) ^ Math.imul(i | 0, 0xc2b2ae35);+ h ^= h >>> 16; h = Math.imul(h, 0x7feb352d); h ^= h >>> 15; h = Math.imul(h, 0x846ca68b); h ^= h >>> 16;+ return (h >>> 0) / 4294967296;+};+/** smooth 1D value noise in [-1, 1]: quintic between seeded lattice values one unit apart */+export const noise1 = (seed: number, x: number) => {+ const i = Math.floor(x), t = x - i, s = t * t * t * (t * (t * 6 - 15) + 10);+ const a = hash01(seed, i) * 2 - 1, b = hash01(seed, i + 1) * 2 - 1;+ return a + (b - a) * s;+};+/**+ * An operator holding the camera: aim wander, roll and a little sway, all seeded smooth noise.+ * amount 1 = about 0.5 deg of aim wander; freq in wobbles per second at 24 fps (default 0.6).+ */+export const handheld = (seed: number, amount = 1, o: { freq?: number; fps?: number } = {}): Mod => (s, f) => {+ const x = (f / (o.fps ?? 24)) * (o.freq ?? 0.6), n = (k: number) => noise1(seed * 31 + k, x + k * 0.37) * 0.7 + noise1(seed * 31 + k + 9, x * 2.3) * 0.3;+ const { right, up } = axes(s), dist = v(s.target).sub(v(s.pos)).length(), aim = Math.tan(0.5 * amount * D2R) * dist, sway = 0.004 * amount * dist;+ const dt = right.clone().multiplyScalar(n(1) * aim).add(up.clone().multiplyScalar(n(2) * aim));+ const dp = right.clone().multiplyScalar(n(3) * sway).add(up.clone().multiplyScalar(n(4) * sway));+ return { pos: arr(v(s.pos).add(dp)), target: arr(v(s.target).add(dt).add(dp)), fov: s.fov, roll: s.roll + n(5) * 0.35 * amount };+};++// ---- framing and legibility+/**+ * Frame a box (or an object's bounds): look from `dir` (pointing from the subject toward the+ * camera) at the box centre, at the distance where the box's furthest corner sits `padding` in+ * from the frame edge (padding 1.15 = 15% margin). Solved by bisection on the projected corners,+ * so it is exact for this aspect, not the loose bounding-sphere fit.+ */+export const fitTo = (subject: THREE.Box3 | THREE.Object3D, o: { padding?: number; dir?: V3; fov?: number; aspect?: number } = {}): CamState => {+ const box = (subject as THREE.Box3).isBox3 ? (subject as THREE.Box3) : new THREE.Box3().setFromObject(subject as THREE.Object3D);+ if (box.isEmpty()) throw new Error("fitTo: the subject has no bounds");+ const c = box.getCenter(new THREE.Vector3()), dir = v(o.dir ?? [0, 0.25, 1]).normalize(), fov = o.fov ?? 35, aspect = o.aspect ?? 16 / 9, pad = o.padding ?? 1.15;+ const cam = new THREE.PerspectiveCamera(fov, aspect, 0.01, 1e5);+ const corners = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => new THREE.Vector3(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z));+ const reach = (d: number) => {+ cam.position.copy(c).addScaledVector(dir, d); cam.lookAt(c); cam.updateMatrixWorld(true); cam.updateProjectionMatrix();+ let m = 0; for (const k of corners) { const q = k.clone().applyMatrix4(cam.matrixWorldInverse); if (-q.z <= cam.near) return Infinity; const n = k.clone().project(cam); m = Math.max(m, Math.abs(n.x), Math.abs(n.y)); }+ return m;+ };+ let lo = 1e-3, hi = Math.max(1, box.getSize(new THREE.Vector3()).length()) * 2;+ while (reach(hi) > 1 / pad) hi *= 2;+ for (let i = 0; i < 60; i++) { const mid = (lo + hi) / 2; if (reach(mid) > 1 / pad) lo = mid; else hi = mid; }+ return { pos: arr(c.clone().addScaledVector(dir, hi)), target: arr(c), fov, roll: 0 };+};+/** a focus distance racked from one subject distance to another, eased in dioptres (1/d): how a real focus ring moves */+export const rackFocus = (f: number, f0: number, f1: number, fromDist: number, toDist: number, e: Ease = E.inOutCubic) => 1 / (1 / fromDist + (1 / toDist - 1 / fromDist) * p(f, f0, f1, e));+/** pixels an object worldSize tall covers at `distance` from the camera, at the film's height */+export const screenSize = (cam: { fov: number }, worldSize: number, distance: number, env: Size) => (worldSize * env.H) / (2 * distance * Math.tan((cam.fov * D2R) / 2));+/** the world size that covers `px` pixels at `distance`: size a thin story line by its screen width (lesson 27) */+export const worldForPx = (cam: { fov: number }, px: number, distance: number, env: Size) => (px * 2 * distance * Math.tan((cam.fov * D2R) / 2)) / env.H;+/** the camera distance that shows a subject worldSize tall at `px` pixels through this fov (D = K / tan(fov/2)) */+export const matchCut = (worldSize: number, px: number, fovDeg: number, env: Size) => (worldSize * env.H) / (2 * px * Math.tan((fovDeg * D2R) / 2));+/** the distance through fovB that keeps the size a subject had at distance dA through fovA */+export const matchDistance = (dA: number, fovA: number, fovB: number) => (dA * Math.tan((fovA * D2R) / 2)) / Math.tan((fovB * D2R) / 2);+/** a state through a new lens with the subject at its target holding its screen size (the camera slides along its view axis) */+export const matchLens = (s: CamState, fov: number): CamState => {+ const d = v(s.pos).sub(v(s.target)), k = matchDistance(d.length(), s.fov, fov) / d.length();+ return { ...s, fov, pos: arr(v(s.target).add(d.multiplyScalar(k))), target: [...s.target] };+};+/** where a world point lands on the film, in film pixels [x, y] (call place() first); z > 1 means behind the camera */+export const screenPx = (cam: THREE.PerspectiveCamera, world: V3 | THREE.Vector3, env: Size): [number, number, number] => {+ const q = (Array.isArray(world) ? v(world) : world.clone()).project(cam);+ return [((q.x + 1) / 2) * env.W, ((1 - q.y) / 2) * env.H, q.z];+};+/** distance from the camera to a world point along its view axis (what screenSize wants) */+export const depthOf = (cam: THREE.Camera, world: V3) => -v(world).applyMatrix4(cam.matrixWorldInverse).z;diff --git a/skills/anidoodle/engine/src/three-core/mograph.ts b/skills/anidoodle/engine/src/three-core/mograph.tsnew file mode 100644index 0000000..89b8170--- /dev/null+++ b/skills/anidoodle/engine/src/three-core/mograph.ts@@ -0,0 +1,208 @@+// MOGRAPH. Motion-graphics verbs for three objects, each a pure function of the frame:+// popIn(mesh, f, 24, 12) // at frame 24, over 12 frames+// A verb SETS the channels it owns from the object's rest pose every time it is called: before its+// start it writes the "before" state (usually hidden), after its end the exact rest ("after")+// state, so a frame never inherits anything from the frame drawn before it.+//+// - REST POSE. The pose an object was built in (position, rotation, scale, material opacity and+// emissive) is recorded the first time any verb touches it (or call keepRest() in the build).+// Verbs compute from that, never from the current values, so nothing accumulates.+// - ONE VERB PER CHANNEL. Two verbs that both write scale on one object: the later call wins. To+// layer a pop with an indicate, nest the mesh in a Group and give each its own object.+// - Seeds, never Math.random: explode, wiggle and the noise draw from a pure hash of (seed, index).+import * as THREE from "three";+import { ease as E, seg, spring, type Ease } from "./time";+import { hash01, noise1 } from "./camera";++type V3 = [number, number, number];+type Rest = { position: THREE.Vector3; quaternion: THREE.Quaternion; scale: THREE.Vector3; visible: boolean };+type MatRest = { opacity: number; transparent: boolean; emissive?: THREE.Color };+const REST = "anidoodleRest";++/** record an object's pose as its rest pose now (verbs do this on first touch; call it in a build that moves things later) */+export const keepRest = (o: THREE.Object3D): Rest => {+ if (!o.userData[REST]) o.userData[REST] = { position: o.position.clone(), quaternion: o.quaternion.clone(), scale: o.scale.clone(), visible: o.visible } as Rest;+ return o.userData[REST] as Rest;+};+const rest = keepRest;+const mats = (o: THREE.Object3D): THREE.Material[] => {+ const out: THREE.Material[] = [];+ o.traverse((c) => { const m = (c as THREE.Mesh).material; if (m) for (const x of Array.isArray(m) ? m : [m]) if (!out.includes(x)) out.push(x); });+ return out;+};+const matRest = (m: THREE.Material): MatRest => {+ if (!m.userData[REST]) { const em = (m as THREE.MeshStandardMaterial).emissive; m.userData[REST] = { opacity: m.opacity, transparent: m.transparent, emissive: em ? em.clone() : undefined } as MatRest; }+ return m.userData[REST] as MatRest;+};+const t01 = (f: number, at: number, len: number) => seg(f, at, at + len);+// a scale of exactly 0 gives singular normal matrices; hide instead+const showScaled = (o: THREE.Object3D, r: Rest, k: number, kz = k) => { o.visible = r.visible && k > 1e-4 && kz > 1e-4; o.scale.set(r.scale.x * k, r.scale.y * k, r.scale.z * kz); };++/** scale up from nothing with an overshoot that lands: the default entrance */+export const popIn = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.outBack) => { const r = rest(o), t = t01(f, at, len); showScaled(o, r, t >= 1 ? 1 : Math.max(0, e(t))); };+/** scale down to nothing (anticipation first) */+export const popOut = (o: THREE.Object3D, f: number, at: number, len = 10) => { const r = rest(o), t = t01(f, at, len); showScaled(o, r, t <= 0 ? 1 : Math.max(0, 1 - E.inBack(t))); };+/**+ * Fall from `height` above rest, land at 40% of len, then squash and settle on a closed-form+ * spring (so it is seekable). Hidden before it starts.+ */+export const dropIn = (o: THREE.Object3D, f: number, at: number, len = 18, o2: { height?: number; squash?: number; fps?: number } = {}) => {+ const r = rest(o), land = at + Math.max(1, Math.round(len * 0.4)), h = o2.height ?? 3, sq = o2.squash ?? 0.28;+ o.position.copy(r.position);+ o.position.y += h * (1 - E.inQuad(seg(f, at, land)));+ // the spring rings from the landing; fade it to exactly 0 by the end so "after" is the rest pose+ const s = f >= at + len ? 0 : spring(f, land, o2.fps ?? 24, 3, 0.35) * sq * (1 - seg(f, land, at + len));+ o.scale.set(r.scale.x * (1 + s * 0.5), r.scale.y * (1 - s), r.scale.z * (1 + s * 0.5));+ o.visible = r.visible && f >= at;+};+/** rise out of the floor from `depth` below rest (hidden before it starts) */+export const riseFromFloor = (o: THREE.Object3D, f: number, at: number, len = 14, depth = 1, e: Ease = E.outCubic) => {+ const r = rest(o); o.position.copy(r.position); o.position.y -= depth * (1 - e(t01(f, at, len))); o.visible = r.visible && f >= at;+};+/** grow out of a point (in the parent's space): travel from it while scaling up */+export const growFrom = (o: THREE.Object3D, f: number, at: number, len: number, point: V3, e: Ease = E.outCubic) => {+ const r = rest(o), k = e(t01(f, at, len)); o.position.set(point[0], point[1], point[2]).lerp(r.position, k); showScaled(o, r, k);+};+const setOpacity = (o: THREE.Object3D, k: number) => {+ for (const m of mats(o)) {+ const mr = matRest(m);+ m.opacity = mr.opacity * k;+ // back to opaque when fully in, or sorting artefacts linger on a finished object+ const tr = k < 1 || mr.transparent;+ if (m.transparent !== tr) { m.transparent = tr; m.needsUpdate = true; }+ }+ o.visible = rest(o).visible && k > 0;+};+/** fade materials in (every material of every mesh below, arrays too) */+export const fadeIn = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.inOutSine) => setOpacity(o, e(t01(f, at, len)));+/** fade materials out */+export const fadeOut = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.inOutSine) => setOpacity(o, 1 - e(t01(f, at, len)));+/** type or a shape gaining its depth: scale z from a sliver to rest (real bevel-last extrusion is type3d's job) */+export const extrudeIn = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.outCubic) => { const r = rest(o), t = t01(f, at, len); showScaled(o, r, t > 0 ? 1 : 0, 0.02 + 0.98 * e(t)); };++/**+ * Draw a path on from 0 to t (a fraction) with setDrawRange. A TubeGeometry draws whole tubular+ * segments (radialSegments * 6 indices each); a Line or Points draws whole vertices.+ */+export const drawTo = (mesh: THREE.Mesh | THREE.Line | THREE.Points, t: number) => {+ const g = mesh.geometry as THREE.BufferGeometry & { parameters?: { tubularSegments?: number; radialSegments?: number } };+ const k = Math.max(0, Math.min(1, t));+ if (g.parameters?.tubularSegments && g.parameters.radialSegments && g.index) g.setDrawRange(0, Math.round(k * g.parameters.tubularSegments) * g.parameters.radialSegments * 6);+ else g.setDrawRange(0, Math.round(k * (g.index ? g.index.count : g.attributes.position.count)));+ mesh.visible = k > 0;+};+/** write a path on over len frames */+export const writeOn = (mesh: THREE.Mesh | THREE.Line | THREE.Points, f: number, at: number, len: number, e: Ease = E.inOutCubic) => drawTo(mesh, e(t01(f, at, len)));+/** put an object at fraction t along a curve (constant speed by arc length); orient turns its +z along the travel */+export const moveAlongPath = (o: THREE.Object3D, curve: THREE.Curve<THREE.Vector3>, t: number, orient = false) => {+ const k = Math.max(0, Math.min(1, t));+ o.position.copy(curve.getPointAt(k));+ if (orient) o.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), curve.getTangentAt(k).normalize());+};++// ---- morphs+/** n points spaced evenly by arc length along a polyline (closed adds the edge back to the start) */+export const resample = (pts: V3[], n: number, closed = false): V3[] => {+ const P = closed ? [...pts, pts[0]] : pts, cum = [0];+ for (let i = 1; i < P.length; i++) cum.push(cum[i - 1] + Math.hypot(P[i][0] - P[i - 1][0], P[i][1] - P[i - 1][1], P[i][2] - P[i - 1][2]));+ const L = cum[cum.length - 1], out: V3[] = [], m = closed ? n : n - 1;+ let j = 0;+ for (let i = 0; i < n; i++) {+ const d = m > 0 ? (L * i) / m : 0;+ while (j < P.length - 2 && cum[j + 1] < d) j++;+ const span = cum[j + 1] - cum[j], u = span > 0 ? (d - cum[j]) / span : 0;+ out.push([0, 1, 2].map((k) => P[j][k] + (P[j + 1][k] - P[j][k]) * u) as V3);+ }+ return out;+};+/** one shape becoming another: both resampled to the same count by arc length, then mixed at t */+export const morph = (a: V3[], b: V3[], t: number, o: { n?: number; closed?: boolean } = {}): V3[] => {+ const n = o.n ?? Math.max(a.length, b.length), A = resample(a, n, o.closed), B = resample(b, n, o.closed);+ return A.map((p, i) => [p[0] + (B[i][0] - p[0]) * t, p[1] + (B[i][1] - p[1]) * t, p[2] + (B[i][2] - p[2]) * t] as V3);+};+/** write points into a Line/Points geometry's position attribute (same count every frame) */+export const writePoints = (g: THREE.BufferGeometry, pts: V3[]) => {+ const a = g.attributes.position as THREE.BufferAttribute;+ if (a.count !== pts.length) throw new Error(`writePoints: geometry holds ${a.count} points, got ${pts.length}`);+ pts.forEach((p, i) => a.setXYZ(i, p[0], p[1], p[2]));+ a.needsUpdate = true; g.computeBoundingSphere();+};+/** rebuild a TubeGeometry in place along new points (same segment counts, so the buffers keep their size) */+export const writeTube = (g: THREE.TubeGeometry, pts: V3[], closed = false) => {+ const { tubularSegments, radius, radialSegments } = g.parameters;+ const fresh = new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts.map((p) => new THREE.Vector3(...p)), closed, "centripetal"), tubularSegments, radius, radialSegments, closed);+ for (const k of ["position", "normal"] as const) { (g.attributes[k] as THREE.BufferAttribute).copyArray(fresh.attributes[k].array as Float32Array); g.attributes[k].needsUpdate = true; }+ g.computeBoundingSphere(); fresh.dispose();+};++// ---- groups+const kids = (g: THREE.Object3D | THREE.Object3D[]) => (Array.isArray(g) ? g : g.children);+const unit = (seed: number, i: number) => { const z = hash01(seed, i * 3) * 2 - 1, a = hash01(seed, i * 3 + 1) * Math.PI * 2, r = Math.sqrt(1 - z * z); return new THREE.Vector3(r * Math.cos(a), z, r * Math.sin(a)); };+/**+ * Fly children apart (k 0 = assembled, 1 = exploded): each shard leaves along its direction from+ * the group's centre plus a seeded spread, and tumbles by up to `spin` turns.+ */+export const shatter = (g: THREE.Object3D | THREE.Object3D[], k: number, o: { seed?: number; distance?: number; spin?: number; upward?: boolean } = {}) => {+ const cs = kids(g), seed = o.seed ?? 1, centre = new THREE.Vector3();+ cs.forEach((c) => centre.add(rest(c).position)); centre.divideScalar(Math.max(1, cs.length));+ cs.forEach((c, i) => {+ const r = rest(c), out = r.position.clone().sub(centre);+ const dir = (out.lengthSq() > 1e-9 ? out.normalize() : new THREE.Vector3(0, 1, 0)).add(unit(seed, i).multiplyScalar(0.6)).normalize();+ // upward: a block on the floor must not throw shards through it+ if (o.upward) { dir.y = Math.abs(dir.y) + 0.2; dir.normalize(); }+ const d = (o.distance ?? 3) * (0.6 + 0.8 * hash01(seed, i * 3 + 2));+ c.position.copy(r.position).addScaledVector(dir, d * k);+ c.quaternion.copy(r.quaternion).multiply(new THREE.Quaternion().setFromAxisAngle(unit(seed + 7, i), (o.spin ?? 0.5) * Math.PI * 2 * k * (0.5 + hash01(seed + 3, i))));+ c.scale.copy(r.scale);+ });+};+/** blow the children apart from frame `at` (assembled before, exploded after) */+export const explode = (g: THREE.Object3D | THREE.Object3D[], f: number, at: number, len = 18, o: { seed?: number; distance?: number; spin?: number; upward?: boolean; ease?: Ease } = {}) => shatter(g, (o.ease ?? E.outCubic)(t01(f, at, len)), o);+/** bring scattered children home (exploded before, assembled after) */+export const assemble = (g: THREE.Object3D | THREE.Object3D[], f: number, at: number, len = 18, o: { seed?: number; distance?: number; spin?: number; upward?: boolean; ease?: Ease } = {}) => shatter(g, 1 - (o.ease ?? E.inOutCubic)(t01(f, at, len)), o);+/** call attention: a scale pulse and an emissive flash that peak mid-way and return exactly to rest */+export const indicate = (o: THREE.Object3D, f: number, at: number, len = 12, o2: { scale?: number; color?: string; strength?: number } = {}) => {+ const r = rest(o), t = t01(f, at, len), b = t > 0 && t < 1 ? Math.sin(Math.PI * t) : 0, flash = new THREE.Color(o2.color ?? "#ffffff");+ showScaled(o, r, 1 + ((o2.scale ?? 1.15) - 1) * b);+ for (const m of mats(o)) { const mr = matRest(m), em = (m as THREE.MeshStandardMaterial).emissive; if (em && mr.emissive) em.copy(mr.emissive).lerp(flash, b * (o2.strength ?? 0.6)); }+};+/** a seeded wobble about z that swells and dies within [at, at + len] */+export const wiggle = (o: THREE.Object3D, f: number, at: number, len = 18, o2: { seed?: number; deg?: number; freq?: number } = {}) => {+ const r = rest(o), t = t01(f, at, len), env = t > 0 && t < 1 ? Math.sin(Math.PI * t) : 0;+ const a = env * (o2.deg ?? 10) * (Math.PI / 180) * noise1(o2.seed ?? 1, (f - at) * (o2.freq ?? 0.5));+ o.quaternion.copy(r.quaternion).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), a));+};+/** a bump that travels across the children in order, lifting each by `height` as it passes */+export const wave = (g: THREE.Object3D | THREE.Object3D[], f: number, at: number, len = 24, o: { height?: number; width?: number; axis?: V3 } = {}) => {+ const cs = kids(g), n = cs.length, w = o.width ?? 2, ax = new THREE.Vector3(...(o.axis ?? [0, 1, 0]));+ const head = t01(f, at, len) * (n - 1 + 2 * w) - w;+ cs.forEach((c, i) => { const r = rest(c), d = (i - head) / w, b = Math.abs(d) < 1 ? 0.5 + 0.5 * Math.cos(Math.PI * d) : 0; c.position.copy(r.position).addScaledVector(ax, (o.height ?? 0.4) * b); });+};++/** a verb as lagged() and grid() call it: one child, the frame, its own start frame, its index */+export type Verb = (o: THREE.Object3D, f: number, at: number, i: number) => void;+/** start a verb on each child `stagger` frames after the one before (Manim's LaggedStart) */+export const lagged = (g: THREE.Object3D | THREE.Object3D[], f: number, start: number, stagger: number, verb: Verb) => kids(g).forEach((c, i) => verb(c, f, start + i * stagger, i));+/**+ * Stagger a verb across a layout by distance: rings of children equally far from the centre (or+ * from the outside in, with from "edge") start together, `stagger` frames per ring.+ */+export const grid = (g: THREE.Object3D | THREE.Object3D[], f: number, start: number, stagger: number, verb: Verb, o: { from?: "center" | "edge" | V3 } = {}) => {+ const cs = kids(g), c = new THREE.Vector3();+ if (Array.isArray(o.from)) c.set(...o.from); else { cs.forEach((x) => c.add(rest(x).position)); c.divideScalar(Math.max(1, cs.length)); }+ const d = cs.map((x) => Math.round(rest(x).position.distanceTo(c) * 1000) / 1000), rings = [...new Set(d)].sort((a, b) => a - b);+ cs.forEach((x, i) => { const ring = rings.indexOf(d[i]); verb(x, f, start + stagger * (o.from === "edge" ? rings.length - 1 - ring : ring), i); });+};+/**+ * Per-letter type motion for a group whose children are letters in reading order (type3d builds+ * them): each letter enters `stagger` frames after the last, by rise, pop, drop or spin.+ */+export const kinetic = (letters: THREE.Object3D, f: number, start: number, stagger = 2, o: { style?: "rise" | "pop" | "drop" | "spin"; len?: number } = {}) => {+ const len = o.len ?? 12, style = o.style ?? "rise";+ lagged(letters, f, start, stagger, (c, ff, at) => {+ if (style === "pop") popIn(c, ff, at, len);+ else if (style === "drop") dropIn(c, ff, at, len, { height: 1 });+ else if (style === "spin") { const r = rest(c), t = t01(ff, at, len); c.quaternion.copy(r.quaternion).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), (1 - E.outCubic(t)) * Math.PI)); c.visible = r.visible && t > 0; }+ else { const r = rest(c), t = E.outCubic(t01(ff, at, len)); c.position.copy(r.position); c.position.y -= 0.5 * (1 - t); setOpacity(c, t); }+ });+};diff --git a/skills/anidoodle/engine/src/three-core/time.ts b/skills/anidoodle/engine/src/three-core/time.tsnew file mode 100644index 0000000..a441e2f--- /dev/null+++ b/skills/anidoodle/engine/src/three-core/time.ts@@ -0,0 +1,75 @@+// TIME. The shared vocabulary every 3D module speaks. A frame number goes in, a number comes out;+// nothing here keeps state, so any frame can be drawn first.+//+// seg(f, a, b) 0 before frame a, 1 after frame b, linear between (the workhorse)+// ease.* shaping curves on [0, 1]+// spring(f, at, ...) a damped spring that was kicked at frame `at`, in closed form: follow-through+// and settle WITHOUT simulating from frame 0, so it stays seekable+// storyClock(...) maps the film's real frames onto the frames the shots were written in, so a+// narrator that stretches the film is a table edit, not 100 hand-moved numbers++export const clamp01 = (x: number) => (x < 0 ? 0 : x > 1 ? 1 : x);+export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;+/** progress of frame f through [a, b]: 0 before, 1 after */+export const seg = (f: number, a: number, b: number) => (b <= a ? (f >= a ? 1 : 0) : clamp01((f - a) / (b - a)));++export type Ease = (t: number) => number;+const back = 1.70158;+export const ease = {+ linear: ((t) => t) as Ease,+ inQuad: ((t) => t * t) as Ease,+ outQuad: ((t) => 1 - (1 - t) * (1 - t)) as Ease,+ inOutQuad: ((t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2)) as Ease,+ inCubic: ((t) => t * t * t) as Ease,+ outCubic: ((t) => 1 - (1 - t) ** 3) as Ease,+ inOutCubic: ((t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2)) as Ease,+ outQuint: ((t) => 1 - (1 - t) ** 5) as Ease,+ inOutSine: ((t) => -(Math.cos(Math.PI * t) - 1) / 2) as Ease,+ outExpo: ((t) => (t >= 1 ? 1 : 1 - 2 ** (-10 * t))) as Ease,+ inOutExpo: ((t) => (t <= 0 ? 0 : t >= 1 ? 1 : t < 0.5 ? 2 ** (20 * t - 10) / 2 : (2 - 2 ** (-20 * t + 10)) / 2)) as Ease,+ /** overshoots then lands: pops, drops, arrivals */+ outBack: ((t) => 1 + (back + 1) * (t - 1) ** 3 + back * (t - 1) ** 2) as Ease,+ /** pulls back first: anticipation before a move */+ inBack: ((t) => (back + 1) * t * t * t - back * t * t) as Ease,+ outElastic: ((t) => (t <= 0 ? 0 : t >= 1 ? 1 : 2 ** (-10 * t) * Math.sin((t * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1)) as Ease,+ outBounce: ((t) => { const n = 7.5625, d = 2.75; if (t < 1 / d) return n * t * t; if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75; if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375; return n * (t -= 2.625 / d) * t + 0.984375; }) as Ease,+ /** smoothstep: soft in and out, the default for camera moves */+ smooth: ((t) => t * t * (3 - 2 * t)) as Ease,+};+/** eased progress of frame f through [a, b] */+export const tween = (f: number, a: number, b: number, e: Ease = ease.inOutCubic) => e(seg(f, a, b));++/**+ * A damped spring kicked at frame `at`: returns the displacement (starting at 1, ringing down to 0)+ * at frame f. Multiply by an amplitude for follow-through (an antenna after a stop, a jar swinging+ * after a turn). Closed form, so frame 300 never needs frames 0-299. freq in Hz, damping 0-1.+ */+export const spring = (f: number, at: number, fps: number, freq = 2.2, damping = 0.28) => {+ if (f < at) return 0;+ const t = (f - at) / fps, w = 2 * Math.PI * freq, z = Math.min(0.999, Math.max(0, damping)), wd = w * Math.sqrt(1 - z * z);+ return Math.exp(-z * w * t) * (Math.cos(wd * t) + ((z * w) / wd) * Math.sin(wd * t));+};++/** frames per beat at a tempo; integer when the film's grid is valid (validate() enforces it) */+export const beatFrames = (bpm: number, fps: number) => (60 * fps) / bpm;++/**+ * STORY CLOCK. Shots are written against story frames (the grid they were planned on). When the+ * narration or the score stretches the film, give the real frame of each story anchor and every+ * shot follows: between anchors, time maps linearly. Anchors must increase in both columns.+ * const clock = storyClock([[0, 0], [240, 300], [480, 590]]); // [storyFrame, realFrame]+ * draw: (ctx, local, env) => shot(clock.story(start + local) - storyStart)+ * real(f) goes the other way. For cyclic motion that must keep its real speed (a walk, flicker),+ * use the real frame directly.+ */+export const storyClock = (anchors: [story: number, real: number][]) => {+ const a = [...anchors].sort((x, y) => x[0] - y[0]);+ for (let i = 1; i < a.length; i++) if (!(a[i][0] > a[i - 1][0] && a[i][1] > a[i - 1][1])) throw new Error(`storyClock: anchors must increase in both columns (at ${a[i - 1]} -> ${a[i]})`);+ const map = (x: number, from: 0 | 1, to: 0 | 1) => {+ if (a.length === 1) return x - a[0][from] + a[0][to];+ let i = 0; while (i < a.length - 2 && x > a[i + 1][from]) i++;+ const [p, q] = [a[i], a[i + 1]];+ return p[to] + ((x - p[from]) * (q[to] - p[to])) / (q[from] - p[from]);+ };+ return { story: (real: number) => map(real, 1, 0), real: (story: number) => map(story, 0, 1) };+};diff --git a/skills/anidoodle/engine/src/three-core/timeline.ts b/skills/anidoodle/engine/src/three-core/timeline.tsnew file mode 100644index 0000000..e1ba964--- /dev/null+++ b/skills/anidoodle/engine/src/three-core/timeline.ts@@ -0,0 +1,174 @@+// TIMELINE. Author motion the way a director talks ("these three pop in one after another, then the+// title slides up on the word 'three'"), compile it to a flat list of timed tweens, and read any+// track at any frame. Nothing is played: tl.value(name, f) is a pure lookup, so frame 300 never needs+// frames 0-299 and parallel renders agree.+//+// const tl = timeline(24, { labels: { drop: 48 }, words: [{ text: "three", frame: 96 }] });+// tl.at(0, set("x", 0), set("tint", "#ff6b5b"));+// tl.at("drop", chain(to("x", 2, 12, ease.outBack), wait(6), to("x", 0, 12)));+// tl.at({ word: "three" }, sequence(3, to("a", 1, 8), to("b", 1, 8), to("c", 1, 8)));+// draw: mesh.position.x = tl.num("x", f);+//+// Rules that keep it honest:+// - A clip is placed RELATIVE to where its parent puts it; only tl.at() names absolute frames (a+// number, a label, or a spoken word), so beats can come from narration timing later.+// - A tween with no `from` starts from whatever the track holds when it starts (the previous+// tween's end), resolved once at compile time. A track with nothing before it must be set() or+// use fromTo(), or compile throws: a silent 0 is how a prop teleports on frame 1.+// - Before the first key a track holds its first value; after the last it holds its last.+// - Colours mix in LINEAR light: sRGB midpoints read muddy and dark (red to green through brown).+// - check() names two tweens writing one track at once (the later-starting one wins, which is+// rarely what was meant) and cues off the beat grid.+import { ease as E, type Ease } from "./time";++export type Vec3 = [number, number, number];+/** a track's value: a number, an [x, y, z] vector, or a "#rrggbb" colour */+export type Value = number | Vec3 | string;+export type Tween = { track: string; start: number; end: number; from?: Value; to: Value; ease: Ease; src: string };+/** a piece of motion that does not know where it sits yet: emit() writes its tweens from `start` and returns its length */+export type Clip = { len: number; emit: (start: number, out: Tween[]) => void };+export type When = number | string | { label: string; offset?: number } | { word: string; nth?: number; offset?: number };++// ---- values+const hex = (s: string): Vec3 => {+ const m = /^#?([0-9a-f]{6})$/i.exec(s.trim()) ?? /^#?([0-9a-f]{3})$/i.exec(s.trim());+ if (!m) throw new Error(`timeline: '${s}' is not a #rrggbb colour`);+ const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255) as Vec3;+};+const toLin = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);+const toSrgb = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055);+const byte = (c: number) => Math.max(0, Math.min(255, Math.round(c * 255))).toString(16).padStart(2, "0");+/** a #rrggbb colour as linear-light rgb in [0, 1] (what three's Color holds internally) */+export const linear = (s: string): Vec3 => hex(s).map(toLin) as Vec3;+/** mix two values at t: numbers and vectors linearly, colours in linear light (returned as #rrggbb) */+export const mix = (a: Value, b: Value, t: number): Value => {+ if (typeof a === "number" && typeof b === "number") return a + (b - a) * t;+ if (typeof a === "string" && typeof b === "string") { const p = linear(a), q = linear(b); return "#" + p.map((x, i) => byte(toSrgb(x + (q[i] - x) * t))).join(""); }+ if (Array.isArray(a) && Array.isArray(b) && a.length === 3 && b.length === 3) return [0, 1, 2].map((i) => a[i] + (b[i] - a[i]) * t) as Vec3;+ throw new Error(`timeline: cannot mix ${JSON.stringify(a)} with ${JSON.stringify(b)} (one track, one kind of value)`);+};++// ---- clips (relative time)+const whole = (n: number, what: string) => { if (!Number.isFinite(n) || n < 0) throw new Error(`timeline: ${what} must be a frame count >= 0, got ${n}`); return n; };+/** move a track to `value` over `frames`, starting from wherever it is */+export const to = (track: string, value: Value, frames: number, e: Ease = E.inOutCubic): Clip => ({ len: whole(frames, "to() length"), emit: (s, o) => o.push({ track, start: s, end: s + frames, to: value, ease: e, src: `to(${track})` }) });+/** move a track from `a` to `b` over `frames` (jumps to `a` when it starts) */+export const fromTo = (track: string, a: Value, b: Value, frames: number, e: Ease = E.inOutCubic): Clip => ({ len: whole(frames, "fromTo() length"), emit: (s, o) => o.push({ track, start: s, end: s + frames, from: a, to: b, ease: e, src: `fromTo(${track})` }) });+/** jump a track to `value` with no motion */+export const set = (track: string, value: Value): Clip => ({ len: 0, emit: (s, o) => o.push({ track, start: s, end: s, from: value, to: value, ease: E.linear, src: `set(${track})` }) });+/** nothing for n frames (a held breath inside a chain) */+export const wait = (n: number): Clip => ({ len: whole(n, "wait()"), emit: () => {} });+/** play clips together; lasts as long as the longest */+export const all = (...clips: Clip[]): Clip => ({ len: Math.max(0, ...clips.map((c) => c.len)), emit: (s, o) => clips.forEach((c) => c.emit(s, o)) });+/** play clips one after another */+export const chain = (...clips: Clip[]): Clip => ({ len: clips.reduce((n, c) => n + c.len, 0), emit: (s, o) => { let t = s; for (const c of clips) { c.emit(t, o); t += c.len; } } });+/** start each clip `stagger` frames after the one before (Manim's LaggedStart) */+export const sequence = (stagger: number, ...clips: Clip[]): Clip => ({ len: Math.max(0, ...clips.map((c, i) => i * stagger + c.len)), emit: (s, o) => clips.forEach((c, i) => c.emit(s + i * whole(stagger, "sequence() stagger"), o)) });+/** start a clip n frames late */+export const delay = (n: number, ...clips: Clip[]): Clip => chain(wait(n), all(...clips));+/** play a clip n times back to back; pass a function of the pass index to vary each pass */+export const loop = (n: number, clip: Clip | ((i: number) => Clip)): Clip => chain(...Array.from({ length: whole(n, "loop() count") }, (_, i) => (typeof clip === "function" ? clip(i) : clip)));++export type TimelineOpts = { labels?: Record<string, number>; words?: { text: string; frame: number }[]; beat?: number };+export type Issue = { track?: string; frame: number; msg: string };++/** a seekable timeline at `fps`; labels and spoken-word cues may be passed in from narration timing */+export const timeline = (fps: number, opts: TimelineOpts = {}) => {+ const labels: Record<string, number> = { ...(opts.labels ?? {}) };+ const placed: { at: number; src: string; tweens: Tween[] }[] = [];+ let compiled: Map<string, (Tween & { from: Value })[]> | null = null;++ const resolve = (w: When): number => {+ if (typeof w === "number") return w;+ if (typeof w === "string") { if (!(w in labels)) throw new Error(`timeline: no label '${w}' (have: ${Object.keys(labels).join(", ") || "none"})`); return labels[w]; }+ if ("label" in w) return resolve(w.label) + (w.offset ?? 0);+ const hits = (opts.words ?? []).filter((x) => x.text.toLowerCase().replace(/[^\p{L}\p{N}']/gu, "") === w.word.toLowerCase());+ const hit = hits[w.nth ?? 0];+ if (!hit) throw new Error(`timeline: the word '${w.word}'${w.nth ? ` (#${w.nth})` : ""} is not in the narration timing`);+ return hit.frame + (w.offset ?? 0);+ };++ const compile = () => {+ if (compiled) return compiled;+ const by = new Map<string, Tween[]>();+ for (const p of placed) for (const t of p.tweens) { if (!by.has(t.track)) by.set(t.track, []); by.get(t.track)!.push(t); }+ compiled = new Map();+ for (const [track, list] of by) {+ // stable sort: same start keeps authored order, so a set() then a to() at one frame reads right+ const ts = list.map((t, i) => ({ t, i })).sort((a, b) => a.t.start - b.t.start || a.i - b.i).map((x) => x.t);+ const out: (Tween & { from: Value })[] = [];+ for (const t of ts) {+ let from = t.from;+ if (from === undefined) {+ if (!out.length) throw new Error(`timeline: track '${track}' moves at frame ${t.start} with no starting value: set() it first or use fromTo()`);+ from = evalTrack(out, t.start);+ }+ out.push({ ...t, from });+ }+ compiled.set(track, out);+ }+ return compiled;+ };++ // the track's value at frame f: the latest tween that has started wins; before any, the first value+ const evalTrack = (ts: (Tween & { from: Value })[], f: number): Value => {+ if (f < ts[0].start) return ts[0].from;+ let k = 0;+ for (let i = 0; i < ts.length; i++) if (ts[i].start <= f) k = i;+ const t = ts[k];+ if (f >= t.end) return t.to;+ return mix(t.from, t.to, t.ease((f - t.start) / (t.end - t.start)));+ };++ const tl = {+ fps,+ labels,+ /** name a cue frame so clips can be placed on it */+ label(name: string, frame: number) { labels[name] = frame; return tl; },+ /** frame of a label, a word cue or a number */+ frame: resolve,+ /** place clips (played together) at an absolute frame, label or spoken word */+ at(w: When, ...clips: Clip[]) {+ const at = resolve(w), tweens: Tween[] = [];+ all(...clips).emit(at, tweens);+ placed.push({ at, src: typeof w === "object" ? JSON.stringify(w) : String(w), tweens });+ compiled = null;+ return tl;+ },+ /** last frame any tween reaches */+ get end() { return Math.max(0, ...placed.flatMap((p) => p.tweens.map((t) => t.end))); },+ tracks: () => [...compile().keys()],+ /** every compiled tween, in time order per track (for tests and debugging) */+ tweens: (track?: string) => (track ? compile().get(track) ?? [] : [...compile().values()].flat()),+ /** a track's value at frame f */+ value(track: string, f: number): Value {+ const ts = compile().get(track);+ if (!ts) throw new Error(`timeline: no track '${track}'`);+ return evalTrack(ts, f);+ },+ num: (track: string, f: number) => { const v = tl.value(track, f); if (typeof v !== "number") throw new Error(`timeline: track '${track}' is not a number`); return v; },+ vec: (track: string, f: number) => { const v = tl.value(track, f); if (!Array.isArray(v)) throw new Error(`timeline: track '${track}' is not a vector`); return v; },+ color: (track: string, f: number) => { const v = tl.value(track, f); if (typeof v !== "string") throw new Error(`timeline: track '${track}' is not a colour`); return v; },+ /** every track's value at frame f */+ sample(f: number): Record<string, Value> { const o: Record<string, Value> = {}; for (const [k, ts] of compile()) o[k] = evalTrack(ts, f); return o; },+ /** tweens fighting over one track, and cues (tl.at placements) off the beat grid */+ check(grid: { beat?: number; subdiv?: number } = {}): Issue[] {+ const issues: Issue[] = [];+ for (const [track, ts] of compile()) {+ for (let i = 0; i < ts.length; i++) for (let j = i + 1; j < ts.length; j++) {+ const a = ts[i], b = ts[j];+ if (b.start < a.end && a.end > a.start && b.end > b.start) issues.push({ track, frame: b.start, msg: `track '${track}': ${b.src} ${b.start}-${b.end} starts while ${a.src} ${a.start}-${a.end} is still moving (they fight; the later one wins)` });+ }+ }+ const beat = grid.beat ?? opts.beat;+ if (beat) {+ const step = beat / (grid.subdiv ?? 1);+ for (const p of placed) if (Math.abs(p.at / step - Math.round(p.at / step)) > 1e-9) issues.push({ frame: p.at, msg: `cue ${p.src} at frame ${p.at} is off the beat grid (every ${step} frames)` });+ }+ return issues;+ },+ };+ return tl;+};+export type Timeline = ReturnType<typeof timeline>;diff --git a/skills/anidoodle/engine/test/threeCamera.test.ts b/skills/anidoodle/engine/test/threeCamera.test.tsnew file mode 100644index 0000000..3c16223--- /dev/null+++ b/skills/anidoodle/engine/test/threeCamera.test.ts@@ -0,0 +1,85 @@+// THREE CAMERA TESTS. src/three-core/camera.ts: named moves are pure, a dolly runs at constant speed+// by arc length, a match cut keeps screen size across a lens change, handheld repeats for a seed+// and fitTo frames what it is given.+// node tools/test.mjs threeCamera+import * as THREE from "three";+import { crane, dolly, dutch, fitTo, handheld, hold, look, matchCut, matchDistance, matchLens, orbit, pan, path, place, pullBack, pushIn, rackFocus, screenPx, screenSize, tilt, truck, whipPan, withMods, worldForPx, type CamState, type Move } from "../src/three-core/camera";+import { ease } from "../src/three-core/time";++export const name = "threeCamera";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const env = { W: 1920, H: 1080 };+ const near = (a: number, b: number, eps = 1e-6) => Math.abs(a - b) <= eps;+ const dist = (a: number[], b: number[]) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);+ const base = look([0, 1, 10], [0, 0, 0], 35);++ // 1. purity: every move, shuffled frames vs sequential+ const curve = path([[-6, 1, 8], [-2, 2, 5], [0, 1.5, 4.5], [4, 1, 6], [6, 3, 9]]);+ const moves: [string, Move][] = [+ ["pushIn", pushIn(base, 0.4, 0, 48)], ["pullBack", pullBack(base, 0.5, 0, 48)], ["dolly", dolly(curve, 0, 48, { target: [0, 0, 0] })],+ ["orbit", orbit([0, 0, 0], -30, 60, 8, 2, 0, 48)], ["crane", crane(base, 3, 0, 48)], ["truck", truck(base, 2, 0, 48)], ["pan", pan(base, 20, 0, 48)], ["tilt", tilt(base, 10, 0, 48)],+ ["whipPan", whipPan(base, look([0, 1, 10], [8, 0, 4]), 0, 12)], ["handheld", withMods(hold(base), handheld(3, 1), dutch((f) => f * 0.1))],+ ];+ const frames = Array.from({ length: 60 }, (_, i) => i - 5);+ let s = 99; const shuffled = [...frames].sort(() => ((s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff) - 0.5);+ const impure = moves.filter(([, m]) => { const a = frames.map((f) => JSON.stringify(m(f))), got = new Map(shuffled.map((f) => [f, JSON.stringify(m(f))])); return !frames.every((f, i) => got.get(f) === a[i]); }).map(([n]) => n);+ ok(impure.length === 0, `10 moves give the same state in shuffled order as in sequence${impure.length ? ` (impure: ${impure.join(", ")})` : ""}`);+ ok(moves.filter(([n]) => n !== "handheld").every(([, m]) => JSON.stringify(m(-5)) === JSON.stringify(m(0)) && JSON.stringify(m(48)) === JSON.stringify(m(200))), "every keyed move holds before it starts and after it ends (handheld is meant to keep breathing)");++ // 2. push / pull in log distance+ const flat = look([0, 0, 10], [0, 0, 0], 35), pi = pushIn(flat, 0.75, 0, 48, ease.linear);+ ok(near(dist(pi(48).pos, flat.target), 10 * 0.25) && near(dist(pi(24).pos, flat.target), 10 * 0.5), "pushIn 75% ends at a quarter of the distance and is at half way through (log-distance easing)");+ ok(near(dist(pullBack(flat, 1, 0, 10)(10).pos, flat.target), 20), "pullBack 100% doubles the distance");++ // 3. dolly runs at constant speed by arc length+ const lin = dolly(curve, 0, 100, { ease: ease.linear }), steps: number[] = [];+ for (let f = 0; f < 100; f++) steps.push(dist(lin(f).pos, lin(f + 1).pos));+ const mean = steps.reduce((a, b) => a + b, 0) / steps.length, spread = Math.max(...steps.map((x) => Math.abs(x / mean - 1)));+ ok(spread < 0.02, `a linear dolly moves the same distance every frame within 2% (worst ${(spread * 100).toFixed(2)}%) though its control points bunch up`);+ ok(dist(lin(0).pos, [-6, 1, 8]) < 1e-6 && dist(lin(100).pos, [6, 3, 9]) < 1e-6, "the dolly starts and ends on its path's ends");++ // 4. orbit keeps its radius and height+ const ob = orbit([1, 0, 1], 0, 90, 5, 2, 0, 24), mid = ob(12);+ ok(near(Math.hypot(mid.pos[0] - 1, mid.pos[2] - 1), 5) && near(mid.pos[1], 2) && near(ob(24).pos[0], 6) && near(ob(24).pos[2], 1), "orbit circles at radius 5 and height 2, ending at 90 degrees on +x");++ // 5. match cut: the subject keeps its screen size across a lens change+ const cam = new THREE.PerspectiveCamera(35, env.W / env.H, 0.1, 100), sub = 0.4;+ const dA = matchCut(sub, 120, 35, env);+ ok(near(screenSize({ fov: 35 }, sub, dA, env), 120), `matchCut puts a 0.4-unit subject at exactly 120 px at 35 deg (${dA.toFixed(3)} units out)`);+ const dB = matchDistance(dA, 35, 18);+ ok(near(screenSize({ fov: 18 }, sub, dB, env), 120) && dB > dA, "matchDistance keeps it at 120 px on an 18 deg lens, from farther away");+ const sA = look([0, 0, 4], [0, 0, 0], 50), sB = matchLens(sA, 20);+ const edge = (st: CamState) => { place(cam, st, env); return screenPx(cam, [0.5, 0, 0], env)[0] - screenPx(cam, [0, 0, 0], env)[0]; };+ ok(near(edge(sA), edge(sB), 1e-6), `matchLens keeps the subject's projected width when the fov changes 50 -> 20 (${edge(sA).toFixed(2)} px both)`);+ ok(near(worldForPx({ fov: 35 }, 2, 12, env) * 0 + screenSize({ fov: 35 }, worldForPx({ fov: 35 }, 2, 12, env), 12, env), 2), "worldForPx sizes a thread to exactly 2 px at its distance (lesson 27)");++ // 6. place + screenPx: the target lands on the frame's centre, roll turns it about the view axis+ place(cam, base, env); const c = screenPx(cam, base.target, env);+ ok(near(c[0], 960, 1e-6) && near(c[1], 540, 1e-6), "the target projects to the centre of a 1920x1080 frame");+ place(cam, { ...base, roll: 90 }, env); const r = screenPx(cam, [1, 0, 0], env);+ ok(near(r[0], 960, 1e-3) && Math.abs(r[1] - 540) > 50, "a 90 deg roll turns a point on the right to straight above or below centre");++ // 7. handheld: seeded and repeatable, different seeds differ, smooth (no per-frame jumps)+ const h1 = withMods(hold(base), handheld(7, 1)), h1b = withMods(hold(base), handheld(7, 1)), h2 = withMods(hold(base), handheld(8, 1));+ ok(frames.every((f) => JSON.stringify(h1(f)) === JSON.stringify(h1b(f))), "the same seed gives the same shake on every frame");+ ok(frames.some((f) => JSON.stringify(h1(f)) !== JSON.stringify(h2(f))), "another seed gives another shake");+ const jumps = frames.slice(1).map((f) => dist(h1(f).target, h1(f - 1).target)), wander = Math.max(...frames.map((f) => dist(h1(f).target, base.target)));+ ok(Math.max(...jumps) < wander * 0.25 && wander > 0.01 && wander < 0.3, `handheld wanders ${wander.toFixed(3)} units and never jumps more than a quarter of that in one frame (smooth, not static)`);++ // 8. whip pan holds posed frames on both ends+ const to = look([0, 1, 10], [8, 0, 4]), wp = whipPan(base, to, 0, 12, { hold: 2 });+ ok(JSON.stringify(wp(0)) === JSON.stringify(wp(2)) && JSON.stringify(wp(10)) === JSON.stringify(wp(12)) && JSON.stringify(wp(5)) !== JSON.stringify(wp(2)), "whipPan holds frames 0-2 and 10-12 still and moves between");+ ok(dist(wp(12).target, to.target) < 1e-6, "and lands exactly on its destination aim");+ let threw = false; try { whipPan(base, to, 0, 5, { hold: 2 }); } catch { threw = true; } ok(threw, "a whip too short for its held frames is refused");++ // 9. fitTo frames a box: every corner inside, the furthest one at the padding+ const box = new THREE.Box3(new THREE.Vector3(-2, 0, -1), new THREE.Vector3(3, 1.5, 1.2)), fit = fitTo(box, { padding: 1.2, aspect: env.W / env.H });+ place(cam, fit, env);+ const ndc = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => new THREE.Vector3(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z).project(cam)), reach = Math.max(...ndc.map((n) => Math.max(Math.abs(n.x), Math.abs(n.y))));+ ok(near(reach, 1 / 1.2, 1e-4), `fitTo puts the box's furthest corner exactly at the 1.2 padding (reach ${reach.toFixed(5)} of the frame)`);+ const g = new THREE.Mesh(new THREE.BoxGeometry(1, 4, 1)); g.position.set(5, 2, 0); g.updateMatrixWorld(true);+ const fo = fitTo(g); ok(near(fo.target[0], 5) && near(fo.target[1], 2), "fitTo takes an object and aims at its bounds' centre");++ // 10. rack focus eases in dioptres+ ok(near(rackFocus(0, 0, 10, 2, 8), 2) && near(rackFocus(10, 0, 10, 2, 8), 8) && near(rackFocus(5, 0, 10, 2, 8, ease.linear), 1 / ((1 / 2 + 1 / 8) / 2)), "rackFocus lands on both distances and is linear in 1/d (3.2 at the midpoint, not 5)");+};diff --git a/skills/anidoodle/engine/test/threeMograph.test.ts b/skills/anidoodle/engine/test/threeMograph.test.tsnew file mode 100644index 0000000..bf4d7a0--- /dev/null+++ b/skills/anidoodle/engine/test/threeMograph.test.ts@@ -0,0 +1,99 @@+// THREE MOGRAPH TESTS. src/three-core/mograph.ts: every verb writes a "before" state before it+// starts and the exact rest state after it ends, frames agree in any order, and morph resamples+// both shapes to equal counts by arc length.+// node tools/test.mjs threeMograph+import * as THREE from "three";+import { assemble, dropIn, explode, extrudeIn, fadeIn, fadeOut, grid, growFrom, indicate, kinetic, lagged, morph, moveAlongPath, popIn, popOut, resample, riseFromFloor, wave, wiggle, writeOn, writePoints, writeTube } from "../src/three-core/mograph";++export const name = "threeMograph";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;+ const mk = (x = 0, y = 0, z = 0) => { const m = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: "#ff0000", emissive: "#000000" })); m.position.set(x, y, z); m.rotation.set(0.1, 0.2, 0.3); m.scale.set(1, 2, 1); return m; };+ const pose = (o: THREE.Object3D) => JSON.stringify([o.position.toArray(), o.quaternion.toArray(), o.scale.toArray(), o.visible, ...((o as THREE.Mesh).material ? [((o as THREE.Mesh).material as THREE.MeshStandardMaterial).opacity, ((o as THREE.Mesh).material as THREE.MeshStandardMaterial).emissive.getHex()] : [])]);+ const restOf = (o: THREE.Object3D) => { const c = mk(); c.position.copy(o.position); c.quaternion.copy(o.quaternion); c.scale.copy(o.scale); return pose(c); };++ // 1. before / after states, verb by verb+ const verbs: [string, (o: THREE.Object3D, f: number) => void, (o: THREE.Object3D) => boolean][] = [+ ["popIn", (o, f) => popIn(o, f, 10, 12), (o) => !o.visible],+ ["dropIn", (o, f) => dropIn(o, f, 10, 18), (o) => !o.visible],+ ["riseFromFloor", (o, f) => riseFromFloor(o, f, 10, 14, 1), (o) => !o.visible && near(o.position.y, 2 - 1)],+ ["growFrom", (o, f) => growFrom(o, f, 10, 12, [0, 0, 0]), (o) => !o.visible && o.position.length() === 0],+ ["fadeIn", (o, f) => fadeIn(o, f, 10, 12), (o) => !o.visible && ((o as THREE.Mesh).material as THREE.Material).opacity === 0],+ ["extrudeIn", (o, f) => extrudeIn(o, f, 10, 12), (o) => !o.visible],+ ["indicate", (o, f) => indicate(o, f, 10, 12), (o) => o.visible],+ ["wiggle", (o, f) => wiggle(o, f, 10, 12, { seed: 4 }), (o) => o.visible],+ ];+ for (const [n, verb, before] of verbs) {+ const o = mk(1, 2, 3), want = restOf(o);+ verb(o, 40); const after = pose(o);+ verb(o, 0); const isBefore = before(o);+ verb(o, 16); verb(o, 40);+ ok(after === want && pose(o) === want && isBefore, `${n}: hidden-or-rest before it starts, exactly the rest pose after it ends, even after a mid-way frame`);+ }+ const outO = mk(); popOut(outO, 40, 10); const outB = mk(); fadeOut(outB, 40, 10);+ ok(!outO.visible && !outB.visible && ((outB.material as THREE.Material).opacity === 0), "popOut and fadeOut end hidden");+ const fm = mk(); fadeIn(fm, 15, 10, 10); ok((fm.material as THREE.Material).transparent && fm.visible, "fadeIn mid-way is transparent"); fadeIn(fm, 99, 10, 10); ok(!(fm.material as THREE.Material).transparent, "and opaque again once fully in (no sorting artefacts left on)");+ const multi = new THREE.Mesh(new THREE.BoxGeometry(), [new THREE.MeshBasicMaterial(), new THREE.MeshBasicMaterial({ opacity: 0.5, transparent: true })]);+ fadeIn(multi, 15, 10, 10, (t) => t); const ms = multi.material as THREE.Material[];+ ok(near(ms[0].opacity, 0.5) && near(ms[1].opacity, 0.25), "fadeIn scales every material in an array by its own rest opacity");+ const pop = mk(); popIn(pop, 18, 10, 12); ok(pop.scale.x > 1, "popIn overshoots on the way");+ const ind = mk(); indicate(ind, 16, 10, 12); ok((ind.material as THREE.MeshStandardMaterial).emissive.r > 0.5 && ind.scale.x > 1.1, "indicate flashes and swells at its peak");++ // 2. purity: shuffled frames equal sequential frames, on one shared object+ const frames = Array.from({ length: 50 }, (_, i) => i - 2);+ let s = 7; const shuffled = [...frames].sort(() => ((s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff) - 0.5);+ const impure = verbs.filter(([, verb]) => { const o = mk(1, 2, 3), seq = frames.map((f) => (verb(o, f), pose(o))), got = new Map(shuffled.map((f) => [f, (verb(o, f), pose(o))])); return !frames.every((f, i) => got.get(f) === seq[i]); }).map(([n]) => n);+ // RED: a verb that nudges instead of setting (position += ...) must be caught by the same harness+ const leaky = (o: THREE.Object3D, f: number) => { o.position.x += f > 10 ? 0.1 : 0; };+ const lo = mk(), lseq = frames.map((f) => (leaky(lo, f), pose(lo))), lgot = new Map(shuffled.map((f) => [f, (leaky(lo, f), pose(lo))]));+ ok(!frames.every((f, i) => lgot.get(f) === lseq[i]), "RED: an accumulating verb (position += 0.1) fails the shuffled-order check");+ ok(impure.length === 0, `8 verbs on one object give the same pose in shuffled order as in sequence${impure.length ? ` (impure: ${impure.join(", ")})` : ""}`);++ // 3. groups: explode / assemble, lagged, grid, wave, kinetic+ const g = new THREE.Group(); for (let x = -1; x <= 1; x++) for (let y = -1; y <= 1; y++) g.add(mk(x, y, 0));+ const restG = g.children.map(restOf);+ explode(g, 0, 10, 12, { seed: 3 }); const pre = g.children.map(pose);+ explode(g, 30, 10, 12, { seed: 3 }); const blown = g.children.map(pose);+ ok(pre.every((p, i) => p === restG[i]) && blown.every((p, i) => p !== restG[i]), "explode: assembled before, every shard moved after");+ explode(g, 30, 10, 12, { seed: 3 }); ok(g.children.map(pose).every((p, i) => p === blown[i]), "explode is seeded: the same shards land in the same places");+ explode(g, 30, 10, 12, { seed: 4 }); ok(g.children.map(pose).some((p, i) => p !== blown[i]), "another seed scatters differently");+ assemble(g, 0, 10, 12, { seed: 3 }); ok(g.children.map(pose).every((p, i) => p === blown[i]), "assemble starts from exactly the exploded pose of the same seed");+ assemble(g, 22, 10, 12, { seed: 3 }); ok(g.children.map(pose).every((p, i) => p === restG[i]), "and ends exactly at rest");+ const starts: number[] = []; lagged(g, 0, 5, 3, (_c, _f, at) => starts.push(at)); ok(starts.join() === "5,8,11,14,17,20,23,26,29", "lagged starts each child 3 frames after the last");+ const gs: number[] = []; grid(g, 0, 0, 4, (_c, _f, at) => gs.push(at));+ ok(gs[4] === 0 && [1, 3, 5, 7].every((i) => gs[i] === 4) && [0, 2, 6, 8].every((i) => gs[i] === 8), "grid from the centre: middle first, edges one ring later, corners last");+ const ge: number[] = []; grid(g, 0, 0, 4, (_c, _f, at) => ge.push(at), { from: "edge" }); ok(ge[4] === 8 && ge[0] === 0, "grid from the edge reverses the rings");+ wave(g, 0, 10, 24); const w0 = g.children.map(pose); wave(g, 99, 10, 24); ok(w0.every((p, i) => p === restG[i]) && g.children.map(pose).every((p, i) => p === restG[i]), "wave leaves every child at rest before and after");+ wave(g, 22, 10, 24); ok(g.children.some((c) => c.position.y > (c.userData.anidoodleRest.position.y as number) + 0.1), "and lifts some mid-way");+ const word = new THREE.Group(); for (let i = 0; i < 4; i++) word.add(mk(i * 0.6, 0, 0));+ const wr = word.children.map(restOf);+ kinetic(word, 0, 2, 3); const k0 = word.children.map((c) => c.visible);+ kinetic(word, 50, 2, 3); ok(k0.every((v) => !v) && word.children.map(pose).every((p, i) => p === wr[i]), "kinetic: letters hidden before, all at rest after");+ kinetic(word, 9, 2, 3); ok(word.children.map((c) => c.visible).join() === "true,true,true,false", "and each letter enters 3 frames after the one before");++ // 4. paths: writeOn draws whole tube segments, moveAlongPath runs at constant speed+ const curve = new THREE.CatmullRomCurve3([new THREE.Vector3(0, 0, 0), new THREE.Vector3(1, 2, 0), new THREE.Vector3(1.2, 2.1, 0), new THREE.Vector3(5, 0, 1)]);+ const tube = new THREE.Mesh(new THREE.TubeGeometry(curve, 40, 0.05, 8));+ writeOn(tube, 0, 10, 20); const r0 = tube.geometry.drawRange.count, v0 = tube.visible;+ writeOn(tube, 20, 10, 20, (t) => t); const rMid = tube.geometry.drawRange.count;+ writeOn(tube, 40, 10, 20);+ ok(r0 === 0 && !v0 && rMid === 20 * 8 * 6 && tube.geometry.drawRange.count === tube.geometry.index!.count, `writeOn: nothing before, half the tube's segments at the midpoint (${rMid} indices), the whole index after`);+ const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(curve.getSpacedPoints(99))); writeOn(line, 15, 10, 10, (t) => t); ok(line.geometry.drawRange.count === 50, "writeOn on a Line draws half its vertices at half way");+ const bead = new THREE.Object3D(), gaps: number[] = []; let last = new THREE.Vector3();+ for (let i = 0; i <= 50; i++) { moveAlongPath(bead, curve, i / 50, true); if (i) gaps.push(bead.position.distanceTo(last)); last = bead.position.clone(); }+ const mean = gaps.reduce((a, b) => a + b) / gaps.length; ok(Math.max(...gaps.map((x) => Math.abs(x / mean - 1))) < 0.03, "moveAlongPath covers equal distance per equal step in t (within 3%)");+ moveAlongPath(bead, curve, 0.5, true); ok(new THREE.Vector3(0, 0, 1).applyQuaternion(bead.quaternion).angleTo(curve.getTangentAt(0.5)) < 1e-6, "orient turns +z along the travel");++ // 5. morph: equal counts by arc length+ const sq: [number, number, number][] = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], tri: [number, number, number][] = [[0, 0, 0], [2, 0, 0], [1, 2, 0], [0.5, 1, 0], [0.2, 0.4, 0], [0.1, 0.2, 0], [0.05, 0.1, 0]];+ const rs = resample(sq, 8, true), steps = rs.map((p, i) => { const q = rs[(i + 1) % 8]; return Math.hypot(q[0] - p[0], q[1] - p[1]); });+ ok(rs.length === 8 && steps.every((d) => near(d, 0.5, 1e-9)), "resample spaces 8 points 0.5 apart round a unit square (closed)");+ const m0 = morph(sq, tri, 0, { closed: true }), m1 = morph(sq, tri, 1, { closed: true }), mh = morph(sq, tri, 0.5, { closed: true });+ ok(m0.length === 7 && m1.length === 7 && mh.length === 7, "morph resamples both shapes to the larger count (7)");+ ok(JSON.stringify(m0) === JSON.stringify(resample(sq, 7, true)) && JSON.stringify(m1) === JSON.stringify(resample(tri, 7, true)), "and is exactly shape A at 0 and shape B at 1");+ ok(near(mh[0][0], (m0[0][0] + m1[0][0]) / 2), "with a straight mix between");+ const lg = new THREE.BufferGeometry().setFromPoints(Array.from({ length: 7 }, () => new THREE.Vector3())); writePoints(lg, mh); ok(near(lg.attributes.position.getX(1), mh[1][0], 1e-6), "writePoints puts a morph into a geometry");+ let threw = false; try { writePoints(lg, m0.slice(0, 3)); } catch { threw = true; } ok(threw, "and refuses a point count the buffer was not built for");+ const tg = new THREE.TubeGeometry(curve, 20, 0.1, 6), size = tg.attributes.position.count; writeTube(tg, [[0, 0, 0], [0, 3, 0], [3, 3, 0]]);+ ok(tg.attributes.position.count === size && Math.abs(tg.attributes.position.getY(tg.attributes.position.count - 1) - 3) < 0.2, "writeTube re-lays a tube along new points in the same buffers");+};diff --git a/skills/anidoodle/engine/test/threeTimeline.test.ts b/skills/anidoodle/engine/test/threeTimeline.test.tsnew file mode 100644index 0000000..63d0094--- /dev/null+++ b/skills/anidoodle/engine/test/threeTimeline.test.ts@@ -0,0 +1,63 @@+// THREE TIMELINE TESTS. src/three-core/timeline.ts compiles director-style combinators to flat+// tweens and reads any frame purely. Timing must be exact to the frame, frames must agree in any+// order, and check() must catch two tweens fighting (a red fixture beside the green one).+// node tools/test.mjs threeTimeline+import { all, chain, delay, fromTo, loop, mix, sequence, set, timeline, to, wait } from "../src/three-core/timeline";+import { ease } from "../src/three-core/time";++export const name = "threeTimeline";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;++ // 1. easing ends: every curve starts at 0 and lands on 1 exactly+ const bad = Object.entries(ease).filter(([, e]) => !near(e(0), 0, 1e-12) || !near(e(1), 1, 1e-12)).map(([k]) => k);+ ok(bad.length === 0, `every ease is 0 at 0 and 1 at 1 (${Object.keys(ease).length} curves${bad.length ? `, off: ${bad.join(", ")}` : ""})`);+ ok(ease.outBack(0.7) > 1, "outBack overshoots before it lands");++ // 2. chain / all / sequence / delay / loop land on exact frames+ const tl = timeline(24, { labels: { drop: 48 }, words: [{ text: "Three,", frame: 96 }, { text: "three", frame: 130 }] });+ tl.at(0, set("a", 0), set("b", 0), set("c", 0), set("d", 0), set("e", 0));+ tl.at(10, chain(to("a", 1, 12, ease.linear), wait(6), to("a", 2, 12, ease.linear)));+ tl.at(10, all(to("b", 5, 4, ease.linear), to("c", 5, 20, ease.linear)));+ tl.at(10, sequence(3, to("d", 1, 6, ease.linear), fromTo("e", 10, 20, 6, ease.linear)));+ ok(tl.num("a", 22) === 1 && tl.num("a", 28) === 1 && near(tl.num("a", 34), 1.5) && tl.num("a", 40) === 2, "chain: first tween ends at 22, holds through the wait, second ends at 40");+ ok(tl.num("b", 14) === 5 && near(tl.num("c", 14), 1) && tl.num("c", 30) === 5, "all: both start at 10, each ends at its own length");+ ok(tl.num("e", 12) === 0 && tl.num("e", 13) === 10 && tl.num("e", 19) === 20, "sequence: the second clip starts exactly 3 frames later (fromTo jumps to its start)");+ ok(sequence(4, wait(10), wait(10), wait(3)).len === 14 && chain(wait(5), all(wait(3), wait(7))).len === 12 && delay(5, wait(3)).len === 8, "lengths: sequence = last start + its length, chain = sum, all = max, delay adds");+ const tl2 = timeline(24);+ tl2.at(0, set("x", 0), loop(3, (i) => chain(to("x", i + 1, 4, ease.linear), wait(2))));+ ok(tl2.num("x", 4) === 1 && tl2.num("x", 10) === 2 && tl2.num("x", 16) === 3 && tl2.end === 16, "loop: three passes of 6 frames, each pass may vary");++ // 3. holds before the first key and after the last+ ok(tl.num("a", -50) === 0 && tl.num("a", 9999) === 2, "a track holds its first value before and its last after");+ const lone = timeline(24); lone.at(20, fromTo("y", 3, 4, 10));+ ok(lone.num("y", 0) === 3 && lone.num("y", 100) === 4, "a fromTo alone holds its `from` before it starts");++ // 4. labels and spoken-word cues+ tl.at("drop", fromTo("f", 0, 1, 12, ease.linear)).at({ word: "three" }, fromTo("g", 0, 1, 1)).at({ word: "three", nth: 1, offset: 2 }, fromTo("h", 0, 1, 1));+ ok(tl.num("f", 54) === 0.5 && tl.frame("drop") === 48, "a label places a clip on its frame");+ ok(tl.frame({ word: "three" }) === 96 && tl.num("g", 95) === 0 && tl.num("g", 97) === 1 && tl.frame({ word: "three", nth: 1, offset: 2 }) === 132, "word cues match case- and punctuation-free, by occurrence, with an offset");+ let threw = ""; try { tl.at("nope", wait(1)); } catch (e) { threw = String(e); } ok(threw.includes("no label 'nope'"), "an unknown label is refused by name");+ let threw2 = ""; try { const t = timeline(24); t.at(4, to("z", 1, 4)); t.value("z", 5); } catch (e) { threw2 = String(e); } ok(threw2.includes("no starting value"), "a to() on a track that was never set is refused, not started from a silent 0");++ // 5. values: vectors and colours (linear light)+ const tv = timeline(24); tv.at(0, set("p", [0, 0, 0]), set("col", "#ff0000")).at(0, to("p", [2, 4, -6], 10, ease.linear), to("col", "#00ff00", 10, ease.linear));+ const pv = tv.vec("p", 5); ok(pv[0] === 1 && pv[1] === 2 && pv[2] === -3, "vectors mix per axis");+ ok(tv.color("col", 5) === "#bcbc00" && mix("#ff0000", "#00ff00", 0.5) === "#bcbc00", "red to green passes through a bright yellow in linear light (#bcbc00, not the muddy #808000)");+ ok(tv.color("col", 0) === "#ff0000" && tv.color("col", 10) === "#00ff00", "colour ends are exact");++ // 6. purity: random order equals sequence+ const frames = Array.from({ length: 160 }, (_, i) => i - 10), seq = frames.map((f) => JSON.stringify(tl.sample(f)));+ let s = 12345; const shuffled = [...frames].sort(() => ((s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff) - 0.5);+ const byFrame = new Map(shuffled.map((f) => [f, JSON.stringify(tl.sample(f))]));+ ok(frames.every((f, i) => byFrame.get(f) === seq[i]), "160 frames sampled in a shuffled order equal the frames sampled in sequence");++ // 7. check(): green, then red fixtures+ ok(tl.check({ beat: 1 }).length === 0, "a timeline with no fights and integer cues has nothing to report");+ const red = timeline(24); red.at(0, set("x", 0)).at(0, to("x", 1, 12)).at(6, to("x", 2, 12));+ const fights = red.check(); ok(fights.length === 1 && fights[0].track === "x" && fights[0].frame === 6, `RED: two tweens writing 'x' at once are named (${fights[0]?.msg ?? "none"})`);+ ok(red.num("x", 18) === 2, "and the later-starting tween is the one that wins");+ const grid = timeline(24, { beat: 12 }); grid.at(0, set("x", 0)).at(24, to("x", 1, 6)).at(30, to("x", 2, 6));+ const off = grid.check(); ok(off.length === 1 && off[0].frame === 30, "RED: a cue at frame 30 on a 12-frame beat is off the grid");+ ok(grid.check({ subdiv: 2 }).length === 0, "and allowed when the grid is split into half beats");+};diff --git a/skills/anidoodle/engine/tools/adapters/html-player.mjs b/skills/anidoodle/engine/tools/adapters/html-player.mjsindex 6a21961..c421f27 100644--- a/skills/anidoodle/engine/tools/adapters/html-player.mjs+++ b/skills/anidoodle/engine/tools/adapters/html-player.mjs@@ -10,6 +10,7 @@import { readFileSync, statSync } from "node:fs";import { resolve } from "node:path";import { pathToFileURL } from "node:url";+import { glArgs } from "./playwright.mjs";import { buildPage } from "../build-page.mjs";import { detect } from "../detect.mjs";import { loadBakes, saveBakes } from "../bake-cache.mjs";@@ -52,7 +53,7 @@ export const open = async (film, opts = {}) => {const built = await buildPage({ entry: `src/hosts/page-${film}.ts`, out, title: film });const html = readFileSync(out, "utf8");- const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling"] });+ const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling", ...glArgs(out)] });const context = await browser.newContext({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 1 });const pages = [], bv = browser.version();for (let i = 0; i < workers; i++) {diff --git a/skills/anidoodle/engine/tools/emit.mjs b/skills/anidoodle/engine/tools/emit.mjsindex 8cdc9a0..3019e51 100644--- a/skills/anidoodle/engine/tools/emit.mjs+++ b/skills/anidoodle/engine/tools/emit.mjs@@ -22,6 +22,7 @@ import { pathToFileURL } from "node:url";import { buildPage } from "./build-page.mjs";import { requireFilm } from "./names.mjs";import { pageChecks, probe } from "./adapters/html-player.mjs";+import { glArgs } from "./adapters/playwright.mjs";const VAL = new Set(["out", "frames", "scale"]);const pos = [], opt = {};@@ -55,7 +56,7 @@ pageChecks(html, ship.assets).forEach((c) => say(c.ok, c.label, c.detail));say(statSync(out).size === ship.bytes, "the file on disk is the file that was built", `${statSync(out).size} bytes`);// ---------------------------------------------------------------- 2 & 3. run it-const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling"] });+const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling", ...glArgs(out)] });const context = await browser.newContext({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 1 });const openPage = async (file) => {const page = await context.newPage(), errors = [], reached = [];diff --git a/skills/anidoodle/engine/tools/gate.mjs b/skills/anidoodle/engine/tools/gate.mjsindex d8f1149..29e0c9b 100644--- a/skills/anidoodle/engine/tools/gate.mjs+++ b/skills/anidoodle/engine/tools/gate.mjs@@ -64,7 +64,7 @@ const walk = (dir, out = []) => { for (const e of execFileSync("find", [dir, "-nconst contractScan = () => {head(2, "CONTRACT the art core cannot reach a clock, the network or a file");// the worked example is part of the same tree at build time (tools/overlay.mjs): scan it too- const files = [...walk("src/canvas-core"), ...(existsSync("../example/src/canvas-core") ? walk("../example/src/canvas-core") : []), `src/hosts/page-${film}.ts`].filter((f) => existsSync(f));+ const files = [...walk("src/canvas-core"), ...(existsSync("src/three-core") ? walk("src/three-core") : []), ...(existsSync("../example/src/canvas-core") ? walk("../example/src/canvas-core") : []), `src/hosts/page-${film}.ts`].filter((f) => existsSync(f));const hits = [];for (const f of files) { const src = stripComments(readFileSync(f, "utf8")); FORBIDDEN.forEach(([re, label]) => { const m = src.match(new RegExp(re.source, "g")); if (m) hits.push(`${f}: ${label} x${m.length}`); }); }say(hits.length === 0, `no forbidden call in ${files.length} art-core modules`, hits.length ? hits.slice(0, 6).join(" | ") : "Math.random, Date, performance.now, ctx.filter, network, image/font loads: none");diff --git a/skills/anidoodle/engine/tools/keys-compare.py b/skills/anidoodle/engine/tools/keys-compare.pyindex 978e765..b5725c7 100644--- a/skills/anidoodle/engine/tools/keys-compare.py+++ b/skills/anidoodle/engine/tools/keys-compare.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# Needs numpy (offline research tool, not used by renders): pip install numpy"""Spectral A/B of rendered piano notes vs the CC0 VCSL Steinway B (offline, numpy only).python3 tools/keys-compare.py <VCSL root> <probe dir> (probe dir holds old-<note>_vl<k>.wav / v2-<note>_vl<k>.wav)diff --git a/skills/anidoodle/engine/tools/keys-fit.py b/skills/anidoodle/engine/tools/keys-fit.pyindex c2b7856..4080749 100644--- a/skills/anidoodle/engine/tools/keys-fit.py+++ b/skills/anidoodle/engine/tools/keys-fit.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# Needs numpy (offline research tool, not used by renders): pip install numpy"""Offline "measured physics" fitter for the keys voices (piano, mallets, organ).python3 tools/keys-fit.py <VCSL root> [--json out.json]diff --git a/skills/anidoodle/engine/tools/keys-metrics.py b/skills/anidoodle/engine/tools/keys-metrics.pyindex d4088a2..52b9d56 100644--- a/skills/anidoodle/engine/tools/keys-metrics.py+++ b/skills/anidoodle/engine/tools/keys-metrics.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# Needs numpy (offline research tool, not used by renders): pip install numpy"""Anti-MIDI metrics for the keys phrases (research sec. 9.2): per-band inter-channel correlation(< 0.9 above 500 Hz = real width; ~1 below 120 Hz = mono lows), click detector (sample steps far above thelocal signal), spectral flux in sustains (a static oscillator is ~flat). numpy only.diff --git a/skills/anidoodle/engine/tools/scaffold.mjs b/skills/anidoodle/engine/tools/scaffold.mjsindex 1ce7de2..8f2f0c9 100644--- a/skills/anidoodle/engine/tools/scaffold.mjs+++ b/skills/anidoodle/engine/tools/scaffold.mjs@@ -69,6 +69,8 @@ mkdirSync(target, { recursive: true });cpSync(join(ENGINE, "src"), join(target, "src"), { recursive: true, filter: (f) => !skip.has(f) });cpSync(join(ENGINE, "tools"), join(target, "tools"), { recursive: true });for (const f of ["package.json", "package-lock.json", "tsconfig.json"]) if (existsSync(join(ENGINE, f))) cpSync(join(ENGINE, f), join(target, f));+// three.js for 3D shots: the vendored, hash-pinned build and its types (vendor/three/PROVENANCE.md)+if (existsSync(join(ENGINE, "vendor"))) cpSync(join(ENGINE, "vendor"), join(target, "vendor"), { recursive: true });if (opt.example) {const ex = join(SKILL, "example", "src");diff --git a/skills/anidoodle/references/camera.md b/skills/anidoodle/references/camera.mdindex 0d997ee..7f4b942 100644--- a/skills/anidoodle/references/camera.md+++ b/skills/anidoodle/references/camera.md@@ -1,5 +1,7 @@# The camera: one dolly and one lens, keyed on the frame grid+**Contents:** The move · Depth planes (parallax) · Lens and dolly · Time: speed ramps, slow motion, freeze frames · Shake · Line weight at close range · The two drawing paths+`engine/src/canvas-core/camera.ts` is the camera. A film either draws in world coordinatesinside `begin()`/`end()` (the transform path: dirty boxes stay right because the camera ridesthe `Gfx` transform stack), or asks `toScreen()` where a world point lands and draws there (thediff --git a/skills/anidoodle/references/formats.md b/skills/anidoodle/references/formats.mdindex a619741..6b9c422 100644--- a/skills/anidoodle/references/formats.md+++ b/skills/anidoodle/references/formats.md@@ -1,5 +1,7 @@# Formats: what you are making, and how each one ships+**Contents:** Stills: hero art, spots, covers, cards, diagrams · Motion without a story: loops, stickers, logos, ambient art · Films: the story ones · Delivering+Everything is a `Film`: meta, shots that tile `[0, duration)`, and optionally a score. A stillis a film one frame long, so every tool works on every format. Scaffold the kind you need:diff --git a/skills/anidoodle/references/motion-grammar.md b/skills/anidoodle/references/motion-grammar.mdindex d252743..c0f995c 100644--- a/skills/anidoodle/references/motion-grammar.md+++ b/skills/anidoodle/references/motion-grammar.md@@ -1,5 +1,7 @@# Motion grammar: six ways to get from one picture to the next+**Contents:** 1. Foreground as transition · 2. Persistent actor · 3. Selection to expansion · 4. Registered decomposition · 5. Continuous canvas · 6. Exploded layers · Three ready-made seams · Cuts that carry motion · Dealing a hand · Names people use · Names we refuse · Callouts and the label handoff · Choosing+A film that shows one good thing, then another unrelated good thing, reads as a slideshow howeverwell each is animated. These six mechanisms are ways to make the next picture come OUT of thecurrent one. They are a grammar to compose from, never presets: pick the one the story is alreadydiff --git a/skills/anidoodle/references/music/README.md b/skills/anidoodle/references/music/README.mdindex 13a56d5..ca1f0b5 100644--- a/skills/anidoodle/references/music/README.md+++ b/skills/anidoodle/references/music/README.md@@ -1,5 +1,7 @@# Music: composed as data, performed, measured, then heard once+**Contents:** The pipeline · Recorded instruments: the optional sound pack · Any length, never hard-coded · Styles (21) and moods (21) · Keys and modes (13) · How to write a score · The guards (guards.ts): sad is allowed, formless is not · The 8-second human listen+Every score in anidoodle is written as data and every voice is the engine's own: you write thenotes, the engine performs them. You cannot hear what you make, so every choice is a number, everynumber is measured, and a human hears 8 seconds before anything ships.diff --git a/skills/anidoodle/references/music/compose.md b/skills/anidoodle/references/music/compose.mdindex 145a5b8..d6e6045 100644--- a/skills/anidoodle/references/music/compose.md+++ b/skills/anidoodle/references/music/compose.md@@ -1,5 +1,7 @@# Compose: from a brief to an original score+**Contents:** The workflow · Recorded instruments · The material format · What makes it beautiful (check before you call it done) · What checks what+A style is a **vocabulary**. It gives you:- sound: voices, levels and fx;- groove families;diff --git a/skills/anidoodle/references/music/sound-design.md b/skills/anidoodle/references/music/sound-design.mdindex d2955c0..2ece5e4 100644--- a/skills/anidoodle/references/music/sound-design.md+++ b/skills/anidoodle/references/music/sound-design.md@@ -1,5 +1,7 @@# Sound design: the effects kit, placed by frame, heard over the score+**Contents:** What makes an effect sound designed, not generated · The kit · Placing effects in a film · Sound across a cut (J-cut and L-cut) · Levels and the audibility rule · Taste: when to use effects · The finished mix · Checking the finished film's sound · Tools and checks+Every anidoodle sound effect is **built in code, from nothing**: no samples, no recordings, ever.(The music's acoustic instruments can play recordings from the optional sound pack; effects neverdo.) Every effect is deterministic: the same cue and seed give identical samples.diff --git a/skills/anidoodle/references/music/styles/lofi-electronic.md b/skills/anidoodle/references/music/styles/lofi-electronic.mdindex 3fde11d..2da504d 100644--- a/skills/anidoodle/references/music/styles/lofi-electronic.md+++ b/skills/anidoodle/references/music/styles/lofi-electronic.md@@ -1,5 +1,7 @@# Style: lo-fi electronic (chill, upbeat, clean)+**Contents:** The sound · Grooves · Harmony language (write your own progression) · Melody rules (write your own motif) · Arrangement grammar · Mixing: balance by stem RMS, then master+> A vocabulary, not a song. The data is `VOCAB.lofiElectronic` in `engine/src/canvas-core/music/vocab.ts`> (print it: `node tools/music.mjs vocab lofiElectronic`). You compose the notes with> [../compose.md](../compose.md). Our launch film was scored in this style (`launchLofi3`). Thatdiff --git a/skills/anidoodle/references/music/styles/vocabularies.md b/skills/anidoodle/references/music/styles/vocabularies.mdindex f918db4..0d0c531 100644--- a/skills/anidoodle/references/music/styles/vocabularies.md+++ b/skills/anidoodle/references/music/styles/vocabularies.md@@ -1,5 +1,7 @@# Style vocabularies+**Contents:** Groove families · Section kinds (the arrangement grammar) · lofiElectronic: lo-fi electronic · drive: driving electronic · cinematic: cinematic / orchestral · ambient: airy ambient · folk: tender acoustic · playful: playful / bouncy · musicBox: music box · nocturne: nocturne / solo piano · minimalist: minimalist / pulse · jazz: jazz / swing · lullaby: lullaby · chiptune: chiptune · lofi: dusty lo-fi hip-hop · orchestral: orchestral / epic · suspense: suspense / horror · rock: rock / band · hipHop: hip-hop / trap · house: house / EDM · synthwave: synthwave / retro · world: world / modal folk · choral: choral / sacred+> GENERATED by `node tools/music.mjs vocab --md` from `engine/src/canvas-core/music/vocab.ts` and `vocabMore.ts`. Do not edit by hand.> A style is a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It never> contains notes. You compose the notes ([../compose.md](../compose.md)).diff --git a/skills/anidoodle/references/music/theory/form.md b/skills/anidoodle/references/music/theory/form.mdindex 2726511..89f208b 100644--- a/skills/anidoodle/references/music/theory/form.md+++ b/skills/anidoodle/references/music/theory/form.md@@ -1,5 +1,7 @@# Form, arrangement, orchestration, counterpoint+**Contents:** 1. Song forms (and the engine's section kinds) · 2. Film cue structure (scoring to picture) · 3. Builds and releases · 4. Orchestration: registers and frequency slots · 5. Counterpoint basics (a second line that helps)+## 1. Song forms (and the engine's section kinds)| Form | Shape | Engine kinds |diff --git a/skills/anidoodle/references/music/theory/harmony.md b/skills/anidoodle/references/music/theory/harmony.mdindex e687239..bc4d39f 100644--- a/skills/anidoodle/references/music/theory/harmony.md+++ b/skills/anidoodle/references/music/theory/harmony.md@@ -1,5 +1,7 @@# Harmony: function, voice leading, colour, tension+**Contents:** 1. Function: home, away, leaning, home · 2. Cadences: where a phrase breathes · 3. Voice leading · 4. Voicing and the low end · 5. Colour: modes, borrowed chords, extensions · 6. Secondary dominants, pedals, modulation · 7. Harmonic rhythm: pacing · 8. Tension curve+Roman numerals are relative to the key (`I ii iii IV V vi vii°` in major, `i ii° III iv v VI VII` inminor, `b` = borrowed or lowered). These are idioms, which are vocabulary. A multi-bar progressiontogether with its rhythm and groove is a piece, and novelty checks for that. `craft` measures this pagediff --git a/skills/anidoodle/references/music/theory/melody.md b/skills/anidoodle/references/music/theory/melody.mdindex 55012e3..b964030 100644--- a/skills/anidoodle/references/music/theory/melody.md+++ b/skills/anidoodle/references/music/theory/melody.md@@ -1,5 +1,7 @@# Melody: motif, contour, phrase+**Contents:** 1. Start from a motif, then develop it · 2. Phrase and period · 3. Contour and climax · 4. Steps, leaps and recovery · 5. Range and tessitura · 6. Rhythm and melody together · 7. Non-chord tones: where the feeling is · 8. Phrase endings · Checklist+Notation on this page: scale degrees (`1 2 3 ... 7`, `b3`, `#4`; `5,` = the octave below, `1'` = the octaveabove), durations in beats after a colon (`3:.5`). These are shapes to apply, never tunes to copy.`node tools/music.mjs craft <score>` measures every rule below (the **melody** line and `CRAFT melody:` findings).diff --git a/skills/anidoodle/references/music/theory/rhythm.md b/skills/anidoodle/references/music/theory/rhythm.mdindex d0bd286..63e8c00 100644--- a/skills/anidoodle/references/music/theory/rhythm.md+++ b/skills/anidoodle/references/music/theory/rhythm.md@@ -1,5 +1,7 @@# Rhythm and groove+**Contents:** 1. Metric hierarchy · 2. Syncopation · 3. The backbeat and core patterns · 4. Swing and feel · 5. Polyrhythm and hemiola · 6. Fills and transitions · 7. Density arcs · 8. Rhythm in the melody · 9. Humanize or quantize+Positions are beats in the bar (`1`, `1&` = the eighth after it, `1e&a` = sixteenths). In 6/8 and 12/8 abeat is a dotted quarter. `craft` measures this page on the **rhythm** line.diff --git a/skills/anidoodle/references/music/theory/sound.md b/skills/anidoodle/references/music/theory/sound.mdindex 635af1d..c2cf4cd 100644--- a/skills/anidoodle/references/music/theory/sound.md+++ b/skills/anidoodle/references/music/theory/sound.md@@ -1,5 +1,7 @@# Sound theory: psychoacoustics for composing and mixing+**Contents:** 1. Critical bands and roughness · 2. Masking: why the tune gets buried · 3. Equal loudness (Fletcher-Munson / ISO 226) · 4. Tonal balance by genre (long-term spectrum) · 5. Stereo and depth · 6. Reverb and delay timing · 7. Loudness and dynamics+You write notes, and the engine mixes. Most "muddy", "thin" or "buried" results are decided by thenotes: register, spacing, density and which parts overlap. This page is the physics behind thosechoices. The engine's guards and `craft` check the parts you can control from the score. The mixdiff --git a/skills/anidoodle/references/workflows/interactive.md b/skills/anidoodle/references/workflows/interactive.mdindex 10f74dd..c32083a 100644--- a/skills/anidoodle/references/workflows/interactive.md+++ b/skills/anidoodle/references/workflows/interactive.md@@ -1,5 +1,7 @@# Interactive web animation+**Contents:** The contract: a frame is a fact, given its input log · Making one · What the replay gate proves · Measured (headless Chromium 1140, this Mac, 1280x800 at DPR 2, September 2026) · Limits+Hand-drawn pieces that live on a web page and answer the person using it. They follow the pointer,react to hovered and focused buttons, draw themselves as you scroll, and read along with a form.None of this is a video or an embedded player: the piece is part of the page's UI.diff --git a/skills/anidoodle/references/workflows/launch-video-kit.md b/skills/anidoodle/references/workflows/launch-video-kit.mdindex 8cd32c5..fd9d96c 100644--- a/skills/anidoodle/references/workflows/launch-video-kit.md+++ b/skills/anidoodle/references/workflows/launch-video-kit.md@@ -1,5 +1,7 @@# The launch kit: build your product's launch film+**Contents:** Start from the template (16 s, one file) · The parts, for a film of your own shape · Worked example+The pieces anidoodle's own launch film is made of, in `engine/src/canvas-core/`, usable for anyproduct. The rules they serve are in `launch-video.md`.diff --git a/skills/anidoodle/references/workflows/launch-video.md b/skills/anidoodle/references/workflows/launch-video.mdindex 4e9847a..2ad39b9 100644--- a/skills/anidoodle/references/workflows/launch-video.md+++ b/skills/anidoodle/references/workflows/launch-video.md@@ -1,5 +1,7 @@# Launch and product videos+**Contents:** Inputs the person brings · Ground it in the real product first · Made for this product, every frame and every note · The story · Type · Motion · The motif · Two registers · Brand and the end card · Sound · Delivery · The process+A launch video makes one promise about a product and shows it being kept. It is a short filmwith a job: in the first seconds the viewer knows what the thing is, by the end they know whereto get it. Every rule below was paid for on anidoodle's own 77 s launch film (four cuts) anddiff --git a/skills/anidoodle/references/workflows/machines.md b/skills/anidoodle/references/workflows/machines.mdindex 24c7947..f7bf80e 100644--- a/skills/anidoodle/references/workflows/machines.md+++ b/skills/anidoodle/references/workflows/machines.md@@ -1,5 +1,7 @@# Machines: explain an idea by building it, in any style+**Contents:** 1. Turn the idea into a machine · 2. Parts list before geometry · 3. One model drives everything · 4. Build with the kit · 5. Draw it in a style: the hand · 6. Films and interactive pieces · 7. Check it+A machine is a subject, not a look. The kit (`engine/src/canvas-core/mechanismKit.ts`) builds realparts in 3D, sorts them, takes them apart and folds them back; a **hand** marks them in a style'sown medium. The same music box draws as cyanotype, coloured pencil, stipple or flat iso planes.diff --git a/skills/anidoodle/references/workflows/review.md b/skills/anidoodle/references/workflows/review.mdindex 995c897..3aab465 100644--- a/skills/anidoodle/references/workflows/review.md+++ b/skills/anidoodle/references/workflows/review.md@@ -1,5 +1,7 @@# The review: a fresh critic, three rounds at most+**Contents:** The loop · What the critic does · The four readings · Severity · The check before fixing · The scorecard · The gate · The fix ledger+The builder never judges its own work. A builder who has watched the film forty times sees whatthey meant, forgives the hand they know is hard, and grades the effort. So every review is done bya **fresh critic**: a new subagent (or a new session) that has seen none of the building.