Skip to content

Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.

3D rigs (two-bone IK, grips, walk, follow-through) and checks (grip, proximity, path, label, screen size) with red fixtures; Nib demo

Alex Greenshpun71b3e6f6d033
diff --git a/skills/anidoodle/engine/src/canvas-core/threeRigDemo.ts b/skills/anidoodle/engine/src/canvas-core/threeRigDemo.ts
new file mode 100644
index 0000000..7fefa37
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/threeRigDemo.ts
@@ -0,0 +1,246 @@
+// THREE RIG DEMO. Nib, a little lamp-lighter robot built from primitives with three-core/rig.ts,
+// walks in (arms counter-swinging, body bobbing), stops (antenna and body follow through), winds up,
+// reaches for a lantern on a crate with two-bone IK, takes the handle in its jaws, lifts it (the
+// lantern lags, then swings through), turns to the camera and waves. Every frame is posed from the
+// frame number alone, and every frame passes checks3d (grip, proximity, self, path, screen size):
+// test/threeChecks.test.ts runs them on all 192 frames, and on two broken variants that must fail.
+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, lerp, seg, spring, tween } from "../three-core/time";
+import { anticipate, bodyMatrix, flag, followThrough, grip, handle, head, limb, makeRig, part, pose, walkCycle, type Limb, type LimbPose } from "../three-core/rig";
+import { checking, registerGrip, registerPath, registerRig, registerSize, resetChecks, runChecks } from "../three-core/checks3d";
+
+const W = 1920, H = 1080, FPS = 24, N = 192;
+type V3 = THREE.Vector3;
+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+
+// ---------------------------------------------------------------- the beats (frames)
+export const BEATS = { stop: 84, windup: 92, reach: 100, approach: 114, onBar: 121, closed: 126, lift: 128, lifted: 146, turn: 140, wave: 156, giggle: 160 };
+const STRIDE = 0.56, CYCLES = 3.55; // the walk ends at phase .55: both feet planted (stance 0.6), so the stop never freezes a foot mid-air
+const STOP_X = 0.05;
+// the carry: the lantern lags AWAY from the arm as it rises, and the wrist bends over it so the
+// forearm stays clear of the lid (an upright wrist put the forearm through the lid: checks3d found it)
+const LAG = 0.1, WR = -0.4;
+export type Variant = "clean" | "offset" | "path";
+
+// ---------------------------------------------------------------- materials and parts
+const std = (color: string, o: THREE.MeshStandardMaterialParameters = {}) => new THREE.MeshStandardMaterial({ color, roughness: 0.5, ...o });
+const glow = (color: string, k = 1.6) => new THREE.MeshStandardMaterial({ color: "#000000", emissive: color, emissiveIntensity: k, roughness: 1 });
+
+// Nib's hand: a palm and two jaws hinged at the back of a ring. Closed, the jaws make a ring whose
+// hole runs along the hand's x axis: a handle passes THROUGH it (lesson 37), never through the palm.
+const RING_R = 0.035, RING_T = 0.0125, GRIP_Y = 0.074;
+const makeHand = (jaws: Record<string, THREE.Group[]>, name: string, cream: THREE.Material, coral: THREE.Material) => () => {
+ const g = new THREE.Group();
+ const palm = new THREE.Mesh(new THREE.SphereGeometry(0.038, 20, 14), cream); palm.scale.set(1.15, 1, 1); g.add(palm);
+ const hingeY = GRIP_Y - RING_R, list: THREE.Group[] = [];
+ // the ring lies in the hand's y-z plane; a point at angle a: centre + R (cos a y + sin a z)
+ const basis = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(v3(0, 1, 0), v3(0, 0, 1), v3(1, 0, 0)));
+ for (const s of [1, -1]) {
+ const hinge = new THREE.Group(); hinge.position.set(0, hingeY, 0);
+ const a0 = s > 0 ? 0.035 * Math.PI : -Math.PI + 0.06, len = 0.93 * Math.PI;
+ const m = new THREE.Mesh(new THREE.TorusGeometry(RING_R, RING_T, 10, 28, len), coral);
+ m.position.set(0, RING_R, 0); m.quaternion.copy(basis).multiply(new THREE.Quaternion().setFromAxisAngle(v3(0, 0, 1), a0));
+ m.userData.part = `${name}.jaw`; hinge.add(m); hinge.userData.side = s; list.push(hinge); g.add(hinge);
+ }
+ jaws[name] = list;
+ return g;
+};
+
+const build = () => {
+ const scene = new THREE.Scene();
+ const cream = std("#f4eee3", { roughness: 0.42 }), coral = std("#ff7656", { roughness: 0.45 }), slate = std("#5c6a80", { roughness: 0.5, metalness: 0.15 });
+ const visorM = std("#18202f", { roughness: 0.16, metalness: 0.35 }), eyeM = glow("#8ff4ff", 2.2), cheekM = glow("#ff8f80", 0.9);
+
+ // ---- Nib
+ const nib = makeRig("nib", { hipHeight: 0.515 });
+ const torso = part(nib, nib.body, "torso", new THREE.Mesh(new THREE.CapsuleGeometry(0.2, 0.2, 10, 32), cream)); torso.position.y = 0.25; torso.scale.set(1.05, 1, 0.92);
+ const bib = part(nib, nib.body, "bib", new THREE.Mesh(new THREE.CylinderGeometry(0.203, 0.203, 0.15, 32, 1, true, -0.5, 1.0), coral)); bib.position.y = 0.22; bib.scale.set(1.05, 1, 0.92);
+ const button = part(nib, nib.body, "button", new THREE.Mesh(new THREE.SphereGeometry(0.024, 16, 12), std("#ffd25e", { emissive: "#ffb000", emissiveIntensity: 0.35 }))); button.position.set(0, 0.235, 0.19);
+ const neck = new THREE.Group(); nib.hips.add(neck); nib.anchors.push({ obj: neck, base: v3(0, 0.56, 0) });
+ part(nib, neck, "neck", new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.06, 0.09, 20), slate)).position.y = 0.03;
+ const hd = head(nib, "head", { at: [0, 0.6, 0], max: [1.15, 0.55] });
+ const skull = part(nib, hd.pivot, "head", new THREE.Mesh(new THREE.SphereGeometry(0.2, 40, 28), cream)); skull.position.y = 0.17; skull.scale.set(1.12, 0.92, 1);
+ const visor = part(nib, skull, "visor", new THREE.Mesh(new THREE.SphereGeometry(0.204, 40, 20, Math.PI / 2 - 0.95, 1.9, 1.0, 1.05), visorM)); void visor;
+ const eyes: THREE.Mesh[] = [];
+ for (const s of [-1, 1]) {
+ const e = part(nib, hd.pivot, "eye", new THREE.Mesh(new THREE.CapsuleGeometry(0.021, 0.028, 6, 14), eyeM)); e.position.set(0.064 * s, 0.195, 0.196); e.rotation.x = -0.12; eyes.push(e);
+ const c = part(nib, hd.pivot, "cheek", new THREE.Mesh(new THREE.CircleGeometry(0.017, 20), cheekM)); c.position.set(0.112 * s, 0.14, 0.186); c.rotation.set(-0.15, 0.5 * s, 0);
+ const ear = part(nib, hd.pivot, "ear", new THREE.Mesh(new THREE.CylinderGeometry(0.052, 0.052, 0.045, 24), coral)); ear.rotation.z = Math.PI / 2; ear.position.set(0.222 * s, 0.17, 0);
+ }
+ const mouth = part(nib, hd.pivot, "mouth", new THREE.Mesh(new THREE.TorusGeometry(0.026, 0.0055, 8, 24, Math.PI), eyeM)); mouth.position.set(0, 0.142, 0.203); mouth.rotation.set(-0.2, 0, Math.PI);
+ const antenna = new THREE.Group(); antenna.position.set(0, 0.352, -0.01); hd.pivot.add(antenna);
+ part(nib, antenna, "antenna", new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.01, 0.12, 10), slate)).position.y = 0.06;
+ part(nib, antenna, "antenna.tip", new THREE.Mesh(new THREE.SphereGeometry(0.03, 18, 12), std("#ff7656", { emissive: "#ff5a36", emissiveIntensity: 0.5 }))).position.y = 0.14;
+
+ const jaws: Record<string, THREE.Group[]> = {};
+ const arm = (side: "left" | "right", s: number) => limb(nib, `arms.${side}`, { at: [0.235 * s, 0.4, 0], lengths: [0.19, 0.19], radius: [0.032, 0.029], rest: [0.05 * s, -0.34, 0.04], pole: [0.3 * s, -0.1, -1], material: slate, jointMaterial: coral, end: makeHand(jaws, `arms.${side}`, cream, coral), gripPoint: [0, GRIP_Y, 0], gripAxis: [1, 0, 0] });
+ const leg = (side: "left" | "right", s: number) => limb(nib, `legs.${side}`, { at: [0.1 * s, -0.02, 0], lengths: [0.23, 0.23], radius: [0.042, 0.038], rest: [0, -0.42, 0.02], pole: [0, 0, 1], material: slate, jointMaterial: coral, endMode: "level",
+ end: () => { const f = new THREE.Mesh(new THREE.CapsuleGeometry(0.052, 0.09, 6, 18), coral); f.rotation.x = Math.PI / 2; f.position.set(0, -0.002, 0.035); f.scale.set(1.05, 1, 0.8); return f; } });
+ // left is +x in Nib's own space (it faces +z), right is -x
+ arm("left", 1); arm("right", -1); leg("left", 1); leg("right", -1);
+ flag(nib, "blink", (_r, val) => eyes.forEach((e) => e.scale.set(1, Math.max(0.08, 1 - 0.92 * val), 1)));
+ flag(nib, "antenna", (_r, val) => antenna.rotation.set(val, 0, 0));
+ for (const n of ["arms.left", "arms.right"]) flag(nib, `jaws.${n.slice(5)}`, (_r, val) => jaws[n].forEach((h) => h.rotation.set(h.userData.side * 0.62 * val, 0, 0)));
+ scene.add(nib.root);
+
+ // ---- the crate and the lantern
+ const crate = new THREE.Group(); crate.name = "crate"; crate.position.set(0.56, 0, -0.2);
+ const wood = std("#c9935c", { roughness: 0.8 }), woodDark = std("#9a6a3e", { roughness: 0.85 });
+ const box = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.34, 0.4), wood); box.position.y = 0.17; crate.add(box);
+ for (const y of [0.012, 0.115, 0.225, 0.328]) { const b = new THREE.Mesh(new THREE.BoxGeometry(0.408, 0.022, 0.408), woodDark); b.position.y = y; crate.add(b); }
+ crate.traverse((o) => { o.castShadow = o.receiveShadow = true; o.userData.part ??= "crate"; });
+ scene.add(crate);
+
+ const lantern = new THREE.Group(); lantern.name = "lantern";
+ const iron = std("#3a4150", { roughness: 0.45, metalness: 0.5 }), glass = new THREE.MeshStandardMaterial({ color: "#ffe6b0", emissive: "#ffae45", emissiveIntensity: 1.25, roughness: 0.3 });
+ const add = (m: THREE.Mesh, y: number, nm: string) => { m.position.y = y; m.userData.part = nm; m.castShadow = true; lantern.add(m); return m; };
+ add(new THREE.Mesh(new THREE.CylinderGeometry(0.072, 0.076, 0.03, 28), iron), 0.015, "lantern.base");
+ add(new THREE.Mesh(new THREE.CylinderGeometry(0.058, 0.058, 0.13, 28), glass), 0.095, "lantern.glass").castShadow = false;
+ for (let k = 0; k < 4; k++) { const a = Math.PI / 4 + (k * Math.PI) / 2, p = add(new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.007, 0.13, 8), iron), 0.095, "lantern.post"); p.position.x = Math.cos(a) * 0.062; p.position.z = Math.sin(a) * 0.062; }
+ add(new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.074, 0.024, 28), iron), 0.172, "lantern.lid");
+ add(new THREE.Mesh(new THREE.ConeGeometry(0.056, 0.036, 28), iron), 0.202, "lantern.roof");
+ // the bail: a wire arc from rim to rim with a wooden grip across its top. The grip is the handle
+ const bail = new THREE.Group(); bail.userData.handlePart = true; lantern.add(bail);
+ const arc = new THREE.Mesh(new THREE.TorusGeometry(0.074, 0.0055, 8, 32, Math.PI), iron); arc.position.y = 0.176; arc.userData.part = "lantern.bail"; arc.userData.handlePart = true; bail.add(arc);
+ const gripM = new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 0.07, 16), std("#6b4428", { roughness: 0.7 })); gripM.rotation.z = Math.PI / 2; gripM.position.y = 0.25; gripM.userData.part = "lantern.handle"; gripM.userData.handlePart = true; bail.add(gripM);
+ handle(lantern, [-0.035, 0.25, 0], [0.035, 0.25, 0], 0.012);
+ const flame = new THREE.PointLight("#ffb35c", 0.5, 3, 2); flame.position.y = 0.1; lantern.add(flame);
+ scene.add(lantern);
+
+ // ---- the set: a photo-studio sweep (floor curving up into a wall) turned to face the lens
+ const prof: [number, number][] = []; // (z, y): floor from the front to the cove, a quarter circle, the wall
+ for (let i = 0; i <= 12; i++) prof.push([8 - (i / 12) * 10, 0]);
+ for (let i = 1; i <= 16; i++) { const a = (i / 16) * (Math.PI / 2); prof.push([-2 - Math.sin(a) * 2, 2 - Math.cos(a) * 2]); }
+ for (let i = 1; i <= 6; i++) prof.push([-4, 2 + i]);
+ const pos: number[] = [], idx: number[] = [], XS = [-12, -4, 4, 12];
+ prof.forEach(([z, y]) => XS.forEach((x) => pos.push(x, y, z)));
+ for (let i = 0; i < prof.length - 1; i++) for (let j = 0; j < XS.length - 1; j++) { const a = i * XS.length + j, b = a + 1, c = a + XS.length, d = c + 1; idx.push(a, c, b, b, c, d); }
+ const sg = new THREE.BufferGeometry(); sg.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3)); sg.setIndex(idx); sg.computeVertexNormals();
+ const sweep = new THREE.Mesh(sg, std("#efe6d8", { roughness: 0.95, side: THREE.DoubleSide })); sweep.receiveShadow = true; sweep.rotation.y = 0.5; sweep.position.set(-0.4, 0, 0.3);
+ scene.add(sweep);
+
+ // ---- light: a warm key with soft shadows, a cool sky, a cool rim from behind
+ scene.add(new THREE.HemisphereLight("#e8efff", "#d6c6ae", 1.1));
+ const fill = new THREE.DirectionalLight("#fff6ea", 0.75); fill.position.set(2.2, 1.6, 4.5); scene.add(fill);
+ const key = new THREE.DirectionalLight("#fff0da", 2.5); key.castShadow = true; key.shadow.mapSize.set(2048, 2048); key.shadow.bias = -0.0004; key.shadow.normalBias = 0.02; key.shadow.radius = 5;
+ const sc = key.shadow.camera as THREE.OrthographicCamera; sc.left = -2.4; sc.right = 2.4; sc.top = 2.4; sc.bottom = -2.4; sc.near = 0.5; sc.far = 14;
+ key.target.position.set(-0.8, 0, 0.1); key.position.set(-0.8 - 1.6, 4.2, 0.1 + 3.2); scene.add(key, key.target);
+ const rim = new THREE.DirectionalLight("#cfe0ff", 1.3); rim.position.set(-2.5, 2.6, -2.8); scene.add(rim);
+
+ const cam = new THREE.PerspectiveCamera(30, W / H, 0.05, 60);
+ return { scene, nib, crate, lantern, cam, jaws };
+};
+type Built = ReturnType<typeof build>;
+
+// ---------------------------------------------------------------- the motion, from the frame alone
+const distAt = (f: number) => {
+ const D = STRIDE * CYCLES, f1 = 66, T = BEATS.stop - f1, v = D / (f1 + T / 2);
+ if (f <= f1) return v * f;
+ if (f < BEATS.stop) { const t = f - f1; return v * f1 + v * (t - (t * t) / (2 * T)); }
+ return D;
+};
+const rootAt = (f: number, variant: Variant) => v3(STOP_X + (variant === "path" ? 0.18 : 0) - STRIDE * CYCLES + distAt(f), 0, 0);
+const BLINKS = [36, 140, 183];
+const blinkAt = (f: number) => { for (const b of BLINKS) if (f >= b && f < b + 4) return [0.6, 1, 1, 0.5][f - b]; return 0; };
+
+/** Pose the whole scene for frame f (no rendering): what the draw and the checks both use. */
+export const rigDemoFrame = (env: Env, f: number, variant: Variant = "clean") => {
+ const B = memo(env, "threeRigDemo", build) as Built, { nib, lantern, cam } = B;
+ resetChecks();
+ const at = rootAt(f, variant), yaw = Math.PI / 2;
+
+ // the walk: phase from distance, so planted feet never slide through the ease-out
+ const wk = walkCycle(f, { distance: distAt(f), stride: STRIDE, bob: 0.022, lift: 0.07, sway: 0.012, armSwing: 1 });
+ const S = BEATS;
+ // body: walk lean that rocks through the stop, the wind-up and the reach, then straightens for the lift
+ const reachP = anticipate(f, { at: S.reach, dur: S.approach - S.reach, lead: S.reach - S.windup, amount: 0.25 });
+ const settle = followThrough(f, FPS, [{ at: S.stop, amp: 0.07, held: 1, freq: 1.4, damping: 0.32 }]);
+ const lean = settle + 0.2 * Math.max(-0.25, reachP) * (1 - tween(f, S.lift, S.lifted)) + 0.02 * tween(f, S.lift, S.lifted);
+ const giggle = f >= S.giggle ? 0.04 * Math.sin((2 * Math.PI * (f - S.giggle)) / 8) * (1 - seg(f, S.giggle, S.giggle + 22)) : 0;
+ const lift = wk.bob - 0.05 * Math.max(0, reachP) * (1 - tween(f, S.lift, S.lifted)) + giggle * 0.4;
+ const twist = f < S.stop ? wk.twist * 0.12 : -0.22 * tween(f, S.turn + 6, S.turn + 24);
+
+ // feet: planted in the world from the walk; toes lift a little as a foot swings
+ const bm = bodyMatrix(nib, { at, yaw });
+ const feet: Record<string, LimbPose> = {};
+ (["left", "right"] as const).forEach((side, i) => { const ft = wk.feet[i], s = side === "left" ? 1 : -1; feet[side] = { target: v3(0.1 * s, 0.052 + ft.lift, ft.fwd).applyMatrix4(bm.root), wrist: [-4.5 * ft.lift, 0] }; });
+
+ // arms: counter-swing that dies into the stop and springs through it
+ const mvA = 1 - 0.6 * seg(f, 66, S.stop);
+ const swing = (i: number) => f < S.stop ? wk.arms[i] * mvA : walkCycle(S.stop, { distance: distAt(S.stop), stride: STRIDE }).arms[i] * 0.4 * spring(f, S.stop, FPS, 1.6, 0.3);
+ const armSwing = (i: number): LimbPose => ({ offset: [0, 0.025 * Math.abs(swing(i)), 0.13 * swing(i)] });
+
+ // the reach: rest > a point just short of the handle (jaws opening) > onto the handle > lift to show it
+ const hb = lantern.userData.handle as { a: V3; b: V3 };
+ const onCrate = () => { lantern.position.set(0.42, 0.34, -0.2); lantern.rotation.set(0, Math.PI / 2, 0); lantern.updateWorldMatrix(true, true); };
+ onCrate();
+ const bar = lantern.localToWorld(hb.a.clone().lerp(hb.b, 0.5)), axis = v3(0, 0, 1);
+ const approachPt = bar.clone().add(v3(-0.08, 0.1, 0)), showPt = v3(STOP_X + 0.35, 0.95, -0.24);
+ let carry: LimbPose = armSwing(0), jawsC = 0;
+ if (f >= S.reach && f < S.lift) {
+ if (f < S.approach) carry = { grip: { point: approachPt, axis }, weight: ease.inOutCubic(seg(f, S.reach, S.approach)) };
+ else carry = { grip: { point: approachPt.clone().lerp(bar, ease.inOutSine(seg(f, S.approach, S.onBar))), axis } };
+ jawsC = seg(f, S.reach + 4, S.approach) - seg(f, S.onBar, S.closed);
+ } else if (f >= S.lift) {
+ const u = ease.inOutCubic(seg(f, S.lift, S.lifted)), p = bar.clone().lerp(showPt, u); p.y += 0.06 * Math.sin(Math.PI * u);
+ carry = { grip: { point: p, axis }, wrist: [WR * Math.min(1, 2 * u + seg(f, S.closed, S.lift)), 0] };
+ }
+ if (f >= S.reach - 6 && f < S.reach) carry = { offset: [0, 0.03 * -reachP, -0.08 * -reachP / 0.25] }; // the wind-up: the hand draws back first
+ // the free hand (the lens side) balances during the reach, then waves at the lens
+ let free: LimbPose = armSwing(1), jawsF = 0;
+ if (f >= S.windup && f < S.wave) { const b = Math.max(0, reachP) * (1 - seg(f, S.lift, S.lifted)); free = { offset: [-0.06 * b, 0.05 * b, -0.1 * b] }; }
+ if (f >= S.wave) { const w = ease.inOutCubic(seg(f, S.wave, S.wave + 10)), osc = Math.sin((2 * Math.PI * (f - S.wave - 10)) / 11) * seg(f, S.wave + 8, S.wave + 14); free = { offset: [-0.07 * w - 0.045 * osc, 0.62 * w, 0.06 * w], wrist: [0, -0.35 * osc] }; jawsF = 0.6 * w; }
+
+ // the head: ahead, then the lantern, then the lens
+ const ahead = at.clone().add(v3(1.6, 0.55, 0));
+ const lanternC = v3(); // the lantern, wherever it is this frame (set after the grip below, read by the look)
+ const camPos = cameraAt(f, B);
+ const lookFor = (lc: V3) => { const t1 = ease.inOutSine(seg(f, 44, 64)), t2 = ease.inOutCubic(seg(f, S.turn + 4, S.turn + 18)); return ahead.clone().lerp(lc, t1).lerp(camPos, t2); };
+
+ // antenna: trails while walking, swings through at the stop, the lift and the giggle
+ const ant = -0.2 * (f < S.stop ? 1 : 0) * Math.min(1, f / 6) + 0.05 * Math.sin(4 * Math.PI * wk.phase) * (f < S.stop ? 1 : 0)
+ + followThrough(f, FPS, [{ at: S.stop, amp: -0.2, freq: 1.8, damping: 0.22 }, { at: S.lifted, amp: 0.14, freq: 1.8, damping: 0.25 }, { at: S.giggle + 4, amp: -0.12, freq: 2.2, damping: 0.25 }]);
+
+ // pose once with the look on the lantern's resting place, grip, then re-aim the look (cheap: head only)
+ const p = { at, yaw, lift, lean, twist, squash: giggle, look: { target: lookFor(bar) }, arms: { left: carry, right: free }, legs: feet,
+ flags: { blink: blinkAt(f), antenna: ant, "jaws.left": jawsC, "jaws.right": jawsF } };
+ pose(nib, p);
+
+ // the lantern: on the crate until the jaws close on it, then hanging from them, lagging and swinging
+ const hand = nib.limbs["arms.left"] as Limb;
+ if (f >= S.closed) {
+ const lag = f < S.lifted ? LAG * ease.inOutSine(seg(f, S.lift, S.lift + 9)) : LAG * spring(f, S.lifted, FPS, 1.3, 0.18);
+ grip(hand, lantern, 0.5, { hang: true, swing: lag });
+ if (variant === "offset") { const back = v3(0, -0.05, 0).transformDirection(hand.end.matrixWorld).multiplyScalar(0.05); lantern.position.add(back); lantern.updateWorldMatrix(false, true); }
+ }
+ lantern.getWorldPosition(lanternC).add(v3(0, 0.12, 0));
+ if (f >= S.lift) pose(nib, { ...p, look: { target: lookFor(lanternC) } });
+
+ // the camera follows Nib in, then pushes in for the look
+ cam.position.copy(camPos); cam.lookAt(camTarget(f)); cam.updateMatrixWorld();
+
+ // what this frame must keep true (checks3d): nothing through anything, the grip held and seen
+ registerRig("nib", nib); registerRig("crate", B.crate); registerRig("lantern", lantern);
+ if (f >= S.approach - 2) registerGrip(nib, hand, lantern, { closing: f < S.closed });
+ if (f >= S.approach && f < S.lifted + 12) registerSize(hand.end, 40);
+ registerPath({ name: "nib", at: (g) => rootAt(g, variant), from: f, to: f, radius: 0.22, height: 1.4 }, [{ name: "crate", box: B.crate }]);
+ return { ...B, hand };
+};
+// the camera keeps Nib a little left of centre while walking, then settles on the reach and pushes in
+const camTarget = (f: number) => v3(lerp(rootAt(f, "clean").x + 0.3, 0.2, tween(f, 64, 118)), lerp(0.72, 0.8, tween(f, 90, 160)), lerp(0.05, -0.02, tween(f, 64, 118)));
+const cameraAt = (f: number, _b?: Built) => { const t = camTarget(f), k = ease.inOutCubic(seg(f, 30, 170)); return t.add(v3(lerp(1.45, 1.35, k), lerp(0.5, 0.4, k), lerp(3.3, 3.0, k))); };
+
+// ---------------------------------------------------------------- the film
+const shot = (ctx: Ctx, f: number, env: Env) => {
+ const s = rigDemoFrame(env, f);
+ if (checking()) runChecks(f, s.cam, env); else resetChecks();
+ draw3d(ctx, env, s.scene, s.cam, { clear: "#e9e1d4", shadows: true });
+};
+export const threeRigDemo: Film = {
+ meta: { title: "three rig demo", W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "story", poster: 150 },
+ assets: { images: {} },
+ shots: [{ id: "nib", start: 0, end: N, draw: shot }],
+};
diff --git a/skills/anidoodle/engine/src/hosts/page-threeRigDemo.ts b/skills/anidoodle/engine/src/hosts/page-threeRigDemo.ts
new file mode 100644
index 0000000..f318c9c
--- /dev/null
+++ b/skills/anidoodle/engine/src/hosts/page-threeRigDemo.ts
@@ -0,0 +1,4 @@
+import { threeRigDemo } from "../canvas-core/threeRigDemo";
+import { mountFilm } from "./page";
+
+mountFilm(threeRigDemo);
diff --git a/skills/anidoodle/engine/src/three-core/checks3d.ts b/skills/anidoodle/engine/src/three-core/checks3d.ts
new file mode 100644
index 0000000..63d29d2
--- /dev/null
+++ b/skills/anidoodle/engine/src/three-core/checks3d.ts
@@ -0,0 +1,359 @@
+// CHECKS 3D. What a director runs on a frame of a 3D shot, from inside its draw, to catch the faults
+// Alex caught by eye on the last 3D film: a prop through the hand meant to hold it (lesson 37), a
+// claw holding nothing on screen (48), two characters clipping (38), a walk through a closed gate
+// (22), a label covered by a claw (42), a contact beat too small to read (25).
+//
+// Every check is a plain function returning { ok, findings }. For a whole shot, register what the
+// frame holds as it is posed, then runChecks() once the camera is set:
+//
+// resetChecks(); // first thing in the draw: nothing carries over from another frame
+// pose(robot, ...); grip(hand, lantern, 0.5, { hang: true });
+// registerRig("robot", robot); registerGrip(robot, robot.limbs["arms.right"], lantern);
+// if (checking()) runChecks(f, camera, env); // the collector (a host, a test) gets the findings
+//
+// Checks sample real surfaces, not bounding boxes: boxes of curved tubes are mostly air and flagged
+// thousands of points while rigs stood metres apart (lesson 38). Hidden objects never count (a
+// carried jar that is switched off is not a collision).
+//
+// PERSISTENT VISUAL CHECK (a practice, not code): run the full check pass after EVERY batch of shot
+// changes, not once at the end. On the last film a new jar swing broke a catch that had been clean,
+// and only the re-run found it (lesson 48). Pair it with a 2x crop of each grip (still --scale 2):
+// a green check with a prop through a hand is a failed gate, so look.
+import * as THREE from "three";
+import { gripFrame, handleOf, isLimb, meshesOf, type Limb, type Rig } from "./rig";
+
+type V3 = THREE.Vector3;
+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+export type Finding = { frame: number; kind: string; where: string; detail: string };
+export type CheckResult = { ok: boolean; findings: Finding[] };
+const result = (findings: Finding[]): CheckResult => ({ ok: findings.length === 0, findings });
+const fmt = (p: V3) => p.toArray().map((x) => x.toFixed(2)).join(", ");
+type Obj = THREE.Object3D;
+const objOf = (x: Rig | Obj): Obj => ("hips" in x && "limbs" in x ? (x as Rig).root : (x as Obj));
+const within = (o: Obj, anc: Obj) => { let n: Obj | null = o; while (n) { if (n === anc) return true; n = n.parent; } return false; };
+const partName = (m: THREE.Mesh) => String(m.userData.part ?? (m.name || m.geometry.type));
+
+// ---------------------------------------------------------------- surface sampling
+// Points spread over every triangle at `spacing` (vertices alone miss a big flat face pushed through
+// a small part). Cached per geometry in its own space: geometry never changes per frame, so the cache
+// cannot carry frame state; the world positions are recomputed from the mesh's matrix every call.
+const sampleCache = new WeakMap<THREE.BufferGeometry, Map<number, Float32Array>>();
+const MAX_PTS = 6000;
+const localSamples = (g: THREE.BufferGeometry, spacing: number): Float32Array => {
+ let byS = sampleCache.get(g); if (!byS) sampleCache.set(g, (byS = new Map()));
+ const hit = byS.get(spacing); if (hit) return hit;
+ const pos = g.attributes.position, idx = g.index, n = idx ? idx.count : pos.count, tri = (i: number) => (idx ? idx.getX(i) : i);
+ const A = v3(), B = v3(), C = v3(), out: number[] = [];
+ let sp = spacing;
+ for (let pass = 0; pass < 6; pass++) {
+ out.length = 0;
+ // every vertex once, then extra points only inside triangles bigger than the spacing (a dense
+ // sphere needs no more than its vertices; a two-triangle wall needs a grid)
+ for (let i = 0; i < pos.count; i++) out.push(pos.getX(i), pos.getY(i), pos.getZ(i));
+ for (let t = 0; t + 2 < n; t += 3) {
+ A.fromBufferAttribute(pos, tri(t)); B.fromBufferAttribute(pos, tri(t + 1)); C.fromBufferAttribute(pos, tri(t + 2));
+ const k = Math.ceil(Math.max(A.distanceTo(B), B.distanceTo(C), C.distanceTo(A)) / sp);
+ if (k < 2) continue;
+ for (let i = 0; i <= k; i++) for (let j = 0; j <= k - i; j++) { if ((i === 0 && j === 0) || (i === k && j === 0) || (i === 0 && j === k)) continue; const a = i / k, b = j / k, c = 1 - a - b; out.push(A.x * c + B.x * a + C.x * b, A.y * c + B.y * a + C.y * b, A.z * c + B.z * a + C.z * b); }
+ }
+ if (out.length / 3 <= MAX_PTS) break;
+ sp *= 1.6;
+ }
+ const arr = new Float32Array(out); byS.set(spacing, arr); return arr;
+};
+/** World-space surface points of a mesh, about `spacing` apart. */
+export const surfacePoints = (m: THREE.Mesh, spacing: number): V3[] => { const w = worldPts(m, spacing), out: V3[] = []; for (let i = 0; i < w.length; i += 3) out.push(v3(w[i], w[i + 1], w[i + 2])); return out; };
+// the same as a flat array (the checks' hot path: no object per point)
+const worldPts = (m: THREE.Mesh, spacing: number): Float32Array => {
+ m.updateWorldMatrix(true, false);
+ const s = localSamples(m.geometry, spacing), e = m.matrixWorld.elements, out = new Float32Array(s.length);
+ for (let i = 0; i < s.length; i += 3) { const x = s[i], y = s[i + 1], z = s[i + 2]; out[i] = e[0] * x + e[4] * y + e[8] * z + e[12]; out[i + 1] = e[1] * x + e[5] * y + e[9] * z + e[13]; out[i + 2] = e[2] * x + e[6] * y + e[10] * z + e[14]; }
+ return out;
+};
+const segDist = (p: V3, a: V3, b: V3) => segDistXYZ(p.x, p.y, p.z, a, b);
+const segDistXYZ = (px: number, py: number, pz: number, a: V3, b: V3) => {
+ const abx = b.x - a.x, aby = b.y - a.y, abz = b.z - a.z, L = abx * abx + aby * aby + abz * abz;
+ let t = L > 0 ? ((px - a.x) * abx + (py - a.y) * aby + (pz - a.z) * abz) / L : 0; t = t < 0 ? 0 : t > 1 ? 1 : t;
+ const dx = px - a.x - abx * t, dy = py - a.y - aby * t, dz = pz - a.z - abz * t; return Math.sqrt(dx * dx + dy * dy + dz * dz);
+};
+
+// Is a point INSIDE a closed mesh? Ray parity in the mesh's own space, both faces counted. A hand
+// sunk wholly into a body touches no surface point, so surface distance alone misses it.
+const CLOSED = new Set(["SphereGeometry", "CapsuleGeometry", "BoxGeometry", "IcosahedronGeometry", "OctahedronGeometry", "DodecahedronGeometry", "TetrahedronGeometry", "ExtrudeGeometry"]);
+const isClosed = (m: THREE.Mesh) => {
+ if (m.userData.closed !== undefined) return !!m.userData.closed;
+ const g = m.geometry as THREE.BufferGeometry & { parameters?: Record<string, number | boolean> }, t = g.type, p = g.parameters ?? {};
+ if (t === "CylinderGeometry") return !p.openEnded && (p.thetaLength === undefined || (p.thetaLength as number) >= Math.PI * 2 - 1e-6);
+ if (t === "TorusGeometry") return (p.arc as number) >= Math.PI * 2 - 1e-6;
+ if (t === "SphereGeometry") return (p.phiLength as number) >= Math.PI * 2 - 1e-6 && (p.thetaLength as number) >= Math.PI - 1e-6;
+ return CLOSED.has(t);
+};
+// triangles of a geometry as one flat array, cached (geometry is static; the frame never is)
+const triCache = new WeakMap<THREE.BufferGeometry, Float32Array>();
+const trisOf = (g: THREE.BufferGeometry) => {
+ let t = triCache.get(g); if (t) return t;
+ const pos = g.attributes.position, idx = g.index, n = idx ? idx.count : pos.count; t = new Float32Array(Math.floor(n / 3) * 9);
+ for (let i = 0, k = 0; i + 2 < n; i += 3) for (let j = 0; j < 3; j++) { const q = idx ? idx.getX(i + j) : i + j; t[k++] = pos.getX(q); t[k++] = pos.getY(q); t[k++] = pos.getZ(q); }
+ triCache.set(g, t); return t;
+};
+const DX = 1, DY = 0.000713, DZ = 0.000419; // a skewed ray so it never runs exactly along an edge
+type Solid = { box: THREE.Box3; lbox: THREE.Box3; inv: number[]; tris: Float32Array; name: string };
+const solidOf = (m: THREE.Mesh): Solid => { m.updateWorldMatrix(true, false); const g = m.geometry; g.boundingBox ?? g.computeBoundingBox(); return { box: new THREE.Box3().copy(g.boundingBox!).applyMatrix4(m.matrixWorld), lbox: g.boundingBox!, inv: m.matrixWorld.clone().invert().elements, tris: trisOf(g), name: partName(m) }; };
+const insideSolid = (s: Solid, x: number, y: number, z: number) => {
+ if (x < s.box.min.x || x > s.box.max.x || y < s.box.min.y || y > s.box.max.y || z < s.box.min.z || z > s.box.max.z) return false;
+ const e = s.inv, px = e[0] * x + e[4] * y + e[8] * z + e[12], py = e[1] * x + e[5] * y + e[9] * z + e[13], pz = e[2] * x + e[6] * y + e[10] * z + e[14];
+ const lb = s.lbox; if (px < lb.min.x || px > lb.max.x || py < lb.min.y || py > lb.max.y || pz < lb.min.z || pz > lb.max.z) return false;
+ const t = s.tris; let k = 0;
+ for (let i = 0; i < t.length; i += 9) { // Moller-Trumbore, both faces
+ const ax = t[i], ay = t[i + 1], az = t[i + 2], e1x = t[i + 3] - ax, e1y = t[i + 4] - ay, e1z = t[i + 5] - az, e2x = t[i + 6] - ax, e2y = t[i + 7] - ay, e2z = t[i + 8] - az;
+ const hx = DY * e2z - DZ * e2y, hy = DZ * e2x - DX * e2z, hz = DX * e2y - DY * e2x, det = e1x * hx + e1y * hy + e1z * hz;
+ if (det > -1e-12 && det < 1e-12) continue;
+ const f = 1 / det, sx = px - ax, sy = py - ay, sz = pz - az, u = f * (sx * hx + sy * hy + sz * hz); if (u < 0 || u > 1) continue;
+ const qx = sy * e1z - sz * e1y, qy = sz * e1x - sx * e1z, qz = sx * e1y - sy * e1x, v = f * (DX * qx + DY * qy + DZ * qz); if (v < 0 || u + v > 1) continue;
+ if (f * (e2x * qx + e2y * qy + e2z * qz) > 0) k++;
+ }
+ return (k & 1) === 1;
+};
+
+// ---------------------------------------------------------------- proximity (two rigs clipping)
+export type ProximityOpts = { frame?: number; tol?: number; minPoints?: number; spacing?: number; exempt?: Obj[]; deep?: boolean; kind?: string };
+/**
+ * Do two things touch or pass through each other? A spatial hash of A's surface points; B's surface
+ * points within `tol` of one are counted, and (deep) B's points sunk inside A's closed parts. A
+ * finding names the hit centre and the parts on both sides. `exempt` subtrees (a held prop, the
+ * holding hand) are skipped on either side. Default tol: 2% of the larger one's height.
+ */
+export const proximity = (rigA: Rig | Obj, rigB: Rig | Obj, exempt: Obj[] = [], o: ProximityOpts = {}): CheckResult => {
+ const A = objOf(rigA), B = objOf(rigB), ex = [...exempt, ...(o.exempt ?? [])], skip = (m: THREE.Mesh) => ex.some((e) => within(m, e));
+ A.updateWorldMatrix(true, true); B.updateWorldMatrix(true, true);
+ let ma = meshesOf(A, skip).filter((m) => !within(m, B)), mb = meshesOf(B, skip).filter((m) => !within(m, A));
+ if (!ma.length || !mb.length) return result([]);
+ const boxOf = (ms: THREE.Mesh[]) => { const b = new THREE.Box3(); ms.forEach((m) => b.expandByObject(m)); return b; };
+ const bA = boxOf(ma), bB = boxOf(mb);
+ const tol = o.tol ?? 0.02 * Math.max(bA.getSize(v3()).y, bB.getSize(v3()).y), sp = o.spacing ?? tol * 0.75, minN = o.minPoints ?? 12;
+ // boxes only PRUNE (a part whose box is nowhere near the other side cannot touch it); they never decide a hit
+ bA.expandByScalar(tol); bB.expandByScalar(tol);
+ ma = ma.filter((m) => new THREE.Box3().setFromObject(m).intersectsBox(bB)); mb = mb.filter((m) => new THREE.Box3().setFromObject(m).intersectsBox(bA));
+ if (!ma.length || !mb.length) return result([]);
+ const cell = new Map<number, number[]>(), c = (u: number) => Math.floor(u / tol), key = (x: number, y: number, z: number) => ((x * 73856093) ^ (y * 19349663) ^ (z * 83492791)) | 0;
+ const AP: number[] = [], AN: string[] = [];
+ for (const m of ma) { const w = worldPts(m, sp), nm = partName(m); for (let i = 0; i < w.length; i += 3) { const id = AP.length / 3; AP.push(w[i], w[i + 1], w[i + 2]); AN.push(nm); const k = key(c(w[i]), c(w[i + 1]), c(w[i + 2])); let l = cell.get(k); if (!l) cell.set(k, (l = [])); l.push(id); } }
+ let n = 0; const hitC = v3(), partsA: Record<string, number> = {}, partsB: Record<string, number> = {}, t2 = tol * tol;
+ const solids = o.deep === false ? [] : ma.filter(isClosed).map(solidOf);
+ for (const m of mb) {
+ const w = worldPts(m, sp), pb = partName(m);
+ for (let i = 0; i < w.length; i += 3) {
+ const x = w[i], y = w[i + 1], z = w[i + 2], X = c(x), Y = c(y), Z = c(z); let near: string | null = null;
+ for (let a = -1; a <= 1 && !near; a++) for (let b = -1; b <= 1 && !near; b++) for (let d = -1; d <= 1 && !near; d++) for (const id of cell.get(key(X + a, Y + b, Z + d)) ?? []) { const dx = AP[id * 3] - x, dy = AP[id * 3 + 1] - y, dz = AP[id * 3 + 2] - z; if (dx * dx + dy * dy + dz * dz < t2) { near = AN[id]; break; } }
+ if (!near) for (const sd of solids) if (insideSolid(sd, x, y, z)) { near = sd.name + " (inside)"; break; }
+ if (near) { n++; hitC.x += x; hitC.y += y; hitC.z += z; partsA[near] = (partsA[near] ?? 0) + 1; partsB[pb] = (partsB[pb] ?? 0) + 1; }
+ }
+ }
+ if (n < minN) return result([]);
+ const top = (r: Record<string, number>) => Object.entries(r).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([k, x]) => `${k} ${x}`).join(", ");
+ return result([{ frame: o.frame ?? 0, kind: o.kind ?? "proximity", where: `${A.name || "A"} / ${B.name || "B"} at ${fmt(hitC.divideScalar(n))}`, detail: `${n} surface points within ${tol.toFixed(3)} (A: ${top(partsA)}; B: ${top(partsB)})` }]);
+};
+
+/** A rig's own limbs through its own body (an arm swung through the belly): lower bones and ends against the torso. */
+export const selfClear = (rig: Rig, o: { frame?: number; tol?: number; minPoints?: number } = {}): CheckResult => {
+ const f: Finding[] = [];
+ for (const L of Object.values(rig.limbs)) {
+ // the far half only: the upper bone and the root joint sit in the shoulder by design
+ const meshes = [L.lower, ...meshesOf(L.end)];
+ const r = proximityMeshes(meshes, meshesOf(rig.body), { tol: o.tol ?? 0.004, minPoints: o.minPoints ?? 6, frame: o.frame ?? 0, where: `${rig.name}: ${L.name} into its own body` });
+ f.push(...r);
+ }
+ return result(f);
+};
+const proximityMeshes = (mb: THREE.Mesh[], ma: THREE.Mesh[], o: { tol: number; minPoints: number; frame: number; where: string }): Finding[] => {
+ let n = 0; const at = v3(), parts: Record<string, number> = {}, solids = ma.filter(isClosed).map(solidOf);
+ for (const m of mb) { const w = worldPts(m, o.tol * 3); for (let i = 0; i < w.length; i += 3) for (const sd of solids) if (insideSolid(sd, w[i], w[i + 1], w[i + 2])) { n++; at.x += w[i]; at.y += w[i + 1]; at.z += w[i + 2]; parts[sd.name] = (parts[sd.name] ?? 0) + 1; break; } }
+ return n >= o.minPoints ? [{ frame: o.frame, kind: "self", where: `${o.where} at ${fmt(at.divideScalar(n))}`, detail: `${n} points inside ${Object.keys(parts).join(", ")}` }] : [];
+};
+
+// ---------------------------------------------------------------- grips
+export type GripOpts = { tol?: number; contact?: number; minTouch?: number; closing?: boolean; others?: Obj[] };
+const onScreen = (p: V3, cam: THREE.Camera, m = 0.98) => { const q = p.clone().project(cam); return q.z < 1 && q.z > -1 && Math.abs(q.x) < m && Math.abs(q.y) < m; };
+const handPart = (prop: Obj, m: THREE.Mesh) => !!m.userData.handlePart || (within(m, prop) && !!(m.parent && m.parent.userData.handlePart));
+/**
+ * Is the prop really held? (1) the hand's grip point is on the handle (within tol); (2) the hand is
+ * closed on it: enough of its surface just outside the handle; (3) the handle does not run through
+ * the hand (points inside the handle's core) or (4) through the holder's own body; (5) the prop's
+ * body is not pushed into the holder; and with a camera, (6) the grip is in frame when the prop is,
+ * and (7) not hidden behind the holder, the prop or another rig. `closing`: the hand is still on its
+ * way, so only "through the hand" and "through the holder" apply.
+ */
+export const checkGrip = (holder: Rig | Obj, hand: Limb | Obj, prop: Obj, frame = 0, camera?: THREE.Camera, o: GripOpts = {}): CheckResult => {
+ const H = objOf(holder), end = isLimb(hand) ? hand.end : hand, F: Finding[] = [], where = `${H.name || "holder"} holding ${prop.name || "prop"}`;
+ H.updateWorldMatrix(true, true); prop.updateWorldMatrix(true, true);
+ const h = handleOf(prop), sc = prop.getWorldScale(v3()).x, a = prop.localToWorld(h.a.clone()), b = prop.localToWorld(h.b.clone()), r = h.r * sc;
+ const { point: gp } = gripFrame(hand);
+ const handMeshes = meshesOf(end), handPts = handMeshes.flatMap((m) => surfacePoints(m, r * 0.6));
+ const handR = handPts.reduce((mx, p) => Math.max(mx, p.distanceTo(gp)), 0);
+ const tol = o.tol ?? Math.max(r * 3, handR * 0.25);
+ const gap = segDist(gp, a, b);
+ let inside = 0, touch = 0;
+ for (const p of handPts) { const d = segDist(p, a, b); if (d < r * 0.5) inside++; else if (d < r + (o.contact ?? Math.max(r * 2.5, handR * 0.6))) touch++; }
+ if (!o.closing && gap > tol) F.push({ frame, kind: "grip-gap", where, detail: `the grip point is ${gap.toFixed(3)} from the handle (tolerance ${tol.toFixed(3)}): the prop floats off the hand` });
+ if (!o.closing && touch < (o.minTouch ?? 8)) F.push({ frame, kind: "grip-open", where, detail: `only ${touch} hand points close on the handle: it reads as not held` });
+ if (inside > 6) F.push({ frame, kind: "grip-through-hand", where, detail: `${inside} hand points inside the handle: the handle passes through the hand` });
+ // the handle through the holder: body points on the handle's line, away from the hand
+ const body = meshesOf(H, (m) => within(m, end) || within(m, prop));
+ let thru = 0; const thruParts: Record<string, number> = {}, reachBox = new THREE.Box3().setFromPoints([a, b]).expandByScalar(r * 1.2);
+ // along the handle: samples sunk inside a closed part of the holder (a body's big flat faces are
+ // sampled sparsely, so this side of the test is the one that never misses a pole through a torso)
+ const solids = body.filter((m) => isClosed(m) && new THREE.Box3().setFromObject(m).intersectsBox(reachBox)).map(solidOf), L = a.distanceTo(b), nS = Math.max(2, Math.ceil(L / r));
+ for (let i = 0; i <= nS; i++) { const p = a.clone().lerp(b, i / nS); if (p.distanceTo(gp) <= handR) continue; for (const sd of solids) if (insideSolid(sd, p.x, p.y, p.z)) { thru++; thruParts[sd.name] = (thruParts[sd.name] ?? 0) + 1; break; } }
+ for (const m of body) { if (!new THREE.Box3().setFromObject(m).intersectsBox(reachBox)) continue; const w = worldPts(m, r); for (let i = 0; i < w.length; i += 3) { const dx = w[i] - gp.x, dy = w[i + 1] - gp.y, dz = w[i + 2] - gp.z; if (dx * dx + dy * dy + dz * dz > handR * handR && segDistXYZ(w[i], w[i + 1], w[i + 2], a, b) < r * 1.2) { thru++; thruParts[partName(m)] = (thruParts[partName(m)] ?? 0) + 1; } } }
+ if (thru > 3) F.push({ frame, kind: "grip-through-holder", where, detail: `the handle runs through the holder (${Object.entries(thruParts).map(([k, x]) => `${k} ${x}`).join(", ")})` });
+ // the prop's body pushed into the holder (a lantern in the belly)
+ const pr = proximity(H, prop, [end, ...meshesOf(prop).filter((m) => handPart(prop, m))], { frame, minPoints: 6, kind: "grip-prop-in-holder" });
+ F.push(...pr.findings);
+ if (camera) {
+ camera.updateMatrixWorld();
+ const eye = camera.getWorldPosition(v3());
+ if (!o.closing && onScreen(new THREE.Box3().setFromObject(prop).getCenter(v3()), camera) && !onScreen(gp, camera)) F.push({ frame, kind: "grip-offscreen", where, detail: "the prop is in frame but the hand holding it is not: it reads as dropped" });
+ if (onScreen(gp, camera)) {
+ const occ = [...body, ...meshesOf(prop, (m) => handPart(prop, m)), ...(o.others ?? []).flatMap((x) => meshesOf(x))];
+ const ax = b.clone().sub(a).normalize(); let hid = 0, centre = false, what = "";
+ for (const t of [-1, -0.5, 0, 0.5, 1]) {
+ const pt = gp.clone().addScaledVector(ax, t * handR * 0.8), dir = pt.clone().sub(eye), L = dir.length();
+ const hit = new THREE.Raycaster(eye, dir.normalize(), 0, L - handR * 0.6).intersectObjects(occ, false)[0];
+ if (hit) { hid++; if (t === 0) centre = true; what = partName(hit.object as THREE.Mesh); }
+ }
+ if (centre || hid >= 3) F.push({ frame, kind: "grip-hidden", where, detail: `the grip is hidden behind ${what} (${hid}/5 points along the hold)` });
+ }
+ }
+ return result(F);
+};
+
+// ---------------------------------------------------------------- paths through set props
+export type PathSpec = { at: (f: number) => V3; from: number; to: number; step?: number; radius: number; height?: number; name?: string };
+export type PropBox = { name: string; box: THREE.Box3 | Obj; open?: boolean };
+/**
+ * Does a character walk through a set prop (a closed gate, a crate)? The character is an upright
+ * cylinder of `radius` and `height` standing on path.at(f); props are boxes (or objects, boxed).
+ * An `open` prop (a gate swung open) is skipped. One finding per run of colliding frames.
+ */
+export const pathClear = (path: PathSpec, props: PropBox[]): CheckResult => {
+ const F: Finding[] = [], hgt = path.height ?? 1, st = path.step ?? 1;
+ const boxes = props.filter((p) => !p.open).map((p) => ({ name: p.name, b: (p.box as THREE.Box3).isBox3 ? (p.box as THREE.Box3) : new THREE.Box3().setFromObject(p.box as Obj) }));
+ for (const { name, b } of boxes) {
+ let run: number[] = [], worst = 0;
+ const flush = () => { if (run.length) F.push({ frame: run[0], kind: "path", where: `${path.name ?? "character"} through ${name}`, detail: `frames ${run[0]}-${run[run.length - 1]}: ${worst.toFixed(3)} into it` }); run = []; worst = 0; };
+ for (let f = path.from; f <= path.to; f += st) {
+ const p = path.at(f), dx = Math.max(b.min.x - p.x, 0, p.x - b.max.x), dz = Math.max(b.min.z - p.z, 0, p.z - b.max.z), d = Math.hypot(dx, dz);
+ const yHit = p.y < b.max.y && p.y + hgt > b.min.y;
+ if (yHit && d < path.radius) { run.push(f); worst = Math.max(worst, path.radius - d); } else flush();
+ }
+ flush();
+ }
+ return result(F);
+};
+
+// ---------------------------------------------------------------- labels
+export type Label = { obj: Obj; w: number; h: number; name: string };
+const LABEL_PTS: [number, number][] = [[0, 0], [-0.42, 0.38], [0.42, 0.38], [-0.42, -0.38], [0.42, -0.38], [-0.42, 0], [0.42, 0], [0, 0.38], [0, -0.38]];
+/**
+ * Can the label be read? Nine points on it (its local xy plane, w x h, facing +z) are raycast from
+ * the camera past `occluders`; any hidden point, a label turned more than ~70 degrees from the lens,
+ * or one out of frame is a finding.
+ */
+export const labelVisible = (label: Label, camera: THREE.Camera, occluders: Obj[], frame = 0): CheckResult => {
+ const F: Finding[] = [], occ = occluders.flatMap((o) => meshesOf(o, (m) => within(m, label.obj)));
+ label.obj.updateWorldMatrix(true, true); camera.updateMatrixWorld();
+ const eye = camera.getWorldPosition(v3()); let hid = 0, off = 0; const what = new Set<string>();
+ for (const [x, y] of LABEL_PTS) {
+ const pt = label.obj.localToWorld(v3(x * label.w, y * label.h, 0.001)), dir = pt.clone().sub(eye), L = dir.length();
+ if (!onScreen(pt, camera, 1)) { off++; continue; }
+ const hit = new THREE.Raycaster(eye, dir.normalize(), 0, L - 1e-3).intersectObjects(occ, false)[0];
+ if (hit) { hid++; what.add(partName(hit.object as THREE.Mesh)); }
+ }
+ const nrm = v3(0, 0, 1).transformDirection(label.obj.matrixWorld), toEye = eye.clone().sub(label.obj.getWorldPosition(v3())).normalize();
+ if (off) F.push({ frame, kind: "label-offscreen", where: label.name, detail: `${off}/9 points of the label out of frame` });
+ if (hid) F.push({ frame, kind: "label-hidden", where: label.name, detail: `${hid}/9 points hidden behind ${[...what].join(", ")}` });
+ if (nrm.dot(toEye) < 0.35) F.push({ frame, kind: "label-turned", where: label.name, detail: `the label faces ${(Math.acos(Math.max(-1, Math.min(1, nrm.dot(toEye)))) * 180 / Math.PI).toFixed(0)} degrees from the lens` });
+ return result(F);
+};
+/** Turn a label about its parent's up so its face points at the camera (a tag on a string, a sign). */
+export const faceCamera = (obj: Obj, camera: THREE.Camera) => {
+ obj.updateWorldMatrix(true, false); camera.updateMatrixWorld();
+ const par = obj.parent, eye = camera.getWorldPosition(v3()), at = par ? par.worldToLocal(eye.clone()) : eye.clone();
+ obj.rotation.set(0, Math.atan2(at.x - obj.position.x, at.z - obj.position.z), 0);
+ obj.updateWorldMatrix(false, true);
+};
+/**
+ * AFTER THE CAMERA: place a label where it reads. Each try sets the label's transform from scratch
+ * (slide along a handle, swing round, shorten the string); the first that passes labelVisible wins.
+ * If none passes, the last try stays and its findings are returned. Run it after the frame's camera
+ * is set, never before (lesson 42: a tag reading "/co act" because a claw covered two letters).
+ */
+export const placeLabel = (label: Label, camera: THREE.Camera, occluders: Obj[], tries: ((obj: Obj, k: number) => void)[], frame = 0) => {
+ let last = result([]);
+ for (let k = 0; k < tries.length; k++) { tries[k](label.obj, k); label.obj.updateWorldMatrix(true, true); last = labelVisible(label, camera, occluders, frame); if (last.ok) return { ...last, pick: k }; }
+ return { ...last, pick: -1 };
+};
+
+// ---------------------------------------------------------------- screen size
+/**
+ * Is it big enough to read? The object's box projected through the camera, its larger side in
+ * pixels at 1080p (a 4K or 720p film is scaled to 1080 lines). A contact beat (a hand on a handle)
+ * needs about 40 px, or the acting reads as nothing (lesson 25).
+ */
+export const screenSizeOk = (object: Obj, camera: THREE.Camera, env: { W: number; H: number }, minPx = 40, frame = 0): CheckResult & { px: number } => {
+ object.updateWorldMatrix(true, true); camera.updateMatrixWorld();
+ const pts = meshesOf(object).flatMap((m) => surfacePoints(m, 1e9));
+ if (!pts.length) return { ...result([{ frame, kind: "screen-size", where: object.name || "object", detail: "nothing visible to measure" }]), px: 0 };
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (const p of pts) { const q = p.clone().project(camera); const x = ((q.x + 1) / 2) * env.W, y = ((1 - q.y) / 2) * env.H; x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); }
+ const px = (Math.max(x1 - x0, y1 - y0) * 1080) / env.H;
+ return { ...result(px >= minPx ? [] : [{ frame, kind: "screen-size", where: object.name || "object", detail: `${px.toFixed(0)} px at 1080p, under ${minPx}: the action will not read` }]), px };
+};
+
+// ---------------------------------------------------------------- the per-frame registry
+// A draw registers what this frame holds; runChecks reads it and clears it. Module state, but reset
+// at the start of every draw (resetChecks) and at the end of every run, so no frame sees another's.
+type Reg = { rigs: { name: string; obj: Obj; rig?: Rig }[]; grips: { holder: Rig | Obj; hand: Limb | Obj; prop: Obj; o: GripOpts }[]; labels: Label[]; sizes: { obj: Obj; minPx: number }[]; paths: { path: PathSpec; props: PropBox[] }[] };
+let REG: Reg = { rigs: [], grips: [], labels: [], sizes: [], paths: [] };
+const G = globalThis as { __ANIDOODLE_CHECK3D__?: (frame: number, findings: Finding[]) => void };
+/** True while a host or a test is collecting 3D findings. Draws skip the checks otherwise: no cost. */
+export const checking = () => typeof G.__ANIDOODLE_CHECK3D__ === "function";
+export const resetChecks = () => { REG = { rigs: [], grips: [], labels: [], sizes: [], paths: [] }; };
+/** A character (or any object) the proximity check pairs with every other registered one. */
+export const registerRig = (name: string, rig: Rig | Obj) => { const obj = objOf(rig); obj.name ||= name; REG.rigs.push({ name, obj, rig: "limbs" in rig ? (rig as Rig) : undefined }); };
+/** A held prop: checked by checkGrip, and exempt (with its hand) from proximity between holder and prop. */
+export const registerGrip = (holder: Rig | Obj, hand: Limb | Obj, prop: Obj, o: GripOpts = {}) => { REG.grips.push({ holder, hand, prop, o }); };
+export const registerLabel = (label: Label) => { REG.labels.push(label); };
+export const registerSize = (obj: Obj, minPx = 40) => { REG.sizes.push({ obj, minPx }); };
+export const registerPath = (path: PathSpec, props: PropBox[]) => { REG.paths.push({ path, props }); };
+/**
+ * Run every registered check on this frame and hand the findings to the collector (when one is
+ * listening). Proximity runs for every pair of registered rigs, with held props and their hands
+ * exempt between holder and prop; selfClear runs for every registered rig.
+ */
+export const runChecks = (frame: number, camera: THREE.Camera, env: { W: number; H: number }, o: { proximity?: ProximityOpts } = {}): CheckResult => {
+ const F: Finding[] = [];
+ const others = (h: Obj) => REG.rigs.map((r) => r.obj).filter((x) => x !== h && !REG.grips.some((g) => g.prop === x));
+ for (const g of REG.grips) F.push(...checkGrip(g.holder, g.hand, g.prop, frame, camera, { others: others(objOf(g.holder)), ...g.o }).findings);
+ for (let i = 0; i < REG.rigs.length; i++) for (let j = i + 1; j < REG.rigs.length; j++) {
+ // two set props touching (a lantern standing on a crate) is staging; a pair needs a character in it
+ if (!REG.rigs[i].rig && !REG.rigs[j].rig) continue;
+ const A = REG.rigs[i].obj, B = REG.rigs[j].obj, ex: Obj[] = [];
+ for (const g of REG.grips) { const H = objOf(g.holder); if ((H === A && g.prop === B) || (H === B && g.prop === A)) ex.push(isLimb(g.hand) ? g.hand.end : g.hand, ...meshesOf(g.prop).filter((m) => handPart(g.prop, m))); }
+ F.push(...proximity(A, B, ex, { ...o.proximity, frame }).findings);
+ }
+ for (const r of REG.rigs) if (r.rig) F.push(...selfClear(r.rig, { frame }).findings);
+ for (const l of REG.labels) F.push(...labelVisible(l, camera, REG.rigs.map((r) => r.obj), frame).findings);
+ for (const s of REG.sizes) F.push(...screenSizeOk(s.obj, camera, env, s.minPx, frame).findings);
+ for (const p of REG.paths) F.push(...pathClear({ ...p.path, from: frame, to: frame }, p.props).findings.map((x) => ({ ...x, frame })));
+ resetChecks();
+ if (checking()) G.__ANIDOODLE_CHECK3D__!(frame, F);
+ return result(F);
+};
+/** Collect the findings of everything `run` draws (a test, a host's check pass). */
+export const collectChecks = (run: () => void): Finding[] => {
+ const out: Finding[] = [], prev = G.__ANIDOODLE_CHECK3D__;
+ G.__ANIDOODLE_CHECK3D__ = (_f, fs) => { out.push(...fs); };
+ try { run(); } finally { if (prev) G.__ANIDOODLE_CHECK3D__ = prev; else delete G.__ANIDOODLE_CHECK3D__; }
+ return out;
+};
diff --git a/skills/anidoodle/engine/src/three-core/rig.ts b/skills/anidoodle/engine/src/three-core/rig.ts
new file mode 100644
index 0000000..51f613f
--- /dev/null
+++ b/skills/anidoodle/engine/src/three-core/rig.ts
@@ -0,0 +1,440 @@
+// RIG. Posable characters from primitives: a biped, a quadruped, a crab, a mascot. A rig is a tree
+// of groups built ONCE (memo it), and pose(rig, p) sets every joint from the pose alone, so any frame
+// can be posed first. Nothing here reads a clock or keeps a value from the pose before.
+//
+// makeRig(name) root (placed in the world) > hips (bob, lean) > body (the squashable torso)
+// part(rig, parent, name, m) add a mesh with a part name (the checks report hits by part name)
+// limb(rig, name, opts) a two-bone chain (arm, leg, claw) with its own end (hand, foot), posable at once
+// head(rig, name, opts) a head that can turn to look at things
+// flag(rig, name, apply) a custom pose flag (blink, antenna) that THIS rig supports
+// handle(prop, a, b, r) declare the segment of a prop a hand can hold (grip and the checks read it)
+// pose(rig, p) put the whole character in a pose; unknown limbs or flags THROW
+//
+// Why limbs are the default: a rig whose arms are fixed geometry plays every shot with frozen hands,
+// and retrofitting an arm rig after shots are rendered costs a reshoot (lessons 10 and 23). Why
+// unknown flags throw: a flag built into one variant of a rig silently did nothing on the other
+// variant, and only a render showed it (lesson 32).
+//
+// Verbs for the director: solveTwoBone (the IK), grip (a prop held along the hand's axis through
+// the grip), bodyMatrix (where the body will be, without posing meshes), lookAt, followThrough,
+// squashStretch, walkCycle, anticipate.
+import * as THREE from "three";
+import { clamp01, ease, lerp, seg, spring, type Ease } from "./time";
+
+type V3 = THREE.Vector3;
+export type Vec = [number, number, number];
+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+const vec = (a: Vec | V3) => (Array.isArray(a) ? v3(a[0], a[1], a[2]) : a.clone());
+const UP = v3(0, 1, 0);
+
+// ---------------------------------------------------------------- two-bone IK
+export type TwoBone = { mid: V3; end: V3; reached: boolean; bend: number };
+/**
+ * Analytic two-bone IK (law of cosines). root, mid, end give the bone lengths; the answer puts the
+ * end on the target when it can, and the middle joint on the side of the pole point. A target out
+ * of reach gives a straight limb pointing at it; one too close folds the limb as far as it goes.
+ * Deterministic and exact: no iterations, so no frame ever depends on the frame before.
+ */
+export const solveTwoBone = (root: V3, mid: V3, end: V3, target: V3, pole: V3): TwoBone => {
+ const L1 = root.distanceTo(mid), L2 = mid.distanceTo(end);
+ const d = target.clone().sub(root);
+ let D = d.length();
+ const dir = D > 1e-9 ? d.divideScalar(D) : end.clone().sub(root).normalize();
+ const maxD = L1 + L2, minD = Math.abs(L1 - L2);
+ const reached = D <= maxD + 1e-9 && D >= minD - 1e-9;
+ D = Math.min(maxD, Math.max(minD + 1e-9, D));
+ const a = (L1 * L1 - L2 * L2 + D * D) / (2 * D), h = Math.sqrt(Math.max(0, L1 * L1 - a * a));
+ // the bend plane: the pole's offset from the root, minus its part along the limb
+ const p = pole.clone().sub(root), perp = p.sub(dir.clone().multiplyScalar(p.dot(dir)));
+ if (perp.lengthSq() < 1e-12) perp.copy(v3().crossVectors(dir, Math.abs(dir.y) < 0.9 ? UP : v3(1, 0, 0)));
+ perp.normalize();
+ const m = root.clone().addScaledVector(dir, a).addScaledVector(perp, h), e = root.clone().addScaledVector(dir, D);
+ const bend = m.clone().sub(root).angleTo(e.clone().sub(m)); // 0 = straight
+ return { mid: m, end: e, reached, bend };
+};
+
+// ---------------------------------------------------------------- the rig
+export type LimbPose = {
+ /** where the end goes, in WORLD space (a hand on a bar, a foot on a step) */
+ target?: V3;
+ /** an offset from the rest end, in the limb's parent space (a swing, a wave) */
+ offset?: Vec | V3;
+ /** 0..1 blend from the rest (or offset) end to `target`: ease a reach in and out with it */
+ weight?: number;
+ /** a different bend direction for this pose, in the parent's space (a world point is NOT expected) */
+ pole?: Vec | V3;
+ /** put the hand's grip point on `point` with its grip axis along `axis` (world): reachFor a handle */
+ grip?: { point: V3; axis: V3 };
+ /** wrist: pitch and twist of the end in radians, after it is aimed (a flick, a toe lift) */
+ wrist?: [pitch: number, twist: number];
+};
+export type Limb = {
+ name: string; rig: Rig;
+ root: THREE.Group; upper: THREE.Mesh; lower: THREE.Mesh; joints: THREE.Mesh[]; end: THREE.Group;
+ L1: number; L2: number; base: V3; rest: V3; pole: V3; endMode: "forearm" | "level";
+ gripPoint: V3; gripAxis: V3;
+ /** the last solve (read it to know whether the target was reached) */
+ solved: TwoBone;
+};
+export type Head = { name: string; pivot: THREE.Group; max: [yaw: number, pitch: number] };
+export type Rig = {
+ name: string; root: THREE.Group; hips: THREE.Group; body: THREE.Group;
+ hipHeight: number;
+ limbs: Record<string, Limb>; heads: Record<string, Head>;
+ flags: Record<string, (rig: Rig, value: number, p: Pose) => void>;
+ /** groups whose rest position rides the squash of the body (shoulders, the neck) */
+ anchors: { obj: THREE.Object3D; base: V3 }[];
+};
+export type Pose = {
+ at?: Vec | V3; yaw?: number;
+ /** hip height offset (a bob, a crouch); legs solved to world feet stay planted */
+ lift?: number;
+ /** forward pitch of the hips (radians), side tilt, and twist about the spine */
+ lean?: number; tilt?: number; twist?: number;
+ /** volume-preserving squash (negative) or stretch (positive) of the body */
+ squash?: number;
+ /** turn a head to a world point: amount 0..1 blends from straight ahead */
+ look?: { target: V3; amount?: number; head?: string };
+ /** limbs by full name ("arms.left", "claws.big") */
+ limbs?: Record<string, LimbPose>;
+ /** sugar: arms.left is limbs["arms.left"], legs.right is limbs["legs.right"] */
+ arms?: Record<string, LimbPose>; legs?: Record<string, LimbPose>;
+ /** this rig's own flags (registered with flag()); a flag it does not have throws */
+ flags?: Record<string, number | boolean>;
+};
+
+/** A new empty character: root > hips (at hipHeight) > body. Add parts, limbs and heads to it. */
+export const makeRig = (name: string, opts: { hipHeight?: number } = {}): Rig => {
+ const root = new THREE.Group(), hips = new THREE.Group(), body = new THREE.Group();
+ root.name = `${name}`; hips.name = `${name}.hips`; body.name = `${name}.body`;
+ root.add(hips); hips.add(body);
+ const hipHeight = opts.hipHeight ?? 0;
+ hips.position.y = hipHeight;
+ hips.rotation.order = "YXZ";
+ const r: Rig = { name, root, hips, body, hipHeight, limbs: {}, heads: {}, flags: {}, anchors: [] };
+ root.userData.rig = r;
+ return r;
+};
+
+/** Add a mesh under `parent` with a part name the checks will print ("visor", "arms.left.hand"). */
+export const part = <T extends THREE.Object3D>(rig: Rig, parent: THREE.Object3D, name: string, obj: T): T => {
+ obj.traverse((o) => { if ((o as THREE.Mesh).isMesh) { o.userData.part ??= name; o.castShadow = true; o.receiveShadow = true; } });
+ obj.name ||= name;
+ parent.add(obj);
+ void rig;
+ return obj;
+};
+
+/** Make a group ride the body's squash: its rest position scales with the torso (shoulders, the neck). */
+export const anchor = (rig: Rig, obj: THREE.Object3D, at: Vec | V3) => { const b = vec(at); obj.position.copy(b); rig.anchors.push({ obj, base: b }); return obj; };
+
+export type LimbOpts = {
+ /** what the limb hangs from (default: the hips). Its root rides the squash when it hangs from the hips */
+ parent?: THREE.Object3D;
+ /** the root joint (shoulder, hip) in the parent's space */
+ at: Vec;
+ /** upper and lower bone lengths */
+ lengths: [number, number];
+ /** bone radius (one number, or [upper, lower]) */
+ radius?: number | [number, number];
+ /** where the end rests, relative to the root joint, in the parent's space */
+ rest: Vec;
+ /** which way the middle joint bends at rest (elbows back, knees forward): a direction in the parent's space */
+ pole: Vec;
+ material: THREE.Material;
+ jointMaterial?: THREE.Material;
+ /** the end (a hand, a foot, a claw), built in its own frame: +y runs along the forearm out of the wrist */
+ end?: (limb: Limb) => THREE.Object3D;
+ /** the point a handle passes through, and the axis it runs along, in the end's frame (default: 1.6 radii out, along x) */
+ gripPoint?: Vec; gripAxis?: Vec;
+ /** "forearm": the end follows the lower bone (hands). "level": it stays level with the parent (feet) */
+ endMode?: "forearm" | "level";
+ /** smoothness of the bones */
+ segments?: number;
+};
+/** Add a two-bone limb. It is posable at once: pose(rig, { limbs: { [name]: { target } } }). */
+export const limb = (rig: Rig, name: string, o: LimbOpts): Limb => {
+ if (rig.limbs[name]) throw new Error(`limb: ${rig.name} already has a limb called "${name}"`);
+ const [L1, L2] = o.lengths, [r1, r2] = typeof o.radius === "number" ? [o.radius, o.radius * 0.9] : o.radius ?? [0.1 * L1, 0.09 * L2];
+ const parent = o.parent ?? rig.hips, seg = o.segments ?? 12;
+ const root = new THREE.Group(); root.name = `${name}.root`; parent.add(root);
+ if (parent === rig.hips) anchor(rig, root, o.at); else root.position.set(...o.at);
+ const bone = (r: number, L: number, nm: string) => { const m = new THREE.Mesh(new THREE.CapsuleGeometry(r, Math.max(1e-4, L - r * 0.2), 4, seg), o.material); m.userData.part = nm; m.castShadow = m.receiveShadow = true; root.add(m); return m; };
+ const upper = bone(r1, L1, `${name}.upper`), lower = bone(r2, L2, `${name}.lower`);
+ const jm = o.jointMaterial ?? o.material;
+ const joints = [r1 * 1.15, r2 * 1.15].map((r, i) => { const m = new THREE.Mesh(new THREE.SphereGeometry(r, seg, Math.max(6, seg >> 1)), jm); m.userData.part = `${name}.${i ? "mid" : "root"}joint`; m.castShadow = m.receiveShadow = true; root.add(m); return m; });
+ const end = new THREE.Group(); end.name = `${name}.end`; root.add(end);
+ const rest = vec(o.rest), pole = vec(o.pole).normalize();
+ const L: Limb = { name, rig, root, upper, lower, joints, end, L1, L2, base: vec(o.at), rest, pole, endMode: o.endMode ?? "forearm",
+ gripPoint: o.gripPoint ? vec(o.gripPoint) : v3(0, r2 * 1.6, 0), gripAxis: (o.gripAxis ? vec(o.gripAxis) : v3(1, 0, 0)).normalize(), solved: { mid: v3(), end: rest.clone(), reached: true, bend: 0 } };
+ if (o.end) { const e = o.end(L); e.traverse((n) => { if ((n as THREE.Mesh).isMesh) { n.userData.part ??= `${name}.end`; n.castShadow = n.receiveShadow = true; } }); end.add(e); }
+ rig.limbs[name] = L;
+ setLimb(L, rest);
+ return L;
+};
+
+const Q = new THREE.Quaternion();
+const restMid = (L: Limb) => { const d = L.rest.clone(), n = d.length() || 1; return d.clone().multiplyScalar(L.L1 / (L.L1 + L.L2)).addScaledVector(L.pole, 0.3 * n); };
+/** Solve a limb so its end sits at `endLocal` (in the limb root's space) and place its meshes. */
+const setLimb = (L: Limb, endLocal: V3, lp: LimbPose = {}, axisLocal?: V3, endQ?: THREE.Quaternion) => {
+ const root = v3(), mid0 = restMid(L).setLength(L.L1), end0 = mid0.clone().add(L.rest.clone().sub(mid0).setLength(L.L2));
+ const pole = lp.pole ? vec(lp.pole).normalize() : L.pole;
+ const s = solveTwoBone(root, mid0, end0, endLocal, pole.clone().multiplyScalar(L.L1 + L.L2));
+ L.solved = s;
+ const put = (m: THREE.Mesh, a: V3, b: V3) => { m.position.copy(a).add(b).multiplyScalar(0.5); m.quaternion.setFromUnitVectors(UP, b.clone().sub(a).normalize()); };
+ put(L.upper, root, s.mid); put(L.lower, s.mid, s.end);
+ L.joints[0].position.copy(root); L.joints[1].position.copy(s.mid);
+ L.end.position.copy(s.end);
+ L.end.quaternion.copy(endQ ?? endFrame(L, s, pole, axisLocal));
+ if (lp.wrist) L.end.quaternion.multiply(Q.setFromEuler(new THREE.Euler(lp.wrist[0], lp.wrist[1], 0, "YXZ")));
+};
+// The end's frame. A hand: +y along the forearm; its grip axis across it, on the side away from the
+// bend (so a fist's handle runs across the knuckles), or turned to a requested axis. A foot: level.
+const endFrame = (L: Limb, s: TwoBone, pole: V3, axisLocal?: V3) => {
+ if (L.endMode === "level") return new THREE.Quaternion();
+ let y = s.end.clone().sub(s.mid).normalize(), x: V3;
+ if (axisLocal && axisLocal.lengthSq() > 1e-10) {
+ // a grip: the axis is honoured exactly and the wrist bends (a handle off the jaw axis clips the jaw)
+ x = axisLocal.clone().normalize(); const yy = y.clone().sub(x.clone().multiplyScalar(y.dot(x)));
+ y = yy.lengthSq() > 1e-10 ? yy.normalize() : v3().crossVectors(x, Math.abs(x.z) < 0.9 ? v3(0, 0, 1) : v3(1, 0, 0)).normalize();
+ } else {
+ x = v3().crossVectors(y, pole);
+ if (x.lengthSq() < 1e-10) x = v3().crossVectors(y, Math.abs(y.z) < 0.9 ? v3(0, 0, 1) : v3(1, 0, 0));
+ x.normalize();
+ }
+ // the declared grip axis sits along end-local gripAxis; build the basis so gripAxis maps to x
+ const z = v3().crossVectors(x, y).normalize(), basis = new THREE.Matrix4().makeBasis(x, y, z), q = new THREE.Quaternion().setFromRotationMatrix(basis);
+ const toAxis = new THREE.Quaternion().setFromUnitVectors(v3(1, 0, 0), L.gripAxis);
+ return q.multiply(toAxis.invert());
+};
+
+// the hand's turn for a grip: grip axis along the handle, fingers pointing from the root joint to it
+const gripTurn = (L: Limb, ptLocal: V3, axisLocal: V3) => {
+ const x = axisLocal.clone().normalize(); let y = ptLocal.clone().sub(x.clone().multiplyScalar(ptLocal.dot(x)));
+ if (y.lengthSq() < 1e-10) y = L.rest.clone().sub(x.clone().multiplyScalar(L.rest.dot(x)));
+ if (y.lengthSq() < 1e-10) y = v3().crossVectors(x, Math.abs(x.z) < 0.9 ? v3(0, 0, 1) : v3(1, 0, 0));
+ y.normalize();
+ const z = v3().crossVectors(x, y).normalize(), q = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(x, y, z));
+ return q.multiply(new THREE.Quaternion().setFromUnitVectors(v3(1, 0, 0), L.gripAxis).invert());
+};
+
+/** A head: a pivot at `at` (in the parent's space, riding the squash) that lookAt and pose.look turn. */
+export const head = (rig: Rig, name: string, o: { parent?: THREE.Object3D; at: Vec; max?: [number, number] }): Head => {
+ const pivot = new THREE.Group(); pivot.name = name; pivot.rotation.order = "YXZ";
+ const parent = o.parent ?? rig.hips; parent.add(pivot);
+ if (parent === rig.hips) anchor(rig, pivot, o.at); else pivot.position.set(...o.at);
+ const h: Head = { name, pivot, max: o.max ?? [1.2, 0.6] };
+ rig.heads[name] = h;
+ return h;
+};
+
+/** Register a pose flag this rig supports. pose() calls apply(rig, value) and throws on any other flag. */
+export const flag = (rig: Rig, name: string, apply: (rig: Rig, value: number, p: Pose) => void) => { rig.flags[name] = apply; };
+
+const HIPS_EULER = new THREE.Euler(0, 0, 0, "YXZ");
+/**
+ * Where the body goes for a pose, as matrices, WITHOUT touching a mesh: root and hips in world
+ * space, and toWorld() for any point in hips space (a shoulder, the chest). Plan a reach or a camera
+ * from it before posing anything (lesson 24: a world-space grip used to cost a whole extra build).
+ */
+export const bodyMatrix = (rig: Rig, p: Pose = {}) => {
+ const root = new THREE.Matrix4().compose(p.at ? vec(p.at) : v3(), new THREE.Quaternion().setFromAxisAngle(UP, p.yaw ?? 0), v3(1, 1, 1));
+ if (rig.root.parent) { rig.root.parent.updateWorldMatrix(true, false); root.premultiply(rig.root.parent.matrixWorld); }
+ HIPS_EULER.set(p.lean ?? 0, p.twist ?? 0, p.tilt ?? 0, "YXZ");
+ const hips = root.clone().multiply(new THREE.Matrix4().compose(v3(0, rig.hipHeight + (p.lift ?? 0), 0), new THREE.Quaternion().setFromEuler(HIPS_EULER), v3(1, 1, 1)));
+ const sq = squashStretch(p.squash ?? 0);
+ return { root, hips, squash: sq, toWorld: (local: Vec | V3, rides = true) => { const q = vec(local); if (rides) q.multiply(sq); return q.applyMatrix4(hips); } };
+};
+
+const LIMB_KEYS = new Set(["target", "offset", "weight", "pole", "grip", "wrist"]);
+const POSE_KEYS = new Set(["at", "yaw", "lift", "lean", "tilt", "twist", "squash", "look", "limbs", "arms", "legs", "flags"]);
+/**
+ * Put the rig in a pose. Every joint is SET (limbs not named go to rest), so the pose depends on
+ * nothing but `p`. Unknown keys, limbs, heads and flags throw: a pose a rig cannot show must say so.
+ */
+export const pose = (rig: Rig, p: Pose = {}) => {
+ for (const k of Object.keys(p)) if (!POSE_KEYS.has(k)) throw new Error(`pose: unknown pose key "${k}" for ${rig.name}`);
+ const limbs: Record<string, LimbPose> = { ...(p.limbs ?? {}) };
+ for (const [grp, m] of [["arms", p.arms], ["legs", p.legs]] as const) for (const [side, lp] of Object.entries(m ?? {})) limbs[`${grp}.${side}`] = lp;
+ for (const [n, lp] of Object.entries(limbs)) {
+ if (!rig.limbs[n]) throw new Error(`pose: ${rig.name} has no limb "${n}" (it has: ${Object.keys(rig.limbs).join(", ") || "none"})`);
+ for (const k of Object.keys(lp)) if (!LIMB_KEYS.has(k)) throw new Error(`pose: unknown limb key "${k}" on ${n}`);
+ }
+ for (const n of Object.keys(p.flags ?? {})) if (!rig.flags[n]) throw new Error(`pose: ${rig.name} has no flag "${n}" (it has: ${Object.keys(rig.flags).join(", ") || "none"}). Build the flag into every variant or leave it out of the pose.`);
+ if (p.look && !Object.keys(rig.heads).length) throw new Error(`pose: ${rig.name} has no head to look with`);
+ if (p.look?.head && !rig.heads[p.look.head]) throw new Error(`pose: ${rig.name} has no head "${p.look.head}"`);
+
+ // the body
+ rig.root.position.copy(p.at ? vec(p.at) : v3()); rig.root.rotation.set(0, p.yaw ?? 0, 0);
+ rig.hips.position.set(0, rig.hipHeight + (p.lift ?? 0), 0); rig.hips.rotation.set(p.lean ?? 0, p.twist ?? 0, p.tilt ?? 0, "YXZ");
+ const sq = squashStretch(p.squash ?? 0); rig.body.scale.copy(sq);
+ for (const a of rig.anchors) a.obj.position.copy(a.base).multiply(sq);
+ for (const h of Object.values(rig.heads)) h.pivot.rotation.set(0, 0, 0);
+ rig.root.updateWorldMatrix(true, true);
+
+ // flags (blink, antenna...) before the look, so a flag may move a head's parent
+ for (const [n, val] of Object.entries(p.flags ?? {})) rig.flags[n](rig, typeof val === "boolean" ? (val ? 1 : 0) : val, p);
+ if (p.look) { const h = rig.heads[p.look.head ?? Object.keys(rig.heads)[0]]; lookAt(h, p.look.target, 0, { weight: p.look.amount ?? 1 }); }
+
+ // limbs, every one of them: rest unless posed
+ for (const L of Object.values(rig.limbs)) {
+ const lp = limbs[L.name] ?? {};
+ L.root.updateWorldMatrix(true, false);
+ const inv = L.root.matrixWorld.clone().invert(), rotInv = new THREE.Quaternion().setFromRotationMatrix(L.root.matrixWorld).invert();
+ const from = L.rest.clone().add(lp.offset ? vec(lp.offset) : v3());
+ let to = from, axisLocal: V3 | undefined, endQ: THREE.Quaternion | undefined;
+ if (lp.grip) {
+ // reachFor: the hand is aimed from the shoulder toward the handle (known BEFORE the solve), so
+ // the wrist is exactly the handle point minus the turned grip offset: one solve, no iteration
+ const pt = lp.grip.point.clone().applyMatrix4(inv); axisLocal = lp.grip.axis.clone().applyQuaternion(rotInv).normalize();
+ endQ = gripTurn(L, pt, axisLocal);
+ if (lp.wrist) endQ.multiply(Q.setFromEuler(new THREE.Euler(lp.wrist[0], lp.wrist[1], 0, "YXZ")));
+ to = pt.clone().sub(L.gripPoint.clone().applyQuaternion(endQ));
+ } else if (lp.target) to = lp.target.clone().applyMatrix4(inv);
+ const w = lp.weight ?? 1;
+ // endQ already carries the wrist; a partial reach turns the hand from the forearm and bends the wrist after
+ setLimb(L, w >= 1 ? to : from.clone().lerp(to, clamp01(w)), endQ && w >= 1 ? { ...lp, wrist: undefined } : lp, axisLocal, endQ && w >= 1 ? endQ : undefined);
+ }
+ rig.root.updateWorldMatrix(true, true);
+ return rig;
+};
+
+/** Every mesh of a rig (or of any object), visible ones only: what the checks sample. */
+export const meshesOf = (o: THREE.Object3D, skip?: (m: THREE.Mesh) => boolean) => { const out: THREE.Mesh[] = []; o.traverseVisible((n) => { const m = n as THREE.Mesh; if (m.isMesh && m.geometry?.attributes?.position && !(skip && skip(m))) out.push(m); }); return out; };
+
+// ---------------------------------------------------------------- holding props
+/** Declare a prop's handle: a segment a..b of radius r in the prop's own space. grip() and the checks read it. */
+export const handle = (prop: THREE.Object3D, a: Vec, b: Vec, r: number) => { prop.userData.handle = { a: vec(a), b: vec(b), r }; return prop; };
+export type Handle = { a: V3; b: V3; r: number };
+export const handleOf = (prop: THREE.Object3D): Handle => { const h = prop.userData.handle as Handle | undefined; if (!h) throw new Error(`grip: prop "${prop.name || prop.type}" has no handle (call handle(prop, a, b, r) when you build it)`); return h; };
+/** The hand's grip point and axis in world space (for a limb, or any object carrying userData.gripPoint/gripAxis). */
+export const gripFrame = (hand: Limb | THREE.Object3D) => {
+ const end = isLimb(hand) ? hand.end : hand, gp = isLimb(hand) ? hand.gripPoint : vec(end.userData.gripPoint ?? [0, 0, 0]), ga = isLimb(hand) ? hand.gripAxis : vec(end.userData.gripAxis ?? [1, 0, 0]);
+ end.updateWorldMatrix(true, false);
+ return { point: end.localToWorld(gp.clone()), axis: ga.clone().transformDirection(end.matrixWorld).normalize(), end };
+};
+export const isLimb = (x: unknown): x is Limb => !!x && typeof x === "object" && "L1" in (x as object) && "end" in (x as object);
+/**
+ * Hold a prop: its handle, at `at` (0..1 along it), sits on the hand's grip point and runs along the
+ * hand's grip axis, through the grip (lesson 37: a handle glued to a palm passes through the hand).
+ * hang: the prop turns about the handle so its +y points up (a lantern, a bucket), then swings by
+ * `swing` radians. Without hang it turns with the hand (a mug, a sword), rolled by `roll`.
+ * Sets the prop's transform in its parent's space; the prop stays wherever it lives in the scene.
+ */
+export const grip = (hand: Limb | THREE.Object3D, prop: THREE.Object3D, at = 0.5, o: { hang?: boolean; swing?: number; roll?: number } = {}) => {
+ const h = handleOf(prop), { point, axis, end } = gripFrame(hand);
+ const ha = h.b.clone().sub(h.a).normalize(), hp = h.a.clone().lerp(h.b, at);
+ let q: THREE.Quaternion;
+ if (o.hang) {
+ q = new THREE.Quaternion().setFromUnitVectors(ha, axis);
+ // roll about the handle until the prop's up is as close to world up as it can get
+ const up = UP.clone().applyQuaternion(q), want = UP.clone().sub(axis.clone().multiplyScalar(UP.dot(axis)));
+ if (want.lengthSq() > 1e-8) { want.normalize(); const cur = up.sub(axis.clone().multiplyScalar(up.dot(axis))).normalize(); const ang = Math.atan2(v3().crossVectors(cur, want).dot(axis), cur.dot(want)); q.premultiply(new THREE.Quaternion().setFromAxisAngle(axis, ang)); }
+ if (o.swing) q.premultiply(new THREE.Quaternion().setFromAxisAngle(axis, o.swing));
+ } else {
+ const eq = end.getWorldQuaternion(new THREE.Quaternion()), ga = isLimb(hand) ? hand.gripAxis : vec(end.userData.gripAxis ?? [1, 0, 0]);
+ q = eq.multiply(new THREE.Quaternion().setFromUnitVectors(ha, ga.clone().normalize()));
+ if (o.roll) q.premultiply(new THREE.Quaternion().setFromAxisAngle(axis, o.roll));
+ }
+ const pos = point.clone().sub(hp.clone().multiply(prop.getWorldScale(v3())).applyQuaternion(q));
+ const par = prop.parent;
+ if (par) { par.updateWorldMatrix(true, false); const pq = par.getWorldQuaternion(new THREE.Quaternion()).invert(); prop.quaternion.copy(pq.multiply(q)); prop.position.copy(par.worldToLocal(pos)); }
+ else { prop.quaternion.copy(q); prop.position.copy(pos); }
+ prop.updateWorldMatrix(false, true);
+ return { a: prop.localToWorld(h.a.clone()), b: prop.localToWorld(h.b.clone()), point };
+};
+
+// ---------------------------------------------------------------- motion verbs (all closed form)
+/**
+ * Turn a head (or any object whose +z is its face) toward a world point, eased: weight from
+ * tween(f, at, at + dur) when `at` is given, else opts.weight (default 1). Clamped to the head's
+ * max yaw and pitch, so a target behind the character gives a shoulder check, not an owl.
+ */
+export const lookAt = (h: Head | THREE.Object3D, target: V3, f: number, o: { at?: number; dur?: number; ease?: Ease; weight?: number; from?: [number, number]; max?: [number, number] } = {}) => {
+ const obj = "pivot" in h ? h.pivot : h, max = o.max ?? ("pivot" in h ? h.max : [1.2, 0.6]);
+ const par = obj.parent; if (par) par.updateWorldMatrix(true, false);
+ const t = par ? par.worldToLocal(target.clone()) : target.clone(); t.sub(obj.position);
+ let yaw = Math.atan2(t.x, t.z), pitch = -Math.atan2(t.y, Math.hypot(t.x, t.z));
+ yaw = Math.max(-max[0], Math.min(max[0], yaw)); pitch = Math.max(-max[1], Math.min(max[1], pitch));
+ const w = o.at !== undefined ? (o.ease ?? ease.inOutCubic)(seg(f, o.at, o.at + (o.dur ?? 12))) : clamp01(o.weight ?? 1);
+ const [y0, p0] = o.from ?? [0, 0];
+ obj.rotation.order = "YXZ"; obj.rotation.set(lerp(p0, pitch, w), lerp(y0, yaw, w), 0);
+ obj.updateWorldMatrix(false, true);
+ return { yaw: lerp(y0, yaw, w), pitch: lerp(p0, pitch, w), weight: w };
+};
+
+export type Kick = { at: number; amp: number; freq?: number; damping?: number; held?: number };
+/**
+ * Secondary motion: the sum of springs kicked at each event (a stop, a lift, a hop). Before its kick
+ * an event contributes amp x held (a lag held while moving, 0 by default); from the kick on it rings
+ * down from amp to 0. Closed form (time.ts spring): frame 300 never needs frames 0-299.
+ */
+export const followThrough = (f: number, fps: number, kicks: Kick[]) => {
+ let s = 0;
+ for (const k of kicks) s += k.amp * (f < k.at ? (k.held ?? 0) : spring(f, k.at, fps, k.freq, k.damping));
+ return s;
+};
+
+/** Volume-preserving squash (s < 0) or stretch (s > 0) as a scale: y = 1 + s, x = z = 1 / sqrt(1 + s). */
+export const squashStretch = (s: number) => { const y = 1 + Math.max(-0.9, s), xz = 1 / Math.sqrt(y); return v3(xz, y, xz); };
+
+/**
+ * Anticipation: a move from `at` to `at + dur` that first goes the other way. Returns progress in
+ * [-amount, 1]: easing down to -amount over the `lead` frames before `at`, then over to 1. Multiply
+ * a move vector by it (a wind-up before a reach, a crouch before a hop).
+ */
+export const anticipate = (f: number, o: { at: number; dur: number; lead?: number; amount?: number; ease?: Ease }) => {
+ const lead = o.lead ?? Math.max(1, Math.round(o.dur * 0.5)), amt = o.amount ?? 0.15;
+ if (f < o.at) return -amt * ease.inOutSine(seg(f, o.at - lead, o.at));
+ return lerp(-amt, 1, (o.ease ?? ease.inOutCubic)(seg(f, o.at, o.at + o.dur)));
+};
+
+export type WalkOpts = {
+ fps?: number;
+ /** full cycles (two steps for a biped) per second, when the walk runs on the frame */
+ cadence?: number;
+ /** distance travelled: when given, the phase is distance / stride, so planted feet never slide at any speed, eases and stops included */
+ distance?: number;
+ /** distance the body travels in one full cycle */
+ stride?: number;
+ /** body bob: the hips dip this far at each contact */
+ bob?: number;
+ /** fraction of the cycle a foot is planted (0.6 walks, under 0.5 runs) */
+ stance?: number;
+ /** how high a swinging foot lifts */
+ lift?: number;
+ /** side sway of the hips over the planted foot */
+ sway?: number;
+ /** arm counter-swing amplitude (the arms[] values are -1..1 times this) */
+ armSwing?: number;
+ /** phase offset of each foot (biped [0, 0.5]; a quadruped walk [0, 0.5, 0.25, 0.75]) */
+ offsets?: number[];
+ /** 0..1: blends every output toward standing still (a start or a stop) */
+ moving?: number;
+};
+export type WalkFoot = { u: number; stance: boolean; fwd: number; lift: number };
+export type Walk = { phase: number; feet: WalkFoot[]; bob: number; sway: number; twist: number; arms: number[] };
+/**
+ * A walk, as numbers: per foot its place along the travel relative to the hips (fwd) and its lift,
+ * the hip bob, sway and twist, and each foot's arm counter-swing (arms[i] swings against foot i:
+ * forward while that foot is back). Periodic in the phase. Feet are planted for `stance` of the cycle
+ * and travel back under the body exactly as fast as the body moves, so with `distance` they stick.
+ */
+export const walkCycle = (f: number, o: WalkOpts = {}): Walk => {
+ const stride = o.stride ?? 1, S = o.stance ?? 0.6, mv = clamp01(o.moving ?? 1), offs = o.offsets ?? [0, 0.5];
+ const phase = o.distance !== undefined ? o.distance / stride : (f / (o.fps ?? 24)) * (o.cadence ?? 1);
+ const frac = (x: number) => x - Math.floor(x);
+ const feet = offs.map((off): WalkFoot => {
+ const u = frac(phase + off);
+ if (u < S) return { u, stance: true, fwd: mv * stride * (S / 2 - u), lift: 0 };
+ const s = (u - S) / (1 - S), e = s * s * (3 - 2 * s);
+ return { u, stance: false, fwd: mv * stride * lerp(-S / 2, S / 2, e), lift: mv * (o.lift ?? 0.1 * stride) * Math.sin(Math.PI * s) };
+ });
+ const arms = feet.map((ft) => { const u = ft.u, a = u < S ? -Math.cos((Math.PI * u) / S) : Math.cos(Math.PI * ((u - S) / (1 - S))); return mv * (o.armSwing ?? 1) * a; });
+ // hips: lowest at each contact (u = 0 of a foot), highest as the other leg passes (mid stance)
+ const k = offs.length > 2 ? 2 : offs.length;
+ const bob = -mv * (o.bob ?? 0) * (0.5 - 0.5 * Math.cos(2 * Math.PI * k * (phase - S / 2)));
+ const sway = mv * (o.sway ?? 0) * Math.cos(2 * Math.PI * (phase - S / 2));
+ const twist = mv * 0.5 * (feet[0].fwd - (feet[1]?.fwd ?? 0)) / Math.max(1e-6, stride);
+ return { phase, feet, bob, sway, twist, arms };
+};
diff --git a/skills/anidoodle/engine/test/threeChecks.test.ts b/skills/anidoodle/engine/test/threeChecks.test.ts
new file mode 100644
index 0000000..9443b88
--- /dev/null
+++ b/skills/anidoodle/engine/test/threeChecks.test.ts
@@ -0,0 +1,190 @@
+// CHECKS 3D TESTS. Every check in src/three-core/checks3d.ts gets a GREEN scene it must pass and a
+// RED scene (a known fault) it must fail, because a check that has never failed proves nothing
+// (lesson 44). Then the demo film: all 192 frames clean, and two broken variants that must fail.
+// node tools/test.mjs threeChecks
+import * as THREE from "three";
+import { grip, handle, limb, makeRig, part, pose, type Rig } from "../src/three-core/rig";
+import { checkGrip, checking, collectChecks, labelVisible, pathClear, placeLabel, faceCamera, proximity, registerGrip, registerRig, runChecks, screenSizeOk, selfClear, type Finding } from "../src/three-core/checks3d";
+import { rigDemoFrame } from "../src/canvas-core/threeRigDemo";
+
+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+const mat = new THREE.MeshStandardMaterial();
+const ENV = { W: 1920, H: 1080 };
+// a holder: box torso (hips at 1, torso 1.0-1.8), ring hands whose hole runs along the hand's x
+const holder = (name = "h", at = v3()) => {
+ const r = makeRig(name, { hipHeight: 1 });
+ part(r, r.body, "torso", new THREE.Mesh(new THREE.BoxGeometry(0.6, 0.8, 0.4), mat)).position.y = 0.4;
+ for (const [side, s] of [["left", 1], ["right", -1]] as const) limb(r, `arms.${side}`, { at: [0.36 * s, 0.75, 0], lengths: [0.35, 0.35], radius: 0.05, rest: [0.05 * s, -0.65, 0.05], pole: [0.2 * s, 0, -1], material: mat,
+ end: () => { const g = new THREE.Group(); const ring = new THREE.Mesh(new THREE.TorusGeometry(0.06, 0.02, 10, 24), mat); ring.rotation.y = Math.PI / 2; ring.position.y = 0.1; g.add(ring); return g; }, gripPoint: [0, 0.1, 0], gripAxis: [1, 0, 0] });
+ pose(r, { at });
+ return r;
+};
+// a lantern-like prop: a body under a short handle (the handle meshes are marked as handle parts)
+const lantern = (bodyLen = 0.2) => {
+ const p = new THREE.Group(); p.name = "lantern";
+ const body = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.08, bodyLen, 20), mat); body.position.y = 0.2 - bodyLen / 2; body.userData.part = "lantern.body"; p.add(body);
+ const h = new THREE.Mesh(new THREE.CylinderGeometry(0.01, 0.01, 0.08, 10), mat); h.rotation.z = Math.PI / 2; h.position.y = 0.3; h.userData.handlePart = true; p.add(h);
+ handle(p, [-0.04, 0.3, 0], [0.04, 0.3, 0], 0.01);
+ return p;
+};
+const camAt = (pos: THREE.Vector3, look: THREE.Vector3, fov = 35) => { const c = new THREE.PerspectiveCamera(fov, 16 / 9, 0.05, 50); c.position.copy(pos); c.lookAt(look); c.updateMatrixWorld(); c.updateProjectionMatrix(); return c; };
+const kinds = (fs: Finding[]) => new Set(fs.map((f) => f.kind));
+const scene = (...o: THREE.Object3D[]) => { const s = new THREE.Scene(); o.forEach((x) => s.add(x)); s.updateMatrixWorld(true); return s; };
+// pose a holder gripping `prop` at a world point along `axis`, then hang the prop from the hand
+const holding = (h: Rig, prop: THREE.Object3D, point: THREE.Vector3, axis = v3(1, 0, 0)) => { pose(h, { arms: { right: { grip: { point, axis } } } }); grip(h.limbs["arms.right"], prop, 0.5, { hang: true }); };
+
+export const name = "threeChecks";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ // ---- grip
+ {
+ const h = holder(), p = lantern(); scene(h.root, p); const cam = camAt(v3(0.2, 1.6, 3), v3(-0.3, 1.3, 0.3));
+ holding(h, p, v3(-0.45, 1.35, 0.45));
+ const g = checkGrip(h, h.limbs["arms.right"], p, 0, cam);
+ ok(g.ok, `GREEN grip: the handle through the closed hand, the lantern clear of the body, in view (${g.findings.map((x) => x.kind).join(", ") || "no findings"})`);
+ // RED: the prop offset through the hand (the demo's broken variant, in miniature)
+ p.position.add(v3(0, -0.06, 0).applyQuaternion(h.limbs["arms.right"].end.getWorldQuaternion(new THREE.Quaternion()))); p.updateMatrixWorld(true);
+ const t = checkGrip(h, h.limbs["arms.right"], p, 7, cam);
+ ok(kinds(t.findings).has("grip-through-hand") && kinds(t.findings).has("grip-gap") && t.findings[0].frame === 7, `RED prop offset through the hand: ${[...kinds(t.findings)].join(", ")}`);
+ // RED: the prop floating off the hand
+ holding(h, p, v3(-0.45, 1.35, 0.45)); p.position.x -= 0.3; p.updateMatrixWorld(true);
+ const fl = checkGrip(h, h.limbs["arms.right"], p, 0, cam);
+ ok(kinds(fl.findings).has("grip-gap") && kinds(fl.findings).has("grip-open"), `RED prop floating off the hand: ${[...kinds(fl.findings)].join(", ")}`);
+ // closing: the hand is on its way, so a gap is fine but a handle through the hand is not
+ ok(checkGrip(h, h.limbs["arms.right"], p, 0, cam, { closing: true }).ok, "closing: a hand still on its way is not asked to hold yet");
+ }
+ {
+ // RED: a long handle that runs on through the holder's own body
+ const h = holder(), pole = new THREE.Group(); pole.name = "pole"; handle(pole, [0, 0, -0.6], [0, 0, 0.6], 0.015);
+ const m = new THREE.Mesh(new THREE.CylinderGeometry(0.015, 0.015, 1.2, 10), mat); m.rotation.x = Math.PI / 2; m.userData.handlePart = true; pole.add(m); scene(h.root, pole);
+ pose(h, { arms: { right: { grip: { point: v3(-0.2, 1.4, 0.4), axis: v3(0, 0, 1) } } } }); grip(h.limbs["arms.right"], pole, 0.5 + 0.4 / 1.2);
+ const r = checkGrip(h, h.limbs["arms.right"], pole);
+ ok(kinds(r.findings).has("grip-through-holder") && r.findings.some((x) => x.detail.includes("torso")), `RED handle through the holder's body, part named: ${r.findings.map((x) => x.detail).join(" | ")}`);
+ }
+ {
+ // RED: the lantern's body pushed into the holder's belly
+ const h = holder(), p = lantern(0.4); scene(h.root, p);
+ holding(h, p, v3(-0.2, 1.45, 0.27));
+ const r = checkGrip(h, h.limbs["arms.right"], p);
+ ok(kinds(r.findings).has("grip-prop-in-holder"), `RED prop body in the holder: ${r.findings.map((x) => x.where + " " + x.detail).join(" | ")}`);
+ }
+ {
+ // RED: the grip hidden behind something between it and the lens; GREEN once it moves away
+ const h = holder(), p = lantern(), wall = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.4, 0.05), mat); wall.userData.part = "sign";
+ const cam = camAt(v3(-0.45, 1.4, 3), v3(-0.45, 1.3, 0.4)); wall.position.set(-0.45, 1.36, 1.2); scene(h.root, p, wall);
+ holding(h, p, v3(-0.45, 1.35, 0.45));
+ const r = checkGrip(h, h.limbs["arms.right"], p, 0, cam, { others: [wall] });
+ ok(kinds(r.findings).has("grip-hidden") && r.findings.some((x) => x.detail.includes("sign")), `RED grip hidden behind another object, named: ${r.findings.map((x) => x.detail).join(" | ")}`);
+ wall.position.x = 2; wall.updateMatrixWorld();
+ ok(checkGrip(h, h.limbs["arms.right"], p, 0, cam, { others: [wall] }).ok, "GREEN the same grip with the sign moved aside");
+ }
+ {
+ // RED: a long prop in frame whose holding hand is out of frame (reads as dropped, lesson 43)
+ const h = holder(), sword = new THREE.Group(); sword.name = "sword"; handle(sword, [-0.04, 0, 0], [0.04, 0, 0], 0.012);
+ const blade = new THREE.Mesh(new THREE.BoxGeometry(0.04, 2, 0.04), mat); blade.position.y = -1.05; sword.add(blade); scene(h.root, sword);
+ holding(h, sword, v3(-0.45, 1.35, 0.45));
+ const c = new THREE.Box3().setFromObject(sword).getCenter(v3()), cam = camAt(c.clone().add(v3(0, 0, 1.2)), c, 30);
+ const r = checkGrip(h, h.limbs["arms.right"], sword, 0, cam);
+ ok(kinds(r.findings).has("grip-offscreen"), `RED prop in frame, hand out of frame: ${[...kinds(r.findings)].join(", ")}`);
+ const wide = camAt(v3(-0.4, 0.6, 5), v3(-0.4, 0.6, 0), 40);
+ ok(!kinds(checkGrip(h, h.limbs["arms.right"], sword, 0, wide).findings).has("grip-offscreen"), "GREEN a wider lens keeps the hand in frame");
+ }
+
+ // ---- proximity (two rigs)
+ {
+ const a = holder("a"), b = holder("b", v3(2, 0, 0)); scene(a.root, b.root);
+ ok(proximity(a, b).ok, "GREEN two characters 2 units apart");
+ pose(b, { at: v3(0.45, 0, 0.1) });
+ const r = proximity(a, b, [], { frame: 12 });
+ ok(!r.ok && r.findings[0].frame === 12 && /torso|arms/.test(r.findings[0].detail) && /at -?\d/.test(r.findings[0].where), `RED overlapping characters, with the hit centre and parts: ${r.findings[0]?.where} ${r.findings[0]?.detail}`);
+ ok(proximity(a, b, [b.root]).ok, "exempt subtrees are skipped (a held prop, a planned hug)");
+ // lesson 38: boxes of diagonal tubes overlap almost entirely while the tubes are far apart
+ const tube = (x: number, rz: number) => { const m = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.03, 3, 12, 30), mat); m.position.set(x, 0, 0); m.rotation.z = rz; const g = new THREE.Group(); g.add(m); return g; };
+ const t1 = tube(0, Math.PI / 4), t2 = tube(0.7, Math.PI / 4); scene(t1, t2);
+ ok(new THREE.Box3().setFromObject(t1).intersectsBox(new THREE.Box3().setFromObject(t2)) && proximity(t1, t2, [], { tol: 0.05 }).ok, "GREEN two parallel diagonal tubes 0.5 apart: their boxes overlap, the check is not fooled (lesson 38)");
+ const t3 = tube(0, -Math.PI / 4); scene(t1, t3);
+ ok(!proximity(t1, t3, [], { tol: 0.05, minPoints: 3 }).ok, "RED two crossing tubes touch where they cross");
+ // a small part sunk wholly inside a big one touches no surface point; the inside test finds it
+ const big = new THREE.Group(), small = new THREE.Group(); big.add(new THREE.Mesh(new THREE.SphereGeometry(0.5, 24, 16), mat)); small.add(new THREE.Mesh(new THREE.SphereGeometry(0.08, 12, 8), mat)); scene(big, small);
+ const deep = proximity(big, small, [], { tol: 0.02 });
+ ok(!deep.ok && deep.findings[0].detail.includes("inside"), `RED a hand sunk wholly inside a body: ${deep.findings[0]?.detail}`);
+ ok(proximity(big, small, [], { tol: 0.02, deep: false }).ok, "(and without the inside test it would have passed: why the test exists)");
+ small.visible = false; ok(proximity(big, small, [], { tol: 0.02 }).ok, "hidden objects never collide (a switched-off jar, lesson 38)");
+ }
+
+ // ---- selfClear (an arm through its own body)
+ {
+ const h = holder(); scene(h.root);
+ ok(selfClear(h).ok, "GREEN arms at rest beside the body");
+ pose(h, { arms: { right: { target: v3(0.05, 1.35, 0) } } });
+ const r = selfClear(h, { frame: 3 });
+ ok(!r.ok && r.findings[0].kind === "self" && r.findings[0].where.includes("arms.right"), `RED a hand driven into its own torso: ${r.findings[0]?.where}`);
+ }
+
+ // ---- pathClear (walking through a closed prop, lesson 22)
+ {
+ const gate = new THREE.Box3(v3(-0.1, 0, -1), v3(0.1, 1.2, 1));
+ const through = { name: "walker", at: (f: number) => v3(-2 + f * 0.1, 0, 0), from: 0, to: 40, radius: 0.25, height: 1.5 };
+ const r = pathClear(through, [{ name: "gate", box: gate }]);
+ ok(!r.ok && r.findings.length === 1 && r.findings[0].frame === 17 && r.findings[0].detail.startsWith("frames 17-23"), `RED a walk through a closed gate, one finding per run of frames: ${r.findings[0]?.detail}`);
+ ok(pathClear(through, [{ name: "gate", box: gate, open: true }]).ok, "GREEN the same walk through the gate once it is open");
+ ok(pathClear({ ...through, at: (f) => v3(-2 + f * 0.1, 0, 1.4) }, [{ name: "gate", box: gate }]).ok, "GREEN a walk that passes beside it");
+ ok(pathClear({ ...through, at: (f) => v3(-2 + f * 0.1, 1.3, 0) }, [{ name: "gate", box: gate }]).ok, "GREEN a flight over it (height counts)");
+ }
+
+ // ---- labels (lesson 42)
+ {
+ const tag = new THREE.Mesh(new THREE.PlaneGeometry(0.4, 0.2), mat); tag.position.set(0, 1, 0); const label = { obj: tag, w: 0.4, h: 0.2, name: "tag" };
+ const claw = new THREE.Group(); const cm = new THREE.Mesh(new THREE.BoxGeometry(0.15, 0.15, 0.05), mat); cm.userData.part = "claw"; claw.add(cm); claw.position.set(0.1, 1, 0.5);
+ scene(tag, claw); const cam = camAt(v3(0, 1, 3), v3(0, 1, 0));
+ claw.position.x = 3; claw.updateMatrixWorld(true);
+ ok(labelVisible(label, cam, [claw]).ok, "GREEN a label facing the lens with nothing in front");
+ claw.position.x = 0.1; claw.updateMatrixWorld(true);
+ const hid = labelVisible(label, cam, [claw], 4);
+ ok(kinds(hid.findings).has("label-hidden") && hid.findings[0].detail.includes("claw"), `RED a claw covering part of the label: ${hid.findings[0]?.detail}`);
+ tag.rotation.y = Math.PI; tag.updateMatrixWorld(true); claw.position.x = 3; claw.updateMatrixWorld(true);
+ ok(kinds(labelVisible(label, cam, [claw]).findings).has("label-turned"), "RED a label turned away from the lens");
+ faceCamera(tag, cam); ok(labelVisible(label, cam, [claw]).ok, "faceCamera turns it back to read");
+ tag.position.x = 3; tag.updateMatrixWorld(true);
+ ok(kinds(labelVisible(label, cam, []).findings).has("label-offscreen"), "RED a label out of frame");
+ // after the camera: slide along until it reads
+ claw.position.set(0.1, 1, 0.5); claw.updateMatrixWorld(true);
+ const tries = [0, 0.1, -0.5].map((dx) => (o: THREE.Object3D) => { o.position.set(dx, 1, 0); faceCamera(o, cam); });
+ const pl = placeLabel(label, cam, [claw], tries);
+ ok(pl.ok && pl.pick === 2, `placeLabel slides the label until no claw covers it (picked try ${pl.pick})`);
+ const none = placeLabel(label, cam, [claw], [tries[0]]);
+ ok(!none.ok && none.pick === -1, "and says so when no try reads");
+ }
+
+ // ---- screen size (lesson 25)
+ {
+ const cam = camAt(v3(0, 0, 3), v3(0, 0, 0), 30);
+ const ball = (r: number) => { const g = new THREE.Group(); g.name = "hand"; g.add(new THREE.Mesh(new THREE.SphereGeometry(r, 16, 12), mat)); scene(g); return g; };
+ const small = screenSizeOk(ball(0.02), cam, ENV, 40), big = screenSizeOk(ball(0.05), cam, ENV, 40);
+ ok(!small.ok && small.px > 20 && small.px < 34, `RED a contact beat ${small.px.toFixed(0)} px tall at 1080p`);
+ ok(big.ok && big.px > 55, `GREEN the same beat ${big.px.toFixed(0)} px tall`);
+ ok(Math.abs(screenSizeOk(ball(0.05), cam, { W: 3840, H: 2160 }, 40).px - big.px) < 1e-6, "sizes are read at 1080 lines whatever the film's resolution");
+ }
+
+ // ---- the registry: per frame, collected, never carried over
+ {
+ ok(!checking(), "no collector: checking() is false and draws skip the checks");
+ const h = holder(), p = lantern(); scene(h.root, p); const cam = camAt(v3(0.2, 1.6, 3), v3(-0.3, 1.3, 0.3));
+ holding(h, p, v3(-0.45, 1.35, 0.45)); p.position.x -= 0.3; p.updateMatrixWorld(true);
+ const got = collectChecks(() => { registerRig("h", h); registerRig("lantern", p); registerGrip(h, h.limbs["arms.right"], p); runChecks(42, cam, ENV); });
+ ok(got.length > 0 && got.every((x) => x.frame === 42) && got.some((x) => x.kind === "grip-gap"), `collectChecks receives the frame's findings (${got.length}, all on frame 42)`);
+ ok(!checking() && runChecks(43, cam, ENV).ok, "the registry is cleared after a run: the next frame starts empty");
+ }
+
+ // ---- the demo film: every frame clean; two broken variants that must fail
+ {
+ const env = () => ({ W: 1920, H: 1080, scale: 1, cache: new Map(), canvas: () => { throw new Error("no canvas in a unit test"); } }) as never;
+ const e = env(), all: Finding[] = [];
+ for (let f = 0; f < 192; f++) { const s = rigDemoFrame(e, f); all.push(...runChecks(f, s.cam, ENV).findings); }
+ ok(all.length === 0, `threeRigDemo: all 192 frames pass every check (${all.length} findings${all.length ? ": " + all.slice(0, 3).map((x) => `${x.frame} ${x.kind} ${x.detail}`).join(" | ") : ""})`);
+ const off: Finding[] = []; for (let f = 120; f < 192; f += 4) { const s = rigDemoFrame(e, f, "offset"); off.push(...runChecks(f, s.cam, ENV).findings); }
+ const offF = new Set(off.map((x) => x.frame)), held = Array.from({ length: 18 }, (_, i) => 120 + i * 4).filter((f) => f >= 126);
+ ok(kinds(off).has("grip-through-hand") && held.every((f) => offF.has(f)) && ![120, 124].some((f) => offF.has(f)), `RED threeRigDemo "offset" (lantern shifted through the jaws): fails on every held frame, not before (${[...kinds(off)].join(", ")})`);
+ const path: Finding[] = []; for (let f = 60; f < 100; f += 4) { const s = rigDemoFrame(e, f, "path"); path.push(...runChecks(f, s.cam, ENV).findings); }
+ ok(path.some((x) => x.kind === "path" && x.where.includes("crate")) && path.filter((x) => x.kind === "path").every((x) => x.frame >= 60), `RED threeRigDemo "path" (stops 0.18 further on): walks into the crate (${path.filter((x) => x.kind === "path").map((x) => x.frame).join(",")})`);
+ }
+};
diff --git a/skills/anidoodle/engine/test/threeRig.test.ts b/skills/anidoodle/engine/test/threeRig.test.ts
new file mode 100644
index 0000000..d2f4c89
--- /dev/null
+++ b/skills/anidoodle/engine/test/threeRig.test.ts
@@ -0,0 +1,165 @@
+// RIG TESTS. src/three-core/rig.ts: the IK is exact where it can be and sensible where it cannot,
+// a pose reaches its world targets in one pass, unknown pose flags throw on every variant, the walk
+// is periodic with planted feet, the motion verbs are closed form, and the demo film poses the same
+// frame whatever order frames are asked in. node tools/test.mjs threeRig
+import * as THREE from "three";
+import { rand } from "../src/three-core/stage";
+import { spring } from "../src/three-core/time";
+import { anticipate, bodyMatrix, flag, followThrough, grip, gripFrame, handle, head, limb, lookAt, makeRig, part, pose, solveTwoBone, squashStretch, walkCycle } from "../src/three-core/rig";
+import { rigDemoFrame } from "../src/canvas-core/threeRigDemo";
+
+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+const mat = new THREE.MeshStandardMaterial();
+// a small test character: a box torso, two arms with ring hands, a head, optional antenna
+export const testRig = (name = "t", o: { antenna?: boolean } = {}) => {
+ const r = makeRig(name, { hipHeight: 1 });
+ part(r, r.body, "torso", new THREE.Mesh(new THREE.BoxGeometry(0.6, 0.8, 0.4), mat)).position.y = 0.4;
+ for (const [side, s] of [["left", 1], ["right", -1]] as const) limb(r, `arms.${side}`, { at: [0.36 * s, 0.75, 0], lengths: [0.35, 0.35], radius: 0.05, rest: [0.05 * s, -0.65, 0.05], pole: [0.2 * s, 0, -1], material: mat,
+ end: () => { const g = new THREE.Group(); const ring = new THREE.Mesh(new THREE.TorusGeometry(0.06, 0.02, 10, 24), mat); ring.rotation.y = Math.PI / 2; ring.position.y = 0.1; g.add(ring); return g; }, gripPoint: [0, 0.1, 0], gripAxis: [1, 0, 0] });
+ const h = head(r, "head", { at: [0, 0.85, 0], max: [1.0, 0.5] });
+ part(r, h.pivot, "skull", new THREE.Mesh(new THREE.SphereGeometry(0.2, 16, 12), mat)).position.y = 0.2;
+ if (o.antenna) { const a = new THREE.Group(); h.pivot.add(a); flag(r, "antenna", (_r, v) => a.rotation.set(v, 0, 0)); }
+ return r;
+};
+
+export const name = "threeRig";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const R = rand(7), rv = (s = 1) => v3((R() * 2 - 1) * s, (R() * 2 - 1) * s, (R() * 2 - 1) * s);
+
+ // ---- 1. two-bone IK
+ let worst = 0, lenErr = 0, poleBad = 0;
+ for (let i = 0; i < 400; i++) {
+ const root = rv(2), L1 = 0.2 + R(), L2 = 0.2 + R(), dir = rv().normalize(), D = Math.abs(L1 - L2) + 0.02 + R() * (L1 + L2 - Math.abs(L1 - L2) - 0.04);
+ const target = root.clone().addScaledVector(dir, D), mid = root.clone().add(v3(L1, 0, 0)), end = mid.clone().add(v3(0, L2, 0)), pole = root.clone().add(rv(3));
+ const s = solveTwoBone(root, mid, end, target, pole);
+ worst = Math.max(worst, s.end.distanceTo(target)); lenErr = Math.max(lenErr, Math.abs(s.mid.distanceTo(root) - L1), Math.abs(s.end.distanceTo(s.mid) - L2));
+ // the elbow is on the pole's side of the root-end line
+ const ax = s.end.clone().sub(root).normalize(), off = (p: THREE.Vector3) => p.clone().sub(root).sub(ax.clone().multiplyScalar(p.clone().sub(root).dot(ax)));
+ if (off(pole).lengthSq() > 1e-6 && off(s.mid).dot(off(pole)) <= 0) poleBad++;
+ }
+ ok(worst < 1e-3, `IK puts the end on 400 reachable targets (worst miss ${worst.toExponential(1)})`);
+ ok(lenErr < 1e-6, `IK keeps both bone lengths (worst ${lenErr.toExponential(1)})`);
+ ok(poleBad === 0, `the middle joint bends toward the pole every time (${poleBad} wrong sides)`);
+ {
+ const root = v3(0, 1, 0), s = solveTwoBone(root, v3(0.4, 1, 0), v3(0.4, 1.5, 0), v3(3, 2, 1), v3(0, 0, -1)), dir = v3(3, 1, 1).normalize();
+ ok(!s.reached && s.end.distanceTo(root.clone().addScaledVector(dir, 0.9)) < 1e-6, "a target out of reach gives a fully extended limb pointing at it");
+ ok(s.mid.distanceTo(root.clone().addScaledVector(dir, 0.4)) < 1e-6 && s.bend < 1e-6, "the out-of-reach limb is straight (no bend at the middle joint)");
+ const c = solveTwoBone(root, v3(0.4, 1, 0), v3(0.4, 1.3, 0), root.clone().add(v3(0.01, 0, 0)), v3(0, 0, 1));
+ ok(!c.reached && Math.abs(c.end.distanceTo(root) - 0.1) < 1e-6, "a target closer than the limb can fold gives the limb folded as far as it goes");
+ }
+
+ // ---- 2. a rig reaches world targets in one pose, from any placement
+ const r = testRig();
+ let miss = 0;
+ for (let i = 0; i < 40; i++) {
+ const at = rv(3).setY(0), yaw = R() * 6.28, lean = (R() - 0.5) * 0.6;
+ const bm = bodyMatrix(r, { at, yaw, lean }), shoulder = bm.toWorld([-0.36, 0.75, 0]);
+ const target = shoulder.clone().add(rv().normalize().multiplyScalar(0.15 + R() * 0.5));
+ pose(r, { at, yaw, lean, arms: { right: { target } } });
+ miss = Math.max(miss, r.limbs["arms.right"].end.getWorldPosition(v3()).distanceTo(target));
+ }
+ ok(miss < 1e-3, `pose.arms.right = { target } puts the hand on a world point at any place, turn and lean (worst ${miss.toExponential(1)})`);
+ {
+ pose(r, { at: [1, 0, 2], yaw: 0.7, lean: 0.2, twist: 0.1 });
+ const bm = bodyMatrix(r, { at: [1, 0, 2], yaw: 0.7, lean: 0.2, twist: 0.1 });
+ const d = bm.hips.elements.reduce((m, x, i) => Math.max(m, Math.abs(x - r.hips.matrixWorld.elements[i])), 0);
+ ok(d < 1e-9, "bodyMatrix gives exactly the hips matrix pose() builds");
+ const before = r.root.position.clone(); bodyMatrix(r, { at: [9, 9, 9] });
+ ok(r.root.position.equals(before), "bodyMatrix touches no mesh (lesson 24: plan a reach without a second build)");
+ const restHand = (() => { pose(r, {}); return r.limbs["arms.left"].end.getWorldPosition(v3()); })();
+ ok(restHand.distanceTo(v3(0.41, 1.1, 0.05)) < 1e-6, "an unposed limb goes to its rest (no value kept from the pose before)");
+ }
+ // reachFor: the GRIP POINT on a handle, along its axis
+ {
+ let gm = 0, ga = 0;
+ for (let i = 0; i < 30; i++) {
+ const at = rv(2).setY(0), yaw = R() * 6.28; const sh = bodyMatrix(r, { at, yaw }).toWorld([-0.36, 0.75, 0]);
+ const point = sh.clone().add(rv().normalize().multiplyScalar(0.25 + R() * 0.3)), axis = rv().normalize();
+ pose(r, { at, yaw, arms: { right: { grip: { point, axis } } } });
+ const g = gripFrame(r.limbs["arms.right"]); gm = Math.max(gm, g.point.distanceTo(point)); ga = Math.max(ga, 1 - Math.abs(g.axis.dot(axis)));
+ }
+ ok(gm < 1e-3, `a grip pose puts the hand's grip point on the handle (worst ${gm.toExponential(1)})`);
+ ok(ga < 1e-6, `and turns the hand so the handle runs along its grip axis (worst 1-cos ${ga.toExponential(1)})`);
+ }
+ // grip(): the handle sits in the hand, along its axis; hang keeps the prop upright
+ {
+ const scene = new THREE.Scene(); scene.add(r.root);
+ const prop = new THREE.Group(); prop.add(new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, 0.3), mat)); handle(prop, [-0.05, 0.3, 0], [0.05, 0.3, 0], 0.01); scene.add(prop);
+ pose(r, { arms: { right: { target: v3(-0.6, 1.3, 0.4) } } });
+ const g = grip(r.limbs["arms.right"], prop, 0.5, { hang: true }), gf = gripFrame(r.limbs["arms.right"]);
+ ok(g.a.clone().lerp(g.b, 0.5).distanceTo(gf.point) < 1e-6 && Math.abs(g.b.clone().sub(g.a).normalize().dot(gf.axis)) > 1 - 1e-9, "grip() puts the handle's middle on the grip point, running along the grip axis");
+ const up = v3(0, 1, 0).applyQuaternion(prop.quaternion), want = v3(0, 1, 0).sub(gf.axis.clone().multiplyScalar(gf.axis.y)).normalize();
+ ok(up.dot(want) > 1 - 1e-9, "hang turns the prop about the handle until its top points as far up as it can");
+ grip(r.limbs["arms.right"], prop, 0.5, { hang: true, swing: 0.3 }); const up2 = v3(0, 1, 0).applyQuaternion(prop.quaternion);
+ ok(Math.abs(up2.angleTo(up) - 0.3) < 1e-6, "swing turns it about the handle by exactly that angle");
+ scene.remove(r.root);
+ }
+
+ // ---- 3. pose flags work on every variant or throw (lesson 32)
+ const plain = testRig("plain"), withAnt = testRig("ant", { antenna: true });
+ const throws = (fn: () => void, has: string) => { try { fn(); return false; } catch (e) { return String(e).includes(has); } };
+ ok(throws(() => pose(plain, { flags: { antenna: 0.3 } }), 'has no flag "antenna"'), "a flag the variant does not have throws, naming it (never silently ignored)");
+ ok(!throws(() => pose(withAnt, { flags: { antenna: 0.3 } }), "antenna"), "the variant that has it takes it");
+ ok(throws(() => pose(plain, { limbs: { "claws.big": { target: v3() } } }), 'no limb "claws.big"'), "a limb the rig does not have throws");
+ ok(throws(() => pose(plain, { arms: { right: { reach: 1 } as never } }), 'unknown limb key "reach"'), "a misspelt limb key throws");
+ ok(throws(() => pose(plain, { leen: 0.2 } as never), 'unknown pose key "leen"'), "a misspelt pose key throws");
+ ok(throws(() => pose(makeRig("headless"), { look: { target: v3() } }), "no head"), "a look on a rig with no head throws");
+ ok(Object.keys(plain.limbs).length === 2 && !!plain.limbs["arms.left"].end, "a rig built with limb() has posable arms from the start (lesson 23)");
+
+ // ---- 4. head turns
+ {
+ const t = testRig("look"); pose(t, {});
+ const h = t.heads.head, tgt = v3(1, 1.85, 1), res = lookAt(h, tgt, 0, {});
+ const fwd = v3(0, 0, 1).transformDirection(h.pivot.matrixWorld), want = tgt.clone().sub(h.pivot.getWorldPosition(v3())).normalize();
+ ok(fwd.dot(want) > 0.9999 && res.weight === 1, "lookAt faces the head at a world point");
+ const half = lookAt(h, tgt, 6, { at: 0, dur: 12, ease: (x) => x });
+ ok(Math.abs(half.weight - 0.5) < 1e-9 && Math.abs(half.yaw - res.yaw / 2) < 1e-9, "eased: half way through its frames it is half way round");
+ const behind = lookAt(h, v3(0, 1.85, -3), 0, {});
+ ok(Math.abs(Math.abs(behind.yaw) - 1.0) < 1e-9, "a target behind is clamped to the head's max turn (a shoulder check, not an owl)");
+ }
+
+ // ---- 5. walk, follow-through, squash, anticipation
+ {
+ let per = 0;
+ for (let f = 0; f < 48; f += 0.7) { const a = walkCycle(f, { fps: 24, cadence: 1.2, stride: 0.6, bob: 0.03, sway: 0.01 }), b = walkCycle(f + 24 / 1.2, { fps: 24, cadence: 1.2, stride: 0.6, bob: 0.03, sway: 0.01 });
+ per = Math.max(per, Math.abs(a.bob - b.bob), Math.abs(a.sway - b.sway), ...a.feet.map((x, i) => Math.abs(x.fwd - b.feet[i].fwd) + Math.abs(x.lift - b.feet[i].lift)), ...a.arms.map((x, i) => Math.abs(x - b.arms[i]))); }
+ ok(per < 1e-9, `walkCycle repeats exactly every cycle (worst ${per.toExponential(1)})`);
+ // planted feet stay put in the world while the body moves at changing speed
+ let slide = 0;
+ for (let i = 0; i < 300; i++) { const d0 = 0.01 * i * (1 + 0.5 * Math.sin(i * 0.1)), d1 = d0 + 0.004, a = walkCycle(0, { distance: d0, stride: 0.5 }), b = walkCycle(0, { distance: d1, stride: 0.5 });
+ a.feet.forEach((ft, k) => { if (ft.stance && b.feet[k].stance && b.feet[k].u > ft.u) slide = Math.max(slide, Math.abs(d0 + ft.fwd - (d1 + b.feet[k].fwd))); }); }
+ ok(slide < 1e-9, `with distance, a planted foot never slides in the world (worst ${slide.toExponential(1)})`);
+ let corr = 0; for (let p = 0; p < 1; p += 0.01) { const w = walkCycle(0, { distance: p, stride: 1 }); corr += w.arms[0] * w.feet[0].fwd; }
+ ok(corr < 0, "each arm swings against its own leg (counter-swing, lesson 10)");
+ const bobs = Array.from({ length: 100 }, (_, i) => walkCycle(0, { distance: i / 100, stride: 1, bob: 0.03 }).bob);
+ ok(Math.abs(Math.min(...bobs) + 0.03) < 1e-3 && Math.max(...bobs) <= 1e-12, "the body bobs down by `bob` at contact and back up as the legs pass");
+ const still = walkCycle(10, { fps: 24, cadence: 1, stride: 0.5, bob: 0.03, moving: 0 });
+ ok(still.feet.every((x) => x.fwd === 0 && x.lift === 0) && still.bob === 0 && still.arms.every((x) => x === 0), "moving 0 is standing still");
+ }
+ {
+ ok(spring(10, 12, 24) === 0 && Math.abs(spring(12, 12, 24) - 1) < 1e-12, "spring: nothing before its kick, the full displacement at it");
+ const late = Array.from({ length: 24 }, (_, i) => Math.abs(spring(12 + 48 + i, 12, 24))), early = Array.from({ length: 24 }, (_, i) => Math.abs(spring(12 + i, 12, 24)));
+ ok(Math.max(...late) < 0.05 * Math.max(...early) && Math.max(...late) < 0.05, `spring decays: 2 s after the kick under 5% (${Math.max(...late).toFixed(4)})`);
+ const ft = (f: number) => followThrough(f, 24, [{ at: 20, amp: 0.3, held: 1 }, { at: 40, amp: -0.1 }]);
+ ok(ft(5) === 0.3 && Math.abs(ft(20) - 0.3) < 1e-12 && Math.abs(ft(200)) < 1e-4, "followThrough holds the lag until the stop, springs through it, settles to rest");
+ ok(Math.abs(ft(45) - (0.3 * spring(45, 20, 24) - 0.1 * spring(45, 40, 24))) < 1e-12, "kicks add up, each from its own frame");
+ let vol = 0; for (const s of [-0.5, -0.2, 0, 0.3, 1]) { const k = squashStretch(s); vol = Math.max(vol, Math.abs(k.x * k.y * k.z - 1)); }
+ ok(vol < 1e-12, "squashStretch keeps the volume");
+ const an = (f: number) => anticipate(f, { at: 20, dur: 10, lead: 6, amount: 0.2 });
+ ok(an(10) === 0 && Math.abs(an(20) + 0.2) < 1e-12 && an(30) === 1 && an(17) < 0 && an(17) > -0.2, "anticipate dips the other way first, then goes all the way");
+ }
+
+ // ---- 6. purity: the demo film poses frame N the same whatever came before
+ {
+ const env = () => ({ W: 1920, H: 1080, scale: 1, cache: new Map(), canvas: () => { throw new Error("no canvas in a unit test"); } }) as never;
+ const print = (s: ReturnType<typeof rigDemoFrame>) => { const out: number[] = []; s.scene.updateMatrixWorld(true); s.scene.traverse((o) => { if ((o as THREE.Mesh).isMesh) out.push(...o.matrixWorld.elements.map((x) => Math.round(x * 1e7))); }); out.push(...s.cam.matrixWorld.elements.map((x) => Math.round(x * 1e7))); return out.join(","); };
+ const frames = [0, 13, 48, 84, 90, 101, 115, 122, 126, 131, 146, 150, 163, 175, 191];
+ const e1 = env(), seq = frames.map((f) => print(rigDemoFrame(e1, f)));
+ const order = [...frames.keys()]; const rr = rand(3); for (let i = order.length - 1; i > 0; i--) { const j = Math.floor(rr() * (i + 1)); [order[i], order[j]] = [order[j], order[i]]; }
+ const e2 = env(), shuffled: string[] = []; for (const i of order) shuffled[i] = print(rigDemoFrame(e2, frames[i]));
+ // and with other frames drawn in between (a chunked render that starts mid-film)
+ const e3 = env(); rigDemoFrame(e3, 140); rigDemoFrame(e3, 20);
+ ok(seq.every((x, i) => x === shuffled[i]), `the demo poses identically in shuffled order (${frames.length} frames, every mesh and the camera)`);
+ ok(print(rigDemoFrame(e3, 126)) === seq[frames.indexOf(126)], "and after unrelated frames (the grip frame after 140 and 20)");
+ }
+};