Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.
TypeScript agent-skillsanimationcanvasclaude-codeclaude-pluginclaude-skillscodex-plugincreative-codecreative-codingcreative-toolsdeterministicgenerative-arthand-drawnillustrationlaunch-videomotion-designmotion-graphicspluginprocedural-generationskill
machines: explain an idea by building a working machine that plays, comes apart and folds home, drawn in any style; 0.8.0
Alex Greenshpun1dad92060095
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 401aaab..3c64b66 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -13,7 +13,7 @@"name": "anidoodle","source": "./","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.7.2",+ "version": "0.8.0","author": {"name": "Alex Greenshpun","url": "https://linkedin.com/in/alexgreensh"diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex a7fc0c1..5d8d2bb 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"name": "anidoodle","displayName": "anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.7.2",+ "version": "0.8.0","icon": "./assets/icon.png","author": {"name": "Alex Greenshpun",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 2541ac0..4012701 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "anidoodle",- "version": "0.7.2",+ "version": "0.8.0","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.","skills": "./skills/","interface": {diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.jsonindex ee68e6b..f3b566c 100644--- a/.grok-plugin/marketplace.json+++ b/.grok-plugin/marketplace.json@@ -10,7 +10,7 @@"name": "anidoodle","source": "./plugins/anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.7.2",+ "version": "0.8.0","author": {"name": "Alex Greenshpun","url": "https://linkedin.com/in/alexgreensh"diff --git a/README.es-ES.md b/README.es-ES.mdindex 5fcbf73..bdc3d34 100644--- a/README.es-ES.md+++ b/README.es-ES.md@@ -156,7 +156,7 @@ Pregunta cómo dibujar algo, o trae un dibujo, y anidoodle lo reconstruye como l| Para | Obtienes ||---|---|| **Tu web** | Una ilustración de cabecera, ilustraciones para cada funcionalidad, estados vacíos y un 404, todo de la misma mano. PNG transparentes a cualquier tamaño desde una sola fuente, así que retina e impresión salen gratis. |-| **Explicativos e informes** | Diagramas de cómo funciona, vistas en sección e infografías animadas, rotuladas con letras trazadas a mano. La tiza, el plano técnico y el bolígrafo van bien para los más serios. |+| **Explicativos e informes** | Diagramas de cómo funciona, vistas en sección e infografías animadas, rotuladas con letras trazadas a mano. La tiza, el plano técnico y el bolígrafo van bien para los más serios. Una idea puede convertirse en una máquina que funciona, se desmonta y vuelve a montarse, dibujada en cualquier estilo. || **Tu marca** | Un logo que se dibuja solo, una secuencia de títulos, una plantilla de tarjeta social que mantiene tu marca en cada publicación. || **Redes y chat** | Loops sin fin, GIFs y stickers animados transparentes, con el tamaño justo para el feed. || **Presentaciones y documentos** | Una familia de ilustraciones de sección desde un solo programa. Una nueva semilla da una imagen hermana en el mismo estilo. |diff --git a/README.fr-FR.md b/README.fr-FR.mdindex 6274c97..1a729da 100644--- a/README.fr-FR.md+++ b/README.fr-FR.md@@ -156,7 +156,7 @@ Demandez comment dessiner quelque chose, ou apportez un de vos dessins, et anido| Pour | Vous obtenez ||---|---|| **Votre site web** | Une illustration d'en-tête, des vignettes pour chaque fonctionnalité, des états vides et une page 404, tout de la même main. Des PNG transparents à toute taille depuis une seule source, donc les écrans Retina et l'impression sont couverts d'office. |-| **Explications et rapports** | Des schémas de fonctionnement, des vues en coupe et des infographies animées, légendés en lettrage technique. La craie, le plan technique et le stylo bille conviennent aux sujets sérieux. |+| **Explications et rapports** | Des schémas de fonctionnement, des vues en coupe et des infographies animées, légendés en lettrage technique. La craie, le plan technique et le stylo bille conviennent aux sujets sérieux. Une idée peut devenir une machine qui fonctionne, se démonte et se remonte, dessinée dans n'importe quel style. || **Votre marque** | Un logo qui se dessine tout seul, un générique, un gabarit de carte sociale qui reste fidèle à votre marque à chaque publication. || **Réseaux sociaux et messagerie** | Des boucles infinies, des GIF et des stickers animés transparents, aux bonnes dimensions pour le fil d'actualité. || **Présentations et documents** | Une famille d'illustrations de section issues d'un seul programme. Une nouvelle graine donne une image sœur dans le même style. |diff --git a/README.ja-JP.md b/README.ja-JP.mdindex 26b3d19..627ad3d 100644--- a/README.ja-JP.md+++ b/README.ja-JP.md@@ -156,7 +156,7 @@ https://github.com/user-attachments/assets/1cf7f75c-b040-4c00-bf0c-cf1885f8b8da| 用途 | できること ||---|---|| **あなたのウェブサイト** | ヒーローイラスト、各機能のスポットアート、空状態や404ページまで、すべて同じ手で。透過PNGは元データから好きなサイズで書き出せるので、Retina対応も印刷用も追加コストなしで手に入る。 |-| **説明資料やレポート** | 仕組み図、断面図、アニメーション付きインフォグラフィックを、手描き風のレタリングでラベル付けして。黒板、設計図、ボールペンのスタイルは真面目な内容にぴったり。 |+| **説明資料やレポート** | 仕組み図、断面図、アニメーション付きインフォグラフィックを、手描き風のレタリングでラベル付けして。黒板、設計図、ボールペンのスタイルは真面目な内容にぴったり。アイデアを、動いて、分解して、また組み上がる機械として、好きなスタイルで描けます。 || **ブランド表現** | 自ら描き上がっていくロゴ、タイトルシークエンス、どの投稿でもブランドを保てるソーシャルカードのテンプレート。 || **SNSやチャット** | 終わりのないループ、GIF、透過背景のアニメーションスタンプを、フィードに合わせたサイズで。 || **資料やドキュメント** | ひとつのプログラムから生まれる、章ごとのイラストのファミリー。シード値を変えるだけで、同じスタイルの姉妹画像が手に入る。 |diff --git a/README.ko-KR.md b/README.ko-KR.mdindex 9dfc556..7812ed0 100644--- a/README.ko-KR.md+++ b/README.ko-KR.md@@ -156,7 +156,7 @@ https://github.com/user-attachments/assets/1cf7f75c-b040-4c00-bf0c-cf1885f8b8da| 용도 | 받게 되는 것 ||---|---|| **웹사이트** | 히어로 일러스트, 기능마다 들어갈 스팟 아트, 빈 상태 화면과 404 페이지까지 전부 한 손에서 나온 그림으로. 하나의 소스에서 어떤 크기로든 투명 배경 PNG를 뽑아내니, 레티나 디스플레이와 인쇄용 해상도가 그냥 따라와요. |-| **설명 자료와 보고서** | 작동 원리를 보여주는 다이어그램, 단면도, 애니메이션 인포그래픽에 손글씨 느낌의 라벨까지. 진지한 내용에는 칠판, 청사진, 볼펜 스타일이 잘 어울려요. |+| **설명 자료와 보고서** | 작동 원리를 보여주는 다이어그램, 단면도, 애니메이션 인포그래픽에 손글씨 느낌의 라벨까지. 진지한 내용에는 칠판, 청사진, 볼펜 스타일이 잘 어울려요. 아이디어를 작동하고, 스스로 분해됐다가 다시 조립되는 기계로, 어떤 스타일로든 그릴 수 있어요. || **브랜드** | 스스로 그려지는 로고, 타이틀 시퀀스, 게시물마다 브랜드를 지켜주는 소셜 카드 템플릿. || **소셜과 채팅** | 끊임없이 반복되는 루프, GIF, 투명 배경 애니메이션 스티커까지, 피드에 맞는 크기로. || **덱과 문서** | 하나의 프로그램에서 나온 한 세트의 섹션 일러스트. 시드값만 바꾸면 같은 스타일의 자매 이미지가 나와요. |diff --git a/README.md b/README.mdindex e98e0c8..151355d 100644--- a/README.md+++ b/README.md@@ -163,7 +163,7 @@ Ask how to draw something, or bring a drawing, and anidoodle rebuilds it as a le| For | You get ||---|---|| **Your website** | A hero illustration, spot art for each feature, empty states and a 404, all in one hand. Transparent PNGs at any size from one source, so retina and print come free. |-| **Explainers and reports** | How-it-works diagrams, cutaways and animated infographics, labelled in drafted lettering. Chalkboard, blueprint and ballpoint suit the serious ones. |+| **Explainers and reports** | How-it-works diagrams, cutaways and animated infographics, labelled in drafted lettering. Chalkboard, blueprint and ballpoint suit the serious ones. An idea can become a working machine that plays, takes itself apart and folds back, drawn in any style. || **Your brand** | A logo that draws itself on, a title sequence, a social card template that stays on brand for every post. || **Social and chat** | Endless loops, GIFs and transparent animated stickers, sized for the feed. || **Decks and docs** | A family of section illustrations from one program. A new seed gives a sister image in the same style. |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 1248d53..0be25ca 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -156,7 +156,7 @@ https://github.com/user-attachments/assets/1cf7f75c-b040-4c00-bf0c-cf1885f8b8da| 用途 | 你能得到什么 ||---|---|| **官网** | 一张主视觉插画,每个功能点一张点缀小图,空状态和 404 页面,全部出自同一双手。同一份源码可以导出任意尺寸的透明 PNG,视网膜屏和印刷都不在话下。 |-| **说明图和报告** | 原理图、剖视图和动态信息图,配上手绘风格的标注文字。严肃一点的话题,粉笔黑板、蓝图和圆珠笔风格都很合适。 |+| **说明图和报告** | 原理图、剖视图和动态信息图,配上手绘风格的标注文字。严肃一点的话题,粉笔黑板、蓝图和圆珠笔风格都很合适。一个想法也能变成一台会运转、会自己拆开再装回去的机器,用任何风格来画。 || **品牌** | 一个会自己画出来的 Logo,一段片头动画,一套每次发帖都保持品牌调性的社交卡片模板。 || **社交和聊天** | 无限循环的动图、GIF,以及适配信息流尺寸的透明动态贴纸。 || **幻灯片和文档** | 一个程序生成一整套章节插画。换个种子,就能得到风格相同的姊妹图。 |diff --git a/plugins/anidoodle/.claude-plugin/plugin.json b/plugins/anidoodle/.claude-plugin/plugin.jsonindex a7fc0c1..5d8d2bb 100644--- a/plugins/anidoodle/.claude-plugin/plugin.json+++ b/plugins/anidoodle/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"name": "anidoodle","displayName": "anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.7.2",+ "version": "0.8.0","icon": "./assets/icon.png","author": {"name": "Alex Greenshpun",diff --git a/plugins/anidoodle/.codex-plugin/plugin.json b/plugins/anidoodle/.codex-plugin/plugin.jsonindex 2541ac0..4012701 100644--- a/plugins/anidoodle/.codex-plugin/plugin.json+++ b/plugins/anidoodle/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "anidoodle",- "version": "0.7.2",+ "version": "0.8.0","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.","skills": "./skills/","interface": {diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.mdindex 03f2a5b..5b78254 100644--- a/plugins/anidoodle/skills/anidoodle/SKILL.md+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md@@ -35,7 +35,7 @@ say why in one line. Write the answers into a short brief before drawing.| A picture that draws itself (timelapse, making-of) | `references/workflows/drawing-process.md` || A loop, sticker, animated logo, ambient header | Loop workflow below, `references/formats.md` || A story film, any length | Film workflow below, `references/workflows/long-film.md` |-| An explainer or an infographic | `references/workflows/explainer.md` |+| An explainer or infographic; a machine that comes apart to explain an idea, in any style | `references/workflows/explainer.md`, `references/workflows/machines.md` || A launch or product video (their screenshots welcome) | `references/workflows/launch-video.md`; build it on `references/workflows/launch-video-kit.md` || An interactive web animation that reacts to the UI | `references/workflows/interactive.md` || A drawing lesson, or "how do I draw this?" | `references/workflows/teach-drawing.md` |diff --git a/plugins/anidoodle/skills/anidoodle/engine/package.json b/plugins/anidoodle/skills/anidoodle/engine/package.jsonindex 48c833e..a201729 100644--- a/plugins/anidoodle/skills/anidoodle/engine/package.json+++ b/plugins/anidoodle/skills/anidoodle/engine/package.json@@ -1,6 +1,6 @@{"name": "anidoodle-engine",- "version": "0.7.2",+ "version": "0.8.0","private": true,"type": "module","description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/input.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/input.tsindex 1c7a6bc..d20cecd 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/input.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/input.ts@@ -63,6 +63,8 @@ export type Discrete = {export type SpringSpec = {omega: number; // rad per tick. 0.2 settles in ~0.4 s; 0.08 is lazy+ zeta?: number; // damping ratio. Omitted or 1: critically damped, no overshoot. 0.85 to 0.9: lands+ // with one faint overshoot, the weight of a real part (an exploded view, a sprung button)target: (d: Discrete) => number | P; // MUST depend on d only: that is what makes it closed form};export type InputSpec = { springs: Record<string, SpringSpec>; init?: Partial<Pick<Discrete, "state" | "scroll" | "reduced">> };@@ -108,8 +110,15 @@ const apply = (d: Discrete, e: InputEvent) => {type Seg = { t0: number; tgt: number[]; x0: number[]; v0: number[] };const vec = (v: number | P): number[] => (typeof v === "number" ? [v] : [v[0], v[1]]);const unvec = (a: number[]): number | P => (a.length === 1 ? a[0] : [a[0], a[1]]);-const evalSeg = (s: Seg, w: number, t: number): { x: number[]; v: number[] } => {+const evalSeg = (s: Seg, w: number, t: number, z = 1): { x: number[]; v: number[] } => {const dt = t - s.t0; if (dt <= 0) return { x: s.tgt.map((g, i) => g + s.x0[i]), v: s.v0.slice() };+ if (z < 1) { // underdamped, still closed form: x(t) = g + e^(-z w t) (A cos wd t + B sin wd t)+ const wd = w * Math.sqrt(1 - z * z), ex = Math.exp(-z * w * dt), co = Math.cos(wd * dt), si = Math.sin(wd * dt);+ return {+ x: s.tgt.map((g, i) => { const A = s.x0[i], B = (s.v0[i] + z * w * A) / wd; return g + ex * (A * co + B * si); }),+ v: s.tgt.map((_, i) => { const A = s.x0[i], B = (s.v0[i] + z * w * A) / wd; return ex * ((B * wd - z * w * A) * co - (A * wd + z * w * B) * si); }),+ };+ }const e = Math.exp(-w * dt);return {x: s.tgt.map((g, i) => { const c = s.v0[i] + w * s.x0[i]; return g + (s.x0[i] + c * dt) * e; }),@@ -141,7 +150,7 @@ const advance = (spec: InputSpec, log: InputLog, f: Fold, to: number) => {const g = vec(s.target(f.d)), seg = f.segs[k];if (same(g, seg.tgt)) continue; // untouched springs keep their segment: bit-identical either wayif (f.d.reduced) { f.segs[k] = { t0: e.tick, tgt: g, x0: g.map(() => 0), v0: g.map(() => 0) }; continue; } // reduced motion: arrive, do not travel- const { x, v } = evalSeg(seg, s.omega, e.tick); // where it is and how fast, at the interruption+ const { x, v } = evalSeg(seg, s.omega, e.tick, s.zeta); // where it is and how fast, at the interruptionf.segs[k] = { t0: e.tick, tgt: g, x0: x.map((xi, i) => xi - g[i]), v0: v };}f.ref = e; f.idx++;@@ -162,7 +171,7 @@ export const stateAt = (tick: number, log: InputLog, spec: InputSpec): InputStatfor (let b = (k + 1) * CP; b <= t; b += CP) { advance(spec, log, f, b); if (cps.length === b / CP) cps.push(cloneFold(f, b)); }advance(spec, log, f, t);const spring: Record<string, number | P> = {}, vel: Record<string, number | P> = {};- for (const [k2, s] of Object.entries(spec.springs)) { const r = evalSeg(f.segs[k2], s.omega, t); spring[k2] = unvec(r.x); vel[k2] = unvec(r.v); }+ for (const [k2, s] of Object.entries(spec.springs)) { const r = evalSeg(f.segs[k2], s.omega, t, s.zeta); spring[k2] = unvec(r.x); vel[k2] = unvec(r.v); }return { ...f.d, tick: t, attention: attentionOf(f.d), spring, vel };};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanism.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanism.tsnew file mode 100644index 0000000..6293e8c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanism.ts@@ -0,0 +1,285 @@+// MECHANISM · "Fig 1, the 18-note movement". A cylinder music box, drawn as an exploded technical figure.+//+// MEDIUM (physical): technical illustration as it was made for parts manuals and patent plates. A+// technical pen on drafting film: one even inner weight, the silhouette gone over a size heavier.+// Under the film, adhesive grey tone sheets cut with a knife to each face, four greys and a white+// for the tops, picked by which way the face looks at the lamp. One part, the one to watch, gets+// the single colour sheet. Lettering by scriber and template, upright and even.+// MARKS: the ruled line (silhouette, crease, seam), the cut tone shape, the dot (screw, pin), the+// template letter. EDGE: crisp; tone meets tone and a line sits on every outline.+// ORDER (the film): the card's rule -> the bench -> the parts in assembly order, each inked first+// (the pen runs its outlines) and then toned (the sheet laid and cut) -> the lettering -> the+// mechanism runs -> it comes apart into its assemblies and they are read out one by one -> it folds home.+// PALETTE: warm drafting-film white, four cool-to-warm greys per material, one brass sheet.+// LIGHT: one lamp, locked to the viewer, up and to the left: tops white, left faces light, right dark.+// SUBJECT + REALISM: an 18-note cylinder movement of the common Japanese pattern (reference, from+// knowledge: a die-cast zinc bedplate; a brass cylinder about 14 mm across carrying steel pins,+// turned between two bridges by a great wheel; a steel comb of 18 tuned teeth screwed to the plate+// through a heel block, the bass teeth longer and weighted with lead underneath; a spring barrel in a+// housing at one end, wound by a crank; an air-brake governor, a worm and a two-blade fan on a+// vertical arbor, that holds the tempo). The tune on the pins is our own, 32 steps per turn.+// THE POINT: the pins are the score. The drum turning is time; each tooth is a pitch; the readout+// names the pin, the tooth and the note from the same model that places the pins and bends the teeth.+// NOT ITS NEAREST NEIGHBOURS: isometric (flat three-tone planes, no line, a colour night scene) and+// blueprint (white ink on Prussian blue, dimension lines). Here every part is outlined, the tones are+// grey sheets from a camera-locked lamp, the figure sits in a card, and there are no dimensions.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import { isometricHand } from "./mechanismHands";+import {+ Cam, V3, P2, Material, Item, prism, box, rrect, circle, turned, cyl, sphere, frameAlong, at, facingAt, screw, slab, leverRing, tubeAlong, stroke, fill,+ paintAll, sharesAt, ExplodePlan, card, smooth, clamp01, add, setReveal, tone, ink, inkDot, knock, Hand, setHand, flatHand, hand, freshPen,+} from "./mechanismKit";++const W = 1080, H = 1080, FPS = 30, N = 310, N_DRAW = 350;+const PAPER = "#f3f0e8", INK = "#232227", SOFT = "#6d6a70", RULE = "#9a968e";+const mat = (name: string, ramp: Material["ramp"], seam: string, pigment: string, accent = false): Material => ({ name, ramp, ink: INK, seam, pigment, accent });+const ZINC = mat("zinc", ["#a9a69f", "#bdbab3", "#cfccc4", "#dedbd3", "#f4f1ea"], "#8a877f", "#8d8b86");+const STEEL = mat("steel", ["#9aa0a6", "#b0b5ba", "#c5c9cd", "#d8dbde", "#f0f2f3"], "#80868c", "#6f86a0");+const PLINTH = mat("wood", ["#b3ada2", "#c4beb3", "#d3cec4", "#e1ddd4", "#f1eee7"], "#948e84", "#a8774c");+const LEAD = mat("lead", ["#6c6d71", "#7e7f83", "#909195", "#a3a4a7", "#c3c4c6"], "#56575b", "#55575e");+const BRASS = mat("brass", ["#a39d8e", "#b6b0a1", "#c8c2b3", "#d8d3c5", "#efebe1"], "#8a8476", "#ab9a72"); // brass, seen in grey (a quiet pigment: only the accent may shout)+const ACCENT = mat("accent", ["#a2652a", "#ba7a37", "#cd904a", "#dda863", "#f2d29c"], "#8a5420", "#d0502a", true); // the part to watch++// ---------------------------------------------------------------- the model: tune, teeth, drum, explode+const TEETH = [48, 50, 52, 53, 55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72, 74, 76, 79]; // MIDI pitch of each tooth, bass first+const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];+const noteName = (m: number) => NAMES[m % 12] + (Math.floor(m / 12) - 1);+const hz = (m: number) => 440 * 2 ** ((m - 69) / 12);+const STEPS = 32;+// our tune, step -> pitches (melody over a walking bass); every pitch must be a tooth+const TUNE: Record<number, number[]> = {+ 0: [48, 72], 2: [76], 4: [60, 79], 6: [76], 7: [74], 8: [55, 72], 10: [74], 12: [59, 71], 14: [67],+ 16: [53, 69], 18: [72], 20: [57, 76], 22: [74], 23: [72], 24: [55, 71], 26: [74], 28: [48, 64, 72], 30: [60],+};+const PINS = Object.entries(TUNE).flatMap(([s, ms]) => ms.map((m) => ({ step: +s, tooth: TEETH.indexOf(m) }))).sort((a, b) => a.step - b.step || a.tooth - b.tooth);+if (PINS.some((p) => p.tooth < 0)) throw new Error("mechanism: a pin asks for a pitch no tooth plays");+const DSTEP = (2 * Math.PI) / STEPS;+const DRUM = { o: [12.5, 17.5, 16.2] as V3, len: 34, r: 7, pin: 0.9 };+const TH_C = Math.atan2(-7.8, 1.5); // where a pin meets a tooth tip, in the drum's frame (u = +y, v = +z)+const toothX = (j: number) => 13.1 + j * 1.83;+const toothRoot = (j: number) => 29.8 - (j / 17) * 5;+const TIP = 19;++const PLAN: ExplodePlan = { order: ["governor", "crank", "housing", "screws", "comb", "bridgeL", "bridgeR", "drum"], stagger: 0.07, w: 8, z: 0.89 };+const MOVE: Record<string, V3> = { governor: [30, 0, 30], crank: [42, 0, 8], housing: [30, 0, 8], screws: [0, 13, 24], comb: [0, 13, 9], bridgeL: [-13, 0, 0], bridgeR: [10, 0, 0], drum: [0, 0, 24] };+const ABOUT: Record<string, string> = {+ governor: "AIR BRAKE · HOLDS THE TEMPO", crank: "CRANK · WINDS THE SPRING", housing: "SPRING BARREL · THE MOTOR", screws: "SCREWS · HOLD THE COMB DOWN",+ comb: "COMB · 18 TUNED TEETH", bridgeL: "BRIDGE · CARRIES THE DRUM", bridgeR: "BRIDGE · CARRIES THE DRUM", drum: "DRUM · THE PINS ARE THE SCORE",+};++// the film's timeline (frames)+// two films: the making (rule, build, words) and the run (play, apart, tour, home, play)+const T = { rule: [0, 12], build: [12, 318], text: [318, 350], play: 0, apart: 106, tour: [146, 234], home: 234, end: N } as const;+const CUES = [{ t: T.apart / FPS, apart: true }, { t: T.home / FPS, apart: false }];+const REV = 9.6; // seconds per drum turn: 0.3 s a step+/** drum angle: it turns while the movement is whole and playing */+const rotAt = (f: number) => { const run = (a: number, b: number) => Math.max(0, Math.min(f, b) - a); const fr = run(T.play, T.apart) + run(T.home + 30, N); return (fr / FPS / REV) * 2 * Math.PI; };+export type State = { rot: number; shares: Record<string, number>; lit: string; read: string; bend: number[]; fan: number; crank: number };+/** what the drum is doing at angle rot: how far each tooth bends, and which pin last spoke. One model for pins, teeth and words. */+export const play = (rot: number, quiet = 0) => {+ const bend = TEETH.map(() => 0), turn = rot % (2 * Math.PI); let last = -1;+ PINS.forEach((p, k) => {+ const ahead = ((p.step * DSTEP - rot) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI); // radians until it reaches the tip+ if (ahead < 0.14) bend[p.tooth] += -0.55 * (1 - ahead / 0.14) * (1 - quiet);+ const since = 2 * Math.PI - ahead; if (rot >= p.step * DSTEP && since < 1.2) { const age = (since / (2 * Math.PI)) * REV; bend[p.tooth] += 0.4 * Math.exp(-age / 0.28) * Math.sin(age * 2 * Math.PI * 6) * (1 - quiet); }+ if (turn >= p.step * DSTEP) last = k;+ });+ if (last < 0 && rot >= 2 * Math.PI) last = PINS.length - 1;+ let read = "WOUND · READY";+ if (last >= 0) { const p = PINS[last], m = TEETH[p.tooth]; read = `PIN ${last + 1} · TOOTH ${p.tooth + 1} · ${noteName(m)} ${Math.round(hz(m))} HZ`; }+ return { bend, read, fan: (turn / (2 * Math.PI)) * 2 * Math.PI * 9, crank: Math.PI * 0.3 + 0.12 * Math.sin(rot) };+};+export const stateAt = (f: number): State => {+ const t = f / FPS, rot = rotAt(f), shares = sharesAt(PLAN, CUES, t), moving = Object.values(shares).some((s) => s > 0.003 && s < 0.997);+ const apart = Object.values(shares).every((s) => s > 0.997), pl = play(rot);+ // apart, the parts float: each breathes a little along its own path of travel, out of step with the others+ const settled = clamp01((f - T.apart) / 40) * (1 - clamp01((f - T.home + 6) / 6));+ if (settled > 0) PLAN.order.forEach((id, i) => { shares[id] += 0.035 * settled * Math.sin((2 * Math.PI * t) / 2.6 + i * 0.9); });+ let lit = "drum", read = pl.read;+ if (moving) read = f < T.home ? "TAKING APART" : "PUTTING BACK";+ if (apart) {+ const k = Math.floor(clamp01((f - T.tour[0]) / (T.tour[1] - T.tour[0])) * PLAN.order.length * 0.9999);+ lit = PLAN.order[f < T.tour[0] ? PLAN.order.length - 1 : k]; read = f < T.tour[0] ? `${PLAN.order.length} ASSEMBLIES APART` : `${PLAN.order.indexOf(lit) + 1}/${PLAN.order.length} · ${ABOUT[lit]}`;+ }+ return { rot, shares, lit, read, bend: pl.bend, fan: pl.fan, crank: pl.crank };+};++// ---------------------------------------------------------------- the parts list+const vane = (psi: number, side: number): P2[] => { const c = Math.cos(psi), s = Math.sin(psi), e = 0.22; const pts: [number, number][] = side > 0 ? [[0.5, -e], [4.6, -e], [4.6, e], [0.5, e]] : [[-4.6, -e], [-0.5, -e], [-0.5, e], [-4.6, e]]; return pts.map(([x, y]) => [60 + x * c - y * s, 12 + x * s + y * c] as P2); };+const bar = (ctx: Ctx, c: Cam, x0: number, x1: number, yR: number, yT: number, z0: number, z1: number, dz: number, m: Material, off: P2) => {+ const P = (x: number, y: number, z: number): P2 => { const s = c.p([x, y, z + (y < yR ? dz * ((yR - y) / (yR - yT)) ** 1.6 : 0)]); return [s[0] + off[0], s[1] + off[1]]; };+ const n = 6, ys = Array.from({ length: n + 1 }, (_, i) => yR + ((yT - yR) * i) / n);+ const side = ys.map((y) => P(x1, y, z0)).concat(ys.map((y) => P(x1, y, z1)).reverse()), top = ys.map((y) => P(x0, y, z1)).concat(ys.map((y) => P(x1, y, z1)).reverse());+ tone(ctx, side, m, 0.8); tone(ctx, top, m, 4);+ ink(ctx, top.concat(side.slice(0, n + 1).reverse()), "in", m);+ ink(ctx, [...ys.map((y) => P(x0, y, z1)), P(x0, yT, z0 + 0.0001), ...ys.slice().reverse().map((y) => P(x1, y, z0))], "in", m);+};++const parts = (c: Cam, s: State): Item[] => {+ const items: Item[] = [];+ const put = (id: string, atp: V3, draw: Item["draw"], ride?: string, bias = 0) => items.push({ id, at: atp, draw, ride, bias });+ const lit = (a: string) => s.lit === a, M = (a: string, base: Material) => (lit(a) ? ACCENT : base);+ // the bench+ put("plinth", [35, 23, -9], (ctx, o) => box(ctx, c, -3, 4.5, -9, 76, 44.5, 6, PLINTH, { r: 3, bevel: 1.2, off: o }), undefined, -100);+ put("ruler", [24, 45, -3], (ctx, o) => box(ctx, c, 1, 43.2, -3, 46, 3.6, 0.35, STEEL, { off: o, inner: (x) => {+ for (let i = 0; i <= 46; i += 1) { const major = i % 10 === 0, mid = i % 5 === 0, L = major ? 2.2 : mid ? 1.5 : 0.9; const a = c.p([1 + i, 43.2, -2.65]), b = c.p([1 + i, 43.2 + L, -2.65]); ink(x, [[a[0] + o[0], a[1] + o[1]], [b[0] + o[0], b[1] + o[1]]], major ? "in" : "hair", STEEL); }+ } }), undefined, -60);+ put("label", [61, 44, -3], (ctx, o) => box(ctx, c, 52, 41.5, -3, 18, 5, 0.4, STEEL, { off: o, inner: (x) => {+ [[0.9, 0.8], [2.2, 0.55], [3.4, 0.7]].forEach(([yy, f]) => { const a = c.p([54, 41.5 + yy, -2.6]), b = c.p([54 + 14 * f, 41.5 + yy, -2.6]); ink(x, [[a[0] + o[0], a[1] + o[1]], [b[0] + o[0], b[1] + o[1]]], "seam", STEEL); });+ } }), undefined, -60);+ ([[0, 8], [70, 8], [70, 46], [0, 46]] as P2[]).forEach(([x, y], i) => put(`pscrew${i}`, [x, y, -3], (ctx, o) => screw(ctx, c, [x, y, -3], [0, 0, 1], 1.1, STEEL, 0.4 + i, o), undefined, -50));+ ([[9, 10], [64, 10], [64, 36], [9, 36]] as P2[]).forEach(([x, y], i) => put(`post${i}`, [x, y, -1.5], (ctx, o) => turned(ctx, c, frameAlong([x, y, -3], [0, 0, 1]), cyl(0, 3, 2.2), ZINC, { off: o }), undefined, -40));+ put("bedplate", [36, 23, 0], (ctx, o) => box(ctx, c, 5, 6, 0, 63, 34, 3.5, ZINC, { r: 2.5, bevel: 0.9, off: o, inner: (q) => {+ ([[7.6, 37.4], [65.4, 37.4], [65.4, 8.6], [32, 24], [40, 24]] as P2[]).forEach(([x, y], i) => { const r = i < 3 ? 1.1 : 1.6; const h = circle(x, y, r, 24).map(([a, b]) => { const p = c.p([a, b, 3.5]); return [p[0] + o[0], p[1] + o[1]] as P2; }); tone(q, h, ZINC, 0.4); ink(q, h, "hair", ZINC, true); });+ } }), undefined, -30);+ // the comb: heel, plate, teeth, lead weights, screws+ put("heel", [29.5, 33.5, 6], (ctx, o) => box(ctx, c, 11.5, 30, 3.5, 36, 7, 5.1, M("comb", STEEL), { r: 0.8, bevel: 0.6, off: o, lit: lit("comb") }), "comb");+ put("plate", [29.5, 27.5, 8], (ctx, o) => prism(ctx, c, [[12, 29.9], [47, 24.6], [47, 30.6], [12, 30.6]], 7.6, 0.8, M("comb", STEEL), { off: o }), "comb", -0.5);+ TEETH.forEach((_, j) => {+ const x0 = toothX(j), yR = toothRoot(j);+ if (j < 5) put(`weight${j}`, [x0 + 0.7, 20.9, 7], (ctx, o) => box(ctx, c, x0 + 0.05, TIP + 0.4, 6.4 + s.bend[j] * 0.7, 1.25, 3, 1.2, LEAD, { off: o }), "comb", -0.3);+ put(`tooth${j}`, [x0 + 0.7, (yR + TIP) / 2, 8], (ctx, o) => bar(ctx, c, x0, x0 + 1.35, yR, TIP, 7.6, 8.4, s.bend[j], M("comb", STEEL), o), "comb", -0.6 + j * 0.001);+ });+ ([[17, 33.5], [42, 33.5]] as P2[]).forEach(([x, y], i) => put(`cscrew${i}`, [x, y, 8.6], (ctx, o) => screw(ctx, c, [x, y, 8.6], [0, 0, 1], 1.5, M("screws", STEEL), 0.9 + i, o), "screws", 1));+ // bridges with their feet and screws+ const bridge = (id: string, x: number, foot: number) => {+ put(`${id}foot`, [foot + 2.4, 17.5, 4.2], (ctx, o) => box(ctx, c, foot, 9.5, 3.5, 5, 16, 1.4, M(id, ZINC), { r: 0.5, off: o, lit: lit(id) }), id, -0.2);+ put(`${id}`, [x + 1.1, 17.5, 12], (ctx, o) => box(ctx, c, x, 11, 4.9, 2.2, 13, 13.4, M(id, ZINC), { r: 0.6, bevel: 0.4, off: o, lit: lit(id), inner: (q) => {+ const hole = circle(17.5, 16.2, 1.6, 20).map(([y, z]) => { const p = c.p([x + 2.2, y, z]); return [p[0] + o[0], p[1] + o[1]] as P2; }); tone(q, hole, ZINC, 1.2); ink(q, hole, "hair", ZINC, true);+ } }), id);+ [10.8, 24.2].forEach((y, i) => put(`${id}s${i}`, [foot + (id === "bridgeL" ? 1 : 3.9), y, 4.9], (ctx, o) => screw(ctx, c, [foot + (id === "bridgeL" ? 1 : 3.9), y, 4.9], [0, 0, 1], 0.9, STEEL, 0.2 + i, o), id, 0.3));+ };+ bridge("bridgeL", 9, 7.6); bridge("bridgeR", 49.6, 48.3);+ // the drum: arbor, cylinder with its pins, the great wheel+ const D = frameAlong(DRUM.o, [1, 0, 0]);+ put("arborL", [10.5, 17.5, 16.2], (ctx, o) => turned(ctx, c, frameAlong([8.4, 17.5, 16.2], [1, 0, 0]), cyl(0, 4.2, 0.85), STEEL, { off: o }), "drum", -0.5);+ put("drum", [29.5, 17.5, 16.2], (ctx, o) => {+ turned(ctx, c, D, cyl(0, DRUM.len, DRUM.r), M("drum", BRASS), { off: o, lit: lit("drum"), rims: [0.8, DRUM.len - 0.8] });+ for (const p of PINS) { // each pin: a short steel stub standing off the surface, fading as the drum turns it away+ const th = TH_C + p.step * DSTEP - s.rot, f = facingAt(c, D, th), a = smooth(0.02, 0.4, f); if (a <= 0.01) continue;+ const sx = toothX(p.tooth) + 0.67 - DRUM.o[0], A = c.p(at(D, sx, DRUM.r - 0.05, th)), B = c.p(at(D, sx, DRUM.r + DRUM.pin, th));+ ink(ctx, [[A[0] + o[0], A[1] + o[1]], [B[0] + o[0], B[1] + o[1]]], "in", STEEL, false, a);+ inkDot(ctx, [B[0] + o[0], B[1] + o[1]], 1.5, STEEL, a);+ }+ }, "drum");+ put("wheel", [48, 17.5, 16.2], (ctx, o) => {+ const G = frameAlong([47.4, 17.5, 16.2], [1, 0, 0]);+ turned(ctx, c, G, cyl(0, 1.2, 9.5), M("drum", BRASS), { off: o, lit: lit("drum") });+ for (let i = 0; i < 64; i++) { const th = (i / 64) * 2 * Math.PI - s.rot, f = facingAt(c, G, th); if (f < 0.02) continue; const A = c.p(at(G, 1.2, 8.6, th)), B = c.p(at(G, 1.2, 9.45, th)); ink(ctx, [[A[0] + o[0], A[1] + o[1]], [B[0] + o[0], B[1] + o[1]]], "seam", BRASS, false, smooth(0.02, 0.4, f)); }+ turned(ctx, c, frameAlong([48.6, 17.5, 16.2], [1, 0, 0]), cyl(0, 0.8, 2.4), M("drum", BRASS), { off: o });+ }, "drum", -3);+ put("arborR", [50.5, 17.5, 16.2], (ctx, o) => turned(ctx, c, frameAlong([49.4, 17.5, 16.2], [1, 0, 0]), cyl(0, 2.6, 0.85), STEEL, { off: o }), "drum", 1.2);+ // the motor: housing, its screws, the crank+ put("housing", [60, 22, 10.7], (ctx, o) => box(ctx, c, 54, 6, 3.5, 12, 32, 14.5, M("housing", ZINC), { r: 2.5, bevel: 0.9, seams: [5.2], off: o, lit: lit("housing") }), "housing");+ ([[56, 8.5], [64, 8.5], [64, 35.5], [56, 35.5]] as P2[]).forEach(([x, y], i) => put(`hscrew${i}`, [x, y, 18], (ctx, o) => screw(ctx, c, [x, y, 18], [0, 0, 1], 0.9, M("housing", STEEL), 1.1 + i, o), "housing", 0.5));+ put("crank", [70, 24, 10], (ctx, o) => {+ tubeAlong(ctx, c, [[66, 22, 10], [69.2, 22, 10]], 0.9, STEEL, { off: o, caps: [false, true] });+ // the lever: a flat steel plate turning in the plane x = 69.2, a boss on the shaft, a turned wooden knob at its end+ const A = frameAlong([69.2, 22, 10], [1, 0, 0]), ang = s.crank, e: V3 = [69.2, 22 + 7 * Math.cos(ang), 10 + 7 * Math.sin(ang)];+ const lv = leverRing(7, 1.6, 1.25).map(([u, v]) => { const cu = Math.cos(ang), su = Math.sin(ang); return [u * cu - v * su, u * su + v * cu] as P2; });+ slab(ctx, c, { ...A, u: [0, 1, 0], v: [0, 0, 1] }, lv, 0.9, M("crank", STEEL), { off: o, lit: lit("crank") });+ turned(ctx, c, frameAlong([70.1, 22, 10], [1, 0, 0]), cyl(0, 0.7, 1.15), M("crank", STEEL), { off: o });+ turned(ctx, c, frameAlong(add(e, [0.9, 0, 0]), [1, 0, 0]), cyl(0, 3.4, 1.35), M("crank", PLINTH), { off: o, lit: lit("crank") });+ turned(ctx, c, frameAlong(add(e, [4.3, 0, 0]), [1, 0, 0]), sphere(0, 0.9, -0.5, 1.45), M("crank", PLINTH), { off: o, caps: [false, false] });+ }, "crank");+ put("stop", [58, 42, 12], (ctx, o) => {+ tubeAlong(ctx, c, [[57.5, 38, 13], [57.5, 42.5, 13], [54.5, 45, 13.8]], 0.45, M("housing", STEEL), { off: o, caps: [false, false] });+ turned(ctx, c, frameAlong([54.5, 45, 12.6], [0, 0, 1]), sphere(0, 2.4, 1.2, 1.2), M("housing", PLINTH), { off: o, caps: [false, false] });+ }, "housing", 0.4);+ // the governor: shaft, worm, fan (two blades, sorted round the shaft), cap+ const G0: V3 = [60, 12, 18];+ put("gshaft", [60, 12, 24], (ctx, o) => {+ turned(ctx, c, frameAlong(G0, [0, 0, 1]), cyl(0, 1.1, 1.9), M("governor", ZINC), { off: o, rims: [0.5] });+ turned(ctx, c, frameAlong(add(G0, [0, 0, 1.1]), [0, 0, 1]), cyl(0, 11.3, 0.55), STEEL, { off: o });+ const F = frameAlong([60, 12, 19.4], [0, 0, 1]); turned(ctx, c, F, cyl(0, 4, 1.5), M("governor", STEEL), { off: o, lit: lit("governor") });+ const KS = Math.round(20 / (hand().coarse ?? 1)); for (let i = 0; i < 9; i++) { const z0 = 0.3 + i * 0.42; for (let k = 0; k < KS; k++) { const th0 = (k / KS) * 2 * Math.PI + s.fan * 0.15, th1 = th0 + (2 * Math.PI) / KS, f = facingAt(c, F, (th0 + th1) / 2); if (f < 0.05) continue; const A = c.p(at(F, z0 + (k / KS) * 0.42, 1.5, th0)), B = c.p(at(F, z0 + ((k + 1) / KS) * 0.42, 1.5, th1)); ink(ctx, [[A[0] + o[0], A[1] + o[1]], [B[0] + o[0], B[1] + o[1]]], "seam", STEEL, false, smooth(0.05, 0.5, f)); } }+ }, "governor");+ [1, -1].forEach((side) => { const ring = vane(s.fan, side), mid = ring.reduce((a, q) => [a[0] + q[0] / 4, a[1] + q[1] / 4], [0, 0]); put(`vane${side}`, [mid[0], mid[1], 26.5], (ctx, o) => prism(ctx, c, ring, 24.6, 4.2, M("governor", ZINC), { off: o, lit: lit("governor") }), "governor", 0); });+ put("hub", [60, 12, 26.7], (ctx, o) => turned(ctx, c, frameAlong([60, 12, 24.4], [0, 0, 1]), cyl(0, 4.6, 0.95), M("governor", STEEL), { off: o }), "governor", 0.05);+ put("gcap", [60, 12, 30.6], (ctx, o) => turned(ctx, c, frameAlong([60, 12, 30.2], [0, 0, 1]), cyl(0, 0.8, 1.3), STEEL, { off: o }), "governor", 2);+ // travel lines: a chain line from where a part sits to where it went, drawn under everything that moved+ const travel = (id: string, home: V3, ride: string) => put(`path-${id}`, home, (ctx) => {+ const sh = s.shares[ride] ?? 0; if (sh < 0.05) return;+ const a = c.p(home), b = c.p(add(home, [MOVE[ride][0] * sh, MOVE[ride][1] * sh, MOVE[ride][2] * sh]));+ ink(ctx, [a, b], "chain", STEEL, false, 0.8 * smooth(0.05, 0.4, sh));+ }, undefined, -25);+ travel("cs0", [17, 33.5, 8.6], "screws"); travel("cs1", [42, 33.5, 8.6], "screws");+ travel("arbor", [29.5, 17.5, 16.2], "drum"); travel("gov", [60, 12, 18], "governor");+ travel("crank", [66, 22, 10], "crank");+ return items;+};++// ---------------------------------------------------------------- the camera, fit once to everything the film shows+const BENCH: V3[] = [[-3, 4.5, -9], [73, 4.5, -9], [73, 49, -9], [-3, 49, -9], [-3, 4.5, -3], [73, 49, -3], [-3, 49, -3], [5, 6, 3.5]];+const HOME = Cam.fit(36, 30, [...BENCH, [60, 12, 31], [74, 22, 18], [10, 11, 24]], [205, 215, 875, 865]);+const APART = Cam.fit(36, 30, [...BENCH, [90, 12, 61], [116, 22, 26], [-4, 17, 21], [30, 45, 34], [30, 17, 48]], [130, 120, 950, 930]);+export const camAt = (sh: Record<string, number>) => { const m = Object.values(sh).reduce((a, b) => a + b, 0) / PLAN.order.length, e = smooth(0, 1, m); return new Cam(36, 30, HOME.k + (APART.k - HOME.k) * e, HOME.ox + (APART.ox - HOME.ox) * e, HOME.oy + (APART.oy - HOME.oy) * e); };++// the order the pen visits the parts in the film: the bench, the plate, then each assembly as it is put together+const BUILD = ["plinth", "ruler", "label", "pscrew", "post", "bedplate", "bridgeL", "bridgeR", "arbor", "drum", "wheel", "plate", "tooth", "weight", "heel", "cscrew", "housing", "hscrew", "stop", "crank", "gshaft", "hub", "vane", "gcap"];+// time is shared by how much there is to draw: a screw takes a beat, a drum takes a breath+const SMALL = new Set(["pscrew", "post", "arbor", "weight", "cscrew", "hscrew", "stop", "hub", "gcap", "label"]);+const BW = BUILD.map((b) => (SMALL.has(b) ? 0.45 : 1.3)), BSTART = BW.map((_, i) => BW.slice(0, i).reduce((a, w) => a + w, 0)), BTOTAL = BW.reduce((a, w) => a + w, 0);+const buildRank = (id: string) => { const i = BUILD.findIndex((b) => id === b || id.startsWith(b)); return i < 0 ? BUILD.length - 1 : i; };+const buildAt = (id: string, f: number): [number, number] => {+ const [b0, b1] = T.build, unit = (b1 - b0) / (BTOTAL + 1), r = buildRank(id), st = b0 + BSTART[r] * unit, len = BW[r] * unit;+ return [clamp01((f - st) / (len * 1.15)), clamp01((f - st - len * 0.9) / (len * 1.5))];+};+// the camera's own move: while it plays, push in to where the pins meet the teeth and drift along the+// comb from bass to treble; pull back before it comes apart; at the end, settle in a little on the drum+const CLOSE = { a: 0, in: 30, out: 78, b: 104 }, FINAL = { a: 262, b: 310 };+const zoomAt = (f: number): { z: number; focus: V3; pull: number } => {+ if (f >= CLOSE.a && f < CLOSE.b) {+ const e = f < CLOSE.in ? smooth(CLOSE.a, CLOSE.in, f) : f < CLOSE.out ? 1 : 1 - smooth(CLOSE.out, CLOSE.b, f), drift = clamp01((f - CLOSE.a) / (CLOSE.b - CLOSE.a));+ return { z: 1 + 1.25 * e, focus: [16 + 26 * drift, 20, 10], pull: e };+ }+ if (f >= FINAL.a) { const e = smooth(FINAL.a, FINAL.b, f); return { z: 1 + 0.32 * e, focus: [30, 18, 13], pull: e * 0.6 }; }+ return { z: 1, focus: [30, 18, 13], pull: 0 };+};+const zoomed = (c: Cam, f: number): Cam => {+ const { z, focus, pull } = zoomAt(f); if (z <= 1.0001) return c;+ const s0 = c.p(focus), u: P2 = [(s0[0] - c.ox) / c.k, (s0[1] - c.oy) / c.k], tgt: P2 = [s0[0] + (W / 2 - s0[0]) * pull, s0[1] + (H / 2 - s0[1]) * pull], k = c.k * z;+ return new Cam(c.A, c.E, k, tgt[0] - k * u[0], tgt[1] - k * u[1]);+};++export { PLAN, MOVE, ABOUT, REV, PAPER, parts, W as FIG_W, H as FIG_H };+/** the figure on its card at a given state: the film and the interactive explorer both paint through this */+export const paintFigure = (ctx: Ctx, s: State, hint: string, o: { cam?: Cam; build?: (id: string) => [number, number]; card?: number; shadow?: number } = {}) => {+ freshPen(ctx);+ const CAM = o.cam ?? camAt(s.shares), items = parts(CAM, s), text = { fig: "FIG 1", title: "18-NOTE MOVEMENT", hint, read: s.read };+ card(ctx, W, H, text, { progress: o.card ?? 1, part: "ground" });+ ctx.save(); ctx.beginPath(); ctx.rect(35, 35, W - 70, H - 70); ctx.clip(); // the figure lives inside the card's rule+ const foot = rrect(-3, 4.5, 76, 44.5, 3).map(([x, y]) => CAM.p([x, y, -9]));+ const sh = o.shadow ?? 1; // the shadow is laid like a tone sheet, left to right, never faded in+ if (sh > 0) { const x0 = Math.min(...foot.map((q) => q[0])) - 20, x1 = Math.max(...foot.map((q) => q[0])) + 20; ctx.save(); ctx.beginPath(); ctx.rect(x0, -1e4, (x1 - x0) * sh, 2e4); ctx.clip(); hand().shadow?.(ctx, foot, 1); ctx.restore(); }+ const wrapped = o.build ? items.map((it) => ({ ...it, draw: (x: Ctx, off: P2) => { const [ink, tone] = o.build!(it.id); if (ink <= 0) return; setReveal(ink, tone, PAPER); it.draw(x, off); setReveal(1, 1); } })) : items;+ paintAll(ctx, CAM, wrapped, MOVE, s.shares);+ ctx.restore(); freshPen(ctx);+ card(ctx, W, H, text, { progress: o.card ?? 1, part: "words" });+ return CAM;+};+export const camApart = APART;+/** the run: it plays (the camera close on the pins), comes apart, tours its parts, folds home, plays on */+export const drawMechanism = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ const s = stateAt(f);+ paintFigure(ctx, s, "THE PINS ARE THE SCORE", { cam: zoomed(camAt(s.shares), f) });+};+/** the making: the card's rule, then each part inked and toned in assembly order, then the words */+export const drawMechanismMaking = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ const s = stateAt(0), ruleP = clamp01((f - T.rule[0]) / (T.rule[1] - T.rule[0])), textP = clamp01((f - T.text[0]) / (T.text[1] - T.text[0]));+ paintFigure(ctx, s, "THE PINS ARE THE SCORE", { card: ruleP < 1 ? ruleP * 0.5 : 0.5 + textP * 0.5, shadow: buildAt("plinth", f)[1], build: (id) => buildAt(id, f) });+};++/** the same figure, film and all, in the hand of another style */+export const mechanismIn = (handId: string, make: (ctx: Ctx, env: Env, f: number) => Hand, making = false): Film => ({+ meta: making+ ? { title: `Mechanism · the 18-note movement, drawn (${handId})`, W, H, fps: FPS, bpm: 100, durationFrames: N_DRAW, kind: "drawing", poster: N_DRAW - 1 }+ : { title: `Mechanism · the 18-note movement (${handId})`, W, H, fps: FPS, bpm: 100, durationFrames: N, kind: "explainer", poster: 140 },+ assets: { images: {} },+ shots: [{ id: "figure", start: 0, end: making ? N_DRAW : N, draw: (ctx, f, env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); setHand(make(ctx, env, f)); try { (making ? drawMechanismMaking : drawMechanism)(ctx, f, env); } finally { setHand(flatHand()); } } }],+});+/** the plain film: the movement in the house isometric hand (flat planes, three tones, no line) */+export const mechanism: Film = mechanismIn("isometric", () => isometricHand());diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismBlueprint.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismBlueprint.tsnew file mode 100644index 0000000..698ce01--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismBlueprint.ts@@ -0,0 +1,5 @@+// The 18-note movement in the blueprint hand: a machine is a subject, drawn in any style.+import { mechanismIn } from "./mechanism";+import { blueprintHand } from "./mechanismHands";++export const mechanismBlueprint = mechanismIn("blueprint", blueprintHand);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismDraw.tsnew file mode 100644index 0000000..8f8a0f6--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismDraw.ts@@ -0,0 +1,5 @@+// The 18-note movement drawing itself, in the house isometric hand: each part traced, then filled, in assembly order.+import { mechanismIn } from "./mechanism";+import { isometricHand } from "./mechanismHands";++export const mechanismDraw = mechanismIn("isometric", () => isometricHand(), true);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismExplorer.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismExplorer.tsnew file mode 100644index 0000000..e1ef8fc--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismExplorer.ts@@ -0,0 +1,60 @@+// MECHANISM EXPLORER. The 18-note movement as a piece on a web page, in the isometric hand.+// Untouched, it plays its tune forever (the drum's turn is the loop). Hover it, focus it, or the+// page's button, and it comes apart: each assembly on its own slightly underdamped spring, the outer+// ones quicker, so it opens outside-in and lands with a little weight. Point at a part and it lights;+// the readout says what that part does. Leave and it folds home and plays on.+// Web profile: the camera is fixed (fit to the exploded machine), so the card and the bench never+// change; they are drawn once per device scale into a cached layer and the machine is drawn over it.+import type { Piece, Discrete } from "./input";+import { HZ, attentionOf } from "./input";+import type { Layer } from "./core";+import { parts, play, camApart, PLAN, MOVE, ABOUT, REV, FIG_W as W, FIG_H as H, type State } from "./mechanism";+import { setHand, flatHand, add, mul, paintAll, card, freshPen, rrect, type V3, type P2 } from "./mechanismKit";+import { isometricHand } from "./mechanismHands";++const LOOP = Math.round(REV * HZ), ART = { x0: 120, y0: 110, x1: 960, y1: 950 };+const HOME: Record<string, V3> = { governor: [60, 12, 25], crank: [72, 22, 10], housing: [60, 22, 10], screws: [30, 33.5, 9], comb: [30, 26, 8], bridgeL: [10, 17, 12], bridgeR: [50.7, 17, 12], drum: [30, 17.5, 16] };+const BENCH = (id: string) => id === "plinth" || id === "ruler" || id === "label" || id === "bedplate" || id.startsWith("pscrew") || id.startsWith("post"); // never move, and every moving part paints after them+const inside = (p: Discrete["pointer"]) => !!p && p[0] >= ART.x0 && p[0] <= ART.x1 && p[1] >= ART.y0 && p[1] <= ART.y1;+const springs = Object.fromEntries(PLAN.order.map((id, i) => [id, { omega: 0.17 - i * 0.008, zeta: 0.82, target: (d: Discrete) => (inside(d.pointer) || attentionOf(d) === "apart" || d.focus === "self" ? 1 : 0) }]));+const HAND = isometricHand(), CAM = camApart, TITLE = { fig: "FIG 1", title: "18-NOTE MOVEMENT" };+const hintOf = (reduced: boolean) => (reduced ? "FOCUS TO TAKE IT APART" : "HOVER TO TAKE IT APART");+const REST: State = { rot: 0, shares: {}, lit: "", read: "", bend: [], fan: 0, crank: 0 };++/** the card and the bench, which never move: drawn once per device scale */+const benchLayer = (env: Parameters<Piece["draw"]>[2], reduced: boolean): Layer => {+ const DW = Math.round(W * env.scale), DH = Math.round(H * env.scale), key = `mechExplorer:bench:${DW}x${DH}:${reduced}`;+ let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ L = env.canvas(DW, DH); const c = L.ctx; c.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ setHand(HAND);+ try {+ card(c, W, H, { ...TITLE, hint: hintOf(reduced), read: "" });+ HAND.shadow?.(c, rrect(-3, 4.5, 76, 44.5, 3).map(([x, y]) => CAM.p([x, y, -9])), 1);+ paintAll(c, CAM, parts(CAM, { ...REST, bend: play(0).bend }).filter((it) => BENCH(it.id)));+ } finally { setHand(flatHand()); }+ env.cache.set(key, L); return L;+};++export const mechanismExplorer: Piece = {+ meta: { title: "Mechanism explorer", W, H, loop: LOOP, alt: "An 18-note music box movement drawn in flat isometric planes, playing. Hover or focus it to take it apart; point at a part to read what it does." },+ input: { springs: springs as Piece["input"]["springs"] },+ draw: (ctx, tick, env, s) => {+ const L = benchLayer(env, s.reduced);+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); freshPen(ctx); ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore();+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); freshPen(ctx);+ const shares = Object.fromEntries(PLAN.order.map((id) => [id, Math.max(0, s.spring[id] as number)])), mean = PLAN.order.reduce((a, id) => a + shares[id], 0) / PLAN.order.length;+ const rot = s.reduced ? 0.4 : ((tick % LOOP) / LOOP) * 2 * Math.PI, pl = play(rot, Math.min(1, mean * 3));+ const state: State = { rot, shares, lit: "drum", read: pl.read, bend: pl.bend, fan: pl.fan, crank: pl.crank };+ if (mean > 0.02 && mean < 0.9) state.read = (s.spring[PLAN.order[0]] as number) > 0.5 ? "TAKING APART" : "PUTTING BACK";+ if (mean >= 0.9 && s.pointer) { // the part under the pointer: the nearest assembly, where it is now+ let best = Infinity;+ for (const id of PLAN.order) { const q: P2 = CAM.p(add(HOME[id], mul(MOVE[id], shares[id]))), d = Math.hypot(q[0] - s.pointer[0], q[1] - s.pointer[1]); if (d < best) { best = d; state.lit = id; } }+ state.read = `${PLAN.order.indexOf(state.lit) + 1}/${PLAN.order.length} · ${ABOUT[state.lit]}`;+ }+ setHand(HAND);+ try {+ HAND.text(ctx, state.read, W - 96, H - 34 - 20 - 13, { cap: 13, align: "right" }); // clear of the host's pause button in the corner+ paintAll(ctx, CAM, parts(CAM, state).filter((it) => !BENCH(it.id)), MOVE, shares);+ } finally { setHand(flatHand()); }+ },+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismHands.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismHands.tsnew file mode 100644index 0000000..25f1667--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismHands.ts@@ -0,0 +1,198 @@+// HANDS FOR THE MECHANISM KIT. The same machine, marked in a style's own medium. Each hand follows+// the recipe in references/styles/<id>.md: what the mark is, what an edge is, what tone is, and+// whether the medium has light at all. The kit says WHAT is there; a hand decides HOW it is drawn.+//+// blueprint white ink on cyanotype: no light, no shadow; outlines ruled, the part to watch+// section-lined, travel shown as chain lines+// colouredPencil one dominant hatch diagonal in each material's pigment, darks cross-hatched,+// thin broken sepia-graphite contours heavier where the form turns from the lamp+// stipple one pen, dots only: tone is density, an edge is where density changes+//+// Patterns are anchored to the part (its exploded offset), never to the screen, so a part that+// moves carries its marks with it, and a still part's marks never boil.+import type { Ctx, Env, Layer, P } from "./core";+import { Gfx, rng, PENCIL, GRAPHITE } from "./core";+import { kit, sheet, border, WHITE, CYAN, DIM, DRAFT } from "./blueprintKit";+import { letter } from "./drafting";+import { type Hand, type Material, type P2, type Role, offset, path, rawStroke, flatHand, reveal } from "./mechanismKit";++const hash = (...v: number[]) => { let h = 2166136261; for (const x of v) { h ^= Math.round(x * 8) | 0; h = Math.imul(h, 16777619); } return h >>> 0; };+const nameHash = (m: Material) => hash(...[...(m.name ?? "m")].map((c) => c.charCodeAt(0)));++/** the ground of a hand, drawn once into a device-size layer, then knocked back in as a pattern */+const groundLayer = (env: Env, key: string, paint: (L: Layer, g: Gfx) => void): Layer => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), k = `mechHand:${key}:${DW}x${DH}`;+ let L = env.cache.get(k) as Layer | undefined;+ if (!L) { L = env.canvas(DW, DH); L.ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); paint(L, new Gfx(L.ctx, env, 0, DRAFT)); env.cache.set(k, L); }+ return L;+};+const patternOf = (ctx: Ctx, L: Layer, scale: number) => { const p = ctx.createPattern(L.canvas as CanvasImageSource, "no-repeat")!; p.setTransform(new DOMMatrix().scale(1 / scale)); return p; };+const knockWith = (ctx: Ctx, L: Layer, scale: number, pts: P2[]) => { ctx.globalAlpha = 1; ctx.fillStyle = patternOf(ctx, L, scale); path(ctx, pts); ctx.fill(); ctx.strokeStyle = ctx.fillStyle; ctx.lineWidth = 0.6; ctx.stroke(); };+const blit = (ctx: Ctx, L: Layer, env: Env) => { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); };++/** parallel lines at angle `ang`, `gap` apart, anchored at `anchor`, cut to a polygon: [a, b, lineIndex] */+export const hatchSegs = (pts: P2[], ang: number, gap: number, anchor: P2 = [0, 0]): [P2, P2, number][] => {+ const c = Math.cos(ang), s = Math.sin(ang), proj = pts.map(([x, y]) => -s * (x - anchor[0]) + c * (y - anchor[1]));+ const lo = Math.floor(Math.min(...proj) / gap), hi = Math.ceil(Math.max(...proj) / gap), out: [P2, P2, number][] = [];+ for (let n = lo; n <= hi; n++) {+ const off = n * gap, ox = anchor[0] - s * off, oy = anchor[1] + c * off, ts: number[] = [];+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {+ const a = pts[j], b = pts[i], da = -s * (a[0] - ox) + c * (a[1] - oy), db = -s * (b[0] - ox) + c * (b[1] - oy);+ if ((da < 0) === (db < 0) || da === db) continue; const t = da / (da - db), px = a[0] + (b[0] - a[0]) * t, py = a[1] + (b[1] - a[1]) * t; ts.push(c * (px - ox) + s * (py - oy));+ }+ ts.sort((x, y) => x - y); for (let k = 0; k + 1 < ts.length; k += 2) out.push([[ox + c * ts[k], oy + s * ts[k]], [ox + c * ts[k + 1], oy + s * ts[k + 1]], n]);+ }+ return out;+};+/** points every `step` px along a polyline, the first `progress` of it */+const along = (pts: P2[], step: number, close: boolean, progress = 1): P2[] => {+ const q = close ? [...pts, pts[0]] : pts, out: P2[] = []; let L = 0; for (let i = 1; i < q.length; i++) L += Math.hypot(q[i][0] - q[i - 1][0], q[i][1] - q[i - 1][1]);+ const end = L * progress; let d = 0, need = 0;+ for (let i = 1; i < q.length && need <= end; i++) { const a = q[i - 1], b = q[i], l = Math.hypot(b[0] - a[0], b[1] - a[1]); while (need <= d + l && need <= end) { const t = l ? (need - d) / l : 0; out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); need += step; } d += l; }+ return out;+};++// ---------------------------------------------------------------- blueprint: white ink on cyanotype+export const blueprintHand = (ctx0: Ctx, env: Env, frame: number): Hand => {+ const g = new Gfx(ctx0, env, frame, DRAFT), k = kit(g), L = groundLayer(env, "blueprint", (_, lg) => sheet(kit(lg)));+ const seedOf = (pts: P2[]) => hash(pts[0][0] - offset()[0], pts[0][1] - offset()[1], pts.length);+ const W: Partial<Record<Role, [number, string, number]>> = { out: [1.7, WHITE, 0.95], lit: [2.2, WHITE, 1], in: [1.05, WHITE, 0.85], crease: [0.9, CYAN, 0.8], seam: [0.75, CYAN, 0.7], hair: [0.75, CYAN, 0.8] };+ return {+ id: "blueprint",+ knock: (ctx, pts) => knockWith(ctx, L, env.scale, pts),+ // no light on a drawing: the only tone is section lining, and only the part to watch is cut+ region: (_ctx, pts, _q, m) => { if (!m.accent) return; const o = offset(); for (const [a, b, n] of hatchSegs(pts, Math.PI / 4, 5.5, o)) { const l = Math.hypot(b[0] - a[0], b[1] - a[1]); if (l < 2.5) continue; k.ln(a, b, 0.8, { seed: hash(n, nameHash(m)), color: CYAN, opacity: 0.8, taper: 0.7 }); } },+ line: (ctx, pts, role, _m, close, a, prog) => {+ if (role === "light") return;+ if (role === "chain") { const [p0, p1] = [pts[0], pts[pts.length - 1]]; k.chain(p0 as P, p1 as P, 0.8, { color: DIM, opacity: 0.85 * a, progress: prog }); return; }+ const [w, col, op] = W[role]!; k.pen(pts as P[], w, { color: col, opacity: op * a, closed: close, seed: seedOf(pts), progress: prog, wobble: 0.35 });+ void ctx;+ },+ dot: (ctx, at, r, _m, a) => { ctx.globalAlpha = a; ctx.fillStyle = WHITE; ctx.beginPath(); ctx.arc(at[0], at[1], r * 0.9, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx) => blit(ctx, L, env),+ frame: (_ctx, _W, _H, p) => border(k, p),+ text: (_ctx, t, x, y, o) => k.text(t, x, y, { cap: o.cap, align: o.align, color: o.soft ? CYAN : WHITE, w: Math.max(1, o.cap * 0.1), opacity: o.alpha ?? 1, seed: hash(x, y) }),+ };+};++// ---------------------------------------------------------------- coloured pencil: hatched in one diagonal+const ANG = -1.02, X2 = ANG + 1.25, CREAM = "#f3ecdc", SEPIA = "#4a3d36";+export const colouredPencilHand = (ctx0: Ctx, env: Env, frame: number): Hand => {+ const g = new Gfx(ctx0, env, frame, PENCIL), L = groundLayer(env, "pencil", (lay, lg) => { lay.ctx.fillStyle = CREAM; lay.ctx.fillRect(0, 0, env.W, env.H); lg.paper("paper", 0.34); lg.paper("coldpress", 0.2); });+ const strokes = (ctx: Ctx, pts: P2[], ang: number, gap: number, col: string, alpha: number, seed: number, w = 1.25) => {+ const o = offset(); ctx.strokeStyle = col; ctx.lineWidth = w; ctx.lineCap = "round";+ for (const [a, b, n] of hatchSegs(pts, ang, gap, o)) {+ const r = rng(hash(n, seed)), l = Math.hypot(b[0] - a[0], b[1] - a[1]); if (l < 1.5) continue;+ // a hatch stroke: lands fast, lifts in a flick, and breaks where the lead skips the paper's valleys+ const s0 = (r() - 0.35) * 2.2, s1 = (r() - 0.6) * 2.2, ux = (b[0] - a[0]) / l, uy = (b[1] - a[1]) / l;+ ctx.globalAlpha = alpha * (0.75 + r() * 0.4); ctx.setLineDash([3 + r() * 9, 0.8 + r() * 1.6]); ctx.lineDashOffset = r() * 10;+ ctx.beginPath(); ctx.moveTo(a[0] - ux * s0, a[1] - uy * s0); ctx.lineTo(b[0] + ux * s1, b[1] + uy * s1); ctx.stroke();+ }+ ctx.setLineDash([]); ctx.globalAlpha = 1;+ };+ const W: Partial<Record<Role, [number, number]>> = { out: [1.5, 0.8], lit: [1.9, 0.95], in: [1, 0.6], crease: [0.85, 0.45], seam: [0.7, 0.4], hair: [0.7, 0.55] };+ return {+ id: "colouredPencil",+ knock: (ctx, pts) => knockWith(ctx, L, env.scale, pts),+ region: (ctx, pts, q, m) => {+ const d = Math.max(0, Math.min(1, 1 - q / 4)), pig = m.pigment ?? "#8a8a8a", sd = nameHash(m);+ strokes(ctx, pts, ANG, 3.1, pig, (m.accent ? 0.55 : 0.32) + 0.4 * d, sd); // local colour, light to dark by pressure+ if (d > 0.35) strokes(ctx, pts, ANG, 3.1, pig, 0.25 + 0.3 * d, sd + 7, 1.1); // a second pass, offset by the hand+ if (d > 0.6) strokes(ctx, pts, X2, 3.6, m.accent ? "#5a1e14" : "#3b3550", 0.18 + 0.35 * (d - 0.6), sd + 13, 1); // darks cross-hatched, never filled+ },+ line: (ctx, pts, role, m, close, a, prog) => {+ if (role === "light") return;+ if (role === "chain") { ctx.save(); ctx.setLineDash([7, 4]); rawStroke(ctx, pts, SEPIA, 0.8, false, 0.55 * a, prog); ctx.restore(); return; }+ const [w, op] = W[role]!; g.pen(pts as P[], { w, color: m.accent && role === "lit" ? "#6b2414" : SEPIA, opacity: op * a, closed: close, seed: hash(pts[0][0] - offset()[0], pts[0][1] - offset()[1]), boil: 0, wobble: 0.45, taper: 0.9, progress: prog });+ void ctx;+ },+ dot: (ctx, at, r, _m, a) => { ctx.globalAlpha = 0.85 * a; ctx.fillStyle = GRAPHITE; ctx.beginPath(); ctx.arc(at[0], at[1], r * 0.85, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx) => blit(ctx, L, env),+ frame: (ctx, W0, H0, p) => { const pad = 34, edges: [P2, P2][] = [[[pad, pad], [W0 - pad, pad]], [[W0 - pad, pad], [W0 - pad, H0 - pad]], [[W0 - pad, H0 - pad], [pad, H0 - pad]], [[pad, H0 - pad], [pad, pad]]]; edges.forEach(([a, b], i) => g.pen([a, b] as P[], { w: 0.9, color: SEPIA, opacity: 0.55, seed: 40 + i, boil: 0, wobble: 0.8, progress: Math.max(0, Math.min(1, p * 4 - i)) })); void ctx; },+ text: (_ctx, t, x, y, o) => letter(g, t, x, y, { cap: o.cap, align: o.align, color: o.soft ? "#7a6a5e" : SEPIA, opacity: (o.alpha ?? 1) * 0.9, seed: hash(x, y), slant: 0.12 }),+ shadow: (ctx, pts, s) => { const off = pts.map(([x, y]) => [x + 2, y + 8] as P2); strokes(ctx, off, X2, 3.4, "#5a5260", 0.22 * s, 99, 1); },+ };+};++// ---------------------------------------------------------------- stipple: one pen, dots only+const CARBON = "#15120e", BRISTOL = "#fbfaf5";+export const stippleHand = (ctx0: Ctx, env: Env, frame: number): Hand => {+ const g = new Gfx(ctx0, env, frame, { ...PENCIL, wobble: 0.3 }), L = groundLayer(env, "stipple", (lay, lg) => { lay.ctx.fillStyle = BRISTOL; lay.ctx.fillRect(0, 0, env.W, env.H); lg.paper("paper", 0.05); });+ // dot fields come from tiles, one per density step, drawn once: a dot is in a step's tile when its draw is+ // under that density, so a darker step only adds dots. A whole region is then one patterned fill, cheap+ // enough for a close-up, and the pattern is anchored to the part so its dots travel with it.+ const CELL = 2, SPAN = 64, STEPS = 24, TILE = CELL * SPAN;+ const tile = (seed: number, step: number) => {+ const k = `mechHand:stipple:${seed}:${step}:${env.scale}`; let T = env.cache.get(k) as Layer | undefined;+ if (!T) {+ const D = Math.round(TILE * env.scale); T = env.canvas(D, D); const c = T.ctx; c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = CARBON; c.beginPath();+ for (let j = 0; j < SPAN; j++) for (let i = 0; i < SPAN; i++) {+ const r = rng(hash(i, j, seed)); if (r() > step / STEPS) continue;+ const x = (i + r()) * CELL, y = (j + r()) * CELL, rad = 0.62 + r() * 0.18;+ // a dot near the tile edge is drawn again across it, so tiles meet without a seam+ for (const dx of [0, x < 1 ? TILE : x > TILE - 1 ? -TILE : 0]) for (const dy of [0, y < 1 ? TILE : y > TILE - 1 ? -TILE : 0]) { c.moveTo(x + dx + rad, y + dy); c.ellipse(x + dx, y + dy, rad * 1.08, rad, 0.4, 0, Math.PI * 2); }+ }+ c.fill(); env.cache.set(k, T);+ }+ return T;+ };+ const dots = (ctx: Ctx, pts: P2[], density: number, seed: number) => {+ const step = Math.min(STEPS, Math.round(density * STEPS)); if (step <= 0) return; const o = offset();+ const pat = ctx.createPattern(tile(seed % 4, step).canvas as CanvasImageSource, "repeat")!; pat.setTransform(new DOMMatrix().translate(o[0], o[1]).scale(1 / env.scale));+ ctx.fillStyle = pat; path(ctx, pts); ctx.fill();+ };+ const SPACE: Partial<Record<Role, [number, number]>> = { out: [1.5, 0.8], lit: [1.15, 0.95], in: [2.6, 0.72], crease: [3.2, 0.7], seam: [3.8, 0.66], hair: [3.2, 0.7], chain: [5.5, 0.66] };+ return {+ id: "stipple",+ knock: (ctx, pts) => knockWith(ctx, L, env.scale, pts),+ region: (ctx, pts, q, m) => { const d = Math.max(0, Math.min(1, 1 - q / 4)); dots(ctx, pts, Math.min(0.95, 0.04 + 0.78 * d ** 1.25 + (m.accent ? 0.22 : 0)), nameHash(m)); },+ // no contours in this medium: an outline is a denser row of the same dots+ line: (ctx, pts, role, _m, close, a, prog) => {+ if (role === "light") return; const [step, r] = SPACE[role]!, o = offset(), pa = along(pts, step, close, prog);+ ctx.globalAlpha = a; ctx.fillStyle = CARBON; ctx.beginPath();+ pa.forEach(([x, y], i) => { const rr = rng(hash(x - o[0], y - o[1], i)); const jx = (rr() - 0.5) * 0.5, jy = (rr() - 0.5) * 0.5; ctx.moveTo(x + jx + r, y + jy); ctx.arc(x + jx, y + jy, r * (0.85 + rr() * 0.3), 0, Math.PI * 2); });+ ctx.fill(); ctx.globalAlpha = 1;+ },+ dot: (ctx, at, r, _m, a) => { ctx.globalAlpha = a; ctx.fillStyle = CARBON; ctx.beginPath(); ctx.arc(at[0], at[1], Math.max(0.8, r * 0.7), 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx) => blit(ctx, L, env),+ frame: (ctx, W0, H0, p) => { const pad = 34; const ring: P2[] = [[pad, pad], [W0 - pad, pad], [W0 - pad, H0 - pad], [pad, H0 - pad]]; const pa = along(ring, 3, true, p); ctx.fillStyle = CARBON; ctx.globalAlpha = 0.55; ctx.beginPath(); pa.forEach(([x, y]) => { ctx.moveTo(x + 0.6, y); ctx.arc(x, y, 0.6, 0, Math.PI * 2); }); ctx.fill(); ctx.globalAlpha = 1; },+ text: (_ctx, t, x, y, o) => letter(g, t, x, y, { cap: o.cap, align: o.align, color: o.soft ? "#6b665e" : CARBON, opacity: o.alpha ?? 1, seed: hash(x, y), slant: 0, w: Math.max(0.9, o.cap * 0.085) }),+ shadow: (ctx, pts, s) => dots(ctx, pts.map(([x, y]) => [x + 2, y + 7] as P2), 0.22 * s, 7),+ };+};++// ---------------------------------------------------------------- isometric: flat planes, three tones, no line+// The house iso medium (references/styles/isometric.md): every plane ONE flat colour, exactly three+// tones per material (top lightest, the lamp-side face middle, the far face darkest), tone meets tone+// with no contour, details as hairlines, cast shadows one flat shape. Fills only, so it is fast+// enough for an interactive page.+const mixHex = (a: string, b: string, t: number) => { const pa = [1, 3, 5].map((i) => parseInt(a.slice(i, i + 2), 16)), pb = [1, 3, 5].map((i) => parseInt(b.slice(i, i + 2), 16)); return "#" + pa.map((v, i) => Math.round(v + (pb[i] - v) * t).toString(16).padStart(2, "0")).join(""); };+export const isometricHand = (paper = "#efe8dc", ink = "#2b2a33"): Hand => {+ const tones = new Map<string, [string, string, string]>();+ const three = (m: Material) => { const k = m.pigment ?? "#9a9a9a"; let t = tones.get(k); if (!t) { t = [mixHex(k, "#1d1a2a", 0.3), k, mixHex(k, "#ffffff", 0.5)]; tones.set(k, t); } return t; };+ const flat = (ctx: Ctx, pts: P2[], col: string, a = 1) => { ctx.globalAlpha = a; ctx.fillStyle = col; path(ctx, pts); ctx.fill(); ctx.strokeStyle = col; ctx.lineWidth = 0.5; ctx.lineJoin = "round"; ctx.stroke(); ctx.globalAlpha = 1; };+ const base = flatHand(paper, "#7a7280", "#b9b0a3");+ return {+ ...base, id: "isometric", coarse: 3.4,+ knock: (ctx, pts) => flat(ctx, pts, paper),+ region: (ctx, pts, q, m, a) => { const [far, side, top] = three(m); flat(ctx, pts, q >= 3.6 ? top : q >= 1.8 ? side : far, a); },+ step: (q) => (q >= 3.6 ? 2 : q >= 1.8 ? 1 : 0), opaque: true,+ line: (ctx, pts, role, m, close, a, prog) => {+ // a plane is pen-traced before it is filled; once filled, tone meets tone and the trace is gone+ if ((role === "out" || role === "lit" || role === "in" || role === "crease") && reveal().tone < 1) { rawStroke(ctx, pts, "#6f8cc4", 1.6, close, 0.9 * a, prog); return; }+ if (role === "seam" || role === "hair") rawStroke(ctx, pts, three(m)[0], 0.7, close, 0.8 * a, prog);+ else if (role === "chain") { ctx.save(); ctx.setLineDash([6, 4]); rawStroke(ctx, pts, ink, 0.8, false, 0.35 * a, prog); ctx.restore(); }+ },+ dot: (ctx, at, r, m, a) => { ctx.globalAlpha = a; ctx.fillStyle = three(m)[0]; ctx.beginPath(); ctx.arc(at[0], at[1], r, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ shadow: (ctx, pts, s) => flat(ctx, pts.map(([x, y]) => [x + 6, y + 9] as P2), "#3a3346", 0.13 * s),+ };+};++/** every hand, by the id of the style whose medium it follows ("flat" is the kit's plain reference hand) */+export const HANDS: Record<string, (ctx: Ctx, env: Env, frame: number) => Hand> = {+ flat: () => flatHand(),+ blueprint: blueprintHand,+ colouredPencil: colouredPencilHand,+ stipple: stippleHand,+ isometric: () => isometricHand(),+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismKit.tsnew file mode 100644index 0000000..4c4c9ee--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismKit.ts@@ -0,0 +1,424 @@+// MECHANISM KIT. The technical illustrator's bench, in code: a free-angle axonometric camera,+// one light locked to it, solids that know their own silhouettes, turned parts shaded in exact+// bands, hardware that fades as it turns away, a depth-sorted parts list, a closed-form spring for+// exploded views, and the figure card. Every function is pure; nothing reads a clock.+//+// World: millimetres, z up. The camera looks down at elevation E from azimuth A; (cos A, sin A) is+// the floor direction toward the viewer. At A = 45, E = 30 it is the 2:1 dimetric of isometricKit.+//+// The light rides with the camera, up and to the viewer's left, so the same face family is always+// the light one. A face's tone is how many thresholds its light score passes (0, .2, .42, .62):+// five tones per material, darkest side to top. Near a threshold the tone crossfades, so a part+// that turns never flips colour in one frame.+import type { Ctx } from "./core";+import { G, width as glyphWidth } from "./drafting";++export type V3 = [number, number, number];+export type P2 = [number, number];+export const add = (a: V3, b: V3): V3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+export const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+export const mul = (a: V3, k: number): V3 => [a[0] * k, a[1] * k, a[2] * k];+export const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+export const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+export const unit = (a: V3): V3 => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };+export const clamp01 = (t: number) => (t <= 0 ? 0 : t >= 1 ? 1 : t);+export const smooth = (a: number, b: number, x: number) => { const t = clamp01((x - a) / (b - a)); return t * t * (3 - 2 * t); };+const D2R = Math.PI / 180;++// ---------------------------------------------------------------- camera+export class Cam {+ readonly sA: number; readonly cA: number; readonly sE: number; readonly cE: number;+ readonly V: V3; readonly L: V3;+ constructor(public A: number, public E: number, public k: number, public ox: number, public oy: number) {+ this.sA = Math.sin(A * D2R); this.cA = Math.cos(A * D2R); this.sE = Math.sin(E * D2R); this.cE = Math.cos(E * D2R);+ this.V = [this.cA * this.cE, this.sA * this.cE, this.sE];+ this.L = unit([-this.sA, this.cA, 1.2]);+ }+ p(q: V3): P2 { const [x, y, z] = q; return [this.ox + this.k * (x * this.sA - y * this.cA), this.oy + this.k * ((x * this.cA + y * this.sA) * this.sE - z * this.cE)]; }+ /** larger is nearer the viewer */+ depth(q: V3) { return dot(q, this.V); }+ /** screen offset of a world translation (exact in an orthographic camera) */+ dv(v: V3): P2 { return [this.k * (v[0] * this.sA - v[1] * this.cA), this.k * ((v[0] * this.cA + v[1] * this.sA) * this.sE - v[2] * this.cE)]; }+ /** fit world points into a box: the same camera, rescaled and centred */+ static fit(A: number, E: number, pts: V3[], box: [number, number, number, number]): Cam {+ const c = new Cam(A, E, 1, 0, 0), s = pts.map((q) => c.p(q));+ const x0 = Math.min(...s.map((q) => q[0])), x1 = Math.max(...s.map((q) => q[0])), y0 = Math.min(...s.map((q) => q[1])), y1 = Math.max(...s.map((q) => q[1]));+ const k = Math.min((box[2] - box[0]) / (x1 - x0), (box[3] - box[1]) / (y1 - y0));+ return new Cam(A, E, k, (box[0] + box[2]) / 2 - k * (x0 + x1) / 2, (box[1] + box[3]) / 2 - k * (y0 + y1) / 2);+ }+}++// ---------------------------------------------------------------- tone+export const THRESH = [0, 0.2, 0.42, 0.62] as const;+/** a continuous tone level 0..4; integer away from thresholds, a 0.07-wide crossfade across each */+export const level = (score: number, soft = 0.035) => THRESH.reduce((q: number, t: number) => q + smooth(t - soft, t + soft, score), 0);+export type Material = { ramp: [string, string, string, string, string]; ink: string; seam: string; pigment?: string; accent?: boolean; name?: string };+const hexRgb = (h: string): V3 => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];+const mixMemo = new Map<string, string>();+/** the colour of level q of a material, quantised to 1/64 so the memo stays small */+export const toneColour = (m: Material, q: number): string => {+ const Q = Math.round(Math.max(0, Math.min(4, q)) * 64), key = m.ramp[0] + m.ramp[4] + Q;+ let c = mixMemo.get(key); if (c) return c;+ const i = Math.min(3, Math.floor(Q / 64)), f = (Q - i * 64) / 64, a = hexRgb(m.ramp[i]), b = hexRgb(m.ramp[i + 1]);+ c = `rgb(${[0, 1, 2].map((j) => Math.round(a[j] + (b[j] - a[j]) * f)).join(",")})`; mixMemo.set(key, c); return c;+};+export const toneOf = (c: Cam, n: V3) => level(dot(unit(n), c.L));++// ---------------------------------------------------------------- marks+export const W_OUT = 1.6, W_IN = 0.9, W_HAIR = 0.6; // silhouette, inner line, faint line (logical px)+export const path = (ctx: Ctx, pts: P2[], close = true) => { ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); if (close) ctx.closePath(); };+/** a flat region; the hairline of its own colour closes the antialias seam against its neighbours */+// The making order, for films that draw themselves: a part is inked first (its lines run out to+// full length), then toned (the paper knocks out what is behind it, and the grey sheet is laid+// across it left to right). Set per part by the plate; (1, 1) is the finished drawing.+const REVEAL = { ink: 1, tone: 1, paper: "#ffffff" };+export const setReveal = (ink: number, tone: number, paper = REVEAL.paper) => { REVEAL.ink = ink; REVEAL.tone = tone; REVEAL.paper = paper; };+/** where the making order stands for the part being painted (hands that trace before they fill read it) */+export const reveal = (): { ink: number; tone: number } => ({ ink: REVEAL.ink, tone: REVEAL.tone });+export const solid = (ctx: Ctx, pts: P2[], colour: string, alpha: number) => { ctx.globalAlpha = alpha; ctx.fillStyle = colour; path(ctx, pts); ctx.fill(); ctx.strokeStyle = colour; ctx.lineWidth = 0.45; ctx.lineJoin = "round"; ctx.stroke(); ctx.globalAlpha = 1; };+export const fill = (ctx: Ctx, pts: P2[], colour: string, alpha = 1) => {+ if (pts.length < 3) return;+ if (REVEAL.tone >= 1) return solid(ctx, pts, colour, alpha);+ if (REVEAL.ink < 1) return;+ solid(ctx, pts, REVEAL.paper, alpha); if (REVEAL.tone <= 0) return;+ const x0 = Math.min(...pts.map((q) => q[0])), x1 = Math.max(...pts.map((q) => q[0]));+ ctx.save(); ctx.beginPath(); ctx.rect(x0 - 1, -1e5, (x1 - x0 + 2) * REVEAL.tone, 2e5); ctx.clip(); solid(ctx, pts, colour, alpha); ctx.restore();+};+export const stroke = (ctx: Ctx, pts: P2[], colour: string, w: number, close = false, alpha = 1) => rawStroke(ctx, pts, colour, w, close, alpha, REVEAL.ink);+/** a ruled line; progress < 1 draws its first part only (the pen still travelling) */+export const rawStroke = (ctx: Ctx, pts: P2[], colour: string, w: number, close: boolean, alpha: number, progress: number) => {+ if (pts.length < 2 || progress <= 0) return; ctx.globalAlpha = alpha; ctx.strokeStyle = colour; ctx.lineWidth = w; ctx.lineCap = "round"; ctx.lineJoin = "round"; path(ctx, pts, close);+ if (progress < 1) { let L = 0; for (let i = 1; i < pts.length; i++) L += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]); if (close) L += Math.hypot(pts[0][0] - pts[pts.length - 1][0], pts[0][1] - pts[pts.length - 1][1]); ctx.setLineDash([L * progress, L + 1]); }+ ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;+};+/** a line that must stop on a bare face fades out over its last `fade` px instead of ending on a cap */+export const strokeFade = (ctx: Ctx, a: P2, b: P2, colour: string, w: number, fade: number, alpha = 1) => {+ const L = Math.hypot(b[0] - a[0], b[1] - a[1]); if (L < 0.5) return;+ const g = ctx.createLinearGradient(a[0], a[1], b[0], b[1]), [r, gg, bb] = hexRgb(colour), f = Math.min(0.5, fade / L);+ g.addColorStop(0, `rgba(${r},${gg},${bb},${alpha})`); g.addColorStop(1 - f, `rgba(${r},${gg},${bb},${alpha})`); g.addColorStop(1, `rgba(${r},${gg},${bb},0)`);+ ctx.strokeStyle = g; ctx.lineWidth = w; ctx.lineCap = "butt"; ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke();+};+// ---------------------------------------------------------------- the hand: who makes the marks+// The kit decides WHAT is there (a region of tone q on a material, a silhouette, a crease, a seam);+// the hand decides HOW it is marked, in its own medium. A flat hand fills tones and rules lines; a+// pencil hand hatches, a stipple hand dots, a blueprint hand rules white ink and section-lines the+// part to watch. Any style can draw any machine by bringing a hand. q is 0 (darkest side) to 4 (top).+export type Role = "out" | "lit" | "in" | "crease" | "seam" | "hair" | "light" | "chain";+export type Hand = {+ id: string;+ knock(ctx: Ctx, pts: P2[]): void; // paint the ground back: a part hides what is behind it+ region(ctx: Ctx, pts: P2[], q: number, m: Material, alpha: number): void;+ line(ctx: Ctx, pts: P2[], role: Role, m: Material, close: boolean, alpha: number, progress: number): void;+ dot(ctx: Ctx, at: P2, r: number, m: Material, alpha: number): void;+ sheet(ctx: Ctx, W: number, H: number): void; // the ground of the whole card+ frame(ctx: Ctx, W: number, H: number, progress: number): void; // the card's rule+ text(ctx: Ctx, s: string, x: number, y: number, o: { cap: number; align?: "left" | "right" | "center"; soft?: boolean; alpha?: number }): void;+ shadow?(ctx: Ctx, pts: P2[], strength: number): void; // a contact shadow, if the medium has light at all+ coarse?: number; // > 1: fewer rows on turned parts (flat media need less), for speed+ step?(q: number, m: Material): number;+ opaque?: boolean; // a full-strength region hides what is under it, so it needs no knock first // a medium with few tones: which one q lands on, so a band that repeats its neighbour is not painted+};+const WEIGHT: Record<Role, number> = { out: W_OUT, lit: W_OUT * 1.2, in: W_IN, crease: W_IN, seam: W_HAIR, hair: W_HAIR, light: W_IN, chain: W_HAIR };+/** the plain hand: flat tone fills and ruled lines. The kit's default and its reference. */+export const flatHand = (paper = "#f3f0e8", soft = "#6d6a70", rule = "#9a968e"): Hand => ({+ id: "flat",+ knock: (ctx, pts) => solid(ctx, pts, paper, 1),+ region: (ctx, pts, q, m, a) => solid(ctx, pts, toneColour(m, q), a),+ line: (ctx, pts, role, m, close, a, prog) => {+ const col = role === "crease" || role === "seam" ? m.seam : role === "light" ? "#ffffff" : role === "chain" ? soft : m.ink;+ if (role === "chain") { ctx.save(); ctx.setLineDash([9, 3, 1.5, 3]); rawStroke(ctx, pts, col, WEIGHT[role], close, a, prog); ctx.restore(); return; }+ rawStroke(ctx, pts, col, WEIGHT[role], close, role === "light" ? a * 0.85 : a, prog);+ },+ dot: (ctx, at, r, m, a) => { ctx.globalAlpha = a; ctx.fillStyle = m.ink; ctx.beginPath(); ctx.arc(at[0], at[1], r, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx, W, H) => { ctx.fillStyle = paper; ctx.fillRect(0, 0, W, H); },+ frame: (ctx, W, H, p) => ruleFrame(ctx, W, H, rule, p),+ text: (ctx, t, x, y, o) => stencil(ctx, t, x, y, { cap: o.cap, colour: o.soft ? soft : "#232227", align: o.align, alpha: o.alpha }),+ shadow: (ctx, pts, k) => { const cx = pts.reduce((a, q) => a + q[0], 0) / pts.length, cy = pts.reduce((a, q) => a + q[1], 0) / pts.length; for (let i = 0; i < 8; i++) { const f = 1 + i * 0.012; solid(ctx, pts.map(([x, y]) => [cx + (x - cx) * f, cy + (y - cy) * f + 5 + i] as P2), "#5b574f", 0.022 * k); } },+});+let HAND: Hand = flatHand();+let OFFSET: P2 = [0, 0];+/** the screen offset of the part being painted: hands anchor their patterns to it, so marks travel with their part */+export const offset = (): P2 => OFFSET;+export const setHand = (h: Hand) => { HAND = h; };+export const hand = () => HAND;+/** a toned region in the current hand, honouring the making order (inked, then toned left to right) */+export const tone = (ctx: Ctx, pts: P2[], m: Material, q: number, alpha = 1) => {+ if (pts.length < 3) return;+ if (REVEAL.tone >= 1) { if (!(HAND.opaque && alpha >= 1)) HAND.knock(ctx, pts); HAND.region(ctx, pts, q, m, alpha); return; }+ if (REVEAL.ink < 1) return;+ HAND.knock(ctx, pts); if (REVEAL.tone <= 0) return;+ const x0 = Math.min(...pts.map((v) => v[0])), x1 = Math.max(...pts.map((v) => v[0]));+ ctx.save(); ctx.beginPath(); ctx.rect(x0 - 1, -1e5, (x1 - x0 + 2) * REVEAL.tone, 2e5); ctx.clip(); HAND.region(ctx, pts, q, m, alpha); ctx.restore();+};+/** paint the ground back over a shape without toning it (the paper inside a hull) */+export const knock = (ctx: Ctx, pts: P2[]) => { if (pts.length >= 3 && (REVEAL.tone >= 1 || REVEAL.ink >= 1)) HAND.knock(ctx, pts); };+export const ink = (ctx: Ctx, pts: P2[], role: Role, m: Material, close = false, alpha = 1) => { if (pts.length >= 2 && REVEAL.ink > 0) HAND.line(ctx, pts, role, m, close, alpha, REVEAL.ink); };+export const inkDot = (ctx: Ctx, at: P2, r: number, m: Material, alpha = 1) => { if (REVEAL.ink >= 1) HAND.dot(ctx, at, r, m, alpha); };+const ruleFrame = (ctx: Ctx, W: number, H: number, colour: string, p: number, pad = 34) => {+ if (p <= 0) return; ctx.strokeStyle = colour; ctx.lineWidth = 1.2; ctx.globalAlpha = 1; ctx.lineCap = "butt"; ctx.setLineDash([]);+ const L = 2 * (W + H - 4 * pad) * clamp01(p), segs: [P2, P2][] = [[[pad, pad], [W - pad, pad]], [[W - pad, pad], [W - pad, H - pad]], [[W - pad, H - pad], [pad, H - pad]], [[pad, H - pad], [pad, pad]]];+ let left = L; ctx.beginPath(); for (const [a, b] of segs) { if (left <= 0) break; const l = Math.hypot(b[0] - a[0], b[1] - a[1]), f = Math.min(1, left / l); ctx.moveTo(a[0], a[1]); ctx.lineTo(a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f); left -= l; } ctx.stroke();+};++export const hull = (pts: P2[]): P2[] => {+ const s = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]); if (s.length < 3) return s;+ const cr = (o: P2, a: P2, b: P2) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);+ const lo: P2[] = [], up: P2[] = [];+ for (const p of s) { while (lo.length >= 2 && cr(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); }+ for (let i = s.length - 1; i >= 0; i--) { const p = s[i]; while (up.length >= 2 && cr(up[up.length - 2], up[up.length - 1], p) <= 0) up.pop(); up.push(p); }+ return lo.slice(0, -1).concat(up.slice(0, -1));+};++// ---------------------------------------------------------------- plans (floor outlines)+export const rrect = (x: number, y: number, w: number, d: number, r: number, steps = 6): P2[] => {+ r = Math.max(0, Math.min(r, w / 2, d / 2)); if (r === 0) return [[x, y], [x + w, y], [x + w, y + d], [x, y + d]];+ const c: [number, number, number][] = [[x + w - r, y + r, -Math.PI / 2], [x + w - r, y + d - r, 0], [x + r, y + d - r, Math.PI / 2], [x + r, y + r, Math.PI]];+ return c.flatMap(([cx, cy, a0]) => Array.from({ length: steps + 1 }, (_, i) => { const a = a0 + (i / steps) * (Math.PI / 2); return [cx + Math.cos(a) * r, cy + Math.sin(a) * r] as P2; }));+};+export const circle = (cx: number, cy: number, r: number, steps = 40): P2[] => Array.from({ length: steps }, (_, i) => { const a = (i / steps) * Math.PI * 2; return [cx + Math.cos(a) * r, cy + Math.sin(a) * r] as P2; });+const ccw = (ring: P2[]) => ring.reduce((s, a, i) => { const b = ring[(i + 1) % ring.length]; return s + a[0] * b[1] - b[0] * a[1]; }, 0) > 0;++// ---------------------------------------------------------------- prisms: a convex plan extruded up+export type PrismOpts = { lit?: boolean; seams?: number[]; bevel?: number; outline?: boolean; inner?: (ctx: Ctx) => void; off?: P2 };+/** paints a convex floor plan extruded from z to z + h: paper, sides by tone, top, crease, bevel, seams, outline */+export const prism = (ctx: Ctx, c: Cam, ring: P2[], z: number, h: number, m: Material, o: PrismOpts = {}) => {+ const [dx, dy] = o.off ?? [0, 0], P = (q: V3): P2 => { const s = c.p(q); return [s[0] + dx, s[1] + dy]; };+ const R = ccw(ring) ? ring : [...ring].reverse(), n = R.length, top = R.map(([x, y]) => P([x, y, z + h])), bot = R.map(([x, y]) => P([x, y, z]));+ const out = hull(top.concat(bot)); knock(ctx, out);+ const facing: boolean[] = [];+ for (let i = 0; i < n; i++) {+ const a = R[i], b = R[(i + 1) % n], nx = b[1] - a[1], ny = -(b[0] - a[0]), l = Math.hypot(nx, ny) || 1, nn: V3 = [nx / l, ny / l, 0];+ facing[i] = nn[0] * c.cA + nn[1] * c.sA > 1e-9; if (!facing[i]) continue;+ tone(ctx, [bot[i], bot[(i + 1) % n], top[(i + 1) % n], top[i]], m, Math.min(3, toneOf(c, nn)));+ }+ tone(ctx, top, m, 4);+ const runs: P2[][] = []; // the top ring along facing edges: the crease where the top meets the sides+ for (let i = 0; i < n; i++) if (facing[i]) { const last = runs[runs.length - 1]; if (last && facing[(i - 1 + n) % n] && last[last.length - 1] === top[i]) last.push(top[(i + 1) % n]); else runs.push([top[i], top[(i + 1) % n]]); }+ for (const s of o.seams ?? []) for (let i = 0; i < n; i++) if (facing[i]) ink(ctx, [P([R[i][0], R[i][1], z + s]), P([R[(i + 1) % n][0], R[(i + 1) % n][1], z + s])], "seam", m);+ if (o.bevel) { // a bright line just inside the crease: the light catching a softened edge+ const cx = R.reduce((s, q) => s + q[0], 0) / n, cy = R.reduce((s, q) => s + q[1], 0) / n;+ const ins = R.map(([x, y]) => { const l = Math.hypot(x - cx, y - cy) || 1; return P([x - ((x - cx) / l) * o.bevel!, y - ((y - cy) / l) * o.bevel!, z + h]); });+ for (let i = 0; i < n; i++) if (facing[i]) ink(ctx, [ins[i], ins[(i + 1) % n]], "light", m);+ }+ o.inner?.(ctx);+ runs.forEach((r) => ink(ctx, r, "crease", m));+ if (o.outline !== false) ink(ctx, out, o.lit ? "lit" : "out", m, true);+ return out;+};+export const box = (ctx: Ctx, c: Cam, x: number, y: number, z: number, w: number, d: number, h: number, m: Material, o: PrismOpts & { r?: number } = {}) =>+ prism(ctx, c, rrect(x, y, w, d, o.r ?? 0), z, h, m, o);++// ---------------------------------------------------------------- frames and turned parts+export type Frame = { o: V3; a: V3; u: V3; v: V3 };+export const frameAlong = (o: V3, a: V3): Frame => { a = unit(a); const h: V3 = Math.abs(a[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1], u = unit(cross(h, a)); return { o, a, u, v: cross(a, u) }; };+export const at = (F: Frame, s: number, r: number, th: number): V3 => add(add(F.o, mul(F.a, s)), add(mul(F.u, r * Math.cos(th)), mul(F.v, r * Math.sin(th))));+export const radial = (F: Frame, th: number): V3 => add(mul(F.u, Math.cos(th)), mul(F.v, Math.sin(th)));+/** how squarely the surface of a turned part faces the viewer at (s, th), -1..1 */+export const facingAt = (c: Cam, F: Frame, th: number, slope = 0) => dot(unit(sub(radial(F, th), mul(F.a, slope))), c.V);+export type Profile = { s0: number; s1: number; r: (s: number) => number; dr: (s: number) => number };+export const cyl = (s0: number, s1: number, r: number): Profile => ({ s0, s1, r: () => r, dr: () => 0 });+export const cone = (s0: number, s1: number, r0: number, r1: number): Profile => ({ s0, s1, r: (s) => r0 + ((r1 - r0) * (s - s0)) / (s1 - s0), dr: () => (r1 - r0) / (s1 - s0) });+/** a dome or a ball segment: radius R sphere centred at sc on the axis, between s0 and s1 */+export const sphere = (s0: number, s1: number, sc: number, R: number): Profile => ({ s0, s1, r: (s) => Math.sqrt(Math.max(1e-6, R * R - (s - sc) ** 2)), dr: (s) => -(s - sc) / Math.sqrt(Math.max(1e-3, R * R - (s - sc) ** 2)) });++type Arc = [number, number] | null;+const wrap = (a: number) => { a = (a + Math.PI) % (2 * Math.PI); if (a < 0) a += 2 * Math.PI; return a - Math.PI; };+// The interval of angles (relative to the view's own angle) where cos(th - centre) >= c, cut to+// [-half, half]; the largest piece if the cut leaves two.+const band = (centre: number, c: number, half: number): Arc => {+ if (c > 1 || half <= 0) return null; const g = c < -1 ? Math.PI : Math.acos(c); if (g >= Math.PI) return [-half, half];+ let best: Arc = null;+ for (const k of [-2 * Math.PI, 0, 2 * Math.PI]) { const lo = Math.max(-half, centre - g + k), hi = Math.min(half, centre + g + k); if (hi > lo && (!best || hi - lo > best[1] - best[0])) best = [lo, hi]; }+ return best;+};++export type TurnOpts = { caps?: [boolean, boolean]; lit?: boolean; off?: P2; rows?: number; outline?: boolean; capTone?: [number?, number?]; rims?: number[] };+/** A surface of revolution about frame F, shaded in exact light bands: every band's border is solved+ * per ring in closed form, so curved bodies never staircase, and a band that appears is born at zero width. */+export const turned = (ctx: Ctx, c: Cam, F: Frame, pr: Profile, m: Material, o: TurnOpts = {}) => {+ const [dx, dy] = o.off ?? [0, 0], P = (q: V3): P2 => { const s = c.p(q); return [s[0] + dx, s[1] + dy]; };+ const pl = (w: V3) => [dot(w, F.u), dot(w, F.v), dot(w, F.a)] as V3;+ const [vu, vv, va] = pl(c.V), [lu, lv, la] = pl(c.L), phV = Math.atan2(vv, vu), Vp = Math.hypot(vu, vv), phL = Math.atan2(lv, lu), Lp = Math.hypot(lu, lv);+ const screenLen = Math.hypot(...(c.dv(mul(F.a, pr.s1 - pr.s0)) as [number, number])) + c.k * Math.abs(pr.r(pr.s1) - pr.r(pr.s0));+ const N = o.rows ?? Math.max(8, Math.min(120, Math.ceil(screenLen / (2.5 * (HAND.coarse ?? 1)))));+ const ss = Array.from({ length: N + 1 }, (_, i) => pr.s0 + ((pr.s1 - pr.s0) * i) / N);+ const rows = ss.map((s) => {+ const r = pr.r(s), d = pr.dr(s), len = Math.hypot(1, d), nr = 1 / len, na = -d / len;+ const vis = Vp < 1e-9 ? (na * va > 0 ? Math.PI : 0) : Math.acos(Math.max(-1, Math.min(1, (-na * va) / (nr * Vp))));+ const lvl = THRESH.map((t) => (Lp < 1e-9 ? (na * la >= t ? ([-vis, vis] as Arc) : null) : band(wrap(phL - phV), (t - na * la) / (nr * Lp), vis)));+ return { s, r, vis, lvl };+ });+ const pt = (i: number, rel: number) => P(at(F, rows[i].s, rows[i].r, phV + rel));+ // the region between two angle curves over runs of rows where it exists; it closes to a point where it is born+ const region = (get: (i: number) => Arc): P2[][] => {+ const polys: P2[][] = []; let i = 0;+ while (i <= N) {+ if (!get(i)) { i++; continue; }+ const j0 = i; while (i <= N && get(i)) i++; const j1 = i - 1;+ const left: P2[] = [], right: P2[] = [];+ if (j0 > 0) { const a = get(j0)!; left.push(pt(j0 - 1, (a[0] + a[1]) / 2)); }+ for (let j = j0; j <= j1; j++) { const a = get(j)!; left.push(pt(j, a[0])); right.push(pt(j, a[1])); }+ if (j1 < N) { const a = get(j1)!; right.push(pt(j1 + 1, (a[0] + a[1]) / 2)); }+ // at an end of the solid the band is bounded by the end's circle, never by a chord across it+ const arc = (i: number, from: number, to: number) => { const n = Math.max(2, Math.min(16, Math.ceil((Math.abs(to - from) * c.k * rows[i].r) / 5))); return Array.from({ length: n - 1 }, (_, k) => pt(i, from + ((to - from) * (k + 1)) / n)); };+ const tail = j1 === N ? arc(N, get(N)![0], get(N)![1]) : [], head = j0 === 0 ? arc(0, get(0)![1], get(0)![0]) : [];+ polys.push(left.concat(tail, right.reverse(), head));+ }+ return polys;+ };+ const sideArc = (i: number): Arc => (rows[i].vis > 0.01 ? [-rows[i].vis, rows[i].vis] : null);+ const ring = (i: number, steps = 64) => Array.from({ length: steps }, (_, j) => pt(i, (j / steps) * 2 * Math.PI));+ const lit = o.lit ? 0.35 : 0;+ region(sideArc).forEach((p) => tone(ctx, p, m, 0 + lit));+ // the bands nest, so one that lands on the same tone as the band under it adds nothing+ let under = HAND.step?.(lit, m);+ for (let t = 0; t < 4; t++) { const q = Math.min(t === 3 ? 4 : 3.4, t + 1) + lit, k = HAND.step?.(q, m); if (k !== undefined && k === under) continue; under = k; region((i) => rows[i].lvl[t]).forEach((p) => tone(ctx, p, m, q)); }+ // end caps: a disc faces the viewer at one end at most+ const caps = o.caps ?? [true, true], capVis = [dot(F.a, c.V) < 0, dot(F.a, c.V) > 0];+ const capIdx = [0, N];+ [0, 1].forEach((e) => { if (!caps[e] || !capVis[e]) return; const nrm = e ? F.a : mul(F.a, -1); tone(ctx, ring(capIdx[e]), m, (o.capTone?.[e] ?? toneOf(c, nrm)) + lit); });+ for (const s of o.rims ?? []) { const i = Math.round(((s - pr.s0) / (pr.s1 - pr.s0)) * N), v = rows[i].vis; if (v > 0.05) ink(ctx, Array.from({ length: 33 }, (_, j) => pt(i, -v + (2 * v * j) / 32)), "seam", m); }+ if (o.outline === false) return;+ const w: Role = o.lit ? "lit" : "out";+ [0, 1].forEach((e) => { const i = capIdx[e]; if (caps[e] && capVis[e]) ink(ctx, ring(i), "in", m, true); });+ const L: P2[] = [], Rr: P2[] = [];+ rows.forEach((row, i) => { if (row.vis > 0.01) { L.push(pt(i, -row.vis)); Rr.push(pt(i, row.vis)); } });+ ink(ctx, L, w, m); ink(ctx, Rr, w, m);+ [0, 1].forEach((e) => { const i = capIdx[e], v = rows[i].vis; if (caps[e] && capVis[e]) ink(ctx, Array.from({ length: 33 }, (_, j) => pt(i, v + ((2 * Math.PI - 2 * v) * j) / 32)), w, m); else if (v > 0.01) ink(ctx, Array.from({ length: 33 }, (_, j) => pt(i, -v + (2 * v * j) / 32)), w, m); });+};++/** a flat disc (a washer face, a screw head, a dial) lying in the plane through `o` with normal `n` */+export const disc = (c: Cam, o: V3, n: V3, r: number, steps = 32, off: P2 = [0, 0]): P2[] => {+ const F = frameAlong(o, n); return Array.from({ length: steps }, (_, i) => { const s = c.p(at(F, 0, r, (i / steps) * 2 * Math.PI)); return [s[0] + off[0], s[1] + off[1]] as P2; });+};+/** a slotted screw head seated on a face: domed disc, rim line, slot */+export const screw = (ctx: Ctx, c: Cam, o: V3, n: V3, r: number, m: Material, slot = 0.6, off: P2 = [0, 0]) => {+ const F = frameAlong(o, n), lift = add(o, mul(F.a, r * 0.35));+ tone(ctx, disc(c, o, n, r, 24, off), m, toneOf(c, n) - 0.6); ink(ctx, disc(c, o, n, r, 24, off), "hair", m, true);+ tone(ctx, disc(c, lift, n, r * 0.72, 24, off), m, toneOf(c, n));+ const e = [at(F, r * 0.35, r * 0.7, slot), at(F, r * 0.35, r * 0.7, slot + Math.PI)].map((q) => { const s = c.p(q); return [s[0] + off[0], s[1] + off[1]] as P2; });+ ink(ctx, e, "in", m);+};++/** a flat plate of any convex outline lying in a frame's (u, v) plane, thickness t along its axis: a lever, a vane, a bracket */+export const slab = (ctx: Ctx, c: Cam, F: Frame, ring: P2[], t: number, m: Material, o: { lit?: boolean; off?: P2 } = {}) => {+ const [dx, dy] = o.off ?? [0, 0], P = (q: V3): P2 => { const s = c.p(q); return [s[0] + dx, s[1] + dy]; };+ const R = ccw(ring) ? ring : [...ring].reverse(), n = R.length, W3 = (q: P2, s: number): V3 => add(add(F.o, mul(F.a, s)), add(mul(F.u, q[0]), mul(F.v, q[1])));+ const back = R.map((q) => P(W3(q, 0))), front = R.map((q) => P(W3(q, t))), out = hull(back.concat(front)), lit = o.lit ? 0.3 : 0;+ knock(ctx, out);+ for (let i = 0; i < n; i++) {+ const a = R[i], b = R[(i + 1) % n], nn = unit(add(mul(F.u, b[1] - a[1]), mul(F.v, -(b[0] - a[0]))));+ if (dot(nn, c.V) > 1e-6) tone(ctx, [back[i], back[(i + 1) % n], front[(i + 1) % n], front[i]], m, Math.min(3, toneOf(c, nn)) + lit);+ }+ const capN = dot(F.a, c.V) > 0 ? F.a : mul(F.a, -1), cap = dot(F.a, c.V) > 0 ? front : back;+ tone(ctx, cap, m, toneOf(c, capN) + lit); ink(ctx, cap, "crease", m, true);+ ink(ctx, out, o.lit ? "lit" : "out", m, true);+};+/** a 2D outline of a bar with round ends, from (0,0) to (len,0), half-width w: a lever's plan */+export const leverRing = (len: number, w: number, w2 = w, steps = 10): P2[] => [+ ...Array.from({ length: steps + 1 }, (_, i) => { const a = Math.PI / 2 + (i / steps) * Math.PI; return [Math.cos(a) * w, Math.sin(a) * w] as P2; }),+ ...Array.from({ length: steps + 1 }, (_, i) => { const a = -Math.PI / 2 + (i / steps) * Math.PI; return [len + Math.cos(a) * w2, Math.sin(a) * w2] as P2; }),+];++// ---------------------------------------------------------------- tubes along 3D routes+/** fillet each corner of a 3D polyline with radius R (quadratic Bezier through the corner) */+export const fillet = (pts: V3[], R: number): V3[] => {+ if (pts.length < 3) return pts; const out: V3[] = [pts[0]];+ for (let i = 1; i < pts.length - 1; i++) {+ const a = pts[i - 1], b = pts[i], d = pts[i + 1], ui = unit(sub(b, a)), uo = unit(sub(d, b)), th = Math.acos(Math.max(-1, Math.min(1, dot(ui, uo))));+ const cut = Math.min(R * Math.tan(th / 2), 0.48 * Math.hypot(...sub(b, a)), 0.48 * Math.hypot(...sub(d, b))), p0 = sub(b, mul(ui, cut)), p1 = add(b, mul(uo, cut)), n = Math.max(3, Math.ceil((10 * th) / (Math.PI / 2)));+ for (let j = 0; j <= n; j++) { const t = j / n, q = (x: V3, y: V3) => add(x, mul(sub(y, x), t)); out.push(q(q(p0, b), q(b, p1))); }+ }+ out.push(pts[pts.length - 1]); return out;+};+/** a round tube along a route: body, a shade stripe, a shine stripe, outlines and visible end caps */+export const tubeAlong = (ctx: Ctx, c: Cam, route: V3[], r: number, m: Material, o: { bend?: number; caps?: [boolean, boolean]; off?: P2; lit?: boolean } = {}) => {+ const pts = fillet(route, o.bend ?? Math.max(3, 2.6 * r)), [dx, dy] = o.off ?? [0, 0], S = pts.map((q) => { const s = c.p(q); return [s[0] + dx, s[1] + dy] as P2; }), h = r * c.k;+ const nrm = S.map((_, i) => { const a = S[Math.max(0, i - 1)], b = S[Math.min(S.length - 1, i + 1)], tx = b[0] - a[0], ty = b[1] - a[1], l = Math.hypot(tx, ty) || 1; return [-ty / l, tx / l] as P2; });+ const off = (f: number) => S.map((p, i) => [p[0] + nrm[i][0] * h * f, p[1] + nrm[i][1] * h * f] as P2);+ const Ls: P2 = [-0.55, -0.835], wv = nrm.map((n) => n[0] * Ls[0] + n[1] * Ls[1]);+ const strip = (centre: number, half: number) => { const L: P2[] = [], R: P2[] = []; S.forEach((p, i) => { const cc = centre * wv[i]; L.push([p[0] + nrm[i][0] * h * (cc - half), p[1] + nrm[i][1] * h * (cc - half)]); R.push([p[0] + nrm[i][0] * h * (cc + half), p[1] + nrm[i][1] * h * (cc + half)]); }); return L.concat(R.reverse()); };+ const lit = o.lit ? 0.3 : 0;+ const cap = (i: number, dir: number) => { const j = Math.min(pts.length - 1, Math.max(0, i + dir)), T = unit(sub(pts[i], pts[j])); return { pts: disc(c, pts[i], T, r, 28, [dx, dy]), facing: dot(T, c.V) > 0 }; };+ const caps = o.caps ?? [true, true], ends = [cap(0, 1), cap(pts.length - 1, -1)];+ tone(ctx, off(1).concat(off(-1).reverse()), m, 2 + lit);+ ends.forEach((e, k) => { if (caps[k]) tone(ctx, e.pts, m, 2 + lit); });+ if (h > 1.3) { tone(ctx, strip(-0.62, 0.2), m, 0.6 + lit); tone(ctx, strip(0.44, 0.24), m, 4); }+ ends.forEach((e, k) => { if (caps[k] && e.facing) { tone(ctx, e.pts, m, 3 + lit); ink(ctx, e.pts, "in", m, true); } });+ ink(ctx, off(1), o.lit ? "lit" : "out", m); ink(ctx, off(-1), o.lit ? "lit" : "out", m);+};++// ---------------------------------------------------------------- the parts list, depth-sorted+export type Item = { id: string; at: V3; bias?: number; ride?: string; draw: (ctx: Ctx, off: P2) => void };+/** paint items far to near; each rides its assembly's world offset `move[ride] * share[ride]` */+export const paintAll = (ctx: Ctx, c: Cam, items: Item[], move: Record<string, V3> = {}, share: Record<string, number> = {}) => {+ const keyed = items.map((it, i) => { const mv = it.ride && move[it.ride] ? mul(move[it.ride], share[it.ride] ?? 0) : ([0, 0, 0] as V3); return { it, i, mv, key: c.depth(add(it.at, mv)) + (it.bias ?? 0) }; });+ keyed.sort((a, b) => a.key - b.key || a.i - b.i);+ for (const k of keyed) { OFFSET = c.dv(k.mv); k.it.draw(ctx, OFFSET); }+ OFFSET = [0, 0];+};++// ---------------------------------------------------------------- springs and the exploded view+/** closed-form damped spring from (x0, v0) toward g after tau seconds: any damping ratio z */+export const springAt = (w: number, z: number, x0: number, v0: number, g: number, tau: number): { x: number; v: number } => {+ if (tau <= 0) return { x: x0, v: v0 };+ const e0 = x0 - g;+ if (z < 0.999) { const wd = w * Math.sqrt(1 - z * z), A = e0, B = (v0 + z * w * e0) / wd, ex = Math.exp(-z * w * tau), co = Math.cos(wd * tau), si = Math.sin(wd * tau); return { x: g + ex * (A * co + B * si), v: ex * ((B * wd - z * w * A) * co - (A * wd + z * w * B) * si) }; }+ if (z <= 1.001) { const B = v0 + w * e0, ex = Math.exp(-w * tau); return { x: g + ex * (e0 + B * tau), v: ex * (B - w * (e0 + B * tau)) }; }+ const s = w * Math.sqrt(z * z - 1), r1 = -z * w + s, r2 = -z * w - s, C2 = (v0 - r1 * e0) / (r2 - r1), C1 = e0 - C2; return { x: g + C1 * Math.exp(r1 * tau) + C2 * Math.exp(r2 * tau), v: C1 * r1 * Math.exp(r1 * tau) + C2 * r2 * Math.exp(r2 * tau) };+};+export type ExplodePlan = { order: string[]; stagger: number; w: number; z: number };+/** The share (0 home, 1 apart) of every assembly at time t, from a list of cues (t, apart).+ * Opening runs in `order`, closing in reverse; a cue that lands mid-stagger cancels the moves+ * still pending and re-staggers only the assemblies whose target actually changes. Pure. */+export const sharesAt = (plan: ExplodePlan, cues: { t: number; apart: boolean }[], t: number): Record<string, number> => {+ const n = plan.order.length, ev: { t: number; g: number }[][] = plan.order.map(() => []);+ const targetAt = (i: number, time: number) => { let g = 0; for (const e of ev[i]) if (e.t <= time) g = e.g; return g; };+ for (const cue of [...cues].sort((a, b) => a.t - b.t)) {+ if (cue.t > t) break; const g = cue.apart ? 1 : 0;+ for (let i = 0; i < n; i++) ev[i] = ev[i].filter((e) => e.t <= cue.t);+ const idx = Array.from({ length: n }, (_, i) => i).filter((i) => targetAt(i, cue.t) !== g); if (!cue.apart) idx.reverse();+ idx.forEach((i, k) => ev[i].push({ t: cue.t + k * plan.stagger, g }));+ }+ const out: Record<string, number> = {};+ plan.order.forEach((id, i) => { let x = 0, v = 0, t0 = 0, g = 0; for (const e of ev[i]) { if (e.t > t) break; const s = springAt(plan.w, plan.z, x, v, g, e.t - t0); x = s.x; v = s.v; t0 = e.t; g = e.g; } out[id] = springAt(plan.w, plan.z, x, v, g, t - t0).x; });+ return out;+};+/** a one-shot envelope by age in seconds: smoothstep attack, exponential release; 0 before and long after */+export const envelope = (age: number, rise = 0.06, fall = 0.35) => (age < 0 ? 0 : age < rise ? smooth(0, rise, age) : Math.exp(-(age - rise) / fall));++// ---------------------------------------------------------------- template lettering and the card+/** single-stroke technical lettering, as with a scriber and template: one even weight, upright, crisp */+export const stencil = (ctx: Ctx, text: string, x: number, y: number, o: { cap?: number; colour?: string; align?: "left" | "center" | "right"; w?: number; track?: number; alpha?: number } = {}) => {+ const cap = o.cap ?? 12, s = cap / 6, track = o.track ?? 2.2, col = o.colour ?? "#26252b", Wd = stencilWidth(text, cap, track);+ let cx = o.align === "center" ? x - Wd / 2 : o.align === "right" ? x - Wd : x;+ ctx.globalAlpha = o.alpha ?? 1; ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = o.w ?? Math.max(0.9, cap * 0.1); ctx.lineCap = "round"; ctx.lineJoin = "round";+ for (const ch of text) {+ if (ch === "·") { ctx.beginPath(); ctx.arc(cx + 1.5 * s, y + 3 * s, ctx.lineWidth * 0.75, 0, Math.PI * 2); ctx.fill(); cx += (3 + track) * s; continue; }+ if (ch === " ") { cx += (2.6 + track) * s; continue; }+ const g = G[ch] ?? G[ch.toUpperCase()] ?? G["-"]; ctx.beginPath();+ for (const st of [...(g.l ?? []), ...(g.c ?? [])]) st.forEach(([px, py], i) => (i ? ctx.lineTo(cx + px * s, y + py * s) : ctx.moveTo(cx + px * s, y + py * s)));+ ctx.stroke(); cx += ((g.w ?? 4) + track) * s;+ }+ ctx.globalAlpha = 1;+};+export const stencilWidth = (text: string, cap = 12, track = 2.2) => { const s = cap / 6; let w = 0; for (const ch of text) w += ch === "·" ? (3 + track) * s : ch === " " ? (2.6 + track) * s : glyphWidth(ch, cap, 0) + track * s; return w - track * s; };+export type CardText = { fig: string; title: string; hint: string; read: string };+/** The figure card, in the current hand: its ground, one rule, and the four corners: figure number, title, hint, live readout. */+/** a frame must never inherit pen state from the frame drawn before it */+export const freshPen = (ctx: Ctx) => { ctx.setLineDash([]); ctx.lineDashOffset = 0; ctx.lineCap = "butt"; ctx.lineJoin = "miter"; ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; };+export const card = (ctx: Ctx, W: number, H: number, t: CardText, o: { pad?: number; cap?: number; progress?: number; part?: "all" | "ground" | "words" } = {}) => {+ const pad = o.pad ?? 34, cap = o.cap ?? 13, p = o.progress ?? 1, part = o.part ?? "all"; freshPen(ctx);+ if (part !== "words") { HAND.sheet(ctx, W, H); if (p <= 0) return; HAND.frame(ctx, W, H, clamp01(p * 1.6)); }+ if (part === "ground" || p <= 0) return;+ const ty = clamp01((p - 0.5) * 2), i = pad + 22, top = pad + 20, bot = H - pad - 20 - cap;+ if (part === "words" && ty > 0) { // over a figure that fills the card, each word sits on its own cut of ground+ const sz = (s: string) => stencilWidth(s, cap) + 14, cut = (x: number, y: number, w: number) => HAND.knock(ctx, [[x - 7, y - 7], [x + w - 7, y - 7], [x + w - 7, y + cap + 7], [x - 7, y + cap + 7]]);+ cut(i, top, sz(t.fig)); cut(W - i - sz(t.title) + 14, top, sz(t.title)); cut(i, bot, sz(t.hint)); cut(W - i - sz(t.read) + 14, bot, sz(t.read));+ }+ if (ty > 0) {+ const upTo = (w: string) => (ty >= 1 ? w : w.slice(0, Math.ceil(w.length * ty))); // lettered left to right, never faded in+ HAND.text(ctx, upTo(t.fig), i, top, { cap }); if (ty >= 1) HAND.text(ctx, t.title, W - i, top, { cap, align: "right", soft: true }); else HAND.text(ctx, upTo(t.title), W - i - stencilWidth(t.title, cap) + stencilWidth(upTo(t.title), cap), top, { cap, align: "right", soft: true });+ HAND.text(ctx, upTo(t.hint), i, bot, { cap, soft: true }); if (ty >= 1) HAND.text(ctx, t.read, W - i, bot, { cap, align: "right" }); else HAND.text(ctx, upTo(t.read), W - i - stencilWidth(t.read, cap) + stencilWidth(upTo(t.read), cap), bot, { cap, align: "right" });+ }+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismPencil.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismPencil.tsnew file mode 100644index 0000000..d910b65--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismPencil.ts@@ -0,0 +1,5 @@+// The 18-note movement in the colouredPencil hand: a machine is a subject, drawn in any style.+import { mechanismIn } from "./mechanism";+import { colouredPencilHand } from "./mechanismHands";++export const mechanismPencil = mechanismIn("colouredPencil", colouredPencilHand);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismStipple.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismStipple.tsnew file mode 100644index 0000000..7041c7b--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismStipple.ts@@ -0,0 +1,5 @@+// The 18-note movement in the stipple hand: a machine is a subject, drawn in any style.+import { mechanismIn } from "./mechanism";+import { stippleHand } from "./mechanismHands";++export const mechanismStipple = mechanismIn("stipple", stippleHand);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/demos/mechanism-explorer.html b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/demos/mechanism-explorer.htmlnew file mode 100644index 0000000..b38d2dd--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/demos/mechanism-explorer.html@@ -0,0 +1,43 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>How a music box reads its tune</title>+<meta name="description" content="An anidoodle interactive demo: an 18-note music box movement that plays, and comes apart when you hover it.">+<style>+ :root { --paper: #efe8dc; --ink: #2b2a33; --soft: #6c6573; }+ * { box-sizing: border-box; }+ html, body { margin: 0; background: var(--paper); color: var(--ink); font: 17px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }+ main { max-width: 1100px; margin: 0 auto; padding: 40px 24px 60px; display: grid; grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.2fr); gap: 36px; align-items: center; }+ h1 { font-size: clamp(34px, 4.6vw, 56px); line-height: 1.05; letter-spacing: -0.02em; margin: 0 0 16px; font-weight: 650; }+ p { color: var(--soft); max-width: 36ch; margin: 0 0 14px; }+ ani-doodle { display: block; width: min(100%, 56vw); margin-left: auto; outline-offset: 6px; }+ button { font: 600 16px/1 ui-sans-serif, system-ui, sans-serif; padding: 14px 22px; border-radius: 999px; border: 2px solid var(--ink); background: var(--ink); color: var(--paper); cursor: pointer; margin-top: 8px; }+ button:focus-visible { outline: 3px solid #d0502a; outline-offset: 3px; }+ article { max-width: 760px; margin: 0 auto; padding: 0 24px 120px; color: var(--soft); }+ article h2 { color: var(--ink); font-size: 26px; margin: 40px 0 10px; }+ ani-doodle:focus-visible { outline: 2px solid var(--ink); }+ @media (max-width: 760px) { main { grid-template-columns: 1fr; } ani-doodle { margin: 0 auto; } }+</style>+</head>+<body>+<main>+ <section>+ <h1>The pins are the score.</h1>+ <p>A music box stores its tune as pins on a turning drum. Each pin lifts one tuned steel tooth, and the tooth rings.</p>+ <p>Hover the movement, or Tab to it, and it comes apart. Point at a part to see what it does.</p>+ <button type="button" data-anidoodle="apart">Take it apart</button>+ </section>+ <ani-doodle piece="mechanism-explorer" tabindex="0"></ani-doodle>+</main>+<article>+ <h2>Eighteen teeth, one drum</h2>+ <p>The comb is a single steel plate cut into eighteen teeth, each filed to a pitch. The long bass teeth carry small lead weights underneath, which lower them further than length alone could.</p>+ <p>The drum turns once in about ten seconds. Every pin is a note at a moment: where it sits along the drum picks the tooth, and how far round it sits picks the time.</p>+ <h2>Why it keeps time</h2>+ <p>A spring would let the drum race. The governor spins a small two-blade fan on a worm, and the air it pushes against holds the tempo steady from the first bar to the last.</p>+</article>+<!--anidoodle-->+</body>+</html>diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanism.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanism.tsnew file mode 100644index 0000000..1c8c577--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanism.ts@@ -0,0 +1,4 @@+import { mechanism } from "../canvas-core/mechanism";+import { mountFilm } from "./page";++mountFilm(mechanism);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.tsnew file mode 100644index 0000000..f4abd46--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.ts@@ -0,0 +1,4 @@+import { mechanismBlueprint } from "../canvas-core/mechanismBlueprint";+import { mountFilm } from "./page";++mountFilm(mechanismBlueprint);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismDraw.tsnew file mode 100644index 0000000..3891e08--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismDraw.ts@@ -0,0 +1,4 @@+import { mechanismDraw } from "../canvas-core/mechanismDraw";+import { mountFilm } from "./page";++mountFilm(mechanismDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismPencil.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismPencil.tsnew file mode 100644index 0000000..1f42662--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismPencil.ts@@ -0,0 +1,4 @@+import { mechanismPencil } from "../canvas-core/mechanismPencil";+import { mountFilm } from "./page";++mountFilm(mechanismPencil);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismStipple.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismStipple.tsnew file mode 100644index 0000000..1d60455--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismStipple.ts@@ -0,0 +1,4 @@+import { mechanismStipple } from "../canvas-core/mechanismStipple";+import { mountFilm } from "./page";++mountFilm(mechanismStipple);diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.tsnew file mode 100644index 0000000..5523d22--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts@@ -0,0 +1,67 @@+// MECHANISM KIT TESTS. The kit's claims are arithmetic: the camera is the house dimetric at 45/30, the+// light ladder is monotone, the springs are exact closed forms, an exploded view staggers out and folds+// back last-out-first-home, hatching stays inside its shape, and the music box's words come from its pins.+// node tools/test.mjs mechanism+import { Cam, level, springAt, sharesAt, type ExplodePlan, hand, flatHand } from "../src/canvas-core/mechanismKit";+import { Iso } from "../src/canvas-core/isometricKit";+import { hatchSegs } from "../src/canvas-core/mechanismHands";+import { play, PLAN, REV } from "../src/canvas-core/mechanism";++export const name = "mechanism";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;++ // 1. the camera at 45/30 is exactly the house 2:1 dimetric+ const k = 20, c = new Cam(45, 30, k, 300, 200), iso = new Iso(null as unknown as CanvasRenderingContext2D, (k * Math.SQRT2) / 2, 300, 200);+ const pts: [number, number, number][] = [[0, 0, 0], [3, -2, 5], [-4, 7, 1.5]];+ ok(pts.every((q) => { const a = c.p(q), b = iso.p(...q); return near(a[0], b[0], 1e-3) && near(a[1], b[1], 1e-2); }), "Cam(45, 30) projects like Iso.p (Iso rounds cos 30 to 4 places)");+ ok(c.depth(c.V) > c.depth([0, 0, 0]), "depth grows toward the viewer");+ const off = c.dv([2, -1, 3]), a0 = c.p([1, 1, 1]), a1 = c.p([3, 0, 4]);+ ok(near(a1[0] - a0[0], off[0], 1e-9) && near(a1[1] - a0[1], off[1], 1e-9), "dv is the screen offset of a world move");++ // 2. the light ladder: 0 to 4, monotone, whole numbers away from the thresholds+ const xs = Array.from({ length: 201 }, (_, i) => -1 + i / 100), ls = xs.map((x) => level(x));+ ok(ls.every((v, i) => !i || v >= ls[i - 1]), "level never falls as the light score rises");+ ok(near(level(-1), 0) && near(level(1), 4) && near(level(0.1), 1) && near(level(0.3), 2) && near(level(0.5), 3), "level is 0..4 and an integer between thresholds");+ ok(level(0.2) > 1.4 && level(0.2) < 1.6, "level crossfades across a threshold instead of flipping");++ // 3. springs: exact, continuous, and the damping ratio means what it says+ const step = (z: number) => Array.from({ length: 400 }, (_, i) => springAt(8, z, 0, 0, 1, i / 100).x);+ const crit = step(1), under = step(0.89), over = step(1.6);+ ok(crit.every((x) => x <= 1 + 1e-12), "critically damped: never overshoots");+ ok(Math.max(...under) > 1.0005 && Math.max(...under) < 1.05, `z 0.89: one faint overshoot (peak ${Math.max(...under).toFixed(4)})`);+ ok(over.every((x) => x <= 1 + 1e-12) && over[50] < crit[50], "overdamped: slower, no overshoot");+ ok([crit, under, over].every((s) => Math.abs(s[399] - 1) < 2e-3), "every spring arrives");+ for (const z of [0.6, 1, 1.4]) { const t = 0.37, h = 1e-6, v = springAt(8, z, 0.2, -0.5, 1, t).v, num = (springAt(8, z, 0.2, -0.5, 1, t + h).x - springAt(8, z, 0.2, -0.5, 1, t - h).x) / (2 * h); ok(Math.abs(v - num) < 1e-4, `z ${z}: velocity is the derivative of position`); }+ ok(springAt(8, 0.89, 0.3, 2, 1, 0).x === 0.3, "at tau 0 a spring is where it starts");++ // 4. the exploded view+ const P: ExplodePlan = { order: ["a", "b", "c", "d"], stagger: 0.1, w: 8, z: 0.89 };+ const open = [{ t: 1, apart: true }];+ ok(Object.values(sharesAt(P, open, 0.99)).every((v) => v === 0), "nothing moves before the cue");+ const early = sharesAt(P, open, 1.15); ok(early.a > early.b && early.b > 0 && early.c === 0 && early.d === 0, "it opens in order, one stagger apart");+ ok(Object.values(sharesAt(P, open, 5)).every((v) => Math.abs(v - 1) < 1e-3), "and arrives apart");+ const cycle = [{ t: 1, apart: true }, { t: 4, apart: false }], back = sharesAt(P, cycle, 4.12);+ ok(back.d < back.a && back.c < back.a, "it folds back last-out first-home");+ ok(Object.values(sharesAt(P, cycle, 9)).every((v) => Math.abs(v) < 1e-3), "and comes all the way home");+ const rev = [{ t: 1, apart: true }, { t: 1.15, apart: false }], r = sharesAt(P, rev, 1.2);+ ok(r.c === 0 && r.d === 0, "a reversal mid-stagger cancels the moves still pending");+ ok(Object.values(sharesAt(P, rev, 8)).every((v) => Math.abs(v) < 1e-3), "and what had left comes home");+ ok(JSON.stringify(sharesAt(P, cycle, 2.5)) === JSON.stringify(sharesAt(P, [...cycle].reverse(), 2.5)), "cue order in the list does not matter");++ // 5. hatching stays inside its shape and is anchored, not screen-locked+ const sq: [number, number][] = [[0, 0], [40, 0], [40, 30], [0, 30]], segs = hatchSegs(sq, Math.PI / 4, 4);+ ok(segs.length > 10 && segs.every(([a, b]) => [a, b].every(([x, y]) => x >= -1e-6 && x <= 40 + 1e-6 && y >= -1e-6 && y <= 30 + 1e-6)), `hatching: ${segs.length} lines, all inside the square`);+ const moved = hatchSegs(sq.map(([x, y]) => [x + 7, y + 3] as [number, number]), Math.PI / 4, 4, [7, 3]);+ ok(moved.length === segs.length && moved.every(([a], i) => near(a[0], segs[i][0][0] + 7, 1e-6) && near(a[1], segs[i][0][1] + 3, 1e-6)), "anchored hatching travels with its part");++ // 6. the music box: one model for pins, teeth and words+ ok(PLAN.order.length === 8, "eight assemblies");+ const quiet = play(0.0001);+ ok(/^PIN [12] · TOOTH \d+ · [A-G]#?\d \d+ HZ$/.test(quiet.read), `at the start the first chord speaks (its top note): ${quiet.read}`);+ const a4 = play(2 * Math.PI * (16 / 32) + 1e-6).read; ok(a4.includes("A4 440 HZ") || a4.includes("F3"), `at step 16 the readout names that step's pin: ${a4}`);+ const loop = play(2 * Math.PI * 3 + 0.4), first = play(0.4);+ ok(loop.read === first.read && loop.bend.every((v, i) => near(v, first.bend[i], 0.05)), "the drum's story repeats every turn");+ ok(REV > 0 && hand().id === "flat", "the kit's default hand is the plain reference hand");+ void flatHand;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/choreo/mechanism-explorer.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/choreo/mechanism-explorer.mjsnew file mode 100644index 0000000..fde1ed6--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/choreo/mechanism-explorer.mjs@@ -0,0 +1,11 @@+// ~14 s of a visitor: watch it play, hover the movement (it comes apart), point at the drum, the+// comb and the governor (each lights and the readout says what it does), leave (it folds home and plays).+export default async (r) => {+ await r.hold(70);+ const c = await r.box("ani-doodle canvas"), at = (fx, fy) => ({ x: c.x + c.width * fx, y: c.y + c.height * fy });+ await r.glide(at(0.5, 0.55), 26); await r.hold(70);+ await r.glide(at(0.5, 0.22), 22); await r.hold(46);+ await r.glide(at(0.3, 0.47), 22); await r.hold(46);+ await r.glide(at(0.82, 0.3), 22); await r.hold(46);+ await r.glide({ x: c.x - 120, y: c.y + c.height * 0.5 }, 24); await r.hold(80);+};diff --git a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md b/plugins/anidoodle/skills/anidoodle/references/craft-bar.mdindex 38cecc4..bab6955 100644--- a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md+++ b/plugins/anidoodle/skills/anidoodle/references/craft-bar.md@@ -6,6 +6,9 @@ The test: would a proud human illustrator ship this, or is it mechanical shape-a|---|---|| A subject built from ellipses and capsules | Hand-placed control points over real anatomy || One style recoloured to look like another | The mark, the edge and the order of marks all change |+| Boxes and arrows standing for an idea | A real machine whose working IS the idea, many small parts, each with a job (`machines.md`) |+| A line that stops in the air; a texture cut dead mid-surface | Every line ends on something; a row of ribs or pins fades as the surface turns away |+| Parts floating off or sunk into each other | Every joint flush, tangent or seated, every part held; check the joints at 3x || Flat colour fields | Wash, then pattern wet-on-damp, then line; one named light; cast shadows || Every stroke the same weight and speed | Long strokes fast, fiddly ones slow, thick-thin, tapered || Even scatter, one flower stamped 200 times | Hand-placed drifts with bare rests; 4-5 authored views per species |diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/explainer.md b/plugins/anidoodle/skills/anidoodle/references/workflows/explainer.mdindex 6c9d664..9b1cfc4 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/explainer.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/explainer.md@@ -27,6 +27,8 @@ review when the person wants that step; otherwise build from it.- **Captions are drawn lettering** (`lettering.ts`, `drafting.ts`, a style's own hand), sized forthe smallest shape the piece ships in. Keep them short enough to read twice in their time onscreen.+- **A mechanism beats a diagram.** When the idea has moving parts, build it as a real machine that+ comes apart and reads out its own state, in whichever style the piece uses: `machines.md`.- **A recurring guide** (a mascot, a hand, an object) gives continuity across chapters; build itonce as a character module.- **Charts are drawn to scale** from the ledger's numbers, labelled with the values they reach,diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.md b/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.mdindex e9a6ac5..f5a3041 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.md@@ -10,6 +10,7 @@ Three worked demos. Each is one self-contained HTML file that opens offline:|---|---|| **Landing mascot** (`mascotHero`) | Bit watches your pointer anywhere on the page, eyes first and head a beat later. Hover or Tab to a button and he turns, presents it with his near arm, raises his brows and brightens his bulb. Press: a crouch. Click "Get started": he jumps and cheers, with pencil twinkles. "Take the tour" gets a wave, and poking him makes him giggle. || **Scroll-drawn hero** (`scrollHero`) | The storybook plate draws itself as you scroll: construction ovals, a head-first pencil sketch, washes spreading from where the brush lands, then the final line, with a pencil or brush at the nib throughout. Scroll back and it un-draws. The last frame is the plate itself, pixel for pixel. |+| **Machine explorer** (`mechanismExplorer`) | A music box movement plays its tune. Hover, focus or press "Take it apart" and it comes apart outside-in, each assembly on its own bouncy spring; point at a part and it lights, and the readout says what it does. Built on `machines.md`. || **Form mascot** (`formMascot`) | He reads your caret, nodding at each keystroke, and shuts his eyes with hands up for the password. Press "Show" and he is caught peeking. A bad submit gets a worried head-shake. "Busy" whirs his key, and success is the cheer. |All three use the storybook plate's hand (pencil + watercolour). Bit is drawn by the plate's own@@ -34,7 +35,7 @@ proves it for every emitted page.| Can a drawn frame change later? | No. An event is stamped after every tick already drawn: `max(lastDrawn + 1, clock)`. || Initial configuration? | It is in the log at tick 0, before anything is drawn: target rectangles, scroll, reduced motion, state and device scale. || Resize, DPR? | Log coordinates are in the piece's logical space, so a resize logs new `rect`s and a `view` (the device scale), and changes no state. The host re-bakes at the new scale in the background and swaps on a frame boundary. |-| Interrupted motion? | Springs are critically damped and closed form. A target is a pure function of the discrete state, which only changes at events. Position and velocity carry across an interruption into a new exact segment. |+| Interrupted motion? | Springs are closed form, critically damped by default; `zeta: 0.8` to `0.9` lands with one faint overshoot, the weight of a real part. A target is a pure function of the discrete state, which only changes at events. Position and velocity carry across an interruption into a new exact segment. || One-shot reactions? | Fixed-length clips restarted by each trigger (`clip(s, "click:start", 72)`), with randomness seeded from the log (`reactionSeed`). || Keyboard? | Keyboard focus counts as hover (`attention` is the more recent of the two), and Enter or Space is a click. Every hover reaction has a focus equivalent. || Touch? | A tap logs its position. A lifted finger logs `exit` and `leave`, so nothing stays hovered. |diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/machines.md b/plugins/anidoodle/skills/anidoodle/references/workflows/machines.mdnew file mode 100644index 0000000..26db3d1--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/machines.md@@ -0,0 +1,92 @@+# Machines: explain an idea by building it, in any style++A machine is a subject, not a look. The kit (`engine/src/canvas-core/mechanismKit.ts`) builds real+parts in 3D, sorts them, takes them apart and folds them back; a **hand** marks them in a style's+own medium. The same music box draws as cyanotype, coloured pencil, stipple or flat iso planes.+Worked example: `mechanism.ts` (the 18-note movement), `mechanismHands.ts`, `mechanismExplorer.ts`.++## 1. Turn the idea into a machine++1. **State the truth.** Ledger the concept's real quantities: counts, sizes, rates, limits (`explainer.md`).+2. **Find its verbs** (fills, waits, matches, rejects, decays) and **its nouns with quantities**.+3. **Find a physical mechanism that performs those verbs on those nouns**, one a general reader can+ name: a lock for "every condition must match", drawers sized by bytes, a sluice for a queue.+4. **Say it in one sentence:** "X moves, and its motion means Y." If you cannot, the mapping is wrong.+5. **Give every part a meaning**, and mark where the metaphor stops being literal.+6. **Pick the one part to watch.** It alone gets the accent (`accent: true` on its material).+7. **Add an instrument that reads the quantity** (a dial, a ruler, a counter, a readout corner).+8. **Choose the view** so the mechanism faces the viewer: `Cam.fit(A, E, points, box)`, A 35 to 60.++Two failures, one fix: too abstract (floating slabs, labelled boxes) or too flat (one big plate+with a few lines). Fix both with a recognisable machine of many small, purposeful parts.++## 2. Parts list before geometry++Write the parts by group: base (plate, feet, screws, label, ruler), structure (posts, bridges,+rails, stops), mechanism, controls (crank, knob), and the subject. Every part rests on another+and has a job. A figure is 40 to 80 parts; a hero 80 to 150; past that, propose a smaller version+that keeps the core. Detail comes from structure (a boss under a shaft, holes in a bedplate, a+stop lever), never from texture noise. A bare face or an empty corner is unfinished, not calm.++## 3. One model drives everything++The film's moving parts, the readout and any caption all read one pure model of `(frame)` or of+the input state. In the music box, `play(rot)` places the pins, bends the teeth and names the pin,+the tooth and the pitch in the readout; nothing is typed twice. Read words from where parts ARE+(the readout says "TAKING APART" while any spring is moving), and build counts from the list that+draws them ("8 ASSEMBLIES APART" is `PLAN.order.length`).++## 4. Build with the kit++| Need | Use |+|---|---|+| Camera, depth, a world offset on screen | `Cam`, `Cam.fit`, `c.depth`, `c.dv` |+| Slabs, plates, boxes with rounded plans, seams, bevels | `prism`, `box`, `rrect`, `circle` |+| Drums, posts, knobs, domes: any surface of revolution | `turned` with `cyl`, `cone`, `sphere`; bands are exact, never staircased |+| A lever, a vane, a bracket in any plane | `slab` with `leverRing` or any convex outline |+| Pipes, wires, cables along a route | `tubeAlong` (filleted bends, end caps) |+| Screws, pins, ticks, ribs that fade as they turn away | `screw`, `facingAt` + `smooth` for alpha |+| Many parts in the right order | `paintAll(items)`; each item has `at`, `bias`, `ride` (its assembly) |+| An exploded view | `ExplodePlan` + `sharesAt(plan, cues, t)`: staggered out, last-out first-home, reversals cancel pending moves |+| A frame in a card with four corners (figure, title, hint, live readout) | `card` |++Rules that keep it clean: split a part that wraps another (back half, inner, front half); every+part is held by something; explode real assemblies along their true direction, the outside ones+first; draw a chain line along each path of travel; fit the figure to 55 to 65 percent of the card.++## 5. Draw it in a style: the hand++The kit never chooses a colour. It calls the current hand with meaning: a region and its tone `q`+(0 darkest side, 4 top), a line and its role (`out`, `lit`, `in`, `crease`, `seam`, `hair`,+`light`, `chain`), a dot, the card's sheet, rule and lettering. `setHand(h)` before painting,+`setHand(flatHand())` after. Shipped hands: `isometric` (fast, the default), `blueprint`, `colouredPencil`,+`stipple`. To add one, read the style's recipe in `references/styles/<id>.md` and answer five+questions in code:++1. **Is there light?** Blueprint has none (tone is section lining, only on the part to watch);+ stipple's light is dot density; pencil's is pressure and stacked passes.+2. **What is an edge?** A ruled line, a broken pencil contour heavier on the shade side, a denser+ row of dots, or nothing at all (iso planes meet tone to tone).+3. **How is the accent made?** A colour, section lining, or density.+4. **What is the ground?** Draw it once into a cached layer; `knock` paints it back over a part.+5. **Are the marks anchored?** Anchor hatching and dots to `offset()`, never to the screen, and+ seed them from the part, so a still part never boils and a moving one carries its marks.++## 6. Films and interactive pieces++Two films, not one: the making (`kind: "drawing"`, each part inked then toned in assembly order+with `setReveal(ink, tone, paper)`, then the words) and the run (`kind: "explainer"`: play close on+the part to watch, explode, tour, home). One film holding both fails the dead-air gate, because a+build's slow strokes are measured against an explainer's floor. While apart, let each assembly+breathe a little along its own path, out of step with the others, so the tour never freezes. An interactive piece (`interactive.md`): one+spring per assembly with `zeta` 0.8 to 0.9 so parts land with weight, outer ones faster; a fixed+camera so the card and the bench bake once; the part nearest the pointer lights and the readout+says what it does; reduced motion holds the drum still.++## 7. Check it++Render at `--scale 2` or 3 and crop every joint (flange, bridge, crank, wire end, tooth tips); the+fault list, in order: a line that stops in the air, a part sunk into or floating off another, a+nearer part drawn behind, a texture cut at full strength mid-surface, a doubled edge. Then+`node tools/test.mjs mechanism` and, for a page, `emit-interactive.mjs` and `replay.mjs` (22 checks,+including 6 ms a frame at DPR 2). Measured, not assumed: say which of these you ran.diff --git a/skills/anidoodle/SKILL.md b/skills/anidoodle/SKILL.mdindex 03f2a5b..5b78254 100644--- a/skills/anidoodle/SKILL.md+++ b/skills/anidoodle/SKILL.md@@ -35,7 +35,7 @@ say why in one line. Write the answers into a short brief before drawing.| A picture that draws itself (timelapse, making-of) | `references/workflows/drawing-process.md` || A loop, sticker, animated logo, ambient header | Loop workflow below, `references/formats.md` || A story film, any length | Film workflow below, `references/workflows/long-film.md` |-| An explainer or an infographic | `references/workflows/explainer.md` |+| An explainer or infographic; a machine that comes apart to explain an idea, in any style | `references/workflows/explainer.md`, `references/workflows/machines.md` || A launch or product video (their screenshots welcome) | `references/workflows/launch-video.md`; build it on `references/workflows/launch-video-kit.md` || An interactive web animation that reacts to the UI | `references/workflows/interactive.md` || A drawing lesson, or "how do I draw this?" | `references/workflows/teach-drawing.md` |diff --git a/skills/anidoodle/engine/package-lock.json b/skills/anidoodle/engine/package-lock.jsonindex f7051d0..397418f 100644--- a/skills/anidoodle/engine/package-lock.json+++ b/skills/anidoodle/engine/package-lock.json@@ -1,12 +1,12 @@{"name": "anidoodle-engine",- "version": "0.7.2",+ "version": "0.8.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "anidoodle-engine",- "version": "0.7.2",+ "version": "0.8.0","dependencies": {"esbuild": "0.25.12"},diff --git a/skills/anidoodle/engine/package.json b/skills/anidoodle/engine/package.jsonindex 48c833e..a201729 100644--- a/skills/anidoodle/engine/package.json+++ b/skills/anidoodle/engine/package.json@@ -1,6 +1,6 @@{"name": "anidoodle-engine",- "version": "0.7.2",+ "version": "0.8.0","private": true,"type": "module","description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",diff --git a/skills/anidoodle/engine/src/canvas-core/input.ts b/skills/anidoodle/engine/src/canvas-core/input.tsindex 1c7a6bc..d20cecd 100644--- a/skills/anidoodle/engine/src/canvas-core/input.ts+++ b/skills/anidoodle/engine/src/canvas-core/input.ts@@ -63,6 +63,8 @@ export type Discrete = {export type SpringSpec = {omega: number; // rad per tick. 0.2 settles in ~0.4 s; 0.08 is lazy+ zeta?: number; // damping ratio. Omitted or 1: critically damped, no overshoot. 0.85 to 0.9: lands+ // with one faint overshoot, the weight of a real part (an exploded view, a sprung button)target: (d: Discrete) => number | P; // MUST depend on d only: that is what makes it closed form};export type InputSpec = { springs: Record<string, SpringSpec>; init?: Partial<Pick<Discrete, "state" | "scroll" | "reduced">> };@@ -108,8 +110,15 @@ const apply = (d: Discrete, e: InputEvent) => {type Seg = { t0: number; tgt: number[]; x0: number[]; v0: number[] };const vec = (v: number | P): number[] => (typeof v === "number" ? [v] : [v[0], v[1]]);const unvec = (a: number[]): number | P => (a.length === 1 ? a[0] : [a[0], a[1]]);-const evalSeg = (s: Seg, w: number, t: number): { x: number[]; v: number[] } => {+const evalSeg = (s: Seg, w: number, t: number, z = 1): { x: number[]; v: number[] } => {const dt = t - s.t0; if (dt <= 0) return { x: s.tgt.map((g, i) => g + s.x0[i]), v: s.v0.slice() };+ if (z < 1) { // underdamped, still closed form: x(t) = g + e^(-z w t) (A cos wd t + B sin wd t)+ const wd = w * Math.sqrt(1 - z * z), ex = Math.exp(-z * w * dt), co = Math.cos(wd * dt), si = Math.sin(wd * dt);+ return {+ x: s.tgt.map((g, i) => { const A = s.x0[i], B = (s.v0[i] + z * w * A) / wd; return g + ex * (A * co + B * si); }),+ v: s.tgt.map((_, i) => { const A = s.x0[i], B = (s.v0[i] + z * w * A) / wd; return ex * ((B * wd - z * w * A) * co - (A * wd + z * w * B) * si); }),+ };+ }const e = Math.exp(-w * dt);return {x: s.tgt.map((g, i) => { const c = s.v0[i] + w * s.x0[i]; return g + (s.x0[i] + c * dt) * e; }),@@ -141,7 +150,7 @@ const advance = (spec: InputSpec, log: InputLog, f: Fold, to: number) => {const g = vec(s.target(f.d)), seg = f.segs[k];if (same(g, seg.tgt)) continue; // untouched springs keep their segment: bit-identical either wayif (f.d.reduced) { f.segs[k] = { t0: e.tick, tgt: g, x0: g.map(() => 0), v0: g.map(() => 0) }; continue; } // reduced motion: arrive, do not travel- const { x, v } = evalSeg(seg, s.omega, e.tick); // where it is and how fast, at the interruption+ const { x, v } = evalSeg(seg, s.omega, e.tick, s.zeta); // where it is and how fast, at the interruptionf.segs[k] = { t0: e.tick, tgt: g, x0: x.map((xi, i) => xi - g[i]), v0: v };}f.ref = e; f.idx++;@@ -162,7 +171,7 @@ export const stateAt = (tick: number, log: InputLog, spec: InputSpec): InputStatfor (let b = (k + 1) * CP; b <= t; b += CP) { advance(spec, log, f, b); if (cps.length === b / CP) cps.push(cloneFold(f, b)); }advance(spec, log, f, t);const spring: Record<string, number | P> = {}, vel: Record<string, number | P> = {};- for (const [k2, s] of Object.entries(spec.springs)) { const r = evalSeg(f.segs[k2], s.omega, t); spring[k2] = unvec(r.x); vel[k2] = unvec(r.v); }+ for (const [k2, s] of Object.entries(spec.springs)) { const r = evalSeg(f.segs[k2], s.omega, t, s.zeta); spring[k2] = unvec(r.x); vel[k2] = unvec(r.v); }return { ...f.d, tick: t, attention: attentionOf(f.d), spring, vel };};diff --git a/skills/anidoodle/engine/src/canvas-core/mechanism.ts b/skills/anidoodle/engine/src/canvas-core/mechanism.tsnew file mode 100644index 0000000..6293e8c--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanism.ts@@ -0,0 +1,285 @@+// MECHANISM · "Fig 1, the 18-note movement". A cylinder music box, drawn as an exploded technical figure.+//+// MEDIUM (physical): technical illustration as it was made for parts manuals and patent plates. A+// technical pen on drafting film: one even inner weight, the silhouette gone over a size heavier.+// Under the film, adhesive grey tone sheets cut with a knife to each face, four greys and a white+// for the tops, picked by which way the face looks at the lamp. One part, the one to watch, gets+// the single colour sheet. Lettering by scriber and template, upright and even.+// MARKS: the ruled line (silhouette, crease, seam), the cut tone shape, the dot (screw, pin), the+// template letter. EDGE: crisp; tone meets tone and a line sits on every outline.+// ORDER (the film): the card's rule -> the bench -> the parts in assembly order, each inked first+// (the pen runs its outlines) and then toned (the sheet laid and cut) -> the lettering -> the+// mechanism runs -> it comes apart into its assemblies and they are read out one by one -> it folds home.+// PALETTE: warm drafting-film white, four cool-to-warm greys per material, one brass sheet.+// LIGHT: one lamp, locked to the viewer, up and to the left: tops white, left faces light, right dark.+// SUBJECT + REALISM: an 18-note cylinder movement of the common Japanese pattern (reference, from+// knowledge: a die-cast zinc bedplate; a brass cylinder about 14 mm across carrying steel pins,+// turned between two bridges by a great wheel; a steel comb of 18 tuned teeth screwed to the plate+// through a heel block, the bass teeth longer and weighted with lead underneath; a spring barrel in a+// housing at one end, wound by a crank; an air-brake governor, a worm and a two-blade fan on a+// vertical arbor, that holds the tempo). The tune on the pins is our own, 32 steps per turn.+// THE POINT: the pins are the score. The drum turning is time; each tooth is a pitch; the readout+// names the pin, the tooth and the note from the same model that places the pins and bends the teeth.+// NOT ITS NEAREST NEIGHBOURS: isometric (flat three-tone planes, no line, a colour night scene) and+// blueprint (white ink on Prussian blue, dimension lines). Here every part is outlined, the tones are+// grey sheets from a camera-locked lamp, the figure sits in a card, and there are no dimensions.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import { isometricHand } from "./mechanismHands";+import {+ Cam, V3, P2, Material, Item, prism, box, rrect, circle, turned, cyl, sphere, frameAlong, at, facingAt, screw, slab, leverRing, tubeAlong, stroke, fill,+ paintAll, sharesAt, ExplodePlan, card, smooth, clamp01, add, setReveal, tone, ink, inkDot, knock, Hand, setHand, flatHand, hand, freshPen,+} from "./mechanismKit";++const W = 1080, H = 1080, FPS = 30, N = 310, N_DRAW = 350;+const PAPER = "#f3f0e8", INK = "#232227", SOFT = "#6d6a70", RULE = "#9a968e";+const mat = (name: string, ramp: Material["ramp"], seam: string, pigment: string, accent = false): Material => ({ name, ramp, ink: INK, seam, pigment, accent });+const ZINC = mat("zinc", ["#a9a69f", "#bdbab3", "#cfccc4", "#dedbd3", "#f4f1ea"], "#8a877f", "#8d8b86");+const STEEL = mat("steel", ["#9aa0a6", "#b0b5ba", "#c5c9cd", "#d8dbde", "#f0f2f3"], "#80868c", "#6f86a0");+const PLINTH = mat("wood", ["#b3ada2", "#c4beb3", "#d3cec4", "#e1ddd4", "#f1eee7"], "#948e84", "#a8774c");+const LEAD = mat("lead", ["#6c6d71", "#7e7f83", "#909195", "#a3a4a7", "#c3c4c6"], "#56575b", "#55575e");+const BRASS = mat("brass", ["#a39d8e", "#b6b0a1", "#c8c2b3", "#d8d3c5", "#efebe1"], "#8a8476", "#ab9a72"); // brass, seen in grey (a quiet pigment: only the accent may shout)+const ACCENT = mat("accent", ["#a2652a", "#ba7a37", "#cd904a", "#dda863", "#f2d29c"], "#8a5420", "#d0502a", true); // the part to watch++// ---------------------------------------------------------------- the model: tune, teeth, drum, explode+const TEETH = [48, 50, 52, 53, 55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72, 74, 76, 79]; // MIDI pitch of each tooth, bass first+const NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];+const noteName = (m: number) => NAMES[m % 12] + (Math.floor(m / 12) - 1);+const hz = (m: number) => 440 * 2 ** ((m - 69) / 12);+const STEPS = 32;+// our tune, step -> pitches (melody over a walking bass); every pitch must be a tooth+const TUNE: Record<number, number[]> = {+ 0: [48, 72], 2: [76], 4: [60, 79], 6: [76], 7: [74], 8: [55, 72], 10: [74], 12: [59, 71], 14: [67],+ 16: [53, 69], 18: [72], 20: [57, 76], 22: [74], 23: [72], 24: [55, 71], 26: [74], 28: [48, 64, 72], 30: [60],+};+const PINS = Object.entries(TUNE).flatMap(([s, ms]) => ms.map((m) => ({ step: +s, tooth: TEETH.indexOf(m) }))).sort((a, b) => a.step - b.step || a.tooth - b.tooth);+if (PINS.some((p) => p.tooth < 0)) throw new Error("mechanism: a pin asks for a pitch no tooth plays");+const DSTEP = (2 * Math.PI) / STEPS;+const DRUM = { o: [12.5, 17.5, 16.2] as V3, len: 34, r: 7, pin: 0.9 };+const TH_C = Math.atan2(-7.8, 1.5); // where a pin meets a tooth tip, in the drum's frame (u = +y, v = +z)+const toothX = (j: number) => 13.1 + j * 1.83;+const toothRoot = (j: number) => 29.8 - (j / 17) * 5;+const TIP = 19;++const PLAN: ExplodePlan = { order: ["governor", "crank", "housing", "screws", "comb", "bridgeL", "bridgeR", "drum"], stagger: 0.07, w: 8, z: 0.89 };+const MOVE: Record<string, V3> = { governor: [30, 0, 30], crank: [42, 0, 8], housing: [30, 0, 8], screws: [0, 13, 24], comb: [0, 13, 9], bridgeL: [-13, 0, 0], bridgeR: [10, 0, 0], drum: [0, 0, 24] };+const ABOUT: Record<string, string> = {+ governor: "AIR BRAKE · HOLDS THE TEMPO", crank: "CRANK · WINDS THE SPRING", housing: "SPRING BARREL · THE MOTOR", screws: "SCREWS · HOLD THE COMB DOWN",+ comb: "COMB · 18 TUNED TEETH", bridgeL: "BRIDGE · CARRIES THE DRUM", bridgeR: "BRIDGE · CARRIES THE DRUM", drum: "DRUM · THE PINS ARE THE SCORE",+};++// the film's timeline (frames)+// two films: the making (rule, build, words) and the run (play, apart, tour, home, play)+const T = { rule: [0, 12], build: [12, 318], text: [318, 350], play: 0, apart: 106, tour: [146, 234], home: 234, end: N } as const;+const CUES = [{ t: T.apart / FPS, apart: true }, { t: T.home / FPS, apart: false }];+const REV = 9.6; // seconds per drum turn: 0.3 s a step+/** drum angle: it turns while the movement is whole and playing */+const rotAt = (f: number) => { const run = (a: number, b: number) => Math.max(0, Math.min(f, b) - a); const fr = run(T.play, T.apart) + run(T.home + 30, N); return (fr / FPS / REV) * 2 * Math.PI; };+export type State = { rot: number; shares: Record<string, number>; lit: string; read: string; bend: number[]; fan: number; crank: number };+/** what the drum is doing at angle rot: how far each tooth bends, and which pin last spoke. One model for pins, teeth and words. */+export const play = (rot: number, quiet = 0) => {+ const bend = TEETH.map(() => 0), turn = rot % (2 * Math.PI); let last = -1;+ PINS.forEach((p, k) => {+ const ahead = ((p.step * DSTEP - rot) % (2 * Math.PI) + 2 * Math.PI) % (2 * Math.PI); // radians until it reaches the tip+ if (ahead < 0.14) bend[p.tooth] += -0.55 * (1 - ahead / 0.14) * (1 - quiet);+ const since = 2 * Math.PI - ahead; if (rot >= p.step * DSTEP && since < 1.2) { const age = (since / (2 * Math.PI)) * REV; bend[p.tooth] += 0.4 * Math.exp(-age / 0.28) * Math.sin(age * 2 * Math.PI * 6) * (1 - quiet); }+ if (turn >= p.step * DSTEP) last = k;+ });+ if (last < 0 && rot >= 2 * Math.PI) last = PINS.length - 1;+ let read = "WOUND · READY";+ if (last >= 0) { const p = PINS[last], m = TEETH[p.tooth]; read = `PIN ${last + 1} · TOOTH ${p.tooth + 1} · ${noteName(m)} ${Math.round(hz(m))} HZ`; }+ return { bend, read, fan: (turn / (2 * Math.PI)) * 2 * Math.PI * 9, crank: Math.PI * 0.3 + 0.12 * Math.sin(rot) };+};+export const stateAt = (f: number): State => {+ const t = f / FPS, rot = rotAt(f), shares = sharesAt(PLAN, CUES, t), moving = Object.values(shares).some((s) => s > 0.003 && s < 0.997);+ const apart = Object.values(shares).every((s) => s > 0.997), pl = play(rot);+ // apart, the parts float: each breathes a little along its own path of travel, out of step with the others+ const settled = clamp01((f - T.apart) / 40) * (1 - clamp01((f - T.home + 6) / 6));+ if (settled > 0) PLAN.order.forEach((id, i) => { shares[id] += 0.035 * settled * Math.sin((2 * Math.PI * t) / 2.6 + i * 0.9); });+ let lit = "drum", read = pl.read;+ if (moving) read = f < T.home ? "TAKING APART" : "PUTTING BACK";+ if (apart) {+ const k = Math.floor(clamp01((f - T.tour[0]) / (T.tour[1] - T.tour[0])) * PLAN.order.length * 0.9999);+ lit = PLAN.order[f < T.tour[0] ? PLAN.order.length - 1 : k]; read = f < T.tour[0] ? `${PLAN.order.length} ASSEMBLIES APART` : `${PLAN.order.indexOf(lit) + 1}/${PLAN.order.length} · ${ABOUT[lit]}`;+ }+ return { rot, shares, lit, read, bend: pl.bend, fan: pl.fan, crank: pl.crank };+};++// ---------------------------------------------------------------- the parts list+const vane = (psi: number, side: number): P2[] => { const c = Math.cos(psi), s = Math.sin(psi), e = 0.22; const pts: [number, number][] = side > 0 ? [[0.5, -e], [4.6, -e], [4.6, e], [0.5, e]] : [[-4.6, -e], [-0.5, -e], [-0.5, e], [-4.6, e]]; return pts.map(([x, y]) => [60 + x * c - y * s, 12 + x * s + y * c] as P2); };+const bar = (ctx: Ctx, c: Cam, x0: number, x1: number, yR: number, yT: number, z0: number, z1: number, dz: number, m: Material, off: P2) => {+ const P = (x: number, y: number, z: number): P2 => { const s = c.p([x, y, z + (y < yR ? dz * ((yR - y) / (yR - yT)) ** 1.6 : 0)]); return [s[0] + off[0], s[1] + off[1]]; };+ const n = 6, ys = Array.from({ length: n + 1 }, (_, i) => yR + ((yT - yR) * i) / n);+ const side = ys.map((y) => P(x1, y, z0)).concat(ys.map((y) => P(x1, y, z1)).reverse()), top = ys.map((y) => P(x0, y, z1)).concat(ys.map((y) => P(x1, y, z1)).reverse());+ tone(ctx, side, m, 0.8); tone(ctx, top, m, 4);+ ink(ctx, top.concat(side.slice(0, n + 1).reverse()), "in", m);+ ink(ctx, [...ys.map((y) => P(x0, y, z1)), P(x0, yT, z0 + 0.0001), ...ys.slice().reverse().map((y) => P(x1, y, z0))], "in", m);+};++const parts = (c: Cam, s: State): Item[] => {+ const items: Item[] = [];+ const put = (id: string, atp: V3, draw: Item["draw"], ride?: string, bias = 0) => items.push({ id, at: atp, draw, ride, bias });+ const lit = (a: string) => s.lit === a, M = (a: string, base: Material) => (lit(a) ? ACCENT : base);+ // the bench+ put("plinth", [35, 23, -9], (ctx, o) => box(ctx, c, -3, 4.5, -9, 76, 44.5, 6, PLINTH, { r: 3, bevel: 1.2, off: o }), undefined, -100);+ put("ruler", [24, 45, -3], (ctx, o) => box(ctx, c, 1, 43.2, -3, 46, 3.6, 0.35, STEEL, { off: o, inner: (x) => {+ for (let i = 0; i <= 46; i += 1) { const major = i % 10 === 0, mid = i % 5 === 0, L = major ? 2.2 : mid ? 1.5 : 0.9; const a = c.p([1 + i, 43.2, -2.65]), b = c.p([1 + i, 43.2 + L, -2.65]); ink(x, [[a[0] + o[0], a[1] + o[1]], [b[0] + o[0], b[1] + o[1]]], major ? "in" : "hair", STEEL); }+ } }), undefined, -60);+ put("label", [61, 44, -3], (ctx, o) => box(ctx, c, 52, 41.5, -3, 18, 5, 0.4, STEEL, { off: o, inner: (x) => {+ [[0.9, 0.8], [2.2, 0.55], [3.4, 0.7]].forEach(([yy, f]) => { const a = c.p([54, 41.5 + yy, -2.6]), b = c.p([54 + 14 * f, 41.5 + yy, -2.6]); ink(x, [[a[0] + o[0], a[1] + o[1]], [b[0] + o[0], b[1] + o[1]]], "seam", STEEL); });+ } }), undefined, -60);+ ([[0, 8], [70, 8], [70, 46], [0, 46]] as P2[]).forEach(([x, y], i) => put(`pscrew${i}`, [x, y, -3], (ctx, o) => screw(ctx, c, [x, y, -3], [0, 0, 1], 1.1, STEEL, 0.4 + i, o), undefined, -50));+ ([[9, 10], [64, 10], [64, 36], [9, 36]] as P2[]).forEach(([x, y], i) => put(`post${i}`, [x, y, -1.5], (ctx, o) => turned(ctx, c, frameAlong([x, y, -3], [0, 0, 1]), cyl(0, 3, 2.2), ZINC, { off: o }), undefined, -40));+ put("bedplate", [36, 23, 0], (ctx, o) => box(ctx, c, 5, 6, 0, 63, 34, 3.5, ZINC, { r: 2.5, bevel: 0.9, off: o, inner: (q) => {+ ([[7.6, 37.4], [65.4, 37.4], [65.4, 8.6], [32, 24], [40, 24]] as P2[]).forEach(([x, y], i) => { const r = i < 3 ? 1.1 : 1.6; const h = circle(x, y, r, 24).map(([a, b]) => { const p = c.p([a, b, 3.5]); return [p[0] + o[0], p[1] + o[1]] as P2; }); tone(q, h, ZINC, 0.4); ink(q, h, "hair", ZINC, true); });+ } }), undefined, -30);+ // the comb: heel, plate, teeth, lead weights, screws+ put("heel", [29.5, 33.5, 6], (ctx, o) => box(ctx, c, 11.5, 30, 3.5, 36, 7, 5.1, M("comb", STEEL), { r: 0.8, bevel: 0.6, off: o, lit: lit("comb") }), "comb");+ put("plate", [29.5, 27.5, 8], (ctx, o) => prism(ctx, c, [[12, 29.9], [47, 24.6], [47, 30.6], [12, 30.6]], 7.6, 0.8, M("comb", STEEL), { off: o }), "comb", -0.5);+ TEETH.forEach((_, j) => {+ const x0 = toothX(j), yR = toothRoot(j);+ if (j < 5) put(`weight${j}`, [x0 + 0.7, 20.9, 7], (ctx, o) => box(ctx, c, x0 + 0.05, TIP + 0.4, 6.4 + s.bend[j] * 0.7, 1.25, 3, 1.2, LEAD, { off: o }), "comb", -0.3);+ put(`tooth${j}`, [x0 + 0.7, (yR + TIP) / 2, 8], (ctx, o) => bar(ctx, c, x0, x0 + 1.35, yR, TIP, 7.6, 8.4, s.bend[j], M("comb", STEEL), o), "comb", -0.6 + j * 0.001);+ });+ ([[17, 33.5], [42, 33.5]] as P2[]).forEach(([x, y], i) => put(`cscrew${i}`, [x, y, 8.6], (ctx, o) => screw(ctx, c, [x, y, 8.6], [0, 0, 1], 1.5, M("screws", STEEL), 0.9 + i, o), "screws", 1));+ // bridges with their feet and screws+ const bridge = (id: string, x: number, foot: number) => {+ put(`${id}foot`, [foot + 2.4, 17.5, 4.2], (ctx, o) => box(ctx, c, foot, 9.5, 3.5, 5, 16, 1.4, M(id, ZINC), { r: 0.5, off: o, lit: lit(id) }), id, -0.2);+ put(`${id}`, [x + 1.1, 17.5, 12], (ctx, o) => box(ctx, c, x, 11, 4.9, 2.2, 13, 13.4, M(id, ZINC), { r: 0.6, bevel: 0.4, off: o, lit: lit(id), inner: (q) => {+ const hole = circle(17.5, 16.2, 1.6, 20).map(([y, z]) => { const p = c.p([x + 2.2, y, z]); return [p[0] + o[0], p[1] + o[1]] as P2; }); tone(q, hole, ZINC, 1.2); ink(q, hole, "hair", ZINC, true);+ } }), id);+ [10.8, 24.2].forEach((y, i) => put(`${id}s${i}`, [foot + (id === "bridgeL" ? 1 : 3.9), y, 4.9], (ctx, o) => screw(ctx, c, [foot + (id === "bridgeL" ? 1 : 3.9), y, 4.9], [0, 0, 1], 0.9, STEEL, 0.2 + i, o), id, 0.3));+ };+ bridge("bridgeL", 9, 7.6); bridge("bridgeR", 49.6, 48.3);+ // the drum: arbor, cylinder with its pins, the great wheel+ const D = frameAlong(DRUM.o, [1, 0, 0]);+ put("arborL", [10.5, 17.5, 16.2], (ctx, o) => turned(ctx, c, frameAlong([8.4, 17.5, 16.2], [1, 0, 0]), cyl(0, 4.2, 0.85), STEEL, { off: o }), "drum", -0.5);+ put("drum", [29.5, 17.5, 16.2], (ctx, o) => {+ turned(ctx, c, D, cyl(0, DRUM.len, DRUM.r), M("drum", BRASS), { off: o, lit: lit("drum"), rims: [0.8, DRUM.len - 0.8] });+ for (const p of PINS) { // each pin: a short steel stub standing off the surface, fading as the drum turns it away+ const th = TH_C + p.step * DSTEP - s.rot, f = facingAt(c, D, th), a = smooth(0.02, 0.4, f); if (a <= 0.01) continue;+ const sx = toothX(p.tooth) + 0.67 - DRUM.o[0], A = c.p(at(D, sx, DRUM.r - 0.05, th)), B = c.p(at(D, sx, DRUM.r + DRUM.pin, th));+ ink(ctx, [[A[0] + o[0], A[1] + o[1]], [B[0] + o[0], B[1] + o[1]]], "in", STEEL, false, a);+ inkDot(ctx, [B[0] + o[0], B[1] + o[1]], 1.5, STEEL, a);+ }+ }, "drum");+ put("wheel", [48, 17.5, 16.2], (ctx, o) => {+ const G = frameAlong([47.4, 17.5, 16.2], [1, 0, 0]);+ turned(ctx, c, G, cyl(0, 1.2, 9.5), M("drum", BRASS), { off: o, lit: lit("drum") });+ for (let i = 0; i < 64; i++) { const th = (i / 64) * 2 * Math.PI - s.rot, f = facingAt(c, G, th); if (f < 0.02) continue; const A = c.p(at(G, 1.2, 8.6, th)), B = c.p(at(G, 1.2, 9.45, th)); ink(ctx, [[A[0] + o[0], A[1] + o[1]], [B[0] + o[0], B[1] + o[1]]], "seam", BRASS, false, smooth(0.02, 0.4, f)); }+ turned(ctx, c, frameAlong([48.6, 17.5, 16.2], [1, 0, 0]), cyl(0, 0.8, 2.4), M("drum", BRASS), { off: o });+ }, "drum", -3);+ put("arborR", [50.5, 17.5, 16.2], (ctx, o) => turned(ctx, c, frameAlong([49.4, 17.5, 16.2], [1, 0, 0]), cyl(0, 2.6, 0.85), STEEL, { off: o }), "drum", 1.2);+ // the motor: housing, its screws, the crank+ put("housing", [60, 22, 10.7], (ctx, o) => box(ctx, c, 54, 6, 3.5, 12, 32, 14.5, M("housing", ZINC), { r: 2.5, bevel: 0.9, seams: [5.2], off: o, lit: lit("housing") }), "housing");+ ([[56, 8.5], [64, 8.5], [64, 35.5], [56, 35.5]] as P2[]).forEach(([x, y], i) => put(`hscrew${i}`, [x, y, 18], (ctx, o) => screw(ctx, c, [x, y, 18], [0, 0, 1], 0.9, M("housing", STEEL), 1.1 + i, o), "housing", 0.5));+ put("crank", [70, 24, 10], (ctx, o) => {+ tubeAlong(ctx, c, [[66, 22, 10], [69.2, 22, 10]], 0.9, STEEL, { off: o, caps: [false, true] });+ // the lever: a flat steel plate turning in the plane x = 69.2, a boss on the shaft, a turned wooden knob at its end+ const A = frameAlong([69.2, 22, 10], [1, 0, 0]), ang = s.crank, e: V3 = [69.2, 22 + 7 * Math.cos(ang), 10 + 7 * Math.sin(ang)];+ const lv = leverRing(7, 1.6, 1.25).map(([u, v]) => { const cu = Math.cos(ang), su = Math.sin(ang); return [u * cu - v * su, u * su + v * cu] as P2; });+ slab(ctx, c, { ...A, u: [0, 1, 0], v: [0, 0, 1] }, lv, 0.9, M("crank", STEEL), { off: o, lit: lit("crank") });+ turned(ctx, c, frameAlong([70.1, 22, 10], [1, 0, 0]), cyl(0, 0.7, 1.15), M("crank", STEEL), { off: o });+ turned(ctx, c, frameAlong(add(e, [0.9, 0, 0]), [1, 0, 0]), cyl(0, 3.4, 1.35), M("crank", PLINTH), { off: o, lit: lit("crank") });+ turned(ctx, c, frameAlong(add(e, [4.3, 0, 0]), [1, 0, 0]), sphere(0, 0.9, -0.5, 1.45), M("crank", PLINTH), { off: o, caps: [false, false] });+ }, "crank");+ put("stop", [58, 42, 12], (ctx, o) => {+ tubeAlong(ctx, c, [[57.5, 38, 13], [57.5, 42.5, 13], [54.5, 45, 13.8]], 0.45, M("housing", STEEL), { off: o, caps: [false, false] });+ turned(ctx, c, frameAlong([54.5, 45, 12.6], [0, 0, 1]), sphere(0, 2.4, 1.2, 1.2), M("housing", PLINTH), { off: o, caps: [false, false] });+ }, "housing", 0.4);+ // the governor: shaft, worm, fan (two blades, sorted round the shaft), cap+ const G0: V3 = [60, 12, 18];+ put("gshaft", [60, 12, 24], (ctx, o) => {+ turned(ctx, c, frameAlong(G0, [0, 0, 1]), cyl(0, 1.1, 1.9), M("governor", ZINC), { off: o, rims: [0.5] });+ turned(ctx, c, frameAlong(add(G0, [0, 0, 1.1]), [0, 0, 1]), cyl(0, 11.3, 0.55), STEEL, { off: o });+ const F = frameAlong([60, 12, 19.4], [0, 0, 1]); turned(ctx, c, F, cyl(0, 4, 1.5), M("governor", STEEL), { off: o, lit: lit("governor") });+ const KS = Math.round(20 / (hand().coarse ?? 1)); for (let i = 0; i < 9; i++) { const z0 = 0.3 + i * 0.42; for (let k = 0; k < KS; k++) { const th0 = (k / KS) * 2 * Math.PI + s.fan * 0.15, th1 = th0 + (2 * Math.PI) / KS, f = facingAt(c, F, (th0 + th1) / 2); if (f < 0.05) continue; const A = c.p(at(F, z0 + (k / KS) * 0.42, 1.5, th0)), B = c.p(at(F, z0 + ((k + 1) / KS) * 0.42, 1.5, th1)); ink(ctx, [[A[0] + o[0], A[1] + o[1]], [B[0] + o[0], B[1] + o[1]]], "seam", STEEL, false, smooth(0.05, 0.5, f)); } }+ }, "governor");+ [1, -1].forEach((side) => { const ring = vane(s.fan, side), mid = ring.reduce((a, q) => [a[0] + q[0] / 4, a[1] + q[1] / 4], [0, 0]); put(`vane${side}`, [mid[0], mid[1], 26.5], (ctx, o) => prism(ctx, c, ring, 24.6, 4.2, M("governor", ZINC), { off: o, lit: lit("governor") }), "governor", 0); });+ put("hub", [60, 12, 26.7], (ctx, o) => turned(ctx, c, frameAlong([60, 12, 24.4], [0, 0, 1]), cyl(0, 4.6, 0.95), M("governor", STEEL), { off: o }), "governor", 0.05);+ put("gcap", [60, 12, 30.6], (ctx, o) => turned(ctx, c, frameAlong([60, 12, 30.2], [0, 0, 1]), cyl(0, 0.8, 1.3), STEEL, { off: o }), "governor", 2);+ // travel lines: a chain line from where a part sits to where it went, drawn under everything that moved+ const travel = (id: string, home: V3, ride: string) => put(`path-${id}`, home, (ctx) => {+ const sh = s.shares[ride] ?? 0; if (sh < 0.05) return;+ const a = c.p(home), b = c.p(add(home, [MOVE[ride][0] * sh, MOVE[ride][1] * sh, MOVE[ride][2] * sh]));+ ink(ctx, [a, b], "chain", STEEL, false, 0.8 * smooth(0.05, 0.4, sh));+ }, undefined, -25);+ travel("cs0", [17, 33.5, 8.6], "screws"); travel("cs1", [42, 33.5, 8.6], "screws");+ travel("arbor", [29.5, 17.5, 16.2], "drum"); travel("gov", [60, 12, 18], "governor");+ travel("crank", [66, 22, 10], "crank");+ return items;+};++// ---------------------------------------------------------------- the camera, fit once to everything the film shows+const BENCH: V3[] = [[-3, 4.5, -9], [73, 4.5, -9], [73, 49, -9], [-3, 49, -9], [-3, 4.5, -3], [73, 49, -3], [-3, 49, -3], [5, 6, 3.5]];+const HOME = Cam.fit(36, 30, [...BENCH, [60, 12, 31], [74, 22, 18], [10, 11, 24]], [205, 215, 875, 865]);+const APART = Cam.fit(36, 30, [...BENCH, [90, 12, 61], [116, 22, 26], [-4, 17, 21], [30, 45, 34], [30, 17, 48]], [130, 120, 950, 930]);+export const camAt = (sh: Record<string, number>) => { const m = Object.values(sh).reduce((a, b) => a + b, 0) / PLAN.order.length, e = smooth(0, 1, m); return new Cam(36, 30, HOME.k + (APART.k - HOME.k) * e, HOME.ox + (APART.ox - HOME.ox) * e, HOME.oy + (APART.oy - HOME.oy) * e); };++// the order the pen visits the parts in the film: the bench, the plate, then each assembly as it is put together+const BUILD = ["plinth", "ruler", "label", "pscrew", "post", "bedplate", "bridgeL", "bridgeR", "arbor", "drum", "wheel", "plate", "tooth", "weight", "heel", "cscrew", "housing", "hscrew", "stop", "crank", "gshaft", "hub", "vane", "gcap"];+// time is shared by how much there is to draw: a screw takes a beat, a drum takes a breath+const SMALL = new Set(["pscrew", "post", "arbor", "weight", "cscrew", "hscrew", "stop", "hub", "gcap", "label"]);+const BW = BUILD.map((b) => (SMALL.has(b) ? 0.45 : 1.3)), BSTART = BW.map((_, i) => BW.slice(0, i).reduce((a, w) => a + w, 0)), BTOTAL = BW.reduce((a, w) => a + w, 0);+const buildRank = (id: string) => { const i = BUILD.findIndex((b) => id === b || id.startsWith(b)); return i < 0 ? BUILD.length - 1 : i; };+const buildAt = (id: string, f: number): [number, number] => {+ const [b0, b1] = T.build, unit = (b1 - b0) / (BTOTAL + 1), r = buildRank(id), st = b0 + BSTART[r] * unit, len = BW[r] * unit;+ return [clamp01((f - st) / (len * 1.15)), clamp01((f - st - len * 0.9) / (len * 1.5))];+};+// the camera's own move: while it plays, push in to where the pins meet the teeth and drift along the+// comb from bass to treble; pull back before it comes apart; at the end, settle in a little on the drum+const CLOSE = { a: 0, in: 30, out: 78, b: 104 }, FINAL = { a: 262, b: 310 };+const zoomAt = (f: number): { z: number; focus: V3; pull: number } => {+ if (f >= CLOSE.a && f < CLOSE.b) {+ const e = f < CLOSE.in ? smooth(CLOSE.a, CLOSE.in, f) : f < CLOSE.out ? 1 : 1 - smooth(CLOSE.out, CLOSE.b, f), drift = clamp01((f - CLOSE.a) / (CLOSE.b - CLOSE.a));+ return { z: 1 + 1.25 * e, focus: [16 + 26 * drift, 20, 10], pull: e };+ }+ if (f >= FINAL.a) { const e = smooth(FINAL.a, FINAL.b, f); return { z: 1 + 0.32 * e, focus: [30, 18, 13], pull: e * 0.6 }; }+ return { z: 1, focus: [30, 18, 13], pull: 0 };+};+const zoomed = (c: Cam, f: number): Cam => {+ const { z, focus, pull } = zoomAt(f); if (z <= 1.0001) return c;+ const s0 = c.p(focus), u: P2 = [(s0[0] - c.ox) / c.k, (s0[1] - c.oy) / c.k], tgt: P2 = [s0[0] + (W / 2 - s0[0]) * pull, s0[1] + (H / 2 - s0[1]) * pull], k = c.k * z;+ return new Cam(c.A, c.E, k, tgt[0] - k * u[0], tgt[1] - k * u[1]);+};++export { PLAN, MOVE, ABOUT, REV, PAPER, parts, W as FIG_W, H as FIG_H };+/** the figure on its card at a given state: the film and the interactive explorer both paint through this */+export const paintFigure = (ctx: Ctx, s: State, hint: string, o: { cam?: Cam; build?: (id: string) => [number, number]; card?: number; shadow?: number } = {}) => {+ freshPen(ctx);+ const CAM = o.cam ?? camAt(s.shares), items = parts(CAM, s), text = { fig: "FIG 1", title: "18-NOTE MOVEMENT", hint, read: s.read };+ card(ctx, W, H, text, { progress: o.card ?? 1, part: "ground" });+ ctx.save(); ctx.beginPath(); ctx.rect(35, 35, W - 70, H - 70); ctx.clip(); // the figure lives inside the card's rule+ const foot = rrect(-3, 4.5, 76, 44.5, 3).map(([x, y]) => CAM.p([x, y, -9]));+ const sh = o.shadow ?? 1; // the shadow is laid like a tone sheet, left to right, never faded in+ if (sh > 0) { const x0 = Math.min(...foot.map((q) => q[0])) - 20, x1 = Math.max(...foot.map((q) => q[0])) + 20; ctx.save(); ctx.beginPath(); ctx.rect(x0, -1e4, (x1 - x0) * sh, 2e4); ctx.clip(); hand().shadow?.(ctx, foot, 1); ctx.restore(); }+ const wrapped = o.build ? items.map((it) => ({ ...it, draw: (x: Ctx, off: P2) => { const [ink, tone] = o.build!(it.id); if (ink <= 0) return; setReveal(ink, tone, PAPER); it.draw(x, off); setReveal(1, 1); } })) : items;+ paintAll(ctx, CAM, wrapped, MOVE, s.shares);+ ctx.restore(); freshPen(ctx);+ card(ctx, W, H, text, { progress: o.card ?? 1, part: "words" });+ return CAM;+};+export const camApart = APART;+/** the run: it plays (the camera close on the pins), comes apart, tours its parts, folds home, plays on */+export const drawMechanism = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ const s = stateAt(f);+ paintFigure(ctx, s, "THE PINS ARE THE SCORE", { cam: zoomed(camAt(s.shares), f) });+};+/** the making: the card's rule, then each part inked and toned in assembly order, then the words */+export const drawMechanismMaking = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ const s = stateAt(0), ruleP = clamp01((f - T.rule[0]) / (T.rule[1] - T.rule[0])), textP = clamp01((f - T.text[0]) / (T.text[1] - T.text[0]));+ paintFigure(ctx, s, "THE PINS ARE THE SCORE", { card: ruleP < 1 ? ruleP * 0.5 : 0.5 + textP * 0.5, shadow: buildAt("plinth", f)[1], build: (id) => buildAt(id, f) });+};++/** the same figure, film and all, in the hand of another style */+export const mechanismIn = (handId: string, make: (ctx: Ctx, env: Env, f: number) => Hand, making = false): Film => ({+ meta: making+ ? { title: `Mechanism · the 18-note movement, drawn (${handId})`, W, H, fps: FPS, bpm: 100, durationFrames: N_DRAW, kind: "drawing", poster: N_DRAW - 1 }+ : { title: `Mechanism · the 18-note movement (${handId})`, W, H, fps: FPS, bpm: 100, durationFrames: N, kind: "explainer", poster: 140 },+ assets: { images: {} },+ shots: [{ id: "figure", start: 0, end: making ? N_DRAW : N, draw: (ctx, f, env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); setHand(make(ctx, env, f)); try { (making ? drawMechanismMaking : drawMechanism)(ctx, f, env); } finally { setHand(flatHand()); } } }],+});+/** the plain film: the movement in the house isometric hand (flat planes, three tones, no line) */+export const mechanism: Film = mechanismIn("isometric", () => isometricHand());diff --git a/skills/anidoodle/engine/src/canvas-core/mechanismBlueprint.ts b/skills/anidoodle/engine/src/canvas-core/mechanismBlueprint.tsnew file mode 100644index 0000000..698ce01--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanismBlueprint.ts@@ -0,0 +1,5 @@+// The 18-note movement in the blueprint hand: a machine is a subject, drawn in any style.+import { mechanismIn } from "./mechanism";+import { blueprintHand } from "./mechanismHands";++export const mechanismBlueprint = mechanismIn("blueprint", blueprintHand);diff --git a/skills/anidoodle/engine/src/canvas-core/mechanismDraw.ts b/skills/anidoodle/engine/src/canvas-core/mechanismDraw.tsnew file mode 100644index 0000000..8f8a0f6--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanismDraw.ts@@ -0,0 +1,5 @@+// The 18-note movement drawing itself, in the house isometric hand: each part traced, then filled, in assembly order.+import { mechanismIn } from "./mechanism";+import { isometricHand } from "./mechanismHands";++export const mechanismDraw = mechanismIn("isometric", () => isometricHand(), true);diff --git a/skills/anidoodle/engine/src/canvas-core/mechanismExplorer.ts b/skills/anidoodle/engine/src/canvas-core/mechanismExplorer.tsnew file mode 100644index 0000000..e1ef8fc--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanismExplorer.ts@@ -0,0 +1,60 @@+// MECHANISM EXPLORER. The 18-note movement as a piece on a web page, in the isometric hand.+// Untouched, it plays its tune forever (the drum's turn is the loop). Hover it, focus it, or the+// page's button, and it comes apart: each assembly on its own slightly underdamped spring, the outer+// ones quicker, so it opens outside-in and lands with a little weight. Point at a part and it lights;+// the readout says what that part does. Leave and it folds home and plays on.+// Web profile: the camera is fixed (fit to the exploded machine), so the card and the bench never+// change; they are drawn once per device scale into a cached layer and the machine is drawn over it.+import type { Piece, Discrete } from "./input";+import { HZ, attentionOf } from "./input";+import type { Layer } from "./core";+import { parts, play, camApart, PLAN, MOVE, ABOUT, REV, FIG_W as W, FIG_H as H, type State } from "./mechanism";+import { setHand, flatHand, add, mul, paintAll, card, freshPen, rrect, type V3, type P2 } from "./mechanismKit";+import { isometricHand } from "./mechanismHands";++const LOOP = Math.round(REV * HZ), ART = { x0: 120, y0: 110, x1: 960, y1: 950 };+const HOME: Record<string, V3> = { governor: [60, 12, 25], crank: [72, 22, 10], housing: [60, 22, 10], screws: [30, 33.5, 9], comb: [30, 26, 8], bridgeL: [10, 17, 12], bridgeR: [50.7, 17, 12], drum: [30, 17.5, 16] };+const BENCH = (id: string) => id === "plinth" || id === "ruler" || id === "label" || id === "bedplate" || id.startsWith("pscrew") || id.startsWith("post"); // never move, and every moving part paints after them+const inside = (p: Discrete["pointer"]) => !!p && p[0] >= ART.x0 && p[0] <= ART.x1 && p[1] >= ART.y0 && p[1] <= ART.y1;+const springs = Object.fromEntries(PLAN.order.map((id, i) => [id, { omega: 0.17 - i * 0.008, zeta: 0.82, target: (d: Discrete) => (inside(d.pointer) || attentionOf(d) === "apart" || d.focus === "self" ? 1 : 0) }]));+const HAND = isometricHand(), CAM = camApart, TITLE = { fig: "FIG 1", title: "18-NOTE MOVEMENT" };+const hintOf = (reduced: boolean) => (reduced ? "FOCUS TO TAKE IT APART" : "HOVER TO TAKE IT APART");+const REST: State = { rot: 0, shares: {}, lit: "", read: "", bend: [], fan: 0, crank: 0 };++/** the card and the bench, which never move: drawn once per device scale */+const benchLayer = (env: Parameters<Piece["draw"]>[2], reduced: boolean): Layer => {+ const DW = Math.round(W * env.scale), DH = Math.round(H * env.scale), key = `mechExplorer:bench:${DW}x${DH}:${reduced}`;+ let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ L = env.canvas(DW, DH); const c = L.ctx; c.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ setHand(HAND);+ try {+ card(c, W, H, { ...TITLE, hint: hintOf(reduced), read: "" });+ HAND.shadow?.(c, rrect(-3, 4.5, 76, 44.5, 3).map(([x, y]) => CAM.p([x, y, -9])), 1);+ paintAll(c, CAM, parts(CAM, { ...REST, bend: play(0).bend }).filter((it) => BENCH(it.id)));+ } finally { setHand(flatHand()); }+ env.cache.set(key, L); return L;+};++export const mechanismExplorer: Piece = {+ meta: { title: "Mechanism explorer", W, H, loop: LOOP, alt: "An 18-note music box movement drawn in flat isometric planes, playing. Hover or focus it to take it apart; point at a part to read what it does." },+ input: { springs: springs as Piece["input"]["springs"] },+ draw: (ctx, tick, env, s) => {+ const L = benchLayer(env, s.reduced);+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); freshPen(ctx); ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore();+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); freshPen(ctx);+ const shares = Object.fromEntries(PLAN.order.map((id) => [id, Math.max(0, s.spring[id] as number)])), mean = PLAN.order.reduce((a, id) => a + shares[id], 0) / PLAN.order.length;+ const rot = s.reduced ? 0.4 : ((tick % LOOP) / LOOP) * 2 * Math.PI, pl = play(rot, Math.min(1, mean * 3));+ const state: State = { rot, shares, lit: "drum", read: pl.read, bend: pl.bend, fan: pl.fan, crank: pl.crank };+ if (mean > 0.02 && mean < 0.9) state.read = (s.spring[PLAN.order[0]] as number) > 0.5 ? "TAKING APART" : "PUTTING BACK";+ if (mean >= 0.9 && s.pointer) { // the part under the pointer: the nearest assembly, where it is now+ let best = Infinity;+ for (const id of PLAN.order) { const q: P2 = CAM.p(add(HOME[id], mul(MOVE[id], shares[id]))), d = Math.hypot(q[0] - s.pointer[0], q[1] - s.pointer[1]); if (d < best) { best = d; state.lit = id; } }+ state.read = `${PLAN.order.indexOf(state.lit) + 1}/${PLAN.order.length} · ${ABOUT[state.lit]}`;+ }+ setHand(HAND);+ try {+ HAND.text(ctx, state.read, W - 96, H - 34 - 20 - 13, { cap: 13, align: "right" }); // clear of the host's pause button in the corner+ paintAll(ctx, CAM, parts(CAM, state).filter((it) => !BENCH(it.id)), MOVE, shares);+ } finally { setHand(flatHand()); }+ },+};diff --git a/skills/anidoodle/engine/src/canvas-core/mechanismHands.ts b/skills/anidoodle/engine/src/canvas-core/mechanismHands.tsnew file mode 100644index 0000000..25f1667--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanismHands.ts@@ -0,0 +1,198 @@+// HANDS FOR THE MECHANISM KIT. The same machine, marked in a style's own medium. Each hand follows+// the recipe in references/styles/<id>.md: what the mark is, what an edge is, what tone is, and+// whether the medium has light at all. The kit says WHAT is there; a hand decides HOW it is drawn.+//+// blueprint white ink on cyanotype: no light, no shadow; outlines ruled, the part to watch+// section-lined, travel shown as chain lines+// colouredPencil one dominant hatch diagonal in each material's pigment, darks cross-hatched,+// thin broken sepia-graphite contours heavier where the form turns from the lamp+// stipple one pen, dots only: tone is density, an edge is where density changes+//+// Patterns are anchored to the part (its exploded offset), never to the screen, so a part that+// moves carries its marks with it, and a still part's marks never boil.+import type { Ctx, Env, Layer, P } from "./core";+import { Gfx, rng, PENCIL, GRAPHITE } from "./core";+import { kit, sheet, border, WHITE, CYAN, DIM, DRAFT } from "./blueprintKit";+import { letter } from "./drafting";+import { type Hand, type Material, type P2, type Role, offset, path, rawStroke, flatHand, reveal } from "./mechanismKit";++const hash = (...v: number[]) => { let h = 2166136261; for (const x of v) { h ^= Math.round(x * 8) | 0; h = Math.imul(h, 16777619); } return h >>> 0; };+const nameHash = (m: Material) => hash(...[...(m.name ?? "m")].map((c) => c.charCodeAt(0)));++/** the ground of a hand, drawn once into a device-size layer, then knocked back in as a pattern */+const groundLayer = (env: Env, key: string, paint: (L: Layer, g: Gfx) => void): Layer => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), k = `mechHand:${key}:${DW}x${DH}`;+ let L = env.cache.get(k) as Layer | undefined;+ if (!L) { L = env.canvas(DW, DH); L.ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); paint(L, new Gfx(L.ctx, env, 0, DRAFT)); env.cache.set(k, L); }+ return L;+};+const patternOf = (ctx: Ctx, L: Layer, scale: number) => { const p = ctx.createPattern(L.canvas as CanvasImageSource, "no-repeat")!; p.setTransform(new DOMMatrix().scale(1 / scale)); return p; };+const knockWith = (ctx: Ctx, L: Layer, scale: number, pts: P2[]) => { ctx.globalAlpha = 1; ctx.fillStyle = patternOf(ctx, L, scale); path(ctx, pts); ctx.fill(); ctx.strokeStyle = ctx.fillStyle; ctx.lineWidth = 0.6; ctx.stroke(); };+const blit = (ctx: Ctx, L: Layer, env: Env) => { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); };++/** parallel lines at angle `ang`, `gap` apart, anchored at `anchor`, cut to a polygon: [a, b, lineIndex] */+export const hatchSegs = (pts: P2[], ang: number, gap: number, anchor: P2 = [0, 0]): [P2, P2, number][] => {+ const c = Math.cos(ang), s = Math.sin(ang), proj = pts.map(([x, y]) => -s * (x - anchor[0]) + c * (y - anchor[1]));+ const lo = Math.floor(Math.min(...proj) / gap), hi = Math.ceil(Math.max(...proj) / gap), out: [P2, P2, number][] = [];+ for (let n = lo; n <= hi; n++) {+ const off = n * gap, ox = anchor[0] - s * off, oy = anchor[1] + c * off, ts: number[] = [];+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {+ const a = pts[j], b = pts[i], da = -s * (a[0] - ox) + c * (a[1] - oy), db = -s * (b[0] - ox) + c * (b[1] - oy);+ if ((da < 0) === (db < 0) || da === db) continue; const t = da / (da - db), px = a[0] + (b[0] - a[0]) * t, py = a[1] + (b[1] - a[1]) * t; ts.push(c * (px - ox) + s * (py - oy));+ }+ ts.sort((x, y) => x - y); for (let k = 0; k + 1 < ts.length; k += 2) out.push([[ox + c * ts[k], oy + s * ts[k]], [ox + c * ts[k + 1], oy + s * ts[k + 1]], n]);+ }+ return out;+};+/** points every `step` px along a polyline, the first `progress` of it */+const along = (pts: P2[], step: number, close: boolean, progress = 1): P2[] => {+ const q = close ? [...pts, pts[0]] : pts, out: P2[] = []; let L = 0; for (let i = 1; i < q.length; i++) L += Math.hypot(q[i][0] - q[i - 1][0], q[i][1] - q[i - 1][1]);+ const end = L * progress; let d = 0, need = 0;+ for (let i = 1; i < q.length && need <= end; i++) { const a = q[i - 1], b = q[i], l = Math.hypot(b[0] - a[0], b[1] - a[1]); while (need <= d + l && need <= end) { const t = l ? (need - d) / l : 0; out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); need += step; } d += l; }+ return out;+};++// ---------------------------------------------------------------- blueprint: white ink on cyanotype+export const blueprintHand = (ctx0: Ctx, env: Env, frame: number): Hand => {+ const g = new Gfx(ctx0, env, frame, DRAFT), k = kit(g), L = groundLayer(env, "blueprint", (_, lg) => sheet(kit(lg)));+ const seedOf = (pts: P2[]) => hash(pts[0][0] - offset()[0], pts[0][1] - offset()[1], pts.length);+ const W: Partial<Record<Role, [number, string, number]>> = { out: [1.7, WHITE, 0.95], lit: [2.2, WHITE, 1], in: [1.05, WHITE, 0.85], crease: [0.9, CYAN, 0.8], seam: [0.75, CYAN, 0.7], hair: [0.75, CYAN, 0.8] };+ return {+ id: "blueprint",+ knock: (ctx, pts) => knockWith(ctx, L, env.scale, pts),+ // no light on a drawing: the only tone is section lining, and only the part to watch is cut+ region: (_ctx, pts, _q, m) => { if (!m.accent) return; const o = offset(); for (const [a, b, n] of hatchSegs(pts, Math.PI / 4, 5.5, o)) { const l = Math.hypot(b[0] - a[0], b[1] - a[1]); if (l < 2.5) continue; k.ln(a, b, 0.8, { seed: hash(n, nameHash(m)), color: CYAN, opacity: 0.8, taper: 0.7 }); } },+ line: (ctx, pts, role, _m, close, a, prog) => {+ if (role === "light") return;+ if (role === "chain") { const [p0, p1] = [pts[0], pts[pts.length - 1]]; k.chain(p0 as P, p1 as P, 0.8, { color: DIM, opacity: 0.85 * a, progress: prog }); return; }+ const [w, col, op] = W[role]!; k.pen(pts as P[], w, { color: col, opacity: op * a, closed: close, seed: seedOf(pts), progress: prog, wobble: 0.35 });+ void ctx;+ },+ dot: (ctx, at, r, _m, a) => { ctx.globalAlpha = a; ctx.fillStyle = WHITE; ctx.beginPath(); ctx.arc(at[0], at[1], r * 0.9, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx) => blit(ctx, L, env),+ frame: (_ctx, _W, _H, p) => border(k, p),+ text: (_ctx, t, x, y, o) => k.text(t, x, y, { cap: o.cap, align: o.align, color: o.soft ? CYAN : WHITE, w: Math.max(1, o.cap * 0.1), opacity: o.alpha ?? 1, seed: hash(x, y) }),+ };+};++// ---------------------------------------------------------------- coloured pencil: hatched in one diagonal+const ANG = -1.02, X2 = ANG + 1.25, CREAM = "#f3ecdc", SEPIA = "#4a3d36";+export const colouredPencilHand = (ctx0: Ctx, env: Env, frame: number): Hand => {+ const g = new Gfx(ctx0, env, frame, PENCIL), L = groundLayer(env, "pencil", (lay, lg) => { lay.ctx.fillStyle = CREAM; lay.ctx.fillRect(0, 0, env.W, env.H); lg.paper("paper", 0.34); lg.paper("coldpress", 0.2); });+ const strokes = (ctx: Ctx, pts: P2[], ang: number, gap: number, col: string, alpha: number, seed: number, w = 1.25) => {+ const o = offset(); ctx.strokeStyle = col; ctx.lineWidth = w; ctx.lineCap = "round";+ for (const [a, b, n] of hatchSegs(pts, ang, gap, o)) {+ const r = rng(hash(n, seed)), l = Math.hypot(b[0] - a[0], b[1] - a[1]); if (l < 1.5) continue;+ // a hatch stroke: lands fast, lifts in a flick, and breaks where the lead skips the paper's valleys+ const s0 = (r() - 0.35) * 2.2, s1 = (r() - 0.6) * 2.2, ux = (b[0] - a[0]) / l, uy = (b[1] - a[1]) / l;+ ctx.globalAlpha = alpha * (0.75 + r() * 0.4); ctx.setLineDash([3 + r() * 9, 0.8 + r() * 1.6]); ctx.lineDashOffset = r() * 10;+ ctx.beginPath(); ctx.moveTo(a[0] - ux * s0, a[1] - uy * s0); ctx.lineTo(b[0] + ux * s1, b[1] + uy * s1); ctx.stroke();+ }+ ctx.setLineDash([]); ctx.globalAlpha = 1;+ };+ const W: Partial<Record<Role, [number, number]>> = { out: [1.5, 0.8], lit: [1.9, 0.95], in: [1, 0.6], crease: [0.85, 0.45], seam: [0.7, 0.4], hair: [0.7, 0.55] };+ return {+ id: "colouredPencil",+ knock: (ctx, pts) => knockWith(ctx, L, env.scale, pts),+ region: (ctx, pts, q, m) => {+ const d = Math.max(0, Math.min(1, 1 - q / 4)), pig = m.pigment ?? "#8a8a8a", sd = nameHash(m);+ strokes(ctx, pts, ANG, 3.1, pig, (m.accent ? 0.55 : 0.32) + 0.4 * d, sd); // local colour, light to dark by pressure+ if (d > 0.35) strokes(ctx, pts, ANG, 3.1, pig, 0.25 + 0.3 * d, sd + 7, 1.1); // a second pass, offset by the hand+ if (d > 0.6) strokes(ctx, pts, X2, 3.6, m.accent ? "#5a1e14" : "#3b3550", 0.18 + 0.35 * (d - 0.6), sd + 13, 1); // darks cross-hatched, never filled+ },+ line: (ctx, pts, role, m, close, a, prog) => {+ if (role === "light") return;+ if (role === "chain") { ctx.save(); ctx.setLineDash([7, 4]); rawStroke(ctx, pts, SEPIA, 0.8, false, 0.55 * a, prog); ctx.restore(); return; }+ const [w, op] = W[role]!; g.pen(pts as P[], { w, color: m.accent && role === "lit" ? "#6b2414" : SEPIA, opacity: op * a, closed: close, seed: hash(pts[0][0] - offset()[0], pts[0][1] - offset()[1]), boil: 0, wobble: 0.45, taper: 0.9, progress: prog });+ void ctx;+ },+ dot: (ctx, at, r, _m, a) => { ctx.globalAlpha = 0.85 * a; ctx.fillStyle = GRAPHITE; ctx.beginPath(); ctx.arc(at[0], at[1], r * 0.85, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx) => blit(ctx, L, env),+ frame: (ctx, W0, H0, p) => { const pad = 34, edges: [P2, P2][] = [[[pad, pad], [W0 - pad, pad]], [[W0 - pad, pad], [W0 - pad, H0 - pad]], [[W0 - pad, H0 - pad], [pad, H0 - pad]], [[pad, H0 - pad], [pad, pad]]]; edges.forEach(([a, b], i) => g.pen([a, b] as P[], { w: 0.9, color: SEPIA, opacity: 0.55, seed: 40 + i, boil: 0, wobble: 0.8, progress: Math.max(0, Math.min(1, p * 4 - i)) })); void ctx; },+ text: (_ctx, t, x, y, o) => letter(g, t, x, y, { cap: o.cap, align: o.align, color: o.soft ? "#7a6a5e" : SEPIA, opacity: (o.alpha ?? 1) * 0.9, seed: hash(x, y), slant: 0.12 }),+ shadow: (ctx, pts, s) => { const off = pts.map(([x, y]) => [x + 2, y + 8] as P2); strokes(ctx, off, X2, 3.4, "#5a5260", 0.22 * s, 99, 1); },+ };+};++// ---------------------------------------------------------------- stipple: one pen, dots only+const CARBON = "#15120e", BRISTOL = "#fbfaf5";+export const stippleHand = (ctx0: Ctx, env: Env, frame: number): Hand => {+ const g = new Gfx(ctx0, env, frame, { ...PENCIL, wobble: 0.3 }), L = groundLayer(env, "stipple", (lay, lg) => { lay.ctx.fillStyle = BRISTOL; lay.ctx.fillRect(0, 0, env.W, env.H); lg.paper("paper", 0.05); });+ // dot fields come from tiles, one per density step, drawn once: a dot is in a step's tile when its draw is+ // under that density, so a darker step only adds dots. A whole region is then one patterned fill, cheap+ // enough for a close-up, and the pattern is anchored to the part so its dots travel with it.+ const CELL = 2, SPAN = 64, STEPS = 24, TILE = CELL * SPAN;+ const tile = (seed: number, step: number) => {+ const k = `mechHand:stipple:${seed}:${step}:${env.scale}`; let T = env.cache.get(k) as Layer | undefined;+ if (!T) {+ const D = Math.round(TILE * env.scale); T = env.canvas(D, D); const c = T.ctx; c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = CARBON; c.beginPath();+ for (let j = 0; j < SPAN; j++) for (let i = 0; i < SPAN; i++) {+ const r = rng(hash(i, j, seed)); if (r() > step / STEPS) continue;+ const x = (i + r()) * CELL, y = (j + r()) * CELL, rad = 0.62 + r() * 0.18;+ // a dot near the tile edge is drawn again across it, so tiles meet without a seam+ for (const dx of [0, x < 1 ? TILE : x > TILE - 1 ? -TILE : 0]) for (const dy of [0, y < 1 ? TILE : y > TILE - 1 ? -TILE : 0]) { c.moveTo(x + dx + rad, y + dy); c.ellipse(x + dx, y + dy, rad * 1.08, rad, 0.4, 0, Math.PI * 2); }+ }+ c.fill(); env.cache.set(k, T);+ }+ return T;+ };+ const dots = (ctx: Ctx, pts: P2[], density: number, seed: number) => {+ const step = Math.min(STEPS, Math.round(density * STEPS)); if (step <= 0) return; const o = offset();+ const pat = ctx.createPattern(tile(seed % 4, step).canvas as CanvasImageSource, "repeat")!; pat.setTransform(new DOMMatrix().translate(o[0], o[1]).scale(1 / env.scale));+ ctx.fillStyle = pat; path(ctx, pts); ctx.fill();+ };+ const SPACE: Partial<Record<Role, [number, number]>> = { out: [1.5, 0.8], lit: [1.15, 0.95], in: [2.6, 0.72], crease: [3.2, 0.7], seam: [3.8, 0.66], hair: [3.2, 0.7], chain: [5.5, 0.66] };+ return {+ id: "stipple",+ knock: (ctx, pts) => knockWith(ctx, L, env.scale, pts),+ region: (ctx, pts, q, m) => { const d = Math.max(0, Math.min(1, 1 - q / 4)); dots(ctx, pts, Math.min(0.95, 0.04 + 0.78 * d ** 1.25 + (m.accent ? 0.22 : 0)), nameHash(m)); },+ // no contours in this medium: an outline is a denser row of the same dots+ line: (ctx, pts, role, _m, close, a, prog) => {+ if (role === "light") return; const [step, r] = SPACE[role]!, o = offset(), pa = along(pts, step, close, prog);+ ctx.globalAlpha = a; ctx.fillStyle = CARBON; ctx.beginPath();+ pa.forEach(([x, y], i) => { const rr = rng(hash(x - o[0], y - o[1], i)); const jx = (rr() - 0.5) * 0.5, jy = (rr() - 0.5) * 0.5; ctx.moveTo(x + jx + r, y + jy); ctx.arc(x + jx, y + jy, r * (0.85 + rr() * 0.3), 0, Math.PI * 2); });+ ctx.fill(); ctx.globalAlpha = 1;+ },+ dot: (ctx, at, r, _m, a) => { ctx.globalAlpha = a; ctx.fillStyle = CARBON; ctx.beginPath(); ctx.arc(at[0], at[1], Math.max(0.8, r * 0.7), 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx) => blit(ctx, L, env),+ frame: (ctx, W0, H0, p) => { const pad = 34; const ring: P2[] = [[pad, pad], [W0 - pad, pad], [W0 - pad, H0 - pad], [pad, H0 - pad]]; const pa = along(ring, 3, true, p); ctx.fillStyle = CARBON; ctx.globalAlpha = 0.55; ctx.beginPath(); pa.forEach(([x, y]) => { ctx.moveTo(x + 0.6, y); ctx.arc(x, y, 0.6, 0, Math.PI * 2); }); ctx.fill(); ctx.globalAlpha = 1; },+ text: (_ctx, t, x, y, o) => letter(g, t, x, y, { cap: o.cap, align: o.align, color: o.soft ? "#6b665e" : CARBON, opacity: o.alpha ?? 1, seed: hash(x, y), slant: 0, w: Math.max(0.9, o.cap * 0.085) }),+ shadow: (ctx, pts, s) => dots(ctx, pts.map(([x, y]) => [x + 2, y + 7] as P2), 0.22 * s, 7),+ };+};++// ---------------------------------------------------------------- isometric: flat planes, three tones, no line+// The house iso medium (references/styles/isometric.md): every plane ONE flat colour, exactly three+// tones per material (top lightest, the lamp-side face middle, the far face darkest), tone meets tone+// with no contour, details as hairlines, cast shadows one flat shape. Fills only, so it is fast+// enough for an interactive page.+const mixHex = (a: string, b: string, t: number) => { const pa = [1, 3, 5].map((i) => parseInt(a.slice(i, i + 2), 16)), pb = [1, 3, 5].map((i) => parseInt(b.slice(i, i + 2), 16)); return "#" + pa.map((v, i) => Math.round(v + (pb[i] - v) * t).toString(16).padStart(2, "0")).join(""); };+export const isometricHand = (paper = "#efe8dc", ink = "#2b2a33"): Hand => {+ const tones = new Map<string, [string, string, string]>();+ const three = (m: Material) => { const k = m.pigment ?? "#9a9a9a"; let t = tones.get(k); if (!t) { t = [mixHex(k, "#1d1a2a", 0.3), k, mixHex(k, "#ffffff", 0.5)]; tones.set(k, t); } return t; };+ const flat = (ctx: Ctx, pts: P2[], col: string, a = 1) => { ctx.globalAlpha = a; ctx.fillStyle = col; path(ctx, pts); ctx.fill(); ctx.strokeStyle = col; ctx.lineWidth = 0.5; ctx.lineJoin = "round"; ctx.stroke(); ctx.globalAlpha = 1; };+ const base = flatHand(paper, "#7a7280", "#b9b0a3");+ return {+ ...base, id: "isometric", coarse: 3.4,+ knock: (ctx, pts) => flat(ctx, pts, paper),+ region: (ctx, pts, q, m, a) => { const [far, side, top] = three(m); flat(ctx, pts, q >= 3.6 ? top : q >= 1.8 ? side : far, a); },+ step: (q) => (q >= 3.6 ? 2 : q >= 1.8 ? 1 : 0), opaque: true,+ line: (ctx, pts, role, m, close, a, prog) => {+ // a plane is pen-traced before it is filled; once filled, tone meets tone and the trace is gone+ if ((role === "out" || role === "lit" || role === "in" || role === "crease") && reveal().tone < 1) { rawStroke(ctx, pts, "#6f8cc4", 1.6, close, 0.9 * a, prog); return; }+ if (role === "seam" || role === "hair") rawStroke(ctx, pts, three(m)[0], 0.7, close, 0.8 * a, prog);+ else if (role === "chain") { ctx.save(); ctx.setLineDash([6, 4]); rawStroke(ctx, pts, ink, 0.8, false, 0.35 * a, prog); ctx.restore(); }+ },+ dot: (ctx, at, r, m, a) => { ctx.globalAlpha = a; ctx.fillStyle = three(m)[0]; ctx.beginPath(); ctx.arc(at[0], at[1], r, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ shadow: (ctx, pts, s) => flat(ctx, pts.map(([x, y]) => [x + 6, y + 9] as P2), "#3a3346", 0.13 * s),+ };+};++/** every hand, by the id of the style whose medium it follows ("flat" is the kit's plain reference hand) */+export const HANDS: Record<string, (ctx: Ctx, env: Env, frame: number) => Hand> = {+ flat: () => flatHand(),+ blueprint: blueprintHand,+ colouredPencil: colouredPencilHand,+ stipple: stippleHand,+ isometric: () => isometricHand(),+};diff --git a/skills/anidoodle/engine/src/canvas-core/mechanismKit.ts b/skills/anidoodle/engine/src/canvas-core/mechanismKit.tsnew file mode 100644index 0000000..4c4c9ee--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanismKit.ts@@ -0,0 +1,424 @@+// MECHANISM KIT. The technical illustrator's bench, in code: a free-angle axonometric camera,+// one light locked to it, solids that know their own silhouettes, turned parts shaded in exact+// bands, hardware that fades as it turns away, a depth-sorted parts list, a closed-form spring for+// exploded views, and the figure card. Every function is pure; nothing reads a clock.+//+// World: millimetres, z up. The camera looks down at elevation E from azimuth A; (cos A, sin A) is+// the floor direction toward the viewer. At A = 45, E = 30 it is the 2:1 dimetric of isometricKit.+//+// The light rides with the camera, up and to the viewer's left, so the same face family is always+// the light one. A face's tone is how many thresholds its light score passes (0, .2, .42, .62):+// five tones per material, darkest side to top. Near a threshold the tone crossfades, so a part+// that turns never flips colour in one frame.+import type { Ctx } from "./core";+import { G, width as glyphWidth } from "./drafting";++export type V3 = [number, number, number];+export type P2 = [number, number];+export const add = (a: V3, b: V3): V3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+export const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+export const mul = (a: V3, k: number): V3 => [a[0] * k, a[1] * k, a[2] * k];+export const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+export const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+export const unit = (a: V3): V3 => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };+export const clamp01 = (t: number) => (t <= 0 ? 0 : t >= 1 ? 1 : t);+export const smooth = (a: number, b: number, x: number) => { const t = clamp01((x - a) / (b - a)); return t * t * (3 - 2 * t); };+const D2R = Math.PI / 180;++// ---------------------------------------------------------------- camera+export class Cam {+ readonly sA: number; readonly cA: number; readonly sE: number; readonly cE: number;+ readonly V: V3; readonly L: V3;+ constructor(public A: number, public E: number, public k: number, public ox: number, public oy: number) {+ this.sA = Math.sin(A * D2R); this.cA = Math.cos(A * D2R); this.sE = Math.sin(E * D2R); this.cE = Math.cos(E * D2R);+ this.V = [this.cA * this.cE, this.sA * this.cE, this.sE];+ this.L = unit([-this.sA, this.cA, 1.2]);+ }+ p(q: V3): P2 { const [x, y, z] = q; return [this.ox + this.k * (x * this.sA - y * this.cA), this.oy + this.k * ((x * this.cA + y * this.sA) * this.sE - z * this.cE)]; }+ /** larger is nearer the viewer */+ depth(q: V3) { return dot(q, this.V); }+ /** screen offset of a world translation (exact in an orthographic camera) */+ dv(v: V3): P2 { return [this.k * (v[0] * this.sA - v[1] * this.cA), this.k * ((v[0] * this.cA + v[1] * this.sA) * this.sE - v[2] * this.cE)]; }+ /** fit world points into a box: the same camera, rescaled and centred */+ static fit(A: number, E: number, pts: V3[], box: [number, number, number, number]): Cam {+ const c = new Cam(A, E, 1, 0, 0), s = pts.map((q) => c.p(q));+ const x0 = Math.min(...s.map((q) => q[0])), x1 = Math.max(...s.map((q) => q[0])), y0 = Math.min(...s.map((q) => q[1])), y1 = Math.max(...s.map((q) => q[1]));+ const k = Math.min((box[2] - box[0]) / (x1 - x0), (box[3] - box[1]) / (y1 - y0));+ return new Cam(A, E, k, (box[0] + box[2]) / 2 - k * (x0 + x1) / 2, (box[1] + box[3]) / 2 - k * (y0 + y1) / 2);+ }+}++// ---------------------------------------------------------------- tone+export const THRESH = [0, 0.2, 0.42, 0.62] as const;+/** a continuous tone level 0..4; integer away from thresholds, a 0.07-wide crossfade across each */+export const level = (score: number, soft = 0.035) => THRESH.reduce((q: number, t: number) => q + smooth(t - soft, t + soft, score), 0);+export type Material = { ramp: [string, string, string, string, string]; ink: string; seam: string; pigment?: string; accent?: boolean; name?: string };+const hexRgb = (h: string): V3 => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];+const mixMemo = new Map<string, string>();+/** the colour of level q of a material, quantised to 1/64 so the memo stays small */+export const toneColour = (m: Material, q: number): string => {+ const Q = Math.round(Math.max(0, Math.min(4, q)) * 64), key = m.ramp[0] + m.ramp[4] + Q;+ let c = mixMemo.get(key); if (c) return c;+ const i = Math.min(3, Math.floor(Q / 64)), f = (Q - i * 64) / 64, a = hexRgb(m.ramp[i]), b = hexRgb(m.ramp[i + 1]);+ c = `rgb(${[0, 1, 2].map((j) => Math.round(a[j] + (b[j] - a[j]) * f)).join(",")})`; mixMemo.set(key, c); return c;+};+export const toneOf = (c: Cam, n: V3) => level(dot(unit(n), c.L));++// ---------------------------------------------------------------- marks+export const W_OUT = 1.6, W_IN = 0.9, W_HAIR = 0.6; // silhouette, inner line, faint line (logical px)+export const path = (ctx: Ctx, pts: P2[], close = true) => { ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); if (close) ctx.closePath(); };+/** a flat region; the hairline of its own colour closes the antialias seam against its neighbours */+// The making order, for films that draw themselves: a part is inked first (its lines run out to+// full length), then toned (the paper knocks out what is behind it, and the grey sheet is laid+// across it left to right). Set per part by the plate; (1, 1) is the finished drawing.+const REVEAL = { ink: 1, tone: 1, paper: "#ffffff" };+export const setReveal = (ink: number, tone: number, paper = REVEAL.paper) => { REVEAL.ink = ink; REVEAL.tone = tone; REVEAL.paper = paper; };+/** where the making order stands for the part being painted (hands that trace before they fill read it) */+export const reveal = (): { ink: number; tone: number } => ({ ink: REVEAL.ink, tone: REVEAL.tone });+export const solid = (ctx: Ctx, pts: P2[], colour: string, alpha: number) => { ctx.globalAlpha = alpha; ctx.fillStyle = colour; path(ctx, pts); ctx.fill(); ctx.strokeStyle = colour; ctx.lineWidth = 0.45; ctx.lineJoin = "round"; ctx.stroke(); ctx.globalAlpha = 1; };+export const fill = (ctx: Ctx, pts: P2[], colour: string, alpha = 1) => {+ if (pts.length < 3) return;+ if (REVEAL.tone >= 1) return solid(ctx, pts, colour, alpha);+ if (REVEAL.ink < 1) return;+ solid(ctx, pts, REVEAL.paper, alpha); if (REVEAL.tone <= 0) return;+ const x0 = Math.min(...pts.map((q) => q[0])), x1 = Math.max(...pts.map((q) => q[0]));+ ctx.save(); ctx.beginPath(); ctx.rect(x0 - 1, -1e5, (x1 - x0 + 2) * REVEAL.tone, 2e5); ctx.clip(); solid(ctx, pts, colour, alpha); ctx.restore();+};+export const stroke = (ctx: Ctx, pts: P2[], colour: string, w: number, close = false, alpha = 1) => rawStroke(ctx, pts, colour, w, close, alpha, REVEAL.ink);+/** a ruled line; progress < 1 draws its first part only (the pen still travelling) */+export const rawStroke = (ctx: Ctx, pts: P2[], colour: string, w: number, close: boolean, alpha: number, progress: number) => {+ if (pts.length < 2 || progress <= 0) return; ctx.globalAlpha = alpha; ctx.strokeStyle = colour; ctx.lineWidth = w; ctx.lineCap = "round"; ctx.lineJoin = "round"; path(ctx, pts, close);+ if (progress < 1) { let L = 0; for (let i = 1; i < pts.length; i++) L += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]); if (close) L += Math.hypot(pts[0][0] - pts[pts.length - 1][0], pts[0][1] - pts[pts.length - 1][1]); ctx.setLineDash([L * progress, L + 1]); }+ ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1;+};+/** a line that must stop on a bare face fades out over its last `fade` px instead of ending on a cap */+export const strokeFade = (ctx: Ctx, a: P2, b: P2, colour: string, w: number, fade: number, alpha = 1) => {+ const L = Math.hypot(b[0] - a[0], b[1] - a[1]); if (L < 0.5) return;+ const g = ctx.createLinearGradient(a[0], a[1], b[0], b[1]), [r, gg, bb] = hexRgb(colour), f = Math.min(0.5, fade / L);+ g.addColorStop(0, `rgba(${r},${gg},${bb},${alpha})`); g.addColorStop(1 - f, `rgba(${r},${gg},${bb},${alpha})`); g.addColorStop(1, `rgba(${r},${gg},${bb},0)`);+ ctx.strokeStyle = g; ctx.lineWidth = w; ctx.lineCap = "butt"; ctx.beginPath(); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke();+};+// ---------------------------------------------------------------- the hand: who makes the marks+// The kit decides WHAT is there (a region of tone q on a material, a silhouette, a crease, a seam);+// the hand decides HOW it is marked, in its own medium. A flat hand fills tones and rules lines; a+// pencil hand hatches, a stipple hand dots, a blueprint hand rules white ink and section-lines the+// part to watch. Any style can draw any machine by bringing a hand. q is 0 (darkest side) to 4 (top).+export type Role = "out" | "lit" | "in" | "crease" | "seam" | "hair" | "light" | "chain";+export type Hand = {+ id: string;+ knock(ctx: Ctx, pts: P2[]): void; // paint the ground back: a part hides what is behind it+ region(ctx: Ctx, pts: P2[], q: number, m: Material, alpha: number): void;+ line(ctx: Ctx, pts: P2[], role: Role, m: Material, close: boolean, alpha: number, progress: number): void;+ dot(ctx: Ctx, at: P2, r: number, m: Material, alpha: number): void;+ sheet(ctx: Ctx, W: number, H: number): void; // the ground of the whole card+ frame(ctx: Ctx, W: number, H: number, progress: number): void; // the card's rule+ text(ctx: Ctx, s: string, x: number, y: number, o: { cap: number; align?: "left" | "right" | "center"; soft?: boolean; alpha?: number }): void;+ shadow?(ctx: Ctx, pts: P2[], strength: number): void; // a contact shadow, if the medium has light at all+ coarse?: number; // > 1: fewer rows on turned parts (flat media need less), for speed+ step?(q: number, m: Material): number;+ opaque?: boolean; // a full-strength region hides what is under it, so it needs no knock first // a medium with few tones: which one q lands on, so a band that repeats its neighbour is not painted+};+const WEIGHT: Record<Role, number> = { out: W_OUT, lit: W_OUT * 1.2, in: W_IN, crease: W_IN, seam: W_HAIR, hair: W_HAIR, light: W_IN, chain: W_HAIR };+/** the plain hand: flat tone fills and ruled lines. The kit's default and its reference. */+export const flatHand = (paper = "#f3f0e8", soft = "#6d6a70", rule = "#9a968e"): Hand => ({+ id: "flat",+ knock: (ctx, pts) => solid(ctx, pts, paper, 1),+ region: (ctx, pts, q, m, a) => solid(ctx, pts, toneColour(m, q), a),+ line: (ctx, pts, role, m, close, a, prog) => {+ const col = role === "crease" || role === "seam" ? m.seam : role === "light" ? "#ffffff" : role === "chain" ? soft : m.ink;+ if (role === "chain") { ctx.save(); ctx.setLineDash([9, 3, 1.5, 3]); rawStroke(ctx, pts, col, WEIGHT[role], close, a, prog); ctx.restore(); return; }+ rawStroke(ctx, pts, col, WEIGHT[role], close, role === "light" ? a * 0.85 : a, prog);+ },+ dot: (ctx, at, r, m, a) => { ctx.globalAlpha = a; ctx.fillStyle = m.ink; ctx.beginPath(); ctx.arc(at[0], at[1], r, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },+ sheet: (ctx, W, H) => { ctx.fillStyle = paper; ctx.fillRect(0, 0, W, H); },+ frame: (ctx, W, H, p) => ruleFrame(ctx, W, H, rule, p),+ text: (ctx, t, x, y, o) => stencil(ctx, t, x, y, { cap: o.cap, colour: o.soft ? soft : "#232227", align: o.align, alpha: o.alpha }),+ shadow: (ctx, pts, k) => { const cx = pts.reduce((a, q) => a + q[0], 0) / pts.length, cy = pts.reduce((a, q) => a + q[1], 0) / pts.length; for (let i = 0; i < 8; i++) { const f = 1 + i * 0.012; solid(ctx, pts.map(([x, y]) => [cx + (x - cx) * f, cy + (y - cy) * f + 5 + i] as P2), "#5b574f", 0.022 * k); } },+});+let HAND: Hand = flatHand();+let OFFSET: P2 = [0, 0];+/** the screen offset of the part being painted: hands anchor their patterns to it, so marks travel with their part */+export const offset = (): P2 => OFFSET;+export const setHand = (h: Hand) => { HAND = h; };+export const hand = () => HAND;+/** a toned region in the current hand, honouring the making order (inked, then toned left to right) */+export const tone = (ctx: Ctx, pts: P2[], m: Material, q: number, alpha = 1) => {+ if (pts.length < 3) return;+ if (REVEAL.tone >= 1) { if (!(HAND.opaque && alpha >= 1)) HAND.knock(ctx, pts); HAND.region(ctx, pts, q, m, alpha); return; }+ if (REVEAL.ink < 1) return;+ HAND.knock(ctx, pts); if (REVEAL.tone <= 0) return;+ const x0 = Math.min(...pts.map((v) => v[0])), x1 = Math.max(...pts.map((v) => v[0]));+ ctx.save(); ctx.beginPath(); ctx.rect(x0 - 1, -1e5, (x1 - x0 + 2) * REVEAL.tone, 2e5); ctx.clip(); HAND.region(ctx, pts, q, m, alpha); ctx.restore();+};+/** paint the ground back over a shape without toning it (the paper inside a hull) */+export const knock = (ctx: Ctx, pts: P2[]) => { if (pts.length >= 3 && (REVEAL.tone >= 1 || REVEAL.ink >= 1)) HAND.knock(ctx, pts); };+export const ink = (ctx: Ctx, pts: P2[], role: Role, m: Material, close = false, alpha = 1) => { if (pts.length >= 2 && REVEAL.ink > 0) HAND.line(ctx, pts, role, m, close, alpha, REVEAL.ink); };+export const inkDot = (ctx: Ctx, at: P2, r: number, m: Material, alpha = 1) => { if (REVEAL.ink >= 1) HAND.dot(ctx, at, r, m, alpha); };+const ruleFrame = (ctx: Ctx, W: number, H: number, colour: string, p: number, pad = 34) => {+ if (p <= 0) return; ctx.strokeStyle = colour; ctx.lineWidth = 1.2; ctx.globalAlpha = 1; ctx.lineCap = "butt"; ctx.setLineDash([]);+ const L = 2 * (W + H - 4 * pad) * clamp01(p), segs: [P2, P2][] = [[[pad, pad], [W - pad, pad]], [[W - pad, pad], [W - pad, H - pad]], [[W - pad, H - pad], [pad, H - pad]], [[pad, H - pad], [pad, pad]]];+ let left = L; ctx.beginPath(); for (const [a, b] of segs) { if (left <= 0) break; const l = Math.hypot(b[0] - a[0], b[1] - a[1]), f = Math.min(1, left / l); ctx.moveTo(a[0], a[1]); ctx.lineTo(a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f); left -= l; } ctx.stroke();+};++export const hull = (pts: P2[]): P2[] => {+ const s = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]); if (s.length < 3) return s;+ const cr = (o: P2, a: P2, b: P2) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);+ const lo: P2[] = [], up: P2[] = [];+ for (const p of s) { while (lo.length >= 2 && cr(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); }+ for (let i = s.length - 1; i >= 0; i--) { const p = s[i]; while (up.length >= 2 && cr(up[up.length - 2], up[up.length - 1], p) <= 0) up.pop(); up.push(p); }+ return lo.slice(0, -1).concat(up.slice(0, -1));+};++// ---------------------------------------------------------------- plans (floor outlines)+export const rrect = (x: number, y: number, w: number, d: number, r: number, steps = 6): P2[] => {+ r = Math.max(0, Math.min(r, w / 2, d / 2)); if (r === 0) return [[x, y], [x + w, y], [x + w, y + d], [x, y + d]];+ const c: [number, number, number][] = [[x + w - r, y + r, -Math.PI / 2], [x + w - r, y + d - r, 0], [x + r, y + d - r, Math.PI / 2], [x + r, y + r, Math.PI]];+ return c.flatMap(([cx, cy, a0]) => Array.from({ length: steps + 1 }, (_, i) => { const a = a0 + (i / steps) * (Math.PI / 2); return [cx + Math.cos(a) * r, cy + Math.sin(a) * r] as P2; }));+};+export const circle = (cx: number, cy: number, r: number, steps = 40): P2[] => Array.from({ length: steps }, (_, i) => { const a = (i / steps) * Math.PI * 2; return [cx + Math.cos(a) * r, cy + Math.sin(a) * r] as P2; });+const ccw = (ring: P2[]) => ring.reduce((s, a, i) => { const b = ring[(i + 1) % ring.length]; return s + a[0] * b[1] - b[0] * a[1]; }, 0) > 0;++// ---------------------------------------------------------------- prisms: a convex plan extruded up+export type PrismOpts = { lit?: boolean; seams?: number[]; bevel?: number; outline?: boolean; inner?: (ctx: Ctx) => void; off?: P2 };+/** paints a convex floor plan extruded from z to z + h: paper, sides by tone, top, crease, bevel, seams, outline */+export const prism = (ctx: Ctx, c: Cam, ring: P2[], z: number, h: number, m: Material, o: PrismOpts = {}) => {+ const [dx, dy] = o.off ?? [0, 0], P = (q: V3): P2 => { const s = c.p(q); return [s[0] + dx, s[1] + dy]; };+ const R = ccw(ring) ? ring : [...ring].reverse(), n = R.length, top = R.map(([x, y]) => P([x, y, z + h])), bot = R.map(([x, y]) => P([x, y, z]));+ const out = hull(top.concat(bot)); knock(ctx, out);+ const facing: boolean[] = [];+ for (let i = 0; i < n; i++) {+ const a = R[i], b = R[(i + 1) % n], nx = b[1] - a[1], ny = -(b[0] - a[0]), l = Math.hypot(nx, ny) || 1, nn: V3 = [nx / l, ny / l, 0];+ facing[i] = nn[0] * c.cA + nn[1] * c.sA > 1e-9; if (!facing[i]) continue;+ tone(ctx, [bot[i], bot[(i + 1) % n], top[(i + 1) % n], top[i]], m, Math.min(3, toneOf(c, nn)));+ }+ tone(ctx, top, m, 4);+ const runs: P2[][] = []; // the top ring along facing edges: the crease where the top meets the sides+ for (let i = 0; i < n; i++) if (facing[i]) { const last = runs[runs.length - 1]; if (last && facing[(i - 1 + n) % n] && last[last.length - 1] === top[i]) last.push(top[(i + 1) % n]); else runs.push([top[i], top[(i + 1) % n]]); }+ for (const s of o.seams ?? []) for (let i = 0; i < n; i++) if (facing[i]) ink(ctx, [P([R[i][0], R[i][1], z + s]), P([R[(i + 1) % n][0], R[(i + 1) % n][1], z + s])], "seam", m);+ if (o.bevel) { // a bright line just inside the crease: the light catching a softened edge+ const cx = R.reduce((s, q) => s + q[0], 0) / n, cy = R.reduce((s, q) => s + q[1], 0) / n;+ const ins = R.map(([x, y]) => { const l = Math.hypot(x - cx, y - cy) || 1; return P([x - ((x - cx) / l) * o.bevel!, y - ((y - cy) / l) * o.bevel!, z + h]); });+ for (let i = 0; i < n; i++) if (facing[i]) ink(ctx, [ins[i], ins[(i + 1) % n]], "light", m);+ }+ o.inner?.(ctx);+ runs.forEach((r) => ink(ctx, r, "crease", m));+ if (o.outline !== false) ink(ctx, out, o.lit ? "lit" : "out", m, true);+ return out;+};+export const box = (ctx: Ctx, c: Cam, x: number, y: number, z: number, w: number, d: number, h: number, m: Material, o: PrismOpts & { r?: number } = {}) =>+ prism(ctx, c, rrect(x, y, w, d, o.r ?? 0), z, h, m, o);++// ---------------------------------------------------------------- frames and turned parts+export type Frame = { o: V3; a: V3; u: V3; v: V3 };+export const frameAlong = (o: V3, a: V3): Frame => { a = unit(a); const h: V3 = Math.abs(a[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1], u = unit(cross(h, a)); return { o, a, u, v: cross(a, u) }; };+export const at = (F: Frame, s: number, r: number, th: number): V3 => add(add(F.o, mul(F.a, s)), add(mul(F.u, r * Math.cos(th)), mul(F.v, r * Math.sin(th))));+export const radial = (F: Frame, th: number): V3 => add(mul(F.u, Math.cos(th)), mul(F.v, Math.sin(th)));+/** how squarely the surface of a turned part faces the viewer at (s, th), -1..1 */+export const facingAt = (c: Cam, F: Frame, th: number, slope = 0) => dot(unit(sub(radial(F, th), mul(F.a, slope))), c.V);+export type Profile = { s0: number; s1: number; r: (s: number) => number; dr: (s: number) => number };+export const cyl = (s0: number, s1: number, r: number): Profile => ({ s0, s1, r: () => r, dr: () => 0 });+export const cone = (s0: number, s1: number, r0: number, r1: number): Profile => ({ s0, s1, r: (s) => r0 + ((r1 - r0) * (s - s0)) / (s1 - s0), dr: () => (r1 - r0) / (s1 - s0) });+/** a dome or a ball segment: radius R sphere centred at sc on the axis, between s0 and s1 */+export const sphere = (s0: number, s1: number, sc: number, R: number): Profile => ({ s0, s1, r: (s) => Math.sqrt(Math.max(1e-6, R * R - (s - sc) ** 2)), dr: (s) => -(s - sc) / Math.sqrt(Math.max(1e-3, R * R - (s - sc) ** 2)) });++type Arc = [number, number] | null;+const wrap = (a: number) => { a = (a + Math.PI) % (2 * Math.PI); if (a < 0) a += 2 * Math.PI; return a - Math.PI; };+// The interval of angles (relative to the view's own angle) where cos(th - centre) >= c, cut to+// [-half, half]; the largest piece if the cut leaves two.+const band = (centre: number, c: number, half: number): Arc => {+ if (c > 1 || half <= 0) return null; const g = c < -1 ? Math.PI : Math.acos(c); if (g >= Math.PI) return [-half, half];+ let best: Arc = null;+ for (const k of [-2 * Math.PI, 0, 2 * Math.PI]) { const lo = Math.max(-half, centre - g + k), hi = Math.min(half, centre + g + k); if (hi > lo && (!best || hi - lo > best[1] - best[0])) best = [lo, hi]; }+ return best;+};++export type TurnOpts = { caps?: [boolean, boolean]; lit?: boolean; off?: P2; rows?: number; outline?: boolean; capTone?: [number?, number?]; rims?: number[] };+/** A surface of revolution about frame F, shaded in exact light bands: every band's border is solved+ * per ring in closed form, so curved bodies never staircase, and a band that appears is born at zero width. */+export const turned = (ctx: Ctx, c: Cam, F: Frame, pr: Profile, m: Material, o: TurnOpts = {}) => {+ const [dx, dy] = o.off ?? [0, 0], P = (q: V3): P2 => { const s = c.p(q); return [s[0] + dx, s[1] + dy]; };+ const pl = (w: V3) => [dot(w, F.u), dot(w, F.v), dot(w, F.a)] as V3;+ const [vu, vv, va] = pl(c.V), [lu, lv, la] = pl(c.L), phV = Math.atan2(vv, vu), Vp = Math.hypot(vu, vv), phL = Math.atan2(lv, lu), Lp = Math.hypot(lu, lv);+ const screenLen = Math.hypot(...(c.dv(mul(F.a, pr.s1 - pr.s0)) as [number, number])) + c.k * Math.abs(pr.r(pr.s1) - pr.r(pr.s0));+ const N = o.rows ?? Math.max(8, Math.min(120, Math.ceil(screenLen / (2.5 * (HAND.coarse ?? 1)))));+ const ss = Array.from({ length: N + 1 }, (_, i) => pr.s0 + ((pr.s1 - pr.s0) * i) / N);+ const rows = ss.map((s) => {+ const r = pr.r(s), d = pr.dr(s), len = Math.hypot(1, d), nr = 1 / len, na = -d / len;+ const vis = Vp < 1e-9 ? (na * va > 0 ? Math.PI : 0) : Math.acos(Math.max(-1, Math.min(1, (-na * va) / (nr * Vp))));+ const lvl = THRESH.map((t) => (Lp < 1e-9 ? (na * la >= t ? ([-vis, vis] as Arc) : null) : band(wrap(phL - phV), (t - na * la) / (nr * Lp), vis)));+ return { s, r, vis, lvl };+ });+ const pt = (i: number, rel: number) => P(at(F, rows[i].s, rows[i].r, phV + rel));+ // the region between two angle curves over runs of rows where it exists; it closes to a point where it is born+ const region = (get: (i: number) => Arc): P2[][] => {+ const polys: P2[][] = []; let i = 0;+ while (i <= N) {+ if (!get(i)) { i++; continue; }+ const j0 = i; while (i <= N && get(i)) i++; const j1 = i - 1;+ const left: P2[] = [], right: P2[] = [];+ if (j0 > 0) { const a = get(j0)!; left.push(pt(j0 - 1, (a[0] + a[1]) / 2)); }+ for (let j = j0; j <= j1; j++) { const a = get(j)!; left.push(pt(j, a[0])); right.push(pt(j, a[1])); }+ if (j1 < N) { const a = get(j1)!; right.push(pt(j1 + 1, (a[0] + a[1]) / 2)); }+ // at an end of the solid the band is bounded by the end's circle, never by a chord across it+ const arc = (i: number, from: number, to: number) => { const n = Math.max(2, Math.min(16, Math.ceil((Math.abs(to - from) * c.k * rows[i].r) / 5))); return Array.from({ length: n - 1 }, (_, k) => pt(i, from + ((to - from) * (k + 1)) / n)); };+ const tail = j1 === N ? arc(N, get(N)![0], get(N)![1]) : [], head = j0 === 0 ? arc(0, get(0)![1], get(0)![0]) : [];+ polys.push(left.concat(tail, right.reverse(), head));+ }+ return polys;+ };+ const sideArc = (i: number): Arc => (rows[i].vis > 0.01 ? [-rows[i].vis, rows[i].vis] : null);+ const ring = (i: number, steps = 64) => Array.from({ length: steps }, (_, j) => pt(i, (j / steps) * 2 * Math.PI));+ const lit = o.lit ? 0.35 : 0;+ region(sideArc).forEach((p) => tone(ctx, p, m, 0 + lit));+ // the bands nest, so one that lands on the same tone as the band under it adds nothing+ let under = HAND.step?.(lit, m);+ for (let t = 0; t < 4; t++) { const q = Math.min(t === 3 ? 4 : 3.4, t + 1) + lit, k = HAND.step?.(q, m); if (k !== undefined && k === under) continue; under = k; region((i) => rows[i].lvl[t]).forEach((p) => tone(ctx, p, m, q)); }+ // end caps: a disc faces the viewer at one end at most+ const caps = o.caps ?? [true, true], capVis = [dot(F.a, c.V) < 0, dot(F.a, c.V) > 0];+ const capIdx = [0, N];+ [0, 1].forEach((e) => { if (!caps[e] || !capVis[e]) return; const nrm = e ? F.a : mul(F.a, -1); tone(ctx, ring(capIdx[e]), m, (o.capTone?.[e] ?? toneOf(c, nrm)) + lit); });+ for (const s of o.rims ?? []) { const i = Math.round(((s - pr.s0) / (pr.s1 - pr.s0)) * N), v = rows[i].vis; if (v > 0.05) ink(ctx, Array.from({ length: 33 }, (_, j) => pt(i, -v + (2 * v * j) / 32)), "seam", m); }+ if (o.outline === false) return;+ const w: Role = o.lit ? "lit" : "out";+ [0, 1].forEach((e) => { const i = capIdx[e]; if (caps[e] && capVis[e]) ink(ctx, ring(i), "in", m, true); });+ const L: P2[] = [], Rr: P2[] = [];+ rows.forEach((row, i) => { if (row.vis > 0.01) { L.push(pt(i, -row.vis)); Rr.push(pt(i, row.vis)); } });+ ink(ctx, L, w, m); ink(ctx, Rr, w, m);+ [0, 1].forEach((e) => { const i = capIdx[e], v = rows[i].vis; if (caps[e] && capVis[e]) ink(ctx, Array.from({ length: 33 }, (_, j) => pt(i, v + ((2 * Math.PI - 2 * v) * j) / 32)), w, m); else if (v > 0.01) ink(ctx, Array.from({ length: 33 }, (_, j) => pt(i, -v + (2 * v * j) / 32)), w, m); });+};++/** a flat disc (a washer face, a screw head, a dial) lying in the plane through `o` with normal `n` */+export const disc = (c: Cam, o: V3, n: V3, r: number, steps = 32, off: P2 = [0, 0]): P2[] => {+ const F = frameAlong(o, n); return Array.from({ length: steps }, (_, i) => { const s = c.p(at(F, 0, r, (i / steps) * 2 * Math.PI)); return [s[0] + off[0], s[1] + off[1]] as P2; });+};+/** a slotted screw head seated on a face: domed disc, rim line, slot */+export const screw = (ctx: Ctx, c: Cam, o: V3, n: V3, r: number, m: Material, slot = 0.6, off: P2 = [0, 0]) => {+ const F = frameAlong(o, n), lift = add(o, mul(F.a, r * 0.35));+ tone(ctx, disc(c, o, n, r, 24, off), m, toneOf(c, n) - 0.6); ink(ctx, disc(c, o, n, r, 24, off), "hair", m, true);+ tone(ctx, disc(c, lift, n, r * 0.72, 24, off), m, toneOf(c, n));+ const e = [at(F, r * 0.35, r * 0.7, slot), at(F, r * 0.35, r * 0.7, slot + Math.PI)].map((q) => { const s = c.p(q); return [s[0] + off[0], s[1] + off[1]] as P2; });+ ink(ctx, e, "in", m);+};++/** a flat plate of any convex outline lying in a frame's (u, v) plane, thickness t along its axis: a lever, a vane, a bracket */+export const slab = (ctx: Ctx, c: Cam, F: Frame, ring: P2[], t: number, m: Material, o: { lit?: boolean; off?: P2 } = {}) => {+ const [dx, dy] = o.off ?? [0, 0], P = (q: V3): P2 => { const s = c.p(q); return [s[0] + dx, s[1] + dy]; };+ const R = ccw(ring) ? ring : [...ring].reverse(), n = R.length, W3 = (q: P2, s: number): V3 => add(add(F.o, mul(F.a, s)), add(mul(F.u, q[0]), mul(F.v, q[1])));+ const back = R.map((q) => P(W3(q, 0))), front = R.map((q) => P(W3(q, t))), out = hull(back.concat(front)), lit = o.lit ? 0.3 : 0;+ knock(ctx, out);+ for (let i = 0; i < n; i++) {+ const a = R[i], b = R[(i + 1) % n], nn = unit(add(mul(F.u, b[1] - a[1]), mul(F.v, -(b[0] - a[0]))));+ if (dot(nn, c.V) > 1e-6) tone(ctx, [back[i], back[(i + 1) % n], front[(i + 1) % n], front[i]], m, Math.min(3, toneOf(c, nn)) + lit);+ }+ const capN = dot(F.a, c.V) > 0 ? F.a : mul(F.a, -1), cap = dot(F.a, c.V) > 0 ? front : back;+ tone(ctx, cap, m, toneOf(c, capN) + lit); ink(ctx, cap, "crease", m, true);+ ink(ctx, out, o.lit ? "lit" : "out", m, true);+};+/** a 2D outline of a bar with round ends, from (0,0) to (len,0), half-width w: a lever's plan */+export const leverRing = (len: number, w: number, w2 = w, steps = 10): P2[] => [+ ...Array.from({ length: steps + 1 }, (_, i) => { const a = Math.PI / 2 + (i / steps) * Math.PI; return [Math.cos(a) * w, Math.sin(a) * w] as P2; }),+ ...Array.from({ length: steps + 1 }, (_, i) => { const a = -Math.PI / 2 + (i / steps) * Math.PI; return [len + Math.cos(a) * w2, Math.sin(a) * w2] as P2; }),+];++// ---------------------------------------------------------------- tubes along 3D routes+/** fillet each corner of a 3D polyline with radius R (quadratic Bezier through the corner) */+export const fillet = (pts: V3[], R: number): V3[] => {+ if (pts.length < 3) return pts; const out: V3[] = [pts[0]];+ for (let i = 1; i < pts.length - 1; i++) {+ const a = pts[i - 1], b = pts[i], d = pts[i + 1], ui = unit(sub(b, a)), uo = unit(sub(d, b)), th = Math.acos(Math.max(-1, Math.min(1, dot(ui, uo))));+ const cut = Math.min(R * Math.tan(th / 2), 0.48 * Math.hypot(...sub(b, a)), 0.48 * Math.hypot(...sub(d, b))), p0 = sub(b, mul(ui, cut)), p1 = add(b, mul(uo, cut)), n = Math.max(3, Math.ceil((10 * th) / (Math.PI / 2)));+ for (let j = 0; j <= n; j++) { const t = j / n, q = (x: V3, y: V3) => add(x, mul(sub(y, x), t)); out.push(q(q(p0, b), q(b, p1))); }+ }+ out.push(pts[pts.length - 1]); return out;+};+/** a round tube along a route: body, a shade stripe, a shine stripe, outlines and visible end caps */+export const tubeAlong = (ctx: Ctx, c: Cam, route: V3[], r: number, m: Material, o: { bend?: number; caps?: [boolean, boolean]; off?: P2; lit?: boolean } = {}) => {+ const pts = fillet(route, o.bend ?? Math.max(3, 2.6 * r)), [dx, dy] = o.off ?? [0, 0], S = pts.map((q) => { const s = c.p(q); return [s[0] + dx, s[1] + dy] as P2; }), h = r * c.k;+ const nrm = S.map((_, i) => { const a = S[Math.max(0, i - 1)], b = S[Math.min(S.length - 1, i + 1)], tx = b[0] - a[0], ty = b[1] - a[1], l = Math.hypot(tx, ty) || 1; return [-ty / l, tx / l] as P2; });+ const off = (f: number) => S.map((p, i) => [p[0] + nrm[i][0] * h * f, p[1] + nrm[i][1] * h * f] as P2);+ const Ls: P2 = [-0.55, -0.835], wv = nrm.map((n) => n[0] * Ls[0] + n[1] * Ls[1]);+ const strip = (centre: number, half: number) => { const L: P2[] = [], R: P2[] = []; S.forEach((p, i) => { const cc = centre * wv[i]; L.push([p[0] + nrm[i][0] * h * (cc - half), p[1] + nrm[i][1] * h * (cc - half)]); R.push([p[0] + nrm[i][0] * h * (cc + half), p[1] + nrm[i][1] * h * (cc + half)]); }); return L.concat(R.reverse()); };+ const lit = o.lit ? 0.3 : 0;+ const cap = (i: number, dir: number) => { const j = Math.min(pts.length - 1, Math.max(0, i + dir)), T = unit(sub(pts[i], pts[j])); return { pts: disc(c, pts[i], T, r, 28, [dx, dy]), facing: dot(T, c.V) > 0 }; };+ const caps = o.caps ?? [true, true], ends = [cap(0, 1), cap(pts.length - 1, -1)];+ tone(ctx, off(1).concat(off(-1).reverse()), m, 2 + lit);+ ends.forEach((e, k) => { if (caps[k]) tone(ctx, e.pts, m, 2 + lit); });+ if (h > 1.3) { tone(ctx, strip(-0.62, 0.2), m, 0.6 + lit); tone(ctx, strip(0.44, 0.24), m, 4); }+ ends.forEach((e, k) => { if (caps[k] && e.facing) { tone(ctx, e.pts, m, 3 + lit); ink(ctx, e.pts, "in", m, true); } });+ ink(ctx, off(1), o.lit ? "lit" : "out", m); ink(ctx, off(-1), o.lit ? "lit" : "out", m);+};++// ---------------------------------------------------------------- the parts list, depth-sorted+export type Item = { id: string; at: V3; bias?: number; ride?: string; draw: (ctx: Ctx, off: P2) => void };+/** paint items far to near; each rides its assembly's world offset `move[ride] * share[ride]` */+export const paintAll = (ctx: Ctx, c: Cam, items: Item[], move: Record<string, V3> = {}, share: Record<string, number> = {}) => {+ const keyed = items.map((it, i) => { const mv = it.ride && move[it.ride] ? mul(move[it.ride], share[it.ride] ?? 0) : ([0, 0, 0] as V3); return { it, i, mv, key: c.depth(add(it.at, mv)) + (it.bias ?? 0) }; });+ keyed.sort((a, b) => a.key - b.key || a.i - b.i);+ for (const k of keyed) { OFFSET = c.dv(k.mv); k.it.draw(ctx, OFFSET); }+ OFFSET = [0, 0];+};++// ---------------------------------------------------------------- springs and the exploded view+/** closed-form damped spring from (x0, v0) toward g after tau seconds: any damping ratio z */+export const springAt = (w: number, z: number, x0: number, v0: number, g: number, tau: number): { x: number; v: number } => {+ if (tau <= 0) return { x: x0, v: v0 };+ const e0 = x0 - g;+ if (z < 0.999) { const wd = w * Math.sqrt(1 - z * z), A = e0, B = (v0 + z * w * e0) / wd, ex = Math.exp(-z * w * tau), co = Math.cos(wd * tau), si = Math.sin(wd * tau); return { x: g + ex * (A * co + B * si), v: ex * ((B * wd - z * w * A) * co - (A * wd + z * w * B) * si) }; }+ if (z <= 1.001) { const B = v0 + w * e0, ex = Math.exp(-w * tau); return { x: g + ex * (e0 + B * tau), v: ex * (B - w * (e0 + B * tau)) }; }+ const s = w * Math.sqrt(z * z - 1), r1 = -z * w + s, r2 = -z * w - s, C2 = (v0 - r1 * e0) / (r2 - r1), C1 = e0 - C2; return { x: g + C1 * Math.exp(r1 * tau) + C2 * Math.exp(r2 * tau), v: C1 * r1 * Math.exp(r1 * tau) + C2 * r2 * Math.exp(r2 * tau) };+};+export type ExplodePlan = { order: string[]; stagger: number; w: number; z: number };+/** The share (0 home, 1 apart) of every assembly at time t, from a list of cues (t, apart).+ * Opening runs in `order`, closing in reverse; a cue that lands mid-stagger cancels the moves+ * still pending and re-staggers only the assemblies whose target actually changes. Pure. */+export const sharesAt = (plan: ExplodePlan, cues: { t: number; apart: boolean }[], t: number): Record<string, number> => {+ const n = plan.order.length, ev: { t: number; g: number }[][] = plan.order.map(() => []);+ const targetAt = (i: number, time: number) => { let g = 0; for (const e of ev[i]) if (e.t <= time) g = e.g; return g; };+ for (const cue of [...cues].sort((a, b) => a.t - b.t)) {+ if (cue.t > t) break; const g = cue.apart ? 1 : 0;+ for (let i = 0; i < n; i++) ev[i] = ev[i].filter((e) => e.t <= cue.t);+ const idx = Array.from({ length: n }, (_, i) => i).filter((i) => targetAt(i, cue.t) !== g); if (!cue.apart) idx.reverse();+ idx.forEach((i, k) => ev[i].push({ t: cue.t + k * plan.stagger, g }));+ }+ const out: Record<string, number> = {};+ plan.order.forEach((id, i) => { let x = 0, v = 0, t0 = 0, g = 0; for (const e of ev[i]) { if (e.t > t) break; const s = springAt(plan.w, plan.z, x, v, g, e.t - t0); x = s.x; v = s.v; t0 = e.t; g = e.g; } out[id] = springAt(plan.w, plan.z, x, v, g, t - t0).x; });+ return out;+};+/** a one-shot envelope by age in seconds: smoothstep attack, exponential release; 0 before and long after */+export const envelope = (age: number, rise = 0.06, fall = 0.35) => (age < 0 ? 0 : age < rise ? smooth(0, rise, age) : Math.exp(-(age - rise) / fall));++// ---------------------------------------------------------------- template lettering and the card+/** single-stroke technical lettering, as with a scriber and template: one even weight, upright, crisp */+export const stencil = (ctx: Ctx, text: string, x: number, y: number, o: { cap?: number; colour?: string; align?: "left" | "center" | "right"; w?: number; track?: number; alpha?: number } = {}) => {+ const cap = o.cap ?? 12, s = cap / 6, track = o.track ?? 2.2, col = o.colour ?? "#26252b", Wd = stencilWidth(text, cap, track);+ let cx = o.align === "center" ? x - Wd / 2 : o.align === "right" ? x - Wd : x;+ ctx.globalAlpha = o.alpha ?? 1; ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = o.w ?? Math.max(0.9, cap * 0.1); ctx.lineCap = "round"; ctx.lineJoin = "round";+ for (const ch of text) {+ if (ch === "·") { ctx.beginPath(); ctx.arc(cx + 1.5 * s, y + 3 * s, ctx.lineWidth * 0.75, 0, Math.PI * 2); ctx.fill(); cx += (3 + track) * s; continue; }+ if (ch === " ") { cx += (2.6 + track) * s; continue; }+ const g = G[ch] ?? G[ch.toUpperCase()] ?? G["-"]; ctx.beginPath();+ for (const st of [...(g.l ?? []), ...(g.c ?? [])]) st.forEach(([px, py], i) => (i ? ctx.lineTo(cx + px * s, y + py * s) : ctx.moveTo(cx + px * s, y + py * s)));+ ctx.stroke(); cx += ((g.w ?? 4) + track) * s;+ }+ ctx.globalAlpha = 1;+};+export const stencilWidth = (text: string, cap = 12, track = 2.2) => { const s = cap / 6; let w = 0; for (const ch of text) w += ch === "·" ? (3 + track) * s : ch === " " ? (2.6 + track) * s : glyphWidth(ch, cap, 0) + track * s; return w - track * s; };+export type CardText = { fig: string; title: string; hint: string; read: string };+/** The figure card, in the current hand: its ground, one rule, and the four corners: figure number, title, hint, live readout. */+/** a frame must never inherit pen state from the frame drawn before it */+export const freshPen = (ctx: Ctx) => { ctx.setLineDash([]); ctx.lineDashOffset = 0; ctx.lineCap = "butt"; ctx.lineJoin = "miter"; ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; };+export const card = (ctx: Ctx, W: number, H: number, t: CardText, o: { pad?: number; cap?: number; progress?: number; part?: "all" | "ground" | "words" } = {}) => {+ const pad = o.pad ?? 34, cap = o.cap ?? 13, p = o.progress ?? 1, part = o.part ?? "all"; freshPen(ctx);+ if (part !== "words") { HAND.sheet(ctx, W, H); if (p <= 0) return; HAND.frame(ctx, W, H, clamp01(p * 1.6)); }+ if (part === "ground" || p <= 0) return;+ const ty = clamp01((p - 0.5) * 2), i = pad + 22, top = pad + 20, bot = H - pad - 20 - cap;+ if (part === "words" && ty > 0) { // over a figure that fills the card, each word sits on its own cut of ground+ const sz = (s: string) => stencilWidth(s, cap) + 14, cut = (x: number, y: number, w: number) => HAND.knock(ctx, [[x - 7, y - 7], [x + w - 7, y - 7], [x + w - 7, y + cap + 7], [x - 7, y + cap + 7]]);+ cut(i, top, sz(t.fig)); cut(W - i - sz(t.title) + 14, top, sz(t.title)); cut(i, bot, sz(t.hint)); cut(W - i - sz(t.read) + 14, bot, sz(t.read));+ }+ if (ty > 0) {+ const upTo = (w: string) => (ty >= 1 ? w : w.slice(0, Math.ceil(w.length * ty))); // lettered left to right, never faded in+ HAND.text(ctx, upTo(t.fig), i, top, { cap }); if (ty >= 1) HAND.text(ctx, t.title, W - i, top, { cap, align: "right", soft: true }); else HAND.text(ctx, upTo(t.title), W - i - stencilWidth(t.title, cap) + stencilWidth(upTo(t.title), cap), top, { cap, align: "right", soft: true });+ HAND.text(ctx, upTo(t.hint), i, bot, { cap, soft: true }); if (ty >= 1) HAND.text(ctx, t.read, W - i, bot, { cap, align: "right" }); else HAND.text(ctx, upTo(t.read), W - i - stencilWidth(t.read, cap) + stencilWidth(upTo(t.read), cap), bot, { cap, align: "right" });+ }+};diff --git a/skills/anidoodle/engine/src/canvas-core/mechanismPencil.ts b/skills/anidoodle/engine/src/canvas-core/mechanismPencil.tsnew file mode 100644index 0000000..d910b65--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanismPencil.ts@@ -0,0 +1,5 @@+// The 18-note movement in the colouredPencil hand: a machine is a subject, drawn in any style.+import { mechanismIn } from "./mechanism";+import { colouredPencilHand } from "./mechanismHands";++export const mechanismPencil = mechanismIn("colouredPencil", colouredPencilHand);diff --git a/skills/anidoodle/engine/src/canvas-core/mechanismStipple.ts b/skills/anidoodle/engine/src/canvas-core/mechanismStipple.tsnew file mode 100644index 0000000..7041c7b--- /dev/null+++ b/skills/anidoodle/engine/src/canvas-core/mechanismStipple.ts@@ -0,0 +1,5 @@+// The 18-note movement in the stipple hand: a machine is a subject, drawn in any style.+import { mechanismIn } from "./mechanism";+import { stippleHand } from "./mechanismHands";++export const mechanismStipple = mechanismIn("stipple", stippleHand);diff --git a/skills/anidoodle/engine/src/hosts/demos/mechanism-explorer.html b/skills/anidoodle/engine/src/hosts/demos/mechanism-explorer.htmlnew file mode 100644index 0000000..b38d2dd--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/demos/mechanism-explorer.html@@ -0,0 +1,43 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>How a music box reads its tune</title>+<meta name="description" content="An anidoodle interactive demo: an 18-note music box movement that plays, and comes apart when you hover it.">+<style>+ :root { --paper: #efe8dc; --ink: #2b2a33; --soft: #6c6573; }+ * { box-sizing: border-box; }+ html, body { margin: 0; background: var(--paper); color: var(--ink); font: 17px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }+ main { max-width: 1100px; margin: 0 auto; padding: 40px 24px 60px; display: grid; grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.2fr); gap: 36px; align-items: center; }+ h1 { font-size: clamp(34px, 4.6vw, 56px); line-height: 1.05; letter-spacing: -0.02em; margin: 0 0 16px; font-weight: 650; }+ p { color: var(--soft); max-width: 36ch; margin: 0 0 14px; }+ ani-doodle { display: block; width: min(100%, 56vw); margin-left: auto; outline-offset: 6px; }+ button { font: 600 16px/1 ui-sans-serif, system-ui, sans-serif; padding: 14px 22px; border-radius: 999px; border: 2px solid var(--ink); background: var(--ink); color: var(--paper); cursor: pointer; margin-top: 8px; }+ button:focus-visible { outline: 3px solid #d0502a; outline-offset: 3px; }+ article { max-width: 760px; margin: 0 auto; padding: 0 24px 120px; color: var(--soft); }+ article h2 { color: var(--ink); font-size: 26px; margin: 40px 0 10px; }+ ani-doodle:focus-visible { outline: 2px solid var(--ink); }+ @media (max-width: 760px) { main { grid-template-columns: 1fr; } ani-doodle { margin: 0 auto; } }+</style>+</head>+<body>+<main>+ <section>+ <h1>The pins are the score.</h1>+ <p>A music box stores its tune as pins on a turning drum. Each pin lifts one tuned steel tooth, and the tooth rings.</p>+ <p>Hover the movement, or Tab to it, and it comes apart. Point at a part to see what it does.</p>+ <button type="button" data-anidoodle="apart">Take it apart</button>+ </section>+ <ani-doodle piece="mechanism-explorer" tabindex="0"></ani-doodle>+</main>+<article>+ <h2>Eighteen teeth, one drum</h2>+ <p>The comb is a single steel plate cut into eighteen teeth, each filed to a pitch. The long bass teeth carry small lead weights underneath, which lower them further than length alone could.</p>+ <p>The drum turns once in about ten seconds. Every pin is a note at a moment: where it sits along the drum picks the tooth, and how far round it sits picks the time.</p>+ <h2>Why it keeps time</h2>+ <p>A spring would let the drum race. The governor spins a small two-blade fan on a worm, and the air it pushes against holds the tempo steady from the first bar to the last.</p>+</article>+<!--anidoodle-->+</body>+</html>diff --git a/skills/anidoodle/engine/src/hosts/page-mechanism.ts b/skills/anidoodle/engine/src/hosts/page-mechanism.tsnew file mode 100644index 0000000..1c8c577--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-mechanism.ts@@ -0,0 +1,4 @@+import { mechanism } from "../canvas-core/mechanism";+import { mountFilm } from "./page";++mountFilm(mechanism);diff --git a/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.ts b/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.tsnew file mode 100644index 0000000..f4abd46--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.ts@@ -0,0 +1,4 @@+import { mechanismBlueprint } from "../canvas-core/mechanismBlueprint";+import { mountFilm } from "./page";++mountFilm(mechanismBlueprint);diff --git a/skills/anidoodle/engine/src/hosts/page-mechanismDraw.ts b/skills/anidoodle/engine/src/hosts/page-mechanismDraw.tsnew file mode 100644index 0000000..3891e08--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-mechanismDraw.ts@@ -0,0 +1,4 @@+import { mechanismDraw } from "../canvas-core/mechanismDraw";+import { mountFilm } from "./page";++mountFilm(mechanismDraw);diff --git a/skills/anidoodle/engine/src/hosts/page-mechanismPencil.ts b/skills/anidoodle/engine/src/hosts/page-mechanismPencil.tsnew file mode 100644index 0000000..1f42662--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-mechanismPencil.ts@@ -0,0 +1,4 @@+import { mechanismPencil } from "../canvas-core/mechanismPencil";+import { mountFilm } from "./page";++mountFilm(mechanismPencil);diff --git a/skills/anidoodle/engine/src/hosts/page-mechanismStipple.ts b/skills/anidoodle/engine/src/hosts/page-mechanismStipple.tsnew file mode 100644index 0000000..1d60455--- /dev/null+++ b/skills/anidoodle/engine/src/hosts/page-mechanismStipple.ts@@ -0,0 +1,4 @@+import { mechanismStipple } from "../canvas-core/mechanismStipple";+import { mountFilm } from "./page";++mountFilm(mechanismStipple);diff --git a/skills/anidoodle/engine/test/mechanism.test.ts b/skills/anidoodle/engine/test/mechanism.test.tsnew file mode 100644index 0000000..5523d22--- /dev/null+++ b/skills/anidoodle/engine/test/mechanism.test.ts@@ -0,0 +1,67 @@+// MECHANISM KIT TESTS. The kit's claims are arithmetic: the camera is the house dimetric at 45/30, the+// light ladder is monotone, the springs are exact closed forms, an exploded view staggers out and folds+// back last-out-first-home, hatching stays inside its shape, and the music box's words come from its pins.+// node tools/test.mjs mechanism+import { Cam, level, springAt, sharesAt, type ExplodePlan, hand, flatHand } from "../src/canvas-core/mechanismKit";+import { Iso } from "../src/canvas-core/isometricKit";+import { hatchSegs } from "../src/canvas-core/mechanismHands";+import { play, PLAN, REV } from "../src/canvas-core/mechanism";++export const name = "mechanism";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;++ // 1. the camera at 45/30 is exactly the house 2:1 dimetric+ const k = 20, c = new Cam(45, 30, k, 300, 200), iso = new Iso(null as unknown as CanvasRenderingContext2D, (k * Math.SQRT2) / 2, 300, 200);+ const pts: [number, number, number][] = [[0, 0, 0], [3, -2, 5], [-4, 7, 1.5]];+ ok(pts.every((q) => { const a = c.p(q), b = iso.p(...q); return near(a[0], b[0], 1e-3) && near(a[1], b[1], 1e-2); }), "Cam(45, 30) projects like Iso.p (Iso rounds cos 30 to 4 places)");+ ok(c.depth(c.V) > c.depth([0, 0, 0]), "depth grows toward the viewer");+ const off = c.dv([2, -1, 3]), a0 = c.p([1, 1, 1]), a1 = c.p([3, 0, 4]);+ ok(near(a1[0] - a0[0], off[0], 1e-9) && near(a1[1] - a0[1], off[1], 1e-9), "dv is the screen offset of a world move");++ // 2. the light ladder: 0 to 4, monotone, whole numbers away from the thresholds+ const xs = Array.from({ length: 201 }, (_, i) => -1 + i / 100), ls = xs.map((x) => level(x));+ ok(ls.every((v, i) => !i || v >= ls[i - 1]), "level never falls as the light score rises");+ ok(near(level(-1), 0) && near(level(1), 4) && near(level(0.1), 1) && near(level(0.3), 2) && near(level(0.5), 3), "level is 0..4 and an integer between thresholds");+ ok(level(0.2) > 1.4 && level(0.2) < 1.6, "level crossfades across a threshold instead of flipping");++ // 3. springs: exact, continuous, and the damping ratio means what it says+ const step = (z: number) => Array.from({ length: 400 }, (_, i) => springAt(8, z, 0, 0, 1, i / 100).x);+ const crit = step(1), under = step(0.89), over = step(1.6);+ ok(crit.every((x) => x <= 1 + 1e-12), "critically damped: never overshoots");+ ok(Math.max(...under) > 1.0005 && Math.max(...under) < 1.05, `z 0.89: one faint overshoot (peak ${Math.max(...under).toFixed(4)})`);+ ok(over.every((x) => x <= 1 + 1e-12) && over[50] < crit[50], "overdamped: slower, no overshoot");+ ok([crit, under, over].every((s) => Math.abs(s[399] - 1) < 2e-3), "every spring arrives");+ for (const z of [0.6, 1, 1.4]) { const t = 0.37, h = 1e-6, v = springAt(8, z, 0.2, -0.5, 1, t).v, num = (springAt(8, z, 0.2, -0.5, 1, t + h).x - springAt(8, z, 0.2, -0.5, 1, t - h).x) / (2 * h); ok(Math.abs(v - num) < 1e-4, `z ${z}: velocity is the derivative of position`); }+ ok(springAt(8, 0.89, 0.3, 2, 1, 0).x === 0.3, "at tau 0 a spring is where it starts");++ // 4. the exploded view+ const P: ExplodePlan = { order: ["a", "b", "c", "d"], stagger: 0.1, w: 8, z: 0.89 };+ const open = [{ t: 1, apart: true }];+ ok(Object.values(sharesAt(P, open, 0.99)).every((v) => v === 0), "nothing moves before the cue");+ const early = sharesAt(P, open, 1.15); ok(early.a > early.b && early.b > 0 && early.c === 0 && early.d === 0, "it opens in order, one stagger apart");+ ok(Object.values(sharesAt(P, open, 5)).every((v) => Math.abs(v - 1) < 1e-3), "and arrives apart");+ const cycle = [{ t: 1, apart: true }, { t: 4, apart: false }], back = sharesAt(P, cycle, 4.12);+ ok(back.d < back.a && back.c < back.a, "it folds back last-out first-home");+ ok(Object.values(sharesAt(P, cycle, 9)).every((v) => Math.abs(v) < 1e-3), "and comes all the way home");+ const rev = [{ t: 1, apart: true }, { t: 1.15, apart: false }], r = sharesAt(P, rev, 1.2);+ ok(r.c === 0 && r.d === 0, "a reversal mid-stagger cancels the moves still pending");+ ok(Object.values(sharesAt(P, rev, 8)).every((v) => Math.abs(v) < 1e-3), "and what had left comes home");+ ok(JSON.stringify(sharesAt(P, cycle, 2.5)) === JSON.stringify(sharesAt(P, [...cycle].reverse(), 2.5)), "cue order in the list does not matter");++ // 5. hatching stays inside its shape and is anchored, not screen-locked+ const sq: [number, number][] = [[0, 0], [40, 0], [40, 30], [0, 30]], segs = hatchSegs(sq, Math.PI / 4, 4);+ ok(segs.length > 10 && segs.every(([a, b]) => [a, b].every(([x, y]) => x >= -1e-6 && x <= 40 + 1e-6 && y >= -1e-6 && y <= 30 + 1e-6)), `hatching: ${segs.length} lines, all inside the square`);+ const moved = hatchSegs(sq.map(([x, y]) => [x + 7, y + 3] as [number, number]), Math.PI / 4, 4, [7, 3]);+ ok(moved.length === segs.length && moved.every(([a], i) => near(a[0], segs[i][0][0] + 7, 1e-6) && near(a[1], segs[i][0][1] + 3, 1e-6)), "anchored hatching travels with its part");++ // 6. the music box: one model for pins, teeth and words+ ok(PLAN.order.length === 8, "eight assemblies");+ const quiet = play(0.0001);+ ok(/^PIN [12] · TOOTH \d+ · [A-G]#?\d \d+ HZ$/.test(quiet.read), `at the start the first chord speaks (its top note): ${quiet.read}`);+ const a4 = play(2 * Math.PI * (16 / 32) + 1e-6).read; ok(a4.includes("A4 440 HZ") || a4.includes("F3"), `at step 16 the readout names that step's pin: ${a4}`);+ const loop = play(2 * Math.PI * 3 + 0.4), first = play(0.4);+ ok(loop.read === first.read && loop.bend.every((v, i) => near(v, first.bend[i], 0.05)), "the drum's story repeats every turn");+ ok(REV > 0 && hand().id === "flat", "the kit's default hand is the plain reference hand");+ void flatHand;+};diff --git a/skills/anidoodle/engine/tools/choreo/mechanism-explorer.mjs b/skills/anidoodle/engine/tools/choreo/mechanism-explorer.mjsnew file mode 100644index 0000000..fde1ed6--- /dev/null+++ b/skills/anidoodle/engine/tools/choreo/mechanism-explorer.mjs@@ -0,0 +1,11 @@+// ~14 s of a visitor: watch it play, hover the movement (it comes apart), point at the drum, the+// comb and the governor (each lights and the readout says what it does), leave (it folds home and plays).+export default async (r) => {+ await r.hold(70);+ const c = await r.box("ani-doodle canvas"), at = (fx, fy) => ({ x: c.x + c.width * fx, y: c.y + c.height * fy });+ await r.glide(at(0.5, 0.55), 26); await r.hold(70);+ await r.glide(at(0.5, 0.22), 22); await r.hold(46);+ await r.glide(at(0.3, 0.47), 22); await r.hold(46);+ await r.glide(at(0.82, 0.3), 22); await r.hold(46);+ await r.glide({ x: c.x - 120, y: c.y + c.height * 0.5 }, 24); await r.hold(80);+};diff --git a/skills/anidoodle/references/craft-bar.md b/skills/anidoodle/references/craft-bar.mdindex 38cecc4..bab6955 100644--- a/skills/anidoodle/references/craft-bar.md+++ b/skills/anidoodle/references/craft-bar.md@@ -6,6 +6,9 @@ The test: would a proud human illustrator ship this, or is it mechanical shape-a|---|---|| A subject built from ellipses and capsules | Hand-placed control points over real anatomy || One style recoloured to look like another | The mark, the edge and the order of marks all change |+| Boxes and arrows standing for an idea | A real machine whose working IS the idea, many small parts, each with a job (`machines.md`) |+| A line that stops in the air; a texture cut dead mid-surface | Every line ends on something; a row of ribs or pins fades as the surface turns away |+| Parts floating off or sunk into each other | Every joint flush, tangent or seated, every part held; check the joints at 3x || Flat colour fields | Wash, then pattern wet-on-damp, then line; one named light; cast shadows || Every stroke the same weight and speed | Long strokes fast, fiddly ones slow, thick-thin, tapered || Even scatter, one flower stamped 200 times | Hand-placed drifts with bare rests; 4-5 authored views per species |diff --git a/skills/anidoodle/references/workflows/explainer.md b/skills/anidoodle/references/workflows/explainer.mdindex 6c9d664..9b1cfc4 100644--- a/skills/anidoodle/references/workflows/explainer.md+++ b/skills/anidoodle/references/workflows/explainer.md@@ -27,6 +27,8 @@ review when the person wants that step; otherwise build from it.- **Captions are drawn lettering** (`lettering.ts`, `drafting.ts`, a style's own hand), sized forthe smallest shape the piece ships in. Keep them short enough to read twice in their time onscreen.+- **A mechanism beats a diagram.** When the idea has moving parts, build it as a real machine that+ comes apart and reads out its own state, in whichever style the piece uses: `machines.md`.- **A recurring guide** (a mascot, a hand, an object) gives continuity across chapters; build itonce as a character module.- **Charts are drawn to scale** from the ledger's numbers, labelled with the values they reach,diff --git a/skills/anidoodle/references/workflows/interactive.md b/skills/anidoodle/references/workflows/interactive.mdindex e9a6ac5..f5a3041 100644--- a/skills/anidoodle/references/workflows/interactive.md+++ b/skills/anidoodle/references/workflows/interactive.md@@ -10,6 +10,7 @@ Three worked demos. Each is one self-contained HTML file that opens offline:|---|---|| **Landing mascot** (`mascotHero`) | Bit watches your pointer anywhere on the page, eyes first and head a beat later. Hover or Tab to a button and he turns, presents it with his near arm, raises his brows and brightens his bulb. Press: a crouch. Click "Get started": he jumps and cheers, with pencil twinkles. "Take the tour" gets a wave, and poking him makes him giggle. || **Scroll-drawn hero** (`scrollHero`) | The storybook plate draws itself as you scroll: construction ovals, a head-first pencil sketch, washes spreading from where the brush lands, then the final line, with a pencil or brush at the nib throughout. Scroll back and it un-draws. The last frame is the plate itself, pixel for pixel. |+| **Machine explorer** (`mechanismExplorer`) | A music box movement plays its tune. Hover, focus or press "Take it apart" and it comes apart outside-in, each assembly on its own bouncy spring; point at a part and it lights, and the readout says what it does. Built on `machines.md`. || **Form mascot** (`formMascot`) | He reads your caret, nodding at each keystroke, and shuts his eyes with hands up for the password. Press "Show" and he is caught peeking. A bad submit gets a worried head-shake. "Busy" whirs his key, and success is the cheer. |All three use the storybook plate's hand (pencil + watercolour). Bit is drawn by the plate's own@@ -34,7 +35,7 @@ proves it for every emitted page.| Can a drawn frame change later? | No. An event is stamped after every tick already drawn: `max(lastDrawn + 1, clock)`. || Initial configuration? | It is in the log at tick 0, before anything is drawn: target rectangles, scroll, reduced motion, state and device scale. || Resize, DPR? | Log coordinates are in the piece's logical space, so a resize logs new `rect`s and a `view` (the device scale), and changes no state. The host re-bakes at the new scale in the background and swaps on a frame boundary. |-| Interrupted motion? | Springs are critically damped and closed form. A target is a pure function of the discrete state, which only changes at events. Position and velocity carry across an interruption into a new exact segment. |+| Interrupted motion? | Springs are closed form, critically damped by default; `zeta: 0.8` to `0.9` lands with one faint overshoot, the weight of a real part. A target is a pure function of the discrete state, which only changes at events. Position and velocity carry across an interruption into a new exact segment. || One-shot reactions? | Fixed-length clips restarted by each trigger (`clip(s, "click:start", 72)`), with randomness seeded from the log (`reactionSeed`). || Keyboard? | Keyboard focus counts as hover (`attention` is the more recent of the two), and Enter or Space is a click. Every hover reaction has a focus equivalent. || Touch? | A tap logs its position. A lifted finger logs `exit` and `leave`, so nothing stays hovered. |diff --git a/skills/anidoodle/references/workflows/machines.md b/skills/anidoodle/references/workflows/machines.mdnew file mode 100644index 0000000..26db3d1--- /dev/null+++ b/skills/anidoodle/references/workflows/machines.md@@ -0,0 +1,92 @@+# Machines: explain an idea by building it, in any style++A machine is a subject, not a look. The kit (`engine/src/canvas-core/mechanismKit.ts`) builds real+parts in 3D, sorts them, takes them apart and folds them back; a **hand** marks them in a style's+own medium. The same music box draws as cyanotype, coloured pencil, stipple or flat iso planes.+Worked example: `mechanism.ts` (the 18-note movement), `mechanismHands.ts`, `mechanismExplorer.ts`.++## 1. Turn the idea into a machine++1. **State the truth.** Ledger the concept's real quantities: counts, sizes, rates, limits (`explainer.md`).+2. **Find its verbs** (fills, waits, matches, rejects, decays) and **its nouns with quantities**.+3. **Find a physical mechanism that performs those verbs on those nouns**, one a general reader can+ name: a lock for "every condition must match", drawers sized by bytes, a sluice for a queue.+4. **Say it in one sentence:** "X moves, and its motion means Y." If you cannot, the mapping is wrong.+5. **Give every part a meaning**, and mark where the metaphor stops being literal.+6. **Pick the one part to watch.** It alone gets the accent (`accent: true` on its material).+7. **Add an instrument that reads the quantity** (a dial, a ruler, a counter, a readout corner).+8. **Choose the view** so the mechanism faces the viewer: `Cam.fit(A, E, points, box)`, A 35 to 60.++Two failures, one fix: too abstract (floating slabs, labelled boxes) or too flat (one big plate+with a few lines). Fix both with a recognisable machine of many small, purposeful parts.++## 2. Parts list before geometry++Write the parts by group: base (plate, feet, screws, label, ruler), structure (posts, bridges,+rails, stops), mechanism, controls (crank, knob), and the subject. Every part rests on another+and has a job. A figure is 40 to 80 parts; a hero 80 to 150; past that, propose a smaller version+that keeps the core. Detail comes from structure (a boss under a shaft, holes in a bedplate, a+stop lever), never from texture noise. A bare face or an empty corner is unfinished, not calm.++## 3. One model drives everything++The film's moving parts, the readout and any caption all read one pure model of `(frame)` or of+the input state. In the music box, `play(rot)` places the pins, bends the teeth and names the pin,+the tooth and the pitch in the readout; nothing is typed twice. Read words from where parts ARE+(the readout says "TAKING APART" while any spring is moving), and build counts from the list that+draws them ("8 ASSEMBLIES APART" is `PLAN.order.length`).++## 4. Build with the kit++| Need | Use |+|---|---|+| Camera, depth, a world offset on screen | `Cam`, `Cam.fit`, `c.depth`, `c.dv` |+| Slabs, plates, boxes with rounded plans, seams, bevels | `prism`, `box`, `rrect`, `circle` |+| Drums, posts, knobs, domes: any surface of revolution | `turned` with `cyl`, `cone`, `sphere`; bands are exact, never staircased |+| A lever, a vane, a bracket in any plane | `slab` with `leverRing` or any convex outline |+| Pipes, wires, cables along a route | `tubeAlong` (filleted bends, end caps) |+| Screws, pins, ticks, ribs that fade as they turn away | `screw`, `facingAt` + `smooth` for alpha |+| Many parts in the right order | `paintAll(items)`; each item has `at`, `bias`, `ride` (its assembly) |+| An exploded view | `ExplodePlan` + `sharesAt(plan, cues, t)`: staggered out, last-out first-home, reversals cancel pending moves |+| A frame in a card with four corners (figure, title, hint, live readout) | `card` |++Rules that keep it clean: split a part that wraps another (back half, inner, front half); every+part is held by something; explode real assemblies along their true direction, the outside ones+first; draw a chain line along each path of travel; fit the figure to 55 to 65 percent of the card.++## 5. Draw it in a style: the hand++The kit never chooses a colour. It calls the current hand with meaning: a region and its tone `q`+(0 darkest side, 4 top), a line and its role (`out`, `lit`, `in`, `crease`, `seam`, `hair`,+`light`, `chain`), a dot, the card's sheet, rule and lettering. `setHand(h)` before painting,+`setHand(flatHand())` after. Shipped hands: `isometric` (fast, the default), `blueprint`, `colouredPencil`,+`stipple`. To add one, read the style's recipe in `references/styles/<id>.md` and answer five+questions in code:++1. **Is there light?** Blueprint has none (tone is section lining, only on the part to watch);+ stipple's light is dot density; pencil's is pressure and stacked passes.+2. **What is an edge?** A ruled line, a broken pencil contour heavier on the shade side, a denser+ row of dots, or nothing at all (iso planes meet tone to tone).+3. **How is the accent made?** A colour, section lining, or density.+4. **What is the ground?** Draw it once into a cached layer; `knock` paints it back over a part.+5. **Are the marks anchored?** Anchor hatching and dots to `offset()`, never to the screen, and+ seed them from the part, so a still part never boils and a moving one carries its marks.++## 6. Films and interactive pieces++Two films, not one: the making (`kind: "drawing"`, each part inked then toned in assembly order+with `setReveal(ink, tone, paper)`, then the words) and the run (`kind: "explainer"`: play close on+the part to watch, explode, tour, home). One film holding both fails the dead-air gate, because a+build's slow strokes are measured against an explainer's floor. While apart, let each assembly+breathe a little along its own path, out of step with the others, so the tour never freezes. An interactive piece (`interactive.md`): one+spring per assembly with `zeta` 0.8 to 0.9 so parts land with weight, outer ones faster; a fixed+camera so the card and the bench bake once; the part nearest the pointer lights and the readout+says what it does; reduced motion holds the drum still.++## 7. Check it++Render at `--scale 2` or 3 and crop every joint (flange, bridge, crank, wire end, tooth tips); the+fault list, in order: a line that stops in the air, a part sunk into or floating off another, a+nearer part drawn behind, a texture cut at full strength mid-surface, a doubled edge. Then+`node tools/test.mjs mechanism` and, for a page, `emit-interactive.mjs` and `replay.mjs` (22 checks,+including 6 ms a frame at DPR 2). Measured, not assumed: say which of these you ran.