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
anidoodle v1 work: 31 styles with drawing films, music engine, interactive web, style-from-reference, photo recreation, lessons, characters
Alex Greenshpun2450b1f64f4c
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.jsonnew file mode 100644index 0000000..75dce4f--- /dev/null+++ b/.agents/plugins/marketplace.json@@ -0,0 +1,20 @@+{+ "name": "alexgreensh-anidoodle",+ "interface": {+ "displayName": "anidoodle by alexgreensh"+ },+ "plugins": [+ {+ "name": "anidoodle",+ "source": {+ "source": "local",+ "path": "./plugins/anidoodle"+ },+ "policy": {+ "installation": "AVAILABLE",+ "authentication": "ON_INSTALL"+ },+ "category": "Design"+ }+ ]+}diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 0000000..e6454f5--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,28 @@+{+ "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",+ "name": "alexgreensh-anidoodle",+ "owner": {+ "name": "Alex Greenshpun",+ "email": "[email protected]"+ },+ "metadata": {+ "description": "Hand-drawn art, written as code"+ },+ "plugins": [+ {+ "name": "anidoodle",+ "source": "./",+ "description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",+ "version": "0.4.0",+ "author": {+ "name": "Alex Greenshpun",+ "url": "https://linkedin.com/in/alexgreensh"+ },+ "homepage": "https://github.com/alexgreensh/anidoodle",+ "repository": "https://github.com/alexgreensh/anidoodle",+ "license": "Apache-2.0",+ "keywords": ["illustration", "animation", "film", "drawing", "art", "music", "explainer"],+ "category": "design"+ }+ ]+}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonnew file mode 100644index 0000000..540069a--- /dev/null+++ b/.claude-plugin/plugin.json@@ -0,0 +1,13 @@+{+ "name": "anidoodle",+ "description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",+ "author": {+ "name": "Alex Greenshpun",+ "url": "https://linkedin.com/in/alexgreensh"+ },+ "homepage": "https://github.com/alexgreensh/anidoodle",+ "repository": "https://github.com/alexgreensh/anidoodle",+ "version": "0.4.0",+ "license": "Apache-2.0",+ "keywords": ["illustration", "animation", "film", "drawing", "art", "music", "explainer", "generative", "deterministic"]+}diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonnew file mode 100644index 0000000..57af672--- /dev/null+++ b/.codex-plugin/plugin.json@@ -0,0 +1,30 @@+{+ "name": "anidoodle",+ "version": "0.4.0",+ "description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",+ "skills": "./skills/",+ "interface": {+ "displayName": "anidoodle",+ "shortDescription": "Hand-drawn art, written as code.",+ "longDescription": "Illustrations, drawing timelapses, films of any length, explainers, infographics and interactive web animations in 31 hand-made styles, with original scores composed and synthesized in code. Match a style from your image, recreate a photo in any style, keep a character consistent, or learn how a drawing is built. Every render is deterministic, with no generated assets.",+ "developerName": "Alex Greenshpun",+ "category": "Design",+ "capabilities": [+ "31 drawing styles",+ "Drawing timelapses",+ "Scored films of any length",+ "Style from a reference image",+ "Interactive web animations",+ "Drawing lessons"+ ],+ "websiteURL": "https://github.com/alexgreensh/anidoodle",+ "defaultPrompt": [+ "Show me the anidoodle styles and help me pick one for my landing page hero.",+ "Draw a colored-pencil illustration of a fox in the snow, and a video of it being drawn.",+ "Make a 60-second vertical explainer about how bees find flowers, with a score.",+ "Recreate this photo as a Japanese woodblock print.",+ "Teach me how to draw a cat sitting, step by step."+ ],+ "brandColor": "#C2410C"+ }+}diff --git a/.gitignore b/.gitignoreindex 6ef6db6..fea87f7 100644--- a/.gitignore+++ b/.gitignore@@ -11,3 +11,14 @@ _readme-preview.html_*.png.style-gallery-brief.md.banner-brief.md++# PRIVATE, never ship: the owner's personal recreations and studies of others' artwork+# (Louis keepsakes, the orchard frame study, the Clawd lesson). Kept locally only.+engine/src/canvas-core/cat*.ts+engine/src/hosts/page-cat*.ts+engine/src/canvas-core/folkTaleStudy*.ts+engine/src/hosts/page-folkTaleStudy.ts+engine/src/canvas-core/lessonClawd*.ts+engine/src/hosts/page-lessonClawd*.ts+# agent worktrees+.claude/diff --git a/README.es-ES.md b/README.es-ES.mdindex 8ad07be..37e6929 100644--- a/README.es-ES.md+++ b/README.es-ES.md@@ -7,7 +7,7 @@<p align="center"><strong>Arte dibujado a mano, escrito en código.</strong></p><p align="center">- Ilustraciones, animaciones y cortometrajes en nueve estilos dibujados a mano.<br>+ Ilustraciones, timelapses de dibujo, películas, vídeos explicativos y arte web interactivo en 31 estilos.<br>Cada trazo es una función y cada nota es aritmética, así que la misma fuente<br>redibuja la misma imagen en cualquier máquina, a cualquier tamaño, para siempre.</p>@@ -22,20 +22,20 @@<p align="center"><a href="README.md">English</a> · <a href="README.ja-JP.md">日本語</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ko-KR.md">한국어</a> · <a href="README.fr-FR.md">Français</a> · <b>Español</b></p><p align="center">- <a href="#nueve-estilos-entre-los-que-elegir">Estilos</a> ·+ <a href="#31-estilos-entre-los-que-elegir">Estilos</a> ·<a href="#qué-puedes-crear">Qué puedes crear</a> ·<a href="#qué-trae-dentro">Qué trae dentro</a> ·<a href="#primero-dibuja-luego-se-mueve">Movimiento</a> ·<a href="#empieza-aquí">Empieza aquí</a></p>-## Nueve estilos entre los que elegir+## 31 estilos entre los que elegir<p align="center">- <img src="assets/styles.jpg" width="100%" alt="Nueve ilustraciones, cada una en su propio estilo: un ranúnculo en lápiz y acuarela, una carpa koi de cómic en rotulador, un reloj de bolsillo en bolígrafo, un globo aerostático en ceras, un chochín en tinta y aguada, las fases de la luna en tiza, un zorro en papel recortado, un faro en risografía, y una luna grabada en una sola línea">+ <img src="assets/styles.jpg" width="100%" alt="31 ilustraciones, cada una con su estilo, desde lápiz y acuarela, cómic con rotulador y risografía hasta pixel art, bloques de juguete, xilografía, sumi-e, esgrafiado, bordado, óleo y libros de cuentos populares"></p>-Cada estilo es su propia forma de dejar una marca: el afilado de una plumilla, el sangrado de una aguada, el rozado de la tiza sobre la pizarra, el borde rasgado del papel recortado, la trama de un tambor de risografía, una sola línea grabada que se enrosca hasta convertirse en luna. El motivo cambia de forma según la mano que lo dibuje, igual que le pasaría con nueve ilustradores distintos. Elige uno para tu marca y cada imagen que venga después llegará de la misma mano. Cada lámina de arriba, y la propia hoja de contactos, está dibujada por código en este repositorio.+Cada estilo es su propia forma de dejar una marca: el afilado de una plumilla, el sangrado de una aguada, el rozado de la tiza sobre la pizarra, el borde rasgado del papel recortado, la trama de un tambor de risografía, una sola línea grabada que se enrosca hasta convertirse en luna. El motivo cambia de forma según la mano que lo dibuje, igual que le pasaría con treinta y un ilustradores distintos. Cada estilo incluye además una película en la que su imagen se dibuja trazo a trazo, siguiendo el orden de trabajo de un artista de ese medio. Elige uno para tu marca y cada imagen que venga después llegará de la misma mano. Cada lámina de arriba, y la propia hoja de contactos, está dibujada por código en este repositorio.## Qué puedes crear@@ -46,7 +46,11 @@ Cada estilo es su propia forma de dejar una marca: el afilado de una plumilla, e| **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. |-| **Historias** | Storyboards y animatics que crecen hasta convertirse en un cortometraje terminado con banda sonora original. |+| **Historias** | Storyboards y animatics que crecen hasta convertirse en una película terminada de cualquier duración, con banda sonora original. |+| **Tu propia imagen** | Trae un dibujo para aplicar su estilo a otro motivo, o una foto para recrearla en cualquiera de las 31 formas de dibujar, con cada trazo hecho en código. |+| **Páginas web** | Ilustraciones interactivas que siguen el cursor, reaccionan a clics y formularios, o se dibujan al desplazarte por la página. |+| **Aprendizaje** | Lecciones de dibujo con láminas paso a paso y timelapses que enseñan cómo se construye una imagen, qué observar y qué errores evitar. |+| **Personajes** | Un personaje creado una sola vez que se mantiene idéntico entre planos, poses y estilos. |Pídelo con tus propias palabras, *«un faro en risografía para nuestra página de empleo, 1600×900»* o *«un explicativo en tiza de cómo se comparan nuestros planes de precios»*, y anidoodle lo dirige al flujo de trabajo y la receta de estilo adecuados, preguntando solo por lo que la petición deje abierto.@@ -56,8 +60,8 @@ El motor es la mitad fácil. El oficio es la parte que anidoodle carga por ti: s- **Historia** le da un sentido a cada pieza. Una idea y un motivo central para una imagen fija; una transformación, una recompensa y un elemento recurrente para una película. → [`storytelling.md`](references/storytelling.md)- **Realismo** viene de nombrarlo todo. La anatomía, el punto de vista y la referencia que abriste, para que una mariposa se lea como una criatura con cuerpo y venas. → [`realism-and-craft.md`](references/realism-and-craft.md)-- **Estilo** vive en el trazo. Nueve recetas completas, una guía para elegir una según el encargo, y los pasos para inventar la tuya propia. → [`styles.md`](references/styles.md)-- **Música** sigue una receta. Tono mayor, punteado, una frase que pregunta y resuelve en la tónica, cálida y segura. → [`music-recipe.md`](references/music-recipe.md)+- **Estilo** vive en el trazo. Treinta y una recetas completas, una guía para elegir una según el encargo, y los pasos para inventar la tuya propia. → [`styles.md`](references/styles.md)+- **Música** se compone en notas y se sintetiza con código: un piano modelado y una docena de instrumentos, todas las tonalidades mayores y menores, un ánimo para cada sección y un tema que se adapta a cualquier duración. → [`music/README.md`](references/music/README.md)- **Determinismo** es la garantía. Funciones puras y un aleatorio con semilla, para que cualquiera con la fuente reconstruya exactamente la misma pieza. → [`determinism-and-contract.md`](references/determinism-and-contract.md)- **Método** te mantiene rápido. Demuestra el look en una sola imagen fija, construye de un tirón, y gasta las aprobaciones donde equivocarse sale caro. → [`working-method.md`](references/working-method.md)@@ -88,16 +92,27 @@ Un modelo de imágenes gasta tokens y cómputo en cada fotograma de cada render,## Empieza aquí-anidoodle es una skill de agente: una carpeta con un `SKILL.md` en la raíz. Para Claude Code, clónala en tu carpeta de skills:+**Claude Code:**```bash-git clone https://github.com/alexgreensh/anidoodle ~/.claude/skills/anidoodle+/plugin marketplace add alexgreensh/anidoodle+/plugin install anidoodle@alexgreensh-anidoodle```+**Codex:**++```bash+codex plugin marketplace add alexgreensh/anidoodle+```++Después, en la interfaz de Codex, abre `/plugins` e instala anidoodle.++**Cualquier otro agente:** anidoodle es una carpeta de skill estándar (`skills/anidoodle/SKILL.md`), así que puedes copiarla a cualquier entorno que lea skills.+Luego pide lo que quieras: *«dibuja una pera en lápiz y acuarela para nuestra página de recetas»*. Para manejar el motor tú mismo:```bash-node ~/.claude/skills/anidoodle/engine/tools/scaffold.mjs ~/art --still hero --film intro+node <anidoodle>/engine/tools/scaffold.mjs ~/art --still hero --film intro --format 9x16 --duration 60cd ~/art && npm install && npx playwright-core install chromiumnode tools/still.mjs hero --out out/hero.png --scale 2 # a finished illustration, print size@@ -114,7 +129,7 @@ Cuatro backends comparten un mismo núcleo de arte, y el núcleo vive felizmente## La película de ejemplo-`example/` contiene **Mechanical Lepidoptera**: 1.410 fotogramas, 47 segundos, una mariposa de relojería que se dibuja a sí misma, cobra vida en acuarela y deja su plano entre la hierba. Es el motor entero en una sola pieza: puntos de control colocados a mano sobre anatomía real, una clave de caché que nombra cada entrada de la que depende un píxel, una banda sonora construida a partir de la receta, y un movimiento continuo desde el boceto hasta la vida. Las nueve láminas de estilo están junto al motor en `engine/src/canvas-core/`, cada una con su receta escrita en la parte de arriba. Abre cualquiera de ellas, cambia un número, y mira qué se mueve.+`example/` contiene **Mechanical Lepidoptera**: 1.410 fotogramas, 47 segundos, una mariposa de relojería que se dibuja a sí misma, cobra vida en acuarela y deja su plano entre la hierba. Es el motor entero en una sola pieza: puntos de control colocados a mano sobre anatomía real, una clave de caché que nombra cada entrada de la que depende un píxel, una banda sonora construida a partir de la receta, y un movimiento continuo desde el boceto hasta la vida. Las láminas de estilo están junto al motor en `engine/src/canvas-core/`, cada una con su receta escrita en la parte de arriba. Abre cualquiera de ellas, cambia un número, y mira qué se mueve.## Honesto por diseñodiff --git a/README.fr-FR.md b/README.fr-FR.mdindex 7e7e326..b6ff7ca 100644--- a/README.fr-FR.md+++ b/README.fr-FR.md@@ -7,7 +7,7 @@<p align="center"><strong>De l'art dessiné à la main, écrit en code.</strong></p><p align="center">- Illustrations, animations et courts métrages dans neuf styles dessinés à la main.<br>+ Illustrations, accélérés de dessin, films, vidéos explicatives et art web interactif dans 31 styles.<br>Chaque trait est une fonction et chaque note un calcul, si bien que la même source<br>redessine la même image sur toute machine, à toute taille, pour de bon.</p>@@ -22,20 +22,20 @@<p align="center"><a href="README.md">English</a> · <a href="README.ja-JP.md">日本語</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ko-KR.md">한국어</a> · <b>Français</b> · <a href="README.es-ES.md">Español</a></p><p align="center">- <a href="#neuf-styles-au-choix">Styles</a> ·+ <a href="#31-styles-au-choix">Styles</a> ·<a href="#ce-que-vous-pouvez-créer">Ce que vous pouvez créer</a> ·<a href="#ce-quil-embarque">Ce qu'il embarque</a> ·<a href="#ça-dessine-puis-ça-bouge">Mouvement</a> ·<a href="#démarrer">Démarrer</a></p>-## Neuf styles au choix+## 31 styles au choix<p align="center">- <img src="assets/styles.jpg" width="100%" alt="Neuf illustrations, chacune dans son propre style : renoncule au crayon et à l'aquarelle, carpe koï façon bande dessinée au marqueur, montre à gousset au stylo bille, montgolfière au crayon de couleur, roitelet à l'encre et au lavis, phases de lune à la craie, renard en papier découpé, phare en risographie, et une lune gravée d'un seul trait">+ <img src="assets/styles.jpg" width="100%" alt="31 illustrations, chacune dans son style, du crayon et de l’aquarelle, de la BD au marqueur et de la risographie au pixel art, aux briques de jeu, à la gravure sur bois, au sumi-e, à la carte à gratter, à la broderie, à la peinture à l’huile et au livre de contes populaires"></p>-Chaque style est une façon bien à lui de poser une trace : l'effilement d'une plume, le débordement d'un lavis, le grain de la craie sur l'ardoise, le bord déchiré du papier découpé, la trame d'un tambour de risographie, un seul trait gravé qui s'enroule pour devenir une lune. Le sujet change de forme selon la main qui le dessine, comme il le ferait pour neuf illustrateurs différents. Choisissez-en un pour votre marque, et toutes les images suivantes arriveront de la même main. Chaque planche ci-dessus, et la planche-contact elle-même, est dessinée par du code dans ce dépôt.+Chaque style est une façon bien à lui de poser une trace : l'effilement d'une plume, le débordement d'un lavis, le grain de la craie sur l'ardoise, le bord déchiré du papier découpé, la trame d'un tambour de risographie, un seul trait gravé qui s'enroule pour devenir une lune. Le sujet change de forme selon la main qui le dessine, comme il le ferait pour trente et un illustrateurs différents. Chaque style s’accompagne aussi d’un film où son image se dessine trait après trait, dans l’ordre de travail d’un artiste qui emploie ce médium. Choisissez-en un pour votre marque, et toutes les images suivantes arriveront de la même main. Chaque planche ci-dessus, et la planche-contact elle-même, est dessinée par du code dans ce dépôt.## Ce que vous pouvez créer@@ -46,7 +46,11 @@ Chaque style est une façon bien à lui de poser une trace : l'effilement d'une| **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. |-| **Récits** | Des storyboards et des animatics qui grandissent jusqu'à devenir un court métrage fini, avec une bande originale. |+| **Récits** | Des storyboards et des animatics qui grandissent jusqu’à devenir un film achevé, de n’importe quelle durée, avec une bande originale. |+| **Votre propre image** | Apportez un dessin et reprenez son style pour un nouveau sujet, ou apportez une photo et recréez-la dans l’une des 31 manières, chaque trait tracé par le code. |+| **Pages web** | Des illustrations interactives qui suivent le curseur, réagissent aux clics et aux formulaires, ou se dessinent au fil du défilement. |+| **Apprentissage** | Des leçons de dessin en étapes et en accéléré, pour comprendre la construction d’une image, les points à observer et les erreurs courantes. |+| **Personnages** | Un personnage créé une fois, qui reste identique d’un plan, d’une pose et d’un style à l’autre. |Demandez avec vos propres mots, *« un phare en risographie pour notre page carrières, 1600×900 »* ou *« un schéma à la craie qui explique comment s'articulent nos formules tarifaires »*, et anidoodle l'oriente vers le bon flux de travail et la bonne recette de style, en ne vous questionnant que sur ce que la demande laisse ouvert.@@ -56,8 +60,8 @@ Le moteur, c'est la partie facile. Le métier, c'est ce qu'anidoodle porte pour- **Le récit** donne un sens à chaque pièce. Une idée et un sujet focal pour une image fixe ; une transformation, une résolution et un motif qui revient pour un film. → [`storytelling.md`](references/storytelling.md)- **Le réalisme** vient du fait de le nommer. L'anatomie, l'angle de vue et la référence que vous avez ouverte, pour qu'un papillon se lise comme une créature avec un corps et des nervures. → [`realism-and-craft.md`](references/realism-and-craft.md)-- **Le style** habite la trace. Neuf recettes complètes, un guide pour en choisir une par projet, et la marche à suivre pour inventer la vôtre. → [`styles.md`](references/styles.md)-- **La musique** suit une recette. Tonalité majeure, cordes pincées, une phrase qui pose une question et se résout sur la tonique, chaleureuse et sûre d'elle. → [`music-recipe.md`](references/music-recipe.md)+- **Le style** habite la trace. Trente et une recettes complètes, un guide pour en choisir une par projet, et la marche à suivre pour inventer la vôtre. → [`styles.md`](references/styles.md)+- **La musique** se compose en notes et se synthétise par code : un piano modélisé et une douzaine d’instruments, toutes les tonalités majeures et mineures, une humeur par section et un thème adapté à toute durée. → [`music/README.md`](references/music/README.md)- **Le déterminisme** est la garantie. Des fonctions pures et un aléatoire à graine fixe, pour que quiconque a le code source reconstruise exactement la même pièce. → [`determinism-and-contract.md`](references/determinism-and-contract.md)- **La méthode** vous fait gagner du temps. Prouvez le rendu sur une seule image fixe, construisez d'une traite, et réservez les validations aux endroits où se tromper coûte cher. → [`working-method.md`](references/working-method.md)@@ -88,16 +92,27 @@ Un modèle d'image dépense des tokens et du calcul à chaque image de chaque re## Démarrer-anidoodle est une compétence d'agent (agent skill) : un seul dossier avec un `SKILL.md` à la racine. Pour Claude Code, clonez-la dans votre dossier de compétences :+**Claude Code:**```bash-git clone https://github.com/alexgreensh/anidoodle ~/.claude/skills/anidoodle+/plugin marketplace add alexgreensh/anidoodle+/plugin install anidoodle@alexgreensh-anidoodle```+**Codex:**++```bash+codex plugin marketplace add alexgreensh/anidoodle+```++Puis, dans l’interface Codex, ouvrez `/plugins` et installez anidoodle.++**Tout autre agent :** anidoodle est un dossier de compétence standard (`skills/anidoodle/SKILL.md`) ; vous pouvez le copier dans tout environnement capable de lire les compétences.+Ensuite, demandez ce que vous voulez : *« dessine une poire au crayon et à l'aquarelle pour notre page de recettes »*. Pour piloter le moteur vous-même :```bash-node ~/.claude/skills/anidoodle/engine/tools/scaffold.mjs ~/art --still hero --film intro+node <anidoodle>/engine/tools/scaffold.mjs ~/art --still hero --film intro --format 9x16 --duration 60cd ~/art && npm install && npx playwright-core install chromiumnode tools/still.mjs hero --out out/hero.png --scale 2 # a finished illustration, print size@@ -114,7 +129,7 @@ Quatre moteurs de rendu partagent un même noyau artistique, et ce noyau ignore## Le film d'exemple-`example/` contient **Mechanical Lepidoptera** : 1 410 images, 47 secondes, un papillon mécanique qui se dessine lui-même au trait technique, prend vie à l'aquarelle, et laisse son plan dans l'herbe. C'est tout le moteur réuni dans une seule pièce : des points de contrôle placés à la main sur une anatomie réelle, une clé de cache qui nomme chaque entrée dont dépend un pixel, une bande-son construite à partir de la recette, et un mouvement ininterrompu du plan à la vie. Les neuf planches de style se trouvent à côté du moteur dans `engine/src/canvas-core/`, chacune avec sa recette écrite en haut. Ouvrez-en une, changez un chiffre, et regardez ce qui bouge.+`example/` contient **Mechanical Lepidoptera** : 1 410 images, 47 secondes, un papillon mécanique qui se dessine lui-même au trait technique, prend vie à l'aquarelle, et laisse son plan dans l'herbe. C'est tout le moteur réuni dans une seule pièce : des points de contrôle placés à la main sur une anatomie réelle, une clé de cache qui nomme chaque entrée dont dépend un pixel, une bande-son construite à partir de la recette, et un mouvement ininterrompu du plan à la vie. Les planches de style se trouvent à côté du moteur dans `engine/src/canvas-core/`, chacune avec sa recette écrite en haut. Ouvrez-en une, changez un chiffre, et regardez ce qui bouge.## Honnête par conceptiondiff --git a/README.ja-JP.md b/README.ja-JP.mdindex 0d120c8..11f5feb 100644--- a/README.ja-JP.md+++ b/README.ja-JP.md@@ -7,7 +7,7 @@<p align="center"><strong>手描きのアートを、コードで書く。</strong></p><p align="center">- イラスト、アニメーション、そして短編映画を、9つの手描きスタイルで。<br>+ イラスト、作画タイムラプス、映画、解説動画、インタラクティブなウェブアートを、31のスタイルで。<br>一筆一筆が関数で、一音一音が計算式だから、同じソースコードは<br>どのマシンでも、どんなサイズでも、いつまでも同じ絵を描き直す。</p>@@ -22,20 +22,20 @@<p align="center"><a href="README.md">English</a> · <b>日本語</b> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ko-KR.md">한국어</a> · <a href="README.fr-FR.md">Français</a> · <a href="README.es-ES.md">Español</a></p><p align="center">- <a href="#選べる9つのスタイル">スタイル</a> ·+ <a href="#選べる31のスタイル">スタイル</a> ·<a href="#つくれるもの">つくれるもの</a> ·<a href="#搭載しているもの">搭載しているもの</a> ·<a href="#描いてから動きだす">動き</a> ·<a href="#はじめる">はじめる</a></p>-## 選べる9つのスタイル+## 選べる31のスタイル<p align="center">- <img src="assets/styles.jpg" width="100%" alt="9枚のイラスト、それぞれ異なるスタイルで描かれている。鉛筆と水彩のラナンキュラス、マーカーで描いたコミック風の鯉、ボールペンの懐中時計、クレヨンの熱気球、インクと淡彩のミソサザイ、黒板に描いた月の満ち欠け、切り絵のキツネ、リソグラフの灯台、そして一本の線で彫られた月。">+ <img src="assets/styles.jpg" width="100%" alt="それぞれ異なるスタイルで描かれた31枚のイラスト。鉛筆と水彩、マーカーのコミック、リソグラフから、ピクセルアート、おもちゃのブロック、木版画、墨絵、スクラッチボード、刺繍、油彩、民話の絵本まで"></p>-どのスタイルも、線の生み出し方がまったく違う。ペン先のしなり、水彩のにじみ、黒板チョークの擦れ、切り絵の破れた縁、リソグラフのドラムが作る網点、一本の彫り線が渦を巻いて月になる瞬間。同じ題材でも、9人の描き手がいれば9通りの形になるように、スタイルごとに姿を変える。ブランド用にひとつ選べば、その後のすべての絵が同じ手で描かれたように揃う。上の見本も、コンタクトシートそのものも、すべてこのリポジトリのコードで描かれている。+どのスタイルも、線の生み出し方がまったく違う。ペン先のしなり、水彩のにじみ、黒板チョークの擦れ、切り絵の破れた縁、リソグラフのドラムが作る網点、一本の彫り線が渦を巻いて月になる瞬間。同じ題材でも、31人の描き手がそれぞれ描いたように、スタイルごとに姿を変える。各スタイルには、その画材を使う作家の手順どおりに、一筆ずつ絵ができあがる映像も付いている。ブランド用にひとつ選べば、その後のすべての絵が同じ手で描かれたように揃う。上の見本も、コンタクトシートそのものも、すべてこのリポジトリのコードで描かれている。## つくれるもの@@ -46,7 +46,11 @@| **ブランド表現** | 自ら描き上がっていくロゴ、タイトルシークエンス、どの投稿でもブランドを保てるソーシャルカードのテンプレート。 || **SNSやチャット** | 終わりのないループ、GIF、透過背景のアニメーションスタンプを、フィードに合わせたサイズで。 || **資料やドキュメント** | ひとつのプログラムから生まれる、章ごとのイラストのファミリー。シード値を変えるだけで、同じスタイルの姉妹画像が手に入る。 |-| **物語** | 絵コンテやアニマティックから、オリジナルスコア付きの短編映画へと育っていく。 |+| **物語** | 絵コンテやアニマティックから、オリジナルスコア付きの、長さを問わない完成映像へと育っていく。 |+| **手持ちの画像** | 絵を持ち込めば、そのスタイルで別の題材を描ける。写真を持ち込めば、31のどの画風でも、一筆ずつコードで描き直せる。 |+| **ウェブページ** | カーソルを追い、クリックやフォームに反応し、スクロールに合わせて描き上がるインタラクティブなイラスト。 |+| **学習** | 絵の組み立て方を、注目すべき点やよくある間違いとともに教える作画手順シートとタイムラプス。 |+| **キャラクター** | 一度作ったキャラクターを、カットやポーズ、スタイルが変わっても同じ姿に保てる。 |「採用ページ用にリソグラフ風の灯台のイラストがほしい、1600×900で」とか「料金プランの違いを黒板スタイルで説明する図を作って」というように、ふだんの言葉でお願いすればいい。anidoodleがそれを適切なワークフローとスタイルのレシピに振り分けて、足りない情報だけを聞き返してくる。@@ -56,8 +60,8 @@- **物語**が、作品に意味を与える。一枚絵ならひとつのアイデアとひとつの主題。映画ならひとつの変化、ひとつの見せ場、そして繰り返し登場するモチーフがひとつ。→ [`storytelling.md`](references/storytelling.md)- **リアリズム**は、名づけることから生まれる。解剖学的な構造、視点、そして開いた参考資料。それがあってはじめて、蝶は体と翅脈を持つ生き物として見えてくる。→ [`realism-and-craft.md`](references/realism-and-craft.md)-- **スタイル**は、線そのものに宿る。9つの完全なレシピ、案件ごとに選ぶためのガイド、そして自分だけのスタイルを生み出す手順。→ [`styles.md`](references/styles.md)-- **音楽**は、ひとつのレシピに従う。長調、爪弾き、問いを投げかけてから主音に帰って解決するフレーズ、温かくて確かな響き。→ [`music-recipe.md`](references/music-recipe.md)+- **スタイル**は、線そのものに宿る。31の完全なレシピ、案件ごとに選ぶためのガイド、そして自分だけのスタイルを生み出す手順。→ [`styles.md`](references/styles.md)+- **音楽**は、音符を作曲し、コードで合成する。モデル化されたピアノと十数種類の楽器、すべての長調と短調、セクションごとの情感、どんな長さにも合うテーマを備えている。→ [`music/README.md`](references/music/README.md)- **決定性**が、その保証になる。純粋関数とシード付き乱数だから、ソースコードさえあれば誰でもまったく同じ作品を再構築できる。→ [`determinism-and-contract.md`](references/determinism-and-contract.md)- **手法**が、スピードを保ってくれる。まず一枚の絵で見た目を確かめ、そのまま一気に作り上げ、間違えるとコストの高いところにだけ承認をかける。→ [`working-method.md`](references/working-method.md)@@ -88,16 +92,27 @@ https://github.com/user-attachments/assets/019d46d3-536a-4843-9f68-8e8f5f5c3401## はじめる-anidoodleはエージェントスキル。トップに`SKILL.md`を置いた、ひとつのフォルダだけで完結している。Claude Codeなら、スキルフォルダにクローンすればいい:+**Claude Code:**```bash-git clone https://github.com/alexgreensh/anidoodle ~/.claude/skills/anidoodle+/plugin marketplace add alexgreensh/anidoodle+/plugin install anidoodle@alexgreensh-anidoodle```+**Codex:**++```bash+codex plugin marketplace add alexgreensh/anidoodle+```++続いてCodexのTUIで`/plugins`を開き、anidoodleをインストールする。++**その他のエージェント:** anidoodleは標準的なスキルフォルダ(`skills/anidoodle/SKILL.md`)なので、スキルを読み込める環境ならコピーして使える。+あとは欲しいものを言葉で伝えるだけ。たとえば「レシピページ用に、鉛筆と水彩で洋梨を描いて」というように。エンジンを直接動かしたいときは:```bash-node ~/.claude/skills/anidoodle/engine/tools/scaffold.mjs ~/art --still hero --film intro+node <anidoodle>/engine/tools/scaffold.mjs ~/art --still hero --film intro --format 9x16 --duration 60cd ~/art && npm install && npx playwright-core install chromiumnode tools/still.mjs hero --out out/hero.png --scale 2 # a finished illustration, print size@@ -114,7 +129,7 @@ Node 20以降が必要。一枚絵なら上記のブラウザだけで足りる## サンプルのショートフィルム-`example/`には**Mechanical Lepidoptera(機械仕掛けの鱗翅目)**が入っている。1,410フレーム、47秒、自ら製図されていくぜんまい仕掛けの蝶が、水彩の中で命を得て、草の上に自分の設計図を残していく。これはエンジンのすべてが詰まった一作だ。実際の解剖学的構造の上に手で置かれた制御点、1ピクセルが依存するすべての入力に名前をつけるキャッシュキー、レシピから組み立てられたスコア、そして「組み立てられた状態」から「命を得た状態」へと途切れなく移り変わる動き。9枚のスタイルプレートは`engine/src/canvas-core/`にエンジンと並んで置かれていて、それぞれの先頭にレシピが書かれている。どれでも開いて、数字をひとつ変えて、何が動くか見てみてほしい。+`example/`には**Mechanical Lepidoptera(機械仕掛けの鱗翅目)**が入っている。1,410フレーム、47秒、自ら製図されていくぜんまい仕掛けの蝶が、水彩の中で命を得て、草の上に自分の設計図を残していく。これはエンジンのすべてが詰まった一作だ。実際の解剖学的構造の上に手で置かれた制御点、1ピクセルが依存するすべての入力に名前をつけるキャッシュキー、レシピから組み立てられたスコア、そして「組み立てられた状態」から「命を得た状態」へと途切れなく移り変わる動き。スタイルプレートは`engine/src/canvas-core/`にエンジンと並んで置かれていて、それぞれの先頭にレシピが書かれている。どれでも開いて、数字をひとつ変えて、何が動くか見てみてほしい。## 正直に設計されているdiff --git a/README.ko-KR.md b/README.ko-KR.mdindex 4804214..3dab191 100644--- a/README.ko-KR.md+++ b/README.ko-KR.md@@ -7,7 +7,7 @@<p align="center"><strong>코드로 쓰는 손그림.</strong></p><p align="center">- 아홉 가지 손그림 스타일로 그리는 일러스트, 애니메이션, 단편 영화.<br>+ 31가지 스타일로 만드는 일러스트, 그림 타임랩스, 영화, 설명 영상, 인터랙티브 웹 아트.<br>모든 선은 함수이고 모든 음표는 연산이라, 같은 소스가<br>어떤 기기에서도, 어떤 크기로도, 언제까지나 같은 그림을 다시 그려내요.</p>@@ -22,20 +22,20 @@<p align="center"><a href="README.md">English</a> · <a href="README.ja-JP.md">日本語</a> · <a href="README.zh-CN.md">简体中文</a> · <b>한국어</b> · <a href="README.fr-FR.md">Français</a> · <a href="README.es-ES.md">Español</a></p><p align="center">- <a href="#고를-수-있는-아홉-가지-스타일">스타일</a> ·+ <a href="#고를-수-있는-31가지-스타일">스타일</a> ·<a href="#만들-수-있는-것">만들 수 있는 것</a> ·<a href="#담겨-있는-것">담겨 있는 것</a> ·<a href="#먼저-그려지고-그다음-움직여요">움직임</a> ·<a href="#시작하기">시작하기</a></p>-## 고를 수 있는 아홉 가지 스타일+## 고를 수 있는 31가지 스타일<p align="center">- <img src="assets/styles.jpg" width="100%" alt="아홉 개의 일러스트, 저마다 다른 스타일로 그렸어요: 연필과 수채화로 그린 미나리아재비, 마커로 그린 만화풍 잉어, 볼펜으로 그린 회중시계, 크레용으로 그린 열기구, 잉크와 담채로 그린 굴뚝새, 칠판에 그린 달의 위상, 색종이 오림으로 만든 여우, 리소그래프로 찍은 등대, 그리고 한 줄의 선으로 새긴 달">+ <img src="assets/styles.jpg" width="100%" alt="저마다 다른 스타일로 그린 31개 일러스트. 연필과 수채화, 마커 만화, 리소그래프부터 픽셀 아트, 장난감 블록, 목판화, 수묵화, 스크래치보드, 자수, 유화, 민담 그림책까지"></p>-스타일마다 선을 긋는 방식이 달라요: 펜촉이 가늘어지는 모양, 물감이 번지는 자국, 분필이 슬레이트 위에서 스치는 질감, 색종이를 찢어낸 가장자리, 리소그래프 드럼의 망점, 그리고 한 줄의 새김선이 소용돌이치며 달이 되는 과정까지. 같은 소재도 손이 다르면 모양이 달라지는데, 마치 아홉 명의 일러스트레이터가 각자 그린 것처럼요. 브랜드에 맞는 스타일을 하나 고르면, 그 뒤로 나오는 모든 그림이 같은 손끝에서 나온 듯 일관돼요. 위의 모든 플레이트와 콘택트 시트 자체도 이 저장소 안의 코드로 그린 거예요.+스타일마다 선을 긋는 방식이 달라요: 펜촉이 가늘어지는 모양, 물감이 번지는 자국, 분필이 슬레이트 위에서 스치는 질감, 색종이를 찢어낸 가장자리, 리소그래프 드럼의 망점, 그리고 한 줄의 새김선이 소용돌이치며 달이 되는 과정까지. 같은 소재도 손이 다르면 모양이 달라지는데, 마치 31명의 일러스트레이터가 각자 그린 것처럼요. 스타일마다 그 매체를 다루는 화가의 작업 순서대로, 그림이 한 획씩 완성되는 영상도 함께 들어 있어요. 브랜드에 맞는 스타일을 하나 고르면, 그 뒤로 나오는 모든 그림이 같은 손끝에서 나온 듯 일관돼요. 위의 모든 플레이트와 콘택트 시트 자체도 이 저장소 안의 코드로 그린 거예요.## 만들 수 있는 것@@ -46,7 +46,11 @@| **브랜드** | 스스로 그려지는 로고, 타이틀 시퀀스, 게시물마다 브랜드를 지켜주는 소셜 카드 템플릿. || **소셜과 채팅** | 끊임없이 반복되는 루프, GIF, 투명 배경 애니메이션 스티커까지, 피드에 맞는 크기로. || **덱과 문서** | 하나의 프로그램에서 나온 한 세트의 섹션 일러스트. 시드값만 바꾸면 같은 스타일의 자매 이미지가 나와요. |-| **스토리** | 스토리보드와 애니매틱이 오리지널 스코어를 갖춘 완성된 단편 영화로 자라나요. |+| **스토리** | 스토리보드와 애니매틱이 오리지널 스코어를 갖춘, 길이에 제한 없는 완성된 영화로 자라나요. |+| **내 이미지** | 그림을 가져오면 그 스타일로 새로운 소재를 그려요. 사진을 가져오면 31가지 화풍 중 하나로 다시 만들고, 모든 획을 코드로 그려요. |+| **웹페이지** | 커서를 따라 움직이고 클릭과 폼에 반응하며, 페이지를 스크롤하면 스스로 그려지는 인터랙티브 일러스트. |+| **학습** | 그림이 만들어지는 과정을 알려주는 단계별 시트와 타임랩스. 어디를 살펴봐야 하는지, 흔한 실수는 무엇인지도 배워요. |+| **캐릭터** | 한 번 만든 캐릭터를 장면과 포즈, 스타일이 달라져도 똑같이 유지해요. |그냥 평범한 말로 요청하면 돼요. *“채용 페이지에 쓸 리소그래프 등대 이미지, 1600×900 사이즈로”* 또는 *“요금제 단계를 한눈에 보여주는 칠판 스타일 설명 그림”* 같은 식으로요. anidoodle이 알아서 적절한 워크플로와 스타일 레시피로 연결해주고, 요청에서 빠진 부분만 되물어요.@@ -56,8 +60,8 @@- **스토리**는 모든 작품에 의미를 줘요. 스틸컷 하나에는 아이디어 하나와 초점이 되는 소재 하나, 영화에는 하나의 변화와 하나의 결말, 그리고 되돌아오는 상징 하나. → [`storytelling.md`](references/storytelling.md)- **사실감**은 이름을 붙이는 데서 나와요. 해부 구조, 시점, 그리고 펼쳐본 레퍼런스까지 정확히 짚어야, 나비 한 마리도 몸과 날개맥을 가진 생명체로 읽혀요. → [`realism-and-craft.md`](references/realism-and-craft.md)-- **스타일**은 선 하나하나에 깃들어요. 아홉 가지 완전한 레시피, 작업에 맞게 하나를 고르는 가이드, 그리고 나만의 스타일을 만드는 방법까지. → [`styles.md`](references/styles.md)-- **음악**은 정해진 레시피를 따라요. 장조, 발현악기 음색, 질문을 던졌다가 으뜸음으로 돌아와 해결되는 프레이즈까지, 따뜻하고 확신에 찬 소리로. → [`music-recipe.md`](references/music-recipe.md)+- **스타일**은 선 하나하나에 깃들어요. 31가지 완전한 레시피, 작업에 맞게 하나를 고르는 가이드, 그리고 나만의 스타일을 만드는 방법까지. → [`styles.md`](references/styles.md)+- **음악**은 음표로 작곡하고 코드로 합성해요. 모델링한 피아노와 십여 가지 악기, 모든 장조와 단조, 구간별 분위기, 어떤 길이에도 맞는 테마까지 갖췄어요. → [`music/README.md`](references/music/README.md)- **결정론**은 우리의 보증이에요. 순수 함수와 시드값 기반 난수를 쓰니까, 소스만 있으면 누구든 완전히 똑같은 작품을 다시 만들어낼 수 있어요. → [`determinism-and-contract.md`](references/determinism-and-contract.md)- **작업 방식**이 속도를 지켜줘요. 스틸컷 하나로 룩을 먼저 검증하고, 그다음은 막힘없이 쭉 밀고 나가고, 틀렸을 때 비용이 큰 지점에서만 승인을 받는 식으로요. → [`working-method.md`](references/working-method.md)@@ -88,16 +92,27 @@ https://github.com/user-attachments/assets/019d46d3-536a-4843-9f68-8e8f5f5c3401## 시작하기-anidoodle은 에이전트 스킬이에요. 맨 위에 `SKILL.md`가 있는 폴더 하나가 전부예요. Claude Code를 쓴다면 스킬 폴더에 클론하세요:+**Claude Code:**```bash-git clone https://github.com/alexgreensh/anidoodle ~/.claude/skills/anidoodle+/plugin marketplace add alexgreensh/anidoodle+/plugin install anidoodle@alexgreensh-anidoodle```+**Codex:**++```bash+codex plugin marketplace add alexgreensh/anidoodle+```++그다음 Codex TUI에서 `/plugins`를 열어 anidoodle을 설치하세요.++**다른 에이전트:** anidoodle은 표준 스킬 폴더(`skills/anidoodle/SKILL.md`)이므로 스킬을 읽는 환경이라면 어디든 복사해서 쓸 수 있어요.+그다음엔 원하는 걸 말하면 돼요: *“레시피 페이지에 쓸 연필과 수채화 스타일의 배 그림 그려줘”*. 엔진을 직접 다뤄보고 싶다면:```bash-node ~/.claude/skills/anidoodle/engine/tools/scaffold.mjs ~/art --still hero --film intro+node <anidoodle>/engine/tools/scaffold.mjs ~/art --still hero --film intro --format 9x16 --duration 60cd ~/art && npm install && npx playwright-core install chromiumnode tools/still.mjs hero --out out/hero.png --scale 2 # a finished illustration, print size@@ -114,7 +129,7 @@ Node 20 이상이 필요해요. 스틸컷은 위에서 설치한 브라우저만## 예제 영화-`example/` 폴더에는 **Mechanical Lepidoptera**가 들어있어요: 1,410개 프레임, 47초 분량으로, 스스로 설계도를 그리다가 수채화 속에서 살아나고, 풀밭에 자신의 청사진을 남기고 떠나는 태엽 나비 이야기예요. 엔진 전체가 이 한 작품 안에 담겨 있어요. 실제 해부 구조 위에 손으로 찍은 제어점, 픽셀 하나가 무엇에 의존하는지 전부 이름 붙인 캐시 키, 레시피로 만든 스코어, 그리고 설계도에서 생명으로 끊김 없이 이어지는 움직임까지요. 아홉 개의 스타일 플레이트는 `engine/src/canvas-core/` 안에 엔진과 나란히 놓여 있고, 각각 맨 위에 레시피가 적혀 있어요. 아무거나 열어서 숫자 하나만 바꿔보면, 뭐가 움직이는지 바로 보여요.+`example/` 폴더에는 **Mechanical Lepidoptera**가 들어있어요: 1,410개 프레임, 47초 분량으로, 스스로 설계도를 그리다가 수채화 속에서 살아나고, 풀밭에 자신의 청사진을 남기고 떠나는 태엽 나비 이야기예요. 엔진 전체가 이 한 작품 안에 담겨 있어요. 실제 해부 구조 위에 손으로 찍은 제어점, 픽셀 하나가 무엇에 의존하는지 전부 이름 붙인 캐시 키, 레시피로 만든 스코어, 그리고 설계도에서 생명으로 끊김 없이 이어지는 움직임까지요. 스타일 플레이트는 `engine/src/canvas-core/` 안에 엔진과 나란히 놓여 있고, 각각 맨 위에 레시피가 적혀 있어요. 아무거나 열어서 숫자 하나만 바꿔보면, 뭐가 움직이는지 바로 보여요.## 설계부터 정직하게diff --git a/README.md b/README.mdindex 36c8b03..b2c515a 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@<p align="center"><strong>Hand-drawn art, written as code.</strong></p><p align="center">- Illustrations, animations and short films in nine hand-drawn styles.<br>+ Illustrations, drawing timelapses, films, explainers and interactive web art in 31 styles.<br>Every mark is a function and every note is arithmetic, so the same source<br>redraws the same picture on every machine, at every size, for good.</p>@@ -22,20 +22,20 @@<p align="center"><b>English</b> · <a href="README.ja-JP.md">日本語</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.ko-KR.md">한국어</a> · <a href="README.fr-FR.md">Français</a> · <a href="README.es-ES.md">Español</a></p><p align="center">- <a href="#nine-styles-to-choose-from">Styles</a> ·+ <a href="#31-styles-to-choose-from">Styles</a> ·<a href="#what-you-can-make">What you can make</a> ·<a href="#what-it-packs">What it packs</a> ·<a href="#it-draws-then-it-moves">Motion</a> ·<a href="#get-started">Get started</a></p>-## Nine styles to choose from+## 31 styles to choose from<p align="center">- <img src="assets/styles.jpg" width="100%" alt="Nine illustrations, each in its own style: pencil and watercolour ranunculus, marker comic koi, ballpoint pocket watch, crayon hot-air balloon, ink and line-wash wren, chalkboard moon phases, cut-paper fox, risograph lighthouse, and a single-line engraved moon">+ <img src="assets/styles.jpg" width="100%" alt="31 illustrations, each in its own style, from pencil and watercolour, marker comic and risograph to pixel art, toy brick, woodcut, sumi-e, scratchboard, embroidery, painted oil and a folk-tale storybook"></p>-Each style is its own way of making a mark: the taper of a nib, the bleed of a wash, the scumble of chalk on slate, the torn edge of cut paper, the halftone of a risograph drum, one engraved line spiralling out to become a moon. The subject changes shape in each hand, the way it would for nine different illustrators. Pick one for your brand and every picture after it arrives in the same hand. Every plate above, and the contact sheet itself, is drawn by code in this repo.+Each style is its own way of making a mark: the taper of a nib, the bleed of a wash, the scumble of chalk on slate, the torn edge of cut paper, the halftone of a risograph drum, one engraved line spiralling out to become a moon. The subject changes shape in each hand, the way it would for thirty-one different illustrators. Every style also ships a film of its picture being drawn, mark by mark, in the order an artist in that medium works. Pick one for your brand and every picture after it arrives in the same hand. Every plate above, and the contact sheet itself, is drawn by code in this repo.## What you can make@@ -46,7 +46,11 @@ Each style is its own way of making a mark: the taper of a nib, the bleed of a w| **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. |-| **Stories** | Storyboards and animatics that grow into a finished short film with an original score. |+| **Stories** | Storyboards and animatics that grow into a finished film of any length, with an original score. |+| **Your own image** | Bring a picture and get its style on a new subject, or bring a photo and get it recreated in any of the 31 hands, every mark drawn in code. |+| **Web pages** | Interactive illustrations that watch the cursor, react to clicks and forms, or draw themselves as the page scrolls. |+| **Learning** | Drawing lessons: step sheets and timelapses that teach how a picture is built, with what to look for and the common mistakes. |+| **Characters** | One character, built once and kept identical across shots, poses and styles. |Ask in plain words, *"a risograph lighthouse for our careers page, 1600×900"* or *"a chalkboard explainer of how our pricing tiers stack up"*, and anidoodle routes it to the right workflow and style recipe, asking only for what the request leaves open.@@ -56,8 +60,8 @@ The engine is the easy half. The craft is the part anidoodle carries for you, si- **Story** gives every piece a point. One idea and one focal subject for a still; one transformation, one payoff and one returning token for a film. → [`storytelling.md`](references/storytelling.md)- **Realism** comes from naming it. The anatomy, the view and the reference you opened, so a butterfly reads as a creature with a body and veins. → [`realism-and-craft.md`](references/realism-and-craft.md)-- **Style** lives in the mark. Nine full recipes, a guide for picking one per job, and the steps for inventing your own. → [`styles.md`](references/styles.md)-- **Music** follows a recipe. Major key, plucked, a phrase that asks a question and resolves home, warm and sure. → [`music-recipe.md`](references/music-recipe.md)+- **Style** lives in the mark. Thirty-one full recipes, a guide for picking one per job, and the steps for inventing your own. → [`styles.md`](references/styles.md)+- **Music** is composed as notes and synthesized in code: a modelled piano and a dozen instruments, every major and minor mode, moods per section, and a theme that fits any length. → [`music/README.md`](references/music/README.md)- **Determinism** is the guarantee. Pure functions and a seeded random, so anyone with the source rebuilds the exact same piece. → [`determinism-and-contract.md`](references/determinism-and-contract.md)- **Method** keeps you fast. Prove the look on one still, build straight through, and spend approval where being wrong is expensive. → [`working-method.md`](references/working-method.md)@@ -88,16 +92,27 @@ A picture model spends tokens and compute on every frame of every render, and it## Get started-anidoodle is an agent skill: one folder with a `SKILL.md` at the top. For Claude Code, clone it into your skills folder:+**Claude Code:**```bash-git clone https://github.com/alexgreensh/anidoodle ~/.claude/skills/anidoodle+/plugin marketplace add alexgreensh/anidoodle+/plugin install anidoodle@alexgreensh-anidoodle```+**Codex:**++```bash+codex plugin marketplace add alexgreensh/anidoodle+```++Then in the Codex TUI: `/plugins` and install anidoodle.++**Any other agent:** anidoodle is a standard skill folder (`skills/anidoodle/SKILL.md`), so it can be copied into any harness that reads skills.+Then ask for what you want: *"draw a pencil & watercolour pear for our recipes page"*. To drive the engine yourself:```bash-node ~/.claude/skills/anidoodle/engine/tools/scaffold.mjs ~/art --still hero --film intro+node <anidoodle>/engine/tools/scaffold.mjs ~/art --still hero --film intro --format 9x16 --duration 60cd ~/art && npm install && npx playwright-core install chromiumnode tools/still.mjs hero --out out/hero.png --scale 2 # a finished illustration, print size@@ -114,7 +129,7 @@ Four backends share one art core, and the core stays blissfully unaware of which## The example film-`example/` holds **Mechanical Lepidoptera**: 1,410 frames, 47 seconds, a clockwork butterfly that drafts itself, comes alive in watercolour, and leaves its blueprint in the grass. It is the whole engine in one piece: control points placed by hand over real anatomy, a cache key that names every input a pixel depends on, a score built from the recipe, and one unbroken move from built to alive. The nine style plates sit beside the engine in `engine/src/canvas-core/`, each with its recipe written at the top. Open any of them, change a number, and watch what moves.+`example/` holds **Mechanical Lepidoptera**: 1,410 frames, 47 seconds, a clockwork butterfly that drafts itself, comes alive in watercolour, and leaves its blueprint in the grass. It is the whole engine in one piece: control points placed by hand over real anatomy, a cache key that names every input a pixel depends on, a score built from the recipe, and one unbroken move from built to alive. The style plates sit beside the engine in `engine/src/canvas-core/`, each with its recipe written at the top. Open any of them, change a number, and watch what moves.## Honest by designdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex d998bf6..c429626 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -7,7 +7,7 @@<p align="center"><strong>手绘的艺术,用代码写成。</strong></p><p align="center">- 插画、动画和短片,九种手绘风格任你挑选。<br>+ 插画、绘画延时视频、影片、讲解视频和互动网页艺术,31 种风格任你挑选。<br>每一笔都是一个函数,每一个音符都是一次算术运算,于是同一份源码<br>在任何机器、任何尺寸下,都会重新画出同一张画,永远如此。</p>@@ -22,20 +22,20 @@<p align="center"><a href="README.md">English</a> · <a href="README.ja-JP.md">日本語</a> · <b>简体中文</b> · <a href="README.ko-KR.md">한국어</a> · <a href="README.fr-FR.md">Français</a> · <a href="README.es-ES.md">Español</a></p><p align="center">- <a href="#九种风格随你挑选">风格</a> ·+ <a href="#31-种风格随你挑选">风格</a> ·<a href="#你能做出什么">你能做出什么</a> ·<a href="#它自带了什么">它自带了什么</a> ·<a href="#先画后动">动态效果</a> ·<a href="#开始使用">开始使用</a></p>-## 九种风格,随你挑选+## 31 种风格,随你挑选<p align="center">- <img src="assets/styles.jpg" width="100%" alt="九幅插画,各有各的风格:铅笔与水彩画成的陆莲花、马克笔漫画风的锦鲤、圆珠笔画的怀表、蜡笔热气球、墨水与淡彩画的鹪鹩、粉笔黑板上的月相图、剪纸狐狸、孔版印刷风格的灯塔,还有一枚用单线雕刻而成的月亮">+ <img src="assets/styles.jpg" width="100%" alt="31 幅各具风格的插画,从铅笔水彩、马克笔漫画和孔版印刷,到像素画、玩具积木、木刻、墨绘、刮画、刺绣、油画和民间故事绘本"></p>-每种风格都有自己独特的落笔方式:笔尖的收锋、水彩的晕染、粉笔在石板上的揉擦、剪纸边缘的撕裂感、孔版印刷滚筒的网点、一条雕刻线螺旋展开变成一轮月亮。同一个主题,在不同的风格里会呈现出完全不同的样子,就像出自九位不同插画师之手。为你的品牌选定一种风格,之后的每一张画都会出自同一双手。上面的每一幅样图,连同这张对照表本身,都是这个仓库里的代码画出来的。+每种风格都有自己独特的落笔方式:笔尖的收锋、水彩的晕染、粉笔在石板上的揉擦、剪纸边缘的撕裂感、孔版印刷滚筒的网点、一条雕刻线螺旋展开变成一轮月亮。同一个主题,在不同的风格里会呈现出完全不同的样子,就像出自 31 位不同插画师之手。每种风格还附有一段影片,按使用这种媒介的画家实际作画的顺序,逐笔展示画面如何诞生。为你的品牌选定一种风格,之后的每一张画都会出自同一双手。上面的每一幅样图,连同这张对照表本身,都是这个仓库里的代码画出来的。## 你能做出什么@@ -46,7 +46,11 @@| **品牌** | 一个会自己画出来的 Logo,一段片头动画,一套每次发帖都保持品牌调性的社交卡片模板。 || **社交和聊天** | 无限循环的动图、GIF,以及适配信息流尺寸的透明动态贴纸。 || **幻灯片和文档** | 一个程序生成一整套章节插画。换个种子,就能得到风格相同的姊妹图。 |-| **故事** | 分镜和动态预览,一步步长成一部配有原创配乐的完整短片。 |+| **故事** | 分镜和动态预览,一步步长成一部任意时长、配有原创配乐的完整影片。 |+| **你自己的图片** | 带来一张画,就能用它的风格画新主题;带来一张照片,就能用 31 种画风中的任意一种重新创作,每一笔都由代码绘制。 |+| **网页** | 会追随光标、响应点击和表单,或随着页面滚动自行绘制的互动插画。 |+| **学习** | 用分步图和延时视频教你一幅画如何完成,还会指出该看什么、常见错误有哪些。 |+| **角色** | 一个角色只需构建一次,在不同镜头、姿势和风格中始终保持一致。 |用大白话说出你的需求就行,比如 *“给我们的招聘页面画一张孔版印刷风格的灯塔,1600×900”*,或者 *“用粉笔黑板风格画一张解释我们定价方案的说明图”*,anidoodle 会自动把它路由到合适的工作流和风格配方,只有在你没说清楚的地方才会追问。@@ -56,8 +60,8 @@- **故事**,让每件作品都有一个重点。一张静态图只讲一个想法、聚焦一个主体;一部短片只有一次转变、一个高潮,和一个反复出现的意象。→ [`storytelling.md`](references/storytelling.md)- **写实感**,来自把它说清楚。解剖结构、观察视角,以及你参考过的资料,都要交代明白,这样一只蝴蝶读起来才像是一个有身体、有翅脉的真实生物。→ [`realism-and-craft.md`](references/realism-and-craft.md)-- **风格**,活在笔触里。九套完整配方,外加一份按场合挑风格的指南,以及自创风格的步骤。→ [`styles.md`](references/styles.md)-- **音乐**,遵循一套配方。大调、拨弦,一句先提问后归家的旋律,温暖而笃定。→ [`music-recipe.md`](references/music-recipe.md)+- **风格**,活在笔触里。31 套完整配方,外加一份按场合挑风格的指南,以及自创风格的步骤。→ [`styles.md`](references/styles.md)+- **音乐**,先写成音符,再由代码合成:建模钢琴和十余种乐器、所有大小调、每个段落各自的情绪,以及能适配任意时长的主题旋律。→ [`music/README.md`](references/music/README.md)- **确定性**,是这套系统的承诺。纯函数加上带种子的随机数,任何人拿到源码都能重建出一模一样的作品。→ [`determinism-and-contract.md`](references/determinism-and-contract.md)- **方法**,让你保持速度。先用一张静态图验证效果,再一路做到底,把审批环节留给那些出错代价高的地方。→ [`working-method.md`](references/working-method.md)@@ -88,16 +92,27 @@ https://github.com/user-attachments/assets/019d46d3-536a-4843-9f68-8e8f5f5c3401## 开始使用-anidoodle 是一个 agent skill:一个文件夹,顶层放着一个 `SKILL.md`。如果你用的是 Claude Code,把它克隆进你的 skills 文件夹:+**Claude Code:**```bash-git clone https://github.com/alexgreensh/anidoodle ~/.claude/skills/anidoodle+/plugin marketplace add alexgreensh/anidoodle+/plugin install anidoodle@alexgreensh-anidoodle```+**Codex:**++```bash+codex plugin marketplace add alexgreensh/anidoodle+```++然后在 Codex 的 TUI 中输入 `/plugins`,安装 anidoodle。++**其他智能体:** anidoodle 是标准的 skill 文件夹(`skills/anidoodle/SKILL.md`),可以复制到任何能读取 skill 的运行环境。+然后直接说出你想要什么就行,比如 *“给我们的菜谱页面画一个铅笔加水彩风格的梨”*。如果你想亲自操作引擎:```bash-node ~/.claude/skills/anidoodle/engine/tools/scaffold.mjs ~/art --still hero --film intro+node <anidoodle>/engine/tools/scaffold.mjs ~/art --still hero --film intro --format 9x16 --duration 60cd ~/art && npm install && npx playwright-core install chromiumnode tools/still.mjs hero --out out/hero.png --scale 2 # a finished illustration, print size@@ -114,7 +129,7 @@ node tools/gate.mjs hero # determinism, contra## 示例短片-`example/` 目录里放着**机械鳞翅目**(Mechanical Lepidoptera):1,410 帧,47 秒,一只机械蝴蝶自己画出自己的图纸,在水彩中苏醒过来,又把蓝图留在了草丛里。这一部作品,就是整个引擎的缩影:控制点是按照真实解剖结构手工摆放的,缓存键记录了每个像素依赖的每一个输入,配乐按照配方生成,从画成到活过来,是一气呵成的一个动作。九张风格样图和引擎放在一起,都在 `engine/src/canvas-core/` 里,每一张的顶部都写着自己的配方。随便打开一个,改一个数字,看看会发生什么变化。+`example/` 目录里放着**机械鳞翅目**(Mechanical Lepidoptera):1,410 帧,47 秒,一只机械蝴蝶自己画出自己的图纸,在水彩中苏醒过来,又把蓝图留在了草丛里。这一部作品,就是整个引擎的缩影:控制点是按照真实解剖结构手工摆放的,缓存键记录了每个像素依赖的每一个输入,配乐按照配方生成,从画成到活过来,是一气呵成的一个动作。风格样图和引擎放在一起,都在 `engine/src/canvas-core/` 里,每一张的顶部都写着自己的配方。随便打开一个,改一个数字,看看会发生什么变化。## 诚实是设计出来的diff --git a/SKILL.md b/SKILL.mdindex 5812577..429a591 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,6 +1,6 @@---name: anidoodle-description: Code-drawn illustrations, animations and scored films in nine hand-drawn styles, zero assets, identical every render. Use for hero art, explainers, stickers, loops, animated logos, storyboards or a short film.+description: Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with composed scores. Matches a reference style, keeps characters consistent, teaches drawing. Deterministic, no generated assets.metadata:created_by: Alex Greenshpun (10x Company)license: Apache-2.0@@ -8,140 +8,128 @@ metadata:# anidoodle-Pictures, loops and films drawn entirely in code. One pure function, `renderFrame(film, ctx,-frame, env)`, paints every frame; a second pure function writes every audio sample. A still is-that function called once. Nothing downloaded, nothing sampled, nothing random, so the source-rebuilds the same pixels on any machine, at any size, for as long as the file exists.+Pictures, films and interactive pieces drawn entirely in code. One pure function paints every+frame; another composes and synthesizes every audio sample. The same source rebuilds the same+pixels and the same sound on any machine, at any size, at any length.-The engine is the easy half. Pieces get thrown away because they had no point, because the-subject looked like a road-sign icon of itself, because the style was a palette swap, because the-music sounded like a ghost crying, or because the client's patience went on approving fragments.-This skill carries the craft that prevents each of those.+The engine is the easy half. Work gets thrown away because it had no point, because the subject+was an icon of itself, because a style was only a palette swap, because the music had no form,+or because the person spent their patience approving fragments. This skill carries the craft+that prevents each of those.-## What are you making?+## Start by asking, then build-| Making | Scaffold | Workflow | Read |-|---|---|---|---|-| A still: hero art, spot, cover, social card, diagram, a series | `--still <name>` | **Still**, below | `styles.md`, `formats.md` |-| Motion without a story: loop, sticker, animated logo, ambient header | `--film <name>` | **Loop**, below | `formats.md`, `styles.md` |-| A film: 30 to 90 s, a transformation, a score | `--film <name>` | **Film**, below | all of `references/` |+Read `references/workflows/start-here.md` and run its intake: one question at a time, only+what the request leaves open, your recommendation first. **What** are they making, in **which+style** (show `assets/gallery/styles.jpg`; the list is `references/styles/INDEX.md`), what+**shape** (1x1, 9x16, 16x9, 4x5 or any W x H), how **long** (any length; never cap it), what+**sound** (silent or a music style and mood), which **characters**. "You pick" means pick and+say why in one line. Write the answers into a short brief before drawing.-Ask for the size, the style (or pick one from `references/styles.md` and say why) and where it-will live, if the request leaves them open. Everything else has a default.+## What are you making?++| Making | Read |+|---|---|+| A still: hero, spot, cover, card, poster, a series | Still workflow below, `references/formats.md` |+| 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` |+| A launch or product video (their screenshots welcome) | `references/workflows/launch-video.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` |+| A character kept identical in any style (woodcut to toy brick) | `references/workflows/character-consistency.md`, `references/anatomy.md` |+| A style matched from their image | `references/workflows/adapt-a-style.md` |+| A score or soundtrack | `references/music/README.md` |## The seven laws1. **Every piece has a point.** A still: one idea, one focal subject, one light. A film: one- transformation, one payoff, one visual token that returns. → `references/storytelling.md`-2. **State the realism.** "A butterfly" gets you the road-sign icon of a butterfly. Name the- anatomy, the view, and the reference you opened. → `references/realism-and-craft.md`+ transformation, one payoff, one token that returns. → `references/storytelling.md`+2. **State the realism.** Name the anatomy, the view and the reference you opened, for animals,+ objects and people alike. → `references/realism-and-craft.md`, `references/anatomy.md`3. **A style is a way of making marks.** Change the medium, the edge and the order of the marks,beyond the palette. → `references/styles.md`-4. **Prove the look on ONE still, then build end to end.** One still buys the look. After that,- gates cost more than they save. → `references/working-method.md`-5. **The contract is absolute.** Pure in `(frame, env)`, `rng(seed)` only, no clock, no- `ctx.filter`, no assets. Texture is geometry and seeded tiles. → `references/determinism-and-contract.md`-6. **Music gets a recipe, never an adjective.** Major key, plucked, I-IV-V-I, no pads, no drones,- no long reverb. You cannot hear your output, so you do not improvise. → `references/music-recipe.md`-7. **One directs, one builds, both write everything down.** When a session degrades, reset it;- the files are the memory. → `references/working-method.md`+4. **Prove the look on ONE still, then build end to end.** After that, gates cost more than they+ save. → `references/working-method.md`+5. **The contract is absolute.** Pure in `(frame, env)` (and the input log, for interactive+ pieces), `rng(seed)` only, no clock, no `ctx.filter`. Nothing generated or downloaded; images+ the person brings may be embedded, pinned by hash. → `references/determinism-and-contract.md`+6. **Music gets a plan, never an adjective.** A style, a mood per section, the notes as data, then+ measurements. You cannot hear it, so one human listens before it ships. → `references/music/`+7. **One directs, one builds, both write everything down.** When a session degrades, reset; the+ files are the memory. → `references/working-method.md`## Workflows-**Still.** (1) Say the idea in one sentence and name the focal subject and the light. (2) Open-real reference for anything that exists, and note which. (3) Pick the style and read its plate's-module first. (4) Draw: cast shadow, form, line, paper, in that medium's order. (5) Render with-`still.mjs` at full size, critique it in writing against the craft bar. ✋ **One approval.**-(6) Deliver at every size asked for from the same source, and say `reproducible` was printed.--**Loop.** As a still, plus: every motion is periodic over the loop (whole cycles only), the-subject never stops, something moves in every second. Check the seam (last frame against frame-0). Export GIF, WebM or APNG per `references/formats.md`. ✋ **One approval, on the moving file.**--**Film.**-1. **Write the story in three sentences** (setup, transformation, payoff) and name the token. If- you cannot, stop. Do not open an editor.-2. **Put it on the grid.** 120 bpm at 30 fps is a 15-frame beat. Cuts on multiples of 15, events on- multiples of 5. ONE cue table per film holds every frame number, and a checker runs at load.-3. **Open real reference** for anything that exists in the world, and write down which images.-4. **ONE look still**: the hardest frame, hero subject large, in its world, in the final medium- and light. Critique it yourself in writing first. ✋ **Approval gate.**-5. **ONE 8-second music sample** from the recipe. ✋ **Approval gate.** The client listens; you can't.-6. **Build the whole film.** No per-shot approvals. Mechanical checks run continuously and need- nobody: types, grid, contract scan, draw budget, determinism, dead air.-7. **Review the whole film once**, from the rendered file: contact sheet at one tile per beat, each- cut as a before/after pair, the dead-air numbers. One ranked fix list. One rebuild.-8. **Verify and deliver.** ✋ **Final approval.** Say what you verified and what you cannot: you- cannot hear it and you cannot watch it move.+**Still.** (1) Say the idea in one sentence; name the focal subject and the light. (2) Open real+reference for anything that exists, and note which. (3) Pick the style and read its plate's+header first. (4) Draw in that medium's order. (5) Render with `still.mjs` at full size, run the+**detail pass** on crops (faces, hands, feet, joins; `references/craft-bar.md`), critique in writing. ✋ **One approval.** (6) Deliver every+size and shape asked for from the same source, and say `reproducible` was printed.++**Loop.** As a still, plus: every motion is periodic over the loop, the subject never stops,+something moves every second. Check the seam (last frame against frame 0). ✋ **One approval,+on the moving file.**++**Film.** (1) **The story in three sentences** (setup, transformation, payoff) and the token; for+longer films, a spine plus one line per chapter. If you cannot write it, stop. (2) **The grid**:+at 120 bpm and 30 fps a beat is 15 frames; one cue table holds every frame number and a checker+runs at load. (3) **Real reference** for anything that exists. (4) **ONE look still**, the hardest+frame, critiqued in writing. ✋ **Approval.** (5) **ONE 8-second music sample.** ✋ **Approval.**+(6) **Build the whole film**; mechanical checks run continuously. (7) **Review once** from the+rendered file: a contact sheet per beat, each cut as a pair, the dead-air numbers. One ranked fix+list, one rebuild. (8) ✋ **Final approval.** Say what you verified and what you cannot.Three approval gates at most. Approval is a budget; spend it where being wrong is expensive.## The craft bar-The test: would a proud human illustrator ship this, or is it mechanical shape-assembly?+The test: would a proud human illustrator ship this, or is it mechanical shape-assembly? The+full table of tells is `references/craft-bar.md`. The ones that sink most work: subjects built+from ellipses, one style recoloured into another, things that fade in instead of being drawn,+people with rubber joints, and a character drawn differently from shot to shot.-| The tell | What passes |-|---|---|-| 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 |-| 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 |-| Gradient sky, disc sun, oval bokeh | Granulating wash, sun as paper left light, lost edges |-| Decoration | Every element has a one-line reason or it is not drawn |-| A row of style vignettes (film) | One arc. The medium changes only when the STORY changes state |-| Things fade or scale in | Marks are MADE, in the order a hand makes them |-| Both sides do the same thing at once | One side leads, by a few frames, never half a cycle |-| A hold | The camera may creep. The subject never stops |--**No dead air** in anything that moves: something visibly changes in every second, from frame 0.-Check it with the tool AND by eye: a creeping camera changes every pixel and satisfies the tool-while the eye sees a still.+**No dead air** in anything that moves: something visibly changes every second. A film that+draws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze still fails.## The engine-`engine/` is the portable art core plus the tooling. Nothing in `engine/src/canvas-core` knows-about React, Remotion, the DOM, or any backend; that separation is verified, not asserted.+`engine/` is the portable art core plus the tooling. `engine/src/canvas-core` knows nothing+about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`.```bash-node <skill>/engine/tools/scaffold.mjs ~/art --still hero --film intro # either or both+node <skill>/engine/tools/scaffold.mjs ~/art --film intro --format 9x16 --duration 180cd ~/art && npm install && npx playwright-core install chromium-node tools/still.mjs hero --out out/hero.png --scale 2 # a picture, with its reproducibility hash-node tools/render.mjs intro # the MP4; --out x.gif | x.webm | x.apng for loops-node tools/gate.mjs intro --mp4 out/intro.mp4 # determinism + contract + dead air-node tools/emit.mjs intro --out out/intro.html # one self-contained offline player+node tools/still.mjs intro --frame 0 --out out/look.png --scale 2 # a still, with its hash+node tools/render.mjs intro # MP4; --out x.gif|x.webm|x.apng+node tools/gate.mjs intro # determinism, contract, dead air+node tools/emit.mjs intro --out out/intro.html # one self-contained offline player```| Tool | What it does ||---|---|-| `scaffold.mjs` | engine + a starter still and/or film (+ `--example`) into one working project |-| `still.mjs` | one frame, full size, drawn twice, with its hash; needs a browser only |-| `render.mjs` | MP4, GIF, WebM or APNG, then a determinism probe |-| `gate.mjs` | determinism, contract, dead air, any adapter; marks checks a piece has no use for as `----` |-| `emit.mjs` | one offline HTML file that redraws the piece, then verifies the file it wrote |-| `snap.mjs` / `deadair.mjs` | contact sheets; per-frame changed-pixel fraction |-| `verify-frame-adapter.mjs` | holds a page-side seek adapter to its contract |+| `scaffold.mjs` | a project with a still and/or film; `--duration`, `--format` or `--size`, `--fps`, `--bpm` |+| `still.mjs` / `render.mjs` | one frame, drawn twice with its hash / the whole piece in any format, then a determinism probe |+| `gate.mjs` | determinism, contract, dead air, artifact; `--self-test` proves it can fail |+| `registry.mjs` / `gallery.mjs` | the style list from the plates themselves / the gallery sheet |+| `docs-check.mjs` | fails when any doc's style count, length or path disagrees with the code |+| `music.mjs` | renders and meters a score (loudness, range, onsets, brightness) |-Four backends, one art core: `playwright`, `html-player`, `remotion`, `hyperframes`. Each is-roughly 100 lines and none is visible from the core. → `references/backends-and-adapters.md`+Four backends, one art core: `playwright`, `html-player`, `remotion`, `hyperframes`.+→ `references/backends-and-adapters.md`## Worked examples-- **The nine style plates** in `engine/src/canvas-core/` (`ranunculus`, `koi`, `pocketWatch`,- `balloon`, `wren`, `moonPhases`, `fox`, `lighthouse`, `mellan`): one still each, the recipe in- the header. `banner.ts` is an ambient loop; `mellanUnspool.ts` a still that draws itself.-- **MECHANICAL LEPIDOPTERA** in `example/`: 1410 frames, 47 s, a clockwork butterfly that is- drawn, comes alive, and leaves its blueprint in the grass. Spec: `example/butterfly-film-spec.md`.- `butterfly/alive/anatomy.ts` is realism as code; `butterfly/surface.ts` is a cache key that- names everything its pixels depend on. `node <skill>/engine/tools/scaffold.mjs ~/study --example`+- **The style plates** in `engine/src/canvas-core/`: every hand has a still and a film of it being+ drawn, with the recipe in the header and `references/styles/<id>.md`.+- **MECHANICAL LEPIDOPTERA** in `example/`: a 47 s scored film. `scaffold.mjs ~/study --example`.-**Study them. Do not copy them.** Copying gets you somebody else's picture with your title on-it, and the craft bar is not satisfied by inheritance.+**Study them. Do not copy them.** The craft bar is not satisfied by inheritance.## Honest limits-You cannot hear the score and you cannot watch the film move. Every claim about either must come-from a measurement or from a human. Say which. A green checkmark is a claim, not evidence, until-you re-run it: on the worked film the dead-air gate passed while a second of near-stillness sat-in the cut, and a cache key that was wrong in one frame order survived every eye that read the-code. The machine found that one; no human was ever going to.+You cannot hear the score, watch the film move, or use the interactive piece. Every claim about+them comes from a measurement or from a human; say which. A green checkmark is a claim until you+re-run it. Render one frame at `--scale 2` before trusting a still: a layer blitted through the+wrong transform looks right at 1x and breaks at 2x.diff --git a/assets/styles.jpg b/assets/styles.jpgindex 175f36b..d22375c 100644Binary files a/assets/styles.jpg and b/assets/styles.jpg differdiff --git a/engine/package-lock.json b/engine/package-lock.jsonindex 69ddb2d..af0c1b4 100644--- a/engine/package-lock.json+++ b/engine/package-lock.json@@ -1,12 +1,12 @@{"name": "anidoodle-engine",- "version": "1.0.0",+ "version": "0.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "anidoodle-engine",- "version": "1.0.0",+ "version": "0.3.0","dependencies": {"esbuild": "^0.25.0"},diff --git a/engine/package.json b/engine/package.jsonindex f7022f2..47f8875 100644--- a/engine/package.json+++ b/engine/package.json@@ -1,6 +1,6 @@{"name": "anidoodle-engine",- "version": "1.0.0",+ "version": "0.3.0","private": true,"type": "module","description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",diff --git a/engine/src/canvas-core/adaptAquarelle.ts b/engine/src/canvas-core/adaptAquarelle.tsnew file mode 100644index 0000000..aa6f3db--- /dev/null+++ b/engine/src/canvas-core/adaptAquarelle.ts@@ -0,0 +1,108 @@+// PASTEL BLOTCH WATERCOLOUR · a hand ADAPTED from a reference the owner brought+// (~/Pictures/aquarelle/lightshot-aquarelle.png, a pastel watercolour backdrop behind a terminal+// window; the window is UI, not the hand, and was excluded from the analysis). Grown from the+// nearest plate by eye, ranunculus (pencil & watercolour), with the pencil taken OUT: this hand has+// no drawn line at all. The reference's picture (an abstract rainbow backdrop, the terminal) is not+// used: only its way of making marks. Subject here is new.+//+// MEDIUM RECIPE (written before any code, adapt-a-style.md step 3):+// MARK a blotch: one loaded round brush set down and pushed about, so each shape is ONE flat+// puddle of dilute pigment with a jagged coastline (big lobes plus a fine torn fringe),+// never an ellipse, never a stroke with a direction.+// EDGE hard-dry: the puddle dries with a crisp, slightly darker rim where pigment migrates to+// the edge, a pale bloom inside. No soft blending into neighbours, no line.+// ORDER palest big puddles first, left to dry; smaller, stronger puddles GLAZED over them (the+// overlaps multiply into deeper secondary colours); paper left bare between islands;+// a few spatter dots flicked on; last, opaque white gouache sparkles with a halo.+// PAPER warm cream cold-press, a soft grain that shows in the washes.+// PALETTE high key only (the darkest wash is still light): apricot, butter, blush, mauve,+// lilac, mint, seafoam, powder blue, a clear teal for the deepest glaze.+//+// SUBJECT: a moon jellyfish (Aurelia aurita) drifting in sunlit water. Anatomy: a shallow+// translucent bell, wider than tall, seen a little from the side so its rim is an ellipse; FOUR+// horseshoe-shaped gonads (the pale rings that name it) showing through the bell's top; a fringe+// of many fine marginal tentacles hanging from the rim; four frilly oral arms trailing from the+// centre underneath, longer than the bell is wide. REFERENCE (from knowledge): aquarium and diver+// photographs of Aurelia; its structure only, never a photograph's composition.+// LIGHT: from the surface, above: the top of the bell is left as bare paper, the water deepens+// from apricot at the top to teal at the bottom, the arms catch the light on their upper folds.+import { Gfx, PENCIL, displace, fractal, rng, type Ctx, type Env, type P } from "./core";+import type { Film } from "./film";++export const STYLE = { id: "adaptAquarelle", name: "Pastel blotch watercolour", family: "watercolour", medium: "dilute watercolour puddles with hard pooled rims on cream cold-press, white gouache sparkles; no line", nearest: "ranunculus", hero: "a moon jellyfish in sunlit water", house: "styles/house/pastel-blotch.json" };++const PAPER = "#f5f1e6";+const J = { bell: "#c173b8", bell2: "#9d5fb8", gonad: "#a8418c", arm: "#e0708f", arm2: "#b15aa8", fringe: "#9a4e97" }; // the subject: warm magentas against a cool ground, a full value step darker than the water+const C = { apricot: "#f7a86a", butter: "#f7d77e", blush: "#f5b5a6", rose: "#eb97ad", mauve: "#cf95c6", lilac: "#b49ae0", mint: "#a6e0bd", sea: "#8fd3cc", powder: "#9dbdec", teal: "#5fb3b8", deep: "#4f8fc4" }; // the reference is pastel but CLEAN: high key, real chroma+const W = 1080, H = 1080;++const ellipse = (cx: number, cy: number, rx: number, ry: number, rot = 0, n = 72): P[] => Array.from({ length: n }, (_, i) => { const a = (i / n) * Math.PI * 2, x = Math.cos(a) * rx, y = Math.sin(a) * ry; return [cx + x * Math.cos(rot) - y * Math.sin(rot), cy + x * Math.sin(rot) + y * Math.cos(rot)] as P; });+const densify = (pts: P[], step: number): P[] => { const out: P[] = []; for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length], n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step)); for (let k = 0; k < n; k++) out.push([a[0] + ((b[0] - a[0]) * k) / n, a[1] + ((b[1] - a[1]) * k) / n]); } return out; };+const size = (pts: P[]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); } return Math.max(20, Math.min(x1 - x0, y1 - y0)); };+// the coastline: big lobes scaled to the puddle, then a fine torn fringe that is the same size on every puddle (it is the paper's, not the shape's)+// (fractal() sits near 0.5 with a spread of about +-0.15, so the amplitudes are ~3x the visible wobble)+const coast = (pts: P[], seed: number, lobes = 1): P[] => { const s = size(pts); return displace(displace(displace(densify(pts, 3), s * 0.9 * lobes, 1.4 / s, 2, seed), s * 0.22 * lobes, 5 / s, 2, seed + 7), 13, 0.06, 3, seed + 17); };+const hex = (c: string) => [parseInt(c.slice(1, 3), 16), parseInt(c.slice(3, 5), 16), parseInt(c.slice(5, 7), 16)];+const darker = (c: string, k: number) => { const [r, g, b] = hex(c); return `rgb(${Math.round(r * k)},${Math.round(g * k)},${Math.round(b * k)})`; };+const path = (c: Ctx, pts: P[]) => { c.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) c.lineTo(pts[i][0], pts[i][1]); c.closePath(); };++// ONE puddle: flat pigment, a darker dried rim, a paler bloom inside. `holes` are reserved paper.+const puddle = (g: Gfx, shape: P[], col: string, o: { seed: number; a?: number; rim?: number; lobes?: number; holes?: P[][] }) => {+ const c = g.cur, edge = coast(shape, o.seed, o.lobes ?? 1), a = o.a ?? 0.55; g.mark(edge, 12);+ c.save(); if (o.holes?.length) { c.beginPath(); c.rect(-50, -50, W + 100, H + 100); o.holes.forEach((h) => path(c, h)); c.clip("evenodd"); } // reserved paper: the brush went round it+ c.beginPath(); path(c, edge); c.globalAlpha = a; c.fillStyle = col; c.fill();+ c.globalAlpha = (o.rim ?? 0.5) * a; c.strokeStyle = darker(col, 0.72); c.lineWidth = 3; c.lineJoin = "round"; c.beginPath(); path(c, edge); c.stroke();+ // the bloom: where the water pushed pigment outward as it dried, the middle is a shade paler (drawn as the paper colour, thin)+ const r = rng(o.seed * 7 + 3), s = size(shape), cx = shape.reduce((t, p) => t + p[0], 0) / shape.length, cy = shape.reduce((t, p) => t + p[1], 0) / shape.length;+ if (s > 60 && !o.holes?.length) { c.globalAlpha = 0.16; c.fillStyle = PAPER; c.beginPath(); path(c, coast(ellipse(cx + (r() - 0.5) * s * 0.2, cy + (r() - 0.5) * s * 0.2, s * 0.22, s * 0.17, r() * 3), o.seed + 9, 0.8)); c.fill(); }+ c.globalAlpha = 1; c.restore();+};+const sparkle = (c: Ctx, x: number, y: number, s: number, rot: number) => {+ const gr = c.createRadialGradient(x, y, 0, x, y, s * 1.6); gr.addColorStop(0, "rgba(255,255,250,0.85)"); gr.addColorStop(0.3, "rgba(255,255,250,0.35)"); gr.addColorStop(1, "rgba(255,255,250,0)"); c.fillStyle = gr; c.fillRect(x - s * 2, y - s * 2, s * 4, s * 4);+ c.fillStyle = "rgba(255,255,252,0.97)";+ for (const [ax, ay, len, wid] of [[Math.cos(rot), Math.sin(rot), s * 2.2, s * 0.16], [-Math.sin(rot), Math.cos(rot), s * 1.6, s * 0.14]] as number[][]) { c.beginPath(); c.moveTo(x - ax * len, y - ay * len); c.quadraticCurveTo(x - ay * wid, y + ax * wid, x + ax * len, y + ay * len); c.quadraticCurveTo(x + ay * wid, y - ax * wid, x - ax * len, y - ay * len); c.fill(); }+};++// ---------------------------------------------------------------- the jellyfish+const BELL = { cx: 548, top: 250, rimY: 452, rx: 232, ry: 58 };+const bellShape = (): P[] => { const out: P[] = []; for (let i = 0; i <= 40; i++) { const t = i / 40, a = Math.PI + t * Math.PI; out.push([BELL.cx + Math.cos(a) * BELL.rx, BELL.rimY + Math.sin(a) * (BELL.rimY - BELL.top) * (0.92 + 0.08 * Math.sin(t * Math.PI))]); } for (let i = 1; i < 30; i++) { const a = (i / 30) * Math.PI; out.push([BELL.cx + Math.cos(a) * BELL.rx, BELL.rimY + Math.sin(a) * BELL.ry]); } return out; };+// a horseshoe: a thick arc seen through the curved top of the bell+const horseshoe = (cx: number, cy: number, r: number, open: number, sq: number): P[] => { const o: P[] = [], i2: P[] = []; for (let k = 0; k <= 24; k++) { const a = open + 0.55 + (k / 24) * (Math.PI * 2 - 1.1); o.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r * sq]); i2.push([cx + Math.cos(a) * r * 0.52, cy + Math.sin(a) * r * 0.52 * sq]); } return [...o, ...i2.reverse()]; };+// an oral arm: a ribbon that wavers as it trails, its frilled edge given by the puddle's own coastline+// oral arms are frilled curtains, not limbs: wide and ruffled under the bell, twisting as they sway, thinning to wisps+const arm = (x0: number, y0: number, len: number, lean: number, w0: number, seed: number): P[] => { const r = rng(seed), L: P[] = [], R: P[] = [], n = 40, ph = r() * 6; for (let i = 0; i <= n; i++) { const t = i / n, x = x0 + lean * t * len + Math.sin(t * 7 + ph) * 40 * t, y = y0 + t * len * (1 - 0.1 * t), twist = 0.55 + 0.45 * Math.abs(Math.cos(t * 6 + ph)), w = w0 * Math.pow(1 - t, 0.8) * twist + 2, fr = (k: number) => Math.sin(t * 60 + k + ph) * 6 * (1 - t); L.push([x - w + fr(0), y]); R.push([x + w + fr(2), y]); } return [...L, ...R.reverse()]; };+// all four drift the same way (the current carries them), one leads, never splayed like legs+const ARMS = [[528, 468, 380, 0.22, 36, 61], [556, 474, 450, 0.34, 42, 62], [582, 470, 330, 0.46, 34, 63], [544, 478, 270, 0.12, 28, 64]] as const;++const draw = (ctx: Ctx, _f: number, env: Env) => {+ const g = new Gfx(ctx, env, 0, PENCIL), r = rng(4242);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H);+ const bell = bellShape(), reserve: P[][] = [displace(densify(bell.map(([x, y]) => [BELL.cx + (x - BELL.cx) * 1.14, 470 + (y - 470) * 1.14] as P), 3), 20, 0.07, 3, 5)]; // the painter works AROUND the jellyfish's bell+ // 1. the water: pale big puddles, warm near the surface, cool below, islands of bare paper between+ const rows = [{ y: 90, cols: [C.apricot, C.butter, C.sea, C.apricot, C.butter, C.mint] }, { y: 300, cols: [C.butter, C.mint, C.sea, C.powder, C.apricot, C.sea] }, { y: 520, cols: [C.mint, C.lilac, C.sea, C.powder, C.mint, C.lilac] }, { y: 740, cols: [C.sea, C.powder, C.teal, C.mint, C.powder, C.sea] }, { y: 960, cols: [C.powder, C.teal, C.sea, C.deep, C.teal, C.powder] }];+ g.group("paint", () => rows.forEach((row, ri) => row.cols.forEach((col, ci) => {+ if ((ri * 7 + ci * 3) % 3 === 1) return; // a third of the places stay bare paper: rests the eye can breathe in // a bare rest: not every place gets a puddle+ const x = 40 + ci * 205 + (ri % 2) * 90 + (r() - 0.5) * 60, y = row.y + (r() - 0.5) * 60, rx = 115 + r() * 60, ry = 95 + r() * 45;+ puddle(g, ellipse(x, y, rx, ry, r() * 3), col, { seed: 100 + ri * 10 + ci, a: 0.62, rim: 0.8, holes: ri < 3 ? reserve : undefined });+ })), { blend: "multiply", blur: 1.6 }); // the first, wettest puddles dried with a slightly softer edge+ // 2. glazes: smaller, stronger puddles over the first, some crossing each other+ g.group("paint", () => { for (let i = 0; i < 5; i++) { const band = i % 5, x = 60 + r() * 960, y = 60 + band * 220 + (r() - 0.5) * 120, near = Math.hypot(x - BELL.cx, (y - 380) * 1.6) < 300; if (near && band < 2) continue; const col = [C.apricot, C.rose, C.lilac, C.sea, C.teal][band]; puddle(g, ellipse(x, y, 50 + r() * 50, 40 + r() * 40, r() * 3), col, { seed: 300 + i, a: 0.34, rim: 0.6, holes: reserve }); } }, { blend: "multiply" });+ // 3. the jellyfish: bell wash with the sunlit top left as paper, the gonads, the arms, the fringe+ const hi = coast(ellipse(BELL.cx - 70, BELL.top + 58, 105, 30, -0.18), 511, 0.15);+ g.group("paint", () => { puddle(g, bell, J.bell, { seed: 501, a: 0.62, rim: 1, lobes: 0.03, holes: [hi] }); puddle(g, ellipse(BELL.cx, BELL.rimY, BELL.rx * 0.96, BELL.ry * 0.9), J.bell2, { seed: 502, a: 0.45, rim: 0.9, lobes: 0.03 }); }, { blend: "multiply" });+ g.group("paint", () => { // four horseshoes in a clover round the bell's centre, each opening toward the middle, foreshortened by the tilt+ [0.8, 2.35, 3.9, 5.5].forEach((a, i) => { const x = BELL.cx + Math.cos(a) * 58, y = 392 + Math.sin(a) * 30; puddle(g, horseshoe(x, y, 42, a + Math.PI - 0.2, 0.58), J.gonad, { seed: 520 + i, a: 0.42, rim: 0.7, lobes: 0.03 } /* big soft rings touching in a clover: small dark ones read as a face */); }); }, { blend: "multiply" });+ g.group("paint", () => ARMS.forEach(([x, y, len, lean, w, s]) => puddle(g, arm(x, y, len, lean, w, s), s % 2 ? J.arm : J.arm2, { seed: s, a: 0.55, rim: 1, lobes: 0.04 })), { blend: "multiply" });+ // the marginal tentacles: the only thin marks, a rigger brush dragged down from the rim and lifted+ g.group("paint", () => { for (let i = 0; i < 46; i++) { const t = i / 45, a = Math.PI * (0.02 + t * 0.96), x = BELL.cx + Math.cos(a) * BELL.rx * 0.97, y = BELL.rimY + Math.sin(a) * BELL.ry * 0.9, len = 70 + r() * 110 + Math.sin(t * Math.PI) * 60, ph = r() * 6; const pts: P[] = Array.from({ length: 8 }, (_, k) => [x + Math.sin(k * 0.7 + ph) * 7 * (k / 7) + (k / 7) * (x - BELL.cx) * 0.08, y + (k / 7) * len] as P); g.pen(pts, { w: 1.2, color: i % 3 ? J.fringe : J.arm, seed: 700 + i, opacity: 0.8, boil: 0, wobble: 0.4, retrace: false, taper: 1 }); } }, { blend: "multiply" });+ // 4. spatter: pigment flicked off the brush, a few, in drifts+ const c = g.cur; ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ for (let i = 0; i < 38; i++) { const cluster = [[180, 220], [880, 160], [860, 720], [200, 820], [520, 900]][i % 5], x = cluster[0] + (r() - 0.5) * 260, y = cluster[1] + (r() - 0.5) * 200, s = 1.4 + r() * r() * 5.5; ctx.globalAlpha = 0.55; ctx.fillStyle = [C.rose, C.teal, C.apricot, C.lilac, C.deep][i % 5]; ctx.beginPath(); ctx.arc(x, y, s, 0, Math.PI * 2); ctx.fill(); }+ ctx.globalAlpha = 1;+ // 5. white gouache sparkles last: bioluminescent glints round the bell and sunlight in the water+ [[330, 250, 17, 0.1], [800, 300, 12, 0.3], [700, 560, 21, 0.05], [410, 610, 10, 0.2], [940, 470, 16, 0.15], [140, 470, 13, 0.25], [860, 900, 18, 0.1], [260, 980, 12, 0.2], [620, 170, 9, 0.3], [470, 760, 9, 0.1], [90, 120, 14, 0.05]].forEach(([x, y, s, rt]) => sparkle(ctx, x, y, s, rt));+ ctx.restore(); void c; void fractal;+ g.paper("coldpress", 0.1); g.paper("paper", 0.05);+};++export const adaptAquarelle: Film = { meta: { title: "Moon jellyfish · pastel blotch watercolour (adapted hand)", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "still", start: 0, end: 1, draw }] };diff --git a/engine/src/canvas-core/adaptScrapbook.ts b/engine/src/canvas-core/adaptScrapbook.tsnew file mode 100644index 0000000..6eebb34--- /dev/null+++ b/engine/src/canvas-core/adaptScrapbook.ts@@ -0,0 +1,117 @@+// QUIET ARCHIVAL SCRAPBOOK · a hand ADAPTED from a reference the owner brought: frame 10 of+// Ritwika's explainer film (refs/ritwika-explainer/frames/f_10.png, a slide about a frozen LLM+// encoder). Its subject, its diagram and its layout are NOT used; what is borrowed is the hand.+// Nearest plate by eye: scrapbook (v1 wave), which is loud (foxed parchment, ransom titles,+// copperplate everywhere). This reference is its quiet sibling, and that difference IS the recipe.+//+// MEDIUM RECIPE (adapt-a-style.md step 3, written before code):+// MARK flat pieces of coloured stock with a torn deckle edge, laid on a pale page; words+// struck by a typewriter (one weight, each strike its own ink density); diagrams in a+// thin, steady technical pen; ONE small vintage engraving as ornament; annotations in a+// red pen and a blue pencil, used once or twice, not everywhere.+// EDGE torn but tidy: the deckle is fine and even, never ragged; every piece throws the same+// soft shadow down-right; the ink lines are clean and unhatched except in the engraving.+// ORDER page; cards laid down (big first); coloured label chips; the diagram inked on its card;+// typed labels; the engraving; red and blue annotations last.+// PAPER a pale warm sheet, barely aged: a soft mottle and a slight darkening toward the edges.+// No foxing, no tape, no pegs (those belong to the loud sibling).+// PALETTE muted pastels on cream: duck-egg blue, dusty rose, sage-teal, one vermilion accent,+// a sepia-black ink. Mostly empty page: the pieces are islands with air round them.+//+// SUBJECT (new): "why sourdough rises": a jar of starter with its rise marked by a rubber band,+// the two organisms that do the work as label chips, a small chart of height over hours with the+// peak annotated, and a wheat-ear engraving. Realism: a straight-sided glass jar with a screw+// thread at the neck; dough surface domed with bubbles pressed against the glass; the band sits at+// the level of the feed; the curve rises, peaks near hour six to eight and slumps as the acids win.+// LIGHT: a desk lamp upper left: every card's shadow falls down and right.+import { Gfx, displace, fractal, rng, type Ctx, type Env, type Medium, type P } from "./core";+import type { Film } from "./film";+import { letter, width } from "./drafting";++export const STYLE = { id: "adaptScrapbook", name: "Quiet archival scrapbook", family: "collage", medium: "torn pastel card pieces with soft shadows on a pale page, typewriter strikes, thin technical-pen diagrams, one small engraving, red-pen and blue-pencil notes", nearest: "scrapbook", hero: "why sourdough rises (an explainer slide)", house: "styles/house/quiet-scrapbook.json" };++const W = 1280, H = 720;+const PAGE = "#efe7d3", INK = "#35302d", RED = "#c44a36", BLUEP = "#4f86c6", DUCK = "#bcd3d6", ROSE = "#e3a3a6", SAGE = "#7fa99e", CREAM = "#f4efe3", CARD = "#e6e1d2";+const PENM: Medium = { nib: 1, taper: 0.3, pressure: 0.25, retrace: false, wobble: 0.35, rough: 0.25 };++const densify = (pts: P[], step: number): P[] => { const out: P[] = []; for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length], n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step)); for (let k = 0; k < n; k++) out.push([a[0] + ((b[0] - a[0]) * k) / n, a[1] + ((b[1] - a[1]) * k) / n]); } return out; };+const rot = (pts: P[], cx: number, cy: number, a: number): P[] => pts.map(([x, y]) => [cx + (x - cx) * Math.cos(a) - (y - cy) * Math.sin(a), cy + (x - cx) * Math.sin(a) + (y - cy) * Math.cos(a)]);+const path = (c: Ctx, pts: P[]) => { c.beginPath(); c.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) c.lineTo(pts[i][0], pts[i][1]); c.closePath(); };+// a torn piece: a rectangle whose edge is bitten by a fine, even deckle (tidy, not ragged)+const piece = (cx: number, cy: number, w: number, h: number, a: number, seed: number, deckle = 3.2): P[] => rot(displace(densify([[cx - w / 2, cy - h / 2], [cx + w / 2, cy - h / 2], [cx + w / 2, cy + h / 2], [cx - w / 2, cy + h / 2]], 2.2), deckle * 2.6, 0.32, 2, seed), cx, cy, a);++// lay a card: its soft shadow first (the lamp is upper left), then the stock, then its grain+const lay = (g: Gfx, pts: P[], col: string, lift = 1) => {+ g.group("plain", () => g.fill(pts.map(([x, y]) => [x + 4 * lift, y + 6 * lift] as P), "#5a4a38", 0.3), { blur: 5 * lift, alpha: 0.55 });+ g.group("plain", () => g.fill(pts, col, 1), { textures: [] });+};+// the typewriter: upright single-stroke capitals, one weight, each strike its own ink density and a hair off the line+const type = (g: Gfx, text: string, x: number, y: number, cap: number, seed: number, col = INK, align: "left" | "center" = "left") => {+ const r = rng(seed), cell = cap * 0.86, cx0 = align === "center" ? x - (text.length * cell) / 2 : x; // monospace: every strike gets the same cell+ [...text].forEach((ch, i) => { if (ch === " ") return; const w = width(ch, cap, 0); letter(g, ch, cx0 + i * cell + (cell - w) / 2, y + (r() - 0.5) * cap * 0.08, { cap, color: col, seed: seed + i, w: Math.max(1.3, cap * 0.13), opacity: 0.7 + r() * 0.28, slant: 0 }); });+};++const draw = (ctx: Ctx, _f: number, env: Env) => {+ const g = new Gfx(ctx, env, 0, PENM), r = rng(99);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAGE; ctx.fillRect(0, 0, W, H);+ // the page: a slow mottle, a little darker toward the handled edges+ g.group("plain", () => { const c = g.cur; for (let y = 0; y < H; y += 16) for (let x = 0; x < W; x += 16) { const v = fractal(5, x, y, 0.004, 0.004, 3), e = Math.max(Math.abs(x - W / 2) / (W / 2), Math.abs(y - H / 2) / (H / 2)); c.globalAlpha = Math.max(0, (v - 0.5) * 0.45 + Math.pow(e, 3) * 0.22); c.fillStyle = "#b89d76"; c.fillRect(x, y, 16, 16); } g.touch(0, 0, W, H); }, { blur: 14 });++ // 1. cards, the big one first+ const jarCard = piece(420, 400, 430, 470, -0.018, 11), chartCard = piece(965, 470, 390, 290, 0.022, 12), tag = piece(1105, 185, 190, 200, -0.05, 13);+ lay(g, jarCard, DUCK, 1.1); lay(g, chartCard, CREAM); lay(g, tag, CARD, 0.8);+ // 2. label chips: a strip of coloured stock each, torn short ends+ const chipA = piece(760, 150, 220, 42, 0.012, 21, 2), chipB = piece(760, 212, 250, 42, -0.01, 22, 2), sect = piece(175, 64, 250, 40, -0.02, 23, 2);+ lay(g, chipA, ROSE, 0.6); lay(g, chipB, DUCK, 0.6); lay(g, sect, CARD, 0.6);++ // 3. the diagram, inked on the blue card: a jar of starter+ const jx = 420, top = 250, bot = 560, jw = 230;+ g.group("plain", () => {+ // dough: domed surface, with bubbles pressed against the glass+ const surf = 360, dough: P[] = [[jx - jw / 2 + 6, bot - 6], [jx - jw / 2 + 6, surf + 10], [jx - 60, surf - 6], [jx, surf - 12], [jx + 60, surf - 6], [jx + jw / 2 - 6, surf + 10], [jx + jw / 2 - 6, bot - 6]];+ g.fill(dough, "#efe4c8", 1);+ for (let i = 0; i < 26; i++) { const x = jx - jw / 2 + 16 + r() * (jw - 32), y = surf + 14 + r() * (bot - surf - 30), s = 2.5 + r() * r() * 9; g.pen(Array.from({ length: 8 }, (_, k) => [x + Math.cos((k / 8) * Math.PI * 2) * s, y + Math.sin((k / 8) * Math.PI * 2) * s] as P), { w: 1, closed: true, color: INK, seed: 40 + i, opacity: 0.55, boil: 0, retrace: false }); }+ });+ g.group("plain", () => {+ const L = jx - jw / 2, R = jx + jw / 2;+ g.pen([[L + 14, top + 26], [L, top + 44], [L, bot - 14], [L + 16, bot], [R - 16, bot], [R, bot - 14], [R, top + 44], [R - 14, top + 26]], { w: 1.6, color: INK, seed: 31, boil: 0 });+ [0, 1, 2].forEach((k) => g.pen([[L + 12, top + 4 + k * 8], [jx, top + k * 8 + 1], [R - 12, top + 4 + k * 8]], { w: 1.2, color: INK, seed: 32 + k, boil: 0, opacity: 0.8 })); // the screw thread+ g.pen([[L + 30, top + 60], [L + 26, bot - 40]], { w: 1.4, color: "#ffffff", seed: 35, boil: 0, opacity: 0.8 }); // glass catching the lamp+ g.pen([[L + 6, 360], [jx - 60, 348], [jx, 342], [jx + 60, 348], [R - 6, 360]], { w: 1.3, color: INK, seed: 36, boil: 0, opacity: 0.85 });+ // the rubber band at the feed line, and a dashed line where it has risen to+ g.pen([[L - 4, 452], [jx, 458], [R + 4, 452]], { w: 5, color: RED, seed: 37, boil: 0, opacity: 0.9, taper: 0 });+ for (let x = L - 30; x < R + 40; x += 18) g.pen([[x, 342], [x + 10, 342]], { w: 1.2, color: INK, seed: 38 + x, boil: 0, opacity: 0.7, taper: 0 });+ g.pen([[R + 52, 450], [R + 52, 350]], { w: 1.4, color: INK, seed: 39, boil: 0 }); g.pen([[R + 45, 360], [R + 52, 346], [R + 59, 360]], { w: 1.4, color: INK, seed: 40, boil: 0 });+ });+ type(g, "FED", jx + jw / 2 + 12, 460, 13, 51); type(g, "6 H LATER", jx + jw / 2 + 64, 386, 13, 52);+ type(g, "STARTER, FIG. 1", jx, 600, 15, 53, INK, "center");++ // 4. chips and section label, typed+ type(g, "YEAST: GAS", 670, 141, 17, 61); type(g, "BACTERIA: ACID", 655, 203, 17, 62); type(g, "NO. 2 FERMENTATION", 70, 55, 16, 63);+ type(g, "TWO WORKERS, ONE JAR.", 660, 262, 15, 64, "#5c524a");++ // 5. the chart: height over hours, on its cream card+ g.group("plain", () => {+ const x0 = 820, y0 = 575, x1 = 1120, y1 = 385; // axes+ for (let k = 1; k <= 4; k++) g.pen([[x0, y0 - (k * (y0 - y1)) / 4], [x1, y0 - (k * (y0 - y1)) / 4]], { w: 0.7, color: BLUEP, seed: 70 + k, boil: 0, opacity: 0.35, taper: 0 });+ g.pen([[x0, y1 - 10], [x0, y0]], { w: 1.5, color: INK, seed: 75, boil: 0, taper: 0.2 }); g.pen([[x0, y0], [x1 + 10, y0]], { w: 1.5, color: INK, seed: 74, boil: 0, taper: 0.2 });+ const curve: P[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map((h) => [x0 + (h / 12) * (x1 - x0), y0 - 10 - (y0 - y1 - 20) * (h < 7 ? 1 / (1 + Math.exp(-(h - 3.6) * 1.3)) : 1 - (h - 7) * 0.07)] as P);+ g.pen(curve, { w: 2.4, color: RED, seed: 76, boil: 0, taper: 0.4 });+ [0, 6, 12].forEach((h, i) => { g.pen([[x0 + (h / 12) * (x1 - x0), y0], [x0 + (h / 12) * (x1 - x0), y0 + 6]], { w: 1.2, color: INK, seed: 80 + i, boil: 0 }); });+ });+ type(g, "0", 815, 588, 11, 81); type(g, "6", 965, 588, 11, 82); type(g, "12 H", 1106, 588, 11, 83); type(g, "RISE", 790, 360, 12, 84);+ // the annotation: a blue-pencil ring round the peak and a red-pen note, once each+ g.group("plain", () => { const px = 820 + (7 / 12) * 300, py = 385 + 10; const ring: P[] = Array.from({ length: 30 }, (_, i) => { const a = -2 + (i / 29) * Math.PI * 2.15; return [px + Math.cos(a) * 34, py + Math.sin(a) * 20] as P; }); g.pen(ring, { w: 2, color: BLUEP, seed: 90, boil: 0, opacity: 0.8, taper: 0.8 }); });+ type(g, "BAKE HERE", 1010, 345, 14, 91, RED);++ // 6. the engraving on the tag: a wheat ear, grains in pairs, each shaded by a few swelling burin lines+ g.group("plain", () => {+ const sx = 1100, sy = 268; g.pen([[sx + 6, sy], [sx + 2, sy - 70], [sx - 4, sy - 130]], { w: 1.6, color: INK, seed: 100, boil: 0, taper: 0.6 });+ for (let k = 0; k < 7; k++) for (const side of [-1, 1]) { const y = sy - 70 - k * 13, x = sx + 2 - k * 0.9, gx = x + side * 11, gy = y - 6, grain: P[] = [[x, y], [gx - side * 2, gy - 9], [gx + side * 4, gy - 2], [x + side * 2, y + 2]]; g.pen(grain, { w: 1.1, color: INK, seed: 110 + k * 2 + (side > 0 ? 1 : 0), closed: true, boil: 0, opacity: 0.9 }); for (let h = 0; h < 3; h++) g.pen([[x + side * (3 + h * 2), y - 1 - h], [gx + side * (1 + h), gy - 5 + h]], { w: 0.6, color: INK, seed: 130 + k * 6 + h + (side > 0 ? 3 : 0), boil: 0, opacity: 0.7, taper: 1 }); if (k === 6) g.pen([[gx, gy - 8], [gx + side * 6, gy - 40]], { w: 0.7, color: INK, seed: 150 + side, boil: 0, opacity: 0.8 }); }+ });+ type(g, "TRITICUM", 1105, 262, 10, 160, INK, "center");++ g.paper("paper", 0.06);+};++export const adaptScrapbook: Film = { meta: { title: "Why sourdough rises · quiet archival scrapbook (adapted hand)", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "still", start: 0, end: 1, draw }] };diff --git a/engine/src/canvas-core/bake.ts b/engine/src/canvas-core/bake.tsnew file mode 100644index 0000000..f956cef--- /dev/null+++ b/engine/src/canvas-core/bake.ts@@ -0,0 +1,98 @@+// THE WEB PROFILE. A plate draws a character in ~130 ms at DPR 2 (every stroke ribboned, every group+// blurred and toothed). A web page has 6. So an interactive piece does the drawing ONCE, at mount,+// into sprites, and each frame is a composite of sprites plus a handful of live marks.+//+// A sprite is a pure function of its key (and env.scale, which the key includes): contract rule 5.+// It is cropped to exactly the device box the drawing touched, at integer device pixels, so an+// untransformed blit puts back the very pixels the plate drew. Moving parts are blitted with a+// rotation or a DOWN-scale about a pivot, never an up-scale (contract rule 6).+import { Env, Gfx, Layer, Medium, PENCIL, type Ctx, type Rect } from "./core";++export type Sprite = { c: CanvasImageSource; x: number; y: number; w: number; h: number };+export const stats = { baked: 0, bytes: 0, ms: 0 }; // for the host's report only; pixels never read it++const resettable = (c: unknown) => !!c && typeof (c as { reset?: unknown }).reset === "function";+const scratch = (env: Env): Layer => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), key = `bake:scratch:${DW}x${DH}`;+ let L = env.cache.get(key) as Layer | undefined;+ if (L && resettable(L.ctx)) (L.ctx as unknown as { reset(): void }).reset(); else { L = env.canvas(DW, DH); env.cache.set(key, L); } /* see bake(): pristine, or new */+ return L;+};++// Draw `fn` with a fresh Gfx on a clean full-size scratch, crop what it composited, cache it.+export const bake = (env: Env, key: string, fn: (g: Gfx) => void, o: { medium?: Medium; frame?: number; full?: boolean; raw?: boolean } = {}): Sprite => {+ const k = `sprite:${key}@${env.scale}`, hit = env.cache.get(k) as Sprite | undefined; if (hit) return hit;+ const S = scratch(env), DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), c = S.ctx;+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; c.clearRect(0, 0, DW, DH);+ // Every bake starts from pristine surfaces. Measured in Chromium: a 2D canvas that has EVER filled+ // with a gradient (Gfx.glow, Gfx.vignette) rasterises later drawing differently, up to 8/255, even+ // after its pixels are cleared and its fillStyle reset. The layer pool and the scratch are shared, so+ // without this a sprite depended on which sprites were baked before it (the replay gate caught it+ // as cold != warm). ctx.reset() restores a canvas completely; where it is missing, drop the pool.+ const pool = env.cache.get(`pool:${DW}x${DH}`) as (Layer & { dirty?: unknown })[] | undefined;+ if (pool) { if (resettable(pool[0]?.ctx)) pool.forEach((L) => { (L.ctx as unknown as { reset(): void }).reset(); L.dirty = null; }); else pool.length = 0; }+ const g = new Gfx(c, env, o.frame ?? 0, o.medium ?? PENCIL); fn(g);+ const r: Rect = o.full || !g.drawn ? [0, 0, DW, DH] : g.drawn, w = Math.max(1, r[2] - r[0]), h = Math.max(1, r[3] - r[1]);+ let L = env.canvas(w, h); L.ctx.drawImage(S.canvas as CanvasImageSource, r[0], r[1], w, h, 0, 0, w, h);+ c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, DW, DH);+ const P = env.cache.get("bake:paper") as { data: Uint8ClampedArray; DW: number } | undefined;+ if (P && !o.raw) L = sheeted(env, L, r[0], r[1], w, h, P);+ const s: Sprite = { c: L.canvas as CanvasImageSource, x: r[0], y: r[1], w, h }; env.cache.set(k, s);+ stats.baked++; stats.bytes += w * h * 4;+ return s;+};++// Blit at rest, offset by whole device pixels: crisp, and exactly the baked pixels.+export const blit = (ctx: Ctx, s: Sprite, dx = 0, dy = 0, alpha = 1) => {+ if (alpha <= 0) return;+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = alpha; ctx.drawImage(s.c, s.x + Math.round(dx), s.y + Math.round(dy)); ctx.globalAlpha = 1;+};+// Blit rotated by `deg` and scaled by (sx, sy) <= 1 about a device-pixel pivot, then moved by (tx, ty).+// Falls back to the crisp path when there is nothing to transform.+export const blitT = (ctx: Ctx, s: Sprite, pivot: [number, number], deg: number, tx: number, ty: number, sx = 1, sy = 1, alpha = 1) => {+ if (alpha <= 0) return;+ const kx = Math.min(1, sx), ky = Math.min(1, sy);+ if (Math.abs(deg) < 0.05 && kx === 1 && ky === 1) return blit(ctx, s, tx, ty, alpha);+ const a = (deg * Math.PI) / 180, c = Math.cos(a), n = Math.sin(a);+ ctx.setTransform(c * kx, n * kx, -n * ky, c * ky, pivot[0] + tx, pivot[1] + ty); ctx.globalAlpha = alpha;+ ctx.drawImage(s.c, s.x - pivot[0], s.y - pivot[1]);+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1;+};++// The sheet over everything, as ONE multiply. Gfx.paper() multiplies a tile at an opacity; applied to+// white that leaves exactly the per-pixel factor, and two factors multiply into one. So a plate's+// `paper("paper", .13); paper("coldpress", .2)` becomes one full-canvas blit per frame.+export const paperFactor = (env: Env, sheets: [string, number][]): Sprite => bake(env, `paper:${sheets.map((s) => s.join("=")).join(",")}`, (g) => {+ const m = g.main; m.setTransform(1, 0, 0, 1, 0, 0); m.fillStyle = "#ffffff"; m.fillRect(0, 0, Math.round(env.W * env.scale), Math.round(env.H * env.scale));+ sheets.forEach(([kind, a]) => g.paper(kind, a));+}, { full: true, raw: true });+// PAPER IN THE SPRITES. (a over b) x F == (a x F) over (b x F): multiply by a per-pixel factor+// distributes over source-over. So instead of one full-canvas multiply every frame, every sprite is+// multiplied ONCE, at bake, by the sheet factor under its rest position, and the frame needs no+// sheet pass at all. Exact for anything drawn where it was baked; a part that moves carries its+// patch of paper grain with it (a few percent of tone, invisible in motion). usePaper() turns it on+// for every later bake in this env; the factor itself and anything baked { raw: true } are exempt.+export const usePaper = (env: Env, sheets: [string, number][]) => {+ if (env.cache.has("bake:paper")) return;+ const f = paperFactor(env, sheets), DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), R = env.canvas(DW, DH);+ R.ctx.drawImage(f.c, 0, 0); env.cache.set("bake:paper", { data: R.ctx.getImageData(0, 0, DW, DH).data, DW });+};+// read once, multiply in integers, write into a FRESH surface (one that is never read back stays on the GPU)+const sheeted = (env: Env, L: Layer, x0: number, y0: number, w: number, h: number, P: { data: Uint8ClampedArray; DW: number }): Layer => {+ const img = L.ctx.getImageData(0, 0, w, h), d = img.data, f = P.data;+ for (let y = 0; y < h; y++) { let i = y * w * 4, j = ((y0 + y) * P.DW + x0) * 4; for (let x = 0; x < w; x++, i += 4, j += 4) { if (!d[i + 3]) continue; d[i] = (d[i] * f[j] + 127) / 255; d[i + 1] = (d[i + 1] * f[j + 1] + 127) / 255; d[i + 2] = (d[i + 2] * f[j + 2] + 127) / 255; } }+ const out = env.canvas(w, h); out.ctx.putImageData(img, 0, 0); return out;+};+export const multiply = (ctx: Ctx, s: Sprite) => { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = "multiply"; ctx.drawImage(s.c, s.x, s.y); ctx.globalCompositeOperation = "source-over"; };++// A Gfx that runs only SOME of a plate's groups: bake one part of a character from the plate's own+// drawing function, unchanged, by the index of the group calls it makes. `census` lists them.+export class Only extends Gfx {+ n = 0; census: string[] = [];+ constructor(main: Ctx, env: Env, frame: number, medium: Medium, public keep: (i: number) => boolean) { super(main, env, frame, medium); }+ group(kind: "ink" | "paint" | "plain", fn: () => void, opts: Parameters<Gfx["group"]>[2] = {}) { const i = this.n++; this.census.push(kind); if (this.keep(i)) super.group(kind, fn, opts); }+ inkGroup(fn: () => void, o: Parameters<Gfx["inkGroup"]>[1] = {}) { const i = this.n++; this.census.push("inkGroup"); if (this.keep(i)) super.inkGroup(fn, o); }+}+// bake() for a part of a plate: `draw(g)` receives an Only that keeps groups in `keep`.+export const bakePart = (env: Env, key: string, keep: (i: number) => boolean, draw: (g: Gfx) => void, o: { medium?: Medium; frame?: number } = {}): Sprite =>+ bake(env, key, (g0) => { const g = new Only(g0.main, env, o.frame ?? 0, o.medium ?? PENCIL, keep); draw(g); g0.drawn = g.drawn; }, o);diff --git a/engine/src/canvas-core/bakerSheet.ts b/engine/src/canvas-core/bakerSheet.tsnew file mode 100644index 0000000..a6ad360--- /dev/null+++ b/engine/src/canvas-core/bakerSheet.ts@@ -0,0 +1,47 @@+// THEO THE BAKER, coloured pencil: the adult proof of the drawing layer. The hero (presenting a+// loaf, three-quarter view), the construction it was built on (the gesture lay-in alone), and the+// same man turned three ways at a smaller scale. Every figure is theoBaker.toScene(pose): the rig+// and its gates underneath, the designed masses on top, the pencil hand over all of it.+import { GRAPHITE, Gfx, PENCIL, type Ctx, type Env } from "./core";+import type { Film } from "./film";+import { add, camera, lensPx } from "./character/math3";+import type { Scene } from "./character/types";+import { order } from "./character/build";+import { renderPencil } from "./character/render/pencil";+import { letter } from "./drafting";+import { bakerPose, loafPart, theoBaker } from "./characters/theo/baker";++const W = 2500, H = 1900;+export const BAKER_PENCIL = {+ skin: { base: "#e3a882", shade: "#b87458" }, nail: { base: "#eecab4", shade: "#d4a58c" }, shirt: { base: "#eef0ec", shade: "#aeb8c6" }, apron: { base: "#d9c493", shade: "#a58e57" },+ apronDark: { base: "#7d6a42", shade: "#5a4a2c" }, trousers: { base: "#5d5650", shade: "#3a3531" }, boots: { base: "#7e4c2b", shade: "#4e2c16" }, hair: { base: "#4a3a31", shade: "#2c211b" },+ grey: { base: "#a9a4a0", shade: "#86817d" }, beard: { base: "#6a5244", shade: "#43322a" }, crust: { base: "#cf8e46", shade: "#8e5424" }, crustDark: { base: "#7a4217", shade: "#5a2e10" }, flour: { base: "#fbf6ea", shade: "#e6dcc8" },+ pupil: { base: "#4a3a2c", shade: "#2c2118" }, white: { base: "#fffdf6", shade: "#e8e2d4" }, blush: { base: "#dd8a7c", shade: "#bb6a5e" }, mouth: { base: "#7a3434", shade: "#5a2222" }, lip: { base: "#b8665e", shade: "#94483f" },+};+const withLoaf = (s: Scene, cam: ReturnType<typeof camera>, at: [number, number, number]): Scene => ({ ...s, parts: order([...s.parts, loafPart(cam, at)]) });++export const drawBakerSheet = (ctx: Ctx, _f: number, env: Env) => {+ const s = env.scale; ctx.setTransform(s, 0, 0, s, 0, 0); ctx.fillStyle = "#e9e3d6"; ctx.fillRect(0, 0, W, H);+ const tile = (x: number, y: number, w: number, h: number, draw: (g: Gfx, sub: Env) => void) => {+ const L = env.canvas(Math.round(w * s), Math.round(h * s)), sub: Env = { W: w, H: h, scale: s, cache: env.cache, canvas: env.canvas, image: env.image };+ L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.clearRect(0, 0, L.canvas.width, L.canvas.height); draw(new Gfx(L.ctx, sub, 0, PENCIL), sub);+ ctx.setTransform(s, 0, 0, s, 0, 0); ctx.fillStyle = "rgba(60,45,30,0.12)"; ctx.fillRect(x + 6, y + 8, w, h); ctx.drawImage(L.canvas as CanvasImageSource, 0, 0, L.canvas.width, L.canvas.height, x, y, w, h);+ };+ const g = new Gfx(ctx, env, 0, PENCIL);+ // the hero: three-quarter, 50 mm, eye at his chest+ const hero = bakerPose(-28), eye = add(hero.pose.root, [-1.1, 0.12, 2.9]); // a level camera at his waist: verticals stay vertical, he does not lean+ const heroCam = (w: number, h: number) => camera(eye, add(hero.pose.root, [0.05, 0.12, 0.1]), lensPx(50, w * 1.45), w * 0.5, h * 0.47);+ tile(40, 40, 1300, 1820, (gg, sub) => { const cam = heroCam(sub.W, sub.H); renderPencil(gg, sub, withLoaf(theoBaker.toScene(hero.pose, cam), cam, hero.loaf), BAKER_PENCIL, { horizon: sub.H * 0.86, ground: "#b39b7c" }); });+ // the construction: the gesture lay-in alone, then the lay-in with the designed contours+ tile(1380, 40, 540, 760, (gg, sub) => { const cam = heroCam(sub.W, sub.H); renderPencil(gg, sub, withLoaf(theoBaker.toScene(hero.pose, cam), cam, hero.loaf), BAKER_PENCIL, { horizon: sub.H * 0.86, only: ["layin"] }); });+ tile(1940, 40, 520, 760, (gg, sub) => { const cam = heroCam(sub.W, sub.H); renderPencil(gg, sub, withLoaf(theoBaker.toScene(hero.pose, cam), cam, hero.loaf), BAKER_PENCIL, { horizon: sub.H * 0.86, only: ["layin", "line"] }); });+ // the same man turned: front, profile, back (a long lens, so the three read as a turnaround)+ [0, 90, 180].forEach((yaw, i) => tile(1380 + i * 367, 880, 350, 900, (gg, sub) => {+ const b = bakerPose(yaw), cam = camera(add(b.pose.root, [0, -0.1, 11]), add(b.pose.root, [0, -0.1, 0]), (sub.H * 0.9 * 11) / 1.8, sub.W / 2, sub.H * 0.5);+ renderPencil(gg, sub, withLoaf(theoBaker.toScene(b.pose, cam), cam, b.loaf), BAKER_PENCIL, { horizon: sub.H * 0.92 });+ }));+ letter(g, "LAY-IN: THE GESTURE FIRST", 1380, 820, { cap: 16, color: GRAPHITE, seed: 3, w: 1.6 });+ letter(g, "THEN THE DESIGNED CONTOURS", 1940, 820, { cap: 16, color: GRAPHITE, seed: 4, w: 1.6 });+ letter(g, "THEO THE BAKER / COLOURED PENCIL / RIG UNDERNEATH, DRAWING ON TOP", 1380, 1810, { cap: 17, color: GRAPHITE, seed: 5, w: 1.7 });+};+export const bakerSheet: Film = { meta: { title: "Theo the baker", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "sheet", start: 0, end: 1, draw: drawBakerSheet }] };diff --git a/engine/src/canvas-core/balloon.ts b/engine/src/canvas-core/balloon.tsindex 0f3a72d..9d95a99 100644--- a/engine/src/canvas-core/balloon.ts+++ b/engine/src/canvas-core/balloon.ts@@ -1,6 +1,6 @@import { Gfx, fractal, rng, type Ctx, type Env, type Medium, type P } from "./core";import type { Film } from "./film";-import { blob, bounds, clamp, fillShape, hatchRuns, inside, lerp, lerpP, mix, smooth } from "./gallery";+import { blob, bounds, clamp, clipped, fillShape as fillShape0, hatchRuns, inside, lerp, lerpP, mix, smooth } from "./gallery";// HOT-AIR BALLOON · crayon. Wax on toothy paper: every fill is a back-and-forth scribble that// skips the valleys of the sheet, a second, darker crayon is worked across the shade side, a@@ -15,20 +15,41 @@ import { blob, bounds, clamp, fillShape, hatchRuns, inside, lerp, lerpP, mix, smconst CRAYON_M: Medium = { nib: 2.9, taper: 0.3, pressure: 0.8, retrace: true, wobble: 2.2, rough: 1.3 };const K = { red: "#e5392d", orange: "#f68b1f", yellow: "#ffd21f", green: "#3dae49", blue: "#2f7de1", sky: "#69c3f2", purple: "#8d4fc7", pink: "#ff78ae", brown: "#8b5a3c", white: "#fffdf4", black: "#262233", leaf: "#2f8a3b" };const PAPER = "#fdf8ea";+// OPTIONAL draw-on clock (balloonDraw.ts). Absent, every mark is drawn whole and the still is byte-identical.+// Present, each scribble and line asks it how far along it is (0 = not yet, 1 = done), in drawing order.+export type CrayonKind = "fill" | "shade" | "burnish" | "line";+export type BalloonClock = { n: number; sec: string; p: (kind: CrayonKind, i: number, pts: P[]) => number; lay: (i: number, pts: P[]) => number };+type Clocked = Gfx & { clk?: BalloonClock };+// a solid crayon patch: under the clock it is coloured in from its left edge; paper knock-outs are always there+const fillShape = (g: Gfx, pts: P[], color: string, alpha?: number) => {+ const clk = (g as Clocked).clk;+ if (clk && color !== PAPER) {+ const p = clk.p("fill", clk.n++, pts); if (p <= 0) return;+ if (p < 1) { const b = bounds(pts), x = b.x0 - 2 + (b.x1 - b.x0 + 4) * p; clipped(g, [[b.x0 - 2, b.y0 - 2], [x, b.y0 - 2], [x, b.y1 + 2], [b.x0 - 2, b.y1 + 2]], () => fillShape0(g, pts, color, alpha)); return; }+ }+ fillShape0(g, pts, color, alpha);+};const dark = (c: string) => mix(c, "#2a1d3a", 0.45);// ---------------------------------------------------------------- the crayon// A scribble fill: hatch runs joined end to end into one back-and-forth stroke, drawn in short// passes so the pressure (alpha) wanders the way a child's hand does.-const scribble = (g: Gfx, region: P[], color: string, o: { angle: number; gap: number; w: number; alpha: number; seed: number; keep?: (x: number, y: number) => boolean; over?: number }) => {+const scribble = (g: Gfx, region: P[], color: string, o: { angle: number; gap: number; w: number; alpha: number; seed: number; keep?: (x: number, y: number) => boolean; over?: number; kind?: CrayonKind }) => {+ const clk = (g as Clocked).clk, p = clk ? clk.p(o.kind ?? "fill", clk.n++, region) : 1; // the draw-on clock: how much of this scribble exists yet+ if (p <= 0) return;const { angle, gap, w, alpha, seed, keep = () => true, over = 1.035 } = o, r = rng(seed), b = bounds(region);const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, grown = region.map(([x, y]) => [cx + (x - cx) * over, cy + (y - cy) * over] as P);- const runs = hatchRuns({ x0: b.x0 - 8, y0: b.y0 - 8, x1: b.x1 + 8, y1: b.y1 + 8 }, angle, gap, (x, y) => inside(grown, x, y) && keep(x, y), 5, seed);+ // the runs are pure geometry of this call site (region, angle, gap, seed, colour, and its keep rule, which is fixed per site): computed once per page+ const rk = `balloon:runs:${seed}:${angle}:${gap}:${over}:${color}:${region.length}:${region[0][0].toFixed(3)},${region[0][1].toFixed(3)}:${region[region.length >> 1][0].toFixed(3)}`;+ let runs = g.env.cache.get(rk) as P[][] | undefined;+ if (!runs) { runs = hatchRuns({ x0: b.x0 - 8, y0: b.y0 - 8, x1: b.x1 + 8, y1: b.y1 + 8 }, angle, gap, (x, y) => inside(grown, x, y) && keep(x, y), 5, seed); g.env.cache.set(rk, runs); }const c = g.cur; g.touch(b.x0 - 14, b.y0 - 14, b.x1 + 14, b.y1 + 14);c.save(); c.lineCap = "round"; c.lineJoin = "round"; c.strokeStyle = color; c.lineWidth = w;- let prev: P | null = null;+ let prev: P | null = null; const lim = p * runs.length;runs.forEach((run, i) => {- const pts = (i % 2 ? [...run].reverse() : run).filter((_, k, a) => k % 3 === 0 || k === a.length - 1).map(([x, y]) => [x + (r() - 0.5) * 1.6, y + (r() - 0.5) * 1.6] as P);+ if (i >= lim) return;+ let pts = (i % 2 ? [...run].reverse() : run).filter((_, k, a) => k % 3 === 0 || k === a.length - 1).map(([x, y]) => [x + (r() - 0.5) * 1.6, y + (r() - 0.5) * 1.6] as P);+ if (lim - i < 1) pts = pts.slice(0, Math.max(2, Math.ceil(pts.length * (lim - i))));const jump = prev ? Math.hypot(pts[0][0] - prev[0], pts[0][1] - prev[1]) : 0;c.globalAlpha = alpha * (0.72 + r() * 0.4);c.beginPath();@@ -38,7 +59,14 @@ const scribble = (g: Gfx, region: P[], color: string, o: { angle: number; gap: n});c.restore();};-const line = (g: Gfx, pts: P[], color: string, w: number, seed: number, op = 0.92, wob = 1) => g.pen(pts, { w, color, seed, wobble: wob, boil: 0, opacity: op, retrace: true, taper: 1 });+const line = (g: Gfx, pts: P[], color: string, w: number, seed: number, op = 0.92, wob = 1) => {+ const clk = (g as Clocked).clk;+ if (!clk) return g.pen(pts, { w, color, seed, wobble: wob, boil: 0, opacity: op, retrace: true, taper: 1 });+ // drawn on: a thin light lay-in of the contour first, then the fat line gone over twice, which replaces it+ const i = clk.n++, full = clk.p("line", i, pts), lay = clk.lay(i, pts);+ if (full < 1 && lay > 0) g.pen(pts, { w: w * 0.45, color, seed, wobble: wob, boil: 0, opacity: op * 0.6, retrace: false, taper: 1, progress: lay });+ if (full > 0) g.pen(pts, { w, color, seed, wobble: wob, boil: 0, opacity: op, retrace: true, taper: 1, progress: full });+};// wax skips the valleys of the sheet: every crayon layer is punched by the paper's toothconst wax = (g: Gfx, fn: () => void) => g.group("plain", fn, { textures: ["pencilTooth"] });@@ -60,12 +88,12 @@ const envelope = (g: Gfx) => {scribble(g, gore, col, { angle: -0.35 + (k % 2) * 0.2, gap: 9, w: 5, alpha: 0.5, seed: 101 + k * 7 });// the shade crayon, worked across the side away from the light and under the bellyconst sh = (x: number, y: number) => { const u = (x - CX) / R, v = (y - EQ) / R; return u * 0.9 + v * 0.8 + (fractal(9, x, y, 0.02, 0.02, 2) - 0.5) * 0.35 > 0.15 + litG * 0.4; };- scribble(g, gore, dark(col), { angle: 0.55, gap: 6.5, w: 5, alpha: 0.72, seed: 102 + k * 7, keep: sh });+ scribble(g, gore, dark(col), { angle: 0.55, gap: 6.5, w: 5, alpha: 0.72, kind: "shade", seed: 102 + k * 7, keep: sh });const deep = (x: number, y: number) => { const u = (x - CX) / R, v = (y - EQ) / R; return u * 0.9 + v * 0.9 > 0.75 + litG * 0.35; };- scribble(g, gore, mix(dark(col), K.black, 0.3), { angle: -0.6, gap: 7, w: 4.4, alpha: 0.6, seed: 103 + k * 7, keep: deep });+ scribble(g, gore, mix(dark(col), K.black, 0.3), { angle: -0.6, gap: 7, w: 4.4, alpha: 0.6, kind: "shade", seed: 103 + k * 7, keep: deep });// burnished highlight: white crayon pressed hard over the colour, upper leftconst hi = (x: number, y: number) => { const u = (x - CX) / R + 0.42, v = (y - EQ) / R + 0.52; return u * u * 1.4 + v * v < 0.1 + (fractal(10, x, y, 0.03, 0.03, 2) - 0.5) * 0.06; };- scribble(g, gore, K.white, { angle: 1.0, gap: 5, w: 4.5, alpha: 0.75, seed: 104 + k * 7, keep: hi, over: 1 });+ scribble(g, gore, K.white, { angle: 1.0, gap: 5, w: 4.5, alpha: 0.75, kind: "burnish", seed: 104 + k * 7, keep: hi, over: 1 });});}// seams: load tapes down every meridian, a few latitude tapes, the crown ring, the outline twice@@ -87,11 +115,11 @@ const rigging = (g: Gfx) => {[[-tw * 0.9, bk.x0 + 4], [-tw * 0.3, bk.x0 + 40], [tw * 0.3, bk.x1 - 40], [tw * 0.9, bk.x1 - 4]].forEach(([a, b2], i) => line(g, [[CX + a, throatY + 30], [lerp(CX + a, b2, 0.5), lerp(throatY + 30, bk.y0, 0.5)], [b2, bk.y0]], "#4a3a36", 0.9, 300 + i, 0.85, 0.6));fillShape(g, skirt, PAPER);scribble(g, skirt, K.red, { angle: 1.4, gap: 5, w: 5.5, alpha: 0.9, seed: 310 });- scribble(g, skirt, dark(K.red), { angle: 0.4, gap: 6, w: 4.5, alpha: 0.65, seed: 311, keep: (x) => x > CX });+ scribble(g, skirt, dark(K.red), { angle: 0.4, gap: 6, w: 4.5, alpha: 0.65, kind: "shade", seed: 311, keep: (x) => x > CX });line(g, [...skirt, skirt[0]], K.black, 1.8, 312, 0.9, 0.8);// the burner, and its flame roaring up into the throatconst burner: P[] = [[CX - 26, 790], [CX + 26, 790], [CX + 22, 806], [CX - 22, 806]];- fillShape(g, burner, "#aab4c4"); scribble(g, burner, "#7f8aa0", { angle: 0.3, gap: 4, w: 3.5, alpha: 0.8, seed: 320, keep: (x) => x > CX - 4 });+ fillShape(g, burner, "#aab4c4"); scribble(g, burner, "#7f8aa0", { angle: 0.3, gap: 4, w: 3.5, alpha: 0.8, kind: "shade", seed: 320, keep: (x) => x > CX - 4 });line(g, [...burner, burner[0]], K.black, 1.4, 321, 0.9, 0.5);const flame = smooth([[CX - 17, 792], [CX - 19, 772], [CX - 8, 754], [CX + 1, 736], [CX + 9, 752], [CX + 19, 770], [CX + 17, 792]], true, 8); // it disappears up into the skirtfillShape(g, flame, PAPER);@@ -107,7 +135,7 @@ const rigging = (g: Gfx) => {[[CX - 40, K.pink, 1], [CX + 40, K.blue, -1]].forEach(([x, c, s], i) => {const hx = x as number, hy = bk.y0 - 30;fillShape(g, blob(hx, hy + 18, 13, 14, 340 + i, 0.1, 10), PAPER); scribble(g, blob(hx, hy + 18, 13, 14, 340 + i, 0.1, 10), c as string, { angle: 1.2, gap: 4, w: 4, alpha: 0.9, seed: 341 + i });- fillShape(g, blob(hx, hy, 11, 12, 345 + i, 0.08, 10), "#f6c8a0"); scribble(g, blob(hx, hy, 11, 12, 345 + i, 0.08, 10), "#e8a37c", { angle: 0.4, gap: 5, w: 3.4, alpha: 0.6, seed: 346 + i, keep: (xx) => xx > hx });+ fillShape(g, blob(hx, hy, 11, 12, 345 + i, 0.08, 10), "#f6c8a0"); scribble(g, blob(hx, hy, 11, 12, 345 + i, 0.08, 10), "#e8a37c", { angle: 0.4, gap: 5, w: 3.4, alpha: 0.6, kind: "shade", seed: 346 + i, keep: (xx) => xx > hx });line(g, blob(hx, hy, 11, 12, 345 + i, 0.08, 10), "#6b3e2e", 1.3, 347 + i, 0.85, 0.5);fillShape(g, blob(hx - 2, hy - 9, 11, 5, 348 + i, 0.2, 10), i ? K.brown : K.orange);if (s === 1) { line(g, [[hx - 9, hy + 16], [hx - 24, hy + 2], [hx - 30, hy - 20]], "#e8a37c", 2.6, 349, 0.95, 0.5); fillShape(g, blob(hx - 31, hy - 24, 5, 5, 356, 0.1, 8), "#f6c8a0"); } // waving@@ -116,9 +144,9 @@ const rigging = (g: Gfx) => {fillShape(g, basket, PAPER);scribble(g, basket, "#c98f4e", { angle: 1.4, gap: 4.5, w: 5, alpha: 0.9, seed: 350 });for (let yy = bk.y0 + 8; yy < bk.y1 - 3; yy += 8) for (let xx = bk.x0 + 4 + ((yy / 8) % 2) * 6; xx < bk.x1 - 6; xx += 12) line(g, [[xx, yy], [xx + 7, yy + 3]], K.brown, 1.0, 351 + xx * 3 + yy, 0.75, 0.3); // the weave- scribble(g, basket, K.brown, { angle: 0.35, gap: 6, w: 4, alpha: 0.6, seed: 352, keep: (x) => x > CX + 12 });+ scribble(g, basket, K.brown, { angle: 0.35, gap: 6, w: 4, alpha: 0.6, kind: "shade", seed: 352, keep: (x) => x > CX + 12 });const rim: P[] = [[bk.x0 - 5, bk.y0 - 9], [bk.x1 + 5, bk.y0 - 9], [bk.x1 + 5, bk.y0 + 5], [bk.x0 - 5, bk.y0 + 5]];- fillShape(g, rim, "#7a4a2c"); scribble(g, rim, "#5a3420", { angle: 0.1, gap: 3, w: 3, alpha: 0.7, seed: 353, keep: (x) => x > CX });+ fillShape(g, rim, "#7a4a2c"); scribble(g, rim, "#5a3420", { angle: 0.1, gap: 3, w: 3, alpha: 0.7, kind: "shade", seed: 353, keep: (x) => x > CX });line(g, [...basket, basket[0]], "#4a2c1c", 1.9, 354, 0.9, 0.7); line(g, [...rim, rim[0]], "#3a2216", 1.6, 355, 0.9, 0.6);});};@@ -133,7 +161,7 @@ const sky = (g: Gfx) => {// the sun, where the light comes fromwax(g, () => {const sun = blob(150, 140, 62, 60, 20, 0.05, 16);- fillShape(g, sun, PAPER); scribble(g, sun, K.yellow, { angle: 0.9, gap: 4.5, w: 5.5, alpha: 0.95, seed: 21 }); scribble(g, sun, K.orange, { angle: -0.7, gap: 7, w: 4, alpha: 0.45, seed: 22, keep: (x, y) => (x - 150) + (y - 140) > 20 });+ fillShape(g, sun, PAPER); scribble(g, sun, K.yellow, { angle: 0.9, gap: 4.5, w: 5.5, alpha: 0.95, seed: 21 }); scribble(g, sun, K.orange, { angle: -0.7, gap: 7, w: 4, alpha: 0.45, kind: "shade", seed: 22, keep: (x, y) => (x - 150) + (y - 140) > 20 });line(g, sun.filter((_, i) => i % 3 === 0), K.orange, 1.8, 23, 0.9, 1);for (let i = 0; i < 12; i++) { const a = (i / 12) * Math.PI * 2 + 0.15, r0 = 80, r1 = 106 + (i % 2) * 16; line(g, [[150 + Math.cos(a) * r0, 140 + Math.sin(a) * r0], [150 + Math.cos(a) * (r0 + r1) / 2, 140 + Math.sin(a) * (r0 + r1) / 2 + 2], [150 + Math.cos(a) * r1, 140 + Math.sin(a) * r1]], K.yellow, 2.4, 24 + i, 0.95, 1.2); }});@@ -143,7 +171,7 @@ const sky = (g: Gfx) => {for (let i = 0; i < 6; i++) puffs.push(blob(cx + (i - 2.5) * 32 * s + (r() - 0.5) * 10, cy - Math.sin((i / 5) * Math.PI) * 28 * s + (r() - 0.5) * 8, (34 + r() * 16) * s, (28 + r() * 10) * s, seed + i, 0.08, 12));wax(g, () => {puffs.forEach((p) => fillShape(g, p, PAPER));- puffs.forEach((p, i) => scribble(g, p, "#b9cde6", { angle: 0.2, gap: 6, w: 4.5, alpha: 0.55, seed: seed + 10 + i, keep: (x, y) => y > cy + 4 * s }));+ puffs.forEach((p, i) => scribble(g, p, "#b9cde6", { angle: 0.2, gap: 6, w: 4.5, alpha: 0.55, kind: "shade", seed: seed + 10 + i, keep: (x, y) => y > cy + 4 * s }));puffs.forEach((p, i) => {// walk this puff's edge and keep only the stretches no other puff covers: the silhouettelet run: P[] = []; const runs: P[][] = [];@@ -172,16 +200,16 @@ const land = (g: Gfx) => {const back: P[] = smooth([[0, 900], [180, 868], [420, 884], [700, 852], [900, 866], [1080, 846], [1080, 1080], [0, 1080]], true, 10);const front: P[] = smooth([[0, 968], [220, 930], [480, 958], [760, 936], [1080, 972], [1080, 1080], [0, 1080]], true, 10);wax(g, () => {- fillShape(g, back, PAPER); scribble(g, back, "#8ccf5a", { angle: 0.15, gap: 5.5, w: 6, alpha: 0.9, seed: 400, over: 1 }); scribble(g, back, K.green, { angle: -0.4, gap: 8, w: 5, alpha: 0.5, seed: 401, over: 1, keep: (x, y) => y > 890 + Math.sin(x * 0.01) * 12 });+ fillShape(g, back, PAPER); scribble(g, back, "#8ccf5a", { angle: 0.15, gap: 5.5, w: 6, alpha: 0.9, seed: 400, over: 1 }); scribble(g, back, K.green, { angle: -0.4, gap: 8, w: 5, alpha: 0.5, kind: "shade", seed: 401, over: 1, keep: (x, y) => y > 890 + Math.sin(x * 0.01) * 12 });line(g, back.filter((_, i) => i % 4 === 0 && back[i][1] < 1000), "#2f7a33", 1.8, 402, 0.85, 1);// trees on the far hill: round crowns on stubby trunks, each shaded on its right[[160, 872, 1], [214, 880, 0.8], [760, 858, 0.9], [982, 852, 1.1]].forEach(([x, y, s], i) => {line(g, [[x, y + 2], [x + 1, y - 18 * s]], K.brown, 2.2, 410 + i, 0.95, 0.4);const c = blob(x, y - 34 * s, 22 * s, 24 * s, 420 + i, 0.12, 12);- fillShape(g, c, PAPER); scribble(g, c, K.green, { angle: 1.1, gap: 4, w: 4.5, alpha: 0.9, seed: 430 + i }); scribble(g, c, K.leaf, { angle: 0.3, gap: 5, w: 3.6, alpha: 0.7, seed: 440 + i, keep: (xx) => xx > x + 2 });+ fillShape(g, c, PAPER); scribble(g, c, K.green, { angle: 1.1, gap: 4, w: 4.5, alpha: 0.9, seed: 430 + i }); scribble(g, c, K.leaf, { angle: 0.3, gap: 5, w: 3.6, alpha: 0.7, kind: "shade", seed: 440 + i, keep: (xx) => xx > x + 2 });line(g, c.filter((_, k) => k % 3 === 0), "#1f5a28", 1.4, 450 + i, 0.85, 0.8);});- fillShape(g, front, PAPER); scribble(g, front, K.green, { angle: -0.12, gap: 5, w: 6.5, alpha: 0.92, seed: 460, over: 1 }); scribble(g, front, K.leaf, { angle: 0.5, gap: 7, w: 5, alpha: 0.55, seed: 461, over: 1, keep: (x, y) => y > 985 });+ fillShape(g, front, PAPER); scribble(g, front, K.green, { angle: -0.12, gap: 5, w: 6.5, alpha: 0.92, seed: 460, over: 1 }); scribble(g, front, K.leaf, { angle: 0.5, gap: 7, w: 5, alpha: 0.55, kind: "shade", seed: 461, over: 1, keep: (x, y) => y > 985 });// a winding path, and grass flicked up along the hill's edgeconst path = smooth([[610, 1080], [560, 1030], [620, 990], [590, 950]], false, 10);const pw: P[] = [...path.map(([x, y], i) => [x - 22 + i * 0.35, y] as P), ...path.map(([x, y], i) => [x + 22 - i * 0.35, y] as P).reverse()];@@ -191,11 +219,13 @@ const land = (g: Gfx) => {});};-export const drawBalloon = (ctx: Ctx, _frame: number, env: Env) => {- const g = new Gfx(ctx, env, 0, CRAYON_M);+export const drawBalloon = (ctx: Ctx, _frame: number, env: Env, clock?: BalloonClock) => {+ const g = new Gfx(ctx, env, 0, CRAYON_M) as Clocked;+ if (clock) { clock.n = 0; g.clk = clock; }+ const sec = (s: string) => { if (clock) clock.sec = s; };ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);ctx.fillStyle = PAPER; ctx.fillRect(0, 0, 1080, 1080);- sky(g); land(g); envelope(g); rigging(g);+ sec("sky"); sky(g); sec("land"); land(g); sec("envelope"); envelope(g); sec("rigging"); rigging(g);g.paper("paper", 0.08);};diff --git a/engine/src/canvas-core/balloonDraw.ts b/engine/src/canvas-core/balloonDraw.tsnew file mode 100644index 0000000..9313ded--- /dev/null+++ b/engine/src/canvas-core/balloonDraw.ts@@ -0,0 +1,72 @@+import type { Ctx, Env, P } from "./core";+import type { Film } from "./film";+import { drawBalloon, type BalloonClock, type CrayonKind } from "./balloon";++// HOT-AIR BALLOON · crayon, drawn on. The balloon plate's own marks, replayed in the order a+// child (or an illustrator working in wax crayon) makes them:+//+// 1. the contours, thin and light, the hero first: envelope, basket and burner, then the sun,+// clouds, the far balloon and birds, then the hills and trees+// 2. scribble fills, back and forth, the balloon's gores one colour at a time, then the rest of+// the picture, and the sky last, because the sky is always coloured last+// 3. a darker crayon worked over the shade side of everything+// 4. the white crayon pressed hard into the highlight (burnished)+// 5. the fat contour gone over twice, which swallows the light lay-in line under it+//+// Every mark keeps its place in the plate's LAYER order (a later fill still sits under the+// outline drawn before it, the way wax colours up to a line); only its TIME moves. Frame 0 is the+// bare sheet. From frame 420 the plate is drawn with no clock at all, so the last 30 frames are the+// balloon still, byte for byte.++const N = 450; // 15 s at 30 fps+const PHASE: Record<"lay" | CrayonKind, [number, number]> = { // frames, all on the 5-frame grid+ lay: [5, 100], fill: [105, 285], shade: [290, 335], burnish: [340, 365], line: [370, 415],+};+const DONE = 420;+Object.values(PHASE).forEach(([a, b]) => { if (a % 5 || b % 5 || b > DONE) throw new Error("balloonDraw: phase off the grid"); });++type Mark = { i: number; kind: CrayonKind; sec: string; len: number; area: number };+const PRIO: Record<string, number> = { envelope: 0, rigging: 1, sky: 2, land: 3 };+const polyLen = (pts: P[]) => pts.reduce((s, p, k) => (k ? s + Math.hypot(p[0] - pts[k - 1][0], p[1] - pts[k - 1][1]) : 0), 0);+const boxArea = (pts: P[]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; pts.forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }); return Math.max(1, (x1 - x0) * (y1 - y0)); };+const clamp = (v: number) => Math.max(0, Math.min(1, v));++// one survey pass of the plate with a clock that draws nothing and writes down every mark+const survey = (ctx: Ctx, env: Env): Mark[] => {+ const marks: Mark[] = [];+ const clk: BalloonClock = { n: 0, sec: "", p: (kind, i, pts) => { marks[i] = { i, kind, sec: clk.sec, len: polyLen(pts), area: boxArea(pts) }; return 0; }, lay: () => 0 };+ drawBalloon(ctx, 0, env, clk);+ return marks;+};++// windows [t0, t1) per mark, one hand working through each phase in order; a long mark is fast+// per unit of length, and every lift of the crayon costs a beat of its own+type Plan = { full: Map<number, [number, number]>; lay: Map<number, [number, number]> };+const plan = (marks: Mark[]): Plan => {+ const full = new Map<number, [number, number]>(), lay = new Map<number, [number, number]>();+ const prio = (m: Mark) => (m.area > 400000 ? 9 : PRIO[m.sec] ?? 5); // the sky wash waits for everything else+ const cost = (m: Mark) => (m.kind === "line" ? Math.pow(m.len, 0.75) + 6 : Math.sqrt(m.area) * 0.9 + 14);+ const lay1 = (list: Mark[], [a, b]: [number, number], into: Map<number, [number, number]>) => {+ const sorted = [...list].sort((p, q) => prio(p) - prio(q) || p.i - q.i), tot = sorted.reduce((s, m) => s + cost(m), 0); let acc = 0;+ sorted.forEach((m) => { const t0 = a + ((b - a) * acc) / tot; acc += cost(m); into.set(m.i, [t0, a + ((b - a) * acc) / tot]); });+ };+ (["fill", "shade", "burnish", "line"] as CrayonKind[]).forEach((k) => lay1(marks.filter((m) => m && m.kind === k), PHASE[k], full));+ lay1(marks.filter((m) => m && m.kind === "line" && m.len >= 25), PHASE.lay, lay); // tiny flicks (grass, weave) get no lay-in+ return { full, lay };+};++const at = (w: [number, number] | undefined, f: number) => (w ? clamp((f - w[0]) / Math.max(1e-6, w[1] - w[0])) : 0);++export const balloonDraw: Film = {+ meta: { title: "Hot-air balloon · crayon, drawn on", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{+ id: "drawing", start: 0, end: N, draw: (ctx, f, env) => {+ if (f >= DONE) return drawBalloon(ctx, 0, env); // the plate itself: the still, exactly+ const key = "balloonDraw:plan:v1"; let P = env.cache.get(key) as Plan | undefined;+ if (!P) { P = plan(survey(ctx, env)); env.cache.set(key, P); } // a pure function of the plate; drawn over below+ const Q = P, clk: BalloonClock = { n: 0, sec: "", p: (_k, i) => at(Q.full.get(i), f), lay: (i) => at(Q.lay.get(i), f) };+ drawBalloon(ctx, 0, env, clk);+ },+ }],+};diff --git a/engine/src/canvas-core/bitRig.ts b/engine/src/canvas-core/bitRig.tsnew file mode 100644index 0000000..f8ffb09--- /dev/null+++ b/engine/src/canvas-core/bitRig.ts@@ -0,0 +1,257 @@+// BIT, RIGGED FOR THE WEB. The storybook plate's wind-up robot (storybook.ts, pencil + watercolour),+// cut into parts that are drawn ONCE by the plate's own code and then moved as sprites.+//+// legs + boots + ground hatch drawBit groups 0, 3-8 (boil variants)+// wind-up key drawBit groups 1-2 (8 turn phases)+// arms storybook limb() + hand() (ARM_CELS angles per side, on twos)+// body + collar drawBit groups 17-20 (boil variants)+// antenna, bulb, ears, head drawBit groups 22-25 (boil variants; tilts about the neck)+// blush drawBit group 26+// face re-inked here with the plate's pen, one cel per expression,+// because an interactive face needs expressions the still never drew+// glow live: one radial gradient, the only mark made per frame+//+// Nothing here knows about input. A piece turns InputState into a BitPose; the rig draws the pose.+import { GRAPHITE, TINT, arc, heart, line, oval, rng, turn, type Ctx, type Env, type Gfx, type P } from "./core";+import { bake, bakePart, blit, paperFactor, type Sprite } from "./bake";+import { SHADE, drawBit, hand, limb } from "./storybook";++// ---------------------------------------------------------------- placement: the plate's own+export const SHEET = 560;+const X = 272, Y = 492, S = 2.75 * (SHEET / 1080), SEED = 3;+const REST = { look: 0, tilt: 0, lean: 0, handL: [-80, -58] as P, handR: [94, -178] as P };+export const HIP: P = [0, -40], NECK: P = [0, -140], FACE: P = [0, -194], BULB: P = [39, -130 - 200];+export const toSheet = (p: P): P => [X + p[0] * S, Y + p[1] * S]; // Bit-local -> sheet (logical) px+export const BOIL = 2; // boil variants of the big outlines+export const KEY_PHASES = 8;+export const ARM_CELS = 16, ARM_MAX = 0.8; // arm lift u in [0, ARM_MAX]++// ---------------------------------------------------------------- affine, in device px+export type M = [number, number, number, number, number, number];+export const I: M = [1, 0, 0, 1, 0, 0];+export const mul = (m: M, n: M): M => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3], m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];+export const tr = (x: number, y: number): M => [1, 0, 0, 1, x, y];+export const about = (p: [number, number], deg: number, sx = 1, sy = 1): M => { const a = (deg * Math.PI) / 180, c = Math.cos(a), s = Math.sin(a); return mul(tr(p[0], p[1]), mul([c * sx, s * sx, -s * sy, c * sy, 0, 0], tr(-p[0], -p[1]))); };+export const apply = (m: M, p: [number, number]): [number, number] => [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]];+// draw a sprite through m: a pure translation stays on whole device pixels (crisp); anything else+// resamples. Rule 6: never enlarge a bitmap.+export const blitM = (ctx: Ctx, s: Sprite, m: M, alpha = 1) => {+ if (alpha <= 0) return;+ if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) return blit(ctx, s, m[4], m[5], alpha);+ if (Math.hypot(m[0], m[1]) > 1 + 1e-9 || Math.hypot(m[2], m[3]) > 1 + 1e-9) throw new Error("bitRig: a sprite may only be scaled down");+ ctx.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]); ctx.globalAlpha = alpha; ctx.drawImage(s.c, s.x, s.y); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1;+};++// ---------------------------------------------------------------- parts+const glowSprite = (env: Env) => bake(env, "bit:glow", (g) => { const c = toSheet(BULB), r = 46 * S * 1.2; g.group("plain", () => { g.touch(c[0] - r * 2, c[1] - r * 2, c[0] + r * 2, c[1] + r * 2); g.glow(c[0], c[1], r, TINT.glow, 1); }); });+const headLayer = (env: Env, w: number, h: number) => { const key = `bit:headLayer:${w}x${h}`; let L = env.cache.get(key) as ReturnType<Env["canvas"]> | undefined; if (!L) { L = env.canvas(w, h); env.cache.set(key, L); } return L; };+const dev = (env: Env, p: P): [number, number] => { const q = toSheet(p); return [q[0] * env.scale, q[1] * env.scale]; };+const part = (env: Env, name: string, groups: number[], v: number, frame = v * 4) => bakePart(env, `bit:${name}:${v}`, (i) => groups.includes(i), (g) => { g.push(X, Y, S); drawBit(g, frame, SEED, REST); g.pop(); }, { frame });+export const LEGS = [0, 3, 4, 5, 6, 7, 8], KEY = [1, 2], BODY = [17, 18, 19, 20], HEAD = [22, 23, 24, 25], BLUSH = [26];+const legs = (env: Env, v: number) => part(env, "legs", LEGS, v);+const body = (env: Env, v: number) => part(env, "body", BODY, v);+const head = (env: Env, v: number) => part(env, "head", HEAD, v);+const blush = (env: Env) => part(env, "blush", BLUSH, 0);+// keyTurn = |cos(frame * 0.22)| in the plate: phase i of 8 is frame i*pi/8/0.22+const key = (env: Env, i: number) => part(env, `key${i}`, KEY, 0, (i * Math.PI) / KEY_PHASES / 0.22);++// arms: the plate's limb() and hand(), at a lift u. Right shoulder is (50, -114); the left mirrors it.+const SHOULDER = (side: number): P => [side * 50, -114];+const armAngle = (u: number) => 62 - 177 * u; // degrees, right arm; 62 = hanging, -80 = up+const armLen = (u: number) => 64 + 12 * Math.min(1, u / 0.66);+export const handAt = (side: number, u: number): P => { const a = (armAngle(u) * Math.PI) / 180, L = armLen(u), s = SHOULDER(side); return [s[0] + side * Math.cos(a) * L, s[1] + Math.sin(a) * L]; };+export const armCel = (u: number) => Math.max(0, Math.min(ARM_CELS - 1, Math.round((u / ARM_MAX) * (ARM_CELS - 1))));+const arm = (env: Env, side: number, cel: number) => bake(env, `bit:arm:${side}:${cel}`, (g) => {+ const u = (cel / (ARM_CELS - 1)) * ARM_MAX, s = SHOULDER(side), h = handAt(side, u), bend = side * 14, mid = line(s, h, bend)[1];+ g.push(X, Y, S); limb(g, s, h, bend, 7.5, SEED + (side < 0 ? 40 : 50)); hand(g, h, Math.atan2(h[1] - mid[1], h[0] - mid[0]), u < 0.16 ? "rest" : "open", SEED + (side < 0 ? 60 : 80)); g.pop();+});++// the face, re-inked. Eye centres are fo + (+-31, 0|-1), the plate's gap; the pen and seeds are the plate's.+const GAP = 31, FS = SEED + 170;+const eyeC = (s: number): P => [FACE[0] + s * GAP, FACE[1] + (s > 0 ? -1 : 0)];+const face = (env: Env, name: string, draw: (g: Gfx) => void) => bake(env, `bit:face:${name}`, (g) => { g.push(X, Y, S); draw(g); g.pop(); });+const eye = (env: Env, s: number) => face(env, `eye${s}`, (g) => g.group("ink", () => {+ const c = eyeC(s), k = g.cur; g.touch(c[0] - 13, c[1] - 13, c[0] + 13, c[1] + 13);+ k.fillStyle = GRAPHITE; k.beginPath(); k.ellipse(c[0], c[1], 8.4, 10.8, 0, 0, Math.PI * 2); k.fill();+ k.fillStyle = "#fffaf3"; k.beginPath(); k.arc(c[0] - 2.6, c[1] - 3.8, 3.3, 0, Math.PI * 2); k.fill(); k.globalAlpha = 0.85; k.beginPath(); k.arc(c[0] + 2.8, c[1] + 3.6, 1.5, 0, Math.PI * 2); k.fill(); k.globalAlpha = 1;+}));+export type Eyes = "open" | "happy" | "shut" | "blink" | "squint";+const lids = (env: Env, kind: Exclude<Eyes, "open">, s: number) => face(env, `lid-${kind}${s}`, (g) => g.group("ink", () => {+ const [x, y] = eyeC(s), o = { w: 2.6, seed: FS + 40 + s, wobble: 0.3, boil: 0.25, taper: 0.5 };+ if (kind === "happy") g.pen(arc(x, y + 4, 9, 8, 1.1 * Math.PI, 1.9 * Math.PI, 6), o); // ^ ^+ if (kind === "blink") g.pen(arc(x, y - 3, 9, 4, 0.12 * Math.PI, 0.88 * Math.PI, 5), o); // a closed lid, lashes down+ if (kind === "shut") g.pen([[x - 8 * s, y - 7], [x + 5 * s, y], [x - 8 * s, y + 7]], { ...o, w: 2.9 }); // > < squeezed shut+ if (kind === "squint") g.pen(arc(x, y + 1, 9, 5, 1.08 * Math.PI, 1.92 * Math.PI, 5), { ...o, w: 3 });+}));+export type Brows = "neutral" | "up" | "worried" | "none";+const brow = (env: Env, kind: Exclude<Brows, "none">, s: number) => face(env, `brow-${kind}${s}`, (g) => g.group("ink", () => {+ const [x, y] = eyeC(s), lift = kind === "up" ? -6 : kind === "worried" ? -3 : 0, pts = arc(x, y - 13 + lift, 10, 6, 1.25 * Math.PI, 1.75 * Math.PI, 4);+ g.pen(kind === "worried" ? turn(pts, x, y - 13 + lift, s * 16) : pts, { w: 2.1, seed: FS + 14 + (s > 0 ? 1 : 0), wobble: 0.3, opacity: kind === "neutral" ? 0.55 : 0.75, retrace: false });+}));+export type Mouth = "smile" | "grin" | "o" | "wobble" | "flat";+const mouth = (env: Env, kind: Mouth) => face(env, `mouth-${kind}`, (g) => {+ const [x, y] = [FACE[0], FACE[1] + 20], o = { w: 2.9, seed: FS + 20, wobble: 0.3, boil: 0.3 };+ if (kind === "grin") {+ const lip: P[] = [[x - 13, y - 3], [x - 6, y - 4], [x, y - 4], [x + 6, y - 4], [x + 13, y - 3]], cup: P[] = [...lip, ...arc(x, y - 3, 13, 12, 0.05 * Math.PI, 0.95 * Math.PI, 9)];+ g.group("paint", () => { g.fill(cup, "#5b3a44", 0.92); g.wash(oval(x + 1, y + 5, 7, 4, 8), TINT.blush, { alpha: 0.9, seed: FS + 23, dx: 0, dy: 0, shrink: 1, rim: false }); });+ g.group("ink", () => g.pen(cup, { ...o, closed: true, w: 2.6, taper: 0.4 }));+ } else g.group("ink", () => {+ if (kind === "smile") g.pen(arc(x, y, 9, 8, 0.12 * Math.PI, 0.88 * Math.PI, 6), o);+ if (kind === "o") g.pen(oval(x, y + 3, 5.5, 6.5, 8), { ...o, closed: true, w: 2.6, taper: 0.4 });+ if (kind === "wobble") g.pen([[x - 10, y + 5], [x - 5, y + 2], [x, y + 5], [x + 5, y + 2], [x + 10, y + 5]], { ...o, w: 2.5 });+ if (kind === "flat") g.pen(line([x - 7, y + 4], [x + 7, y + 3], 0.5), o);+ });+});+const cheeks = (env: Env) => face(env, "cheeks", (g) => g.group("ink", () => [-1, 1].forEach((s) => { const c: P = [FACE[0] + s * (GAP + 22) - 7, FACE[1] + 17]; g.hatch(c[0], c[1], 13, { n: 3, len: 9, color: TINT.blush, pw: 2.6, opacity: 0.9, seed: FS + 30 + s }); })));+// the chest heart, re-inked 25% larger so a beat can shrink it back to the plate's size (never enlarge)+const HEART: P = [0, -86 - 13], BIG = 1.25;+const heartBig = (env: Env) => face(env, "heart", (g) => { g.group("paint", () => g.wash(heart(HEART[0], HEART[1], 10 * BIG), TINT.blush, { alpha: 0.95, seed: SEED + 102, dx: 0, dy: 0, shrink: 1, rim: false })); g.group("ink", () => g.pen(heart(HEART[0], HEART[1], 10 * BIG), { closed: true, w: 1.9 * BIG, color: "#c9566b", seed: SEED + 113, wobble: 0.3, taper: 0.4 })); });+// a pencil twinkle for celebrations: four strokes from a point and a dab of butter wash+export const twinkle = (env: Env, v: number) => bake(env, `bit:twinkle:${v}`, (g) => {+ const c: P = TWINKLE_AT(v); g.push(X, Y, S);+ g.group("paint", () => g.wash(oval(c[0], c[1], 11, 11, 7), TINT.butter, { alpha: 0.9, seed: 900 + v, dx: 0, dy: 0, shrink: 1, rim: false }));+ g.group("ink", () => [0, 1, 2, 3].forEach((i) => { const a = (i * Math.PI) / 2 + v * 0.4, r0 = 15, r1 = 34 + (i % 2) * 10; g.pen(line([c[0] + Math.cos(a) * r0, c[1] + Math.sin(a) * r0], [c[0] + Math.cos(a) * r1, c[1] + Math.sin(a) * r1]), { w: 3, seed: 910 + v * 4 + i, wobble: 0.3, retrace: false }); }));+ g.pop();+});+export const TWINKLE_AT = (v: number): P => [-140 + v * 60, -60]; /* baked on the sheet, then moved: a bake crops to the canvas */++// ---------------------------------------------------------------- the pose and the draw+export type BitPose = {+ off: P; // whole figure, local units (a jump is negative y)+ bob: number; // upper body only, local units (breathing)+ squash: number; // <= 1, vertical, about the feet+ lean: number; // degrees, upper body about the hips+ headOff: P; // local units, the head turning toward what it looks at+ tilt: number; // degrees, head about the neck+ look: P; // local units, eyes inside the face+ armL: number; armR: number; // lift, 0 hanging .. ARM_MAX+ eyes: Eyes; eyesR?: Eyes; // eyesR: the right eye, when it differs (a peek)+ blink: number; // 0 open .. 1 closed (open eyes only)+ brows: Brows; mouth: Mouth;+ blush: number; glow: number; heart: number; // heart: 0 rest .. 1 full beat+ key: number; // phase index (any integer)+ boil: number; // variant index (any integer)+ twinkles?: { at: P; k: number; a: number; v: number }[];+ faceFade?: number; // reduced motion: 0 = resting face .. 1 = this pose's face, crossfaded // sheet-local positions, 0.4 <= k <= 1 scale, alpha+};+export const restPose = (): BitPose => ({ off: [0, 0], bob: 0, squash: 1, lean: 0, headOff: [0, 0], tilt: 0, look: [0, 0], armL: 0, armR: 0, eyes: "open", blink: 0, brows: "neutral", mouth: "smile", blush: 0.8, glow: 1, heart: 0, key: 0, boil: 0 });++export const drawBit2 = (ctx: Ctx, env: Env, p: BitPose) => {+ const k = S * env.scale, v = ((p.boil % BOIL) + BOIL) % BOIL;+ const F = mul(tr(Math.round(p.off[0] * k), Math.round(p.off[1] * k)), about(dev(env, [0, 0]), 0, 1, p.squash));+ // lean is a whole-pixel shift of the upper body, not a rotation: crisp, and a rotated blit costs ~8x+ // an axis-aligned one on a software canvas. Only the head rotates (tilt), and only once: see below.+ const U = mul(F, tr(Math.round(p.lean * 1.2 * k), Math.round(p.bob * k))), H = mul(U, mul(tr(p.headOff[0] * k, p.headOff[1] * k), about(dev(env, NECK), p.tilt)));+ const snap = (m: M): M => (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 ? [1, 0, 0, 1, Math.round(m[4]), Math.round(m[5])] : m);+ blitM(ctx, legs(env, v), snap(F));+ blitM(ctx, key(env, ((p.key % KEY_PHASES) + KEY_PHASES) % KEY_PHASES), snap(U));+ blitM(ctx, arm(env, -1, armCel(p.armL)), snap(U)); blitM(ctx, arm(env, 1, armCel(p.armR)), snap(U));+ blitM(ctx, body(env, v), snap(U));+ if (p.heart > 0) { const c = dev(env, HEART), s = 1 / BIG + (1 - 1 / BIG) * Math.min(1, p.heart); blitM(ctx, heartBig(env), mul(U, about(c, 0, s, s))); }+ // the bulb's glow: the plate's radial falloff, the only thing drawn live+ // the bulb's glow: the plate's radial falloff, baked once at full strength, blitted with the pose's alpha+ const b = apply(H, dev(env, BULB)), op = Math.min(1, 0.56 * p.glow), gs = glowSprite(env);+ if (op > 0.01) blit(ctx, gs, Math.round(b[0] - (gs.x + gs.w / 2)), Math.round(b[1] - (gs.y + gs.h / 2)), op);+ // head and face are composed axis-aligned on one layer (in rest device coords), then that layer is+ // blitted through H once: one rotated blit instead of ten+ const hs = head(env, v), bx = hs.x - Math.round(12 * k), by = hs.y - Math.round(8 * k), bw = hs.w + Math.round(24 * k), bh = hs.h + Math.round(16 * k), HL = headLayer(env, bw, bh), outer = ctx;+ { const c = HL.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; c.clearRect(0, 0, bw, bh); }+ const hctx = HL.ctx as Ctx, B0 = tr(-bx, -by);+ blitM(hctx, hs, B0);+ // the face rides on the head, and slides a little toward what it looks at+ const Fc = snap(mul(B0, tr(p.look[0] * 0.45 * k, p.look[1] * 0.35 * k))), Fe = snap(mul(B0, tr(p.look[0] * k, p.look[1] * k)));+ const faceOf = (q: Pick<BitPose, "eyes" | "eyesR" | "blink" | "brows" | "mouth" | "blush">, al: number) => {+ if (al <= 0) return;+ blitM(hctx, blush(env), Fc, q.blush * al); if (q.blush > 0.9) blitM(hctx, cheeks(env), Fc, Math.min(1, (q.blush - 0.9) * 10) * al);+ [-1, 1].forEach((s) => {+ const e = s > 0 && q.eyesR ? q.eyesR : q.eyes;+ if (e === "open") { const bl = Math.max(0, Math.min(1, q.blink)); if (bl < 0.85) { const c = apply(Fe, dev(env, eyeC(s))); blitM(hctx, eye(env, s), mul(about(c, 0, 1, 1 - bl * 0.9), Fe), al); } else blitM(hctx, lids(env, "blink", s), Fc, al); }+ else blitM(hctx, lids(env, e, s), Fc, al);+ if (q.brows !== "none") blitM(hctx, brow(env, q.brows, s), Fc, al);+ });+ blitM(hctx, mouth(env, q.mouth), Fc, al);+ };+ // reduced motion: an expression change is a short crossfade from the resting face, never a movement+ if (p.faceFade !== undefined) { const a = Math.max(0, Math.min(1, p.faceFade)); faceOf({ eyes: "open", blink: 0, brows: "neutral", mouth: "smile", blush: 0.8 }, 1 - a); faceOf(p, a); }+ else faceOf(p, 1);+ blitM(outer, { c: HL.canvas as CanvasImageSource, x: bx, y: by, w: bw, h: bh }, snap(H));+ (p.twinkles ?? []).forEach((t) => { const tv = t.v % 3, c = dev(env, TWINKLE_AT(tv)); blitM(ctx, twinkle(env, tv), mul(tr(t.at[0] * env.scale - c[0], t.at[1] * env.scale - c[1]), about(c, t.v * 17, t.k, t.k)), t.a); });+};++// Everything the rig can ever blit, in the order a first frame needs it: rest first, cels after.+export function* bakeBit(env: Env): Generator<string> {+ yield "legs"; legs(env, 0); yield "key"; key(env, 0); yield "arms"; arm(env, -1, 0); arm(env, 1, 0); yield "body"; body(env, 0); yield "head"; head(env, 0);+ yield "face"; blush(env); cheeks(env); [-1, 1].forEach((s) => { eye(env, s); brow(env, "neutral", s); }); mouth(env, "smile");+ for (let v = 1; v < BOIL; v++) { yield `boil${v}`; legs(env, v); body(env, v); head(env, v); }+ for (let i = 1; i < KEY_PHASES; i++) { yield `key${i}`; key(env, i); }+ for (let c = 1; c < ARM_CELS; c++) { yield `arm${c}`; arm(env, -1, c); arm(env, 1, c); }+ yield "expressions";+ [-1, 1].forEach((s) => { (["happy", "blink", "shut", "squint"] as const).forEach((l) => lids(env, l, s)); (["up", "worried"] as const).forEach((b) => brow(env, b, s)); });+ (["grin", "o", "wobble", "flat"] as const).forEach((m) => mouth(env, m)); heartBig(env); [0, 1, 2].forEach((v) => twinkle(env, v));+}++// ---------------------------------------------------------------- the meadow, re-authored from drawStorybook without Bit+// (drawStorybook builds its own Gfx, so its scene cannot be filtered; these are its calls, same seeds)+export const meadow = (g: Gfx, o: { flowers?: boolean; underdrawing?: boolean; splatter?: boolean; vignette?: boolean; base?: boolean } = {}) => {+ const ctx = g.main, env = g.env;+ if (o.base !== false) { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = "#fbf6ea"; ctx.fillRect(0, 0, env.W, env.H); }+ g.group("paint", () => {+ g.wash([[40, 46], [170, 36], [300, 42], [430, 34], [522, 44], [528, 170], [520, 300], [526, 430], [518, 488], [400, 480], [280, 490], [150, 482], [42, 490], [34, 380], [42, 250], [36, 130]], "#f3d9b4", { alpha: 0.62, seed: 2 });+ g.wash(oval(170, 150, 150, 105, 9), "#a9cdea", { alpha: 0.24, seed: 3 }); g.wash(oval(420, 330, 120, 150, 9), "#f2b9a0", { alpha: 0.26, seed: 4 }); g.wash(oval(318, 96, 80, 70, 8), TINT.glow, { alpha: 0.5, seed: 5 });+ g.wash([[34, 470], [150, 452], [300, 460], [430, 450], [530, 466], [524, 530], [300, 538], [44, 530]], "#9cc79a", { alpha: 0.62, seed: 6 }); g.wash([[60, 486], [200, 474], [330, 480], [330, 500], [190, 506], [70, 504]], "#6fa874", { alpha: 0.35, seed: 7 });+ g.wash(oval(292, 494, 124, 13, 10), "#7d6fa8", { alpha: 0.42, seed: 8 });+ });+ g.group("ink", () => {+ const U = "#8d90a6";+ if (o.underdrawing !== false) { g.pen(turn(oval(300, 214, 128, 104, 12), 300, 214, 6), { closed: true, w: 1.4, color: U, seed: 9, opacity: 0.45, wobble: 2 }); g.pen(oval(292, 392, 86, 92, 10), { closed: true, w: 1.4, color: U, seed: 10, opacity: 0.42, wobble: 2 }); g.pen([[318, 96], [300, 214], [288, 400], [286, 500]], { w: 1.3, color: U, seed: 11, opacity: 0.42 }); g.pen([[170, 232], [300, 214], [432, 196]], { w: 1.3, color: U, seed: 12, opacity: 0.4 }); }+ g.pen([[36, 470], [150, 454], [300, 461], [430, 452], [530, 468]], { w: 2, seed: 13, opacity: 0.55 });+ [[66, 0], [84, 1], [104, 0], [128, 1], [430, 0], [452, 1], [474, 0], [500, 1]].forEach(([x, k], i) => g.pen([[x, 472], [x + (k ? 5 : -4), 456 - (i % 3) * 4], [x + (k ? 9 : -8), 444 - (i % 3) * 5]], { w: 1.9, color: "#5f8f62", seed: 20 + i, retrace: false }));+ [[176, 512, 9, 5], [396, 516, 11, 6], [232, 524, 6, 4]].forEach(([x, y, a, b], i) => g.pen(oval(x, y, a, b, 7), { closed: true, w: 1.6, seed: 40 + i, opacity: 0.6 }));+ });+ if (o.flowers !== false) ([[64, 440, "#f2899c", 50], [488, 430, "#c7b3e0", 60], [446, 452, "#f5b98a", 70], [98, 462, "#f3d577", 80]] as [number, number, string, number][]).forEach(([x, y, c, seed]) => {+ g.group("paint", () => { const flat = { dx: 3, dy: 2, shrink: 0.94, rim: true }; [0, 1, 2, 3, 4].forEach((i) => g.wash(oval(x + Math.cos(i * 1.256 + 0.4) * 9, y + Math.sin(i * 1.256 + 0.4) * 9, 7.5, 7.5, 6), c, { alpha: 0.85, seed: seed + i, ...flat })); g.wash(oval(x, y, 3.4, 3.4, 5), TINT.butter, { alpha: 0.95, seed: seed + 6, ...flat }); });+ g.group("ink", () => { g.pen([[x, y + 9], [x + 2, y + 24], [x - 1, y + 40]], { w: 1.8, color: "#6f9b6a", seed: seed + 7, retrace: false }); g.pen(oval(x, y, 16, 16, 9), { closed: true, w: 1.5, seed: seed + 8, opacity: 0.6, wobble: 2 }); });+ });+ if ((o.splatter ?? o.flowers) !== false) splatter(g);+ if (o.vignette !== false) g.vignette("rgba(90,50,50,0.11)");+};+// paint flicked off the brush (drawStorybook draws it last, over Bit)+export const splatter = (g: Gfx) => g.group("paint", () => { const c = g.cur; ([[5, 26, [50, 60, 510, 470], "#e9a887", 3], [8, 12, [60, 380, 500, 520], "#6fa874", 2.6]] as [number, number, number[], string, number][]).forEach(([sd, n, box, col, rmax]) => { const r = rng(sd); for (let i = 0; i < n; i++) { const x = box[0] + r() * (box[2] - box[0]), y = box[1] + r() * (box[3] - box[1]), k = r(); g.touch(x - 5, y - 5, x + 5, y + 5); c.globalAlpha = 0.5 * (0.5 + r() * 0.5); c.fillStyle = col; c.beginPath(); c.arc(x, y, 0.5 + k * k * rmax, 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; }); });+export const SHADES = SHADE;++// ---------------------------------------------------------------- shared behaviour, for any piece that uses Bit+export const LOOP = 480; // 8 s; every idle period below divides it+const tri = (u: number) => (u < 0.5 ? u * 2 : 2 - u * 2);+export const FACE_SHEET = toSheet(FACE);+export const S_LOCAL = S;+// breathing, blinking, the key turning, the line boiling, the bulb pulsing: never a dead second+export const idle = (p: BitPose, t: number) => {+ const lt = t % LOOP;+ p.key = Math.floor(t / 4); p.boil = Math.floor(t / 8); p.bob = -1.2 * Math.sin((2 * Math.PI * t) / 120);+ p.glow = 1 + 0.25 * Math.sin((2 * Math.PI * t) / 60);+ const b = lt >= 100 && lt < 108 ? (lt - 100) / 8 : lt >= 330 && lt < 338 ? (lt - 330) / 8 : -1; if (b >= 0) p.blink = tri(b);+};+// eyes and head toward two sprung points in sheet px+export const attend = (p: BitPose, look: P, head: P) => {+ const gz = gazeAt(FACE_SHEET, look, 6 * S, 160), hg = gazeAt(FACE_SHEET, head, 1, 260);+ p.look = [gz[0] / S, Math.max(-4, Math.min(4, gz[1] / S))]; p.headOff = [hg[0] * 5, hg[1] * 3]; p.tilt = hg[0] * 4; p.lean = hg[0] * 2;+};+const gazeAt = (eye: P, at: P, reach: number, near: number): P => { const dx = at[0] - eye[0], dy = at[1] - eye[1], d = Math.hypot(dx, dy); if (d < 1e-6) return [0, 0]; const k = reach * Math.tanh(d / near); return [(dx / d) * k, (dy / d) * k]; };+// the cheer: 72 ticks. Wind-up crouch, a jump, both arms up and waving, twinkles, a landing squash.+export const CHEER = 72;+export const cheer = (p: BitPose, f: number, seed: number, reduced: boolean) => {+ p.eyes = "happy"; p.mouth = "grin"; p.brows = "up"; p.blush = 1; p.heart = tri((f % 18) / 18);+ if (reduced) return;+ p.squash = f < 6 ? 1 - 0.05 * (f / 6) : f >= 30 && f < 38 ? 1 - 0.05 * tri((f - 30) / 8) : 1;+ if (f >= 6 && f < 30) p.off = [0, -24 * Math.sin((Math.PI * (f - 6)) / 24)];+ p.armL = Math.min(ARM_MAX, 0.6 + 0.07 * Math.sin((2 * Math.PI * f) / 12)); p.armR = Math.min(ARM_MAX, 0.6 + 0.07 * Math.sin((2 * Math.PI * (f + 3)) / 12));+ p.key += f; p.look = [0, -2]; p.headOff = [0, -2]; p.tilt = 0; p.lean = 0;+ const r = rng(seed); p.twinkles = [];+ for (let i = 0; i < 7; i++) { const side = i % 2 ? 1 : -1, ang = -Math.PI * (0.5 + side * (0.12 + 0.36 * r())), dist = 175 + r() * 60, f0 = 6 + i * 3, u = f - f0; if (u < 0) continue; const at: P = [FACE_SHEET[0] + Math.cos(ang) * dist, FACE_SHEET[1] + 60 + Math.sin(ang) * dist * 0.8]; /* either side of him, never over his face */ p.twinkles.push({ at, k: Math.min(1, 0.45 + u / 10), a: Math.max(0, Math.min(1, (CHEER - f) / 14)), v: i }); }+};++// the meadow and the sheet, baked once per scale+export const meadowSprite = (env: Env, o: Parameters<typeof meadow>[1] = {}) => bake(env, `meadow:${o.flowers !== false}:${o.underdrawing !== false}`, (g) => meadow(g, o), { full: true });+export const sheetSprite = (env: Env) => paperFactor(env, [["paper", 0.13], ["coldpress", 0.2]]);+export const SHEETS: [string, number][] = [["paper", 0.13], ["coldpress", 0.2]];+diff --git a/engine/src/canvas-core/blueprint.ts b/engine/src/canvas-core/blueprint.tsnew file mode 100644index 0000000..1a6b682--- /dev/null+++ b/engine/src/canvas-core/blueprint.ts@@ -0,0 +1,393 @@+import { type Ctx, type Env, Gfx, type P, sample } from "./core";+import type { Film } from "./film";+import { CYAN, DIM, DRAFT, GROUND, type Kit, WHITE, blit, border, cut, kit, sheet, slot, stagger, tooth } from "./blueprintKit";++// GOING TRAIN · cyanotype drafting sheet.+//+// MEDIUM, physically: a ruling pen and a spring-bow compass loaded with white ink (a white-print+// is the negative of a cyanotype: the draftsman's black line exposes as white on Prussian blue),+// on a sheet of blueprint stock that never exposed evenly (brighter where the arc lamp stood,+// mottled, two old fold lines, dust). The ink sits on the tooth of the sheet and breaks up on it,+// and white on blue always blooms a little, so every line has a faint halo.+// MARKS: ruled lines that are never dead straight, compass circles that are (the compass does+// not wobble, the freehand does), chain lines (long dash, short dash) for centres and pitch+// circles, section lining at 45 degrees that starts and stops just inside each part, arrowheads+// filled in, figures and notes in single-stroke inclined gothic capitals (drafting.ts).+// EDGE: a thin even pen line with a slight taper where the nib lifts; no tone except section+// lining and the solid fill a thin section gets by convention.+// LINE HIERARCHY: visible outlines heavy white; section lining, pitch circles, dimensions and+// leaders thin cyan; construction and projection lines thinner, dim, left on the sheet as real+// drafting leaves them.+// ORDER OF MARKS (the film): bare sheet; the border is ruled and zone-marked; the title block box+// ruled; construction (centre lines, pitch circles swung, projection lines dropped to where the+// section will go); ruling-pen outlines, the plate first, then each wheel from the top of the+// stack down, rim and teeth first and the crossings outside-in, each pinion before the wheel it+// sits on; the section outlines; section lining; the detail; dimensions (witness lines, the+// dimension line, arrows, figure); the train table; notes and balloons; the title block lettered+// last and the drawing's title the very last thing written.+// PALETTE: Prussian ground #123a63, white ink #f1f7fb, cyan #a7d8ec, dim cyan #7fbcd8.+// LIGHT: none. An orthographic engineering drawing has no light source and no cast shadow; its+// tone is section lining and nothing else, and that is the honest version of this medium.+// SUBJECT and REALISM: the going train of a small watch movement, top plate removed. A real+// train: centre wheel 64 T drives the third pinion of 8 leaves, third wheel 60 T drives the+// fourth pinion of 8, fourth wheel 60 T drives the escape pinion of 7, escape wheel 15 club+// teeth. 64/8 x 60/8 = 60, so the fourth wheel turns once a minute (the seconds arbor), which is+// the arithmetic every going train is designed around. Centre distance of every mesh = wheel+// pitch radius + pinion pitch radius (module x (Z1 + Z2) / 2), and that is how the arbors are+// placed. Wheels are crossed out (5 curved arms, 4 on the small wheels), pinions have deep roots+// and rounded (ogival) leaf tips, wheel teeth ogival, club teeth with the impulse face on the+// club. Section A-A is a stepped section through the pillars and the four arbors, projected+// straight down: plates and bushes section-lined in opposing directions, thin wheels solid (the+// convention for thin sections), arbors and pinions not sectioned (the convention for shafts),+// pivots running into bushes with oil sinks on the outer faces, the centre arbor running on+// through the pillar plate to the motion work.+// REFERENCE (from knowledge): the plan and section plates of watchmaking textbooks (Daniels,+// "Watchmaking"; de Carle, "Practical Watch Repairing"), the BS 308 / ISO 128 conventions for+// sections, chain lines and dimensioning, and a Swiss school drawing of a going train. The+// sheet's hand is ported from the worked film's PLATE I (example/, butterfly/kit.ts + parts.ts).++const N = 540, HOLD = 30;+// ---------------------------------------------------------------- THE CUE TABLE (frames)+// Every frame number in the film is here and nowhere else. Parts run one after another, as one+// hand does them; a part is 0 before its start and exactly 1 from its end.+const CUES: [string, number, number][] = [+ ["border", 0, 50], /* the sheet is ruled stroke by stroke, then zone-marked */+ ["titleBox", 50, 80], /* the title block is ruled early; it is lettered last */+ ["construct", 80, 150], /* centre lines, pitch circles swung, projection lines dropped */+ ["plate", 150, 175], /* the pillar plate's edge and its four pillars */+ ["w0", 175, 205], /* centre wheel, the top of the stack */+ ["p1", 205, 215], ["w1", 215, 240], /* third pinion, then the third wheel under it */+ ["p2", 240, 250], ["w2", 250, 270], /* fourth pinion, fourth wheel */+ ["p3", 270, 280], ["w3", 280, 300], /* escape pinion, escape wheel */+ ["section", 300, 345], /* section A-A outlines */+ ["lining", 345, 375], /* section lining */+ ["detail", 375, 395], /* detail C, the club tooth */+ ["detailD", 395, 410], /* detail D, the depthing of the first mesh */+ ["dims", 410, 440], /* dimensions and the cutting plane */+ ["table", 440, 465], /* the train table */+ ["notes", 465, 490], /* balloons, callouts, notes */+ ["title", 490, 510], /* the title block lettering; the title itself is the last word */+];+{ let t = 0; for (const [id, a, b] of CUES) { if (a % 5 || b % 5) throw new Error(`blueprint: cue ${id} off the 5-frame grid`); if (a < t) throw new Error(`blueprint: cue ${id} overlaps the one before`); t = b; } if (t > N - HOLD) throw new Error("blueprint: the hold is shorter than 30 frames"); if (N % 15) throw new Error("blueprint: duration off the beat"); }++// ---------------------------------------------------------------- the train (design units; 20 units = 1 mm)+const S = 1.22, OX = 248, OY = 268; // plan placement on the sheet+const PL = (x: number, y: number): P => [OX + x * S, OY + y * S];+const pol = (c: P, r: number, a: number): P => [c[0] + Math.cos(a) * r, c[1] + Math.sin(a) * r];+const deg = Math.PI / 180;+const M1 = 3.2, M2 = 3.2, M3 = 2.4; // modules of the three meshes (0.16, 0.16, 0.12 mm)+const Z = { w0: 64, p1: 8, w1: 60, p2: 8, w2: 60, p3: 7, w3: 15 };+const D01 = (M1 * (Z.w0 + Z.p1)) / 2, D12 = (M2 * (Z.w1 + Z.p2)) / 2, D23 = (M3 * (Z.w2 + Z.p3)) / 2;+const A0: P = [0, 0], A1 = pol(A0, D01, -18 * deg), A2 = pol(A1, D12, 22 * deg), A3 = pol(A2, D23, -25 * deg);+const ARB = [A0, A1, A2, A3];+const R_ESC = 40; // escape wheel tip radius+const PILLARS: P[] = [[-135, 40], [-95, -108], [232, 104], [338, 14]];+const CUTL = PILLARS[0], CUTR = PILLARS[3]; // the stepped cutting plane runs pillar, four arbors, pillar+const OUTLINE: P[] = [[-158, 48], [-152, -40], [-122, -112], [-52, -148], [40, -160], [120, -168], [205, -140], [292, -86], [352, -48], [368, 18], [338, 78], [262, 126], [160, 122], [60, 126], [-40, 124], [-118, 104]];++// ---------------------------------------------------------------- tooth forms (display coordinates)+// wheel: radial flanks from a deep root, ogival addendum; pinion: deep root, rounded leaves+const toothed = (c: P, n: number, R: number, add: number, ded: number, half: number, ph: number, parallel = false): P[] => {+ const out: P[] = [], fl = (r: number) => (parallel ? (half * R) / r : half); /* a pinion leaf has PARALLEL flanks; a wheel tooth's flanks are radial */+ for (let i = 0; i < n; i++) {+ const t = ph + (i / n) * Math.PI * 2, g = Math.PI / n, rr = R - ded, rf = R - add * 0.1;+ ([[rr, -fl(rr) * 1.02], [rf, -fl(rf)], [R + add * 0.55, -half * 0.82], [R + add * 0.9, -half * 0.46], [R + add, 0], [R + add * 0.9, half * 0.46], [R + add * 0.55, half * 0.82], [rf, fl(rf)], [rr, fl(rr) * 1.02], [rr * 0.985, g]] as [number, number][]).forEach(([r, a]) => out.push(pol(c, r * S, t + a)));+ }+ return out;+};+const wheelTeeth = (c: P, n: number, m: number, ph: number) => toothed(PL(...c), n, (m * n) / 2, 1.35 * m, 1.55 * m, (Math.PI / n) * 0.5, ph);+const pinionLeaves = (c: P, n: number, m: number, ph: number) => toothed(PL(...c), n, (m * n) / 2, 0.85 * m, 1.9 * m, (Math.PI / n) * 0.34, ph, true);+// club teeth: the back rises to the locking corner, the club carries the impulse face, the front drops to the root+// a Swiss club tooth, [radius / tip radius, fraction of the tooth pitch]: slim stem, heel, impulse face+// rising across the club to the locking corner, locking face raked back about 24 degrees (draw)+export const CLUB: [number, number][] = [[0.64, 0.12], [0.72, 0.2], [0.8, 0.25], [0.87, 0.28], [0.935, 0.3], [0.97, 0.48], [1, 0.66], [0.95, 0.6], [0.9, 0.545], [0.84, 0.52], [0.76, 0.52], [0.68, 0.55], [0.64, 0.6], [0.62, 0.75], [0.615, 0.9], [0.62, 1.0], [0.64, 1.12]];+const HEEL = 4, CORNER = 6, FACE = 8; // indices in CLUB where the straight faces start and stop+// club teeth: a slender back rising to the heel, the impulse face across the club to the locking+// corner, the locking face undercut back down, the front flank to a wide root+const clubTeeth = (c0: P, ph: number): P[] => {+ const c = PL(...c0), out: P[] = [], R = R_ESC, st = (Math.PI * 2) / Z.w3;+ for (let i = 0; i < Z.w3; i++) { const t = ph + i * st; CLUB.slice(0, 16).forEach(([r, a]) => out.push(pol(c, r * R * S, t + a * st))); }+ return out;+};+// the crossings: windows between the arms, bounded by the rim, the hub and each arm's edges+const windows = (c0: P, Ri: number, Rh: number, arms: number, twist: number, armW: number, ph: number): P[][] => {+ const c = PL(...c0), out: P[][] = [];+ for (let k = 0; k < arms; k++) {+ const a0 = ph + (k / arms) * Math.PI * 2, a1 = ph + ((k + 1) / arms) * Math.PI * 2, tw = (r: number) => twist * ((r - Rh) / (Ri - Rh)) ** 1.3;+ const L = (r: number) => a0 + armW / 2 / r + tw(r), R = (r: number) => a1 - armW / 2 / r + tw(r), pts: P[] = [], n = 6;+ for (let j = 0; j <= n; j++) { const r = Rh + ((Ri - Rh) * j) / n; pts.push(pol(c, r * S, L(r))); }+ for (let j = 1; j < 9; j++) { const a = L(Ri) + ((R(Ri) - L(Ri)) * j) / 9; pts.push(pol(c, Ri * S, a)); }+ for (let j = n; j >= 0; j--) { const r = Rh + ((Ri - Rh) * j) / n; pts.push(pol(c, r * S, R(r))); }+ for (let j = 8; j > 0; j--) { const a = L(Rh) + ((R(Rh) - L(Rh)) * j) / 9; pts.push(pol(c, Rh * S, a)); }+ out.push(pts);+ }+ return out;+};+type Wheel = { c: P; teeth: P[]; win: P[][]; hub: number; arbor: number; R: number };+const WHEELS: Wheel[] = [+ { c: A0, teeth: wheelTeeth(A0, Z.w0, M1, -18 * deg), win: windows(A0, (M1 * Z.w0) / 2 - 1.55 * M1 - 9, 21, 5, 0.34, 7, 0.3), hub: 21, arbor: 4.5, R: (M1 * Z.w0) / 2 },+ { c: A1, teeth: wheelTeeth(A1, Z.w1, M2, 22 * deg), win: windows(A1, (M2 * Z.w1) / 2 - 1.55 * M2 - 8.5, 19, 5, 0.34, 6.5, 0.9), hub: 19, arbor: 4, R: (M2 * Z.w1) / 2 },+ { c: A2, teeth: wheelTeeth(A2, Z.w2, M3, -25 * deg), win: windows(A2, (M3 * Z.w2) / 2 - 1.55 * M3 - 7, 15, 4, 0.3, 5.5, 0.5), hub: 15, arbor: 3.5, R: (M3 * Z.w2) / 2 },+ { c: A3, teeth: clubTeeth(A3, 0.1), win: windows(A3, R_ESC * 0.7 - 5, 9, 4, 0, 4, 0.2), hub: 9, arbor: 3, R: R_ESC },+];+const PINIONS = [null, { c: A1, pts: pinionLeaves(A1, Z.p1, M1, (162 - 180 / Z.p1) * deg), r: (M1 * Z.p1) / 2 }, { c: A2, pts: pinionLeaves(A2, Z.p2, M2, (202 - 180 / Z.p2) * deg), r: (M2 * Z.p2) / 2 }, { c: A3, pts: pinionLeaves(A3, Z.p3, M3, (155 - 180 / Z.p3) * deg), r: (M3 * Z.p3) / 2 }];++// a wheel lower in the stack is hidden under the METAL of every wheel above it, never under its+// crossings: the clip is the sheet minus each upper wheel's outline plus its windows (even-odd)+const hideUnder = (c: Ctx, above: { teeth: P[]; win: P[][] }[]) => above.forEach((w) => { c.beginPath(); c.rect(-10, -10, 2000, 2000); [w.teeth, ...w.win].forEach((pts) => { pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }); c.clip("evenodd"); });++// ---------------------------------------------------------------- the section A-A+const SY0 = 500; // the top face of the top plate+const SX = (x: number) => OX + x * S, SZ = (z: number) => SY0 + z * S;+const TP = 12, GAP = 96, BP = 12; // top plate, frame height, pillar plate (design)+const Z_WHEEL = [24, 46, 70, 92], PIN_Z: ([number, number] | null)[] = [[80, 100], [18, 32], [40, 54], [64, 78]]; // wheel planes; each arbor's pinion span+const X0 = -150, X1 = 356; // where the cut leaves the plate outline+const rect = (x0: number, z0: number, x1: number, z1: number): P[] => [[SX(x0), SZ(z0)], [SX(x1), SZ(z0)], [SX(x1), SZ(z1)], [SX(x0), SZ(z1)]];+const BUSH = 6.5, PIV = 1.4; // bush half-width, pivot half-width (design)++// ---------------------------------------------------------------- the parts, each drawn at a progress+const rule = (k: Kit, pts: P[], w: number, seed: number, q: number, o: { color?: string; opacity?: number } = {}) => { const n = pts.length, st = stagger(q, n, Math.min(1, 1.6 / n)); pts.forEach((a, i) => k.ln(a, pts[(i + 1) % n], w, { seed: seed + i, taper: 0.15, progress: st(i), ...o })); };++const titleBox = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const x0 = 650, x1 = 1026, y0 = 890, y1 = 1026, bq = cut(q, 0, 0.6), lq = cut(q, 0.5, 1);+ [[0, 2.6], [5, 1.1]].forEach(([m, w], j) => rule(k, [[x0 + m, y0 + m], [x1 - m, y0 + m], [x1 - m, y1 - m], [x0 + m, y1 - m]], w, 800 + j * 4, stagger(bq, 2, 0.8)(j)));+ k.ln([x0 + 5, y0 + 62], [x1 - 5, y0 + 62], 1.2, { seed: 812, progress: cut(lq, 0, 0.5) }); k.ln([x0 + 5, y0 + 99], [x1 - 5, y0 + 99], 1, { seed: 813, color: CYAN, progress: cut(lq, 0.3, 0.8) }); [x0 + 128, x0 + 252].forEach((x, i) => k.ln([x, y0 + 62], [x, y1 - 5], 1, { seed: 814 + i, color: CYAN, progress: cut(lq, 0.5, 1) }));+}); };++const construct = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const s = stagger(q, 4, 0.4), o = { color: DIM, opacity: 0.85 };+ // 1. centre lines through every arbor, and the line of centres+ const c1 = s(0), cs = stagger(c1, 4, 0.55);+ ARB.forEach((a, i) => { const p = PL(...a), L = (WHEELS[i].R + 12) * S; k.chain([p[0] - L, p[1]], [p[0] + L, p[1]], 0.75, { ...o, seed: 1000 + i * 4, progress: cut(cs(i), 0, 0.5) }); k.chain([p[0], p[1] - L], [p[0], p[1] + L], 0.75, { ...o, seed: 1002 + i * 4, progress: cut(cs(i), 0.5, 1) }); });+ // 2. the line of centres, then the pitch circles swung on it (a mesh is two pitch circles touching)+ const c2 = s(1); [0, 1, 2].forEach((i) => k.ln(PL(...ARB[i]), PL(...ARB[i + 1]), 0.7, { ...o, opacity: 0.55, seed: 1020 + i, progress: stagger(cut(c2, 0, 0.3), 3, 0.5)(i) }));+ const ps = stagger(cut(c2, 0.25, 1), 7, 0.35), pr: [P, number][] = [[A0, (M1 * Z.w0) / 2], [A1, (M1 * Z.p1) / 2], [A1, (M2 * Z.w1) / 2], [A2, (M2 * Z.p2) / 2], [A2, (M3 * Z.w2) / 2], [A3, (M3 * Z.p3) / 2], [A3, R_ESC * 0.92]];+ pr.forEach(([c, r], i) => { const p = PL(...c); k.chainRing(p[0], p[1], r * S, 0.75, { color: CYAN, opacity: 0.6, seed: 1040 + i * 40, progress: ps(i), a0: -2.4 + i }); });+ // 3. projection lines dropped from the plan to where the section will stand+ const c3 = s(2); [CUTL, ...ARB, CUTR].forEach((a, i) => { const p = PL(...a); k.ln([p[0], p[1] + 6], [p[0], SZ(-6)], 0.6, { ...o, opacity: 0.45, seed: 1080 + i, progress: stagger(c3, 6, 0.5)(i) }); });+ // 4. the section's datum lines: the plate faces, projected across+ const c4 = s(3); [0, TP, TP + GAP, TP + GAP + BP].forEach((z, i) => k.ln([SX(X0 - 20), SZ(z)], [SX(X1 + 20), SZ(z)], 0.6, { ...o, opacity: 0.45, seed: 1090 + i, progress: stagger(c4, 4, 0.55)(i) }));+}); };++const pillarPlan = (k: Kit, c0: P, seed: number, q: number) => { const c = PL(...c0); k.circle(c[0], c[1], 9 * S, 1.5, { seed, progress: cut(q, 0, 0.45), a0: seed }); k.circle(c[0], c[1], 5.2 * S, 1.1, { seed: seed + 1, progress: cut(q, 0.4, 0.75), a0: seed + 2 }); const sq = cut(q, 0.7, 1), a = 0.6 + seed * 0.3; k.ln(pol(c, 5.2 * S, a), pol(c, 5.2 * S, a + Math.PI), 1.3, { seed: seed + 2, progress: sq }); };+const plate = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const pq = cut(q, 0, 0.55), o = k.g.cur; void o;+ k.pen(OUTLINE.map(([x, y]) => PL(x, y)), 1.9, { seed: 1100, closed: true, wobble: 0.3, taper: 0.2, progress: pq });+ const st = stagger(cut(q, 0.5, 1), 4, 0.45); PILLARS.forEach((p, i) => pillarPlan(k, p, 1110 + i * 5, st(i)));+}); };++const wheelPart = (k: Kit, i: number, q: number) => { if (q <= 0) return; k.ink(() => {+ const w = WHEELS[i], c = k.raw(), above = [...WHEELS.slice(0, i).map((u) => ({ teeth: u.teeth, win: u.win })), ...PINIONS.slice(1, i + 1).filter((p) => p).map((p) => ({ teeth: p!.pts, win: [] }))];+ c.save(); hideUnder(c, above); const p = PL(...w.c); k.g.touch(p[0] - w.R * S - 8, p[1] - w.R * S - 8, p[0] + w.R * S + 8, p[1] + w.R * S + 8);+ k.pen(w.teeth, i === 3 ? 1.5 : 1.45, { seed: 1200 + i * 50, closed: true, wobble: 0.05, taper: 0.1, progress: cut(q, 0, 0.45) }); /* rim and teeth first, round the wheel in one go */+ const ws = stagger(cut(q, 0.4, PINIONS[i] ? 1 : 0.9), w.win.length, 0.45); /* with a pinion over the hub, the last window is the last thing seen */ w.win.forEach((pts, j) => k.pen(pts, 1.45, { seed: 1210 + i * 50 + j, closed: true, wobble: 0.1, taper: 0.1, progress: ws(j) })); /* the crossings, window by window */+ const hq = cut(q, 0.85, 1); if (!PINIONS[i]) k.circle(p[0], p[1], w.hub * 0.72 * S, 1.3, { seed: 1230 + i, progress: hq }); k.circle(p[0], p[1], w.arbor * S, 1.2, { seed: 1231 + i, progress: hq, a0: 1 }); if (!PINIONS[i]) k.circle(p[0], p[1], 1.6 * S, 1, { seed: 1232 + i, progress: hq });+ c.restore();+}); };+const pinionPart = (k: Kit, i: number, q: number) => { if (q <= 0) return; const pn = PINIONS[i]!; k.ink(() => {+ const c = k.raw(), p = PL(...pn.c); c.save(); hideUnder(c, WHEELS.slice(0, i - 1).map((u) => ({ teeth: u.teeth, win: u.win }))); k.g.touch(p[0] - 30, p[1] - 30, p[0] + 30, p[1] + 30);+ k.pen(pn.pts, 1.2, { seed: 1300 + i * 10, closed: true, wobble: 0.04, taper: 0.1, progress: cut(q, 0, 0.75) });+ k.circle(p[0], p[1], 2.2 * S, 1.1, { seed: 1305 + i, progress: cut(q, 0.7, 1) }); /* the pivot, seen end on */+ c.restore();+}); };++// SECTION A-A: outlines+const sectionOut = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const s = stagger(q, 6, 0.3);+ // plates: each face ruled across, ends closed+ const pq = s(0); rule(k, rect(X0, 0, X1, TP), 1.8, 1400, cut(pq, 0, 0.5)); rule(k, rect(X0, TP + GAP, X1, TP + GAP + BP), 1.8, 1410, cut(pq, 0.5, 1));+ // bushes through both plates, with their pivot holes and the oil sink on the outer face+ const bq = stagger(s(1), 4, 0.5);+ ARB.forEach((a, i) => { const x = a[0], q2 = bq(i); if (q2 <= 0) return; [[0, TP], [TP + GAP, TP + GAP + BP]].forEach(([z0, z1], j) => { const qq = stagger(q2, 2, 0.7)(j); k.ln([SX(x - BUSH), SZ(z0)], [SX(x - BUSH), SZ(z1)], 1.2, { seed: 1420 + i * 8 + j * 4, progress: qq }); k.ln([SX(x + BUSH), SZ(z0)], [SX(x + BUSH), SZ(z1)], 1.2, { seed: 1421 + i * 8 + j * 4, progress: qq }); const zo = j ? z1 : z0, dz = j ? -1 : 1; k.pen([[SX(x - 3.2), SZ(zo)], [SX(x - PIV), SZ(zo + dz * 2.2)], [SX(x + PIV), SZ(zo + dz * 2.2)], [SX(x + 3.2), SZ(zo)]], 1, { seed: 1422 + i * 8 + j * 4, taper: 0.2, wobble: 0.05, progress: cut(qq, 0.5, 1) }); }); });+ // pillars and their screws+ const lq = stagger(s(2), 2, 0.7); [CUTL, CUTR].forEach(([x], i) => { const q2 = lq(i); rule(k, [[SX(x - 7), SZ(TP)], [SX(x - 7), SZ(TP + GAP)]], 1.6, 1460 + i * 6, cut(q2, 0, 0.4)); k.ln([SX(x + 7), SZ(TP)], [SX(x + 7), SZ(TP + GAP)], 1.6, { seed: 1462 + i * 6, progress: cut(q2, 0.2, 0.6) }); rule(k, [[SX(x - 6), SZ(-4.5)], [SX(x + 6), SZ(-4.5)], [SX(x + 6), SZ(0)], [SX(x - 6), SZ(0)]], 1.3, 1464 + i * 6, cut(q2, 0.6, 1)); if (q2 >= 1) k.ln([SX(x), SZ(-4.5)], [SX(x), SZ(-1.8)], 1.3, { seed: 1469 + i * 6 }); });+ // arbors (not sectioned): body between shoulders, pivots into the bushes+ const aq = stagger(s(3), 4, 0.5);+ ARB.forEach((a, i) => { const x = a[0], w = WHEELS[i].arbor * 0.55, q2 = aq(i); if (q2 <= 0) return; const zb = i === 0 ? TP + GAP + BP + 26 : TP + GAP - 2; k.ln([SX(x - w), SZ(TP + 2)], [SX(x - w), SZ(zb)], 1.35, { seed: 1480 + i * 6, progress: cut(q2, 0, 0.6) }); k.ln([SX(x + w), SZ(TP + 2)], [SX(x + w), SZ(zb)], 1.35, { seed: 1481 + i * 6, progress: cut(q2, 0.1, 0.7) }); const pv = cut(q2, 0.6, 1); k.pen([[SX(x - PIV), SZ(TP + 2)], [SX(x - PIV), SZ(3)], [SX(x + PIV), SZ(3)], [SX(x + PIV), SZ(TP + 2)]], 1.1, { seed: 1482 + i * 6, taper: 0.1, wobble: 0.03, progress: pv }); if (i) k.pen([[SX(x - PIV), SZ(TP + GAP - 2)], [SX(x - PIV), SZ(TP + GAP + BP - 3)], [SX(x + PIV), SZ(TP + GAP + BP - 3)], [SX(x + PIV), SZ(TP + GAP - 2)]], 1.1, { seed: 1483 + i * 6, taper: 0.1, wobble: 0.03, progress: pv }); else k.ln([SX(x - w), SZ(zb)], [SX(x + w), SZ(zb)], 1.2, { seed: 1484, progress: pv }); });+ // pinions (not sectioned): the leaves seen side on, their tips and roots as lines+ const nq = stagger(s(4), 4, 0.5);+ PIN_Z.forEach((zz, i) => { if (!zz) return; const x = ARB[i][0], r = i === 0 ? (M1 * 12) / 2 : PINIONS[i]!.r, q2 = nq(i); if (q2 <= 0) return; rule(k, rect(x - r - 1, zz[0], x + r + 1, zz[1]), 1.4, 1500 + i * 8, cut(q2, 0, 0.7)); [-0.45, 0.45].forEach((f, j) => k.ln([SX(x + r * f), SZ(zz[0] + 1)], [SX(x + r * f), SZ(zz[1] - 1)], 0.9, { seed: 1505 + i * 8 + j, color: CYAN, progress: cut(q2, 0.6, 1) })); });+ // wheels seen edge on, and each wheel's collet on its arbor+ const wq = stagger(s(5), 4, 0.5);+ WHEELS.forEach((w, i) => { const x = w.c[0], z = Z_WHEEL[i], R = w.R + (i === 3 ? 0 : 1.35 * (i === 2 ? M3 : M1)), q2 = wq(i); if (q2 <= 0) return; rule(k, rect(x - R, z - 1.6, x + R, z + 1.6), 1.3, 1540 + i * 8, cut(q2, 0, 0.6)); const cz = z < (PIN_Z[i]?.[0] ?? 999) ? [z + 1.6, z + 7] : [z - 7, z - 1.6], h = w.hub * 0.72; if (i > 0 || true) rule(k, rect(x - h, cz[0], x + h, cz[1]), 1.2, 1546 + i * 8, cut(q2, 0.6, 1)); });+}); };+// SECTION A-A: lining. Plates one way, bushes and collets the other; thin wheels solid.+const lining = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const s = stagger(q, 4, 0.4), xs = ARB.map((a) => a[0]).sort((a, b) => a - b), pil = [CUTL[0], CUTR[0]];+ const cuts = [X0, ...xs.flatMap((x) => [x - BUSH, x + BUSH]), X1];+ [[0, TP, 0.785, 0], [TP + GAP, TP + GAP + BP, -0.785, 1]].forEach(([z0, z1, ang, j]) => { const segs: P[][] = []; for (let i = 0; i + 1 < cuts.length; i += 2) segs.push(rect(cuts[i] + 0.4, z0 + 0.4, cuts[i + 1] - 0.4, z1 - 0.4)); const hs = stagger(s(j), segs.length, 0.5); segs.forEach((r, i) => k.hatch(r, ang, 3.4, 0.75, 1600 + j * 40 + i * 5, { opacity: 0.85, progress: hs(i) })); void pil; });+ const bs = stagger(s(2), 8, 0.4); let n = 0;+ ARB.forEach((a) => [[0, TP, -0.785], [TP + GAP, TP + GAP + BP, 0.785]].forEach(([z0, z1, ang]) => { const x = a[0]; [[x - BUSH, x - PIV], [x + PIV, x + BUSH]].forEach(([u0, u1], h) => k.hatch(rect(u0 + 0.3, z0 + 0.3, u1 - 0.3, z1 - 0.3), ang, 2.4, 0.7, 1700 + n * 3 + h, { opacity: 0.85, progress: bs(n) })); n++; }));+ const ws = stagger(s(3), 8, 0.4);+ WHEELS.forEach((w, i) => { const x = w.c[0], z = Z_WHEEL[i], R = w.R + (i === 3 ? 0 : 1.35 * (i === 2 ? M3 : M1)), q2 = ws(i * 2 + 1); if (q2 > 0) { const len = (x + R - (x - R)) * cut(q2, 0, 1); k.fill(rect(x - R + 0.8, z - 1.2, x - R + 0.8 + Math.max(0.1, len - 1.6), z + 1.2), WHITE, 0.9); } const cz = z < (PIN_Z[i]?.[0] ?? 999) ? [z + 1.6, z + 7] : [z - 7, z - 1.6], h = w.hub * 0.72, aw = w.arbor * 0.55; [[x - h, x - aw], [x + aw, x + h]].forEach(([u0, u1], j) => k.hatch(rect(u0 + 0.3, cz[0] + 0.3, u1 - 0.3, cz[1] - 0.3), -0.785, 2.2, 0.7, 1760 + i * 4 + j, { opacity: 0.85, progress: ws(i * 2) })); });+}); };++const straight = (a: P, b: P, step = 1.5): P[] => { const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step)); return Array.from({ length: n }, (_, i) => [a[0] + ((b[0] - a[0]) * (i + 1)) / n, a[1] + ((b[1] - a[1]) * (i + 1)) / n] as P); };+const arcPts = (c: P, r: number, a0: number, a1: number, step = 1.2): P[] => { const n = Math.max(2, Math.ceil((Math.abs(a1 - a0) * r) / step)); return Array.from({ length: n + 1 }, (_, i) => pol(c, r, a0 + ((a1 - a0) * i) / n)); };+const lerp2 = (a: P, b: P, t: number): P => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];+// DETAIL C: two club teeth enlarged, set symmetric about the vertical so the tooth's own rake reads,+// not the wheel's curvature. Curved stem and root smoothed; the impulse and locking faces RULED.+const DC: P = [884, 572], DK = 8.6;+const detail = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const s = stagger(q, 5, 0.35), st = (Math.PI * 2) / Z.w3, base = -Math.PI / 2 - st * 1.08, cc: P = [DC[0], DC[1] + R_ESC * DK];+ const T = (r: number, a: number): P => pol(cc, r * DK, a), at = (i: number, j: number): P => T(CLUB[j][0] * R_ESC, base + (i + CLUB[j][1]) * st);+ const prof: P[] = [T(0.62 * R_ESC, base - st * 0.12)];+ for (let i = 0; i < 2; i++) {+ prof.push(...sample([prof[prof.length - 1], ...Array.from({ length: HEEL + 1 }, (_, j) => at(i, j))], false, 8).slice(1)); /* the back of the stem, a curve, up to the heel */+ prof.push(...straight(at(i, HEEL), at(i, CORNER))); /* the impulse face, ruled */+ prof.push(...straight(at(i, CORNER), at(i, FACE))); /* the locking face, ruled, raked back */+ const tail = Array.from({ length: CLUB.length - FACE - (i ? 0 : 1) }, (_, j) => at(i, FACE + j)); prof.push(...sample(tail, false, 8).slice(1)); /* front of the stem and the root */+ }+ k.pen(prof, 1.8, { seed: 1800, wobble: 0.1, taper: 0.15, progress: s(0) });+ k.pen(Array.from({ length: 15 }, (_, i) => T(R_ESC * 0.92, base - 0.02 + ((2.2 * st) * i) / 14)), 0.8, { seed: 1801, color: CYAN, opacity: 0.8, progress: s(1) }); /* the pitch circle */+ const a1 = base + st * CLUB[CORNER][1], a2 = a1 + st;+ [a1, a2].forEach((a, i) => k.chain(T(R_ESC * 0.5, a), T(R_ESC * 1.1, a), 0.8, { seed: 1802 + i * 4, color: CYAN, progress: stagger(s(2), 2, 0.7)(i) }));+ const aq = s(3); k.pen(Array.from({ length: 9 }, (_, i) => T(R_ESC * 1.07, a1 + (st * i) / 8)), 0.9, { seed: 1810, color: CYAN, progress: cut(aq, 0, 0.6) }); if (aq >= 1) { k.arrow(T(R_ESC * 1.07, a1), a1 - Math.PI / 2, 9, CYAN); k.arrow(T(R_ESC * 1.07, a2), a2 + Math.PI / 2, 9, CYAN); } const tp = T(R_ESC * 1.1, a1 + st / 2); k.text("24o", tp[0], tp[1] - 14, { cap: 9.5, align: "center", seed: 1811, progress: cut(aq, 0.6, 1) });+ /* the rake of the locking face, dimensioned against the radial through the corner */+ const cr = at(1, CORNER), fb = at(1, FACE), d = [fb[0] - cr[0], fb[1] - cr[1]], L = Math.hypot(d[0], d[1]) || 1, ext: P = [cr[0] + (d[0] / L) * 70, cr[1] + (d[1] / L) * 70];+ k.ln(fb, ext, 0.8, { seed: 1813, color: CYAN, progress: cut(s(4), 0, 0.3) });+ k.callout("IMPULSE FACE", [752, 516], lerp2(at(1, HEEL), at(1, CORNER), 0.5), 1812, "left", cut(s(4), 0, 0.45), 8.5);+ k.callout("LOCKING FACE, DRAW 24o", [1012, 752], lerp2(at(1, CORNER), at(1, FACE), 0.5), 1815, "right", cut(s(4), 0.2, 0.65), 8.5);+ k.text("DETAIL C", 760, 780, { cap: 12, seed: 1820, progress: cut(s(4), 0.6, 0.85) }); k.text("ESCAPE WHEEL, CLUB TOOTH, 7 : 1 OF PLAN", 760, 800, { cap: 7.5, seed: 1821, color: CYAN, progress: cut(s(4), 0.8, 1) });+}); };+// DETAIL D: the depthing of the first mesh, drawn fresh at the detail's own size (never a magnified+// plan): ogival wheel teeth whose tip arcs are swung from the opposite flank's pitch point (radius =+// tooth thickness), radial flanks, a root arc; pinion leaves with parallel flanks and a round tip.+// Every outline is ruled segments and compass arcs. A wheel tooth sits in a leaf gap on the line+// of centres, and the two pitch circles are chain lines tangent at the pitch point.+const DD: P = [178, 902], DDR = 104, DDK = 3.6;+const detailD = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const s = stagger(q, 5, 0.35), c = k.raw(), K = DDK * S, u: P = [Math.cos(-18 * deg), Math.sin(-18 * deg)], th = Math.atan2(u[1], u[0]);+ const Rw = ((M1 * Z.w0) / 2) * K, rp = ((M1 * Z.p1) / 2) * K, m = M1 * K, Cw: P = [DD[0] - u[0] * Rw, DD[1] - u[1] * Rw], Cp: P = [DD[0] + u[0] * rp, DD[1] + u[1] * rp];+ k.circle(DD[0], DD[1], DDR, 1.5, { seed: 1850, progress: s(0), a0: -2.6 });+ c.save(); c.beginPath(); c.arc(DD[0], DD[1], DDR - 2, 0, Math.PI * 2); c.clip(); k.g.touch(DD[0] - DDR, DD[1] - DDR, DD[0] + DDR, DD[1] + DDR);+ // the wheel: seven teeth either side of the line of centres, one continuous outline+ const tw = (Math.PI * m) / 2, hw = tw / 2 / Rw, gw = (Math.PI * 2) / Z.w0, Rr = Rw - 1.55 * m, wheel: P[] = [];+ for (let j = -4; j <= 4; j++) {+ const a = th + j * gw, L = pol(Cw, Rw, a - hw), R = pol(Cw, Rw, a + hw), tipH = Math.sqrt(tw * tw - (tw / 2) ** 2);+ if (j === -4) wheel.push(...arcPts(Cw, Rr, a - gw / 2, a - hw * 1.08)); else wheel.push(...arcPts(Cw, Rr, a - gw + hw * 1.08, a - hw * 1.08).slice(1));+ wheel.push(...straight(pol(Cw, Rr, a - hw * 1.08), L)); /* radial flank */+ const aL = Math.atan2(L[1] - R[1], L[0] - R[0]), aTip = Math.atan2(pol(Cw, Rw + tipH, a)[1] - R[1], pol(Cw, Rw + tipH, a)[0] - R[0]); wheel.push(...arcPts(R, tw, aL, aTip).slice(1)); /* ogive, swung from the right flank's pitch point */+ const bT = Math.atan2(pol(Cw, Rw + tipH, a)[1] - L[1], pol(Cw, Rw + tipH, a)[0] - L[0]), bR = Math.atan2(R[1] - L[1], R[0] - L[0]); wheel.push(...arcPts(L, tw, bT, bR).slice(1)); /* and from the left's */+ wheel.push(...straight(R, pol(Cw, Rr, a + hw * 1.08)));+ if (j === 4) wheel.push(...arcPts(Cw, Rr, a + hw * 1.08, a + gw / 2).slice(1));+ }+ k.pen(wheel, 1.6, { seed: 1851, wobble: 0.1, taper: 0.1, progress: s(1) });+ // the pinion: eight leaves, a GAP facing the wheel, parallel flanks, round tips+ const lw = rp * (Math.PI / Z.p1) * 0.34, rr = rp - 1.9 * m, tipC = rp + 0.85 * m - lw, pin: P[] = [], back = th + Math.PI;+ for (let j = 0; j < Z.p1; j++) {+ const a = back + Math.PI / Z.p1 + (j * Math.PI * 2) / Z.p1, n: P = [Math.cos(a), Math.sin(a)], t: P = [-n[1], n[0]], at = (r: number, w: number): P => [Cp[0] + n[0] * r + t[0] * w, Cp[1] + n[1] * r + t[1] * w];+ const rootA = (w: number) => Math.sqrt(Math.max(0, rr * rr - w * w)), aNext = a + (Math.PI * 2) / Z.p1;+ pin.push(...straight(at(rootA(lw), -lw), at(tipC, -lw)).slice(j ? 0 : 0)); /* flank */+ pin.push(...arcPts(at(tipC, 0), lw, a - Math.PI / 2, a + Math.PI / 2).slice(1)); /* the round tip */+ pin.push(...straight(at(tipC, lw), at(rootA(lw), lw)).slice(1));+ const g0 = Math.atan2(at(rootA(lw), lw)[1] - Cp[1], at(rootA(lw), lw)[0] - Cp[0]), nn: P = [Math.cos(aNext), Math.sin(aNext)], tt: P = [-nn[1], nn[0]], nx: P = [Cp[0] + nn[0] * rootA(lw) - tt[0] * lw, Cp[1] + nn[1] * rootA(lw) - tt[1] * lw], g1 = Math.atan2(nx[1] - Cp[1], nx[0] - Cp[0]);+ pin.push(...arcPts(Cp, rr, g0, g1 < g0 ? g1 + Math.PI * 2 : g1).slice(1)); /* root */+ }+ k.pen(pin, 1.6, { seed: 1852, closed: true, wobble: 0.1, taper: 0.1, progress: s(2) });+ k.circle(Cp[0], Cp[1], 2.2 * K, 1.2, { seed: 1853, progress: s(2) }); /* the arbor */+ // both pitch circles, chain lines, tangent at the pitch point; and the line of centres+ const chainArc = (cc: P, r: number, a0: number, a1: number, seed: number, qq: number) => { const L = Math.abs(a1 - a0) * r, n = Math.floor(L / 30); for (let i = 0; i < n && i < qq * n; i++) { const d0 = a0 + ((a1 - a0) * (i * 30)) / L, d1 = a0 + ((a1 - a0) * (i * 30 + 19)) / L, e0 = a0 + ((a1 - a0) * (i * 30 + 23)) / L, e1 = a0 + ((a1 - a0) * (i * 30 + 26)) / L; k.pen(arcPts(cc, r, d0, d1, 2), 0.8, { color: CYAN, seed: seed + i * 2, wobble: 0.05, taper: 0.3, opacity: 0.85 }); k.pen(arcPts(cc, r, e0, e1, 1), 0.8, { color: CYAN, seed: seed + i * 2 + 1, wobble: 0.05, taper: 0.3, opacity: 0.85 }); } };+ const pq = s(3), span = (DDR * 1.1) / Rw; chainArc(Cw, Rw, th - span, th + span, 1860, pq); chainArc(Cp, rp, back - Math.PI, back + Math.PI, 1900, pq);+ k.chain([DD[0] - u[0] * 110, DD[1] - u[1] * 110], [DD[0] + u[0] * 110, DD[1] + u[1] * 110], 0.8, { seed: 1870, color: DIM, progress: pq });+ if (pq >= 1) k.fill(k.oval(DD[0], DD[1], 2.4, 2.4, 8), WHITE, 0.95); /* the pitch point */+ c.restore();+ const tq = s(4); k.text("DETAIL D", 302, 832, { cap: 12, seed: 1880, progress: cut(tq, 0, 0.3) }); k.text("DEPTHING, CENTRE WHEEL TO THIRD PINION, 4.4 : 1", 302, 852, { cap: 7.5, seed: 1881, color: CYAN, progress: cut(tq, 0.25, 0.6) });+ k.callout("PITCH CIRCLES TANGENT", [302, 930], DD, 1882, "left", cut(tq, 0.55, 1), 8.5);+}); };+// the ring on the plan that says where Detail C is taken from+const detailRing = (k: Kit, q: number) => {+ const st = (Math.PI * 2) / Z.w3, a = -Math.PI / 2 - st * 0.62, c = pol(PL(...A3), R_ESC * S * 0.9, a); k.circle(c[0], c[1], 19, 1.1, { color: CYAN, seed: 1830, progress: cut(q, 0, 0.4) }); k.text("C", c[0] + 14, c[1] - 32, { cap: 11, seed: 1831, w: 1.5, progress: cut(q, 0.35, 0.5) });+ const d = PL(...pol(A0, (M1 * Z.w0) / 2, -18 * deg)); k.circle(d[0], d[1], 22, 1.1, { color: CYAN, seed: 1832, progress: cut(q, 0.5, 0.9) }); k.text("D", d[0] - 24, d[1] + 18, { cap: 11, seed: 1833, w: 1.5, progress: cut(q, 0.85, 1) });+};+const mm = (d: number) => (d * 0.05).toFixed(2);+const dims = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const s = stagger(q, 6, 0.3);+ // the cutting plane: thick at the ends and the steps, chain between, arrows for the direction of view+ const cq = s(0), pts = [CUTL, ...ARB, CUTR].map(([x, y]) => PL(x, y));+ const cs = stagger(cut(cq, 0, 0.7), pts.length - 1, 0.4); for (let i = 0; i + 1 < pts.length; i++) k.chain(pts[i], pts[i + 1], 0.9, { seed: 1900 + i * 10, color: CYAN, progress: cs(i) });+ [[pts[0], [pts[0][0] - 22, pts[0][1]]], [pts[pts.length - 1], [pts[pts.length - 1][0] + 22, pts[pts.length - 1][1]]]].forEach(([a, b], i) => { const qq = cut(cq, 0.65, 0.9); k.ln(a as P, b as P, 2.6, { seed: 1960 + i, taper: 0.1, progress: qq }); if (qq >= 1) { k.ln(b as P, [(b as P)[0], (b as P)[1] + 20], 1.2, { seed: 1962 + i }); k.arrow([(b as P)[0], (b as P)[1] + 24], Math.PI / 2, 11); } k.text("A", (b as P)[0] + (i ? 6 : -16), (b as P)[1] - 20, { cap: 13, seed: 1964 + i, w: 1.7, progress: cut(cq, 0.85, 1) }); });+ // centre distances along the line of centres+ // the section: arbor spacing along the foot, overall length, plate and frame heights+ const fy = TP + GAP + BP, xq = stagger(s(2), 3, 0.5); for (let i = 0; i < 3; i++) k.dim([SX(ARB[i][0]), SZ(fy + 4)], [SX(ARB[i + 1][0]), SZ(fy + 4)], -36, mm(ARB[i + 1][0] - ARB[i][0]), 1930 + i * 6, xq(i), { cap: 8.5, gap: 0, ext: 3 });+ k.dim([SX(X0), SZ(fy)], [SX(X1), SZ(fy)], -62, mm(X1 - X0), 1950, s(3), { cap: 9, gap: 3, ext: 4 });+ const vq = stagger(s(4), 3, 0.5), xl = SX(X1); k.dim([xl, SZ(0)], [xl, SZ(TP)], 18, mm(TP), 1970, vq(0), { cap: 8, gap: 3, ext: 3 }); k.dim([xl, SZ(TP)], [xl, SZ(TP + GAP)], 18, mm(GAP), 1976, vq(1), { cap: 8.5, gap: 3, ext: 3 }); k.dim([xl, SZ(0)], [xl, SZ(fy)], 62, mm(fy), 1982, vq(2), { cap: 8.5, gap: 3, ext: 3 });+ const lq = s(5); k.text("SECTION A-A", SX((X0 + X1) / 2), SZ(fy) + 84, { cap: 13, align: "center", seed: 1990, w: 1.7, progress: cut(lq, 0, 0.6) }); k.ln([SX((X0 + X1) / 2) - 58, SZ(fy) + 104], [SX((X0 + X1) / 2) + 58, SZ(fy) + 104], 1.1, { seed: 1991, progress: cut(lq, 0.55, 0.8) });+ detailRing(k, cut(lq, 0.6, 1));+}); };++const ROWS: [string, string, string, string, string][] = [["1", "CENTRE WHEEL", "64", "0.16", "-"], ["2", "THIRD PINION", "8", "0.16", mm(D01)], ["3", "THIRD WHEEL", "60", "0.16", "-"], ["4", "FOURTH PINION", "8", "0.16", mm(D12)], ["5", "FOURTH WHEEL", "60", "0.12", "-"], ["6", "ESCAPE PINION", "7", "0.12", mm(D23)], ["7", "ESCAPE WHEEL", "15", "CLUB", "-"]];+const table = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const x0 = 722, x1 = 1026, y0 = 84, rh = 16.5, yb = y0 + rh * (ROWS.length + 1), fq = cut(q, 0, 0.2), hq = cut(q, 0.15, 0.35), rq = cut(q, 0.3, 0.85), cx = [x0 + 26, x1 - 118, x1 - 86, x1 - 46];+ rule(k, [[x0, y0], [x1, y0], [x1, yb], [x0, yb]], 1.6, 2000, fq); k.ln([x0, y0 + rh], [x1, y0 + rh], 1.4, { seed: 2005, progress: hq }); cx.forEach((x, i) => k.ln([x, y0], [x, yb], 0.95, { seed: 2006 + i, color: CYAN, progress: hq }));+ const mid = [(x0 + cx[0]) / 2, (cx[0] + cx[1]) / 2, (cx[1] + cx[2]) / 2, (cx[2] + cx[3]) / 2, (cx[3] + x1) / 2];+ ["NO.", "PART", "T", "MOD.", "C.D."].forEach((t, i) => k.text(t, mid[i], y0 + 4, { cap: 8, align: "center", seed: 2010 + i, color: CYAN, w: 1.05, progress: stagger(hq, 5, 0.5)(i) }));+ const rs = stagger(rq, ROWS.length, 0.35); ROWS.forEach((row, i) => { const y = y0 + rh * (i + 1), qq = rs(i); if (qq <= 0) return; if (i) k.ln([x0, y], [x1, y], 0.75, { seed: 2020 + i, color: DIM, opacity: 0.7, progress: cut(qq, 0, 0.25) }); const ws = stagger(cut(qq, 0.2, 1), 5, 0.45); row.forEach((t, j) => k.text(t, j === 1 ? cx[0] + 6 : mid[j], y + 4, { cap: 8, align: j === 1 ? "left" : "center", seed: 2030 + i * 7 + j, w: 1.05, progress: ws(j) })); });+ k.text("GOING TRAIN", x0, y0 - 22, { cap: 11, seed: 2070, w: 1.5, progress: cut(q, 0.85, 1) });+ /* the scale bar: millimetres at the scale of the drawing */+ const u = 20 * S, bx = x0, by = 272, sq = stagger(cut(q, 0.6, 1), 6, 0.4);+ for (let i = 0; i < 5; i++) { const a: P = [bx + i * u, by], b: P = [bx + (i + 1) * u, by], qq = sq(i); if (qq <= 0) continue; if (i % 2 === 0 && qq >= 1) k.fill([[a[0], by - 6], [b[0], by - 6], [b[0], by], [a[0], by]], WHITE, 0.9); k.ln([a[0], by - 6], [b[0], by - 6], 1.1, { seed: 2080 + i, progress: qq }); k.ln(a, b, 1.1, { seed: 2086 + i, progress: qq }); k.ln([b[0], by - 10], [b[0], by], 1.1, { seed: 2092 + i, progress: qq }); }+ k.ln([bx, by - 10], [bx, by], 1.1, { seed: 2098, progress: sq(0) }); ["0", "1", "2", "3", "4", "5 MM"].forEach((t, i) => k.text(t, bx + i * u, by - 24, { cap: 7, align: i === 5 ? "left" : "center", seed: 2100 + i, color: CYAN, w: 1, progress: sq(5) }));+}); };+const NOTE_LINES = ["NOTES", "1. 64/8 x 60/8 GIVES 60: THE FOURTH", " WHEEL TURNS ONCE A MINUTE", "2. WHEELS HARD BRASS, CROSSED OUT", "3. PINIONS & ARBORS STEEL,", " PIVOTS HARDENED & BURNISHED", "4. OIL SINKS ON OUTER FACES", "5. CENTRE PINION DRIVEN FROM", " THE BARREL, NOT SHOWN"];+const notes = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const s = stagger(q, 3, 0.45);+ // balloons, in number order, each ringed then numbered then led to its part+ const bs = stagger(s(0), 7, 0.35), tgt: [P, P][] = [[[54, 96], pol(PL(...A0), ((M1 * Z.w0) / 2 - 6) * S, -2.35)], [[234, 52], pol(PL(...A1), 8, -2.0)], [[424, 46], pol(PL(...A1), 70 * S, -0.9)], [[520, 458], pol(PL(...A2), 7, 1.6)], [[410, 458], pol(PL(...A2), 48 * S, 2.1)], [[648, 116], pol(PL(...A3), 6, -1.3)], [[612, 458], pol(PL(...A3), 36 * S, 1.2)]];+ tgt.forEach(([at, to], i) => k.balloon(String(i + 1), at, to, 2100 + i * 3, bs(i)));+ // section callouts+ const cs = stagger(s(1), 3, 0.5), fy = TP + GAP + BP;+ k.callout("BUSH, OIL SINK", [SX(ARB[1][0]) - 40, SZ(-30)], [SX(ARB[1][0]), SZ(-1)], 2130, "right", cs(0), 8.5);+ k.callout("PILLAR", [SX(CUTR[0]) + 10, SZ(-30)], [SX(CUTR[0]) + 2, SZ(TP + 30)], 2133, "left", cs(1), 8.5);+ k.callout("TO MOTION WORK", [SX(A0[0]) - 34, SZ(fy) + 22], [SX(A0[0]) - 3, SZ(fy + 18)], 2136, "right", cs(2), 8.5);+ // the notes block, a line at a time+ const ns = stagger(s(2), NOTE_LINES.length, 0.3); NOTE_LINES.forEach((t, i) => k.text(t, 722, 322 + i * 17 + (i ? 6 : 0), { cap: i ? 8.5 : 11, seed: 2150 + i * 3, w: i ? 1.05 : 1.5, color: i ? "#eef6fb" : WHITE, progress: ns(i) }));+}); };++const title = (k: Kit, q: number) => { if (q <= 0) return; k.ink(() => {+ const x0 = 650, x1 = 1026, y0 = 890, f1 = cut(q, 0, 0.3), f2 = cut(q, 0.25, 0.5), sq = cut(q, 0.5, 0.68), tq = cut(q, 0.66, 1);+ ([["PLATE", "IV", x0 + 66], ["SCALE", "10 : 1", x0 + 190], ["SHEET", "1 OF 1", x0 + 314]] as [string, string, number][]).forEach(([a, v, x], i) => { const qq = stagger(f1, 3, 0.55)(i); k.text(a, x, y0 + 67, { cap: 7, align: "center", seed: 2200 + i, color: CYAN, w: 0.95, progress: cut(qq, 0, 0.5) }); k.text(v, x, y0 + 79, { cap: 12.5, align: "center", seed: 2203 + i, w: 1.6, progress: cut(qq, 0.4, 1) }); });+ ([["DRAWN", "F.B.", x0 + 66], ["DIMENSIONS", "MILLIMETRES", x0 + 190], ["DATE", "25 IX 2026", x0 + 314]] as [string, string, number][]).forEach(([a, v, x], i) => { const qq = stagger(f2, 3, 0.55)(i); k.text(a, x, y0 + 104, { cap: 7, align: "center", seed: 2210 + i, color: CYAN, w: 0.95, progress: cut(qq, 0, 0.5) }); k.text(v, x, y0 + 116, { cap: 9.5, align: "center", seed: 2213 + i, w: 1.2, progress: cut(qq, 0.4, 1) }); });+ k.text("WATCH MOVEMENT - PLAN & SECTION A-A", (x0 + x1) / 2, y0 + 45, { cap: 8.6, align: "center", seed: 2220, color: CYAN, w: 1.05, progress: sq });+ k.text("GOING TRAIN", (x0 + x1) / 2, y0 + 14, { cap: 20, align: "center", seed: 2221, w: 2.3, progress: tq });+}); };++// ---------------------------------------------------------------- composition+type Part = (k: Kit, q: number) => void;+const PART: Record<string, Part> = {+ border: (k, q) => border(k, q), titleBox, construct, plate,+ w0: (k, q) => wheelPart(k, 0, q), p1: (k, q) => pinionPart(k, 1, q), w1: (k, q) => wheelPart(k, 1, q), p2: (k, q) => pinionPart(k, 2, q), w2: (k, q) => wheelPart(k, 2, q), p3: (k, q) => pinionPart(k, 3, q), w3: (k, q) => wheelPart(k, 3, q),+ section: sectionOut, lining, detail, detailD, dims, table, notes, title,+};+const progressAt = (f: number, a: number, b: number) => (f >= b ? 1 : f <= a ? 0 : (f - a) / (b - a));++// Everything finished is flattened onto ONE cached surface: the sheet plus the first `n` parts,+// in cue order. Its key is n (and the surface's size), which is everything its pixels depend on;+// going forward it is extended in place (drawing parts n0..n-1 on top of stack(n0) gives exactly+// the pixels of drawing 0..n-1 from scratch), going backward it is rebuilt from the bare sheet.+const stack = (env: Env, n: number) => {+ const s = slot(env, "stack"), have = s.key === null ? -1 : Number(s.key);+ if (have === n) return s.L;+ const g = new Gfx(s.L.ctx, env, 0, DRAFT), k = kit(g);+ let from = have;+ if (have < 0 || have > n) { s.L.ctx.setTransform(1, 0, 0, 1, 0, 0); s.L.ctx.clearRect(0, 0, s.L.canvas.width, s.L.canvas.height); g.cur = s.L.ctx; sheet(k); from = 0; }+ for (let i = from; i < n; i++) PART[CUES[i][0]](k, 1);+ s.key = String(n); return s.L;+};++export const drawBlueprint = (ctx: Ctx, frame: number, env: Env) => {+ const f = Math.max(0, Math.min(N - 1, frame)), n = CUES.filter(([, , b]) => f >= b).length;+ blit(ctx, stack(env, n));+ const g = new Gfx(ctx, env, 0, DRAFT), k = kit(g);+ CUES.forEach(([id, a, b], i) => { if (i < n) return; const q = progressAt(f, a, b); if (q > 0) PART[id](k, q); });+ tooth(g); /* the sheet's tooth is over the whole frame, ink and all */+};++export const blueprint: Film = {+ meta: { title: "Going train · cyanotype drafting sheet", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "blueprint", start: 0, end: N, draw: (ctx, f, env) => drawBlueprint(ctx, f, env) }],+};++export const STYLE = { id: "blueprint", name: "Cyanotype blueprint", family: "technical drawing", medium: "ruling pen and spring-bow compass in white ink on Prussian-blue cyanotype stock", nearest: "pocketWatch", hero: "a watch movement's going train, plan and section A-A" };+void GROUND;diff --git a/engine/src/canvas-core/blueprintKit.ts b/engine/src/canvas-core/blueprintKit.tsnew file mode 100644index 0000000..f97a9cb--- /dev/null+++ b/engine/src/canvas-core/blueprintKit.ts@@ -0,0 +1,111 @@+// THE DRAFTSMAN'S KIT, ported into the engine from the worked film (example/…/butterfly/kit.ts and+// parts.ts) so a plate can draw a cyanotype without importing the example. Every mark on a+// blueprint sheet is made with one of these: a ruling pen that is never quite straight, a swung+// compass ring, a chain line, section lining that starts and stops inside the part, an arrowhead,+// inclined gothic lettering (drafting.ts). Bound to one Gfx, so the same kit draws on the frame or+// into a cached surface without knowing the difference.+//+// Additions over the example: `circle` (a compass circle that can be swung part-way, starting+// where the needle-leg swings from), `chainRing` (a pitch circle as a long-dash-short-dash line),+// `dim` (a whole linear dimension: witness lines, dimension line, arrows, figure, in drafting+// order), and the surface slot (`slot`/`blit`) for cached part layers.+import { type Ctx, type Env, Gfx, type Layer, type Medium, type P, arc, jitter, line, oval, poly, rng } from "./core";+import { letter, width } from "./drafting";+import { bounds, inside } from "./riso";++export const WHITE = "#f1f7fb", CYAN = "#a7d8ec", DIM = "#7fbcd8", GROUND = "#123a63";+export const DRAFT: Medium = { nib: 1, taper: 0.6, pressure: 0.75, retrace: false, wobble: 0.5, rough: 0.55 }; // a ruling pen in a human hand+export type PenO = { color?: string; seed?: number; opacity?: number; closed?: boolean; taper?: number; wobble?: number; progress?: number };+export type Kit = ReturnType<typeof kit>;++export const lerp = (a: P, b: P, t: number): P => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];+export const cen = (pts: P[]): P => [pts.reduce((a, p) => a + p[0], 0) / pts.length, pts.reduce((a, p) => a + p[1], 0) / pts.length];+// element i of a run of n, drawn in order, each taking `dur` of the whole: the hand works down the part+export const stagger = (p: number, n: number, dur = Math.min(1, 2 / n)) => { const step = n > 1 ? (1 - dur) / (n - 1) : 0; return (i: number) => (p >= 1 ? 1 : Math.max(0, Math.min(1, (p - i * step) / dur))); };+export const cut = (p: number, a: number, b: number) => (p >= 1 ? 1 : Math.max(0, Math.min(1, (p - a) / (b - a))));++export const kit = (g: Gfx) => {+ const ink = (fn: () => void) => g.inkGroup(fn, { blur: 1.8, alpha: 0.28, textures: ["draftTooth"] }); // white ink on blue always blooms a little+ const pen = (pts: P[], w: number, p: PenO = {}) => g.pen(pts, { w, color: p.color ?? WHITE, seed: p.seed ?? 1, opacity: p.opacity ?? 0.95, closed: p.closed, taper: p.taper ?? 0.6, wobble: p.wobble ?? 0.5, boil: 0, progress: p.progress });+ const ln = (a: P, b: P, w: number, p: PenO = {}) => pen(line(a, b, (((p.seed ?? 1) % 3) - 1) * 0.6), w, p); // nobody rules a dead straight line freehand+ // a run of pieces along a line, each drawn as the pen reaches it (progress runs along the whole line)+ const pieces = (a: P, b: P, segs: [number, number][], w: number, p: PenO) => { const L = Math.hypot(b[0] - a[0], b[1] - a[1]), q = (p.progress ?? 1) * L; segs.forEach(([d0, d1], i) => { if (q <= d0) return; const e = Math.min(d1, q); ln(lerp(a, b, d0 / L), lerp(a, b, e / L), w, { ...p, seed: (p.seed ?? 1) + i, taper: 0.3, progress: 1 }); }); };+ const dash = (a: P, b: P, on: number, off: number, w: number, p: PenO = {}) => { const L = Math.hypot(b[0] - a[0], b[1] - a[1]), s: [number, number][] = []; for (let d = 0; d < L; d += on + off) s.push([d, Math.min(L, d + on)]); pieces(a, b, s, w, p); };+ const chain = (a: P, b: P, w: number, p: PenO = {}) => { const L = Math.hypot(b[0] - a[0], b[1] - a[1]), s: [number, number][] = []; for (let d = 0; d < L; d += 34) { s.push([d, Math.min(L, d + 22)]); if (d + 29 < L) s.push([d + 26, d + 29]); } pieces(a, b, s, w, p); }; // long dash, short dash: a centre line+ const arrow = (tip: P, ang: number, size = 11, color = WHITE) => g.fill([tip, [tip[0] - Math.cos(ang - 0.17) * size, tip[1] - Math.sin(ang - 0.17) * size], [tip[0] - Math.cos(ang) * size * 0.82, tip[1] - Math.sin(ang) * size * 0.82], [tip[0] - Math.cos(ang + 0.17) * size, tip[1] - Math.sin(ang + 0.17) * size]], color, 0.95);+ const fill = (pts: P[], color: string, alpha = 1) => g.fill(pts, color, alpha);+ const ring = (cx: number, cy: number, r: number, w: number, seed: number, p: PenO = {}) => pen(jitter(oval(cx, cy, r, r * (0.97 + (seed % 5) * 0.012), 12, -1.9 + seed), r * 0.03, seed), w, { ...p, seed, closed: true, taper: 0.4 }); // hand-swung, never a true circle+ // a compass circle: true round (the compass does not wobble), swung from angle a0, part-way by progress+ const circle = (cx: number, cy: number, r: number, w: number, p: PenO & { a0?: number } = {}) => { const q = p.progress ?? 1; if (q <= 0) return; const a0 = p.a0 ?? -2.2, n = Math.max(24, Math.round(r * 0.5)), pts: P[] = []; for (let i = 0; i <= n; i++) { const a = a0 + (i / n) * Math.PI * 2 * 1.02; pts.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]); } g.pen(pts, { w, color: p.color ?? WHITE, seed: p.seed ?? 1, opacity: p.opacity ?? 0.95, taper: 0.25, wobble: 0.08, boil: 0, progress: q }); };+ const chainRing = (cx: number, cy: number, r: number, w: number, p: PenO & { a0?: number } = {}) => { const q = p.progress ?? 1; if (q <= 0) return; const L = Math.PI * 2 * r, a0 = p.a0 ?? -2.2, n = Math.max(1, Math.round(L / 34)), per = (Math.PI * 2) / n, drawn = q * n; for (let i = 0; i < n && i < drawn; i++) { const a = a0 + i * per, fr = Math.min(1, drawn - i); const seg = (s: number, e: number, k: number) => { const m = Math.max(3, Math.round((e - s) * r / 5)); const pts: P[] = []; for (let j = 0; j <= m; j++) { const t = a + s + ((e - s) * j) / m; pts.push([cx + Math.cos(t) * r, cy + Math.sin(t) * r]); } g.pen(pts, { w, color: p.color ?? CYAN, seed: (p.seed ?? 1) + i * 2 + k, opacity: p.opacity ?? 0.85, taper: 0.3, wobble: 0.05, boil: 0, progress: 1 }); }; const d1 = per * (22 / 34) * Math.min(1, fr * 1.3); seg(0, d1, 0); if (fr >= 0.85) seg(per * (26 / 34), per * (29 / 34), 1); } };+ // section lines / cross-hatch: parallel strokes that start and stop inside the part+ const hatch = (pts: P[], ang: number, gap: number, w: number, seed: number, p: { color?: string; opacity?: number; progress?: number } = {}) => {+ const c = Math.cos(ang), s = Math.sin(ang), r = rng(seed), proj = pts.map(([x, y]) => -s * x + c * y), lo = Math.min(...proj), hi = Math.max(...proj), segs: [P, P, number][] = [];+ for (let off = lo + gap * 0.5, n = 0; off < hi; off += gap * (0.9 + r() * 0.2), n++) {+ const ox = -s * off, oy = c * off, ts: number[] = [];+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[j], b = pts[i], ex = b[0] - a[0], ey = b[1] - a[1], den = c * ey - s * ex; if (Math.abs(den) < 1e-9) continue; const t = ((a[0] - ox) * ey - (a[1] - oy) * ex) / den, u = ((a[0] - ox) * s - (a[1] - oy) * c) / den; if (u >= 0 && u < 1) ts.push(t); }+ ts.sort((a, b) => a - b);+ for (let k = 0; k + 1 < ts.length; k += 2) { const t0 = ts[k] + 0.6 + r() * 1.2, t1 = ts[k + 1] - 0.6 - r() * 1.2; if (t1 - t0 < 2) continue; segs.push([[ox + c * t0, oy + s * t0], [ox + c * t1, oy + s * t1], seed + n * 7 + k]); }+ }+ const vis = (p.progress ?? 1) * segs.length; /* section lines run on one stroke at a time, the last one half made */+ segs.forEach(([a, b, sd], i) => { const q = Math.min(1, vis - i); if (q > 0) ln(a, b, w, { seed: sd, color: p.color ?? CYAN, opacity: p.opacity ?? 0.8, taper: 0.7, progress: q }); });+ };+ const stipple = (pts: P[], n: number, seed: number, dens: (x: number, y: number) => number, color = WHITE) => { const b = bounds(pts), r = rng(seed), c = g.cur; g.touch(b.x0, b.y0, b.x1, b.y1); c.fillStyle = color; for (let i = 0; i < n; i++) { const x = b.x0 + r() * (b.x1 - b.x0), y = b.y0 + r() * (b.y1 - b.y0); if (!inside(pts, x, y) || r() > dens(x, y)) continue; c.globalAlpha = 0.6 + r() * 0.35; c.beginPath(); c.ellipse(x, y, 0.7 + r() * 0.7, 0.6 + r() * 0.5, r() * 3, 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; };+ const k0text = (s: string, x: number, y: number, p: { cap?: number; seed?: number; align?: "left" | "center" | "right"; w?: number; progress?: number }) => letter(g, s, x, y, { ...p, color: "#eef6fb" });+ const text = (s: string, x: number, y: number, p: { cap?: number; color?: string; seed?: number; align?: "left" | "center" | "right"; w?: number; opacity?: number; progress?: number } = {}) => letter(g, s, x, y, { ...p, color: p.color ?? "#eef6fb" });+ const balloon = (n: string, at: P, to: P, seed: number, q = 1) => { if (q <= 0) return; const a = Math.atan2(to[1] - at[1], to[0] - at[0]), s3 = (i: number) => Math.min(1, Math.max(0, q * 3 - i)); ring(at[0], at[1], 12.5, 1.5, seed, { progress: s3(0) }); text(n, at[0] - 0.5, at[1] - 6, { cap: 12, align: "center", seed, w: 1.6, progress: s3(1) }); ln([at[0] + Math.cos(a) * 13, at[1] + Math.sin(a) * 13], to, 1.05, { seed: seed + 1, color: CYAN, progress: s3(2) }); if (q >= 1) fill(oval(to[0], to[1], 2.4, 2.4, 7), WHITE, 0.95); };+ // a note with its leader: the word first, the rule under it, then the leader out to the part+ const callout = (t: string, at: P, to: P, seed: number, align: "left" | "right" = "left", q = 1, cap = 10) => { if (q <= 0) return; const wd = width(t, cap), x0 = align === "left" ? at[0] : at[0] - wd, s3 = (i: number) => Math.min(1, Math.max(0, q * 3 - i)); text(t, x0, at[1] - cap - 1, { cap, seed, color: WHITE, progress: s3(0) }); ln([x0 - 2, at[1] + 4], [x0 + wd + 2, at[1] + 4], 1, { seed: seed + 1, color: CYAN, progress: s3(1) }); const from: P = align === "left" ? [x0 - 2, at[1] + 4] : [x0 + wd + 2, at[1] + 4]; ln(from, to, 1, { seed: seed + 2, color: CYAN, progress: s3(2) }); if (q >= 1) fill(oval(to[0], to[1], 2.2, 2.2, 7), WHITE, 0.95); };+ // A LINEAR DIMENSION between a and b, measured along the unit direction `u`, set off by `off`+ // along the normal. Order a draftsman uses: witness lines, the dimension line, arrows, the figure.+ const dim = (a: P, b: P, off: number, label: string, seed: number, q = 1, o: { cap?: number; gap?: number; ext?: number; textSide?: number } = {}) => {+ if (q <= 0) return; const cap = o.cap ?? 10, gap = o.gap ?? 4, ext = o.ext ?? 5, dx = b[0] - a[0], dy = b[1] - a[1], L = Math.hypot(dx, dy) || 1, u: P = [dx / L, dy / L], n: P = [u[1], -u[0]];+ const A: P = [a[0] + n[0] * off, a[1] + n[1] * off], B: P = [b[0] + n[0] * off, b[1] + n[1] * off], sg = Math.sign(off) || 1;+ const wit = (p0: P, i: number, qq: number) => ln([p0[0] + n[0] * gap * sg, p0[1] + n[1] * gap * sg], [p0[0] + n[0] * (off + ext * sg), p0[1] + n[1] * (off + ext * sg)], 0.85, { seed: seed + i, color: CYAN, progress: qq });+ wit(a, 0, cut(q, 0, 0.25)); wit(b, 1, cut(q, 0.1, 0.35));+ ln(A, B, 0.95, { seed: seed + 2, color: CYAN, progress: cut(q, 0.3, 0.6) });+ if (cut(q, 0.6, 0.7) >= 1) { const ang = Math.atan2(u[1], u[0]); arrow(A, ang + Math.PI, 10, CYAN); arrow(B, ang, 10, CYAN); }+ const m = lerp(A, B, 0.5), ts = o.textSide ?? 1, tq = cut(q, 0.7, 1), wd = width(label, cap); /* unidirectional dimensioning: every figure reads from the bottom of the sheet */+ if (Math.abs(u[0]) >= Math.abs(u[1])) k0text(label, m[0], m[1] - cap - 3.5, { cap, align: "center", seed: seed + 3, w: Math.max(1, cap * 0.11), progress: tq });+ else k0text(label, ts > 0 ? m[0] + 6 : m[0] - 6 - wd, m[1] - cap / 2, { cap, seed: seed + 3, w: Math.max(1, cap * 0.11), progress: tq });+ };+ const raw = (): Ctx => g.cur;+ return { g, ink, pen, ln, dash, chain, arrow, fill, ring, circle, chainRing, hatch, stipple, text, balloon, callout, dim, raw, arc, poly, oval, jitter, rng };+};++// ---------------------------------------------------------------- the sheet (the ground: frame 0)+export const sheet = (k: Kit) => {+ const c = k.g.main, e = k.g.env, W = e.W, H = e.H, dw = Math.round(W * e.scale), dh = Math.round(H * e.scale);+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.fillStyle = GROUND; c.fillRect(0, 0, dw, dh); c.restore();+ c.save(); c.setTransform(e.scale, 0, 0, e.scale, 0, 0); /* the exposure is never even: brighter where the arc lamp stood */+ const glow = c.createRadialGradient(W * 0.46, H * 0.4, 60, W * 0.5, H * 0.5, W * 0.78); glow.addColorStop(0, "rgba(58,120,178,0.34)"); glow.addColorStop(0.55, "rgba(30,84,140,0.1)"); glow.addColorStop(1, "rgba(4,16,36,0.5)"); c.fillStyle = glow; c.fillRect(0, 0, W, H);+ c.restore();+ k.g.paper("blueMottle", 0.55);+ c.save(); c.setTransform(e.scale, 0, 0, e.scale, 0, 0); /* two old fold lines: a sheet that has lived in a drawer */+ [[W * 0.5 + 3, 0, W * 0.5 - 2, H], [0, H * 0.5 - 4, W, H * 0.5 + 2]].forEach(([x0, y0, x1, y1]) => { c.strokeStyle = "rgba(190,225,245,0.07)"; c.lineWidth = 2.4; c.beginPath(); c.moveTo(x0, y0); c.lineTo(x1, y1); c.stroke(); c.strokeStyle = "rgba(2,10,26,0.16)"; c.lineWidth = 1.2; c.beginPath(); c.moveTo(x0 + 2, y0 + 2); c.lineTo(x1 + 2, y1 + 2); c.stroke(); });+ c.restore();+ dust(k);+};+export const dust = (k: Kit) => k.g.group("plain", () => { const c = k.raw(), r = k.rng(77), W = k.g.env.W, H = k.g.env.H; k.g.touch(0, 0, W, H); for (let i = 0; i < 260; i++) { c.globalAlpha = 0.1 + r() * 0.3; c.fillStyle = r() < 0.75 ? "#dff1fb" : "#06142c"; c.beginPath(); c.arc(r() * W, r() * H, 0.4 + r() * r() * 1.8, 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; });+export const tooth = (g: Gfx) => { g.paper("paper", 0.34); g.paper("coldpress", 0.2); };++// the border is ruled stroke by stroke, outer frame first, inner rule chasing it; zone marks after+export const border = (k: Kit, p = 1) => { if (p <= 0) return; const W = k.g.env.W, H = k.g.env.H; k.ink(() => {+ const q = stagger(cut(p, 0, 0.7), 8, 0.42);+ [[22, 2.6], [34, 1.2]].forEach(([m, w], j) => [[[m, m], [W - m, m]], [[W - m, m], [W - m, H - m]], [[W - m, H - m], [m, H - m]], [[m, H - m], [m, m]]].forEach(([a, b], i) => k.ln(a as P, b as P, w, { seed: 900 + j * 4 + i, taper: 0.15, progress: q(i * 2 + j) })));+ const z = cut(p, 0.65, 1);+ ["A", "B", "C", "D"].forEach((t, i) => { const y = 34 + ((H - 68) * (i + 0.5)) / 4, qq = stagger(z, 8, 0.4)(i); k.text(t, 24.5, y - 4, { cap: 7, seed: 910 + i, color: CYAN, w: 1, progress: qq }); if (i) k.ln([22, 34 + ((H - 68) * i) / 4], [34, 34 + ((H - 68) * i) / 4], 1, { seed: 920 + i, progress: qq }); });+ ["1", "2", "3", "4"].forEach((t, i) => { const x = 34 + ((W - 68) * (i + 0.5)) / 4, qq = stagger(z, 8, 0.4)(i + 4); k.text(t, x, 24.5, { cap: 7, seed: 930 + i, color: CYAN, w: 1, align: "center", progress: qq }); if (i) k.ln([34 + ((W - 68) * i) / 4, 22], [34 + ((W - 68) * i) / 4, 34], 1, { seed: 940 + i, progress: qq }); });+}); };++// ---------------------------------------------------------------- cached part surfaces+// A slot holds one surface and the key its pixels were drawn under. The key must name everything+// the pixels depend on; a slot redrawn under the same key gives the same pixels.+export type Slot = { L: Layer; key: string | null };+export const slot = (env: Env, name: string): Slot => {+ const dw = Math.round(env.W * env.scale), dh = Math.round(env.H * env.scale), id = `bp:${name}:${dw}x${dh}`; let s = env.cache.get(id) as Slot | undefined;+ if (!s) { s = { L: env.canvas(dw, dh), key: null }; env.cache.set(id, s); }+ return s;+};+export const blit = (ctx: Ctx, L: Layer) => { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore(); };+export { arc, poly };diff --git a/engine/src/canvas-core/brokenColour.ts b/engine/src/canvas-core/brokenColour.tsnew file mode 100644index 0000000..56e02b0--- /dev/null+++ b/engine/src/canvas-core/brokenColour.ts@@ -0,0 +1,302 @@+// BROKEN COLOUR · a small harbour at sunrise, painted in dabs.+//+// MEDIUM, physically: oil paint straight from the tube on a lead-white primed linen canvas, worked+// outdoors in one sitting. A flat hog-bristle brush, loaded and put down ONCE: it lands blunt,+// pushes a ridge of paint up along one side, and drags thin where it lifts. Colours are not mixed+// on the palette into the colour of the thing; two or three unmixed colours are laid side by side+// and the eye mixes them at a distance (optical mixing). The linen's weave shows through the thin+// lay-in and in the gaps between dabs.+// MARKS: short, separate, opaque dabs. Water: flat, horizontal, longer. Sky: varied, turning around+// the sun, streaking along the cloud banks. Buildings: short and upright. Hulls: along the hull.+// Masts and oars: one pull of a thin rigger.+// EDGE: no outlines anywhere. A form ends where its dabs stop; the boats are dark dabs against light+// dabs. Edges are lost into the haze, found only on the sunlit rims.+// ORDER: (1) a thin warm imprimatura scrubbed over the white, (2) placement drawn with thinned+// ultramarine, (3) the big masses in big dabs, (4) smaller broken dabs over everything, sky to+// water, (5) boats, masts and the sun restated, (6) complementary accents, (7) reflections,+// (8) the last sparkles on the sun's path.+// PALETTE (high key): lead white, cadmium orange + red, chrome yellow, rose madder, cobalt violet,+// ultramarine, viridian. No black: the darkest dark is ultramarine + rose madder. Complementary+// accents: orange dropped into blue shadow, violet into gold light.+// GROUND: primed linen, plain weave (brokenColourKit.weave), multiplied last.+// LIGHT: ONE sun, low in the east behind the harbour, a little right of centre, orange through+// morning haze. Everything is contre-jour: boats and figures are dark silhouettes with a warm rim+// on their sun side, their cast shadows and reflections fall toward the viewer on the water.+// SUBJECT + STRUCTURE: a working harbour. Left, the far town in haze: warehouse roofs, a campanile,+// a chimney whose smoke drifts east (the wind), a stone breakwater with a lamp post running out+// from the left edge, masts of moored boats. Right, a low headland. Centre, the sun's path on the+// water, a vertical column made of horizontal ripples that break the reflection into bars.+// Focal: a clinker rowing dinghy in the near water, three-quarter from the port side, bow to the+// right and higher than the stern, transom stern, the far gunwale visible as a sliver of lit+// interior; one oarsman on the centre thwart facing the stern (oarsmen face aft), both oars+// squared at mid-drive, the near blade throwing a splash. Mid-distance right, a gaff-rigged+// fishing boat with a rust lugsail half up. Far, in the sun's path, a skiff sculled standing.+// REFERENCE (from knowledge): plein-air harbour studies of the 1870s broken-colour painters (their+// technique only: sun path as horizontal bars, boats as a few dark strokes); the construction of+// a clinker dinghy and the rowing stroke (oarsman faces aft, blades square at the drive); how+// reflections work on rippled water (each ripple faces a different slice of sky, so a reflection+// stretches DOWN and breaks into bars; a vertical mast reflects as a wobbling zig-zag).+import { fractal, rng, type P } from "./core";+import type { Film } from "./film";+import { brush, checkOps, fromHsl, linen, mixC, schedule, smoothstep, staged, toHsl, type Mark, type Op, type RGB } from "./brokenColourKit";++const N = 450, HOLD = N - 30;+const META = { title: "Broken colour · harbour at sunrise", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" as const };+const W = META.W, H = META.H;++// ---------------------------------------------------------------- the motif, in unit coordinates+const HZ = 0.5; // horizon+const SUN: P = [0.62, 0.392], SUN_R = 0.031;+const inPoly = (poly: P[], x: number, y: number) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) c = !c; } return c; };+const interp = (knots: P[], u: number) => { if (u <= knots[0][0]) return knots[0][1]; for (let i = 1; i < knots.length; i++) if (u <= knots[i][0]) { const [a, va] = knots[i - 1], [b, vb] = knots[i]; return va + ((vb - va) * (u - a)) / (b - a || 1); } return knots[knots.length - 1][1]; };+// the far town: roof line, a campanile at 0.13, a chimney at 0.42, stepping down to the harbour mouth+const TOWN: P[] = [[0, 0.437], [0.03, 0.437], [0.031, 0.429], [0.068, 0.429], [0.07, 0.442], [0.1, 0.442], [0.124, 0.44], [0.125, 0.398], [0.1315, 0.384], [0.138, 0.398], [0.139, 0.441], [0.168, 0.445], [0.17, 0.434], [0.218, 0.431], [0.221, 0.447], [0.268, 0.452], [0.3, 0.455], [0.335, 0.451], [0.4, 0.458], [0.417, 0.457], [0.418, 0.409], [0.427, 0.409], [0.428, 0.461], [0.46, 0.47], [0.5, 0.481], [0.525, 0.493], [0.54, 0.5]];+const HEAD: P[] = [[0.66, 0.5], [0.7, 0.487], [0.76, 0.479], [0.86, 0.473], [1, 0.466]];+const town = (u: number, v: number) => u < 0.54 && v < HZ && v > interp(TOWN, u);+const head = (u: number, v: number) => u > 0.66 && v < HZ && v > interp(HEAD, u);+// breakwater: from the left edge out to 0.235, top face lit, sea face in shadow+const JETTY: P[] = [[0, 0.546], [0.12, 0.541], [0.235, 0.536], [0.237, 0.553], [0.12, 0.566], [0, 0.584]];+const JETTY_TOP = (u: number) => 0.546 - (0.01 * u) / 0.235;+// the dinghy (focal): hull, the lit sliver of its far gunwale, the oarsman+const HULL: P[] = [[0.255, 0.699], [0.3, 0.707], [0.35, 0.711], [0.4, 0.707], [0.44, 0.699], [0.468, 0.687], [0.463, 0.698], [0.451, 0.711], [0.4, 0.722], [0.35, 0.727], [0.3, 0.727], [0.262, 0.724]];+const INSIDE: P[] = [[0.26, 0.695], [0.31, 0.699], [0.36, 0.701], [0.41, 0.698], [0.45, 0.692], [0.466, 0.688], [0.44, 0.699], [0.4, 0.707], [0.35, 0.711], [0.3, 0.707], [0.256, 0.699]];+const ROWER: P[] = [[0.363, 0.706], [0.366, 0.686], [0.362, 0.664], [0.354, 0.652], [0.343, 0.653], [0.336, 0.66], [0.327, 0.672], [0.317, 0.681], [0.318, 0.688], [0.331, 0.682], [0.341, 0.692], [0.325, 0.697], [0.318, 0.704], [0.34, 0.706]];+const HEADC: P = [0.351, 0.641], HEAD_R = 0.0105;+const ROW_WL = 0.727;+// the fishing boat (mid right) and its lugsail; the far skiff+const SMACK: P[] = [[0.742, 0.582], [0.8, 0.587], [0.866, 0.577], [0.861, 0.588], [0.85, 0.597], [0.8, 0.6], [0.752, 0.596]];+const SAIL: P[] = [[0.79, 0.458], [0.793, 0.574], [0.748, 0.577], [0.764, 0.53], [0.772, 0.49]];+const SMACK_WL = 0.6, MAST_U = 0.792, MAST_TOP = 0.43;+const SKIFF: P[] = [[0.513, 0.537], [0.535, 0.54], [0.559, 0.534], [0.553, 0.543], [0.52, 0.544]];+const SKIFF_WL = 0.544;+const BOATS = [{ poly: [...HULL], wl: ROW_WL, top: 0.64, k: 1.25 }, { poly: SMACK, wl: SMACK_WL, top: 0.577, k: 1.3 }, { poly: SAIL, wl: SMACK_WL, top: 0.458, k: 1.1 }, { poly: SKIFF, wl: SKIFF_WL, top: 0.515, k: 1.3 }];+const inRower = (u: number, v: number) => inPoly(ROWER, u, v) || Math.hypot(u - HEADC[0], v - HEADC[1]) < HEAD_R;++// ---------------------------------------------------------------- palette+const C = {+ skyTop: [150, 154, 200] as RGB, skyMid: [205, 180, 206] as RGB, skyLow: [236, 198, 186] as RGB,+ glow: [246, 178, 110] as RGB, halo: [252, 206, 132] as RGB, sun: [246, 126, 52] as RGB, sunCore: [252, 184, 96] as RGB,+ cloud: [160, 150, 192] as RGB, cloudLit: [242, 160, 118] as RGB, smoke: [200, 172, 190] as RGB,+ town: [124, 122, 168] as RGB, townLit: [214, 150, 140] as RGB, head: [182, 164, 196] as RGB,+ far: [206, 186, 206] as RGB, mid: [150, 158, 204] as RGB, near: [82, 104, 158] as RGB, green: [96, 142, 146] as RGB,+ path: [246, 146, 66] as RGB, pathHot: [253, 206, 116] as RGB,+ hull: [58, 54, 98] as RGB, rim: [232, 128, 72] as RGB, wood: [176, 112, 96] as RGB, sail: [150, 82, 82] as RGB, sailLit: [226, 124, 78] as RGB,+ jetty: [88, 82, 134] as RGB, jettyTop: [228, 166, 138] as RGB, refl: [74, 72, 122] as RGB,+};+const mix3 = (a: RGB, b: RGB, c: RGB, t: number) => (t < 0.5 ? mixC(a, b, t * 2) : mixC(b, c, (t - 0.5) * 2));+const nz = (s: number, u: number, v: number, fu: number, fv: number, o = 3) => fractal(s, u * 1000, v * 1000, fu, fv, o);++// ---------------------------------------------------------------- the analytic colour field+// region: 0 sky, 1 town/headland, 2 water, 3 boat, 4 jetty, 5 sun, 6 sun path, 7 reflection+type Here = { c: RGB; region: number; ang: number; size: number };+const sunDist = (u: number, v: number) => Math.hypot(u - SUN[0], (v - SUN[1]) * 1.05);+const sky = (u: number, v: number): Here => {+ const t = Math.min(1, v / HZ), d = sunDist(u, v);+ let c = mix3(C.skyTop, C.skyMid, C.skyLow, Math.pow(t, 1.15));+ c = mixC(c, C.glow, 0.7 * Math.exp(-((d / 0.2) ** 2)));+ c = mixC(c, C.halo, 0.85 * Math.exp(-((d / 0.065) ** 2)));+ // cloud banks: long horizontal streaks, their undersides lit where they pass the sun+ let bank = 0;+ for (const [vb, th, s] of [[0.12, 0.024, 3], [0.205, 0.018, 5], [0.27, 0.014, 7], [0.322, 0.009, 9]] as [number, number, number][]) {+ const wav = vb + 0.018 * (nz(s, u, 0, 0.0025, 0.0025, 2) - 0.5), thick = th * smoothstep(0.35, 0.7, nz(s + 1, u, 0, 0.004, 0.004, 3)), k = thick < 1e-4 ? 0 : smoothstep(thick, thick * 0.3, Math.abs(v - wav));+ if (k > 0) { const lit = v > wav ? Math.exp(-(((u - SUN[0]) / 0.22) ** 2)) : 0.15 * Math.exp(-(((u - SUN[0]) / 0.3) ** 2)); c = mixC(c, mixC(C.cloud, C.cloudLit, lit), 0.75 * k); bank = Math.max(bank, k); }+ }+ // smoke from the chimney, drifting east and rising+ const sx = u - 0.422; if (sx > -0.01 && sx < 0.16 && v < 0.415) { const cy = 0.409 - 0.5 * sx - 1.2 * sx * sx, wdt = 0.006 + 0.1 * sx, k = smoothstep(wdt, 0, Math.abs(v - cy)) * smoothstep(0.16, 0.04, sx) * (0.6 + 0.4 * nz(13, u, v, 0.02, 0.02, 2)); c = mixC(c, C.smoke, 0.5 * k); }+ // strokes streak along the banks, loosen higher up, and turn part-way round the sun close to it+ // the hand changes direction patch by patch: some patches hatched up-right, some down-right, some flat+ const hatch = nz(21, u, v, 0.0035, 0.0045, 2), lean = hatch < 0.42 ? -0.55 : hatch > 0.58 ? 0.5 : 0;+ const free = (-0.06 + lean * smoothstep(0.02, 0.1, Math.abs(hatch - 0.5)) + (nz(19, u, v, 0.009, 0.012, 2) - 0.5) * (0.7 + 0.8 * (1 - t))) * (1 - 0.8 * bank), tang = Math.atan2(v - SUN[1], u - SUN[0]) + Math.PI / 2, diff = ((tang - free + Math.PI * 2.5) % Math.PI) - Math.PI / 2;+ const ang = free + diff * 0.5 * smoothstep(0.13, 0.045, d);+ if (d < SUN_R * 1.35) { const sc = mixC(mixC(C.sun, c, smoothstep(0.8, 1.35, d / SUN_R)), [255, 236, 176], smoothstep(0.7, 0.2, d / SUN_R)); return { c: sc, region: d < SUN_R * 1.05 ? 5 : 0, ang: ang + (nz(23, u, v, 0.05, 0.05, 1) - 0.5) * 2, size: 0.45 }; }+ return { c, region: 0, ang, size: 1 };+};+const land = (u: number, v: number): Here => {+ const hz = 1 - Math.exp(-(((u - SUN[0]) / 0.22) ** 2)) * 0.4; // haze thicker toward the sun+ if (head(u, v)) return { c: mixC(C.head, C.skyLow, 0.25), region: 1, ang: (nz(23, u, v, 0.02, 0.02) - 0.5) * 0.4, size: 0.7 };+ const top = interp(TOWN, u), edge = smoothstep(0.006, 0, v - top), lit = edge * Math.exp(-(((u - SUN[0]) / 0.35) ** 2));+ let c = mixC(C.town, C.skyLow, 0.28 * (1 - hz) + 0.12); c = mixC(c, C.townLit, 0.7 * lit);+ c = mixC(c, mixC(C.town, [96, 94, 150], 0.5), 0.3 * smoothstep(0.35, 0.65, nz(29, u, v, 0.03, 0.006, 2))); // gables and gaps in shadow+ return { c, region: 1, ang: (nz(31, u, v, 0.02, 0.02) - 0.5) * 0.5, size: 0.5 };+};+const ripple = (u: number, v: number, s = 41) => nz(s, u, v, 0.0045, 0.075 + 0.05 * (1 - (v - HZ) * 2), 3);+const water = (u: number, v: number): Here => {+ const t = (v - HZ) / (1 - HZ), rp = ripple(u, v);+ let c = mix3(C.far, C.mid, C.near, Math.pow(t, 0.75));+ c = mixC(c, C.green, 0.28 * t * smoothstep(0.4, 0.7, nz(43, u, v, 0.0015, 0.004, 2)));+ c = mixC(c, C.glow, 0.35 * Math.exp(-(((u - SUN[0]) / 0.28) ** 2)) * (1 - t) ** 2); // the glow of the sky in the far water+ c = mixC(c, rp > 0.5 ? [240, 222, 226] : C.near, Math.abs(rp - 0.5) * 0.5); // each ripple faces another slice of sky+ let region = 2;+ // the sun's path: widening toward us, broken into horizontal bars by the ripples+ const uc = SUN[0] + 0.006 * (nz(47, 0, v, 0.01, 0.01, 2) - 0.5), hw = 0.012 + 0.15 * Math.pow(v - HZ, 0.85), k = Math.exp(-(((u - uc) / hw) ** 2)), bar = smoothstep(0.44, 0.6, ripple(u, v, 53)), inten = k * (0.25 + 0.75 * bar) * (1 - 0.4 * t);+ if (inten > 0.08) { c = mixC(c, mixC(C.path, C.pathHot, smoothstep(0.55, 0.95, k * bar)), Math.min(1, inten * 1.25)); if (inten > 0.3) region = 6; }+ // the town and headland, mirrored and broken just under the horizon+ const wob = 0.012 * (ripple(u, v, 59) - 0.5), vm = HZ - (v - HZ) * 1.05;+ if (v < HZ + 0.07 && (town(u + wob, vm) || head(u + wob, vm)) && ripple(u, v, 61) > 0.36) { c = mixC(c, mixC(C.town, C.far, 0.35), 0.75); region = 7; }+ // the breakwater's reflection+ if (u < 0.24 && v > JETTY_TOP(u) + 0.02 && v < 0.62 && inPoly(JETTY, u + wob, 2 * 0.566 - v + (0.584 - 0.566) * (1 - u / 0.235))) { c = mixC(c, C.refl, 0.55); region = 7; }+ // boats stretch DOWN in the water and break into bars+ for (const b of BOATS) {+ if (v <= b.wl || v > b.wl + (b.wl - b.top) * b.k) continue;+ const vm2 = b.wl - (v - b.wl) / b.k, w2 = 0.004 * (v - b.wl) * 60 * (ripple(u, v, 67) - 0.5);+ if ((inPoly(b.poly, u + w2, vm2) || (b.poly === BOATS[0].poly && inRower(u + w2, vm2))) && ripple(u, v, 71) > 0.3) { c = mixC(c, C.refl, 0.8); region = 7; }+ }+ if (v > SMACK_WL && v < SMACK_WL + (SMACK_WL - MAST_TOP) * 0.9) { const zz = MAST_U + 0.006 * Math.sin((v - SMACK_WL) * 260) * smoothstep(0, 0.05, v - SMACK_WL); if (Math.abs(u - zz) < 0.0022 && ripple(u, v, 73) > 0.35) { c = mixC(c, C.refl, 0.7); region = 7; } }+ return { c, region, ang: (nz(79, u, v, 0.01, 0.01, 2) - 0.5) * 0.08, size: 1 };+};+export const field = (u: number, v: number): Here => {+ if (v >= JETTY_TOP(u) && inPoly(JETTY, u, v)) { const top = v < JETTY_TOP(u) + 0.007; return { c: top ? C.jettyTop : mixC(C.jetty, C.skyLow, 0.12 * (1 - u)), region: 4, ang: -0.04, size: 0.6 }; }+ if (inRower(u, v)) { const rim = inRower(u + 0.004, v) ? 0 : 1; return { c: mixC(C.hull, C.rim, rim * 0.8), region: 3, ang: Math.PI / 2, size: 0.3 }; }+ if (inPoly(INSIDE, u, v)) return { c: C.wood, region: 3, ang: -0.06, size: 0.35 };+ if (inPoly(HULL, u, v)) { const rim = inPoly(HULL, u, v - 0.004) ? 0 : 1; return { c: mixC(C.hull, C.rim, rim * 0.75), region: 3, ang: -0.05, size: 0.4 }; }+ if (inPoly(SAIL, u, v)) { const e = inPoly(SAIL, u - 0.005, v) ? 0 : 1; return { c: mixC(C.sail, C.sailLit, 0.25 + 0.6 * e + 0.2 * (v - 0.46) * 5), region: 3, ang: Math.PI / 2 + 0.1, size: 0.4 }; }+ if (inPoly(SMACK, u, v)) return { c: mixC(C.hull, C.rim, inPoly(SMACK, u, v - 0.003) ? 0.05 : 0.6), region: 3, ang: 0, size: 0.35 };+ if (inPoly(SKIFF, u, v)) return { c: mixC(C.hull, C.path, 0.15), region: 3, ang: 0, size: 0.3 };+ if (v < HZ) { if (town(u, v) || head(u, v)) return land(u, v); return sky(u, v); }+ return water(u, v);+};++// ---------------------------------------------------------------- turning the field into brush marks+const ACC_WARM: RGB[] = [[238, 138, 82], [242, 170, 128], [228, 112, 92]]; // orange and rose, into blue shadow+const ACC_COOL: RGB[] = [[150, 128, 204], [172, 150, 214], [128, 120, 190]]; // violet and lilac, into gold light+const broken = (c: RGB, r: () => number, hj: number, lj: number, sat: [number, number]): RGB => { const [h, s, l] = toHsl(c); return fromHsl([h + (r() - 0.5) * 2 * hj, Math.min(1, s * (sat[0] + r() * (sat[1] - sat[0]))), Math.max(0.04, Math.min(0.97, l + (r() - 0.5) * 2 * lj))]); };+const mk = (x: number, y: number, ang: number, L: number, w: number, rgb: RGB, alpha: number, seed: number, kind: 0 | 1 | 2 = 0, bend = 0): Mark => ({ a: [x - (Math.cos(ang) * L) / 2, y - (Math.sin(ang) * L) / 2], b: [x + (Math.cos(ang) * L) / 2, y + (Math.sin(ang) * L) / 2], bend, w, rgb, alpha, seed, kind });+const line = (pts: P[], w: number, rgb: RGB, alpha: number, seed: number, kind: 0 | 1 | 2 = 1): Mark[] => pts.slice(1).map((p, i) => ({ a: [pts[i][0] * W, pts[i][1] * H], b: [p[0] * W, p[1] * H], bend: 0, w, rgb, alpha, seed: seed + i, kind }));+type Pass = { marks: Mark[]; f0: number; f1: number; dur: number; pace?: (u: number) => number };+// grid points, jittered, visited in a sweep that wanders patch by patch the way a hand moves round a canvas+const sweep = (step: number, seed: number, patch: number, keyOf: (x: number, y: number, h: Here) => number) => {+ const r = rng(seed), out: { x: number; y: number; h: Here; key: number }[] = [];+ for (let y = -step / 2; y < H + step; y += step) for (let x = -step / 2; x < W + step; x += step) {+ const px = x + (r() - 0.5) * step * 1.3, py = y + (r() - 0.5) * step * 1.3, h = field(Math.max(0, Math.min(1, px / W)), Math.max(0, Math.min(1, py / H)));+ out.push({ x: px, y: py, h, key: keyOf(px, py, h) + fractal(seed + 2, px, py, 1 / patch, 1 / patch, 2) * patch * 1.4 + r() * patch * 0.25 });+ }+ return out.sort((a, b) => a.key - b.key);+};+const regionOrder = (h: Here) => (h.region === 0 || h.region === 5 ? 0 : h.region === 1 ? 1 : h.region === 4 ? 3 : h.region === 3 ? 4 : 2);++const passes = (): Pass[] => {+ const r = rng(1874);+ // (1) imprimatura: thin warm rose-ochre, scrubbed with a big brush, the white still breathing through+ const tone: Mark[] = [];+ for (let i = 0; i < 16; i++) { const y = (i + 0.5) * (H / 16) + (r() - 0.5) * 20, x0 = -60 + r() * 80, x1 = W + 60 - r() * 80, ya = y + (r() - 0.5) * 50, yb = y + (r() - 0.5) * 50, back = i % 2 === 1; tone.push({ a: back ? [x1, yb] : [x0, ya], b: back ? [x0, ya] : [x1, yb], bend: (r() - 0.5) * 40, w: 90 + r() * 40, rgb: i < 8 ? [218, 172, 146] : [200, 164, 156], alpha: 0.62, seed: 100 + i, kind: 2 }); }+ // (2) placement in thinned ultramarine: horizon, town, breakwater, the three boats, the sun+ const U: RGB = [96, 104, 168], draw: Mark[] = [];+ draw.push(...line([[0.02, HZ + 0.001], [0.3, HZ - 0.001], [0.62, HZ + 0.002], [0.98, HZ]], 3, U, 0.6, 200));+ draw.push(...line(TOWN.filter((_, i) => i % 3 === 0).concat([[0.54, 0.5]]), 3, U, 0.55, 210));+ draw.push(...line([[0.66, 0.5], [0.8, 0.476], [1, 0.466]], 3, U, 0.5, 230));+ draw.push(...line([[0, 0.546], [0.235, 0.536], [0.237, 0.553], [0, 0.584]], 3, U, 0.55, 240));+ draw.push(...line([[0.255, 0.699], [0.35, 0.711], [0.468, 0.687], [0.451, 0.711], [0.35, 0.727], [0.262, 0.724], [0.255, 0.699]], 3.2, U, 0.65, 250));+ draw.push(...line([[0.34, 0.706], [0.345, 0.66], [0.35, 0.641]], 2.4, U, 0.5, 260), ...line([[0.336, 0.708], [0.305, 0.775]], 2, U, 0.45, 263), ...line([[0.345, 0.701], [0.372, 0.676]], 2, U, 0.45, 265));+ draw.push(...line([[0.742, 0.582], [0.866, 0.577], [0.8, 0.6], [0.742, 0.582]], 2.2, U, 0.45, 270), ...line([[MAST_U, 0.585], [MAST_U, MAST_TOP]], 2, U, 0.45, 274));+ draw.push(...line([[0.513, 0.538], [0.559, 0.535]], 2, U, 0.45, 276));+ draw.push(...Array.from({ length: 6 }, (_, i) => { const a0 = -1.2 + i * 1.05, a1 = a0 + 1.0; return { a: [(SUN[0] + Math.cos(a0) * SUN_R) * W, (SUN[1] + Math.sin(a0) * SUN_R) * H] as P, b: [(SUN[0] + Math.cos(a1) * SUN_R) * W, (SUN[1] + Math.sin(a1) * SUN_R) * H] as P, bend: -SUN_R * W * 0.14, w: 2.2, rgb: U, alpha: 0.45, seed: 280 + i, kind: 1 as const }; }));+ // (3) the big masses: large dabs, colour taken from a wide neighbourhood, little breaking yet+ const mass: Mark[] = sweep(W * 0.022, 300, W * 0.2, (x, y, h) => regionOrder(h) * 1e5 + y).map(({ x, y, h }, i) => {+ let acc: RGB = [0, 0, 0]; if (h.region === 3) acc = h.c; else for (const [dx, dy] of [[0, 0], [-22, 0], [22, 0], [0, -14], [0, 14]]) { const q = field(Math.max(0, Math.min(1, (x + dx) / W)), Math.max(0, Math.min(1, (y + dy) / H))).c; acc = [acc[0] + q[0] / 5, acc[1] + q[1] / 5, acc[2] + q[2] / 5]; }+ const water = h.region >= 2 && h.region !== 3 && h.region !== 4 && h.region !== 5, k = h.region === 3 ? 0.45 : h.region === 1 ? 0.6 : 1;+ return mk(x, y, h.ang, (water ? 64 : 50) * k * (0.8 + r() * 0.4), (water ? 17 : 22) * k * (0.8 + r() * 0.4), broken(acc, r, 0.01, 0.025, [0.9, 1.05]), 0.9, 1000 + i, 0, (r() - 0.5) * 6);+ });+ // (4) broken colour: small dabs everywhere, hue and value broken, the eye does the mixing+ const brk: Mark[] = [];+ sweep(W * 0.0095, 400, W * 0.12, (x, y, h) => regionOrder(h) * 1e5 + y).forEach(({ x, y, h }, i) => {+ const water = h.region === 2 || h.region === 6 || h.region === 7, sky = h.region === 0;+ if (sky && r() < 0.3) return; // the sky breathes: the mass shows between dabs+ const len = W * (water ? 0.028 : sky ? 0.026 : 0.021) * h.size * (0.6 + r() * 0.7), wd = W * (water ? 0.0058 : sky ? 0.0078 : 0.0072) * Math.max(0.55, h.size) * (0.7 + r() * 0.5);+ let c = broken(h.c, r, sky ? 0.025 : 0.035, water ? 0.07 : sky ? 0.05 : 0.03, [0.95, water ? 1.4 : 1.25]); const [, , l] = toHsl(h.c), warm = h.c[0] > h.c[2] + 20;+ if (h.region !== 3 && h.region !== 5 && r() < (water ? 0.025 : 0.018)) c = warm ? ACC_COOL[Math.floor(r() * 3)] : l < 0.6 ? ACC_WARM[Math.floor(r() * 3)] : c;+ brk.push(mk(x, y, h.ang + (r() - 0.5) * (water ? 0.08 : sky ? 0.55 : 0.35), len, wd, c, 0.95, 5000 + i, 0, (r() - 0.5) * (water ? 1.5 : 5)));+ });+ // (5) restate the boats, masts, breakwater and the sun, each stroke following its form+ const det: Mark[] = [], inside = (poly: P[], n: number, seed: number, f: (x: number, y: number, h: Here, rr: () => number) => Mark | null) => { const rr = rng(seed); let x0 = 1, y0 = 1, x1 = 0, y1 = 0; poly.forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }); for (let k = 0, got = 0; k < n * 20 && got < n; k++) { const u = x0 + rr() * (x1 - x0), v = y0 + rr() * (y1 - y0); if (!inPoly(poly, u, v)) continue; const m = f(u * W, v * H, field(u, v), rr); if (m) { det.push(m); got++; } } };+ // the town restated as one hazy mass: flat roofs laid horizontally, the campanile and chimney upright+ const TOWN_POLY: P[] = [...TOWN, [0.54, HZ], [0, HZ]];+ inside(TOWN_POLY, 480, 590, (x, y, h, rr) => mk(x, y, (rr() - 0.5) * 0.25, 15 * (0.7 + rr() * 0.6), 6.5, broken(h.c, rr, 0.02, 0.035, [0.9, 1.15]), 0.95, 5900 + Math.floor(x * 5 + y)));+ det.push(...line([[0.1315, 0.44], [0.1315, 0.39]], 6, mixC(C.town, C.townLit, 0.15), 0.95, 596, 0), ...line([[0.4225, 0.458], [0.4225, 0.411]], 5, mixC(C.town, C.townLit, 0.1), 0.95, 598, 0));+ // masts of the moored boats behind the breakwater: one pull of the rigger each, lost in the haze+ [[0.245, 0.452, 0.385], [0.262, 0.453, 0.36], [0.287, 0.455, 0.402], [0.31, 0.455, 0.378], [0.352, 0.453, 0.395]].forEach(([u, v0, v1], i) => det.push(...line([[u, v0], [u + 0.001, v1]], 1.9, mixC(C.town, C.skyLow, 0.2), 0.8, 600 + i)));+ inside(JETTY, 70, 610, (x, y, h, rr) => mk(x, y, -0.04 + (rr() - 0.5) * 0.1, 22 * (0.7 + rr() * 0.5), 6.5, broken(h.c, rr, 0.02, 0.05, [0.9, 1.2]), 0.95, 6100 + Math.floor(x * 7 + y)));+ det.push(...line([[0.226, 0.537], [0.2265, 0.49]], 3, [70, 66, 112], 0.95, 620), ...line([[0.2215, 0.49], [0.2315, 0.49]], 5, [250, 196, 120], 0.95, 622, 0));+ // the far skiff, sculled standing, dead in the sun's path+ inside(SKIFF, 14, 630, (x, y, _h, rr) => mk(x, y, 0.02, 12, 4.4, mixC(C.hull, [120, 70, 90], rr() * 0.4), 0.96, 6300 + Math.floor(x + y * 3)));+ det.push(...line([[0.537, 0.538], [0.536, 0.514]], 4.2, [60, 52, 92], 0.96, 640), ...line([[0.536, 0.52], [0.567, 0.55]], 1.8, [60, 52, 92], 0.9, 642));+ // the fishing boat: hull along its length, lugsail in upright dabs with its lit leech, mast and gaff+ inside(SMACK, 40, 650, (x, y, h, rr) => mk(x, y, (rr() - 0.5) * 0.12, 16 * (0.7 + rr() * 0.5), 5, broken(h.c, rr, 0.02, 0.05, [0.9, 1.2]), 0.96, 6500 + Math.floor(x * 3 + y)));+ inside(SAIL, 55, 660, (x, y, h, rr) => mk(x, y, Math.PI / 2 + 0.12 + (rr() - 0.5) * 0.2, 17 * (0.7 + rr() * 0.5), 6, broken(h.c, rr, 0.03, 0.07, [0.9, 1.3]), 0.96, 6600 + Math.floor(x * 3 + y)));+ det.push(...line([[MAST_U, 0.588], [MAST_U - 0.0015, MAST_TOP]], 3, [64, 56, 96], 0.96, 670), ...line([[MAST_U, 0.572], [0.747, 0.576]], 2.4, [64, 56, 96], 0.9, 672), ...line([[0.79, 0.458], [0.772, 0.49]], 2, [226, 124, 78], 0.9, 674));+ // the dinghy: interior sliver, hull planks along the sheer, a sunlit rim on the gunwale+ inside(INSIDE, 26, 680, (x, y, _h, rr) => mk(x, y, -0.06 + (rr() - 0.5) * 0.1, 13, 3.6, broken(C.wood, rr, 0.03, 0.08, [0.9, 1.3]), 0.96, 6800 + Math.floor(x * 3 + y)));+ inside(HULL, 95, 690, (x, y, h, rr) => { const u = x / W, slope = u > 0.43 ? -0.35 : u < 0.28 ? 0.1 : -0.04; return mk(x, y, slope + (rr() - 0.5) * 0.08, 19 * (0.7 + rr() * 0.5), 5.4, broken(h.c, rr, 0.03, 0.05, [0.9, 1.25]), 0.97, 6900 + Math.floor(x * 3 + y)); });+ det.push(...line([[0.258, 0.7], [0.3, 0.7075], [0.35, 0.7115], [0.4, 0.7075], [0.44, 0.6995], [0.467, 0.688]], 3.2, C.rim, 0.95, 700, 0));+ det.push(...line([[0.265, 0.7235], [0.3, 0.7265], [0.35, 0.7265], [0.4, 0.7215], [0.45, 0.7105]], 3.6, [40, 40, 80], 0.9, 710, 0));+ // the oarsman: upright dabs, a warm rim down his sun side, cap and head last+ inside(ROWER, 75, 720, (x, y, h, rr) => mk(x, y, Math.PI / 2 + (rr() - 0.5) * 0.4, 10 * (0.7 + rr() * 0.5), 6.5, broken(h.c, rr, 0.02, 0.04, [0.9, 1.1]), 0.97, 7200 + Math.floor(x * 3 + y)));+ det.push(...line([[0.3655, 0.704], [0.3665, 0.686], [0.3625, 0.665], [0.356, 0.654]], 2.6, C.rim, 0.9, 730, 0));+ for (let k = 0; k < 7; k++) { const a = (k / 6) * Math.PI * 2, rr = k === 6 ? 0 : HEAD_R * 0.32; det.push(mk((HEADC[0] + Math.cos(a) * rr) * W, (HEADC[1] + Math.sin(a) * rr) * H, a + Math.PI / 2, 9, 7, k === 0 ? mixC(C.hull, C.rim, 0.6) : C.hull, 0.97, 740 + k)); }+ det.push(mk((HEADC[0] - 0.004) * W, (HEADC[1] - 0.008) * H, -0.1, 12, 4.5, [52, 50, 88], 0.97, 748)); // the cap's brim, toward the stern+ // oars squared at the drive: near blade toward us throwing a splash, far blade beyond the hull++ // the sun, all dabs: a hot core of cream and yellow laid every which way, orange round it, and orange and+ // pink dabs breaking the edge out into the haze so there is never a clean circle+ { const sr = rng(760), SX = SUN[0] * W, SY = SUN[1] * H, R = SUN_R * W;+ const at = (rad: number, spread: number) => { const a = sr() * Math.PI * 2, q = rad + (sr() - 0.5) * spread; return [SX + Math.cos(a) * q * R, SY + Math.sin(a) * q * R * 0.95, a] as const; };+ for (let k = 0; k < 16; k++) { const [x, y, a] = at(0.62, 0.5); det.push(mk(x, y, a + Math.PI / 2 + (sr() - 0.5) * 0.9, 11 + sr() * 9, 6 + sr() * 3, [[246, 128, 56], [240, 110, 60], [250, 150, 70]][k % 3] as RGB, 0.95, 760 + k)); }+ for (let k = 0; k < 18; k++) { const [x, y, a] = at(1.05, 0.7); det.push(mk(x, y, (sr() < 0.5 ? a + Math.PI / 2 : a) + (sr() - 0.5) * 0.8, 8 + sr() * 10, 4 + sr() * 3, [[246, 146, 80], [240, 158, 150], [250, 176, 120], [236, 136, 128]][k % 4] as RGB, 0.9, 780 + k)); }+ for (let k = 0; k < 22; k++) { const [x, y] = at(0.22, 0.55); det.push(mk(x, y, (sr() - 0.5) * 2.4, 8 + sr() * 7, 5 + sr() * 3, [[255, 238, 180], [255, 226, 140], [252, 206, 110]][k % 3] as RGB, 0.97, 800 + k)); } }+ // (6) accents: orange into the blue shadow of the near water and the town, violet into the gold+ const acc: Mark[] = [];+ for (let k = 0, got = 0; k < 6000 && got < 150; k++) {+ const x = r() * W, y = r() * H, h = field(x / W, y / H), [, , l] = toHsl(h.c); let c: RGB | null = null;+ if (h.region === 6 && r() < 0.8) c = ACC_COOL[Math.floor(r() * 3)];+ else if ((h.region === 2 && y > 0.62 * H) || h.region === 1) { if (l < 0.5 && r() < 0.2) c = ACC_WARM[Math.floor(r() * 3)]; }+ else if (h.region === 0 && h.c[0] > h.c[2] + 30 && sunDist(x / W, y / H) > 0.13 && r() < 0.15) c = ACC_COOL[Math.floor(r() * 3)];+ if (!c) continue; got++;+ acc.push(mk(x, y, h.ang, W * 0.016 * (0.6 + r() * 0.6), W * 0.0052, c, 0.95, 8000 + got));+ }+ // (7) reflections: horizontal bars, sun's path first, then the boats' dark stretched shapes+ const refl: Mark[] = [];+ for (let k = 0, got = 0; k < 60000 && got < 700; k++) {+ const u = SUN[0] + (r() - 0.5) * 0.36, v = HZ + 0.004 + r() * (1 - HZ), h = field(u, v); if (h.region !== 6) continue; got++;+ refl.push(mk(u * W, v * H, (r() - 0.5) * 0.05, W * (0.012 + 0.02 * r()) * (0.6 + (v - HZ)), W * 0.0042 * (0.7 + 0.6 * (v - HZ)), broken(h.c, r, 0.02, 0.05, [1, 1.3]), 0.97, 9000 + got));+ }+ const refDark: Mark[] = [];+ for (let k = 0, got = 0; k < 90000 && got < 420; k++) {+ const u = 0.2 + r() * 0.7, v = HZ + r() * 0.35, h = field(u, v); if (h.region !== 7) continue; got++;+ refDark.push(mk(u * W, v * H, (r() - 0.5) * 0.06, W * (0.01 + 0.014 * r()), W * 0.0045, broken(h.c, r, 0.02, 0.04, [0.9, 1.1]), 0.95, 11000 + got));+ }+ refDark.sort((a, b) => a.a[1] - b.a[1]);+ // (8) the last sparkles: near-white bars on the crests of the path+ const spark: Mark[] = [];+ for (let k = 0, got = 0; k < 40000 && got < 110; k++) {+ const u = SUN[0] + (r() - 0.5) * 0.25, v = HZ + 0.01 + r() * 0.4, h = field(u, v); if (h.region !== 6 || ripple(u, v, 53) < 0.62) continue; got++;+ spark.push(mk(u * W, v * H, 0, W * (0.006 + 0.01 * r()), W * 0.0032, r() < 0.7 ? [255, 238, 190] : [255, 214, 150], 0.98, 12000 + got));+ }+ // (9) last touches over the water: the oars, squared at the drive, the near blade throwing a splash+ const oars: Mark[] = [...line([[0.318, 0.684], [0.337, 0.707], [0.322, 0.745], [0.306, 0.776]], 3.8, [56, 52, 92], 0.96, 750), mk(0.304 * W, 0.779 * H, 1.25, 20, 9, [60, 58, 100], 0.96, 754),+ ...line([[0.321, 0.683], [0.35, 0.697], [0.393, 0.682]], 2.4, [60, 56, 96], 0.94, 756), mk(0.398 * W, 0.6815 * H, -0.12, 15, 4.2, [84, 80, 128], 0.96, 758),+ ...[[-14, 2], [-6, -4], [4, 3], [12, -2], [-2, 7]].map(([dx, dy], k) => mk(0.304 * W + dx, 0.781 * H + dy, (k - 2) * 0.1, 9, 3.4, k % 2 ? [236, 232, 240] : [214, 206, 232], 0.95, 760 + k))];+ const up = (u: number) => u * u * (3 - 2 * u) * 0.35 + u * 0.65; // a hand settling into the rhythm+ return [+ { marks: tone, f0: 0.5, f1: 40, dur: 10 },+ { marks: draw, f0: 39, f1: 70, dur: 5 },+ { marks: mass, f0: 69, f1: 186, dur: 4, pace: up },+ { marks: brk, f0: 185, f1: 330, dur: 3, pace: up },+ { marks: det, f0: 329, f1: 378, dur: 3 },+ { marks: acc, f0: 377, f1: 392, dur: 3 },+ { marks: [...refl, ...refDark], f0: 391, f1: 413, dur: 3 },+ { marks: [...oars, ...spark], f0: 412, f1: HOLD, dur: 2 },+ ];+};++const OPS_KEY = "brokenColour:ops:v1";+const ops = (cache: Map<string, unknown>) => () => {+ let o = cache.get(OPS_KEY) as Op[] | undefined; if (o) return o;+ o = [];+ for (const p of passes()) { const t = schedule(p.marks.length, p.f0, p.f1, p.dur, p.pace); p.marks.forEach((m, i) => o!.push({ t0: t[i].t0, t1: t[i].t1, draw: (ctx, env, pr) => brush(ctx, env, m, pr) })); }+ cache.set(OPS_KEY, checkOps(o, HOLD)); return o;+};+const GROUND: RGB = [240, 234, 222];+export const drawBrokenColour = (ctx: CanvasRenderingContext2D, frame: number, env: import("./core").Env) =>+ staged("brokenColour", ops(env.cache), (c, e) => { c.setTransform(1, 0, 0, 1, 0, 0); c.fillStyle = `rgb(${GROUND.join(",")})`; c.fillRect(0, 0, Math.round(e.W * e.scale), Math.round(e.H * e.scale)); }, (c, e) => linen(c, e, 0.26))(ctx, frame, env);++export const STYLE = { id: "brokenColour", name: "Broken colour", family: "oil", medium: "opaque oil dabs from a loaded flat hog brush on primed linen, unmixed colours side by side for the eye to mix", nearest: "ranunculus", hero: "a small harbour at sunrise" };+export const brokenColour: Film = { meta: META, assets: { images: {} }, shots: [{ id: "brokenColour", start: 0, end: N, draw: drawBrokenColour }] };diff --git a/engine/src/canvas-core/brokenColourKit.ts b/engine/src/canvas-core/brokenColourKit.tsnew file mode 100644index 0000000..999bb4e--- /dev/null+++ b/engine/src/canvas-core/brokenColourKit.ts@@ -0,0 +1,116 @@+// BROKEN-COLOUR KIT. Three primitives the core does not have, written here so the lead can promote them:+//+// staged(...) a still that draws itself: an ordered list of timed ops, a cached canvas holding the+// finished prefix, and the ops still in progress drawn on top at their progress. Pure in+// (frame, env): the cached canvas is always "ground + ops[0..n)" and is rebuilt from the+// ground whenever a frame asks for less than it holds, so frame order cannot change pixels.+// brush(...) one loaded oil brush stroke: blunt where the flat brush lands, full through the body,+// dragged thin where it lifts, with an impasto ridge on one side and a groove on the other.+// weave(...) a primed linen canvas: a seeded, periodic plain-weave tile multiplied over the frame.+import { fractal, rng, type Ctx, type Env, type Layer, type P } from "./core";++// ---------------------------------------------------------------- colour+export type RGB = [number, number, number];+export const mixC = (a: RGB, b: RGB, t: number): RGB => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+export const css = (c: RGB) => `rgb(${Math.round(Math.max(0, Math.min(255, c[0])))},${Math.round(Math.max(0, Math.min(255, c[1])))},${Math.round(Math.max(0, Math.min(255, c[2])))})`;+export const toHsl = ([r, g, b]: RGB): [number, number, number] => {+ r /= 255; g /= 255; b /= 255; const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2;+ if (mx === mn) return [0, 0, l];+ const d = mx - mn, s = l > 0.5 ? d / (2 - mx - mn) : d / (mx + mn);+ const h = mx === r ? (g - b) / d + (g < b ? 6 : 0) : mx === g ? (b - r) / d + 2 : (r - g) / d + 4;+ return [h / 6, s, l];+};+export const fromHsl = ([h, s, l]: [number, number, number]): RGB => {+ if (s === 0) return [l * 255, l * 255, l * 255];+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s, p = 2 * l - q, f = (t: number) => { t = ((t % 1) + 1) % 1; return t < 1 / 6 ? p + (q - p) * 6 * t : t < 0.5 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p; };+ return [f(h + 1 / 3) * 255, f(h) * 255, f(h - 1 / 3) * 255];+};+export const smoothstep = (a: number, b: number, x: number) => { const t = Math.max(0, Math.min(1, (x - a) / (b - a))); return t * t * (3 - 2 * t); };++// ---------------------------------------------------------------- the staged still+export type Op = { t0: number; t1: number; draw: (ctx: Ctx, env: Env, p: number) => void };+// ops MUST be sorted so that t1 never decreases: then "finished by frame f" is a prefix, and the cached+// canvas stacks marks in exactly the order the finished still does.+export const checkOps = (ops: Op[], last: number): Op[] => {+ for (let i = 0; i < ops.length; i++) {+ const o = ops[i];+ if (!(o.t1 > o.t0) || o.t0 <= 0) throw new Error(`op ${i}: bad timing ${o.t0}..${o.t1}`);+ if (i && o.t1 < ops[i - 1].t1) throw new Error(`op ${i}: t1 ${o.t1} before op ${i - 1}'s ${ops[i - 1].t1}`);+ if (o.t1 > last) throw new Error(`op ${i}: finishes at ${o.t1}, after the hold starts at ${last}`);+ }+ return ops;+};+type Progress = { L: Layer; n: number };+export const staged = (key: string, ops: () => Op[], ground: (ctx: Ctx, env: Env) => void, finish: (ctx: Ctx, env: Env) => void) => (ctx: Ctx, frame: number, env: Env) => {+ const list = ops(), DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale);+ let lo = 0, hi = list.length; while (lo < hi) { const m = (lo + hi) >> 1; if (list[m].t1 <= frame) lo = m + 1; else hi = m; }+ const n = lo, ck = `${key}:progress:${DW}x${DH}`;+ let pr = env.cache.get(ck) as Progress | undefined;+ if (!pr) { pr = { L: env.canvas(DW, DH), n: -1 }; env.cache.set(ck, pr); }+ if (pr.n < 0 || pr.n > n) { const c = pr.L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; c.clearRect(0, 0, DW, DH); ground(c, env); pr.n = 0; }+ for (let i = pr.n; i < n; i++) list[i].draw(pr.L.ctx, env, 1);+ pr.n = n;+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; ctx.drawImage(pr.L.canvas as CanvasImageSource, 0, 0);+ for (let i = n; i < list.length && list[i].t0 < frame; i++) list[i].draw(ctx, env, Math.max(0.001, Math.min(0.999, (frame - list[i].t0) / (list[i].t1 - list[i].t0))));+ finish(ctx, env);+};+// lay `count` ops out over [f0, f1): starts follow a pace curve, each lasts `dur` frames, t1 monotonic+export const schedule = (count: number, f0: number, f1: number, dur: number, pace: (u: number) => number = (u) => u) =>+ Array.from({ length: count }, (_, i) => { const t0 = f0 + (f1 - dur - f0) * pace(count > 1 ? i / (count - 1) : 0); return { t0, t1: t0 + dur }; });++// ---------------------------------------------------------------- one loaded brush stroke+// kind 0: an opaque dab (flat brush, ridge + groove). kind 1: a rigger/liner line, tapered both ends.+// kind 2: a thin scrubbed lay-in stroke, bristles skipping, the ground showing between them.+export type Mark = { a: P; b: P; bend: number; w: number; rgb: RGB; alpha: number; seed: number; kind: 0 | 1 | 2 };+const quad = (m: Mark, t: number): P => { const dx = m.b[0] - m.a[0], dy = m.b[1] - m.a[1], L = Math.hypot(dx, dy) || 1, nx = -dy / L, ny = dx / L, s = 4 * t * (1 - t) * m.bend; return [m.a[0] + dx * t + nx * s, m.a[1] + dy * t + ny * s]; };+const fillRibbon = (c: Ctx, m: Mark, prog: number, prof: (t: number) => number, w: number, off: number, n: number, jit: number, seed: number) => {+ const r = rng(seed), L: P[] = [], R: P[] = [];+ for (let i = 0; i <= n; i++) {+ const t = (i / n) * prog, p = quad(m, t), q = quad(m, Math.min(1, t + 0.02)), o = quad(m, Math.max(0, t - 0.02)), dx = q[0] - o[0], dy = q[1] - o[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l;+ const hw = (w / 2) * prof(t), j1 = 1 + (r() - 0.5) * jit, j2 = 1 + (r() - 0.5) * jit, cx = p[0] + nx * off, cy = p[1] + ny * off;+ L.push([cx + nx * hw * j1, cy + ny * hw * j1]); R.push([cx - nx * hw * j2, cy - ny * hw * j2]);+ }+ c.beginPath(); L.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); for (let i = R.length - 1; i >= 0; i--) c.lineTo(R[i][0], R[i][1]); c.closePath(); c.fill();+};+const flat = (t: number) => (t < 0.1 ? 0.8 + 2 * t : t > 0.6 ? 1 - 0.62 * Math.pow((t - 0.6) / 0.4, 1.5) : 1);+const liner = (t: number) => Math.pow(Math.sin(Math.PI * Math.min(1, Math.max(0, t * 0.92 + 0.04))), 0.6);+export const brush = (c: Ctx, env: Env, m: Mark, prog = 1) => {+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.globalCompositeOperation = "source-over";+ const lighter = mixC(m.rgb, [255, 250, 238], 0.2), darker = mixC(m.rgb, [20, 18, 40], 0.14);+ if (m.kind === 0) {+ c.globalAlpha = m.alpha; c.fillStyle = css(m.rgb); fillRibbon(c, m, prog, flat, m.w, 0, 8, 0.2, m.seed);+ if (m.w >= 3.2) {+ c.globalAlpha = m.alpha * 0.5; c.fillStyle = css(lighter); fillRibbon(c, m, prog, flat, m.w * 0.2, m.w * 0.24, 6, 0.4, m.seed + 1); // the ridge the bristles push up+ c.globalAlpha = m.alpha * 0.32; c.fillStyle = css(darker); fillRibbon(c, m, prog, flat, m.w * 0.12, -m.w * 0.3, 6, 0.5, m.seed + 2); // the groove beside it+ }+ if (m.w >= 11) { const r = rng(m.seed + 3); for (let k = 0; k < 3; k++) { c.globalAlpha = m.alpha * (0.4 + r() * 0.4); c.fillStyle = css(k === 1 ? lighter : m.rgb); fillRibbon(c, m, prog, (t) => (t < 0.55 ? 0 : 0.9), m.w * 0.09, (r() - 0.5) * m.w * 0.7, 6, 0.3, m.seed + 4 + k); } } // dry bristle tails+ } else if (m.kind === 1) {+ c.globalAlpha = m.alpha; c.fillStyle = css(m.rgb); fillRibbon(c, m, prog, liner, m.w, 0, 14, 0.25, m.seed);+ } else {+ const r = rng(m.seed);+ for (let k = 0; k < 7; k++) { const off = ((k + 0.5) / 7 - 0.5) * m.w, len = 0.82 + r() * 0.18; c.globalAlpha = m.alpha * (0.45 + r() * 0.55); c.fillStyle = css(mixC(m.rgb, k % 2 ? [255, 244, 228] : m.rgb, 0.18)); fillRibbon(c, m, prog * len, (t) => (t / len > 0.85 ? Math.max(0.1, (1 - t / len) / 0.15) : 1), (m.w / 7) * (1.2 + r() * 0.5), off, 10, 0.6, m.seed + 10 + k); }+ }+ c.globalAlpha = 1;+};++// ---------------------------------------------------------------- the primed linen+// A plain weave: warp and weft alternate over/under, each thread a rounded ridge, thread thickness+// wandering along its length. Near white, so multiplied at full opacity it only darkens the valleys.+const TILE = 512, PITCH = TILE / 190;+export const weave = (env: Env): Layer => {+ const key = `tile:linen:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const n = Math.round(TILE * env.scale); L = env.canvas(n, n);+ const img = L.ctx.createImageData(n, n), d = img.data;+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {+ const lx = x / env.scale, ly = y / env.scale, cx = Math.floor(lx / PITCH), cy = Math.floor(ly / PITCH), fx = lx / PITCH - cx, fy = ly / PITCH - cy;+ const warpOver = ((cx + cy) & 1) === 0, thick = 0.75 + 0.5 * fractal(61, warpOver ? lx : ly, warpOver ? ly : lx, 0.35, 0.012, 2, TILE);+ const across = warpOver ? fx : fy, along = warpOver ? fy : fx, ridge = Math.pow(Math.sin(Math.PI * across), thick), dip = 0.55 + 0.45 * Math.sin(Math.PI * along);+ const v = ridge * dip * (0.85 + 0.3 * fractal(67, lx, ly, 0.08, 0.08, 2, TILE)), i = (y * n + x) * 4, g = 255 * Math.min(1, 1 - 0.26 * (1 - v));+ d[i] = g; d[i + 1] = g * 0.995; d[i + 2] = g * 0.985; d[i + 3] = 255;+ }+ L.ctx.putImageData(img, 0, 0); env.cache.set(key, L); return L;+};+export const linen = (ctx: Ctx, env: Env, opacity: number) => {+ const t = weave(env); ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = "multiply"; ctx.globalAlpha = opacity;+ ctx.fillStyle = ctx.createPattern(t.canvas as CanvasImageSource, "repeat")!; ctx.fillRect(0, 0, Math.round(env.W * env.scale), Math.round(env.H * env.scale)); ctx.restore();+};diff --git a/engine/src/canvas-core/character/build.ts b/engine/src/canvas-core/character/build.tsnew file mode 100644index 0000000..4a63a3f--- /dev/null+++ b/engine/src/canvas-core/character/build.ts@@ -0,0 +1,54 @@+// FROM VOLUMES TO A SCENE. Blobs are projected through the camera; a chain of blobs becomes+// the union of pairwise hulls (a swept, tapering limb that keeps its concave side), a group of+// blobs becomes one hull (a skull), and parts are put in paint order: far to near, with+// explicit "over" rules for what depth alone gets wrong (a coat over the thigh it contains).+import type { P } from "../core";+import { Blob, Camera, V3, blobPts, project } from "./math3";+import { ccw, hull } from "./shape2d";+import type { Mark, Part, Role } from "./types";++export type Group = { blobs: Blob[]; mode: "chain" | "hull" | "each" };+export type BlobPart = {+ id: string; role: Role; groups: Group[];+ seams?: { at: V3; r: number; with: string }[]; // r in metres+ marks?: Mark[]; over?: string[]; depthBias?: number; feature?: string; outline?: boolean; fill?: boolean;+ depthAt?: V3; // measure depth here instead of the blob mean+ marksFn?: (cam: Camera) => Mark[]; // marks that need the camera (a nail seen or not)+ keepLineFn?: (cam: Camera) => ((p: P) => boolean) | undefined;+};++export const polysOf = (cam: Camera, groups: Group[]): P[][] => {+ const out: P[][] = [];+ for (const g of groups) {+ const pp = g.blobs.map((b) => blobPts(cam, b));+ if (g.mode === "hull") out.push(ccw(hull(pp.flat())));+ else if (g.mode === "each" || pp.length === 1) pp.forEach((p) => out.push(ccw(hull(p))));+ else for (let i = 0; i + 1 < pp.length; i++) out.push(ccw(hull([...pp[i], ...pp[i + 1]])));+ }+ return out;+};++export const toPart = (cam: Camera, bp: BlobPart): Part => {+ const all = bp.groups.flatMap((g) => g.blobs);+ const depth = bp.depthAt ? project(cam, bp.depthAt).z : all.reduce((a, b) => a + project(cam, b.c).z, 0) / Math.max(1, all.length);+ const size = all.reduce((a, b) => a + Math.max(b.r[0], b.r[2]) * project(cam, b.c).s, 0) / Math.max(1, all.length);+ return {+ id: bp.id, role: bp.role, depth: depth + (bp.depthBias ?? 0), polys: polysOf(cam, bp.groups), size,+ seams: (bp.seams ?? []).map((s) => { const q = project(cam, s.at); return { at: [q.x, q.y] as P, r: s.r * q.s, with: s.with }; }),+ marks: [...(bp.marks ?? []), ...(bp.marksFn ? bp.marksFn(cam) : [])], keepLine: bp.keepLineFn?.(cam), over: bp.over, feature: bp.feature, outline: bp.outline, fill: bp.fill,+ };+};++// far to near; then every "over" rule is enforced by moving the part just after what it covers+export const order = (parts: Part[]): Part[] => {+ const o = [...parts].sort((a, b) => b.depth - a.depth || a.id.localeCompare(b.id));+ for (let pass = 0; pass < 4; pass++) {+ let moved = false;+ for (const p of [...o]) for (const under of p.over ?? []) {+ const i = o.indexOf(p), j = o.findIndex((q) => q.id === under);+ if (j > i) { o.splice(i, 1); o.splice(o.findIndex((q) => q.id === under) + 1, 0, p); moved = true; }+ }+ if (!moved) break;+ }+ return o;+};diff --git a/engine/src/canvas-core/character/check.ts b/engine/src/canvas-core/character/check.tsnew file mode 100644index 0000000..57f8a05--- /dev/null+++ b/engine/src/canvas-core/character/check.ts@@ -0,0 +1,104 @@+// CHARACTER GATE. The invariants a character must hold in every shot, as pure functions over+// its rig and its Scenes. tools/character-check.mjs runs them and prints a verdict; every check+// has a negative twin that must FAIL, so a green line is evidence, not a claim.+//+// What these checks can prove: proportions against a declared canon, joints inside their range,+// bone lengths constant, left/right symmetric, five digits in the right length order, balance,+// feet planted while planted, distinguishing features present per view, palette roles inside+// their hue families in every hand. What they CANNOT prove: that a hand LOOKS like a hand, that+// a face reads as the same person, that motion feels alive. That is the model sheet's job, and a+// human's (see references/anatomy.md: the look-at-it list).+import type { V3 } from "./math3";+import type { Pose, RoleSpec, Scene } from "./types";+import type { CanonRow } from "./human/canon";+import { type Rig, SIDES, boneLengths, dimsFromCanon, fk, limitViolations } from "./human/skeleton";+import { DIGITS, handModel, resolveHand, FINGERS } from "./human/hands";+import { balance } from "./human/balance";++export type Result = { id: string; ok: boolean; detail: string };+const R = (id: string, ok: boolean, detail: string): Result => ({ id, ok, detail });++// ---- proportions. Adult canon rules (Loomis) where the canon is realistic; Winter's segment+// ratios (fractions of height) for the body below the head in every canon, with a stylised+// canon measured against its BODY height (height minus the head it enlarged).+const WINTER = { upperArm: 0.186, forearm: 0.146, hand: 0.108, thigh: 0.245, shank: 0.246, foot: 0.152 };+export const canonChecks = (c: CanonRow, height: number, realHeads = c.heads): Result[] => {+ const d = dimsFromCanon(c, height), r = fk(d, { root: [0, d.root, 0], yaw: 0, joints: {}, expression: {} }), out: Result[] = [];+ const crown = r.joints.crown[1], floor = Math.min(r.joints.heelL[1], r.joints.heelR[1]) - d.ankleH * 0.1;+ const heads = (crown - floor) / d.hh;+ out.push(R("canon.heads", Math.abs(heads - c.heads) < 0.12, `${heads.toFixed(2)} heads measured from the rest skeleton, declared ${c.heads}`));+ // body height: what a real-canon figure of this age would be, minus the head the stylisation added+ const bodyH = height - (d.hh - height / realHeads);+ const seg: [string, number, number][] = [["upperArm", d.upperArm, WINTER.upperArm], ["forearm", d.forearm, WINTER.forearm], ["hand", d.hand, WINTER.hand], ["thigh", d.thigh, WINTER.thigh], ["shank", d.shin, WINTER.shank], ["foot", d.heel + d.toe, WINTER.foot]];+ seg.forEach(([n, len, w]) => { const got = len / bodyH; out.push(R(`canon.segment.${n}`, Math.abs(got / w - 1) < 0.16, `${(got * 100).toFixed(1)}% of body height, Winter ${(w * 100).toFixed(1)}% (${((got / w - 1) * 100).toFixed(0)}%)`)); });+ if (!c.stylised) {+ const crotch = r.joints.hipL[1] - 0.2 * d.hh; // the crotch sits about a fifth of a head under the hip joints+ out.push(R("canon.crotchAtHalf", Math.abs(crotch / height - 0.5) < 0.03, `crotch at ${((crotch / height) * 100).toFixed(1)}% of height (Loomis: 50%)`));+ const armDown = fk(d, { root: [0, d.root, 0], yaw: 0, joints: {}, expression: {} });+ out.push(R("canon.elbowAtWaist", Math.abs(armDown.joints.elbowL[1] - armDown.joints.lumbar[1]) < 0.35 * d.hh, `elbow ${((armDown.joints.elbowL[1] - armDown.joints.lumbar[1]) / d.hh).toFixed(2)} hh from the waist`));+ out.push(R("canon.wristAtCrotch", Math.abs(armDown.joints.wristL[1] - crotch) < 0.35 * d.hh, `wrist ${((armDown.joints.wristL[1] - crotch) / d.hh).toFixed(2)} hh from the crotch`));+ out.push(R("canon.handIsFace", Math.abs(d.hand / (0.78 * d.hh) - 1) < 0.12, `hand ${(d.hand / d.hh).toFixed(2)} hh vs face ~0.78 hh`));+ out.push(R("canon.footIsForearm", Math.abs((d.heel + d.toe) / d.forearm - 1) < 0.12, `foot ${((d.heel + d.toe) / d.hh).toFixed(2)} hh vs forearm ${(d.forearm / d.hh).toFixed(2)} hh`));+ }+ return out;+};++// ---- the rig under a set of poses+export const poseChecks = (name: string, c: CanonRow, height: number, poses: [string, Pose, { seated?: V3[]; dynamic?: boolean }?][], rigOf: (p: Pose) => Rig): Result[] => {+ const d = dimsFromCanon(c, height), rest = boneLengths(fk(d, { root: [0, 1, 0], yaw: 0, joints: {}, expression: {} })), out: Result[] = [];+ for (const [pn, p, o] of poses) {+ const v = limitViolations(p.joints);+ out.push(R(`${name}.${pn}.limits`, v.length === 0, v.length ? v.join("; ") : `${Object.keys(p.joints).length} joints inside their range`));+ const r = rigOf(p), bl = boneLengths(r), worst = Object.keys(rest).reduce((a, k) => Math.max(a, Math.abs(bl[k] - rest[k])), 0);+ out.push(R(`${name}.${pn}.boneLengths`, worst < 1e-6, `largest bone length change ${(worst * 1000).toFixed(4)} mm`));+ if (!o?.dynamic) { const b = balance(r, o?.seated ?? []); out.push(R(`${name}.${pn}.balance`, b.inside && b.margin > 0.002, `centre of mass ${b.inside ? "inside" : "OUTSIDE"} the support polygon${o?.seated ? " (seat included)" : ""}, margin ${(b.margin * 100).toFixed(1)} cm`)); }+ const low = Math.min(...SIDES.flatMap((s) => [r.joints["heel" + s][1], r.joints["toeTip" + s][1]]));+ out.push(R(`${name}.${pn}.floor`, low > -0.012, `lowest foot point ${(low * 1000).toFixed(1)} mm (below the floor is a foot through it)`));+ }+ // left/right symmetry of the rest skeleton+ const sym = ["upperArm", "forearm", "thigh", "shin", "hipWidth"].map((k) => Math.abs(rest[k + "L"] - rest[k + "R"]));+ out.push(R(`${name}.symmetry`, Math.max(...sym) < 1e-9, `largest left/right bone difference ${(Math.max(...sym) * 1000).toFixed(6)} mm`));+ return out;+};++// ---- hands: count, order, opposition+export const handChecks = (name: string, rig: Rig, Lh: number): Result[] => {+ const out: Result[] = [], hm = handModel(rig.hand.R, "R", Lh, resolveHand("relaxed"));+ out.push(R(`${name}.hand.digits`, hm.digits.length === 5 && DIGITS.every((d) => hm.digits.some((x) => x.digit === d)), `${hm.digits.length} digits: ${hm.digits.map((x) => x.digit).join(", ")}`));+ const L = (d: keyof typeof FINGERS) => FINGERS[d].len.reduce((a, b) => a + b, 0) + FINGERS[d].mcp[1] * -1;+ const order = L("middle") > L("ring") && L("ring") >= L("index") - 0.01 && L("index") > L("little");+ out.push(R(`${name}.hand.lengthOrder`, order, `reach from the wrist (Lh): middle ${L("middle").toFixed(3)}, ring ${L("ring").toFixed(3)}, index ${L("index").toFixed(3)}, little ${L("little").toFixed(3)}`));+ const arc = hm.mcpArc.map((p) => p), mid = arc[1], ends = [arc[0], arc[3]];+ const dist = (a: V3, b: V3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]), wrist = rig.joints.wristR;+ out.push(R(`${name}.hand.knuckleArc`, dist(mid, wrist) > dist(ends[0], wrist) && dist(ends[0], wrist) > dist(ends[1], wrist), `knuckle distance from the wrist: middle ${(dist(mid, wrist) / Lh).toFixed(3)} > index ${(dist(ends[0], wrist) / Lh).toFixed(3)} > little ${(dist(ends[1], wrist) / Lh).toFixed(3)}`));+ const pinch = handModel(rig.hand.R, "R", Lh, resolveHand("pinch")), th = pinch.digits[0].pts[3], ix = pinch.digits[1].pts[3], gap = dist(th, ix) / Lh;+ out.push(R(`${name}.hand.opposition`, gap < 0.16, `pinch: thumb tip to index tip ${(gap * 100).toFixed(1)}% of hand length`));+ return out;+};++// ---- identity across views and hands+export const featureChecks = (name: string, features: { id: string; parts: string[]; visible: (y: number) => boolean }[], views: [number, Scene][]): Result[] => {+ const out: Result[] = [];+ for (const [yaw, s] of views) {+ const ids = new Set(s.parts.filter((p) => p.polys.length || p.marks.length).map((p) => p.id));+ const missing = features.filter((f) => f.visible(yaw) && !f.parts.some((pid) => ids.has(pid))).map((f) => f.id);+ out.push(R(`${name}.features.yaw${yaw}`, missing.length === 0, missing.length ? `MISSING: ${missing.join(", ")}` : `all ${features.filter((f) => f.visible(yaw)).length} features expected at yaw ${yaw} are present`));+ }+ return out;+};+const hue = (hex: string) => { const n = parseInt(hex.slice(1), 16), r = ((n >> 16) & 255) / 255, g = ((n >> 8) & 255) / 255, b = (n & 255) / 255, mx = Math.max(r, g, b), mn = Math.min(r, g, b), d = mx - mn; if (d < 1e-6) return 0; let h = mx === r ? ((g - b) / d) % 6 : mx === g ? (b - r) / d + 2 : (r - g) / d + 4; h *= 60; return h < 0 ? h + 360 : h; };+const inHue = (h: number, [a, b]: [number, number]) => (a <= b ? h >= a && h <= b : h >= a || h <= b);+// the colour a riso recipe actually prints: the paper times each ink at its coverage+export const risoColour = (inks: [string, number][], drum: Record<string, string>, paper = "#f5efe2") => {+ const p = parseInt(paper.slice(1), 16); let c = [(p >> 16) & 255, (p >> 8) & 255, p & 255];+ inks.forEach(([n, t]) => { const k = parseInt(drum[n].slice(1), 16), ink = [(k >> 16) & 255, (k >> 8) & 255, k & 255]; c = c.map((v, i) => v * (1 - t * (1 - ink[i] / 255))); });+ return "#" + c.map((v) => Math.round(v).toString(16).padStart(2, "0")).join("");+};+export const paletteChecks = (name: string, roles: Record<string, RoleSpec>, hands: Record<string, Record<string, string>>): Result[] => {+ const out: Result[] = [];+ for (const [role, spec] of Object.entries(roles)) {+ const got = Object.entries(hands).map(([hand, m]) => { const c = m[role]; if (!c) return `${hand}: UNMAPPED`; const h = hue(c); return `${hand} ${c} ${Math.round(h)}deg${inHue(h, spec.hue) ? "" : " OUT"}`; });+ out.push(R(`${name}.palette.${role}`, got.every((s) => !s.includes("OUT") && !s.includes("UNMAPPED")), `${spec.family} [${spec.hue.join("-")}]: ${got.join(" | ")}`));+ }+ return out;+};diff --git a/engine/src/canvas-core/character/design.ts b/engine/src/canvas-core/character/design.tsnew file mode 100644index 0000000..270b87a--- /dev/null+++ b/engine/src/canvas-core/character/design.ts@@ -0,0 +1,89 @@+// THE DRAWING LAYER. The skeleton is the invisible pose source; what is SEEN is designed.+//+// A designed mass is a SWEEP: a gesture curve through the joints (the line an illustrator draws+// first), carrying an authored cross-section table: at each station along the curve, four+// half-widths (lateral, medial, front, back) placed by hand, so one side can run straight while+// the other curves, a knee can notch, a calf can swell high at the back and a shin stay flat in+// front. The silhouette at any view is the support of that section in the direction square to+// the curve and the line of sight, so the contour is ONE designed curve per mass, never a chain+// of ellipsoid hulls. Long masses are split at their joints into overlapping sub-sweeps (so a+// bent elbow folds instead of self-intersecting); the union contour joins them into one line.+import type { P } from "../core";+import { Camera, Frame, V3, add, apply, cross, dot, mul, mv, norm, project, sub } from "./math3";+import { ccw } from "./shape2d";++// [station 0..1 along the curve, lateral, medial, front, back] half-widths in head units.+// "lateral" is the side away from the body's midline (+x of the frame times the side sign).+export type Section = [number, number, number, number, number];+export type Station = { at: V3; frame: Frame }; // a point the curve passes, and the body's axes there++const catmull = (p0: V3, p1: V3, p2: V3, p3: V3, t: number): V3 => {+ const t2 = t * t, t3 = t2 * t;+ return [0, 1, 2].map((i) => 0.5 * (2 * p1[i] + (-p0[i] + p2[i]) * t + (2 * p0[i] - 5 * p1[i] + 4 * p2[i] - p3[i]) * t2 + (-p0[i] + 3 * p1[i] - 3 * p2[i] + p3[i]) * t3)) as V3;+};+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;+// smooth interpolation of the table at u (cosine between stations: the curves are the designer's, not linear kinks)+export const sectionAt = (tab: Section[], u: number): [number, number, number, number] => {+ if (u <= tab[0][0]) return [tab[0][1], tab[0][2], tab[0][3], tab[0][4]];+ for (let i = 1; i < tab.length; i++) if (u <= tab[i][0]) { const a = tab[i - 1], b = tab[i], t = (u - a[0]) / (b[0] - a[0] || 1), s = (1 - Math.cos(t * Math.PI)) / 2; return [lerp(a[1], b[1], s), lerp(a[2], b[2], s), lerp(a[3], b[3], s), lerp(a[4], b[4], s)]; }+ const z = tab[tab.length - 1]; return [z[1], z[2], z[3], z[4]];+};++export type SweepOpts = { hh: number; side: 1 | -1; n?: number; from?: number; to?: number; caps?: [boolean, boolean]; inset?: [number, number] }; // inset: a span at each end where the section narrows a touch, to bury a cut inside the neighbouring sub-sweep+// the gesture curve through the stations, as samples with interpolated axes+export const curve = (st: Station[], n: number) => {+ const pts: V3[] = [], xs: V3[] = [], zs: V3[] = [], us: number[] = [];+ const P = (i: number) => st[Math.max(0, Math.min(st.length - 1, i))].at;+ for (let seg = 0; seg < st.length - 1; seg++) for (let k = 0; k < n; k++) {+ const t = k / n; pts.push(catmull(P(seg - 1), P(seg), P(seg + 1), P(seg + 2), t));+ const A = st[seg].frame.R, B = st[seg + 1].frame.R, s = (1 - Math.cos(t * Math.PI)) / 2;+ xs.push(norm(add(mul([A[0], A[3], A[6]], 1 - s), mul([B[0], B[3], B[6]], s)))); zs.push(norm(add(mul([A[2], A[5], A[8]], 1 - s), mul([B[2], B[5], B[8]], s))));+ }+ pts.push(st[st.length - 1].at); const Z = st[st.length - 1].frame.R; xs.push([Z[0], Z[3], Z[6]]); zs.push([Z[2], Z[5], Z[8]]);+ let L = 0; us.push(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], pts[i][2] - pts[i - 1][2]); us.push(L); }+ return { pts, xs, zs, us: us.map((u) => u / (L || 1)), len: L };+};++// One sweep's screen polygon (plus end caps). `from`/`to` cut a sub-range of the curve.+export const sweep = (cam: Camera, st: Station[], tab: Section[], o: SweepOpts): P[][] => {+ const n = o.n ?? 10, c = curve(st, n), side = o.side, hh = o.hh, from = o.from ?? 0, to = o.to ?? 1;+ const Lp: P[] = [], Rp: P[] = [], ends: { at: V3; X: V3; Z: V3; T: V3; w: [number, number, number, number] }[] = [];+ for (let i = 0; i < c.pts.length; i++) {+ const u = c.us[i]; if (u < from - 1e-6 || u > to + 1e-6) continue;+ const p = c.pts[i], T = norm(sub(c.pts[Math.min(c.pts.length - 1, i + 1)], c.pts[Math.max(0, i - 1)]));+ // the section's own axes, square to the curve+ const X = norm(sub(c.xs[i], mul(T, dot(c.xs[i], T)))), Z0 = norm(cross(X, T)), Z: V3 = dot(Z0, c.zs[i]) >= 0 ? Z0 : mul(Z0, -1);+ const inA = o.inset?.[0] ? Math.max(0, 1 - (u - from) / o.inset[0]) : 0, inB = o.inset?.[1] ? Math.max(0, 1 - (to - u) / o.inset[1]) : 0, shrink = 1 - 0.08 * Math.max(inA, inB);+ const [lat, med, fr, bk] = sectionAt(tab, u).map((v) => v * hh * shrink), view = norm(sub(p, cam.eye));+ let e = cross(T, view); if (Math.hypot(...e) < 1e-6) e = X; e = norm(e);+ const ex = dot(e, X) * side, ez = dot(e, Z);+ const sup = (a: number, b: number) => Math.sqrt((a * (a > 0 ? lat : med)) ** 2 + (b * (b > 0 ? fr : bk)) ** 2); // support of the four-quadrant section along a direction+ const wp = sup(ex, ez), wm = sup(-ex, -ez);+ const qa = project(cam, add(p, mul(e, wp))), qb = project(cam, add(p, mul(e, -wm)));+ Lp.push([qa.x, qa.y]); Rp.push([qb.x, qb.y]);+ if (ends.length === 0 || i === c.pts.length - 1 || c.us[i + 1] > to + 1e-6) ends.push({ at: p, X, Z, T, w: [lat, med, fr, bk] });+ }+ if (Lp.length < 2) return [];+ const out: P[][] = [ccw([...Lp, ...Rp.reverse()])];+ // caps: the end sections themselves, for when the mass points at the lens (foreshortened to a round end)+ const [c0, c1] = o.caps ?? [true, true];+ [ends[0], ends[ends.length - 1]].forEach((E, k) => {+ if (!E || (k === 0 && !c0) || (k === 1 && !c1)) return;+ const ring: P[] = Array.from({ length: 16 }, (_, j) => { const a = (j / 16) * Math.PI * 2, cx = Math.cos(a), cz = Math.sin(a), r = add(mul(E.X, cx * side * (cx * side > 0 ? E.w[0] : E.w[1])), mul(E.Z, cz * (cz > 0 ? E.w[2] : E.w[3]))); const q = project(cam, add(E.at, r)); return [q.x, q.y]; });+ out.push(ccw(ring));+ });+ return out;+};++// a mass split at its joints into overlapping sub-sweeps (each nearly straight), unioned by the part+export const jointed = (cam: Camera, st: Station[], tab: Section[], o: SweepOpts & { cuts: number[]; overlap?: number }): P[][] => {+ const cuts = [0, ...o.cuts, 1], ov = o.overlap ?? 0.09, out: P[][] = []; // the overlap must span several samples, or the pieces meet edge to edge and the seam draws+ for (let i = 0; i + 1 < cuts.length; i++) out.push(...sweep(cam, st, tab, { ...o, n: Math.max(o.n ?? 10, 18), from: Math.max(0, cuts[i] - ov), to: Math.min(1, cuts[i + 1] + ov), caps: [i === 0 && (o.caps?.[0] ?? true), i === cuts.length - 2 && (o.caps?.[1] ?? true)], inset: [i > 0 ? ov * 1.2 : 0, i < cuts.length - 2 ? ov * 1.2 : 0] }));+ return out;+};++// where along a jointed curve a given station sits (for putting cuts exactly at the joints)+export const stationU = (st: Station[], idx: number) => { let L = 0; const ds: number[] = [0]; for (let i = 1; i < st.length; i++) { L += Math.hypot(...sub(st[i].at, st[i - 1].at)); ds.push(L); } return ds[idx] / (L || 1); };+export const station = (f: Frame, local: V3 = [0, 0, 0]): Station => ({ at: apply(f, local), frame: f });+export const lineOn = (cam: Camera, pts: V3[]): P[] => pts.map((v) => { const q = project(cam, v); return [q.x, q.y] as P; });+export { mv };diff --git a/engine/src/canvas-core/character/human/balance.ts b/engine/src/canvas-core/character/human/balance.tsnew file mode 100644index 0000000..1302b45--- /dev/null+++ b/engine/src/canvas-core/character/human/balance.ts@@ -0,0 +1,119 @@+// BALANCE and REACH. A standing figure is checked, not trusted: its centre of mass (from standard+// segment-mass tables) must fall inside the polygon its feet (and any seat) make on the floor.+// Contrapposto is built, not drawn: the weight leg is carried under the centre, the pelvis+// drops on the free side, the shoulders tilt against it.+//+// Segment masses and centre-of-mass positions: Winter (2009) table 4.1 / Dempster (1955):+// head+neck 8.1%, thorax 21.6%, abdomen 13.9%, pelvis 14.2%, upper arm 2.8% (COM 43.6% from+// the shoulder), forearm 1.6% (43%), hand 0.6%, thigh 10% (43.3%), shank 4.65% (43.3%), foot 1.45%.+import { DEG, V3, add, apply, dist, mix3, mul, mv, sub, tr } from "../math3";+import type { Pose } from "../types";+import { hull, insidePoly, edgeDist } from "../shape2d";+import type { P } from "../../core";+import { type Dims, type Rig, type Side, SIDES, fk, limitViolations, lowestFoot, sgn } from "./skeleton";++export const centreOfMass = (r: Rig): V3 => {+ const J = r.joints, d = r.dims, acc: [V3, number][] = [];+ acc.push([apply(r.head, [0, (0.5 - 0.25) * d.hh, 0.05 * d.hh]), 0.081], [apply(r.chest, [0, 0.55 * d.hh, 0]), 0.216], [J.lumbar, 0.139], [J.pelvis, 0.142]);+ for (const s of SIDES) {+ acc.push([mix3(J["shoulder" + s], J["elbow" + s], 0.436), 0.028], [mix3(J["elbow" + s], J["wrist" + s], 0.43), 0.016], [apply(r.hand[s], [0, -d.hand * 0.4, 0]), 0.006]);+ acc.push([mix3(J["hip" + s], J["knee" + s], 0.433), 0.1], [mix3(J["knee" + s], J["ankle" + s], 0.433), 0.0465], [mix3(J["heel" + s], J["toeTip" + s], 0.45), 0.0145]);+ }+ const tot = acc.reduce((a, [, m]) => a + m, 0);+ return mul(acc.reduce((a, [p, m]) => add(a, mul(p, m)), [0, 0, 0] as V3), 1 / tot);+};++// the support polygon on the floor (x, z): every foot point within `eps` of the floor, plus extras (a seat)+export const supportPolygon = (r: Rig, eps = 0.012, extra: V3[] = []): P[] => {+ const pts: P[] = [], d = r.dims;+ for (const s of SIDES) {+ const cand: V3[] = [[0, -d.ankleH, -d.heel * 0.9], [d.ankleH * 0.35, -d.ankleH, -d.heel * 0.6], [-d.ankleH * 0.35, -d.ankleH, -d.heel * 0.6]].map((l) => apply(r.foot[s], l as V3));+ cand.push(...([[0.035 * d.height, 0, 0], [-0.035 * d.height, 0, 0], [0, 0, d.toe - d.ball]] as V3[]).map((l) => apply(r.toes[s], [l[0], -d.ankleH * 0.15, l[2]])));+ cand.forEach((q) => { if (q[1] < eps) pts.push([q[0], q[2]]); });+ }+ extra.forEach((q) => pts.push([q[0], q[2]]));+ return pts.length >= 3 ? hull(pts) : pts;+};++export type Balance = { com: V3; support: P[]; inside: boolean; margin: number };+export const balance = (r: Rig, extra: V3[] = []): Balance => {+ const com = centreOfMass(r), sup = supportPolygon(r, 0.012, extra);+ const inside = sup.length >= 3 && insidePoly(sup, com[0], com[2]);+ return { com, support: sup, inside, margin: sup.length >= 3 ? (inside ? 1 : -1) * edgeDist(sup, [com[0], com[2]]) : -1 };+};++// ---------------------------------------------------------------- inverse kinematics+// Legs are analytic (two bones, knee in the leg's own sagittal plane): given where the ankle+// must be, return hipFlex, hipAbd, knee. The foot is then set flat unless a pitch is given.+export const legIK = (r: Rig, s: Side, ankle: V3, footPitch = 0): Record<string, number> => {+ const d = r.dims, k = sgn(s), H = r.joints["hip" + s], a = d.thigh, b = d.shin;+ const dl = mv(tr(r.pelvis.R), sub(ankle, H)), L = Math.min(a + b - 1e-4, Math.max(Math.abs(a - b) + 1e-3, Math.hypot(...dl)));+ const inner = Math.acos(Math.max(-1, Math.min(1, (a * a + b * b - L * L) / (2 * a * b)))), knee = Math.PI - inner;+ const y0 = -a - b * Math.cos(knee), z0 = -b * Math.sin(knee);+ const sinT = Math.max(-1, Math.min(1, dl[0] / -y0)), th = Math.asin(sinT), y1 = Math.cos(th) * y0, z1 = z0;+ const phi = Math.atan2(dl[2], dl[1]) - Math.atan2(z1, y1);+ let flex = -phi / DEG; while (flex > 180) flex -= 360; while (flex < -180) flex += 360;+ return { ["hipFlex" + s]: flex, ["hipAbd" + s]: (th / DEG) * k, ["knee" + s]: knee / DEG, ["ankle" + s]: 0, _pitch: footPitch };+};+// after legIK, the ankle angle that puts the sole at `pitch` degrees (toes up +) to the floor+export const flatFoot = (dims: Dims, pose: Pose, s: Side, pitch = 0): number => {+ const r = fk(dims, { ...pose, joints: { ...pose.joints, ["ankle" + s]: 0 } }), R = r.shin[s].R;+ // foot forward in the world = shinR * (0, sin a, cos a); want its elevation = pitch+ const target = Math.sin(pitch * DEG), A = R[4], B = R[5], m = Math.hypot(A, B), base = Math.atan2(B, A);+ const a = Math.asin(Math.max(-1, Math.min(1, target / (m || 1)))) - base;+ let deg = a / DEG; while (deg > 180) deg -= 360; while (deg < -180) deg += 360;+ return deg;+};++// A small deterministic numeric solver: coordinate descent on named joints, inside their limits.+// Used for reaching (an arm to a point), pinching (thumb pad to finger pad), anything with a goal.+export const solve = (pose: Pose, keys: string[], cost: (p: Pose) => number, iters = 60, step0 = 16): Pose => {+ let p = { ...pose, joints: { ...pose.joints } }, c = cost(p), step = step0;+ for (let it = 0; it < iters && step > 0.05; it++) {+ let improved = false;+ for (const k of keys) for (const sgnv of [1, -1]) {+ const q = { ...p, joints: { ...p.joints, [k]: (p.joints[k] ?? 0) + sgnv * step } };+ if (limitViolations(q.joints).length) continue;+ const cq = cost(q); if (cq < c - 1e-9) { p = q; c = cq; improved = true; }+ }+ if (!improved) step *= 0.5;+ }+ return p;+};+export const reach = (dims: Dims, pose: Pose, s: Side, target: V3, keep: Partial<Record<string, number>> = {}): Pose => {+ const keys = ["shoulderRaise", "shoulderSwing", "elbow", "shoulderTwist"].map((k) => k + s).filter((k) => keep[k] === undefined);+ return solve(pose, keys, (p) => { const r = fk(dims, p); return dist(r.joints["wrist" + s], target) + 0.0005 * Math.abs(p.joints["shoulderTwist" + s] ?? 0); });+};++// Contrapposto: weight on one leg. The pelvis drops on the FREE side, the shoulders tilt the+// other way, the free knee relaxes forward and a little out.+export const contrapposto = (weight: Side, amount = 1): Record<string, number> => {+ const w = sgn(weight), free: Side = weight === "L" ? "R" : "L", a = amount;+ return {+ pelvisSide: -7 * a * w, spineSide: 14 * a * w, pelvisTwist: -5 * a * w, spineTwist: 4 * a * w,+ ["hipAbd" + weight]: -3 * a, ["hipAbd" + free]: 5 * a, ["hipFlex" + free]: 12 * a, ["knee" + free]: 20 * a, ["ankle" + free]: -4 * a, ["hipRot" + free]: 10 * a,+ neckSide: -4 * a * w,+ };+};++// Put the feet where they are asked (ankle targets on the floor), solve both legs, set the soles+// flat (or at a pitch), and slide the pelvis until the centre of mass sits over `over` (a point+// on the floor: the weight foot for contrapposto, between the feet for an even stance).+export const stand = (dims: Dims, pose: Pose, feet: Record<Side, V3>, over: [number, number] | null, pitch: Partial<Record<Side, number>> = {}, iters = 8, floor = 0): Pose => {+ let p: Pose = { ...pose, plant: false, joints: { ...pose.joints } };+ const legs = () => { for (let pass = 0; pass < 2; pass++) {+ // a leg cannot stretch: if a foot is out of reach, the pelvis sinks until it is not+ for (let k = 0; k < 3; k++) { const r0 = fk(dims, p), over = Math.max(...SIDES.map((s) => dist(r0.joints["hip" + s], feet[s]) - (dims.thigh + dims.shin) * 0.998)); if (over <= 0) break; p = { ...p, root: [p.root[0], p.root[1] - over * 1.05, p.root[2]] }; }+ const r = fk(dims, p); for (const s of SIDES) { const ik = legIK(r, s, feet[s]); delete ik._pitch; Object.assign(p.joints, ik); } for (const s of SIDES) p.joints["ankle" + s] = Math.max(-44, Math.min(24, flatFoot(dims, p, s, pitch[s] ?? 0))); } }; // an ankle at its limit lifts the heel instead of folding further+ for (let it = 0; it < iters; it++) {+ legs();+ if (!over) break;+ const com = centreOfMass(fk(dims, p)), k = 0.9;+ p = { ...p, root: [p.root[0] + (over[0] - com[0]) * k, p.root[1], p.root[2] + (over[1] - com[2]) * k] };+ }+ legs(); // the last pelvis move must be followed by a leg solve, or the feet leave the floor+ // a pitched foot rests on its ball, not its ankle target: settle the whole figure onto the floor+ const low = lowestFoot(fk(dims, p));+ return { ...p, root: [p.root[0], p.root[1] - (low - floor), p.root[2]] };+};+export { SIDES, dist };diff --git a/engine/src/canvas-core/character/human/canon.ts b/engine/src/canvas-core/character/human/canon.tsnew file mode 100644index 0000000..f74fb2e--- /dev/null+++ b/engine/src/canvas-core/character/human/canon.ts@@ -0,0 +1,51 @@+// HUMAN CANON. Proportions are data, declared per character and CHECKED, never eyeballed.+//+// Sources (standard figure-drawing canon, cross-checked): Loomis, "Figure Drawing for All It's+// Worth" (1943), the heads-by-age chart and the 8-head ideal; Hogarth "Dynamic Anatomy" for+// the 7.5 average adult; anthropometric segment ratios from Winter, "Biomechanics and Motor+// Control of Human Movement" (4th ed., table 4.1: segment lengths as fractions of height,+// segment masses and centre-of-mass positions). Those are the numbers below.+//+// Every landmark is a height above the floor IN HEAD UNITS (hh = chin to crown). A stylised+// canon (storybook, rubber hose) is a declared ROW here, never an exception in drawing code.++export type CanonRow = {+ id: string; label: string; age: number; stylised: boolean; note: string;+ heads: number; // crown height / head height+ eyeLine: number; // eye line above chin, as a fraction of head height (0.5 adult, lower in children)+ // landmark heights above the floor (hh)+ root: number; hip: number; knee: number; ankle: number; lumbar: number; chest: number; neckBase: number; pivot: number; shoulder: number;+ hipX: number; shoulderX: number;+ upperArm: number; forearm: number; hand: number; foot: number; heel: number;+ build: number; // 0 = slight, 1 = heavy; scales girths+};++// heads tall by age: the reference column (Loomis' age chart; the average adult is 7.5).+export const HEADS_BY_AGE: [number, number][] = [[1, 4], [3, 5], [6, 5.75], [8, 6], [9, 6.2], [12, 7], [15, 7.25], [25, 7.5]];+export const headsForAge = (age: number) => { const t = HEADS_BY_AGE; if (age <= t[0][0]) return t[0][1]; for (let i = 1; i < t.length; i++) if (age <= t[i][0]) { const [a0, h0] = t[i - 1], [a1, h1] = t[i]; return h0 + ((h1 - h0) * (age - a0)) / (a1 - a0); } return t[t.length - 1][1]; };+// eye line sinks toward the chin in children: the cranium is proportionally bigger+export const EYE_LINE_BY_AGE: [number, number][] = [[1, 0.38], [3, 0.4], [6, 0.42], [9, 0.44], [12, 0.46], [16, 0.49], [25, 0.5]];+export const eyeLineForAge = (age: number) => { const t = EYE_LINE_BY_AGE; if (age <= t[0][0]) return t[0][1]; for (let i = 1; i < t.length; i++) if (age <= t[i][0]) { const [a0, h0] = t[i - 1], [a1, h1] = t[i]; return h0 + ((h1 - h0) * (age - a0)) / (a1 - a0); } return t[t.length - 1][1]; };++export const CANON: Record<string, CanonRow> = {+ // The average adult, 7.5 heads: crotch at half height, elbow at the waist, wrist at the crotch,+ // hand = face, foot = forearm.+ adult: {+ id: "adult", label: "Adult, realistic (7.5 heads)", age: 30, stylised: false, note: "Hogarth / Loomis average adult",+ heads: 7.5, eyeLine: 0.5,+ root: 4.12, hip: 3.9, knee: 2.1, ankle: 0.36, lumbar: 4.5, chest: 5.0, neckBase: 6.24, pivot: 6.74, shoulder: 6.12,+ hipX: 0.42, shoulderX: 0.76, upperArm: 1.42, forearm: 1.12, hand: 0.8, foot: 1.1, heel: 0.24, build: 0.5,+ },+ // A nine-year-old is about 6.2 heads in life. Storybook enlarges the head (the reader looks at+ // the face) so the same child reads 5.2 heads tall. Limb ratios below the neck are the real+ // child's, rescaled: legs are 46% of height, not the adult 50%.+ storybookChild: {+ id: "storybookChild", label: "Child 9 y, storybook (5.2 heads, declared stylisation of 6.2)", age: 9, stylised: true, note: "head enlarged 1.19x over the age-9 canon; body ratios kept",+ heads: 5.2, eyeLine: 0.44,+ root: 2.72, hip: 2.62, knee: 1.42, ankle: 0.22, lumbar: 2.9, chest: 3.12, neckBase: 3.98, pivot: 4.44, shoulder: 3.9,+ hipX: 0.28, shoulderX: 0.6, upperArm: 0.9, forearm: 0.72, hand: 0.5, foot: 0.72, heel: 0.15, build: 0.35,+ },+};++// The canon rules a figure is checked against. Each returns [ok, measured, wanted].+export type CanonCheck = { id: string; rule: string; ok: boolean; got: number; want: number; tol: number };diff --git a/engine/src/canvas-core/character/human/clothing.ts b/engine/src/canvas-core/character/human/clothing.tsnew file mode 100644index 0000000..7d297c9--- /dev/null+++ b/engine/src/canvas-core/character/human/clothing.ts@@ -0,0 +1,51 @@+// CLOTHING is a second skin with thickness, not a recolour. A garment is built from the same+// blobs as the body under it, inflated, and cut to length along the bone; it paints OVER the+// part it covers whatever the depth sort says. So a sleeve always turns with its arm, and a coat+// hem swings with the thighs inside it.+import { Blob, M3, V3, cross, mix3, mv, norm, sub } from "../math3";+import type { BlobPart } from "../build";+import { type B, type BodySpec, blob } from "./mannequin";+import { type Rig, type Side, SIDES } from "./skeleton";++// blobs of a chain, cut at `t` (0 = first blob, 1 = last): the last blob is interpolated+export const cutChain = (bs: Blob[], t: number): Blob[] => {+ const f = t * (bs.length - 1), i = Math.floor(f), u = f - i, out = bs.slice(0, i + 1);+ if (u > 1e-3 && i + 1 < bs.length) { const a = bs[i], b = bs[i + 1]; out.push({ c: mix3(a.c, b.c, u), R: b.R, r: mix3(a.r, b.r, u) }); }+ return out;+};+// a cut edge: the last blob widened by the flare and squashed flat along the bone, so the garment ends in an opening, not a dome+const hemOf = (b: Blob, flare: number, hh: number): Blob => ({ ...b, r: [b.r[0] + flare, 0.025 * hh, b.r[2] + flare] as V3 });++// a sleeve from the shoulder down the arm to `to` (0..1 upper arm, 1..2 on into the forearm),+// with a cuff that stands off the arm by `flare`+export const sleeve = (r: Rig, spec: BodySpec, s: Side, o: { role: string; to: number; inflate: number; flare?: number; id?: string }): BlobPart => {+ const hh = r.dims.hh, up = spec.upperArm.map((b) => blob(r, b, s, o.inflate)), fore = spec.foreArm.slice(0, 2).map((b) => blob(r, b, s, o.inflate));+ const all = o.to <= 1 ? cutChain(up, o.to) : [...up, ...cutChain(fore, Math.min(1, o.to - 1))];+ const last = all.length - 1; all[last] = hemOf(all[last], (o.flare ?? 0) * hh, hh);+ return { id: o.id ?? "sleeve" + s, role: o.role, groups: [{ blobs: all, mode: "chain" }], over: ["upperArm" + s, ...(o.to > 1 ? ["foreArm" + s] : [])], seams: [{ at: r.joints["shoulder" + s], r: spec.seam.shoulder * hh * 1.1, with: "torso" }], depthBias: -0.065 * hh };+};++// a garment leg (shorts, trousers) over the thigh and on down the shin+export const trouserLeg = (r: Rig, spec: BodySpec, s: Side, o: { role: string; to: number; inflate: number; flare?: number }): BlobPart => {+ const hh = r.dims.hh, th = spec.thigh.map((b) => blob(r, b, s, o.inflate)), sh = spec.shin.map((b) => blob(r, b, s, o.inflate * 0.8));+ const all = o.to <= 1 ? cutChain(th, o.to) : [...th, ...cutChain(sh, Math.min(1, o.to - 1))];+ const last = all.length - 1; all[last] = hemOf(all[last], (o.flare ?? 0) * hh, hh);+ return { id: "leg" + s, role: o.role, groups: [{ blobs: all, mode: "chain" }], over: ["thigh" + s, ...(o.to > 1 ? ["shin" + s] : [])], seams: [{ at: r.joints["hip" + s], r: spec.seam.hip * hh, with: "hips" }], depthBias: -0.025 * hh };+};++// A coat body: chest, waist and hips inflated, then a hem ellipse at `hemY` (head heights above+// the floor at rest) that follows the thighs, so it swings with the stride.+export const coatBody = (r: Rig, spec: BodySpec, o: { role: string; inflate: number; hemBelowHip: number; hemFlare: number }): BlobPart => {+ const hh = r.dims.hh, P = r.pelvis;+ const torso = spec.torso.map((b) => blob(r, b, "L", o.inflate)).reverse(), hips = spec.hips.map((b) => blob(r, b, "L", o.inflate * 1.1));+ // the hem hangs from the hips, pulled toward wherever the knees have gone+ const knees = SIDES.map((s) => r.joints["knee" + s]), hipsJ = SIDES.map((s) => r.joints["hip" + s]);+ const mid = mix3(mix3(hipsJ[0], hipsJ[1], 0.5), mix3(knees[0], knees[1], 0.5), Math.min(0.95, o.hemBelowHip / (r.dims.thigh / hh)));+ const spread = Math.hypot(knees[0][0] - knees[1][0], knees[0][2] - knees[1][2]) / hh;+ // the hem ring lies square to the thighs: flat when she stands, upright across her knees when she sits+ const hm = mix3(hipsJ[0], hipsJ[1], 0.5), km = mix3(knees[0], knees[1], 0.5), dn = norm(sub(hm, km)), sideA = norm(cross(dn, mv(P.R, [0, 0, 1]))), fwdA = cross(sideA, dn);+ const hemR: M3 = [sideA[0], dn[0], fwdA[0], sideA[1], dn[1], fwdA[1], sideA[2], dn[2], fwdA[2]];+ const hem: Blob = { c: mid, R: hemR, r: [(0.62 + o.hemFlare + spread * 0.25) * hh, 0.05 * hh, (0.46 + o.hemFlare * 0.8 + spread * 0.18) * hh] };+ const sided: Blob[] = SIDES.flatMap((s) => spec.torsoSided.slice(0, 2).map((b: B) => blob(r, b, s, o.inflate)));+ return { id: "coat", role: o.role, groups: [{ blobs: [...torso, hips[1], hem], mode: "chain" }, { blobs: sided, mode: "each" }], over: ["torso", "hips", "thighL", "thighR"], depthAt: r.joints.lumbar };+};diff --git a/engine/src/canvas-core/character/human/figure.ts b/engine/src/canvas-core/character/human/figure.tsnew file mode 100644index 0000000..341fea4--- /dev/null+++ b/engine/src/canvas-core/character/human/figure.ts@@ -0,0 +1,60 @@+// A HUMAN FIGURE, assembled: canon -> skeleton -> pose (validated) -> mannequin + head + hands ->+// parts in paint order. Characters build on this and add what makes them themselves (hair,+// clothes, props); nothing here knows about any particular character or any hand of drawing.+import type { P } from "../../core";+import { Camera, V3, apply, project } from "../math3";+import { BlobPart, order, toPart } from "../build";+import { hull } from "../shape2d";+import type { Part, Pose, Scene } from "../types";+import type { CanonRow } from "./canon";+import { type Dims, type Rig, SIDES, dimsFromCanon, fk, limitViolations, lowestFoot } from "./skeleton";+import { type BodySpec, bodyParts } from "./mannequin";+import { type HeadCtx, type HeadSpec, faceMarks, headCtx, headParts } from "./head";+import { type HandAngles, handViolations, resolveHand } from "./hands";++export type FigureSpec = { canon: CanonRow; height: number; body: BodySpec; head: HeadSpec; roles?: Partial<Record<string, string>>; inflate?: Partial<Record<string, number>> };+export type Built = { rig: Rig; dims: Dims; hands: Record<"L" | "R", HandAngles>; head: HeadCtx; parts: BlobPart[]; extra: Part[] };++// A pose outside the range of motion fails HERE, at load, with every reason listed.+export const checkPose = (p: Pose, tag = "pose"): Record<"L" | "R", HandAngles> => {+ const bad = limitViolations(p.joints);+ const hands = { L: resolveHand(p.hands?.L), R: resolveHand(p.hands?.R) };+ bad.push(...handViolations(hands.L, "handL"), ...handViolations(hands.R, "handR"));+ if (bad.length) throw new Error(`${tag}: outside the range of motion:\n ` + bad.join("\n "));+ return hands;+};++export const rigFor = (spec: FigureSpec, p: Pose): Rig => {+ const dims = dimsFromCanon(spec.canon, spec.height);+ let rig = fk(dims, p);+ if (p.plant) { const dy = lowestFoot(rig); rig = fk(dims, { ...p, root: [p.root[0], p.root[1] - dy, p.root[2]] }); }+ return rig;+};++export const build = (spec: FigureSpec, p: Pose, cam: Camera): Built => {+ const hands = checkPose(p);+ const rig = rigFor(spec, p), dims = rig.dims;+ const head = headCtx(rig.head, dims.hh, spec.head, cam);+ const parts = [...bodyParts(rig, spec.body, { hands, roles: spec.roles, inflate: spec.inflate }), ...headParts(head, spec.roles?.head ?? spec.roles?.skin ?? "skin")];+ return { rig, dims, hands, head, parts, extra: [] };+};++// the contact shadow: the feet and the body's footprint, pushed away from the light+export const groundShadow = (cam: Camera, rig: Rig, away: [number, number] = [0.5, 0]): P[] => {+ const pts: V3[] = [];+ const hh = rig.dims.hh;+ SIDES.forEach((s) => { for (const loc of [[0, -rig.dims.ankleH, -rig.dims.heel], [0, -rig.dims.ankleH, 0]] as V3[]) { const w = apply(rig.foot[s], loc); pts.push([w[0], 0, w[2]]); } const t = apply(rig.toes[s], [0, 0, rig.dims.toe - rig.dims.ball]); pts.push([t[0], 0, t[2]]); });+ const pel = rig.joints.pelvis; pts.push([pel[0] + away[0] * hh, 0, pel[2] + away[1] * hh]);+ const ring: V3[] = []; pts.forEach((q) => { for (let a = 0; a < 8; a++) ring.push([q[0] + Math.cos(a * 0.785) * hh * 0.35, 0, q[2] + Math.sin(a * 0.785) * hh * 0.22]); });+ return hull(ring.map((q) => { const r = project(cam, q); return [r.x, r.y] as P; }));+};++export type FaceRoles = { line: string; pupil: string; white: string; blush: string; brow: string; mouth: string; lip: string };+// `post` sees the projected parts and returns more (hair, glasses: things placed against the head)+export const assemble = (cam: Camera, b: Built, p: Pose, faceRoles: FaceRoles, meta: Record<string, string | number> = {}, post?: (parts: Part[]) => Part[]): Scene => {+ const parts = b.parts.map((bp) => toPart(cam, bp));+ const head = parts.find((q) => q.id === "head");+ if (head) head.marks.push(...faceMarks(b.head, p.expression, faceRoles, head.size * 2));+ const all = order([...parts, ...b.extra, ...(post ? post(parts) : [])]);+ return { parts: all, light: [-0.62, -0.78], ground: { y: 0, shadow: groundShadow(cam, b.rig) }, px: project(cam, b.rig.joints.head).s * b.dims.hh, meta };+};diff --git a/engine/src/canvas-core/character/human/hands.ts b/engine/src/canvas-core/character/human/hands.tsnew file mode 100644index 0000000..91f78ca--- /dev/null+++ b/engine/src/canvas-core/character/human/hands.ts@@ -0,0 +1,143 @@+// HANDS. A hand skeleton, not a mitten: 5 digits, 14 phalanges, the metacarpal knuckle ARC+// (middle knuckle most distal, little finger's far back), finger lengths in their true order+// (middle > ring >= index > little), and a thumb that leaves the wrist, not the palm, and+// OPPOSES by swinging in front of the palm while turning its pad toward the fingers.+//+// Reference opened: Gray's Anatomy fig. 219-220 (bones of the left hand, dorsal and palmar);+// Buchholz & Armstrong (1992) "A kinematic model of the human hand" for segment-length ratios+// (proximal : middle : distal about 1 : 0.65 : 0.48 for the middle finger); Hogarth "Drawing+// Dynamic Hands" for the wedge-and-block construction and the knuckle arc.+//+// Canonical frame: the LEFT hand, arm hanging. Distal = -y, palm normal = -x (toward the body),+// thumb side = +z (forward). The right hand is the mirror (x -> -x). Units: hand length Lh+// (wrist crease to middle fingertip).+import { Blob, DEG, Frame, M3, MIRROR_X, V3, add, apply, cross, mix3, mm, mv, norm, rx, ry, rz, I3 } from "../math3";++export type Digit = "thumb" | "index" | "middle" | "ring" | "little";+export const DIGITS: Digit[] = ["thumb", "index", "middle", "ring", "little"];+export type HandAngles = Record<Digit, [number, number, number, number]>; // fingers: [spread, mcp, pip, dip]; thumb: [abd, opp, mcp, ip]++type FingerSpec = { mcp: V3; len: [number, number, number]; r: number; spreadDir: number };+export const FINGERS: Record<Exclude<Digit, "thumb">, FingerSpec> = {+ // knuckle positions trace the arc: middle furthest out, little finger well back+ index: { mcp: [-0.012, -0.452, 0.128], len: [0.225, 0.14, 0.105], r: 0.05, spreadDir: -1 },+ middle: { mcp: [0.0, -0.47, 0.042], len: [0.245, 0.16, 0.12], r: 0.052, spreadDir: 0 },+ ring: { mcp: [-0.006, -0.456, -0.046], len: [0.232, 0.152, 0.11], r: 0.048, spreadDir: 1 },+ little: { mcp: [-0.02, -0.415, -0.128], len: [0.182, 0.112, 0.096], r: 0.041, spreadDir: 1.35 },+};+export const THUMB = { cmc: [-0.035, -0.07, 0.1] as V3, len: [0.225, 0.155, 0.13] as [number, number, number], r: 0.062 };++// finger-joint limits (degrees): MCP flexes 90 and hyperextends ~20; PIP 110; DIP 80+export const HAND_LIMITS = { spread: [-15, 25], mcp: [-20, 90], pip: [0, 110], dip: [-5, 80], abd: [0, 70], opp: [0, 80], tmcp: [-10, 60], ip: [-15, 80] };+export const handViolations = (a: HandAngles, tag: string): string[] => {+ const out: string[] = [], L = HAND_LIMITS;+ DIGITS.forEach((d) => {+ const v = a[d]; if (!v || v.length !== 4) { out.push(`${tag} ${d}: missing`); return; }+ const lims = d === "thumb" ? [L.abd, L.opp, L.tmcp, L.ip] : [L.spread, L.mcp, L.pip, L.dip], names = d === "thumb" ? ["abd", "opp", "mcp", "ip"] : ["spread", "mcp", "pip", "dip"];+ v.forEach((x, i) => { if (x < lims[i][0] || x > lims[i][1]) out.push(`${tag} ${d}.${names[i]} = ${x} outside ${lims[i][0]}..${lims[i][1]}`); });+ });+ return out;+};++// ---------------------------------------------------------------- the pose library (joint angles, never pixels)+const F = (s: number, m: number, p: number, d: number): [number, number, number, number] => [s, m, p, d];+export const HAND_POSES: Record<string, HandAngles> = {+ // hanging at rest: each finger a little more curled than the one before it (the cascade)+ relaxed: { thumb: F(10, 15, 10, 12), index: F(2, 14, 22, 10), middle: F(0, 20, 30, 14), ring: F(2, 26, 36, 18), little: F(4, 32, 40, 22) },+ open: { thumb: F(52, 8, 0, -5), index: F(10, 0, 2, 0), middle: F(0, 0, 2, 0), ring: F(8, 0, 3, 0), little: F(14, 0, 4, 2) },+ point: { thumb: F(12, 44, 30, 28), index: F(0, 0, 2, 0), middle: F(0, 86, 100, 55), ring: F(2, 88, 102, 58), little: F(3, 90, 100, 60) },+ fist: { thumb: F(10, 52, 30, 26), index: F(0, 86, 100, 62), middle: F(0, 88, 102, 62), ring: F(2, 90, 102, 62), little: F(3, 90, 100, 60) },+ // closed around a cylinder about 0.3 Lh across (a mug, a tool handle)+ grip: { thumb: F(30, 58, 20, 22), index: F(0, 52, 62, 32), middle: F(0, 56, 66, 34), ring: F(2, 60, 68, 36), little: F(4, 64, 70, 38) },+ // thumb pad meets index pad; the rest fall away in a cascade+ pinch: { thumb: F(34, 52, 20, 16), index: F(-2, 50, 56, 18), middle: F(2, 40, 50, 20), ring: F(4, 44, 56, 24), little: F(6, 50, 60, 28) },+ // a wave: open, fingers a touch back, fanned wider toward the little finger+ wave: { thumb: F(46, 10, 4, -2), index: F(8, -8, 4, 0), middle: F(0, -8, 4, 0), ring: F(10, -6, 5, 2), little: F(18, -4, 6, 2) },+};+export const resolveHand = (h: string | Record<string, number> | { angles: Record<string, [number, number, number, number]> } | undefined): HandAngles => {+ if (h && typeof h === "object" && "angles" in h) return h.angles as HandAngles;+ if (!h) return HAND_POSES.relaxed;+ if (typeof h === "string") { const p = HAND_POSES[h]; if (!p) throw new Error(`unknown hand pose '${h}' (have ${Object.keys(HAND_POSES).join(", ")})`); return p; }+ // an object: blend two named poses {a: "fist", b: "point", t: 0.5} is spelled {fist: 0.5, point: 0.5}+ const acc = { thumb: [0, 0, 0, 0], index: [0, 0, 0, 0], middle: [0, 0, 0, 0], ring: [0, 0, 0, 0], little: [0, 0, 0, 0] } as unknown as HandAngles; let tot = 0;+ for (const [name, w] of Object.entries(h as Record<string, number>)) { const p = HAND_POSES[name]; if (!p) throw new Error(`unknown hand pose '${name}'`); tot += w; DIGITS.forEach((d) => p[d].forEach((v, i) => (acc[d][i] += v * w))); }+ DIGITS.forEach((d) => acc[d].forEach((_, i) => (acc[d][i] /= tot || 1)));+ return acc;+};++// ---------------------------------------------------------------- forward kinematics of the hand+export type HandJoints = { digit: Digit; pts: V3[]; radii: number[]; frames: Frame[] }; // pts: base, joint, joint, tip+export type HandModel = { palm: Blob[]; digits: HandJoints[]; nails: { digit: Digit; c: V3; R: M3; w: number; l: number }[]; mcpArc: V3[] };++export const handModel = (wrist: Frame, side: "L" | "R", Lh: number, ang: HandAngles, girth = 1): HandModel => {+ const M = side === "L" ? I3 : MIRROR_X;+ // express a canonical-left local point/rotation in the world+ const W = (p: V3): V3 => apply(wrist, mv(M, p.map((v) => v * Lh) as V3));+ const WR = (R: M3): M3 => mm(wrist.R, mm(M, mm(R, M)));+ const digits: HandJoints[] = [], nails: HandModel["nails"] = [];+ (Object.keys(FINGERS) as Exclude<Digit, "thumb">[]).forEach((d) => {+ const s = FINGERS[d], [sp, m, p, q] = ang[d];+ // flexed fingers converge toward the middle finger (their tips point at the scaphoid)+ const conv = -Math.sign(s.spreadDir) * Math.min(m, 80) * 0.06;+ // spread: index toward +z (radial), ring/little toward -z (ulnar); flexing pulls them together+ const R: M3 = mm(rx(((s.spreadDir < 0 ? -sp : s.spreadDir > 0 ? sp : 0) + conv) * DEG), rz(-m * DEG));+ let pos: V3 = s.mcp; const pts: V3[] = [W(pos)], frames: Frame[] = [], radii = [s.r * girth, s.r * 0.9 * girth, s.r * 0.8 * girth, s.r * 0.72 * girth];+ const bends = [0, p, q];+ let Rc: M3 = R;+ for (let k = 0; k < 3; k++) {+ if (k) Rc = mm(Rc, rz(-bends[k] * DEG));+ frames.push({ p: W(pos), R: WR(Rc) });+ pos = add(pos, mv(Rc, [0, -s.len[k], 0]));+ pts.push(W(pos));+ }+ // the fingertip pad sits a hair short of the bone end: pull the last point back by the radius+ digits.push({ digit: d, pts, radii: radii.map((r) => r * Lh), frames });+ // the nail: on the dorsal (+x) face of the distal phalanx, toward its tip+ const last = frames[2];+ nails.push({ digit: d, c: apply(last, mv(M, [s.r * 0.8 * Lh, -s.len[2] * 0.6 * Lh, 0])), R: last.R, w: s.r * 1.25 * Lh, l: s.len[2] * 0.55 * Lh });+ });+ // the thumb: a rest frame pointing distal, radial and a little palmar; abduction swings it off+ // the index, opposition carries it round in FRONT of the palm (toward -x) and turns the pad+ // f0 = the way the thumb curls: toward the palm (-x) and across it (-z), square to d0+ const [abd, opp, tm, ip] = ang.thumb, d0 = norm([-0.22, -0.8, 0.52]), f0 = norm(cross(cross(d0, norm([-0.8, 0, -0.6])), d0) as V3);+ // a frame whose -y is d0 and whose -x is f0, so the same rz(-bend) curls it as it curls a finger+ const colX: V3 = [-f0[0], -f0[1], -f0[2]], colY: V3 = [-d0[0], -d0[1], -d0[2]], colZ = norm(cross(colX, colY));+ const B: M3 = [colX[0], colY[0], colZ[0], colX[1], colY[1], colZ[1], colX[2], colY[2], colZ[2]];+ let R: M3 = mm(ry(-opp * DEG), mm(rx(-abd * DEG), B));+ let pos: V3 = THUMB.cmc; const tp: V3[] = [W(pos)], tf: Frame[] = [], tl: V3[] = [pos];+ const tb = [0, tm, ip];+ for (let k = 0; k < 3; k++) {+ if (k) R = mm(R, rz(-tb[k] * DEG));+ tf.push({ p: W(pos), R: WR(R) });+ pos = add(pos, mv(R, [0, -THUMB.len[k], 0]));+ tp.push(W(pos)); tl.push(pos);+ }+ const tr0 = THUMB.r * girth;+ digits.unshift({ digit: "thumb", pts: tp, radii: [tr0 * 1.35, tr0 * 1.02, tr0 * 0.97, tr0 * 0.9].map((r) => r * Lh), frames: tf });+ nails.unshift({ digit: "thumb", c: apply(tf[2], mv(M, [0.05 * Lh, -THUMB.len[2] * 0.62 * Lh, 0])), R: tf[2].R, w: THUMB.r * 1.2 * Lh, l: THUMB.len[2] * 0.55 * Lh });+ const blob = (c: V3, r: V3): Blob => ({ c: W(c), R: WR(I3), r: r.map((v) => v * Lh * girth) as V3 });+ const palm = [+ blob([0.004, -0.05, 0.0], [0.07, 0.07, 0.17]), // heel of the hand, over the carpals+ blob([0.0, -0.25, -0.005], [0.07, 0.2, 0.215]), // the palm block+ blob([0.006, -0.44, -0.005], [0.06, 0.085, 0.205]), // the knuckle row, and the web of skin that runs a third of the way up the fingers+ blob([-0.022, -0.22, -0.12], [0.06, 0.17, 0.075]), // hypothenar pad, little-finger side+ blob(mix3(tl[0], tl[1], 0.45), [0.085, 0.085, 0.085]), // the thenar eminence: the thumb's metacarpal is buried in it, the thumb only leaves the palm at its MCP+ blob(mix3(tl[0], tl[1], 0.8), [0.066, 0.066, 0.066]),+ ];+ return { palm, digits, nails, mcpArc: (["index", "middle", "ring", "little"] as const).map((d) => W(FINGERS[d].mcp)) };+};++// The pinch is SOLVED, not typed: thumb pad pulled onto index pad (tips meet, radii touching),+// inside every joint limit. Deterministic coordinate descent, once, at load.+const solvePinch = (start: HandAngles): HandAngles => {+ const id: Frame = { p: [0, 0, 0], R: I3 }, a: HandAngles = JSON.parse(JSON.stringify(start));+ const cost = (h: HandAngles) => { const m = handModel(id, "L", 1, h), t = m.digits[0], i = m.digits[1], d = Math.hypot(t.pts[3][0] - i.pts[3][0], t.pts[3][1] - i.pts[3][1], t.pts[3][2] - i.pts[3][2]) - (t.radii[3] + i.radii[3]) * 0.85; return d * d + handViolations(h, "").length; };+ let e = cost(a), step = 8;+ for (let it = 0; it < 80 && step > 0.1; it++) {+ let imp = false;+ for (const [dg, k] of [["thumb", 0], ["thumb", 1], ["thumb", 2], ["thumb", 3], ["index", 1], ["index", 2], ["index", 3]] as [Digit, number][]) for (const s of [1, -1]) { const t: HandAngles = JSON.parse(JSON.stringify(a)); t[dg][k] += s * step; const et = cost(t); if (et < e) { e = et; Object.assign(a, t); imp = true; } }+ if (!imp) step *= 0.5;+ }+ return a;+};+HAND_POSES.pinch = solvePinch(HAND_POSES.pinch);diff --git a/engine/src/canvas-core/character/human/head.ts b/engine/src/canvas-core/character/human/head.tsnew file mode 100644index 0000000..a3b5741--- /dev/null+++ b/engine/src/canvas-core/character/human/head.ts@@ -0,0 +1,262 @@+// THE HEAD, Loomis construction. A ball (the cranium) with the sides planed off, a jaw hung+// under it, and the features placed ON the surface of the face, so turning the head moves and+// foreshortens them the way a real face does: the far eye narrows, the mouth corner on the far+// side slides round the curve and then disappears, the nose breaks the profile.+//+// Reference opened: Loomis, "Drawing the Head and Hands" (1956) pp. 22-39 (ball, side planes,+// brow / nose / chin thirds, the eye line at half the head in adults); the age chart on p. 29 for+// the child's lower eye line and bigger cranium; Hogarth "Drawing the Human Head" for the jaw+// angle and the ear sitting between the brow line and the base of the nose.+//+// Head-local units: head heights (hh). Origin at chin level, x = her left, y = up, z = forward;+// z = 0 is the column of the ear holes.+import type { P } from "../../core";+import { Blob, Camera, Frame, V3, add, apply, blobPts, dot, mul, mv, norm, project, sub } from "../math3";+import type { BlobPart } from "../build";+import { ccw, hull } from "../shape2d";+import type { Mark, Part } from "../types";++export type Ell = { c: V3; r: V3 };+export type HeadSpec = {+ pivot: V3; // the atlas joint in head-local units (where the neck carries the head)+ skull: Ell[]; // hulled together: cranium, cheeks, jaw, chin+ nose: Ell[]; // chained: a separate poly so the nose breaks the profile+ ear: Ell; // her left ear; the right is mirrored+ face: Ell; // the surface the features sit on+ eyeStyle: "bead" | "almond";+ eyeY: number; eyeX: number; eyeW: number; eyeH: number;+ browY: number; noseY: number; mouthY: number; mouthW: number;+ blush?: boolean; freckles?: [number, number][];+};++export const CHILD_HEAD: HeadSpec = {+ pivot: [0, 0.26, -0.06],+ skull: [{ c: [0, 0.6, -0.04], r: [0.43, 0.43, 0.46] }, { c: [0.2, 0.3, 0.14], r: [0.2, 0.2, 0.21] }, { c: [-0.2, 0.3, 0.14], r: [0.2, 0.2, 0.21] }, { c: [0, 0.09, 0.2], r: [0.14, 0.09, 0.14] }, { c: [0.1, 0.13, 0.18], r: [0.12, 0.1, 0.14] }, { c: [-0.1, 0.13, 0.18], r: [0.12, 0.1, 0.14] }],+ nose: [{ c: [0, 0.37, 0.39], r: [0.045, 0.05, 0.04] }, { c: [0, 0.32, 0.44], r: [0.05, 0.045, 0.045] }],+ ear: { c: [0.43, 0.42, -0.02], r: [0.05, 0.11, 0.08] },+ face: { c: [0, 0.42, -0.02], r: [0.42, 0.56, 0.44] },+ eyeStyle: "bead", eyeY: 0.44, eyeX: 0.155, eyeW: 0.047, eyeH: 0.062,+ browY: 0.575, noseY: 0.31, mouthY: 0.19, mouthW: 0.075, blush: true,+};+export const ADULT_HEAD: HeadSpec = {+ pivot: [0, 0.27, -0.06],+ skull: [+ { c: [0, 0.63, -0.05], r: [0.36, 0.41, 0.46] },+ { c: [0.25, 0.44, 0.18], r: [0.11, 0.1, 0.14] }, { c: [-0.25, 0.44, 0.18], r: [0.11, 0.1, 0.14] }, // cheekbones+ { c: [0.27, 0.15, 0.0], r: [0.09, 0.1, 0.1] }, { c: [-0.27, 0.15, 0.0], r: [0.09, 0.1, 0.1] }, // jaw angles: wide and low, a man's jaw+ { c: [0, 0.61, 0.35], r: [0.27, 0.05, 0.08] }, // the brow ridge, over the eyes+ { c: [0, 0.2, 0.28], r: [0.15, 0.12, 0.11] }, // the muzzle over the teeth+ { c: [0.045, 0.04, 0.3], r: [0.07, 0.06, 0.08] }, { c: [-0.045, 0.04, 0.3], r: [0.07, 0.06, 0.08] }, // a squared chin, two eminences+ ],+ nose: [{ c: [0, 0.54, 0.4], r: [0.03, 0.04, 0.03] }, { c: [0, 0.45, 0.44], r: [0.034, 0.05, 0.034] }, { c: [0, 0.36, 0.47], r: [0.042, 0.034, 0.034] }],+ ear: { c: [0.36, 0.43, -0.03], r: [0.045, 0.14, 0.085] },+ face: { c: [0, 0.45, -0.05], r: [0.34, 0.56, 0.46] },+ eyeStyle: "almond", eyeY: 0.5, eyeX: 0.138, eyeW: 0.066, eyeH: 0.026,+ browY: 0.6, noseY: 0.33, mouthY: 0.2, mouthW: 0.1,+};++// the expression parameters, all 0 at rest+export const EXPRESSION_KEYS = ["browRaise", "browFurrow", "browSad", "lidUpper", "lidLower", "cheek", "smile", "mouthOpen", "mouthWide", "lookX", "lookY"] as const;+export const EXPRESSIONS: Record<string, Record<string, number>> = {+ neutral: {},+ happy: { smile: 0.9, cheek: 0.6, lidLower: 0.25, browRaise: 0.2 },+ laughing: { smile: 1, cheek: 1, lidUpper: 1, mouthOpen: 0.75, mouthWide: 0.3, browRaise: 0.35 },+ surprised: { browRaise: 1, mouthOpen: 0.7, mouthWide: -0.5, lidUpper: -0.3 },+ worried: { browSad: 1, smile: -0.5, lookX: -0.5, lookY: -0.3, mouthWide: -0.2 },+ determined: { browFurrow: 1, lidUpper: 0.25, smile: -0.1, mouthWide: -0.3, lookX: 0.4 },+ curious: { browRaise: 0.6, browFurrow: 0.0, smile: 0.25, lookX: 0.6, lookY: 0.4, lidUpper: -0.1 },+};++export type HeadCtx = { f: Frame; hh: number; spec: HeadSpec; cam: Camera; M: (q: V3) => V3 };+export const headCtx = (head: Frame, hh: number, spec: HeadSpec, cam: Camera): HeadCtx => ({ f: head, hh, spec, cam, M: (q) => apply(head, mul(sub(q, spec.pivot), hh)) });++// head-local ellipsoid -> world blob+const toBlob = (h: HeadCtx, e: Ell, mirror = false): Blob => ({ c: h.M(mirror ? [-e.c[0], e.c[1], e.c[2]] : e.c), R: h.f.R, r: mul(e.r, h.hh) });++// a point ON the face at (x, y), its outward normal, and whether the camera can see it+export const onFace = (h: HeadCtx, x: number, y: number, lift = 0.004) => {+ const F = h.spec.face, u = (x - F.c[0]) / F.r[0], v = (y - F.c[1]) / F.r[1], w = Math.sqrt(Math.max(0, 1 - u * u - v * v));+ const local: V3 = [x, y, F.c[2] + F.r[2] * w], n0 = norm([u / F.r[0], v / F.r[1], w / F.r[2]]);+ const world = h.M(add(local, mul(n0, lift))), n = mv(h.f.R, n0), facing = dot(n, norm(sub(h.cam.eye, world)));+ const q = project(h.cam, world);+ return { p: [q.x, q.y] as P, facing, world };+};+// a polyline in face coordinates, split into the runs the camera can see+const faceRuns = (h: HeadCtx, pts: [number, number][], min = 0.05): P[][] => {+ const out: P[][] = []; let cur: P[] = [];+ pts.forEach(([x, y]) => { const f = onFace(h, x, y); if (f.facing > min) cur.push(f.p); else { if (cur.length > 1) out.push(cur); cur = []; } });+ if (cur.length > 1) out.push(cur);+ return out;+};+const ring = (cx: number, cy: number, rx: number, ry: number, n = 14, a0 = 0, a1 = Math.PI * 2): [number, number][] => Array.from({ length: n }, (_, i) => { const a = a0 + ((a1 - a0) * i) / (n - (a1 - a0 >= Math.PI * 2 - 1e-6 ? 0 : 1)); return [cx + Math.cos(a) * rx, cy + Math.sin(a) * ry]; });+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;+const clampE = (v: number) => Math.max(-1, Math.min(1, v));++// convex clip (Sutherland-Hodgman): the iris inside the lids+const clipConvex = (subject: P[], clip: P[]): P[] => {+ let out = subject; const n = clip.length, sgnA = Math.sign(clip.reduce((a, p, i) => { const q = clip[(i + 1) % n]; return a + p[0] * q[1] - q[0] * p[1]; }, 0)) || 1;+ for (let i = 0; i < n && out.length; i++) {+ const a = clip[i], b = clip[(i + 1) % n], inn = (p: P) => sgnA * ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])) >= 0, inp = out; out = [];+ inp.forEach((p, k) => { const q = inp[(k + inp.length - 1) % inp.length], pi = inn(p), qi = inn(q); if (pi !== qi) { const d1 = (b[0] - a[0]) * (q[1] - a[1]) - (b[1] - a[1]) * (q[0] - a[0]), d2 = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]), t = d1 / (d1 - d2); out.push([q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t]); } if (pi) out.push(p); });+ }+ return out;+};++// every mark of the face, for this expression+export const faceMarks = (h: HeadCtx, ex: Record<string, number>, roles: { line: string; pupil: string; white: string; blush: string; brow: string; mouth: string; lip: string }, px: number): Mark[] => {+ const S = h.spec, E = (k: string) => ex[k] ?? 0, marks: Mark[] = [], w = Math.max(0.9, px * 0.018);+ const lookX = clampE(E("lookX")), lookY = clampE(E("lookY"));+ const vis = (x: number, y: number, k = 0.12) => onFace(h, x, y).facing > k;+ // --- brows: raise lifts them, furrow pulls the inner ends down and together, sad lifts the inner ends+ [-1, 1].forEach((s) => {+ const inner = s * S.eyeX * 0.42, outer = s * (S.eyeX + S.eyeW * 1.35), y0 = S.browY + E("browRaise") * 0.035;+ const pts: [number, number][] = Array.from({ length: 7 }, (_, i) => { const t = i / 6, x = lerp(inner - s * E("browFurrow") * 0.012, outer, t), arch = Math.sin(t * Math.PI * 0.9) * 0.018; return [x, y0 + arch + (1 - t) * (-E("browFurrow") * 0.03 + E("browSad") * 0.035) - t * E("browSad") * 0.01]; });+ if (S.eyeStyle === "bead") faceRuns(h, pts, 0.12).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.brow, w: w * 1.5 }));+ else if (vis((inner + outer) / 2, y0, 0.15)) {+ // an adult brow has MASS: a band thick at its head by the nose, tapering to a fine tail+ const band = [...pts.map(([x, y], i) => [x, y + 0.013 * (1 - i / 7)] as [number, number]), ...pts.slice().reverse().map(([x, y], i) => [x, y - 0.009 * (i / 7) - 0.002] as [number, number])];+ marks.push({ kind: "fill", pts: band.map(([x, y]) => onFace(h, x, y).p), role: roles.brow, alpha: 0.85 });+ }+ });+ // --- eyes+ [-1, 1].forEach((s) => {+ const cx = s * S.eyeX, cy = S.eyeY, c = onFace(h, cx, cy);+ if (c.facing < 0.12) return;+ const lid = Math.max(-0.4, Math.min(1, E("lidUpper"))), low = Math.max(0, Math.min(1, E("lidLower") + E("cheek") * 0.35));+ if (S.eyeStyle === "bead") {+ if (lid > 0.85) { // closed: a happy arch if smiling, a flat lash line if not+ const up = E("smile") > 0.2 ? 1 : 0;+ faceRuns(h, ring(cx, cy - S.eyeH * 0.1, S.eyeW * 1.15, S.eyeH * (up ? 0.55 : 0.12), 9, Math.PI * 1.02, Math.PI * 1.98).map(([x, y]) => [x, cy - (y - cy) * (up ? 1 : -1)] as [number, number]), 0.1).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 2 }));+ return;+ }+ const ry = S.eyeH * (1 - Math.max(0, lid) * 0.75) * (1 - low * 0.35) * (1 + Math.max(0, -lid) * 0.25), ox = lookX * S.eyeW * 0.25, oy = lookY * S.eyeH * 0.18;+ const shape = ring(cx + ox, cy + oy - (S.eyeH - ry) * 0.5 * Math.sign(lid), S.eyeW, ry, 16).map(([x, y]) => onFace(h, x, y).p);+ marks.push({ kind: "fill", pts: shape, role: roles.pupil });+ const hi = onFace(h, cx + ox - S.eyeW * 0.32, cy + oy + ry * 0.36), hi2 = onFace(h, cx + ox + S.eyeW * 0.38, cy + oy - ry * 0.4);+ const k = project(h.cam, c.world).s * h.hh;+ marks.push({ kind: "dot", at: hi.p, rx: S.eyeW * 0.36 * k * Math.max(0.5, c.facing), ry: S.eyeW * 0.36 * k, rot: 0, role: roles.white });+ marks.push({ kind: "dot", at: hi2.p, rx: S.eyeW * 0.16 * k * Math.max(0.5, c.facing), ry: S.eyeW * 0.16 * k, rot: 0, role: roles.white, alpha: 0.85 });+ // the upper lid, a short lash stroke over the eye (children's eyes read bigger with it)+ faceRuns(h, ring(cx, cy + ry * 0.2, S.eyeW * 1.28, ry * 1.25, 7, Math.PI * 0.18, Math.PI * 0.82).map(([x, y]) => [x, 2 * cy - y + ry * 0.4] as [number, number]), 0.12).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 1.2, alpha: 0.7 }));+ } else {+ // almond: inner corner low and round, the upper lid peaks a third of the way out, the lower lid is flatter and peaks further out+ const inner = cx - s * S.eyeW * 0.95, outer = cx + s * S.eyeW * 1.0, open = S.eyeH * (1 - Math.max(0, lid) * 0.9) * (1 + Math.max(0, -lid) * 0.35);+ const up: [number, number][] = Array.from({ length: 9 }, (_, i) => { const t = i / 8, x = lerp(inner, outer, t), b = Math.sin(Math.pow(t, 0.8) * Math.PI); return [x, cy + 0.002 + open * b * 0.95 - t * 0.004]; });+ const lo: [number, number][] = Array.from({ length: 9 }, (_, i) => { const t = 1 - i / 8, x = lerp(inner, outer, t), b = Math.sin(Math.pow(t, 1.25) * Math.PI); return [x, cy - open * b * (0.62 - low * 0.35) - t * 0.004 + low * 0.006]; });+ const open2D = [...up, ...lo].map(([x, y]) => onFace(h, x, y).p);+ marks.push({ kind: "fill", pts: open2D, role: roles.white, alpha: 0.9 });+ const ir = S.eyeH * 0.95, ix = cx + lookX * S.eyeW * 0.35, iy = cy + open * 0.35 + lookY * open * 0.3;+ const iris = clipConvex(ring(ix, iy, ir, ir, 16).map(([x, y]) => onFace(h, x, y).p), open2D.length > 2 ? convexify(open2D) : open2D);+ if (iris.length > 2) marks.push({ kind: "fill", pts: iris, role: roles.pupil, alpha: 0.85 });+ const pup = clipConvex(ring(ix, iy, ir * 0.42, ir * 0.42, 10).map(([x, y]) => onFace(h, x, y).p), convexify(open2D));+ if (pup.length > 2) marks.push({ kind: "fill", pts: pup, role: roles.line });+ faceRuns(h, up, 0.1).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 1.5 }));+ faceRuns(h, lo, 0.1).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 0.7, alpha: 0.6 }));+ // the lid crease, following the upper lid a little higher+ faceRuns(h, up.slice(1, 8).map(([x, y]) => [x, y + 0.016 + E("browRaise") * 0.006] as [number, number]), 0.12).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 0.8, alpha: 0.55 }));+ }+ });+ // --- nose+ if (S.eyeStyle === "bead") {+ faceRuns(h, ring(0, S.noseY + 0.02, 0.028, 0.022, 7, Math.PI * 0.15, Math.PI * 0.85).map(([x, y]) => [x, 2 * (S.noseY + 0.02) - y] as [number, number]), 0.2).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 1.2, alpha: 0.75 }));+ } else {+ [-1, 1].forEach((s) => faceRuns(h, ring(s * 0.036, S.noseY + 0.006, 0.02, 0.016, 7, s > 0 ? -0.6 : Math.PI - 1.9, s > 0 ? 1.9 : Math.PI + 0.6), 0.15).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 1.1, alpha: 0.8 })));+ // the bridge, on the side turned from the light+ faceRuns(h, [[-0.035, 0.53], [-0.038, 0.46], [-0.04, 0.4], [-0.036, 0.355]], 0.15).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 0.7, alpha: 0.4 }));+ }+ // --- mouth+ const mw = S.mouthW * (1 + E("mouthWide") * 0.35 + Math.max(0, E("smile")) * 0.15), sm = E("smile"), op = Math.max(0, E("mouthOpen"));+ const upper: [number, number][] = Array.from({ length: 11 }, (_, i) => { const t = -1 + (2 * i) / 10; return [t * mw, S.mouthY + sm * 0.032 * t * t - (S.eyeStyle === "almond" ? 0.004 * Math.cos(t * Math.PI * 1.5) * (1 - Math.abs(t)) : 0) + op * 0.012]; });+ if (op > 0.05) {+ const lower = [...upper].reverse().map(([x, y]) => { const t = x / mw; return [x, y - op * 0.085 * (1 - t * t) * (sm > 0.3 ? 1.1 : 1) - op * 0.012] as [number, number]; });+ const shape = [...upper, ...lower].map(([x, y]) => onFace(h, x, y).p);+ if (vis(0, S.mouthY, 0.1)) {+ marks.push({ kind: "fill", pts: shape, role: roles.mouth, line: w * 1.4, tag: "mouth" });+ const tongue = lower.slice(2, 9).map(([x, y]) => [x * 0.8, y + 0.012] as [number, number]);+ marks.push({ kind: "fill", pts: [...tongue, ...tongue.slice().reverse().map(([x, y]) => [x, y + op * 0.022] as [number, number])].map(([x, y]) => onFace(h, x, y).p), role: roles.lip, alpha: 0.9, tag: "mouth" });+ }+ } else {+ faceRuns(h, upper, 0.12).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * (S.eyeStyle === "bead" ? 1.7 : 1.3), tag: "mouth" }));+ if (S.eyeStyle === "almond" && vis(0, S.mouthY, 0.12)) {+ // the lips: an upper lip with a cupid's bow and two peaks under the philtrum, a fuller lower lip, the shadow under it+ const top = Array.from({ length: 13 }, (_, i) => { const t = -1 + (2 * i) / 12; return [t * mw * 1.02, S.mouthY + sm * 0.032 * t * t + 0.02 * Math.pow(1 - t * t, 0.55) - 0.008 * Math.exp(-((t / 0.13) ** 2))] as [number, number]; });+ const bot = Array.from({ length: 13 }, (_, i) => { const t = 1 - (2 * i) / 12; return [t * mw * 0.96, S.mouthY + sm * 0.03 * t * t - 0.028 * Math.pow(1 - t * t, 0.7)] as [number, number]; });+ marks.push({ kind: "fill", pts: [...top, ...upper.slice().reverse()].map(([x, y]) => onFace(h, x, y).p), role: roles.lip, alpha: 0.55, tag: "mouth" });+ marks.push({ kind: "fill", pts: [...upper, ...bot].map(([x, y]) => onFace(h, x, y).p), role: roles.lip, alpha: 0.32, tag: "mouth" });+ faceRuns(h, top.slice(2, 11), 0.12).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 0.6, alpha: 0.35 }));+ faceRuns(h, Array.from({ length: 5 }, (_, i) => [(-0.5 + i / 4) * mw * 0.7, S.mouthY - 0.042] as [number, number]), 0.12).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 0.9, alpha: 0.4 }));+ [-1, 1].forEach((s) => faceRuns(h, [[s * 0.018, S.noseY - 0.035], [s * 0.022, S.mouthY + 0.03]], 0.2).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 0.5, alpha: 0.25 })));+ }+ }+ // dimples at the corners when she smiles+ if (sm > 0.4 && S.eyeStyle === "bead") [-1, 1].forEach((s) => faceRuns(h, [[s * (mw + 0.012), S.mouthY + sm * 0.04], [s * (mw + 0.02), S.mouthY + sm * 0.022]], 0.15).forEach((r) => marks.push({ kind: "line", pts: r, role: roles.line, w: w * 1.1, alpha: 0.7 })));+ // --- cheeks and freckles+ if (S.blush) [-1, 1].forEach((s) => { const c = onFace(h, s * 0.235, 0.3 + E("cheek") * 0.02); if (c.facing > 0.2) { const k = project(h.cam, c.world).s * h.hh; marks.push({ kind: "dot", at: c.p, rx: 0.075 * k * Math.max(0.35, c.facing), ry: 0.045 * k, rot: 0, role: roles.blush, alpha: 0.55 }); } });+ (S.freckles ?? []).forEach(([x, y]) => { const c = onFace(h, x, y); if (c.facing > 0.25) { const k = project(h.cam, c.world).s * h.hh; marks.push({ kind: "dot", at: c.p, rx: 0.008 * k * c.facing, ry: 0.008 * k, rot: 0, role: roles.brow, alpha: 0.7 }); } });+ return marks;+};+const convexify = (pts: P[]): P[] => { // the hull, in the same winding as the input+ const s = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]), x = (o: P, a: P, b: P) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]), lo: P[] = [], hi: P[] = [];+ for (const p of s) { while (lo.length >= 2 && x(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 (hi.length >= 2 && x(hi[hi.length - 2], hi[hi.length - 1], p) <= 0) hi.pop(); hi.push(p); }+ return [...lo.slice(0, -1), ...hi.slice(0, -1)];+};++// the head's volumes as parts: skull + nose (one part), and the two ears+export const headParts = (h: HeadCtx, skinRole: string, id = "head"): BlobPart[] => {+ const S = h.spec;+ const adult = S.eyeStyle === "almond";+ // the ear's rim (helix) and bowl (concha), drawn when the ear turns toward us+ const earMarks = (s: 1 | -1) => (cam: Camera): Mark[] => {+ const e = S.ear, c: V3 = [s * e.c[0], e.c[1], e.c[2]], n = mv(h.f.R, [s, 0, 0.3]), w = h.M(c);+ if (!adult || dot(norm(n), norm(sub(cam.eye, w))) < 0.2) return [];+ const P = (q: V3): P => { const r = project(cam, h.M(q)); return [r.x, r.y]; }, px = project(cam, w).s * h.hh, lw = Math.max(0.7, px * 0.012);+ const helix = Array.from({ length: 9 }, (_, i) => { const a = -0.3 + (i / 8) * Math.PI * 1.15; return P([s * (e.c[0] + e.r[0] * 0.9), e.c[1] + Math.sin(a) * e.r[1] * 0.72, e.c[2] - Math.cos(a) * e.r[2] * 0.7]); });+ const concha = Array.from({ length: 7 }, (_, i) => { const a = Math.PI * 0.2 + (i / 6) * Math.PI * 1.1; return P([s * (e.c[0] + e.r[0] * 0.9), e.c[1] - 0.02 + Math.sin(a) * e.r[1] * 0.3, e.c[2] - Math.cos(a) * e.r[2] * 0.3 + 0.01]); });+ return [{ kind: "line", pts: helix, role: "line", w: lw, alpha: 0.5 }, { kind: "line", pts: concha, role: "line", w: lw, alpha: 0.4 }];+ };+ const ear = (s: 1 | -1): BlobPart => ({ id: s > 0 ? "earL" : "earR", role: skinRole, groups: [{ blobs: [toBlob(h, S.ear, s < 0)], mode: "each" }], depthBias: 0.004 * h.hh / 0.25, seams: [], marksFn: earMarks(s) });+ const skull: BlobPart = { id, role: skinRole, over: ["neck", "neckSkin"], groups: [{ blobs: S.skull.map((e) => toBlob(h, e)), mode: "hull" }, ...(adult ? [] : [{ blobs: S.nose.map((e) => toBlob(h, e)), mode: "chain" as const }])], depthAt: h.M([0, 0.5, 0]) };+ if (!adult) return [skull, ear(1), ear(-1)];+ // An adult nose is its own form: a bridge, a ball, wings. It is drawn as a draftsman draws it,+ // by its FAR edge only (the line against the far cheek); in profile that edge is the whole nose.+ const nose: BlobPart = {+ id: "nose", role: skinRole, groups: [{ blobs: S.nose.map((e) => toBlob(h, e)), mode: "chain" }, { blobs: [-1, 1].map((s) => toBlob(h, { c: [s * 0.033, 0.345, 0.43], r: [0.022, 0.02, 0.024] })), mode: "each" }],+ over: [id], depthAt: h.M([0, 0.42, 0.3]),+ keepLineFn: (cam) => {+ const tip = project(cam, h.M([0, 0.36, 0.48])), root = project(cam, h.M([0, 0.4, 0])), dx = tip.x - root.x, dy = tip.y - root.y, L = Math.hypot(dx, dy), hs = project(cam, h.M([0, 0.4, 0])).s * h.hh;+ if (L < hs * 0.12) return () => false; // straight on: the nose is its tip and wings, no contour+ const ux = dx / L, uy = dy / L; return (p: P) => (p[0] - tip.x) * ux + (p[1] - tip.y) * uy > -hs * 0.05 - (L / hs) * hs * 0.1;+ },+ };+ return [skull, nose, ear(1), ear(-1)];+};+// A SHORT-HAIR CAP with no authored drawing. The cranium, inflated by the hair's thickness,+// projected to its silhouette; then clipped to the region above the VISIBLE stretch of the+// hairline (a loop from the brow, over the ear, to the nape). A convex hull of the hair would be+// wrong: from the front, the nape projects over the mouth.+export const hairCap = (h: HeadCtx, role: string, o: { lift?: number; front?: number; side?: number; back?: number; sideburn?: number; volume?: Ell[] } = {}): Part => {+ const c = h.spec.skull[0], lift = o.lift ?? 0.03, front = o.front ?? 0.82, side = o.side ?? 0.6, back = o.back ?? 0.3;+ const R: V3 = [c.r[0] + lift, c.r[1] + lift, c.r[2] + lift];+ const sil = hull(blobPts(h.cam, { c: h.M(c.c), R: h.f.R, r: mul(R, h.hh) }));+ const N = 72, loop = Array.from({ length: N }, (_, j) => {+ const th = (j / N) * Math.PI * 2, zf = Math.cos(th), yl0 = zf > 0 ? lerp(side, front, zf ** 1.6) : lerp(side, back, (-zf) ** 0.45), yl = yl0 - (o.sideburn ?? 0) * Math.exp(-(((Math.abs(Math.sin(th)) - 0.97) / 0.05) ** 2)) * (zf > 0 ? 1 : 0); // a sideburn dips in front of the ear+ const v = Math.max(-0.999, Math.min(0.999, (yl - c.c[1]) / R[1])), rr = Math.sqrt(1 - v * v);+ const q: V3 = [c.c[0] + Math.sin(th) * R[0] * rr, yl, c.c[2] + Math.cos(th) * R[2] * rr], n0 = norm([(q[0] - c.c[0]) / R[0] ** 2, (q[1] - c.c[1]) / R[1] ** 2, (q[2] - c.c[2]) / R[2] ** 2]);+ const w = h.M(q), f = dot(mv(h.f.R, n0), norm(sub(h.cam.eye, w))), pq = project(h.cam, w);+ return { p: [pq.x, pq.y] as P, f };+ });+ // the longest run of visible loop points (it wraps)+ let best: number[] = [], cur: number[] = [];+ for (let k = 0; k < N * 2; k++) { const j = k % N; if (loop[j].f > 0) { cur.push(j); if (cur.length > best.length && cur.length <= N) best = [...cur]; } else cur = []; }+ const b = sil.reduce((a, p) => ({ x0: Math.min(a.x0, p[0]), y0: Math.min(a.y0, p[1]), x1: Math.max(a.x1, p[0]), y1: Math.max(a.y1, p[1]) }), { x0: 1e9, y0: 1e9, x1: -1e9, y1: -1e9 });+ let poly: P[] = sil;+ if (best.length > 1 && best.length < N) {+ // close the region over the top of the head, outward from each end of the visible arc+ const arc = best.map((j) => loop[j].p), a0 = arc[0], a1 = arc[arc.length - 1], big = (b.x1 - b.x0) * 2, s0 = a0[0] < a1[0] ? -1 : 1;+ const region: P[] = [...arc, [a1[0] - s0 * big, a1[1]], [a1[0] - s0 * big, b.y0 - big], [a0[0] + s0 * big, b.y0 - big], [a0[0] + s0 * big, a0[1]]];+ poly = clipConvex(region, ccw(sil));+ }+ const d = project(h.cam, h.M([0, 0.62, -0.02]));+ return { id: "hair", role, depth: d.z - h.hh * 0.02, polys: [...(poly.length > 2 ? [ccw(poly)] : []), ...(o.volume ?? []).map((e) => ccw(hull(blobPts(h.cam, { c: h.M(e.c), R: h.f.R, r: mul(e.r, h.hh) }))))], size: h.hh * 0.2 * d.s, marks: [], over: ["head", "earL", "earR"], feature: "hair" };+};diff --git a/engine/src/canvas-core/character/human/mannequin.ts b/engine/src/canvas-core/character/human/mannequin.tsnew file mode 100644index 0000000..31ad9d8--- /dev/null+++ b/engine/src/canvas-core/character/human/mannequin.ts@@ -0,0 +1,151 @@+// THE MANNEQUIN. Volumes hung on the skeleton: an egg of a ribcage, a bowl of a pelvis, a waist+// between them, and limbs as chains of ellipsoids whose widths follow the MUSCLE PROFILE, not a+// capsule: the calf bulges high and at the back while the shin stays straight in front; the+// forearm is widest just below the elbow and flattens to a wrist wider than it is deep; the+// thigh carries the quadriceps forward; the deltoid caps the shoulder. "Straights against curves."+//+// Reference opened: Bridgman "Constructive Anatomy" (the wedged masses of ribcage and pelvis);+// Hogarth "Dynamic Anatomy" pp. 40-120 (the offset bulges of calf, forearm, thigh); Winter+// (2009) table 4.1 for where segment masses sit (used by balance.ts).+//+// Units: head heights (hh). A blob is [frame, centre, radii]; x is LATERAL (mirrored per side:+// + is away from the body's midline), y along the bone, z forward.+import type { P } from "../../core";+import { Blob, Camera, Frame, MIRROR_X, V3, add, apply, dot, mm, mul, mv, norm, project, sub, I3 } from "../math3";+import type { Mark } from "../types";+import type { BlobPart } from "../build";+import { type Rig, type Side, SIDES, sgn } from "./skeleton";+import { FINGERS, type HandAngles, handModel } from "./hands";++type FrameName = "pelvis" | "lumbar" | "chest" | "neck" | "upper" | "fore" | "hand" | "thigh" | "shin" | "foot" | "toes";+export type B = [FrameName, V3, V3];+export type BodySpec = {+ torso: B[]; torsoSided: B[]; // waist to shoulders, chained; pecs, traps, lats mirrored+ hips: B[]; hipsSided: B[]; // the pelvis bowl chained up to the waist; glutes and hip flare mirrored+ neck: B[]; upperArm: B[]; foreArm: B[]; thigh: B[]; shin: B[]; shinExtra: B[]; foot: B[]; toes: B[];+ seam: { neck: number; waist: number; shoulder: number; elbow: number; wrist: number; hip: number; knee: number; ankle: number };+ handGirth: number;+ handDetail?: boolean; // knuckle wrinkles, joint creases, palm lines (adult realism; storybook leaves them out)+ landmarks?: Partial<Record<"upperArm" | "foreArm" | "thigh" | "shin", B[]>>; // bony points and offset muscle heads that break the smooth sweep of a limb+};++export const CHILD_BODY: BodySpec = {+ torso: [["lumbar", [0, 0.14, 0.035], [0.39, 0.3, 0.31]], ["chest", [0, 0.36, 0.0], [0.42, 0.44, 0.31]], ["chest", [0, 0.66, -0.02], [0.46, 0.16, 0.27]]],+ torsoSided: [["chest", [0.2, 0.74, -0.05], [0.24, 0.1, 0.14]], ["chest", [0.42, 0.72, -0.02], [0.2, 0.11, 0.16]]],+ hips: [["lumbar", [0, 0.1, 0.03], [0.38, 0.2, 0.3]], ["pelvis", [0, -0.04, -0.01], [0.42, 0.28, 0.3]]],+ hipsSided: [["pelvis", [0.16, -0.14, -0.12], [0.2, 0.22, 0.17]]],+ neck: [["neck", [0, 0.0, 0.02], [0.17, 0.1, 0.16]], ["neck", [0, 0.44, 0.0], [0.155, 0.08, 0.15]]],+ upperArm: [["upper", [0.02, -0.13, 0], [0.13, 0.15, 0.14]], ["upper", [0, -0.45, 0.005], [0.112, 0.28, 0.118]], ["upper", [0, -0.87, -0.01], [0.092, 0.08, 0.088]]],+ foreArm: [["fore", [0.005, -0.2, 0.0], [0.105, 0.2, 0.098]], ["fore", [0, -0.5, 0], [0.082, 0.16, 0.08]], ["hand", [0, 0.03, 0], [0.058, 0.05, 0.08]]],+ thigh: [["thigh", [0.05, -0.18, 0], [0.24, 0.26, 0.24]], ["thigh", [0, -0.6, 0.03], [0.185, 0.38, 0.19]], ["thigh", [0, -1.18, 0.01], [0.13, 0.1, 0.13]]],+ shin: [["shin", [0, -0.04, 0.01], [0.125, 0.1, 0.13]], ["shin", [0.005, -0.38, -0.045], [0.125, 0.3, 0.13]], ["shin", [0, -1.13, 0], [0.074, 0.06, 0.074]]],+ shinExtra: [],+ foot: [["foot", [0, -0.03, 0], [0.085, 0.07, 0.085]], ["foot", [0, -0.14, -0.08], [0.08, 0.08, 0.09]], ["foot", [0, -0.14, 0.16], [0.1, 0.075, 0.16]]],+ toes: [["toes", [0, 0.01, 0.08], [0.1, 0.05, 0.09]]],+ seam: { neck: 0.2, waist: 0.45, shoulder: 0.2, elbow: 0.12, wrist: 0.09, hip: 0.3, knee: 0.14, ankle: 0.1 },+ handGirth: 1.12,+};+// Adult, 7.5 heads. Front half-widths (hh): deltoids ~0.98, chest at the armpit ~0.7, waist+// ~0.52, hips ~0.66. Depths: chest 0.44, waist 0.36, buttocks reach 0.46 behind the hip joint.+export const ADULT_BODY: BodySpec = {+ torso: [["lumbar", [0, 0.16, 0.04], [0.5, 0.34, 0.35]], ["chest", [0, 0.52, 0.0], [0.6, 0.62, 0.43]], ["chest", [0, 0.9, -0.01], [0.66, 0.26, 0.38]]],+ torsoSided: [+ ["chest", [0.25, 0.86, 0.22], [0.27, 0.2, 0.18]], // pectorals: their lower edge squares the chest+ ["chest", [0.22, 1.2, -0.08], [0.26, 0.16, 0.17]], // trapezius: the slope from the neck down to the acromion+ ["chest", [0.44, 0.62, -0.08], [0.17, 0.36, 0.3]], // latissimus: the V under the arm+ ["chest", [0.56, 1.0, -0.03], [0.23, 0.15, 0.22]], // the shoulder girdle: clavicle and scapula carry the torso out to the acromion+ ],+ hips: [["lumbar", [0, 0.1, 0.03], [0.5, 0.22, 0.35]], ["pelvis", [0, -0.08, -0.02], [0.6, 0.34, 0.38]]],+ hipsSided: [["pelvis", [0.23, -0.24, -0.2], [0.27, 0.3, 0.25]], ["pelvis", [0.44, -0.22, 0.0], [0.19, 0.24, 0.25]]], // glutes; the flare over the trochanter+ neck: [["neck", [0, 0.02, 0.04], [0.215, 0.14, 0.21]], ["neck", [0, 0.5, 0.02], [0.19, 0.1, 0.19]]],+ upperArm: [["upper", [0.02, -0.26, 0], [0.18, 0.3, 0.22]], ["upper", [0, -0.66, 0.03], [0.19, 0.42, 0.21]], ["upper", [0, -1.36, -0.02], [0.15, 0.12, 0.14]]],+ foreArm: [["fore", [0.02, -0.28, 0.01], [0.19, 0.3, 0.17]], ["fore", [0, -0.72, 0], [0.13, 0.22, 0.12]], ["hand", [0, 0.04, 0], [0.085, 0.07, 0.13]]],+ thigh: [["thigh", [0.04, -0.25, 0.0], [0.31, 0.38, 0.33]], ["thigh", [0, -0.88, 0.05], [0.3, 0.51, 0.3]], ["thigh", [0, -1.77, 0.02], [0.19, 0.16, 0.2]]],+ shin: [["shin", [0, -0.05, 0.02], [0.18, 0.14, 0.19]], ["shin", [0.01, -0.49, -0.09], [0.2, 0.46, 0.21]], ["shin", [0, -1.66, 0], [0.12, 0.08, 0.12]]],+ shinExtra: [["shin", [-0.06, -0.54, -0.11], [0.16, 0.32, 0.17]]], // gastrocnemius: the inner head sits lower than the outer+ foot: [["foot", [0, -0.1, 0], [0.12, 0.08, 0.12]], ["foot", [0, -0.24, -0.14], [0.12, 0.12, 0.14]], ["foot", [0, -0.22, 0.25], [0.16, 0.11, 0.26]]],+ toes: [["toes", [0, -0.01, 0.1], [0.17, 0.05, 0.13]]],+ seam: { neck: 0.3, waist: 0.62, shoulder: 0.28, elbow: 0.17, wrist: 0.13, hip: 0.42, knee: 0.2, ankle: 0.15 },+ handGirth: 1, handDetail: true,+ landmarks: {+ upperArm: [["upper", [0, -0.62, 0.1], [0.16, 0.3, 0.14]], ["upper", [0, -0.72, -0.1], [0.15, 0.36, 0.13]]], // biceps in front, triceps behind: two masses, not a tube+ foreArm: [["fore", [0, 0.02, -0.12], [0.08, 0.08, 0.07]], ["fore", [0.02, -0.2, 0.1], [0.14, 0.22, 0.11]], ["fore", [-0.06, -0.3, -0.03], [0.13, 0.26, 0.12]], ["hand", [0.05, 0.06, -0.1], [0.035, 0.035, 0.035]]], // elbow point; brachioradialis swell high on the thumb side; the flexor mass lower on the inside; the ulnar head at the wrist+ thigh: [["thigh", [-0.12, -1.52, 0.08], [0.14, 0.22, 0.13]]], // vastus medialis: the teardrop above the inner knee+ shin: [["shin", [0, 0.02, 0.19], [0.1, 0.11, 0.06]], ["shin", [-0.1, -0.03, 0.0], [0.12, 0.12, 0.14]], ["shin", [0.07, -0.38, -0.1], [0.15, 0.28, 0.16]], ["shin", [-0.1, -1.6, 0.0], [0.055, 0.055, 0.055]], ["shin", [0.1, -1.68, -0.02], [0.05, 0.05, 0.05]], ["shin", [0, -1.32, -0.12], [0.07, 0.2, 0.05]]], // kneecap; the inner condyle; outer calf head HIGHER than the inner; inner ankle bone higher than the outer; Achilles+ },+};++const frameOf = (r: Rig, n: FrameName, s: Side): Frame => (n === "pelvis" || n === "lumbar" || n === "chest" || n === "neck" ? r[n] : r[n][s]);+export const blob = (r: Rig, [fn, c, rad]: B, s: Side, inflate = 0): Blob => {+ const hh = r.dims.hh, k = sgn(s), f = frameOf(r, fn, s);+ return { c: apply(f, [c[0] * k * hh, c[1] * hh, c[2] * hh]), R: mm(f.R, I3), r: [(rad[0] + inflate) * hh, (rad[1] + inflate * 0.6) * hh, (rad[2] + inflate) * hh] };+};++export type BodyOpts = { roles?: Partial<Record<string, string>>; inflate?: Partial<Record<string, number>>; hands: Record<Side, HandAngles> };+// every body part as blobs, with the seams that hide where one part grows out of another+export const bodyParts = (r: Rig, spec: BodySpec, o: BodyOpts): BlobPart[] => {+ const hh = r.dims.hh, J = r.joints, role = (id: string) => o.roles?.[id] ?? o.roles?.skin ?? "skin", inf = (id: string) => o.inflate?.[id] ?? 0;+ const chain = (bs: B[], s: Side, id: string) => bs.map((b) => blob(r, b, s, inf(id)));+ const sided = (bs: B[], id: string) => SIDES.flatMap((s) => bs.map((b) => blob(r, b, s, inf(id))));+ const parts: BlobPart[] = [+ { id: "torso", role: role("torso"), groups: [{ blobs: chain(spec.torso, "L", "torso"), mode: "chain" }, { blobs: sided(spec.torsoSided, "torso"), mode: "each" }], depthAt: J.chest },+ { id: "hips", role: role("hips"), groups: [{ blobs: chain(spec.hips, "L", "hips"), mode: "chain" }, { blobs: sided(spec.hipsSided, "hips"), mode: "each" }], seams: [{ at: J.lumbar, r: spec.seam.waist * hh, with: "torso" }], depthAt: J.pelvis },+ { id: "neck", role: role("neck"), groups: [{ blobs: chain(spec.neck, "L", "neck"), mode: "chain" }], seams: [{ at: J.neck, r: spec.seam.neck * hh, with: "torso" }, { at: J.head, r: 0.3 * hh, with: "head" }], depthBias: 0.03 * hh, over: ["torso"] }, // the neck stands IN FRONT of the trapezius: seen from the front it paints over the shoulders+ ];+ for (const s of SIDES) {+ parts.push(+ { id: "upperArm" + s, role: role("upperArm"), groups: [{ blobs: chain(spec.upperArm, s, "upperArm"), mode: "chain" }], seams: [{ at: J["shoulder" + s], r: spec.seam.shoulder * hh, with: "torso" }, { at: J["elbow" + s], r: spec.seam.elbow * hh, with: "foreArm" + s }], depthBias: -0.06 * hh },+ { id: "foreArm" + s, role: role("foreArm"), groups: [{ blobs: chain(spec.foreArm, s, "foreArm"), mode: "chain" }], seams: [{ at: J["elbow" + s], r: spec.seam.elbow * hh, with: "upperArm" + s }, { at: J["wrist" + s], r: spec.seam.wrist * hh, with: "palm" + s }], depthBias: -0.07 * hh },+ { id: "thigh" + s, role: role("thigh"), groups: [{ blobs: chain(spec.thigh, s, "thigh"), mode: "chain" }], seams: [{ at: J["hip" + s], r: spec.seam.hip * hh, with: "hips" }, { at: J["knee" + s], r: spec.seam.knee * hh, with: "shin" + s }], depthBias: -0.02 * hh },+ { id: "shin" + s, role: role("shin"), groups: [{ blobs: chain(spec.shin, s, "shin"), mode: "chain" }, ...(spec.shinExtra.length ? [{ blobs: spec.shinExtra.map((b) => blob(r, b, s, inf("shin"))), mode: "each" as const }] : [])], seams: [{ at: J["knee" + s], r: spec.seam.knee * hh, with: "thigh" + s }, { at: J["ankle" + s], r: spec.seam.ankle * hh, with: "foot" + s }], depthBias: -0.02 * hh },+ { id: "foot" + s, role: role("foot"), groups: [{ blobs: chain(spec.foot, s, "foot"), mode: "chain" }, { blobs: [blob(r, spec.foot[2], s, inf("foot")), ...spec.toes.map((b) => blob(r, b, s, inf("foot")))], mode: "chain" }], seams: [{ at: J["ankle" + s], r: spec.seam.ankle * hh, with: "shin" + s }], depthBias: -0.03 * hh },+ );+ for (const [pid, bs] of Object.entries(spec.landmarks ?? {})) { const part = parts.find((q) => q.id === pid + s); if (part && bs?.length) part.groups.push({ blobs: bs.map((b) => blob(r, b, s, inf(pid))), mode: "each" }); }+ // the hand: palm block, then each digit its own part so fingers overlap each other correctly+ const hm = handModel(r.hand[s], s, r.dims.hand, o.hands[s], spec.handGirth);+ const Lh = r.dims.hand, Mh = s === "L" ? I3 : MIRROR_X, H = r.hand[s];+ const palmMarks = (cam: Camera): Mark[] => {+ const px = project(cam, H.p).s * Lh; if (!spec.handDetail || px < 70) return [];+ const L = (v: V3): V3 => apply(H, mv(Mh, mul(v, Lh))), P2 = (vs: V3[]): P[] => vs.map((v) => { const p = project(cam, L(v)); return [p.x, p.y]; });+ const back = mv(H.R, mv(Mh, [1, 0, 0])), toCam = norm(sub(cam.eye, H.p)), out: Mark[] = [], w = Math.max(0.6, px * 0.006);+ if (dot(back, toCam) > 0.2) hm.mcpArc.forEach((_, i) => { const m = (["index", "middle", "ring", "little"] as const)[i], c = FINGERS[m].mcp; out.push({ kind: "line", pts: P2([[0.07, c[1] - 0.005, c[2] - 0.035], [0.078, c[1] + 0.012, c[2]], [0.07, c[1] - 0.005, c[2] + 0.035]]), role: "line", w, alpha: 0.35 }); });+ if (dot(back, toCam) < -0.2) {+ // the palm's three great creases: heart line, head line, and the thenar crease round the ball of the thumb+ out.push({ kind: "line", pts: P2([[-0.074, -0.37, -0.19], [-0.076, -0.385, -0.08], [-0.075, -0.39, 0.03], [-0.072, -0.4, 0.1]]), role: "line", w, alpha: 0.4 });+ out.push({ kind: "line", pts: P2([[-0.074, -0.3, 0.15], [-0.076, -0.31, 0.04], [-0.075, -0.33, -0.08], [-0.072, -0.35, -0.15]]), role: "line", w, alpha: 0.35 });+ out.push({ kind: "line", pts: P2([[-0.074, -0.3, 0.14], [-0.078, -0.22, 0.08], [-0.078, -0.12, 0.05], [-0.074, -0.05, 0.03]]), role: "line", w, alpha: 0.35 });+ }+ return out;+ };+ parts.push({ id: "palm" + s, role: role("hand"), groups: [{ blobs: hm.palm, mode: "hull" }], seams: [{ at: J["wrist" + s], r: spec.seam.wrist * hh * 1.2, with: "foreArm" + s }], depthBias: -0.08 * hh, marksFn: palmMarks });+ hm.digits.forEach((d) => {+ // the thumb leaves the palm at its MCP: its metacarpal is inside the thenar, in the palm part+ const from = d.digit === "thumb" ? 1 : 0, bl: Blob[] = d.pts.slice(from).map((p, i) => ({ c: p, R: I3, r: [d.radii[i + from], d.radii[i + from], d.radii[i + from]] }));+ const nail = hm.nails.find((n) => n.digit === d.digit)!, k = sgn(s);+ const marksFn = (cam: Camera): Mark[] => {+ const out: Mark[] = [], rpx = project(cam, d.pts[2]).s * d.radii[2];+ // joint creases, only where the hand is big enough on screen to carry them: wrinkles over the+ // back of each finger joint, a single fold line on the palm side+ if (spec.handDetail && rpx > 2.2) d.frames.forEach((f, j) => {+ if (j === 0 || (d.digit === "thumb" && j === 0)) return;+ const at = d.pts[j], rad = d.radii[j], dn = mv(f.R, [k, 0, 0]), la = mv(f.R, [0, 0, 1]), al = mv(f.R, [0, -1, 0]);+ const arc = (side: number, off: number, span: number) => Array.from({ length: 5 }, (_, i) => { const u = -1 + i / 2; return add(add(at, mul(dn, side * rad * Math.sqrt(1 - (u * span) ** 2) * 0.98)), add(mul(la, u * span * rad), mul(al, off * rad + side * 0.12 * rad * u * u))); });+ const seen = (side: number) => dot(mul(dn, side), norm(sub(cam.eye, at))) > 0.2;+ const P2 = (q: V3[]): P[] => q.map((v) => { const p = project(cam, v); return [p.x, p.y]; });+ if (seen(1)) (j === 1 ? [-0.25, 0.05, 0.3] : [0.0]).forEach((off, i) => out.push({ kind: "line", pts: P2(arc(1, off, 0.62 - Math.abs(off) * 0.4)), role: "line", w: Math.max(0.5, rpx * 0.12), alpha: 0.32 - i * 0.04 }));+ if (seen(-1)) out.push({ kind: "line", pts: P2(arc(-1, 0.05, 0.75)), role: "line", w: Math.max(0.5, rpx * 0.14), alpha: 0.4 });+ });+ const nrm = mv(nail.R, [k, 0, 0]), dist = mv(nail.R, [0, -1, 0]), lat = mv(nail.R, [0, 0, 1]);+ if (dot(nrm, norm(sub(cam.eye, nail.c))) < 0.15) return out;+ const pts = Array.from({ length: 12 }, (_, i) => { const a = (i / 12) * Math.PI * 2, u = Math.cos(a), v = Math.sin(a), sq = (t: number) => Math.sign(t) * Math.abs(t) ** 0.7; return project(cam, add(nail.c, add(mul(lat, sq(u) * nail.w * 0.5), mul(dist, sq(v) * nail.l * 0.5)))); }).map((q) => [q.x, q.y] as P);+ out.push({ kind: "fill", pts, role: "nail", alpha: 0.55, line: 0.5 });+ // the moon-shaped free edge of the nail catches light: a lighter crescent at its tip+ if (spec.handDetail && rpx > 3) out.push({ kind: "line", pts: Array.from({ length: 5 }, (_, i) => { const u = -0.8 + (i / 4) * 1.6; const q = project(cam, add(nail.c, add(mul(lat, u * nail.w * 0.45), mul(dist, nail.l * (0.42 - 0.08 * u * u))))); return [q.x, q.y] as P; }), role: "white", w: Math.max(0.5, rpx * 0.15), alpha: 0.6 });+ return out;+ };+ parts.push({ id: `${d.digit}${s}`, role: role("hand"), groups: [{ blobs: bl, mode: "chain" }], seams: [{ at: d.pts[from], r: d.radii[from] * (d.digit === "thumb" ? 1.3 : 1.5), with: "palm" + s }], depthBias: -0.085 * hh, depthAt: d.pts[2], marksFn });+ });+ }+ return parts;+};+export { handModel };diff --git a/engine/src/canvas-core/character/human/skeleton.ts b/engine/src/canvas-core/character/human/skeleton.tsnew file mode 100644index 0000000..9eb524a--- /dev/null+++ b/engine/src/canvas-core/character/human/skeleton.ts@@ -0,0 +1,136 @@+// THE 3D SKELETON. Bone lengths come from the canon row; joint angles come from the pose; a pose+// outside the range of motion FAILS AT LOAD, which catches broken elbows before anyone looks.+//+// Ranges of motion: American Academy of Orthopaedic Surgeons "Joint Motion: Method of Measuring+// and Recording" (1965) / Norkin & White "Measurement of Joint Motion" (normal adult values),+// rounded. Elbow 0-150, knee 0-140, hip flexion 125 (90 with the knee straight: hamstrings),+// hyperextension never past 5-10. Wrist, neck and shoulder are CONES, not independent boxes.+import { DEG, Frame, M3, V3, add, apply, cross, mm, mv, norm, rotAxis, rx, ry, rz, I3 } from "../math3";+import type { Pose } from "../types";+import type { CanonRow } from "./canon";++export type Side = "L" | "R";+export const SIDES: Side[] = ["L", "R"];+export const sgn = (s: Side) => (s === "L" ? 1 : -1); // her left is +x++// ---------------------------------------------------------------- joint limits+type Lim = [number, number];+export const LIMITS: Record<string, Lim> = {+ pelvisTilt: [-20, 30], pelvisSide: [-15, 15], pelvisTwist: [-40, 40],+ spineBend: [-30, 70], spineSide: [-35, 35], spineTwist: [-45, 45],+ neckBend: [-40, 45], neckSide: [-35, 35], neckTwist: [-60, 60],+ headNod: [-30, 30], headTilt: [-20, 20], headTurn: [-30, 30],+ clavLift: [-10, 30], clavFwd: [-15, 25],+ shoulderRaise: [0, 180], shoulderSwing: [-90, 140], shoulderTwist: [-90, 90],+ elbow: [0, 150], pronation: [-90, 90],+ wristFlex: [-70, 80], wristDev: [-25, 35],+ hipFlex: [-20, 125], hipAbd: [-25, 45], hipRot: [-40, 45],+ knee: [0, 140], ankle: [-45, 25], toe: [0, 60],+};+export const JOINT_NAMES = [+ "pelvisTilt", "pelvisSide", "pelvisTwist", "spineBend", "spineSide", "spineTwist", "neckBend", "neckSide", "neckTwist", "headNod", "headTilt", "headTurn",+ ...["clavLift", "clavFwd", "shoulderRaise", "shoulderSwing", "shoulderTwist", "elbow", "pronation", "wristFlex", "wristDev", "hipFlex", "hipAbd", "hipRot", "knee", "ankle", "toe"].flatMap((j) => [j + "L", j + "R"]),+];+const baseName = (j: string) => (/[LR]$/.test(j) && LIMITS[j.slice(0, -1)] ? j.slice(0, -1) : j);++// Every violation, in words a human can act on. Empty means the pose is legal.+export const limitViolations = (j: Record<string, number>): string[] => {+ const out: string[] = [];+ for (const [k, v] of Object.entries(j)) {+ const b = baseName(k), L = LIMITS[b];+ if (!L) { out.push(`unknown joint '${k}'`); continue; }+ if (!Number.isFinite(v)) out.push(`${k} is not a number`);+ else if (v < L[0] - 1e-6 || v > L[1] + 1e-6) out.push(`${k} = ${v.toFixed(1)} outside ${L[0]}..${L[1]}`);+ }+ const g = (k: string) => j[k] ?? 0;+ // cones: combined motion is limited more than each axis alone+ for (const s of ["L", "R"]) {+ const f = g("wristFlex" + s), d = g("wristDev" + s), lf = f >= 0 ? 80 : 70, ld = d >= 0 ? 35 : 25;+ if ((f / lf) ** 2 + (d / ld) ** 2 > 1.0001) out.push(`wrist${s} cone: flex ${f} with deviation ${d} exceeds the wrist ellipse`);+ const r = g("shoulderRaise" + s), w = g("shoulderSwing" + s);+ if (w < 0 && r * Math.sin(-w * DEG) > 62) out.push(`shoulder${s} cone: ${(r * Math.sin(-w * DEG)).toFixed(0)} deg of extension behind the body (max ~60)`);+ if (w > 90 && r * Math.sin((w - 90) * DEG) > 55) out.push(`shoulder${s} cone: ${(r * Math.sin((w - 90) * DEG)).toFixed(0)} deg of cross-body adduction (max ~50)`);+ if (g("knee" + s) < 20 && g("hipFlex" + s) > 95) out.push(`hip${s}: flexion ${g("hipFlex" + s)} with a straight knee (hamstrings stop a straight leg near 90)`);+ }+ const nb = g("neckBend") + g("headNod"), ns = g("neckSide") + g("headTilt"), nt = g("neckTwist") + g("headTurn");+ if ((nb / (nb >= 0 ? 60 : 55)) ** 2 + (ns / 45) ** 2 > 1.0001) out.push(`neck cone: bend ${nb} with side ${ns} exceeds the cervical ellipse`);+ if (Math.abs(nt) > 80) out.push(`neck: total head rotation ${nt} (max ~80)`);+ return out;+};++// ---------------------------------------------------------------- bone lengths+export type Dims = {+ hh: number; height: number;+ root: number; hipDrop: number; hipX: number; thigh: number; shin: number; ankleH: number; heel: number; toe: number; ball: number;+ lumbar: number; chest: number; neckBase: number; neckBaseZ: number; neck: number; pivotToChin: number;+ shoulderX: number; shoulderY: number; upperArm: number; forearm: number; hand: number;+};+export const dimsFromCanon = (c: CanonRow, heightM: number): Dims => {+ const hh = heightM / c.heads, k = (v: number) => v * hh;+ return {+ hh, height: heightM, root: k(c.root), hipDrop: k(c.root - c.hip), hipX: k(c.hipX), thigh: k(c.hip - c.knee), shin: k(c.knee - c.ankle), ankleH: k(c.ankle),+ heel: k(c.heel), toe: k(c.foot - c.heel), ball: k((c.foot - c.heel) * 0.72),+ lumbar: k(c.lumbar - c.root), chest: k(c.chest - c.lumbar), neckBase: k(c.neckBase - c.chest), neckBaseZ: -k(0.1), neck: k(c.pivot - c.neckBase), pivotToChin: k(c.pivot - (c.heads - 1)),+ shoulderX: k(c.shoulderX), shoulderY: k(c.shoulder - c.chest), upperArm: k(c.upperArm), forearm: k(c.forearm), hand: k(c.hand),+ };+};++// ---------------------------------------------------------------- forward kinematics+export type Rig = {+ dims: Dims; j: Record<string, number>;+ pelvis: Frame; lumbar: Frame; chest: Frame; neck: Frame; head: Frame;+ shoulder: Record<Side, Frame>; upper: Record<Side, Frame>; fore: Record<Side, Frame>; hand: Record<Side, Frame>;+ hip: Record<Side, Frame>; thigh: Record<Side, Frame>; shin: Record<Side, Frame>; foot: Record<Side, Frame>; toes: Record<Side, Frame>;+ joints: Record<string, V3>; // named joint centres, world+};+const child = (f: Frame, off: V3, R: M3 = I3): Frame => ({ p: apply(f, off), R: mm(f.R, R) });+// anatomical rotations in a parent frame whose x = her left, y = up, z = forward+const flexFwd = (a: number) => rx(a * DEG); // +y (or +z) toward the front+const sideTo = (a: number) => rz(-a * DEG); // +y toward her left (+x)+const twist = (a: number) => ry(a * DEG); // face turns to her left++export const fk = (dims: Dims, pose: Pose): Rig => {+ const j = pose.joints, g = (k: string) => j[k] ?? 0, d = dims;+ const body = mm(ry(pose.yaw * DEG), mm(rx((pose.pitch ?? 0) * DEG), rz(-(pose.roll ?? 0) * DEG)));+ const pelvis: Frame = { p: pose.root, R: mm(body, mm(twist(g("pelvisTwist")), mm(flexFwd(g("pelvisTilt")), sideTo(g("pelvisSide"))))) };+ const spine = (k: number) => mm(twist(g("spineTwist") * k), mm(flexFwd(g("spineBend") * k), sideTo(g("spineSide") * k)));+ const lumbar = child(pelvis, [0, d.lumbar, -0.01 * d.hh], spine(0.5));+ const chest = child(lumbar, [0, d.chest, 0], spine(0.5));+ const neck = child(chest, [0, d.neckBase, d.neckBaseZ], mm(twist(g("neckTwist")), mm(flexFwd(g("neckBend") + 12), sideTo(g("neckSide"))))); // the neck leans forward ~12 deg at rest+ const head = child(neck, [0, d.neck, 0], mm(twist(g("headTurn")), mm(flexFwd(g("headNod") - 12), sideTo(g("headTilt")))));+ const rig = { dims, j, pelvis, lumbar, chest, neck, head, shoulder: {}, upper: {}, fore: {}, hand: {}, hip: {}, thigh: {}, shin: {}, foot: {}, toes: {}, joints: {} } as unknown as Rig;+ for (const s of SIDES) {+ const k = sgn(s), G = (n: string) => g(n + s);+ // shoulder girdle: the clavicle lifts and protracts the joint+ const sh = child(chest, [k * d.shoulderX, d.shoulderY + Math.sin(G("clavLift") * DEG) * d.shoulderX * 0.55, -0.02 * d.hh + Math.sin(G("clavFwd") * DEG) * d.shoulderX * 0.5]);+ // raise the arm from hanging, toward a direction `swing` (0 = out to the side, 90 = forward)+ const out: V3 = [k, 0, 0], fwd: V3 = [0, 0, 1], down: V3 = [0, -1, 0], w = G("shoulderSwing") * DEG;+ const h = norm(add(out.map((v) => v * Math.cos(w)) as V3, fwd.map((v) => v * Math.sin(w)) as V3));+ const Rr = rotAxis(cross(down, h), G("shoulderRaise") * DEG), dir = mv(Rr, down);+ const Rup = mm(rotAxis(dir, -k * G("shoulderTwist") * DEG), Rr);+ const upper: Frame = { p: sh.p, R: mm(chest.R, Rup) };+ const fore = child(upper, [0, -d.upperArm, 0], rx(-G("elbow") * DEG));+ const wrist = child(fore, [0, -d.forearm, 0], mm(ry(-k * G("pronation") * DEG), mm(rz(-k * G("wristFlex") * DEG), rx(-G("wristDev") * DEG))));+ rig.shoulder[s] = sh; rig.upper[s] = upper; rig.fore[s] = fore; rig.hand[s] = wrist;+ const hip = child(pelvis, [k * d.hipX, -d.hipDrop, 0]);+ const thigh: Frame = { p: hip.p, R: mm(pelvis.R, mm(rx(-G("hipFlex") * DEG), mm(rz(k * G("hipAbd") * DEG), ry(k * G("hipRot") * DEG)))) };+ const shin = child(thigh, [0, -d.thigh, 0], rx(G("knee") * DEG));+ const foot = child(shin, [0, -d.shin, 0], rx(-G("ankle") * DEG));+ const toes = child(foot, [0, -d.ankleH * 0.85, d.ball], rx(-G("toe") * DEG));+ rig.hip[s] = hip; rig.thigh[s] = thigh; rig.shin[s] = shin; rig.foot[s] = foot; rig.toes[s] = toes;+ Object.assign(rig.joints, { ["shoulder" + s]: sh.p, ["elbow" + s]: fore.p, ["wrist" + s]: wrist.p, ["hip" + s]: hip.p, ["knee" + s]: shin.p, ["ankle" + s]: foot.p, ["ball" + s]: toes.p, ["heel" + s]: apply(foot, [0, -d.ankleH * 0.9, -d.heel]), ["toeTip" + s]: apply(toes, [0, 0, d.toe - d.ball]) });+ }+ Object.assign(rig.joints, { pelvis: pelvis.p, lumbar: lumbar.p, chest: chest.p, neck: neck.p, head: head.p, crown: apply(head, [0, d.hh - d.pivotToChin, 0]) });+ return rig;+};++// Drop (or lift) the root so the lowest point of either foot rests on the floor.+export const lowestFoot = (r: Rig) => Math.min(...SIDES.flatMap((s) => [apply(r.foot[s], [0, -r.dims.ankleH, -r.dims.heel * 0.9])[1], apply(r.toes[s], [0, -r.dims.ankleH * 0.15, r.dims.toe - r.dims.ball])[1], apply(r.foot[s], [0, -r.dims.ankleH, 0])[1]]));++// bone lengths measured back OUT of the posed rig: the gate compares them with the rest pose+export const boneLengths = (r: Rig): Record<string, number> => {+ const J = r.joints, D = (a: V3, b: V3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]), o: Record<string, number> = {};+ for (const s of SIDES) { o["upperArm" + s] = D(J["shoulder" + s], J["elbow" + s]); o["forearm" + s] = D(J["elbow" + s], J["wrist" + s]); o["thigh" + s] = D(J["hip" + s], J["knee" + s]); o["shin" + s] = D(J["knee" + s], J["ankle" + s]); o["hipWidth" + s] = D(J.pelvis, J["hip" + s]); }+ o.neck = D(J.neck, J.head); o.lumbarSeg = D(J.pelvis, J.lumbar); o.thoracicSeg = D(J.lumbar, J.chest); // the spine is two segments: its end-to-end span changes when it bends, each segment does not+ return o;+};diff --git a/engine/src/canvas-core/character/human/walk.ts b/engine/src/canvas-core/character/human/walk.tsnew file mode 100644index 0000000..895c911--- /dev/null+++ b/engine/src/canvas-core/character/human/walk.ts@@ -0,0 +1,103 @@+// THE WALK, from footsteps. A walk is a list of heel strikes (which foot, when, where); every+// frame is solved from it: each foot is either PLANTED (heel strike, rolling flat, heel lifting,+// pushing off the ball) or SWINGING on an arc to its next strike; the pelvis rides over the+// planted foot, lowest at double support and highest at mid-stance; the pelvis turns toward the+// swinging leg and the ribcage turns against it; the arms swing against the legs; the head stays+// level. Legs are solved with the analytic IK, so a foot never slides while it is planted.+//+// Reference opened: Richard Williams, "The Animator's Survival Kit" (2001), the walk chapter+// (contact, down, passing, up; the arms opposite the legs; the down position just after contact);+// Perry & Burnfield, "Gait Analysis" (2010) for the timing: stance ~60% and swing ~40% of the+// cycle, heel rocker / ankle rocker / forefoot rocker, knee ~15 deg at loading, ~60 deg in swing.+import { DEG, V3, add, mul } from "../math3";+import type { Pose } from "../types";+import { stand } from "./balance";+import type { Dims, Side } from "./skeleton";++export type Strike = { side: Side; t: number; s: number }; // frame, distance along the path of the HEEL contact+export type WalkPlan = { strikes: Strike[]; cycle: number; stance: number; lift: number; stride: number; rootS: (t: number) => number; stopAt: number; lateral: number };++const ease = (u: number) => u * u * (3 - 2 * u);+const clamp01 = (u: number) => Math.max(0, Math.min(1, u));++// Walk `n` steps from s0, first foot `first`, a step every `cycle/2` frames starting at t0, then+// bring the trailing foot up beside the leading one and settle.+export const planWalk = (o: { t0: number; s0: number; step: number; cycle: number; n: number; first: Side; lateral: number }): WalkPlan => {+ const half = o.cycle / 2, v = o.step / half, strikes: Strike[] = [];+ const other = (s: Side): Side => (s === "L" ? "R" : "L");+ let side = o.first;+ // the root is a little behind the leading heel at strike (the heel lands ~40% of a step ahead)+ const ahead = o.step * 0.42;+ for (let k = 0; k < o.n; k++) { const t = o.t0 + k * half; strikes.push({ side, t, s: o.s0 + v * (t - o.t0) + ahead }); side = other(side); }+ // the closing step: the trailing foot comes up level with the leading one+ const last = strikes[strikes.length - 1], tClose = last.t + half;+ strikes.push({ side, t: tClose, s: last.s });+ const tStop = tClose + half * 0.9, sStop = last.s - o.step * 0.12, tDec = last.t - half * 0.2, sDec = o.s0 + v * (tDec - o.t0);+ const rootS = (t: number) => {+ if (t <= tDec) return o.s0 + v * (t - o.t0);+ if (t >= tStop) return sStop;+ // Hermite from (tDec, sDec, v) to (tStop, sStop, 0)+ const T = tStop - tDec, u = (t - tDec) / T, h00 = 2 * u ** 3 - 3 * u * u + 1, h10 = u ** 3 - 2 * u * u + u, h01 = -2 * u ** 3 + 3 * u * u;+ return h00 * sDec + h10 * T * v + h01 * sStop;+ };+ return { strikes, cycle: o.cycle, stance: o.cycle * 0.6, lift: 0, stride: o.step * 2, rootS, stopAt: tStop, lateral: o.lateral };+};++// the foot's pitch (toes up +) and which point it pivots on, through stance+const stancePitch = (phi: number): { pitch: number; pivot: "heel" | "flat" | "ball" } => {+ if (phi < 0.12) return { pitch: 14 * (1 - ease(phi / 0.12)), pivot: "heel" }; // heel rocker+ if (phi < 0.5) return { pitch: 0, pivot: "flat" }; // ankle rocker+ return { pitch: -38 * Math.pow((phi - 0.5) / 0.5, 1.4), pivot: "ball" }; // forefoot rocker, push-off+};++// sagittal (forward f, up u) position of the ankle for a foot whose heel contact is at f = s+const ankleAt = (d: Dims, s: number, pitch: number, pivot: "heel" | "flat" | "ball"): [number, number] => {+ const p = pitch * DEG, rot = (f: number, u: number): [number, number] => [f * Math.cos(p) - u * Math.sin(p), f * Math.sin(p) + u * Math.cos(p)];+ const heelToAnkle: [number, number] = [d.heel * 0.9, d.ankleH], ball = s + d.heel * 0.9 + d.ball;+ if (pivot === "ball") { const r = rot(-d.ball, d.ankleH); return [ball + r[0], r[1]]; }+ const r = rot(heelToAnkle[0], heelToAnkle[1]); return [s + r[0], r[1]];+};++export type WalkFrame = { pose: Pose; phase: number; amp: number };+// Pose at frame t. `path` is where s = 0 is, and which way is forward (a unit vector on the floor).+export const walkAt = (d: Dims, plan: WalkPlan, t: number, base: Pose, path: { origin: V3; dir: V3 }, style: { armSwing?: number; bob?: number; twist?: number } = {}): WalkFrame => {+ const fwd = path.dir, yaw = Math.atan2(fwd[0], fwd[2]) / DEG, left: V3 = [Math.cos(yaw * DEG), 0, -Math.sin(yaw * DEG)];+ const at = (s: number, l: number, u: number): V3 => add(add(path.origin, mul(fwd, s)), add(mul(left, l), [0, u, 0]));+ const feet = {} as Record<Side, V3>, pitch = {} as Record<Side, number>;+ const lastStrike = plan.strikes[plan.strikes.length - 1];+ for (const side of ["L", "R"] as Side[]) {+ const mine = plan.strikes.filter((k) => k.side === side), lat = (side === "L" ? 1 : -1) * plan.lateral;+ let k = -1; for (let i = 0; i < mine.length; i++) if (mine[i].t <= t) k = i;+ const next = mine[k + 1];+ if (k < 0) { // before this foot's first strike: planted where it stood, one step back, lifting at the end+ const s0 = next.s - plan.stride, tOff = next.t - (plan.cycle - plan.stance);+ if (t < tOff) { const phi = 0.5 + 0.5 * clamp01((t - (tOff - plan.stance * 0.5)) / (plan.stance * 0.5)), sp = stancePitch(phi), a = ankleAt(d, s0, sp.pitch, sp.pivot); feet[side] = at(a[0], lat, a[1]); pitch[side] = sp.pitch; }+ else { const u = clamp01((t - tOff) / (next.t - tOff)), A = ankleAt(d, s0, -38, "ball"), B = ankleAt(d, next.s, 14, "heel"), e = ease(u); feet[side] = at(A[0] + (B[0] - A[0]) * e, lat, A[1] + (B[1] - A[1]) * e + d.ankleH * 0.55 * Math.sin(Math.PI * Math.pow(u, 0.8))); pitch[side] = -38 + 52 * e; }+ continue;+ }+ const cur = mine[k], isLast = cur === lastStrike || !next;+ const stanceEnd = isLast ? Infinity : cur.t + plan.stance;+ if (t < stanceEnd) {+ const phi = isLast ? Math.min(0.49, (t - cur.t) / plan.stance) : (t - cur.t) / plan.stance, sp = stancePitch(phi), a = ankleAt(d, cur.s, sp.pitch, sp.pivot);+ feet[side] = at(a[0], lat, a[1]); pitch[side] = sp.pitch;+ } else {+ const u = clamp01((t - stanceEnd) / (next.t - stanceEnd)), A = ankleAt(d, cur.s, -38, "ball"), closing = next === lastStrike, B = ankleAt(d, next.s, closing ? 4 : 14, "heel"), e = ease(u);+ feet[side] = at(A[0] + (B[0] - A[0]) * e, lat, A[1] + (B[1] - A[1]) * e + d.ankleH * (closing ? 0.35 : 0.55) * Math.sin(Math.PI * Math.pow(u, 0.8)));+ pitch[side] = -38 + (closing ? 42 : 52) * e;+ }+ }+ // the gait phase: 0 at a left heel strike, 0.5 at a right one; the amplitude fades as she stops+ const Ls = plan.strikes.filter((k) => k.side === "L"), prevL = [...Ls].reverse().find((k) => k.t <= t) ?? Ls[0];+ const phase = ((t - prevL.t) / plan.cycle) % 1, amp = clamp01((plan.stopAt - t) / (plan.cycle * 0.75)), c = Math.cos(2 * Math.PI * phase) * amp, s2 = Math.cos(4 * Math.PI * phase) * amp;+ const A = style.armSwing ?? 22, tw = style.twist ?? 6;+ const arm = (a: number) => { const side = 7, r = Math.hypot(a, side); return { raise: r, swing: (Math.atan2(a, side) / DEG) }; };+ const aL = arm(-A * c), aR = arm(A * c);+ const joints = { ...base.joints,+ pelvisTwist: -tw * c, spineTwist: tw * 1.7 * c, neckTwist: -tw * 0.6 * c, pelvisSide: 2.5 * Math.sin(2 * Math.PI * phase) * amp,+ shoulderRaiseL: aL.raise, shoulderSwingL: aL.swing, shoulderRaiseR: aR.raise, shoulderSwingR: aR.swing,+ elbowL: 14 + 16 * Math.max(0, -c), elbowR: 14 + 16 * Math.max(0, c), spineBend: (base.joints.spineBend ?? 0) + 3 * amp };+ const bob = (style.bob ?? 0.022) * amp;+ const root: V3 = at(plan.rootS(t), 0, base.root[1] - bob * (0.5 + 0.5 * s2) - 0.012 * amp);+ const pose = stand(d, { ...base, root, yaw, joints, plant: false }, feet, null, pitch, 1);+ return { pose, phase, amp };+};diff --git a/engine/src/canvas-core/character/identity.ts b/engine/src/canvas-core/character/identity.tsnew file mode 100644index 0000000..8bdff55--- /dev/null+++ b/engine/src/canvas-core/character/identity.ts@@ -0,0 +1,31 @@+// IDENTITY PER HAND. The character spec lists what makes her HER; each hand must still show it.+// Line hands draw the same Scene geometry, so their check is the Scene's (every feature part+// present and drawn). Grid hands (pixel, brick) RE-EXPRESS her, so their check is on the grid+// itself: enough cells of the right roles, the rims still rings, the eyes still dark, and the+// silhouette's IoU against the Scene sampled finer.+import type { Scene } from "./types";+import type { Grid } from "./render/grid";+import { gridIoU } from "./render/grid";++export type Check = { feature: string; ok: boolean; got: string };+export const sceneFeatures = (s: Scene, feats: { id: string; parts: string[] }[]): Check[] => {+ const drawn = new Set(s.parts.filter((p) => p.polys.length || p.marks.length).map((p) => p.id));+ return feats.map((f) => { const has = f.parts.filter((p) => drawn.has(p)); return { feature: f.id, ok: has.length > 0, got: has.join("+") || "none" }; });+};+// on a grid: count cells by role (body cells) and by mark role (features), relative to the figure+export const gridFeatures = (g: Grid, s: Scene): Check[] => {+ const body: Record<string, number> = {}, mk: Record<string, number> = {}; let fig = 0;+ g.cells.forEach((c) => { if (c.role) { fig++; body[c.role] = (body[c.role] ?? 0) + 1; } });+ const markCells = new Map<number, string>(); g.marks.forEach((m) => markCells.set(m.i, m.role)); markCells.forEach((r) => (mk[r] = (mk[r] ?? 0) + 1));+ const iou = gridIoU(s, g), pct = (n: number) => `${((100 * n) / (fig || 1)).toFixed(0)}%`;+ return [+ { feature: "glasses", ok: (mk.glasses ?? 0) >= 10, got: `${mk.glasses ?? 0} rim cells` },+ { feature: "eyes", ok: (mk.pupil ?? 0) >= 2, got: `${mk.pupil ?? 0} pupil cells` },+ { feature: "raincoat", ok: (body.coat ?? 0) / fig > 0.3, got: `coat ${pct(body.coat ?? 0)} of the figure` },+ { feature: "toggles", ok: (mk.toggle ?? 0) >= 2, got: `${mk.toggle ?? 0} toggle cells` },+ { feature: "satchel", ok: (body.satchel ?? 0) >= 12, got: `${body.satchel ?? 0} cells` },+ { feature: "fringe", ok: (body.hair ?? 0) / fig > 0.06, got: `hair ${pct(body.hair ?? 0)}` },+ { feature: "wellies", ok: (body.boots ?? 0) >= 12, got: `${body.boots ?? 0} cells` },+ { feature: "silhouette", ok: iou > 0.8, got: `IoU ${iou.toFixed(2)} vs the scene` },+ ];+};diff --git a/engine/src/canvas-core/character/math3.ts b/engine/src/canvas-core/character/math3.tsnew file mode 100644index 0000000..587c465--- /dev/null+++ b/engine/src/canvas-core/character/math3.ts@@ -0,0 +1,76 @@+// 3D MATH for characters. Vectors, rotation matrices, a pinhole camera with a REAL focal length,+// and the one 3D primitive everything is built from: an oriented ellipsoid ("blob").+//+// World frame: x to screen right, y up, z toward the camera for a front view. A character at+// yaw 0 faces +z. Its LEFT side is +x (facing us, her left hand is on our right).+// Pure functions only: no randomness, no clock.+import type { P } from "../core";++export type V3 = [number, number, number];+export type M3 = [number, number, number, number, number, number, number, number, number]; // row-major++export const DEG = Math.PI / 180;+export const v3 = (x = 0, y = 0, z = 0): V3 => [x, y, z];+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 len = (a: V3) => Math.hypot(a[0], a[1], a[2]);+export const norm = (a: V3): V3 => { const l = len(a) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };+export const mix3 = (a: V3, b: V3, t: number): V3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+export const dist = (a: V3, b: V3) => len(sub(a, b));++export const I3: M3 = [1, 0, 0, 0, 1, 0, 0, 0, 1];+export const mv = (m: M3, v: V3): V3 => [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];+export const mm = (a: M3, b: M3): M3 => {+ const o = new Array(9).fill(0) as M3;+ for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) o[r * 3 + c] = a[r * 3] * b[c] + a[r * 3 + 1] * b[3 + c] + a[r * 3 + 2] * b[6 + c];+ return o;+};+export const tr = (m: M3): M3 => [m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8]];+export const rx = (a: number): M3 => { const c = Math.cos(a), s = Math.sin(a); return [1, 0, 0, 0, c, -s, 0, s, c]; };+export const ry = (a: number): M3 => { const c = Math.cos(a), s = Math.sin(a); return [c, 0, s, 0, 1, 0, -s, 0, c]; };+export const rz = (a: number): M3 => { const c = Math.cos(a), s = Math.sin(a); return [c, -s, 0, s, c, 0, 0, 0, 1]; };+export const rotAxis = (axis: V3, a: number): M3 => {+ const [x, y, z] = norm(axis), c = Math.cos(a), s = Math.sin(a), t = 1 - c;+ return [t * x * x + c, t * x * y - s * z, t * x * z + s * y, t * x * y + s * z, t * y * y + c, t * y * z - s * x, t * x * z - s * y, t * y * z + s * x, t * z * z + c];+};+// columns of a rotation = where the local axes point in the parent frame+export const col = (m: M3, i: number): V3 => [m[i], m[3 + i], m[6 + i]];+export const fromCols = (a: V3, b: V3, c: V3): M3 => [a[0], b[0], c[0], a[1], b[1], c[1], a[2], b[2], c[2]];+export const MIRROR_X: M3 = [-1, 0, 0, 0, 1, 0, 0, 0, 1];++// A rigid frame: rotation R (local -> world) and origin p.+export type Frame = { R: M3; p: V3 };+export const apply = (f: Frame, local: V3): V3 => add(f.p, mv(f.R, local));++// ---------------------------------------------------------------- camera+// A pinhole camera. `f` is the focal length IN PIXELS: f = (sensor-px / sensor-mm) * lens-mm.+// A long lens far away (f large, eye far) is near-orthographic, right for a turnaround; a short+// lens close up is what makes a hand pointed at the viewer grow and the arm behind it shrink.+export type Camera = { eye: V3; right: V3; up: V3; fwd: V3; f: number; cx: number; cy: number };+export const camera = (eye: V3, target: V3, f: number, cx: number, cy: number, upHint: V3 = [0, 1, 0]): Camera => {+ const fwd = norm(sub(target, eye)), right = norm(cross(fwd, upHint)), up = cross(right, fwd);+ return { eye, right, up, fwd, f, cx, cy };+};+// focal length in px for a lens in mm on a 36 mm-wide full-frame sensor rendered `widthPx` wide+export const lensPx = (mm: number, widthPx: number) => (mm / 36) * widthPx;+export type Proj = { x: number; y: number; z: number; s: number }; // screen px, depth, px per world unit at that depth+export const project = (c: Camera, p: V3): Proj => {+ const d = sub(p, c.eye), z = Math.max(1e-4, dot(d, c.fwd)), s = c.f / z;+ return { x: c.cx + dot(d, c.right) * s, y: c.cy - dot(d, c.up) * s, z, s };+};+export const toCam = (c: Camera, v: V3): V3 => [dot(v, c.right), dot(v, c.up), dot(v, c.fwd)]; // a DIRECTION in camera axes+export const pt = (q: Proj): P => [q.x, q.y];++// ---------------------------------------------------------------- blobs+// An oriented ellipsoid: centre c, local axes = columns of R, radii r. Every body volume in the+// mannequin is one of these; limbs are chains of them, swept pairwise.+export type Blob = { c: V3; R: M3; r: V3 };+const LAT = 7, LON = 14;+const UNIT: V3[] = (() => { const o: V3[] = []; for (let i = 0; i <= LAT; i++) { const ph = -Math.PI / 2 + (i / LAT) * Math.PI; const n = i === 0 || i === LAT ? 1 : LON; for (let j = 0; j < n; j++) { const th = (j / n) * Math.PI * 2; o.push([Math.cos(ph) * Math.cos(th), Math.sin(ph), Math.cos(ph) * Math.sin(th)]); } } return o; })();+// surface samples, projected. The convex hull of these IS the ellipsoid's silhouette under+// perspective (to within the sampling), so foreshortening needs no special case.+export const blobPts = (cam: Camera, b: Blob): P[] => UNIT.map((u) => { const q = project(cam, add(b.c, mv(b.R, [u[0] * b.r[0], u[1] * b.r[1], u[2] * b.r[2]]))); return [q.x, q.y] as P; });+export const blobInFrame = (f: Frame, c: V3, r: V3, R: M3 = I3): Blob => ({ c: apply(f, c), R: mm(f.R, R), r });diff --git a/engine/src/canvas-core/character/render/brick.ts b/engine/src/canvas-core/character/render/brick.tsnew file mode 100644index 0000000..a5d64f8--- /dev/null+++ b/engine/src/canvas-core/character/render/brick.ts@@ -0,0 +1,48 @@+// TOY-BRICK HAND for any character Scene: the character BUILT, as a studs-out mosaic seen+// straight on. Every cell is a 1x1 plate in a real brick colour (a stud, a bevel catching the+// light, a hairline seam between plates); the shade side of each form is built in that colour's+// darker brick; the features are 1x1 ROUND TILES (smooth, no stud, a glossy highlight), so her+// round red glasses are a ring of red round tiles and her eyes are black round tiles.+import type { Env, Gfx } from "../../core";+import { shade } from "../../toyBrickKit";+import { insidePoly } from "../shape2d";+import type { Scene } from "../types";+import { type Grid, sampleScene } from "./grid";++export type BrickPalette = { base: string; baseStud: boolean; ground: string; roles: Record<string, [string, string]> };+export const brickGrid = (scene: Scene, W: number, H: number, cell: number): Grid => sampleScene(scene, 0, 0, cell, Math.floor(W / cell), Math.floor(H / cell), 1.6, true);++export const renderBrick = (g: Gfx, env: Env, scene: Scene, pal: BrickPalette, o: { cell: number; horizon: number }) => {+ const W = env.W, H = env.H, s = o.cell, gr = brickGrid(scene, W, H, s), { G, H: GH, cells } = gr, c = g.cur;+ // a builder places round tiles only for the face's features; a strap is built in its own colour; seams and stitching do not exist in bricks+ const FACE = new Set(["glasses", "pupil", "mouth", "blush", "lip"]), tile = new Map<number, string>(), plateCol = new Map<number, string>();+ gr.marks.forEach(({ i, role, part }) => { if (FACE.has(role) || (role === "line" && (part === "head" || part === "nose"))) tile.set(i, role === "line" ? "pupil" : role); else if (role !== "line" && role !== "white" && pal.roles[role]) plateCol.set(i, role); });+ const shadow = scene.ground?.shadow ?? [];+ const plate = (x: number, y: number, col: string, stud: boolean) => {+ c.fillStyle = shade(col, -0.5); c.fillRect(x, y, s, s); // the seam+ c.fillStyle = col; c.fillRect(x + 0.6, y + 0.6, s - 1.2, s - 1.2);+ c.fillStyle = shade(col, 0.28); c.fillRect(x + 0.6, y + 0.6, s - 1.2, 1.2); c.fillRect(x + 0.6, y + 0.6, 1.2, s - 1.2); // bevel, lit edges+ c.fillStyle = shade(col, -0.22); c.fillRect(x + 0.6, y + s - 1.8, s - 1.2, 1.2); c.fillRect(x + s - 1.8, y + 0.6, 1.2, s - 1.2);+ if (!stud) return;+ const cx = x + s / 2, cy = y + s / 2, r = s * 0.3;+ c.fillStyle = shade(col, -0.3); c.beginPath(); c.arc(cx + r * 0.18, cy + r * 0.2, r * 1.02, 0, Math.PI * 2); c.fill(); // the stud's shadow+ c.fillStyle = shade(col, 0.06); c.beginPath(); c.arc(cx, cy, r, 0, Math.PI * 2); c.fill();+ c.strokeStyle = shade(col, 0.45); c.lineWidth = Math.max(0.8, s * 0.06); c.beginPath(); c.arc(cx, cy, r * 0.72, Math.PI * 1.05, Math.PI * 1.6); c.stroke(); // the highlight+ };+ const round = (x: number, y: number, col: string) => {+ const cx = x + s / 2, cy = y + s / 2, r = s * 0.47;+ c.fillStyle = shade(col, -0.45); c.beginPath(); c.arc(cx + 0.5, cy + 0.6, r, 0, Math.PI * 2); c.fill();+ c.fillStyle = col; c.beginPath(); c.arc(cx, cy, r * 0.94, 0, Math.PI * 2); c.fill();+ c.fillStyle = "rgba(255,255,255,0.55)"; c.beginPath(); c.ellipse(cx - r * 0.3, cy - r * 0.35, r * 0.34, r * 0.2, -0.6, 0, Math.PI * 2); c.fill(); // gloss+ };+ g.touch(0, 0, W, H);+ for (let j = 0; j < GH; j++) for (let i = 0; i < G; i++) {+ const q = j * G + i, cl = cells[q], x = i * s, y = j * s;+ if (!cl.role) { const onGround = (j + 0.5) * s > o.horizon, sh = shadow.length > 2 && insidePoly(shadow, (i + 0.5) * s, (j + 0.5) * s); plate(x, y, onGround ? (sh ? shade(pal.ground, -0.25) : pal.ground) : pal.base, pal.baseStud || onGround); continue; }+ const ramp = pal.roles[cl.role] ?? ["#ff00ff", "#990099"], t = tile.get(q);+ if (t) { plate(x, y, cl.lit ? ramp[0] : ramp[1], false); round(x, y, (pal.roles[t] ?? ["#1b2a34"])[0]); continue; }+ const pc = plateCol.get(q); if (pc) { plate(x, y, pal.roles[pc][cl.lit ? 0 : 1], true); continue; }+ plate(x, y, cl.lit ? ramp[0] : ramp[1], true);+ }+ return gr;+};diff --git a/engine/src/canvas-core/character/render/grid.ts b/engine/src/canvas-core/character/render/grid.tsnew file mode 100644index 0000000..d578119--- /dev/null+++ b/engine/src/canvas-core/character/render/grid.ts@@ -0,0 +1,59 @@+// A SCENE ON A GRID. Pixel art and toy bricks do not draw a character's contour; they RE-EXPRESS+// the character in their own units. This samples a Scene at cell centres: which part is on top,+// its role, whether the cell is on the lit or the shade side of that form, and where the marks+// (eyes, glasses, mouth) fall, stamped at grid resolution so a small feature survives as cells.+import type { P } from "../../core";+import { insidePoly } from "../shape2d";+import type { Mark, Scene } from "../types";++export type Cell = { role: string | null; part: string | null; lit: boolean };+export type Grid = { G: number; H: number; x0: number; y0: number; cell: number; cells: Cell[]; marks: { i: number; role: string; part: string }[] };++const bb = (s: P[]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of s) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } return { x0, y0, x1, y1 }; };++export const sampleScene = (scene: Scene, x0: number, y0: number, cell: number, G: number, H: number, minRing = 2, sprite = false): Grid => {+ const L = scene.light, parts = scene.parts.filter((p) => p.fill !== false && p.polys.length);+ const boxes = parts.map((p) => p.polys.map(bb)), cells: Cell[] = [];+ for (let j = 0; j < H; j++) for (let i = 0; i < G; i++) {+ const x = x0 + (i + 0.5) * cell, y = y0 + (j + 0.5) * cell; let hit: Cell = { role: null, part: null, lit: true };+ for (let k = parts.length - 1; k >= 0; k--) {+ const p = parts[k], inn = p.polys.some((q, n) => { const b = boxes[k][n]; return x >= b.x0 && x <= b.x1 && y >= b.y0 && y <= b.y1 && insidePoly(q, x, y); });+ if (!inn) continue;+ const dx = -L[0] * p.size * 0.32, dy = -L[1] * p.size * 0.32, lit = p.polys.some((q) => insidePoly(q, x + dx, y + dy)); // the lit form, shifted toward the light, covers this cell+ hit = { role: p.role, part: p.id, lit }; break;+ }+ cells.push(hit);+ }+ // marks at grid resolution, in paint order (later parts' marks win)+ let cur = "";+ const marks: { i: number; role: string; part: string }[] = [], toCell = (p: P) => [Math.floor((p[0] - x0) / cell), Math.floor((p[1] - y0) / cell)] as [number, number];+ const put = (cx: number, cy: number, role: string) => { if (cx >= 0 && cy >= 0 && cx < G && cy < H) marks.push({ i: cy * G + cx, role, part: cur }); };+ const line = (a: P, b: P, role: string) => { let [x0g, y0g] = toCell(a); const [x1g, y1g] = toCell(b), dx = Math.abs(x1g - x0g), dy = -Math.abs(y1g - y0g), sx = x0g < x1g ? 1 : -1, sy = y0g < y1g ? 1 : -1; let e = dx + dy; for (let n = 0; n < 400; n++) { put(x0g, y0g, role); if (x0g === x1g && y0g === y1g) break; const e2 = 2 * e; if (e2 >= dy) { e += dy; x0g += sx; } if (e2 <= dx) { e += dx; y0g += sy; } } };+ // A signature ring (a lens rim) smaller than the grid can hold is EXAGGERATED, as a sprite artist+ // would: a midpoint circle of at least `minRing` cells round the ring's centre, never a smear.+ const ring = (cxp: number, cyp: number, rc: number, role: string) => {+ let x = Math.round(rc), y = 0, err = 1 - x; const [cx, cy] = toCell([cxp, cyp]);+ while (x >= y) { [[x, y], [y, x], [-y, x], [-x, y], [-x, -y], [-y, -x], [y, -x], [x, -y]].forEach(([a, b]) => put(cx + a, cy + b, role)); y++; if (err < 0) err += 2 * y + 1; else { x--; err += 2 * (y - x) + 1; } }+ };+ const stamp = (m: Mark) => {+ if (m.kind === "line") {+ if ((m.alpha ?? 1) < 0.45 || m.role === "white") return;+ // the sprite policy: at sprite size only what reads survives (rims, pupils, mouth, cheeks): no lids, brows or temple arms+ if (sprite && (m.role === "hair" || (cur === "head" && (m.alpha ?? 1) < 0.8) || cur === "temples")) return;+ const a = m.pts[0], z = m.pts[m.pts.length - 1], b = bb(m.pts), span = Math.max(b.x1 - b.x0, b.y1 - b.y0);+ if (m.pts.length > 12 && Math.hypot(a[0] - z[0], a[1] - z[1]) < span * 0.25 && span < cell * 6) { ring((b.x0 + b.x1) / 2, (b.y0 + b.y1) / 2, Math.max(minRing, span / 2 / cell), m.role); return; }+ for (let k = 1; k < m.pts.length; k++) line(m.pts[k - 1], m.pts[k], m.role);+ }+ else if (m.kind === "fill") { const b = bb(m.pts); let any = false; for (let cy = Math.floor((b.y0 - y0) / cell); cy <= Math.floor((b.y1 - y0) / cell); cy++) for (let cx = Math.floor((b.x0 - x0) / cell); cx <= Math.floor((b.x1 - x0) / cell); cx++) if (insidePoly(m.pts, x0 + (cx + 0.5) * cell, y0 + (cy + 0.5) * cell)) { put(cx, cy, m.role); any = true; } if (!any) { const c = toCell([(b.x0 + b.x1) / 2, (b.y0 + b.y1) / 2]); put(c[0], c[1], m.role); } }+ else { if (m.rx * 2 >= cell * 0.6 || m.role === "pupil") { const c = toCell(m.at); put(c[0], c[1], m.role); } }+ };+ scene.parts.forEach((p) => { cur = p.id; p.marks.forEach(stamp); });+ return { G, H, x0, y0, cell, cells, marks };+};+// how well the grid holds the silhouette: IoU of its figure cells against the scene sampled 4x finer+export const gridIoU = (scene: Scene, g: Grid): number => {+ const fine = sampleScene(scene, g.x0, g.y0, g.cell / 4, g.G * 4, g.H * 4);+ let inter = 0, uni = 0;+ for (let j = 0; j < g.H * 4; j++) for (let i = 0; i < g.G * 4; i++) { const a = !!fine.cells[j * g.G * 4 + i].role, b = !!g.cells[Math.floor(j / 4) * g.G + Math.floor(i / 4)].role; if (a && b) inter++; if (a || b) uni++; }+ return inter / (uni || 1);+};diff --git a/engine/src/canvas-core/character/render/marker.ts b/engine/src/canvas-core/character/render/marker.tsnew file mode 100644index 0000000..6fbac04--- /dev/null+++ b/engine/src/canvas-core/character/render/marker.ts@@ -0,0 +1,46 @@+// MARKER COMIC HAND for any character Scene: koi.ts's recipe. Flat cel colour; a HARD shadow+// (the shade colour, with the lit colour laid over it shifted toward the light and cut to the+// form, no softening); one confident brush-marker contour that swells on the side turned away+// from the light and tapers at its ends; marks inked, not pencilled. Same Scene, other marks.+import { Gfx, P } from "../../core";+import { ink } from "../../gallery";+import { bbox, signedArea, thin } from "../shape2d";+import type { Mark, Scene } from "../types";+import { type Palette, contourRuns, hashId } from "./storybook";++export const COMIC_INK = "#15122a";+const pathPolys = (c: CanvasRenderingContext2D, polys: P[][], dx = 0, dy = 0) => { c.beginPath(); polys.forEach((s) => { s.forEach(([x, y], i) => (i ? c.lineTo(x + dx, y + dy) : c.moveTo(x + dx, y + dy))); c.closePath(); }); };++const markInk = (g: Gfx, marks: Mark[], col: (r: string) => string, seed: number, light: P) => {+ marks.forEach((m, i) => {+ const c = g.cur;+ if (m.kind === "line") { if (m.pts.length > 1) ink(g, m.pts, m.role === "line" ? COMIC_INK : col(m.role), { w: m.w * 1.25, light, shadow: 0.3, taper: [0.2, 0.2], seed: seed + i, rough: 0.15 }, m.alpha ?? 1); }+ else if (m.kind === "fill") { const b = bbox([m.pts]); g.touch(b.x0 - 3, b.y0 - 3, b.x1 + 3, b.y1 + 3); c.globalAlpha = m.alpha ?? 1; c.fillStyle = col(m.role); pathPolys(c, [m.pts]); c.fill(); c.globalAlpha = 1; if (m.line) ink(g, [...m.pts, m.pts[0]], COMIC_INK, { w: m.line * 1.3, light, shadow: 0.4, taper: [0.02, 0.02], seed: seed + i + 50 }); }+ else { g.touch(m.at[0] - m.rx - 2, m.at[1] - m.ry - 2, m.at[0] + m.rx + 2, m.at[1] + m.ry + 2); c.globalAlpha = m.alpha ?? 1; c.fillStyle = col(m.role); c.beginPath(); c.ellipse(m.at[0], m.at[1], Math.max(0.3, m.rx), Math.max(0.3, m.ry), m.rot, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1; }+ });+};++export const renderMarker = (g: Gfx, scene: Scene, pal: Palette, o: { weight?: number } = {}) => {+ const byId = new Map(scene.parts.map((p) => [p.id, p])), L = scene.light, lightTo: P = [L[0], L[1]], sw = (r: string) => pal[r] ?? { base: "#ff00ff", shade: "#990099" };+ const col = (r: string) => (r === "line" ? COMIC_INK : sw(r).base);+ g.group("plain", () => {+ if (scene.ground?.shadow.length) { const c = g.cur, b = bbox([scene.ground.shadow]); g.touch(b.x0, b.y0, b.x1, b.y1); c.fillStyle = "rgba(21,18,42,0.28)"; pathPolys(c, [scene.ground.shadow]); c.fill(); }+ for (const part of scene.parts) {+ const s = sw(part.role), k = part.size, seed = hashId(part.id), c = g.cur;+ if (part.fill !== false && part.polys.length) {+ const b = bbox(part.polys); g.touch(b.x0 - 4, b.y0 - 4, b.x1 + 4, b.y1 + 4);+ c.fillStyle = s.shade; pathPolys(c, part.polys); c.fill("nonzero");+ c.save(); pathPolys(c, part.polys); c.clip("nonzero"); c.fillStyle = s.base; pathPolys(c, part.polys, L[0] * k * 0.34, L[1] * k * 0.34); c.fill("nonzero"); c.restore();+ }+ if (part.outline !== false) {+ const w = Math.max(1.6, Math.min(6.5, 1.2 + k * 0.1)) * (o.weight ?? 1);+ contourRuns(part, byId).forEach((run, i) => {+ const r = thin(run, Math.max(1, Math.round(run.length / 60)));+ // which side of this run is outside: the polygons were wound one way (ccw), so -1+ ink(g, r, COMIC_INK, { w, light: lightTo, shadow: 0.95, taper: [0.06, 0.06], seed: seed + i, side: signedArea(part.polys[0]) >= 0 ? -1 : 1, rough: 0.2, min: 0.3 });+ });+ }+ markInk(g, part.marks, col, seed + 700, lightTo);+ }+ });+};diff --git a/engine/src/canvas-core/character/render/pencil.ts b/engine/src/canvas-core/character/render/pencil.tsnew file mode 100644index 0000000..8789a11--- /dev/null+++ b/engine/src/canvas-core/character/render/pencil.ts@@ -0,0 +1,59 @@+// COLOURED-PENCIL HAND for any character Scene (colouredPencil.ts's recipe, through its kit). A+// sheet of passes: a light lay-in, a local-colour pass hatched on one diagonal per form, a shade+// pass cross-hatched in the shadow colour on the side turned from the light, darks pressed hard,+// and a contour in dark pencil as a chain of overlapping strokes. Every pass is bitten by the+// paper's tooth (wax only lands on the ridges), so the cream shows through the colour.+import { type Env, type Gfx, type P, sample } from "../../core";+import { limb } from "../../pixelArtKit";+import { Sheet, contour, dot, hatch, layLine, minus, poly, union, type Mark, type Region } from "../../colouredPencilKit";+import { runLength } from "../shape2d";+import type { Scene } from "../types";+import type { Palette } from "./storybook";+import { contourRuns, hashId, occlude, occluders } from "./storybook";++const PAPER = "#f4eddc", LEAD = "#3a2f3d";+const fillMark = (c: CanvasRenderingContext2D, m: Mark) => { c.globalAlpha = m.a; c.fillStyle = m.col; c.beginPath(); c.moveTo(m.poly[0], m.poly[1]); for (let i = 2; i < m.poly.length; i += 2) c.lineTo(m.poly[i], m.poly[i + 1]); c.closePath(); c.fill(); };++export const pencilSheet = (scene: Scene, pal: Palette, o: { horizon: number; W: number; ground?: string } = { horizon: 0, W: 0 }) => {+ const S = new Sheet(), L = scene.light, byId = new Map(scene.parts.map((p) => [p.id, p])), covOf = new Map(scene.parts.map((p, i) => [p.id, occluders(scene, i)]));+ S.pass("ground", 0);+ if (o.ground) hatch(S, poly([[0, o.horizon], [o.W, o.horizon], [o.W, o.horizon + 400], [0, o.horizon + 400]]), { ang: -0.12, gap: 4.5, len: 60, w: 1.4, col: o.ground, a: 0.35, seed: 3, dens: (_x, y) => Math.max(0, 1 - (y - o.horizon) / 380) });+ if (scene.ground?.shadow.length) hatch(S, poly(scene.ground.shadow), { ang: -0.2, gap: 2.4, len: 30, w: 1.5, col: "#7a6a86", a: 0.55, seed: 5 });+ S.pass("layin", 0); S.pass("local", 1); S.pass("shade", 1); S.pass("dark", 2); S.pass("line", 2);+ // the gesture first: long, light, running lines through the pose, overshooting their ends the way a lay-in does+ S.into("layin"); (scene.gesture ?? []).forEach((pl, gi) => pl.forEach((pt, i) => { if (i) layLine(S, pl[i - 1], pt, "#9a8f9e", 300 + gi * 31 + i, 1.1, 0.5); }));+ // what is covered later is not coloured twice: each part's region minus the regions painted over it+ const regs = scene.parts.map((p) => (p.fill === false || !p.polys.length ? null : union(...p.polys.map((q) => poly(q)))));+ scene.parts.forEach((part, i) => {+ const reg0 = regs[i]; if (!reg0) return;+ const above = regs.slice(i + 1).filter((r): r is Region => !!r), reg = above.length ? minus(reg0, ...above) : reg0, sw = pal[part.role]; if (!sw) return;+ const seed = hashId(part.id), k = part.size, shifted = union(...part.polys.map((q) => poly(q.map(([x, y]) => [x + L[0] * k * 0.32, y + L[1] * k * 0.32] as P))));+ const shadeReg = minus(reg, shifted), ang = -0.95 + ((seed % 7) - 3) * 0.04;+ // local colour in TWO layers at crossing angles, pressed firmly: wax on the tooth needs layering to read as colour+ S.into("local"); hatch(S, reg, { ang, gap: Math.max(1.4, Math.min(2.6, k * 0.055)), len: Math.max(10, Math.min(34, k * 0.8)), w: 1.7, col: sw.base, a: 0.92, seed }); hatch(S, reg, { ang: ang + 0.35, gap: Math.max(1.8, Math.min(3.2, k * 0.07)), len: Math.max(10, Math.min(30, k * 0.7)), w: 1.6, col: sw.base, a: 0.7, seed: seed + 5 });+ S.into("shade"); hatch(S, shadeReg, { ang: ang + 0.75, gap: Math.max(1.6, Math.min(3, k * 0.06)), len: Math.max(8, Math.min(26, k * 0.6)), w: 1.4, col: sw.shade, a: 0.6, seed: seed + 1 });+ S.into("dark"); hatch(S, shadeReg, { ang: ang + 1.5, gap: 5, len: 12, w: 1.2, col: sw.shade, a: 0.35, seed: seed + 2, dens: () => 0.6 });+ });+ scene.parts.forEach((part) => {+ const seed = hashId(part.id), k = part.size;+ S.into("layin"); if (part.outline !== false) contourRuns(part, byId, 3).forEach((run, i) => { if (runLength(run) > 8) contour(S, run.map(([x, y]) => [x + 1.5, y - 1] as P), { w: 0.9, col: "#8a8090", a: 0.35, seed: seed + 90 + i, seg: 90 }); });+ S.into("line"); if (part.outline !== false) contourRuns(part, byId, 2).flatMap((r) => occlude(r, covOf.get(part.id)!)).forEach((run, i) => { if (runLength(run) > 4) contour(S, run, { w: Math.max(1.3, Math.min(2.8, 1.1 + k * 0.035)), col: LEAD, a: 0.95, seed: seed + i, seg: 50 }); });+ part.marks.forEach((m, i) => {+ if (m.kind === "line" && m.w > 4 && m.role !== "line") occlude(m.pts, covOf.get(part.id)!).forEach((pts, j) => { const band = limb(sample(pts, false, 4) as [number, number][], m.w / 2, m.w / 2) as P[]; hatch(S, poly(band), { ang: 0.4, gap: 1.2, len: 10, w: 1.3, col: pal[m.role]?.base ?? LEAD, a: 0.9, seed: seed + 70 + i + j }); contour(S, band, { w: 0.9, col: pal[m.role]?.shade ?? LEAD, a: 0.7, seed: seed + 80 + i + j, seg: 40, closed: true }); }); // a strap is a BAND: hatched, edged, never a string of tapered strokes+ else if (m.kind === "line" && m.role !== "white" && (m.alpha ?? 1) > 0.25) occlude(m.pts, covOf.get(part.id)!).forEach((pts) => contour(S, pts, { w: Math.max(0.9, m.w * 0.9), col: m.role === "line" ? LEAD : (pal[m.role]?.shade ?? LEAD), a: 0.85 * (m.alpha ?? 1), seed: seed + 40 + i, seg: 30, smooth: pts.length > 2 }));+ else if (m.kind === "fill") hatch(S, poly(m.pts), { ang: 0.6, gap: 1.1, len: 8, w: 1.3, col: m.role === "white" ? "#fffdf6" : (pal[m.role]?.base ?? LEAD), a: 0.9 * (m.alpha ?? 1), seed: seed + 60 + i, over: 0.2 });+ else if (m.kind === "dot" && m.role !== "white") dot(S, m.at[0], m.at[1], Math.max(0.8, Math.min(m.rx, m.ry)), pal[m.role]?.base ?? LEAD, 0.8 * (m.alpha ?? 1), 1.2);+ });+ });+ return S;+};++export const renderPencil = (g: Gfx, env: Env, scene: Scene, pal: Palette, o: { horizon: number; ground?: string; only?: string[] }) => {+ const W = env.W, H = env.H, S = pencilSheet(scene, pal, { horizon: o.horizon, W, ground: o.ground });+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); c.fillStyle = PAPER; c.fillRect(0, 0, W, H); });+ for (const p of S.passes.filter((q) => !o.only || o.only.includes(q.id))) g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); p.marks.forEach((m) => fillMark(c, m)); c.globalAlpha = 1; }, { textures: [p.tooth === 2 ? "draftTooth" : "pencilTooth"] });+ // highlights lifted out with an eraser: the eye glints, back to paper+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); for (const part of scene.parts) for (const m of part.marks) if (m.kind === "dot" && m.role === "white") { c.fillStyle = "#fffaf0"; c.beginPath(); c.ellipse(m.at[0], m.at[1], m.rx, m.ry, 0, 0, Math.PI * 2); c.fill(); } });+ g.paper("paper", 0.1);+ return S;+};diff --git a/engine/src/canvas-core/character/render/pixel.ts b/engine/src/canvas-core/character/render/pixel.tsnew file mode 100644index 0000000..fbd78e1--- /dev/null+++ b/engine/src/canvas-core/character/render/pixel.ts@@ -0,0 +1,41 @@+// PIXEL-ART HAND for any character Scene (pixelArt.ts's recipe). The character is re-expressed+// as a sprite: a limited palette, each role a two-step ramp (lit, shade) chosen by which side of+// the form a cell sits on, a dark silhouette outline, a shade-coloured inner line where one part+// overlaps another, and the features (eyes, glasses, mouth) stamped as single pixels so they+// survive at sprite size. Painted as whole cells: every device pixel is exactly one palette colour.+import type { Env, Gfx } from "../../core";+import { insidePoly } from "../shape2d";+import type { Scene } from "../types";+import { type Grid, sampleScene } from "./grid";++export type PixelPalette = { bg: string; ground: string; groundShadow: string; outline: string; roles: Record<string, [string, string]> };++export const pixelGrid = (scene: Scene, W: number, H: number, cell: number): Grid => sampleScene(scene, 0, 0, cell, Math.floor(W / cell), Math.floor(H / cell), 2, true);++export const renderPixel = (g: Gfx, env: Env, scene: Scene, pal: PixelPalette, o: { cell: number; horizon: number }) => {+ const W = env.W, H = env.H, cell = o.cell, gr = pixelGrid(scene, W, H, cell), { G, H: GH, cells } = gr, c = g.cur, k = env.scale;+ const colOf = new Array<string>(G * GH);+ const shadow = scene.ground?.shadow ?? [];+ for (let j = 0; j < GH; j++) for (let i = 0; i < G; i++) {+ const q = j * G + i, cl = cells[q], x = (i + 0.5) * cell, y = (j + 0.5) * cell;+ if (!cl.role) { colOf[q] = y > o.horizon ? (shadow.length > 2 && insidePoly(shadow, x, y) ? pal.groundShadow : pal.ground) : pal.bg; continue; }+ const ramp = pal.roles[cl.role] ?? ["#ff00ff", "#990099"]; colOf[q] = cl.lit ? ramp[0] : ramp[1];+ }+ // outline: a figure cell touching the ground or sky; inner line: a cell whose right or lower neighbour is another part+ for (let j = 0; j < GH; j++) for (let i = 0; i < G; i++) {+ const q = j * G + i, cl = cells[q]; if (!cl.role) continue;+ const nb = [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]].map(([a, b]) => (a < 0 || b < 0 || a >= G || b >= GH ? null : cells[b * G + a]));+ if (nb.some((n) => !n || !n.role)) { colOf[q] = pal.outline; continue; }+ const r = nb[1], d = nb[3];+ if ((r && r.part !== cl.part && r.role !== cl.role) || (d && d.part !== cl.part && d.role !== cl.role)) colOf[q] = (pal.roles[cl.role] ?? ["", pal.outline])[1] === colOf[q] ? pal.outline : (pal.roles[cl.role] ?? ["", pal.outline])[1];+ }+ // features last, in paint order+ gr.marks.forEach(({ i, role }) => { const r = pal.roles[role]; colOf[i] = role === "line" ? pal.outline : r ? r[0] : pal.outline; });+ // paint whole cells, one fillRect per run of a colour+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.imageSmoothingEnabled = false; c.globalAlpha = 1; c.globalCompositeOperation = "source-over";+ const cd = Math.round(cell * k);+ for (let j = 0; j < GH; j++) { let i = 0; while (i < G) { const col = colOf[j * G + i]; let e = i + 1; while (e < G && colOf[j * G + e] === col) e++; c.fillStyle = col; c.fillRect(i * cd, j * cd, (e - i) * cd, cd); i = e; } }+ c.restore();+ g.touch(0, 0, W, H);+ return gr;+};diff --git a/engine/src/canvas-core/character/render/riso.ts b/engine/src/canvas-core/character/render/riso.tsnew file mode 100644index 0000000..966c3ce--- /dev/null+++ b/engine/src/canvas-core/character/render/riso.ts@@ -0,0 +1,66 @@+// RISOGRAPH HAND for any character Scene: lighthouse.ts / print.ts's recipe. Three drums+// (yellow, fluorescent pink, blue), each its own layer, each overprinted by multiply through its+// own registration offset and eaten by pinholes and mottle. A palette ROLE is a recipe of drums+// and tones (the coat is yellow at 100%; skin is pink 20% over yellow 28%); tone is a halftone+// screen at that drum's angle; the shadow side is a second screen of the role's shade ink. Every+// part KNOCKS OUT what is under it on every drum before it prints, so occlusion is real paper,+// not overprint soup. The line is blue litho crayon, on the blue drum.+import { type Env, Gfx, type P, halftone } from "../../core";+import { bbox, runLength, thin } from "../shape2d";+import type { Mark, Scene } from "../types";+import { contourRuns, hashId } from "./storybook";++export type RisoRecipe = { inks: [string, number][]; shadeInk?: string; shadeTone?: number };+export const DRUM = { yellow: { col: "#ffd400", ang: 28, off: [-4.5, 3.5] as P }, pink: { col: "#ff48b0", ang: 62, off: [4.5, -3] as P }, blue: { col: "#0078bf", ang: 12, off: [0, 0] as P } } as const;+type DrumName = keyof typeof DRUM;+const NAMES: DrumName[] = ["yellow", "pink", "blue"];+const pathPolys = (c: CanvasRenderingContext2D, polys: P[][], dx = 0, dy = 0) => { c.beginPath(); polys.forEach((s) => { s.forEach(([x, y], i) => (i ? c.lineTo(x + dx, y + dy) : c.moveTo(x + dx, y + dy))); c.closePath(); }); };++export const renderRiso = (g: Gfx, env: Env, scene: Scene, recipes: Record<string, RisoRecipe>, o: { pitch?: number; lineW?: number; before?: (d: Record<DrumName, CanvasRenderingContext2D>) => void } = {}) => {+ const pitch = o.pitch ?? 6.5, byId = new Map(scene.parts.map((p) => [p.id, p])), L = scene.light, W = Math.round(env.W * env.scale), H = Math.round(env.H * env.scale);+ // one persistent surface per drum, reused across frames+ const drums = {} as Record<DrumName, CanvasRenderingContext2D>; let shadeL: CanvasRenderingContext2D;+ NAMES.forEach((n) => { const key = `riso:${n}:${W}x${H}`; let l = env.cache.get(key) as { ctx: CanvasRenderingContext2D } | undefined; if (!l) { l = env.canvas(W, H) as unknown as { ctx: CanvasRenderingContext2D }; env.cache.set(key, l); } l.ctx.setTransform(1, 0, 0, 1, 0, 0); l.ctx.globalCompositeOperation = "source-over"; l.ctx.globalAlpha = 1; l.ctx.clearRect(0, 0, W, H); l.ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); drums[n] = l.ctx; });+ { const key = `riso:shade:${W}x${H}`; let l = env.cache.get(key) as { ctx: CanvasRenderingContext2D } | undefined; if (!l) { l = env.canvas(W, H) as unknown as { ctx: CanvasRenderingContext2D }; env.cache.set(key, l); } shadeL = l.ctx; }+ o.before?.(drums);+ const screen = (c: CanvasRenderingContext2D, polys: P[][], drum: DrumName, tone: number) => {+ if (tone >= 0.96) { c.fillStyle = "#000"; pathPolys(c, polys); c.fill("nonzero"); return; }+ const b = bbox(polys); c.save(); pathPolys(c, polys); c.clip("nonzero"); c.fillStyle = "#000"; c.beginPath();+ halftone(b, pitch, DRUM[drum].ang, () => tone).forEach(([x, y, r]) => { c.moveTo(x + r, y); c.arc(x, y, r, 0, Math.PI * 2); }); c.fill(); c.restore();+ };+ const knock = (polys: P[][]) => NAMES.forEach((n) => { const c = drums[n]; c.globalCompositeOperation = "destination-out"; c.fillStyle = "#000"; pathPolys(c, polys); c.fill("nonzero"); c.globalCompositeOperation = "source-over"; });+ const recipe = (r: string): RisoRecipe => recipes[r] ?? { inks: [["blue", 0.5]] };+ const darkest = (r: string): DrumName => { const rc = recipe(r).inks; return (rc.find(([n]) => n === "blue")?.[0] ?? rc[0]?.[0] ?? "blue") as DrumName; };+ const markOn = (m: Mark, seed: number) => {+ if (m.kind === "line") { if (m.role === "white") { knock([[...m.pts]]); return; } const on: [DrumName, number][] = m.role === "line" ? [["blue", 1]] : recipe(m.role).inks.filter(([, t]) => t >= 0.1).map(([n, t]) => [n as DrumName, Math.min(1, t * 1.15)]); const prev = g.cur; (on.length ? on : [[darkest(m.role), 1] as [DrumName, number]]).forEach(([n, t], k) => { g.cur = drums[n]; g.pen(m.pts, { w: m.w * 1.1, color: "#000", seed: seed + k, wobble: 0.4, boil: 0.2, retrace: false, opacity: t, closed: m.closed }); }); g.cur = prev; return; } // a coloured line prints on every drum its colour is made of+ const pts = m.kind === "fill" ? m.pts : Array.from({ length: 12 }, (_, i) => [m.at[0] + Math.cos((i / 12) * Math.PI * 2) * m.rx, m.at[1] + Math.sin((i / 12) * Math.PI * 2) * m.ry] as P);+ knock([pts]);+ if (m.role !== "white") recipe(m.role).inks.forEach(([n, t]) => screen(drums[n as DrumName], [pts], n as DrumName, Math.min(1, t * (m.alpha ?? 1) + (m.kind === "fill" && m.role === "pupil" ? 1 : 0))));+ if (m.kind === "fill" && m.line) { const prev = g.cur; g.cur = drums.blue; g.pen(pts, { w: m.line, color: "#000", seed, wobble: 0.3, closed: true, retrace: false }); g.cur = prev; }+ };+ if (scene.ground?.shadow.length) screen(drums.blue, [scene.ground.shadow], "blue", 0.35);+ for (const part of scene.parts) {+ const seed = hashId(part.id), rc = recipe(part.role), k = part.size;+ if (part.fill !== false && part.polys.length) {+ knock(part.polys);+ rc.inks.forEach(([n, t]) => screen(drums[n as DrumName], part.polys, n as DrumName, t));+ if (rc.shadeInk) { // the shadow side: a screen, minus the lit form shifted toward the light+ const b = bbox(part.polys), sc = shadeL; sc.setTransform(env.scale, 0, 0, env.scale, 0, 0); sc.clearRect(b.x0 - 10, b.y0 - 10, b.x1 - b.x0 + 20, b.y1 - b.y0 + 20);+ screen(sc, part.polys, rc.shadeInk as DrumName, rc.shadeTone ?? 0.4);+ sc.globalCompositeOperation = "destination-out"; sc.fillStyle = "#000"; pathPolys(sc, part.polys, L[0] * k * 0.4, L[1] * k * 0.4); sc.fill("nonzero"); sc.globalCompositeOperation = "source-over";+ const d = drums[rc.shadeInk as DrumName]; d.save(); d.setTransform(1, 0, 0, 1, 0, 0); const x0 = Math.max(0, Math.floor((b.x0 - 10) * env.scale)), y0 = Math.max(0, Math.floor((b.y0 - 10) * env.scale)), w = Math.min(W - x0, Math.ceil((b.x1 - b.x0 + 20) * env.scale)), h = Math.min(H - y0, Math.ceil((b.y1 - b.y0 + 20) * env.scale)); if (w > 0 && h > 0) d.drawImage(sc.canvas as CanvasImageSource, x0, y0, w, h, x0, y0, w, h); d.restore();+ }+ }+ if (part.outline !== false) { const prev = g.cur; g.cur = drums.blue; const w = Math.max(1.3, Math.min(4.2, 0.9 + k * 0.06)) * (o.lineW ?? 1); contourRuns(part, byId).forEach((run, i) => { if (runLength(run) > 3) g.pen(thin(run, Math.max(2, Math.round(run.length / 26))), { w, color: "#000", seed: seed + i * 7, wobble: 0.5, boil: 0.2, taper: 0.9, retrace: false, opacity: 1 }); }); g.cur = prev; }+ part.marks.forEach((m, i) => markOn(m, seed + 300 + i));+ }+ // print: each drum in its ink, multiplied through its own registration offset+ NAMES.forEach((n) => {+ g.group("plain", () => {+ const c = g.cur; g.touch(0, 0, env.W, env.H);+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0);+ c.drawImage(drums[n].canvas as CanvasImageSource, 0, 0);+ c.globalCompositeOperation = "source-in"; c.fillStyle = DRUM[n].col; c.fillRect(0, 0, W, H); c.restore();+ }, { blend: "multiply", off: DRUM[n].off, textures: ["risoSpeck", "risoMottle"] });+ });+};diff --git a/engine/src/canvas-core/character/render/scratch.ts b/engine/src/canvas-core/character/render/scratch.tsnew file mode 100644index 0000000..afbc7e6--- /dev/null+++ b/engine/src/canvas-core/character/render/scratch.ts@@ -0,0 +1,65 @@+// SCRATCHBOARD HAND for any character Scene (scratchboard.ts's recipe, tinted). A black board;+// each form is SCRAPED to white clay in lines that cross its long axis (cross-contour), twice as+// close on the side the light reaches; the contour is where the scraping stops, so the outline is+// a black gap, never a drawn line; features are left black or scraped white. Then the tinted+// scratchboard step: transparent colour laid over the scraped white of each role (on black it+// cannot show), which keeps her palette in a monochrome medium.+import { type Env, type Gfx, type P, rng } from "../../core";+import { hatchRuns } from "../../gallery";+import { bbox, insidePoly } from "../shape2d";+import type { Scene } from "../types";+import { contourRuns, hashId } from "./storybook";++const BOARD = "#141214", CLAY = "#f3efe6";+const path = (c: CanvasRenderingContext2D, polys: P[][], dx = 0, dy = 0) => { c.beginPath(); polys.forEach((s) => { s.forEach(([x, y], i) => (i ? c.lineTo(x + dx, y + dy) : c.moveTo(x + dx, y + dy))); c.closePath(); }); };+// the long axis of a set of points (principal direction)+const axis = (pts: P[]) => { let mx = 0, my = 0; pts.forEach(([x, y]) => { mx += x; my += y; }); mx /= pts.length; my /= pts.length; let a = 0, b = 0, d = 0; pts.forEach(([x, y]) => { a += (x - mx) ** 2; b += (x - mx) * (y - my); d += (y - my) ** 2; }); return 0.5 * Math.atan2(2 * b, a - d); };++export const renderScratch = (g: Gfx, env: Env, scene: Scene, tint: Record<string, string>, o: { horizon: number }) => {+ const W = env.W, H = env.H, L = scene.light, byId = new Map(scene.parts.map((p) => [p.id, p]));+ g.group("plain", () => {+ const c = g.cur; g.touch(0, 0, W, H); c.fillStyle = BOARD; c.fillRect(0, 0, W, H);+ c.strokeStyle = CLAY; c.lineCap = "round";+ // the ground: long sparse horizontal scrapes, closer toward us; a few stars+ const r = rng(7);+ for (let y = o.horizon; y < H; y += 5 + (H - y) * 0.03) { c.globalAlpha = 0.55; c.lineWidth = 0.9; c.beginPath(); let x = r() * 30; while (x < W) { const l = 30 + r() * 120; c.moveTo(x, y + (r() - 0.5) * 2); c.lineTo(x + l, y + (r() - 0.5) * 2); x += l + 6 + r() * 40; } c.stroke(); }+ for (let i = 0; i < 60; i++) { c.globalAlpha = 0.4 + r() * 0.5; c.lineWidth = 1 + r(); const x = r() * W, y = r() * o.horizon * 0.8; c.beginPath(); c.moveTo(x - 2, y); c.lineTo(x + 2, y); c.moveTo(x, y - 2); c.lineTo(x, y + 2); c.stroke(); }+ c.globalAlpha = 1;+ if (scene.ground?.shadow.length) { c.fillStyle = BOARD; path(c, [scene.ground.shadow]); c.fill(); }+ for (const part of scene.parts) {+ if (part.fill === false || !part.polys.length) continue;+ const seed = hashId(part.id), b = bbox(part.polys), k = part.size, ang = axis(part.polys.flat()) + Math.PI / 2 + 0.12;+ c.fillStyle = BOARD; path(c, part.polys); c.fill("nonzero"); // what is under it is covered+ const inside = (x: number, y: number) => part.polys.some((q) => insidePoly(q, x, y));+ const lit = (x: number, y: number) => part.polys.some((q) => insidePoly(q, x - L[0] * k * 0.35, y - L[1] * k * 0.35));+ const pale = part.role === "skin" || part.role === "nail" ? 0.42 : part.role === "coat" ? 0.62 : 1, gap = Math.max(2.2, Math.min(5.5, k * 0.1)) * pale, light = tint[part.role] ? 1 : 0.6;+ c.lineWidth = Math.max(0.7, gap * 0.34); c.globalAlpha = light;+ // pass 1 everywhere; pass 2 in between, only where the light reaches: tone is line spacing+ // each line BOWS across the form (a cross-contour on a cylinder), the bow along the form's long axis+ const ax = Math.cos(ang - Math.PI / 2), ay = Math.sin(ang - Math.PI / 2), sg = ay >= 0 ? 1 : -1;+ c.save(); path(c, part.polys); c.clip("nonzero");+ [0, 1].forEach((pass) => { const off = pass * gap, nx = -Math.sin(ang) * off, ny = Math.cos(ang) * off; c.beginPath(); hatchRuns(b, ang, gap * 2, (x, y) => inside(x + nx, y + ny) && (pass === 0 || lit(x + nx, y + ny)), 2, seed + pass * 7).forEach((run) => { const a = run[0], z = run[run.length - 1], len = Math.hypot(z[0] - a[0], z[1] - a[1]), bow = len * 0.16 * sg; c.moveTo(a[0] + nx, a[1] + ny); c.quadraticCurveTo((a[0] + z[0]) / 2 + nx + ax * bow, (a[1] + z[1]) / 2 + ny + ay * bow, z[0] + nx, z[1] + ny); }); c.stroke(); });+ c.restore();+ c.globalAlpha = 1;+ // the contour: scraping stops short of the edge, leaving a black gap+ c.strokeStyle = BOARD; c.lineWidth = Math.max(1.6, Math.min(4, 1.2 + k * 0.05));+ if (part.outline !== false) contourRuns(part, byId, 2).forEach((run) => { c.beginPath(); run.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke(); });+ c.strokeStyle = CLAY;+ // features+ for (const m of part.marks) {+ if (m.kind === "fill") { c.fillStyle = m.role === "pupil" || m.role === "mouth" ? BOARD : CLAY; path(c, [m.pts]); c.fill(); if (m.line) { c.strokeStyle = BOARD; c.lineWidth = m.line; path(c, [m.pts]); c.stroke(); c.strokeStyle = CLAY; } } // coloured fills are scraped white and take their tint; only pupils and the mouth stay board+ else if (m.kind === "line" && (m.alpha ?? 1) > 0.3) { c.strokeStyle = m.role === "glasses" || m.role === "white" ? CLAY : BOARD; c.lineWidth = Math.max(1, m.w * (m.role === "glasses" ? 1.2 : 0.9)); c.beginPath(); m.pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke(); c.strokeStyle = CLAY; }+ else if (m.kind === "dot") { c.fillStyle = m.role === "white" ? CLAY : m.role === "blush" ? "rgba(243,239,230,0.35)" : BOARD; c.beginPath(); c.ellipse(m.at[0], m.at[1], m.rx, m.ry, 0, 0, Math.PI * 2); c.fill(); }+ }+ }+ });+ // the tint: transparent colour over each role's region (multiply: it only shows on the scraped white)+ g.group("plain", () => {+ const c = g.cur; g.touch(0, 0, W, H);+ for (const part of scene.parts) {+ const t = tint[part.role];+ if (t && part.fill !== false && part.polys.length) { c.fillStyle = t; path(c, part.polys); c.fill("nonzero"); }+ for (const m of part.marks) if (m.kind === "line" && m.role === "glasses" && tint.glasses) { c.strokeStyle = tint.glasses; c.lineWidth = m.w * 1.6; c.beginPath(); m.pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke(); }+ }+ }, { blend: "multiply" });+};diff --git a/engine/src/canvas-core/character/render/storybook.ts b/engine/src/canvas-core/character/render/storybook.tsnew file mode 100644index 0000000..d80cc05--- /dev/null+++ b/engine/src/canvas-core/character/render/storybook.ts@@ -0,0 +1,70 @@+// STORYBOOK HAND (pencil + watercolour) for any character Scene. Per part, in paint order:+// a wash in the role's shadow colour, the lit colour laid over it shifted TOWARD the light and+// clipped to the form (so a band of shadow survives on the far side, softened by the paint+// layer), then graphite along the union contour, heavier where the part is bigger, then the+// part's own marks (eyes, mouth, seams of clothing). The same recipe as storybook.ts's Bit.+import { GRAPHITE, Gfx, P, displace, rng } from "../../core";+import { bbox, insidePoly, runLength, thin, unionRuns } from "../shape2d";+import type { Mark, Part, Scene } from "../types";++export type Swatch = { base: string; shade: string; line?: string };+export type Palette = Record<string, Swatch>;+export const hashId = (s: string) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return (h >>> 0) % 100000; };++const pathPolys = (c: CanvasRenderingContext2D, polys: P[][], dx = 0, dy = 0) => { c.beginPath(); polys.forEach((s) => s.forEach(([x, y], i) => (i ? c.lineTo(x + dx, y + dy) : c.moveTo(x + dx, y + dy)))); polys.forEach(() => c.closePath()); };++// contour runs, minus seams where a part grows out of its parent+export const contourRuns = (part: Part, byId: Map<string, Part>, step = 1.5): P[][] => {+ const seams = (part.seams ?? []).map((s) => ({ ...s, polys: byId.get(s.with)?.polys ?? [] })).filter((s) => s.polys.length);+ const seamHide = (p: P) => seams.some((s) => Math.hypot(p[0] - s.at[0], p[1] - s.at[1]) < s.r && s.polys.some((q) => insidePoly(q, p[0], p[1])));+ const hide = seams.length || part.keepLine ? (p: P) => (part.keepLine ? !part.keepLine(p) : false) || seamHide(p) : undefined;+ return unionRuns(part.polys, step, hide).filter((r) => runLength(r) > 2.5);+};++// Hands that lay ALL their lines in one late pass (a key block, a brush pass, a pencil line pass)+// must cut each line where a later-painted part covers it, or hidden edges show through.+type Cover = { q: P[]; b: { x0: number; y0: number; x1: number; y1: number } }[];+export const occluders = (scene: Scene, idx: number): Cover => scene.parts.slice(idx + 1).filter((p) => p.fill !== false && p.polys.length).flatMap((p) => p.polys.map((q) => ({ q, b: bbox([q]) })));+export const occlude = (pts: P[], cover: Cover): P[][] => {+ const out: P[][] = []; let cur: P[] = [];+ pts.forEach((p) => { if (cover.some(({ q, b }) => p[0] >= b.x0 && p[0] <= b.x1 && p[1] >= b.y0 && p[1] <= b.y1 && insidePoly(q, p[0], p[1]))) { if (cur.length > 1) out.push(cur); cur = []; } else cur.push(p); });+ if (cur.length > 1) out.push(cur);+ return out;+};++export const inkWeight =(part: Part, k = 1) => Math.max(1.1, Math.min(4.2, 0.9 + part.size * 0.055)) * k;++export const drawMarks = (g: Gfx, marks: Mark[], col: (role: string) => string, seed: number, penW = 1) => {+ marks.forEach((m, i) => {+ const c = g.cur;+ if (m.kind === "line") g.pen(m.pts, { w: m.w * penW, color: col(m.role), seed: seed + i * 7, wobble: Math.min(0.5, m.w * 0.2), boil: 0.25, opacity: m.alpha ?? 0.92, retrace: false, closed: m.closed, taper: 0.8 });+ else if (m.kind === "fill") { g.fill(m.pts, col(m.role), m.alpha ?? 1); if (m.line) g.pen(m.pts, { w: m.line * penW, color: GRAPHITE, seed: seed + i * 7 + 1, wobble: 0.3, boil: 0.2, closed: true, retrace: false, taper: 0.4 }); }+ else { g.touch(m.at[0] - m.rx - 2, m.at[1] - m.ry - 2, m.at[0] + m.rx + 2, m.at[1] + m.ry + 2); c.globalAlpha = m.alpha ?? 1; c.fillStyle = col(m.role); c.beginPath(); c.ellipse(m.at[0], m.at[1], Math.max(0.3, m.rx), Math.max(0.3, m.ry), m.rot, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1; }+ });+};++export const renderStorybook = (g: Gfx, scene: Scene, pal: Palette, o: { weight?: number; paintAlpha?: number } = {}) => {+ const byId = new Map(scene.parts.map((p) => [p.id, p])), L = scene.light, sw = (r: string) => pal[r] ?? { base: "#ff00ff", shade: "#990099" };+ const col = (r: string) => (r === "line" ? GRAPHITE : sw(r).base);+ if (scene.ground?.shadow.length) g.group("paint", () => g.wash(scene.ground!.shadow, "#7d6fa8", { alpha: 0.32, seed: 8, dx: 0, dy: 0, shrink: 1, rim: false }));+ for (const part of scene.parts) {+ const seed = hashId(part.id), s = sw(part.role), k = part.size, clipPolys = part.clipTo ? byId.get(part.clipTo)?.polys : undefined;+ const clipped = (fn: () => void) => { if (!clipPolys?.length) return fn(); const c = g.cur; c.save(); pathPolys(c, clipPolys); c.clip("nonzero"); fn(); c.restore(); };+ if (part.fill !== false && part.polys.length) {+ const wet = Math.min(3.2, 0.6 + k * 0.05), polys = part.polys.map((q, i) => displace(q, wet, 0.03, 2, seed + i));+ g.group("paint", () => {+ clipped(() => { const c = g.cur, b = bbox(polys); g.touch(b.x0 - 6, b.y0 - 6, b.x1 + 6, b.y1 + 6);+ c.globalAlpha = o.paintAlpha ?? 0.97; c.fillStyle = s.shade; pathPolys(c, polys); c.fill("nonzero");+ c.save(); pathPolys(c, polys); c.clip("nonzero"); c.fillStyle = s.base; pathPolys(c, polys, L[0] * k * 0.28, L[1] * k * 0.28); c.fill("nonzero");+ c.restore(); c.globalAlpha = 1; });+ });+ }+ g.group("ink", () => clipped(() => {+ if (part.outline !== false) {+ const w = inkWeight(part, o.weight ?? 1), r = rng(seed);+ contourRuns(part, byId).forEach((run, i) => { const every = Math.max(2, Math.round(run.length / 26)); g.pen(thin(run, every), { w, color: s.line ?? GRAPHITE, seed: seed + i * 13 + Math.floor(r() * 9), wobble: Math.min(1, 0.2 + k * 0.012), boil: 0.3, taper: 0.7, opacity: 0.95 }); });+ }+ drawMarks(g, part.marks, col, seed + 500, 1);+ }));+ }+};diff --git a/engine/src/canvas-core/character/render/sumi.ts b/engine/src/canvas-core/character/render/sumi.tsnew file mode 100644index 0000000..77e5f28--- /dev/null+++ b/engine/src/canvas-core/character/render/sumi.ts@@ -0,0 +1,56 @@+// SUMI-E HAND for any character Scene (sumiE.ts's recipe, with light colour: the Chinese+// "ink and light colour" tradition). Pale colour washes laid first, soft, bleeding a little into+// the xuan paper; then the contour as BRUSH strokes: one loaded brush of real hairs per stroke,+// pressing in, running dry, lifting (sumiEKit.brush); the hair is one wet mass of scorched ink; the+// features are fine brush lines; the glasses in vermilion, the one strong colour; a red seal.+import { type Env, type Gfx, type P, rng } from "../../core";+import { brush, INK_BLACK, JIAO, NONG, ZHONG, DAN } from "../../sumiEKit";+import { runLength, thin } from "../shape2d";+import type { Scene } from "../types";+import { contourRuns, hashId, occlude, occluders } from "./storybook";+import { mix } from "../../gallery";++const XUAN = "#f1eadb", CINNABAR = "#c8412c";+const path = (c: CanvasRenderingContext2D, polys: P[][]) => { c.beginPath(); polys.forEach((s) => { s.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }); };++export const renderSumi = (g: Gfx, env: Env, scene: Scene, wash: Record<string, [string, number]>, o: { horizon: number; inkRoles?: string[] }) => {+ const W = env.W, H = env.H, byId = new Map(scene.parts.map((p) => [p.id, p])), inkRoles = new Set(o.inkRoles ?? ["hair"]), covOf = new Map(scene.parts.map((p, i) => [p.id, occluders(scene, i)]));+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); c.fillStyle = XUAN; c.fillRect(0, 0, W, H); });+ // the ground: three dry, broken horizontal strokes of pale ink+ const r = rng(3);+ [0, 1, 2].forEach((i) => brush(g, { ctrl: [[W * (0.08 + r() * 0.1), o.horizon + 30 + i * 26], [W * 0.5, o.horizon + 26 + i * 26 + (r() - 0.5) * 6], [W * (0.84 + r() * 0.1), o.horizon + 32 + i * 26]], w: 16 - i * 3, press: [[0, 0.3], [0.2, 0.9], [0.8, 0.7], [1, 0.1]], ink: DAN - i * 0.06, dry: 0.9, split: 0.9, bleed: 0.2, streak: true, seed: 900 + i }));+ // colour first, pale and soft. A painter leaves paper where a near form covers a far one, so each+ // wash is laid OPAQUE as that colour thinned into the paper (never multiplied over what is behind)+ g.group("plain", () => {+ const c = g.cur; g.touch(0, 0, W, H);+ for (const part of scene.parts) {+ if (part.fill === false || !part.polys.length) continue;+ if (inkRoles.has(part.role)) { c.globalAlpha = 1; c.fillStyle = mix("#f1eadb", INK_BLACK, 0.9); path(c, part.polys); c.fill("nonzero"); continue; }+ const w = wash[part.role]; c.globalAlpha = 1; c.fillStyle = w ? mix("#f1eadb", w[0], w[1]) : "#f1eadb"; path(c, part.polys); c.fill("nonzero");+ }+ c.globalAlpha = 1;+ }, { blend: "multiply", blur: 1.4 });+ // the brush: every contour run a stroke, heavier on the big masses, lighter ink on small ones+ for (const part of scene.parts) {+ const seed = hashId(part.id), k = part.size;+ if (part.outline !== false && !inkRoles.has(part.role)) contourRuns(part, byId, 2).flatMap((r) => occlude(r, covOf.get(part.id)!)).forEach((run, i) => {+ if (runLength(run) < 6) return;+ brush(g, { ctrl: thin(run, Math.max(2, Math.round(run.length / 9))), w: Math.max(2.2, Math.min(7.5, 1.4 + k * 0.1)), press: [[0, 0.25], [0.12, 0.95], [0.7, 0.75], [1, 0.12]], ink: k > 40 ? NONG : ZHONG, load: 0.95, dry: 0.35, split: 0.6, bleed: 0.35, slow: [[0.02, 0.6]], seed: seed + i * 3 });+ });+ part.marks.forEach((m, i) => {+ if (m.kind === "line" && m.role !== "white" && (m.alpha ?? 1) > 0.3) occlude(m.pts, covOf.get(part.id)!).forEach((pts) => brush(g, { ctrl: pts.length > 2 ? pts : [pts[0], [(pts[0][0] + pts[1][0]) / 2, (pts[0][1] + pts[1][1]) / 2], pts[1]], w: Math.max(1.2, m.w * 1.1), press: [[0, 0.4], [0.3, 1], [1, 0.3]], ink: m.role === "glasses" ? JIAO : m.role === "hair" ? JIAO : ZHONG, dry: 0.1, bleed: 0.15, hairs: 10, seed: seed + 60 + i }));+ });+ // the glasses and the pupils again in colour over the ink: vermilion rims, scorched-ink pupils+ g.group("plain", () => {+ const c = g.cur; g.touch(0, 0, W, H);+ part.marks.forEach((m) => {+ if (m.kind === "line" && m.role === "glasses") { c.strokeStyle = CINNABAR; c.lineWidth = m.w * 1.3; c.lineCap = "round"; c.beginPath(); m.pts.forEach(([x, y], j) => (j ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke(); }+ if (m.kind === "fill" && (m.role === "pupil" || m.role === "mouth")) { c.fillStyle = INK_BLACK; c.globalAlpha = 0.9; path(c, [m.pts]); c.fill(); c.globalAlpha = 1; }+ if (m.kind === "dot" && m.role === "white") { c.fillStyle = XUAN; c.beginPath(); c.ellipse(m.at[0], m.at[1], m.rx, m.ry, 0, 0, Math.PI * 2); c.fill(); }+ if (m.kind === "dot" && m.role === "blush") { c.fillStyle = "#e0897e"; c.globalAlpha = 0.35; c.beginPath(); c.ellipse(m.at[0], m.at[1], m.rx, m.ry, 0, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1; }+ });+ });+ }+ // the seal, lower right: a vermilion square with a white cut character+ g.group("plain", () => { const c = g.cur, x = W - 110, y = H - 150; g.touch(x - 4, y - 4, x + 64, y + 64); c.fillStyle = CINNABAR; c.globalAlpha = 0.88; c.fillRect(x, y, 56, 56); c.globalAlpha = 1; c.strokeStyle = XUAN; c.lineWidth = 4; c.lineCap = "square"; c.beginPath(); c.moveTo(x + 12, y + 16); c.lineTo(x + 44, y + 16); c.moveTo(x + 28, y + 16); c.lineTo(x + 28, y + 44); c.moveTo(x + 14, y + 44); c.lineTo(x + 42, y + 44); c.moveTo(x + 14, y + 30); c.lineTo(x + 42, y + 30); c.stroke(); }, { blend: "multiply" });+};diff --git a/engine/src/canvas-core/character/render/woodcut.ts b/engine/src/canvas-core/character/render/woodcut.tsnew file mode 100644index 0000000..47d610a--- /dev/null+++ b/engine/src/canvas-core/character/render/woodcut.ts@@ -0,0 +1,50 @@+// WOODCUT HAND (ukiyo-e colour woodblock, woodcut.ts's recipe) for any character Scene. Washi+// paper; one colour block per role, printed flat and multiplied, the plank's grain knocking the+// pigment thin in streaks; a bokashi wipe in the sky; last, the KEY BLOCK: every contour and+// every feature line as the knife leaves it (two cuts either side of a ridge, a stepped width,+// chisel ends), in sumi black. No shading gradients on the figure: ukiyo-e states form with line.+import type { Env, Gfx, P } from "../../core";+import { bokashi, carved, fillAll, grain, washi } from "../../woodcutKit";+import { runLength, thin } from "../shape2d";+import type { Scene } from "../types";+import { contourRuns, hashId, occlude, occluders } from "./storybook";++export const SUMI = "#1d1916";+export type WoodPalette = Record<string, string>;++export const renderWoodcut = (g: Gfx, env: Env, scene: Scene, pal: WoodPalette, o: { horizon: number; sky: string; ground: string }) => {+ const W = env.W, H = env.H, byId = new Map(scene.parts.map((p) => [p.id, p])), covOf = new Map(scene.parts.map((p, i) => [p.id, occluders(scene, i)]));+ // the sheet+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.drawImage(washi(env).canvas as CanvasImageSource, 0, 0); c.restore(); });+ // sky bokashi, ground block+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); bokashi(c, 0, W, 0, o.horizon * 0.55, o.sky, 41); c.fillStyle = o.ground; c.fillRect(0, o.horizon, W, H - o.horizon); grain(c, env, 0.35, [13, 7]); }, { blend: "multiply" });+ // the carver cleared the sky and ground blocks where the figure stands: back to bare paper there+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); c.save(); c.beginPath(); for (const p of scene.parts) if (p.fill !== false) for (const q of p.polys) { q.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); } c.clip("nonzero"); c.setTransform(1, 0, 0, 1, 0, 0); c.drawImage(washi(env).canvas as CanvasImageSource, 0, 0); c.restore(); });+ // colour blocks, part by part in paint order (each a flat print; later prints cover earlier)+ g.group("plain", () => {+ const c = g.cur; g.touch(0, 0, W, H);+ if (scene.ground?.shadow.length) { c.globalAlpha = 0.35; fillAll(c, [scene.ground.shadow], "#6b5a4a"); c.globalAlpha = 1; }+ for (const part of scene.parts) {+ if (part.fill === false || !part.polys.length) continue;+ fillAll(c, part.polys, pal[part.role] ?? "#ff00ff");+ for (const m of part.marks) if (m.kind === "fill" && m.role !== "pupil") { c.globalAlpha = m.alpha ?? 1; fillAll(c, [m.pts], pal[m.role] ?? SUMI); c.globalAlpha = 1; }+ }+ grain(c, env, 0.3, [37, 19], 0.04);+ }, { blend: "multiply", alpha: 0.96 });+ // the key block: knife lines, black+ g.group("plain", () => {+ const c = g.cur; g.touch(0, 0, W, H); const cuts: P[][] = [], red: P[][] = []; // red: a detail that is its own colour block (her glasses), cut as the knife cuts, printed in vermilion+ for (const part of scene.parts) {+ const seed = hashId(part.id), w = Math.max(2.2, Math.min(5.2, 1.8 + part.size * 0.07));+ if (part.outline !== false) contourRuns(part, byId, 2).flatMap((r) => occlude(r, covOf.get(part.id)!)).forEach((run, i) => { if (runLength(run) > 4) cuts.push(carved(thin(run, 3), w, seed + i)); });+ part.marks.forEach((m, i) => {+ if (m.kind === "line" && m.role !== "white" && (m.alpha ?? 1) > 0.3) occlude(m.pts, covOf.get(part.id)!).forEach((pts, j) => (m.role === "glasses" ? red : cuts).push(carved(pts, Math.max(1.1, m.w * (m.role === "glasses" ? 1.25 : 0.9)), seed + 50 + i + j * 97, { tail: 0.7 })));+ if (m.kind === "fill" && m.role === "pupil") cuts.push(m.pts);+ if (m.kind === "dot" && m.role !== "white" && m.role !== "blush") cuts.push(Array.from({ length: 8 }, (_, k) => [m.at[0] + Math.cos(k * 0.785) * m.rx, m.at[1] + Math.sin(k * 0.785) * m.ry] as P));+ });+ }+ fillAll(c, cuts.filter((q) => q.length > 2), SUMI); fillAll(c, red.filter((q) => q.length > 2), pal.glasses ?? "#cf3b2a");+ // the highlights are uncut wood: bare paper left inside the pupils+ for (const part of scene.parts) for (const m of part.marks) if (m.kind === "dot" && m.role === "white") { c.fillStyle = "#efe6d1"; c.beginPath(); c.ellipse(m.at[0], m.at[1], m.rx, m.ry, 0, 0, Math.PI * 2); c.fill(); }+ }, { alpha: 0.95 });+};diff --git a/engine/src/canvas-core/character/shape2d.ts b/engine/src/canvas-core/character/shape2d.tsnew file mode 100644index 0000000..9c80dba--- /dev/null+++ b/engine/src/canvas-core/character/shape2d.ts@@ -0,0 +1,63 @@+// 2D SHAPE OPS for characters: convex hull, point-in-polygon, and the one that matters most,+// UNION CONTOURS. A body part is a union of convex polygons (a limb is a chain of swept blob+// pairs). Its outline is every boundary point of every polygon that is NOT inside another+// polygon of the same part, so the elbow of one arm has no seam, while a forearm crossing in+// front of its own upper arm (a separate part) still gets its overlap line.+import type { P } from "../core";++export const hull = (pts: P[]): P[] => {+ const s = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]);+ if (s.length < 3) return s;+ const x = (o: P, a: P, b: P) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);+ const lo: P[] = [], hi: P[] = [];+ for (const p of s) { while (lo.length >= 2 && x(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 (hi.length >= 2 && x(hi[hi.length - 2], hi[hi.length - 1], p) <= 0) hi.pop(); hi.push(p); }+ return [...lo.slice(0, -1), ...hi.slice(0, -1)];+};+export const signedArea = (s: P[]) => s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2;+// every polygon in a union must wind the same way, or nonzero filling punches holes+export const ccw = (s: P[]): P[] => (signedArea(s) < 0 ? [...s].reverse() : s);+export const insidePoly = (pts: P[], x: number, y: number) => { let k = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[i], b = pts[j]; if (a[1] > y !== b[1] > y && x < ((b[0] - a[0]) * (y - a[1])) / (b[1] - a[1]) + a[0]) k = !k; } return k; };+const segDist = (p: P, a: P, b: P) => { const dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy || 1, t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2)); return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy); };+export const edgeDist = (poly: P[], p: P) => { let d = 1e9; for (let i = 0; i < poly.length; i++) d = Math.min(d, segDist(p, poly[i], poly[(i + 1) % poly.length])); return d; };+export const bbox = (polys: P[][]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const s of polys) for (const [x, y] of s) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } return { x0, y0, x1, y1 }; };+export const centroid = (s: P[]): P => { let x = 0, y = 0; s.forEach((p) => { x += p[0]; y += p[1]; }); return [x / s.length, y / s.length]; };++// walk a closed polygon at `step` px+export const densifyClosed = (s: P[], step: number): P[] => {+ const out: P[] = [];+ for (let i = 0; i < s.length; i++) { const a = s[i], b = s[(i + 1) % s.length], n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step)); for (let k = 0; k < n; k++) out.push([a[0] + ((b[0] - a[0]) * k) / n, a[1] + ((b[1] - a[1]) * k) / n]); }+ return out;+};++// The outline of a union, as open runs. `hide(p)` removes extra points (seams where a part+// joins its parent). Coincident edges are kept once: the lower-index polygon owns them.+export const unionRuns = (polys: P[][], step: number, hide?: (p: P) => boolean, eps = 0.8): P[][] => {+ const runs: P[][] = [];+ const bbs = polys.map((s) => bbox([s]));+ polys.forEach((poly, i) => {+ if (poly.length < 3) return;+ const d = densifyClosed(poly, step), keep = d.map((p) => {+ if (hide && hide(p)) return false;+ for (let j = 0; j < polys.length; j++) {+ if (j === i || polys[j].length < 3) continue; const b = bbs[j];+ if (p[0] < b.x0 - eps || p[0] > b.x1 + eps || p[1] < b.y0 - eps || p[1] > b.y1 + eps) continue;+ const inn = insidePoly(polys[j], p[0], p[1]), e = edgeDist(polys[j], p);+ if (inn && e > eps) return false; // buried inside a sibling+ if (e <= eps && j < i) return false; // shared edge: the lower index draws it+ }+ return true;+ });+ const n = d.length; if (!n) return;+ if (keep.every(Boolean)) { runs.push([...d, d[0]]); return; }+ // rotate so we start on a hidden point, then collect kept stretches+ const s0 = keep.findIndex((k) => !k); let cur: P[] = [];+ for (let k = 1; k <= n; k++) { const i2 = (s0 + k) % n; if (keep[i2]) cur.push(d[i2]); else { if (cur.length > 1) runs.push(cur); cur = []; } }+ if (cur.length > 1) runs.push(cur);+ });+ return runs;+};++// thin a dense run for a pen that splines its own control points+export const thin = (s: P[], every: number): P[] => { if (s.length <= 3) return s; const o = s.filter((_, i) => i % every === 0); if (o[o.length - 1] !== s[s.length - 1]) o.push(s[s.length - 1]); return o; };+export const runLength = (s: P[]) => s.reduce((a, p, i) => (i ? a + Math.hypot(p[0] - s[i - 1][0], p[1] - s[i - 1][1]) : 0), 0);diff --git a/engine/src/canvas-core/character/types.ts b/engine/src/canvas-core/character/types.tsnew file mode 100644index 0000000..d7779df--- /dev/null+++ b/engine/src/canvas-core/character/types.ts@@ -0,0 +1,48 @@+// THE CHARACTER CONTRACT. A character is ONE module: rig, drawn views, palette roles, canon,+// distinguishing features, and toScene(pose). Shots pose characters; they never redraw them.+// A Scene is what every hand (storybook, marker comic, riso ...) renders with its own marks.+import type { P } from "../core";+import type { Camera, V3 } from "./math3";++// A pose. Angles in DEGREES, named anatomically (see human/skeleton.ts for every joint and its+// range of motion). `hands` names a pose from the hand library or gives its joint angles.+export type HandPose = string | Record<string, number> | { angles: Record<string, [number, number, number, number]> }; // a library name, a blend {fist: 0.5, point: 0.5}, or raw angles+export type Pose = {+ root: V3; // pelvis centre, world metres; y is height above the floor+ yaw: number; pitch?: number; roll?: number; // body orientation: yaw 0 faces the camera axis (+z), +yaw turns to her left+ joints: Record<string, number>;+ expression: Record<string, number>;+ hands?: { L?: HandPose; R?: HandPose };+ plant?: boolean; // drop the root so the lowest foot touches y = 0+ aux?: Record<string, number>; // secondary motion a character defines for itself (a bag swinging on its strap)+};++export type Role = string;+export type Mark =+ | { kind: "line"; pts: P[]; role: Role; w: number; closed?: boolean; alpha?: number; tag?: string }+ | { kind: "fill"; pts: P[]; role: Role; alpha?: number; line?: number; tag?: string }+ | { kind: "dot"; at: P; rx: number; ry: number; rot: number; role: Role; alpha?: number };++export type Part = {+ id: string; role: Role; depth: number;+ polys: P[][]; // union of convex-ish polygons, screen px+ size: number; // typical radius in px: mark weight is scaled from it+ seams?: { at: P; r: number; with: string }[];+ marks: Mark[]; // drawn with the part, after its fill+ outline?: boolean; fill?: boolean;+ feature?: string; // a distinguishing feature this part carries+ over?: string[]; // parts this one must paint over whatever the depth says (clothing over body)+ keepLine?: (p: P) => boolean; // draw only these contour points (a nose draws its far edge, never a ring)+ clipTo?: string; // paint and ink only inside another part (a neckline is cut INTO the shirt)+};+export type Scene = { parts: Part[]; light: P; ground: { y: number; shadow: P[] } | null; px: number; meta: Record<string, string | number>; gesture?: P[][] }; // gesture: the construction curves the drawing layer was built on (a hand may lay them in first)++export type RoleSpec = { family: string; hue: [number, number]; note: string }; // hue range in degrees the role must stay in, in every hand+export type Feature = { id: string; parts: string[]; note: string; visible: (viewYaw: number) => boolean };+export type Character = {+ id: string; name: string; version: string; canonId: string; description: string;+ roles: Record<Role, RoleSpec>;+ features: Feature[];+ pose: (p: Pose) => Pose; // validates against joint limits; throws at load+ toScene: (p: Pose, cam: Camera, o?: { t?: number }) => Scene;+};diff --git a/engine/src/canvas-core/character/view25d.ts b/engine/src/canvas-core/character/view25d.tsnew file mode 100644index 0000000..86638c5--- /dev/null+++ b/engine/src/canvas-core/character/view25d.ts@@ -0,0 +1,40 @@+// 2.5D CARTOON PARTS (Rivers, Igarashi & Durand, "2.5D Cartoon Models", SIGGRAPH 2010).+// A part that a volume cannot describe well (a fringe, a cowlick, a hood's opening) is DRAWN by+// hand in a few views, each a 2D polygon with the SAME number of points in the same order, and+// hung on a 3D anchor. The view angle picks the two nearest drawings and blends them point for+// point; negative yaw mirrors. So the part turns with the head, and every in-between is a blend+// of two drawings someone authored, never a squash of one.+import type { P } from "../core";+import { Camera, Frame, V3, apply, project, toCam, col } from "./math3";++export type Views = { yaw: number[]; shapes: P[][] }; // yaw ascending, 0..180; shapes in anchor units, x right, y DOWN+export const checkViews = (id: string, v: Views) => {+ const n = v.shapes[0].length;+ v.shapes.forEach((s, i) => { if (s.length !== n) throw new Error(`2.5D part '${id}': view ${v.yaw[i]} has ${s.length} points, view ${v.yaw[0]} has ${n}; every view must correspond point for point`); });+ if (v.yaw.length !== v.shapes.length) throw new Error(`2.5D part '${id}': ${v.yaw.length} angles for ${v.shapes.length} shapes`);+};++// the anchor's frame as the camera sees it: which way it faces (yaw, pitch) and its roll on screen+export const viewOf = (cam: Camera, f: Frame) => {+ const fwd = toCam(cam, col(f.R, 2)), up = toCam(cam, col(f.R, 1));+ const yaw = (Math.atan2(fwd[0], -fwd[2]) * 180) / Math.PI; // +: faces screen right+ const pitch = (Math.asin(Math.max(-1, Math.min(1, fwd[1]))) * 180) / Math.PI; // +: faces up+ const roll = Math.atan2(up[0], up[1]); // screen tilt of the head's up axis+ return { yaw, pitch, roll };+};++export const blendViews = (v: Views, yawDeg: number): P[] => {+ const mirror = yawDeg < 0, a = Math.min(Math.abs(yawDeg), v.yaw[v.yaw.length - 1]);+ let i = 0; while (i < v.yaw.length - 2 && a > v.yaw[i + 1]) i++;+ const t = Math.max(0, Math.min(1, (a - v.yaw[i]) / (v.yaw[i + 1] - v.yaw[i] || 1))), s = t * t * (3 - 2 * t); // ease so the held drawings dominate+ const A = v.shapes[i], B = v.shapes[i + 1] ?? A;+ return A.map((p, k) => [(mirror ? -1 : 1) * (p[0] + (B[k][0] - p[0]) * s), p[1] + (B[k][1] - p[1]) * s]);+};++// place a blended drawing on screen: anchor point in the frame, unit = `unit` metres+export const place25d = (cam: Camera, f: Frame, anchor: V3, unit: number, v: Views, o: { pitchShift?: number } = {}): { pts: P[]; yaw: number; px: number } => {+ const vw = viewOf(cam, f), q = project(cam, apply(f, anchor)), k = q.s * unit, c = Math.cos(vw.roll), s = Math.sin(vw.roll);+ const dy = -(o.pitchShift ?? 0) * Math.sin((vw.pitch * Math.PI) / 180), sy = Math.cos((vw.pitch * Math.PI) / 180) * 0.25 + 0.75;+ const pts = blendViews(v, vw.yaw).map(([x, y]) => { const X = x * k, Y = (y * sy + dy) * k; return [q.x + X * c - Y * s, q.y + X * s + Y * c] as P; });+ return { pts, yaw: vw.yaw, px: k };+};diff --git a/engine/src/canvas-core/characters/mira/drawn.ts b/engine/src/canvas-core/characters/mira/drawn.tsnew file mode 100644index 0000000..879aa7c--- /dev/null+++ b/engine/src/canvas-core/characters/mira/drawn.ts@@ -0,0 +1,54 @@+// MIRA, DRAWN. Her coat, sleeves, legs and wellies as DESIGNED masses: an authored cross-section+// table swept along the gesture curve through her joints. The rig only says where the curve goes;+// the shape is these numbers, placed by hand (head units: lateral, medial, front, back).+//+// Shape language: the raincoat is a trapezoid (narrow shoulders, straight sides, a hem that kicks+// out), the one big shape; sleeves are soft straight tubes with a cuff that bells; the legs are+// thin and straight in front with the calf swelling behind; the wellies are stiff cylinders,+// wider at the top, on a rounded toe. Big (coat), medium (boots, sleeves), small (hands, glasses).+import type { Camera, V3 } from "../../character/math3";+import { apply, mix3, mv, project } from "../../character/math3";+import { type Section, type Station, jointed, station, stationU, sweep } from "../../character/design";+import type { Part } from "../../character/types";+import { type Rig, type Side, SIDES, sgn } from "../../character/human/skeleton";++// ---- the coat: hem (0) to collar (1)+const COAT: Section[] = [+ [0.0, 0.66, 0.66, 0.5, 0.5], [0.18, 0.57, 0.57, 0.43, 0.43], [0.38, 0.5, 0.5, 0.37, 0.39], [0.5, 0.46, 0.46, 0.36, 0.36],+ [0.62, 0.47, 0.47, 0.36, 0.34], [0.84, 0.5, 0.5, 0.33, 0.3], [0.93, 0.5, 0.5, 0.29, 0.28], [0.97, 0.3, 0.3, 0.22, 0.22], [1.0, 0.19, 0.19, 0.17, 0.17],+];+// ---- a sleeve: shoulder (0) to wrist (1); the deltoid rounds the lateral side, the cuff bells+const SLEEVE: Section[] = [[0, 0.09, 0.08, 0.1, 0.1], [0.1, 0.17, 0.14, 0.17, 0.16], [0.25, 0.165, 0.15, 0.17, 0.16], [0.5, 0.14, 0.135, 0.145, 0.15], [0.8, 0.125, 0.12, 0.125, 0.125], [0.94, 0.14, 0.14, 0.14, 0.14], [1, 0.14, 0.14, 0.14, 0.14]];+// ---- a leg in tights: hip (0) to ankle (1): the knee notches, the calf swells high at the back, the shin runs straight+const LEG: Section[] = [[0, 0.22, 0.2, 0.22, 0.24], [0.28, 0.19, 0.17, 0.19, 0.2], [0.44, 0.14, 0.13, 0.155, 0.13], [0.5, 0.13, 0.125, 0.15, 0.12], [0.6, 0.14, 0.13, 0.12, 0.165], [0.72, 0.125, 0.12, 0.11, 0.14], [0.9, 0.095, 0.09, 0.09, 0.09], [1, 0.08, 0.08, 0.08, 0.08]];+// ---- a welly: shaft top (0) down to the ankle (1), then the foot from heel (0) to toe (1)+const SHAFT: Section[] = [[0, 0.165, 0.165, 0.165, 0.165], [0.15, 0.155, 0.155, 0.155, 0.155], [0.75, 0.12, 0.12, 0.12, 0.125], [1, 0.12, 0.12, 0.12, 0.12]];+const FOOT: Section[] = [[0, 0.085, 0.085, 0.085, 0.085], [0.35, 0.1, 0.1, 0.085, 0.085], [0.75, 0.105, 0.105, 0.065, 0.065], [1, 0.075, 0.075, 0.045, 0.045]]; // top and sole kept equal: along the foot "front" has no meaning++const part = (id: string, role: string, polys: ReturnType<typeof sweep>, cam: Camera, at: V3, bias: number, o: Partial<Part> = {}): Part => {+ const q = project(cam, at); return { id, role, depth: q.z + bias, polys, size: q.s * 0.12, marks: [], ...o };+};++export const drawnMira = (r: Rig, cam: Camera): Part[] => {+ const hh = r.dims.hh, out: Part[] = [];+ // the coat's gesture: from the hem (hung between the knees) up the spine to the collar+ const knees = mix3(r.joints.kneeL, r.joints.kneeR, 0.5), hips = mix3(r.joints.hipL, r.joints.hipR, 0.5), hem = mix3(hips, knees, 0.6);+ const coatSt: Station[] = [{ at: hem, frame: r.pelvis }, station(r.pelvis), station(r.lumbar), station(r.chest), station(r.chest, [0, 0.78 * hh, 0]), station(r.chest, [0, 0.9 * hh, -0.02 * hh])];+ out.push(part("coat", "coat", sweep(cam, coatSt, COAT, { hh, side: 1, n: 12, caps: [true, false] }), cam, r.joints.lumbar, 0, { over: ["legL", "legR"] }));+ for (const s of SIDES) {+ const k = sgn(s) as 1 | -1;+ // sleeve: shoulder, elbow, wrist; cut at the elbow so a bent arm folds, never self-crosses+ const sl: Station[] = [station(r.upper[s], [-k * 0.02 * hh, -0.04 * hh, 0]), station(r.fore[s]), station(r.hand[s], [0, 0.02 * hh, 0])];+ out.push(part("sleeve" + s, "coat", jointed(cam, sl, SLEEVE, { hh, side: k, n: 10, cuts: [stationU(sl, 1)] }), cam, r.joints["elbow" + s], -0.06 * hh, { seams: [{ at: pt(cam, r.joints["shoulder" + s]), r: 0.22 * hh * project(cam, r.joints["shoulder" + s]).s, with: "coat" }] }));+ // leg: hip, knee, ankle+ const lg: Station[] = [station(r.thigh[s]), station(r.shin[s]), station(r.foot[s])];+ out.push(part("leg" + s, "tights", jointed(cam, lg, LEG, { hh, side: k, n: 10, cuts: [stationU(lg, 1)] }), cam, r.joints["knee" + s], -0.02 * hh));+ // welly: the shaft from mid-shin to the ankle, and the foot from heel to toe, one part+ const sh: Station[] = [station(r.shin[s], [0, -0.52 * r.dims.shin, 0]), station(r.foot[s], [0, 0.02 * hh, 0])];+ const ft: Station[] = [station(r.foot[s], [0, -0.13 * hh, -0.1 * hh]), station(r.foot[s], [0, -0.14 * hh, 0.14 * hh]), station(r.toes[s], [0, -0.02 * hh, 0.1 * hh])];+ out.push(part("boot" + s, "boots", [...sweep(cam, sh, SHAFT, { hh, side: k, n: 8, caps: [true, false] }), ...sweep(cam, ft, FOOT, { hh, side: k, n: 8 })], cam, apply(r.foot[s], [0, 0, 0.05 * hh]), -0.025 * hh, { over: ["leg" + s], feature: "wellies" }));+ }+ return out;+};+const pt = (cam: Camera, v: V3): [number, number] => { const q = project(cam, v); return [q.x, q.y]; };+export { mv };diff --git a/engine/src/canvas-core/characters/mira/index.ts b/engine/src/canvas-core/characters/mira/index.tsnew file mode 100644index 0000000..7db85e6--- /dev/null+++ b/engine/src/canvas-core/characters/mira/index.ts@@ -0,0 +1,225 @@+// MIRA, v1.0.0. The ONE source of truth for her: canon, rig, drawn views, palette roles,+// distinguishing features, toScene(pose). Every still, sheet and film imports this module and+// poses her; nothing anywhere else is allowed to draw her.+//+// Who: a nine-year-old inventor. Round red glasses; a short dark-auburn bob with a straight+// fringe and one cowlick that will not lie down; freckles across the nose; a yellow raincoat+// (hood down, three wooden toggles, two flap pockets); a tan leather satchel on her left hip,+// strap over her right shoulder, brass buckle, a spanner handle poking out; navy tights; teal+// wellies.+//+// Canon: CANON.storybookChild, 5.2 heads, 1.30 m (a declared storybook enlargement of a real+// 6.2-head nine-year-old). Hands, joints and limb ratios below the neck are the real child's.+//+// Parts that are volumes (body, coat, sleeves, boots, bag) turn in 3D. Parts that are drawings+// (the fringe, the cowlick) are 2.5D: authored in three views and blended (character/view25d).+import type { P } from "../../core";+import { Blob, Camera, DEG, Frame, I3, V3, add, apply, dot, mm, mv, norm, project, ry, rz, sub } from "../../character/math3";+import type { BlobPart } from "../../character/build";+import { ccw, hull, insidePoly } from "../../character/shape2d";+import { Views, checkViews, place25d, viewOf } from "../../character/view25d";+import type { Character, Mark, Part, Pose, Scene } from "../../character/types";+import { CANON } from "../../character/human/canon";+import { CHILD_BODY, blob } from "../../character/human/mannequin";+import { CHILD_HEAD, type HeadCtx } from "../../character/human/head";+import { type FigureSpec, assemble, build, checkPose } from "../../character/human/figure";+import { cutChain } from "../../character/human/clothing";+import { drawnMira } from "./drawn";+import { type Rig, type Side, SIDES, sgn } from "../../character/human/skeleton";++export const MIRA_VERSION = "1.0.0";+export const MIRA_SPEC: FigureSpec = {+ canon: CANON.storybookChild, height: 1.3, body: CHILD_BODY,+ head: { ...CHILD_HEAD, freckles: [[-0.07, 0.36], [-0.1, 0.33], [-0.05, 0.325], [-0.12, 0.365], [0.07, 0.36], [0.1, 0.33], [0.05, 0.325], [0.12, 0.365], [0.0, 0.385]] },+ roles: { skin: "skin", torso: "coat", hips: "coat", upperArm: "coat", thigh: "tights", shin: "tights", foot: "boots" },+};++// ---------------------------------------------------------------- palette ROLES (each hand maps them)+export const MIRA_ROLES = {+ skin: { family: "warm light skin", hue: [14, 36] as [number, number], note: "peach, never pink-grey" },+ hair: { family: "dark auburn", hue: [8, 30] as [number, number], note: "warm dark brown with red in it" },+ coat: { family: "yellow", hue: [40, 58] as [number, number], note: "THE identity colour: a raincoat yellow in every hand" },+ tights: { family: "navy", hue: [210, 240] as [number, number], note: "dark cool blue" },+ boots: { family: "teal", hue: [165, 195] as [number, number], note: "blue-green wellies" },+ satchel: { family: "tan leather", hue: [18, 34] as [number, number], note: "warm mid brown" },+ glasses: { family: "red", hue: [350, 12] as [number, number], note: "round red frames" },+ toggle: { family: "wood", hue: [18, 36] as [number, number], note: "" },+ buckle: { family: "brass", hue: [38, 52] as [number, number], note: "" },+};++// ---------------------------------------------------------------- distinguishing features+export const MIRA_FEATURES = [+ { id: "glasses", parts: ["glasses"], note: "round red frames, big for her face", visible: (y: number) => Math.abs(y) < 150 },+ { id: "fringe", parts: ["hairFront"], note: "straight fringe, bob to the jaw", visible: (y: number) => Math.abs(y) < 105 },+ { id: "cowlick", parts: ["tuft"], note: "one tuft at the crown that sticks up", visible: () => true },+ { id: "freckles", parts: ["head"], note: "nine freckles across the nose", visible: (y: number) => Math.abs(y) < 75 },+ { id: "raincoat", parts: ["coat", "sleeveL", "sleeveR"], note: "yellow, hood down, three toggles", visible: () => true },+ { id: "satchel", parts: ["satchel"], note: "tan, left hip, strap over the right shoulder", visible: () => true },+ { id: "wellies", parts: ["bootL", "bootR"], note: "teal, to mid-calf", visible: () => true },+];++// ---------------------------------------------------------------- the 2.5D fringe: three authored views+// Units: head heights, origin at the cranium centre, x right, y DOWN. Every view has 24 points in+// the same order: near hem outer, up the near side, over the top, down the far side, the far hem,+// the far lock's inner edge, the fringe from far to near, the near lock's inner edge.+const FRINGE: Views = {+ yaw: [0, 45, 90],+ shapes: [+ [[-0.49, 0.48], [-0.52, 0.2], [-0.5, -0.1], [-0.4, -0.34], [-0.2, -0.49], [0.02, -0.52], [0.24, -0.48], [0.42, -0.33], [0.5, -0.08], [0.52, 0.2], [0.49, 0.48], [0.38, 0.5], [0.355, 0.22], [0.335, 0.0],+ [0.3, -0.115], [0.2, -0.095], [0.1, -0.135], [0.0, -0.105], [-0.1, -0.14], [-0.2, -0.1], [-0.3, -0.13], [-0.335, 0.0], [-0.355, 0.22], [-0.38, 0.5]],+ [[-0.5, 0.48], [-0.55, 0.2], [-0.54, -0.1], [-0.44, -0.36], [-0.22, -0.5], [0.05, -0.53], [0.28, -0.47], [0.44, -0.32], [0.51, -0.12], [0.52, 0.1], [0.49, 0.38], [0.44, 0.4], [0.44, 0.18], [0.45, -0.02],+ [0.42, -0.1], [0.33, -0.085], [0.24, -0.12], [0.14, -0.09], [0.04, -0.125], [-0.06, -0.09], [-0.15, -0.11], [-0.17, 0.05], [-0.15, 0.26], [-0.12, 0.5]],+ [[-0.47, 0.5], [-0.56, 0.2], [-0.56, -0.12], [-0.44, -0.38], [-0.2, -0.52], [0.08, -0.53], [0.3, -0.45], [0.44, -0.3], [0.52, -0.12], [0.535, -0.04], [0.5, 0.0], [0.45, -0.01], [0.37, -0.06], [0.3, -0.08],+ [0.23, -0.05], [0.19, 0.05], [0.17, 0.15], [0.16, 0.25], [0.15, 0.35], [0.13, 0.44], [0.1, 0.5], [0.0, 0.52], [-0.2, 0.53], [-0.36, 0.52]],+ ],+};+// the cowlick: one tuft at the crown, drawn once and turned with the head+// two thin strands that spring up and curl over toward her left, like hair, not a horn+const TUFT: Views = { yaw: [0, 90], shapes: [+ [[-0.03, 0.03], [-0.035, -0.06], [-0.01, -0.14], [0.05, -0.18], [0.1, -0.165], [0.06, -0.15], [0.025, -0.11], [0.02, -0.07], [0.055, -0.1], [0.075, -0.085], [0.03, -0.04], [0.02, 0.03]],+ [[-0.05, 0.03], [-0.06, -0.06], [-0.04, -0.14], [0.01, -0.19], [0.07, -0.18], [0.03, -0.16], [0.0, -0.12], [-0.005, -0.07], [0.03, -0.1], [0.05, -0.085], [0.01, -0.04], [0.01, 0.03]],+] };+checkViews("fringe", FRINGE); checkViews("tuft", TUFT);++const CRANIUM: V3 = [0, 0.6, -0.04];++// the bob as a 3D shell round the cranium: its hull IS the hair's silhouette from any side+const bobShell = (h: HeadCtx): P[] => {+ const pts: P[] = [], C = CRANIUM;+ for (let i = 0; i <= 10; i++) for (let j = 0; j < 20; j++) {+ const v = i / 10, yl = C[1] + 0.52 - v * 1.0, th = (j / 20) * Math.PI * 2, front = Math.cos(th) > 0.55 && yl < 0.66; // leave the face open+ if (front) continue;+ const flare = 1 + 0.12 * v * v, lat = Math.sqrt(Math.max(0, 1 - ((yl - C[1]) / 0.56) ** 2)) * 0.5 * flare + (v > 0.55 ? 0.03 * v : 0);+ const r = Math.max(lat, v > 0.5 ? 0.46 * flare : 0);+ const q = h.M([C[0] + Math.sin(th) * r, yl, C[2] + Math.cos(th) * r * 1.02]), pq = project(h.cam, q); pts.push([pq.x, pq.y]);+ }+ return ccw(hull(pts));+};++// ---------------------------------------------------------------- glasses: real 3D rims, occluded by the head+const glassesParts = (h: HeadCtx, head: Part, tuftAt: number, hair: P[]): Part[] => {+ const S = h.spec, marks: Mark[] = [], hd = project(h.cam, h.M([0, 0.5, 0])).z, px = project(h.cam, h.M([0, 0.44, 0])).s * h.hh;+ const hidden = (w: V3) => { const q = project(h.cam, w); return q.z > hd - 0.02 * h.hh && (head.polys.some((pl) => insidePoly(pl, q.x, q.y)) || insidePoly(hair, q.x, q.y)); }; // behind the head or the bob+ const temples: Mark[] = [];+ const run = (pts: V3[], w: number, role = "glasses", into = marks) => { let cur: P[] = []; const flush = () => { if (cur.length > 1) into.push({ kind: "line", pts: cur, role, w }); cur = []; }; pts.forEach((p) => { if (hidden(p)) flush(); else { const q = project(h.cam, p); cur.push([q.x, q.y]); } }); flush(); };+ const R = 0.088, zf = 0.47, w = Math.max(1.1, px * 0.022);+ [-1, 1].forEach((s) => {+ const cx = s * S.eyeX, cy = S.eyeY + 0.005;+ const ring: V3[] = Array.from({ length: 29 }, (_, i) => { const a = (i / 28) * Math.PI * 2, x = cx + Math.cos(a) * R; return h.M([x, cy + Math.sin(a) * R, zf - Math.abs(x) * 0.28]); });+ // lens glint: a pale crescent on the side toward the light, only when the lens faces us+ const n = mv(h.f.R, [0, 0, 1]), f = dot(n, norm(sub(h.cam.eye, h.M([cx, cy, zf]))));+ if (f > 0.3) { const g: V3[] = Array.from({ length: 7 }, (_, i) => { const a = Math.PI * (1.05 + i * 0.07); return h.M([cx + Math.cos(a) * R * 0.72, cy - Math.sin(a) * R * 0.72, zf - Math.abs(cx) * 0.28 + 0.005]); }); run(g, w * 0.9, "white"); }+ run(ring, w * 1.25);+ // the temple arm, back over the ear+ run(Array.from({ length: 8 }, (_, i) => { const t = i / 7; return h.M([s * (S.eyeX + R + t * (0.44 - S.eyeX - R)), cy + 0.01 + t * 0.02, zf - 0.08 - t * (zf - 0.02)]); }), w, "glasses", temples);+ });+ // the bridge, arching over the nose+ run(Array.from({ length: 7 }, (_, i) => { const a = Math.PI * (i / 6); return h.M([-Math.cos(a) * (S.eyeX - R), S.eyeY + 0.03 + Math.sin(a) * 0.025, zf + 0.005]); }), w * 1.1);+ // the temple arms go back UNDER the hair; the rims sit over the fringe+ return [{ id: "glasses", role: "glasses", depth: tuftAt - 0.001, polys: [], size: px * 0.1, marks, outline: false, fill: false, over: ["head", "hairFront", "earL", "earR", "temples"], feature: "glasses" },+ { id: "temples", role: "glasses", depth: tuftAt + 0.02 * h.hh, polys: [], size: px * 0.1, marks: temples, outline: false, fill: false, over: ["head", "earL", "earR"] }];+};++// ---------------------------------------------------------------- satchel and strap+const bagFrame = (r: Rig, swing: number): Frame => {+ // hangs from the strap at her left hip, broad face turned out and forward, swinging on the strap+ const P0 = r.pelvis, hh = r.dims.hh, hang = apply(P0, [0.52 * hh, 0.2 * hh, 0.16 * hh]);+ const R = mm(P0.R, mm(ry(-42 * DEG), rz(swing * DEG * 0.35)));+ return { p: add(hang, mv(R, [0, -0.32 * hh, 0])), R };+};+const satchel = (r: Rig, cam: Camera, swing: number): { part: BlobPart; spanner: BlobPart } => {+ const hh = r.dims.hh, F = bagFrame(r, swing), c = 0.055 * hh, W = 0.3 * hh, H = 0.22 * hh, T = 0.075 * hh;+ const corners: Blob[] = [];+ for (const x of [-1, 1]) for (const y of [-1, 1]) for (const z of [-1, 1]) corners.push({ c: apply(F, [x * (T - c * 0.3), y * (H - c), z * (W - c)]), R: F.R, r: [c, c, c] });+ const marks: Mark[] = [], face = mv(F.R, [1, 0, 0]), faceOn = dot(face, norm(sub(cam.eye, F.p)));+ const P = (l: V3): P => { const q = project(cam, apply(F, l)); return [q.x, q.y]; };+ if (faceOn > 0.05) {+ // the flap: over the top two thirds of the front, curved at the bottom, and its brass buckle+ const flap: P[] = [P([T + 0.004 * hh, H * 0.98, -W * 0.96]), P([T + 0.004 * hh, H * 0.98, W * 0.96]), P([T + 0.004 * hh, -H * 0.1, W * 0.94]), P([T + 0.004 * hh, -H * 0.28, W * 0.6]), P([T + 0.004 * hh, -H * 0.36, 0]), P([T + 0.004 * hh, -H * 0.28, -W * 0.6]), P([T + 0.004 * hh, -H * 0.1, -W * 0.94])];+ marks.push({ kind: "fill", pts: flap, role: "satchelDark", alpha: 0.9, line: 1.2 });+ const b = (y: number, z: number): P => P([T + 0.01 * hh, y, z]);+ marks.push({ kind: "fill", pts: [b(-H * 0.2, -0.05 * hh), b(-H * 0.2, 0.05 * hh), b(-H * 0.48, 0.05 * hh), b(-H * 0.48, -0.05 * hh)], role: "buckle", line: 1.1 });+ marks.push({ kind: "line", pts: [b(-H * 0.5, 0), b(-H * 0.75, 0)], role: "satchelDark", w: 2 });+ }+ // a spanner handle out of the top, the inventor's tell+ const sp0 = apply(F, [0, H * 0.9, W * 0.55]), sp1 = apply(F, [0.01 * hh, H + 0.2 * hh, W * 0.75]);+ const spanner: BlobPart = { id: "spanner", role: "metal", groups: [{ blobs: [{ c: sp0, R: I3, r: [0.022 * hh, 0.022 * hh, 0.022 * hh] }, { c: sp1, R: I3, r: [0.024 * hh, 0.024 * hh, 0.024 * hh] }], mode: "chain" }, { blobs: [{ c: add(sp1, mv(F.R, [0, 0.03 * hh, 0.02 * hh])), R: F.R, r: [0.02 * hh, 0.045 * hh, 0.05 * hh] }], mode: "each" }], depthBias: 0.02 * hh };+ return { part: { id: "satchel", role: "satchel", groups: [{ blobs: corners, mode: "hull" }], marks, over: ["coat", "hips", "spanner"], feature: "satchel", depthBias: -0.05 * hh }, spanner };+};++// surface marks on the coat: a line of torso-local points, kept where the coat faces the camera+const coatSurf = (r: Rig, cam: Camera, pts: [keyof Rig & ("chest" | "lumbar" | "pelvis"), V3][], lift: number) => {+ const hh = r.dims.hh, out: { p: P; vis: boolean }[] = [];+ pts.forEach(([fn, l]) => {+ const f = r[fn] as Frame, rad = Math.hypot(l[0], l[2]) || 1, local: V3 = [l[0] * hh * (1 + lift / rad), l[1] * hh, l[2] * hh * (1 + lift / rad)];+ const w = apply(f, local), n = norm(mv(f.R, [l[0], 0, l[2]])), vis = dot(n, norm(sub(cam.eye, w))) > 0.08, q = project(cam, w);+ out.push({ p: [q.x, q.y], vis });+ });+ return out;+};+const runsOf = (s: { p: P; vis: boolean }[]): P[][] => { const o: P[][] = []; let c: P[] = []; s.forEach((q) => { if (q.vis) c.push(q.p); else { if (c.length > 1) o.push(c); c = []; } }); if (c.length > 1) o.push(c); return o; };++const coatMarks = (r: Rig, cam: Camera, px: number): Mark[] => {+ const m: Mark[] = [], w = Math.max(1, px * 0.02);+ // the front opening, chin to hem, and the three toggles across it+ const placket = coatSurf(r, cam, [["chest", [0.035, 0.74, 0.3]], ["chest", [0.04, 0.5, 0.36]], ["chest", [0.04, 0.25, 0.37]], ["lumbar", [0.04, 0.16, 0.38]], ["pelvis", [0.04, 0.02, 0.37]], ["pelvis", [0.045, -0.2, 0.38]], ["pelvis", [0.05, -0.42, 0.39]]], 0.05);+ runsOf(placket).forEach((p) => m.push({ kind: "line", pts: p, role: "line", w: w * 1.1, alpha: 0.85 }));+ [["chest", 0.55, 0.36], ["chest", 0.2, 0.38], ["lumbar", 0.1, 0.39]].forEach(([fn, y, z]) => {+ const s = coatSurf(r, cam, [[fn as "chest", [-0.03, y as number, z as number]], [fn as "chest", [0.09, y as number, (z as number) - 0.005]]], 0.07);+ if (s[0].vis && s[1].vis) m.push({ kind: "line", pts: [s[0].p, s[1].p], role: "toggle", w: w * 3.2 });+ });+ // flap pockets on the hips+ SIDES.forEach((sd) => { const k = sgn(sd); const s = coatSurf(r, cam, [["pelvis", [k * 0.12, -0.12, 0.36]], ["pelvis", [k * 0.24, -0.13, 0.31]], ["pelvis", [k * 0.33, -0.11, 0.22]]], 0.06); runsOf(s).forEach((p) => m.push({ kind: "line", pts: p, role: "line", w: w * 0.9, alpha: 0.75 })); });+ // the satchel strap: over the right shoulder, across the chest to the left hip, and round the back+ const front = coatSurf(r, cam, [["chest", [-0.42, 0.78, 0.08]], ["chest", [-0.3, 0.62, 0.3]], ["chest", [-0.1, 0.44, 0.37]], ["chest", [0.12, 0.26, 0.37]], ["lumbar", [0.28, 0.14, 0.33]], ["pelvis", [0.4, 0.06, 0.24]]], 0.07);+ const back = coatSurf(r, cam, [["chest", [-0.42, 0.78, -0.02]], ["chest", [-0.28, 0.62, -0.27]], ["chest", [-0.05, 0.44, -0.33]], ["chest", [0.16, 0.26, -0.33]], ["lumbar", [0.32, 0.14, -0.26]], ["pelvis", [0.44, 0.06, -0.14]]], 0.07);+ [...runsOf(front), ...runsOf(back)].forEach((p) => m.push({ kind: "line", pts: p, role: "satchel", w: w * 3.6 }));+ return m;+};++// ---------------------------------------------------------------- boots+const boot = (r: Rig, s: Side): BlobPart => {+ const hh = r.dims.hh, sh = CHILD_BODY.shin.map((b) => blob(r, b, s, 0.035));+ const shaft = cutChain(sh.slice().reverse(), 0.55).reverse(); // the boot shaft: the lower 55% of the shin, from the ankle up+ const rim = shaft[0]; shaft[0] = { ...rim, r: [rim.r[0] + 0.025 * hh, 0.025 * hh, rim.r[2] + 0.025 * hh] };+ const ft = CHILD_BODY.foot.map((b) => blob(r, b, s, 0.03)), toe = CHILD_BODY.toes.map((b) => blob(r, b, s, 0.035));+ return { id: "boot" + s, role: "boots", groups: [{ blobs: shaft, mode: "chain" }, { blobs: [ft[0], ft[1]], mode: "chain" }, { blobs: [ft[1], ft[2], ...toe], mode: "chain" }], over: ["shin" + s, "foot" + s], feature: "wellies", depthBias: -0.025 * hh };+};++const FACE = { line: "line", pupil: "pupil", white: "white", blush: "blush", brow: "hair", mouth: "mouth", lip: "lip" };++export const miraScene = (p: Pose, cam: Camera): Scene => {+ const b = build(MIRA_SPEC, p, cam), r = b.rig, hh = r.dims.hh, h = b.head, aux = p.aux ?? {};+ // The body under the clothes is the invisible pose source: what is SEEN of her coat, sleeves,+ // legs and wellies is DRAWN (drawn.ts): designed masses swept along her gesture curves.+ const hidden = new Set(["torso", "hips", "upperArmL", "upperArmR", "foreArmL", "foreArmR", "thighL", "thighR", "shinL", "shinR", "footL", "footR"]);+ b.parts = b.parts.filter((q) => !hidden.has(q.id));+ // a stand-up collar round the neck: a ring of blobs, closed+ const ring: Blob[] = Array.from({ length: 11 }, (_, i) => { const a = (i / 10) * Math.PI * 2; return blob(r, ["chest", [Math.sin(a) * 0.19, 0.86 + Math.cos(a) * 0.015, -0.03 + Math.cos(a) * 0.15], [0.055, 0.065, 0.055]], "L"); });+ b.parts.push({ id: "collar", role: "coat", groups: [{ blobs: ring, mode: "chain" }], over: ["neck", "coat"], depthAt: apply(r.chest, [0, 0.8 * hh, 0.1 * hh]) });+ // the hood, lying down between the shoulder blades+ b.parts.push({ id: "hood", role: "coat", groups: [{ blobs: [blob(r, ["chest", [0, 0.74, -0.3], [0.3, 0.14, 0.13]], "L"), blob(r, ["chest", [0, 0.56, -0.36], [0.24, 0.14, 0.1]], "L")], mode: "chain" }], depthBias: 0.02 * hh });+ const bag = satchel(r, cam, aux.bagSwing ?? 0);+ b.parts.push(bag.part, bag.spanner);+ const px = project(cam, r.joints.chest).s * hh;+ return assemble(cam, b, p, FACE, { character: "mira", version: MIRA_VERSION }, (parts) => {+ const drawn = drawnMira(r, cam), head = parts.find((q) => q.id === "head")!, coat = drawn.find((q) => q.id === "coat")!, vw = viewOf(cam, h.f);+ coat.marks.push(...coatMarks(r, cam, px));+ const face = Math.abs(vw.yaw) < 105, hd = head.depth, out: Part[] = [];+ out.push({ id: "hairBack", role: "hair", depth: face ? hd + 0.35 * hh : hd - 0.06 * hh, polys: [bobShell(h)], size: head.size * 1.1, marks: [], over: face ? [] : ["head", "earL", "earR", "neck"], feature: "fringe" });+ if (face) { const fr = place25d(cam, h.f, [0, CRANIUM[1] - MIRA_SPEC.head.pivot[1], CRANIUM[2] - MIRA_SPEC.head.pivot[2]].map((v) => v * hh) as V3, hh, FRINGE, { pitchShift: 0.12 }); out.push({ id: "hairFront", role: "hair", depth: hd - 0.02 * hh, polys: [ccw(fr.pts)], size: head.size, marks: [], over: ["head", "earL", "earR", "temples"], feature: "fringe" }); }+ const tf = place25d(cam, h.f, [0, (1.02 - MIRA_SPEC.head.pivot[1]) * hh, (-0.12 - MIRA_SPEC.head.pivot[2]) * hh], hh, TUFT);+ out.push({ id: "tuft", role: "hair", depth: hd - 0.03 * hh, polys: [ccw(tf.pts)], size: head.size * 0.4, marks: [], over: ["hairBack", "hairFront", "head"], feature: "cowlick" });+ out.push(...glassesParts(h, head, hd - 0.04 * hh, out[0].polys[0]));+ out.push(...drawn);+ return out;+ });+};++export const mira: Character = {+ id: "mira", name: "Mira", version: MIRA_VERSION, canonId: "storybookChild",+ description: "Nine-year-old inventor, 5.2 heads (storybook), 1.30 m: round red glasses, dark auburn bob with fringe and cowlick, freckles, yellow raincoat, tan satchel, navy tights, teal wellies.",+ roles: MIRA_ROLES, features: MIRA_FEATURES,+ pose: (p: Pose) => { checkPose(p, "mira"); return p; },+ toScene: (p: Pose, cam: Camera) => miraScene(p, cam),+};diff --git a/engine/src/canvas-core/characters/mira/palettes.ts b/engine/src/canvas-core/characters/mira/palettes.tsnew file mode 100644index 0000000..6a9560a--- /dev/null+++ b/engine/src/canvas-core/characters/mira/palettes.ts@@ -0,0 +1,77 @@+// MIRA'S PALETTE ROLES, mapped per hand. A role is fixed for the character ("coat" is her+// raincoat yellow); each hand decides how that role is MADE in its medium. The gate+// (tools/character-check.mjs) holds every mapping to the role's hue family.+import type { Palette } from "../../character/render/storybook";++// storybook pencil + watercolour: transparent washes, shadow colour cooler than the lit colour+export const MIRA_STORYBOOK: Palette = {+ skin: { base: "#f7d5bb", shade: "#e3a98e" }, nail: { base: "#fde8da", shade: "#f0c9b4" }, hair: { base: "#7b4630", shade: "#51291a" }, coat: { base: "#f6d04d", shade: "#dca63a" },+ tights: { base: "#415182", shade: "#2c375d" }, boots: { base: "#4ea79d", shade: "#347c75" }, satchel: { base: "#bb7a4b", shade: "#8b5431" },+ satchelDark: { base: "#9a5f37", shade: "#744424" }, glasses: { base: "#d8443a", shade: "#a52f28" }, toggle: { base: "#9c6436", shade: "#744424" },+ buckle: { base: "#e0b955", shade: "#b08a34" }, metal: { base: "#b9c2cb", shade: "#7f8a96" }, pupil: { base: "#3d3437", shade: "#2a2326" },+ white: { base: "#fffaf3", shade: "#e8e0d4" }, blush: { base: "#f2899c", shade: "#d9687d" }, mouth: { base: "#8c3b3b", shade: "#6b2929" }, lip: { base: "#e98a8f", shade: "#c96a70" },+};+// marker comic: saturated cel flats, a hard shadow a clear step darker+export const MIRA_MARKER: Palette = {+ skin: { base: "#ffd8b8", shade: "#f0a987" }, nail: { base: "#ffeadc", shade: "#f5c3a6" }, hair: { base: "#8a4127", shade: "#4f2012" }, coat: { base: "#ffd21f", shade: "#f0a100" },+ tights: { base: "#2f3f86", shade: "#1b2456" }, boots: { base: "#10a99a", shade: "#067268" }, satchel: { base: "#c7773f", shade: "#8e4a20" },+ satchelDark: { base: "#94501f", shade: "#6d3812" }, glasses: { base: "#ee3524", shade: "#b0170c" }, toggle: { base: "#8e4a20", shade: "#6d3812" },+ buckle: { base: "#ffc933", shade: "#d49a00" }, metal: { base: "#c5d0da", shade: "#7d8b99" }, pupil: { base: "#15122a", shade: "#15122a" },+ white: { base: "#ffffff", shade: "#dfe6ee" }, blush: { base: "#ff7b93", shade: "#e2566f" }, mouth: { base: "#7a1f2a", shade: "#5a1119" }, lip: { base: "#ff7b87", shade: "#d9535f" },+};+// risograph: a role is a RECIPE of drums (ink, tone 0..1) that overprint by multiply. Yellow is+// the coat; pink + yellow is skin; blue + pink + yellow at depth is the hair.+import type { RisoRecipe } from "../../character/render/riso";+export const MIRA_RISO: Record<string, RisoRecipe> = {+ skin: { inks: [["pink", 0.2], ["yellow", 0.28]], shadeInk: "pink", shadeTone: 0.45 }, nail: { inks: [["pink", 0.1]] },+ hair: { inks: [["pink", 0.85], ["yellow", 0.7], ["blue", 0.55]], shadeInk: "blue", shadeTone: 0.4 },+ coat: { inks: [["yellow", 1]], shadeInk: "pink", shadeTone: 0.42 },+ tights: { inks: [["blue", 0.95], ["pink", 0.5]], shadeInk: "blue", shadeTone: 0.5 },+ boots: { inks: [["blue", 0.78], ["yellow", 0.24]], shadeInk: "blue", shadeTone: 0.45 },+ satchel: { inks: [["pink", 0.55], ["yellow", 0.85], ["blue", 0.18]], shadeInk: "pink", shadeTone: 0.5 },+ satchelDark: { inks: [["pink", 0.75], ["yellow", 0.9], ["blue", 0.35]] },+ glasses: { inks: [["pink", 1], ["yellow", 0.8]] }, toggle: { inks: [["pink", 0.7], ["yellow", 0.9], ["blue", 0.3]] },+ buckle: { inks: [["yellow", 1], ["pink", 0.2]] }, metal: { inks: [["blue", 0.35]] }, pupil: { inks: [["blue", 1], ["pink", 0.6]] },+ white: { inks: [] }, blush: { inks: [["pink", 0.55]] }, mouth: { inks: [["pink", 0.9], ["blue", 0.6]] }, lip: { inks: [["pink", 0.7]] },+};++// ukiyo-e woodblock: mineral and vegetable pigments (gamboge, safflower, Prussian blue, sumi)+export const MIRA_WOODCUT: Record<string, string> = {+ skin: "#f3dcc2", nail: "#f6e4d0", hair: "#5a3322", coat: "#e9b73a", tights: "#2f4f86", boots: "#3e8a82", satchel: "#a66b3c", satchelDark: "#7e4a26",+ glasses: "#cf3b2a", toggle: "#7e4a26", buckle: "#d9b04a", metal: "#9aa6ad", white: "#efe6d1", blush: "#e79a8c", mouth: "#8a2f2a", lip: "#d9786c", pupil: "#1d1916",+};+// tinted scratchboard: transparent inks laid over the scraped white+export const MIRA_SCRATCH: Record<string, string> = {+ skin: "#f6c9a8", nail: "#f6d6c0", hair: "#b0643e", coat: "#ffd23a", tights: "#6d86d6", boots: "#3fbfb0", satchel: "#d68f55", satchelDark: "#b06a36",+ glasses: "#ff4a3a", toggle: "#c07a45", buckle: "#ffd060", metal: "#c9d4dc",+};+// ink and light colour: pale washes (colour, strength); the hair is ink, not colour+export const MIRA_SUMI: Record<string, [string, number]> = {+ skin: ["#f0c7a4", 0.4], nail: ["#f0c7a4", 0.3], coat: ["#e8b62c", 0.62], tights: ["#4d6aa8", 0.55], boots: ["#3f9a8e", 0.55], satchel: ["#b57942", 0.5], satchelDark: ["#8a5530", 0.5],+ toggle: ["#8a5530", 0.6], buckle: ["#d8ad3c", 0.6], metal: ["#9aa4ac", 0.4],+};+// pixel art: a limited palette, each role a two-step ramp (lit, shade)+export const MIRA_PIXEL = {+ bg: "#bfe3ee", ground: "#8fcf8a", groundShadow: "#5fa67a", outline: "#2b1d2e",+ roles: {+ skin: ["#f7c9a3", "#d9926f"], nail: ["#f7c9a3", "#d9926f"], hair: ["#8a4a2c", "#5a2c1c"], coat: ["#ffd23f", "#e0961c"], tights: ["#3b4a8c", "#27305e"], boots: ["#22a797", "#12716a"],+ satchel: ["#bd6f38", "#834621"], satchelDark: ["#834621", "#5e3016"], glasses: ["#e2332b", "#a8201a"], toggle: ["#834621", "#5e3016"], buckle: ["#f2c840", "#b88a1c"],+ metal: ["#c3ccd3", "#8a959e"], pupil: ["#2b1d2e", "#2b1d2e"], white: ["#ffffff", "#e6e6e6"], blush: ["#f2898a", "#d06a6c"], mouth: ["#8c2f3a", "#6a1f2a"], lip: ["#e06a78", "#c04a58"],+ } as Record<string, [string, string]>,+};+// toy bricks: real brick colours; the shade side is built in that colour's darker brick+export const MIRA_BRICK = {+ base: "#cfe4ef", baseStud: false, ground: "#4b9f4a",+ roles: {+ skin: ["#f6d7b3", "#e4b98a"], nail: ["#f6d7b3", "#e4b98a"], hair: ["#82422a", "#5c2a18"], coat: ["#f2cd37", "#e39b25"], tights: ["#1e3a6e", "#132749"], boots: ["#00a0a0", "#006f73"],+ satchel: ["#aa7d55", "#7c5236"], satchelDark: ["#7c5236", "#5a3824"], glasses: ["#c91a09", "#8e1206"], toggle: ["#7c5236", "#5a3824"], buckle: ["#dcbc3b", "#b08f20"],+ metal: ["#a0a5a9", "#6c6e68"], pupil: ["#1b2a34", "#1b2a34"], white: ["#ffffff", "#e0e0e0"], blush: ["#e4adc8", "#c98aa8"], mouth: ["#720e0f", "#500a0a"], lip: ["#c84f60", "#a0303f"],+ } as Record<string, [string, string]>,+};+// coloured pencil: pencil colours, local and shadow+export const MIRA_PENCIL = {+ skin: { base: "#f0bf9c", shade: "#c98a74" }, nail: { base: "#f5d6c2", shade: "#e0b49c" }, hair: { base: "#8b4a2e", shade: "#4e2618" }, coat: { base: "#f5c93a", shade: "#d9892a" },+ tights: { base: "#3d4f95", shade: "#262e5c" }, boots: { base: "#2a9d8f", shade: "#1a6b62" }, satchel: { base: "#b8733f", shade: "#7e4524" }, satchelDark: { base: "#8e5530", shade: "#6a3a1e" },+ glasses: { base: "#d9372a", shade: "#9e1f16" }, toggle: { base: "#7e4524", shade: "#5a2e16" }, buckle: { base: "#e2b33c", shade: "#a07820" }, metal: { base: "#a9b3bb", shade: "#707a84" },+ pupil: { base: "#2a2230", shade: "#1a1420" }, white: { base: "#fffdf6", shade: "#e8e2d4" }, blush: { base: "#ec8f92", shade: "#c9676a" }, mouth: { base: "#8c3242", shade: "#6a2030" }, lip: { base: "#e07a82", shade: "#c05a62" },+};diff --git a/engine/src/canvas-core/characters/mira/poses.ts b/engine/src/canvas-core/characters/mira/poses.tsnew file mode 100644index 0000000..a05f275--- /dev/null+++ b/engine/src/canvas-core/characters/mira/poses.ts@@ -0,0 +1,125 @@+// MIRA'S POSES. Built from placed feet, solved legs, balance and reach targets, never from a+// pile of guessed angles where contact matters. Every pose here passes the joint-limit check at+// load (a pose outside the range of motion throws) and every standing pose is balance-checked by+// tools/character-check.mjs.+import { Blob, DEG, I3, V3, add, apply, mix3, mul, mv, norm, sub } from "../../character/math3";+import type { BlobPart } from "../../character/build";+import type { Pose } from "../../character/types";+import { dimsFromCanon } from "../../character/human/skeleton";+import { contrapposto, reach, stand } from "../../character/human/balance";+import { rigFor } from "../../character/human/figure";+import { planWalk, walkAt } from "../../character/human/walk";+import { MIRA_SPEC } from "./index";+import { handModel, resolveHand } from "../../character/human/hands";++export const MIRA_DIMS = dimsFromCanon(MIRA_SPEC.canon, MIRA_SPEC.height);+const D = MIRA_DIMS, hh = D.hh, AH = D.ankleH;+const ry = (yaw: number) => (v: V3): V3 => mv([Math.cos(yaw * DEG), 0, Math.sin(yaw * DEG), 0, 1, 0, -Math.sin(yaw * DEG), 0, Math.cos(yaw * DEG)], v);+export const base = (yaw = 0, j: Record<string, number> = {}, ex: Record<string, number> = {}): Pose => ({ root: [0, D.root, 0], yaw, joints: { shoulderRaiseL: 12, shoulderRaiseR: 12, shoulderSwingL: 22, shoulderSwingR: 22, elbowL: 16, elbowR: 16, ...j }, expression: ex, hands: { L: "relaxed", R: "relaxed" }, plant: true });++export const relaxed = (yaw: number, ex: Record<string, number> = {}): Pose => base(yaw, {}, ex);++// weight on her left leg, right hand holding the satchel strap across her chest+export const strapStand = (yaw: number): Pose => {+ const T = ry(yaw); let p = base(yaw, { ...contrapposto("L", 0.8), headTilt: 6 }, { smile: 0.5, cheek: 0.3, lookX: -0.2 });+ const feet = { L: T([0.04, AH, 0]), R: T([-0.11, AH, 0.08]) }, over = T([0.04, 0, 0.035]);+ p = stand(D, p, feet, [over[0], over[2]], { R: 3 });+ const r = rigFor(MIRA_SPEC, { ...p, plant: false }), strap = apply(r.chest, [-0.2 * hh, 0.5 * hh, 0.44 * hh]);+ p = reach(D, { ...p, joints: { ...p.joints, shoulderRaiseR: 30, shoulderSwingR: 80, elbowR: 110 } }, "R", strap);+ return { ...p, hands: { L: "relaxed", R: "fist" } };+};++// on her toes, right arm up to a high shelf, looking up+export const reachUp = (yaw: number): Pose => {+ const T = ry(yaw); let p = base(yaw, { spineSide: 7, spineBend: -5, neckBend: -12, headNod: -14, toeL: 18, toeR: 18, clavLiftR: 20, shoulderRaiseL: 16, elbowL: 30 }, { browRaise: 0.5, lookY: 0.9, mouthOpen: 0.2, mouthWide: -0.5 });+ p = { ...p, root: [p.root[0], p.root[1] + 0.04, p.root[2]] };+ const feet = { L: T([0.08, AH + 0.03, 0.0]), R: T([-0.08, AH + 0.03, -0.02]) }, fw = T([0, 0, 0.08]);+ p = stand(D, p, feet, [fw[0], fw[2]], { L: -18, R: -18 }, 14);+ // the raised arm moves the centre of mass, so settle the balance again with the arm up, then re-aim the hand+ for (let k = 0; k < 2; k++) { p = reach(D, { ...p, joints: { ...p.joints, shoulderRaiseR: p.joints.shoulderRaiseR ?? 160, shoulderSwingR: p.joints.shoulderSwingR ?? 60, elbowR: p.joints.elbowR ?? 12 } }, "R", T([-0.12, 1.5, 0.14])); p = stand(D, p, feet, [fw[0], fw[2]], { L: -18, R: -18 }, 10); }+ return { ...p, hands: { L: "relaxed", R: "open" } };+};++// sitting on an upturned crate, elbows on her knees, chin propped+export const CRATE_H = 0.3;+export const sitCrate = (yaw: number): Pose => {+ const T = ry(yaw); let p: Pose = { ...base(yaw, { pelvisTilt: -6, spineBend: 26, neckBend: -6, headNod: -16 }, { smile: 0.3, lookY: 0.2, lookX: 0.3 }), root: T([0, CRATE_H + 0.085, -0.03]), plant: false };+ p = stand(D, p, { L: T([0.1, AH, 0.3]), R: T([-0.09, AH, 0.32]) }, null, {}, 1);+ const r = rigFor(MIRA_SPEC, p);+ p = reach(D, p, "R", add(r.joints.kneeR, T([0.02, 0.06, -0.02])));+ p = reach(D, p, "L", add(r.joints.kneeL, T([-0.03, 0.05, 0.0])));+ return { ...p, hands: { L: "relaxed", R: "relaxed" } };+};+export const crate = (yaw: number): BlobPart[] => {+ const T = ry(yaw), c: Blob[] = [];+ for (const x of [-1, 1]) for (const y of [0, 1]) for (const z of [-1, 1]) c.push({ c: T([x * 0.19, 0.02 + y * (CRATE_H - 0.04), -0.03 + z * 0.14]), R: I3, r: [0.02, 0.02, 0.02] });+ return [{ id: "crate", role: "crate", groups: [{ blobs: c, mode: "hull" }], depthBias: 0.05 }];+};++// crouched on her heels, tinkering: screwdriver in the right hand, a gear in the left+export const crouch = (yaw: number): Pose => {+ const T = ry(yaw); let p: Pose = { ...base(yaw, { spineBend: 20, neckBend: -2, headNod: -8, toeL: 36, toeR: 34 }, { browFurrow: 0.6, lidUpper: 0.2, smile: 0.1, mouthWide: -0.3, lookY: -0.8 }), root: T([0, 0.36, -0.02]), plant: false };+ const ov = T([0, 0, 0.13]); // a child crouches on the balls of her feet (the ankle cannot fold further), weight over them+ p = stand(D, p, { L: T([0.11, AH + 0.05, 0.12]), R: T([-0.1, AH + 0.05, 0.08]) }, [ov[0], ov[2]], { L: -36, R: -34 }, 10);+ const r = rigFor(MIRA_SPEC, p), work = add(mix3(r.joints.kneeL, r.joints.kneeR, 0.5), T([0, 0.03, 0.22]));+ p = reach(D, p, "R", add(work, T([-0.05, 0.02, 0])));+ p = reach(D, p, "L", add(work, T([0.07, 0.0, 0.0])));+ return { ...p, hands: { L: "pinch", R: "grip" } };+};++// the wave: arm up and out, the forearm rocking, head tipped, a big smile+export const wave = (yaw: number, t = 0, ex: Record<string, number> = { smile: 1, cheek: 0.8, lidLower: 0.3, browRaise: 0.4 }): Pose => {+ const rock = Math.sin(t);+ const p = base(yaw, { shoulderRaiseR: 128, shoulderSwingR: 20, shoulderTwistR: 30, elbowR: 58 + 14 * rock, pronationR: 25, wristDevR: -8 * rock, headTilt: -8, neckSide: -4, spineSide: -4, clavLiftR: 12 }, ex);+ return { ...p, hands: { L: "relaxed", R: "wave" } };+};++// a walking frame (the contact position) from the same walk the film uses+export const walkContact = (yaw: number): Pose => {+ const plan = planWalk({ t0: 0, s0: 0, step: 0.4, cycle: 30, n: 8, first: "L", lateral: 0.065 });+ const dir: V3 = [Math.sin(yaw * DEG), 0, Math.cos(yaw * DEG)];+ const f = walkAt(D, plan, 60, base(yaw, {}, { smile: 0.3 }), { origin: mul(dir, -plan.rootS(60)), dir }).pose;+ return f;+};++// standing on the crate, reaching up with the screwdriver: the comic panel+export const reachOnCrate = (yaw: number, target: V3): Pose => {+ const T = ry(yaw), fl = CRATE_H; let p = base(yaw, { spineSide: 6, spineBend: -4, neckBend: -14, headNod: -16, toeL: 10, toeR: 10, clavLiftR: 18, shoulderRaiseL: 62, shoulderSwingL: -5, elbowL: 28, wristFlexL: -20 }, { browFurrow: 0.8, lidUpper: 0.15, mouthOpen: 0.25, mouthWide: -0.2, lookY: 0.9, smile: 0.15 });+ p = { ...p, root: [p.root[0], p.root[1] + fl + 0.03, p.root[2]] };+ const feet = { L: T([0.09, fl + AH + 0.015, 0.0]), R: T([-0.08, fl + AH + 0.015, -0.03]) }, fw = T([0, 0, 0.06]);+ for (let k = 0; k < 2; k++) { p = reach(D, { ...p, joints: { ...p.joints, shoulderRaiseR: p.joints.shoulderRaiseR ?? 150, shoulderSwingR: p.joints.shoulderSwingR ?? 60, elbowR: p.joints.elbowR ?? 30 } }, "R", target); p = stand(D, p, feet, [fw[0], fw[2]], { L: -10, R: -10 }, 10, fl); }+ return { ...p, hands: { L: { open: 0.6, relaxed: 0.4 }, R: "grip" } };+};+// sitting on the crate, holding a gear up to her eye: the riso poster+export const gearToEye = (yaw: number): Pose => {+ let p = sitCrate(yaw); p = { ...p, expression: { browRaise: 0.7, smile: 0.35, lookX: 0.55, lookY: 0.1, mouthWide: -0.2 }, joints: { ...p.joints, neckTwist: 18, headTilt: 8, headNod: -6, spineBend: 14 } };+ // at arm's length, out to her right and a little below her eyes, so the hand never covers the face+ const r = rigFor(MIRA_SPEC, p), eye = apply(r.head, [-0.55 * hh, 0.3 * hh, 1.05 * hh]);+ p = reach(D, { ...p, joints: { ...p.joints, shoulderRaiseR: 70, shoulderSwingR: 80, elbowR: 120 } }, "R", eye);+ return { ...p, hands: { L: "relaxed", R: "pinch" } };+};+export const gearAt = (c: V3, n: V3, R = 0.03, id = "gear"): BlobPart => {+ const u = norm(Math.abs(n[1]) < 0.9 ? [n[2], 0, -n[0]] as V3 : [1, 0, 0] as V3), v: V3 = [n[1] * u[2] - n[2] * u[1], n[2] * u[0] - n[0] * u[2], n[0] * u[1] - n[1] * u[0]];+ const teeth: Blob[] = Array.from({ length: 12 }, (_, i) => { const a = (i / 12) * Math.PI * 2; return { c: add(c, add(mul(u, Math.cos(a) * R), mul(v, Math.sin(a) * R))), R: I3, r: [R * 0.2, R * 0.2, R * 0.2] }; });+ const disc: Blob = { c, R: [u[0], n[0], v[0], u[1], n[1], v[1], u[2], n[2], v[2]], r: [R * 0.92, R * 0.14, R * 0.92] };+ return { id, role: "buckle", groups: [{ blobs: [disc], mode: "each" }, { blobs: teeth, mode: "each" }], depthAt: c };+};+export const gearInPinch = (p: Pose, side: "L" | "R" = "R"): BlobPart => {+ // held edge-on between the thumb pad and the index pad: its rim sits where they meet+ const r = rigFor(MIRA_SPEC, p), hm = handModel(r.hand[side], side, D.hand, resolveHand("pinch")), th = hm.digits.find((d) => d.digit === "thumb")!.pts[3], ix = hm.digits.find((d) => d.digit === "index")!.pts[3];+ const grip = mix3(th, ix, 0.5), out = norm(sub(grip, r.joints["wrist" + side])), n = norm(sub(ix, th));+ return gearAt(add(grip, mul(out, 0.03)), n, 0.03);+};++// props+export const screwdriver = (p: Pose): BlobPart[] => {+ const r = rigFor(MIRA_SPEC, p), h = r.hand.R, Lh = D.hand, grip = apply(h, [0.075 * Lh + 0.013, -0.46 * Lh, 0]), ax = norm(mv(h.R, [0, 0, 1]));+ const a = add(grip, mul(ax, 0.05)), b = add(grip, mul(ax, -0.045)), tip = add(grip, mul(ax, -0.13));+ return [{ id: "driverHandle", role: "toolRed", groups: [{ blobs: [{ c: a, R: I3, r: [0.014, 0.014, 0.014] }, { c: b, R: I3, r: [0.016, 0.016, 0.016] }], mode: "chain" }], depthAt: grip },+ { id: "driverShaft", role: "metal", groups: [{ blobs: [{ c: b, R: I3, r: [0.004, 0.004, 0.004] }, { c: tip, R: I3, r: [0.003, 0.003, 0.003] }], mode: "chain" }], depthAt: mix3(b, tip, 0.5) }];+};+export const gear = (p: Pose): BlobPart[] => {+ const r = rigFor(MIRA_SPEC, p), hm = r.hand.L, c = apply(hm, [-0.02, -0.55 * D.hand, 0.1 * D.hand]), n = norm(mv(hm.R, [1, 0, 0]));+ const teeth: Blob[] = Array.from({ length: 10 }, (_, i) => { const a = (i / 10) * Math.PI * 2, u = norm(sub(mv(hm.R, [0, Math.cos(a), Math.sin(a)]), mul(n, 0))); return { c: add(c, mul(u, 0.026)), R: I3, r: [0.006, 0.006, 0.006] }; });+ return [{ id: "gear", role: "buckle", groups: [{ blobs: [{ c, R: hm.R, r: [0.004, 0.024, 0.024] }], mode: "each" }, { blobs: teeth, mode: "each" }], depthAt: c }];+};diff --git a/engine/src/canvas-core/characters/theo/baker.ts b/engine/src/canvas-core/characters/theo/baker.tsnew file mode 100644index 0000000..37850f1--- /dev/null+++ b/engine/src/canvas-core/characters/theo/baker.ts@@ -0,0 +1,145 @@+// THEO, THE BAKER. The adult proof of the drawing layer: a specific man, not a figure model.+// Mid-forties, 1.78 m, the realistic 7.5-head canon (the rig and every gate are Theo's), built+// solid: sloping shoulders, a softening middle, a baker's forearms. Short dark hair going grey at+// the temples, a close beard and moustache, a white shirt with the sleeves rolled to mid-forearm,+// a canvas apron from the chest to below the knee, dark work trousers, brown boots. He holds a+// round loaf out toward us, weight on his left leg, head tipped, pleased with it.+//+// Everything SEEN is designed here: cross-section tables swept along gesture curves through his+// joints (character/design.ts). The skeleton only says where the curves go.+import type { P } from "../../core";+import { Blob, Camera, I3, V3, add, apply, mix3, mul, mv, norm, project, sub } from "../../character/math3";+import { type Section, type Station, jointed, station, stationU, sweep } from "../../character/design";+import { type BlobPart, toPart } from "../../character/build";+import type { Character, Mark, Part, Pose, Scene } from "../../character/types";+import { type Rig, SIDES, sgn } from "../../character/human/skeleton";+import { assemble, build, checkPose, rigFor } from "../../character/human/figure";+import { hairCap } from "../../character/human/head";+import { viewOf } from "../../character/view25d";+import { contrapposto, reach, stand } from "../../character/human/balance";+import { THEO_SPEC } from "./index";+import { THEO_DIMS } from "./poses";++// ---- the designed masses (head units: lateral, medial, front, back)+const SHIRT: Section[] = [[0, 0.62, 0.62, 0.43, 0.46], [0.24, 0.6, 0.6, 0.47, 0.39], [0.5, 0.63, 0.63, 0.45, 0.4], [0.76, 0.68, 0.68, 0.39, 0.36], [0.86, 0.64, 0.64, 0.33, 0.31], [0.93, 0.46, 0.46, 0.27, 0.27], [1, 0.24, 0.24, 0.22, 0.22]]; // the top falls away: sloping shoulders, never a shelf+const SLEEVE: Section[] = [[0, 0.12, 0.1, 0.14, 0.14], [0.12, 0.2, 0.17, 0.2, 0.19], [0.3, 0.21, 0.18, 0.21, 0.2], [0.58, 0.175, 0.165, 0.18, 0.18], [0.84, 0.17, 0.165, 0.17, 0.17], [0.9, 0.21, 0.21, 0.21, 0.21], [1, 0.21, 0.21, 0.21, 0.21]]; // the roll bulges at the end+const FOREARM: Section[] = [[0, 0.165, 0.155, 0.16, 0.165], [0.2, 0.195, 0.16, 0.165, 0.16], [0.55, 0.145, 0.13, 0.125, 0.125], [1, 0.1, 0.09, 0.075, 0.075]]; // swell high on the thumb side, flat at the wrist+const TROUSER: Section[] = [[0, 0.35, 0.31, 0.34, 0.38], [0.3, 0.31, 0.27, 0.31, 0.31], [0.5, 0.23, 0.21, 0.23, 0.21], [0.66, 0.23, 0.21, 0.21, 0.24], [0.94, 0.19, 0.19, 0.19, 0.19], [1, 0.2, 0.2, 0.2, 0.2]];+const BOOT: Section[] = [[0, 0.14, 0.14, 0.14, 0.14], [0.45, 0.175, 0.175, 0.12, 0.12], [0.85, 0.17, 0.17, 0.1, 0.1], [1, 0.13, 0.13, 0.07, 0.07]];+const SHAFT: Section[] = [[0, 0.16, 0.16, 0.16, 0.16], [1, 0.155, 0.155, 0.155, 0.155]];+const APRON: Section[] = [[0, 0.27, 0.27, 0.02, 0.02], [0.18, 0.3, 0.3, 0.02, 0.02], [0.3, 0.5, 0.5, 0.02, 0.02], [0.7, 0.52, 0.52, 0.02, 0.02], [1, 0.54, 0.54, 0.02, 0.02]]; // a plate: wide, thin++const P2 = (cam: Camera, v: V3): P => { const q = project(cam, v); return [q.x, q.y]; };+const mk = (id: string, role: string, polys: P[][], cam: Camera, at: V3, bias: number, o: Partial<Part> = {}): Part => { const q = project(cam, at); return { id, role, depth: q.z + bias, polys, size: q.s * 0.14, marks: [], ...o }; };+const faces = (cam: Camera, at: V3, n: V3) => { const v = norm(sub(cam.eye, at)); return n[0] * v[0] + n[1] * v[1] + n[2] * v[2]; };++export const drawnBaker = (r: Rig, cam: Camera): Part[] => {+ const hh = r.dims.hh, out: Part[] = [], C = r.chest;+ const shirtSt: Station[] = [station(r.pelvis, [0, -0.02 * hh, 0]), station(r.lumbar), station(C, [0, 0.45 * hh, 0]), station(C, [0, 1.0 * hh, 0]), station(C, [0, 1.24 * hh, -0.05 * hh])];+ out.push(mk("shirt", "shirt", sweep(cam, shirtSt, SHIRT, { hh, side: 1, n: 12, caps: [false, false] }), cam, r.joints.chest, 0, { over: ["legL", "legR"] }));+ for (const s of SIDES) {+ const k = sgn(s) as 1 | -1;+ const sl: Station[] = [station(r.upper[s], [-k * 0.03 * hh, -0.02 * hh, 0]), station(r.fore[s]), station(r.fore[s], [0, -0.42 * r.dims.forearm, 0])];+ out.push(mk("sleeve" + s, "shirt", jointed(cam, sl, SLEEVE, { hh, side: k, n: 10, cuts: [stationU(sl, 1)] }), cam, r.joints["elbow" + s], -0.06 * hh, { seams: [{ at: P2(cam, r.joints["shoulder" + s]), r: 0.3 * hh * project(cam, r.joints["shoulder" + s]).s, with: "shirt" }] }));+ const fa: Station[] = [station(r.fore[s], [0, -0.05 * hh, 0]), station(r.hand[s], [0, 0.02 * hh, 0])];+ out.push(mk("forearm" + s, "skin", sweep(cam, fa, FOREARM, { hh, side: k, n: 10, caps: [false, true] }), cam, apply(r.fore[s], [0, -0.6 * r.dims.forearm, 0]), -0.055 * hh, { over: [] }));+ const lg: Station[] = [station(r.thigh[s]), station(r.shin[s]), station(r.foot[s], [0, 0.04 * hh, 0])];+ out.push(mk("leg" + s, "trousers", jointed(cam, lg, TROUSER, { hh, side: k, n: 10, cuts: [stationU(lg, 1)] }), cam, r.joints["knee" + s], -0.02 * hh));+ const sh: Station[] = [station(r.shin[s], [0, -0.82 * r.dims.shin, 0]), station(r.foot[s], [0, -0.05 * hh, 0])];+ const ft: Station[] = [station(r.foot[s], [0, -0.22 * hh, -0.18 * hh]), station(r.foot[s], [0, -0.22 * hh, 0.25 * hh]), station(r.toes[s], [0, -0.03 * hh, 0.14 * hh])];+ out.push(mk("boot" + s, "boots", [...sweep(cam, sh, SHAFT, { hh, side: k, n: 6, caps: [false, false] }), ...sweep(cam, ft, BOOT, { hh, side: k, n: 8 })], cam, apply(r.foot[s], [0, 0, 0.1 * hh]), -0.03 * hh, { over: ["leg" + s] }));+ }+ // the apron: hung from the chest, tied at the waist, falling past the knees; it lies ON his front+ const knees = mix3(r.joints.kneeL, r.joints.kneeR, 0.5), fwd = norm(mv(r.pelvis.R, [0, 0, 1]));+ const apSt: Station[] = [station(C, [0, 0.95 * hh, 0.42 * hh]), station(C, [0, 0.5 * hh, 0.5 * hh]), station(r.lumbar, [0, 0.1 * hh, 0.52 * hh]), station(r.pelvis, [0, -0.3 * hh, 0.46 * hh]), { at: add(add(knees, mul(fwd, 0.28 * hh)), [0, 0.1 * hh, 0]), frame: r.pelvis }];+ // it covers the shirt only from the front: seen from behind it is under him, not painted over his back+ const front = faces(cam, apply(r.lumbar, [0, 0, 0.6 * hh]), fwd) > 0;+ const apron = mk("apron", "apron", sweep(cam, apSt, APRON, { hh, side: 1, n: 10, caps: [false, false] }), cam, apply(r.lumbar, [0, 0, 0.6 * hh]), front ? -0.2 * hh : 0.4 * hh, { over: front ? ["shirt", "legL", "legR"] : [] });+ // the apron's hem stitching, the waist ties, the neck strap, a pocket+ const px = project(cam, r.joints.lumbar).s * hh, w = Math.max(0.8, px * 0.012);+ const onApron = (loc: [V3, V3][]) => loc.map(([f0, l]) => P2(cam, add(f0, l)));+ const waistL = apply(r.lumbar, [0.5 * hh, 0.1 * hh, 0.3 * hh]), waistR = apply(r.lumbar, [-0.5 * hh, 0.1 * hh, 0.3 * hh]), bow = apply(r.lumbar, [-0.62 * hh, 0.02 * hh, 0.1 * hh]);+ if (faces(cam, apply(r.lumbar, [0, 0, 0.6 * hh]), fwd) > 0.05) {+ apron.marks.push({ kind: "line", pts: onApron([[waistL, [0, 0, 0]], [waistR, [0, 0, 0]]]), role: "apronDark", w: w * 2.2, alpha: 0.9 });+ apron.marks.push({ kind: "line", pts: [P2(cam, waistR), P2(cam, bow), P2(cam, add(bow, [0, -0.35 * hh, 0.05 * hh]))], role: "apronDark", w: w * 1.8, alpha: 0.85 });+ const pk = [[-0.22, -0.02], [0.22, -0.02], [0.22, -0.34], [-0.22, -0.34]].map(([x, y]) => P2(cam, apply(r.pelvis, [x * hh, y * hh, 0.5 * hh])));+ apron.marks.push({ kind: "line", pts: [...pk, pk[0]], role: "apronDark", w, alpha: 0.7 });+ // canvas hangs from the tie in long soft folds that open toward the hem+ const hemMid = add(add(knees, mul(fwd, 0.29 * hh)), [0, 0.1 * hh, 0]), side = norm(mv(r.pelvis.R, [1, 0, 0]));+ [-0.34, -0.12, 0.16, 0.38].forEach((x, i) => { const top = apply(r.pelvis, [x * 0.55 * hh, -0.2 * hh, 0.5 * hh]), bot = add(hemMid, mul(side, x * hh * (1 + 0.1 * i))); apron.marks.push({ kind: "line", pts: [0, 0.35, 0.7, 0.95].map((t) => P2(cam, add(mix3(top, bot, t), mul(side, Math.sin(t * Math.PI) * 0.02 * hh * (i % 2 ? 1 : -1))))), role: "apronDark", w: w * 0.9, alpha: 0.45 }); });+ }+ out.push(apron);+ return out;+};++// his head: the beard and moustache as volumes on the jaw, the hair short and greying at the sides+const beardParts = (r: Rig, cam: Camera, headM: (q: V3) => V3, headR: import("../../character/math3").M3): Part[] => {+ const hh = r.dims.hh, B = (c: V3, rr: V3): Blob => ({ c: headM(c), R: headR, r: mul(rr, hh) });+ // a CLOSE beard: it follows the jaw and chin, stops under the mouth, thins up the cheek to the sideburn+ const beard: BlobPart = { id: "beard", role: "beard", groups: [{ blobs: [B([0.265, 0.17, 0.03], [0.08, 0.1, 0.1]), B([-0.265, 0.17, 0.03], [0.08, 0.1, 0.1]), B([0.06, 0.035, 0.3], [0.08, 0.065, 0.09]), B([-0.06, 0.035, 0.3], [0.08, 0.065, 0.09]), B([0, 0.105, 0.31], [0.13, 0.055, 0.09]), B([0.21, 0.25, 0.15], [0.055, 0.075, 0.08]), B([-0.21, 0.25, 0.15], [0.055, 0.075, 0.08])], mode: "hull" }], over: ["head"], depthAt: headM([0, 0.25, 0.1]) };+ const stache: BlobPart = { id: "moustache", role: "beard", groups: [{ blobs: [B([-0.075, 0.245, 0.43], [0.05, 0.022, 0.03]), B([0, 0.262, 0.46], [0.045, 0.02, 0.03]), B([0.075, 0.245, 0.43], [0.05, 0.022, 0.03])], mode: "chain" }], over: ["head", "beard", "nose"], depthAt: headM([0, 0.26, 0.5]) };+ return [toPart(cam, beard), toPart(cam, stache)];+};++const FACE = { line: "line", pupil: "pupil", white: "white", blush: "blush", brow: "hair", mouth: "mouth", lip: "lip" };+export const bakerScene = (p: Pose, cam: Camera): Scene => {+ const b = build(THEO_SPEC, p, cam), r = b.rig, hh = r.dims.hh, h = b.head;+ const hidden = new Set(["torso", "hips", "upperArmL", "upperArmR", "foreArmL", "foreArmR", "thighL", "thighR", "shinL", "shinR", "footL", "footR"]);+ b.parts = b.parts.filter((q) => !hidden.has(q.id));+ const sc = assemble(cam, b, p, FACE, { character: "theo-baker", version: "2.0.0" }, (parts) => {+ const head = parts.find((q) => q.id === "head")!, out: Part[] = [...drawnBaker(r, cam), ...beardParts(r, cam, h.M, h.f.R)];+ // turned away, the beard is behind the head: it must not paint over the back of it+ if (Math.abs(viewOf(cam, h.f).yaw) > 100) out.filter((q) => q.id === "beard" || q.id === "moustache").forEach((q) => { q.over = []; q.depth = head.depth + 0.2 * hh; });+ // the mouth line and lips sit between the moustache and the beard: move them onto the moustache so they paint last+ const lipMarks = head.marks.filter((m) => m.kind !== "dot" && m.tag === "mouth");+ head.marks = head.marks.filter((m) => !lipMarks.includes(m)); out.find((q) => q.id === "moustache")!.marks.push(...lipMarks);+ const hair = hairCap(h, "hair", { front: 0.84, side: 0.58, back: 0.28, lift: 0.035, sideburn: 0.2 });+ // grey at the temples: short strokes where the sides turn toward us+ [-1, 1].forEach((s) => { const pts: P[] = [0, 1, 2, 3].map((i) => P2(cam, h.M([s * 0.37, 0.55 + i * 0.05, 0.12 - i * 0.02]))); const n = mv(h.f.R, [s, 0, 0.2]); if (faces(cam, h.M([s * 0.37, 0.6, 0.1]), n) > 0.15) hair.marks.push({ kind: "line", pts, role: "grey", w: Math.max(1, head.size * 0.03), alpha: 0.9 }); });+ out.push(hair);+ return out;+ });+ // the gesture the drawing was built on: spine, weight leg, arms+ const G = (pts: V3[]) => pts.map((v) => P2(cam, v));+ sc.gesture = [G([r.joints.crown, r.joints.head, r.joints.neck, r.joints.chest, r.joints.lumbar, r.joints.pelvis, r.joints.hipL, r.joints.kneeL, r.joints.ankleL]), G([r.joints.shoulderL, r.joints.elbowL, r.joints.wristL]), G([r.joints.shoulderR, r.joints.elbowR, r.joints.wristR]), G([r.joints.hipR, r.joints.kneeR, r.joints.ankleR])];+ return sc;+};++// ---- the pose: presenting a round loaf, weight on the left leg, head tipped toward it+export const LOAF_R = 0.1;+export const bakerPose = (yaw: number): { pose: Pose; loaf: V3 } => {+ const D = THEO_DIMS, AH = D.ankleH, T = (v: V3): V3 => mv([Math.cos((yaw * Math.PI) / 180), 0, Math.sin((yaw * Math.PI) / 180), 0, 1, 0, -Math.sin((yaw * Math.PI) / 180), 0, Math.cos((yaw * Math.PI) / 180)], v);+ // a gentle contrapposto, the spine bending back exactly as far as the pelvis tips, so the shoulders sit over the feet+ const cp = contrapposto("L", 0.55); cp.spineSide = -(cp.pelvisSide ?? 0) * 1.1;+ let p: Pose = { root: [0, D.root, 0], yaw, joints: { ...cp, spineBend: -3, neckBend: 6, headNod: 6, headTilt: 8, neckTwist: -6 }, expression: { smile: 0.7, cheek: 0.5, lidLower: 0.25, browRaise: 0.25, lookY: -0.2 }, hands: { L: "grip", R: "grip" }, plant: false };+ const feet = { L: T([0.06, AH, 0]), R: T([-0.09, AH, 0.15]) }, over = T([0.06, 0, 0.06]); // the free foot a short step forward, not out: the legs stay near plumb+ p = stand(D, p, feet, [over[0], over[2]], { R: 3 });+ const loaf = add(T([0.0, 0, 0.42]), [p.root[0], 1.12, p.root[2]]);+ for (let k = 0; k < 2; k++) {+ p = reach(D, { ...p, joints: { ...p.joints, shoulderSwingL: p.joints.shoulderSwingL ?? 75, shoulderRaiseL: p.joints.shoulderRaiseL ?? 30, elbowL: p.joints.elbowL ?? 90 } }, "L", add(loaf, T([0.12, -0.05, -0.03])));+ p = reach(D, { ...p, joints: { ...p.joints, shoulderSwingR: p.joints.shoulderSwingR ?? 75, shoulderRaiseR: p.joints.shoulderRaiseR ?? 30, elbowR: p.joints.elbowR ?? 90 } }, "R", add(loaf, T([-0.12, -0.05, -0.03])));+ p = stand(D, p, feet, [over[0], over[2]], { R: 3 }, 6);+ }+ return { pose: p, loaf };+};+// the loaf: a round boule, crust scored in a cross, flour dusted on top+export const loafPart = (cam: Camera, at: V3): Part => {+ const b: BlobPart = { id: "loaf", role: "crust", groups: [{ blobs: [{ c: at, R: I3, r: [LOAF_R * 1.12, LOAF_R * 0.72, LOAF_R * 1.05] }], mode: "each" }], depthAt: add(at, [0, 0, -0.02]) };+ const part = toPart(cam, b), marks: Mark[] = [], s = project(cam, at).s;+ [[-1, 1], [1, 1]].forEach(([a, c]) => marks.push({ kind: "line", pts: [-0.7, -0.35, 0, 0.35, 0.7].map((t) => P2(cam, add(at, [t * LOAF_R * a * 0.8, LOAF_R * 0.66 * Math.sqrt(1 - t * t * 0.6), t * LOAF_R * c * 0.8 + 0.01]))), role: "crustDark", w: Math.max(1.2, s * 0.012), alpha: 0.9 }));+ for (let i = 0; i < 26; i++) { const a = i * 2.39996, rr = Math.sqrt(i / 26) * LOAF_R * 0.7; marks.push({ kind: "dot", at: P2(cam, add(at, [Math.cos(a) * rr, LOAF_R * 0.7, Math.sin(a) * rr])), rx: 1.2, ry: 1.2, rot: 0, role: "flour", alpha: 0.9 }); }+ part.marks = marks; return part;+};++export const theoBaker: Character = {+ id: "theo-baker", name: "Theo the baker", version: "2.0.0", canonId: "adult",+ description: "Baker in his forties, 7.5 heads, 1.78 m: close beard, short hair greying at the temples, white shirt with rolled sleeves, canvas apron, dark trousers, brown boots.",+ roles: {+ skin: { family: "warm skin", hue: [10, 40], note: "" }, shirt: { family: "white", hue: [0, 360], note: "" }, apron: { family: "canvas ochre", hue: [30, 55], note: "" },+ trousers: { family: "warm dark grey", hue: [0, 60], note: "" }, boots: { family: "brown", hue: [15, 35], note: "" }, hair: { family: "dark brown", hue: [0, 40], note: "" },+ },+ features: [{ id: "beard", parts: ["beard", "moustache"], note: "close beard and moustache", visible: (y) => Math.abs(y) < 150 }, { id: "apron", parts: ["apron"], note: "canvas apron", visible: (y) => Math.abs(y) < 100 }],+ pose: (p: Pose) => { checkPose(p, "theo-baker"); return p; },+ toScene: (p: Pose, cam: Camera) => bakerScene(p, cam),+};+export { rigFor };diff --git a/engine/src/canvas-core/characters/theo/index.ts b/engine/src/canvas-core/characters/theo/index.tsnew file mode 100644index 0000000..b5d2e34--- /dev/null+++ b/engine/src/canvas-core/characters/theo/index.ts@@ -0,0 +1,83 @@+// THEO, the realistic-canon adult (7.5 heads, 1.78 m). He exists to prove the human rig on the+// hard cases (turning, reaching, sitting, gripping, a hand pointed at the lens), so he wears as+// little as a figure-class model would: a T-shirt, shorts to just above the knee and plimsolls, which leave+// shoulders, elbows, knees, calves and hands to be judged.+import type { Camera } from "../../character/math3";+import type { Character, Pose, Scene } from "../../character/types";+import { CANON } from "../../character/human/canon";+import { ADULT_BODY } from "../../character/human/mannequin";+import { ADULT_HEAD, type Ell, type HeadCtx, hairCap } from "../../character/human/head";+import { blouse, elbowMarks, kneeMarks, neckMarks, neckline, shorts, softSleeve } from "./wardrobe";+import type { P } from "../../core";+import type { Mark } from "../../character/types";+import { dot, mv, norm, project, sub } from "../../character/math3";+import { type FigureSpec, assemble, build, checkPose } from "../../character/human/figure";+import { trouserLeg } from "../../character/human/clothing";+import { SIDES } from "../../character/human/skeleton";+import type { Palette } from "../../character/render/storybook";++export const THEO_SPEC: FigureSpec = {+ canon: CANON.adult, height: 1.78, body: ADULT_BODY, head: ADULT_HEAD,+ roles: { skin: "skin", torso: "shirt", hips: "shirt", foot: "shoe" },+ inflate: { torso: 0.025, hips: 0.035, foot: 0.03 },+};+export const THEO_PALETTE: Palette = {+ skin: { base: "#e9b996", shade: "#c98e72" }, shirt: { base: "#d9dfe6", shade: "#a9b4c2" }, shorts: { base: "#5e7fa8", shade: "#3f5a80" },+ shoe: { base: "#f2efe8", shade: "#bdb6aa" }, hair: { base: "#4a3a33", shade: "#2f2521" }, hairLine: { base: "#2a201c", shade: "#1c1512" }, pupil: { base: "#5b4636", shade: "#3a2c22" },+ white: { base: "#fffaf3", shade: "#e8e0d4" }, blush: { base: "#e39a8e", shade: "#c77c70" }, mouth: { base: "#6e3434", shade: "#4d2222" }, lip: { base: "#c46e6a", shade: "#a0524e" },+ nail: { base: "#f6dccb", shade: "#e2b9a4" }, cup: { base: "#e9eff4", shade: "#9fb0c0" }, coffee: { base: "#6b4430", shade: "#4b2e20" }, stool: { base: "#c9955e", shade: "#94683d" },+};+// HIS HAIR: short at the back and sides with sideburns, longer on top, parted on his left and+// swept up and over to his right in a soft quiff. The volume is three masses above the cap; the+// strands are drawn ON the cap's surface in the direction the hair grows, so they turn with him.+export const QUIFF: Ell[] = [+ { c: [-0.02, 0.96, 0.17], r: [0.33, 0.1, 0.24] },+];+const STRANDS: [number, number][][] = [+ ...[0.3, 0.2, 0.1, 0.0, -0.1, -0.2].map((z) => [[0.15, z - 0.02], [0.05, z + 0.03], [-0.08, z + 0.07], [-0.22, z + 0.05]] as [number, number][]), // from the part, over to his right+ ...[0.28, 0.14].map((z) => [[0.16, z], [0.26, z - 0.02], [0.33, z - 0.06]] as [number, number][]), // the short side of the part+ [[0.15, 0.36], [0.15, 0.1], [0.15, -0.15], [0.14, -0.32]], // the part itself+];+const hairStrands = (h: HeadCtx, cam: Camera): Mark[] => {+ const c = h.spec.skull[0], R = [c.r[0] + 0.045, c.r[1] + 0.045, c.r[2] + 0.045], px = project(cam, h.M(c.c)).s * h.hh, w = Math.max(0.7, px * 0.009), out: Mark[] = [];+ STRANDS.forEach((st, i) => {+ let cur: P[] = []; const flush = () => { if (cur.length > 1) out.push({ kind: "line", pts: cur, role: i === STRANDS.length - 1 ? "line" : "hairLine", w: i === STRANDS.length - 1 ? w * 0.9 : w, alpha: i === STRANDS.length - 1 ? 0.55 : 0.7 }); cur = []; };+ st.forEach(([x, z]) => {+ const u = x / R[0], v = z / R[2], y = c.c[1] + R[1] * Math.sqrt(Math.max(0, 1 - u * u - v * v)) + 0.012, q = h.M([x, y, c.c[2] + z]), n = norm(mv(h.f.R, [u / R[0], (y - c.c[1]) / R[1] / R[1], v / R[2]]));+ if (dot(n, norm(sub(cam.eye, q))) > 0.12) { const p = project(cam, q); cur.push([p.x, p.y]); } else flush();+ });+ flush();+ });+ return out;+};+const FACE = { line: "line", pupil: "pupil", white: "white", blush: "blush", brow: "hair", mouth: "mouth", lip: "lip" };++export const theo: Character = {+ id: "theo", name: "Theo", version: "1.0.0", canonId: "adult",+ description: "Adult figure model, 7.5 heads, 1.78 m: short dark hair, athletic build, grey vest, blue shorts, white plimsolls.",+ roles: {+ skin: { family: "warm skin", hue: [10, 40], note: "one warm skin tone" }, shirt: { family: "cool grey", hue: [190, 230], note: "" },+ shorts: { family: "blue", hue: [200, 230], note: "" }, shoe: { family: "off-white", hue: [20, 60], note: "" }, hair: { family: "dark brown", hue: [0, 40], note: "" },+ },+ features: [{ id: "shortHair", parts: ["hair"], note: "cropped dark hair", visible: () => true }],+ pose: (p: Pose) => { checkPose(p, "theo"); return p; },+ toScene: (p: Pose, cam: Camera): Scene => {+ const b = build(THEO_SPEC, p, cam), r = b.rig, B = THEO_SPEC.body;+ // the shirt: the body's torso and hips in shirt colour, blousing over the band of the shorts+ const bl = blouse(r, { role: "shirt", ease: 0.03 }), torso = b.parts.find((q) => q.id === "torso")!;+ torso.groups.push({ blobs: [bl.ring], mode: "each" }); torso.marksFn = bl.marksFn;+ SIDES.forEach((s) => {+ b.parts.push(softSleeve(r, B, s, { role: "shirt", len: 0.46, ease: 0.03 }), trouserLeg(r, B, s, { role: "shorts", to: 0.72, inflate: 0.045, flare: 0.02 }));+ const shin = b.parts.find((q) => q.id === "shin" + s)!, fore = b.parts.find((q) => q.id === "foreArm" + s)!;+ shin.marksFn = (c) => kneeMarks(r, s, c); fore.marksFn = (c) => elbowMarks(r, s, c);+ });+ b.parts.push(shorts(r, B, { role: "shorts", ease: 0.04 }));+ const neck = b.parts.find((q) => q.id === "neck")!; neck.marksFn = (c) => neckMarks(r, b.head.M, c);+ return assemble(cam, b, p, FACE, { character: "theo", version: "1.1.0" }, () => {+ const out = [hairCap(b.head, "hair", { front: 0.86, side: 0.6, back: 0.28, lift: 0.04, sideburn: 0.14, volume: QUIFF })];+ out[0].marks.push(...hairStrands(b.head, cam));+ const nl = neckline(r, cam, { skin: "skin", spec: B, ease: 0.025 }); if (nl) out.push(nl);+ return out;+ });+ },+};diff --git a/engine/src/canvas-core/characters/theo/poses.ts b/engine/src/canvas-core/characters/theo/poses.tsnew file mode 100644index 0000000..787d6f3--- /dev/null+++ b/engine/src/canvas-core/characters/theo/poses.ts@@ -0,0 +1,136 @@+// THEO'S POSES, built the way a figure-drawing teacher builds them: feet placed, legs solved,+// weight carried over the support, arms sent to a target. Nothing here is a hand-typed pile of+// angles where contact matters (a foot on the floor, a hand on a hip, fingers round a mug).+//+// Reference opened, per pose: contrapposto: Polykleitos' Doryphoros (Naples copy) and Loomis+// "Figure Drawing" p. 64 (the pelvis and shoulder lines tilting against each other); reaching:+// Hogarth "Dynamic Anatomy" p. 134 (the lengthened side, the ribcage lifting off the pelvis);+// sitting: Loomis p. 113 (thighs foreshorten, the pelvis rolls back on the sit bones); gripping:+// Hogarth "Drawing Dynamic Hands" pp. 70-75 (cylinder grip: four fingers stacked round the form,+// the thumb opposite); pointing at the lens: Hogarth "Dynamic Figure Drawing" ch. 3 (the hand+// overlaps and dwarfs the arm behind it).+import { Blob, Camera, DEG, I3, MIRROR_X, V3, add, apply, dist, mul, mv, norm, sub } from "../../character/math3";+import { order, toPart, type BlobPart } from "../../character/build";+import type { Pose, Scene } from "../../character/types";+import { dimsFromCanon, fk, type Rig } from "../../character/human/skeleton";+import { contrapposto, reach, stand } from "../../character/human/balance";+import { DIGITS, type HandAngles, HAND_POSES, handModel, handViolations } from "../../character/human/hands";+import { THEO_SPEC } from "./index";+import { rigFor } from "../../character/human/figure";+import type { Mark } from "../../character/types";+import type { P } from "../../core";+import { project } from "../../character/math3";++export const THEO_DIMS = dimsFromCanon(THEO_SPEC.canon, THEO_SPEC.height);+const D = THEO_DIMS, hh = D.hh, AH = D.ankleH;+const base = (yaw = 0, j: Record<string, number> = {}, ex: Record<string, number> = {}): Pose => ({ root: [0, D.root, 0], yaw, joints: { shoulderRaiseL: 7, shoulderRaiseR: 7, shoulderSwingL: 15, shoulderSwingR: 15, elbowL: 12, elbowR: 12, ...j }, expression: ex, hands: { L: "relaxed", R: "relaxed" }, plant: true });++// the turnaround stance: feet under the hips, weight even, arms easy+export const relaxed = (yaw: number): Pose => base(yaw);++// Contrapposto, weight on her LEFT leg (world +x at yaw 0): the free right foot steps forward and+// out, the pelvis drops on the right, the shoulders tilt the other way; right hand on the hip.+export const contra = (yaw: number): Pose => {+ const turn = (v: V3): V3 => mv([Math.cos(yaw * DEG), 0, Math.sin(yaw * DEG), 0, 1, 0, -Math.sin(yaw * DEG), 0, Math.cos(yaw * DEG)], v);+ let p = base(yaw, { ...contrapposto("L", 1), shoulderRaiseL: 9, elbowL: 16 }, { smile: 0.2, lookX: -0.2 });+ const feet = { L: turn([0.06, AH, 0.0]), R: turn([-0.14, AH, 0.12]) }; // weight foot near the midline, free foot out and forward+ const over = turn([0.06, 0, 0.055]); // the middle of the weight foot, heel to ball+ p = stand(D, p, feet, [over[0], over[2]], { R: 4 });+ // hand on the hip: the wrist to the side of the pelvis, elbow out+ // the arm swings out to the side and a touch back (swing held at -12), so the elbow points OUT+ const r = fk(D, p), hip = apply(r.pelvis, [-0.76 * hh, 0.24 * hh, -0.02 * hh]);+ p = reach(D, { ...p, joints: { ...p.joints, shoulderSwingR: -12, shoulderRaiseR: 40, elbowR: 95, wristFlexR: 10, pronationR: 40, shoulderTwistR: 20 } }, "R", hip, { shoulderSwingR: -12 });+ return { ...p, hands: { L: "relaxed", R: { relaxed: 0.4, open: 0.6 } } };+};++// Reaching up to a high shelf with the right hand, weight rolling onto the balls of the feet.+export const reachUp = (yaw: number): Pose => {+ const turn = (v: V3): V3 => mv([Math.cos(yaw * DEG), 0, Math.sin(yaw * DEG), 0, 1, 0, -Math.sin(yaw * DEG), 0, Math.cos(yaw * DEG)], v);+ let p = base(yaw, { spineSide: 8, spineBend: -6, neckBend: -14, headNod: -16, shoulderRaiseL: 14, elbowL: 20, clavLiftR: 22, toeL: 18, toeR: 18 }, { browRaise: 0.3, lookY: 0.8 });+ p = { ...p, root: [p.root[0], p.root[1] + 0.05, p.root[2]] }; // up on the toes: the toes bend flat to the floor, the heels lift+ const feet = { L: turn([0.13, AH + 0.04, 0.02]), R: turn([-0.12, AH + 0.04, -0.02]) };+ const fw = turn([0, 0, 0.165]); // over the balls of the feet, where the weight goes when the heels lift+ p = stand(D, p, feet, [(feet.L[0] + feet.R[0]) / 2 + fw[0], (feet.L[2] + feet.R[2]) / 2 + fw[2]], { L: -18, R: -18 });+ const target = turn([-0.18, 2.13, 0.2]);+ p = reach(D, { ...p, joints: { ...p.joints, shoulderRaiseR: 160, shoulderSwingR: 60, elbowR: 15 } }, "R", target);+ return { ...p, hands: { L: "relaxed", R: "open" } };+};++// Sitting on a stool: sit bones on the seat, thighs forward, feet flat, forearms on the thighs.+export const STOOL_H = 0.5;+export const sit = (yaw: number): Pose => {+ const turn = (v: V3): V3 => mv([Math.cos(yaw * DEG), 0, Math.sin(yaw * DEG), 0, 1, 0, -Math.sin(yaw * DEG), 0, Math.cos(yaw * DEG)], v);+ let p: Pose = { ...base(yaw, { pelvisTilt: -8, spineBend: 16, neckBend: 4, headNod: -8 }, { smile: 0.35 }), root: turn([0, STOOL_H + 0.11, -0.02]), plant: false };+ const feet = { L: turn([0.16, AH, 0.44]), R: turn([-0.15, AH, 0.5]) };+ p = stand(D, p, feet, null, {}, 1);+ const r = fk(D, p);+ p = reach(D, p, "L", add(r.joints.kneeL, turn([-0.02, 0.08, -0.08])));+ p = reach(D, p, "R", add(r.joints.kneeR, turn([0.03, 0.09, -0.1])));+ return { ...p, hands: { L: "relaxed", R: { relaxed: 0.6, open: 0.4 } } };+};+export const stool = (yaw: number): BlobPart[] => {+ const turn = (v: V3): V3 => mv([Math.cos(yaw * DEG), 0, Math.sin(yaw * DEG), 0, 1, 0, -Math.sin(yaw * DEG), 0, Math.cos(yaw * DEG)], v), s = STOOL_H;+ const seat: Blob = { c: turn([0, s - 0.03, -0.03]), R: I3, r: [0.19, 0.03, 0.19] };+ const legs: BlobPart[] = [0, 1, 2].map((i) => { const a = (i / 3) * Math.PI * 2 + 0.5, top = turn([Math.cos(a) * 0.12, s - 0.05, -0.03 + Math.sin(a) * 0.12]), foot = turn([Math.cos(a) * 0.2, 0.012, -0.03 + Math.sin(a) * 0.2]); return { id: `stoolLeg${i}`, role: "stool", groups: [{ blobs: [{ c: top, R: I3, r: [0.018, 0.018, 0.018] }, { c: foot, R: I3, r: [0.015, 0.015, 0.015] }], mode: "chain" }] }; });+ return [{ id: "stoolSeat", role: "stool", groups: [{ blobs: [seat], mode: "each" }], depthBias: 0.02 }, ...legs];+};++// Holding a mug in front of the chest. The fingers are SOLVED onto the cylinder: every+// joint and fingertip pulled to the mug's surface, none allowed inside it.+export const MUG_R = 0.042, MUG_H = 0.1;+export const mugFrame = (r: Rig) => { const f = r.hand.R, Lh = D.hand, c = apply(f, mv(MIRROR_X, [-(0.075 * Lh + MUG_R), -0.45 * Lh, 0.02 * Lh])), axis = norm(mv(f.R, [0, 0, 1])); return { c, axis }; };+export const holdCup = (): Pose => {+ let p: Pose = base(-20, { shoulderRaiseR: 22, shoulderSwingR: 75, elbowR: 112, shoulderTwistR: -18, wristFlexR: 8, wristDevR: 6, pronationR: 4, neckBend: 10, headNod: 8 }, { smile: 0.45, cheek: 0.3, lookX: 0.5, lookY: -0.6 });+ const r = rigFor(THEO_SPEC, p), { c, axis } = mugFrame(r);+ const fingers = gripCylinder(r, c, axis, MUG_R);+ return { ...p, hands: { L: "relaxed", R: { angles: fingers } } };+};+// the mug: a cylinder with a rim, coffee in it when we can see in, and a handle on the far side+export const mug = (p: Pose): BlobPart[] => {+ const r = rigFor(THEO_SPEC, p), { c, axis: up } = mugFrame(r), palm = norm(sub(c, r.joints.wristR));+ const out = norm(sub(palm, mul(up, dot3(palm, up)))); // from the palm through the mug, square to its axis+ const bot = add(c, mul(up, -MUG_H * 0.55)), top = add(c, mul(up, MUG_H * 0.45));+ const disc = (at: V3, rad: number): Blob => ({ c: at, R: frameFromUp(up), r: [rad, 0.003, rad] });+ const handle: Blob[] = Array.from({ length: 6 }, (_, i) => { const a = -Math.PI / 2 + (i / 5) * Math.PI; return { c: add(add(c, mul(up, Math.sin(a) * MUG_H * 0.3)), mul(out, MUG_R + Math.cos(a) * MUG_H * 0.22)), R: I3, r: [0.008, 0.008, 0.008] }; });+ const rimMarks = (cam: Camera): Mark[] => {+ const side = norm(cross3(up, out)), ring = Array.from({ length: 20 }, (_, i) => { const a = (i / 20) * Math.PI * 2, q = project(cam, add(top, add(mul(out, Math.cos(a) * MUG_R), mul(side, Math.sin(a) * MUG_R)))); return [q.x, q.y] as P; });+ const seeIn = dot3(up, norm(sub(cam.eye, top))) > 0.05, m: Mark[] = [];+ if (seeIn) { m.push({ kind: "fill", pts: ring, role: "coffee", line: 1.4 }); }+ return m;+ };+ return [+ { id: "mug", role: "cup", groups: [{ blobs: [disc(bot, MUG_R), disc(top, MUG_R * 1.03)], mode: "chain" }], depthAt: c, marksFn: rimMarks },+ { id: "mugHandle", role: "cup", groups: [{ blobs: handle, mode: "chain" }], depthAt: add(c, mul(out, MUG_R + 0.02)) },+ ];+};+const dot3 = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const cross3 = (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]];+const frameFromUp = (up: V3) => { const x = norm(cross3(up, Math.abs(up[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0])), z = cross3(x, up); return [x[0], up[0], z[0], x[1], up[1], z[1], x[2], up[2], z[2]] as import("../../character/math3").M3; };++// finger angles that wrap a cylinder (centre c, axis a, radius R): coordinate descent, deterministic+export const gripCylinder = (r: Rig, c: V3, a: V3, R: number): HandAngles => {+ const ang: HandAngles = JSON.parse(JSON.stringify(HAND_POSES.grip));+ const radial = (p: V3) => { const v = sub(p, c), t = v[0] * a[0] + v[1] * a[1] + v[2] * a[2]; return dist(v, mul(a, t)); };+ const cost = (h: HandAngles) => {+ const hm = handModel(r.hand.R, "R", D.hand, h); let e = 0;+ hm.digits.forEach((d) => d.pts.slice(1).forEach((p, i) => { const gap = radial(p) - (R + d.radii[i + 1] * 0.9); e += gap < 0 ? gap * gap * 40 : gap * gap * (i === 2 ? 3 : 1); }));+ return e + handViolations(h, "").length * 10;+ };+ let e = cost(ang), step = 8;+ for (let it = 0; it < 40 && step > 0.25; it++) {+ let imp = false;+ for (const d of DIGITS) for (let i = 1; i < 4; i++) for (const s of [1, -1]) { const t: HandAngles = JSON.parse(JSON.stringify(ang)); t[d][i] += s * step; const et = cost(t); if (et < e) { e = et; Object.assign(ang, t); imp = true; } }+ if (!imp) step *= 0.5;+ }+ return ang;+};++// Pointing straight at the lens: the right arm raised forward, the index finger toward the camera.+export const pointAtCamera = (target: V3): Pose => {+ let p: Pose = base(-8, { shoulderRaiseR: 86, shoulderSwingR: 86, elbowR: 8, pronationR: 55, wristDevR: -4, spineTwist: 12, neckTwist: 10, headTurn: 6, shoulderRaiseL: 10, elbowL: 18 }, { browFurrow: 0.35, smile: 0.3, lookX: 0.3 });+ p = reach(D, p, "R", sub(target, [0, 0, 0.001]), { elbowR: 8 });+ return { ...p, hands: { L: "relaxed", R: "point" } };+};++export const withProps = (s: Scene, cam: Camera, props: BlobPart[]): Scene => ({ ...s, parts: order([...s.parts, ...props.map((b) => toPart(cam, b))]) });+diff --git a/engine/src/canvas-core/characters/theo/wardrobe.ts b/engine/src/canvas-core/characters/theo/wardrobe.tsnew file mode 100644index 0000000..09b3f1b--- /dev/null+++ b/engine/src/canvas-core/characters/theo/wardrobe.ts@@ -0,0 +1,131 @@+// THEO'S CLOTHES AND SURFACE ANATOMY. Garments hang from the body with gravity and meet it at+// seams; the skin shows its landmarks where a figure-drawing teacher would point at them.+//+// Reference opened: Hogarth "Dynamic Wrinkles and Drapery" (1992): the sleeve hangs from the+// shoulder seam, pipes into a tube and breaks into a diagonal fold at the armpit; the tucked+// shirt blouses over the waistband in soft U-folds. Bammes "The Complete Guide to Anatomy for+// Artists": the sternocleidomastoid V into the pit of the neck, the S of the clavicle, the+// kneecap sitting ON the joint with the tendon running down to the shin's tuberosity.+import type { P } from "../../core";+import { Blob, Camera, Frame, M3, V3, add, apply, cross, dot, mul, mv, norm, project, sub } from "../../character/math3";+import type { BlobPart } from "../../character/build";+import type { Mark, Part } from "../../character/types";+import { type Rig, type Side, SIDES, sgn } from "../../character/human/skeleton";+import { type BodySpec, blob } from "../../character/human/mannequin";+import { cutChain } from "../../character/human/clothing";++// A line ON a body surface: points in a frame (head units), each seen or not by the outward normal+// (away from an axis through `axis`, horizontal in that frame). Returns the visible runs, screen px.+export const surfaceRuns = (r: Rig, cam: Camera, f: Frame, pts: V3[], o: { axis?: V3; min?: number; normal?: V3 } = {}): P[][] => {+ const hh = r.dims.hh, ax = o.axis ?? [0, 0, 0], out: P[][] = []; let cur: P[] = [];+ pts.forEach((l) => {+ const w = apply(f, mul(l, hh)), nl: V3 = o.normal ?? [l[0] - ax[0], 0, l[2] - ax[2]], n = norm(mv(f.R, nl)), vis = dot(n, norm(sub(cam.eye, w))) > (o.min ?? 0.08);+ if (vis) { const q = project(cam, w); cur.push([q.x, q.y]); } else { if (cur.length > 1) out.push(cur); cur = []; }+ });+ if (cur.length > 1) out.push(cur);+ return out;+};+const lines = (runs: P[][], role: string, w: number, alpha = 0.8): Mark[] => runs.map((pts) => ({ kind: "line", pts, role, w, alpha }));+const frameFrom = (y: V3, hintZ: V3): M3 => { const Y = norm(y), X = norm(cross(Y, hintZ)), Z = cross(X, Y); return [X[0], Y[0], Z[0], X[1], Y[1], Z[1], X[2], Y[2], Z[2]]; };++// ---- the sleeve: a soft tube hung from the shoulder seam (never above the shoulder line),+// narrowing to its hem; when the arm lifts, the hem ring tips toward the floor and the underside sags+export const softSleeve = (r: Rig, spec: BodySpec, s: Side, o: { role: string; len: number; ease: number }): BlobPart => {+ const hh = r.dims.hh, k = sgn(s), U = r.upper[s], down: V3 = [0, -1, 0], bone = norm(mv(U.R, [0, -1, 0])), level = 1 - Math.abs(dot(bone, down));+ const seam: Blob = { c: apply(U, [-k * 0.07 * hh, -0.02 * hh, 0]), R: U.R, r: [0.15 * hh, 0.06 * hh, 0.2 * hh] }; // the seam sits ON the shoulder, never proud of it+ const arm = spec.upperArm.map((b) => blob(r, b, s, o.ease)), mid = cutChain(arm, 0.5).pop()!;+ const hemAt = add(apply(U, [0, -o.len * r.dims.upperArm, 0.01 * hh]), mul(down, 0.035 * hh * level)); // the underside sags as the arm lifts+ const hemR = frameFrom(add(bone, mul(down, 0.6 * level)), mv(U.R, [0, 0, 1]));+ const hem: Blob = { c: hemAt, R: hemR, r: [(0.2 + o.ease * 0.6) * hh, 0.02 * hh, (0.21 + o.ease * 0.6) * hh] };+ const marksFn = (cam: Camera): Mark[] => {+ const px = project(cam, U.p).s * hh, w = Math.max(0.8, px * 0.012);+ // the armpit fold: a diagonal from the pit onto the sleeve's front, and a shorter echo+ const f1 = surfaceRuns(r, cam, U, [[-k * 0.1, -0.1, 0.22], [-k * 0.04, -0.22, 0.25], [k * 0.04, -0.34, 0.25]], { min: 0.15 });+ const f2 = surfaceRuns(r, cam, U, [[-k * 0.13, -0.3, 0.18], [-k * 0.07, -0.42, 0.22]], { min: 0.15 });+ // the hem's stitching, just above the edge+ const ring = Array.from({ length: 19 }, (_, i) => { const a = (i / 18) * Math.PI * 2; return add(hemAt, mv(hemR, [Math.cos(a) * hem.r[0] * 0.98, 0.045 * hh, Math.sin(a) * hem.r[2] * 0.98])); });+ const vis = ring.map((q) => ({ q, v: dot(norm(sub(q, hemAt)), norm(sub(cam.eye, q))) > 0.05 }));+ const runs: P[][] = []; let cur: P[] = []; vis.forEach(({ q, v }) => { if (v) { const p = project(cam, q); cur.push([p.x, p.y]); } else { if (cur.length > 1) runs.push(cur); cur = []; } }); if (cur.length > 1) runs.push(cur);+ return [...lines(f1, "line", w, 0.55), ...lines(f2, "line", w * 0.8, 0.4), ...lines(runs, "line", w * 0.7, 0.35)];+ };+ return { id: "sleeve" + s, role: o.role, groups: [{ blobs: [seam, mid, hem], mode: "chain" }], over: ["upperArm" + s], seams: [{ at: apply(U, [-k * 0.05 * hh, 0.02 * hh, 0]), r: 0.3 * hh, with: "torso" }], depthBias: -0.065 * hh, marksFn };+};++// ---- the shorts: a waistband at the navel, the seat, a fly, pockets; the shirt tucks in under the band+export const shorts = (r: Rig, spec: BodySpec, o: { role: string; ease: number }): BlobPart => {+ const hh = r.dims.hh, band: Blob = blob(r, ["lumbar", [0, -0.05, 0.03], [0.5, 0.06, 0.36]], "L", o.ease);+ const seat = blob(r, spec.hips[1], "L", o.ease), sided = SIDES.flatMap((s) => spec.hipsSided.map((b) => blob(r, b, s, o.ease)));+ const marksFn = (cam: Camera): Mark[] => {+ const px = project(cam, r.joints.pelvis).s * hh, w = Math.max(0.8, px * 0.012), e = o.ease;+ const ring = (y: number, rx: number, rz: number) => Array.from({ length: 25 }, (_, i) => { const a = (i / 24) * Math.PI * 2; return [Math.sin(a) * (rx + e), y, 0.03 + Math.cos(a) * (rz + e)] as V3; });+ const L = r.lumbar, Pl = r.pelvis;+ const m: Mark[] = [...lines(surfaceRuns(r, cam, L, ring(-0.105, 0.5, 0.36), { axis: [0, 0, 0.03] }), "line", w * 1.1, 0.7)];+ // the fly: straight down from the band, hooking toward the crotch+ m.push(...lines(surfaceRuns(r, cam, Pl, [[0.03, -0.02, 0.41 + e], [0.035, -0.14, 0.41 + e], [0.03, -0.25, 0.38 + e], [-0.02, -0.31, 0.33 + e]], { min: 0.2 }), "line", w, 0.75));+ // slanted front pockets and belt loops+ SIDES.forEach((s) => { const k = sgn(s); m.push(...lines(surfaceRuns(r, cam, Pl, [[k * 0.22, -0.02, 0.37 + e], [k * 0.36, -0.14, 0.3 + e], [k * 0.44, -0.22, 0.2 + e]], { min: 0.15 }), "line", w * 0.9, 0.6)); [0.3, 0.52].forEach((x) => m.push(...lines(surfaceRuns(r, cam, L, [[k * x, -0.01, Math.sqrt(Math.max(0, 1 - (x / 0.55) ** 2)) * 0.4 + 0.03 + e], [k * x, -0.1, Math.sqrt(Math.max(0, 1 - (x / 0.55) ** 2)) * 0.4 + 0.03 + e]], { min: 0.15, axis: [0, 0, 0.03] }), "line", w * 1.2, 0.6))); });+ return m;+ };+ return { id: "shorts", role: o.role, groups: [{ blobs: [band, seat], mode: "chain" }, { blobs: sided, mode: "each" }], over: ["hips", "torso"], depthAt: r.joints.pelvis, marksFn };+};++// ---- the shirt, tucked: it blouses over the band in soft folds, and a scoop neck shows the+// pit of the neck, the heads of the collarbones and the V of the neck muscles+export const blouse = (r: Rig, o: { role: string; ease: number }): { ring: Blob; marksFn: (cam: Camera) => Mark[] } => {+ const hh = r.dims.hh, ring = blob(r, ["lumbar", [0, 0.06, 0.035], [0.53, 0.07, 0.38]], "L", o.ease);+ const marksFn = (cam: Camera): Mark[] => {+ const px = project(cam, r.joints.lumbar).s * hh, w = Math.max(0.8, px * 0.011), e = o.ease, L = r.lumbar;+ const m: Mark[] = [];+ // U-folds where the fabric bags over the band+ [-0.3, -0.08, 0.16, 0.34].forEach((x, i) => { const z = (xx: number) => Math.sqrt(Math.max(0, 1 - (xx / 0.56) ** 2)) * 0.41 + 0.035 + e; m.push(...lines(surfaceRuns(r, cam, L, [[x - 0.05, 0.1 + (i % 2) * 0.02, z(x - 0.05)], [x, 0.03, z(x)], [x + 0.06, 0.09, z(x + 0.06)]], { min: 0.2, axis: [0, 0, 0.035] }), "line", w, 0.5)); });+ return m;+ };+ return { ring, marksFn };+};+export const neckline = (r: Rig, cam: Camera, o: { skin: string; spec: BodySpec; ease: number }): Part | null => {+ // the FRONT surface of the shirt at (x, y) in the chest frame: the largest z over every chest-frame volume+ const vols = [...o.spec.torso.filter((b) => b[0] === "chest"), ...o.spec.torsoSided.flatMap((b) => (b[0] === "chest" ? [b, ["chest", [-b[1][0], b[1][1], b[1][2]], b[2]] as typeof b] : []))];+ const front = (x: number, y: number) => vols.reduce((z, [, c, rr]) => { const u = (x - c[0]) / (rr[0] + o.ease), v = (y - c[1]) / (rr[1] + o.ease * 0.6), q = 1 - u * u - v * v; return q > 0 ? Math.max(z, c[2] + (rr[2] + o.ease) * Math.sqrt(q)) : z; }, -1);+ const hh = r.dims.hh, C = r.chest;+ // the scoop: from the back of the neck round the trapezius and down in front to a little below the pit+ // the front half of the scoop only: its back half runs behind the neck and is never seen from the front+ const loop: V3[] = Array.from({ length: 17 }, (_, i) => { const a = (-Math.PI / 2 + (i / 16) * Math.PI) * 0.8, fr = Math.max(0, Math.cos(a)), x = Math.sin(a) * 0.25, y = 1.21 - 0.13 * fr ** 2.2; return [x, y, Math.max(front(x, y), 0.02 + Math.cos(a) * 0.2) + 0.004] as V3; });+ // closed along the base of the neck (its front half), not a straight chord: the scoop's upper edge IS the neck+ const neckArc: V3[] = Array.from({ length: 9 }, (_, i) => { const a = (Math.PI / 2 - (i / 8) * Math.PI) * 0.8; return [Math.sin(a) * 0.21, 1.27, -0.08 + Math.cos(a) * 0.22] as V3; });+ const pts = [...loop, ...neckArc].map((l) => { const q = project(cam, apply(C, mul(l, hh))); return [q.x, q.y] as P; });+ const facing = dot(norm(mv(C.R, [0, 0, 1])), norm(sub(cam.eye, C.p)));+ if (facing < 0.25) return null;+ const px = project(cam, C.p).s * hh, w = Math.max(0.8, px * 0.012), marks: Mark[] = [];+ // the collarbones' inner ends, running out from the pit under the neckline, a gentle S+ SIDES.forEach((s) => { const k = sgn(s); marks.push(...lines(surfaceRuns(r, cam, C, [[k * 0.05, 1.12, 0.36], [k * 0.12, 1.135, 0.35], [k * 0.19, 1.15, 0.32], [k * 0.24, 1.17, 0.29]], { min: 0.25, normal: [0, 0.3, 1] }), "line", w, 0.55)); });+ marks.push(...lines(surfaceRuns(r, cam, C, [[-0.03, 1.13, 0.37], [0, 1.105, 0.375], [0.03, 1.13, 0.37]], { min: 0.25, normal: [0, 0.3, 1] }), "line", w * 0.9, 0.5));+ const arc2 = pts.slice(loop.length), nearArc = (p: P) => arc2.some((q, i) => i > 0 && segD(p, arc2[i - 1], q) < 3);+ return { id: "neckSkin", role: o.skin, depth: project(cam, apply(C, [0, 1.15 * hh, 0.35 * hh])).z, polys: [pts], size: px * 0.04, marks, outline: true, keepLine: (p) => !nearArc(p), clipTo: "torso", over: ["torso", "neck", "sleeveL", "sleeveR"] };+};++const segD = (p: P, a: P, b: P) => { const dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy || 1, t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2)); return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy); };++// ---- surface anatomy on the skin+export const neckMarks = (r: Rig, headPt: (q: V3) => V3, cam: Camera): Mark[] => {+ const hh = r.dims.hh, px = project(cam, r.joints.neck).s * hh, w = Math.max(0.8, px * 0.011), m: Mark[] = [];+ // sternocleidomastoid: from behind the ear, down and forward to the pit of the neck: the neck's V+ SIDES.forEach((s) => {+ const k = sgn(s), a = headPt([k * 0.3, 0.34, -0.06]), b = apply(r.neck, [k * 0.035 * hh, 0.02 * hh, 0.2 * hh]), mid = add(mul(add(a, b), 0.5), mv(r.neck.R, [k * 0.04 * hh, 0, 0.06 * hh]));+ const pts = [a, mid, b].map((q) => q), n = norm(mv(r.neck.R, [k * 0.6, 0, 0.8]));+ if (dot(n, norm(sub(cam.eye, mid))) > 0.1) m.push({ kind: "line", pts: pts.map((q) => { const p = project(cam, q); return [p.x, p.y] as P; }), role: "line", w: w * 0.9, alpha: 0.45 });+ });+ return m;+};+export const kneeMarks = (r: Rig, s: Side, cam: Camera): Mark[] => {+ const hh = r.dims.hh, S = r.shin[s], k = sgn(s), px = project(cam, S.p).s * hh, w = Math.max(0.8, px * 0.012);+ // the kneecap's lower rim and the tendon down to the shin's tuberosity+ const cap = surfaceRuns(r, cam, S, [[k * 0.075, 0.06, 0.2], [k * 0.06, -0.04, 0.22], [0, -0.08, 0.23], [-k * 0.06, -0.04, 0.22], [-k * 0.075, 0.06, 0.2]], { min: 0.2 });+ const ten = surfaceRuns(r, cam, S, [[-k * 0.04, -0.1, 0.2], [-k * 0.035, -0.22, 0.19]], { min: 0.25 });+ const inner = surfaceRuns(r, cam, S, [[-k * 0.2, 0.1, 0.02], [-k * 0.21, -0.05, 0.02], [-k * 0.17, -0.18, 0.0]], { min: 0.1 });+ return [...lines(cap, "line", w, 0.55), ...lines(ten, "line", w * 0.8, 0.35), ...lines(inner, "line", w * 0.8, 0.35)];+};+export const elbowMarks = (r: Rig, s: Side, cam: Camera): Mark[] => {+ const hh = r.dims.hh, F = r.fore[s], px = project(cam, F.p).s * hh, w = Math.max(0.8, px * 0.011);+ // the crease in the crook of the arm, and the bony point behind when the arm bends+ return [...lines(surfaceRuns(r, cam, F, [[-0.08, -0.02, 0.13], [0, -0.03, 0.16], [0.08, -0.01, 0.13]], { min: 0.25 }), "line", w, 0.4)];+};diff --git a/engine/src/canvas-core/charcoalErasure.ts b/engine/src/canvas-core/charcoalErasure.tsnew file mode 100644index 0000000..90a1751--- /dev/null+++ b/engine/src/canvas-core/charcoalErasure.ts@@ -0,0 +1,313 @@+import { Gfx, rng, type Ctx, type Env, type Layer, type Medium, type P } from "./core";+import type { Film } from "./film";+import { blob, bounds, clamp, clipped, inside, lerp, lerpP, polyLen, resample, smooth } from "./gallery";+import { COMP, ERASE, INK, STUMP, VINE, dab, dur, noiseAt, rubMark, runPass, sideMarks, spiral, stick, zigzag, type Mark, type Step } from "./charcoalErasureKit";++// ONE TREE, FOUR SEASONS · charcoal, erased and redrawn.+//+// MEDIUM, physically: willow vine charcoal (a soft grey stick that skates over the tooth and+// dusts off at a breath) and compressed charcoal (black, crisp, bites into the paper and barely+// erases), on one sheet of heavy cream rag paper with a strong tooth. A paper stump rubs tone+// into the valleys; a kneaded eraser lifts light back out, and never lifts all of it.+// MARKS: the stick's point for structure (vine first, compressed last), the SIDE of the stick for+// tone, the stump's rubbed zigzag for atmosphere, the eraser's drag for light.+// EDGE: vine edges are powdery and broken by the tooth; compressed edges are crisp; stumped tone+// has no edge at all; an erased edge is streaky, in the direction the eraser was dragged.+// ORDER: tone the sky, lift the sun, lay the tree in with vine, build the limbs, twigs in+// compressed, ground and shadow, lift snow. Then, every season, the erase-and-redraw cycle: rub+// out what changed with the kneaded eraser, re-tone, lift the new sun, redraw. Nothing is ever+// fully gone: each season is drawn on the grey residue of the one before.+// PALETTE: one warm black on cream paper. Value only.+// PAPER: heavy rag, felt-marked; its grain is multiplied over everything, charcoal included.+// LIGHT: the sun, low on the left, lifted out of the sky tone. It climbs from winter to summer+// and sinks again for autumn, and the shadow on the ground says where it is: long in winter, a+// pool at the foot in summer, long again in autumn. The ghosts of every sun and every shadow stay.+// SUBJECT: an open-grown English oak in a field, one sheet, winter -> spring -> summer -> autumn.+// STRUCTURE (from knowledge of parkland oaks and tree-identification winter silhouettes): a short+// thick bole with root flare, splitting low into five crooked limbs, the two lowest near+// horizontal (an oak's signature), the crown broader than tall; every fork conserves the limb's+// cross-section (child widths squared sum to the parent's), branches zigzag at each node, twigs+// are short and stiff; summer foliage sits in lobed clumps at the branch ends with dark+// undersides and sky holes; autumn thins it from the outside in and the wind leans the outer twigs.+// WHAT MAKES IT NOT ITS NEIGHBOUR (pocketWatch, ballpoint): tone here is rubbed and lifted, not+// hatched; the eraser is a drawing tool; and the drawing keeps its own history on the sheet.+// MOTION GRAMMAR: every change is made by a hand. A stroke grows from where the stick touched;+// tone arrives drag by drag; the stump and the eraser travel their zigzags; nothing fades.++const W = 1080, H = 1080, N = 540, HOLD = 30;+const HZ = 770; // horizon+const FOOT: P = [540, 884]; // where the trunk meets the ground+const CHAR_M: Medium = { nib: 1, taper: 1, pressure: 0.6, retrace: false, wobble: 1, rough: 1 };+// The sheet is authored in TREE SPACE and placed on the page by OFF: the oak left of centre, its+// foot on a ground line in the lower third, the canopy filling the upper centre.+const OFF: P = [-78, -46];+const SKY: P[] = [[-200, -200], [1300, -200], [1300, HZ + 4], [-200, HZ + 4]];+const FIELD: P[] = [[-200, HZ - 2], [1300, HZ - 2], [1300, 1200], [-200, 1200]];+// the sun climbs from a low winter sun to a high summer one and drops back for autumn, always to the upper right+const SUNS = { winter: [1080, 560, 28], spring: [1040, 360, 29], summer: [930, 150, 31], autumn: [1010, 262, 31] } as const;+const HAZE: P = [990, 290]; // where the sky was toned for the sun to be lifted out of++// ---------------------------------------------------------------- the tree+type Br = { c: P[]; w0: number; w1: number; d: number; limb: number };+const TRUNK: P[] = [[537, 896], [534, 840], [537, 780], [541, 730], [544, 700]];+const LIMBS: { c: P[]; w: number }[] = [+ { c: [[534, 716], [470, 676], [400, 657], [332, 643], [262, 614]], w: 25 }, // low left, near horizontal+ { c: [[536, 704], [504, 606], [446, 510], [408, 408], [376, 306]], w: 22 },+ { c: [[546, 700], [562, 594], [534, 474], [556, 346], [538, 214]], w: 25 },+ { c: [[553, 703], [612, 612], [672, 504], [736, 404], [782, 312]], w: 22 },+ { c: [[556, 716], [640, 686], [730, 668], [816, 650], [902, 626]], w: 22 }, // low right+];+const unit = (x: number, y: number): P => { const l = Math.hypot(x, y) || 1; return [x / l, y / l]; };+const tanAt = (c: P[], i: number): P => { const a = c[Math.max(0, i - 1)], b = c[Math.min(c.length - 1, i + 1)]; return unit(b[0] - a[0], b[1] - a[1]); };+const growTree = (): Br[] => {+ const out: Br[] = [], r = rng(7);+ const kids = (c: P[], w0: number, w1: number, d: number, limb: number) => {+ out.push({ c, w0, w1, d, limb });+ if (d >= 3) return;+ const n = d === 0 ? 6 : d === 1 ? 3 : 3, L = polyLen(c);+ let side = r() < 0.5 ? 1 : -1;+ for (let i = 0; i < n; i++) {+ const t = (d === 0 ? 0.3 : 0.22) + ((i + 0.3 + r() * 0.5) / n) * (d === 0 ? 0.64 : 0.72), k = Math.round(t * (c.length - 1)), p = c[k], tg = tanAt(c, k);+ const spread = (d === 0 ? 0.62 : 0.55) + r() * 0.4, ca = Math.cos(side * spread), sa = Math.sin(side * spread);+ let dir = unit(tg[0] * ca - tg[1] * sa, tg[0] * sa + tg[1] * ca);+ dir = unit(dir[0] * 0.84, dir[1] * 0.84 - (d === 0 ? 0.22 : 0.3)); // branches reach for the light+ const len = (d === 0 ? L * (1 - t) * 0.62 + 42 : d === 1 ? L * (1 - t) * 0.7 + 22 : 14 + r() * 22) * (0.8 + r() * 0.4);+ const wp = lerp(w0, w1, t), cw = Math.max(0.9, wp * (d === 0 ? 0.52 : 0.6));+ const segs = d >= 2 ? 2 : 4, path: P[] = [p]; let a = Math.atan2(dir[1], dir[0]), q = p;+ for (let s = 0; s < segs; s++) { a += (r() - 0.5) * (d >= 2 ? 0.5 : 0.62); q = [q[0] + Math.cos(a) * len / segs, q[1] + Math.sin(a) * len / segs]; path.push(q); } // an oak zigzags at every node+ kids(resample(smooth(path, false, 5), Math.max(4, Math.round(len / 4))), cw, d >= 2 ? 0.7 : Math.max(0.9, cw * 0.3), d + 1, limb);+ side = -side;+ }+ };+ LIMBS.forEach((l, i) => { const c = resample(smooth(l.c, false, 8), 90); kids(c, l.w, 4.2, 0, i); });+ return out;+};+// autumn wind from the left leans the crown: displacement grows with the square of height and reach+const bend = ([x, y]: P): P => { const h = clamp((700 - y) / 520, 0, 1.3), reach = Math.abs(x - 540) / 400, s = Math.max(0, h * 0.8 + reach * 0.5); return [x + 30 * s * s, y + 6 * s * s]; };++// summer clumps, hand-placed on the limb ends: [x, y, r]+const CLUMPS: [number, number, number][] = [+ [292, 596, 62], [360, 574, 70], [236, 560, 42],+ [372, 318, 82], [322, 410, 74], [430, 424, 82],+ [520, 232, 90], [610, 312, 84], [458, 300, 72],+ [778, 322, 84], [700, 408, 86], [812, 440, 66],+ [870, 590, 64], [790, 582, 70], [704, 548, 64],+ [540, 450, 92], [616, 520, 78], [440, 520, 78],+];+const clumpShape = (x: number, y: number, r: number, seed: number): P[] => {+ const b = blob(x, y, r, r * 0.82, seed, 0.2, 16);+ return b.map(([px, py]) => { const dy = py - y; return [px, dy > 0 ? y + dy * 0.72 : py] as P; });+};+// A foliage clump is a cauliflower: one core lobe and a crown of smaller lobes, most of them on+// the upper side (the leaves reach for the light), the underside flatter. Lobes are wobbly+// circles so a point test stays cheap; their outlines are the same function, for clipping.+type Lobe = { x: number; y: number; r: number; ph: number };+const lobeR = (l: Lobe, a: number) => l.r * (1 + 0.12 * Math.sin(5 * a + l.ph) + 0.06 * Math.sin(9 * a + 2 * l.ph));+const inLobe = (l: Lobe, x: number, y: number) => { const dx = x - l.x, dy = y - l.y; return dx * dx + dy * dy < (l.r * 1.18) ** 2 && Math.hypot(dx, dy) < lobeR(l, Math.atan2(dy, dx)); };+const lobePoly = (l: Lobe, k = 1): P[] => Array.from({ length: 28 }, (_, i) => { const a = (i / 28) * Math.PI * 2; return [l.x + Math.cos(a) * lobeR(l, a) * k, l.y + Math.sin(a) * lobeR(l, a) * k] as P; });+const lobesOf = (x: number, y: number, r: number, seed: number): Lobe[] => {+ const q = rng(seed), out: Lobe[] = [{ x, y: y + r * 0.08, r: r * 0.62, ph: q() * 6 }], n = 9;+ for (let k = 0; k < n; k++) { const a = -Math.PI - 0.35 + ((k + 0.2 + q() * 0.6) / n) * (Math.PI + 0.7), d = r * (0.5 + q() * 0.16); out.push({ x: x + Math.cos(a) * d * 1.08, y: y + Math.sin(a) * d * 0.9, r: r * (0.27 + q() * 0.14), ph: q() * 6 }); }+ for (let k = 0; k < 3; k++) { const a = 0.55 + k * 1.0 + q() * 0.3, d = r * 0.46; out.push({ x: x + Math.cos(a) * d, y: y + Math.sin(a) * d * 0.62, r: r * 0.3, ph: q() * 6 }); }+ return out;+};++// ---------------------------------------------------------------- the passes+type Pass = { id: string; a: number; b: number; steps: (env: Env) => Step[] };+const drawBranch = (b: Br, c: P[], alpha: number, seed: number, rough = 0.6): Mark => ({ t: dur(polyLen(c), b.d >= 2 ? 0.28 : 0.4, b.d >= 2 ? 260 : 420), d: (g, p) => stick(g, c, b.w0, b.w1, alpha, seed, p, { rough }) });+// the shade side of a limb: a strip offset away from the sun, in compressed+const shadeSide = (b: Br, seed: number): Mark => {+ const off = b.c.map((p, i) => { const tg = tanAt(b.c, i); let nx = -tg[1], ny = tg[0]; if (-nx * 0.72 + ny * 0.62 < 0) { nx = -nx; ny = -ny; } const w = lerp(b.w0, b.w1, i / (b.c.length - 1)); return [p[0] + nx * w * 0.26, p[1] + ny * w * 0.26] as P; });+ return { t: dur(polyLen(off), 0.3, 520), d: (g, p) => stick(g, off, b.w0 * 0.5, b.w1 * 0.5, 0.88, seed, p, { rough: 0.9 }) };+};+const trunkPoly = (): P[] => { // the bole with its root flare+ const c = resample(smooth(TRUNK, false, 8), 40), L: P[] = [], R: P[] = [];+ c.forEach((p, i) => { const t = i / 39, tg = tanAt(c, i), w = 34 - 8 * t + 44 * Math.pow(clamp(1 - t / 0.3), 2.6); L.push([p[0] + tg[1] * w, p[1] - tg[0] * w]); R.push([p[0] - tg[1] * w * 1.04, p[1] + tg[0] * w * 1.04]); });+ return [...L, ...R.reverse()];+};+// a shadow on the ground: project a point of height h along the sun's (kx, ky) per unit height+const project = (kx: number, ky: number) => ([x, y]: P): P => { const h = FOOT[1] - y; return [x + h * kx, FOOT[1] + h * ky]; };+const sunLift = (s: readonly number[], seed: number): Step[] => [+ { o: ERASE(0.18, 10), m: [rubMark(spiral(s[0], s[1], 4, s[2] * 1.4, 3, seed + 1), 22, 1)] }, // the glow: a wide light rub+ { o: ERASE(0.88, 2.2), m: [rubMark(spiral(s[0], s[1], 2, s[2] - 6, 3.6, seed), 13, 1)] }, // the disc: pressed and turned+];+const retone = (s: readonly number[], seed: number): Step[] => [+ { o: VINE, m: sideMarks(clumpShape(s[0], s[1], s[2] * 2.2, seed), { angle: -0.22, gap: 7, w: 14, alpha: 0.05, seed, per: 900 }) },+ { o: STUMP(10), m: zigzag(bounds(clumpShape(s[0], s[1], s[2] * 2.2, seed)), 22, 24, seed + 3).map((row) => rubMark(row, 40, 0.04, INK, SKY)) },+];++const PASSES = (env: Env): Pass[] => {+ const tree = cached(env, "ce:tree", growTree), limbs = tree.filter((b) => b.d <= 1), fine = tree.filter((b) => b.d >= 2);+ const clumps = CLUMPS.map(([x, y, r], i) => { const lobes = lobesOf(x, y, r, 300 + i * 7), polys = lobes.map((l) => lobePoly(l)); return { x, y, r, i, lobes, polys, s: [[x - r * 1.25, y - r * 1.2], [x + r * 1.25, y - r * 1.2], [x + r * 1.25, y + r * 0.95], [x - r * 1.25, y + r * 0.95]] as P[], test: (px: number, py: number) => lobes.some((l) => inLobe(l, px, py)) }; });+ const canopy = (x: number, y: number) => clumps.some((k) => Math.hypot(x - k.x, (y - k.y) * 1.1) < k.r * 1.08);+ const shadowOf = (kx: number, ky: number, set: Br[], k: number, seed: number): Mark[] => { const pr = project(kx, ky); return set.map((b, i) => { const c = b.c.map(pr); return { t: dur(polyLen(c), 0.12, 900), d: (g, p) => stick(g, c, b.w0 * k, b.w1 * k, 0.36, seed + i, p, { rough: 1.4 }) }; }); };+ const trunkShadow = (kx: number, ky: number, seed: number): Mark => { const pr = project(kx, ky), c = resample(smooth(TRUNK, false, 6), 20).map(pr); return { t: 1, d: (g, p) => stick(g, c, 56, 30, 0.4, seed, p, { rough: 2 }) }; };+ const hedge: P[] = (() => { const top: P[] = []; for (let x = -10; x <= W + 10; x += 12) { const gap = x > 612 && x < 772, bump = HEDGE_TREES.reduce((a, [bx, bw, bh]) => Math.max(a, bh * Math.sqrt(clamp(1 - ((x - bx) / bw) ** 2))), 0), h = gap ? 0 : 5 + 7 * noiseAt(90, x, 0, 0.03) + bump * (0.85 + 0.3 * noiseAt(91, x, 0, 0.06)); top.push([x, HZ - h]); } return [...top, [W + 10, HZ + 6], [-10, HZ + 6]]; })();+ const fieldTone = (seed: number, alpha: number, near: number): Mark[] => sideMarks(FIELD, { angle: 0.04, gap: 7, w: 9, alpha, seed, keep: (x, y) => Math.hypot((x - FOOT[0]) * 0.55, (y - FOOT[1]) * 1.6) < 110 + 90 * near * (noiseAt(seed, x, y, 0.01) - 0.3), per: 1200 });+ const twigTips = fine.filter((b) => b.d === 3);++ return [+ // WINTER ------------------------------------------------------------------------------+ { id: "w_tone", a: 0, b: 40, steps: () => [+ { o: STUMP(9), m: sideMarks(SKY, { angle: -0.22, gap: 7, w: 18, alpha: 0.075, seed: 11, keep: (x, y) => Math.hypot(x - HAZE[0], (y - HAZE[1]) * 0.8) < 200 + 120 * (noiseAt(12, x, y, 0.01) - 0.5) * 2, per: 1800 }) },+ // (the drags were rubbed in as they went: the stump group softens them, so the haze has no edge)+ ] },+ { id: "w_sun", a: 40, b: 55, steps: () => sunLift(SUNS.winter, 20) },+ { id: "w_lay", a: 55, b: 80, steps: () => [+ { o: VINE, m: [+ { t: 0.8, d: (g, p) => stick(g, [[0, HZ + 1], [W * 0.5, HZ - 1], [W, HZ + 2]], 2.2, 2.2, 0.35, 30, p, { ends: 0.05 }) },+ ...[trunkPoly().slice(0, 40), trunkPoly().slice(40)].map((c, i): Mark => ({ t: 0.6, d: (g, p) => stick(g, c, 3, 2.4, 0.45, 31 + i, p, { ends: 0.1 }) })),+ ...LIMBS.map((l, i): Mark => { const c = smooth(l.c, false, 8); return { t: dur(polyLen(c), 0.2, 700), d: (g, p) => stick(g, c, 3.2, 2, 0.4, 40 + i, p, { ends: 0.08 }) }; }),+ ] },+ ] },+ { id: "w_limbs", a: 80, b: 120, steps: () => [+ { o: VINE, m: [...sideMarks(trunkPoly(), { angle: Math.PI / 2 - 0.06, gap: 3.2, w: 7, alpha: 0.6, seed: 99, per: 300 }), ...limbs.map((b, i) => drawBranch(b, b.c, 0.8, 100 + i))] },+ { o: COMP, m: [...limbs.filter((b) => b.w0 > 6).map((b, i) => shadeSide(b, 200 + i)), { t: 1, d: (g, p) => stick(g, resample(smooth(TRUNK, false, 6), 30).map(([x, y]) => [x - 14, y] as P).reverse().slice(0, 28).reverse(), 34, 20, 0.92, 97, p, { rough: 1.6 }) }, ...bark()] },+ ] },+ { id: "w_twigs", a: 120, b: 150, steps: () => [{ o: COMP, m: fine.map((b, i) => drawBranch(b, b.c, 0.84, 400 + i, 0.3)) }] },+ { id: "w_ground", a: 150, b: 175, steps: () => [+ { o: VINE, m: [...sideMarks(hedge, { angle: -1.2, gap: 3.6, w: 5, alpha: 0.17, seed: 50, per: 500 })] },+ { o: STUMP(4), m: [...zigzag(bounds(hedge), 9, 12, 51).map((row) => rubMark(row, 12, 0.2, INK, hedge))] },+ { o: { ...VINE, blur: 1.6 }, m: [...shadowOf(-1.25, 0.3, limbs, 0.8, 60), trunkShadow(-1.25, 0.3, 58)] },+ { o: COMP, m: [contact(0.9, 70), ...tufts(71, 26)] },+ ] },+ { id: "w_snow", a: 175, b: 190, steps: () => [+ { o: ERASE(0.8, 1), m: limbs.filter((b) => b.w0 > 3).map((b, i) => snowCap(b, 80 + i)).filter((m): m is Mark => !!m) },+ { o: ERASE(0.55, 1.2), m: [rimLight(81)] },+ ] },+ // SPRING ------------------------------------------------------------------------------+ { id: "s_erase", a: 190, b: 210, steps: () => [+ { o: ERASE(0.8, 4), m: zigzag({ x0: -120, y0: 902, x1: 470, y1: 1150 }, 26, 30, 110, -0.25).map((row) => rubMark(row, 36, 1, INK, FIELD)) },+ ] },+ { id: "s_retone", a: 210, b: 225, steps: () => retone(SUNS.winter, 120) },+ { id: "s_sun", a: 225, b: 235, steps: () => sunLift(SUNS.spring, 130) },+ { id: "s_ground", a: 235, b: 265, steps: () => [+ { o: STUMP(5), m: fieldTone(140, 0.11, 0.35) },+ { o: { ...VINE, blur: 1.6 }, m: [...shadowOf(-0.85, 0.24, limbs, 0.7, 141), trunkShadow(-0.85, 0.24, 142)] },+ // (the field is stumped only where it was toned, round the foot)+ { o: COMP, m: tufts(144, 60) },+ ] },+ { id: "s_buds", a: 265, b: 290, steps: () => [{ o: VINE, m: twigTips.map((b, i) => budMark(b, 500 + i)) }] },+ // SUMMER ------------------------------------------------------------------------------+ { id: "u_erase", a: 290, b: 305, steps: () => [+ { o: ERASE(0.8, 4), m: zigzag({ x0: -60, y0: 884, x1: 400, y1: 1120 }, 26, 30, 210, -0.2).map((row) => rubMark(row, 36, 1, INK, FIELD)) },+ ] },+ { id: "u_retone", a: 305, b: 315, steps: () => retone(SUNS.spring, 220) },+ { id: "u_sun", a: 315, b: 325, steps: () => sunLift(SUNS.summer, 230) },+ { id: "u_mass", a: 325, b: 355, steps: () => [{ o: VINE, m: clumps.flatMap((k) => [+ ...sideMarks(k.s, { angle: -0.55 + (k.i % 4) * 0.28, gap: 3.4, w: 7, alpha: 0.2, seed: 600 + k.i, per: 700, test: k.test }),+ ...sideMarks(k.s, { angle: 0.75 - (k.i % 3) * 0.2, gap: 3.8, w: 7, alpha: 0.24, seed: 640 + k.i, test: k.test, keep: (x, y) => -(x - k.x) * 0.55 + (y - k.y) > -k.r * 0.2 + (noiseAt(641 + k.i, x, y, 0.04) - 0.5) * k.r * 0.6, per: 700 }), // the shade side, worked again+ ...sideMarks(k.s, { angle: 1.3, gap: 4.2, w: 6, alpha: 0.26, seed: 680 + k.i, test: k.test, keep: (x, y) => -(x - k.x) * 0.4 + (y - k.y) > k.r * 0.2, per: 700 }), // the underside, a third time+ ]) }] },+ { id: "u_blend", a: 355, b: 370, steps: () => [{ o: STUMP(5), m: clumps.flatMap((k) => zigzag(bounds(k.s), 18, 18, 700 + k.i, -0.5 + k.i * 0.3).map((row) => rubMark(row, 22, 0.16, INK, k.polys, 2400))) }] },+ { id: "u_lift", a: 370, b: 385, steps: () => [+ { o: ERASE(0.58, 2), m: clumps.flatMap((k) => k.lobes.filter((l) => -(l.x - k.x) * 0.7 + (l.y - k.y) < -k.r * 0.25).map((l, j) => rubMark(spiral(l.x + l.r * 0.28, l.y - l.r * 0.32, 1, l.r * 0.5, 1.6, 720 + k.i * 13 + j), 8, 1, INK, lobePoly(l, 0.92), 900))) },+ { o: ERASE(0.8, 1.2), m: SKYHOLES.map(([x, y, r], i) => rubMark(spiral(x, y, 1, r, 2, 740 + i), 6, 1)) },+ ] },+ { id: "u_dark", a: 385, b: 400, steps: () => [+ { o: COMP, m: clumps.flatMap((k) => k.lobes.filter((l) => l.y > k.y + k.r * 0.05).map((l, j): Mark => { const arc: P[] = Array.from({ length: 9 }, (_, q) => { const a = 0.35 + (q / 8) * 2.4; return [l.x + Math.cos(a) * lobeR(l, a) * 0.9, l.y + Math.sin(a) * lobeR(l, a) * 0.9] as P; }); return { t: 0.16, d: (g, p) => stick(g, arc, 5.5, 2, 0.5, 760 + k.i * 7 + j, p, { ends: 0.25, rough: 1.4 }) }; })) },+ { o: VINE, m: clumps.map((k, i): Mark => { const pr = project(-0.22, 0.07), [sx, sy] = pr([k.x, k.y]); const s = blob(sx, sy, k.r * 0.95, k.r * 0.2, 780 + i, 0.2, 12); return { t: 0.25, d: (g, p) => { if (p > 0) fillSolid(g, s, 0.2 * p); } }; }) },+ { o: COMP, m: [contact(0.95, 790)] },+ ] },+ // AUTUMN ------------------------------------------------------------------------------+ { id: "a_erase", a: 400, b: 425, steps: () => [+ { o: RUB(0.93), m: clumps.filter((k) => !KEEP.includes(k.i)).flatMap((k) => zigzag(bounds(k.s), 16, 24, 800 + k.i, 0.3 + k.i * 0.4).map((row) => rubMark(row, 30, 1, INK, k.lobes.map((l) => lobePoly(l, 1.12)), 2400))) },+ { o: RUB(0.8), m: clumps.filter((k) => KEEP.includes(k.i)).flatMap((k) => zigzag(bounds(k.s), 16, 24, 850 + k.i, -0.3).map((row) => rubMark(row, 30, 1, INK, k.lobes.map((l) => lobePoly(l, 1.12)), 2400))) },+ { o: ERASE(0.8, 5), m: [...zigzag({ x0: 300, y0: 904, x1: 900, y1: 960 }, 22, 26, 820, 0), ...zigzag({ x0: 612, y0: 868, x1: 900, y1: 904 }, 22, 26, 821, 0)].map((row) => rubMark(row, 30, 1, INK, FIELD)) }, // round the bole, never through it+ ] },+ { id: "a_retone", a: 425, b: 435, steps: () => retone(SUNS.summer, 830) },+ { id: "a_sun", a: 435, b: 445, steps: () => sunLift(SUNS.autumn, 840) },+ { id: "a_branch", a: 445, b: 470, steps: () => [{ o: COMP, m: tree.filter((b) => b.d >= 1 && b.c.some(([x, y]) => canopy(x, y))).map((b, i) => drawBranch({ ...b, w0: b.w0 * 0.8 }, b.c.map(bend), 0.9, 900 + i, 0.4)) }] },+ { id: "a_leaves", a: 470, b: 490, steps: () => [+ { o: VINE, m: clumps.filter((k) => KEEP.includes(k.i)).flatMap((k) => autumnClump(k.x, k.y, k.r, 1000 + k.i * 13)) },+ { o: { ...VINE, blur: 1.6 }, m: [...shadowOf(-1.3, 0.3, limbs, 0.85, 1050), trunkShadow(-1.3, 0.3, 1051)] },+ { o: COMP, m: clumps.filter((k) => KEEP.includes(k.i)).flatMap((k) => autumnClump(k.x, k.y, k.r * 0.6, 1100 + k.i * 13, 0.72)) },+ ] },+ { id: "a_fall", a: 490, b: 510, steps: () => [{ o: COMP, m: [contact(0.7, 1190), ...FALLING.map(([x, y, a], i) => leafMark(x, y, a, 1.45, 1200 + i, 1, 0.82)), ...drift(1300)] }] },+ ];+};+const HEDGE_TREES: [number, number, number][] = [[46, 44, 26], [128, 58, 40], [262, 36, 18], [338, 52, 30], [428, 30, 14], [846, 40, 22], [952, 70, 42], [1052, 44, 24]]; // distant field trees in the hedge line, a gateway gap to the right of the oak+// a big kneaded-eraser rub, worked over twice: lifts almost everything, evenly+const RUB = (alpha: number) => ({ blend: "destination-out" as GlobalCompositeOperation, alpha, textures: ["ce_blend"], blur: 7 });+const KEEP = [1, 5, 7, 8, 10, 13, 15, 16, 17]; // the clumps that hold on longest: sheltered, low, leeward+const SKYHOLES: [number, number, number][] = [[478, 378, 11], [652, 440, 9], [566, 300, 8], [402, 486, 8], [742, 478, 10]];+const FALLING: [number, number, number][] = [[866, 690, 0.6], [934, 742, -0.9], [812, 752, 2.1], [980, 668, 1.2], [760, 812, -0.3], [904, 822, 0.9], [1010, 790, -1.6], [700, 700, 2.6], [996, 520, 0.4], [946, 610, -2.2], [1040, 880, 1.7]];++const fillSolid = (g: Gfx, s: P[], a: number) => { const c = g.cur, b = bounds(s); g.touch(b.x0 - 2, b.y0 - 2, b.x1 + 2, b.y1 + 2); c.globalAlpha = a; c.fillStyle = INK; c.beginPath(); s.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill(); c.globalAlpha = 1; };+// oak bark: deep vertical fissures, broken, darker on the shade side of the bole+const bark = (): Mark[] => { const r = rng(300), out: Mark[] = []; for (let i = 0; i < 26; i++) { const u = r(), x0 = 514 + u * 52 + (r() - 0.5) * 4, y0 = 712 + r() * 120, len = Math.min(24 + r() * 50, 868 - y0), c: P[] = [[x0, y0], [x0 + (r() - 0.5) * 5, y0 + len * 0.5], [x0 + (r() - 0.5) * 6, y0 + len]]; out.push({ t: 0.18, d: (g, p) => stick(g, c, 2.4 + u * 1.6, 1.2, 0.5 + u * 0.4, 310 + i, p, { ends: 0.25, rough: 1 }) }); } return out; };+const contact = (a: number, seed: number): Mark => { const c: P[] = [[470, 892], [510, 898], [560, 899], [604, 893]]; return { t: 0.5, d: (g, p) => stick(g, c, 7, 4, a, seed, p, { ends: 0.2, rough: 1.2 }) }; };+const tufts = (seed: number, n: number): Mark[] => { const r = rng(seed), out: Mark[] = [], cl: P[] = Array.from({ length: Math.max(3, Math.round(n / 6)) }, () => [60 + r() * 960, HZ + 60 + Math.pow(r(), 0.6) * (H - HZ - 80)] as P); for (let i = 0; i < n; i++) { const c0 = cl[i % cl.length], x = c0[0] + (r() - 0.5) * 70, y = c0[1] + (r() - 0.5) * 30; if (Math.abs(x - 540) < 90 && y < 900) continue; const s = 0.4 + (y - HZ) / (H - HZ), bl = 3 + Math.floor(r() * 4); for (let k = 0; k < bl; k++) { const lean = (r() - 0.45) * 0.9, h = (7 + r() * 18) * s, x0 = x + (r() - 0.5) * 9 * s, al = 0.45 + r() * 0.3, c: P[] = [[x0, y + r() * 2], [x0 + lean * h * 0.35, y - h * 0.55], [x0 + lean * h, y - h]]; out.push({ t: 0.08, d: (g, p) => stick(g, c, 1.4 * s, 0.3, al, seed * 7 + i * 5 + k, p, { rough: 0.25 }) }); } } return out; };+const snowCap = (b: Br, seed: number): Mark | null => {+ const top = b.c.map((p, i) => { const tg = tanAt(b.c, i), w = lerp(b.w0, b.w1, i / (b.c.length - 1)); let nx = -tg[1], ny = tg[0]; if (ny > 0) { nx = -nx; ny = -ny; } return { p: [p[0] + nx * w * 0.36, p[1] + ny * w * 0.36] as P, flat: Math.abs(tg[1]) < 0.55 }; });+ const run = top.filter((q) => q.flat).map((q) => q.p); if (run.length < 4) return null;+ return { t: dur(polyLen(run), 0.2, 600), d: (g, p) => stick(g, run, Math.max(1.4, b.w0 * 0.32), 1, 1, seed, p, { ends: 0.15, rough: 0.8 }) };+};+const rimLight = (seed: number): Mark => { const t = trunkPoly(); const tt = t.slice(t.length - 36, t.length - 4).map(([x, y]) => [x - 4, y] as P); return { t: 0.6, d: (g, p) => stick(g, tt, 3, 2, 1, seed, p, { ends: 0.2 }) }; };+const budMark = (b: Br, seed: number): Mark => { const e = b.c[b.c.length - 1], r = rng(seed), n = 2 + Math.floor(r() * 3), pts: [number, number, number][] = []; for (let k = 0; k < n; k++) pts.push([e[0] + (r() - 0.5) * 9, e[1] + (r() - 0.6) * 8, r() * 3]); return { t: 0.09, d: (g, p) => pts.slice(0, Math.ceil(p * n)).forEach(([x, y, a], k) => dab(g, x, y, 2.6, 1.5, a, 0.5, seed * 3 + k)) }; };+// autumn foliage: no mass any more, separate leaves dabbed in, drifted downwind, holes everywhere+const autumnClump = (cx: number, cy: number, r: number, seed: number, a = 0.5): Mark[] => {+ const rr = rng(seed), out: Mark[] = [], [bx, by] = bend([cx, cy]);+ for (let i = 0; i < Math.round(r * 1.3); i++) { const ang = rr() * Math.PI * 2, d = Math.sqrt(rr()) * r * 0.85, x = bx + Math.cos(ang) * d, y = by + Math.sin(ang) * d * 0.75; if (noiseAt(seed, x, y, 0.03) > 0.58) continue; const shade = -(x - bx) * 0.5 + (y - by) > 0 ? 1 : 0.6; const sz = 0.8 + rr() * 0.6; out.push({ t: 0.035, d: (g, p) => { if (p > 0) dab(g, x, y, 5.2 * sz, 3 * sz, ang, a * shade, seed + i); } }); }+ return out;+};+const leafMark = (x: number, y: number, a: number, k: number, seed: number, flat = 1, alpha = 0.78): Mark => {+ // an oak leaf, seen tumbling: a lobed outline (five rounded lobes a side) and a stalk+ const L = 13 * k, pts: P[] = []; for (let i = 0; i <= 20; i++) { const t = i / 20, u = Math.sin(t * Math.PI), lobe = 0.72 + 0.28 * Math.abs(Math.sin(t * Math.PI * 5)); pts.push([t * L - L / 2, -u * L * 0.32 * lobe]); } for (let i = 20; i >= 0; i--) { const t = i / 20, u = Math.sin(t * Math.PI), lobe = 0.72 + 0.28 * Math.abs(Math.sin(t * Math.PI * 5 + 0.6)); pts.push([t * L - L / 2, u * L * 0.3 * lobe]); }+ const ca = Math.cos(a), sa = Math.sin(a), sq = 0.55 + 0.45 * Math.abs(Math.sin(seed)), T = ([px, py]: P): P => [x + px * ca - py * sq * sa, y + (px * sa + py * sq * ca) * flat];+ const shape = pts.map(T), stalk = [T([-L / 2, 0]), T([-L / 2 - 4 * k, 1])];+ return { t: 0.22, d: (g, p) => { if (p <= 0) return; fillSolid(g, shape.slice(0, Math.max(3, Math.round(shape.length * p))), alpha); if (p > 0.8) stick(g, stalk, 1.2, 0.6, 0.8, seed, 1); } };+};+// fallen leaves: a drift on the leeward side of the bole, thick at the roots, thinning out, with bare rests+const drift = (seed: number): Mark[] => { const r = rng(seed), out: Mark[] = []; for (let i = 0; i < 90; i++) { const u = Math.pow(r(), 1.8), ang = -0.3 + r() * 3.6, d = 34 + u * 300, x = 548 + Math.cos(ang) * d, y = 890 + Math.sin(ang) * d * 0.34 + (r() - 0.5) * 16; if (y < 882 || y > H - 8 || noiseAt(seed, x, y, 0.018) > 0.56) continue; const k = 0.6 + (y - 870) / 260; out.push(leafMark(x, y, r() * 6.28, k, seed + i, 0.5, 0.45 + r() * 0.4)); } return out; };++// ---------------------------------------------------------------- the clock and the sheet+const PASS_KEYS = (env: Env) => cached(env, "ce:passes", () => PASSES(env));+function cached<T>(env: Env, key: string, fn: () => T): T { let v = env.cache.get(key) as T | undefined; if (v === undefined) { v = fn(); env.cache.set(key, v); } return v; }+const check = () => { const p = PASSES({ W, H, scale: 1, cache: new Map(), canvas: () => { throw new Error("no canvas at load"); } } as unknown as Env); let t = 0; for (const s of p) { if (s.a !== t || s.b <= s.a || s.a % 5 || s.b % 5) throw new Error(`charcoalErasure: pass ${s.id} off grid (${s.a}-${s.b}, expected start ${t})`); t = s.b; } if (t !== N - HOLD) throw new Error(`charcoalErasure: passes end at ${t}, expected ${N - HOLD}`); };+check();++const sheetGfx = (L: Layer, env: Env) => { const g = new Gfx(L.ctx, env, 0, CHAR_M); g.push(OFF[0], OFF[1], 1); return g; };+const blobOf = (c: P, r: number): P[] => blob(c[0], c[1], r, r * 0.8, 17, 0.25, 18);+const DW = (env: Env) => Math.round(env.W * env.scale), DH = (env: Env) => Math.round(env.H * env.scale);+const copyInto = (dst: Layer, src: Layer | null) => { const c = dst.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; if (src) { c.globalCompositeOperation = "copy"; c.drawImage(src.canvas as CanvasImageSource, 0, 0); c.globalCompositeOperation = "source-over"; } else c.clearRect(0, 0, dst.canvas.width, dst.canvas.height); };+// the charcoal on the sheet after pass i is finished: a pure function of (i, scale, size)+const stateAt = (env: Env, i: number): Layer | null => {+ if (i < 0) return null;+ const key = `ce:state:${i}:${env.scale}:${env.W}x${env.H}`, hit = env.cache.get(key) as Layer | undefined; if (hit) return hit;+ const prev = stateAt(env, i - 1), L = env.canvas(DW(env), DH(env)); copyInto(L, prev);+ const g = sheetGfx(L, env); runPass(g, PASS_KEYS(env)[i].steps(env), 1);+ env.cache.set(key, L); env.cache.delete(`ce:state:${i - 3}:${env.scale}:${env.W}x${env.H}`); // sequential renders only ever look one pass back+ return L;+};+const passProgress = (f: number, a: number, b: number) => clamp((f - a) / ((b - a) * 0.88)); // a breath between passes++export const drawCharcoal = (ctx: Ctx, f: number, env: Env) => {+ const passes = PASS_KEYS(env), last = passes.length - 1;+ let sheet: Layer | null;+ if (f >= N - HOLD) sheet = stateAt(env, last);+ else {+ const i = passes.findIndex((p) => f >= p.a && f < p.b), p = passProgress(f, passes[i].a, passes[i].b);+ const wkey = `ce:work:${env.scale}:${env.W}x${env.H}`; let work = env.cache.get(wkey) as Layer | undefined; if (!work) { work = env.canvas(DW(env), DH(env)); env.cache.set(wkey, work); }+ copyInto(work, stateAt(env, i - 1));+ if (p > 0) runPass(sheetGfx(work, env), passes[i].steps(env), p);+ sheet = work;+ }+ // the sheet: cream rag, its felt texture, then the charcoal, then the tooth over all of it+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";+ ctx.fillStyle = "#ece5d5"; ctx.fillRect(0, 0, DW(env), DH(env));+ const g = new Gfx(ctx, env, 0, CHAR_M);+ g.paper("ce_sheet", 0.22);+ if (sheet) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(sheet.canvas as CanvasImageSource, 0, 0); ctx.restore(); } // device to device: Gfx leaves ctx at env.scale+ g.paper("paper", 0.16);+ g.vignette("rgba(120,100,80,0.10)");+ void inside; void lerpP;+};++export const charcoalErasure: Film = {+ meta: { title: "One tree, four seasons · charcoal", W, H, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "seasons", start: 0, end: N, draw: drawCharcoal }],+};++export const STYLE = { id: "charcoalErasure", name: "Charcoal, erased and redrawn", family: "dry media", medium: "vine and compressed charcoal on heavy rag paper, stumped, lifted with a kneaded eraser, redrawn over its own residue", nearest: "pocketWatch", hero: "one oak through four seasons on one sheet" };diff --git a/engine/src/canvas-core/charcoalErasureKit.ts b/engine/src/canvas-core/charcoalErasureKit.tsnew file mode 100644index 0000000..d029420--- /dev/null+++ b/engine/src/canvas-core/charcoalErasureKit.ts@@ -0,0 +1,118 @@+// CHARCOAL + ERASURE KIT. The marks a charcoal draughtsman makes, as geometry on a Gfx surface:+// the stick's point (vine = soft grey, compressed = black and crisp), the SIDE of the stick for+// tone, the paper stump that rubs tone into the tooth, and the kneaded eraser that lifts it off+// again but never quite all of it. Plus the pass/mark clock the charcoal film is timed by.+//+// Kit primitives written here (candidates for core): registerTiles (four charcoal tiles),+// taperPoly (a centreline -> tapered, bitten ribbon, cut on the centreline by progress),+// zigzag (a rubbing path over a region), spiral (a circular rubbing), and the Pass/Step/Mark+// clock (`runPass`), which lays marks down one after another inside a pass.+import { Gfx, TILES, rng, fractal, type P } from "./core";+import { bounds, clamp, fillShape, hatchRuns, inside, lerp, lerpP, polyLen, resample, trace } from "./gallery";++// ---------------------------------------------------------------- tiles+// Registered into the shared TILES table under a ce_ prefix so Gfx.group can use them as tooth.+// Pure data, set once at module load; the tile builder caches by (kind, scale).+export const registerTiles = () => {+ TILES.ce_vine = { fx: 0.62, oct: 2, seed: 61, k: -3.1, o: 2.3 }; // vine skates over the tooth: broken, grey+ TILES.ce_comp = { fx: 0.85, oct: 2, seed: 62, k: -2.1, o: 2.0 }; // compressed bites deeper: mostly solid+ TILES.ce_blend = { fx: 0.4, oct: 3, seed: 63, k: -1.3, o: 1.55 }; // stumped tone: pushed into the valleys, still a little open+ TILES.ce_streak = { fx: 0.03, fy: 0.36, oct: 3, seed: 64, k: -1.25, o: 1.5 }; // an eraser drags, it does not lift evenly+ TILES.ce_sheet = { fx: 0.34, oct: 3, seed: 65, gray: true }; // heavy rag paper, felt-marked+};+registerTiles();++export const INK = "#1b1917"; // charcoal is warm black, never #000+export const VINE = { textures: ["ce_vine"], blur: 0.55 };+export const COMP = { textures: ["ce_comp"] };+export const STUMP = (blur = 7) => ({ textures: ["ce_blend"], blur });+export const ERASE = (alpha: number, blur = 2.6) => ({ blend: "destination-out" as GlobalCompositeOperation, alpha, textures: ["ce_streak"], blur });++// ---------------------------------------------------------------- the clock+// A mark is anything a hand puts down in one go; `t` is how long it takes relative to its+// neighbours. A step is a run of marks sharing one tool (one Gfx group). A pass is a run of steps.+export type Mark = { t: number; d: (g: Gfx, p: number) => void };+export type Step = { o: Parameters<Gfx["group"]>[2]; m: Mark[] };+export const dur = (len: number, base = 0.35, per = 380) => base + len / per; // long strokes fast, fiddly strokes slow+export const runPass = (g: Gfx, steps: Step[], p: number) => {+ const total = steps.reduce((a, s) => a + s.m.reduce((b, m) => b + m.t, 0), 0);+ let budget = p >= 1 ? Infinity : p * total;+ for (const st of steps) {+ if (budget <= 0) break;+ const start = budget;+ g.group("plain", () => { let b = start; for (const m of st.m) { if (b <= 0) break; m.d(g, b >= m.t ? 1 : b / m.t); b -= m.t; } }, st.o);+ budget -= st.m.reduce((b, m) => b + m.t, 0);+ }+};++// ---------------------------------------------------------------- the stick+// Cut a polyline at fraction `p` of its vertex run (on the centreline, like core's pen).+export const upTo = (s: P[], p: number): P[] => {+ if (p >= 1) return s; const n = (s.length - 1) * p, i = Math.floor(n), f = n - i, h = s.slice(0, i + 1);+ if (f > 1e-9 && i + 1 < s.length) h.push(lerpP(s[i], s[i + 1], f));+ return h.length > 1 ? h : s.slice(0, 2);+};+// A centreline -> tapered ribbon whose edges the paper bites. Width runs w0 -> w1 along the+// FINISHED stroke, so a stroke seen half made already has its final weight where it has been.+export const taperPoly = (c0: P[], w0: number, w1: number, seed: number, o: { rough?: number; p?: number; ends?: number; step?: number } = {}): P[] => {+ const { rough = 0.5, p = 1, ends = 0, step = 3 } = o, L0 = polyLen(c0), n = Math.max(3, Math.round(L0 / step)), s = resample(c0, n), r = rng(seed);+ const cut = p >= 1 ? n - 1 : (n - 1) * p, L: P[] = [], R: P[] = [], ph = (seed % 13) * 0.7;+ for (let i = 0; i <= Math.ceil(cut) && i < n; i++) {+ const tt = Math.min(i, cut), i0 = Math.floor(tt), f = tt - i0, pt = i0 + 1 < n ? lerpP(s[i0], s[i0 + 1], f) : s[i0];+ const a = s[Math.max(0, i0 - 1)], b = s[Math.min(n - 1, i0 + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, t = tt / (n - 1);+ const endK = ends ? Math.min(1, t / ends, (1 - t) / ends) : 1, w = lerp(w0, w1, Math.pow(t, 0.85)) * (0.3 + 0.7 * Math.pow(clamp(endK), 0.6)) * (1 + 0.1 * Math.sin(t * 11 + ph)) / 2;+ const j1 = (r() - 0.5) * rough, j2 = (r() - 0.5) * rough;+ L.push([pt[0] - (dy / l) * (w + j1), pt[1] + (dx / l) * (w + j1)]); R.push([pt[0] + (dy / l) * (w + j2), pt[1] - (dx / l) * (w + j2)]);+ }+ return [...L, ...R.reverse()];+};+export const stick = (g: Gfx, c: P[], w0: number, w1: number, alpha: number, seed: number, p: number, o: { rough?: number; ends?: number; color?: string } = {}) => {+ if (p <= 0 || c.length < 2) return; fillShape(g, taperPoly(c, w0, w1, seed, { rough: o.rough ?? 0.6, p, ends: o.ends ?? 0 }), o.color ?? INK, alpha);+};++// ---------------------------------------------------------------- the side of the stick+// Broad parallel drags clipped to a region, density steered by `keep`. Returns marks, one per drag.+export const sideMarks = (region: P[], o: { angle: number; gap: number; w: number; alpha: number; seed: number; keep?: (x: number, y: number) => boolean; color?: string; per?: number; test?: (x: number, y: number) => boolean }): Mark[] => {+ const { angle, gap, w, alpha, seed, keep = () => true, color = INK, per = 900, test } = o, r = rng(seed), b = bounds(region);+ const runs = hatchRuns(b, angle, gap, (x, y) => (test ? test(x, y) : inside(region, x, y)) && keep(x, y), 4, seed);+ return runs.map((run) => {+ const a = alpha * (0.75 + r() * 0.45), jit: P[] = run.filter((_, k, arr) => k % 3 === 0 || k === arr.length - 1).map(([x, y]) => [x + (r() - 0.5) * 1.6, y + (r() - 0.5) * 1.6]);+ const len = polyLen(jit);+ return { t: 0.12 + len / per, d: (g: Gfx, p: number) => {+ const pts = upTo(jit, p), c = g.cur, bb = bounds(pts); g.touch(bb.x0 - w, bb.y0 - w, bb.x1 + w, bb.y1 + w);+ c.save(); c.lineCap = "round"; c.lineJoin = "round"; c.strokeStyle = color; c.lineWidth = w; c.globalAlpha = a; trace(c, pts, false); c.stroke(); c.restore();+ } };+ });+};++// ---------------------------------------------------------------- rubbing paths (stump and eraser)+// A back-and-forth rub across a region's box: rows `gap` apart, each a zigzag of amplitude `amp`.+export const zigzag = (b: { x0: number; y0: number; x1: number; y1: number }, gap: number, amp: number, seed: number, angle = 0): P[][] => {+ const r = rng(seed), rows: P[][] = [], cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, ca = Math.cos(angle), sa = Math.sin(angle);+ const hw = (b.x1 - b.x0) / 2 + gap, hh = (b.y1 - b.y0) / 2 + gap, R = Math.hypot(hw, hh);+ for (let v = -R, k = 0; v <= R; v += gap, k++) {+ const row: P[] = []; const dir = k % 2 ? -1 : 1;+ for (let u = -R, j = 0; u <= R; u += amp * 0.9, j++) { const uu = dir * u, vv = v + (j % 2 ? amp : -amp) * 0.5 + (r() - 0.5) * amp * 0.3; const x = cx + uu * ca - vv * sa, y = cy + uu * sa + vv * ca; if (x > b.x0 - gap && x < b.x1 + gap && y > b.y0 - gap && y < b.y1 + gap) row.push([x, y]); }+ if (row.length > 1) rows.push(row);+ }+ return rows;+};+export const spiral = (cx: number, cy: number, r0: number, r1: number, turns: number, seed: number): P[] => {+ const r = rng(seed), out: P[] = [], n = Math.round(turns * 28);+ for (let i = 0; i <= n; i++) { const t = i / n, a = t * turns * Math.PI * 2, rr = lerp(r0, r1, t) * (1 + (r() - 0.5) * 0.08); out.push([cx + Math.cos(a) * rr, cy + Math.sin(a) * rr * 0.96]); }+ return out;+};+// a rub is a round, soft, wide stroke: the stump's or the eraser's contact patch dragged along+// `clip` is one outline or several (a union of lobes, traced as subpaths of one nonzero path)+export const clipTo = (c: CanvasRenderingContext2D, clip: P[] | P[][]) => { const many = Array.isArray(clip[0]?.[0]) ? (clip as P[][]) : [clip as P[]]; c.beginPath(); many.forEach((s) => { s.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }); c.clip(); };+export const rubMark = (path: P[], w: number, alpha: number, color = INK, clip?: P[] | P[][], per = 1400): Mark => ({ t: 0.2 + polyLen(path) / per, d: (g, p) => {+ const pts = upTo(path, p), c = g.cur, bb = bounds(pts); g.touch(bb.x0 - w, bb.y0 - w, bb.x1 + w, bb.y1 + w);+ c.save(); if (clip) clipTo(c, clip); c.lineCap = "round"; c.lineJoin = "round"; c.strokeStyle = color; c.lineWidth = w; c.globalAlpha = alpha; trace(c, pts, false); c.stroke(); c.restore();+} });+// a soft-edged dab (a leaf, a bud, a blot): a small bitten blob+export const dab = (g: Gfx, x: number, y: number, rx: number, ry: number, rot: number, alpha: number, seed: number, color = INK) => {+ const r = rng(seed), n = 9, pts: P[] = [];+ for (let i = 0; i < n; i++) { const a = (i / n) * Math.PI * 2, k = 0.75 + r() * 0.45, px = Math.cos(a) * rx * k, py = Math.sin(a) * ry * k; pts.push([x + px * Math.cos(rot) - py * Math.sin(rot), y + px * Math.sin(rot) + py * Math.cos(rot)]); }+ fillShape(g, pts, color, alpha);+};+export const noiseAt = (seed: number, x: number, y: number, f = 0.01) => fractal(seed, x, y, f, f, 3);diff --git a/engine/src/canvas-core/colouredPencil.ts b/engine/src/canvas-core/colouredPencil.tsnew file mode 100644index 0000000..5a4ec4f--- /dev/null+++ b/engine/src/canvas-core/colouredPencil.ts@@ -0,0 +1,435 @@+import { fractal, type P } from "./core";+import type { Film } from "./film";+import { crowGeometry, crowPasses, crowSilhouette } from "./colouredPencilCrow";+import { Sheet, contour, dot, edgeDist, ellipseR, hatch as hatchRaw, layLine, minus, poly, replay, smoothstep, union, type Cue, type Region } from "./colouredPencilKit";++// THE TIN REPAIRMAN · coloured pencil on cream paper.+//+// MEDIUM, physically: wax-based coloured pencils, sharpened but not needle-fine, on a cream+// cartridge sheet with a real tooth. The lead only deposits on the ridges of the tooth, so every+// passage of colour is speckled with the cream of the valleys; pressing harder fills more of them.+// MARKS: straight, slightly bowed hatching strokes, pressure arriving fast and flicking off,+// laid side by side in strips, almost all in ONE dominant diagonal (lower-left to upper-right, the+// natural swing of a right hand). EDGE: mostly none; an edge is where the hatching stops. A few+// thin contours in a darker pencil (sepia-graphite), broken, heavier on the shade side, drawn last.+// TONE: from pressure and from stacking: a second hue hatched over the first (blue over teal,+// violet over dusk blue, red-brown over ochre), darks CROSS-hatched in a second direction, never+// filled. Colour thickens toward the edge of every form; solid forms keep a paler band on their TOP+// face, because the light is above. ORDER: faint graphite lay-in, big local-colour passes light to+// dark, second-hue layering, darks, contours, then the lamp's halo in yellow over near-bare paper.+// PAPER: cream (#f3ecdc), its tooth one field shared by every layer.+//+// LIGHT: one warm desk lamp (an anglepoise, brick-red enamel shade) hanging over the music box;+// dusk in the open window is a weak cool fill only. Cast shadows: the robot's falls LEFT (the lamp+// is to its right), the box's falls right and forward, the crow's falls right.+//+// SUBJECT: a small wind-up tin robot (boxy tin toy: pressed-tin torso and head as true blocks with+// top faces, riveted seams, porthole eyes, ribbed hose arms, pincer hands, a brass wind-up key in+// its back) mends an open cylinder music box (pinned brass drum, steel comb, bedplate screws,+// butterfly winding key) on a plank workbench at dusk: its screwdriver is on one of the comb's two+// fixing screws; the other hole is empty. Nearer to us, on the bench's front edge with its tail+// across the box's corner, a carrion crow walks off toward the open window, head turned back over+// its shoulder, the missing screw crosswise in its bill.+// REFERENCE (from knowledge): tin toys of the 1950s Japanese "robot" type for construction and+// seams; a Swiss cylinder movement for the drum/comb layout; carrion crow in walking profile+// (bill as long as the head, nasal bristles, shaggy throat hackles, folded primaries reaching+// two-thirds down the tail, scaled tarsus, three toes forward one back); anglepoise lamp geometry.+// Style reference for the MARK only: a coloured-pencil children's-book film (Kevin Ngo's piano+// piece). Its scene, cast and staging are not used.++const D = 1080; // design units; the sheet is rescaled to meta W x H+const ANG = -1.02; // the dominant hatch diagonal: up and to the right+const X2 = 0.22; // the cross-hatch direction for darks+const PAPER = "#f3ecdc";++const C = {+ lay: "#8e8894", sepia: "#3e3134", graphite: "#34333d", blueBlack: "#262a3f",+ dusk: "#7f8dc2", violet: "#8f78b6", indigo: "#3d467f",+ skyTop: "#3f4b8f", skyMid: "#9272ad", skyLow: "#e8977a", skyGold: "#f1c47a", roof: "#4b3f6e",+ ochre: "#cf9557", woodRed: "#b35a31", walnut: "#5c3622", umberDk: "#3b2519", umber: "#7d4a2b",+ mahog: "#8a3822", lining: "#a8262f", brass: "#d6a63e", brassDk: "#8a6420", steel: "#626875",+ teal: "#3aa0a0", tBlue: "#2f5ea8", tDeep: "#22416a", tinRed: "#d1452e",+ shade: "#c5452e", shadeDk: "#7a2823", yellow: "#f6c93f", amber: "#f2a33a", pale: "#f8dc78",+ crow: "#27262e", sheen: "#4f58a3", screw: "#8d93a0", feather: "#9199cf",+};++// ---------------------------------------------------------------- projection for the solid things+const PITCH = 0.36, cP = Math.cos(PITCH), sP = Math.sin(PITCH);+type V3 = [number, number, number];+const proj = (ox: number, oy: number, yaw: number, k = 1) => ([x, y, z]: V3): P => { const X = x * Math.cos(yaw) + z * Math.sin(yaw), Z = -x * Math.sin(yaw) + z * Math.cos(yaw); return [ox + X * k, oy - (y * cP + Z * sP) * k]; };+const cuboid = (pr: (v: V3) => P, x0: number, x1: number, y0: number, y1: number, z0: number, z1: number) => ({+ front: [pr([x0, y0, z0]), pr([x1, y0, z0]), pr([x1, y1, z0]), pr([x0, y1, z0])],+ top: [pr([x0, y1, z0]), pr([x1, y1, z0]), pr([x1, y1, z1]), pr([x0, y1, z1])],+ left: [pr([x0, y0, z1]), pr([x0, y0, z0]), pr([x0, y1, z0]), pr([x0, y1, z1])],+ right: [pr([x1, y0, z0]), pr([x1, y0, z1]), pr([x1, y1, z1]), pr([x1, y1, z0])],+});+const circ3 = (pr: (v: V3) => P, f: (a: number) => V3, n = 20): P[] => Array.from({ length: n }, (_, i) => pr(f((i / n) * Math.PI * 2)));+const ring = (cx: number, cy: number, rx: number, ry: number, n = 24, rot = 0): P[] => Array.from({ length: n }, (_, i) => { const a = (i / n) * Math.PI * 2, x = Math.cos(a) * rx, y = Math.sin(a) * ry; return [cx + x * Math.cos(rot) - y * Math.sin(rot), cy + x * Math.sin(rot) + y * Math.cos(rot)] as P; });+const tubeAlong = (c: P[], r: number): P[] => { const L: P[] = [], R: P[] = []; c.forEach((p, i) => { const q = c[Math.min(c.length - 1, i + 1)], o = c[Math.max(0, i - 1)], dx = q[0] - o[0], dy = q[1] - o[1], l = Math.hypot(dx, dy) || 1; L.push([p[0] - (dy / l) * r, p[1] + (dx / l) * r]); R.push([p[0] + (dy / l) * r, p[1] - (dx / l) * r]); }); return [...L, ...R.reverse()]; };+// every hatch in this plate: short strokes, a firm hand+// the dominant diagonal, turned a few degrees per surface the way a hand re-settles for each patch+const hatch: typeof hatchRaw = (S, reg, o) => hatchRaw(S, reg, { ...o, ang: o.ang + ((((o.seed * 7919) % 13) + 13) % 13 - 6) * 0.018, gap: o.gap * 0.55, len: o.len * 0.85, a: Math.min(1, o.a * 0.72) });+// distance to one edge of a face: the top band of a solid is measured from its top edge+const segD = (a: P, b: P) => (x: number, y: number) => { const dx = b[0] - a[0], dy = b[1] - a[1], t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / (dx * dx + dy * dy || 1))); return Math.hypot(x - a[0] - t * dx, y - a[1] - t * dy); };+const lerpP = (a: P, b: P, t: number): P => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];++// ---------------------------------------------------------------- the scene, as geometry+const scene = () => {+ // the bench: plank top seen from above, a front apron with a drawer, darkness underneath+ const top: P[] = [[-10, 640], [D + 10, 640], [D + 10, 800], [-10, 800]];+ const nose: P[] = [[-10, 800], [D + 10, 800], [D + 10, 810], [-10, 810]];+ const apron: P[] = [[-10, 810], [D + 10, 810], [D + 10, 892], [-10, 892]];+ const drawer: P[] = [[640, 822], [900, 822], [900, 880], [640, 880]];+ const under: P[] = [[-10, 892], [D + 10, 892], [D + 10, D + 10], [-10, D + 10]];+ const legs: P[][] = [[[46, 892], [100, 892], [100, D + 10], [46, D + 10]], [[980, 892], [1034, 892], [1034, D + 10], [980, D + 10]]];++ // the open window the crow came in by+ const win = { x0: 700, x1: 988, y0: 74, y1: 418 };+ const frame: P[] = [[win.x0 - 16, win.y0 - 16], [win.x1 + 16, win.y0 - 16], [win.x1 + 16, win.y1 + 4], [win.x0 - 16, win.y1 + 4]];+ const opening: P[] = [[win.x0, win.y0], [win.x1, win.y0], [win.x1, win.y1], [win.x0, win.y1]];+ const sill: P[] = [[win.x0 - 30, win.y1 + 2], [win.x1 + 30, win.y1 + 2], [win.x1 + 36, win.y1 + 20], [win.x0 - 36, win.y1 + 20]];+ const leftSash: P[] = [[win.x0, win.y0], [846, win.y0], [846, win.y1], [win.x0, win.y1]];+ const leftGlass: P[] = [[win.x0 + 12, win.y0 + 12], [834, win.y0 + 12], [834, win.y1 - 12], [win.x0 + 12, win.y1 - 12]];+ const openSash: P[] = [[win.x1, win.y0 - 2], [1068, win.y0 - 34], [1068, win.y1 + 36], [win.x1, win.y1 + 2]];+ const openGlass: P[] = [[win.x1 + 10, win.y0 + 8], [1058, win.y0 - 18], [1058, win.y1 + 18], [win.x1 + 10, win.y1 - 8]];+ const roofs: P[] = [[win.x0, 372], [728, 372], [728, 350], [760, 328], [792, 350], [792, 366], [818, 366], [818, 340], [826, 340], [826, 358], [862, 358], [862, 344], [900, 318], [936, 344], [936, 376], [962, 376], [962, 360], [win.x1, 360], [win.x1, win.y1], [win.x0, win.y1]];+ const moon = minus(ellipseR(915, 142, 19, 19), ellipseR(924, 136, 17, 17));++ // the lamp: heavy round base on the back edge, two arms of paired rods, a bell shade over the box+ const pivot: P = [392, 196], A: P = [0.277, 0.961], B: P = [0.961, -0.277];+ const sh = (a: number, b: number): P => [pivot[0] + A[0] * a + B[0] * b, pivot[1] + A[1] * a + B[1] * b];+ const shadeProf: [number, number][] = [[-8, 12], [4, 18], [22, 24], [48, 33], [74, 44], [96, 56], [108, 64]];+ const shadeOut: P[] = [...shadeProf.map(([a, h]) => sh(a, -h)), ...[...shadeProf].reverse().map(([a, h]) => sh(a, h))];+ const mouthC = sh(108, 0), mouth = ring(mouthC[0], mouthC[1], 64, 15, 28, Math.atan2(B[1], B[0]));+ const glow = mouth.filter((p) => (p[0] - mouthC[0]) * A[0] + (p[1] - mouthC[1]) * A[1] >= -2);+ const bulb = ring(mouthC[0] + A[0] * 4, mouthC[1] + A[1] * 4, 22, 11, 16, Math.atan2(B[1], B[0]));+ const baseC: P = [724, 636], baseTop = ring(baseC[0], baseC[1] - 10, 46, 11, 28), baseSide: P[] = [...ring(baseC[0], baseC[1] - 10, 46, 11, 28).slice(0, 15), ...ring(baseC[0], baseC[1] + 5, 46, 11, 28).slice(0, 15).reverse()];+ const hinge: P = [726, 604], elbow: P = [612, 318];+ const armLo = tubeAlong([hinge, elbow], 5), armUp = tubeAlong([elbow, sh(-4, 0)], 4.5);+ const riser = tubeAlong([[baseC[0], baseC[1] - 14], hinge], 7);++ // the music box: yawed a little toward the robot, lid thrown back past upright+ const bp = proj(552, 756, 0.18), bx = { x0: -125, x1: 125, h: 78, z0: -55, z1: 55 };+ const box = cuboid(bp, bx.x0, bx.x1, 0, bx.h, bx.z0, bx.z1);+ const lidA = 0.42, lidL = 100, ly = bx.h + lidL * Math.cos(lidA), lz = bx.z1 + lidL * Math.sin(lidA), nY = -Math.sin(lidA) * 9, nZ = Math.cos(lidA) * 9;+ const lidIn: P[] = [bp([bx.x0, bx.h, bx.z1]), bp([bx.x1, bx.h, bx.z1]), bp([bx.x1, ly, lz]), bp([bx.x0, ly, lz])];+ const lidEdge: P[] = [bp([bx.x0, ly, lz]), bp([bx.x1, ly, lz]), bp([bx.x1, ly + nY, lz + nZ]), bp([bx.x0, ly + nY, lz + nZ])];+ const lidPanel: P[] = [[0.1, 0.16], [0.9, 0.16], [0.9, 0.86], [0.1, 0.86]].map(([u, v]) => bp([bx.x0 + (bx.x1 - bx.x0) * u, bx.h + lidL * Math.cos(lidA) * v, bx.z1 + lidL * Math.sin(lidA) * v]));+ const inner: P[] = [bp([-117, bx.h, -47]), bp([117, bx.h, -47]), bp([117, bx.h, 47]), bp([-117, bx.h, 47])];+ const bed: P[] = [bp([-104, 52, -40]), bp([100, 52, -40]), bp([100, 52, 38]), bp([-104, 52, 38])];+ const drumC = (x: number): V3 => [x, 75, 14];+ const drum: P[] = [...Array.from({ length: 9 }, (_, i) => bp([-82 + i * 20, 62 + 13, 14] as V3)), ...Array.from({ length: 9 }, (_, i) => bp([78 - i * 20, 62 - 9, 14 - 10] as V3))];+ const drumEnds = [circ3(bp, (a) => [-84, 62 + Math.sin(a) * 13, 14 + Math.cos(a) * 13], 16), circ3(bp, (a) => [80, 62 + Math.sin(a) * 13, 14 + Math.cos(a) * 13], 16)];+ const comb: P[] = [bp([-70, 64, -12]), bp([76, 64, -12]), bp([76, 66, 4]), bp([-70, 66, 4])];+ const drivePt = bp([-62, 64, -8]); // the comb's fixing screw the robot is turning+ const emptyHole = bp([66, 64, -8]); // its twin's hole, empty: that screw is in the crow's bill+ const keyShaft = [bp([bx.x1, 40, 0]), bp([bx.x1 + 24, 40, 0])];+ const keyBow = [circ3(bp, (a) => [bx.x1 + 30, 52 + Math.sin(a) * 12, Math.cos(a) * 5], 12), circ3(bp, (a) => [bx.x1 + 30, 28 + Math.sin(a) * 12, Math.cos(a) * 5], 12)];+ const escut = circ3(bp, (a) => [0 + Math.cos(a) * 9, 44 + Math.sin(a) * 11, bx.z0 - 0.5], 14);+ const inlay: P[] = [bp([-112, 10, bx.z0]), bp([112, 10, bx.z0]), bp([112, 68, bx.z0]), bp([-112, 68, bx.z0])];++ // the robot: yawed toward the box so its left flank shows, a little larger than life-size for a tin toy+ const rp = proj(300, 744, -0.44, 1.12);+ const feet = [cuboid(rp, -46, -6, 0, 12, -26, 22), cuboid(rp, 6, 46, 0, 12, -26, 22)];+ const legs2 = [cuboid(rp, -40, -12, 12, 52, -15, 15), cuboid(rp, 12, 40, 12, 52, -15, 15)];+ const torso = cuboid(rp, -56, 56, 52, 178, -36, 36);+ const neck = cuboid(rp, -14, 14, 178, 190, -12, 12);+ const head = cuboid(rp, -47, 47, 190, 268, -33, 33);+ const fr = (face: "torso" | "head", x: number, y: number): P => rp([x, y, face === "torso" ? -36.5 : -33.5]);+ const eyes = [-21, 21].map((ex) => circ3(rp, (a) => [ex + Math.cos(a) * 13, 236 + Math.sin(a) * 13, -33.5], 22));+ const pupils = [-21, 21].map((ex) => rp([ex + 5, 232, -34]));+ const mouthG: P[] = [fr("head", -20, 204), fr("head", 20, 204), fr("head", 20, 214), fr("head", -20, 214)];+ const plate: P[] = [fr("torso", -38, 92), fr("torso", 38, 92), fr("torso", 38, 162), fr("torso", -38, 162)];+ const dial = circ3(rp, (a) => [-14 + Math.cos(a) * 14, 140 + Math.sin(a) * 14, -37], 20), dialC = rp([-14, 140, -37]), needle = rp([-5, 149, -37]);+ const button = circ3(rp, (a) => [20 + Math.cos(a) * 7, 140 + Math.sin(a) * 7, -37], 14);+ const antenna = [rp([0, 268, 0]), rp([2, 296, 0])], bobble = rp([2, 302, 0]);+ const earL = circ3(rp, (a) => [-47.5, 230 + Math.sin(a) * 11, Math.cos(a) * 11], 16);+ // wind-up key out of the back, turned so its bow shows past the left flank+ const kS = rp([-8, 120, 36]), kE = rp([-8, 120, 70]);+ const kBow = [circ3(rp, (a) => [-8 + Math.cos(a) * 3, 136 + Math.sin(a) * 15, 76], 14), circ3(rp, (a) => [-8 + Math.cos(a) * 3, 104 + Math.sin(a) * 15, 76], 14)];+ // arms: the near-box arm reaches over the rim with a screwdriver; the other hangs, holding a spare cog+ const shR = rp([60, 164, -4]), shL = rp([-60, 164, -4]);+ const tip = drivePt, handR: P = [tip[0] - 24, tip[1] - 22], elbowR: P = [shR[0] + 30, shR[1] + 44];+ const armR = [shR, elbowR, handR], armL = [shL, [shL[0] - 10, shL[1] + 44] as P, [shL[0] - 6, shL[1] + 88] as P];+ const driverH = [lerpP(handR, tip, -0.22), lerpP(handR, tip, 0.42)], driverS = [lerpP(handR, tip, 0.42), tip];+ const cogL = armL[2];++ // the crow, NEARER than the box: walking right along the bench's front edge, tail across the+ // box's corner, head turned back over its shoulder (guilty) with the stolen screw crosswise in its bill+ const cw = (p: P): P => [872 + (p[0] - 853) * 0.74, 798 + (p[1] - 780) * 0.74]; // ~30% smaller than pass 2: the robot and the box stay the story's centre+ const hw = (p: P): P => cw([936 + (p[0] - 936) * 1.25, 500 + (p[1] - 500) * 1.25]); // the head is a crow's, not a songbird's: big, with a long bill+ const CR = crowGeometry(cw, hw), crowOut = CR.body, headO = CR.head, bill = CR.bill, legBack = CR.legBack, legFront = CR.legFront;+ // cast shadows (hand-placed from the lamp's position) and the loose parts on the bench+ const shRobot: P[] = [[262, 738], [354, 745], [336, 762], [252, 772], [150, 768], [120, 756], [170, 746]];+ const shBox: P[] = [[426, 758], [676, 757], [700, 752], [738, 760], [764, 772], [724, 786], [560, 784], [436, 774]];+ const shCrow: P[] = [[846, 797], [880, 795], [930, 797], [966, 800], [880, 802], [846, 801]];+ const shLamp: P[] = [[748, 646], [780, 642], [792, 650], [764, 656], [730, 654]];+ const parts = { screws: [[[712, 780], [728, 774]], [[748, 790], [762, 790]]] as P[][], cog: [690, 790] as P };++ return { top, nose, apron, drawer, under, legs, win, frame, opening, sill, leftSash, leftGlass, openSash, openGlass, roofs, moon, shadeOut, mouthC, mouth, glow, bulb, baseC, baseTop, baseSide, armLo, armUp, riser, hinge, elbow, sh, box, lidIn, lidEdge, lidPanel, inner, bed, drum, drumEnds, drumC, comb, drivePt, emptyHole, keyShaft, keyBow, escut, inlay, bp, feet, legs2, rp, torso, neck, head, eyes, pupils, mouthG, plate, dial, dialC, needle, button, antenna, bobble, earL, kS, kE, kBow, armR, armL, driverH, driverS, cogL, cw, crowOut, bill, legBack, legFront, headO, CR, shRobot, shBox, shCrow, shLamp, parts };+};++// ---------------------------------------------------------------- the drawing, pass by pass+const draw = (): Sheet => {+ const G = scene(), S = new Sheet();+ const R = (p: P[]) => poly(p);+ const faces = (c: ReturnType<typeof cuboid>, keys: ("front" | "top" | "left" | "right")[]) => union(...keys.map((k) => R(c[k])));+ const robotSil = union(...G.feet.map((f) => faces(f, ["front", "top", "left"])), ...G.legs2.map((f) => faces(f, ["front", "left"])), faces(G.torso, ["front", "top", "left"]), faces(G.neck, ["front", "left"]), faces(G.head, ["front", "top", "left"]), R(tubeAlong(G.armR, 9)), R(tubeAlong(G.armL, 9)), R(tubeAlong(G.antenna, 2.5)), ellipseR(G.bobble[0], G.bobble[1], 7, 7), R(tubeAlong([G.kS, G.kE], 3)), ...G.kBow.map(R));+ const crowSil = crowSilhouette(G.CR), CP = crowPasses(G.CR);+ const inFront = union(crowSil, R(tubeAlong(G.armR, 9)), R(tubeAlong(G.driverH, 4.5)), R(tubeAlong(G.driverS, 2)));+ const RB = (p: P[]) => minus(R(p), inFront); // a box surface, minus whatever stands in front of it+ const boxSil = union(R(G.box.front), R(G.box.top), R(G.box.right), R(G.lidIn), R(G.lidEdge));+ const lampSil = union(R(G.shadeOut), R(G.mouth), R(G.armLo), R(G.armUp), R(G.riser), R(G.baseTop), R(G.baseSide));+ const M = G.mouthC, dM = (x: number, y: number) => Math.hypot(x - M[0], y - M[1]);++ // 1 · lay-in: faint graphite construction, ruled freehand past the corners+ S.pass("lay", 0);+ let sd = 1; const box4 = (q: P[]) => q.forEach((p, i) => layLine(S, p, q[(i + 1) % q.length], C.lay, sd++));+ layLine(S, [0, 640], [D, 640], C.lay, sd++); layLine(S, [0, 800], [D, 800], C.lay, sd++); layLine(S, [0, 892], [D, 892], C.lay, sd++);+ box4(G.opening);+ layLine(S, G.hinge, G.elbow, C.lay, sd++); layLine(S, G.elbow, G.sh(0, 0), C.lay, sd++);+ contour(S, G.shadeOut, { w: 1.0, col: C.lay, a: 0.42, seed: sd++, closed: true, seg: 90 });+ contour(S, G.baseTop, { w: 1.0, col: C.lay, a: 0.42, seed: sd++, closed: true, seg: 90 });+ box4(G.box.front); box4(G.box.top); box4(G.lidIn);+ box4(G.torso.front); box4(G.torso.left); box4(G.head.front); box4(G.head.left);+ G.legs2.forEach((l) => box4(l.front)); G.feet.forEach((f) => box4(f.front));+ layLine(S, G.armR[0], G.armR[1], C.lay, sd++); layLine(S, G.armR[1], G.armR[2], C.lay, sd++);+ // the crow found as a gesture: the long line of the back through the tail, head and body masses+ contour(S, ([[905, 500], [840, 566], [760, 626], [672, 712]] as P[]).map(G.cw), { w: 1.0, col: C.lay, a: 0.44, seed: sd++, seg: 120 });+ contour(S, G.headO, { w: 1.0, col: C.lay, a: 0.42, seed: sd++, closed: true, seg: 100 });+ contour(S, ([[905, 520], [930, 600], [900, 690], [820, 716], [760, 700], [800, 600]] as P[]).map(G.cw), { w: 1.0, col: C.lay, a: 0.4, seed: sd++, closed: true, seg: 120 });+ layLine(S, G.bill[0], G.bill[4], C.lay, sd++); layLine(S, G.legBack[0], G.legBack[2], C.lay, sd++); layLine(S, G.legFront[0], G.legFront[2], C.lay, sd++);++ // 2 · the wall at dusk: light pressure dusk-blue, the paper left nearly bare where the lamp spills+ const wall = minus(R([[-10, -10], [D + 10, -10], [D + 10, 640], [-10, 640]]), R(G.frame), R(G.sill), R(G.openSash), lampSil, robotSil, boxSil, crowSil);+ const wallD = (x: number, y: number) => { const lamp = 0.04 + 0.4 * smoothstep(120, 520, dM(x, y)), corner = 0.3 * smoothstep(380, 700, Math.hypot(x - 520, y - 420)), patch = 0.55 + 0.9 * (fractal(91, x, y, 0.006, 0.009, 2) - 0.5); return (lamp + corner) * patch + (y > 612 ? 0.15 : 0); };+ S.pass("wall", 0);+ hatch(S, wall, { ang: ANG, gap: 3.2, len: 38, w: 1.5, col: C.dusk, a: 0.7, seed: 100, dens: wallD });++ // 3 · the sky in the window: indigo above, violet, a rose-gold band; the moon left as paper; roofs+ const sky = minus(R(G.opening), R(G.leftSash), R(G.roofs), G.moon);+ const glass = minus(R(G.leftGlass), R(G.roofs), R([[G.win.x0, 238], [846, 238], [846, 252], [G.win.x0, 252]]));+ S.pass("sky", 1);+ const band = (y: number, c: number, s: number) => Math.exp(-(((y - c) / s) ** 2));+ const skyT = (y: number) => (y - G.win.y0) / (G.win.y1 - G.win.y0);+ hatch(S, union(sky, glass), { ang: ANG, gap: 2.4, len: 30, w: 1.5, col: C.skyTop, a: 0.75, seed: 110, dens: (x, y) => (1 - skyT(y) * 1.15) * (glass.has(x, y) ? 0.7 : 1) });+ hatch(S, union(sky, glass), { ang: ANG, gap: 2.6, len: 30, w: 1.5, col: C.skyMid, a: 0.6, seed: 111, dens: (x, y) => band(skyT(y), 0.55, 0.25) * (glass.has(x, y) ? 0.7 : 1) });+ hatch(S, union(sky, glass), { ang: ANG, gap: 2.4, len: 30, w: 1.5, col: C.skyLow, a: 0.62, seed: 112, dens: (x, y) => band(skyT(y), 0.86, 0.15) * (glass.has(x, y) ? 0.7 : 1) });+ hatch(S, union(sky, glass), { ang: ANG, gap: 2.8, len: 26, w: 1.4, col: C.skyGold, a: 0.6, seed: 113, dens: (x, y) => band(skyT(y), 0.92, 0.08) });+ hatch(S, R(G.roofs), { ang: ANG, gap: 2.2, len: 24, w: 1.5, col: C.roof, a: 0.85, seed: 114, dens: () => 0.95 });+ hatch(S, R(G.roofs), { ang: X2, gap: 3.2, len: 20, w: 1.3, col: C.indigo, a: 0.6, seed: 115, dens: (x, y) => 0.4 + (y - 330) / 160 });+ // the window's painted frame: barely touched, a grey-violet on its shade sides+ const frameWood = minus(union(R(G.frame), R(G.sill)), R(G.opening));+ hatch(S, frameWood, { ang: ANG, gap: 3.4, len: 22, w: 1.2, col: C.violet, a: 0.35, seed: 116, dens: (x, y) => (x > G.win.x1 || y > G.win.y1 + 8 ? 0.8 : 0.3) });+ hatch(S, minus(R(G.leftSash), R(G.leftGlass)), { ang: ANG, gap: 3.4, len: 22, w: 1.2, col: C.violet, a: 0.3, seed: 117, dens: () => 0.35 });+ hatch(S, minus(R(G.openSash), R(G.openGlass)), { ang: ANG, gap: 3, len: 22, w: 1.2, col: C.violet, a: 0.4, seed: 118, dens: () => 0.6 });+ hatch(S, R(G.openGlass), { ang: ANG, gap: 3.0, len: 30, w: 1.3, col: C.skyMid, a: 0.35, seed: 119, dens: (x, y) => 0.35 + 0.3 * skyT(y) });++ // 4 · wood: the bench top pale where the lamp pools, darker to the back and the ends; apron; underneath+ const benchTop = minus(R(G.top), robotSil, boxSil, crowSil, lampSil);+ const pool = (x: number, y: number) => Math.hypot((x - 520) / 330, (y - 715) / 95);+ S.pass("wood", 1);+ hatch(S, benchTop, { ang: ANG, gap: 2.5, len: 30, w: 1.5, col: C.ochre, a: 0.7, seed: 200, dens: (x, y) => 0.14 + 0.55 * smoothstep(0.35, 1.7, pool(x, y)) + 0.2 * smoothstep(700, 645, y) });+ hatch(S, R(G.nose), { ang: ANG, gap: 3, len: 14, w: 1.3, col: C.ochre, a: 0.5, seed: 201, dens: () => 0.5 });+ hatch(S, minus(R(G.apron), R(G.drawer)), { ang: ANG, gap: 2.2, len: 30, w: 1.6, col: C.ochre, a: 0.85, seed: 202, dens: () => 0.95 });+ hatch(S, R(G.drawer), { ang: ANG, gap: 2.4, len: 30, w: 1.5, col: C.ochre, a: 0.8, seed: 203, dens: (x, y) => 0.7 + 0.3 * smoothstep(850, 880, y) });+ const legsR = union(...G.legs.map(R)), underR = minus(R(G.under), legsR);+ hatch(S, underR, { ang: ANG, gap: 2.2, len: 36, w: 1.7, col: C.walnut, a: 0.8, seed: 204, dens: (x, y) => 0.75 + 0.25 * smoothstep(1000, 900, y) });+ hatch(S, legsR, { ang: -1.45, gap: 2.2, len: 40, w: 1.6, col: C.umber, a: 0.9, seed: 205, dens: () => 0.9 });+ // the lamp base and the far window sill are wood too? no: the base is enamel, done with the lamp++ // 5 · the music box: mahogany body, red felt in the lid, brass movement inside+ const boxFront = RB(G.box.front), boxRight = RB(G.box.right), rim = minus(RB(G.box.top), RB(G.inner));+ const dF = edgeDist(G.box.front);+ S.pass("box", 1);+ const tB = segD(G.box.front[3], G.box.front[2]);+ hatch(S, boxFront, { ang: ANG, gap: 2.3, len: 26, w: 1.5, col: C.mahog, a: 1, seed: 300, dens: (x, y) => 0.7 + 0.3 * smoothstep(14, 0, dF(x, y)) - 0.5 * smoothstep(12, 1, tB(x, y)) });+ hatch(S, boxRight, { ang: ANG, gap: 2.2, len: 20, w: 1.5, col: C.mahog, a: 0.9, seed: 301, dens: () => 1 });+ hatch(S, rim, { ang: ANG, gap: 3, len: 14, w: 1.2, col: C.mahog, a: 0.55, seed: 302, dens: () => 0.45 });+ hatch(S, minus(RB(G.lidIn), RB(G.lidPanel)), { ang: ANG, gap: 2.4, len: 22, w: 1.4, col: C.mahog, a: 1, seed: 303, dens: () => 0.9 });+ hatch(S, RB(G.lidEdge), { ang: ANG, gap: 3, len: 12, w: 1.2, col: C.mahog, a: 0.5, seed: 304, dens: () => 0.4 });+ hatch(S, RB(G.lidPanel), { ang: ANG, gap: 2.3, len: 24, w: 1.5, col: C.lining, a: 1, seed: 305, dens: (x, y) => { const q = G.lidPanel, t = (y - q[2][1]) / (q[0][1] - q[2][1]); return 0.5 + 0.5 * t; } });+ const interior = RB(G.inner);+ hatch(S, interior, { ang: ANG, gap: 2.4, len: 22, w: 1.4, col: C.umber, a: 0.8, seed: 306, dens: () => 0.85 });+ const inBox = (r: Region): Region => ({ box: r.box, has: (x, y) => r.has(x, y) && interior.has(x, y) });+ hatch(S, inBox(RB(G.bed)), { ang: ANG, gap: 2.4, len: 18, w: 1.4, col: C.brass, a: 0.85, seed: 307, dens: () => 0.9 });+ hatch(S, inBox(RB(G.drum)), { ang: ANG, gap: 2.2, len: 14, w: 1.4, col: C.brass, a: 0.9, seed: 308, dens: (x, y) => { const tp = G.drum[0][1]; return 0.35 + 0.65 * smoothstep(tp + 4, tp + 22, y); } });+ hatch(S, inBox(RB(G.comb)), { ang: ANG, gap: 2.6, len: 14, w: 1.3, col: C.steel, a: 0.7, seed: 309, dens: () => 0.7 });+ hatch(S, union(...G.keyBow.map(R), R(tubeAlong(G.keyShaft, 2.5))), { ang: ANG, gap: 2, len: 10, w: 1.3, col: C.brass, a: 0.9, seed: 310, dens: () => 0.9 });+ hatch(S, R(G.escut), { ang: ANG, gap: 2, len: 8, w: 1.2, col: C.brass, a: 0.9, seed: 311, dens: () => 0.9 });++ // 6 · the robot: teal tin, the top faces barely pressed, the lit front medium, the far flank full+ const rTop = union(R(G.head.top), R(G.torso.top), ...G.feet.map((f) => R(f.top)));+ const rFront = union(R(G.head.front), R(G.torso.front), R(G.neck.front), ...G.legs2.map((l) => R(l.front)), ...G.feet.map((f) => R(f.front)));+ const rLeft = union(R(G.head.left), R(G.torso.left), R(G.neck.left), ...G.legs2.map((l) => R(l.left)), ...G.feet.map((f) => R(f.left)));+ const eyesR = union(...G.eyes.map(R));+ const dT = edgeDist(G.torso.front), dH = edgeDist(G.head.front);+ const tT = segD(G.torso.front[3], G.torso.front[2]), tH = segD(G.head.front[3], G.head.front[2]);+ const frontD = (x: number, y: number) => { const e = Math.min(dT(x, y), dH(x, y)), top = Math.min(tT(x, y), tH(x, y)); return 0.5 + 0.4 * smoothstep(16, 0, e) + 0.1 * smoothstep(420, 700, y) - 0.45 * smoothstep(16, 2, top); };+ S.pass("robot", 1);+ hatch(S, rTop, { ang: ANG, gap: 3.2, len: 16, w: 1.2, col: C.teal, a: 0.55, seed: 400, dens: () => 0.4 });+ hatch(S, minus(rFront, eyesR, R(G.plate)), { ang: ANG, gap: 2.3, len: 24, w: 1.5, col: C.teal, a: 0.8, seed: 401, dens: frontD });+ hatch(S, R(G.plate), { ang: ANG, gap: 2.6, len: 20, w: 1.4, col: C.teal, a: 0.6, seed: 402, dens: () => 0.55 });+ const armLR = R(tubeAlong(G.armL, 9)), rLeftV = minus(rLeft, armLR);+ hatch(S, rLeftV, { ang: ANG, gap: 2.1, len: 22, w: 1.6, col: C.teal, a: 0.9, seed: 403, dens: () => 1 });+ hatch(S, union(R(tubeAlong(G.armR, 8)), R(tubeAlong(G.armL, 8))), { ang: ANG, gap: 2.2, len: 12, w: 1.3, col: C.steel, a: 0.8, seed: 404, dens: () => 0.8 });+ hatch(S, union(...G.kBow.map(R), R(tubeAlong([G.kS, G.kE], 3))), { ang: ANG, gap: 2, len: 10, w: 1.3, col: C.brass, a: 0.9, seed: 405, dens: () => 0.9 });+ hatch(S, union(ellipseR(G.bobble[0], G.bobble[1], 7, 7), R(G.button), R(tubeAlong(G.driverH, 4))), { ang: ANG, gap: 1.8, len: 8, w: 1.3, col: C.tinRed, a: 0.95, seed: 406, dens: () => 1 });+ hatch(S, R(G.dial), { ang: ANG, gap: 3, len: 10, w: 1.1, col: C.pale, a: 0.6, seed: 407, dens: () => 0.6 });+ hatch(S, eyesR, { ang: ANG, gap: 2.6, len: 10, w: 1.2, col: C.pale, a: 0.7, seed: 408, dens: () => 0.75 });+ hatch(S, R(G.earL), { ang: ANG, gap: 2, len: 8, w: 1.3, col: C.steel, a: 0.8, seed: 409, dens: () => 0.9 });++ // 7 · the lamp: brick-red enamel shade and base, steel arms, the bulb's mouth left almost paper+ const shadeR = minus(R(G.shadeOut), R(G.glow));+ const dS = edgeDist(G.shadeOut);+ S.pass("lamp", 1);+ hatch(S, shadeR, { ang: ANG, gap: 2.2, len: 22, w: 1.5, col: C.shade, a: 1, seed: 500, dens: (x, y) => 0.6 + 0.4 * smoothstep(12, 0, dS(x, y)) - 0.3 * smoothstep(40, 0, Math.hypot(x - G.sh(10, 0)[0], y - G.sh(10, 0)[1])) });+ hatch(S, union(R(G.baseTop), R(G.baseSide)), { ang: ANG, gap: 2.2, len: 18, w: 1.5, col: C.shade, a: 1, seed: 501, dens: (x, y) => (poly(G.baseTop).has(x, y) ? 0.55 : 1) });+ hatch(S, R(G.baseSide), { ang: X2, gap: 2.6, len: 14, w: 1.3, col: C.shadeDk, a: 0.8, seed: 504, dens: () => 0.8 });+ hatch(S, union(R(G.armLo), R(G.armUp), R(G.riser)), { ang: ANG, gap: 2, len: 10, w: 1.2, col: C.steel, a: 1, seed: 502, dens: () => 1 });+ hatch(S, R(G.glow), { ang: ANG, gap: 3.2, len: 14, w: 1.2, col: C.pale, a: 0.5, seed: 503, dens: () => 0.5 });++ // 8 · the crow: its own module (colouredPencilCrow.ts), worked feather group by feather group+ S.pass("crow", 1);+ CP.base(S);+ // the loose parts on the bench, same pencil family as the box's movement+ hatch(S, union(...G.parts.screws.map((s) => R(tubeAlong(s, 2)))), { ang: ANG, gap: 1.6, len: 6, w: 1.1, col: C.screw, a: 0.9, seed: 604, dens: () => 0.9 });+ hatch(S, ellipseR(G.parts.cog[0], G.parts.cog[1], 12, 5), { ang: ANG, gap: 1.8, len: 8, w: 1.2, col: C.brass, a: 0.9, seed: 605, dens: () => 0.9 });+ hatch(S, ellipseR(G.cogL[0] - 2, G.cogL[1] + 8, 10, 10), { ang: ANG, gap: 1.8, len: 8, w: 1.2, col: C.brass, a: 0.9, seed: 606, dens: () => 0.9 });++ // 9 · second hues, hatched over the first: this is where the colour gets its depth+ S.pass("layer", 1);+ hatch(S, wall, { ang: ANG + 0.08, gap: 3.4, len: 30, w: 1.4, col: C.violet, a: 0.5, seed: 700, dens: (x, y) => 0.7 * smoothstep(320, 640, dM(x, y)) * (0.4 + 0.6 * Math.min(1, Math.hypot(x - 540, y - 300) / 520)) });+ hatch(S, benchTop, { ang: ANG + 0.06, gap: 3, len: 28, w: 1.4, col: C.woodRed, a: 0.55, seed: 701, dens: (x, y) => 0.15 + 0.6 * smoothstep(0.7, 1.7, pool(x, y)) });+ hatch(S, minus(R(G.apron), R(G.drawer)), { ang: ANG + 0.06, gap: 2.6, len: 30, w: 1.5, col: C.woodRed, a: 0.7, seed: 702, dens: () => 0.75 });+ hatch(S, R(G.drawer), { ang: ANG + 0.06, gap: 3, len: 30, w: 1.4, col: C.woodRed, a: 0.6, seed: 703, dens: () => 0.5 });+ hatch(S, union(boxFront, boxRight), { ang: ANG + 0.05, gap: 2.8, len: 24, w: 1.4, col: C.lining, a: 0.55, seed: 704, dens: (x, y) => (boxRight.has(x, y) ? 0.9 : 0.35 + 0.4 * smoothstep(14, 0, dF(x, y))) });+ hatch(S, rLeftV, { ang: ANG + 0.07, gap: 2.4, len: 22, w: 1.5, col: C.tBlue, a: 0.8, seed: 705, dens: () => 0.9 });+ hatch(S, minus(rFront, eyesR, R(G.plate)), { ang: ANG + 0.07, gap: 2.8, len: 22, w: 1.4, col: C.tBlue, a: 0.6, seed: 706, dens: (x, y) => 0.1 + 0.55 * smoothstep(12, 0, Math.min(dT(x, y), dH(x, y))) + 0.25 * smoothstep(300, 250, x) });+ hatch(S, rTop, { ang: ANG, gap: 3.4, len: 14, w: 1.2, col: C.pale, a: 0.6, seed: 707, dens: () => 0.6 });+ hatch(S, shadeR, { ang: ANG + 0.06, gap: 2.8, len: 20, w: 1.4, col: C.shadeDk, a: 0.6, seed: 710, dens: (x, y) => smoothstep(0, 40, (x - G.mouthC[0]) * 0.96 - (y - G.mouthC[1]) * 0.28 + 30) });+ hatch(S, RB(G.lidPanel), { ang: ANG + 0.06, gap: 2.8, len: 20, w: 1.4, col: C.shadeDk, a: 0.5, seed: 711, dens: (x, y) => 0.6 * smoothstep(560, 640, y) });+ hatch(S, inBox(union(RB(G.drum), RB(G.bed))), { ang: ANG + 0.06, gap: 3, len: 12, w: 1.3, col: C.amber, a: 0.6, seed: 712, dens: () => 0.6 });++ // 10 · darks: cast shadows and the deepest places, cross-hatched in a second direction, never filled+ S.pass("darks", 2);+ const shadowTone = (col: string, seed: number, reg: Region, d = 0.9) => { hatch(S, reg, { ang: ANG, gap: 2.4, len: 22, w: 1.5, col, a: 0.75, seed, dens: () => d }); hatch(S, reg, { ang: X2, gap: 3, len: 22, w: 1.4, col, a: 0.6, seed: seed + 1, dens: () => d * 0.85 }); hatch(S, reg, { ang: ANG + 0.35, gap: 3.2, len: 20, w: 1.4, col: C.tBlue, a: 0.5, seed: seed + 50, dens: () => d * 0.75 }); };+ shadowTone(C.walnut, 800, minus(R(G.shRobot), robotSil));+ shadowTone(C.walnut, 802, minus(R(G.shBox), boxSil));+ shadowTone(C.walnut, 804, minus(R(G.shCrow), crowSil));+ shadowTone(C.walnut, 806, minus(R(G.shLamp), lampSil), 0.7);+ hatch(S, underR, { ang: X2, gap: 2.8, len: 34, w: 1.6, col: C.umberDk, a: 0.7, seed: 808, dens: (x, y) => 0.35 + 0.55 * smoothstep(1010, 900, y) });+ hatch(S, legsR, { ang: X2, gap: 3, len: 20, w: 1.3, col: C.umberDk, a: 0.6, seed: 807, dens: (x) => 0.7 * smoothstep(18, 54, x < 540 ? x - 46 : x - 980) });+ hatch(S, R([[-10, 892], [D + 10, 892], [D + 10, 920], [-10, 920]]), { ang: ANG + 0.5, gap: 3, len: 24, w: 1.4, col: C.blueBlack, a: 0.6, seed: 809, dens: () => 0.8 });+ hatch(S, interior, { ang: X2, gap: 2.6, len: 18, w: 1.4, col: C.walnut, a: 0.7, seed: 810, dens: (x, y) => 0.5 + 0.4 * smoothstep(G.inner[3][1], G.inner[0][1], y) });+ hatch(S, rLeftV, { ang: X2, gap: 2.8, len: 18, w: 1.3, col: C.tDeep, a: 0.7, seed: 813, dens: () => 0.75 });+ hatch(S, union(R(tubeAlong(G.armL, 8)), R(tubeAlong(G.armR, 8))), { ang: X2, gap: 3, len: 10, w: 1.2, col: C.tDeep, a: 0.6, seed: 819, dens: () => 0.6 });+ hatch(S, union(RB(G.box.right), R(tubeAlong([...G.box.front.slice(0, 2)], 5))), { ang: X2, gap: 2.8, len: 16, w: 1.3, col: C.walnut, a: 0.65, seed: 814, dens: () => 0.8 });+ hatch(S, R(G.mouthG), { ang: X2, gap: 1.8, len: 10, w: 1.3, col: C.tDeep, a: 0.9, seed: 815, dens: () => 1 });+ // the drawer's gap and the underside of the bench nose+ hatch(S, R([[640, 878], [900, 878], [900, 883], [640, 883]]), { ang: X2, gap: 1.6, len: 30, w: 1.3, col: C.walnut, a: 0.8, seed: 817, dens: () => 1 });+ hatch(S, R([[-10, 810], [D + 10, 810], [D + 10, 818], [-10, 818]]), { ang: X2, gap: 2, len: 30, w: 1.3, col: C.walnut, a: 0.6, seed: 818, dens: () => 0.8 });+ // the robot's pupils: tiny cross-hatched darks+ G.pupils.forEach((p, i) => { hatch(S, ellipseR(p[0], p[1], 5.5, 5.5), { ang: ANG, gap: 1.4, len: 8, w: 1.2, col: C.blueBlack, a: 0.95, seed: 820 + i, dens: () => 1 }); hatch(S, ellipseR(p[0], p[1], 5.5, 5.5), { ang: X2, gap: 1.6, len: 8, w: 1.1, col: C.blueBlack, a: 0.9, seed: 824 + i, dens: () => 1 }); });++ // 11 · contours: sparse, thin, a darker pencil; heavier on the shade side, lost where the light is+ S.pass("line", 1);+ const ln = (pts: P[], seed: number, o: { w?: number; a?: number; col?: string; closed?: boolean; keep?: (x: number, y: number) => boolean; seg?: number; skip?: number; smooth?: boolean } = {}) => contour(S, pts, { w: o.w ?? 1.25, col: o.col ?? C.sepia, a: o.a ?? 0.8, seed, closed: o.closed, keep: o.keep, seg: o.seg ?? 50, skip: o.skip ?? 0.08, smooth: o.smooth ?? true });+ const edge = (a: P, b: P, seed: number, o: { w?: number; a?: number; col?: string } = {}) => ln([a, b], seed, { ...o, smooth: false, skip: 0 });+ // bench: the top's front edge, two plank seams, a few grain lines, drawer and knob+ edge([-10, 800], [D + 10, 800], 900, { w: 1.3 }); edge([-10, 892], [D + 10, 892], 901, { w: 1.1, a: 0.6 });+ [[690, 0.5], [742, 0.6]].forEach(([y, a], i) => ln([[-10, y], [300, y + 1], [700, y - 1], [D + 10, y]], 902 + i, { w: 1.0, a, col: C.umber, skip: 0.25, seg: 80 }));+ [[660, 40, 330], [715, 380, 640], [770, 60, 280], [725, 820, 1070], [672, 700, 960]].forEach(([y, x0, x1], i) => ln([[x0, y], [(x0 + x1) / 2, y + 3], [x1, y - 1]], 910 + i, { w: 0.9, a: 0.45, col: C.umber, skip: 0.3, seg: 70 }));+ G.legs.forEach((l, i) => { edge(l[1], [l[1][0], D], 926 + i, { w: 1.1, a: 0.6 }); edge(l[0], [l[0][0], D], 928 + i, { w: 0.9, a: 0.4 }); });+ ln([...G.drawer, G.drawer[0]], 920, { w: 1.1, a: 0.7, smooth: false }); dot(S, 770, 850, 6, C.brassDk, 0.9, 1.6); dot(S, 770, 850, 3, C.sepia, 0.9);+ // window: the mullion, the glazing bar, the open casement's edges, sill underside+ ln([...G.leftSash, G.leftSash[0]], 921, { w: 1.0, a: 0.55, smooth: false, skip: 0.2 }); edge([G.win.x0, 245], [846, 245], 922, { w: 1, a: 0.5 });+ ln([...G.openSash, G.openSash[0]], 923, { w: 1.0, a: 0.55, smooth: false, skip: 0.15 }); edge(G.sill[3], G.sill[2], 924, { w: 1.1, a: 0.6 });+ ln([...G.frame, G.frame[0]], 925, { w: 0.9, a: 0.4, smooth: false, skip: 0.35 });+ // lamp: the shade's shaded side, the rim of the mouth, the arm's rods and the spring+ ln(G.shadeOut.slice(G.shadeOut.length / 2), 930, { w: 1.3, a: 0.8 }); ln(G.mouth.filter((_, i) => i < 16), 931, { w: 1.2, a: 0.75 });+ ln([G.hinge, G.elbow], 932, { w: 1.0, a: 0.7 }); ln([G.elbow, G.sh(-4, 0)], 933, { w: 1.0, a: 0.7 });+ const coil: P[] = []; { const dx = G.elbow[0] - G.hinge[0], dy = G.elbow[1] - G.hinge[1], l = Math.hypot(dx, dy), nx = -dy / l, ny = dx / l; for (let k = 0; k <= 70; k++) { const t = k / 70, p = lerpP(G.hinge, G.elbow, 0.08 + t * 0.32), c = Math.cos(t * 60) * 3; coil.push([p[0] + nx * (7 + c), p[1] + ny * (7 + c)]); } }+ S.line(coil, 0.9, C.steel, 0.8); dot(S, G.elbow[0], G.elbow[1], 5, C.sepia, 0.8, 1.4); dot(S, G.hinge[0], G.hinge[1], 5, C.sepia, 0.8, 1.4);+ ln(G.baseSide.slice(15), 934, { w: 1.2, a: 0.75 });+ // box: base line, the lid's top edge, the rim, inlay, keyhole, comb teeth, drum pins+ edge(G.box.front[0], G.box.front[1], 940, { w: 1.4 }); edge(G.box.front[1], G.box.right[1], 941, { w: 1.3 }); edge(G.box.front[1], G.box.front[2], 942, { w: 1.1, a: 0.7 });+ edge(G.box.front[3], G.box.front[2], 943, { w: 1.0, a: 0.55 }); ln([...G.inner, G.inner[0]], 944, { w: 1.0, a: 0.6, smooth: false, skip: 0.1 });+ ln([...G.lidEdge, G.lidEdge[0]], 945, { w: 1.1, a: 0.7, smooth: false }); ln([...G.lidPanel, G.lidPanel[0]], 946, { w: 0.9, a: 0.5, smooth: false, skip: 0.2 });+ ln([...G.inlay, G.inlay[0]], 947, { w: 0.8, a: 0.45, col: C.brassDk, smooth: false, skip: 0.25 });+ dot(S, G.escut[0][0] - 9, (G.escut[3][1] + G.escut[10][1]) / 2, 2.4, C.sepia, 0.95, 1.4);+ for (let i = 0; i < 18; i++) { const a = G.bp([-66 + i * 8, 64, -10]), b = G.bp([-66 + i * 8, 66, 3]); if (interior.has(a[0], a[1]) && interior.has(b[0], b[1])) S.line([a, b], 0.9, C.sepia, 0.7); }+ for (let i = 0; i < 26; i++) { const p = G.bp(G.drumC(-78 + i * 6 + ((i * 7) % 5))), dy = ((i * 11) % 7) - 4; if (interior.has(p[0], p[1] + dy * 0.5)) dot(S, p[0], p[1] + dy * 0.5, 1.2, C.brassDk, 0.9, 1); }+ G.drumEnds.forEach((e, i) => ln([...e, e[0]], 948 + i, { w: 1, a: 0.6, keep: (x, y) => interior.has(x, y) }));+ ln([G.keyShaft[0], G.keyShaft[1]], 950, { w: 1, a: 0.7 }); G.keyBow.forEach((k, i) => ln([...k, k[0]], 951 + i, { w: 0.9, a: 0.7 }));+ dot(S, G.drivePt[0], G.drivePt[1], 3.4, C.sepia, 0.9, 1.3);+ { const h = ring(G.emptyHole[0], G.emptyHole[1], 3.4, 2.4, 12); ln([...h, h[0]], 1104, { w: 0.9, a: 0.9, skip: 0 }); dot(S, G.emptyHole[0], G.emptyHole[1], 1, C.blueBlack, 0.9, 1); }+ // robot: the edges between faces, silhouette on the shade side, eyes, plate, rivets, hose rings+ const cube = (c: ReturnType<typeof cuboid>, seed: number, w = 1.2) => { edge(c.front[3], c.front[0], seed, { w: w + 0.2 }); edge(c.front[0], c.front[1], seed + 1, { w }); edge(c.left[0], c.left[1], seed + 2, { w }); edge(c.left[0], c.left[3], seed + 3, { w: w + 0.2 }); edge(c.front[3], c.front[2], seed + 4, { w: w * 0.8, a: 0.55 }); edge(c.top[3], c.top[0], seed + 5, { w: w * 0.8, a: 0.5 }); edge(c.front[1], c.front[2], seed + 6, { w: w * 0.8, a: 0.45 }); };+ cube(G.head, 960); cube(G.torso, 970); cube(G.neck, 980, 0.9); G.legs2.forEach((l, i) => cube(l, 990 + i * 10, 1)); G.feet.forEach((f, i) => cube(f, 1010 + i * 10, 1.1));+ G.eyes.forEach((e, i) => ln([...e, e[0]], 1030 + i, { w: 1.3, a: 0.85, skip: 0 }));+ G.eyes.forEach((e, i) => { const c = e.reduce((s, p) => [s[0] + p[0] / e.length, s[1] + p[1] / e.length] as P, [0, 0] as P); ln(e.slice(1, 9).map(([x, y]) => [c[0] + (x - c[0]) * 0.72, c[1] + (y - c[1]) * 0.72] as P), 1032 + i, { w: 0.9, a: 0.45, skip: 0 }); });+ ln([...G.plate, G.plate[0]], 1034, { w: 1.0, a: 0.7, smooth: false }); ln([...G.dial, G.dial[0]], 1035, { w: 1.0, a: 0.8 }); S.line([G.dialC, G.needle], 1.1, C.tinRed, 0.9);+ ln([...G.button, G.button[0]], 1036, { w: 0.9, a: 0.7 }); ln([...G.mouthG, G.mouthG[0]], 1037, { w: 1.0, a: 0.8, smooth: false });+ for (let i = 1; i < 6; i++) { const a = lerpP(G.mouthG[0], G.mouthG[1], i / 6), b = lerpP(G.mouthG[3], G.mouthG[2], i / 6); S.line([a, b], 0.9, C.pale, 0.7); }+ // rivets down the torso's front seams and at the head's corners+ [[-50, 58], [50, 58], [-50, 172], [50, 172], [-50, 115], [50, 115]].forEach(([x, y]) => { const p = G.rp([x, y, -36.5]); dot(S, p[0], p[1], 1.7, C.tDeep, 0.9, 1.1); });+ [[-41, 196], [41, 196], [-41, 262], [41, 262]].forEach(([x, y]) => { const p = G.rp([x, y, -33.5]); dot(S, p[0], p[1], 1.6, C.tDeep, 0.9, 1.1); });+ // the chest plate's speaker slots+ [102, 110, 118].forEach((y) => S.line([G.rp([-30, y, -37]), G.rp([30, y, -37])], 1.1, C.tDeep, 0.7));+ ln(G.earL.concat([G.earL[0]]), 1038, { w: 1, a: 0.7 });+ ln([G.antenna[0], G.antenna[1]], 1039, { w: 1.1, a: 0.85 }); dot(S, G.bobble[0] - 2, G.bobble[1] - 2, 2, C.pale, 0.9);+ [G.armR, G.armL].forEach((sm) => { for (let k = 1; k < 9; k++) { const t = k / 9, seg = t < 0.5 ? 0 : 1, f = t < 0.5 ? t * 2 : (t - 0.5) * 2, a = sm[seg], b = sm[seg + 1], p = lerpP(a, b, f), dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy); S.line([[p[0] - (dy / l) * 8, p[1] + (dx / l) * 8], [p[0] + dx / l * 1.5, p[1] + dy / l * 1.5], [p[0] + (dy / l) * 8, p[1] - (dx / l) * 8]], 0.9, C.tDeep, 0.6); } });+ ln(tubeAlong(G.armR, 8).slice(0, 3), 1040, { w: 1.1, a: 0.7, smooth: false }); ln(tubeAlong(G.armL, 8).slice(0, 3), 1041, { w: 1.2, a: 0.75, smooth: false });+ // pincers: two short claws closing on the screwdriver; the other hand round a cog+ const pinc = (h: P, dir: number, seed: number) => { const c = Math.cos(dir), s = Math.sin(dir); ln([[h[0], h[1]], [h[0] + c * 10 - s * 6, h[1] + s * 10 + c * 6], [h[0] + c * 16 - s * 2, h[1] + s * 16 + c * 2]], seed, { w: 1.6, a: 0.9, col: C.tDeep, skip: 0 }); ln([[h[0], h[1]], [h[0] + c * 10 + s * 6, h[1] + s * 10 - c * 6], [h[0] + c * 16 + s * 2, h[1] + s * 16 - c * 2]], seed + 1, { w: 1.6, a: 0.9, col: C.tDeep, skip: 0 }); };+ pinc(G.armR[2], Math.atan2(G.drivePt[1] - G.armR[2][1], G.drivePt[0] - G.armR[2][0]), 1042); pinc(G.armL[2], 1.7, 1044);+ S.line(G.driverS, 1.6, C.steel, 0.95); ln([G.driverH[0], G.driverH[1]], 1046, { w: 1, a: 0.6 });+ const cogR = ring(G.cogL[0] - 2, G.cogL[1] + 8, 10, 10, 16); ln([...cogR, cogR[0]], 1047, { w: 0.9, a: 0.7, col: C.brassDk }); for (let k = 0; k < 10; k++) { const a = (k / 10) * Math.PI * 2; S.line([[G.cogL[0] - 2 + Math.cos(a) * 10, G.cogL[1] + 8 + Math.sin(a) * 10], [G.cogL[0] - 2 + Math.cos(a) * 13.5, G.cogL[1] + 8 + Math.sin(a) * 13.5]], 1.8, C.brassDk, 0.9); }+ ln([G.kS, G.kE], 1048, { w: 1, a: 0.7 }); G.kBow.forEach((k, i) => ln([...k, k[0]], 1049 + i, { w: 1, a: 0.8 }));+ // parts on the bench+ G.parts.screws.forEach((s, i) => { ln(s, 1110 + i, { w: 0.9, a: 0.8, skip: 0 }); dot(S, s[0][0], s[0][1], 2.6, C.sepia, 0.8, 1.1); });+ const cogB = ring(G.parts.cog[0], G.parts.cog[1], 12, 5, 18); ln([...cogB, cogB[0]], 1115, { w: 0.9, a: 0.7, col: C.brassDk }); dot(S, G.parts.cog[0], G.parts.cog[1], 2, C.sepia, 0.8);+ for (let k = 0; k < 12; k++) { const a = (k / 12) * Math.PI * 2; S.line([[G.parts.cog[0] + Math.cos(a) * 12, G.parts.cog[1] + Math.sin(a) * 5], [G.parts.cog[0] + Math.cos(a) * 15, G.parts.cog[1] + Math.sin(a) * 6.3]], 1.5, C.brassDk, 0.85); }++ // 12 · the lamp's halo: yellow over near-bare paper, strongest at the mouth, and the pool it throws+ S.pass("halo", 1);+ const haloR = minus(ellipseR(M[0], M[1] + 10, 210, 210), R(G.shadeOut), robotSil, boxSil, R(G.armUp));+ hatch(S, haloR, { ang: ANG, gap: 2.6, len: 22, w: 1.4, col: C.yellow, a: 0.7, seed: 1200, dens: (x, y) => Math.pow(1 - smoothstep(30, 210, dM(x, y)), 1.4) });+ hatch(S, haloR, { ang: ANG + 0.25, gap: 3.4, len: 18, w: 1.3, col: C.amber, a: 0.45, seed: 1201, dens: (x, y) => Math.pow(1 - smoothstep(40, 130, dM(x, y)), 1.6) });+ hatch(S, R(G.glow), { ang: ANG, gap: 2.4, len: 14, w: 1.3, col: C.yellow, a: 0.8, seed: 1202, dens: () => 0.8 });+ hatch(S, union(benchTop, minus(RB(G.box.top), RB(G.inner))), { ang: ANG, gap: 3, len: 26, w: 1.4, col: C.yellow, a: 0.5, seed: 1203, dens: (x, y) => 0.7 * (1 - smoothstep(0.2, 1.1, pool(x, y))) });+ hatch(S, union(rTop, RB(G.lidEdge)), { ang: ANG, gap: 3.4, len: 14, w: 1.2, col: C.yellow, a: 0.5, seed: 1204, dens: () => 0.5 });+ S.into("layer"); CP.layer(S); S.into("darks"); CP.darks(S); S.into("line"); CP.line(S);+ return S;+};++// ---------------------------------------------------------------- the process, on the beat grid+// 540 frames = 18 s at 30 fps. Frame 0 is the bare sheet; every pass starts on a multiple of 5;+// the drawing is finished at 505 and the last 35 frames hold the finished sheet.+const CUES: Cue[] = [+ { pass: "lay", start: 5, end: 45 },+ { pass: "wall", start: 50, end: 115 },+ { pass: "sky", start: 120, end: 150 },+ { pass: "wood", start: 155, end: 205 },+ { pass: "box", start: 210, end: 240 },+ { pass: "robot", start: 245, end: 285 },+ { pass: "lamp", start: 290, end: 305 },+ { pass: "crow", start: 310, end: 345 },+ { pass: "layer", start: 350, end: 395 },+ { pass: "darks", start: 400, end: 440 },+ { pass: "line", start: 445, end: 485 },+ { pass: "halo", start: 490, end: 505 },+];+const N = 540;+CUES.forEach((c, i) => { if (c.start % 5 || c.end % 5 || c.end <= c.start || c.end > N - 30 || (i && c.start < CUES[i - 1].end)) throw new Error(`colouredPencil cue ${c.pass} off the grid`); });++const R = replay({ D, ang: ANG, paper: PAPER, sheet: draw, cues: CUES, key: "tinRepairman-v3", view: { zoom: 1.34, cx: 580, cy: 568 } });++export const STYLE = { id: "colouredPencil", name: "Coloured pencil", family: "dry media", medium: "wax coloured pencils hatched in one diagonal on toothy cream cartridge paper, hues layered, darks cross-hatched", nearest: "balloon (crayon)", hero: "a wind-up tin robot mending a music box while a crow steals a screw" };++export const colouredPencil: Film = {+ meta: { title: "The tin repairman · coloured pencil", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu", kind: "drawing", holds: [[N - 35, N]] },+ assets: { images: {} },+ shots: [{ id: "drawing", start: 0, end: N, draw: (ctx, f, env) => R.draw(ctx, f, env) }],+};diff --git a/engine/src/canvas-core/colouredPencilCrow.ts b/engine/src/canvas-core/colouredPencilCrow.tsnew file mode 100644index 0000000..b0f608a--- /dev/null+++ b/engine/src/canvas-core/colouredPencilCrow.ts@@ -0,0 +1,131 @@+import type { P } from "./core";+import { Sheet, contour, dot, edgeDist, ellipseR, hatch as hatchRaw, minus, poly, union, type Region } from "./colouredPencilKit";++// THE CROW, built the way a pencil artist builds a black bird: never one black mass.+// A warm-grey underlayer first, then blue-black laid FEATHER GROUP BY FEATHER GROUP (head, body,+// coverts, secondaries, primaries, tail), each group with its own value and its own stroke+// direction along the feathers, violet worked into the sheen, and cross-hatching only in the+// deepest places. The paper is RESERVED, not added: thin lines between primaries and secondaries,+// the scallop rows of the coverts, the top of the head and the ridge of the bill are simply where+// the pencil never went. The eye is cross-hatched dark round a catchlight of bare paper; the screw+// is light steel with a bare-paper glint, outlined dark so it reads against wall and bill alike.+//+// Anatomy (carrion crow, walking profile, head turned back over the shoulder): bill as long as the+// head with nasal bristles over its base; shaggy throat; folded wing = lesser/median coverts in+// scalloped rows, secondaries below them, primaries crossing over two-thirds of the tail; wedge+// tail; scaled (scutellate) tarsi; three toes forward, one back, claws hooked over the bench edge.+//+// All geometry is authored in the crow's own sheet coordinates, then placed by `cw` (the body) and+// `hw` (the head, 1.25x the body's scale: a crow's head, not a songbird's).++type Place = (p: P) => P;+const C = { warm: "#8b8279", bb: "#262a3f", ink: "#1d1f2c", violet: "#5b4d93", sheen: "#6d73b8", steel: "#b9c0cc", steelDk: "#565d6b", leg: "#34343c", scute: "#9aa0aa", claw: "#1d1f2c" };+const ANG = -1.02, X2 = 0.22;+const hatch: typeof hatchRaw = (S, reg, o) => hatchRaw(S, reg, { ...o, gap: o.gap * 0.55, len: o.len * 0.85, a: Math.min(1, o.a * 0.72) });++// thin reserved lines: a region that is every point within r of any of the polylines+const near = (lines: P[][], r: number): Region => {+ const segs: [P, P][] = []; lines.forEach((l) => l.forEach((p, i) => { if (i) segs.push([l[i - 1], p]); }));+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; segs.forEach(([a, b]) => [a, b].forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }));+ return { box: { x0: x0 - r, y0: y0 - r, x1: x1 + r, y1: y1 + r }, has: (x, y) => segs.some(([a, b]) => { const dx = b[0] - a[0], dy = b[1] - a[1], t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / (dx * dx + dy * dy || 1))); return Math.hypot(x - a[0] - t * dx, y - a[1] - t * dy) < r; }) };+};+const arcAt = (c: P, s = 1): P[] => [[c[0] - 9 * s, c[1] - 3 * s], [c[0] - 3 * s, c[1] + 4 * s], [c[0] + 7 * s, c[1] + 2 * s]];+const lerp = (a: P, b: P, t: number): P => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];++export const crowGeometry = (cw: Place, hw: Place) => {+ const m = (pts: number[][], f = cw) => (pts as P[]).map(f);+ const body = m([[920, 496], [900, 500], [880, 512], [856, 532], [828, 554], [798, 580], [768, 606], [742, 632], [718, 656], [694, 684], [676, 706], [670, 716], [680, 724], [702, 720], [730, 708], [754, 700], [780, 706], [812, 714], [842, 716], [870, 708], [898, 690], [924, 662], [944, 630], [958, 600], [966, 568], [966, 536], [958, 512], [944, 498]]);+ const head = m([[912, 462], [924, 452], [942, 450], [958, 458], [966, 474], [962, 494], [950, 508], [930, 512], [914, 504], [906, 488], [906, 472]], hw);+ const bill = m([[910, 462], [890, 465], [868, 472], [850, 482], [845, 488], [858, 491], [882, 494], [906, 498]], hw);+ const culmen = m([[908, 463], [890, 466], [868, 473], [852, 482]], hw);+ const coverts = m([[898, 542], [912, 574], [904, 606], [870, 620], [830, 628], [800, 628], [820, 594], [862, 562]]);+ const secondaries = m([[904, 606], [902, 622], [878, 656], [840, 678], [800, 688], [790, 660], [800, 628], [830, 628], [870, 620]]);+ const primaries = m([[800, 628], [790, 660], [800, 688], [796, 690], [748, 696], [716, 696], [740, 674], [778, 630]]);+ const tail = m([[742, 638], [718, 660], [694, 686], [676, 706], [670, 716], [680, 724], [702, 720], [730, 708], [754, 700], [760, 690], [744, 676], [752, 650]]);+ const primLines = [[[790, 652], [760, 676], [728, 692]], [[792, 640], [768, 664], [742, 684]], [[786, 632], [770, 650], [752, 668]], [[798, 668], [772, 684], [752, 692]]].map((l) => m(l));+ const secLines = [[[890, 612], [880, 640], [866, 662]], [[870, 622], [856, 652], [838, 674]], [[846, 626], [830, 656], [814, 682]], [[822, 628], [808, 660], [800, 684]]].map((l) => m(l));+ const covRows = [...[0, 1, 2, 3, 4].map((k) => arcAt(lerp([894, 572], [836, 606], k / 4))), ...[0, 1, 2, 3].map((k) => arcAt(lerp([896, 594], [838, 620], k / 3)))].map((l) => m(l));+ const tailLines = [[[744, 652], [704, 700]], [[752, 664], [716, 710]], [[758, 676], [732, 704]]].map((l) => m(l));+ const legBack = m([[858, 712], [855, 748], [850, 780]]), legFront = m([[892, 706], [899, 744], [904, 780]]);+ // toes: forward pair along the edge, the front claws hooked down over the bench's rounded nose+ const toes = [[[850, 780], [866, 781], [876, 786], [878, 792]], [[850, 780], [862, 784], [868, 790]], [[850, 780], [838, 781], [832, 783]], [[904, 780], [920, 781], [930, 786], [932, 792]], [[904, 780], [916, 784], [922, 790]], [[904, 780], [892, 781], [886, 783]]].map((l) => m(l));+ const eye = hw([922, 474]), eyeR = 6.2 * Math.hypot(hw([1, 0])[0] - hw([0, 0])[0], 0);+ const headTop = hw([940, 450])[1];+ const screw = { head: hw([862, 460]), a: hw([863.5, 466]), b: hw([869, 508]) };+ const gape = m([[908, 484], [884, 486], [860, 488], [846, 488]], hw);+ const bristles = [0, 1, 2, 3, 4, 5].map((k) => m([[912 - k * 2, 464 + k * 1.2], [902 - k * 2.6, 466 + k * 1.4], [892 - k * 2.4, 470 + k * 1.2]], hw));+ const hackles = [cw([958, 530]), cw([958, 596])];+ const belly = m([[780, 706], [812, 714], [842, 716], [870, 708], [898, 690], [924, 662]]);+ const k = Math.hypot(cw([1, 0])[0] - cw([0, 0])[0], 0); // the body's scale, for mark sizes+ return { body, head, bill, culmen, coverts, secondaries, primaries, tail, primLines, secLines, covRows, tailLines, legBack, legFront, toes, eye, eyeR, headTop, screw, gape, bristles, hackles, belly, k };+};+export type Crow = ReturnType<typeof crowGeometry>;++const tube = (c: P[], r: number): P[] => { const L: P[] = [], R: P[] = []; c.forEach((p, i) => { const q = c[Math.min(c.length - 1, i + 1)], o = c[Math.max(0, i - 1)], dx = q[0] - o[0], dy = q[1] - o[1], l = Math.hypot(dx, dy) || 1; L.push([p[0] - (dy / l) * r, p[1] + (dx / l) * r]); R.push([p[0] + (dy / l) * r, p[1] - (dx / l) * r]); }); return [...L, ...R.reverse()]; };+export const crowSilhouette = (G: Crow) => union(poly(G.body), poly(G.head), poly(G.bill), poly(tube(G.legBack, 3.6 * G.k)), poly(tube(G.legFront, 3.6 * G.k)), ...G.toes.map((t) => poly(tube(t, 1.6 * G.k))));++// the four moments the crow is worked on, each called while its pass is current+export const crowPasses = (G: Crow) => {+ const k = G.k, R = poly;+ const screwR = union(ellipseR(G.screw.head[0], G.screw.head[1], 6.5 * k, 4.2 * k), R(tube([G.screw.a, G.screw.b], 3.4 * k)));+ const eyeR = ellipseR(G.eye[0], G.eye[1], G.eyeR + 1, G.eyeR + 1);+ const wingR = union(R(G.coverts), R(G.secondaries), R(G.primaries));+ const headTopR: Region = { box: R(G.head).box, has: (x, y) => y < G.headTop + 5 * k && R(G.head).has(x, y) && edgeDist(G.head)(x, y) < 4.5 * k };+ const reserved = union(near(G.primLines, 0.9 * k), near(G.secLines, 0.9 * k), near(G.covRows, 0.8 * k), near(G.tailLines, 0.7 * k), near([G.culmen], 1.3 * k), headTopR);+ const bodyOnly = minus(R(G.body), wingR, R(G.tail));+ const headR = minus(R(G.head), R(G.bill), eyeR);+ const legs = union(R(tube(G.legBack, 3.4 * k)), R(tube(G.legFront, 3.4 * k)), ...G.toes.map((t) => R(tube(t, 1.7 * k))));+ const dBody = edgeDist(G.body);+ return {+ // 1 · the underlayer: warm grey everywhere the bird is, the reserved lines already kept clear+ base: (S: Sheet) => {+ hatch(S, minus(union(R(G.body), R(G.head)), eyeR, screwR, reserved), { ang: ANG, gap: 2.6, len: 20, w: 1.4, col: C.warm, a: 0.8, seed: 1600, dens: () => 0.75 });+ hatch(S, minus(R(G.bill), screwR, reserved), { ang: -0.42, gap: 2.4, len: 12, w: 1.3, col: C.warm, a: 0.8, seed: 1601, dens: () => 0.8 });+ hatch(S, legs, { ang: -1.5, gap: 1.2, len: 8, w: 1.3, col: C.leg, a: 1, seed: 1602, dens: () => 1 }); hatch(S, legs, { ang: X2, gap: 1.4, len: 6, w: 1.2, col: C.ink, a: 1, seed: 1604, dens: () => 1 });+ hatch(S, minus(screwR, ellipseR(G.screw.head[0] - 1.6 * k, G.screw.head[1] - 1.2 * k, 1.8 * k, 1.4 * k), R(tube([lerp(G.screw.a, G.screw.b, 0.1), lerp(G.screw.a, G.screw.b, 0.9)].map(([x, y]) => [x - 1.4 * k, y] as P), 0.7 * k))), { ang: ANG, gap: 1.5, len: 6, w: 1.1, col: C.steel, a: 1, seed: 1603, dens: () => 0.95 });+ },+ // 2 · blue-black, group by group, each along its own feathers; violet into the sheen+ layer: (S: Sheet) => {+ const g = (reg: Region, ang: number, d: number, seed: number, gap = 2.4, len = 18) => hatch(S, minus(reg, reserved, eyeR, screwR), { ang, gap, len, w: 1.4, col: C.bb, a: 0.95, seed, dens: () => d, jit: 0.06 });+ g(bodyOnly, ANG, 0.88, 1610);+ g(headR, ANG - 0.25, 0.7, 1611);+ g(R(G.coverts), ANG + 0.45, 0.42, 1612, 2.8, 10);+ g(R(G.secondaries), ANG + 0.15, 0.74, 1613);+ g(R(G.primaries), -0.52, 0.86, 1614, 2.2, 22);+ g(R(G.tail), -0.72, 0.9, 1615, 2.2, 22);+ g(minus(R(G.bill), screwR), -0.42, 0.75, 1616, 2.2, 12);+ hatch(S, minus(union(R(G.coverts), headR, R(G.secondaries)), reserved, screwR), { ang: ANG + 0.2, gap: 3.2, len: 14, w: 1.3, col: C.violet, a: 0.8, seed: 1617, dens: (x, y) => (R(G.secondaries).has(x, y) ? 0.3 : 0.6) });+ },+ // 3 · the deepest places, cross-hatched: belly and vent, under the wing, the tail's underside,+ // the head below the eye; then the eye itself round its catchlight+ darks: (S: Sheet) => {+ hatch(S, minus(bodyOnly, reserved), { ang: X2, gap: 2.8, len: 16, w: 1.3, col: C.ink, a: 0.9, seed: 1620, dens: (x, y) => 0.4 + 0.55 * Math.max(0, Math.min(1, (y - G.body[0][1]) / (G.belly[2][1] - G.body[0][1]))) + 0.3 * (dBody(x, y) < 4 * k ? 1 : 0) });+ hatch(S, minus(R(G.primaries), reserved), { ang: X2 - 0.2, gap: 3, len: 14, w: 1.3, col: C.ink, a: 0.85, seed: 1621, dens: () => 0.55 });+ hatch(S, minus(R(G.tail), reserved), { ang: X2 + 0.3, gap: 3, len: 14, w: 1.3, col: C.ink, a: 0.85, seed: 1622, dens: () => 0.6 });+ hatch(S, minus(R(G.secondaries), reserved), { ang: X2, gap: 3.4, len: 12, w: 1.2, col: C.ink, a: 0.7, seed: 1623, dens: (x, y) => 0.5 * Math.max(0, Math.min(1, (y - G.secondaries[0][1]) / 30)) });+ hatch(S, minus(headR, reserved), { ang: X2, gap: 3.2, len: 12, w: 1.2, col: C.ink, a: 0.75, seed: 1624, dens: (x, y) => (y > G.eye[1] + 2 ? 0.55 : 0.15) });+ const iris = minus(ellipseR(G.eye[0], G.eye[1], G.eyeR, G.eyeR), ellipseR(G.eye[0] - G.eyeR * 0.36, G.eye[1] - G.eyeR * 0.36, G.eyeR * 0.3, G.eyeR * 0.3));+ [ANG, X2, ANG + 0.8].forEach((a, i) => hatch(S, iris, { ang: a, gap: 1.2, len: 6, w: 1.1, col: C.ink, a: 1, seed: 1630 + i, dens: () => 1 }));+ },+ // 4 · lines last and sparse: bill and gape, bristles, the eye's rim, feather tips, scutes, claws, the screw+ line: (S: Sheet) => {+ const ln = (pts: P[], seed: number, w: number, a: number, col = C.ink) => contour(S, pts, { w, col, a, seed, seg: 30, skip: 0 });+ ln(G.bill.slice(0, 5), 1640, 1.2, 0.9); ln(G.gape, 1641, 1.1, 0.9);+ G.bristles.forEach((b) => S.line(b, 0.8, C.ink, 0.8));+ ln(Array.from({ length: 12 }, (_, i) => { const a = Math.PI * 0.15 + (i / 11) * Math.PI * 1.1; return [G.eye[0] + Math.cos(a) * (G.eyeR + 1.8), G.eye[1] + Math.sin(a) * (G.eyeR + 1.8)] as P; }), 1642, 0.9, 0.7);+ for (let i = 0; i < 7; i++) { const p = lerp(G.hackles[0], G.hackles[1], i / 6); S.line([[p[0] - 3 * k, p[1] - 2 * k], [p[0] + 3 * k, p[1] + 1.5 * k], [p[0] - 0.5 * k, p[1] + 5 * k]], 0.9, C.ink, 0.85); }+ [G.secondaries.slice(1, 5), G.primaries.slice(2, 6)].forEach((l, i) => ln(l, 1650 + i, 1.1, 0.8));+ ln(G.belly, 1652, 1.1, 0.7);+ // scaled tarsi: pale rings across the dark leg, then the toes and hooked claws in near-black+ [G.legBack, G.legFront].forEach((l) => { for (let i = 1; i < 7; i++) { const p = lerp(l[1], l[2], i / 7), q = lerp(l[0], l[1], i / 7); [p, q].forEach((c) => S.line([[c[0] - 2.4 * k, c[1] - 0.3 * k], [c[0] + 2.4 * k, c[1] + 0.5 * k]], 0.8, C.scute, 0.85)); } });+ G.toes.forEach((t, i) => ln(t, 1660 + i, 1.4, 0.95, C.claw));+ // the screw: dark flanks so it reads against the pale wall and the black bill, threads, a slotted head+ const off = (d: number): P[] => [G.screw.a, G.screw.b].map(([x, y]) => [x + d * k, y] as P);+ S.line(off(-3.4), 0.9, C.steelDk, 0.95); S.line(off(3.4), 0.9, C.steelDk, 0.95);+ for (let i = 0; i < 8; i++) { const p = lerp(G.screw.a, G.screw.b, 0.18 + i * 0.1); S.line([[p[0] - 3.2 * k, p[1] - 0.6 * k], [p[0] + 3.2 * k, p[1] + 0.9 * k]], 0.7, C.steelDk, 0.85); }+ contour(S, Array.from({ length: 13 }, (_, i) => { const a = (i / 12) * Math.PI * 2; return [G.screw.head[0] + Math.cos(a) * 6.5 * k, G.screw.head[1] + Math.sin(a) * 4.2 * k] as P; }), { w: 0.9, col: C.steelDk, a: 0.95, seed: 1670, seg: 40, skip: 0 });+ S.line([[G.screw.head[0] - 3.5 * k, G.screw.head[1] + 0.4 * k], [G.screw.head[0] + 3.5 * k, G.screw.head[1] - 0.4 * k]], 1, C.steelDk, 0.9);+ dot(S, G.eye[0] + G.eyeR * 0.3, G.eye[1] + G.eyeR * 0.3, 1.2, C.ink, 0.9, 1);+ },+ };+};diff --git a/engine/src/canvas-core/colouredPencilKit.ts b/engine/src/canvas-core/colouredPencilKit.tsnew file mode 100644index 0000000..28b3c52--- /dev/null+++ b/engine/src/canvas-core/colouredPencilKit.ts@@ -0,0 +1,219 @@+// COLOURED PENCIL KIT. A picture is an ordered list of PASSES; a pass is an ordered list of+// MARKS; a mark is one pencil stroke (a centreline, a width, a colour, a pressure). The still is+// every pass complete. The film is the same list replayed in time: finished passes are cached as+// one composite bitmap, the pass in hand is redrawn up to the mark the hand has reached.+//+// Wax-based coloured pencil only deposits on the TOOTH of the sheet. Each pass is drawn on its+// own layer and then punched by one tooth field that belongs to the paper (the same valleys stay+// cream through every layer, which is what makes layered pencil read as pencil). Harder pressure+// fills more of the valleys, so passes pick a pressure level: 0 light, 1 medium, 2 burnished.+//+// Pure: marks are a function of constants and rng(seed). Caches are keyed by everything their+// pixels depend on (design size, logical size, device scale, pass index).+import { Gfx, PENCIL, fractal, rng, sample, type Ctx, type Env, type Layer, type P } from "./core";++export type Mark = { c: P[]; w: number; col: string; a: number; len: number; poly: Float32Array };+export type Pass = { id: string; tooth: 0 | 1 | 2; marks: Mark[] };+export type Region = { box: { x0: number; y0: number; x1: number; y1: number }; has: (x: number, y: number) => boolean };++const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));+export const smoothstep = (a: number, b: number, v: number) => { const t = clamp((v - a) / (b - a)); return t * t * (3 - 2 * t); };++// ---------------------------------------------------------------- regions+export const inPoly = (pts: P[], x: number, y: number) => { let k = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[i], b = pts[j]; if (a[1] > y !== b[1] > y && x < ((b[0] - a[0]) * (y - a[1])) / (b[1] - a[1]) + a[0]) k = !k; } return k; };+const boxOf = (pts: P[]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); } return { x0, y0, x1, y1 }; };+export const poly = (pts: P[]): Region => { const box = boxOf(pts); return { box, has: (x, y) => x >= box.x0 && x <= box.x1 && y >= box.y0 && y <= box.y1 && inPoly(pts, x, y) }; };+export const union = (...rs: Region[]): Region => ({ box: { x0: Math.min(...rs.map((r) => r.box.x0)), y0: Math.min(...rs.map((r) => r.box.y0)), x1: Math.max(...rs.map((r) => r.box.x1)), y1: Math.max(...rs.map((r) => r.box.y1)) }, has: (x, y) => rs.some((r) => r.has(x, y)) });+export const minus = (a: Region, ...bs: Region[]): Region => ({ box: a.box, has: (x, y) => a.has(x, y) && !bs.some((b) => b.has(x, y)) });+export const ellipseR = (cx: number, cy: number, rx: number, ry: number): Region => ({ box: { x0: cx - rx, y0: cy - ry, x1: cx + rx, y1: cy + ry }, has: (x, y) => ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 <= 1 });+// distance from a point to a closed polygon's boundary: tone that thickens toward the edge of a form+export const edgeDist = (pts: P[]) => (x: number, y: number) => {+ let d = 1e9;+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const [ax, ay] = pts[j], [bx, by] = pts[i], dx = bx - ax, dy = by - ay, l = dx * dx + dy * dy || 1, t = clamp(((x - ax) * dx + (y - ay) * dy) / l); d = Math.min(d, Math.hypot(x - ax - t * dx, y - ay - t * dy)); }+ return d;+};++// ---------------------------------------------------------------- the stroke+// A pencil hatch stroke: pressure arrives fast, holds, lifts off in a long taper (the flick).+const profile = (t: number) => Math.max(0.22, Math.pow(clamp(t / 0.16), 0.6) * Math.pow(clamp((1 - t) / 0.42), 0.75));+const outline = (c: P[], w: number): Float32Array => {+ const n = c.length, L: number[] = [], R: number[] = [];+ for (let i = 0; i < n; i++) {+ const p = c[i], q = c[Math.min(n - 1, i + 1)], o = c[Math.max(0, i - 1)], dx = q[0] - o[0], dy = q[1] - o[1], l = Math.hypot(dx, dy) || 1, h = (w * profile(i / (n - 1))) / 2;+ L.push(p[0] - (dy / l) * h, p[1] + (dx / l) * h); R.unshift(p[0] + (dy / l) * h, p[1] - (dx / l) * h);+ }+ // R was built reversed pairwise: fix the pair order+ const out = new Float32Array(L.length + R.length); out.set(L, 0);+ for (let i = 0; i < R.length; i += 2) { out[L.length + i] = R[i]; out[L.length + i + 1] = R[i + 1]; }+ return out;+};+const lengthOf = (c: P[]) => { let s = 0; for (let i = 1; i < c.length; i++) s += Math.hypot(c[i][0] - c[i - 1][0], c[i][1] - c[i - 1][1]); return s; };+const stroke = (pts: P[], w: number, col: string, a: number): Mark => {+ const len = lengthOf(pts), per = Math.max(2, Math.min(10, Math.round(len / 6)));+ const c = pts.length > 2 ? sample(pts, false, Math.max(2, Math.round(per / (pts.length - 1)) + 1)) : Array.from({ length: per + 1 }, (_, i) => [pts[0][0] + ((pts[1][0] - pts[0][0]) * i) / per, pts[0][1] + ((pts[1][1] - pts[0][1]) * i) / per] as P);+ return { c, w, col, a, len, poly: outline(c, w) };+};++// ---------------------------------------------------------------- the sheet being drawn+export class Sheet {+ passes: Pass[] = [];+ private cur!: Pass;+ pass(id: string, tooth: 0 | 1 | 2) { this.cur = { id, tooth, marks: [] }; this.passes.push(this.cur); return this; }+ // go back to an earlier pass and add to it (a subject worked in its own module, pass by pass)+ into(id: string) { const p = this.passes.find((q) => q.id === id); if (!p) throw new Error(`no pass ${id}`); this.cur = p; return this; }+ add(m: Mark) { this.cur.marks.push(m); }+ line(pts: P[], w: number, col: string, a: number) { this.add(stroke(pts, w, col, a)); }+}++export type HatchOpts = {+ ang: number; gap: number; len: number; w: number; col: string; a: number; seed: number;+ dens?: (x: number, y: number) => number; // 0..1: pressure and coverage at a point+ jit?: number; // angle wander per stroke, radians+ strip?: number; // how far along the stroke direction the hand works before moving on+ over?: number; // how far a stroke may overshoot the region's edge+};+// Hatch a region: parallel strokes at one angle, laid side by side in strips the way a hand+// works a patch, each stroke a slightly bowed, flicked line. Edges are where the strokes stop.+export const hatch = (S: Sheet, reg: Region, o: HatchOpts) => {+ const { ang, gap, len, w, col, a, seed, dens = () => 1, jit = 0.09, strip = 150, over = 1.2 } = o, r = rng(seed);+ const cs = Math.cos(ang), sn = Math.sin(ang), b = reg.box, cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, R = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) / 2 + gap;+ const at = (u: number, v: number): P => [cx + u * cs - v * sn, cy + u * sn + v * cs];+ const found: { u: number; v: number; m: Mark }[] = [];+ for (let v = -R; v <= R; v += gap * (0.8 + r() * 0.4)) {+ let run0 = NaN;+ for (let u = -R; u <= R + 2; u += 2) {+ const [x, y] = at(u, v), ins = u <= R && x >= b.x0 - 1 && x <= b.x1 + 1 && y >= b.y0 - 1 && y <= b.y1 + 1 && reg.has(x, y);+ if (ins && isNaN(run0)) run0 = u;+ if (!ins && !isNaN(run0)) {+ const u0 = run0 - r() * over, u1 = u - 2 + r() * over; run0 = NaN;+ let s = u0 + (r() - 0.5) * len * 0.5;+ while (s < u1) {+ const L = len * (0.55 + r() * 0.8), e = Math.min(u1, s + L), s0 = Math.max(u0, s);+ if (e - s0 > 2) {+ const mu = (s0 + e) / 2, [mx, my] = at(mu, v), d = clamp(dens(mx, my));+ if (d > 0.02 && r() < Math.pow(d, 0.55)) {+ const tw = (r() - 0.5) * 2 * jit, dv = (e - s0) * Math.sin(tw) / 2, bow = (r() - 0.5) * 1.4;+ const p0 = at(s0, v - dv), p1 = at(e, v + dv), pm = at(mu, v + bow);+ found.push({ u: mu, v, m: stroke([p0, pm, p1], w * (0.8 + r() * 0.4) * (0.75 + 0.25 * d), col, a * (0.35 + 0.65 * d) * (0.75 + r() * 0.45)) });+ }+ }+ s = e + (r() - 0.45) * len * 0.3;+ }+ }+ }+ }+ // the hand works a strip at a time, back and forth across it+ found.sort((p, q) => { const sp = Math.floor((p.u + R) / strip), sq = Math.floor((q.u + R) / strip); return sp !== sq ? sp - sq : (sp % 2 ? q.v - p.v : p.v - q.v); });+ found.forEach((f) => S.add(f.m));+};++// A contour drawn the way a pencil draws one: a chain of overlapping strokes, each a little+// off the last, pressure lifting between them. `keep` loses the edge where the light eats it.+export const contour = (S: Sheet, pts: P[], o: { w: number; col: string; a: number; seed: number; seg?: number; keep?: (x: number, y: number) => boolean; closed?: boolean; smooth?: boolean; skip?: number }) => {+ const { w, col, a, seed, seg = 60, keep = () => true, closed = false, smooth: sm = true, skip = 0 } = o, r = rng(seed);+ const base = sm ? sample(closed ? pts : pts, closed, 8) : densify(closed ? [...pts, pts[0]] : pts, 3);+ const path = densify(base, 2.5), n = path.length;+ let i = 0;+ while (i < n - 1) {+ const segLen = seg * (0.6 + r() * 0.8), start = Math.max(0, i - Math.round(1 + r() * 2)); let j = start, acc = 0;+ while (j < n - 1 && acc < segLen) { acc += Math.hypot(path[j + 1][0] - path[j][0], path[j + 1][1] - path[j][1]); j++; }+ const piece = path.slice(start, j + 1), mid = piece[piece.length >> 1];+ if (piece.length > 1 && keep(mid[0], mid[1]) && r() >= skip) {+ const off = (r() - 0.5) * 0.9, jj = rng(seed * 13 + i);+ S.line(piece.filter((_, k) => k % 2 === 0 || k === piece.length - 1).map(([x, y]) => [x + off + (jj() - 0.5) * 0.5, y + (jj() - 0.5) * 0.5] as P), w * (0.8 + r() * 0.4), col, a * (0.75 + r() * 0.3));+ }+ i = j;+ }+};+const densify = (s: P[], step: number): P[] => { const out: P[] = [s[0]]; for (let i = 1; i < s.length; i++) { const a = s[i - 1], b = s[i], n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step)); for (let k = 1; k <= n; k++) out.push([a[0] + ((b[0] - a[0]) * k) / n, a[1] + ((b[1] - a[1]) * k) / n]); } return out; };++// a construction line: ruled freehand, running past both corners the way a lay-in does+export const layLine = (S: Sheet, a: P, b: P, col: string, seed: number, w = 1.0, al = 0.42) => {+ const r = rng(seed), dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, e0 = 5 + r() * 12, e1 = 5 + r() * 12;+ S.line([[a[0] - (dx / l) * e0, a[1] - (dy / l) * e0], [(a[0] + b[0]) / 2 + (r() - 0.5) * 2, (a[1] + b[1]) / 2 + (r() - 0.5) * 2], [b[0] + (dx / l) * e1, b[1] + (dy / l) * e1]], w, col, al);+};+// a tiny dark dot (a rivet, a pin, a pupil): a pencil twisted in a small spiral+export const dot = (S: Sheet, x: number, y: number, rad: number, col: string, a: number, w = 1.2) => {+ const pts: P[] = []; for (let k = 0; k <= 14; k++) { const t = k / 14, an = t * Math.PI * 3.2, rr = rad * (1 - t * 0.8); pts.push([x + Math.cos(an) * rr, y + Math.sin(an) * rr]); }+ S.line(pts, w, col, a);+};++// ---------------------------------------------------------------- the paper's tooth+// One field per sheet: slightly streaked along the dominant hatch diagonal (the pencil drags+// across the ridges), plus a fine isotropic grain. Computed at design resolution, once.+const LEVELS = [0.53, 0.575, 0.645];+const toothField = (env: Env, D: number, ang: number): Float32Array => {+ const key = `cp:toothField:${D}:${ang}`; let f = env.cache.get(key) as Float32Array | undefined;+ if (f) return f;+ f = new Float32Array(D * D); const c = Math.cos(ang), s = Math.sin(ang);+ for (let y = 0; y < D; y++) for (let x = 0; x < D; x++) { const u = x * c + y * s, v = -x * s + y * c; f[y * D + x] = 0.62 * fractal(71, u, v, 0.12, 0.62, 2) + 0.38 * fractal(73, x, y, 0.8, 0.8, 1); }+ env.cache.set(key, f); return f;+};+const toothMask = (env: Env, D: number, ang: number, lvl: number): Layer => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), key = `cp:tooth:${lvl}:${D}:${ang}:${DW}x${DH}`;+ let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const f = toothField(env, D, ang), small = env.canvas(D, D), img = small.ctx.createImageData(D, D), d = img.data, T = LEVELS[lvl];+ for (let i = 0; i < D * D; i++) { d[i * 4 + 3] = 255 * clamp((T - f[i]) * 11 + 0.5); }+ small.ctx.putImageData(img, 0, 0);+ L = env.canvas(DW, DH); L.ctx.imageSmoothingEnabled = true; L.ctx.drawImage(small.canvas as CanvasImageSource, 0, 0, D, D, 0, 0, DW, DH);+ env.cache.set(key, L); return L;+};++// ---------------------------------------------------------------- replaying the sheet+export type Cue = { pass: string; start: number; end: number };+const fillMark = (c: Ctx, m: Mark, poly = m.poly) => { c.globalAlpha = m.a; c.fillStyle = m.col; c.beginPath(); c.moveTo(poly[0], poly[1]); for (let i = 2; i < poly.length; i += 2) c.lineTo(poly[i], poly[i + 1]); c.closePath(); c.fill(); };+const cutMark = (m: Mark, p: number): Float32Array => { const n = (m.c.length - 1) * p, i = Math.floor(n), f = n - i, head = m.c.slice(0, i + 1); if (f > 1e-6 && i + 1 < m.c.length) head.push([m.c[i][0] + (m.c[i + 1][0] - m.c[i][0]) * f, m.c[i][1] + (m.c[i + 1][1] - m.c[i][1]) * f]); return outline(head.length > 1 ? head : m.c.slice(0, 2), m.w); };++// per-pass cumulative cost: long strokes go fast per unit length, every lift of the pencil costs time+const costs = (p: Pass) => { const out = new Float64Array(p.marks.length + 1); p.marks.forEach((m, i) => (out[i + 1] = out[i] + m.len + 7)); return out; };++// view: the camera on the design sheet (zoom about a design point, which lands at the frame centre)+export type Replay = { D: number; ang: number; paper: string; sheet: () => Sheet; cues: Cue[]; key: string; view?: { zoom: number; cx: number; cy: number } };+export const replay = (R: Replay) => {+ const sheetOf = (env: Env) => { const k = `cp:sheet:${R.key}`; let s = env.cache.get(k) as { S: Sheet; cost: Float64Array[] } | undefined; if (!s) { const S = R.sheet(); s = { S, cost: S.passes.map(costs) }; env.cache.set(k, s); } return s; };+ const order = (S: Sheet) => R.cues.map((c) => { const i = S.passes.findIndex((p) => p.id === c.pass); if (i < 0) throw new Error(`cue for unknown pass ${c.pass}`); return i; });+ const surface = (env: Env, name: string): Layer => { const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), k = `cp:surf:${name}:${DW}x${DH}`; let L = env.cache.get(k) as Layer | undefined; if (!L) { L = env.canvas(DW, DH); env.cache.set(k, L); } return L; };+ const design = (env: Env, c: Ctx) => { const v = R.view ?? { zoom: 1, cx: R.D / 2, cy: R.D / 2 }, kx = (env.scale * env.W * v.zoom) / R.D, ky = (env.scale * env.H * v.zoom) / R.D; c.setTransform(kx, 0, 0, ky, (env.scale * env.W) / 2 - v.cx * kx, (env.scale * env.H) / 2 - v.cy * ky); };+ // draw marks [0, n) of a pass, the n-th one partly, onto a scratch layer, punch it by the tooth, lay it on `dst`+ const lay = (env: Env, dst: Ctx, pass: Pass, n: number, part: number) => {+ const L = surface(env, "scratch"), c = L.ctx, DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale);+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "source-over"; c.globalAlpha = 1; c.clearRect(0, 0, DW, DH);+ design(env, c);+ for (let i = 0; i < n; i++) fillMark(c, pass.marks[i]);+ if (part > 0 && n < pass.marks.length) fillMark(c, pass.marks[n], cutMark(pass.marks[n], part));+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "destination-in"; c.drawImage(toothMask(env, R.D, R.ang, pass.tooth).canvas as CanvasImageSource, 0, 0); c.globalCompositeOperation = "source-over";+ dst.save(); dst.setTransform(1, 0, 0, 1, 0, 0); dst.globalAlpha = 1; dst.globalCompositeOperation = "source-over"; dst.drawImage(L.canvas as CanvasImageSource, 0, 0); dst.restore();+ };+ // the sheet with the first k cued passes complete. Pure in k: built from the nearest cached one below it.+ const cum = (env: Env, k: number): Layer => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), keyOf = (j: number) => `cp:cum:${R.key}:${j}:${DW}x${DH}`;+ const hit = env.cache.get(keyOf(k)) as Layer | undefined; if (hit) return hit;+ let j = k - 1; while (j >= 0 && !env.cache.has(keyOf(j))) j--;+ const { S } = sheetOf(env), ord = order(S), L = env.canvas(DW, DH), c = L.ctx;+ if (j >= 0) { c.drawImage((env.cache.get(keyOf(j)) as Layer).canvas as CanvasImageSource, 0, 0); }+ else { c.fillStyle = R.paper; c.fillRect(0, 0, DW, DH); j = 0; }+ for (let i = j >= 0 && env.cache.has(keyOf(j)) ? j : 0; i < k; i++) { const p = S.passes[ord[i]]; lay(env, c, p, p.marks.length, 0); }+ // keep only a few composites alive: each is a whole sheet of pixels+ const lk = `cp:cumkeys:${R.key}:${DW}x${DH}`, keys = (env.cache.get(lk) as string[] | undefined) ?? []; keys.push(keyOf(k)); while (keys.length > 3) env.cache.delete(keys.shift()!); env.cache.set(lk, keys);+ env.cache.set(keyOf(k), L); return L;+ };+ const finish = (ctx: Ctx, env: Env) => new Gfx(ctx, env, 0, PENCIL).paper("paper", 0.05);+ return {+ total: () => R.cues[R.cues.length - 1].end,+ draw: (ctx: Ctx, frame: number, env: Env) => {+ const { S, cost } = sheetOf(env), ord = order(S);+ let done = 0; while (done < R.cues.length && frame >= R.cues[done].end) done++;+ const base = cum(env, done);+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(base.canvas as CanvasImageSource, 0, 0); ctx.restore();+ if (done < R.cues.length && frame >= R.cues[done].start) {+ const cue = R.cues[done], pi = ord[done], pass = S.passes[pi], cc = cost[pi], t = (frame - cue.start) / (cue.end - cue.start);+ const want = cc[cc.length - 1] * clamp(t * 0.85 + smoothstep(0, 1, t) * 0.15);+ let lo = 0, hi = pass.marks.length; while (lo < hi) { const m = (lo + hi + 1) >> 1; if (cc[m] <= want) lo = m; else hi = m - 1; }+ const part = lo < pass.marks.length ? clamp((want - cc[lo]) / (pass.marks[lo].len + 7)) : 0;+ lay(env, ctx, pass, lo, part);+ }+ finish(ctx, env);+ },+ stats: (env: Env) => { const { S } = sheetOf(env); return S.passes.map((p) => `${p.id}:${p.marks.length}`).join(" "); },+ };+};diff --git a/engine/src/canvas-core/core.ts b/engine/src/canvas-core/core.tsindex f2e290c..c8e52a1 100644--- a/engine/src/canvas-core/core.ts+++ b/engine/src/canvas-core/core.ts@@ -128,13 +128,16 @@ export const GRAPHITE = "#3d3437";export const TINT = { white: "#fffaf3", blush: "#f2899c", rose: "#e9a3ad", butter: "#f3d577", sky: "#a9c8e6", denim: "#6f93c4", sage: "#a9cfa6", lilac: "#c7b3e0", peach: "#f5b98a", glow: "#ffe9a3" };type PenOpts = { w?: number; color?: string; seed?: number; closed?: boolean; wobble?: number; boil?: number; taper?: number; opacity?: number; retrace?: boolean; progress?: number };-type Rect = [number, number, number, number]; // device px: x0, y0, x1, y1+export type Rect = [number, number, number, number]; // device px: x0, y0, x1, y1type Tracked = Layer & { dirty?: Rect | null };// PERFORMANCE RULE: nothing here touches a full-size surface unless it has to. Every primitive// marks the device-pixel box it drew into; blur, texture, compositing and clearing are then// confined to that box. (Phase 0 cleared and composited whole layers ~150 times per frame.)export class Gfx {+ // `drawn`: union of every device box composited onto `main` since construction. Read-only for the+ // art; the web profile (bake.ts) crops a part into a sprite by it. Setting it changes no pixel.+ drawn: Rect | null = null;cur: Ctx; private pool: Tracked[] = []; private stack: [number, number, number][] = [[0, 0, 1]]; private box: Rect | null = null;constructor(public main: Ctx, public env: Env, public frame: number, public medium: Medium) {this.cur = main; this.base(main);@@ -180,6 +183,7 @@ export class Gfx {if (opts.blur) r = this.soften(L, opts.blur, r);(opts.textures ?? []).forEach((t) => this.tooth(L, t, r));const m = this.main, w = r[2] - r[0], h = r[3] - r[1];+ if (w > 0 && h > 0) { const ox = Math.round((opts.off?.[0] ?? 0) * this.env.scale), oy = Math.round((opts.off?.[1] ?? 0) * this.env.scale); this.drawn = this.join(this.drawn, this.clip([r[0] + ox, r[1] + oy, r[2] + ox, r[3] + oy])); }if (w > 0 && h > 0) { m.save(); this.dev(m); m.globalCompositeOperation = opts.blend ?? "source-over"; m.globalAlpha = opts.alpha ?? 1; m.drawImage(L.canvas as CanvasImageSource, r[0], r[1], w, h, r[0] + Math.round((opts.off?.[0] ?? 0) * this.env.scale), r[1] + Math.round((opts.off?.[1] ?? 0) * this.env.scale), w, h); m.restore(); }this.release(L, r);}@@ -195,6 +199,7 @@ export class Gfx {this.dev(H.ctx); H.ctx.drawImage(L.canvas as CanvasImageSource, r[0], r[1], w, h, r[0], r[1], w, h);const rh = this.soften(H, o.blur ?? 1.8, r);(o.textures ?? ["draftTooth"]).forEach((t) => this.tooth(L, t, r));+ this.drawn = this.join(this.drawn, this.join(rh, r));const m = this.main; m.save(); this.dev(m); m.globalCompositeOperation = "source-over";m.globalAlpha = o.alpha ?? 0.28; m.drawImage(H.canvas as CanvasImageSource, rh[0], rh[1], rh[2] - rh[0], rh[3] - rh[1], rh[0], rh[1], rh[2] - rh[0], rh[3] - rh[1]);m.globalAlpha = 1; m.drawImage(L.canvas as CanvasImageSource, r[0], r[1], w, h, r[0], r[1], w, h); m.restore(); this.base(m);diff --git a/engine/src/canvas-core/drafting.ts b/engine/src/canvas-core/drafting.tsindex 9bcb6d3..cc81018 100644--- a/engine/src/canvas-core/drafting.ts+++ b/engine/src/canvas-core/drafting.ts@@ -29,19 +29,25 @@ const G: Record<string, Glyph> = {x: { l: [[[0.5, 1.8], [3.1, 4.8]], [[3.1, 1.8], [0.5, 4.8]]], w: 3.6 }, o: { c: [[[1.2, -0.2], [0.4, 0.5], [0.5, 1.5], [1.3, 2], [2.1, 1.4], [2.1, 0.4], [1.2, -0.2]]], w: 2.8 }, // x = times, o = degree"@": { c: [O], l: [[[0, 6.6], [4, -0.6]]] }, // diameter" ": { w: 2.6 },+ // added for teaching captions (no existing plate spells these, so nothing already drawn changes)+ "'": { l: [[[0.9, 0], [0.7, 1.7]]], w: 1.6 }, '"': { l: [[[0.6, 0], [0.5, 1.7]], [[1.8, 0], [1.7, 1.7]]], w: 2.4 },+ "?": { c: [[[0.3, 1.2], [1.1, 0.1], [2.6, 0.1], [3.4, 1], [3.4, 2], [1.9, 3.1], [1.8, 4.3]]], l: [[[1.7, 5.5], [1.9, 5.9]]], w: 3.6 },+ "!": { l: [[[1, 0], [0.9, 4.3]], [[0.8, 5.5], [1, 5.9]]], w: 1.9 }, ";": { l: [[[0.7, 2], [0.9, 2.4]], [[0.9, 5.4], [0.5, 6.8]]], w: 1.8 },+ "+": { l: [[[0.3, 3.2], [3.3, 3.2]], [[1.8, 1.7], [1.8, 4.7]]], w: 3.6 }, "=": { l: [[[0.4, 2.4], [3.2, 2.4]], [[0.4, 4], [3.2, 4]]], w: 3.6 },+ "%": { l: [[[3.4, 0.2], [0.2, 5.8]]], c: [[[0.9, 0.2], [0.3, 0.8], [0.9, 1.6], [1.5, 0.8], [0.9, 0.2]], [[2.8, 4.3], [2.2, 5], [2.8, 5.8], [3.4, 5], [2.8, 4.3]]], w: 3.6 },};-export type LetterOpts = { cap?: number; color?: string; seed?: number; align?: "left" | "center" | "right"; w?: number; opacity?: number; track?: number; progress?: number };+export type LetterOpts = { cap?: number; color?: string; seed?: number; align?: "left" | "center" | "right"; w?: number; opacity?: number; track?: number; progress?: number; slant?: number };const strokes = (ch: string): number => { const g = G[ch] ?? G[ch.toUpperCase()] ?? G["-"]; return (g.l ?? []).reduce((a, st) => a + st.length - 1, 0) + (g.c ?? []).length; };export const strokeCount = (text: string): number => [...text].reduce((a, ch) => a + strokes(ch), 0);export const width = (text: string, cap = 12, track = 1.25) => { const s = cap / 6; return [...text].reduce((a, ch) => a + ((G[ch] ?? G[ch.toUpperCase()] ?? G["-"]).w ?? 4) * s + track * s, 0) - track * s; };// progress writes the line stroke by stroke, in the order a hand makes them: never a fade.export const letter = (g: Gfx, text: string, x: number, y: number, o: LetterOpts = {}) => {- const { cap = 12, color = "#eef6fb", seed = 1, align = "left", opacity = 0.95, track = 1.25, progress = 1 } = o, s = cap / 6, r = rng(seed * 131 + 7), W = width(text, cap, track);+ const { cap = 12, color = "#eef6fb", seed = 1, align = "left", opacity = 0.95, track = 1.25, progress = 1, slant = 0.2 } = o, s = cap / 6, r = rng(seed * 131 + 7), W = width(text, cap, track);if (progress <= 0) return;let cx = align === "center" ? x - W / 2 : align === "right" ? x - W : x, written = progress >= 1 ? Infinity : progress * strokeCount(text);[...text].forEach((ch0, i) => {const gl = G[ch0] ?? G[ch0.toUpperCase()] ?? G["-"], dy = (r() - 0.5) * cap * 0.07, k = 1 + (r() - 0.5) * 0.06;- const T = ([px, py]: P): P => [cx + (px + (6 - py) * 0.2) * s * k, y + dy + py * s * k]; // 0.2 = the 68 degree slant of inclined lettering+ const T = ([px, py]: P): P => [cx + (px + (6 - py) * slant) * s * k, y + dy + py * s * k]; // 0.2 = the 68 degree slant of inclined lettering; 0 = uprightconst pen = (pts: P[], j: number) => { const p = written === Infinity ? 1 : Math.max(0, Math.min(1, written)); written === Infinity || (written -= 1); if (p > 0) g.pen(pts.map(T), { w: o.w ?? Math.max(1.1, cap * 0.115), color, seed: seed + i * 37 + j * 11, wobble: 0.25, boil: 0, taper: 0.35, opacity, progress: p }); };let j = 0; (gl.l ?? []).forEach((st) => { for (let q = 1; q < st.length; q++) pen([st[q - 1], st[q]], j++); }); (gl.c ?? []).forEach((st) => pen(st, j++));cx += ((gl.w ?? 4) + track) * s;diff --git a/engine/src/canvas-core/drawingMarks.ts b/engine/src/canvas-core/drawingMarks.tsnew file mode 100644index 0000000..30ac95b--- /dev/null+++ b/engine/src/canvas-core/drawingMarks.ts@@ -0,0 +1,138 @@+// DRAWING MARKS. The pencil-family marks a drawing score is made of: a stroke with a pressure+// profile, hatching clipped to a region, a contour as a chain of overlapping strokes, the loose+// construction ellipse a teacher draws, a scribbled dot, an eraser sweep. Every mark is built+// ONCE from (points, seed) and frozen: its geometry never boils, so a finished mark cannot change+// while later marks go down, and `draw(c, 1)` is the still, byte for byte.+//+// Kin to colouredPencilKit.ts (the v1 coloured-pencil plate): same stroke profile idea, but these+// marks are addressable one by one, which is what a score needs.+import { rng, sample, type Ctx, type P } from "./core";++export type Box = [number, number, number, number];+export type Ink = { cost: number; box: Box; draw: (c: Ctx, p: number) => void; cl: P[] };+export type Region = { box: Box; has: (x: number, y: number) => boolean };++const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));+const boxOf = (pts: P[], pad = 0): Box => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } return [x0 - pad, y0 - pad, x1 + pad, y1 + pad]; };+export const lengthOf = (c: P[]) => { let s = 0; for (let i = 1; i < c.length; i++) s += Math.hypot(c[i][0] - c[i - 1][0], c[i][1] - c[i - 1][1]); return s; };+export const densify = (s: P[], step: number): P[] => { const out: P[] = [s[0]]; for (let i = 1; i < s.length; i++) { const a = s[i - 1], b = s[i], n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step)); for (let k = 1; k <= n; k++) out.push([a[0] + ((b[0] - a[0]) * k) / n, a[1] + ((b[1] - a[1]) * k) / n]); } return out; };++// ---------------------------------------------------------------- regions (what hatching is clipped to)+export const inPoly = (pts: P[], x: number, y: number) => { let k = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[i], b = pts[j]; if (a[1] > y !== b[1] > y && x < ((b[0] - a[0]) * (y - a[1])) / (b[1] - a[1]) + a[0]) k = !k; } return k; };+export const polyR = (pts: P[]): Region => { const box = boxOf(pts); return { box, has: (x, y) => x >= box[0] && x <= box[2] && y >= box[1] && y <= box[3] && inPoly(pts, x, y) }; };+export const ellR = (cx: number, cy: number, rx: number, ry: number, rot = 0): Region => { const c = Math.cos(-rot), s = Math.sin(-rot), R = Math.max(rx, ry); return { box: [cx - R, cy - R, cx + R, cy + R], has: (x, y) => { const dx = x - cx, dy = y - cy, u = dx * c - dy * s, v = dx * s + dy * c; return (u / rx) ** 2 + (v / ry) ** 2 <= 1; } }; };+export const union = (...rs: Region[]): Region => ({ box: [Math.min(...rs.map((r) => r.box[0])), Math.min(...rs.map((r) => r.box[1])), Math.max(...rs.map((r) => r.box[2])), Math.max(...rs.map((r) => r.box[3]))], has: (x, y) => rs.some((r) => r.has(x, y)) });+export const minus = (a: Region, ...bs: Region[]): Region => ({ box: a.box, has: (x, y) => a.has(x, y) && !bs.some((b) => b.has(x, y)) });+export const inter = (a: Region, b: Region): Region => ({ box: a.box, has: (x, y) => a.has(x, y) && b.has(x, y) });+// distance to a closed polygon's boundary: tone that gathers toward the turning edge of a form+export const edgeDist = (pts: P[]) => (x: number, y: number) => { let d = 1e9; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const [ax, ay] = pts[j], [bx, by] = pts[i], dx = bx - ax, dy = by - ay, l = dx * dx + dy * dy || 1, t = clamp(((x - ax) * dx + (y - ay) * dy) / l); d = Math.min(d, Math.hypot(x - ax - t * dx, y - ay - t * dy)); } return d; };+export const ellipsePts = (cx: number, cy: number, rx: number, ry: number, rot = 0, n = 24): P[] => Array.from({ length: n }, (_, i) => { const a = (i / n) * Math.PI * 2, x = Math.cos(a) * rx, y = Math.sin(a) * ry; return [cx + x * Math.cos(rot) - y * Math.sin(rot), cy + x * Math.sin(rot) + y * Math.cos(rot)] as P; });++// ---------------------------------------------------------------- the stroke+// Pressure lands fast, holds, lifts in a longer taper. `taper` 0 = a blunt tool (marker, biro).+const profileOf = (t: number, taper: number) => 1 - taper + taper * Math.max(0.2, Math.pow(clamp(t / 0.14), 0.6) * Math.pow(clamp((1 - t) / 0.38), 0.75));+const outline = (c: P[], w: number, taper: number): P[] => {+ const n = c.length, L: P[] = [], R: P[] = [];+ for (let i = 0; i < n; i++) { const p = c[i], q = c[Math.min(n - 1, i + 1)], o = c[Math.max(0, i - 1)], dx = q[0] - o[0], dy = q[1] - o[1], l = Math.hypot(dx, dy) || 1, h = (w * profileOf(n > 1 ? i / (n - 1) : 0.5, taper)) / 2; L.push([p[0] - (dy / l) * h, p[1] + (dx / l) * h]); R.push([p[0] + (dy / l) * h, p[1] - (dx / l) * h]); }+ return [...L, ...R.reverse()];+};+const cut = (c: P[], p: number): P[] => { if (p >= 1) return c; const n = (c.length - 1) * p, i = Math.floor(n), f = n - i, head = c.slice(0, i + 1); if (f > 1e-6 && i + 1 < c.length) head.push([c[i][0] + (c[i + 1][0] - c[i][0]) * f, c[i][1] + (c[i + 1][1] - c[i][1]) * f]); return head.length > 1 ? head : c.slice(0, 2); };+const fillPoly = (c: Ctx, pts: P[]) => { c.beginPath(); c.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) c.lineTo(pts[i][0], pts[i][1]); c.closePath(); c.fill(); };++export type StrokeOpts = { w: number; col: string; a: number; taper?: number; smooth?: boolean };+// One stroke. The centreline is resampled so a partial draw is cut ON the centreline and the+// travelling tip keeps its taper, which is how a line is seen being made.+export const stroke = (pts: P[], o: StrokeOpts): Ink => {+ const { w, col, a, taper = 1, smooth = true } = o, len = lengthOf(pts), per = Math.max(2, Math.min(12, Math.round(len / 5)));+ const c = densify(smooth && pts.length > 2 ? sample(pts, false, Math.max(2, Math.ceil(per / (pts.length - 1)) + 1)) : pts, Math.max(2, len / 40));+ const full = outline(c, w, taper);+ return { cost: len + 9, box: boxOf(full, 2), cl: c, draw: (cx, p) => { if (p <= 0) return; cx.globalAlpha = a; cx.fillStyle = col; fillPoly(cx, p >= 1 ? full : outline(cut(c, p), w, taper)); cx.globalAlpha = 1; } };+};++// ---------------------------------------------------------------- hatching+export type HatchOpts = {+ ang: number; gap: number; len: number; w: number; col: string; a: number; seed: number;+ dens?: (x: number, y: number) => number; // 0..1: how much tone at a point (pressure AND coverage)+ jit?: number; strip?: number; over?: number; taper?: number;+ back?: boolean; // back-and-forth zigzag strokes (a scribble fill) instead of lifted hatches+};+// Parallel strokes at one angle, laid side by side in strips the way a hand works a patch.+// Edges are where the strokes stop; tone is where they sit and how hard they press.+export const hatch = (reg: Region, o: HatchOpts): Ink[] => {+ const { ang, gap, len, w, col, a, seed, dens = () => 1, jit = 0.08, strip = 140, over = 1.5, taper = 1 } = o, r = rng(seed);+ const cs = Math.cos(ang), sn = Math.sin(ang), b = reg.box, cx = (b[0] + b[2]) / 2, cy = (b[1] + b[3]) / 2, R = Math.hypot(b[2] - b[0], b[3] - b[1]) / 2 + gap;+ const at = (u: number, v: number): P => [cx + u * cs - v * sn, cy + u * sn + v * cs];+ const found: { u: number; v: number; m: Ink }[] = [];+ for (let v = -R; v <= R; v += gap * (0.8 + r() * 0.4)) {+ let run0 = NaN;+ for (let u = -R; u <= R + 2; u += 2) {+ const [x, y] = at(u, v), ins = u <= R && reg.has(x, y);+ if (ins && isNaN(run0)) run0 = u;+ if (!ins && !isNaN(run0)) {+ const u0 = run0 - r() * over, u1 = u - 2 + r() * over; run0 = NaN; let s = u0 + (r() - 0.5) * len * 0.4;+ while (s < u1) {+ const L = len * (0.6 + r() * 0.7), e = Math.min(u1, s + L), s0 = Math.max(u0, s);+ if (e - s0 > 2.5) {+ const mu = (s0 + e) / 2, [mx, my] = at(mu, v), d = clamp(dens(mx, my));+ if (d > 0.03 && r() < Math.pow(d, 0.5)) {+ const tw = (r() - 0.5) * 2 * jit, dv = ((e - s0) * Math.sin(tw)) / 2, bow = (r() - 0.5) * 1.6;+ found.push({ u: mu, v, m: stroke([at(s0, v - dv), at(mu, v + bow), at(e, v + dv)], { w: w * (0.8 + r() * 0.4) * (0.7 + 0.3 * d), col, a: a * (0.35 + 0.65 * d) * (0.8 + r() * 0.35), taper }) });+ }+ }+ s = e + (r() - 0.4) * len * 0.3;+ }+ }+ }+ }+ found.sort((p, q) => { const sp = Math.floor((p.u + R) / strip), sq = Math.floor((q.u + R) / strip); return sp !== sq ? sp - sq : sp % 2 ? q.v - p.v : p.v - q.v; });+ // cost is shared: a hand hatches a patch quickly, so a hatch stroke costs less time than its length+ return found.map((f) => ({ ...f.m, cost: f.m.cost * 0.55 }));+};++// ---------------------------------------------------------------- contours+export type ContourOpts = { w: number; col: string; a: number; seed: number; seg?: number; keep?: (x: number, y: number, t: number) => number; closed?: boolean; smooth?: boolean; taper?: number };+// A contour the way a pencil draws one: overlapping strokes, each a touch off the last, the pressure+// lifting between them. keep(x, y, t) -> weight multiplier: 0 loses the edge where the light eats it.+export const contour = (pts: P[], o: ContourOpts): Ink[] => {+ const { w, col, a, seed, seg = 70, keep = () => 1, closed = false, smooth = true, taper = 1 } = o, r = rng(seed);+ const base = smooth ? sample(pts, closed, 8) : densify(closed ? [...pts, pts[0]] : pts, 3), path = densify(base, 2.5), n = path.length, out: Ink[] = [];+ let i = 0;+ while (i < n - 1) {+ const segLen = seg * (0.65 + r() * 0.7), start = Math.max(0, i - Math.round(1 + r() * 2)); let j = start, acc = 0;+ while (j < n - 1 && acc < segLen) { acc += Math.hypot(path[j + 1][0] - path[j][0], path[j + 1][1] - path[j][1]); j++; }+ const piece = path.slice(start, j + 1), mid = piece[piece.length >> 1], k = clamp(keep(mid[0], mid[1], (start + j) / 2 / n), 0, 2);+ if (piece.length > 1 && k > 0.05) { const off = (r() - 0.5) * 0.9, jj = rng(seed * 13 + i); out.push(stroke(piece.filter((_, q) => q % 2 === 0 || q === piece.length - 1).map(([x, y]) => [x + off + (jj() - 0.5) * 0.5, y + (jj() - 0.5) * 0.5] as P), { w: w * (0.8 + r() * 0.35) * (0.6 + 0.4 * k), col, a: a * Math.min(1, 0.5 + 0.5 * k) * (0.8 + r() * 0.25), taper, smooth: false })); }+ i = j;+ }+ return out;+};++// The construction ellipse a teacher draws: one fast, loose loop that goes round a little more than+// once, so the second pass corrects the first. Never a perfect circle.+export const sketchEllipse = (cx: number, cy: number, rx: number, ry: number, o: { rot?: number; w: number; col: string; a: number; seed: number; turns?: number }): Ink => {+ const { rot = 0, w, col, a, seed, turns = 1.18 } = o, r = rng(seed), a0 = -2.2 + r() * 0.6, pts: P[] = [], n = Math.round(40 * turns);+ for (let i = 0; i <= n; i++) { const t = i / n, ang = a0 + t * turns * Math.PI * 2, wob = 1 + (t > 0.85 ? (t - 0.85) * 0.25 : 0) + (r() - 0.5) * 0.02, x = Math.cos(ang) * rx * wob, y = Math.sin(ang) * ry * wob; pts.push([cx + x * Math.cos(rot) - y * Math.sin(rot), cy + x * Math.sin(rot) + y * Math.cos(rot)]); }+ return { ...stroke(pts, { w, col, a, taper: 0.6, smooth: false }), cost: lengthOf(pts) * 0.6 + 12 };+};+// a construction line: ruled freehand, overshooting both ends the way a lay-in does+export const guideLine = (a: P, b: P, o: { w: number; col: string; a: number; seed: number; bow?: number }): Ink => {+ const r = rng(o.seed), dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, e0 = 6 + r() * 12, e1 = 6 + r() * 12, bow = o.bow ?? (r() - 0.5) * 3;+ return stroke([[a[0] - (dx / l) * e0, a[1] - (dy / l) * e0], [(a[0] + b[0]) / 2 - (dy / l) * bow, (a[1] + b[1]) / 2 + (dx / l) * bow], [b[0] + (dx / l) * e1, b[1] + (dy / l) * e1]], { w: o.w, col: o.col, a: o.a, taper: 0.7 });+};+// a small dark shape worked in place: a pencil twisted in a tight spiral (a pupil, a nostril, a note head)+export const scribbleDot = (x: number, y: number, rx: number, ry: number, o: { w: number; col: string; a: number; seed: number; rot?: number; turns?: number }): Ink => {+ const r = rng(o.seed), pts: P[] = [], n = 26, rot = o.rot ?? 0, turns = o.turns ?? 3;+ for (let k = 0; k <= n; k++) { const t = k / n, an = t * Math.PI * 2 * turns + r() * 0.2, rr = 1 - t * 0.75; const u = Math.cos(an) * rx * rr, v = Math.sin(an) * ry * rr; pts.push([x + u * Math.cos(rot) - v * Math.sin(rot), y + u * Math.sin(rot) + v * Math.cos(rot)]); }+ return { ...stroke(pts, { w: o.w, col: o.col, a: o.a, taper: 0.3, smooth: false }), cost: 40 };+};++// ---------------------------------------------------------------- the eraser+// A kneaded eraser worked back and forth over a box: the path it travels, and how wide it bites.+export const eraserPath = (b: Box, o: { seed: number; bite: number; ang?: number }): P[] => {+ const r = rng(o.seed), [x0, y0, x1, y1] = b, rows = Math.max(1, Math.ceil((y1 - y0) / (o.bite * 0.75))), pts: P[] = [];+ for (let i = 0; i <= rows; i++) { const y = y0 + ((y1 - y0) * i) / rows + (r() - 0.5) * o.bite * 0.2; pts.push(i % 2 ? [x1 + (r() - 0.5) * o.bite * 0.3, y] : [x0 + (r() - 0.5) * o.bite * 0.3, y]); }+ return pts;+};+// the eraser's bite, cut at progress p along its travel: ONE stroke() call, so where the path+// crosses itself the eraser still lifts only once (the ghost stays even)+export const eraserStroke = (c: Ctx, path: P[], width: number, p: number) => { const q = cut(densify(path, 6), p); c.lineWidth = width; c.lineJoin = "round"; c.lineCap = "round"; c.beginPath(); c.moveTo(q[0][0], q[0][1]); for (let i = 1; i < q.length; i++) c.lineTo(q[i][0], q[i][1]); c.stroke(); };diff --git a/engine/src/canvas-core/drawingScore.ts b/engine/src/canvas-core/drawingScore.tsnew file mode 100644index 0000000..e264b00--- /dev/null+++ b/engine/src/canvas-core/drawingScore.ts@@ -0,0 +1,171 @@+// THE DRAWING SCORE. A drawing written down as the ORDER a hand makes it: parts of the subject,+// marks with stable ids, what each mark waits for, and the teaching phases they fall in. One+// score drives everything: the finished still, a timelapse, a step sheet, a replay at any frame.+// (Spec 14, "an authored drawing score, not a generated video", plus teach mode from ADVISORY-PLAN+// 4.2. It is authored source data: no model, no image, no fetch at render time.)+//+// parts the subject's pieces, with dependencies ("the ear waits for the head")+// layers isolation for things that must be REMOVED later: blue construction guides, a wrong+// line that gets corrected. An eraser works on ONE layer and only on what is already+// on it, the way a kneaded eraser lifts the col-erase blue without touching graphite.+// marks one stroke each (or one eraser pass). Built once from (points, seed) and frozen, so a+// finished mark never changes while later marks go down.+// steps the lesson: a phase, a title, a caption, and the teaching (what to look for, how,+// the common mistake). Every mark belongs to exactly one step.+//+// Final identity holds because there is only one renderer: the timelapse's last frame, the still+// and the step sheet all call renderArt() with the same marks at progress 1. The gate in+// tools/lesson.mjs still checks it (cached replay path against a cold, uncached one) because a+// green claim is not evidence.+import { Gfx, PENCIL, fractal, type Ctx, type Env, type Layer } from "./core";+import { eraserStroke, type Box, type Ink } from "./drawingMarks";+import type { P } from "./core";++export const PHASES = ["placement", "shapes", "construction", "values", "colour", "edges", "accents"] as const;+export type Phase = (typeof PHASES)[number];+export const PHASE_NAME: Record<Phase, string> = { placement: "placement and gesture", shapes: "big shapes", construction: "construction", values: "value masses", colour: "local colour", edges: "edges and details", accents: "accents" };++export type MarkKind = "guide" | "line" | "fill" | "correction" | "erase";+export type LayerSpec = { id: string; tooth: 0 | 1 | 2 | null; alpha?: number; note?: string };+export type Part = { id: string; label: string; dependsOn: string[] };+export type Mark = { id: string; part: string; layer: string; kind: MarkKind; step: number; cost: number; box: Box; ink?: Ink; erase?: { path: P[]; width: number; ghost: number }; after: string[]; supersedes?: string };+export type StepText = { title: string; caption: string; look: string; how: string; mistake?: string };+export type Step = StepText & { id: string; phase: Phase; marks: number[] };+export type Score = {+ id: string; title: string; medium: string; note?: string; W: number; H: number; paper: string; toothAngle: number;+ layers: LayerSpec[]; parts: Part[]; marks: Mark[]; steps: Step[]; byLayer: Map<string, number[]>; index: Map<string, number>;+};++// ---------------------------------------------------------------- authoring+export class ScoreBuilder {+ private layers: LayerSpec[] = []; private parts: Part[] = []; private marks: Mark[] = []; private steps: Step[] = [];+ constructor(private meta: { id: string; title: string; medium: string; note?: string; W: number; H: number; paper: string; toothAngle?: number }) {}+ layer(id: string, tooth: 0 | 1 | 2 | null, alpha = 1, note?: string) { this.layers.push({ id, tooth, alpha, note }); return this; }+ part(id: string, label: string, dependsOn: string[] = []) { this.parts.push({ id, label, dependsOn }); return this; }+ step(id: string, phase: Phase, t: StepText) { this.steps.push({ id, phase, ...t, marks: [] }); return this; }+ private push(m: Omit<Mark, "step">) { const s = this.steps.length - 1; if (s < 0) throw new Error(`mark ${m.id} before any step`); this.marks.push({ ...m, step: s }); this.steps[s].marks.push(this.marks.length - 1); }+ add(id: string, part: string, layer: string, kind: MarkKind, ink: Ink, o: { after?: string[]; supersedes?: string } = {}) { this.push({ id, part, layer, kind, ink, cost: ink.cost, box: ink.box, after: o.after ?? [], supersedes: o.supersedes }); return id; }+ // many marks under one authored name: ids are name.000, name.001 ... stable as long as the recipe is+ addAll(name: string, part: string, layer: string, kind: MarkKind, inks: Ink[], o: { after?: string[] } = {}) { return inks.map((ink, i) => this.add(`${name}.${String(i).padStart(3, "0")}`, part, layer, kind, ink, i === 0 ? o : {})); }+ erase(id: string, part: string, layer: string, path: P[], o: { width: number; ghost: number; after?: string[] }) {+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of path) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }+ let len = 0; for (let i = 1; i < path.length; i++) len += Math.hypot(path[i][0] - path[i - 1][0], path[i][1] - path[i - 1][1]);+ this.push({ id, part, layer, kind: "erase", erase: { path, width: o.width, ghost: o.ghost }, cost: len * 0.35 + 20, box: [x0 - o.width, y0 - o.width, x1 + o.width, y1 + o.width], after: o.after ?? [] }); return id;+ }+ build(): Score {+ const index = new Map<string, number>(); this.marks.forEach((m, i) => index.set(m.id, i));+ const byLayer = new Map<string, number[]>(this.layers.map((l) => [l.id, []])); this.marks.forEach((m, i) => byLayer.get(m.layer)?.push(i));+ const S: Score = { ...this.meta, toothAngle: this.meta.toothAngle ?? -0.55, layers: this.layers, parts: this.parts, marks: this.marks, steps: this.steps, byLayer, index };+ const { problems } = validate(S); if (problems.length) throw new Error(`drawing score '${S.id}': ${problems.slice(0, 8).join("; ")}${problems.length > 8 ? ` (+${problems.length - 8} more)` : ""}`);+ return S;+ }+}++// ---------------------------------------------------------------- the schema gate+export const validate = (S: Score) => {+ const problems: string[] = [], warnings: string[] = [], seen = new Set<string>(), partIds = new Set(S.parts.map((p) => p.id)), layerIds = new Set(S.layers.map((l) => l.id));+ S.marks.forEach((m) => { if (seen.has(m.id)) problems.push(`duplicate mark id ${m.id}`); seen.add(m.id); if (!partIds.has(m.part)) problems.push(`mark ${m.id}: unknown part ${m.part}`); if (!layerIds.has(m.layer)) problems.push(`mark ${m.id}: unknown layer ${m.layer}`); });+ S.parts.forEach((p) => p.dependsOn.forEach((d) => { if (!partIds.has(d)) problems.push(`part ${p.id}: depends on unknown part ${d}`); }));+ // dependencies acyclic+ const state = new Map<string, number>(), visit = (id: string, path: string[]): void => { if (state.get(id) === 2) return; if (state.get(id) === 1) { problems.push(`part dependency cycle: ${[...path, id].join(" -> ")}`); return; } state.set(id, 1); S.parts.find((p) => p.id === id)?.dependsOn.forEach((d) => visit(d, [...path, id])); state.set(id, 2); };+ S.parts.forEach((p) => visit(p.id, []));+ // order: a part's first mark comes after the first mark of every part it depends on; `after` marks come earlier+ const first = new Map<string, number>(); S.marks.forEach((m, i) => { if (!first.has(m.part)) first.set(m.part, i); });+ S.parts.forEach((p) => { const f = first.get(p.id); if (f === undefined) { warnings.push(`part ${p.id} has no marks`); return; } p.dependsOn.forEach((d) => { const fd = first.get(d); if (fd !== undefined && fd > f) problems.push(`part ${p.id} starts (mark ${S.marks[f].id}) before the part it depends on, ${d}`); }); });+ S.marks.forEach((m, i) => { m.after.forEach((a) => { const j = S.index.get(a); if (j === undefined) problems.push(`mark ${m.id}: after unknown mark ${a}`); else if (j >= i) problems.push(`mark ${m.id}: waits for ${a}, which comes later`); }); });+ // a correction replaces a mark that has been ERASED before the new one starts (on its own layer, so nothing else is lifted)+ S.marks.forEach((m, i) => { if (!m.supersedes) return; const j = S.index.get(m.supersedes); if (j === undefined) { problems.push(`correction ${m.id}: supersedes unknown mark ${m.supersedes}`); return; } const old = S.marks[j]; const e = S.marks.findIndex((x, k) => k > j && k < i && x.kind === "erase" && x.layer === old.layer); if (e < 0) problems.push(`correction ${m.id}: ${old.id} (layer ${old.layer}) is never erased before it`); if (old.layer === m.layer) warnings.push(`correction ${m.id} shares layer ${old.layer} with what it replaces: erase it before drawing`); });+ // phases run forward (a teacher may revisit construction during big shapes, so this only warns)+ S.steps.forEach((s, k) => { if (k && PHASES.indexOf(s.phase) < PHASES.indexOf(S.steps[k - 1].phase)) warnings.push(`step ${s.id} (${s.phase}) comes after ${S.steps[k - 1].id} (${S.steps[k - 1].phase})`); if (!s.marks.length) warnings.push(`step ${s.id} has no marks`); const words = s.caption.split(/\s+/).filter(Boolean).length; if (words > 24) warnings.push(`step ${s.id}: caption is ${words} words (keep it at 24 or fewer)`); });+ // guides must be gone by the end: any mark on a layer whose name starts with "guide" must be under an eraser that runs after it+ S.marks.forEach((m, i) => { if (m.kind !== "guide") return; if (!S.marks.some((x, k) => k > i && x.kind === "erase" && x.layer === m.layer)) warnings.push(`guide ${m.id} is never erased`); });+ const stats = { marks: S.marks.length, parts: S.parts.length, steps: S.steps.length, perPart: Object.fromEntries(S.parts.map((p) => [p.id, S.marks.filter((m) => m.part === p.id).length])), perStep: S.steps.map((s) => `${s.id}:${s.marks.length}`) };+ return { problems, warnings, stats };+};++// ---------------------------------------------------------------- time+export type Timing = { intro: number; captionLead: number; pause: number; hold: number; rate: number; minStep: number; maxStep: number; grid: number };+export type Plan = { total: number; steps: { start: number; markStart: number; markEnd: number; end: number }[]; s: Float64Array; e: Float64Array };+// Steps start on the beat grid. Inside a step the marks run one after another, each taking time+// in proportion to its cost (ink length plus a lift), so long strokes are fast per unit length+// and every lift of the pencil costs a beat of time. One active mark at a time: never two parts at once.+export const schedule = (S: Score, T: Timing): Plan => {+ const n = S.marks.length, s = new Float64Array(n), e = new Float64Array(n), steps: Plan["steps"] = []; let f = T.intro;+ S.steps.forEach((st) => {+ const start = f, markStart = start + T.captionLead, C = st.marks.reduce((a, i) => a + S.marks[i].cost, 0) || 1;+ const dur = Math.max(T.minStep, Math.min(T.maxStep, Math.round(C / T.rate))); let acc = 0;+ st.marks.forEach((i) => { s[i] = markStart + (acc / C) * dur; acc += S.marks[i].cost; e[i] = markStart + (acc / C) * dur; });+ const markEnd = markStart + dur, end = Math.ceil((markEnd + T.pause) / T.grid) * T.grid; steps.push({ start, markStart, markEnd, end }); f = end;+ });+ return { total: Math.ceil((f + T.hold) / T.grid) * T.grid, steps, s, e };+};+export const progressAt = (P: Plan, frame: number) => (i: number) => { const a = P.s[i], b = P.e[i]; return frame >= b ? 1 : frame <= a ? 0 : (frame - a) / (b - a); };++// ---------------------------------------------------------------- rendering+export type View = { x: number; y: number; w: number; h: number }; // device px where design [0,W]x[0,H] lands+const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));+const LEVELS = [0.5, 0.56, 0.64]; // tooth thresholds: light, medium, burnished pressure+const toothField = (env: Env, S: Score): Float32Array => {+ const key = `ds:tooth:${S.W}x${S.H}:${S.toothAngle}`; let f = env.cache.get(key) as Float32Array | undefined; if (f) return f;+ f = new Float32Array(S.W * S.H); const c = Math.cos(S.toothAngle), s = Math.sin(S.toothAngle);+ for (let y = 0; y < S.H; y++) for (let x = 0; x < S.W; x++) { const u = x * c + y * s, v = -x * s + y * c; f[y * S.W + x] = 0.6 * fractal(71, u, v, 0.13, 0.6, 2) + 0.4 * fractal(73, x, y, 0.85, 0.85, 1); }+ env.cache.set(key, f); return f;+};+const toothMask = (env: Env, S: Score, lvl: number, v: View, DW: number, DH: number): Layer => {+ const key = `ds:mask:${S.id}:${lvl}:${v.x},${v.y},${v.w},${v.h}:${DW}x${DH}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const f = toothField(env, S), small = env.canvas(S.W, S.H), img = small.ctx.createImageData(S.W, S.H), d = img.data, T = LEVELS[lvl];+ for (let i = 0; i < S.W * S.H; i++) d[i * 4 + 3] = 255 * clamp((T - f[i]) * 11 + 0.5);+ small.ctx.putImageData(img, 0, 0); L = env.canvas(DW, DH); L.ctx.imageSmoothingEnabled = true; L.ctx.drawImage(small.canvas as CanvasImageSource, 0, 0, S.W, S.H, v.x, v.y, v.w, v.h);+ env.cache.set(key, L); return L;+};+const surface = (env: Env, name: string, DW: number, DH: number): Layer => { const k = `ds:surf:${name}:${DW}x${DH}`; let L = env.cache.get(k) as Layer | undefined; if (!L) { L = env.canvas(DW, DH); env.cache.set(k, L); } return L; };+const toView = (c: Ctx, S: Score, v: View) => c.setTransform(v.w / S.W, 0, 0, v.h / S.H, v.x, v.y);+const drawItem = (c: Ctx, S: Score, i: number, p: number, v: View) => {+ const m = S.marks[i]; toView(c, S, v);+ if (m.erase) { c.globalCompositeOperation = "destination-out"; c.globalAlpha = 1 - m.erase.ghost; c.strokeStyle = "#000"; eraserStroke(c, m.erase.path, m.erase.width, p); c.globalCompositeOperation = "source-over"; c.globalAlpha = 1; }+ else m.ink!.draw(c, p);+};++// Paint the art (paper + every layer) for a progress function, into view `v` of ctx.+// `cache` (a name) turns on prefix caching for replay: per layer, the layer with its first k items+// complete is kept, so a frame only draws the marks that are still moving. Same ops, same order:+// the cached path and the cold path produce the same pixels (gated in tools/lesson.mjs).+export const renderArt = (ctx: Ctx, env: Env, S: Score, prog: (i: number) => number, v: View, o: { cache?: string; paper?: boolean } = {}) => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale);+ if (o.paper !== false) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; ctx.fillStyle = S.paper; ctx.fillRect(v.x, v.y, v.w, v.h); ctx.restore(); }+ for (const Ls of S.layers) {+ const items = S.byLayer.get(Ls.id)!; let any = false; for (const i of items) if (prog(i) > 0) { any = true; break; } if (!any) continue;+ let k = 0; while (k < items.length && prog(items[k]) >= 1) k++;+ const L = surface(env, "scratch", DW, DH), c = L.ctx;+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "source-over"; c.globalAlpha = 1; c.clearRect(0, 0, DW, DH);+ if (o.cache && k > 0) c.drawImage(prefix(env, S, Ls.id, items, k, v, o.cache, DW, DH).canvas as CanvasImageSource, 0, 0);+ else for (let j = 0; j < k; j++) drawItem(c, S, items[j], 1, v);+ for (let j = k; j < items.length; j++) { const p = prog(items[j]); if (p > 0) drawItem(c, S, items[j], Math.min(1, p), v); }+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1;+ if (Ls.tooth !== null) { c.globalCompositeOperation = "destination-in"; c.drawImage(toothMask(env, S, Ls.tooth, v, DW, DH).canvas as CanvasImageSource, 0, 0); c.globalCompositeOperation = "source-over"; }+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = Ls.alpha ?? 1; ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); ctx.restore();+ }+};+// the layer with its first k items complete, built from the nearest cached prefix below k+const prefix = (env: Env, S: Score, layer: string, items: number[], k: number, v: View, name: string, DW: number, DH: number): Layer => {+ const keyOf = (j: number) => `ds:pre:${S.id}:${name}:${layer}:${j}:${v.x},${v.y},${v.w},${v.h}:${DW}x${DH}`, hit = env.cache.get(keyOf(k)) as Layer | undefined; if (hit) return hit;+ const lk = `ds:prekeys:${S.id}:${name}:${layer}:${DW}x${DH}`, keys = (env.cache.get(lk) as string[] | undefined) ?? [];+ let j = 0, from: Layer | undefined; for (const key of keys) { const jj = Number(key.split(":")[5]); if (jj < k && jj > j && env.cache.has(key)) { j = jj; from = env.cache.get(key) as Layer; } }+ const L = keys.length >= 2 ? (env.cache.get(keys[0]) as Layer) : env.canvas(DW, DH); // recycle the oldest surface+ if (keys.length >= 2) { env.cache.delete(keys.shift()!); if (from === L) { from = undefined; j = 0; } }+ const c = L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "source-over"; c.globalAlpha = 1; c.clearRect(0, 0, DW, DH);+ if (from) c.drawImage(from.canvas as CanvasImageSource, 0, 0); else j = 0;+ for (let q = j; q < k; q++) drawItem(c, S, items[q], 1, v);+ keys.push(keyOf(k)); env.cache.set(lk, keys); env.cache.set(keyOf(k), L); return L;+};+// the sheet's grain over everything, once (matches the other pencil plates)+export const paperGrain = (ctx: Ctx, env: Env, opacity = 0.05) => new Gfx(ctx, env, 0, PENCIL).paper("paper", opacity);++// ---------------------------------------------------------------- step views+export const stepOf = (S: Score, i: number) => S.marks[i].step;+export const upTo = (S: Score, k: number) => (i: number) => (S.marks[i].step <= k ? 1 : 0); // steps 0..k complete+export const all = () => () => 1;+// the step-sheet grammar: what was there before step k, erasures of step k applied (drawn pale by+// the caller), and step k's new marks on their own (drawn strong)+export const before = (S: Score, k: number) => (i: number) => { const m = S.marks[i]; return m.step < k || (m.step === k && m.kind === "erase") ? 1 : 0; };+export const only = (S: Score, k: number) => (i: number) => { const m = S.marks[i]; return m.step === k && m.kind !== "erase" ? 1 : 0; };diff --git a/engine/src/canvas-core/embroidery.ts b/engine/src/canvas-core/embroidery.tsnew file mode 100644index 0000000..f2f7ef2--- /dev/null+++ b/engine/src/canvas-core/embroidery.ts@@ -0,0 +1,320 @@+import { Gfx, rng, type Ctx, type Env, type Layer, type Medium, type P } from "./core";+import type { Film } from "./film";+import { clamp, lerp, lerpP, mix, polyLen, resample, smooth } from "./gallery";+import { LIGHT, drawShadows, drawThreads, fishbone, headOf, knot, knots, linenLayer, longShort, runningStitch, satin, splitStitch, stemStitch, straight, type St } from "./embroideryKit";++// A WREATH AND A BEE · hand embroidery in a hoop.+//+// MEDIUM, physically: six-stranded cotton floss, split to two or three strands, and one gold+// thread for the flight line, worked with a crewel needle through natural linen, plain weave with+// slubs, stretched drum-tight in a beech hoop with a brass screw clamp.+// MARKS: a stitch is a length of twisted thread between two holes. Stem stitch (overlapping,+// slanted: a rope) for stems; split stitch (each stitch coming up through the last) for the outlines+// the fills butt against; satin stitch laid side by side ACROSS a form, the direction following it+// (across a petal, from a leaf's edge to its midrib, round a bee's abdomen); long-and-short rows+// shading one thread colour into another; French knots for flower centres, lavender and stamens;+// running stitch for the bee's flight line; single straight stitches for legs and wing veins.+// EDGE: the edge of every shape is the ends of its stitches, a row of tiny pinches into the+// cloth. Nothing is outlined by ink; outlines are thread too.+// ORDER: outlines first (stems in stem stitch, then the split-stitch edges), then the fills+// (leaves, poppy, daisies, forget-me-nots), then the knots, then the bee, last, and the needle is+// parked in the cloth. Each stitch appears as the needle pulls the thread through, one by one.+// PALETTE: oatmeal linen; sage, olive and moss greens; white and shell for daisies; butter and+// ochre centres; cornflower blue; two lavenders; poppy coral to oxblood; bee gold and umber.+// GROUND: the linen, a woven plain weave (warp over weft, weft over warp) you can count.+// LIGHT: a window upper left. Every stitch has a lit side and a shade side, its sheen depends on+// which way it lies to the light (so satin reads the form), and it casts a hair of shadow down and+// right. The hoop's ring casts a shadow onto the cloth inside it at upper left, outside at lower right.+// SUBJECT and STRUCTURE (from knowledge of botanical embroidery and of the plants): an open wreath,+// two stems rising from a crossing at the bottom; oxeye daisy (white rays round a domed yellow+// disc, seen face on, three-quarter and as a bud in its green calyx); field poppy (four crumpled+// petals, a green seed pod with a dark stigma disc and a ring of black stamens); forget-me-nots+// (five round petals, yellow eye, in small coiled clusters); lavender (knotted spikes on bare+// stems); lanceolate and ovate leaves. The bee is a honeybee: head with compound eyes and elbowed+// antennae, furred thorax, banded six-segment abdomen, two pairs of veined wings (the forewing+// larger), six legs, a pollen load on the hind leg; flying in toward the smallest daisy.+// WHAT MAKES IT NOT ITS NEIGHBOUR (fox, cut paper): nothing here is a flat piece; every mark is a+// line with a direction, and tone comes from the direction of the stitches, not from colour fills.++const W = 1080, H = 1080, N = 540, HOLD = 30;+const EMB_M: Medium = { nib: 1, taper: 0, pressure: 0, retrace: false, wobble: 0, rough: 0 };+const HC: P = [540, 548], RO = 470, RI = 446; // the hoop+const C: P = [540, 584], R = 294; // the wreath+const G = { dark: "#4d6636", olive: "#6c7f3e", sage: "#8ea46a", light: "#b3c690", stem: "#5b6f3b", grey: "#8c9a79" };+const WHITE = "#f7f3eb", SHELL = "#dcd4c3", BUTTER = "#f1c33d", OCHRE = "#cf8a1e";+const BLUE = "#6f98d2", BLUE2 = "#a2bfe6", LAV = "#8f7bc0", LAV2 = "#66529a";+const POPPY = ["#f08566", "#e2553b", "#c43b2d", "#8b211c"];+const GOLD = "#e4a62c", UMBER = "#2e231c", FUZZ = "#b0782f", SILVER = "#cfd6db";++const rad = (d: number) => (d * Math.PI) / 180;+const polar = (deg: number, r = R): P => [C[0] + Math.cos(rad(deg)) * r, C[1] + Math.sin(rad(deg)) * r];+const unit = (x: number, y: number): P => { const l = Math.hypot(x, y) || 1; return [x / l, y / l]; };+const rot = (p: P, a: number): P => [p[0] * Math.cos(a) - p[1] * Math.sin(a), p[0] * Math.sin(a) + p[1] * Math.cos(a)];+const add = (a: P, b: P, k = 1): P => [a[0] + b[0] * k, a[1] + b[1] * k];+// the wreath line: a gentle wave on the circle. dir = +1 grows with increasing angle (left branch)+const wreathR = (deg: number) => R + 7 * Math.sin(rad(deg) * 3);+const onWreath = (deg: number): P => polar(deg, wreathR(deg));+const grow = (deg: number, dir: 1 | -1): P => { const a = onWreath(deg), b = onWreath(deg + dir * 1); return unit(b[0] - a[0], b[1] - a[1]); };+const outward = (deg: number): P => [Math.cos(rad(deg)), Math.sin(rad(deg))];++// ---------------------------------------------------------------- plants+type Section = { id: string; a: number; b: number; sts: St[] };+const LEFT = { from: 102, to: 262, dir: 1 as const }, RIGHT = { from: 78, to: -30, dir: -1 as const };+const branchPath = (b: typeof LEFT | typeof RIGHT): P[] => { const out: P[] = []; for (let d = b.from; b.dir > 0 ? d <= b.to : d >= b.to; d += b.dir * 2) out.push(onWreath(d)); return out; };+// the two stems cross at the bottom, where they were tied+const tails = (): P[][] => { const l = onWreath(LEFT.from), r = onWreath(RIGHT.from); return [[l, [l[0] + 26, l[1] + 22], [l[0] + 70, l[1] + 40], [l[0] + 112, l[1] + 50]], [r, [r[0] - 26, r[1] + 20], [r[0] - 72, r[1] + 42], [r[0] - 116, r[1] + 48]]]; };+const TIE: P = [540, 906]; // where the two stems cross: bound with a few wraps of gold++type Leaf = { mid: P[]; half: (t: number) => number; big: boolean; side: number; deg: number };+const LEAVES: [number, number, number, number][] = [ // [deg on the wreath, side (+1 out, -1 in), length, width ratio]: authored, largest near the base+ [108, 1, 70, 0.2], [114, -1, 80, 0.26], [131, -1, 64, 0.2], [140, 1, 56, 0.16], [157, -1, 82, 0.27], [163, 1, 44, 0.2], [173, -1, 60, 0.18], [180, 1, 42, 0.14], [197, -1, 58, 0.2],+ [206, 1, 52, 0.16], [221, 1, 50, 0.2], [226, -1, 48, 0.18], [238, -1, 42, 0.16], [244, 1, 36, 0.22], [253, 1, 34, 0.2], [258, -1, 30, 0.18], [262, 1, 24, 0.2],+ [120, 1, 34, 0.2], [148, -1, 36, 0.2], [186, -1, 34, 0.2], [213, 1, 30, 0.22], [232, 1, 28, 0.2], [249, -1, 26, 0.2],+ [60, 1, 36, 0.22], [49, 1, 32, 0.2], [26, 1, 34, 0.2], [8, -1, 30, 0.22], [-19, 1, 28, 0.2],+ [74, 1, 72, 0.2], [67, -1, 68, 0.24], [55, 1, 84, 0.27], [44, -1, 56, 0.18], [36, 1, 48, 0.16], [20, -1, 60, 0.2], [14, 1, 50, 0.18], [2, -1, 52, 0.2], [-2, 1, 38, 0.24], [-9, 1, 44, 0.16], [-15, -1, 40, 0.18], [-24, -1, 30, 0.2], [-28, 1, 26, 0.2],+];+const BIG = new Set([1, 4, 30]);+const leafOf = ([deg, side, len0, wr]: [number, number, number, number], i: number): Leaf => {+ const len = len0 * 1.12;+ const dir = deg > 90 || deg < -90 ? 1 : (deg >= 90 ? 1 : -1), g = grow(deg, deg >= 90 ? 1 : -1), o = outward(deg), sp = rad(38 + (i % 3) * 6), r = rng(900 + i);+ void dir;+ const d = unit(g[0] * Math.cos(sp) + o[0] * side * Math.sin(sp), g[1] * Math.cos(sp) + o[1] * side * Math.sin(sp)), perp: P = [-d[1], d[0]], bend = (r() - 0.5) * 0.5 + side * 0.12, base = onWreath(deg);+ const mid = resample(smooth([base, add(add(base, d, len * 0.5), perp, bend * len * 0.14), add(add(base, d, len), perp, bend * len * 0.3)], false, 8), 24);+ const W0 = len * wr, pw = 0.7 + (i % 4) * 0.08;+ return { mid, half: (t) => W0 * Math.pow(Math.sin(Math.PI * Math.pow(clamp(t), pw)), 0.85), big: BIG.has(i), side, deg };+};+const outlineOf = (l: Leaf): P[] => {+ const n = l.mid.length, L: P[] = [], Rr: P[] = [];+ l.mid.forEach((p, i) => { const q = l.mid[Math.min(n - 1, i + 1)], pr = l.mid[Math.max(0, i - 1)], u = unit(q[0] - pr[0], q[1] - pr[1]), h = l.half(i / (n - 1)); L.push([p[0] - u[1] * h, p[1] + u[0] * h]); Rr.push([p[0] + u[1] * h, p[1] - u[0] * h]); });+ return [...L, ...Rr.reverse()];+};+// which half of a leaf faces the window: that half gets the lighter green+const litSide = (l: Leaf): number => { const a = l.mid[0], b = l.mid[l.mid.length - 1], u = unit(b[0] - a[0], b[1] - a[1]); return -u[1] * LIGHT[0] + u[0] * LIGHT[1] > 0 ? -1 : 1; };++// POPPY: four petals seen three-quarter from above, the back pair larger, the front pair overlapping+const PC: P = add(polar(127, R + 8), [0, 0]);+const petal = (cDeg: number, half: number, rad0: number, seed: number) => {+ const arc: P[] = [], r = rng(seed), ph = r() * 6;+ for (let k = 0; k <= 18; k++) { const f = k / 18, a = rad(cDeg - half + f * 2 * half), rr = rad0 * (1 + 0.07 * Math.sin(a * 7 + ph) - 0.2 * Math.pow(Math.abs(f - 0.5) * 2, 2.4)); const v = rot([Math.cos(a) * rr, Math.sin(a) * rr * 0.8], rad(-12)); arc.push(add(PC, v)); }+ const inner = (a: number): P => add(PC, rot([Math.cos(rad(a)) * 11, Math.sin(rad(a)) * 9], rad(-12)));+ return { arc, outline: [inner(cDeg - half * 0.5), ...arc, inner(cDeg + half * 0.5)], target: (p: P): P => lerpP(PC, p, 0.2) };+};+const PETALS = [petal(-128, 62, 80, 1), petal(-42, 58, 76, 2), petal(150, 60, 70, 3), petal(48, 62, 72, 4)];++// DAISY: rays from an inner to an outer radius, satin across each ray, then a knotted disc.+// `T` maps the flower's own disc into the page, which is how the three-quarter view is authored.+const daisy = (T: (p: P) => P, n: number, r0: number, r1: number, seed: number, face = 1): St[] => {+ const out: St[] = [], r = rng(seed);+ for (let i = 0; i < n; i++) {+ const a = (i / n) * Math.PI * 2 + r() * 0.12, len = (r1 - r0) * (0.86 + r() * 0.2), dir: P = [Math.cos(a), Math.sin(a)], bend = (r() - 0.5) * 0.3;+ const axis = [0, 0.5, 1].map((f) => { const rr = r0 + len * f, b = bend * f * f * 8; return T([dir[0] * rr - dir[1] * b, dir[1] * rr + dir[0] * b]); });+ const pa = T([0, 0]), pb = T(dir), away = (pb[0] - pa[0]) * LIGHT[0] + (pb[1] - pa[1]) * LIGHT[1] < -0.15 * face;+ out.push(...satin(axis, (t) => 4.6 * Math.pow(Math.sin(Math.PI * clamp(t * 0.92 + 0.08)), 0.55) * (0.75 + 0.25 * face), 2.3, 2.2, (t) => (t < 0.12 ? SHELL : away && t < 0.7 ? SHELL : WHITE), { skew: 0.15 }));+ }+ return out;+};+const disc = (T: (p: P) => P, r: number, seed: number): St[] => knots(0, 0, r, r, 2.3, (u, v) => (u * 0.6 + v * 0.8 > 0.25 ? OCHRE : BUTTER), seed).map((k) => ({ ...k, a: T(k.a) }));+const faceOn = (c: P, k = 1, squash = 1, tilt = 0) => (p: P): P => add(c, rot([p[0] * k, p[1] * k * squash], rad(tilt)));++// FORGET-ME-NOTS: five round petals, a yellow eye, clustered on short stalks+const forgetMeNots = (deg: number, side: number, seed: number): { stems: St[]; petals: St[]; eyes: St[] } => {+ const r = rng(seed), base = onWreath(deg), o = outward(deg), g = grow(deg, deg > 90 || deg < -90 ? 1 : deg >= 90 ? 1 : -1), c0 = add(add(base, o, side * 38), g, 12), stems: St[] = [], petals: St[] = [], eyes: St[] = [];+ const spots: P[] = [];+ for (let k = 0; k < 7; k++) { let p: P = c0; for (let tries = 0; tries < 12; tries++) { p = [c0[0] + (r() - 0.5) * 60, c0[1] + (r() - 0.5) * 52]; if (spots.every((q) => Math.hypot(q[0] - p[0], q[1] - p[1]) > 19)) break; } spots.push(p); }+ spots.forEach((p, k) => {+ stems.push(...stemStitch([base, lerpP(base, p, 0.55), p], 7, 1.6, G.stem, seed + k));+ if (k >= 5) { petals.push(knot(p, 2.4, k === 5 ? "#e7a3b8" : BLUE2)); return; } // buds: pink before they open, as the real plant does+ const tw = r() * 1.2, sq = 0.7 + r() * 0.3;+ for (let q = 0; q < 5; q++) { const a = tw + (q / 5) * Math.PI * 2, d = rot([1, 0], a), pp = (f: number): P => add(p, [d[0] * f, d[1] * f * sq]); const lit = d[0] * LIGHT[0] + d[1] * LIGHT[1] > 0; petals.push(...satin([pp(1.8), pp(5.4), pp(9)], (t) => 3.9 * Math.sin(Math.PI * clamp(t * 0.85 + 0.12)), 1.9, 1.9, () => (lit ? BLUE2 : BLUE))); }+ eyes.push(knot(p, 2, BUTTER));+ });+ return { stems, petals, eyes };+};+// LAVENDER: a bare stem, then a spike of knots in whorls, tighter to the tip+const lavender = (deg: number, seed: number): { stem: St[]; spike: St[] } => {+ const r = rng(seed), base = onWreath(deg), o = outward(deg), g = grow(deg, deg >= 90 ? 1 : -1), d = unit(o[0] * 0.8 + g[0] * 0.6, o[1] * 0.8 + g[1] * 0.6), n: P = [-d[1], d[0]], len = 96 + r() * 16, bend = (r() - 0.5) * 0.3;+ const path = [base, add(add(base, d, len * 0.5), n, bend * 10), add(add(base, d, len), n, bend * 22)], spine = resample(smooth(path, false, 6), 40);+ const spike: St[] = [];+ for (let k = 0; k < 13; k++) { const f = 0.42 + (k / 12) * 0.58, p = spine[Math.min(39, Math.round(f * 39))], s = k % 2 ? 1 : -1, wd = 6.5 * (1 - (k / 12) * 0.5); spike.push(knot(add(p, n, s * wd), 2.8, k % 3 === 0 ? LAV2 : LAV)); if (k % 2 === 0 && k < 11) spike.push(knot(add(p, n, -s * wd * 0.3), 2.5, LAV2)); }+ const leaves = [straight(spine[8], add(spine[8], rot(d, 0.6), 18), 1.8, G.grey), straight(spine[12], add(spine[12], rot(d, -0.55), 16), 1.8, G.grey)];+ return { stem: [...stemStitch(spine, 7, 1.8, G.grey, seed), ...leaves], spike };+};++// ---------------------------------------------------------------- the bee+const BEE: P = [650, 300], HEAD = rad(33), BS = 1.42;+const B = (x: number, y: number): P => add(BEE, rot([x * BS, y * BS], HEAD));+const bee = () => {+ const abdomen: St[] = [], thorax: St[] = [], head: St[] = [], legs: St[] = [], wings: St[] = [], r = rng(77);+ // abdomen: six bands, satin across the body, the band edges bowing toward the tail with the roundness+ const x0 = 1, x1 = -66, hw = (u: number) => 21 * Math.pow(Math.sin(Math.PI * clamp(0.1 + u * 0.88)), 0.6) * (1 - 0.25 * u);+ const band = (u: number) => [0.14, 0.26, 0.41, 0.54, 0.68, 0.8].filter((e) => u > e).length % 2 === 0 ? GOLD : UMBER;+ for (let x = x0; x >= x1; x -= 2.3 / BS) { const u = (x0 - x) / (x0 - x1), h = hw(u); if (h < 1) continue; for (const s of [-1, 1]) { const ym = (s * h) / 2, bow = 0.05 * (ym / 21) ** 2; abdomen.push({ k: "flat", a: B(x + (s < 0 ? 0.3 : -0.3), 0), b: B(x - s * 0.8, s * h), w: 2.3, c: band(u - bow * 4 + (s > 0 ? 0.006 : 0)), t: 1 }); } }+ // thorax: fur, short stitches radiating from a darker centre+ thorax.push(...satin([B(4, 0), B(18, 0), B(32, 0)], (t) => 14 * BS * Math.pow(Math.sin(Math.PI * clamp(t * 0.9 + 0.05)), 0.55), 2.2, 2.2, (t) => (t > 0.25 && t < 0.75 ? "#4a3119" : "#7a5226"))); // the thorax laid in first, dark, so the fur has a body under it+ for (let k = 0; k < 120; k++) { const a = r() * Math.PI * 2, d0 = 5 + r() * 7, d1 = 14 + r() * 7, c = d0 < 6 ? "#5e3d1c" : r() < 0.5 ? FUZZ : "#d19a3e"; thorax.push({ k: "flat", a: B(18 + Math.cos(a) * d0, Math.sin(a) * d0 * 0.95), b: B(18 + Math.cos(a) * d1, Math.sin(a) * d1 * 0.95), w: 1.8, c, t: 0.7 }); }+ // head: satin, then the compound eyes, then a glint in each+ head.push(...satin([B(34, 0), B(42, 0), B(50, 0), B(55, 0)], (t) => 11.5 * BS * Math.pow(Math.sin(Math.PI * clamp(t * 0.94 + 0.03)), 0.5) * (1 - 0.35 * t), 2.2, 2.2, () => "#3b2b1f")); // broad at the eyes, narrowing to the jaws+ for (const s of [-1, 1]) { head.push(...satin([B(38, s * 9), B(44, s * 10.5), B(50, s * 9)], (t) => 4.4 * BS * Math.sin(Math.PI * clamp(t * 0.8 + 0.1)), 1.9, 1.9, () => "#15110e")); head.push(straight(B(41, s * 9.5 - 1.5), B(44, s * 9.5 - 2), 1.2, "#f4f1ea")); }+ // antennae: elbowed, scape then flagellum+ for (const s of [-1, 1]) head.push(...stemStitch([B(52, s * 3.5), B(56, s * 8), B(58, s * 10.5), B(64, s * 13.5), B(70, s * 16)], 6, 1.5, UMBER, 80 + s));+ // legs: three pairs, femur-tibia-tarsus, the hind pair longest with its pollen load+ const LEG: [number, number, number][] = [[28, 0.9, 0.8], [20, 1.35, 1], [12, 1.9, 1.3]];+ LEG.forEach(([x, sweep, k], j) => { for (const s of [-1, 1]) { const p0 = B(x, s * 12), p1 = B(x - 6 * sweep, s * (17 * k)), p2 = B(x - 12 * sweep - 5, s * (18.5 * k)), p3 = B(x - 17 * sweep - 7, s * (18 * k)); legs.push(straight(p0, p1, 2, UMBER), straight(p1, p2, 1.7, UMBER), straight(p2, p3, 1.3, UMBER)); if (j === 2) legs.push(knot(lerpP(p1, p2, 0.5), 3.2, "#e9892c"), knot(lerpP(p1, p2, 0.2), 2.6, "#f0a83a")); } });+ // wings: forewing larger, overlapping the hindwing's leading edge; split-stitch edges, a few veins, sparse fill so the body shows through+ const wing = (s: number, len: number, wd: number, back: number, rootX: number) => {+ const root = B(rootX, s * 9), tipDir = rot([-Math.cos(rad(back)), s * Math.sin(rad(back))], HEAD), nrm: P = [-tipDir[1] * s, tipDir[0] * s];+ const pt = (f: number, g: number): P => add(add(root, tipDir, len * f), nrm, wd * g);+ const edge = smooth([pt(0, 0), pt(0.3, 0.55), pt(0.7, 0.62), pt(0.98, 0.25), pt(0.95, -0.15), pt(0.6, -0.32), pt(0.25, -0.22), pt(0, 0)], false, 6);+ wings.push(...splitStitch(edge, 6, 1.5, "#a9b3ba"));+ wings.push(straight(pt(0.05, 0.05), pt(0.7, 0.3), 1.2, SILVER), straight(pt(0.1, 0), pt(0.85, 0.02), 1.2, SILVER), straight(pt(0.3, 0.15), pt(0.55, -0.2), 1.1, SILVER));+ for (let k = 0; k < 7; k++) { const f = 0.2 + k * 0.1, g0 = -0.25 + (k % 2) * 0.1; wings.push(straight(pt(f, g0), pt(f + 0.12, 0.5 - (k % 3) * 0.08), 1.1, k % 2 ? "#eef1f2" : SILVER)); }+ };+ for (const s of [-1, 1]) { wing(s, 58, 26, 64, 12); wing(s, 82, 34, 40, 16); }+ return { abdomen, thorax, head, legs, wings };+};+const FLIGHT: P[] = [[262, 300], [290, 226], [352, 186], [398, 222], [372, 262], [334, 232], [366, 176], [436, 146], [500, 160], [542, 196], [566, 226]];++// ---------------------------------------------------------------- the timeline: one cue table+const build = (): Section[] => {+ const leaves = LEAVES.map(leafOf), bigLeaves = leaves.filter((l) => l.big), small = leaves.filter((l) => !l.big);+ const fmn = [forgetMeNots(150, 1, 11), forgetMeNots(213, -1, 12), forgetMeNots(47, 1, 13), forgetMeNots(-3, -1, 14)];+ const lav = [lavender(167, 21), lavender(233, 22), lavender(63, 23), lavender(8, 24)];+ const D1 = faceOn(polar(189, R + 20), 1.22), D2 = faceOn(polar(27, R + 16), 1.18, 0.52, -24), D3 = faceOn(polar(-21, R + 8), 0.92, 0.92, 8);+ const budC = polar(247, R + 10), budD = unit(outward(247)[0] * 0.55 + grow(247, 1)[0] * 0.85, outward(247)[1] * 0.55 + grow(247, 1)[1] * 0.85), budN: P = [-budD[1], budD[0]];+ const flowerStem = (deg: number, to: P, seed: number) => stemStitch([onWreath(deg), lerpP(onWreath(deg), to, 0.5), to], 8, 2.2, G.stem, seed);+ const b = bee(), dir = (l: Leaf) => litSide(l);+ const bud: St[] = [+ ...satin([add(budC, budD, -6), add(budC, budD, 2), add(budC, budD, 9)], (t) => 8 * Math.sin(Math.PI * clamp(t * 0.8 + 0.15)), 2.2, 2.2, (t, s) => (s < 0 ? G.light : G.olive)),+ ...[-0.5, -0.2, 0.1, 0.4].map((f, k) => satin([add(add(budC, budD, 8), budN, f * 14), add(add(budC, budD, 14 + (k % 2) * 3), budN, f * 16)], (t) => 2.4 * Math.sin(Math.PI * clamp(t * 0.8 + 0.1)), 1.9, 1.9, () => (k < 2 ? WHITE : SHELL))).flat(),+ ];+ const secs: Section[] = [+ // OUTLINES+ { id: "stems", a: 5, b: 70, sts: [...stemStitch(branchPath(LEFT), 10, 2.8, G.stem, 1), ...stemStitch(branchPath(LEFT).map((p, i, a) => { const q = a[Math.min(a.length - 1, i + 1)], o = a[Math.max(0, i - 1)], u = unit(q[0] - o[0], q[1] - o[1]); return [p[0] + u[1] * 2.6, p[1] - u[0] * 2.6] as P; }), 10, 2.4, G.olive, 5),+ ...stemStitch(branchPath(RIGHT), 10, 2.8, G.stem, 2), ...stemStitch(branchPath(RIGHT).map((p, i, a) => { const q = a[Math.min(a.length - 1, i + 1)], o = a[Math.max(0, i - 1)], u = unit(q[0] - o[0], q[1] - o[1]); return [p[0] - u[1] * 2.6, p[1] + u[0] * 2.6] as P; }), 10, 2.4, G.olive, 6), ...tails().flatMap((t, i) => stemStitch(smooth(t, false, 6), 9, 2.8, G.stem, 3 + i)), ...[-6, -3, 0, 3, 6].map((d) => straight(add(TIE, [d - 2, -9]), add(TIE, [d + 2, 9]), 2.2, GOLD))] },+ { id: "stalks", a: 70, b: 100, sts: [...flowerStem(186, D1([0, 0]), 30), ...flowerStem(30, D2([0, 0]), 31), ...flowerStem(-16, D3([0, 0]), 32), ...flowerStem(242, budC, 33), ...flowerStem(122, PC, 34), ...lav.flatMap((l) => l.stem), ...fmn.flatMap((f) => f.stems)] },+ { id: "edges", a: 100, b: 150, sts: [...bigLeaves.flatMap((l) => splitStitch(outlineOf(l), 5.5, 2, G.dark, true)), ...PETALS.flatMap((p) => splitStitch(p.arc, 5, 2, POPPY[3]))] },+ // FILLS+ { id: "leaves", a: 150, b: 235, sts: small.flatMap((l) => fishbone(l.mid, (t) => l.half(t) * 0.92, 2.3, 2.2, (s) => (s === dir(l) ? G.sage : G.olive))) },+ { id: "shaded", a: 235, b: 265, sts: bigLeaves.flatMap((l, i) => { const out = outlineOf(l), n = out.length, half = Math.floor(n / 2); return [out.slice(0, half), out.slice(half)].flatMap((edge, s) => longShort(edge, (p) => { let best = l.mid[0], bd = 1e9; for (const q of l.mid) { const d = Math.hypot(q[0] - p[0], q[1] - p[1]); if (d < bd) { bd = d; best = q; } } return lerpP(p, best, 1); }, 3, 2.4, 2.1, (s === 0) === (dir(l) < 0) ? [G.light, G.sage, G.olive] : [G.sage, G.olive, G.dark], 200 + i * 2 + s)); }) },+ { id: "poppy", a: 265, b: 300, sts: PETALS.flatMap((p, i) => longShort(p.arc, p.target, 4, 2.3, 2.2, POPPY, 300 + i)) },+ { id: "daisies", a: 300, b: 335, sts: [...daisy(D1, 19, 11, 48, 40), ...daisy(D2, 17, 11, 46, 41, 0.6), ...daisy(D3, 15, 9, 38, 42), ...bud] },+ { id: "forgetmenots", a: 335, b: 355, sts: fmn.flatMap((f) => f.petals) },+ // KNOTS+ { id: "knots", a: 355, b: 400, sts: [...disc(D1, 11, 50), ...disc(D2, 11, 51), ...disc(D3, 9, 52), ...fmn.flatMap((f) => f.eyes), ...lav.flatMap((l) => l.spike),+ ...satin([add(PC, [-9, 0]), PC, add(PC, [9, 0])], (t) => 8 * Math.sin(Math.PI * clamp(t * 0.85 + 0.08)), 2.1, 2, () => "#7d8f4b"),+ ...Array.from({ length: 8 }, (_, k) => straight(PC, add(PC, rot([7, 0], (k / 8) * Math.PI * 2)), 1.3, "#2d2723")),+ ...Array.from({ length: 16 }, (_, k) => knot(add(PC, rot([15 + (k % 2) * 3, 0], (k / 16) * Math.PI * 2 + 0.2)), 2.2, "#221d1a"))] },+ // THE BEE+ { id: "flight", a: 400, b: 420, sts: runningStitch(smooth(FLIGHT, false, 8), 7, 5, 1.6, GOLD) },+ { id: "abdomen", a: 420, b: 450, sts: b.abdomen },+ { id: "thorax", a: 450, b: 465, sts: b.thorax },+ { id: "head", a: 465, b: 475, sts: b.head },+ { id: "legs", a: 475, b: 490, sts: b.legs },+ { id: "wings", a: 490, b: 505, sts: b.wings },+ ];+ for (const s of secs) if (s.a % 5 || s.b % 5) throw new Error(`embroidery: cue ${s.id} off the grid`);+ return secs;+};+// the hand's pace: a stitch takes a moment plus a little per millimetre; a knot takes three wraps+type Timed = St & { f0: number; f1: number };+const timeline = (secs: Section[]): Timed[] => secs.flatMap((s) => {+ const wts = s.sts.map((st) => (st.k === "knot" ? 2.4 : 0.55 + Math.hypot(st.b[0] - st.a[0], st.b[1] - st.a[1]) / 16)), T = wts.reduce((a, b) => a + b, 0), span = (s.b - s.a) * 0.94;+ let acc = 0; return s.sts.map((st, i) => { const f0 = s.a + (acc / T) * span; acc += wts[i]; return { ...st, f0, f1: s.a + (acc / T) * span }; });+});+((): void => { let t = 5; for (const s of build()) { if (s.a !== t || s.b <= s.a) throw new Error(`embroidery: section ${s.id} ${s.a}-${s.b} does not follow ${t}`); t = s.b; } if (t !== 505 || N % 15 || N - HOLD !== 510) throw new Error("embroidery: timeline does not end at 505 before the park and hold"); })();++// ---------------------------------------------------------------- the sheet in the hoop+const cached = <T,>(env: Env, key: string, fn: () => T): T => { let v = env.cache.get(key) as T | undefined; if (v === undefined) { v = fn(); env.cache.set(key, v); } return v; };+const DWH = (env: Env): [number, number] => [Math.round(env.W * env.scale), Math.round(env.H * env.scale)];+const STRIDE = 180; // stitches per cached checkpoint+const drawRun = (L: Layer, env: Env, sts: St[], lastP = 1) => {+ if (!sts.length) return;+ const g = new Gfx(L.ctx, env, 0, EMB_M); let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const s of sts) { x0 = Math.min(x0, s.a[0], s.b[0]); y0 = Math.min(y0, s.a[1], s.b[1]); x1 = Math.max(x1, s.a[0], s.b[0]); y1 = Math.max(y1, s.a[1], s.b[1]); }+ g.group("plain", () => { g.touch(x0 - 8, y0 - 8, x1 + 10, y1 + 10); drawShadows(g.cur, sts, lastP); }, { blur: 0.9 });+ g.group("plain", () => { g.touch(x0 - 6, y0 - 6, x1 + 6, y1 + 6); drawThreads(g.cur, sts, lastP); });+};+const checkpoint = (env: Env, all: Timed[], k: number): Layer | null => {+ if (k <= 0) return null;+ const key = `emb:ck:${k}:${env.scale}:${env.W}x${env.H}`, hit = env.cache.get(key) as Layer | undefined; if (hit) return hit;+ const prev = checkpoint(env, all, k - 1), [dw, dh] = DWH(env), L = env.canvas(dw, dh); L.ctx.setTransform(1, 0, 0, 1, 0, 0);+ if (prev) { L.ctx.globalCompositeOperation = "copy"; L.ctx.drawImage(prev.canvas as CanvasImageSource, 0, 0); L.ctx.globalCompositeOperation = "source-over"; }+ drawRun(L, env, all.slice((k - 1) * STRIDE, k * STRIDE));+ env.cache.set(key, L); env.cache.delete(`emb:ck:${k - 3}:${env.scale}:${env.W}x${env.H}`);+ return L;+};++const ground = (env: Env): Layer => linenLayer(env, "hoop", 4.2, [224, 211, 186], (x, y) => {+ const d = Math.hypot(x - HC[0], y - HC[1]);+ if (d < RI) return 1.03 - 0.05 * (d / RI) ** 2; // drum-tight inside the hoop+ const fold = Math.sin((x * 0.8 + y * 0.35) * 0.012 + Math.sin(y * 0.01) * 1.6); // slack cloth outside it, in soft folds+ return 0.84 + 0.07 * fold;+});+const hoop = (env: Env): Layer => cached(env, `emb:hoop:${env.scale}:${env.W}x${env.H}`, () => {+ const [dw, dh] = DWH(env), L = env.canvas(dw, dh), c = L.ctx, s = env.scale; c.setTransform(s, 0, 0, s, 0, 0);+ const ring = (dx: number, dy: number, r0: number, r1: number) => { c.beginPath(); c.arc(HC[0] + dx, HC[1] + dy, r1, 0, Math.PI * 2); c.arc(HC[0] + dx, HC[1] + dy, r0, 0, Math.PI * 2, true); };+ // the ring's shadow: inside at upper left, outside at lower right; soft by stacking offset copies+ for (let k = 0; k < 6; k++) { c.globalAlpha = 0.07; c.fillStyle = "#2b1d10"; ring(5 + k * 1.6, 7 + k * 2.2, RI - k * 0.8, RO + k * 0.8); c.fill("evenodd"); }+ c.globalAlpha = 1;+ const gr = c.createLinearGradient(HC[0] - RO, HC[1] - RO, HC[0] + RO, HC[1] + RO); gr.addColorStop(0, "#e2b67c"); gr.addColorStop(0.5, "#c89960"); gr.addColorStop(1, "#a97a45");+ c.fillStyle = gr; ring(0, 0, RI, RO); c.fill("evenodd");+ const r = rng(515); c.lineCap = "round"; // beech grain: long broken arcs following the steamed bend+ for (let k = 0; k < 30; k++) { const rr = RI + 2 + r() * (RO - RI - 4), a0 = r() * Math.PI * 2, a1 = a0 + 0.3 + r() * 1.3; c.strokeStyle = r() < 0.5 ? "#96683a" : "#b5854f"; c.globalAlpha = 0.35 + r() * 0.3; c.lineWidth = 0.6 + r() * 0.9; c.beginPath(); c.arc(HC[0], HC[1], rr, a0, a1); c.stroke(); }+ c.globalAlpha = 0.55; c.strokeStyle = "#f6dcae"; c.lineWidth = 2.2; c.beginPath(); c.arc(HC[0], HC[1], RO - 1.5, rad(160), rad(290)); c.stroke(); // the rounded outer edge catching the window+ c.globalAlpha = 0.5; c.strokeStyle = "#7c5530"; c.lineWidth = 1.6; c.beginPath(); c.arc(HC[0], HC[1], RI + 1, 0, Math.PI * 2); c.stroke(); // where the cloth tucks under+ // the clamp: two end-grain lugs and a brass screw with its thumb nut+ const top = HC[1] - RO;+ c.globalAlpha = 0.28; c.fillStyle = "#2b1d10"; c.fillRect(519, top - 36, 52, 52); c.fillRect(520, top - 12, 98, 22); c.globalAlpha = 1;+ for (const x of [512, 546]) { const lg = c.createLinearGradient(x, 0, x + 22, 0); lg.addColorStop(0, "#d9a96b"); lg.addColorStop(1, "#a47440"); c.fillStyle = lg; c.beginPath(); c.roundRect(x, top - 40, 22, 52, 4); c.fill(); c.strokeStyle = "#8a5e33"; c.globalAlpha = 0.5; c.lineWidth = 1; c.strokeRect(x + 3, top - 36, 16, 44); c.globalAlpha = 1; }+ const sg = c.createLinearGradient(0, top - 26, 0, top - 12); sg.addColorStop(0, "#f3dc8e"); sg.addColorStop(0.45, "#c9a043"); sg.addColorStop(1, "#7d5f1f"); c.fillStyle = sg; c.fillRect(500, top - 25, 96, 12);+ c.strokeStyle = "#6e531b"; c.globalAlpha = 0.6; c.lineWidth = 0.8; for (let x = 572; x < 596; x += 3) { c.beginPath(); c.moveTo(x, top - 25); c.lineTo(x + 2, top - 13); c.stroke(); } c.globalAlpha = 1;+ const ng = c.createLinearGradient(596, 0, 614, 0); ng.addColorStop(0, "#f0d27f"); ng.addColorStop(1, "#8a6a24"); c.fillStyle = ng; c.beginPath(); c.roundRect(596, top - 36, 16, 34, 5); c.fill();+ c.strokeStyle = "#6e531b"; c.globalAlpha = 0.5; for (let y = top - 32; y < top - 4; y += 3) { c.beginPath(); c.moveTo(598, y); c.lineTo(610, y); c.stroke(); } c.globalAlpha = 1;+ c.fillStyle = "#c9a043"; c.beginPath(); c.arc(498, top - 19, 6, 0, Math.PI * 2); c.fill();+ return L;+});++// the needle, and the working thread from its eye+const needle = (c: Ctx, tip: P, dir: P, colour: string, parked: boolean) => {+ const len = 52, back = add(tip, dir, -len), n: P = [-dir[1], dir[0]], tail = add(back, dir, -4);+ c.save(); c.lineCap = "round";+ const thread = parked ? [tail, add(tail, [-40, 30]), add(tail, [-10, 76]), add(tail, [-62, 96])] : [tail, add(add(tail, dir, -30), n, 18), add(add(tail, dir, -58), n, 8), add(add(tail, dir, -84), n, 30)];+ const th = smooth(thread, false, 10);+ c.globalAlpha = 0.3; c.strokeStyle = "#3b2c1c"; c.lineWidth = 2.4; c.beginPath(); th.forEach(([x, y], i) => (i ? c.lineTo(x + 2, y + 3) : c.moveTo(x + 2, y + 3))); c.stroke();+ c.globalAlpha = 1; c.strokeStyle = colour; c.lineWidth = 2; c.beginPath(); th.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke();+ const seg = (a: P, b: P) => { c.globalAlpha = 0.35; c.strokeStyle = "#2b1d10"; c.lineWidth = 3; c.beginPath(); c.moveTo(a[0] + 2, a[1] + 3); c.lineTo(b[0] + 2, b[1] + 3); c.stroke(); c.globalAlpha = 1; c.strokeStyle = "#8d949a"; c.lineWidth = 2.6; c.beginPath(); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); c.stroke(); c.strokeStyle = "#f5f7f8"; c.lineWidth = 0.9; c.beginPath(); c.moveTo(a[0] + n[0] * 0.6, a[1] + n[1] * 0.6); c.lineTo(b[0] + n[0] * 0.6, b[1] + n[1] * 0.6); c.stroke(); };+ if (parked) { seg(back, add(back, dir, 17)); seg(add(back, dir, 35), tip); } // woven into the cloth: under three threads in the middle+ else seg(back, tip);+ c.globalAlpha = 1; c.fillStyle = "#3b3f42"; c.beginPath(); c.ellipse(back[0] + dir[0] * 4, back[1] + dir[1] * 4, 2.6, 0.7, Math.atan2(dir[1], dir[0]), 0, Math.PI * 2); c.fill(); // the eye+ c.restore();+};+const PARK: [P, P] = [[642, 742], [0.84, -0.54]];++export const drawEmbroidery = (ctx: Ctx, f: number, env: Env) => {+ const all = cached(env, "emb:timeline", () => timeline(build()));+ const [dw, dh] = DWH(env);+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";+ ctx.drawImage(ground(env).canvas as CanvasImageSource, 0, 0);+ // how far the hand has got: every stitch started by now, the newest one part-pulled+ let n = 0; while (n < all.length && all[n].f0 <= f) n++;+ const last = n ? all[n - 1] : null, p = last ? clamp((f - last.f0) / Math.max(0.01, last.f1 - last.f0)) : 1;+ const k = Math.floor(Math.max(0, n - 1) / STRIDE), base = checkpoint(env, all, k);+ const wkey = `emb:work:${env.scale}:${env.W}x${env.H}`, work = cached(env, wkey, () => env.canvas(dw, dh));+ work.ctx.setTransform(1, 0, 0, 1, 0, 0); if (base) { work.ctx.globalCompositeOperation = "copy"; work.ctx.drawImage(base.canvas as CanvasImageSource, 0, 0); work.ctx.globalCompositeOperation = "source-over"; } else work.ctx.clearRect(0, 0, dw, dh);+ drawRun(work, env, all.slice(k * STRIDE, n), p);+ ctx.drawImage(work.canvas as CanvasImageSource, 0, 0);+ ctx.drawImage(hoop(env).canvas as CanvasImageSource, 0, 0);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ if (f >= 505) { // the last stitch is in: the needle goes into the cloth to wait, the thread left trailing+ const t = clamp((f - 505) / 5), from = last ? headOf(last, 1) : PARK[0], tip = lerpP(from, PARK[0], t * t * (3 - 2 * t));+ needle(ctx, tip, t >= 1 ? PARK[1] : [lerp(0.7, PARK[1][0], t), lerp(0.7, PARK[1][1], t)], GOLD, t >= 1);+ } else if (last) { const a = last.a, h = headOf(last, p), dir = last.k === "knot" ? ([0.7, 0.7] as P) : (() => { const d = Math.hypot(last.b[0] - a[0], last.b[1] - a[1]) || 1; return [(last.b[0] - a[0]) / d, (last.b[1] - a[1]) / d] as P; })(); needle(ctx, add(h, dir, last.k === "knot" ? 4 : 10), dir, last.c, false); }+ void mix; void polyLen;+};++export const embroidery: Film = {+ meta: { title: "A wreath and a bee · hand embroidery", W, H, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "stitching", start: 0, end: N, draw: drawEmbroidery }],+};++export const STYLE = { id: "embroidery", name: "Hand embroidery", family: "textile", medium: "stranded cotton floss stitched through natural plain-weave linen in a beech hoop", nearest: "fox", hero: "a botanical wreath with a honeybee" };diff --git a/engine/src/canvas-core/embroideryKit.ts b/engine/src/canvas-core/embroideryKit.tsnew file mode 100644index 0000000..46c4a5c--- /dev/null+++ b/engine/src/canvas-core/embroideryKit.ts@@ -0,0 +1,159 @@+// EMBROIDERY KIT. Thread on linen, as geometry. A stitch is a length of twisted floss laid from the+// hole where the needle came up to the hole where it went down: it pinches into both holes, it is+// rounded in section so it has a lit side and a shade side, its strands twist so the sheen breaks+// into short slanted glints, and it stands a hair proud of the cloth so it casts a tiny shadow.+// A French knot is thread wrapped round the needle and pulled down: a bead with wraps showing.+//+// Kit primitives written here (candidates for core): linenLayer (a per-pixel plain weave with+// slubs, over/under crossings and pin-hole gaps), drawStitches (shadow pass + thread pass for a+// run of stitches), and the stitch generators: stemStitch, splitStitch, runningStitch, satin+// (across an axis), fishbone (a leaf, from the edge to the midrib), longShort (rows shading one+// thread colour into another), knots (a packed French-knot fill).+import type { Env, Layer, P } from "./core";+import { clamp, lerp, lerpP, mix, polyLen, resample } from "./gallery";+import { rng } from "./core";++export const LIGHT: P = [-0.6, -0.8]; // toward the window, upper left+export type St = { k: "flat" | "knot"; a: P; b: P; w: number; c: string; t: number }; // knot: a = centre, w = radius++// ---------------------------------------------------------------- linen+// Plain weave: warp and weft alternate over/under at every crossing. Each thread is a rounded+// cord (bright on its crown, dark at its flanks), rising where it passes over and dipping where it+// goes under; thread thickness wanders (slubs) and every so often a thread is a shade darker.+// Between the cords, the pin-holes of the weave. Computed per device pixel once, cached by scale.+export const linenLayer = (env: Env, key: string, pitch: number, base: [number, number, number], inside: (x: number, y: number) => number): Layer => {+ const k = `emb:linen:${key}:${env.scale}:${env.W}x${env.H}:${pitch}`, hit = env.cache.get(k) as Layer | undefined; if (hit) return hit;+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), L = env.canvas(DW, DH), img = L.ctx.createImageData(DW, DH), d = img.data;+ const nT = Math.ceil(Math.max(env.W, env.H) / pitch) + 2, r = rng(4411), thick = Array.from({ length: nT * 2 }, () => 0.8 + r() * 0.22), tint = Array.from({ length: nT * 2 }, () => (r() < 0.08 ? 0.95 : 1) * (0.975 + r() * 0.05));+ const SEG = 9, slub = Array.from({ length: nT * 2 }, () => Array.from({ length: Math.ceil(Math.max(env.W, env.H) / SEG) + 2 }, () => (r() < 0.04 ? 0.28 : 0) + (r() - 0.5) * 0.12));+ const sl = (th: number, along: number) => { const s = along / SEG, i = Math.floor(s), f = s - i, row = slub[th]; return row[i] + (row[i + 1] - row[i]) * f; };+ for (let j = 0; j < DH; j++) {+ const y = j / env.scale, v = y / pitch, iv = Math.floor(v), fv = v - iv;+ for (let i = 0; i < DW; i++) {+ const x = i / env.scale, u = x / pitch, iu = Math.floor(u), fu = u - iu;+ const warpHW = 0.5 * clamp(thick[iu] + sl(iu, y), 0.5, 1.15) * 0.94, weftHW = 0.5 * clamp(thick[nT + iv] + sl(nT + iv, x), 0.5, 1.15) * 0.9;+ const dw = Math.abs(fu - 0.5), df = Math.abs(fv - 0.5), inWarp = dw < warpHW, inWeft = df < weftHW, warpTop = ((iu + iv) & 1) === 0;+ let b: number, t: number;+ if (inWarp && (warpTop || !inWeft)) { const cr = Math.cos((dw / warpHW) * Math.PI * 0.5), rise = warpTop ? 0.82 + 0.18 * Math.sin(Math.PI * fv) : 0.74; b = (0.62 + 0.42 * Math.pow(cr, 0.7)) * rise + 0.06 * ((fv * 7 + iu * 0.37) % 1); t = tint[iu]; }+ else if (inWeft) { const cr = Math.cos((df / weftHW) * Math.PI * 0.5), rise = !warpTop ? 0.84 + 0.16 * Math.sin(Math.PI * fu) : 0.74; b = (0.6 + 0.42 * Math.pow(cr, 0.7)) * rise + 0.05 * ((fu * 6 + iv * 0.53) % 1); t = tint[nT + iv]; }+ else { b = 0.5; t = 1; } // a pin-hole: the dark behind the cloth+ const m = inside(x, y) * b * t, o = (j * DW + i) * 4;+ d[o] = clamp(base[0] * m, 0, 255); d[o + 1] = clamp(base[1] * m, 0, 255); d[o + 2] = clamp(base[2] * m, 0, 255); d[o + 3] = 255;+ }+ }+ L.ctx.putImageData(img, 0, 0); env.cache.set(k, L);+ return L;+};++// ---------------------------------------------------------------- drawing a run of stitches+type Tone = { base: string; hi: string; lo: string };+const tone = (c: string): Tone => ({ base: c, hi: mix(c, "#ffffff", 0.5), lo: mix(c, "#1a120c", 0.38) }); // a colour's lit and shade threads+export const headOf = (s: St, p: number): P => (s.k === "knot" ? s.a : p >= 1 ? s.b : lerpP(s.a, s.b, p));+// the shadow each stitch casts on the cloth: down and right, away from the window+export const drawShadows = (c: CanvasRenderingContext2D, sts: St[], lastP = 1) => {+ c.save(); c.lineCap = "round"; c.strokeStyle = "#3b2c1c"; c.fillStyle = "#3b2c1c";+ sts.forEach((s, i) => {+ const p = i === sts.length - 1 ? lastP : 1; if (p <= 0) return;+ if (s.k === "knot") { if (p < 0.5) return; c.globalAlpha = 0.42; c.beginPath(); c.arc(s.a[0] + s.w * 0.4, s.a[1] + s.w * 0.55, s.w * 1.05, 0, Math.PI * 2); c.fill(); return; }+ const b = headOf(s, p); c.globalAlpha = 0.34; c.lineWidth = s.w * 1.1; c.beginPath(); c.moveTo(s.a[0] + 0.9, s.a[1] + 1.3); c.lineTo(b[0] + 0.9, b[1] + 1.3); c.stroke();+ });+ c.restore();+};+export const drawThreads = (c: CanvasRenderingContext2D, sts: St[], lastP = 1) => {+ c.save(); c.lineCap = "round"; c.lineJoin = "round";+ sts.forEach((s, i) => {+ const p = i === sts.length - 1 ? lastP : 1; if (p <= 0) return;+ const T = tone(s.c);+ if (s.k === "knot") { // a French knot: the bead, its shaded side, the wraps, one glint+ if (p < 0.5) { c.globalAlpha = 1; c.strokeStyle = T.base; c.lineWidth = s.w * 0.7; c.beginPath(); c.arc(s.a[0], s.a[1], s.w * 0.55, 0, Math.PI * 2 * (p * 2)); c.stroke(); return; } // the wraps going round the needle+ const [x, y] = s.a, r = s.w;+ c.globalAlpha = 1; c.fillStyle = T.lo; c.beginPath(); c.arc(x + r * 0.12, y + r * 0.16, r, 0, Math.PI * 2); c.fill();+ c.fillStyle = T.base; c.beginPath(); c.arc(x - r * 0.1, y - r * 0.12, r * 0.8, 0, Math.PI * 2); c.fill();+ c.strokeStyle = T.lo; c.globalAlpha = 0.55; c.lineWidth = Math.max(0.5, r * 0.22); const ph = (x * 0.37 + y * 0.61) % Math.PI;+ c.beginPath(); c.arc(x, y, r * 0.5, ph, ph + 2.2); c.stroke(); c.beginPath(); c.arc(x, y, r * 0.78, ph + 3, ph + 4.8); c.stroke();+ c.fillStyle = T.hi; c.globalAlpha = 0.8; c.beginPath(); c.arc(x - r * 0.38, y - r * 0.42, r * 0.26, 0, Math.PI * 2); c.fill();+ return;+ }+ const a = s.a, b = headOf(s, p), dx = b[0] - a[0], dy = b[1] - a[1], L = Math.hypot(dx, dy) || 1, ux = dx / L, uy = dy / L; let nx = -uy, ny = ux;+ if (nx * LIGHT[0] + ny * LIGHT[1] < 0) { nx = -nx; ny = -ny; } // n points to the lit side+ const w = s.w, sheen = 0.35 + 0.65 * Math.abs(ux * LIGHT[1] - uy * LIGHT[0]); // stitches lying across the light catch it most+ const inset = Math.min(L * 0.3, w * 0.25), a1: P = [a[0] + ux * inset, a[1] + uy * inset], b1: P = [b[0] - ux * inset, b[1] - uy * inset];+ c.globalAlpha = 1; c.strokeStyle = T.base; c.lineWidth = w; c.beginPath(); c.moveTo(a1[0], a1[1]); c.lineTo(b1[0], b1[1]); c.stroke();+ c.strokeStyle = T.base; c.lineWidth = w * 0.55; c.beginPath(); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); c.stroke(); // pinched where it dives into the holes+ c.strokeStyle = T.lo; c.globalAlpha = 0.6; c.lineWidth = w * 0.32; c.beginPath(); c.moveTo(a1[0] - nx * w * 0.32, a1[1] - ny * w * 0.32); c.lineTo(b1[0] - nx * w * 0.32, b1[1] - ny * w * 0.32); c.stroke();+ // the twist: slanted grooves between the strands, and a glint on the crown of each twist+ const step = Math.max(1.6, w * 1.05), n = Math.floor(L / step);+ if (n > 0) {+ c.globalAlpha = 0.42; c.strokeStyle = T.lo; c.lineWidth = Math.max(0.45, w * 0.16); c.beginPath();+ for (let k = 1; k <= n; k++) { const m = k * step - step * 0.3, cx = a[0] + ux * m, cy = a[1] + uy * m, sx = (nx - ux * 0.7) * w * 0.42, sy = (ny - uy * 0.7) * w * 0.42; c.moveTo(cx - sx, cy - sy); c.lineTo(cx + sx, cy + sy); }+ c.stroke();+ c.globalAlpha = 0.28 + 0.5 * sheen; c.strokeStyle = T.hi; c.lineWidth = Math.max(0.45, w * 0.22); c.beginPath();+ for (let k = 0; k < n; k++) { const m = k * step + step * 0.25, cx = a[0] + ux * m + nx * w * 0.16, cy = a[1] + uy * m + ny * w * 0.16; c.moveTo(cx - ux * step * 0.22, cy - uy * step * 0.22); c.lineTo(cx + ux * step * 0.22, cy + uy * step * 0.22); }+ c.stroke();+ } else { c.globalAlpha = 0.3 + 0.5 * sheen; c.strokeStyle = T.hi; c.lineWidth = w * 0.25; c.beginPath(); c.moveTo(a1[0] + nx * w * 0.16, a1[1] + ny * w * 0.16); c.lineTo(b1[0] + nx * w * 0.16, b1[1] + ny * w * 0.16); c.stroke(); }+ });+ c.restore();+};++// ---------------------------------------------------------------- stitch generators+const flat = (a: P, b: P, w: number, c: string, t = 1): St => ({ k: "flat", a, b, w, c, t });+export const knot = (a: P, r: number, c: string): St => ({ k: "knot", a, b: a, w: r, c, t: 2.2 });+// STEM STITCH: each stitch goes forward a length and comes back up half a length behind, beside+// the last, so the line twists like a rope. The slant is the tell.+export const stemStitch = (path: P[], len: number, w: number, c: string, seed: number): St[] => {+ const L = polyLen(path), n = Math.max(2, Math.round(L / (len * 0.5))), s = resample(path, n + 2), r = rng(seed), out: St[] = [];+ for (let i = 0; i + 2 < s.length; i++) { const a = s[i], b = s[i + 2], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, o = w * 0.28; out.push(flat([a[0] - (dy / l) * o, a[1] + (dx / l) * o], [b[0] + (dy / l) * o * 0.6 + (r() - 0.5) * 0.4, b[1] - (dx / l) * o * 0.6 + (r() - 0.5) * 0.4], w, c, 0.9)); }+ return out;+};+// SPLIT STITCH: each stitch comes up through the middle of the last one, splitting its strands.+export const splitStitch = (path: P[], len: number, w: number, c: string, closed = false): St[] => {+ const pts = closed ? [...path, path[0]] : path, L = polyLen(pts), n = Math.max(2, Math.round(L / (len * 0.7))), s = resample(pts, n + 1), out: St[] = [];+ for (let i = 0; i + 1 < s.length; i++) { const a = i ? lerpP(s[i - 1], s[i], 0.62) : s[0]; out.push(flat(a, s[i + 1], w, c, 0.9)); }+ return out;+};+export const runningStitch = (path: P[], dash: number, gap: number, w: number, c: string): St[] => {+ const L = polyLen(path), n = Math.max(2, Math.round(L / 1.5)), s = resample(path, n), out: St[] = []; let acc = 0, on = true, start = s[0];+ for (let i = 1; i < s.length; i++) { acc += Math.hypot(s[i][0] - s[i - 1][0], s[i][1] - s[i - 1][1]); if (on && acc >= dash) { out.push(flat(start, s[i], w, c, 0.8)); on = false; acc = 0; } else if (!on && acc >= gap) { start = s[i]; on = true; acc = 0; } }+ return out;+};+export const straight = (a: P, b: P, w: number, c: string): St => flat(a, b, w, c, 1);+// SATIN along an axis: stitches laid ACROSS the axis, side by side, each from edge to edge.+// `half(t)` is the half-width at t; `colour(t, side)` picks the thread. Long spans are split at+// the axis the way an embroiderer would (a stitch longer than ~9 mm snags).+export const satin = (axis: P[], half: (t: number) => number, gap: number, w: number, colour: (t: number, side: number) => string, o: { skew?: number; split?: number } = {}): St[] => {+ const { skew = 0, split = 26 } = o, L = polyLen(axis), n = Math.max(2, Math.round(L / gap)), s = resample(axis, n), out: St[] = [];+ for (let i = 0; i < n; i++) {+ const t = i / (n - 1), p = s[i], q = s[Math.min(n - 1, i + 1)], pr = s[Math.max(0, i - 1)], dx = q[0] - pr[0], dy = q[1] - pr[1], l = Math.hypot(dx, dy) || 1, ux = dx / l, uy = dy / l, h = half(t); if (h < 0.6) continue;+ const e1: P = [p[0] - uy * h + ux * skew * h, p[1] + ux * h + uy * skew * h], e2: P = [p[0] + uy * h - ux * skew * h, p[1] - ux * h - uy * skew * h];+ if (2 * h > split) { out.push(flat(e1, lerpP(e1, e2, 0.5 + (i % 2 ? 0.04 : -0.04)), w, colour(t, -1))); out.push(flat(lerpP(e1, e2, 0.5 + (i % 2 ? 0.04 : -0.04)), e2, w, colour(t, 1))); }+ else out.push(flat(e1, e2, w, colour(t, 0)));+ }+ return out;+};+// FISHBONE / angled satin for a leaf: from the edge down to the midrib, slanting toward the tip,+// alternating sides, so the leaf's two halves catch the light differently.+export const fishbone = (mid: P[], half: (t: number) => number, gap: number, w: number, colour: (side: number, t: number) => string): St[] => {+ const L = polyLen(mid), n = Math.max(4, Math.round(L / gap)), s = resample(mid, n + 1), out: St[] = [];+ const edge = (i: number, side: number): P => { const j = Math.min(n, i), p = s[j], q = s[Math.min(n, j + 1)], pr = s[Math.max(0, j - 1)], dx = q[0] - pr[0], dy = q[1] - pr[1], l = Math.hypot(dx, dy) || 1, h = half(j / n); return [p[0] - (dy / l) * h * side, p[1] + (dx / l) * h * side]; };+ for (let i = 0; i < n; i++) for (const side of [-1, 1]) { const t = i / n, a = edge(i + Math.max(1, Math.round(n * 0.14)), side); if (half(Math.min(1, t + 0.14)) < 0.8) continue; out.push(flat(a, s[i], w, colour(side, t))); }+ return out;+};+// LONG AND SHORT: rows from an edge toward a target, the first row alternating long and short,+// later rows filling in between; each row's thread steps from colour A toward colour B.+export const longShort = (edge: P[], target: (p: P) => P, rows: number, gap: number, w: number, ramp: string[], seed: number): St[] => {+ const L = polyLen(edge), n = Math.max(3, Math.round(L / gap)), s = resample(edge, n), r = rng(seed), out: St[] = [];+ for (let row = 0; row < rows; row++) for (let i = 0; i < n; i++) {+ const e = s[i], tgt = target(e), jitter = (r() - 0.5) * 0.12, longOne = (i + row) % 2 === 0;+ const f0 = row === 0 ? 0 : (row - (longOne ? 0.35 : 0.1)) / rows + jitter * 0.3, f1 = row === rows - 1 ? 1 : (row + 1 + (longOne ? 0.2 : -0.15)) / rows + jitter;+ const pick = clamp((row + (r() - 0.5) * 1.1) / Math.max(1, rows - 1), 0, 1), c = ramp[Math.round(pick * (ramp.length - 1))];+ out.push(flat(lerpP(e, tgt, clamp(f0)), lerpP(e, tgt, clamp(f1)), w, c));+ }+ return out;+};+// a packed French-knot fill of a disc (or ellipse), colour by position+export const knots = (cx: number, cy: number, rx: number, ry: number, r0: number, colour: (u: number, v: number) => string, seed: number): St[] => {+ const r = rng(seed), out: St[] = [], step = r0 * 1.7;+ for (let y = -ry; y <= ry; y += step * 0.87) for (let x = -rx; x <= rx; x += step) { const px = x + ((Math.round((y + ry) / (step * 0.87)) % 2) * step) / 2 + (r() - 0.5) * r0 * 0.5, py = y + (r() - 0.5) * r0 * 0.5; if ((px / rx) ** 2 + (py / ry) ** 2 > 1) continue; out.push(knot([cx + px, cy + py], r0 * (0.9 + r() * 0.2), colour(px / rx, py / ry))); }+ return out;+};+export { flat, lerp };diff --git a/engine/src/canvas-core/figureSheet.ts b/engine/src/canvas-core/figureSheet.tsnew file mode 100644index 0000000..1e0169b--- /dev/null+++ b/engine/src/canvas-core/figureSheet.ts@@ -0,0 +1,83 @@+// FIGURE SHEET: Theo, the realistic-canon adult (7.5 heads), on the hard cases. Turning (four+// views on a head-unit grid), contrapposto (with its centre of mass dropped to the floor inside+// the support polygon), reaching up, sitting on a stool, gripping a mug (fingers solved onto the+// cylinder), and a hand pointed at the lens through a 35 mm lens. Storybook pencil + wash.+import { GRAPHITE, Gfx, PENCIL, type Ctx, type Env, type P } from "./core";+import type { Film } from "./film";+import { Camera, V3, add, camera, lensPx, mix3, mul, norm, project, sub } from "./character/math3";+import { handModel, resolveHand } from "./character/human/hands";+import type { Pose, Scene } from "./character/types";+import { renderStorybook } from "./character/render/storybook";+import { letter } from "./drafting";+import { theo, THEO_PALETTE } from "./characters/theo";+import { THEO_DIMS, contra, holdCup, mug, pointAtCamera, reachUp, relaxed, sit, stool, withProps, STOOL_H } from "./characters/theo/poses";+import { rigFor } from "./character/human/figure";+import { THEO_SPEC } from "./characters/theo";+import { balance } from "./character/human/balance";++const W = 3200, H = 4420, SHEET = "#f7f1e3", MUTED = "#8a7f72";+const label = (g: Gfx, t: string, x: number, y: number, cap = 26, color = GRAPHITE, align: "left" | "center" = "left") => letter(g, t, x, y, { cap, color, seed: t.length * 7 + Math.round(x), w: cap / 11, opacity: 0.9, align });+const only = (s: Scene, re: RegExp): Scene => ({ ...s, parts: s.parts.filter((p) => re.test(p.id)), ground: null });+// a long lens from far away for full figures: near-orthographic, so the grid reads true+const fullCam = (cx: number, floorY: number, figPx: number, yawCam = 0, height = 1.78): Camera => { const d = 14, f = (figPx * d) / height, a = (yawCam * Math.PI) / 180; return camera([Math.sin(a) * d, height * 0.52, Math.cos(a) * d], [0, height * 0.52, 0], f, cx, floorY - figPx * 0.52); };++const grid = (g: Gfx, cam: Camera, x0: number, x1: number) => {+ // head-unit rules: floor to crown in eighths... sevens and a half for a 7.5-head figure+ g.group("ink", () => { for (let i = 0; i <= 8; i++) { const y = project(cam, [0, Math.min(i, 7.5) * THEO_DIMS.hh, 0]).y; g.pen([[x0, y], [x1, y]], { w: i === 0 || i === 8 ? 1.4 : 0.9, color: "#9aa3b5", seed: 40 + i, wobble: 0.4, opacity: 0.5, retrace: false }); label(g, i === 8 ? "7.5" : String(i), x0 - 44, y - 9, 14, "#9aa3b5"); } });+};+const plumb = (g: Gfx, cam: Camera, _s: Scene, pose: Pose, extra: V3[] = []) => {+ const b = balance(rigFor(THEO_SPEC, pose), extra), top = project(cam, b.com), foot = project(cam, [b.com[0], 0, b.com[2]]);+ const sup = b.support.map(([x, z]) => { const q = project(cam, [x, 0.002, z]); return [q.x, q.y] as P; });+ g.group("ink", () => {+ if (sup.length > 2) g.pen(sup, { closed: true, w: 1.3, color: "#c0392b", seed: 71, wobble: 0.3, opacity: 0.8, retrace: false });+ g.pen([[top.x, top.y], [foot.x, foot.y]], { w: 1.2, color: "#c0392b", seed: 72, wobble: 0.2, opacity: 0.75, retrace: false });+ const c = g.cur; g.touch(top.x - 9, top.y - 9, top.x + 9, top.y + 9); c.fillStyle = "#c0392b"; c.beginPath(); c.arc(top.x, top.y, 6, 0, Math.PI * 2); c.fill(); c.beginPath(); c.arc(foot.x, foot.y, 4, 0, Math.PI * 2); c.fill();+ });+ return b;+};++export const drawFigureSheet = (ctx: Ctx, frame: number, env: Env) => {+ const g = new Gfx(ctx, env, frame, PENCIL);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = SHEET; ctx.fillRect(0, 0, W, H);+ label(g, "THEO / FIGURE SHEET / ADULT CANON 7.5 HEADS, 1.78 M", 90, 60, 46);+ label(g, "EVERY POSE BUILT FROM THE SKELETON: JOINT LIMITS, BALANCE AND CONTACT ARE CHECKED IN CODE, NOT EYEBALLED", 90, 128, 20, MUTED);+ // ---- row 1: turning+ label(g, "1 TURNING", 90, 200, 28);+ [0, 45, 90, 180].forEach((yaw, i) => {+ const cx = 480 + i * 720, cam = fullCam(cx, 1110, 860);+ if (i === 0) grid(g, cam, 170, 3050);+ renderStorybook(g, theo.toScene(relaxed(yaw), cam), THEO_PALETTE);+ label(g, ["FRONT", "THREE-QUARTER", "PROFILE", "BACK"][i], cx - 90, 1150, 22, MUTED);+ });+ // ---- row 2: contrapposto, reaching, sitting+ label(g, "2 WEIGHT, REACH, SEAT", 90, 1240, 28);+ { const cx = 560, cam = fullCam(cx, 2170, 860, 0), p = contra(-30); const s = theo.toScene(p, cam); renderStorybook(g, s, THEO_PALETTE); const b = plumb(g, cam, s, p); label(g, "CONTRAPPOSTO: WEIGHT ON THE LEFT LEG", cx - 330, 2210, 20, MUTED); label(g, `CENTRE OF MASS ${b.inside ? "INSIDE" : "OUTSIDE"} SUPPORT, MARGIN ${(b.margin * 100).toFixed(1)} CM`, cx - 330, 2246, 16, "#c0392b"); }+ { const cx = 1600, cam = fullCam(cx, 2170, 860, 0), p = reachUp(-35); const s = theo.toScene(p, cam); renderStorybook(g, s, THEO_PALETTE); const b = plumb(g, cam, s, p); label(g, "REACHING UP, ON THE BALLS OF THE FEET", cx - 330, 2210, 20, MUTED); label(g, `CENTRE OF MASS ${b.inside ? "INSIDE" : "OUTSIDE"} SUPPORT, MARGIN ${(b.margin * 100).toFixed(1)} CM`, cx - 330, 2246, 16, "#c0392b"); }+ { const cx = 2650, cam = fullCam(cx, 2170, 860, 0), p = sit(-40); const s = withProps(theo.toScene(p, cam), cam, stool(-40)); renderStorybook(g, s, THEO_PALETTE); label(g, "SITTING ON A STOOL", cx - 330, 2210, 20, MUTED); label(g, `SEAT ${Math.round(STOOL_H * 100)} CM, THIGHS FORESHORTEN TOWARD US`, cx - 330, 2246, 16, MUTED); }+ // ---- row 3: the hands that carry the story+ label(g, "3 GRIP AND POINT", 90, 2330, 28);+ const cell = (x: number, y: number, w: number, h: number, fn: () => void) => { ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); fn(); ctx.restore(); g.group("ink", () => ([[[x, y], [x + w, y]], [[x + w, y], [x + w, y + h]], [[x + w, y + h], [x, y + h]], [[x, y + h], [x, y]]] as P[][]).forEach((l, i) => g.pen(l, { w: 1.2, color: MUTED, seed: x + i, wobble: 0.5, opacity: 0.5, retrace: false }))); };+ cell(120, 2400, 1440, 880, () => {+ // a medium close-up: the mug hand and the face that is looking at it+ const p = holdCup(), r = rigFor(THEO_SPEC, p), hand = r.joints.wristR, t = mix3(hand, r.joints.head, 0.5), cam = camera(add(t, [-0.24, 0.06, 1.1]), t, 1500, 840, 2840);+ renderStorybook(g, withProps(theo.toScene(p, cam), cam, mug(p)), THEO_PALETTE);+ });+ label(g, "GRIPPING A MUG: FOUR FINGERS SOLVED ONTO THE CYLINDER, THUMB OPPOSED", 130, 3300, 20, MUTED);+ cell(1640, 2400, 1440, 880, () => {+ // the camera sits ON the line of the index finger, half a metre out, with a 28 mm lens+ const p = pointAtCamera([0.05, 1.46, 0.95]), r = rigFor(THEO_SPEC, p), hm = handModel(r.hand.R, "R", THEO_DIMS.hand, resolveHand("point"));+ const idx = hm.digits.find((d) => d.digit === "index")!, tip = idx.pts[3], dir = norm(sub(tip, idx.pts[1]));+ const eye = add(add(tip, mul(dir, 0.28)), [0.055, 0.045, 0]), cam = camera(eye, add(tip, mul(dir, -0.5)), lensPx(24, 1440), 2360, 2840);+ renderStorybook(g, theo.toScene(p, cam), THEO_PALETTE, { weight: 1.1 });+ });+ label(g, "POINTING AT THE LENS, 24 MM, 30 CM: THE HAND DWARFS THE ARM BEHIND IT", 1650, 3300, 20, MUTED);+ // ---- row 4: one face, every view (the head only, big enough to judge)+ label(g, "4 ONE FACE, EVERY VIEW", 90, 3390, 28);+ [[0, 0, "FRONT"], [35, 0, "THREE-QUARTER"], [90, 0, "PROFILE"], [-40, -12, "FROM BELOW"], [160, 0, "BACK THREE-QUARTER"]].forEach(([yaw, tilt, name], i) => {+ const x = 120 + i * 600;+ cell(x, 3450, 560, 860, () => { const p: Pose = { ...relaxed(0), joints: { ...relaxed(0).joints, headTurn: 0 }, expression: i === 1 ? { smile: 0.35 } : {} }, r = rigFor(THEO_SPEC, p), t = add(r.joints.head, [0, 0.03, 0]), a = ((yaw as number) * Math.PI) / 180, el = (tilt as number) * 0.01, cam = camera(add(t, [Math.sin(a) * 1.4, -el * 30 * 0.03 - (tilt ? 0.35 : 0), Math.cos(a) * 1.4]), add(t, [0, tilt ? 0.02 : 0, 0]), 2900, x + 280, 3830); renderStorybook(g, only(theo.toScene(p, cam), /^(head|nose|earL|earR|hair|neck|neckSkin|torso|sleeveL|sleeveR)$/), THEO_PALETTE); });+ label(g, name as string, x + 280, 4340, 18, MUTED, "center");+ });+ g.paper("paper", 0.12); g.paper("coldpress", 0.12);+};+export const figureSheet: Film = { meta: { title: "Theo figure sheet", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "sheet", start: 0, end: 1, draw: drawFigureSheet }] };diff --git a/engine/src/canvas-core/film.ts b/engine/src/canvas-core/film.tsindex 0d64937..9fb1575 100644--- a/engine/src/canvas-core/film.ts+++ b/engine/src/canvas-core/film.ts@@ -8,18 +8,32 @@ export type Assets = { images: Record<string, string>; fonts?: Record<string, st// GPU canvas budget, and when several pages render at once with big layer pools some surfaces// silently fall back to software, which antialiases differently: the same frame then comes out// in more than one way depending on timing. Software everywhere is the same everywhere.-export type Film = { meta: { title: string; W: number; H: number; fps: number; bpm: number; durationFrames: number; raster?: "gpu" | "cpu" }; assets: Assets; shots: Shot[]; audio?: (sampleRate: number) => [Float32Array, Float32Array] };+export type Film = { meta: {+ title: string; W: number; H: number; fps: number; bpm: number; durationFrames: number;+ raster?: "gpu" | "cpu";+ // "drawing": a picture drawing itself. Fine marks change little per frame, so dead air is judged+ // over 1 s at a 0.02% floor, and a hand's short pauses between passes (up to half a second) are allowed.+ kind?: "story" | "drawing" | "loop" | "explainer" | "infographic" | "launch" | "interactive";+ locked?: [from: number, to: number, reason: string][];+ holds?: [from: number, to: number][];+ onTwos?: boolean;+ step?: 1 | 2 | 3;+}; assets: Assets; shots: Shot[]; audio?: (sampleRate: number) => [Float32Array, Float32Array] };// Cheap structural checks every adapter runs before frame 0. (The full gate is Phase 2.)export const validate = (film: Film): string[] => {- const p: string[] = [], { fps, bpm, durationFrames } = film.meta, beat = (60 / bpm) * fps, ids = new Set<string>();- if (!Number.isInteger(beat)) p.push(`bpm ${bpm} at ${fps} fps gives a ${beat}-frame beat: cuts cannot sit on whole frames`);+ const p: string[] = [], { W, H, fps, bpm, durationFrames } = film.meta, beat = bpm ? (60 / bpm) * fps : null, ids = new Set<string>();+ if (![W, H, fps, durationFrames].every((n) => Number.isSafeInteger(n) && n > 0)) p.push("W, H, fps and durationFrames must be positive integers");+ if (!Number.isFinite(bpm) || bpm <= 0 || !Number.isInteger(beat)) p.push(`bpm ${bpm} at ${fps} fps does not give a whole-frame beat`);+ if (film.meta.step !== undefined && ![1, 2, 3].includes(film.meta.step)) p.push("step must be 1, 2 or 3");+ for (const [from, to] of [...(film.meta.holds ?? []), ...(film.meta.locked ?? [])]) if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to > durationFrames || to <= from) p.push(`invalid declared range ${from}-${to}`);+ for (const [, , reason] of film.meta.locked ?? []) if (!reason?.trim()) p.push("locked ranges need a reason");let t = 0;[...film.shots].sort((a, b) => a.start - b.start).forEach((s) => {if (ids.has(s.id)) p.push(`duplicate shot id '${s.id}'`); ids.add(s.id);if (s.start !== t) p.push(`shot '${s.id}' starts at ${s.start}, expected ${t} (gap or overlap)`);if (s.end <= s.start) p.push(`shot '${s.id}' has no length`);- if (Number.isInteger(beat) && s.start % beat) p.push(`shot '${s.id}' cuts off the beat grid (frame ${s.start}, beat = ${beat} frames)`);+ if (beat && Number.isInteger(beat) && s.start % beat) p.push(`shot '${s.id}' cuts off the beat grid (frame ${s.start}, beat = ${beat} frames)`);t = s.end;});if (t !== durationFrames) p.push(`shots end at frame ${t}, film is ${durationFrames}`);diff --git a/engine/src/canvas-core/flatVector.ts b/engine/src/canvas-core/flatVector.tsnew file mode 100644index 0000000..a39ea40--- /dev/null+++ b/engine/src/canvas-core/flatVector.ts@@ -0,0 +1,223 @@+import { rng, type Ctx, type Env, type Layer, type P } from "./core";+import type { Film } from "./film";+import { clamp, smooth } from "./gallery";+import { cut, streakClip, streaks, streakTip } from "./koiDrawKit";++// FLAT VECTOR · the regatta. A modern flat editorial illustration, built the way it is built in a+// vector app.+//+// MEDIUM, physically: a pen tool on a screen. Every shape is a closed path of hand-placed anchors+// (straight corners for sails and hulls, smooth anchors for hills and water), filled with ONE flat+// colour the instant the path closes. No strokes anywhere: an edge is only where two fills meet,+// and it is perfectly crisp. Depth comes from overlapping planes and atmospheric colour, never+// from a line. Shadows are separate shapes with a linear transparency ramp (the "long shadow"),+// and the texture is a grain brush: a raster speckle painted in broad passes over the shade side+// of a shape, clipped to it.+// MARKS: anchor, anchor, anchor, close, fill. ORDER: background planes (sky, clouds, far and mid+// hills, the bay's bands and the sun's glitter), midground (shore, town, headland, lighthouse),+// the boats (hull, sails, boom, mast, wake), the long shadows, and last the grain brush.+// PALETTE: 13 swatches in one key: warm cream sky, lilac -> sage -> deep teal hills by distance,+// three blues for the bay, coral and mustard sails, navy hulls, bone white.+// LIGHT: a low late-afternoon sun off-frame to the LEFT (west): its glitter path runs off the left+// edge, every slope turned right is in shade, and every shadow is long and thrown right.+// SUBJECT & REFERENCE (from knowledge): small keelboats and dinghies racing (sloop rig: mast,+// boom, mainsail with a roached leech aft of the mast, a jib forward to the bow), all on one tack,+// wind from the left so every hull heels right; the leader is rounding the orange turning mark.+// Flat-illustration conventions from contemporary editorial vector work: layered hills with+// atmospheric perspective, geometric clouds with flat bottoms, grain on the shade side only.+// NOT ITS NEIGHBOUR (cut-paper fox): no torn fibres, no paper lift, no shadow under every piece;+// edges are mathematically crisp and the only shadows are cast ones.++const W = 1080, H = 1080, N = 525, HOLD = 30;+const C = { sky: "#f6e5cf", cloud: "#fcf3e6", far: "#cdbbd6", farS: "#b9a6c8", midL: "#9fbdab", mid: "#86ad9d", midS: "#6f9a8b", deep: "#2f6b63", deepS: "#22524c", shore: "#4f8a72", shoreS: "#3d7360", sand: "#ecc99a", bay: "#3a7ca1", bayH: "#6ea6c1", bayM: "#4c8db1", bayF: "#2f6a90", glint: "#f7dcaa", foam: "#d6e9ee", dash: "#8fc2d6", coral: "#ee7a58", mustard: "#f1b74a", navy: "#1f3a56", bone: "#fcf8ef", teal: "#3f9c8f" };+const NAVY_RGB = "31,58,86", LIFT = 84;++type Paint = string | ((c: Ctx) => CanvasGradient);+type Shape = { polys: P[][]; anchors: P[][]; fill: Paint; stage: number; grain?: { ang: number; k: number; from?: number } };+const S1 = 1, S2 = 2, S3 = 3, S4 = 4;++// ---------------------------------------------------------------- construction helpers+const sm = (a: P[], closed = true, per = 8) => smooth(a, closed, per);+const shape = (poly: P[], anchors: P[], fill: Paint, stage: number, grain?: Shape["grain"]): Shape => ({ polys: [poly], anchors: [anchors.length ? anchors : poly.filter((_, i) => i % Math.max(1, Math.floor(poly.length / 6)) === 0)], fill, stage, grain });+// a smooth ridge (anchors left to right) closed straight down to `base`+const ridge = (top: P[], base: number, fill: Paint, stage: number, grain?: Shape["grain"]): Shape => { const t = sm(top, false, 10); return shape([...t, [t[t.length - 1][0], base], [t[0][0], base]], [...top, [top[top.length - 1][0], base], [top[0][0], base]], fill, stage, grain); };+const cloud = (x: number, y: number, s: number): Shape => { const a: P[] = [[x - 110 * s, y], [x - 92 * s, y - 28 * s], [x - 52 * s, y - 38 * s], [x - 28 * s, y - 70 * s], [x + 22 * s, y - 76 * s], [x + 50 * s, y - 44 * s], [x + 88 * s, y - 40 * s], [x + 112 * s, y]]; const t = sm(a, false, 10); return shape(t, a, C.cloud, S1); };+const rot = (pts: P[], o: P, ang: number, s: number): P[] => { const c = Math.cos(ang), n = Math.sin(ang); return pts.map(([x, y]) => [o[0] + (x * c - y * n) * s, o[1] + (x * n + y * c) * s] as P); };+const capsule = (a: P, b: P, r: number): P[] => { const ang = Math.atan2(b[1] - a[1], b[0] - a[0]), out: P[] = []; for (let i = 0; i <= 6; i++) { const t = ang + Math.PI / 2 + (i / 6) * Math.PI; out.push([a[0] + Math.cos(t) * r, a[1] + Math.sin(t) * r]); } for (let i = 0; i <= 6; i++) { const t = ang - Math.PI / 2 + (i / 6) * Math.PI; out.push([b[0] + Math.cos(t) * r, b[1] + Math.sin(t) * r]); } return out; };+// a long soft shadow: the caster's points thrown right along the water by the low western sun,+// ramped from its foot to nothing+const throwShadow = (pts: P[], y0: number, len = 1.4, drop = 0.34): P[] => pts.map(([x, y]) => [x + Math.max(0, y0 - y) * len, y0 + Math.max(0, y0 - y) * drop]);+const ramp = (a: P, b: P, alpha: number) => (c: Ctx) => { const g = c.createLinearGradient(a[0], a[1], b[0], b[1]); g.addColorStop(0, `rgba(${NAVY_RGB},${alpha})`); g.addColorStop(1, `rgba(${NAVY_RGB},0)`); return g; };++// a sloop, facing right, heeled by `heel` (radians, positive = away from a wind on the left)+const boat = (o: P, s: number, heel: number, main: string, jib: string, hull: string): Shape[] => {+ const R = (p: P[]) => rot(p, o, heel, s);+ const hullP: P[] = [[-104, -4], [114, -15], [98, 3], [70, 17], [18, 23], [-52, 21], [-92, 13]];+ const leech = sm([[-95, -22], [-78, -92], [-46, -178], [-6, -262]], false, 6);+ const mainP: P[] = [[-5, -262], [-6, -24], ...leech];+ const jibP: P[] = [[6, -232], [106, -17], ...sm([[42, -29], [30, -120], [6, -232]], false, 6)];+ const mast: P[] = [[-3, -272], [3, -272], [3, -4], [-3, -4]], boom: P[] = [[-2, -26], [-100, -22], [-100, -17], [-2, -20]];+ const y0 = o[1] + 14 * s, sail = [...R(mainP), ...R(jibP)];+ const sh = [...R(mainP)].map((p) => p), shJ = R(jibP), far = throwShadow(sail, y0).reduce((a, p) => (p[0] > a[0] ? p : a), [0, 0] as P);+ const wake: P[] = [[-96, 10], [-150, 6], [-260, 13], [-330, 17], [-250, 19], [-150, 20], [-92, 18]];+ const bow: P[] = [[92, 6], [128, 10], [150, 18], [120, 20], [88, 16]];+ return [+ shape(throwShadow(sh, y0), [], ramp([o[0], y0], far, 0.58), S4),+ shape(throwShadow(shJ, y0), [], ramp([o[0], y0], far, 0.5), S4),+ shape(R(wake), R([[-96, 10], [-330, 17], [-92, 18]]), C.foam, S3),+ shape(R(hullP), R(hullP), hull, S3, { ang: Math.PI / 2 + heel, k: 0.5 }),+ shape(R(mainP), R([[-5, -262], [-6, -24], [-95, -22], [-46, -178]]), main, S3, { ang: Math.PI + heel, k: 0.35, from: 0.3 }),+ shape(R(boom), R(boom), C.navy, S3),+ shape(R(jibP), R([[6, -232], [106, -17], [42, -29]]), jib, S3, { ang: Math.PI + heel, k: 0.3, from: 0.4 }),+ shape(R(mast), R([[0, -272], [0, -4]]), C.navy, S3),+ shape(R(bow), R(bow), C.bone, S3),+ ];+};++const house = (x: number, y: number, w: number, h: number, roof: string): Shape[] => {+ const wall: P[] = [[x, y], [x + w, y], [x + w, y - h], [x, y - h]], rf: P[] = [[x - 3, y - h], [x + w / 2, y - h - w * 0.55], [x + w + 3, y - h]];+ return [shape(throwShadow([[x + w, y], [x + w, y - h], [x + w / 2, y - h - w * 0.55], [x + w * 0.7, y]], y, 1.5, 0.05), [], ramp([x + w, y], [x + w + (h + w * 0.55) * 1.5, y], 0.34), S4), shape(wall, wall, C.bone, S2), shape(rf, rf, roof, S2)];+};++// ---------------------------------------------------------------- the picture, back to front+const scene = (): Shape[] => {+ const r = rng(77), out: Shape[] = [];+ out.push(shape([[0, 0], [W, 0], [W, 560], [0, 560]], [[0, 0], [W, 0], [W, 560], [0, 560]], C.sky, S1, { ang: -Math.PI / 2, k: 0.16, from: 0.4 }));+ out.push(cloud(250, 178, 1.05), cloud(760, 112, 0.8), cloud(985, 222, 0.55));+ out.push(ridge([[0, 452], [130, 404], [262, 432], [402, 388], [556, 424], [704, 372], [862, 410], [1080, 386]], 520, C.far, S1, { ang: 0, k: 0.22 }));+ out.push(ridge([[0, 470], [150, 448], [290, 470], [430, 505]], 530, C.midL, S1, { ang: 0.3, k: 0.2 }));+ out.push(ridge([[420, 520], [560, 470], [700, 438], [830, 456], [950, 426], [1080, 444]], 540, C.mid, S1, { ang: 0.2, k: 0.25 }));+ // the bay: a base, then lighter toward the horizon and deeper toward us, each edge a gentle swell+ const band = (y0: number, y1: number, col: string, amp: number, ph: number, stage = S1): Shape => { const top: P[] = Array.from({ length: 9 }, (_, i) => [i * 135, y0 + Math.sin(i * 1.3 + ph) * amp] as P); const t = sm(top, false, 10); return shape([...t, [W, y1], [0, y1]], [...top, [W, y1], [0, y1]], col, stage); };+ out.push(band(505, H, C.bay, 0, 0), band(505, 548, C.bayH, 0, 0), band(620, 700, C.bayM, 5, 1), band(830, H, C.bayF, 7, 2.2));+ // the sun's glitter: a drift of light dashes running off the left edge, dense there and thinning out+ const gl: P[][] = [], ga: P[][] = [];+ for (let i = 0; i < 46; i++) { const u = r(), x = Math.pow(u, 1.6) * 420 - 20, y = 560 + r() * 240 + x * 0.12, l = 10 + (1 - u) * 34 + r() * 10; if (r() < u * 0.55) continue; const d = capsule([x, y], [x + l, y], 2 + (1 - u) * 2); gl.push(d); ga.push([[x, y], [x + l, y]]); }+ out.push({ polys: gl, anchors: ga, fill: C.glint, stage: S1 });+ // the far shore and its town, watching the race+ out.push(ridge([[640, 530], [760, 506], [880, 494], [1000, 484], [1080, 490]], 556, C.shore, S2, { ang: 0.15, k: 0.3 }));+ out.push(shape(sm([[880, 494], [1000, 484], [1080, 490], [1080, 556], [1010, 540], [940, 520]], true, 6), [[880, 494], [1080, 490], [1080, 556], [940, 520]], C.shoreS, S4));+ [[762, 512, 26, 22, C.coral], [796, 507, 22, 30, C.navy], [834, 503, 30, 24, C.mustard], [884, 497, 24, 28, C.coral], [934, 492, 28, 22, C.teal], [990, 488, 22, 26, C.navy]].forEach(([x, y, w, h, c]) => out.push(...house(x as number, y as number, w as number, h as number, c as string)));+ // the headland and its lighthouse, which marks the mouth of the harbour+ const head: P[] = [[0, 446], [86, 436], [196, 468], [300, 518], [388, 566], [432, 598]];+ const ht = sm(head, false, 10);+ out.push(shape([...ht, [410, 612], [300, 612], [0, 618]], [...head, [300, 612], [0, 618]], C.deep, S2, { ang: 0.4, k: 0.3 }));+ out.push(shape(sm([[86, 436], [196, 468], [300, 518], [388, 566], [432, 598], [330, 600], [220, 540], [130, 470]], true, 8), [[86, 436], [432, 598], [330, 600], [130, 470]], C.deepS, S4));+ out.push(shape(sm([[200, 604], [300, 596], [412, 600], [436, 608], [300, 616], [180, 616]], true, 6), [[200, 604], [436, 608], [180, 616]], C.sand, S2));+ const lx = 352, ly = 550;+ out.push(shape(throwShadow([[lx + 11, ly], [lx + 8, ly - 74], [lx + 2, ly - 94], [lx - 10, ly]], ly, 1.6, 0.12), [], ramp([lx, ly], [lx + 150, ly + 10], 0.34), S4));+ out.push(shape([[lx - 12, ly], [lx + 12, ly], [lx + 8, ly - 70], [lx - 8, ly - 70]], [[lx - 12, ly], [lx + 12, ly], [lx + 8, ly - 70], [lx - 8, ly - 70]], C.bone, S2));+ out.push(shape([[lx - 11, ly - 26], [lx + 11, ly - 26], [lx + 10, ly - 42], [lx - 10, ly - 42]], [[lx - 11, ly - 26], [lx + 11, ly - 26], [lx + 10, ly - 42], [lx - 10, ly - 42]], C.coral, S2));+ out.push(shape([[lx - 11, ly - 70], [lx + 11, ly - 70], [lx + 7, ly - 84], [lx, ly - 94], [lx - 7, ly - 84]], [[lx - 11, ly - 70], [lx + 11, ly - 70], [lx, ly - 94]], C.navy, S2));+ // the land sits high: a wide bay for the race, the sky kept to what the clouds need+ out.forEach((sh) => { if (sh.fill !== C.sky && sh.fill !== C.cloud) { sh.polys = sh.polys.map((p) => p.map(([x, y]) => [x, y >= H - 1 ? H : y - LIFT] as P)); sh.anchors = sh.anchors.map((p) => p.map(([x, y]) => [x, y >= H - 1 ? H : y - LIFT] as P)); } });+ // the fleet, far to near; the leader rounds the mark in the foreground+ const fleet: [P, number, number, string, string, string][] = [[[930, 500], 0.22, 0.1, C.bone, C.bone, C.navy], [[178, 526], 0.28, 0.12, C.coral, C.bone, C.navy], [[640, 546], 0.36, 0.14, C.bone, C.mustard, C.navy], [[850, 636], 0.54, 0.15, C.bone, C.teal, C.coral], [[296, 672], 0.66, 0.13, C.mustard, C.bone, C.navy], [[596, 852], 1.04, 0.16, C.coral, C.bone, C.navy]];+ fleet.forEach(([o, s, h, m, j, hu]) => out.push(...boat(o, s, h, m, j, hu)));+ // the turning mark: an orange inflatable buoy with a white band, its own long shadow+ const bx = 392, by = 902, buoy: P[] = [[bx - 20, by], [bx + 20, by], [bx + 13, by - 30], [bx, by - 44], [bx - 13, by - 30]];+ out.push(shape(throwShadow(buoy, by, 1.4, 0.1), [], ramp([bx, by], [bx + 70, by + 4], 0.3), S4), shape(buoy, buoy, C.coral, S3, { ang: 0, k: 0.4 }), shape([[bx - 17, by - 12], [bx + 17, by - 12], [bx + 14, by - 20], [bx - 14, by - 20]], [[bx - 17, by - 12], [bx + 17, by - 12]], C.bone, S3), shape(capsule([bx - 32, by + 2], [bx + 34, by + 2], 3), [[bx - 32, by + 2], [bx + 34, by + 2]], C.foam, S3));+ // the shore we watch from: two faceted rocks in the near corner, lit face left, shade face right+ const rockA: P[] = [[826, H], [846, 1012], [896, 968], [952, 976], [1000, 1024], [1012, H]], rockAS: P[] = [[896, 968], [952, 976], [1000, 1024], [1012, H], [934, H], [918, 1010]];+ const rockB: P[] = [[972, H], [990, 1036], [1034, 1010], [1080, 1016], [1080, H]], rockBS: P[] = [[1034, 1010], [1080, 1016], [1080, H], [1040, H], [1030, 1040]];+ out.push(shape(throwShadow([[1000, 1024], [952, 976], [896, 968]], 1060, 1.4, 0.05).concat([[1012, 1060]]), [], ramp([1000, 1040], [1080, 1040], 0.4), S4));+ out.push(shape(rockA, rockA, "#4d7480", S2, { ang: 0.2, k: 0.35 }), shape(rockAS, rockAS, "#35555f", S4), shape(rockB, rockB, "#4d7480", S2, { ang: 0.2, k: 0.35 }), shape(rockBS, rockBS, "#35555f", S4));+ out.push(shape(capsule([800, 1046], [860, 1044], 3), [[800, 1046], [860, 1044]], C.foam, S3), shape(capsule([944, 1066], [990, 1064], 2.6), [[944, 1066], [990, 1064]], C.foam, S3));+ // chop: dashes in drifts where the boats and wind work the water, bare rests between+ const dd: P[][] = [], da: P[][] = [], drift = (cx: number, cy: number, n: number, spread: number, s: number) => { for (let i = 0; i < n; i++) { const a = r() * Math.PI * 2, d = Math.sqrt(r()) * spread, x = cx + Math.cos(a) * d * 1.8, y = cy + Math.sin(a) * d * 0.5, l = (14 + r() * 26) * s; dd.push(capsule([x, y], [x + l, y], 2.4 * s)); da.push([[x, y], [x + l, y]]); } };+ drift(680, 970, 11, 110, 1.1); drift(150, 880, 8, 90, 1); drift(980, 800, 6, 70, 0.9); drift(520, 745, 5, 60, 0.8);+ out.push({ polys: dd, anchors: da, fill: C.dash, stage: S3 });+ return out;+};++// ---------------------------------------------------------------- time+// stage windows; inside one, each shape's time is its anchor count (a hand places each anchor)+const WIN: Record<number, [number, number]> = { [S1]: [4, 118], [S2]: [124, 204], [S3]: [210, 386], [S4]: [392, 440] };+const GRAIN: [number, number] = [446, N - HOLD];+type Timed = { sh: Shape; t0: number; t1: number; g0: number; g1: number };+const timeline = (cache: Map<string, unknown>): Timed[] => {+ const key = "flatVector:timeline"; let t = cache.get(key) as Timed[] | undefined; if (t) return t;+ const sc = scene(), out: Timed[] = sc.map((sh) => ({ sh, t0: 0, t1: 0, g0: 0, g1: 0 }));+ [S1, S2, S3, S4].forEach((st) => { const items = out.filter((o) => o.sh.stage === st), wt = (o: Timed) => 2 + o.sh.anchors.reduce((a, b) => a + b.length, 0) * 0.9, tot = items.reduce((a, o) => a + wt(o), 0), [a, b] = WIN[st]; let acc = 0; items.forEach((o) => { o.t0 = a + ((b - a) * acc) / tot; acc += wt(o); o.t1 = a + ((b - a) * acc) / tot; }); });+ const gi = out.filter((o) => o.sh.grain); gi.forEach((o, i) => { o.g0 = GRAIN[0] + ((GRAIN[1] - GRAIN[0]) * i) / gi.length; o.g1 = GRAIN[0] + ((GRAIN[1] - GRAIN[0]) * (i + 1.6)) / gi.length; o.g1 = Math.min(o.g1, GRAIN[1]); });+ cache.set(key, out); return out;+};++// ---------------------------------------------------------------- grain+const grainTile = (env: Env): Layer => {+ const key = `flatVector:grain:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const n = Math.round(240 * env.scale); L = env.canvas(n, n); const img = L.ctx.createImageData(n, n), d = img.data, r = rng(4242);+ for (let i = 0; i < n * n; i++) { const v = r(); if (v < 0.34) { d[i * 4] = 31; d[i * 4 + 1] = 58; d[i * 4 + 2] = 86; d[i * 4 + 3] = Math.round(90 + r() * 165); } }+ L.ctx.putImageData(img, 0, 0); env.cache.set(key, L); return L;+};+const scratch = (env: Env): Layer => { const key = `flatVector:tmp:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (!L) { L = env.canvas(Math.round(W * env.scale), Math.round(H * env.scale)); env.cache.set(key, L); } return L; };+const bbox = (ps: P[][]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; ps.forEach((p) => p.forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); })); return { x0: Math.max(0, x0 - 2), y0: Math.max(0, y0 - 2), x1: Math.min(W, x1 + 2), y1: Math.min(H, y1 + 2) }; };+const path = (c: Ctx, ps: P[][]) => { c.beginPath(); ps.forEach((p) => { p.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }); };+// the grain brush: speckle clipped to the shape, ramped from nothing on the lit side to full on the+// shade side; while it is being applied, only where the brush's passes have been+// Painted into a surface whose device origin sits at logical (ox, oy). A finished grain never+// changes, so it is painted once into its own bbox-sized surface and only composited after that.+const paintGrain = (t: Ctx, env: Env, sh: Shape, q: number, seed: number, ox: number, oy: number) => {+ const gr = sh.grain!, b = bbox(sh.polys), k = env.scale, OX = Math.floor(ox * k), OY = Math.floor(oy * k), dev = (x: number, y: number): [number, number] => [Math.floor(x * k) - OX, Math.floor(y * k) - OY];+ const [sx, sy] = dev(b.x0, b.y0), sw = Math.ceil((b.x1 - b.x0) * k) + 2, shh = Math.ceil((b.y1 - b.y0) * k) + 2;+ t.save(); t.setTransform(1, 0, 0, 1, 0, 0); t.clearRect(sx, sy, sw, shh);+ t.setTransform(k, 0, 0, k, -OX, -OY); path(t, sh.polys); t.clip();+ if (q < 1) streakClip(t, streaks(sh.polys, Math.max(26, (b.y1 - b.y0) * 0.22), gr.ang + Math.PI / 2 + 0.3, seed, 260), q);+ t.setTransform(1, 0, 0, 1, -OX, -OY); t.fillStyle = t.createPattern(grainTile(env).canvas as CanvasImageSource, "repeat")!; t.fillRect(sx + OX, sy + OY, sw, shh); // the grain is anchored to the artboard, cached or not+ t.restore(); t.save(); t.setTransform(k, 0, 0, k, -OX, -OY);+ const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, R = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) / 2, dx = Math.cos(gr.ang), dy = Math.sin(gr.ang), from = gr.from ?? 0.15;+ const g = t.createLinearGradient(cx - dx * R, cy - dy * R, cx + dx * R, cy + dy * R); g.addColorStop(0, "rgba(0,0,0,0)"); g.addColorStop(from, "rgba(0,0,0,0)"); g.addColorStop(1, "rgba(0,0,0,1)");+ t.globalCompositeOperation = "destination-in"; t.fillStyle = g; t.fillRect(b.x0 - 2, b.y0 - 2, b.x1 - b.x0 + 4, b.y1 - b.y0 + 4); t.restore();+ return { sx, sy, sw, shh };+};+const grain = (c: Ctx, env: Env, sh: Shape, q: number, seed: number, idx: number) => {+ const b = bbox(sh.polys), k = env.scale; let src: Layer, r: { sx: number; sy: number; sw: number; shh: number };+ if (q >= 1) {+ const key = `flatVector:grain:${idx}:${k}`; let L = env.cache.get(key) as Layer | undefined;+ if (!L) { L = env.canvas(Math.ceil((b.x1 - b.x0) * k) + 4, Math.ceil((b.y1 - b.y0) * k) + 4); paintGrain(L.ctx, env, sh, 1, seed, b.x0, b.y0); env.cache.set(key, L); }+ src = L; r = { sx: 0, sy: 0, sw: Math.ceil((b.x1 - b.x0) * k) + 2, shh: Math.ceil((b.y1 - b.y0) * k) + 2 };+ } else {+ src = scratch(env); r = paintGrain(src.ctx, env, sh, q, seed, 0, 0);+ const st = streaks(sh.polys, Math.max(26, (b.y1 - b.y0) * 0.22), sh.grain!.ang + Math.PI / 2 + 0.3, seed, 260), [x, y] = streakTip(st, q), rr = st.w / 2; // the grain brush's cursor, a ring the size of its tip+ c.save(); c.strokeStyle = "rgba(255,255,255,0.9)"; c.lineWidth = 2.6; c.beginPath(); c.arc(x, y, rr, 0, Math.PI * 2); c.stroke(); c.strokeStyle = UI; c.lineWidth = 1.2; c.beginPath(); c.arc(x, y, rr, 0, Math.PI * 2); c.moveTo(x - 5, y); c.lineTo(x + 5, y); c.moveTo(x, y - 5); c.lineTo(x, y + 5); c.stroke(); c.restore();+ }+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = sh.grain!.k; c.drawImage(src.canvas as CanvasImageSource, r.sx, r.sy, r.sw, r.shh, Math.floor(b.x0 * k), Math.floor(b.y0 * k), r.sw, r.shh); c.restore();+};++// ---------------------------------------------------------------- the pen tool at work+const UI = "#2b7bf6";+const penTool = (c: Ctx, sh: Shape, q: number) => {+ // the anchors go down one after another along each path; the path follows the cursor; the last+ // anchor placed shows its bezier handles+ const tot = sh.polys.length, per = 1 / tot;+ c.save(); c.lineWidth = 1.4; c.strokeStyle = UI; c.lineJoin = "round";+ sh.polys.forEach((poly, i) => {+ const qi = clamp((q - i * per) / per); if (qi <= 0) return;+ const drawn = cut([...poly, poly[0]], qi); c.beginPath(); drawn.forEach(([x, y], j) => (j ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke();+ const an = sh.anchors[i] ?? [], na = Math.min(an.length, Math.ceil(qi * an.length + 1e-9));+ for (let j = 0; j < na; j++) { const [x, y] = an[j]; c.fillStyle = j === na - 1 && qi < 1 ? UI : "#ffffff"; c.fillRect(x - 3.5, y - 3.5, 7, 7); c.strokeRect(x - 3.5, y - 3.5, 7, 7); }+ if (qi < 1 && na > 0) { const [x, y] = an[na - 1], nx = an[Math.min(an.length - 1, na)], px = an[Math.max(0, na - 2)], hx = (nx[0] - px[0]) * 0.18, hy = (nx[1] - px[1]) * 0.18; c.beginPath(); c.moveTo(x - hx, y - hy); c.lineTo(x + hx, y + hy); c.stroke(); [[x - hx, y - hy], [x + hx, y + hy]].forEach(([hx2, hy2]) => { c.beginPath(); c.arc(hx2, hy2, 3.2, 0, Math.PI * 2); c.fillStyle = "#ffffff"; c.fill(); c.stroke(); }); }+ });+ c.restore();+};++export const drawFlatVector = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, W, H); // the empty artboard+ const tl = timeline(env.cache), drawing: [Shape, number][] = [], fin = f >= N - HOLD;+ tl.forEach(({ sh, t0, t1, g0, g1 }, i) => {+ const q = fin || f >= t1 ? 1 : f <= t0 ? 0 : (f - t0) / (t1 - t0);+ if (q < 1) { if (q > 0) drawing.push([sh, q]); return; }+ ctx.fillStyle = typeof sh.fill === "string" ? sh.fill : sh.fill(ctx); path(ctx, sh.polys); ctx.fill("nonzero"); // the path closed: its fill lands+ if (sh.grain) { const gq = fin || f >= g1 ? 1 : f <= g0 ? 0 : (f - g0) / (g1 - g0); if (gq > 0) grain(ctx, env, sh, gq, 900 + i, i); }+ });+ drawing.forEach(([sh, q]) => penTool(ctx, sh, q));+};++export const STYLE = { id: "flatVector", name: "Flat vector", family: "modern flat illustration", medium: "pen-tool paths in a vector app, flat fills that land when a path closes, long-shadow shapes with a transparency ramp, a raster grain brush over the shade sides", nearest: "fox", hero: "a regatta of small sailboats on a bay under hills, the leader rounding the mark" };++export const flatVector: Film = {+ meta: { title: "Flat vector · the regatta", W, H, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "artboard", start: 0, end: N, draw: drawFlatVector }],+};diff --git a/engine/src/canvas-core/folkTale.ts b/engine/src/canvas-core/folkTale.tsnew file mode 100644index 0000000..532cc4c--- /dev/null+++ b/engine/src/canvas-core/folkTale.ts@@ -0,0 +1,564 @@+import { rng, type Ctx, type Gfx, type Medium, type P } from "./core";+import type { Film } from "./film";+import { clamp, mix } from "./gallery";+import { fit, runProcess, timeline, type Proc } from "./sumiEKit";+import {+ bell, bbox, daisy, darken, dogRose, faded, far, glowBand, gouache, gourdLeaf, grass, HAZE, leaf, leafGeom, lighten, limb, lineLeaf, lineLimb, pencil, pumpkin,+ radial, ramp, reveal, rgba, ribbonOf, sheet, sketch, smooth, stroke, sunflower, tendril, trace, umbel, type Box, type Gouache, type Grass, type Leaf, type Line, type Sun,+} from "./folkTaleKit";++// THE BOY WITH THE ROOSTER · a Russian folk-tale storybook painting.+//+// MEDIUM, physically: gouache and transparent watercolour over an HB graphite drawing on a warm+// cream cartridge sheet. The whole picture is drawn in pencil first. Then it is painted from the+// back to the front, and the paint gets thicker and richer the nearer the thing is: the far+// village is never painted at all (bare pencil on the cream), the middle distance is a thin pale+// wash that lets the drawing through and dissolves into a golden haze, and the foreground is+// opaque body colour laid with a half-dry round brush, so every leaf, petal and blade shows its+// brush drag. DEPTH IS THE MEDIUM: nearness is said by how much paint there is.+// MARKS: pencil lines that breathe with the hand's pressure and are gone over twice; flat opaque+// fills cut by the brush; dry-brush drags inside them; sponge-like mottle in the dark leaves;+// painted veins (a lighter midrib, side veins leaving it toward the margin); sunflower rays laid+// one by one, creased, the sun half lighter; grass as thousands of single blades.+// EDGE: foreground edges crisp and slightly darker where the gouache settles; middle-distance+// edges soft, the paint stopping short of the line; far edges are the pencil line itself.+// ORDER: bare sheet; the whole scene in pencil, big shapes first; a warm glow wash in the sky;+// the meadow laid back to front; the birch wood from far (line) to near (paint); the cottage,+// thinning out into its own drawing; the haze; the fence; the path; the boy and his rooster;+// the pumpkin patch; the sunflowers; foreground grass and flowers; last accents (cheeks, eyes,+// highlights, florets).+// PALETTE: cream paper, sap and olive greens, yellow ochre, cadmium yellow and orange, vermilion,+// cobalt violet for the bellflowers, burnt umber, Payne's grey only in the far pencil.+// LIGHT: a late-summer afternoon sun, low and to the upper left, seen as a golden haze in the+// middle distance; every cast shadow falls to the lower right.+// SUBJECT: a village kitchen garden at the edge of a birch wood. A small boy (about six years+// old, a little under six heads tall: big round head, short neck, short limbs, feet planted+// apart) carries a rooster against his chest on the path through the wattle fence; behind him+// the log cottage (izba) with carved window frames and a horse-head ridge, and far off the+// onion domes of the village church, a bell tower and a post mill.+// REFERENCE (from knowledge): Russian folk-tale book illustration in the storybook-painting+// tradition (gouache over pencil, the drawing left bare at the back); Russian wooden+// architecture (the izba's log corners, carved nalichniki, the konyok ridge; onion domes on+// drums, a tented bell tower, the Orthodox cross); the botany of Helianthus annuus, Cucurbita+// pepo, Betula pendula (white bark with dark lenticels, pendulous twigs, serrate leaves),+// Campanula, Rosa canina, ox-eye daisy; a Russian Orloff-type farmyard cock; children's+// proportions (a six-year-old: ~5.8 heads, the navel near half height).++export const W = 1920, H = 1080;+const N = 540; // 18 s; the last 30 frames are the finished painting+const FT_M: Medium = { nib: 1, taper: 1, pressure: 1, retrace: false, wobble: 0, rough: 0 };++// ---------------------------------------------------------------- the far distance: pencil only+const onion = (cx: number, base: number, w: number, h: number, seed: number, a = 0.55): Line[] => {+ const L: P[] = [[cx - w * 0.32, base], [cx - w * 0.5, base - h * 0.28], [cx - w * 0.44, base - h * 0.52], [cx - w * 0.16, base - h * 0.8], [cx, base - h]];+ const R = L.slice(0, -1).reverse().map(([x, y]) => [2 * cx - x, y] as P);+ const top = base - h;+ return [+ { pts: [...L, ...R], seed, a, w: 0.9 },+ { pts: [[cx, top], [cx, top - h * 0.45]], seed: seed + 1, a, w: 0.8, retrace: false },+ { pts: [[cx - w * 0.14, top - h * 0.33], [cx + w * 0.14, top - h * 0.33]], seed: seed + 2, a, w: 0.7, retrace: false },+ { pts: [[cx - w * 0.1, top - h * 0.14], [cx + w * 0.1, top - h * 0.2]], seed: seed + 3, a, w: 0.7, retrace: false },+ { pts: [[cx - w * 0.26, base - h * 0.2], [cx, base - h * 0.16], [cx + w * 0.26, base - h * 0.2]], seed: seed + 4, a: a * 0.5, w: 0.6, retrace: false },+ ];+};+const box4 = (x0: number, y0: number, x1: number, y1: number, seed: number, a = 0.5): Line[] => [+ { pts: [[x0, y1], [x0, y0]], seed, a }, { pts: [[x1, y0], [x1, y1]], seed: seed + 1, a }, { pts: [[x0 - 2, y0], [x1 + 2, y0]], seed: seed + 2, a },+];+const house = (x: number, y: number, w: number, h: number, seed: number, a = 0.45): Line[] => [+ ...box4(x, y - h, x + w, y, seed, a),+ { pts: [[x - 5, y - h + 2], [x + w / 2, y - h - h * 0.8], [x + w + 5, y - h + 2]], seed: seed + 5, a },+ { pts: [[x + w / 2, y - h - h * 0.8], [x + w * 1.6, y - h - h * 0.72], [x + w * 1.62, y - h * 0.9]], seed: seed + 6, a: a * 0.8 },+ { pts: [[x + w, y], [x + w * 1.6, y - 3]], seed: seed + 7, a: a * 0.6 },+ ...box4(x + w * 0.35, y - h * 0.7, x + w * 0.65, y - h * 0.3, seed + 8, a * 0.7),+];+// a tree in line, the way the far trees in this tradition are drawn: a scalloped crown and a trunk+const lineTree = (cx: number, base: number, rx: number, ry: number, seed: number, a = 0.45): Line[] => {+ const r = rng(seed), pts: P[] = [], n = 13 + Math.floor(r() * 5), cy = base - ry * 1.25;+ for (let i = 0; i <= n; i++) { const th = Math.PI * 0.62 + (i / n) * Math.PI * 1.76, bump = 0.86 + 0.14 * Math.abs(Math.sin(i * 1.7 + r())); pts.push([cx + Math.cos(th) * rx * bump, cy + Math.sin(th) * ry * bump]); }+ const inner: P[] = []; for (let i = 0; i < 4; i++) { const th = -Math.PI * 0.8 + i * 0.5; inner.push([cx + Math.cos(th) * rx * 0.5, cy + Math.sin(th) * ry * 0.45]); }+ return [+ { pts, seed, a, w: 0.85 },+ { pts: inner, seed: seed + 1, a: a * 0.45, w: 0.7, retrace: false },+ { pts: [[cx - rx * 0.1, base], [cx - rx * 0.08, cy + ry * 0.75]], seed: seed + 2, a, w: 0.8 },+ { pts: [[cx + rx * 0.1, base], [cx + rx * 0.06, cy + ry * 0.75]], seed: seed + 3, a, w: 0.8 },+ ];+};+const FAR: Line[] = (() => {+ const L: Line[] = [];+ // the far ridge the village sits on+ L.push({ pts: [[0, 598], [180, 590], [380, 596], [560, 584], [760, 590], [980, 582], [1180, 590], [1380, 584], [1560, 592], [1760, 586], [1920, 590]], seed: 11, a: 0.45, w: 1 });+ L.push({ pts: [[520, 604], [700, 612], [900, 606], [1100, 614], [1250, 608]], seed: 12, a: 0.25, w: 0.8, retrace: false });+ // the church: a cube, four small domes, a drum and a big onion+ L.push(...box4(812, 522, 912, 590, 20, 0.55));+ L.push({ pts: [[806, 524], [862, 500], [918, 524]], seed: 24, a: 0.5 });+ L.push(...box4(846, 470, 878, 505, 25, 0.55));+ L.push(...onion(862, 472, 50, 58, 30, 0.6));+ L.push(...box4(818, 488, 832, 520, 36, 0.45), ...onion(825, 490, 20, 26, 40, 0.5));+ L.push(...box4(892, 488, 906, 520, 46, 0.45), ...onion(899, 490, 20, 26, 50, 0.5));+ L.push(...box4(840, 548, 852, 572, 55, 0.35), ...box4(872, 548, 884, 572, 56, 0.35));+ // the tented bell tower, left of the church+ L.push(...box4(744, 486, 776, 592, 60, 0.55), ...box4(748, 486, 772, 458, 62, 0.5));+ L.push({ pts: [[744, 458], [760, 404], [776, 458]], seed: 64, a: 0.55 });+ L.push(...onion(760, 404, 14, 20, 66, 0.5));+ L.push(...box4(754, 468, 766, 482, 69, 0.35));+ // log houses and gardens round the church+ L.push(...house(620, 598, 46, 26, 70), ...house(688, 596, 40, 22, 80), ...house(944, 594, 50, 28, 90), ...house(1020, 598, 38, 22, 100), ...house(1080, 596, 34, 20, 110, 0.35));+ L.push(...lineTree(586, 598, 26, 20, 120), ...lineTree(716, 592, 22, 18, 130, 0.4), ...lineTree(930, 588, 30, 22, 140), ...lineTree(1000, 590, 20, 16, 150, 0.4), ...lineTree(1135, 594, 28, 22, 160, 0.4), ...lineTree(1180, 596, 22, 17, 170, 0.35));+ // a post mill on the rise to the right+ L.push(...box4(1228, 520, 1252, 556, 180, 0.45), { pts: [[1224, 522], [1240, 506], [1256, 522]], seed: 184, a: 0.45 }, { pts: [[1240, 556], [1240, 588]], seed: 185, a: 0.45 }, { pts: [[1226, 590], [1240, 570], [1254, 590]], seed: 186, a: 0.35 });+ for (let k = 0; k < 4; k++) { const a0 = 0.5 + k * (Math.PI / 2), ex = 1240 + Math.cos(a0) * 50, ey = 526 + Math.sin(a0) * 50, nx = -Math.sin(a0) * 6, ny = Math.cos(a0) * 6; L.push({ pts: [[1240, 526], [ex, ey]], seed: 190 + k, a: 0.45, retrace: false }, { pts: [[1240 + Math.cos(a0) * 14 + nx, 526 + Math.sin(a0) * 14 + ny], [ex + nx, ey + ny]], seed: 195 + k, a: 0.3, w: 0.7, retrace: false }); }+ // far line trees along the ridge, right+ L.push(...lineTree(1330, 590, 34, 26, 200, 0.35), ...lineTree(1400, 586, 24, 20, 210, 0.3), ...lineTree(1720, 590, 40, 30, 220, 0.35), ...lineTree(1800, 592, 30, 24, 230, 0.3));+ return L.map((l) => ({ ...l, a: Math.min(0.85, (l.a ?? 0.5) * 1.45) }));+})();++// ---------------------------------------------------------------- the birch wood+type Birch = { x: number; base: number; w: number; lean: number; d: number; seed: number };+const BIRCHES: Birch[] = [+ { x: 640, base: 668, w: 7, lean: 6, d: 1, seed: 301 }, { x: 588, base: 676, w: 9, lean: -4, d: 1, seed: 302 },+ { x: 520, base: 688, w: 11, lean: 10, d: 0.85, seed: 303 }, { x: 444, base: 704, w: 15, lean: -8, d: 0.66, seed: 304 },+ { x: 356, base: 726, w: 20, lean: 12, d: 0.48, seed: 305 }, { x: 246, base: 756, w: 28, lean: -10, d: 0.28, seed: 306 },+ { x: 118, base: 792, w: 36, lean: 16, d: 0.12, seed: 307 }, { x: 22, base: 830, w: 42, lean: -6, d: 0.05, seed: 308 },+];+const trunkOf = (b: Birch): P[] => { const r = rng(b.seed), H0 = b.base + 30; return [[b.x, b.base + 6], [b.x + b.lean * 0.2 + (r() - 0.5) * b.w * 0.8, b.base - H0 * 0.25], [b.x + b.lean * 0.45 + (r() - 0.5) * b.w * 1.4, b.base - H0 * 0.5], [b.x + b.lean * 0.75 + (r() - 0.5) * b.w * 1.6, b.base - H0 * 0.76], [b.x + b.lean * 1.3 + (r() - 0.5) * b.w * 2, -30]]; };+const trunkAt = (b: Birch, t: number): P => { const s = smooth(trunkOf(b), 10), i = Math.min(s.length - 1, Math.round(t * (s.length - 1))); return s[i]; };+// pendulous birch twigs: out from the trunk, then hanging, leaves alternate along them+type Spray = { twig: P[]; leaves: Leaf[]; d: number; seed: number };+const spray = (x: number, y: number, dir: number, l: number, d: number, seed: number, col = "#7c9c36"): Spray => {+ const r = rng(seed), twig: P[] = [[x, y]]; let a = dir, px = x, py = y;+ for (let i = 0; i < 7; i++) { a += (Math.PI / 2 - a) * 0.22 + (r() - 0.5) * 0.12; px += Math.cos(a) * l / 7; py += Math.sin(a) * l / 7; twig.push([px, py]); }+ const s = smooth(twig, 6), leaves: Leaf[] = [];+ for (let i = 3; i < s.length; i += 3) {+ const side = (i / 3) % 2 ? 1 : -1, q = s[i], nx = s[Math.min(s.length - 1, i + 1)][0] - s[i - 1][0], ny = s[Math.min(s.length - 1, i + 1)][1] - s[i - 1][1], ta = Math.atan2(ny, nx);+ const hue = r(), lc = hue < 0.3 ? lighten(col, 0.15) : hue < 0.6 ? col : mix(col, "#4f6d2a", 0.5);+ leaves.push({ x: q[0], y: q[1], a: ta + side * (0.5 + r() * 0.5), len: 15 + r() * 9, wid: 11 + r() * 5, col: lc, seed: seed * 50 + i, d, serr: 0.1, stalk: 3, round: 0.62 });+ }+ return { twig, leaves, d, seed };+};+const SPRAYS: Spray[] = (() => {+ const out: Spray[] = [], r = rng(401);+ BIRCHES.forEach((b, bi) => {+ const nS = b.d >= 0.95 ? 5 : b.d > 0.6 ? 7 : 10;+ for (let k = 0; k < nS; k++) {+ const t = 0.62 + (k / nS) * 0.36 + r() * 0.04, [x, y] = trunkAt(b, t), side = k % 2 ? 1 : -1, dir = side > 0 ? -0.5 - r() * 0.5 : Math.PI + 0.5 + r() * 0.5;+ out.push(spray(x, y, dir, 60 + r() * 70 + (1 - b.d) * 40, b.d, 500 + bi * 40 + k));+ }+ });+ // the canopy that hangs into the top of the picture from the nearest birches, out over the garden+ for (let k = 0; k < 16; k++) { const x = 40 + k * 44 + r() * 20, y = -10 + r() * 60, d = clamp((x - 150) / 700) * 0.9; out.push(spray(x, y, Math.PI / 2 + (r() - 0.5) * 1.2, 90 + r() * 90, d, 900 + k)); }+ return out.sort((a, b) => b.d - a.d);+})();+const birchLines = (b: Birch): Line[] => { const s = trunkOf(b); return lineLimb(b.w, b.w * 0.6, s, b.seed, 0.55); };+const paintBirch = (g: Gfx, b: Birch, p: number) => {+ const s = trunkOf(b), d = b.d, r = rng(b.seed + 1);+ if (d >= 0.95) return;+ const body = (c: Ctx) => {+ limb(c, s, b.w, b.w * 0.6, "#efeadb", b.seed, d * 0.6, p, 0.28, 0);+ if (p < 1) return;+ // lenticels: dark dashes across the bark, crowded and fissured toward the foot+ const sm = smooth(s, 10), n = sm.length;+ for (let i = 0; i < Math.round(30 + b.w * 1.6); i++) {+ const t = Math.pow(r(), 1.2), idx = Math.min(n - 2, Math.floor(t * (n - 1))), [x, y] = sm[n - 1 - idx], w = b.w * (1 - 0.4 * (1 - t)), big = r() < 0.12, l = w * (big ? 0.35 + r() * 0.4 : 0.12 + r() * 0.4), off = (r() - 0.5) * w * 0.75, th = big ? w * (0.05 + r() * 0.06) : Math.max(0.4, w * (0.012 + r() * 0.02));+ c.globalAlpha = (big ? 0.8 : 0.45 + r() * 0.4) * (1 - 0.5 * d); c.fillStyle = far(big ? "#1f1c19" : "#3a342e", d * 0.8);+ const x0 = x + off - l / 2, x1 = x + off + l / 2, tilt = (r() - 0.5) * 2; c.beginPath(); c.moveTo(x0, y + tilt * 0.3); c.quadraticCurveTo(x + off, y - th - tilt, x1, y - tilt * 0.3); c.quadraticCurveTo(x + off + (r() - 0.5) * l * 0.3, y + th * (big ? 1.4 : 1), x0, y + tilt * 0.3); c.fill();+ }+ for (let i = 0; i < Math.round(b.w * 1.2); i++) { const t = r(), idx = Math.min(n - 2, Math.floor(t * (n - 1))), [x, y] = sm[idx], w = b.w * 0.9, off = (r() - 0.5) * w * 0.6; c.globalAlpha = 0.25 * (1 - d); c.strokeStyle = r() < 0.5 ? "#b8b2a6" : "#fffaf0"; c.lineWidth = 0.8; c.beginPath(); c.moveTo(x + off - w * 0.2, y); c.lineTo(x + off + w * 0.2, y + (r() - 0.5) * 2); c.stroke(); }+ const [bx, by] = s[0]; // the dark fissured foot of an old birch+ c.save(); trace(c, [[bx - b.w * 0.6, by], [bx - b.w * 0.5, by - b.w * 2.2], [bx + b.w * 0.5, by - b.w * 1.6], [bx + b.w * 0.6, by]]); c.clip();+ for (let k = 0; k < 14; k++) { const x = bx - b.w * 0.5 + r() * b.w, y0 = by - r() * b.w * 2.2; stroke(c, [[x, y0], [x + (r() - 0.5) * 3, y0 + b.w * 0.6]], 2.2, 0.8, far("#2e2923", d * 0.8), 0.7 * (1 - 0.5 * d)); }+ c.restore();+ };+ if (d > 0.3) { const bb: Box = [b.x - 60, -40, b.x + 60, b.base + 20]; faded(g, bb, (m) => ramp(m, bb, [0, b.base], [0, b.base - 520 * (1 - d * 0.4)], [[0, 1 - d * 0.5], [0.55, 0.9 - d * 0.6], [1, 0]]), body); }+ else body(g.cur);+};+const paintSpray = (g: Gfx, S: Spray, p: number) => {+ const c = g.cur, d = S.d;+ if (d >= 0.93) { S.leaves.forEach((L, i) => lineLeaf(c, L, clamp(p * S.leaves.length - i), undefined)); return; }+ stroke(c, S.twig, 1.8, 0.6, far("#4b3f33", d), 0.9 * (1 - 0.5 * d), clamp(p * 2), 4);+ S.leaves.forEach((L, i) => leaf(c, L, clamp((p - 0.2) / 0.8 * S.leaves.length - i)));+};+const sprayLines = (S: Spray): Line[] => [{ pts: S.twig, seed: S.seed, a: 0.4, w: 0.7, retrace: false }, ...(S.d > 0.55 ? S.leaves.map((L) => ({ pts: leafGeom(L).outline.filter((_, i) => i % 3 === 0), seed: L.seed, a: 0.4, w: 0.7, closed: true, retrace: false, per: 3 } as Line)) : [])];++// ---------------------------------------------------------------- the cottage (izba), middle distance+const COT = { x0: 1300, x1: 1480, gy: 662, ey: 546, peak: 420, bx: 1600, lift: 14 };+const cottageLines = (): Line[] => {+ const { x0, x1, gy, ey, peak, bx, lift } = COT, cx = (x0 + x1) / 2, L: Line[] = [], a = 0.62;+ L.push({ pts: [[x0, gy], [x0, ey]], seed: 601, a }, { pts: [[x1, gy], [x1, ey]], seed: 602, a }, { pts: [[x0, gy], [x1, gy]], seed: 603, a });+ L.push({ pts: [[x1, gy], [bx, gy - lift]], seed: 604, a }, { pts: [[bx, gy - lift], [bx, ey - lift]], seed: 605, a: a * 0.8 });+ L.push({ pts: [[x0 - 18, ey + 6], [cx, peak], [x1 + 18, ey + 6]], seed: 606, a, w: 1.2 });+ L.push({ pts: [[cx, peak], [bx + 16, peak - lift]], seed: 607, a }, { pts: [[x1 + 18, ey + 6], [bx + 30, ey - lift + 2]], seed: 608, a });+ for (let k = 1; k < 10; k++) { const y = ey + ((gy - ey) * k) / 10; L.push({ pts: [[x0 + 2, y], [x1 - 2, y]], seed: 610 + k, a: 0.32, w: 0.8, retrace: false }, { pts: [[x1 + 2, y], [bx - 2, y - lift * ((y - ey) / (gy - ey)) - lift * (1 - (y - ey) / (gy - ey))]], seed: 630 + k, a: 0.25, w: 0.7, retrace: false }); }+ // carved window frame (nalichnik) on the gable end, the attic window, the ridge horse+ L.push(...box4(cx - 22, 566, cx + 22, 618, 650, 0.6), { pts: [[cx - 30, 566], [cx, 548], [cx + 30, 566]], seed: 655, a: 0.6 }, { pts: [[cx - 28, 626], [cx + 28, 626]], seed: 656, a: 0.5 });+ L.push(...box4(cx - 10, 476, cx + 10, 500, 660, 0.5));+ L.push({ pts: [[cx - 2, peak + 2], [cx - 8, peak - 16], [cx - 20, peak - 22], [cx - 26, peak - 16], [cx - 16, peak - 12], [cx - 10, peak - 2]], seed: 665, a: 0.6 });+ L.push(...box4(1508, 572, 1540, 610, 670, 0.45), ...box4(1556, 568, 1584, 604, 675, 0.4));+ L.push({ pts: [[1530, 468], [1530, 420], [1552, 416], [1552, 462]], seed: 680, a: 0.5 });+ return L;+};+const paintCottage = (g: Gfx, p: number) => {+ const c = g.cur, { x0, x1, gy, ey, peak, bx, lift } = COT, cx = (x0 + x1) / 2, d = 0.42, r = rng(700);+ const bb: Box = [x0 - 40, peak - 60, bx + 50, gy + 30];+ faded(g, bb, (m) => radial(m, bb, 1370, 640, 40, 300, [[0, 0.95], [0.45, 0.8], [0.8, 0.25], [1, 0]], 0.9), (k) => reveal(k, bb, -2.4, p, 710, () => {+ const logs = (poly: P[], cols: [string, string], y0: number, y1: number, slope: number, xA: number, xB: number) => {+ gouache(k, poly, far(cols[0], d), { seed: 720, tex: { cols: [far(cols[1], d), far(lighten(cols[0], 0.3), d)], n: 90, len: 40, w: 4, ang: slope, jit: 0.08, a: 0.35 } });+ k.save(); trace(k, poly); k.clip();+ for (let i = 0; i < 10; i++) { const y = y0 + ((y1 - y0) * (i + 1)) / 10; k.globalAlpha = 0.55; k.strokeStyle = far(darken(cols[0], 0.45), d); k.lineWidth = 2.6; k.beginPath(); k.moveTo(xA, y); k.lineTo(xB, y + slope * (xB - xA)); k.stroke(); k.globalAlpha = 0.35; k.strokeStyle = far(lighten(cols[0], 0.35), d); k.lineWidth = 1.6; k.beginPath(); k.moveTo(xA, y - 4); k.lineTo(xB, y - 4 + slope * (xB - xA)); k.stroke(); }+ k.restore(); k.globalAlpha = 1;+ };+ // the long wall in shade, the gable end in the sun+ logs([[x1, gy], [bx, gy - lift], [bx, ey - lift], [x1, ey]], ["#8a6f4c", "#5c4630"], ey, gy, -lift / (bx - x1), x1, bx);+ logs([[x0, gy], [x1, gy], [x1, ey], [x0, ey]], ["#b8925e", "#7a5a38"], ey, gy, 0, x0, x1);+ // the log ends at the corners+ for (let i = 0; i < 10; i++) { const y = ey + ((gy - ey) * (i + 0.5)) / 10; for (const x of [x0, x1]) { k.globalAlpha = 1; k.fillStyle = far("#c9a472", d); k.beginPath(); k.ellipse(x, y, 7, 6, 0, 0, Math.PI * 2); k.fill(); k.globalAlpha = 0.6; k.strokeStyle = far("#6d5234", d); k.lineWidth = 1; k.beginPath(); k.ellipse(x, y, 4, 3.4, 0, 0, Math.PI * 2); k.stroke(); } }+ // the gable (vertical boards) and the roof planes of weathered grey planks+ gouache(k, [[x0 - 6, ey], [cx, peak + 10], [x1 + 6, ey]], far("#a88a5e", d), { seed: 730, tex: { cols: [far("#735a3a", d), far("#c9ab7c", d)], n: 60, len: 50, w: 3, ang: -Math.PI / 2, jit: 0.05, a: 0.4 } });+ gouache(k, [[cx, peak], [bx + 16, peak - lift], [bx + 30, ey - lift + 2], [x1 + 18, ey + 6]], far("#8f8e86", d), { seed: 731, tex: { cols: [far("#5f5e58", d), far("#bdbab0", d)], n: 110, len: 46, w: 4, ang: 0.95, jit: 0.1, a: 0.45 } });+ gouache(k, [[x0 - 18, ey + 6], [cx, peak], [cx + 4, peak + 12], [x0 - 6, ey + 12]], far("#9a968a", d), { seed: 732, tex: { cols: [far("#6a675e", d)], n: 30, len: 30, w: 3, ang: -0.9, a: 0.4 } });+ gouache(k, [[x1 + 18, ey + 6], [cx, peak], [cx - 4, peak + 12], [x1 + 6, ey + 12]], far("#9a968a", d), { seed: 733 });+ // the carved window: white frame, blue shutters, dark glass with the sky in it+ gouache(k, [[cx - 30, 566], [cx, 546], [cx + 30, 566], [cx + 28, 628], [cx - 28, 628]], far("#f1ece0", d), { seed: 740 });+ gouache(k, [[cx - 20, 568], [cx + 20, 568], [cx + 20, 616], [cx - 20, 616]], far("#34414a", d), { seed: 741 });+ k.fillStyle = far("#7b8fa0", d); k.globalAlpha = 0.6; k.fillRect(cx - 18, 570, 15, 20); k.globalAlpha = 1;+ k.strokeStyle = far("#f1ece0", d); k.lineWidth = 2.5; k.beginPath(); k.moveTo(cx, 568); k.lineTo(cx, 616); k.moveTo(cx - 20, 590); k.lineTo(cx + 20, 590); k.stroke();+ gouache(k, [[cx - 44, 568], [cx - 30, 568], [cx - 30, 618], [cx - 44, 618]], far("#4f78a8", d), { seed: 742 }); gouache(k, [[cx + 30, 568], [cx + 44, 568], [cx + 44, 618], [cx + 30, 618]], far("#4f78a8", d), { seed: 743 });+ for (let i = 0; i < 7; i++) { k.fillStyle = far(i % 2 ? "#c43b27" : "#f1ece0", d); k.beginPath(); k.arc(cx - 24 + i * 8, 560 - Math.abs(i - 3) * 2.5, 2.2, 0, Math.PI * 2); k.fill(); }+ gouache(k, [[cx - 10, 476], [cx + 10, 476], [cx + 10, 500], [cx - 10, 500]], far("#3a4248", d), { seed: 744 });+ // side windows in the shaded wall+ gouache(k, [[1508, 572], [1540, 571], [1540, 609], [1508, 610]], far("#e2dccd", d), { seed: 745 }); gouache(k, [[1512, 576], [1536, 575], [1536, 605], [1512, 606]], far("#2e373d", d), { seed: 746 });+ gouache(k, [[1556, 568], [1584, 567], [1584, 603], [1556, 604]], far("#d8d2c3", d), { seed: 747 }); gouache(k, [[1560, 572], [1580, 571], [1580, 599], [1560, 600]], far("#2e373d", d), { seed: 748 });+ // the carved ridge horse (konyok) and the chimney+ stroke(k, [[cx - 2, peak + 2], [cx - 8, peak - 16], [cx - 20, peak - 22], [cx - 26, peak - 16]], 6, 3, far("#7a5a38", d), 1);+ gouache(k, [[1530, 468], [1530, 420], [1552, 416], [1552, 462]], far("#b0674a", d), { seed: 749 });+ // the sill of grass and the cast shadow to the lower right+ k.globalAlpha = 0.35; k.fillStyle = far("#4a5a2a", d); trace(k, [[x0 - 10, gy], [bx + 40, gy - lift + 4], [bx + 70, gy + 12], [x0 + 20, gy + 16]]); k.fill(); k.globalAlpha = 1;+ void r;+ }));+};++// ---------------------------------------------------------------- the wattle fence+// Split stakes driven in a row; willow withies woven in front of one stake and behind the next,+// each course alternating, so the fabric reads as woven and not as rails.+type Fence = { x0: number; x1: number; y0: number; y1: number; h: number; n: number; d: number; seed: number };+const FENCES: Fence[] = [{ x0: 300, x1: 880, y0: 772, y1: 752, h: 104, n: 11, d: 0.22, seed: 800 }, { x0: 1045, x1: 1930, y0: 750, y1: 722, h: 100, n: 15, d: 0.26, seed: 840 }];+const stakesOf = (F: Fence) => { const r = rng(F.seed); return Array.from({ length: F.n }, (_, i) => { const t = i / (F.n - 1), x = F.x0 + (F.x1 - F.x0) * t + (r() - 0.5) * 10, y = F.y0 + (F.y1 - F.y0) * t, top = y - F.h - 8 - r() * 22, lean = (r() - 0.5) * 6; return { x, y, top, lean, w: 8 + r() * 4 }; }); };+const courseY = (F: Fence, k: number, x: number) => { const t = (x - F.x0) / (F.x1 - F.x0); return F.y0 + (F.y1 - F.y0) * t - 16 - k * 10.5; };+const fenceLines = (F: Fence): Line[] => {+ const S = stakesOf(F), L: Line[] = [];+ S.forEach((s, i) => L.push({ pts: [[s.x, s.y + 4], [s.x + s.lean, s.top]], seed: F.seed + i, a: 0.55, w: 1.1 }));+ for (let k = 0; k < 8; k += 2) L.push({ pts: Array.from({ length: 12 }, (_, j) => { const x = F.x0 + ((F.x1 - F.x0) * j) / 11; return [x, courseY(F, k, x) + Math.sin(j * 2.1) * 2] as P; }), seed: F.seed + 60 + k, a: 0.35, w: 0.8, retrace: false });+ return L;+};+const paintFence = (g: Gfx, F: Fence, p: number) => {+ const c = g.cur, S = stakesOf(F), d = F.d, r = rng(F.seed + 7), bb: Box = [F.x0 - 30, Math.min(F.y0, F.y1) - F.h - 40, F.x1 + 30, Math.max(F.y0, F.y1) + 20];+ reveal(c, bb, 0, p, F.seed, () => {+ const withy = (k: number, i: number, front: boolean) => {+ const a = S[i], b = S[i + 1]; if (!b) return; const ya = courseY(F, k, a.x) + (r() - 0.5) * 5, yb = courseY(F, k, b.x) + (r() - 0.5) * 5, sag = front ? 2 + r() * 3 : -1 - r() * 2, col = far(mix(mix("#a08a62", "#6e5c40", r()), "#8a8a7a", r() * 0.5), d), tw = 5 + r() * 3;+ const ctrl: P[] = [[a.x - 4, ya + (front ? 0 : 1)], [(a.x + b.x) / 2, (ya + yb) / 2 + sag], [b.x + 4, yb + (front ? 1 : 0)]];+ stroke(c, ctrl, tw, tw * 0.85, col, 1 - 0.4 * d); stroke(c, ctrl.map(([x, y]) => [x, y - 2.2] as P), 2, 1.5, far("#c9b48a", d), 0.5); stroke(c, ctrl.map(([x, y]) => [x, y + 2.6] as P), 2, 1.5, far("#4e402c", d), 0.45);+ };+ // courses behind the stakes first, then stakes, then the courses that pass in front+ for (let k = 0; k < 8; k++) for (let i = 0; i < S.length - 1; i++) if ((i + k) % 2) withy(k, i, false);+ S.forEach((s, i) => { limb(c, [[s.x, s.y + 4], [s.x + s.lean * 0.5, (s.y + s.top) / 2], [s.x + s.lean, s.top]], s.w, s.w * 0.8, "#8d7c62", F.seed + i * 3, d, 1, 0.35, 1.2); c.globalAlpha = 0.9; c.fillStyle = far("#5b4c38", d); trace(c, [[s.x + s.lean - s.w * 0.4, s.top + 2], [s.x + s.lean, s.top - 3], [s.x + s.lean + s.w * 0.4, s.top + 3]]); c.fill(); c.globalAlpha = 1; });+ for (let k = 0; k < 8; k++) for (let i = 0; i < S.length - 1; i++) if (!((i + k) % 2)) withy(k, i, true);+ // the fence's shadow on the grass, lower right+ c.globalAlpha = 0.18; c.fillStyle = far("#304018", d); trace(c, [[F.x0, F.y0 + 4], [F.x1, F.y1 + 4], [F.x1 + 40, F.y1 + 22], [F.x0 + 40, F.y0 + 24]]); c.fill(); c.globalAlpha = 1;+ });+};++// ---------------------------------------------------------------- the boy and his rooster+// Local frame: origin between his feet, 1 unit = 1 px at the figure's scale; he is 290 tall.+const BOY = { x: 972, y: 868, s: 1.1 };+const loc = (pts: P[]): P[] => pts.map(([x, y]) => [BOY.x + x * BOY.s, BOY.y + y * BOY.s]);+const SHAPES = {+ legL: [[-30, -140], [-3, -140], [-4, -96], [-7, -44], [-24, -44], [-30, -96]] as P[],+ legR: [[3, -140], [31, -140], [30, -94], [23, -44], [6, -44], [4, -96]] as P[],+ wrapL: [[-24, -46], [-7, -46], [-8, -12], [-22, -12]] as P[],+ wrapR: [[7, -46], [23, -46], [22, -12], [8, -12]] as P[],+ shoeL: [[-24, -14], [-6, -14], [-3, -6], [-8, 0], [-30, 1], [-35, -4], [-31, -10]] as P[],+ shoeR: [[8, -14], [22, -14], [30, -9], [34, -3], [28, 1], [6, 0], [4, -7]] as P[],+ shirt: [[-9, -238], [9, -238], [30, -226], [35, -196], [36, -160], [39, -138], [0, -134], [-39, -138], [-36, -160], [-35, -196], [-31, -226]] as P[],+ sleeveR: [[-31, -226], [-24, -216], [-26, -190], [-22, -172], [-34, -160], [-44, -182], [-42, -214]] as P[], // his right arm, on the viewer's left+ sleeveL: [[31, -224], [44, -214], [48, -190], [42, -178], [20, -198], [30, -206], [34, -214]] as P[], // his left arm, across the bird's back+ head: [[0, -291], [15, -287], [24, -274], [25, -258], [21, -244], [11, -236], [0, -234], [-11, -236], [-21, -244], [-25, -258], [-24, -274], [-15, -287]] as P[],+ hair: [[-25, -258], [-26, -272], [-18, -287], [-3, -293], [12, -291], [23, -282], [27, -268], [26, -257], [21, -262], [15, -266], [9, -263], [3, -267], [-4, -264], [-10, -267], [-16, -263], [-21, -266]] as P[],+ // the rooster+ body: [[-26, -214], [-10, -224], [12, -224], [34, -218], [44, -206], [40, -190], [22, -176], [2, -172], [-16, -176], [-28, -188], [-31, -202]] as P[],+ neck: [[-42, -238], [-34, -246], [-28, -240], [-22, -228], [-14, -216], [-6, -210], [-12, -206], [-9, -200], [-17, -200], [-16, -193], [-24, -197], [-26, -189], [-31, -198], [-36, -194], [-36, -206], [-40, -214], [-43, -226]] as P[],+ wing: [[-12, -214], [8, -218], [30, -212], [42, -202], [38, -190], [22, -186], [4, -190], [-10, -198]] as P[],+ headR: [[-50, -246], [-44, -252], [-35, -250], [-31, -242], [-34, -234], [-43, -233], [-49, -238]] as P[],+ comb: [[-49, -249], [-50, -257], [-46, -253], [-44, -262], [-41, -254], [-38, -262], [-36, -253], [-32, -258], [-32, -249], [-36, -246], [-46, -246]] as P[],+ wattle: [[-48, -236], [-45, -238], [-42, -234], [-43, -226], [-47, -227]] as P[],+ beak: [[-50, -246], [-58, -243], [-50, -240]] as P[],+};+const TAIL: P[][] = [+ [[36, -214], [52, -242], [70, -252], [84, -238], [88, -214]],+ [[38, -210], [58, -236], [78, -236], [90, -216], [92, -194]],+ [[38, -206], [60, -222], [78, -214], [86, -196]],+ [[36, -212], [48, -236], [58, -250], [68, -250]],+ [[36, -204], [54, -210], [70, -198], [76, -184]],+];+const boyLines = (): Line[] => {+ const L: Line[] = [], add = (pts: P[], seed: number, a = 0.55, closed = true) => L.push({ pts: loc(pts), seed, a, w: 1, closed, per: 4 });+ add(SHAPES.head, 1001); add(SHAPES.hair, 1002, 0.4); add(SHAPES.shirt, 1003); add(SHAPES.sleeveR, 1004); add(SHAPES.sleeveL, 1005);+ add(SHAPES.legL, 1006); add(SHAPES.legR, 1007); add(SHAPES.shoeL, 1008); add(SHAPES.shoeR, 1009);+ add(SHAPES.body, 1010); add(SHAPES.neck, 1011); add(SHAPES.headR, 1012); add(SHAPES.comb, 1013, 0.45);+ TAIL.forEach((t, i) => add(t, 1020 + i, 0.45, false));+ return L;+};+const paintBoy = (g: Gfx, p: number) => {+ const c = g.cur, r = rng(1100), ph = (i: number, n: number) => clamp(p * n - i), G = (pts: P[], col: string, o: Partial<Gouache> = {}) => gouache(c, loc(pts), col, { seed: 1100, ...o });+ const S = SHAPES, tx = (x: number) => BOY.x + x * BOY.s, ty = (y: number) => BOY.y + y * BOY.s, n = 9;+ // 0: his cast shadow, the trousers and wrappings and bast shoes+ if (ph(0, n) > 0) {+ c.globalAlpha = 0.3 * ph(0, n); c.fillStyle = "#2f3d15"; c.beginPath(); c.ellipse(tx(26), ty(2), 58, 9, 0.04, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1;+ reveal(c, [tx(-40), ty(-145), tx(40), ty(4)], Math.PI / 2, ph(0, n), 1101, () => {+ const TR = "#6a7a9c", stripes = (pts: P[]) => { c.save(); trace(c, loc(pts)); c.clip(); for (let x = -34; x < 34; x += 5.5) { c.globalAlpha = 0.45; c.strokeStyle = "#3f4c6c"; c.lineWidth = 1.3; c.beginPath(); c.moveTo(tx(x), ty(-140)); c.quadraticCurveTo(tx(x + 1.5), ty(-95), tx(x * 0.7), ty(-44)); c.stroke(); } c.restore(); c.globalAlpha = 1; };+ G(S.legL, TR, { tex: { cols: ["#8a98b8", "#4a5878"], n: 40, len: 26, w: 3, ang: Math.PI / 2, a: 0.35 }, rim: "#343f5a", rimA: 0.5 }); stripes(S.legL);+ G(S.legR, darken(TR, 0.15), { tex: { cols: ["#7a88a8", "#3a4868"], n: 40, len: 26, w: 3, ang: Math.PI / 2, a: 0.35 }, rim: "#2a334a", rimA: 0.5 }); stripes(S.legR);+ for (const [pts, sh] of [[S.wrapL, 0], [S.wrapR, 0.12]] as [P[], number][]) { G(pts, darken("#ece3cb", sh), { tex: { cols: ["#c9bc9c"], n: 12, len: 12, w: 3, ang: 0, a: 0.4 }, rim: "#9a8a68", rimA: 0.5 }); const b = bbox(pts); for (let k = 0; k < 3; k++) { const y = b[1] + 6 + k * 11; stroke(c, loc([[b[0] + 1, y], [b[2] - 1, y + 7]]), 2, 2, "#7a5a2e", 0.9); stroke(c, loc([[b[2] - 1, y], [b[0] + 1, y + 7]]), 2, 2, "#8a6a3a", 0.8); } }+ for (const [pts, sh] of [[S.shoeL, 0], [S.shoeR, 0.12]] as [P[], number][]) { G(pts, darken("#c9a45e", sh), { rim: "#6e5226", rimA: 0.7, rimW: 1.2 }); c.save(); trace(c, loc(pts)); c.clip(); const b = bbox(pts); for (let x = b[0]; x < b[2]; x += 4) { c.globalAlpha = 0.5; c.strokeStyle = "#7d5d2c"; c.lineWidth = 0.9; c.beginPath(); c.moveTo(tx(x), ty(b[1])); c.lineTo(tx(x + 5), ty(b[3])); c.moveTo(tx(x + 5), ty(b[1])); c.lineTo(tx(x), ty(b[3])); c.stroke(); } c.restore(); c.globalAlpha = 1; }+ });+ }+ // 1: the red shirt with its embroidered hem and side placket, the sash+ if (ph(1, n) > 0) reveal(c, [tx(-50), ty(-240), tx(50), ty(-130)], Math.PI / 2, ph(1, n), 1102, () => {+ const RED = "#c9321f";+ G(S.sleeveR, lighten(RED, 0.05), { tex: { cols: ["#e05a3a", "#8e1f16"], n: 30, len: 20, w: 3, ang: 1.9, a: 0.35 }, rim: "#6e1810", rimA: 0.5 });+ G(S.shirt, RED, { tex: { cols: ["#e0583a", "#9a2216", "#b82a1a"], n: 120, len: 26, w: 4, ang: 1.75, jit: 0.4, a: 0.35 }, rim: "#6e1810", rimA: 0.55, rimW: 2 });+ // the shadow side of the shirt, away from the sun+ c.save(); trace(c, loc(S.shirt)); c.clip(); c.globalAlpha = 0.55; c.fillStyle = "#8a1d14"; trace(c, loc([[14, -238], [40, -224], [42, -130], [18, -130], [22, -180]])); c.fill(); c.restore(); c.globalAlpha = 1;+ // embroidered hem: a white band with red and green folk crosses+ const hem: P[] = [[-39, -148], [36, -148], [39, -138], [0, -134], [-39, -138]]; G(hem, "#efe7d4", { rim: "#9a8a68", rimA: 0.4 });+ for (let i = 0; i < 12; i++) { const x = -34 + i * 6.2, y = -141.5; c.fillStyle = i % 2 ? "#2f6a3a" : "#c9321f"; for (const [dx, dy] of [[0, -2.2], [0, 2.2], [-2.2, 0], [2.2, 0], [0, 0]] as P[]) { c.beginPath(); c.arc(tx(x + dx), ty(y + dy), 1.05, 0, Math.PI * 2); c.fill(); } }+ G([[-12, -238], [-5, -238], [-7, -212], [-13, -212]], "#efe7d4", { rim: "#9a8a68", rimA: 0.4 }); for (let i = 0; i < 4; i++) { c.fillStyle = "#c9321f"; c.beginPath(); c.arc(tx(-9), ty(-233 + i * 6), 1.3, 0, Math.PI * 2); c.fill(); }+ G([[-37, -170], [37, -170], [37, -163], [-37, -163]], "#d9a631", { tex: { cols: ["#f2cc5a", "#9a6e1a"], n: 14, len: 12, w: 2, ang: 0, a: 0.4 }, rim: "#7a561a", rimA: 0.5 });+ stroke(c, loc([[28, -165], [31, -150], [29, -140]]), 3.5, 2, "#c99526", 1); stroke(c, loc([[32, -165], [37, -152], [37, -142]]), 3.5, 2, "#b2841f", 1);+ for (const [x, y] of [[29, -139], [37, -141]] as P[]) { c.fillStyle = "#c9321f"; c.beginPath(); c.ellipse(tx(x), ty(y + 3), 2.4, 4, 0, 0, Math.PI * 2); c.fill(); }+ });+ // 2: the rooster's tail (behind his arm), then body, wing, hackles, head+ if (ph(2, n) > 0) TAIL.forEach((t, i) => { const pp = clamp(ph(2, n) * TAIL.length - i); stroke(c, loc(t), 9 - i * 0.6, 2, i === 4 ? "#7a3a1a" : "#1d2a26", 1, pp); if (pp >= 1 && i < 3) stroke(c, loc(t.map(([x, y]) => [x - 1, y - 2.5] as P)).slice(1), 2.2, 0.6, "#4e8c7a", 0.7); });+ if (ph(3, n) > 0) reveal(c, [tx(-60), ty(-265), tx(50), ty(-165)], 0.3, ph(3, n), 1103, () => {+ G(S.body, "#8a3418", { tex: { cols: ["#b4502a", "#5a1e0e"], n: 60, len: 16, w: 3, ang: 0.3, a: 0.4 }, rim: "#3e150a", rimA: 0.5 });+ G(S.wing, "#6a2410", { tex: { cols: ["#9a4424", "#2e1208"], n: 40, len: 14, w: 3, ang: 0.15, a: 0.4 }, rim: "#2a0e06", rimA: 0.6 });+ for (let k = 0; k < 5; k++) stroke(c, loc([[14 + k * 5, -206 + k * 1.5], [26 + k * 4, -196 + k], [34 + k * 2, -190 + k]]), 4, 1.5, k % 2 ? "#1f2a24" : "#2e3a30", 0.9); // the primaries' dark tips+ for (let k = 0; k < 3; k++) stroke(c, loc([[-8 + k * 6, -214], [4 + k * 6, -208], [14 + k * 6, -202]]), 1.2, 0.5, "#c9703a", 0.6); // covert edges+ G(S.neck, "#e08a2a", { tex: { cols: ["#f6c25a", "#b35a18"], n: 50, len: 14, w: 2.5, ang: 1.1, a: 0.5 }, rim: "#7a3a10", rimA: 0.4 });+ for (let k = 0; k < 11; k++) { const t = k / 10; stroke(c, loc([[-40 + t * 18, -236 + t * 4], [-36 + t * 22, -220 + t * 6], [-32 + t * 24, -200 + t * 4 - Math.abs(t - 0.5) * 8]]), 2.4, 0.3, k % 3 ? "#f6c65e" : "#a8501a", 0.8); } // hackle feathers falling over the shoulder+ });+ if (ph(4, n) > 0) {+ const q = ph(4, n);+ G(S.headR, "#c4481c", { a: clamp(q * 3), rim: "#5a1a08", rimA: 0.5 });+ if (q > 0.3) { G(S.comb, "#d8231c", { rim: "#7a0e0a", rimA: 0.6, tex: { cols: ["#f0503a"], n: 8, len: 6, w: 2, ang: -1.4, a: 0.5 } }); G(S.wattle, "#cf221a", { rim: "#7a0e0a", rimA: 0.6 }); }+ if (q > 0.6) { G(S.beak, "#e0b040", { rim: "#8a6a1a", rimA: 0.6 }); c.fillStyle = "#f2b030"; c.beginPath(); c.arc(tx(-43), ty(-245), 2.6, 0, Math.PI * 2); c.fill(); c.fillStyle = "#1a0e08"; c.beginPath(); c.arc(tx(-43.4), ty(-245.2), 1.4, 0, Math.PI * 2); c.fill(); }+ if (q > 0.8) for (const x of [4, 12]) { stroke(c, loc([[x, -174], [x - 1, -160], [x - 2, -152]]), 3, 2.4, "#d9a63a", 1); for (const dx of [-5, 0, 4]) stroke(c, loc([[x - 2, -152], [x - 2 + dx, -147]]), 1.6, 1, "#c9962e", 1); }+ }+ // 5: his arms round the bird: the right hand cupped under the breast, the left hand on its back+ if (ph(5, n) > 0) {+ const q = ph(5, n), SKIN = "#f0c29a", SK2 = "#d6926c";+ G(S.sleeveL, "#b92c1c", { a: clamp(q * 2), tex: { cols: ["#e05a3a", "#7e1a12"], n: 30, len: 18, w: 3, ang: 2.6, a: 0.35 }, rim: "#6e1810", rimA: 0.5 });+ if (q > 0.4) {+ // right hand: palm under the breast, four finger tips curled up over it, the thumb along the side+ G([[-36, -168], [-24, -176], [-14, -176], [-12, -168], [-22, -162], [-34, -160]], SKIN, { rim: "#a0603e", rimA: 0.5 });+ for (let k = 0; k < 4; k++) stroke(c, loc([[-26 + k * 4, -172], [-24 + k * 4, -179], [-22 + k * 4, -181]]), 3.6, 2.8, k % 2 ? SK2 : SKIN, 1);+ stroke(c, loc([[-34, -166], [-36, -176], [-33, -182]]), 4, 3, SKIN, 1);+ // left hand on the back: back of the hand, four fingers over the wing, thumb tucked toward us+ G([[20, -206], [30, -204], [32, -196], [22, -192], [14, -196]], SKIN, { rim: "#a0603e", rimA: 0.5 });+ for (let k = 0; k < 4; k++) stroke(c, loc([[16 - k * 0.5, -205 + k * 3.4], [8 - k * 0.5, -203 + k * 3.6], [2 - k * 0.3, -199 + k * 3.6]]), 3.6, 2.8, k % 2 ? SK2 : SKIN, 1);+ stroke(c, loc([[22, -193], [16, -188], [11, -187]]), 4, 3, SKIN, 1);+ c.globalAlpha = 0.5; c.strokeStyle = "#e05a3a"; c.lineWidth = 2; c.beginPath(); c.moveTo(tx(33), ty(-206)); c.lineTo(tx(30), ty(-192)); c.stroke(); c.globalAlpha = 1; // the gathered cuff+ }+ }+ // 6: his head: skin, the shadow side, ears, the bowl-cut straw hair+ if (ph(6, n) > 0) reveal(c, [tx(-30), ty(-296), tx(30), ty(-230)], Math.PI / 2, ph(6, n), 1106, () => {+ G([[-6, -240], [6, -240], [7, -230], [-6, -230]], "#d9a07a");+ G(S.head, "#f2c59c", { tex: { cols: ["#f8d8b4", "#e0a47c"], n: 26, len: 10, w: 3, ang: 1.2, a: 0.3 }, rim: "#b0704a", rimA: 0.45, rimW: 1.4 });+ c.save(); trace(c, loc(S.head)); c.clip(); c.globalAlpha = 0.45; c.fillStyle = "#d8916a"; c.beginPath(); c.ellipse(tx(20), ty(-252), 14, 24, 0.2, 0, Math.PI * 2); c.fill(); c.restore(); c.globalAlpha = 1;+ for (const x of [-24, 24]) { G([[x - 4, -262], [x + 4 * Math.sign(x), -260], [x + 4 * Math.sign(x), -250], [x, -247]], x < 0 ? "#f2c09a" : "#dea27c", { rim: "#a0603e", rimA: 0.5 }); }+ G(S.hair, "#e9c265", { tex: { cols: ["#f7dc8c", "#b88a34", "#d0a445"], n: 70, len: 16, w: 2.2, ang: 1.5, jit: 0.9, a: 0.55 }, rim: "#8a6424", rimA: 0.5 });+ c.save(); trace(c, loc(S.hair)); c.clip(); c.globalAlpha = 0.4; c.fillStyle = "#a47a2c"; c.beginPath(); c.ellipse(tx(18), ty(-270), 14, 24, 0.3, 0, Math.PI * 2); c.fill(); c.globalAlpha = 0.5; c.fillStyle = "#fbe7a8"; c.beginPath(); c.ellipse(tx(-10), ty(-284), 10, 5, -0.3, 0, Math.PI * 2); c.fill(); c.restore(); c.globalAlpha = 1;+ for (let k = 0; k < 9; k++) { const x = -20 + k * 5; stroke(c, loc([[x, -288 + Math.abs(x) * 0.2], [x + 1, -276], [x + (k % 2 ? 2 : -1), -265]]), 1.2, 0.4, k % 2 ? "#b88a34" : "#8a6424", 0.55); }+ });+ // 7-8: the face, last: rosy cheeks, two dot eyes, a button nose, a small smile+ if (ph(7, n) > 0) {+ const q = ph(7, n);+ for (const x of [-12, 13]) { const gr = c.createRadialGradient(tx(x), ty(-247), 0, tx(x), ty(-247), 8); gr.addColorStop(0, rgba("#e8584a", 0.75 * q)); gr.addColorStop(0.6, rgba("#ec7a62", 0.4 * q)); gr.addColorStop(1, rgba("#f2a080", 0)); c.fillStyle = gr; c.fillRect(tx(x) - 9, ty(-256), 18, 18); }+ c.globalAlpha = q; c.fillStyle = "#e0987a"; c.beginPath(); c.ellipse(tx(1), ty(-251), 3.8, 3.2, 0, 0, Math.PI * 2); c.fill(); c.fillStyle = "#fbe0c8"; c.beginPath(); c.arc(tx(0), ty(-252.4), 1.2, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1;+ }+ if (ph(8, n) > 0) {+ const q = ph(8, n);+ for (const x of [-8, 9]) { c.globalAlpha = clamp(q * 2); c.fillStyle = "#2a1a10"; c.beginPath(); c.ellipse(tx(x), ty(-257), 2.4, 2.9, 0, 0, Math.PI * 2); c.fill(); c.fillStyle = "#fff6e6"; c.beginPath(); c.arc(tx(x - 0.8), ty(-258.2), 0.8, 0, Math.PI * 2); c.fill(); }+ for (const x of [-8, 9]) stroke(c, loc([[x - 4, -263], [x, -264.5], [x + 4, -263]]), 1.2, 0.8, "#9a6a34", 0.7 * clamp(q * 2));+ if (q > 0.5) { c.globalAlpha = 0.85; c.strokeStyle = "#8a3a2a"; c.lineWidth = 1.5; c.lineCap = "round"; c.beginPath(); c.moveTo(tx(-5), ty(-243.5)); c.quadraticCurveTo(tx(1), ty(-239), tx(6), ty(-243.5)); c.stroke(); c.globalAlpha = 1; }+ }+ void r;+};++// ---------------------------------------------------------------- the garden: pumpkins, sunflowers+const PUMPKINS: [number, number, number, number, number][] = [[706, 936, 46, 34, 1201], [338, 958, 88, 62, 1202], [582, 1010, 72, 52, 1203], [150, 1050, 100, 68, 1204]];+const GOURD_LEAVES: [number, number, number, number, number, number][] = [+ [470, 912, 96, -0.3, 0.62, 1301], [230, 905, 104, 0.4, 0.66, 1302], [800, 975, 84, 0.25, 0.6, 1303], [60, 940, 110, 0.3, 0.66, 1305], [640, 905, 70, -0.5, 0.6, 1309],+ [455, 1050, 100, -0.2, 0.7, 1304], [700, 1065, 92, 0.15, 0.7, 1306], [880, 1040, 70, -0.35, 0.62, 1307], [300, 1075, 86, 0.55, 0.7, 1308],+];+type SunPlant = { head: Sun; stalk: P[]; leaves: Leaf[]; petioles: P[][] };+// Helianthus: a thick bristly stalk, alternate heart-shaped leaves hanging on long petioles+// (the lower ones largest), the head turned to the sun on a stalk bent just under it.+const SUN_PLANTS: SunPlant[] = (() => {+ const mk = (hx: number, hy: number, r: number, rot: number, sq: number, base: P, d: number, seed: number, droop = 0, nl = 5): SunPlant => {+ const rr = rng(seed), stalk: P[] = [base, [base[0] + (hx - base[0]) * 0.4 + (rr() - 0.5) * 20, base[1] + (hy - base[1]) * 0.45], [hx + Math.sin(rot) * r * 0.4 + droop, hy + r * 0.9]];+ const leaves: Leaf[] = [], petioles: P[][] = []; const s = smooth(stalk, 8);+ for (let k = 0; k < nl; k++) {+ const t = 0.14 + k * (0.62 / nl), i = Math.round(t * (s.length - 1)), [x, y] = s[i], side = (k + seed) % 2 ? 1 : -1, size = r * (1 - k * 0.1);+ const pl = size * (0.55 + rr() * 0.25), pa = -Math.PI / 2 + side * (0.9 + rr() * 0.3), px = x + Math.cos(pa) * pl, py = y + Math.sin(pa) * pl * 0.8;+ petioles.push([[x, y], [x + Math.cos(pa) * pl * 0.55, y + Math.sin(pa) * pl * 0.55 - 4], [px, py]]);+ leaves.push({ x: px, y: py, a: side > 0 ? 0.55 + rr() * 0.55 : Math.PI - 0.55 - rr() * 0.55, len: size * (2.1 + rr() * 0.4), wid: size * (1.7 + rr() * 0.3), col: k % 2 ? "#4b7628" : "#557f2e", seed: seed * 10 + k, d, bend: side * 0.14, serr: 0.03, round: 0.7, cord: 0.14, tri: true, vein: "#86a860" });+ }+ return { head: { x: hx, y: hy, r, rot, sq, seed, d }, stalk, leaves, petioles };+ };+ return [+ mk(676, 640, 22, -0.15, 0.85, [684, 880], 0.36, 1401, 0, 2), mk(1790, 580, 24, -0.2, 0.85, [1775, 860], 0.36, 1402, 0, 2), mk(560, 620, 27, 0.1, 0.85, [548, 900], 0.3, 1403, 0, 3),+ mk(1700, 320, 58, -0.25, 0.9, [1690, 1090], 0.02, 1404, 0, 5), mk(1860, 470, 50, 0.35, 0.72, [1870, 1090], 0.0, 1405, 0, 4), mk(1540, 470, 44, -0.5, 0.78, [1580, 1090], 0.06, 1406, -10, 4),+ ];+})();+const paintSunPlant = (g: Gfx, S: SunPlant, p: number) => {+ const c = g.cur, d = S.head.d ?? 0, r = rng(S.head.seed + 3), sp = clamp(p * 3);+ limb(c, S.stalk, S.head.r * 0.32, S.head.r * 0.22, "#6a9234", S.head.seed, d, sp, 0.32, 0.8);+ if (sp >= 1 && d < 0.2) { const sm = smooth(S.stalk, 10); c.strokeStyle = far("#d6e0a0", d); c.lineWidth = 0.8; for (let i = 2; i < sm.length - 1; i += 1) for (const sg of [-1, 1]) { const w = S.head.r * 0.15 * sg, [x, y] = sm[i]; c.globalAlpha = 0.5 * r(); c.beginPath(); c.moveTo(x + w, y); c.lineTo(x + w * 1.35 + sg * 2, y - 3); c.stroke(); } c.globalAlpha = 1; }+ S.petioles.forEach((q, i) => stroke(c, q, S.head.r * 0.09, S.head.r * 0.05, far("#5f8a30", d), 1 - 0.5 * d, clamp(p * 3 - 1 - i * 0.2)));+ S.leaves.forEach((L, i) => leaf(c, L, clamp(p * 3 - 1.2 - i * 0.2)));+ sunflower(c, S.head, clamp(p * 1.6 - 0.6));+};+const sunLines = (S: SunPlant): Line[] => {+ const h = S.head, disc: P[] = []; for (let i = 0; i < 10; i++) { const th = (i / 10) * Math.PI * 2, x = Math.cos(th) * h.r, y = Math.sin(th) * h.r * h.sq; disc.push([h.x + x * Math.cos(h.rot) - y * Math.sin(h.rot), h.y + x * Math.sin(h.rot) + y * Math.cos(h.rot)]); }+ return [{ pts: S.stalk, seed: h.seed, a: 0.5 }, { pts: disc, seed: h.seed + 1, a: 0.55, closed: true }, ...S.leaves.map((L) => ({ pts: leafGeom(L).outline.filter((_, i) => i % 3 === 0), seed: L.seed, a: 0.45, closed: true, per: 3 } as Line))];+};++// ---------------------------------------------------------------- ground, grass, flowers+const meadowTop = (x: number) => 606 + Math.sin(x * 0.004) * 6;+const PATH: P[] = ribbonOf(smooth([[1060, 1100], [990, 980], [962, 880], [986, 800], [986, 756]], 10), (t) => 150 * (1 - t) ** 1.3 + 17);+const inPath = (x: number, y: number) => { for (let i = 0, j = PATH.length - 1, k = false; ; j = i++) { if (i >= PATH.length) return k; const a = PATH[i], b = PATH[j]; if (a[1] > y !== b[1] > y && x < ((b[0] - a[0]) * (y - a[1])) / (b[1] - a[1]) + a[0]) k = !k; } };+const paintMeadow = (g: Gfx, p: number) => {+ const c = g.cur, bb: Box = [0, 590, W, H];+ reveal(c, bb, 1.2, p, 1501, () => {+ const poly: P[] = [[0, meadowTop(0)], ...Array.from({ length: 21 }, (_, i) => [(W * i) / 20, meadowTop((W * i) / 20)] as P), [W, H], [0, H]];+ c.save(); trace(c, poly); c.clip();+ glowBand(c, bb, "#bcc56e", [[0, 0], [0.06, 0.25], [0.2, 0.45], [0.45, 0.7], [1, 0.85]]);+ glowBand(c, bb, "#6f9a3a", [[0, 0], [0.25, 0], [0.5, 0.45], [0.8, 0.8], [1, 0.95]]);+ glowBand(c, bb, "#3f6a26", [[0, 0], [0.55, 0], [0.8, 0.35], [1, 0.7]]);+ // the wood's shade under the birches+ const gr = c.createRadialGradient(200, 820, 20, 200, 820, 520); gr.addColorStop(0, rgba("#3f5e26", 0.45)); gr.addColorStop(1, rgba("#3f5e26", 0)); c.fillStyle = gr; c.fillRect(0, 590, 900, 490);+ // the brush's drag across the ground+ const rr = rng(1509); c.lineCap = "round"; for (let i = 0; i < 700; i++) { const x = rr() * W, y = 640 + rr() ** 0.7 * 440, near = (y - 640) / 440; c.strokeStyle = rr() < 0.5 ? rgba("#2e5418", 0.25 * near) : rgba("#c8d27a", 0.2 * (1 - near * 0.5)); c.lineWidth = 1.5 + near * 4; const l = 6 + near * 26 + rr() * 10, an = -1.35 + (rr() - 0.5) * 0.6; c.beginPath(); c.moveTo(x, y); c.lineTo(x + Math.cos(an) * l, y + Math.sin(an) * l); c.stroke(); }+ c.restore();+ });+};+const paintPath = (g: Gfx, p: number) => {+ const c = g.cur, bb = bbox(PATH) as Box;+ reveal(c, bb, -Math.PI / 2, p, 1502, () => {+ gouache(c, PATH, "#c9b283", { seed: 1503, wob: 14, tex: { cols: ["#e6d6a8", "#9e8a5e", "#b8a272"], n: 160, len: 40, w: 4, ang: -1.3, jit: 0.5, a: 0.4 }, rim: "#7e8a44", rimA: 0.35, rimW: 5 });+ c.save(); trace(c, PATH); c.clip(); for (const o of [-0.45, 0.45]) stroke(c, smooth([[1060, 1100], [990, 980], [962, 880], [986, 800], [986, 756]], 10).map(([x, y]) => [x + o * (150 * Math.max(0, (y - 756) / 344) ** 1.3 + 17) * 1.2, y] as P), 7, 2, "#9a845a", 0.35); c.restore();+ });+ c.globalAlpha = 1;+};+const GRASS_BANDS: Grass[] = (() => {+ const out: Grass[] = [];+ for (let b = 0; b < 4; b++) out.push({ x0: (W * b) / 4, x1: (W * (b + 1)) / 4, base: (x) => meadowTop(x) + 30, n: 700, h: [5, 16], w: 1.6, cols: ["#a9b86a", "#c2c985", "#8fa458"], lean: 0.1, seed: 1600 + b, d: 0.55, spread: 120, a: 0.8 });+ for (let b = 0; b < 6; b++) out.push({ x0: (W * b) / 6, x1: (W * (b + 1)) / 6, base: (x) => 752 - (x - 300) * 0.03, n: 900, h: [12, 38], w: 2.6, cols: ["#7fa044", "#9cb455", "#5f8634", "#b9c56a"], tip: "#d8dc8e", lean: 0.2, seed: 1620 + b, d: 0.2, spread: 120, clump: 4, skip: inPath, dry: "#c9b060" });+ return out;+})();+const FORE_GRASS: Grass[] = Array.from({ length: 8 }, (_, b) => ({ x0: (W * b) / 8 - 20, x1: (W * (b + 1)) / 8 + 20, base: () => 860, n: 1100, h: [34, 120], w: 4.4, cols: ["#5e8a30", "#76a03c", "#4a7428", "#8cb04a", "#3c6222"], tip: "#c9d880", lean: 0.22, seed: 1700 + b, d: 0, spread: 220, clump: 6, skip: inPath, dry: "#b8a050" }));+const FRINGE: Grass[] = Array.from({ length: 4 }, (_, b) => ({ x0: (W * b) / 4, x1: (W * (b + 1)) / 4, base: () => 1045, n: 360, h: [18, 60], w: 5, cols: ["#4a7428", "#5e8a30", "#3c6222", "#6f9a38"], tip: "#b9cc70", lean: 0.2, seed: 1760 + b, d: 0, spread: 40, clump: 5 }));+const DAISIES: [number, number, number][] = (() => { const r = rng(1800), out: [number, number, number][] = []; for (let i = 0; i < 110; i++) { const x = 60 + r() * 1800, y = 640 + r() * 430, near = (y - 640) / 430; if (x > 1500 && y < 900) continue; if (x < 900 && y > 880) continue; if (inPath(x, y)) continue; out.push([x, y, 2 + near * near * 13]); } return out.sort((a, b) => a[1] - b[1]); })();+const BELLS: [number, number, number, number][] = [[1160, 1000, 52, 0.3], [1236, 950, 44, -0.2], [1290, 1030, 62, 0.15], [1356, 960, 40, 0.4], [1420, 1040, 56, -0.1], [1100, 1060, 48, 0.25]];+const ROSES: [number, number, number, number][] = [[1410, 872, 24, 0.2], [1478, 836, 21, -0.4], [1356, 842, 18, 0.6], [1500, 900, 23, 0.1], [1448, 918, 16, 0.9]];+const paintFlowers = (g: Gfx, p: number) => {+ const c = g.cur;+ ROSES.forEach(([x, y, r, rot], i) => dogRose(c, x, y, r, rot, 0.8, 1950 + i, 0.02, clamp(p * 2 - i * 0.15)));+ BELLS.forEach(([x, y, s, a], i) => { const q = clamp(p * 2 - 1 + 0.4 - i * 0.05); if (q <= 0) return; const top: P = [x - 12 * Math.sign(a || 1), y - s * 1.7]; stroke(c, [[x + 6, 1090], [x, y + 20], [top[0] - 6, top[1] + 10], top], 2.6, 1.3, "#4a6a2a", 1, q); if (q > 0.4) { bell(c, top[0], top[1] + 2, s, a, 1900 + i, 0, "#5a6cc6", clamp((q - 0.4) / 0.6)); if (s > 32) bell(c, top[0] + s * 0.5, top[1] + s * 0.9, s * 0.7, a + 0.5, 1920 + i, 0, "#5264bc", clamp((q - 0.6) / 0.4)); } });+};+const ROSE_LEAVES: Leaf[] = (() => { const r = rng(1960), out: Leaf[] = []; for (let i = 0; i < 30; i++) out.push({ x: 1330 + r() * 210, y: 810 + r() * 130, a: r() * 6.28, len: 24 + r() * 12, wid: 15 + r() * 6, col: r() < 0.5 ? "#3f6a2c" : "#4d7a32", seed: 1961 + i, serr: 0.12, stalk: 3 }); return out; })();+// burdock by the bottom corner: the nearest thing in the picture, the richest paint+const BURDOCK: Leaf[] = [+ { x: 1560, y: 1090, a: -2.0, len: 170, wid: 118, col: "#3d6a28", seed: 2501, bend: -0.1, serr: 0.03, round: 0.75, cord: 0.18, vein: "#86a860", stalk: 10 },+ { x: 1640, y: 1095, a: -1.2, len: 190, wid: 124, col: "#46732c", seed: 2502, bend: 0.08, serr: 0.03, round: 0.75, cord: 0.18, vein: "#8eae66", stalk: 10 },+ { x: 1760, y: 1090, a: -0.6, len: 180, wid: 118, col: "#3a6426", seed: 2503, bend: 0.12, serr: 0.03, round: 0.75, cord: 0.18, vein: "#80a05a", stalk: 10 },+ { x: 1900, y: 1085, a: -1.7, len: 160, wid: 110, col: "#44702a", seed: 2504, bend: -0.1, serr: 0.03, round: 0.75, cord: 0.18, vein: "#86a860", stalk: 10 },+];++// a haystack (stog) raised round a pole in the meadow: a middle-distance thing, so thin paint that stops short of its own drawing+const STOG = { x: 1150, y: 648, w: 64, h: 92 };+const stogPoly = (): P[] => { const { x, y, w, h } = STOG; return smooth([[x - w / 2, y], [x - w * 0.52, y - h * 0.35], [x - w * 0.36, y - h * 0.75], [x - w * 0.08, y - h * 0.97], [x + w * 0.1, y - h * 0.96], [x + w * 0.38, y - h * 0.72], [x + w * 0.53, y - h * 0.3], [x + w / 2, y]], 6, true); };+const stogLines = (): Line[] => [{ pts: stogPoly(), seed: 2701, a: 0.55, closed: true, per: 2 }, { pts: [[STOG.x - 1, STOG.y - STOG.h * 0.96], [STOG.x + 2, STOG.y - STOG.h - 18]], seed: 2702, a: 0.55 }];+const paintStog = (g: Gfx, p: number) => {+ const { x, y, w, h } = STOG, bb: Box = [x - w, y - h - 30, x + w, y + 14], d = 0.45;+ faded(g, bb, (m) => ramp(m, bb, [0, y], [0, y - h * 1.1], [[0, 0.9], [0.6, 0.7], [1, 0.15]]), (k) => reveal(k, bb, -Math.PI / 2, p, 2703, () => {+ gouache(k, stogPoly(), far("#c9a860", d), { seed: 2704, tex: { cols: [far("#8a6c30", d), far("#ecd49a", d)], n: 70, len: 26, w: 2.5, ang: 1.35, jit: 0.5, a: 0.5 } });+ k.save(); trace(k, stogPoly()); k.clip(); k.globalAlpha = 0.5; k.fillStyle = far("#8a6a34", d); k.beginPath(); k.ellipse(x + w * 0.35, y - h * 0.4, w * 0.35, h * 0.6, 0.2, 0, Math.PI * 2); k.fill(); k.restore(); k.globalAlpha = 1;+ stroke(k, [[x - 1, y - h * 0.96], [x + 2, y - h - 18]], 3, 2, far("#6a5436", d), 0.9);+ k.globalAlpha = 0.25; k.fillStyle = far("#4a5a2a", d); k.beginPath(); k.ellipse(x + w * 0.35, y + 3, w * 0.7, 6, 0, 0, Math.PI * 2); k.fill(); k.globalAlpha = 1;+ }));+};+// swallows skimming low before the evening: three pencil ticks over the cottage+const swallow = (x: number, y: number, s: number, tilt: number, seed: number): Line[] => { const c = Math.cos(tilt), sn = Math.sin(tilt), T = (px: number, py: number): P => [x + (px * c - py * sn) * s, y + (px * sn + py * c) * s]; return [{ pts: [T(-10, -3), T(-5, -1), T(0, 1), T(5, -1), T(10, -4)], seed, a: 0.7, w: 1.1, retrace: false }, { pts: [T(0, 1), T(0.6, 4), T(-0.8, 6)], seed: seed + 1, a: 0.6, w: 0.9, retrace: false }]; };+const SWALLOWS: Line[] = [...swallow(1250, 300, 1.6, 0.15, 2801), ...swallow(1330, 262, 1.2, -0.2, 2803), ...swallow(1196, 352, 1.0, 0.3, 2805)];++// ---------------------------------------------------------------- the process+const SKETCH: Line[][] = [+ [...FAR, ...SWALLOWS],+ BIRCHES.flatMap(birchLines),+ stogLines(),+ cottageLines(),+ FENCES.flatMap(fenceLines),+ [{ pts: PATH.slice(0, PATH.length / 2).filter((_, i) => i % 4 === 0), seed: 2601, a: 0.35 }, { pts: PATH.slice(PATH.length / 2).filter((_, i) => i % 4 === 0), seed: 2602, a: 0.35 }],+ boyLines(),+ [...PUMPKINS.map(([x, y, rx, ry, s]) => ({ pts: Array.from({ length: 12 }, (_, i) => [x + Math.cos((i / 12) * 6.283) * rx, y + Math.sin((i / 12) * 6.283) * ry] as P), seed: s, a: 0.5, closed: true } as Line)), ...GOURD_LEAVES.map(([x, y, s, rot, , seed]) => ({ pts: Array.from({ length: 9 }, (_, i) => { const th = -2.9 + (i / 8) * 5.8; return [x + Math.sin(th + rot) * s, y - Math.cos(th + rot) * s * 0.6] as P; }), seed, a: 0.35 } as Line))],+ SUN_PLANTS.flatMap(sunLines),+ BURDOCK.map((L) => ({ pts: leafGeom(L).outline.filter((_, i) => i % 3 === 0), seed: L.seed, a: 0.45, closed: true, per: 3 } as Line)),+ SPRAYS.filter((s) => s.d > 0.3).flatMap(sprayLines),+];+const ground = (g: Gfx) => sheet(g, [[980, 600, 820, "#fbf3d6"]]);+const finish = (g: Gfx) => { g.paper("paper", 0.14); g.paper("coldpress", 0.07); };+const build = (k: number): Proc => {+ const tl = timeline(4, k, true), add = (dur: number, fn: (g: Gfx, p: number) => void) => tl.add(dur, fn);+ // 1. the pencil drawing of the whole picture, big shapes first+ SKETCH.forEach((lines, i) => { const L = lines.reduce((a, l) => a + l.pts.length, 0); add(Math.max(10, Math.min(38, L / 14)), (g, p) => sketch(g.cur, lines, p)); if (i === 0) tl.wait(4); });+ tl.wait(10);+ // 2. paint, back to front+ add(14, (g, p) => reveal(g.cur, [0, 0, W, 640], 0.2, p, 2001, () => { const c = g.cur, gr = c.createRadialGradient(960, 600, 30, 960, 600, 760); gr.addColorStop(0, rgba("#f7e2a0", 0.42)); gr.addColorStop(0.5, rgba("#f6ebc4", 0.18)); gr.addColorStop(1, rgba("#f3e3a8", 0)); c.fillStyle = gr; c.fillRect(0, 0, W, 640); }));+ add(16, paintMeadow);+ GRASS_BANDS.slice(0, 4).forEach((G) => add(5, (g, p) => grass(g.cur, G, p)));+ BIRCHES.forEach((b) => { if (b.d < 0.95) add(4 + (1 - b.d) * 6, (g, p) => paintBirch(g, b, p)); });+ add(20, paintCottage);+ add(10, paintStog);+ add(10, (g, p) => reveal(g.cur, [0, 540, W, 760], 0, p, 2002, () => glowBand(g.cur, [0, 540, W, 760], "#faf0d4", [[0, 0], [0.3, 0.55], [0.5, 0.7], [0.8, 0.25], [1, 0]]))); // the golden haze+ SUN_PLANTS.slice(0, 3).forEach((S) => add(10, (g, p) => paintSunPlant(g, S, p)));+ FENCES.forEach((F) => add(14, (g, p) => paintFence(g, F, p)));+ for (let i = 0; i < SPRAYS.length; i += 3) { const batch = SPRAYS.slice(i, i + 3); add(3.2, (g, p) => batch.forEach((S, j) => paintSpray(g, S, clamp(p * batch.length - j)))); }+ add(10, paintPath);+ GRASS_BANDS.slice(4).forEach((G) => add(4, (g, p) => grass(g.cur, G, p)));+ add(8, (g, p) => DAISIES.filter(([, y]) => y < 840).forEach(([x, y, r], i, A) => daisy(g.cur, x, y, r, 2100 + i, clamp(1 - (y - 640) / 260) * 0.5, 0.6, clamp(p * A.length - i))));+ add(46, paintBoy);+ tl.wait(6);+ FORE_GRASS.forEach((G) => add(4.5, (g, p) => grass(g.cur, G, p)));+ GOURD_LEAVES.slice(0, 5).forEach(([x, y, s, rot, sq, seed]) => add(5, (g, p) => gourdLeaf(g.cur, x, y, s, rot, sq, "#3f6c26", seed, 0.04, p)));+ PUMPKINS.forEach(([x, y, rx, ry, seed], i) => add(8, (g, p) => pumpkin(g.cur, x, y, rx, ry, seed, i === 0 ? 0.18 : 0, p)));+ GOURD_LEAVES.slice(5).forEach(([x, y, s, rot, sq, seed]) => add(5, (g, p) => gourdLeaf(g.cur, x, y, s, rot, sq, "#3a6624", seed, 0, p)));+ add(8, (g, p) => [[420, 930, -0.4], [640, 960, 3.6], [820, 1000, -0.9], [260, 990, 3.9]].forEach(([x, y, a], i) => tendril(g.cur, x, y, 60, a, 2200 + i, "#6a8a34", 0, clamp(p * 4 - i))));+ SUN_PLANTS.slice(3).forEach((S) => add(24, (g, p) => paintSunPlant(g, S, p)));+ add(12, (g, p) => ROSE_LEAVES.forEach((L, i) => leaf(g.cur, L, clamp(p * ROSE_LEAVES.length / 3 - i / 3))));+ add(14, paintFlowers);+ BURDOCK.forEach((L) => add(8, (g, p) => leaf(g.cur, L, p)));+ FRINGE.forEach((G) => add(3, (g, p) => grass(g.cur, G, p)));+ add(10, (g, p) => DAISIES.filter(([, y]) => y >= 840).forEach(([x, y, r], i, A) => daisy(g.cur, x, y, r, 2300 + i, 0, 0.6, clamp(p * A.length - i))));+ add(8, (g, p) => [[800, 900, 38], [860, 930, 30], [760, 950, 26]].forEach(([x, y, r], i) => { stroke(g.cur, [[x + 10, 1080], [x + 4, y + 60], [x, y]], 2, 1.2, "#2f3320", 0.8, clamp(p * 3 - i)); umbel(g.cur, x, y, r, 2400 + i, "#2f3320", clamp(p * 3 - i - 0.5)); }));+ return { id: "folkTale", medium: FT_M, ground, ops: tl.ops, finish };+};+const PROC = fit(build, N - 31), END = PROC.ops[PROC.ops.length - 1].t1;++export const STYLE = { id: "folkTale", name: "Folk-tale storybook", family: "paint", medium: "gouache and watercolour over an HB pencil drawing on cream cartridge: opaque, dry-brushed paint in the foreground thinning to a pale wash and then to bare pencil in the distance", nearest: "storybook", hero: "a boy carrying a rooster through a village kitchen garden at the edge of a birch wood" };++export const folkTale: Film = {+ meta: { title: "The boy with the rooster · folk-tale storybook", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu", kind: "drawing", holds: [[N - 30, N]] },+ assets: { images: {} },+ shots: [{ id: "paint", start: 0, end: N, draw: (ctx, f, env) => runProcess(PROC, ctx, Math.min(f, END), env) }],+};+void HAZE; void lineLeaf; void pencil;diff --git a/engine/src/canvas-core/folkTaleKit.ts b/engine/src/canvas-core/folkTaleKit.tsnew file mode 100644index 0000000..078e3d4--- /dev/null+++ b/engine/src/canvas-core/folkTaleKit.ts@@ -0,0 +1,435 @@+// FOLK-TALE KIT. The marks of a Russian folk-tale storybook painting, where DEPTH IS THE MEDIUM:+// the same object is painted opaque and rich in the foreground, thin and pale in the middle+// distance, and left as a bare graphite drawing on the cream sheet at the back.+//+// Every mark here takes a depth `d` (0 = at the viewer's feet, 1 = the horizon) and a progress+// `p` (0..1, exactly the finished mark at 1). Depth mixes colour toward the warm haze, thins the+// paint, drops the texture, and past ~0.9 leaves only the pencil.+//+// Kit primitives written for this plate (candidates for promotion to core):+// pencil / sketch graphite line with pressure breaks and a faint retrace; a list of lines drawn in order, paced by length+// gouache an opaque body-colour fill with dry-brush drags, sponge mottle and a darker settled rim, clipped to the shape+// reveal a wet brush front sweeping across a wash (a noisy clip), so a big area is PAINTED rather than faded in+// faded paint an element on a scratch layer and dissolve it by a gradient mask: paint thinning to bare drawing+// leaf / lineLeaf painted leaf (two-tone halves, midrib, side veins, mottle, rim) / the same leaf in pencil+// petal, sunflower, daisy, bell, dogRose, umbel, blade/grass, limb, pumpkin, gourdLeaf, tendril+import { fractal, rng, sample, type Ctx, type Env, type Gfx, type Layer, type P } from "./core";+import { clamp, mix } from "./gallery";++export const PAPER = "#f4edda", HAZE = "#f2e9c9", GRAPH = "#6f665a";+export const LIGHT: P = [-0.6, -0.8]; // toward the sun: low, upper left++export const lighten = (c: string, k: number) => mix(c, "#fffbe8", clamp(k));+export const darken = (c: string, k: number) => mix(c, "#17170d", clamp(k));+export const far = (c: string, d: number) => mix(c, HAZE, clamp(d) * 0.85);++// ---------------------------------------------------------------- geometry+export type Box = [number, number, number, number];+export const bbox = (pts: P[]): Box => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } return [x0, y0, x1, y1]; };+export const trace = (c: Ctx, pts: P[], closed = true) => { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); if (closed) c.closePath(); };+export const len = (s: P[]) => { let l = 0; for (let i = 1; i < s.length; i++) l += Math.hypot(s[i][0] - s[i - 1][0], s[i][1] - s[i - 1][1]); return l; };+export const cutAt = (s: P[], p: number): P[] => {+ if (p >= 1) return s; if (p <= 0) return s.slice(0, 1);+ const n = (s.length - 1) * p, i = Math.floor(n), f = n - i, out = s.slice(0, i + 1);+ if (f > 1e-9 && i + 1 < s.length) out.push([s[i][0] + (s[i + 1][0] - s[i][0]) * f, s[i][1] + (s[i + 1][1] - s[i][1]) * f]);+ return out;+};+const tan = (s: P[], i: number): P => { const a = s[Math.max(0, i - 1)], b = s[Math.min(s.length - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1; return [dx / l, dy / l]; };+// centreline + half-width -> closed outline (left side out, right side back)+export const ribbonOf = (s: P[], hw: (t: number) => number): P[] => {+ const L: P[] = [], R: P[] = [], n = s.length;+ for (let i = 0; i < n; i++) { const t = i / Math.max(1, n - 1), [dx, dy] = tan(s, i), w = hw(t); L.push([s[i][0] - dy * w, s[i][1] + dx * w]); R.push([s[i][0] + dy * w, s[i][1] - dx * w]); }+ return [...L, ...R.reverse()];+};+export const smooth = (pts: P[], per = 8, closed = false) => sample(pts, closed, per);+export const at = (x: number, y: number, a: number, r: number): P => [x + Math.cos(a) * r, y + Math.sin(a) * r];++// ---------------------------------------------------------------- pencil+// Graphite on a cream cartridge sheet: a soft HB line whose weight and darkness breathe with the+// pressure of the hand (noise along its length), lighter where it starts and lifts, with a faint+// second pass that does not quite sit on the first.+export type Line = { pts: P[]; seed: number; w?: number; a?: number; closed?: boolean; per?: number; col?: string; retrace?: boolean };+export const pencil = (c: Ctx, L: Line, p = 1) => {+ if (p <= 0 || L.pts.length < 2) return;+ const { w = 1.1, a = 0.72, seed, closed = false, per = 6, col = GRAPH, retrace = true } = L, r = rng(seed * 13 + 1);+ const ctrl = closed ? [...L.pts, L.pts[0]] : L.pts;+ const pass = (jit: number, alpha: number, wk: number, sd: number) => {+ const j = ctrl.map(([x, y]) => [x + (r() - 0.5) * jit, y + (r() - 0.5) * jit] as P), s = sample(j, false, per), n = s.length, m = p >= 1 ? n : Math.max(2, Math.ceil(n * p));+ c.strokeStyle = col; c.lineCap = "round"; c.lineJoin = "round";+ for (let i = 0; i < m - 1; i += 3) {+ const t = i / Math.max(1, n - 1), nz = fractal(sd, i * 0.19, 3.7, 1, 1, 2), end = Math.min(1, t / 0.07 + 0.4, (1 - t) / 0.09 + 0.35);+ c.globalAlpha = alpha * clamp(0.4 + 0.85 * nz) * end; c.lineWidth = w * wk * (0.7 + 0.6 * nz);+ c.beginPath(); c.moveTo(s[i][0], s[i][1]); for (let k = i + 1; k <= Math.min(m - 1, i + 3); k++) c.lineTo(s[k][0], s[k][1]); c.stroke();+ }+ };+ pass(0.9, a, 1, seed);+ if (retrace) pass(1.8, a * 0.3, 0.6, seed + 77);+ c.globalAlpha = 1;+};+// a sketch is lines drawn one after another; each gets time in proportion to its length+export const sketch = (c: Ctx, lines: Line[], p: number) => {+ if (p <= 0) return; if (p >= 1) { lines.forEach((l) => pencil(c, l, 1)); return; }+ const ls = lines.map((l) => len(l.pts) + 12), tot = ls.reduce((a, b) => a + b, 0); let acc = 0; const at = p * tot;+ for (let i = 0; i < lines.length; i++) { if (acc >= at) break; pencil(c, lines[i], clamp((at - acc) / ls[i])); acc += ls[i]; }+};++// ---------------------------------------------------------------- paint+// A dry-brush drag: a nearly spent flat brush leaves three or four bristle lines that break.+const drag = (c: Ctx, x: number, y: number, ang: number, l: number, w: number, a: number, r: () => number) => {+ const dx = Math.cos(ang), dy = Math.sin(ang), nx = -dy, ny = dx, k = 3 + Math.floor(r() * 2), bow = (r() - 0.5) * l * 0.18;+ for (let b = 0; b < k; b++) {+ const off = (b - (k - 1) / 2) * w * 0.5 + (r() - 0.5) * w * 0.3, l0 = l * r() * 0.3, l1 = l * (0.6 + r() * 0.4);+ c.globalAlpha = a * (0.3 + 0.7 * r()); c.lineWidth = w * (0.22 + 0.3 * r());+ const x0 = x + dx * l0 + nx * off, y0 = y + dy * l0 + ny * off, x1 = x + dx * l1 + nx * off, y1 = y + dy * l1 + ny * off;+ c.beginPath(); c.moveTo(x0, y0); c.quadraticCurveTo((x0 + x1) / 2 + nx * bow, (y0 + y1) / 2 + ny * bow, x1, y1); c.stroke();+ }+};+export type Tex = { cols: string[]; n: number; len: number; w: number; ang: number; jit?: number; a?: number };+export type Mottle = { cols: string[]; n: number; r: number; a?: number; freq?: number };+export type Gouache = { seed: number; a?: number; tex?: Tex; mottle?: Mottle; rim?: string; rimW?: number; rimA?: number; wob?: number };+// Opaque body colour. The shape's edge wobbles as a brush-cut edge does, the paint is dragged+// dry over itself inside the shape, and it settles slightly darker along its rim.+export const gouache = (c: Ctx, poly: P[], col: string, o: Gouache) => {+ const { seed, a = 1, wob = 0 } = o, r = rng(seed * 7 + 5);+ const s = wob ? poly.map(([x, y]) => [x + (fractal(seed, x * 0.05, y * 0.05, 1, 1, 2) - 0.5) * wob, y + (fractal(seed + 3, x * 0.05, y * 0.05, 1, 1, 2) - 0.5) * wob] as P) : poly;+ c.globalAlpha = a; c.fillStyle = col; trace(c, s); c.fill();+ if (!o.tex && !o.mottle && !o.rim) { c.globalAlpha = 1; return; }+ c.save(); trace(c, s); c.clip();+ const [x0, y0, x1, y1] = bbox(s), bw = x1 - x0, bh = y1 - y0;+ if (o.tex) { const t = o.tex; c.lineCap = "round"; for (let i = 0; i < t.n; i++) { c.strokeStyle = t.cols[i % t.cols.length]; drag(c, x0 + r() * bw, y0 + r() * bh, t.ang + (r() - 0.5) * (t.jit ?? 0.3), t.len * (0.5 + r() * 0.7), t.w, (t.a ?? 0.35) * a, r); } }+ if (o.mottle) {+ const m = o.mottle, fq = m.freq ?? 0.06;+ for (let i = 0, tries = 0; i < m.n && tries < m.n * 4; tries++) {+ const x = x0 + r() * bw, y = y0 + r() * bh; if (fractal(seed + 11, x * fq, y * fq, 1, 1, 2) < 0.47 + r() * 0.12) continue; i++;+ const rr = m.r * (0.35 + r() * 0.8); c.globalAlpha = (m.a ?? 0.4) * (0.4 + 0.6 * r()) * a; c.fillStyle = m.cols[i % m.cols.length];+ c.beginPath(); c.ellipse(x, y, rr, rr * (0.55 + r() * 0.4), r() * 3, 0, Math.PI * 2); c.fill();+ }+ }+ if (o.rim) { c.globalAlpha = (o.rimA ?? 0.4) * a; c.strokeStyle = o.rim; c.lineWidth = (o.rimW ?? 2) * 2; c.lineJoin = "round"; trace(c, s); c.stroke(); }+ c.restore(); c.globalAlpha = 1;+};+// the brush front: clip to the part of the plane a sweep along `ang` has reached at progress p+export const reveal = (c: Ctx, box: Box, ang: number, p: number, seed: number, fn: () => void) => {+ if (p >= 1) { fn(); return; } if (p <= 0) return;+ const dx = Math.cos(ang), dy = Math.sin(ang), cs: P[] = [[box[0], box[1]], [box[2], box[1]], [box[0], box[3]], [box[2], box[3]]];+ let u0 = 1e9, u1 = -1e9, v0 = 1e9, v1 = -1e9; cs.forEach(([x, y]) => { const u = x * dx + y * dy, v = -x * dy + y * dx; u0 = Math.min(u0, u); u1 = Math.max(u1, u); v0 = Math.min(v0, v); v1 = Math.max(v1, v); });+ const amp = Math.min(60, (u1 - u0) * 0.12 + 6), thr = u0 - amp + (u1 - u0 + 2 * amp) * p, pts: P[] = [], toXY = (u: number, v: number): P => [u * dx - v * dy, u * dy + v * dx];+ pts.push(toXY(u0 - 50, v0 - 50));+ for (let v = v0 - 50; v <= v1 + 50; v += 8) pts.push(toXY(thr + (fractal(seed, v * 0.018, p * 2, 1, 1, 2) - 0.5) * amp * 2, v));+ pts.push(toXY(thr, v1 + 50), toXY(u0 - 50, v1 + 50));+ c.save(); trace(c, pts); c.clip(); fn(); c.restore();+};+// paint that thins out into bare drawing: draw on a scratch sheet, keep it through a gradient mask+export const faded = (g: Gfx, box: Box, mask: (m: Ctx) => void, draw: (c: Ctx) => void) => {+ const e = g.env, k = e.scale, DW = Math.round(e.W * k), DH = Math.round(e.H * k), key = `ftk:scratch:${DW}x${DH}`;+ let L = e.cache.get(key) as Layer | undefined; if (!L) { L = e.canvas(DW, DH); e.cache.set(key, L); }+ const x0 = Math.max(0, Math.floor(box[0] * k) - 2), y0 = Math.max(0, Math.floor(box[1] * k) - 2), x1 = Math.min(DW, Math.ceil(box[2] * k) + 2), y1 = Math.min(DH, Math.ceil(box[3] * k) + 2);+ if (x1 <= x0 || y1 <= y0) return;+ const s = L.ctx; s.save(); s.setTransform(1, 0, 0, 1, 0, 0); s.globalAlpha = 1; s.globalCompositeOperation = "source-over"; s.clearRect(x0, y0, x1 - x0, y1 - y0);+ s.beginPath(); s.rect(x0, y0, x1 - x0, y1 - y0); s.clip(); s.setTransform(k, 0, 0, k, 0, 0); draw(s);+ s.globalAlpha = 1; s.globalCompositeOperation = "destination-in"; mask(s); s.restore();+ const c = g.cur; c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; c.drawImage(L.canvas as CanvasImageSource, x0, y0, x1 - x0, y1 - y0, x0, y0, x1 - x0, y1 - y0); c.restore();+};+// a mask helper: a linear ramp of opacity across a box (stops as [t, alpha])+export const ramp = (m: Ctx, box: Box, a: P, b: P, stops: [number, number][]) => {+ const gr = m.createLinearGradient(a[0], a[1], b[0], b[1]); stops.forEach(([t, v]) => gr.addColorStop(t, `rgba(0,0,0,${clamp(v)})`));+ m.fillStyle = gr; m.fillRect(box[0] - 4, box[1] - 4, box[2] - box[0] + 8, box[3] - box[1] + 8);+};+export const radial = (m: Ctx, box: Box, cx: number, cy: number, r0: number, r1: number, stops: [number, number][], sy = 1) => {+ m.save(); m.translate(cx, cy); m.scale(1, sy); const gr = m.createRadialGradient(0, 0, r0, 0, 0, r1); stops.forEach(([t, v]) => gr.addColorStop(t, `rgba(0,0,0,${clamp(v)})`));+ m.fillStyle = gr; m.fillRect(-1e4, -1e4, 2e4, 2e4); m.restore(); void box;+};+// a soft wash of colour: a gradient band laid with the brush front+export const glowBand = (c: Ctx, box: Box, col: string, stops: [number, number][], vertical = true) => {+ const gr = vertical ? c.createLinearGradient(0, box[1], 0, box[3]) : c.createLinearGradient(box[0], 0, box[2], 0);+ const [r, g, b] = [1, 3, 5].map((i) => parseInt(col.slice(i, i + 2), 16)); stops.forEach(([t, v]) => gr.addColorStop(t, `rgba(${r},${g},${b},${clamp(v)})`));+ c.globalAlpha = 1; c.fillStyle = gr; c.fillRect(box[0], box[1], box[2] - box[0], box[3] - box[1]);+};+export const rgba = (col: string, a: number) => { const [r, g, b] = [1, 3, 5].map((i) => parseInt(col.slice(i, i + 2), 16)); return `rgba(${r},${g},${b},${clamp(a)})`; };++// a tapered painted stroke (stems, twigs, blades, veins): a ribbon, grown from its base+export const stroke = (c: Ctx, ctrl: P[], w0: number, w1: number, col: string, a = 1, p = 1, per = 6) => {+ if (p <= 0) return; const s = cutAt(smooth(ctrl, per), p), full = p >= 1;+ const poly = ribbonOf(s, (t) => { const tt = full ? t : t * p; return Math.max(0.15, (w0 + (w1 - w0) * tt) / 2); });+ c.globalAlpha = a; c.fillStyle = col; trace(c, poly); c.fill(); c.globalAlpha = 1;+};++// ---------------------------------------------------------------- leaves+export type Leaf = { x: number; y: number; a: number; len: number; wid: number; col: string; seed: number; bend?: number; d?: number; serr?: number; vein?: string; stalk?: number; round?: number; cord?: number; tri?: boolean };+// A leaf is authored on its axis: attachment at t = 0, tip at t = 1. A cordate leaf's blade+// starts BEHIND the attachment (t = -cord), which gives the rounded lobes either side of the stalk.+export const leafGeom = (L: Leaf) => {+ const n = L.serr ? 30 : 16, ux = Math.cos(L.a), uy = Math.sin(L.a), vx = -uy, vy = ux, st = L.stalk ?? 0, bend = L.bend ?? 0, round = L.round ?? 0.78, cord = L.cord ?? 0;+ const c: P[] = [], ts: number[] = [];+ for (let i = 0; i < n; i++) { const t = -cord + ((1 + cord) * i) / (n - 1), u = st + L.len * t, v = bend * L.len * Math.max(0, t) ** 2; c.push([L.x + ux * u + vx * v, L.y + uy * u + vy * v]); ts.push(t); }+ const hw = (i: number) => { const uu = (ts[i] + cord) / (1 + cord), b = (L.wid / 2) * Math.pow(Math.sin(Math.PI * Math.pow(Math.min(1, uu), round)), cord ? 0.5 : 0.85); return L.serr ? b * (1 + (i % 2 ? L.serr : -L.serr * 0.4)) : b; };+ const left: P[] = [], right: P[] = [];+ c.forEach((p, i) => { const [dx, dy] = tan(c, i), w = hw(i); left.push([p[0] - dy * w, p[1] + dx * w]); right.push([p[0] + dy * w, p[1] - dx * w]); });+ const ia = Math.round((cord / (1 + cord)) * (n - 1)), idx = (t: number) => Math.max(0, Math.min(n - 1, Math.round(((t + cord) / (1 + cord)) * (n - 1))));+ return { c, left, right, outline: [...left, ...right.slice().reverse()], n, ia, idx };+};+// the sun side of a leaf: whichever half's normal faces the light+const litLeft = (L: Leaf) => { const vx = -Math.sin(L.a), vy = Math.cos(L.a); return vx * LIGHT[0] + vy * LIGHT[1] > 0; };+const lerpP = (a: P, b: P, t: number): P => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];+export const leaf = (c: Ctx, L: Leaf, p = 1) => {+ if (p <= 0) return; const d = L.d ?? 0;+ if (d >= 0.93) { lineLeaf(c, L, p); return; }+ const G = leafGeom(L), grow = clamp(p / 0.6), det = clamp((p - 0.6) / 0.4), r = rng(L.seed), a = 1 - 0.5 * d;+ const lit = far(lighten(L.col, 0.16), d), shd = far(darken(L.col, 0.2), d), k = Math.max(2, Math.ceil(G.n * grow));+ const halfL = [...G.c.slice(0, k), ...G.left.slice(0, k).reverse()], halfR = [...G.c.slice(0, k), ...G.right.slice(0, k).reverse()], ll = litLeft(L);+ if (L.stalk) stroke(c, [[L.x, L.y], G.c[G.ia]], Math.max(1.6, L.wid * 0.05), Math.max(1.2, L.wid * 0.04), far(darken(L.col, 0.2), d), a);+ const mid = far(L.col, d);+ gouache(c, halfL, ll ? mix(mid, lit, 0.55) : mix(mid, shd, 0.55), { seed: L.seed, a }); gouache(c, halfR, ll ? mix(mid, shd, 0.55) : mix(mid, lit, 0.55), { seed: L.seed + 1, a });+ // the brush lay-in: strokes pulled from the midrib out along the side veins, each half in its own light+ if (grow >= 1 && d < 0.85) for (const [half, side, isLit] of [[halfL, G.left, ll], [halfR, G.right, !ll]] as [P[], P[], boolean][]) {+ c.save(); trace(c, half); c.clip(); const ns = Math.round(Math.max(5, L.len / 4.5) * (1 - d * 0.5));+ for (let i = 0; i < ns; i++) { const t = 0.02 + r() * 0.95, bi = G.idx(t), base = G.c[bi], e = side[G.idx(Math.min(1, t + 0.1))], from = lerpP(base, e, r() * 0.25), to = lerpP(base, e, 0.65 + r() * 0.45), col = isLit ? mix(lit, lighten(L.col, 0.35), r() * 0.6) : mix(shd, darken(L.col, 0.4), r() * 0.6);+ stroke(c, [from, lerpP(from, to, 0.5), to], Math.max(1.4, L.wid * (0.07 + r() * 0.08)), Math.max(0.6, L.wid * 0.03), far(col, d), (0.3 + r() * 0.35) * a, 1, 3); }+ c.restore();+ }+ if (det <= 0) return;+ const O = G.outline, area = L.len * L.wid * 0.6, tex = 1 - d, [bx0, by0, bx1, by1] = bbox(O);+ c.save(); trace(c, O); c.clip(); c.lineCap = "round";+ // dry-brush texture: short drags along the leaf, darker, then light flecks where the brush skipped+ const nd = Math.round((area / 90) * det * tex);+ for (let i = 0; i < nd; i++) { c.strokeStyle = r() < 0.5 ? darken(L.col, 0.3) : lighten(L.col, 0.08); const x = bx0 + r() * (bx1 - bx0), y = by0 + r() * (by1 - by0); c.globalAlpha = (0.1 + r() * 0.16) * a; c.lineWidth = 1 + r() * Math.max(1, L.wid * 0.04); const an = L.a + (r() < 0.5 ? 0.7 : -0.7) + (r() - 0.5) * 0.5, l = L.wid * (0.08 + r() * 0.18); c.beginPath(); c.moveTo(x, y); c.lineTo(x + Math.cos(an) * l, y + Math.sin(an) * l); c.stroke(); }+ const nm = Math.round((area / 22) * det * tex);+ for (let i = 0, t = 0; i < nm && t < nm * 4; t++) { const x = bx0 + r() * (bx1 - bx0), y = by0 + r() * (by1 - by0); if (fractal(L.seed, x * 0.08, y * 0.08, 1, 1, 2) < 0.52) continue; i++; const l = 0.8 + r() * Math.max(1.2, L.wid * 0.05), an = r() * 3.14; c.globalAlpha = (0.14 + r() * 0.24) * a; c.strokeStyle = r() < 0.7 ? lighten(L.col, 0.45) : darken(L.col, 0.4); c.lineWidth = 0.6 + r() * Math.max(0.6, L.wid * 0.022); c.beginPath(); c.moveTo(x, y); c.lineTo(x + Math.cos(an) * l, y + Math.sin(an) * l); c.stroke(); }+ // veins: the midrib, side veins leaving it outward and curving toward the tip, fading at the margin+ const vcol = far(L.vein ?? lighten(L.col, 0.42), d), nv = Math.max(3, Math.min(8, Math.round(L.len / 20))), shown = Math.round(nv * det), vw = Math.max(0.55, L.wid * 0.022);+ stroke(c, G.c.slice(G.ia, Math.max(G.ia + 2, G.idx(0.94))), Math.max(0.9, L.wid * 0.045), 0.3, vcol, 0.75 * a, det);+ if (L.tri) for (const side of [G.left, G.right]) stroke(c, [G.c[G.ia], lerpP(G.c[G.idx(0.1)], side[G.idx(0.12)], 0.6), lerpP(G.c[G.idx(0.45)], side[G.idx(0.5)], 0.72)], vw * 1.4, 0.3, vcol, 0.6 * a, det);+ for (let i = 0; i < shown; i++) {+ const t = 0.1 + (0.72 * (i + 0.5)) / nv, bi = G.idx(t), base = G.c[bi], fwd = G.idx(Math.min(1, t + 0.16));+ for (const side of [G.left, G.right]) stroke(c, [base, lerpP(base, side[bi], 0.5), lerpP(base, side[fwd], 0.8)], vw, 0.2, vcol, (0.28 + r() * 0.18) * a);+ }+ // the settled rim+ c.globalAlpha = 0.3 * a * det; c.strokeStyle = far(darken(L.col, 0.5), d); c.lineWidth = Math.max(1.2, L.wid * 0.03); trace(c, O); c.stroke();+ c.restore(); c.globalAlpha = 1;+};+export const lineLeaf = (c: Ctx, L: Leaf, p = 1, wash?: string) => {+ const G = leafGeom(L);+ if (wash && p >= 0.5) { c.globalAlpha = 0.35; c.fillStyle = wash; trace(c, G.outline); c.fill(); c.globalAlpha = 1; }+ pencil(c, { pts: G.outline.filter((_, i) => i % 2 === 0), seed: L.seed, w: 0.8, a: 0.55, closed: true, per: 4, retrace: false }, clamp(p / 0.8));+ if (p > 0.8) pencil(c, { pts: G.c.filter((_, i) => i % 3 === 0).slice(0, -1), seed: L.seed + 3, w: 0.6, a: 0.4, per: 4, retrace: false }, clamp((p - 0.8) / 0.2));+};++// ---------------------------------------------------------------- flowers+// One sunflower petal: a lanceolate ray, creased down the middle, the sun half lighter, painted+// in streaks along its length, darker where it tucks under the disc.+export const petal = (c: Ctx, cx: number, cy: number, ang: number, r0: number, l: number, w: number, lit: string, shd: string, seed: number, grow = 1, a = 1) => {+ const r = rng(seed), bend = (r() - 0.5) * 0.35, ll = l * grow, n = 9, s: P[] = [];+ for (let i = 0; i < n; i++) { const t = i / (n - 1), rr = r0 + ll * t, aa = ang + bend * t * t * (l / Math.max(1, rr)) * 0.6; s.push([cx + Math.cos(aa) * rr, cy + Math.sin(aa) * rr]); }+ const hw = (t: number) => (w / 2) * Math.pow(Math.sin(Math.PI * Math.pow(Math.min(1, t * 0.97 + 0.03), 0.62)), 0.8);+ const L: P[] = [], R: P[] = []; s.forEach((p, i) => { const [dx, dy] = tan(s, i), h = hw(i / (n - 1)); L.push([p[0] - dy * h, p[1] + dx * h]); R.push([p[0] + dy * h, p[1] - dx * h]); });+ const lft = Math.cos(ang + Math.PI / 2) * LIGHT[0] + Math.sin(ang + Math.PI / 2) * LIGHT[1] > 0;+ c.globalAlpha = a; c.fillStyle = lft ? lit : shd; trace(c, [...s, ...L.slice().reverse()]); c.fill();+ c.fillStyle = lft ? shd : lit; trace(c, [...s, ...R.slice().reverse()]); c.fill();+ // streaks along the ray and a darker root+ c.strokeStyle = darken(shd, 0.25); c.lineCap = "round";+ for (let k = 0; k < 5; k++) { const off = (k - 2) * 0.17, from = 1 + Math.floor(r() * 2), to = n - 2 - Math.floor(r() * 3); c.globalAlpha = a * (0.18 + r() * 0.2); c.lineWidth = Math.max(0.5, w * 0.06); c.beginPath(); for (let i = from; i <= to; i++) { const [dx, dy] = tan(s, i), h = hw(i / (n - 1)) * off * 2; const x = s[i][0] - dy * h, y = s[i][1] + dx * h; i === from ? c.moveTo(x, y) : c.lineTo(x, y); } c.stroke(); }+ c.globalAlpha = a * 0.35; c.strokeStyle = darken(shd, 0.3); c.lineWidth = Math.max(0.6, w * 0.07); trace(c, [...L, ...R.slice().reverse()]); c.stroke();+ c.globalAlpha = a * 0.3; c.strokeStyle = lighten(lit, 0.5); c.lineWidth = Math.max(0.5, w * 0.08); c.beginPath(); c.moveTo(s[2][0], s[2][1]); for (let i = 3; i < n - 1; i++) c.lineTo(s[i][0], s[i][1]); c.stroke();+ c.globalAlpha = 1;+};+export type Sun = { x: number; y: number; r: number; rot: number; sq: number; seed: number; n?: number; pl?: number; pw?: number; d?: number; droop?: number; pal?: [string, string, string, string] };+// A sunflower head: back ray ring, front ray ring, then the disc of florets in concentric bands+// (dark rim, an olive-brown band of open florets, a dark raised centre), spiralled like the plant.+export const sunflower = (c: Ctx, S: Sun, p = 1) => {+ if (p <= 0) return; const d = S.d ?? 0, n = S.n ?? 21, pl = S.pl ?? S.r * 1.25, pw = S.pw ?? S.r * 0.42, r = rng(S.seed), a = 1 - 0.45 * d;+ const units = 2 * n + 6, u = p * units;+ c.save(); c.translate(S.x, S.y); c.rotate(S.rot); c.scale(1, S.sq);+ const [Y, YD, YB, YBd] = S.pal ?? ["#f6c72b", "#dd9314", "#c98612", "#9c5f0e"];+ for (let ring = 0; ring < 2; ring++) for (let i = 0; i < n; i++) {+ const idx = ring * n + i; if (idx >= u) break; const g = clamp(u - idx), ang = ((i + (ring ? 0 : 0.5)) / n) * Math.PI * 2 + (r() - 0.5) * 0.12, ln = pl * (ring ? 0.78 + r() * 0.42 : 0.7 + r() * 0.35), wd = pw * (0.75 + r() * 0.5);+ petal(c, 0, 0, ang, S.r * (ring ? 0.9 : 0.95), ln, wd, far(ring ? Y : YB, d), far(ring ? YD : YBd, d), S.seed * 100 + idx, g, a);+ }+ const dp = clamp((u - 2 * n) / 6);+ if (dp > 0) {+ c.globalAlpha = a * clamp(dp * 3); c.fillStyle = far("#3f2a12", d); c.beginPath(); c.arc(0, 0, S.r * 1.02, 0, Math.PI * 2); c.fill();+ if (dp > 0.3) { c.fillStyle = far("#6d5220", d); c.beginPath(); c.arc(0, 0, S.r * 0.8, 0, Math.PI * 2); c.fill(); c.fillStyle = far("#8a6c2c", d); c.beginPath(); c.arc(-S.r * 0.05, -S.r * 0.05, S.r * 0.66, 0, Math.PI * 2); c.fill(); }+ if (dp > 0.5) { c.fillStyle = far("#4a3214", d); c.beginPath(); c.arc(0, 0, S.r * 0.52, 0, Math.PI * 2); c.fill(); c.fillStyle = far("#2d1d0b", d); c.beginPath(); c.arc(S.r * 0.03, S.r * 0.03, S.r * 0.34, 0, Math.PI * 2); c.fill(); }+ if (dp > 0.7 && d < 0.7) { // the florets: short curved dabs laid round the disc in rings, then the spiral seeds at the heart+ const q = clamp((dp - 0.7) / 0.3), rr = rng(S.seed + 9), R = S.r;+ c.lineCap = "round";+ const ring = (r0: number, r1: number, n: number, cols: string[], w: number, al: number) => { const rr = rng(S.seed + Math.round(r0 * 7)); for (let i = 0; i < Math.round(n * q); i++) { const th = rr() * Math.PI * 2, rad = r0 + (r1 - r0) * rr(), l = w * (1.2 + rr() * 1.5); c.globalAlpha = a * al * (0.5 + rr() * 0.5); c.strokeStyle = cols[i % cols.length]; c.lineWidth = w * (0.6 + rr() * 0.5); c.beginPath(); c.arc(0, 0, rad, th, th + l / rad); c.stroke(); } };+ ring(R * 0.84, R * 1.0, R * 3, ["#2a1a08", "#5a3c16", "#1e1206"], R * 0.07, 0.8);+ ring(R * 0.56, R * 0.82, R * 3.4, ["#b09048", "#7a5a22", "#c8a85a", "#5a4018"], R * 0.07, 0.75);+ ring(R * 0.36, R * 0.56, R * 2, ["#3a2610", "#6a4a1e"], R * 0.06, 0.7);+ const Nn = Math.round(R * R * 0.05 * q); for (let i = 0; i < Nn; i++) { const rad = Math.sqrt((i + 0.5) / Math.max(1, R * R * 0.05)) * R * 0.36, th = i * 2.39996; c.globalAlpha = a * 0.6; c.fillStyle = i % 3 ? "#1a1006" : "#4a3214"; c.beginPath(); c.arc(Math.cos(th) * rad, Math.sin(th) * rad, R * 0.028, 0, Math.PI * 2); c.fill(); }+ c.globalAlpha = a * 0.3; c.strokeStyle = "#f0d078"; c.lineWidth = R * 0.07; c.beginPath(); c.arc(0, 0, R * 0.7, Math.PI * 1.05, Math.PI * 1.6); c.stroke();+ c.globalAlpha = a * 0.4; c.strokeStyle = "#140b04"; c.lineWidth = R * 0.1; c.beginPath(); c.arc(0, 0, R * 0.95, Math.PI * 0.05, Math.PI * 0.75); c.stroke();+ }+ }+ c.restore(); c.globalAlpha = 1;+};+// a meadow daisy (ox-eye), seen a little from above: white rays, their undersides greyed, a yellow boss+export const daisy = (c: Ctx, x: number, y: number, r: number, seed: number, d = 0, sq = 0.62, p = 1) => {+ if (p <= 0) return; const rr = rng(seed), n = 13, a = (1 - 0.5 * d) * clamp(p * 1.5);+ c.save(); c.translate(x, y); c.rotate((rr() - 0.5) * 0.5); c.scale(1, sq);+ for (let i = 0; i < n; i++) { const th = (i / n) * Math.PI * 2 + rr() * 0.2, l = r * (0.85 + rr() * 0.3); c.globalAlpha = a; c.fillStyle = far(Math.sin(th) > 0.3 ? "#ddd8cc" : "#fbf8ef", d); c.beginPath(); c.ellipse(Math.cos(th) * l * 0.55, Math.sin(th) * l * 0.55, l * 0.5, r * 0.19, th, 0, Math.PI * 2); c.fill(); }+ c.globalAlpha = a; c.fillStyle = far("#e8b62a", d); c.beginPath(); c.arc(0, 0, r * 0.3, 0, Math.PI * 2); c.fill();+ c.fillStyle = far("#b9791a", d); c.beginPath(); c.arc(r * 0.07, r * 0.08, r * 0.17, 0, Math.PI * 2); c.fill();+ c.restore(); c.globalAlpha = 1;+};+// a bellflower (Campanula): a nodding bell, narrow at the calyx, flaring to five pointed lobes+// that curl out at the mouth; the dark throat shows between the front lobes+export const bell = (c: Ctx, x: number, y: number, s: number, ang: number, seed: number, d = 0, col = "#5d6fc4", p = 1) => {+ if (p <= 0) return; const r = rng(seed), a = (1 - 0.45 * d) * clamp(p * 1.4), L = s, Wd = s * 0.78;+ c.save(); c.translate(x, y); c.rotate(ang);+ const ctrl: P[] = [[-Wd * 0.1, 0], [-Wd * 0.26, L * 0.35], [-Wd * 0.33, L * 0.7], [-Wd * 0.42, L * 0.88], [-Wd * 0.62, L * 0.98], [-Wd * 0.4, L * 0.97], [-Wd * 0.24, L * 1.0], [0, L * 1.1], [Wd * 0.24, L * 1.0], [Wd * 0.4, L * 0.97], [Wd * 0.62, L * 0.98], [Wd * 0.42, L * 0.88], [Wd * 0.33, L * 0.7], [Wd * 0.26, L * 0.35], [Wd * 0.1, 0]];+ const body = sample(ctrl.map(([px, py]) => [px + (r() - 0.5) * s * 0.03, py] as P), true, 5);+ c.globalAlpha = a; c.fillStyle = far(col, d); trace(c, body); c.fill();+ c.save(); trace(c, body); c.clip();+ c.fillStyle = far(darken(col, 0.32), d); c.beginPath(); c.moveTo(Wd * 0.04, 0); c.quadraticCurveTo(Wd * 0.22, L * 0.6, Wd * 0.2, L * 1.1); c.lineTo(Wd, L * 1.1); c.lineTo(Wd, 0); c.fill();+ c.globalAlpha = a * 0.75; c.fillStyle = far(lighten(col, 0.4), d); c.beginPath(); c.moveTo(-Wd * 0.12, L * 0.08); c.quadraticCurveTo(-Wd * 0.3, L * 0.55, -Wd * 0.26, L * 0.92); c.lineTo(-Wd * 0.14, L * 0.9); c.quadraticCurveTo(-Wd * 0.16, L * 0.5, -Wd * 0.04, L * 0.1); c.fill();+ c.globalAlpha = a * 0.9; c.fillStyle = far("#2a2a5a", d); c.beginPath(); c.ellipse(0, L * 0.97, Wd * 0.26, L * 0.06, 0, 0, Math.PI * 2); c.fill();+ c.globalAlpha = a * 0.45; c.strokeStyle = far(darken(col, 0.45), d); c.lineWidth = Math.max(0.6, s * 0.025); for (const [tx2, ty2] of [[-Wd * 0.55, L * 0.97], [0, L * 1.08], [Wd * 0.55, L * 0.97]] as P[]) { c.beginPath(); c.moveTo(tx2 * 0.15, L * 0.08); c.quadraticCurveTo(tx2 * 0.5, L * 0.6, tx2, ty2); c.stroke(); }+ c.restore();+ c.globalAlpha = a; c.fillStyle = far("#3c5a2a", d); for (const sg of [-1, 1]) { c.beginPath(); c.moveTo(0, -1); c.quadraticCurveTo(sg * Wd * 0.3, L * 0.02, sg * Wd * 0.34, -L * 0.14); c.quadraticCurveTo(sg * Wd * 0.12, L * 0.0, 0, L * 0.12); c.fill(); }+ c.restore(); c.globalAlpha = 1;+};+// dog-rose: five notched pink petals, pale at the heart, a ring of yellow stamens+export const dogRose = (c: Ctx, x: number, y: number, r: number, rot: number, sq: number, seed: number, d = 0, p = 1) => {+ if (p <= 0) return; const rr = rng(seed), a = (1 - 0.45 * d) * clamp(p * 1.4);+ c.save(); c.translate(x, y); c.rotate(rot); c.scale(1, sq);+ for (let i = 0; i < 5; i++) {+ const th = (i / 5) * Math.PI * 2 + rr() * 0.15, pts: P[] = [];+ for (let k = 0; k <= 12; k++) { const t = k / 12, phi = th + (t - 0.5) * 1.25, rad = r * (0.2 + 0.8 * Math.sin(Math.PI * t) ** 0.35) * (1 - 0.12 * Math.exp(-(((t - 0.5) * 9) ** 2))); pts.push([Math.cos(phi) * rad, Math.sin(phi) * rad]); }+ pts.push([0, 0]);+ c.globalAlpha = a; c.fillStyle = far(Math.sin(th) > 0.2 ? "#e48aa0" : "#f3b3c0", d); trace(c, pts); c.fill();+ c.globalAlpha = a * 0.6; c.fillStyle = far("#fde9e6", d); c.beginPath(); c.ellipse(Math.cos(th) * r * 0.32, Math.sin(th) * r * 0.32, r * 0.2, r * 0.13, th, 0, Math.PI * 2); c.fill();+ }+ c.globalAlpha = a; c.fillStyle = far("#c9a33a", d); c.beginPath(); c.arc(0, 0, r * 0.2, 0, Math.PI * 2); c.fill();+ for (let i = 0; i < 16; i++) { const th = (i / 16) * Math.PI * 2, q = r * (0.24 + rr() * 0.06); c.fillStyle = far("#f2c936", d); c.beginPath(); c.arc(Math.cos(th) * q, Math.sin(th) * q, r * 0.045, 0, Math.PI * 2); c.fill(); }+ c.restore(); c.globalAlpha = 1;+};+// cow parsley / wild carrot gone to seed: dark hairline rays, each ending in a small umbel+export const umbel = (c: Ctx, x: number, y: number, r: number, seed: number, col = "#2f3320", p = 1, a = 0.85) => {+ if (p <= 0) return; const rr = rng(seed), n = 11;+ c.strokeStyle = col; c.fillStyle = col; c.lineCap = "round";+ for (let i = 0; i < n; i++) {+ if (i / n > p) break; const th = -Math.PI / 2 + ((i / (n - 1)) - 0.5) * 2.4 + (rr() - 0.5) * 0.15, l = r * (0.75 + rr() * 0.35), ex = x + Math.cos(th) * l, ey = y + Math.sin(th) * l * 0.75;+ c.globalAlpha = a * 0.8; c.lineWidth = Math.max(1, r * 0.028); c.beginPath(); c.moveTo(x, y); c.quadraticCurveTo((x + ex) / 2, (y + ey) / 2 - l * 0.12, ex, ey); c.stroke();+ for (let k = 0; k < 7; k++) { const t2 = -Math.PI / 2 + ((k / 6) - 0.5) * 2.2, l2 = r * 0.22 * (0.7 + rr() * 0.5), fx = ex + Math.cos(t2) * l2, fy = ey + Math.sin(t2) * l2 * 0.8; c.globalAlpha = a * 0.7; c.lineWidth = Math.max(0.6, r * 0.015); c.beginPath(); c.moveTo(ex, ey); c.lineTo(fx, fy); c.stroke(); c.globalAlpha = a; c.beginPath(); c.arc(fx, fy, Math.max(1.3, r * 0.03), 0, Math.PI * 2); c.fill(); }+ }+ c.globalAlpha = 1;+};++// ---------------------------------------------------------------- grass+// A meadow is thousands of blades, painted back to front: dark roots first, then blades in+// several greens, leaning with the wind, the tips catching the light.+export type Grass = { x0: number; x1: number; base: (x: number) => number; n: number; h: [number, number]; w: number; cols: string[]; lean?: number; seed: number; d?: number; tip?: string; spread?: number; a?: number; clump?: number; skip?: (x: number, y: number) => boolean; dry?: string };+// clumps: several blades fanning from one root, as grass actually grows and as a brush lays it+export const grass = (c: Ctx, G: Grass, p = 1) => {+ if (p <= 0) return; const r = rng(G.seed), d = G.d ?? 0, a0 = (G.a ?? 1) * (1 - 0.45 * d), spread = G.spread ?? 14, cols = G.cols.map((k) => far(k, d)), tip = G.tip ? far(G.tip, d) : null, dry = G.dry ? far(G.dry, d) : null, per = G.clump ?? 1;+ const clumps = Math.ceil(G.n / per), m = p >= 1 ? clumps : Math.floor(clumps * p);+ c.lineCap = "round";+ for (let i = 0; i < m; i++) {+ const x = G.x0 + r() * (G.x1 - G.x0), y = G.base(x) + r() * spread, H0 = G.h[0] + (G.h[1] - G.h[0]) * r() ** 1.3, lean0 = (G.lean ?? 0.2) + (r() - 0.5) * 0.5, k = per === 1 ? 1 : Math.max(2, Math.round(per * (0.6 + r() * 0.8))), skip = G.skip?.(x, y) ?? false;+ for (let b = 0; b < k; b++) {+ const fan = k === 1 ? 0 : ((b / (k - 1)) - 0.5) * 1.3, h = H0 * (0.55 + r() * 0.5) * (1 - Math.abs(fan) * 0.3), lean = lean0 + fan * 0.55 + (r() - 0.5) * 0.25, w = G.w * (0.6 + r() * 0.7);+ const col = dry && r() < 0.08 ? dry : cols[Math.floor(r() * cols.length)], al = a0 * (0.6 + r() * 0.4), bx = x + (r() - 0.5) * 4;+ if (skip) continue;+ const tx = bx + lean * h, ty = y - h * (1 - Math.abs(lean) * 0.15), mx = bx + lean * h * 0.3 + (r() - 0.5) * h * 0.08, my = y - h * 0.55;+ c.globalAlpha = al; c.fillStyle = col; c.beginPath(); c.moveTo(bx - w / 2, y); c.quadraticCurveTo(mx - w * 0.35, my, tx, ty); c.quadraticCurveTo(mx + w * 0.35, my, bx + w / 2, y); c.closePath(); c.fill();+ if (tip && r() < 0.5) { c.globalAlpha = al * 0.7; c.strokeStyle = tip; c.lineWidth = Math.max(0.5, w * 0.28); c.beginPath(); c.moveTo(bx + (mx - bx) * 0.9 - w * 0.15, my); c.quadraticCurveTo(mx + (tx - mx) * 0.55, my - h * 0.22, tx, ty); c.stroke(); }+ }+ }+ c.globalAlpha = 1;+};++// ---------------------------------------------------------------- limbs and bark+// A painted limb: body colour, the shadow side laid wet beside it, bark drags along the grain.+export const limb = (c: Ctx, ctrl: P[], w0: number, w1: number, col: string, seed: number, d = 0, p = 1, shade = 0.3, grain = 1) => {+ if (p <= 0) return; const s = cutAt(smooth(ctrl, 8), p), a = 1 - 0.5 * d, r = rng(seed);+ if (s.length < 2) return;+ const hw = (t: number) => (w0 + (w1 - w0) * t * (p >= 1 ? 1 : p)) / 2;+ const body = ribbonOf(s, hw);+ c.globalAlpha = a; c.fillStyle = far(col, d); trace(c, body); c.fill();+ // the shadow half: which side faces away from the sun+ const [tx, ty] = tan(s, Math.floor(s.length / 2)), rightLit = (ty * LIGHT[0] - tx * LIGHT[1]) > 0;+ const shadeSide: P[] = []; const n = s.length;+ for (let i = 0; i < n; i++) { const [dx, dy] = tan(s, i), w = hw(i / Math.max(1, n - 1)), sg = rightLit ? -1 : 1; shadeSide.push([s[i][0] - dy * w * sg, s[i][1] + dx * w * sg]); }+ const mid: P[] = s.map((q, i) => { const [dx, dy] = tan(s, i), w = hw(i / Math.max(1, n - 1)) * 0.15, sg = rightLit ? -1 : 1; return [q[0] - dy * w * sg, q[1] + dx * w * sg]; });+ c.globalAlpha = a * 0.85; c.fillStyle = far(darken(col, shade), d); trace(c, [...mid, ...shadeSide.reverse()]); c.fill();+ if (grain > 0 && d < 0.8) { // bark: drags along the limb+ c.save(); trace(c, body); c.clip(); c.lineCap = "round";+ const L = len(s), k = Math.round((L * (w0 + w1)) / 2 / 40 * grain);+ for (let i = 0; i < k; i++) { const t = r(), idx = Math.min(n - 2, Math.floor(t * (n - 1))), [dx, dy] = tan(s, idx), off = (r() - 0.5) * 2 * hw(t) * 0.95, x = s[idx][0] - dy * off, y = s[idx][1] + dx * off, l = 6 + r() * Math.max(10, w0 * 1.2); c.strokeStyle = far(r() < 0.5 ? darken(col, 0.45) : lighten(col, 0.3), d); drag(c, x, y, Math.atan2(dy, dx) + (r() - 0.5) * 0.15, l, Math.max(1.5, w0 * 0.12), 0.45 * a, r); }+ c.restore();+ }+ c.globalAlpha = 1;+};+// the same limb in pencil only: two edge lines and a few grain ticks+export const lineLimb = (w0: number, w1: number, ctrl: P[], seed: number, a = 0.6): Line[] => {+ const s = smooth(ctrl, 3), n = s.length, L: P[] = [], R: P[] = [];+ s.forEach((q, i) => { const [dx, dy] = tan(s, i), w = (w0 + (w1 - w0) * (i / Math.max(1, n - 1))) / 2; L.push([q[0] - dy * w, q[1] + dx * w]); R.push([q[0] + dy * w, q[1] - dx * w]); });+ const out: Line[] = [{ pts: L, seed, a, w: 0.95, per: 3 }, { pts: R, seed: seed + 1, a: a * 0.85, w: 0.9, per: 3 }];+ if (w0 > 10) { const r = rng(seed); for (let k = 0; k < Math.round(w0 / 5); k++) { const i = Math.floor(r() * (n - 3)), [dx, dy] = tan(s, i), off = (r() - 0.5) * (w0 + (w1 - w0) * (i / n)) * 0.7, x = s[i][0] - dy * off, y = s[i][1] + dx * off, l = 8 + r() * 20; out.push({ pts: [[x, y], [x + dx * l * 0.5 + (r() - 0.5) * 2, y + dy * l * 0.5], [x + dx * l, y + dy * l]], seed: seed + 10 + k, a: a * 0.5, w: 0.7, retrace: false }); } }+ return out;+};++// ---------------------------------------------------------------- the garden+// a ribbed pumpkin: lobes between meridians, lit lobes warm, shadow lobes deep, grooves dark,+// a dry twisted stalk sunk in the dimple, a cast shadow on the ground to the lower right+export const pumpkin = (c: Ctx, x: number, y: number, rx: number, ry: number, seed: number, d = 0, p = 1, col = "#e2761c") => {+ if (p <= 0) return; const r = rng(seed), a = 1 - 0.45 * d, k = 9, ph = clamp(p / 0.7), det = clamp((p - 0.7) / 0.3);+ c.save();+ c.globalAlpha = 0.35 * a * ph; c.fillStyle = far("#2e3e16", d); c.beginPath(); c.ellipse(x + rx * 0.28, y + ry * 0.86, rx * 1.1, ry * 0.26, 0, 0, Math.PI * 2); c.fill();+ const phi = Array.from({ length: k + 1 }, (_, i) => -Math.PI / 2 + (Math.PI * i) / k + (i && i < k ? (r() - 0.5) * 0.08 : 0));+ const mer = (f: number, t: number): P => { const w = Math.pow(Math.sin(Math.PI * t), 0.42), yy = -ry + 2 * ry * t; return [x + Math.sin(f) * rx * w, y + yy * (0.82 + 0.18 * w) + Math.cos(f) * ry * 0.06]; };+ const lobe = (f0: number, f1: number): P[] => { const A: P[] = [], B: P[] = []; for (let s = 0; s <= 14; s++) { const t = s / 14; A.push(mer(f0, t)); B.push(mer(f1, t)); } return [...A, ...B.reverse()]; };+ const order = Array.from({ length: k }, (_, i) => i).sort((i, j) => Math.abs(i + 0.5 - k / 2) < Math.abs(j + 0.5 - k / 2) ? 1 : -1);+ order.forEach((i, o) => {+ if (o / k > ph) return; const m = (i + 0.5) / k, lit = clamp(1 - m * 0.95), base = mix(darken(col, 0.42), lighten(col, 0.1), lit), f0 = phi[i], f1 = phi[i + 1];+ gouache(c, lobe(f0, f1), far(base, d), { seed: seed + i, a, rim: far(darken(col, 0.55), d), rimW: 1.6, rimA: 0.6 });+ // the lobe's own roundness: a lighter lens toward the sun, a dark foot+ gouache(c, lobe(f0 + (f1 - f0) * 0.18, f1 - (f1 - f0) * 0.45).map(([px, py]) => [px, py - ry * 0.06] as P), far(mix(base, "#ffd070", 0.35 * lit + 0.1), d), { seed: seed + 30 + i, a: a * 0.55 });+ if (det > 0) { c.save(); trace(c, lobe(f0, f1)); c.clip();+ for (let q = 1; q < 4; q++) { const f = f0 + ((f1 - f0) * q) / 4; c.globalAlpha = 0.18 * a * det; c.strokeStyle = far(q % 2 ? darken(col, 0.4) : lighten(col, 0.35), d); c.lineWidth = 1.2; c.beginPath(); for (let s = 1; s < 14; s++) { const P0 = mer(f, s / 14); s === 1 ? c.moveTo(P0[0], P0[1]) : c.lineTo(P0[0], P0[1]); } c.stroke(); }+ const gr = c.createLinearGradient(0, y + ry * 0.2, 0, y + ry); gr.addColorStop(0, rgba("#3a1a06", 0)); gr.addColorStop(1, rgba("#3a1a06", 0.45 * det)); c.globalAlpha = a; c.fillStyle = gr; c.fillRect(x - rx - 2, y - ry, rx * 2 + 4, ry * 2 + 4);+ c.restore(); }+ });+ if (det > 0) {+ c.globalAlpha = a * det; c.fillStyle = far(darken(col, 0.5), d); c.beginPath(); c.ellipse(x, y - ry * 0.8, rx * 0.16, ry * 0.07, 0, 0, Math.PI * 2); c.fill();+ const sx = x + (r() - 0.5) * rx * 0.06, top: P = [sx + rx * 0.12, y - ry * 1.18];+ gouache(c, [[sx - rx * 0.08, y - ry * 0.8], [sx - rx * 0.07, y - ry * 1.02], [top[0] - 4, top[1] - 2], [top[0] + 4, top[1] + 3], [sx + rx * 0.07, y - ry * 1.0], [sx + rx * 0.09, y - ry * 0.8]], far("#6a6a2c", d), { seed: seed + 50, a, rim: far("#2e2e10", d), rimA: 0.6, rimW: 1.2 });+ stroke(c, [[sx - rx * 0.03, y - ry * 0.82], [sx - rx * 0.02, y - ry * 1.0], [top[0] - 2, top[1]]], 2, 1, far("#a8a45a", d), 0.7 * a);+ }+ c.restore(); c.globalAlpha = 1;+};+// a pumpkin leaf (Cucurbita): broad, palmately five-lobed with shallow sinuses, a deep notch at the+// stalk, fine teeth; dark and rough, the main veins pale and raised, seen a little from above+export const gourdLeaf = (c: Ctx, x: number, y: number, s: number, rot: number, sq: number, col: string, seed: number, d = 0, p = 1) => {+ if (p <= 0) return; const r = rng(seed), a = 1 - 0.45 * d, g = clamp(p / 0.6), det = clamp((p - 0.6) / 0.4);+ c.save(); c.translate(x, y); c.rotate(rot); c.scale(1, sq);+ const tips = [-1.75, -0.9, 0, 0.9, 1.75].map((t) => t + (r() - 0.5) * 0.15), lens = tips.map(() => 0.85 + r() * 0.2);+ const rad = (th: number) => { let m = 0; tips.forEach((t, k) => { m = Math.max(m, lens[k] * Math.exp(-(((th - t) / 0.36) ** 2))); }); return s * g * (0.62 + 0.38 * m) * (1 - 0.3 * (Math.abs(th) / Math.PI) ** 2) * (1 + 0.025 * Math.sin(th * 46 + seed)); };+ const out: P[] = []; for (let i = 0; i <= 90; i++) { const th = -Math.PI * 0.9 + (i / 90) * Math.PI * 1.8; out.push([Math.sin(th) * rad(th), -Math.cos(th) * rad(th) * 0.95]); }+ const lft = out.filter(([px]) => px <= 0), rgt = out.filter(([px]) => px >= 0);+ gouache(c, [[0, 0], ...lft], far(lighten(col, 0.08), d), { seed, a });+ gouache(c, [[0, 0], ...rgt], far(darken(col, 0.15), d), { seed: seed + 1, a });+ if (det > 0) {+ c.save(); trace(c, [[0, 0], ...out]); c.clip(); c.lineCap = "round";+ for (let i = 0; i < Math.round(s * 0.9 * det); i++) { const th = (r() - 0.5) * 3.2, q = r() * rad(th) * 0.95, px = Math.sin(th) * q, py = -Math.cos(th) * q, l = 3 + r() * s * 0.12, an = th - Math.PI / 2 + (r() - 0.5) * 0.6; c.globalAlpha = (0.12 + r() * 0.16) * a; c.strokeStyle = far(r() < 0.5 ? darken(col, 0.35) : lighten(col, 0.3), d); c.lineWidth = 1 + r() * s * 0.025; c.beginPath(); c.moveTo(px, py); c.lineTo(px + Math.cos(an) * l, py + Math.sin(an) * l); c.stroke(); }+ tips.forEach((th, v) => { const R = rad(th) * 0.9, ex = Math.sin(th) * R, ey = -Math.cos(th) * R * 0.95; stroke(c, [[0, 0], [ex * 0.5 + (r() - 0.5) * 3, ey * 0.5], [ex, ey]], s * 0.035, 0.6, far(lighten(col, 0.45), d), 0.65 * a, det);+ for (let q = 1; q <= 3; q++) { const t = q / 4.2, bx = ex * t, by = ey * t; for (const sg of [-1, 1]) { const th2 = th + sg * 0.7, l = R * 0.28 * (1 - t * 0.4); stroke(c, [[bx, by], [bx + Math.sin(th2) * l * 0.6, by - Math.cos(th2) * l * 0.6], [bx + Math.sin(th2 - sg * 0.3) * l, by - Math.cos(th2 - sg * 0.3) * l]], s * 0.014, 0.3, far(lighten(col, 0.35), d), 0.4 * a, det); } } void v; });+ c.restore();+ c.globalAlpha = 0.45 * a; c.strokeStyle = far(darken(col, 0.55), d); c.lineWidth = 1.6; trace(c, [[0, 0], ...out]); c.stroke();+ }+ c.restore(); c.globalAlpha = 1;+};+export const tendril = (c: Ctx, x: number, y: number, s: number, dir: number, seed: number, col: string, d = 0, p = 1) => {+ if (p <= 0) return; const r = rng(seed), pts: P[] = [[x, y]]; let a = dir, cx = x, cy = y, k = 0.05;+ for (let i = 0; i < 40; i++) { a += k; k *= 1.07; const st = s * 0.05 * (1 - i / 60); cx += Math.cos(a) * st; cy += Math.sin(a) * st; pts.push([cx, cy]); }+ void r; stroke(c, pts, 1.6, 0.5, far(col, d), 0.9 * (1 - 0.4 * d), p, 2);+};++// ---------------------------------------------------------------- the sheet+// Warm cream cartridge with its own slow unevenness: the glow the paint sits in.+export const sheet = (g: Gfx, glow: [number, number, number, string][]) => {+ const c = g.cur, e: Env = g.env; c.save(); c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.globalAlpha = 1; c.fillStyle = PAPER; c.fillRect(0, 0, e.W, e.H);+ glow.forEach(([x, y, rad, col]) => { const gr = c.createRadialGradient(x, y, 0, x, y, rad); gr.addColorStop(0, rgba(col, 0.55)); gr.addColorStop(1, rgba(col, 0)); c.fillStyle = gr; c.fillRect(0, 0, e.W, e.H); });+ c.restore();+};diff --git a/engine/src/canvas-core/formMascot.ts b/engine/src/canvas-core/formMascot.tsnew file mode 100644index 0000000..912bbb1--- /dev/null+++ b/engine/src/canvas-core/formMascot.ts@@ -0,0 +1,76 @@+// FORM MASCOT. Bit (storybook plate) keeps a sign-up form company.+//+// The idea in one sentence: filling in a form is lonelier than it should be, so the robot reads+// along, looks away when you type your password, and is genuinely delighted when it works.+// - focus a text field: he reads your caret, eyes first, head a beat later, with a small nod on+// every keystroke. The host logs only the LENGTH and caret position of what you type, never+// the text: a replay log holds no personal data;+// - focus the password: he shuts his eyes tight and puts both hands up. Tick "show password"+// (page sets state "peek"): one eye opens and one hand drops, caught peeking;+// - submit with a problem (state "error"): a worried head-shake, wobbly mouth, dimmed bulb, and+// he stays worried until you type again;+// - "busy": the key whirrs and he looks up at his bulb, thinking; "success": the cheer.+// Loop 480 ticks. Targets: name, email, password, reveal, submit.+import type { Env, P } from "./core";+import { blit, usePaper } from "./bake";+import { attend, bakeBit, CHEER, cheer, drawBit2, FACE, idle, LOOP, meadowSprite, restPose, SHEETS, type BitPose } from "./bitRig";+import { clip, lookTarget, reactionSeed, ticksSince, type Discrete, type InputState, type Piece } from "./input";+import { toSheet } from "./bitRig";++const FACE_S = toSheet(FACE);+// covering his eyes while the password field is focused, or while its show/hide toggle is (it was the last field)+const covering = (d: Discrete) => d.state !== "success" && d.state !== "busy" && (d.focus === "password" || (d.focus === "reveal" && (d.since["focus:password"] ?? -1) > Math.max(d.since["focus:name"] ?? -1, d.since["focus:email"] ?? -1)));+const armFor = (d: Discrete, side: number) => (d.state === "success" ? 0 : covering(d) ? (d.state === "peek" && side > 0 ? 0.3 : 0.74) : 0);+const tri = (u: number) => (u < 0.5 ? u * 2 : 2 - u * 2);++export const formMascot: Piece = {+ meta: { title: "Bit, reading along", W: 560, H: 560, loop: LOOP, alt: "A pencil-and-watercolour wind-up robot who reads along as you fill in the form, covers his eyes for your password, and cheers when you sign up." },+ input: {+ springs: {+ look: { omega: 0.3, target: (d) => lookTarget(d, FACE_S) },+ head: { omega: 0.1, target: (d) => lookTarget(d, FACE_S) },+ armL: { omega: 0.18, target: (d) => armFor(d, -1) },+ armR: { omega: 0.18, target: (d) => armFor(d, 1) },+ worry: { omega: 0.12, target: (d) => (d.state === "error" ? 1 : 0) },+ },+ },+ bake: function* (env) { yield "paper"; usePaper(env, SHEETS); yield "meadow"; meadowSprite(env); yield* bakeBit(env); },+ draw: (ctx, t, env, s) => {+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";+ usePaper(env, SHEETS); /* the sheet is baked into every sprite (bake.ts): no per-frame multiply */+ blit(ctx, meadowSprite(env as Env));+ drawBit2(ctx, env, pose(t, s));+ },+};++export const pose = (t: number, s: InputState): BitPose => {+ const p = restPose(), R = s.reduced, a = s.attention, st = s.state;+ if (!R) { idle(p, t); attend(p, s.spring.look as P, s.spring.head as P); p.armL = s.spring.armL as number; p.armR = s.spring.armR as number; }+ const typing = a ? clip(s, `key:${a}`, 12) : null;+ if (a && a !== "password" && a !== "submit" && a !== "reveal") { p.brows = "up"; if (typing && !R) { p.headOff[1] += 2 * tri(typing.u); p.key += typing.f; } }+ if (a === "submit") { p.mouth = "grin"; p.brows = "up"; p.glow += 0.7; }+ if (covering(s)) {+ p.eyes = "shut"; p.mouth = "flat"; p.brows = "worried"; p.blush = 1; p.look = [0, 0];+ if (st === "peek") { p.eyesR = "open"; p.eyes = "shut"; p.mouth = "o"; p.brows = "up"; }+ if (!R) { p.tilt = -3; p.headOff = [0, 2]; if (typing) p.key += typing.f; }+ }+ // error: a head-shake clip, then a worried face that lasts until the page clears the state+ const w = s.spring.worry as number;+ if (st === "error") {+ p.brows = "worried"; p.mouth = "wobble"; p.glow = Math.max(0.3, p.glow - 0.8 * w); p.blush = 0.5;+ const sh = clip(s, "state:error", 40);+ if (sh && !R) { const f = sh.f, amp = 1 - f / 40; p.headOff = [7 * Math.sin((2 * Math.PI * f) / 13) * amp, 2]; p.tilt = -5 * Math.sin((2 * Math.PI * f) / 13) * amp; p.look = [-4 * Math.sin((2 * Math.PI * f) / 13) * amp, 2]; }+ else if (!R) { p.look = [p.look[0] * 0.5, 3]; p.headOff[1] += 2; }+ if (R && sh) p.faceFade = Math.min(1, sh.f / 8);+ }+ if (st === "busy") {+ p.brows = "up"; p.mouth = "o";+ if (!R) { p.look = [2, -4]; p.headOff = [0, -1]; p.key += 2 * ticksSince(s, "state:busy"); p.glow = 1.4 + 0.6 * Math.sin((2 * Math.PI * t) / 20); }+ }+ if (st === "success") {+ const ch = clip(s, "state:success", CHEER);+ if (ch) { cheer(p, ch.f, reactionSeed(s, "state:success"), R); if (R) p.faceFade = Math.min(1, ch.f / 8); }+ else { p.eyes = "happy"; p.mouth = "smile"; p.blush = 1; p.heart = tri((t % 40) / 40); if (!R) p.glow += 0.5; }+ }+ return p;+};diff --git a/engine/src/canvas-core/fox.ts b/engine/src/canvas-core/fox.tsindex f658f4c..15aca13 100644--- a/engine/src/canvas-core/fox.ts+++ b/engine/src/canvas-core/fox.ts@@ -39,12 +39,22 @@ const fibres = (g: Gfx, shape: P[], color: string, seed: number, density: number});};-// one layer of paper: every piece's shadow first (soft, down and right), then the pieces-const layer = (g: Gfx, pieces: Piece[]) => {- const shapes = pieces.map((p) => (p.torn ? tear(p.shape, p.torn, p.seed) : cut(p.shape, p.seed)));- g.group("plain", () => pieces.forEach((p, i) => { const l = p.lift ?? 1; fillShape(g, shapes[i].map(([x, y]) => [x + 3 * l, y + 5 * l] as P), SHADOW, 0.5); }), { blur: 4, alpha: 0.55 });+// one layer of paper: every piece's shadow first (soft, down and right), then the pieces.+// An optional Stage (foxDraw) says, per piece, whether it is down yet and how high it is held:+// undefined = settled (the still), null = not placed, a Pose = in the hand. Without one the+// output is byte-identical to the still.+export type Pose = { dx: number; dy: number; lift: number };+export type Stage = { n: number; pose: (layer: number, piece: number) => Pose | null | undefined; count?: number[] };+const layerOf = (g: Gfx, pieces: Piece[], st?: Stage) => {+ const li = st ? st.n++ : 0; st?.count?.push(pieces.length);+ const poses = pieces.map((_, j) => (st ? st.pose(li, j) : undefined));+ if (poses.every((q) => q === null)) return;+ const mv = (s: P[], q: Pose | null | undefined): P[] => (q ? s.map(([x, y]) => [x + q.dx, y + q.dy] as P) : s);+ const shapes = pieces.map((p, i) => mv(p.torn ? tear(p.shape, p.torn, p.seed) : cut(p.shape, p.seed), poses[i]));+ g.group("plain", () => pieces.forEach((p, i) => { if (poses[i] === null) return; const l = (p.lift ?? 1) * (poses[i]?.lift ?? 1); fillShape(g, shapes[i].map(([x, y]) => [x + 3 * l, y + 5 * l] as P), SHADOW, 0.5); }), { blur: 4, alpha: 0.55 });g.group("plain", () => pieces.forEach((p, i) => {- if (p.torn) fillShape(g, tear(p.shape, p.torn * 0.8, p.seed + 1, p.torn * 0.7), PAPER_CORE); // the white core where the sheet tore+ if (poses[i] === null) return;+ if (p.torn) fillShape(g, mv(tear(p.shape, p.torn * 0.8, p.seed + 1, p.torn * 0.7), poses[i]), PAPER_CORE); // the white core where the sheet torefillShape(g, shapes[i], p.color);fibres(g, shapes[i], p.color, p.seed + 2, p.fibre ?? 1);}));@@ -52,7 +62,8 @@ const layer = (g: Gfx, pieces: Piece[]) => {const P0 = (pts: P[], per = 6) => smooth(pts, true, per);// ---------------------------------------------------------------- the dusk-const sky = (g: Gfx) => {+const sky = (g: Gfx, st?: Stage) => {+ const layer = (g2: Gfx, pc: Piece[]) => layerOf(g2, pc, st);layer(g, [{ shape: [[-20, -20], [1100, -20], [1100, 1100], [-20, 1100]], color: "#23485a", seed: 1, fibre: 0.6 }]);layer(g, [{ shape: P0([[-30, 300], [300, 280], [700, 300], [1110, 270], [1110, 1100], [-30, 1100]]), color: "#3d6b74", torn: 3, seed: 2, fibre: 0.5 },@@ -66,7 +77,8 @@ const sky = (g: Gfx) => {layer(g, [[420, 120], [860, 180], [700, 90], [980, 330], [560, 210]].map(([x, y], i) => ({ shape: Array.from({ length: 10 }, (_, k) => { const a = -Math.PI / 2 + (k / 10) * Math.PI * 2, rr = k % 2 ? 4.5 : 11; return [x + Math.cos(a) * rr, y + Math.sin(a) * rr] as P; }), color: "#f2cf6e", seed: 20 + i, lift: 0.3 })));};-const hills = (g: Gfx) => {+const hills = (g: Gfx, st?: Stage) => {+ const layer = (g2: Gfx, pc: Piece[]) => layerOf(g2, pc, st);layer(g, [{ shape: P0([[-30, 600], [170, 548], [380, 574], [600, 540], [820, 566], [1110, 530], [1110, 1100], [-30, 1100]]), color: "#5f7f76", torn: 3.4, seed: 30 }]);// pines along the ridge: tiers of torn dark-green paper, each tier its own scrapconst pine = (x: number, base: number, h: number, seed: number): Piece[] => {@@ -82,7 +94,8 @@ const hills = (g: Gfx) => {// ---------------------------------------------------------------- the foxconst RUST = "#cf5a22", RUST_D = "#9c3c17", RUST_L = "#ec8d45", CREAM = "#f2e2c0", BLACK = "#231813", AMBER = "#e3a53a";-const figure = (g: Gfx) => {+const figure = (g: Gfx, st?: Stage) => {+ const layer = (g2: Gfx, pc: Piece[]) => layerOf(g2, pc, st);// the brush in two parts: the far sweep behind the haunch, and the near sweep that lies IN// FRONT of the paws, curling round them to its white tip, as a sitting fox wraps its feetconst tailBack: P[] = P0([[700, 650], [794, 712], [822, 812], [780, 886], [700, 910], [640, 880], [700, 846], [742, 790], [728, 706]]);@@ -127,7 +140,8 @@ const figure = (g: Gfx) => {};// ---------------------------------------------------------------- the foreground-const foreground = (g: Gfx) => {+const foreground = (g: Gfx, st?: Stage) => {+ const layer = (g2: Gfx, pc: Piece[]) => layerOf(g2, pc, st);// fallen leaves cut from three papers, and torn grass blades across the fox's feetconst leaf = (cx: number, cy: number, s: number, a: number, color: string, seed: number): Piece => {const pts: P[] = [[0, -1], [0.26, -0.64], [0.6, -0.72], [0.44, -0.32], [0.9, -0.12], [0.46, 0.12], [0.62, 0.52], [0.18, 0.34], [0, 0.9], [-0.18, 0.34], [-0.62, 0.52], [-0.46, 0.12], [-0.9, -0.12], [-0.44, -0.32], [-0.6, -0.72], [-0.26, -0.64]];@@ -141,6 +155,10 @@ const foreground = (g: Gfx) => {void inside; void lerpP;};+// the whole collage, in the order it is laid down; foxDraw passes a Stage+export const foxScene = (g: Gfx, st?: Stage) => { sky(g, st); hills(g, st); figure(g, st); foreground(g, st); };+export const PAPER_BOARD = PAPER_CORE;+export const drawFox = (ctx: Ctx, _frame: number, env: Env) => {const g = new Gfx(ctx, env, 0, PENCIL);ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);diff --git a/engine/src/canvas-core/foxDraw.ts b/engine/src/canvas-core/foxDraw.tsnew file mode 100644index 0000000..ee13418--- /dev/null+++ b/engine/src/canvas-core/foxDraw.ts@@ -0,0 +1,75 @@+import { Gfx, PENCIL, rng, type Ctx, type Env, type Layer } from "./core";+import type { Film } from "./film";+import { foxScene, type Pose, type Stage } from "./fox";++// FOX AT DUSK · laid down. The cut-paper fox (fox.ts), made the way a collage artist makes it:+// from the bottom of the stack up. Frame 0 is the bare backing board. Then the sheets go down in+// the plate's own layer order: the sky ground, the torn bands of dusk, the moon and its seas, the+// stars; the hill and its pines tier by tier; the fox from the far sweep of the brush forward to+// the eye's glint; last the leaves and the grass across the feet.+// Each piece arrives in the hand: held a little above the sheet it throws a wide, soft, far+// shadow, then it is lowered and pressed, and the shadow pulls in tight under it. Big sheets are+// slid in from the edge they belong to and go down fast; small pieces are fiddly and slow. A beat+// of rest between the four passes. The last second is the still, pixel for pixel (md5 of the+// last frame = md5 of `fox`).++const N = 480, HOLD = 30, T0 = 5;+type Slot = { start: number; dur: number; dx: number; dy: number };+// the schedule, derived once from the plate's own layer list+const plan = (() => {+ const st: Stage = { n: 0, pose: () => null, count: [] };+ // a dry run: every piece "not placed", so nothing is drawn; we only learn the layer sizes+ const counts = (() => { const fake = { cur: null } as unknown as Gfx; foxScene(fake, st); return st.count!; })();+ const pass = (li: number) => (li < 7 ? 0 : li < 12 ? 1 : li < counts.length - 2 ? 2 : 3); // sky, hill, fox, foreground+ const r = rng(58);+ // raw timing in arbitrary units: big full-bleed sheets are quick, each extra piece in a layer+ // adds a fiddly placement, and a pause separates passes+ const raw: { li: number; t: number; d: number; stag: number }[] = []; let t = 0;+ counts.forEach((n, li) => { if (li > 0 && pass(li) !== pass(li - 1)) t += 12; const stag = n > 1 ? Math.min(pass(li) === 3 ? 1.2 : 2.2, 30 / n) : 0, d = li < 5 || li === 7 || (li >= 10 && li <= 11) ? 12 : pass(li) === 2 ? 11 : 8; raw.push({ li, t, d, stag }); t += d * 0.8 + stag * (n - 1); });+ const k = (N - HOLD - T0 - 12) / t;+ const slots: Slot[][] = raw.map(({ li, t: t0, d, stag }) => Array.from({ length: counts[li] }, (_, j) => {+ const big = li < 5 || li === 7 || li >= 10 && li <= 11; // full-bleed bands slide in from below+ const a = big ? Math.PI / 2 : -Math.PI / 2 + (r() - 0.5) * 2.2, far = big ? 70 : 22 + r() * 16;+ return { start: T0 + (t0 + stag * j) * k, dur: Math.max(6, d * k * (big ? 0.9 : 1.1)), dx: Math.cos(a) * far, dy: Math.sin(a) * far };+ }));+ const done = raw.map(({ li }) => Math.max(...slots[li].map((s) => s.start + s.dur)));+ return { counts, slots, done };+})();+const ease = (u: number) => (u >= 1 ? 1 : 1 - (1 - u) ** 3);+const poseAt = (s: Slot, f: number): Pose | null | undefined => {+ if (f < s.start) return null; const u = (f - s.start) / s.dur; if (u >= 1) return undefined;+ const e = ease(u), h = (1 - e) * (1 - e);+ return { dx: s.dx * (1 - e), dy: s.dy * (1 - e), lift: 1 + 5 * h };+};++export const drawFoxDraw = (ctx: Ctx, f: number, env: Env) => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), L = plan.counts.length;+ let k = 0; while (k < L && plan.done[k] <= f) k++;+ // everything down: draw the plate exactly as fox.ts does, on this canvas, so the held last+ // second is the still byte for byte (a blit of an offscreen base differs by +-3 in places)+ if (k === L) {+ // drawn once, then restored with putImageData (an exact pixel copy, no compositing), so every+ // held frame is the same bytes as `fox` without paying for the whole collage again+ const fk = `foxDraw:final:${DW}x${DH}`, img = env.cache.get(fk) as ImageData | undefined;+ if (img) { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.putImageData(img, 0, 0); return; }+ const g = new Gfx(ctx, env, 0, PENCIL); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); foxScene(g); g.paper("paper", 0.1);+ env.cache.set(fk, ctx.getImageData(0, 0, DW, DH)); return;+ }+ // base = layers [0, k) settled, on the board. Its pixels are a pure function of k; the stored+ // k says which prefix it holds, and it only rolls forward (a backward seek rebuilds).+ const key = `foxDraw:base:${DW}x${DH}`; let c = env.cache.get(key) as { k: number; L: Layer } | undefined;+ if (!c) { c = { k: -1, L: env.canvas(DW, DH) }; env.cache.set(key, c); }+ if (c.k > k || c.k < 0) { const b = c.L.ctx; b.setTransform(1, 0, 0, 1, 0, 0); b.globalAlpha = 1; b.globalCompositeOperation = "source-over"; b.fillStyle = "#e9dfc9"; b.fillRect(0, 0, DW, DH); c.k = 0; } // the backing board+ if (c.k < k) { const from = c.k, g = new Gfx(c.L.ctx, env, 0, PENCIL); foxScene(g, { n: 0, pose: (li) => (li >= from && li < k ? undefined : null) }); c.k = k; }+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(c.L.canvas as CanvasImageSource, 0, 0);+ const g = new Gfx(ctx, env, 0, PENCIL);+ if (k < L) foxScene(g, { n: 0, pose: (li, j) => (li < k ? null : poseAt(plan.slots[li][j], f)) });+ g.paper("paper", 0.1);+};++export const foxDraw: Film = {+ meta: { title: "Fox at dusk · laid down", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "foxDraw", start: 0, end: N, draw: (ctx, f, env) => drawFoxDraw(ctx, f, env) }],+};+export const STYLE = { id: "foxDraw", name: "Cut-paper collage, laid down", family: "collage", medium: "torn and scissor-cut coloured papers on a backing board, each lowered by hand onto the stack", nearest: "fox", hero: "Fox at dusk, assembled bottom layer up" };diff --git a/engine/src/canvas-core/fromPhoto.ts b/engine/src/canvas-core/fromPhoto.tsnew file mode 100644index 0000000..e145a7c--- /dev/null+++ b/engine/src/canvas-core/fromPhoto.ts@@ -0,0 +1,103 @@+// FROM PHOTO. A kit for drawings made FROM a user's photograph: the photo steers the marks, it is+// never shown. It reads a user asset (Film.assets.images -> env.image(name), decoded by the adapter+// before frame 0) into analysis fields, once per environment, cached:+// lum luminance 0..1 (Rec. 709 weights on the stored sRGB values)+// r, g, b the colour, 0..1, for coarse segmentation and for tint decisions+// J11/J12/J22 the smoothed structure tensor of lum: its minor eigenvector is the direction the+// texture runs (fur strands, wood grain, leaf veins), its anisotropy is how sure it is+// edge gradient magnitude, lightly smoothed+// Pure and deterministic: the pixels come from a decoded PNG drawn 1:1 into an env.canvas (no+// resampling), and every number after that is plain arithmetic. The fields are in PHOTO pixels;+// the sampler maps logical film coordinates to photo coordinates with one scale factor k.+import type { Env, P } from "./core";++export type PhotoFields = { iw: number; ih: number; lum: Float32Array; r: Float32Array; g: Float32Array; b: Float32Array; J11: Float32Array; J12: Float32Array; J22: Float32Array; edge: Float32Array };++// separable box blur, `passes` times (3 passes ~ a gaussian of sigma ~ r)+export const boxBlur = (src: Float32Array, w: number, h: number, r: number, passes = 3): Float32Array => {+ let a = src.slice(); const t = new Float32Array(src.length), n = 2 * r + 1;+ for (let p = 0; p < passes; p++) {+ for (let y = 0; y < h; y++) { const o = y * w; let s = 0; for (let i = -r; i <= r; i++) s += a[o + Math.min(w - 1, Math.max(0, i))]; for (let x = 0; x < w; x++) { t[o + x] = s / n; s += a[o + Math.min(w - 1, x + r + 1)] - a[o + Math.max(0, x - r)]; } }+ for (let x = 0; x < w; x++) { let s = 0; for (let i = -r; i <= r; i++) s += t[Math.min(h - 1, Math.max(0, i)) * w + x]; for (let y = 0; y < h; y++) { a[y * w + x] = s / n; s += t[Math.min(h - 1, y + r + 1) * w + x] - t[Math.max(0, y - r) * w + x]; } }+ }+ return a;+};++export const photoFields = (env: Env, name: string, o: { tensorR?: number } = {}): PhotoFields => {+ const tr = o.tensorR ?? 5, key = `photo:${name}:${tr}`; const hit = env.cache.get(key) as PhotoFields | undefined; if (hit) return hit;+ const img = env.image?.(name) as (CanvasImageSource & { width: number; height: number; naturalWidth?: number; naturalHeight?: number }) | undefined;+ if (!img) throw new Error(`fromPhoto: no image '${name}' (declare it in film.assets.images)`);+ const iw = img.naturalWidth ?? img.width, ih = img.naturalHeight ?? img.height, L = env.canvas(iw, ih);+ L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.clearRect(0, 0, iw, ih); L.ctx.drawImage(img, 0, 0);+ const d = L.ctx.getImageData(0, 0, iw, ih).data, n = iw * ih;+ const r = new Float32Array(n), g = new Float32Array(n), b = new Float32Array(n), lum = new Float32Array(n);+ for (let i = 0; i < n; i++) { r[i] = d[i * 4] / 255; g[i] = d[i * 4 + 1] / 255; b[i] = d[i * 4 + 2] / 255; lum[i] = 0.2126 * r[i] + 0.7152 * g[i] + 0.0722 * b[i]; }+ const gx = new Float32Array(n), gy = new Float32Array(n), J11 = new Float32Array(n), J12 = new Float32Array(n), J22 = new Float32Array(n), e = new Float32Array(n);+ for (let y = 1; y < ih - 1; y++) for (let x = 1; x < iw - 1; x++) {+ const i = y * iw + x, a = lum[i - iw - 1], bb = lum[i - iw], c = lum[i - iw + 1], dd = lum[i - 1], f = lum[i + 1], gg = lum[i + iw - 1], hh = lum[i + iw], ii = lum[i + iw + 1];+ const sx = (c + 2 * f + ii - a - 2 * dd - gg) / 8, sy = (gg + 2 * hh + ii - a - 2 * bb - c) / 8;+ gx[i] = sx; gy[i] = sy; J11[i] = sx * sx; J12[i] = sx * sy; J22[i] = sy * sy; e[i] = Math.hypot(sx, sy);+ }+ const F: PhotoFields = { iw, ih, lum, r, g, b, J11: boxBlur(J11, iw, ih, tr), J12: boxBlur(J12, iw, ih, tr), J22: boxBlur(J22, iw, ih, tr), edge: boxBlur(e, iw, ih, 1, 2) };+ env.cache.set(key, F);+ return F;+};++// ---------------------------------------------------------------- sampling in logical coordinates+export type PhotoSampler = ReturnType<typeof sampler>;+export const sampler = (F: PhotoFields, k: number) => {+ const { iw, ih } = F;+ const bil = (a: Float32Array, x: number, y: number) => { const fx = Math.min(iw - 1.001, Math.max(0, x / k - 0.5)), fy = Math.min(ih - 1.001, Math.max(0, y / k - 0.5)), i = Math.floor(fx), j = Math.floor(fy), u = fx - i, v = fy - j, q = j * iw + i; return (a[q] * (1 - u) + a[q + 1] * u) * (1 - v) + (a[q + iw] * (1 - u) + a[q + iw + 1] * u) * v; };+ return {+ k,+ lum: (x: number, y: number) => bil(F.lum, x, y),+ rgb: (x: number, y: number): [number, number, number] => [bil(F.r, x, y), bil(F.g, x, y), bil(F.b, x, y)],+ edge: (x: number, y: number) => bil(F.edge, x, y),+ // the texture's running direction (unit, sign-free) and how coherent it is (0..1)+ flow: (x: number, y: number): [number, number, number] => {+ const a = bil(F.J11, x, y), b = bil(F.J12, x, y), c = bil(F.J22, x, y), tr = a + c, det = Math.sqrt((a - c) * (a - c) + 4 * b * b), th = 0.5 * Math.atan2(2 * b, a - c) + Math.PI / 2;+ return [Math.cos(th), Math.sin(th), tr > 1e-9 ? det / tr : 0];+ },+ };+};+// grey-scale opening (min filter, then max filter, square window 2r+1): removes bright lines thinner+// than the window (whiskers, stray hairs) while keeping broad tone+export const openThinBright = (a: Float32Array, w: number, h: number, r: number): Float32Array => {+ const pass = (src: Float32Array, f: (x: number, y: number) => number) => { const out = new Float32Array(src.length), t = new Float32Array(src.length); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let v = src[y * w + x]; for (let i = Math.max(0, x - r); i <= Math.min(w - 1, x + r); i++) v = f(v, src[y * w + i]); t[y * w + x] = v; } for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let v = t[y * w + x]; for (let j = Math.max(0, y - r); j <= Math.min(h - 1, y + r); j++) v = f(v, t[j * w + x]); out[y * w + x] = v; } return out; };+ return pass(pass(a, Math.min), Math.max);+};+// orient a sign-free direction to agree with a hint, then lean on the hint where the photo is unsure+export const orient = (f: [number, number, number], hint: P, trust = 1): P => {+ let [dx, dy] = f; const c = Math.min(1, f[2] * trust); if (dx * hint[0] + dy * hint[1] < 0) { dx = -dx; dy = -dy; }+ const x = dx * c + hint[0] * (1 - c), y = dy * c + hint[1] * (1 - c), l = Math.hypot(x, y) || 1; return [x / l, y / l];+};++// ---------------------------------------------------------------- coarse segmentation helpers+// rasterise a closed outline (photo coordinates) into a byte mask at photo resolution+export const polyMask = (w: number, h: number, pts: P[], into?: Uint8Array, val = 1): Uint8Array => {+ const m = into ?? new Uint8Array(w * h);+ for (let y = 0; y < h; y++) {+ const yy = y + 0.5, xs: number[] = [];+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[i], b = pts[j]; if ((a[1] > yy) !== (b[1] > yy)) xs.push(a[0] + ((yy - a[1]) * (b[0] - a[0])) / (b[1] - a[1])); }+ xs.sort((a, b) => a - b);+ for (let q = 0; q + 1 < xs.length; q += 2) for (let x = Math.max(0, Math.ceil(xs[q] - 0.5)); x <= Math.min(w - 1, Math.floor(xs[q + 1] - 0.5)); x++) m[y * w + x] = val;+ }+ return m;+};+// label each pixel of a box by its nearest reference colour (squared RGB distance); -1 outside the box+export const classify = (F: PhotoFields, box: [number, number, number, number], refs: [number, number, number][], maxDist = 1): Int8Array => {+ const out = new Int8Array(F.iw * F.ih).fill(-1);+ for (let y = Math.max(0, box[1]); y < Math.min(F.ih, box[3]); y++) for (let x = Math.max(0, box[0]); x < Math.min(F.iw, box[2]); x++) {+ const i = y * F.iw + x; let best = -1, bd = maxDist;+ refs.forEach((c, k) => { const d = (F.r[i] - c[0]) ** 2 + (F.g[i] - c[1]) ** 2 + (F.b[i] - c[2]) ** 2; if (d < bd) { bd = d; best = k; } });+ out[i] = best;+ }+ return out;+};+// chamfer distance (photo px) from the nearest pixel NOT in the mask+export const distInside = (m: Uint8Array, w: number, h: number): Float32Array => {+ const d = new Float32Array(w * h); for (let i = 0; i < d.length; i++) d[i] = m[i] ? 1e6 : 0;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const k = y * w + x; if (!d[k]) continue; let v = d[k]; if (x) v = Math.min(v, d[k - 1] + 1); if (y) v = Math.min(v, d[k - w] + 1); if (x && y) v = Math.min(v, d[k - w - 1] + 1.414); if (y && x < w - 1) v = Math.min(v, d[k - w + 1] + 1.414); d[k] = v; }+ for (let y = h - 1; y >= 0; y--) for (let x = w - 1; x >= 0; x--) { const k = y * w + x; if (!d[k]) continue; let v = d[k]; if (x < w - 1) v = Math.min(v, d[k + 1] + 1); if (y < h - 1) v = Math.min(v, d[k + w] + 1); if (x < w - 1 && y < h - 1) v = Math.min(v, d[k + w + 1] + 1.414); if (y < h - 1 && x) v = Math.min(v, d[k + w - 1] + 1.414); d[k] = v; }+ return d;+};diff --git a/engine/src/canvas-core/halftone.ts b/engine/src/canvas-core/halftone.tsnew file mode 100644index 0000000..4fa36d9--- /dev/null+++ b/engine/src/canvas-core/halftone.ts@@ -0,0 +1,129 @@+import type { Ctx, Env, Layer, P } from "./core";+import type { Film } from "./film";+import { clamp, newsprint, plateLayer, screenDots, starve, toneAt } from "./halftoneKit";+import { buildTone } from "./halftoneScene";++// NEWSPRINT HALFTONE · two-colour, black plus one spot.+//+// MEDIUM, physically: a web-offset newspaper press. The photograph is broken by a contact+// screen into an AM halftone: dots on a fixed grid, their AREA carrying the tone. Two plates:+// BLACK on the classic 45 degree screen and ONE SPOT (a warm orange, the paper's colour ink) on+// its own screen 30 degrees away, at 15, so the two rosette instead of moire. Oil-based ink on+// unbleached groundwood newsprint: every dot soaks sideways into the fibres (dot GAIN, 20-30% in+// the midtones, so the shadows plug toward solid and the light dots fatten), its edge is ragged+// where the fibres wicked it, and a faint halo of spread ink sits round it. Highlights below ~4%+// do not hold on newsprint and drop out to bare paper. The paper stretches across the web+// between the spot unit and the black unit (fan-out) and the units are never quite in register,+// so the orange lands a hair wide and low: a sliver of it shows at the edges of dark shapes.+//+// MARKS: only dots. No line is drawn anywhere; every edge in the picture is where dot size+// changes. EDGE: the photo's own rectangle, with bare newsprint round it (where the misregister+// shows as a thin orange lip on one side). ORDER: the press, not a hand. The original (the+// photograph, built in halftoneScene.ts) is screened into two plates; the spot unit prints, then+// the black unit over it; both multiply, so orange under black is a warm near-black.+// PALETTE: black ink #1d1a17, spot orange #e86a2c, newsprint #e6dfcc. PAPER: newsprint with its+// grey-cream pulp cloud, short dark groundwood fibres, pale surface fibres and the odd bark shive.+//+// NOT RISOGRAPH (its nearest neighbour, lighthouse.ts): riso lays FLAT stencil drums of bright+// fluorescent soy ink that overprint into new colours, with hand-cut shapes and spot tints. This+// is a PHOTOGRAPH: one continuous tone field per ink, rendered only by dot size, dull oil ink,+// dot gain and fibre, one warm spot in a grey world. There are no shapes, only tone.+//+// SUBJECT, LIGHT, REFERENCE: see halftoneScene.ts (Ribblehead-type stone viaduct, a black 4-6-0+// and five coaches, golden hour, sun low to the right, the plume lit on its right flank).+//+// PROCESS (the film): the delivery pile at the end of the press during MAKE-READY. Each beat a+// new sheet is thrown onto the pile. The first sheets carry the spot unit alone, coming up to+// colour: starved and blotchy, then evening out ink key by ink key across the width. Then the+// black unit is thrown on and comes up the same way over the orange; the photograph appears.+// The spot is out of register (the pressman has had nothing to register it TO until the black+// is down); he nudges it in over the last sheets, and the final sheet is the approved print.++const N = 420, BEAT = 15;+// ---------------------------------------------------------------- the cue table (frames)+const CUE = { firstSheet: 15, blackOn: 135, register: 300, lastSheet: 375 } as const;+const SLIDE = 6; // frames for a thrown sheet to land+(() => { if (Object.values(CUE).some((f) => f % 15)) throw new Error("halftone: cue off the beat grid"); if (CUE.lastSheet + SLIDE > N - 30) throw new Error("halftone: the final sheet lands inside the hold"); })();+const SHEETS = (CUE.lastSheet - CUE.firstSheet) / BEAT + 1; // sheets thrown, the last one is the print++export const BLACK = "#1d1a17", SPOT = "#e86a2c";+const PITCH = 5.2, ANG_K = 45, ANG_S = 15, GAIN_K = 0.42, GAIN_S = 0.3, FAN = 0.0016;+const REG_FINAL: P = [1.2, 1.6]; // where the spot sits on the approved sheet (logical px)+const REG_START: P = [9, -7]; // where it sat before the pressman had the black to register to+const KEYS = 12; // ink keys across the width of the fountain++// the photograph occupies a rectangle on the sheet, bare paper round it+const photo = (W: number, H: number) => ({ x0: Math.round(W * 0.045), y0: Math.round(H * 0.045), x1: Math.round(W * 0.955), y1: Math.round(H * 0.955) });++const plates = (env: Env) => {+ const T = buildTone(env), b = photo(env.W, env.H), tag = `${env.W}x${env.H}@${env.scale}`;+ const inside = (x: number, y: number) => x >= b.x0 && x <= b.x1 && y >= b.y0 && y <= b.y1;+ const kDots = env.cache.get(`halftone:kdots:${tag}`) as ReturnType<typeof screenDots> | undefined ?? (() => { const d = screenDots(b, PITCH, ANG_K, (x, y) => (inside(x, y) ? toneAt(T, T.k, x, y) : 0), GAIN_K); env.cache.set(`halftone:kdots:${tag}`, d); return d; })();+ const sDots = env.cache.get(`halftone:sdots:${tag}`) as ReturnType<typeof screenDots> | undefined ?? (() => { const d = screenDots(b, PITCH, ANG_S, (x, y) => (inside(x, y) ? toneAt(T, T.s, x, y) : 0), GAIN_S, FAN); env.cache.set(`halftone:sdots:${tag}`, d); return d; })();+ return { k: plateLayer(env, `halftone:kplate:${tag}`, kDots, BLACK, 0.9, 7), s: plateLayer(env, `halftone:splate:${tag}`, sDots, SPOT, 0.8, 11), b };+};++// ---------------------------------------------------------------- the make-ready schedule+// Sheet i: how far the ink has come up across the width (0 starved .. 1 at colour), and where+// the spot sits. The fountain has KEYS ink keys; the oscillating rollers smear their settings+// sideways, so density varies smoothly across the sheet, never in hard strips.+type Sheet = { spot: (x: number) => number; black: (x: number) => number; reg: P; seed: number };+const hash = (a: number, b: number) => Math.abs(Math.sin(a * 12.9898 + b * 78.233) * 43758.5453) % 1;+const across = (level: number, seed: number) => (x: number) => { // x in 0..1 across the sheet+ if (level >= 1) return 1; if (level <= 0) return 0;+ const f = x * (KEYS - 1), i = Math.floor(f), t = f - i, e = (1 - Math.cos(t * Math.PI)) / 2, key = (z: number) => clamp(level * 1.5 - hash(z, seed) * 0.6 - 0.1);+ return key(i) * (1 - e) + key(Math.min(KEYS - 1, i + 1)) * e;+};+const I_BLACK = (CUE.blackOn - CUE.firstSheet) / BEAT, I_REG = (CUE.register - CUE.firstSheet) / BEAT;+const sheet = (i: number): Sheet => {+ const done = i >= SHEETS - 1, lS = done ? 1 : Math.min(1, (i + 1) / I_BLACK) * (i >= I_BLACK + 2 ? 2 : 1), lK = done ? 1 : i < I_BLACK ? 0 : Math.min(1, (i - I_BLACK + 1) / (I_REG - I_BLACK)) * (i >= I_REG ? 2 : 1);+ const nudge = clamp((i - I_REG) / (SHEETS - 1 - I_REG)), reg: P = [REG_START[0] + (REG_FINAL[0] - REG_START[0]) * nudge, REG_START[1] + (REG_FINAL[1] - REG_START[1]) * nudge];+ return { spot: across(lS, 3 + (i % 3)), black: across(lK, 7 + (i % 2)), reg, seed: i };+};++// one sheet off the press, composited onto its own surface+const STRIPS = 54;+const printSheet = (env: Env, i: number): Layer => {+ const key = `halftone:sheet:${i}:${env.W}x${env.H}@${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ // keep only the sheets on top of the pile: an evicted sheet is rebuilt identically if asked for+ for (const ck of [...env.cache.keys()]) if (ck.startsWith("halftone:sheet:")) { const n = Number(ck.split(":")[2]); if (n < i - 1 || n > i + 1) env.cache.delete(ck); }+ const W = env.W, H = env.H, k = env.scale, DW = Math.round(W * k), DH = Math.round(H * k);+ L = env.canvas(DW, DH); const c = L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.drawImage(newsprint(env, `halftone:paper:${W}x${H}@${k}`).canvas, 0, 0);+ if (i < 0) { env.cache.set(key, L); return L; }+ const sh = sheet(i), P = plates(env), tk = `halftone:tmp:${DW}x${DH}`, tmp = (env.cache.get(tk) as Layer | undefined) ?? (() => { const t = env.canvas(DW, DH); env.cache.set(tk, t); return t; })();+ const ink = (plate: Layer, dens: (x: number) => number, off: P, seed: number) => {+ const sw = W / STRIPS, d = Array.from({ length: STRIPS }, (_, z) => dens((z + 0.5) / STRIPS));+ if (d.every((v) => v <= 0)) return;+ const t = tmp.ctx; t.setTransform(1, 0, 0, 1, 0, 0); t.globalCompositeOperation = "copy"; t.drawImage(plate.canvas, Math.round(off[0] * k), Math.round(off[1] * k)); t.globalCompositeOperation = "source-over";+ const sft: P = [hash(seed, 1) * 256, hash(seed, 2) * 256];+ d.forEach((v, z) => { if (v < 1) starve(t, env, [z * sw, 0, (z + 1) * sw, H], 1 - v * 0.9, sft); });+ // where a key is barely open the film of ink is thin: the zone prints light as well as broken+ c.save(); c.globalCompositeOperation = "multiply";+ d.forEach((v, z) => { if (v <= 0) return; const x0 = Math.floor(z * sw * k), x1 = z === STRIPS - 1 ? DW : Math.floor((z + 1) * sw * k); c.globalAlpha = v >= 1 ? 1 : 0.3 + 0.7 * v; c.drawImage(tmp.canvas, x0, 0, x1 - x0, DH, x0, 0, x1 - x0, DH); });+ c.restore();+ };+ ink(P.s, sh.spot, sh.reg, sh.seed * 2 + 1);+ ink(P.k, sh.black, [0, 0], sh.seed * 2 + 2);+ env.cache.set(key, L); return L;+};++const draw = (ctx: Ctx, f: number, env: Env) => {+ const k = env.scale, DW = Math.round(env.W * k), DH = Math.round(env.H * k);+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ const n = f < CUE.firstSheet ? -1 : Math.min(SHEETS - 1, Math.floor((f - CUE.firstSheet) / BEAT)), t0 = CUE.firstSheet + n * BEAT, u = n < 0 ? 1 : clamp((f - t0) / SLIDE);+ if (f >= CUE.lastSheet + SLIDE || u >= 1) { ctx.drawImage(printSheet(env, n).canvas, 0, 0); return; }+ // a sheet in flight: thrown from the top, it slides down over the pile and lands+ ctx.drawImage(printSheet(env, n - 1).canvas, 0, 0);+ const e = 1 - Math.pow(1 - u, 3), y = Math.round(-DH * (1 - e));+ const sg = ctx.createLinearGradient(0, y + DH, 0, y + DH + 26 * k); sg.addColorStop(0, "rgba(30,25,20,0.32)"); sg.addColorStop(1, "rgba(30,25,20,0)");+ ctx.fillStyle = sg; ctx.fillRect(0, y + DH, DW, 26 * k); // its shadow on the sheet below+ ctx.drawImage(printSheet(env, n).canvas, 0, y);+};++export const halftone: Film = {+ meta: { title: "Viaduct at golden hour · newsprint halftone", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "makeready", start: 0, end: N, draw }],+};++export const STYLE = { id: "halftone", name: "Newsprint halftone", family: "print", medium: "web-offset newspaper print: black on a 45 degree AM screen plus one orange spot at 15 degrees, oil ink gaining into unbleached groundwood newsprint", nearest: "lighthouse", hero: "a steam train crossing a stone viaduct at golden hour" };diff --git a/engine/src/canvas-core/halftoneKit.ts b/engine/src/canvas-core/halftoneKit.tsnew file mode 100644index 0000000..b358aa2--- /dev/null+++ b/engine/src/canvas-core/halftoneKit.ts@@ -0,0 +1,115 @@+// HALFTONE KIT. What a newspaper press needs that the core does not have: a continuous-tone+// ORIGINAL held as two float separations (black and spot), an AM screen that turns one of them+// into irregular, ink-spread dots, the newsprint sheet with its fibres, and the ink-starve mottle+// of a press still coming up to colour. Everything is geometry, seeded tiles or image data built+// once and cached under a key that names what its pixels depend on. No filters, no assets.+import { fractal, rng, type Ctx, type Env, type Layer, type P } from "./core";++export const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));+export const smoothstep = (a: number, b: number, v: number) => { const t = clamp((v - a) / (b - a)); return t * t * (3 - 2 * t); };++// ---------------------------------------------------------------- the original: two separations+// k = black density 0..1, s = spot density 0..1, both at w x h over the logical frame W x H.+export type Tone = { w: number; h: number; W: number; H: number; k: Float32Array; s: Float32Array };+export const newTone = (w: number, h: number, W: number, H: number): Tone => ({ w, h, W, H, k: new Float32Array(w * h), s: new Float32Array(w * h) });+// bilinear read of one separation at a LOGICAL point+export const toneAt = (t: Tone, ch: Float32Array, x: number, y: number) => {+ const fx = clamp((x / t.W) * t.w - 0.5, 0, t.w - 1.001), fy = clamp((y / t.H) * t.h - 0.5, 0, t.h - 1.001), i = Math.floor(fx), j = Math.floor(fy), u = fx - i, v = fy - j, a = j * t.w + i;+ return (ch[a] * (1 - u) + ch[a + 1] * u) * (1 - v) + (ch[a + t.w] * (1 - u) + ch[a + t.w + 1] * u) * v;+};+// Composite a painted RGBA surface over the separations: R = black, G = spot, A = coverage.+// `tex(i, j, bChannel, k, s)` may alter the painted values per pixel (stone courses, weathering)+// and returns [k, s]. The B channel is a material id, read only where coverage is full.+export const over = (t: Tone, L: Layer, tex?: (x: number, y: number, mat: number, k: number, s: number) => [number, number]) => {+ const d = L.ctx.getImageData(0, 0, t.w, t.h).data, sx = t.W / t.w, sy = t.H / t.h;+ for (let j = 0; j < t.h; j++) for (let i = 0; i < t.w; i++) {+ const p = (j * t.w + i) * 4, a = d[p + 3] / 255; if (a <= 0) continue;+ let k = d[p] / 255, s = d[p + 1] / 255; if (tex) [k, s] = tex((i + 0.5) * sx, (j + 0.5) * sy, d[p + 2], k, s);+ const q = j * t.w + i; t.k[q] = t.k[q] * (1 - a) + k * a; t.s[q] = t.s[q] * (1 - a) + s * a;+ }+};+// a colour for painting a separation surface: black density k, spot density s, material m+export const ks = (k: number, s: number, m = 0, a = 1) => `rgba(${Math.round(clamp(k) * 255)},${Math.round(clamp(s) * 255)},${m},${a})`;++// ---------------------------------------------------------------- the screen+// A newspaper AM screen: dots on a rotated grid, area proportional to tone. On newsprint the+// finest highlight dots do not hold (they drop out below ~4%), and every dot GAINS as the ink+// soaks sideways into the fibres, so the shadows plug toward solid. `fan` is the paper's+// fan-out: the sheet stretches across its width between units, so the spot lands a little wider.+export type Dot = [number, number, number];+export const screenDots = (b: { x0: number; y0: number; x1: number; y1: number }, pitch: number, ang: number, tone: (x: number, y: number) => number, gain: number, fan = 0): Dot[] => {+ const a = (ang * Math.PI) / 180, c = Math.cos(a), sn = Math.sin(a), cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, R = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) / 2 + pitch, out: Dot[] = [];+ for (let u = -R; u <= R; u += pitch) for (let v = -R; v <= R; v += pitch) {+ const x = cx + u * c - v * sn, y = cy + u * sn + v * c; if (x < b.x0 - pitch || x > b.x1 + pitch || y < b.y0 - pitch || y > b.y1 + pitch) continue;+ const t = clamp(tone(x, y)); if (t < 0.045) continue;+ // area-true: a dot's area is the tone (sqrt(t / pi)), swelling past 70% so the dots join into a+ // solid with pinholes; then the gain, strongest in the midtones where the dot's edge is longest+ const r = pitch * (Math.sqrt(t / Math.PI) + 0.17 * t * t * t) + gain * (0.5 + 2 * t * (1 - t));+ out.push([x + (x - b.x0) * fan, y, r]);+ }+ return out;+};+// Ink the dots: each an irregular heptagon, its radius bitten by a fixed per-dot hash, so no two+// dots are the same shape and the pattern never looks like a vector grid.+export const inkDots = (c: Ctx, dots: Dot[], seed: number) => {+ c.beginPath();+ for (const [x, y, r] of dots) {+ if (r < 0.35) continue;+ const h = Math.abs(Math.sin(x * 12.9898 + y * 78.233 + seed) * 43758.5453), n = 7, a0 = (h % 1) * 6.283;+ for (let k = 0; k <= n; k++) { const a = a0 + (k / n) * 6.283, w = 1 + 0.14 * Math.sin(a * 2 + h) + 0.08 * Math.sin(a * 3 + h * 1.7), px = x + Math.cos(a) * r * w, py = y + Math.sin(a) * r * w; k ? c.lineTo(px, py) : c.moveTo(px, py); }+ c.closePath();+ }+ c.fill();+};++// ---------------------------------------------------------------- the ink on the paper+// A plate: its dots inked once onto a full-size transparent layer, with the soft wet halo of ink+// spreading into newsprint (a blurred copy of the same dots, never the dots drawn twice).+export const plateLayer = (env: Env, key: string, dots: Dot[], color: string, spread: number, seed: number): Layer => {+ let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), k = env.scale;+ L = env.canvas(DW, DH); const c = L.ctx; c.setTransform(k, 0, 0, k, 0, 0); c.fillStyle = color; inkDots(c, dots, seed);+ // spread: the same dots drawn small and back up (a portable blur), laid UNDER the crisp dots+ const q = Math.max(1, Math.round(DW / (spread * k * 2.2))), qh = Math.max(1, Math.round((q * DH) / DW)), S = env.canvas(q, qh);+ S.ctx.imageSmoothingEnabled = true; S.ctx.drawImage(L.canvas, 0, 0, q, qh);+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "destination-over"; c.globalAlpha = 0.5; c.imageSmoothingEnabled = true; c.drawImage(S.canvas, 0, 0, DW, DH); c.globalAlpha = 1; c.globalCompositeOperation = "source-over";+ env.cache.set(key, L); return L;+};++// ---------------------------------------------------------------- the sheet+// Newsprint: groundwood pulp, unbleached, so it is grey-cream and full of short dark fibres and+// the odd longer pale one lying on the surface. Built once per size.+export const NEWSPRINT = "#e6dfcc";+export const newsprint = (env: Env, key: string): Layer => {+ let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const W = env.W, H = env.H, k = env.scale; L = env.canvas(Math.round(W * k), Math.round(H * k)); const c = L.ctx;+ c.setTransform(k, 0, 0, k, 0, 0); c.fillStyle = NEWSPRINT; c.fillRect(0, 0, W, H);+ // a slow cloud in the pulp: newsprint is never one flat colour+ const img = c.getImageData(0, 0, L.canvas.width, L.canvas.height), d = img.data, n = L.canvas.width;+ for (let y = 0; y < L.canvas.height; y += 1) for (let x = 0; x < n; x += 1) { const v = fractal(301, x / k, y / k, 0.006, 0.006, 3) - 0.5, g = fractal(302, x / k, y / k, 0.35, 0.35, 1) - 0.5, p = (y * n + x) * 4, o = v * 16 + g * 7; d[p] += o; d[p + 1] += o; d[p + 2] += o * 1.2; }+ c.putImageData(img, 0, 0); c.setTransform(k, 0, 0, k, 0, 0);+ const r = rng(303), area = W * H;+ for (let i = 0; i < area / 900; i++) { // short dark groundwood fibres, most tiny, a few longer+ const x = r() * W, y = r() * H, len = 1.5 + Math.pow(r(), 3) * 12, a = r() * 6.283, bend = (r() - 0.5) * 0.9, dark = r() < 0.8;+ c.strokeStyle = dark ? `rgba(92,78,58,${0.1 + r() * 0.22})` : `rgba(250,246,236,${0.3 + r() * 0.4})`; c.lineWidth = 0.35 + r() * 0.5;+ c.beginPath(); c.moveTo(x, y); c.quadraticCurveTo(x + Math.cos(a + bend) * len * 0.5, y + Math.sin(a + bend) * len * 0.5, x + Math.cos(a) * len, y + Math.sin(a) * len); c.stroke();+ }+ for (let i = 0; i < area / 60000; i++) { const x = r() * W, y = r() * H, s = 0.6 + r() * 1.1; c.fillStyle = `rgba(70,55,40,${0.25 + r() * 0.3})`; c.beginPath(); c.ellipse(x, y, s, s * (0.4 + r() * 0.5), r() * 3, 0, 6.283); c.fill(); } // shives: bark flecks+ env.cache.set(key, L); return L;+};++// ---------------------------------------------------------------- starve mottle+// A press coming up to colour lays ink unevenly: streaks running with the feed where the ink train+// has not wetted the rollers yet, and a broken speckle where the film is too thin to transfer. An alpha tile of that blotch, built once; knocked OUT of a plate by how starved it is.+export const mottleTile = (env: Env): Layer => {+ const key = `halftone:mottle:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const n = 256; L = env.canvas(n, n); const img = L.ctx.createImageData(n, n), d = img.data;+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) { const v = fractal(311, x, y, 0.09, 0.012, 3, n) * 0.7 + fractal(312, x, y, 0.5, 0.5, 1, n) * 0.3, p = (y * n + x) * 4; d[p] = d[p + 1] = d[p + 2] = 0; d[p + 3] = 255 * clamp((v - 0.38) * 3.5); /* streaks along the feed, and a fine broken speckle */ }+ L.ctx.putImageData(img, 0, 0); env.cache.set(key, L); return L;+};+export const starve = (c: Ctx, env: Env, rect: [number, number, number, number], amount: number, shift: P) => {+ if (amount <= 0.001) return; const t = mottleTile(env), k = env.scale;+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.beginPath(); c.rect(rect[0] * k, rect[1] * k, (rect[2] - rect[0]) * k, (rect[3] - rect[1]) * k); c.clip();+ c.setTransform(k * 1.6, 0, 0, k * 1.6, shift[0] * k, shift[1] * k); c.globalCompositeOperation = "destination-out"; c.globalAlpha = clamp(amount);+ c.fillStyle = c.createPattern(t.canvas, "repeat")!; c.fillRect(-shift[0] / 1.6 - 10, -shift[1] / 1.6 - 10, env.W / 1.6 + 20, env.H / 1.6 + 20); c.restore();+};diff --git a/engine/src/canvas-core/halftoneScene.ts b/engine/src/canvas-core/halftoneScene.tsnew file mode 100644index 0000000..9e561c8--- /dev/null+++ b/engine/src/canvas-core/halftoneScene.ts@@ -0,0 +1,272 @@+// HALFTONE SCENE: the continuous-tone ORIGINAL the newspaper screens. This is the photograph,+// held as two separations (black density, spot density), built by a pinhole camera over a real+// structure in metres. Nothing here is a mark on paper; the marks are made in halftone.ts.+//+// REFERENCE (from knowledge): Ribblehead Viaduct, North Yorkshire: 24 semicircular arches of+// ~13.7 m span on limestone piers ~32 m high, a thicker KING PIER every sixth pier, coursed+// rubble faces with a dressed arch ring, a string course and a plain parapet; the valley of the+// Ribble with dry-stone-walled pasture and a beck under the arches; Whernside's long ridge behind.+// The engine is a mixed-traffic 4-6-0 of the LMS Black Five kind in plain black: smokebox with+// its door and handrail, a stovepipe chimney, a dome midway along the boiler, Belpaire firebox+// with square shoulders, a cab with a roof overhang, 6 ft driving wheels (their tops alone show+// over the parapet), and a high-sided tender with coal heaped at the front; five maroon Mk1+// coaches behind. Structure borrowed, no real locomotive's number or livery detail copied.+//+// LIGHT: golden hour, the sun low (about 12 degrees) off to the RIGHT and a little toward the+// camera. It rakes the viaduct's face so every course of stone throws a hairline shadow, leaves+// the pier returns and the arch barrels in shade, lights the steam plume on its right flank with+// a warm rim and leaves its left side a cool grey, and puts a glow into the right of the sky.+// CAST SHADOWS: the viaduct throws a band of shade on the valley floor BEHIND it (the sun is so+// low that no light gets through the arches), the parapet shades the coaches' lower panels, the+// cornice drops a line of shade across the face, the plume shades itself.+import { fractal, rng, type Env, type P } from "./core";+import { clamp, ks, newTone, over, smoothstep, type Tone } from "./halftoneKit";++type V3 = [number, number, number];+// ---------------------------------------------------------------- the camera (metres)+// on the hillside across the beck, 15 m up (well below the deck, so the train stands against the+// sky and the piers tower), 50 degrees round from face-on: the viaduct recedes to the right.+export const camera = (W: number, H: number) => {+ const C: V3 = [-18, 15, 50], yaw = (50 * Math.PI) / 180, F = W * 1.22, cx = W * 0.52, cy = H * 0.65;+ const fw: V3 = [Math.sin(yaw), 0, -Math.cos(yaw)], rt: V3 = [Math.cos(yaw), 0, Math.sin(yaw)];+ const proj = (p: V3): P => { const dx = p[0] - C[0], dz = p[2] - C[2], xc = dx * rt[0] + dz * rt[2], zc = dx * fw[0] + dz * fw[2]; return [cx + (F * xc) / zc, cy - (F * (p[1] - C[1])) / zc]; };+ const depth = (p: V3) => (p[0] - C[0]) * fw[0] + (p[2] - C[2]) * fw[2];+ // screen -> the ground plane Y = y0 (null above the horizon)+ const ground = (x: number, y: number, y0 = 0): V3 | null => { if (y <= cy + 0.5) return null; const zc = (F * (C[1] - y0)) / (y - cy), xc = ((x - cx) * zc) / F; return [C[0] + xc * rt[0] + zc * fw[0], y0, C[2] + xc * rt[2] + zc * fw[2]]; };+ // screen -> the viaduct's face plane Z = 0+ const face = (x: number, y: number): V3 => { const u = (x - cx) / F, zc = -C[2] / (u * rt[2] + fw[2]); return [C[0] + zc * (u * rt[0] + fw[0]), C[1] - ((y - cy) / F) * zc, 0]; };+ return { C, F, cx, cy, proj, depth, ground, face };+};+export type Cam = ReturnType<typeof camera>;++// ---------------------------------------------------------------- the viaduct (metres)+export const SPAN = 15, NPIER = 16, SPRING = 22.5, DECK = 30.2, CORNICE = 30.75, PARAPET = 31.6, DEPTH = 6.4, RAIL = 30.5;+const halfW = (k: number, y: number) => (k % 6 === 0 && k > 0 ? 2.3 : 1.25) + 0.028 * (SPRING - Math.min(y, SPRING)) ; // battered piers; every 6th a king pier+const LIGHT: V3 = (() => { const v: V3 = [0.9, 0.21, 0.28], l = Math.hypot(...v); return [v[0] / l, v[1] / l, v[2] / l]; })();++// one arch opening in the plane Z = z, between pier k and k+1, as a world outline+const opening = (k: number, z: number): V3[] => {+ const a = k * SPAN + halfW(k, SPRING), b = (k + 1) * SPAN - halfW(k + 1, SPRING), r = (b - a) / 2, m = (a + b) / 2, out: V3[] = [];+ out.push([k * SPAN + halfW(k, 0), 0, z]);+ for (let i = 0; i <= 28; i++) { const t = Math.PI - (i / 28) * Math.PI; out.push([m + Math.cos(t) * r, SPRING + Math.sin(t) * r, z]); }+ out.push([(k + 1) * SPAN - halfW(k + 1, 0), 0, z]);+ return out;+};++// ---------------------------------------------------------------- the train (metres)+// side elevation of the engine and tender, x measured BACK from the buffer beam, y above rail.+// The engine runs toward -X (toward the near end), so world X = X0 + x.+export const X0 = 25;+const ENGINE: P[] = [ // outline of the whole side, clockwise from the front buffer beam foot+ [0, 0.9], [0, 1.35], [0.25, 1.35], [0.3, 2.0], [0.45, 2.3], [0.62, 3.25], [0.8, 3.55], [1.0, 3.62], // smokebox front, its door bulging+ [1.12, 3.62], [1.12, 4.02], [1.08, 4.08], [1.58, 4.08], [1.54, 4.02], [1.54, 3.64], // stovepipe chimney with a lip+ [2.05, 3.63], [4.25, 3.6], [4.35, 3.78], [4.5, 3.93], [4.95, 3.93], [5.1, 3.78], [5.2, 3.59], // boiler, dome+ [7.4, 3.56], [7.5, 3.72], [7.65, 3.78], [9.1, 3.78], [9.2, 3.72], // Belpaire firebox shoulders+ [9.25, 3.95], [9.3, 4.02], [11.55, 4.02], [11.6, 3.95], // cab roof, overhang at the back+ [11.55, 1.4], [11.75, 1.4], [11.75, 3.35], [19.6, 3.35], [19.6, 1.2], [11.75, 1.2], // tender+ [11.6, 0.9],+];+const COACH = 20.2, COACHES = 5, GAP = 0.7;+// the plume's source: chimney top, world+export const CHIMNEY: V3 = [X0 + 1.33, RAIL + 4.1, -DEPTH / 2];++// ---------------------------------------------------------------- the valley behind (2D, screen)+// Whernside's long whaleback on the left and a nearer fell with a limestone scar on the right,+// both hazed toward the light. Heights are screen y at logical width 1080, scaled.+const ridgeFar = (x: number, W: number) => { const u = x / W; return W * (0.458 + 0.05 * u + 0.018 * Math.sin(u * 5.2 + 0.6) + 0.012 * (fractal(401, x, 0, 3 / W, 3 / W, 3) - 0.5) - 0.03 * smoothstep(0.55, 1.0, u)); };+const ridgeNear = (x: number, W: number) => { const u = x / W; return W * (0.545 + 0.022 * Math.sin(u * 3.1 + 2.2) - 0.035 * Math.exp(-Math.pow((u - 0.78) / 0.12, 2)) + 0.01 * (fractal(402, x, 0, 6 / W, 6 / W, 3) - 0.5)); };++// ---------------------------------------------------------------- building the original+export const buildTone = (env: Env): Tone => {+ const key = `halftone:tone:${env.W}x${env.H}`; const hit = env.cache.get(key) as Tone | undefined; if (hit) return hit;+ const W = env.W, H = env.H, cam = camera(W, H), tw = Math.round(W / 2), th = Math.round(H / 2), T = newTone(tw, th, W, H);+ const sun = cam.proj([cam.C[0] + LIGHT[0] * 1e4, cam.C[1] + LIGHT[1] * 1e4, cam.C[2] + LIGHT[2] * 1e4]);+ const sx = W / tw, sy = H / th;+ // 1. sky, hills, valley floor: per pixel+ for (let j = 0; j < th; j++) for (let i = 0; i < tw; i++) {+ const x = (i + 0.5) * sx, y = (j + 0.5) * sy, q = j * tw + i;+ let k: number, s: number;+ const glow = Math.exp(-Math.pow(Math.hypot((x - sun[0]) * 0.55, y - sun[1]) / (W * 0.5), 2));+ const up = clamp(1 - y / cam.cy);+ const halo = Math.exp(-Math.pow(Math.hypot((x - sun[0]) * 0.45, (y - sun[1]) * 1.4) / (W * 0.62), 2));+ k = 0.3 + 0.26 * Math.pow(up, 1.2) - 0.24 * halo * (1 - up * 0.6); s = 0.22 + 0.3 * (1 - up) + 0.5 * halo - 0.12 * up;+ // strata of cloud low in the west, their undersides lit+ const band = (yc: number, w: number, seed: number) => { const n = fractal(seed, x, y, 0.004, 0.03, 3); return clamp((n - 0.5) * 4) * Math.exp(-Math.pow((y - yc - (n - 0.5) * 30) / w, 2)); };+ const cl = band(H * 0.3, H * 0.022, 411) * 0.9 + band(H * 0.37, H * 0.015, 412) * 0.7 + band(H * 0.19, H * 0.03, 413) * 0.5;+ const rimLit = clamp((fractal(414, x, y + 6, 0.004, 0.03, 3) - fractal(414, x, y, 0.004, 0.03, 3)) * 40); k += cl * 0.3 - rimLit * cl * 0.3; s += cl * 0.15 * (0.5 + halo) + rimLit * cl * 0.4 * halo;+ const rf = ridgeFar(x, W), rn = ridgeNear(x, W);+ if (y > rf) { const d = (y - rf) / (H * 0.1); k = 0.2 + 0.08 * clamp(d) + 0.05 * (fractal(421, x, y, 0.02, 0.05, 3) - 0.5); s = 0.36 - 0.06 * clamp(d) + 0.1 * glow; }+ if (y > rn) { // the nearer fell: rough pasture, a pale limestone scar near its top, walls running down it+ const d = clamp((y - rn) / (H * 0.07)), n = fractal(431, x, y, 0.015, 0.04, 3), scar = Math.exp(-Math.pow((y - rn - H * 0.012) / (H * 0.006), 2)) * smoothstep(0.55, 0.7, x / W) * clamp((n - 0.35) * 3);+ k = 0.3 + 0.12 * d + 0.12 * (n - 0.5) - 0.2 * scar; s = 0.3 - 0.05 * d + 0.12 * scar + 0.06 * glow;+ const wall = Math.abs(((x * 0.9 + y * 2.1 + fractal(432, x, y, 0.01, 0.01, 2) * 60) % 70) - 35) < 0.9; if (wall) k += 0.04;+ }+ const g = cam.ground(x, y);+ if (g && y > rn + H * 0.045) {+ // valley floor: walled pasture in perspective, the beck, the viaduct's long shade behind it+ const X = g[0], Z = g[2], dist = Math.hypot(X - cam.C[0], Z - cam.C[2]), haze = clamp((dist - 60) / 900);+ const fx = Math.floor((X + 13 * Math.sin(Z * 0.011)) / 70), fz = Math.floor((Z + 9 * Math.sin(X * 0.017)) / 55), rr = rng(fx * 7919 + fz * 131 + 5)(), field = 0.26 + rr * 0.14;+ const wallX = Math.abs((((X + 13 * Math.sin(Z * 0.011)) % 70) + 70) % 70 - 35) > 34.3, wallZ = Math.abs((((Z + 9 * Math.sin(X * 0.017)) % 55) + 55) % 55 - 27.5) > 27.0;+ const grass = fractal(441, X, Z, 0.08, 0.08, 3) - 0.5;+ k = field + grass * 0.14 + (wallX || wallZ ? 0.12 * (1 - haze) * (fractal(443, X, Z, 0.3, 0.3, 1) > 0.42 ? 1 : 0) : 0); s = 0.36 - rr * 0.08;+ const beckX = 47 + 9 * Math.sin(Z * 0.045 + 1) + 5 * Math.sin(Z * 0.11) + 0.18 * Z, dB = Math.abs(X - beckX) * 0.9;+ if (dB < 2.6) { const ripple = fractal(442, X, Z * 0.35, 0.9, 0.9, 2); k = 0.04 + 0.4 * clamp((0.56 - ripple) * 4); s = 0.25 + 0.35 * glow; } // the beck throws back the bright western sky+ else if (dB < 5.5) { k += 0.12; } // the beck's shadowed banks and alders+ const shade = Z < 0 && Z > -34 - 6 * Math.sin(X * 0.05); // the viaduct's own shadow, thrown back across the floor+ if (shade) { k = k * 0.8 + 0.3; s *= 0.35; } else if (Z >= 0) { s += 0.08; } // sunlit pasture on our side of it+ k = k * (1 - haze * 0.55) + 0.2 * haze; s = s * (1 - haze * 0.4) + 0.3 * haze;+ }+ T.k[q] = clamp(k); T.s[q] = clamp(s);+ }++ // 2. the viaduct and the train, painted as geometry onto a separation surface, then laid over+ const L = env.canvas(tw, th), c = L.ctx; c.setTransform(tw / W, 0, 0, th / H, 0, 0);+ const pth = (pts: P[]) => { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); };+ const pr = (pts: V3[]) => pts.map((p) => cam.proj(p));+ const visible = (k: number) => { const a = cam.proj([k * SPAN, 0, 0]), b = cam.proj([(k + 1) * SPAN, 0, 0]); return b[0] > -80 && a[0] < W + 80; };+ // 2a. inside each arch: the pier return (in shade) and the barrel soffit (shade, warmed by the+ // bounce off the sunlit pasture), then the far opening knocked back out so the valley shows.+ for (let k = -1; k < NPIER; k++) {+ if (!visible(k)) continue;+ const front = pr(opening(k, 0)), back = pr(opening(k, -DEPTH));+ c.save(); pth(front); c.clip();+ const top = cam.proj([(k + 0.5) * SPAN, SPRING + 6, 0]), bot = cam.proj([(k + 0.5) * SPAN, 0, 0]);+ const gr = c.createLinearGradient(0, top[1], 0, bot[1]); gr.addColorStop(0, ks(0.6, 0.1, 20)); gr.addColorStop(0.35, ks(0.5, 0.16, 20)); gr.addColorStop(1, ks(0.4, 0.24, 20));+ c.fillStyle = gr; c.fillRect(-50, -50, W + 100, H + 100);+ c.globalCompositeOperation = "destination-out"; pth(back); c.fill(); c.globalCompositeOperation = "source-over";+ // the springing line where the barrel meets the pier return: a hard crease of shade+ c.strokeStyle = ks(0.8, 0.05, 21); c.lineWidth = 1.4; const s0 = cam.proj([(k + 1) * SPAN - halfW(k + 1, SPRING), SPRING, 0]), s1 = cam.proj([(k + 1) * SPAN - halfW(k + 1, SPRING), SPRING, -DEPTH]); c.beginPath(); c.moveTo(s0[0], s0[1]); c.lineTo(s1[0], s1[1]); c.stroke();+ c.restore();+ }+ // 2b. the face: one plane of coursed stone, arches cut through it (even-odd)+ const faceTop = pr([[-SPAN, CORNICE, 0], [NPIER * SPAN, CORNICE, 0]]), faceBot = pr([[NPIER * SPAN, 0, 0], [-SPAN, 0, 0]]);+ c.beginPath(); [faceTop[0], faceTop[1], faceBot[0], faceBot[1]].forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath();+ for (let k = -1; k < NPIER; k++) { const o = pr(opening(k, 0)); o.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }+ c.fillStyle = ks(0.2, 0.44, 10); c.fill("evenodd");+ // arch rings: the dressed voussoirs, a band a little paler than the rubble, each ring stone jointed+ for (let k = -1; k < NPIER; k++) {+ if (!visible(k)) continue;+ const a = k * SPAN + halfW(k, SPRING), b = (k + 1) * SPAN - halfW(k + 1, SPRING), r = (b - a) / 2, m = (a + b) / 2, R = r + 0.95;+ const ring: V3[] = []; for (let i = 0; i <= 30; i++) { const t = Math.PI - (i / 30) * Math.PI; ring.push([m + Math.cos(t) * R, SPRING + Math.sin(t) * R, 0]); } for (let i = 30; i >= 0; i--) { const t = Math.PI - (i / 30) * Math.PI; ring.push([m + Math.cos(t) * r, SPRING + Math.sin(t) * r, 0]); }+ pth(pr(ring)); c.fillStyle = ks(0.13, 0.46, 11); c.fill();+ c.strokeStyle = ks(0.42, 0.3, 12); c.lineWidth = 0.7;+ for (let i = 1; i < 26; i++) { const t = Math.PI - (i / 26) * Math.PI, p0 = cam.proj([m + Math.cos(t) * r, SPRING + Math.sin(t) * r, 0]), p1 = cam.proj([m + Math.cos(t) * R, SPRING + Math.sin(t) * R, 0]); c.beginPath(); c.moveTo(p0[0], p0[1]); c.lineTo(p1[0], p1[1]); c.stroke(); }+ }+ // the cornice: a projecting string course, lit on its top lip, throwing a line of shade under it+ const strip = (y0: number, y1: number, z: number): P[] => pr([[-SPAN, y0, z], [NPIER * SPAN, y0, z], [NPIER * SPAN, y1, z], [-SPAN, y1, z]]);+ pth(strip(CORNICE - 0.55, CORNICE - 0.15, 0)); c.fillStyle = ks(0.55, 0.18, 13); c.fill(); // its cast shade on the face+ pth(strip(CORNICE - 0.15, CORNICE + 0.25, 0.3)); c.fillStyle = ks(0.3, 0.38, 13); c.fill(); // the course's face+ pth(strip(CORNICE + 0.25, CORNICE + 0.33, 0.3)); c.fillStyle = ks(0.02, 0.55, 13); c.fill(); // its lit top lip+ pth(strip(CORNICE + 0.33, PARAPET, 0.05)); c.fillStyle = ks(0.24, 0.42, 14); c.fill(); // the parapet+ pth(strip(PARAPET, PARAPET + 0.12, 0.05)); c.fillStyle = ks(0.05, 0.58, 13); c.fill(); // coping, catching the sun++ // 2c. the train, behind the parapet: coaches first (far to near), then tender and engine+ const side = -DEPTH / 2 + 1.45, at = (x: number, y: number): P => cam.proj([X0 + x, RAIL + y, side]);+ const poly = (pts: P[], dx = 0) => pr(pts.map(([x, y]) => [X0 + x + dx, RAIL + y, side] as V3));+ const parTop = (x: number) => cam.proj([x, PARAPET + 0.12, 0.05])[1];+ c.save(); c.beginPath(); // clip to above the parapet coping: the train stands behind it+ { const pts: P[] = []; for (let X = -SPAN; X <= NPIER * SPAN; X += 2) pts.push([cam.proj([X, 0, 0.05])[0], parTop(X)]); c.moveTo(-50, -50); pts.forEach(([x, y]) => c.lineTo(x, y)); c.lineTo(W + 50, pts[pts.length - 1][1]); c.lineTo(W + 50, -50); c.closePath(); }+ c.clip();+ for (let n = COACHES - 1; n >= 0; n--) {+ const x0 = 19.6 + GAP + n * (COACH + GAP), x1 = x0 + COACH;+ const body = poly([[x0, 1.0], [x1, 1.0], [x1, 3.3], [x1 - 0.3, 3.62], [x1 - 1.2, 3.86], [x0 + 1.2, 3.86], [x0 + 0.3, 3.62], [x0, 3.3]]);+ pth(body); c.fillStyle = ks(0.5, 0.36, 50); c.fill(); // maroon side, raked by the sun+ pth(poly([[x0, 3.3], [x1, 3.3], [x1 - 0.3, 3.62], [x1 - 1.2, 3.86], [x0 + 1.2, 3.86], [x0 + 0.3, 3.62]])); c.fillStyle = ks(0.28, 0.4, 51); c.fill(); // the roof's curve, turned up to the light+ pth(poly([[x0, 3.3], [x1, 3.3], [x1, 3.36], [x0, 3.36]])); c.fillStyle = ks(0.85, 0.1, 51); c.fill(); // cantrail shadow line+ for (let w = 0; w < 8; w++) { const wx = x0 + 1.5 + w * 2.25; pth(poly([[wx, 2.05], [wx + 1.55, 2.05], [wx + 1.55, 2.95], [wx, 2.95]])); c.fillStyle = ks(0.12 + 0.5 * (w % 3 === 1 ? 1 : 0), 0.42, 52); c.fill(); } // windows: most throw back the western sky, some see through to dark+ pth(poly([[x0, 1.0], [x1, 1.0], [x1, 1.7], [x0, 1.7]])); c.fillStyle = ks(0.68, 0.2, 53); c.fill(); // lower panels in the parapet's shade+ pth(poly([[x1, 1.0], [x1 + GAP, 1.0], [x1 + GAP, 3.4], [x1, 3.4]])); c.fillStyle = ks(0.85, 0.05, 54); c.fill(); // gangway+ }+ pth(poly(ENGINE)); c.fillStyle = ks(0.84, 0.07, 40); c.fill(); // engine and tender: black+ // the boiler's round: a narrow band of glint where its curve turns up toward the low sun+ const glint = (x0: number, x1: number, y: number, w: number, k: number, s: number) => { pth(poly([[x0, y], [x1, y], [x1, y + w], [x0, y + w]])); c.fillStyle = ks(k, s, 41); c.fill(); };+ glint(2.1, 7.35, 3.08, 0.34, 0.02, 0.78); glint(2.1, 7.35, 2.9, 0.18, 0.4, 0.45); glint(0.75, 1.95, 3.1, 0.3, 0.08, 0.7);+ glint(7.7, 9.05, 3.38, 0.3, 0.05, 0.74); glint(11.8, 19.5, 3.05, 0.25, 0.12, 0.62); glint(4.5, 4.95, 3.6, 0.28, 0.02, 0.8);+ glint(9.3, 11.55, 3.82, 0.18, 0.1, 0.66); glint(0.3, 11.5, 1.3, 0.16, 0.25, 0.5); // cab roof edge, running plate edge+ pth(poly([[1.15, 3.98], [1.55, 3.98], [1.55, 4.06], [1.15, 4.06]])); c.fillStyle = ks(0.2, 0.62, 41); c.fill(); // chimney lip+ pth(poly([[9.7, 2.3], [10.9, 2.3], [10.9, 3.4], [9.7, 3.4]])); c.fillStyle = ks(0.25, 0.7, 42); c.fill(); // cab side window, the fire's glow behind it+ pth(poly([[11.9, 3.35], [15.4, 3.35], [14.9, 3.72], [12.4, 3.78]])); c.fillStyle = ks(0.72, 0.16, 43); c.fill(); // coal heaped at the front of the tender+ // driving wheels: only their tops clear the parapet; splashers over them, a coupling rod+ [3.1, 5.2, 7.3].forEach((wx) => { const cen = at(wx, 0.94), rim = at(wx + 0.94, 0.94), R = Math.abs(rim[0] - cen[0]); c.strokeStyle = ks(0.9, 0.05, 44); c.lineWidth = R * 0.14; c.beginPath(); c.ellipse(cen[0], cen[1], R * 0.93, R * 0.93 * 1.02, 0, Math.PI, 2 * Math.PI); c.stroke(); c.strokeStyle = ks(0.2, 0.55, 44); c.lineWidth = R * 0.05; c.beginPath(); c.ellipse(cen[0], cen[1], R, R, 0, Math.PI * 1.1, Math.PI * 1.6); c.stroke(); });+ c.restore();++ // 2c'. a dry-stone wall running from the viaduct's foot toward us: its sunlit top, its shaded side+ { const path: V3[] = []; for (let t = 0; t <= 1.0001; t += 0.05) path.push([64 - 26 * t + 4 * Math.sin(t * 3), 0, 1 + 34 * t]);+ const top = (h: number, dz: number) => path.map(([x, , z]) => cam.proj([x, h, z + dz]));+ const a = top(1.35, 0), b = top(1.35, 0.7), g0 = top(0, 0.7);+ pth([...b, ...g0.reverse()]); c.fillStyle = ks(0.62, 0.12, 63); c.fill(); // the face toward us, turned from the sun+ pth([...a, ...b.reverse()]); c.fillStyle = ks(0.14, 0.5, 64); c.fill(); // its cope stones, lit+ const r = rng(465); c.fillStyle = ks(0.78, 0.08, 65); for (let i = 0; i < 90; i++) { const t = r(), p = cam.proj([64 - 26 * t + 4 * Math.sin(t * 3), 0.2 + r() * 1.0, 1.7 + 34 * t]), w = 2 + (1 - t) * 4; c.fillRect(p[0], p[1], w, 1 + (1 - t)); } // the dark gaps between the stones+ }+ // 2d. the near bank we stand on: a dark sloping foreground with rushes, their tips caught by the sun+ const bank: P[] = [[-10, H * 0.86], [W * 0.12, H * 0.872], [W * 0.26, H * 0.9], [W * 0.4, H * 0.925], [W * 0.55, H * 0.955], [W * 0.7, H * 0.985], [W * 0.8, H + 10], [-10, H + 10]];+ pth(bank); c.fillStyle = ks(0.72, 0.1, 60); c.fill();+ const rr = rng(451);+ for (let i = 0; i < 110; i++) { const u = Math.pow(rr(), 0.9) * 0.78, bx = u * W, by = H * (0.86 + u * 0.17) + 4 + rr() * 40, h = (18 + rr() * 34) * (1 - u), lean = (rr() - 0.3) * 0.5; c.strokeStyle = ks(0.78, 0.1, 61); c.lineWidth = 1.4; c.beginPath(); c.moveTo(bx, by); c.quadraticCurveTo(bx + lean * h * 0.3, by - h * 0.6, bx + lean * h, by - h); c.stroke(); c.strokeStyle = ks(0.1, 0.62, 62); c.lineWidth = 1; c.beginPath(); c.moveTo(bx + lean * h * 0.8, by - h * 0.8); c.lineTo(bx + lean * h, by - h); c.stroke(); }++ // 3. lay it over, with the stone given its courses and weather+ over(T, L, (x, y, mat, k, s) => {+ if (Math.abs(mat - 10) < 2 || Math.abs(mat - 20) < 2) {+ const f = mat < 15 ? cam.face(x, y) : null, X = f ? f[0] : x * 0.05, Y = f ? f[1] : y * 0.05;+ const course = Math.floor(Y / 0.46), cy = Y / 0.46 - course, joint = cy < 0.12 ? 1 : 0, stone = Math.floor((X + rng(course * 31 + 7)() * 1.4) / (0.7 + (course % 3) * 0.25));+ const tone = (rng(course * 977 + stone * 13 + 3)() - 0.5) * 0.12, weather = (fractal(461, X * 3, Y * 0.3, 0.6, 0.12, 3) - 0.5) * 0.22, rise = f ? clamp((6 - Y) / 6) * 0.1 : 0;+ if (!f) { k += (fractal(462, x, y, 0.01, 0.004, 2) - 0.5) * 0.08; return [clamp(k), clamp(s)]; } // the shaded returns: damp, mottled, no sun to pick out the joints+ const pier = Math.round(X / SPAN), streak = Math.pow(fractal(463, X * 4, Y * 0.08, 0.5, 0.5, 2), 3) * 0.5 * clamp((CORNICE - Y) / 8); // lime and rain run down from the string course+ const damp = clamp((3.5 - Y) / 3.5) * 0.18, age = (rng(pier * 17 + 3)() - 0.5) * 0.07;+ k = k + tone + weather + joint * 0.2 + rise * 0.3 + streak * 0.25 + damp + age; s = s - joint * 0.12 - tone * 0.5 - damp * 0.5;+ }+ return [clamp(k), clamp(s)];+ });++ // 4. the plume, a density field shaded by marching toward the sun (see plume())+ plume(T, cam);+ // 5. newsprint cannot print a full black nor hold a clean white: the tone curve of the press+ for (let q = 0; q < T.k.length; q++) { { const v = T.k[q]; T.k[q] = 0.92 * (0.45 * v + 0.55 * v * v * (3 - 2 * v)); } T.s[q] = 0.62 * Math.pow(T.s[q], 1.35); } // the spot is a warmth, not a colour: only the sunlit and the glow carry much of it+ env.cache.set(key, T); return T;+};++// ---------------------------------------------------------------- the plume+// Coal smoke leaves the chimney as a dense dark column, is thrown up by the blast and bent back+// over the train by its speed, rolls into billows that grow as it rises, whitens to steam, and+// thins to nothing over the fourth coach. Density is a string of puffs along that path, bitten+// into cauliflower by domain-warped noise. Shading: from each point, march toward the sun and+// add up the smoke in the way; the more there is, the less light arrives (the lit rim on the+// right, the grey body on the left). Where it is thin it lets the sky through.+const plume = (T: Tone, cam: Cam) => {+ const W = T.W, puffs: { x: number; y: number; r: number; d: number; z: number }[] = [], R = rng(471);+ // the path: straight up out of the chimney (the blast), bent back by the train's speed, still+ // climbing, then levelling and spreading as it cools. Billows along it, bigger as it goes: each+ // billow a round mass (a sphere, for its shading), the whole a union of them.+ for (let s = 0; s < 100; s += 0.22 + s * 0.04) {+ const up = 3.4 * (1 - Math.exp(-s / 1.5)) + 10 * (1 - Math.exp(-s / 20)), back = s * 0.95 - 1.9 * (1 - Math.exp(-s / 1.5));+ const X = CHIMNEY[0] + back, Y = CHIMNEY[1] + up, Z = CHIMNEY[2] - 0.12 * s, r = 0.26 + 0.44 * Math.pow(s, 0.8);+ const p = cam.proj([X, Y, Z]), q = cam.proj([X + r, Y, Z]), rp = Math.abs(q[0] - p[0]), n = s < 2 ? 1 : 3, j = s < 2 ? 0.15 : 1;+ for (let m = 0; m < n; m++) { const k = 0.35 + Math.pow(R(), 1.6) * 0.95; puffs.push({ x: p[0] + (R() - 0.5) * rp * 1.3 * j, y: p[1] + (R() - 0.5) * rp * 1.1 * j, r: rp * k, d: clamp(1.25 - s / 95) * (0.8 + R() * 0.3), z: -s * 0.6 + R() * rp * 0.5 }); }+ }+ const gw = Math.round(T.w / 1.25), gh = Math.round(T.h / 1.25), gs = W / gw, A = new Float32Array(gw * gh), NX = new Float32Array(gw * gh), NY = new Float32Array(gw * gh), NZ = new Float32Array(gw * gh), DN = new Float32Array(gw * gh);+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; puffs.forEach((p) => { x0 = Math.min(x0, p.x - p.r * 1.5); x1 = Math.max(x1, p.x + p.r * 1.5); y0 = Math.min(y0, p.y - p.r * 1.5); y1 = Math.max(y1, p.y + p.r * 1.5); });+ const ci0 = Math.max(1, Math.floor(x0 / gs)), ci1 = Math.min(gw - 2, Math.ceil(x1 / gs)), cj0 = Math.max(1, Math.floor(y0 / gs)), cj1 = Math.min(gh - 2, Math.ceil(y1 / gs));+ for (let j = cj0; j <= cj1; j++) for (let i = ci0; i <= ci1; i++) {+ const x = (i + 0.5) * gs, y = (j + 0.5) * gs, wx = x + (fractal(481, x, y, 0.01, 0.01, 3) - 0.5) * 22, wy = y + (fractal(482, x, y, 0.01, 0.01, 3) - 0.5) * 22;+ const fz = (fractal(483, x, y, 0.045, 0.045, 3) - 0.5) * 0.5; // the fluff on each billow's edge+ let best = -1e9, cover = 0, q = j * gw + i;+ for (const p of puffs) { const e = ((wx - p.x) ** 2 + (wy - p.y) ** 2) / (p.r * p.r) + fz; if (e >= 1) continue; const nz = Math.sqrt(1 - e), h = p.z + p.r * nz; cover = Math.max(cover, clamp((1 - e) * 5) * p.d); if (h > best) { best = h; NX[q] = (wx - p.x) / p.r; NY[q] = (wy - p.y) / p.r; NZ[q] = nz; DN[q] = p.d; } }+ A[q] = cover;+ }+ const Lv = [0.84, -0.4, 0.36], root = cam.proj(CHIMNEY), PK = new Float32Array(gw * gh), PS = new Float32Array(gw * gh);+ const Aat = (i: number, j: number) => (i < 0 || j < 0 || i >= gw || j >= gh ? 0 : A[j * gw + i]);+ for (let j = cj0; j <= cj1; j++) for (let i = ci0; i <= ci1; i++) {+ const q = j * gw + i; if (A[q] <= 0) continue;+ const lam = clamp(NX[q] * Lv[0] + NY[q] * Lv[1] + NZ[q] * Lv[2]);+ let occ = 0; for (let m = 1; m <= 14; m++) occ += Aat(Math.round(i + 0.92 * m * 2.5), Math.round(j - 0.39 * m * 2.5));+ const x = (i + 0.5) * gs, y = (j + 0.5) * gs, shade = Math.exp(-occ * 0.3), rim = clamp(1 - NZ[q]) * clamp(NX[q] * 0.92 - NY[q] * 0.39) * clamp(1 - occ * 0.25);+ const lit = clamp(0.02 + 1.1 * lam * (0.15 + 0.85 * shade) + 0.8 * rim), coal = clamp(1 - Math.hypot(x - root[0], (y - root[1]) * 1.3) / (W * 0.12)), thin = 1 - DN[q];+ PK[q] = (0.44 * Math.pow(1 - lit, 1.3) * (1 - 0.35 * thin) + 0.3 * coal * (1 - 0.6 * lit)) * A[q]; PS[q] = (0.04 + 0.42 * lit * (1 - lit * 0.45) * (1 - 0.5 * coal) + 0.1 * (1 - lit)) * A[q];+ }+ const sx = W / T.w, sy = T.H / T.h, bl = (M: Float32Array, fx: number, fy: number) => { const a = Math.floor(fx), b = Math.floor(fy), u = fx - a, v = fy - b, g = (i: number, j: number) => (i < 0 || j < 0 || i >= gw || j >= gh ? 0 : M[j * gw + i]); return g(a, b) * (1 - u) * (1 - v) + g(a + 1, b) * u * (1 - v) + g(a, b + 1) * (1 - u) * v + g(a + 1, b + 1) * u * v; };+ for (let j = 0; j < T.h; j++) for (let i = 0; i < T.w; i++) {+ const x = (i + 0.5) * sx, y = (j + 0.5) * sy; if (x < x0 || x > x1 || y < y0 || y > y1) continue;+ const fx = x / gs - 0.5, fy = y / gs - 0.5, al = bl(A, fx, fy); if (al <= 0.003) continue;+ const q = j * T.w + i; T.k[q] = T.k[q] * (1 - al) + clamp(bl(PK, fx, fy) / al) * al; T.s[q] = T.s[q] * (1 - al) + clamp(bl(PS, fx, fy) / al) * al;+ }+};diff --git a/engine/src/canvas-core/input.ts b/engine/src/canvas-core/input.tsnew file mode 100644index 0000000..1c7a6bc--- /dev/null+++ b/engine/src/canvas-core/input.ts@@ -0,0 +1,230 @@+// INPUT AS DATA. The promise for interactive pieces: "a frame is a fact GIVEN ITS INPUT LOG".+//+// A host (hosts/interactive.ts) owns the clock and the DOM. It quantises time to 60 Hz ticks and+// writes what the user did into an append-only log of InputEvents, each stamped with the tick at+// which it takes effect. The art never sees an event, a clock or the DOM: it is handed+//+// draw(ctx, tick, env, stateAt(tick, log, piece.input))+//+// and stateAt is a pure fold of the log. Replay the log in a fresh page, in any order, cold or+// warm, and every frame comes back the same pixels. Nothing else in the contract moves.+//+// Rules the host must keep (the reducer checks the first two and throws):+// 1. ticks never decrease along the log; events sharing a tick apply in log order;+// 2. an event is stamped AFTER every tick already drawn (stamp = max(lastDrawn + 1, clock)), so a+// drawn frame never changes retroactively and a checkpoint never goes stale;+// 3. everything that moves pixels is IN the log, including the initial configuration (target+// rectangles, scroll, reduced motion, state), written at tick 0 before anything is drawn.+// Viewport and DPR changes are logged as `view` events: they change `env.scale`, never the+// state, because every coordinate in the log is already in the piece's logical space.+//+// Motion between events is closed form. A spring is critically damped and its target is a pure+// function of the DISCRETE state (hover, pointer, focus, state...), which only changes AT events.+// Between two events the motion is x(t) = target + (x0 + (v0 + w x0) t) e^(-w t); at an event that+// moves the target, position AND velocity carry over into a new segment. So an interrupted gesture+// (hover, leave, hover again within 3 ticks) is a sum of exact segments, not an integration that+// depends on how often somebody happened to sample it.+import type { Ctx, Env, P } from "./core";+import type { Film } from "./film";++export const HZ = 60; // ticks per second. Hosts quantise to this; the art counts in it.++export type EventType =+ | "move" // pointer at (x, y) in piece coordinates (may be outside the canvas); value = "mouse" | "pen" | "touch"+ | "leave" // the pointer left the page, or a touch ended: there is no pointer now+ | "enter" // pointer entered bound target `target`+ | "exit" // pointer left bound target `target`+ | "down" // press started on `target` (or on the piece itself: target "self")+ | "up" // press released; a click if it lands on the target the press began on+ | "cancel" // press abandoned (pointercancel, drag away): no click+ | "focus" // keyboard focus on `target`: the hover equivalent for people who do not use a mouse+ | "blur" // focus left `target`+ | "key" // text in `target` changed: value = its length, (x, y) = the caret in piece coordinates+ | "scroll" // value = scroll progress 0..1 of the piece's scroll track+ | "state" // value = a UI state name the page set: "idle", "busy", "success", "error", ...+ | "rect" // `target` occupies (x, y, w, h) in piece coordinates+ | "view" // value = device scale the host draws at (logical px -> device px). Env only, never state+ | "motion"; // value = "reduce" | "full": prefers-reduced-motion++export type InputEvent = { tick: number; type: EventType; target?: string; x?: number; y?: number; w?: number; h?: number; value?: number | string };+export type InputLog = InputEvent[];+export type Rect = { x: number; y: number; w: number; h: number };+export type Field = { len: number; caret: P | null };++// The discrete state: everything the log says, nothing it does not.+export type Discrete = {+ pointer: P | null; device: string;+ hover: string | null; focus: string | null; pressed: string | null;+ scroll: number; state: string; reduced: boolean; scale: number;+ rects: Record<string, Rect>; fields: Record<string, Field>;+ since: Record<string, number>; // tick of the latest: move, leave, hover, unhover, focus, blur, press, release, click, cancel, key, scroll, state, and "<kind>:<target|name>"+ count: Record<string, number>; // how many of each, same keys: a seed for reaction variety that is itself in the log+};++export type SpringSpec = {+ omega: number; // rad per tick. 0.2 settles in ~0.4 s; 0.08 is lazy+ 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">> };+export type InputState = Discrete & {+ tick: number;+ attention: string | null; // the most recent of focus and hover: where a keyboard or mouse user is+ spring: Record<string, number | P>; // smoothed values, closed form at this tick+ vel: Record<string, number | P>; // their velocities, per tick+};++// ---------------------------------------------------------------- the discrete fold+const freshDiscrete = (spec: InputSpec): Discrete => ({+ pointer: null, device: "mouse", hover: null, focus: null, pressed: null,+ scroll: spec.init?.scroll ?? 0, state: spec.init?.state ?? "idle", reduced: spec.init?.reduced ?? false, scale: 1,+ rects: {}, fields: {}, since: {}, count: {},+});+const copyDiscrete = (d: Discrete): Discrete => ({ ...d, rects: { ...d.rects }, fields: { ...d.fields }, since: { ...d.since }, count: { ...d.count } });+const bump = (d: Discrete, key: string, tick: number) => { d.since[key] = tick; d.count[key] = (d.count[key] ?? 0) + 1; };++const apply = (d: Discrete, e: InputEvent) => {+ const t = e.tick, tg = e.target;+ switch (e.type) {+ case "move": d.pointer = [e.x ?? 0, e.y ?? 0]; if (typeof e.value === "string") d.device = e.value; bump(d, "move", t); break;+ case "leave": d.pointer = null; d.hover = null; bump(d, "leave", t); break;+ case "enter": if (tg) { d.hover = tg; bump(d, "hover", t); bump(d, `hover:${tg}`, t); } break;+ case "exit": if (tg && d.hover === tg) { d.hover = null; bump(d, "unhover", t); } break;+ case "down": d.pressed = tg ?? "self"; bump(d, "press", t); bump(d, `press:${d.pressed}`, t); break;+ case "up": { const was = d.pressed; d.pressed = null; bump(d, "release", t); if (was && (tg ?? "self") === was) { bump(d, "click", t); bump(d, `click:${was}`, t); } break; }+ case "cancel": d.pressed = null; bump(d, "cancel", t); break;+ case "focus": if (tg) { d.focus = tg; bump(d, "focus", t); bump(d, `focus:${tg}`, t); } break;+ case "blur": if (tg && d.focus === tg) { d.focus = null; bump(d, "blur", t); } break;+ case "key": if (tg) { d.fields[tg] = { len: Number(e.value ?? 0), caret: e.x !== undefined ? [e.x, e.y ?? 0] : null }; bump(d, "key", t); bump(d, `key:${tg}`, t); } break;+ case "scroll": d.scroll = clamp01(Number(e.value ?? 0)); bump(d, "scroll", t); break;+ case "state": { const s = String(e.value ?? "idle"); if (s !== d.state) { d.state = s; bump(d, "state", t); bump(d, `state:${s}`, t); } break; }+ case "rect": if (tg) d.rects[tg] = { x: e.x ?? 0, y: e.y ?? 0, w: e.w ?? 0, h: e.h ?? 0 }; break;+ case "view": d.scale = Number(e.value ?? 1); break;+ case "motion": d.reduced = e.value === "reduce"; break;+ }+};++// ---------------------------------------------------------------- closed-form critically damped springs+// One segment per spring: anchored at tick t0 with displacement x0 from `tgt` and velocity v0.+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 dt = t - s.t0; if (dt <= 0) return { x: s.tgt.map((g, i) => g + s.x0[i]), v: s.v0.slice() };+ 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; }),+ v: s.tgt.map((_, i) => { const c = s.v0[i] + w * s.x0[i]; return (s.v0[i] - w * c * dt) * e; }),+ };+};+const same = (a: number[], b: number[]) => a.length === b.length && a.every((v, i) => v === b[i]);++// ---------------------------------------------------------------- checkpointed pure reducer+type Fold = { tick: number; idx: number; d: Discrete; segs: Record<string, Seg>; ref: InputEvent | null };+const CP = 60; // checkpoint every second of ticks+const caches = new WeakMap<InputSpec, WeakMap<InputLog, Fold[]>>();++const initFold = (spec: InputSpec): Fold => {+ const d = freshDiscrete(spec), segs: Record<string, Seg> = {};+ for (const [k, s] of Object.entries(spec.springs)) { const g = vec(s.target(d)); segs[k] = { t0: 0, tgt: g, x0: g.map(() => 0), v0: g.map(() => 0) }; }+ return { tick: -1, idx: 0, d, segs, ref: null }; // the base sits before tick 0: always valid, whatever tick-0 events say+};+const cloneFold = (f: Fold, tick: number): Fold => ({ tick, idx: f.idx, d: copyDiscrete(f.d), segs: { ...f.segs }, ref: f.ref });++// consume every event with tick <= `to`, in log order, retargeting springs as the discrete state moves+const advance = (spec: InputSpec, log: InputLog, f: Fold, to: number) => {+ while (f.idx < log.length && log[f.idx].tick <= to) {+ const e = log[f.idx];+ if (!Number.isFinite(e.tick) || e.tick < 0) throw new Error(`input log: event ${f.idx} has tick ${e.tick}`);+ if (f.ref && e.tick < f.ref.tick) throw new Error(`input log: ticks go backwards at event ${f.idx} (${f.ref.tick} -> ${e.tick})`);+ apply(f.d, e);+ for (const [k, s] of Object.entries(spec.springs)) {+ 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 way+ if (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+ f.segs[k] = { t0: e.tick, tgt: g, x0: x.map((xi, i) => xi - g[i]), v0: v };+ }+ f.ref = e; f.idx++;+ }+ f.tick = to;+};++export const stateAt = (tick: number, log: InputLog, spec: InputSpec): InputState => {+ const t = Math.max(0, Math.floor(tick));+ let bySpec = caches.get(spec); if (!bySpec) { bySpec = new WeakMap(); caches.set(spec, bySpec); }+ let cps = bySpec.get(log); if (!cps) { cps = [initFold(spec)]; bySpec.set(log, cps); }+ // a checkpoint is valid while the log still agrees with it: the event it ended on is the same object,+ // and nothing at or before its tick was appended after it was taken (rule 2 makes this the normal case)+ const valid = (c: Fold) => (c.idx === 0 || log[c.idx - 1] === c.ref) && (c.idx >= log.length || log[c.idx].tick > c.tick);+ let k = Math.min(cps.length - 1, Math.floor(t / CP));+ while (k > 0 && !valid(cps[k])) { cps.length = k; k--; } // stale tail (the log was rewritten): drop it+ const f = cloneFold(cps[k], cps[k].tick);+ for (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); }+ return { ...f.d, tick: t, attention: attentionOf(f.d), spring, vel };+};++// The state of a piece nobody has touched, built WITHOUT the reducer: the replay gate draws the+// piece from this and from stateAt(t, []) and demands the same pixels, so the fold cannot drift.+export const restState = (tick: number, spec: InputSpec): InputState => {+ const d = freshDiscrete(spec), spring: Record<string, number | P> = {}, vel: Record<string, number | P> = {};+ for (const [k, s] of Object.entries(spec.springs)) { const g = s.target(d); spring[k] = g; vel[k] = typeof g === "number" ? 0 : [0, 0]; }+ return { ...d, tick, attention: null, spring, vel };+};++// ---------------------------------------------------------------- helpers the art uses+export const clamp01 = (v: number) => (v <= 0 ? 0 : v >= 1 ? 1 : v);+export const ease = (u: number) => { const v = clamp01(u); return v >= 1 ? 1 : v * v * (3 - 2 * v); }; // exactly 1 at and past 1+export const lerp = (a: number, b: number, u: number) => (u >= 1 ? b : a + (b - a) * u);+export const centre = (r: Rect): P => [r.x + r.w / 2, r.y + r.h / 2];++// Where to look: the attended target's centre, else the pointer, else `rest`. A spring target.+// The most recent of keyboard focus and pointer hover: every hover reaction has a focus equivalent.+export const attentionOf = (d: Discrete): string | null => (d.focus && d.hover ? ((d.since.focus ?? -1) >= (d.since.hover ?? -1) ? d.focus : d.hover) : d.focus ?? d.hover);+export const lookTarget = (d: Discrete, rest: P, caretFirst = true): P => {+ const a = attentionOf(d);+ if (a && caretFirst && d.fields[a]?.caret) return d.fields[a].caret!;+ if (a && d.rects[a]) return centre(d.rects[a]);+ return d.pointer ?? rest;+};+// Gaze: the offset of a pupil inside its eye, looking from `eye` at `at`. Saturates smoothly at+// `reach`; a point closer than `near` gets a proportionally smaller glance (no cross-eyed snap).+export const gaze = (eye: P, at: P, reach: number, near = 120): P => {+ const dx = at[0] - eye[0], dy = at[1] - eye[1], d = Math.hypot(dx, dy); if (d < 1e-6) return [0, 0];+ const k = reach * Math.tanh(d / near); return [(dx / d) * k, (dy / d) * k];+};+// Lean: a signed amount in [-max, max] toward `at` along x, soft past `range`.+export const lean = (from: P, at: P, max: number, range = 300) => max * Math.tanh((at[0] - from[0]) / range);+// Parallax: a layer at `depth` (0 = pinned, 1 = moves the most) shifted by where the pointer is.+export const parallax = (at: P, c: P, depth: number, range: P): P => [-depth * range[0] * Math.tanh((at[0] - c[0]) / (c[0] || 1)), -depth * range[1] * Math.tanh((at[1] - c[1]) / (c[1] || 1))];+// A discrete reaction: a pre-made clip of FIXED length started by the latest `key` event.+// Retriggering restarts it (the clip is a function of ticks since its trigger, nothing else).+export const clip = (s: InputState, key: string, len: number): { f: number; u: number; n: number } | null => {+ const t0 = s.since[key]; if (t0 === undefined) return null; const f = s.tick - t0;+ return f >= 0 && f < len ? { f, u: f / len, n: s.count[key] ?? 1 } : null;+};+export const ticksSince = (s: InputState, key: string) => (s.since[key] === undefined ? Infinity : s.tick - s.since[key]);+// Randomness in a reaction is seeded from the log: (the trigger's tick, how many there were, the key).+export const reactionSeed = (s: InputState, key: string) => { let h = 2166136261; const str = `${key}|${s.since[key] ?? -1}|${s.count[key] ?? 0}`; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };+// Scroll progress mapped onto a stretch of the track: 0 before a, exactly 1 at and after b.+export const scrollSpan = (p: number, a = 0, b = 1) => clamp01((p - a) / Math.max(1e-9, b - a));++// ---------------------------------------------------------------- the piece contract+export type PieceMeta = { title: string; W: number; H: number; loop: number; alt: string };+export type Piece = {+ meta: PieceMeta; // loop: ticks after which the untouched piece repeats exactly+ input: InputSpec;+ // Pre-draw everything static into env.cache. A generator so a host can spread it over frames;+ // draw() must still be correct if it never ran (cold == warm is part of the gate).+ bake?: (env: Env) => Iterable<unknown>;+ draw: (ctx: Ctx, tick: number, env: Env, input: InputState) => void;+};++// The untouched piece as an ordinary Film (60 fps), so render/gate/emit work on it unchanged.+export const loopFilm = (piece: Piece): Film => ({+ meta: { title: piece.meta.title, W: piece.meta.W, H: piece.meta.H, fps: HZ, bpm: 120, durationFrames: piece.meta.loop },+ assets: { images: {} },+ shots: [{ id: "loop", start: 0, end: piece.meta.loop, draw: (ctx, f, env) => piece.draw(ctx, f, env, restState(f, piece.input)) }],+});diff --git a/engine/src/canvas-core/isometric.ts b/engine/src/canvas-core/isometric.tsnew file mode 100644index 0000000..f7f5567--- /dev/null+++ b/engine/src/canvas-core/isometric.ts@@ -0,0 +1,381 @@+// ISOMETRIC · "the night bake". A cutaway of a tiny two-floor bakery, lit by its oven.+//+// MEDIUM (physical): a flat vector illustration built on a true 2:1 isometric grid, the way an+// iso illustrator works in a pen-tool program: every edge in plan is a 2:1 line, every vertical+// is vertical, every plane is ONE flat colour. Each material has exactly three tones: top (the+// lightest), left face (+y) and right face (+x, the darkest), so form comes from the cube rule,+// never from a gradient. Edges are crisp: tone meets tone with no line and no blur.+// MARKS: the plane (pen-traced outline, then filled), the 2:1 line, the flat light shape.+// EDGE: vector-crisp; texture is sparse and subtle (tile joints, brick courses, grain, a speckle+// on plaster) laid as more planes and hairlines, never as noise over everything.+// ORDER (the film): the iso grid -> massing blocks -> walls and floors -> interiors (oven,+// mezzanine, racks, table, ladder) -> props (bread, sacks, the baker) -> light and shadow (the+// oven's glow poured on the floor and on every face that sees it, shadows thrown away from it)+// -> details (texture, window stars, flour).+// PALETTE: night-cool ambient on warm materials; the only saturated warmth is the oven.+// LIGHT: the oven mouth is the one light. Everything facing it takes a warm flat tint; cast+// shadows fall away from it; the rest of the room sits in cool night ambient.+// SUBJECT + REALISM: a village bakery at 4 a.m. (reference, from knowledge: wood-fired brick+// ovens with an arched mouth and a stone hearth ledge in front; a baker's peel, a long paddle;+// cooling racks on wheels; flour sacks stored on a loft). The baker is 7.5 heads tall (a real+// adult canon), standing with weight on both feet, three-quarter view, holding the peel with a+// fresh boule on it in two hands, turning from the oven to the cooling rack.+// NOT ITS NEAREST NEIGHBOUR (koi, marker comic): no contour line, no thick-thin, no hand wobble;+// the projection is the style: 2:1 edges, three tones, construction-first order.+import type { Ctx } from "./core";+import type { Film } from "./film";+import { clamp01, Iso, Mat, P2, span } from "./isometricKit";++const N = 480, HOLD = 30;+const BG = "#1b2030", GRID = "#333d57", MASS = "#6f8cc4";+const dim = (h: string, f: number) => "#" + [1, 3, 5].map((i) => Math.round(parseInt(h.slice(i, i + 2), 16) * f).toString(16).padStart(2, "0")).join("");+const dimMat = (m: Mat, f: number): Mat => ({ top: dim(m.top, f), left: dim(m.left, f), right: dim(m.right, f) });+const M0: Record<string, Mat> = { // night ambient: warm materials seen by cool light+ plaster: { top: "#c9bba0", left: "#a99b82", right: "#8b806e" },+ cut: { top: "#4d3b35", left: "#3f302b", right: "#332723" },+ tile: { top: "#94593f", left: "#6f3f2c", right: "#5a3223" },+ wood: { top: "#9a7350", left: "#7a5839", right: "#624630" },+ darkwood: { top: "#6a4f3e", left: "#533d31", right: "#422f27" },+ brick: { top: "#a9573a", left: "#8a432a", right: "#6f3522" },+ stone: { top: "#bdb3a2", left: "#9a9080", right: "#7e7567" },+ crust: { top: "#dc9d52", left: "#b87a33", right: "#935d24" },+ sack: { top: "#cdbf9f", left: "#b09f7c", right: "#92835f" },+ iron: { top: "#5d5f6b", left: "#474955", right: "#373843" },+};+// everything but the bread sits a step further into the night, so the oven carries the light+const M: Record<string, Mat> = Object.fromEntries(Object.entries(M0).map(([k, m]) => [k, k === "crust" ? m : dimMat(m, k === "brick" ? 0.92 : 0.84)]));+const WARM = "#ffb04a", HOT = "#ffd98a", CORE = "#fff3cf", EMBER = "#e0662c";++type Item = { stage: number; w?: number; make: (iso: Iso, p: number) => void; light?: (iso: Iso, p: number) => void; detail?: (iso: Iso, p: number) => void };++const scene = (): Item[] => {+ const I: Item[] = [];+ const box = (stage: number, x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, m: Mat, extra: Partial<Item> = {}) =>+ I.push({ stage, make: (iso, p) => iso.make(iso.boxFaces(x0, y0, z0, x1, y1, z1, m), p, m.right), light: (iso, p) => warmBox(iso, x0, y0, z0, x1, y1, z1, p), ...extra });++ // ---------- building shell: slab, two back walls, the chimney+ I.push({ stage: 2, make: (iso, p) => { // the plinth's shadow on the night ground, a flat offset plane+ if (p <= 0) return; iso.ctx.save(); iso.ctx.globalAlpha = 0.45 * Math.min(1, p * 2); iso.face([[12.6, -0.6, -0.6], [12.6, 10.6, -0.6], [0.4, 10.6, -0.6], [0.4, 10, -0.6], [12, 10, -0.6], [12, -0.6, -0.6]], "#0e1119"); iso.ctx.restore();+ } });+ box(2, -0.6, -0.6, -0.6, 12, 10, 0, { top: M.tile.top, left: M.cut.left, right: M.cut.right }, { light: undefined,+ detail: (iso, p) => { // tile joints: every unit a tile, laid as hairlines row by row+ const n = Math.floor(22 * p); for (let k = 1; k <= n; k++) { const t = k <= 11 ? k : 0, s = k > 11 ? k - 11 : 0; if (t && t < 12) iso.line(iso.p(t, 0, 0), iso.p(t, 10, 0), M.tile.left, 1, 0.55); if (s && s < 10) iso.line(iso.p(0, s, 0), iso.p(12, s, 0), M.tile.left, 1, 0.55); }+ } });+ // back wall along y = 0 (its +y face looks at us), cut at the top+ box(2, -0.6, -0.6, 0, 12, 0, 11, { top: M.cut.top, left: M.plaster.left, right: M.cut.right }, { light: undefined,+ detail: (iso, p) => { const r = rngLite(7), n = Math.floor(140 * p); for (let k = 0; k < n; k++) { const x = r() * 12, z = 0.3 + r() * 10.4; if (x > 6.2 && x < 10.8 && z < 5) { r(); continue; } iso.face([[x, 0, z], [x + 0.08, 0, z], [x + 0.08, 0, z + 0.08], [x, 0, z + 0.08]], M.plaster.right, 0.5); } },+ });+ // back wall along x = 0 (its +x face looks at us), with the loft window cut through it+ box(2, -0.6, 0, 0, 0, 10, 11, { top: M.cut.top, left: M.cut.left, right: M.plaster.right }, {+ light: (iso, p) => { // the far wall under the loft catches the oven's reach in two flat bands+ if (p <= 0) return; iso.ctx.save(); iso.ctx.beginPath(); [[0, 0, 0], [0, 10, 0], [0, 10, 5.8], [0, 0, 5.8]].forEach(([x, y, z], i) => { const q = iso.p(x, y, z); if (i) iso.ctx.lineTo(q[0], q[1]); else iso.ctx.moveTo(q[0], q[1]); }); iso.ctx.clip();+ [[4.4, 0.08], [2.8, 0.09]].forEach(([r, a]) => { const pts: [number, number, number][] = []; for (let i = 0; i < 28; i++) { const t = (i / 28) * Math.PI * 2; pts.push([0, 6.2 + Math.cos(t) * r * p, 1.6 + Math.sin(t) * r * 0.8 * p]); } iso.face(pts, WARM, a); }); iso.ctx.restore();+ },+ detail: (iso, p) => { const r = rngLite(11), n = Math.floor(120 * p); for (let k = 0; k < n; k++) { const y = r() * 10, z = 0.3 + r() * 10.4; if (y > 5 && y < 7.4 && z > 7.2 && z < 9.8) { r(); continue; } iso.face([[0, y, z], [0, y + 0.08, z], [0, y + 0.08, z + 0.08], [0, y, z + 0.08]], "#998668", 0.5); } },+ });+ // loft window: reveal (the wall's thickness) then night glass+ I.push({ stage: 3, make: (iso, p) => {+ iso.make([{ pts: [iso.p(0, 5.2, 7.4), iso.p(0, 7.2, 7.4), iso.p(0, 7.2, 9.6), iso.p(0, 5.2, 9.6)], fill: "#6b5a4a" }], p, "#4a3d33");+ iso.make([{ pts: [iso.p(-0.35, 5.45, 7.4), iso.p(-0.35, 7.2, 7.4), iso.p(-0.35, 7.2, 9.35), iso.p(-0.35, 5.45, 9.35)], fill: "#24325a" }], p, "#1a2440");+ }, detail: (iso, p) => {+ if (p <= 0) return; // two stars and a moon sliver, and the window's cross bar+ iso.line(iso.p(-0.35, 6.32, 7.4), iso.p(-0.35, 6.32, 9.35), "#6b5a4a", 3); iso.line(iso.p(-0.35, 5.45, 8.4), iso.p(-0.35, 7.2, 8.4), "#6b5a4a", 3);+ if (p > 0.3) { const m = iso.p(-0.35, 6.85, 9.0); iso.ctx.fillStyle = "#e9eef6"; iso.ctx.beginPath(); iso.ctx.arc(m[0], m[1], iso.u * 0.2, 0, Math.PI * 2); iso.ctx.fill(); iso.ctx.fillStyle = "#24325a"; iso.ctx.beginPath(); iso.ctx.arc(m[0] + iso.u * 0.08, m[1] - iso.u * 0.05, iso.u * 0.18, 0, Math.PI * 2); iso.ctx.fill(); }+ if (p > 0.6) [[5.8, 8.0], [6.0, 9.1], [6.9, 7.8]].forEach(([y, z]) => { const s = iso.p(-0.35, y, z); iso.ctx.fillStyle = "#c9d6ee"; iso.ctx.fillRect(s[0] - 1, s[1] - 1, 2.5, 2.5); });+ } });+ // ground-floor window in the y = 0 wall, under the loft+ I.push({ stage: 3, make: (iso, p) => {+ iso.make([{ pts: [iso.p(1.9, 0, 2.2), iso.p(3.5, 0, 2.2), iso.p(3.5, 0, 4.4), iso.p(1.9, 0, 4.4)], fill: "#6b5a4a" }], p, "#4a3d33");+ iso.make([{ pts: [iso.p(1.9, -0.35, 2.2), iso.p(3.25, -0.35, 2.2), iso.p(3.25, -0.35, 4.15), iso.p(1.9, -0.35, 4.15)], fill: "#24325a" }], p, "#1a2440");+ }, detail: (iso, p) => { if (p > 0) { iso.line(iso.p(2.58, -0.35, 2.2), iso.p(2.58, -0.35, 4.15), "#6b5a4a", 3); iso.line(iso.p(1.9, -0.35, 3.2), iso.p(3.25, -0.35, 3.2), "#6b5a4a", 3); } } });++ // ---------- the loft (mezzanine) over the back-left, and what lives under it+ // wall rack of loaves under the loft, against the x = 0 wall, open toward us (+x)+ const shelfRack = (x0: number, y0: number, x1: number, y1: number, h: number, shelves: number, mat: Mat, loaves: "long" | "round", stage: number) => {+ I.push({ stage, make: (iso, p) => {+ const posts: [number, number][] = [[x0, y0], [x1, y0], [x0, y1], [x1, y1]], t = 0.14;+ const parts = [...posts.map(([x, y]) => iso.boxFaces(x - t / 2, y - t / 2, 0, x + t / 2, y + t / 2, h, mat)), ...Array.from({ length: shelves }, (_, k) => iso.boxFaces(x0, y0, 0.35 + (k * (h - 0.5)) / (shelves - 1) - 0.06, x1, y1, 0.35 + (k * (h - 0.5)) / (shelves - 1), mat))];+ // back posts first, then shelves bottom-up, then the front posts+ const order = [0, 2, ...Array.from({ length: shelves }, (_, k) => 4 + k), 1, 3];+ order.forEach((i, k) => iso.make(parts[i], clamp01(p * order.length - k * 0.7), mat.right));+ } });+ I.push({ stage: 4, make: (iso, p) => {+ const r = rngLite(Math.round(x0 * 100 + y0)); let k = 0; const total = (shelves - 1) * 4;+ for (let s = 0; s < shelves - 1; s++) {+ const z = 0.35 + (s * (h - 0.5)) / (shelves - 1);+ if (loaves === "long") { // baguettes lie along the shelf's depth (x), side by side along y+ for (let j = 0; j < 4; j++) { const y = y0 + 0.25 + j * ((y1 - y0 - 0.5) / 3) + (r() - 0.5) * 0.1; if (clamp01(p * total - k++) <= 0) continue; loaf(iso, x0 + 0.15, y - 0.16, z, x1 - 0.2, y + 0.16, z + 0.3); }+ } else {+ for (let j = 0; j < 4; j++) { const y = y0 + 0.4 + j * ((y1 - y0 - 0.8) / 3), x = (x0 + x1) / 2 + (r() - 0.5) * 0.15; if (clamp01(p * total - k++) <= 0) continue; boule(iso, x, y, z, 0.3); }+ }+ }+ } });+ };+ shelfRack(0.15, 1.0, 1.35, 4.4, 4.6, 5, M.darkwood, "long", 3);+ shelfRack(4.75, 0.15, 6.1, 1.5, 4.4, 5, M.iron, "round", 3); // the cooling rack by the oven: boules just out+ // flour sacks on the ground floor under the loft+ I.push({ stage: 4, make: (iso, p) => { sack(iso, 1.0, 5.4, 0, clamp01(p * 2)); sack(iso, 1.1, 6.9, 0, clamp01(p * 2 - 1)); } });+ // loft posts, slab, sacks up top, railing+ box(3, 4.2, 4.3, 0, 4.55, 4.65, 5.8, M.wood);+ box(3, 4.2, 9.5, 0, 4.55, 9.85, 5.8, M.wood);+ box(3, 0, 0, 5.8, 4.6, 10, 6.3, M.wood, { detail: (iso, p) => { const n = Math.floor(9 * p); for (let k = 1; k <= n; k++) iso.line(iso.p(0, k, 6.3), iso.p(4.6, k, 6.3), M.wood.left, 1, 0.6); } });+ I.push({ stage: 4, make: (iso, p) => { sack(iso, 1.0, 1.6, 6.3, clamp01(p * 3)); sack(iso, 1.1, 3.1, 6.3, clamp01(p * 3 - 1)); sack(iso, 1.05, 2.35, 7.35, clamp01(p * 3 - 2)); } });+ I.push({ stage: 4, make: (iso, p) => { iso.make(iso.boxFaces(2.3, 6.0, 6.3, 3.3, 7.2, 7.0, M.wood), clamp01(p * 1.5), M.wood.right); if (p > 0.6) for (let j = 0; j < 3; j++) boule(iso, 2.8, 6.25 + j * 0.35, 7.0, 0.16); } });+ I.push({ stage: 3, make: (iso, p) => { // railing: posts then the rail, along the loft edge+ const ys = [0.2, 2.6, 5.0, 7.4, 9.8];+ ys.forEach((y, k) => iso.make(iso.boxFaces(4.42, y - 0.06, 6.3, 4.55, y + 0.06, 8.1, M.wood), clamp01(p * 7 - k), M.wood.right));+ iso.make(iso.boxFaces(4.4, 0.1, 7.95, 4.58, 9.9, 8.12, M.wood), clamp01(p * 7 - 5), M.wood.right);+ iso.make(iso.boxFaces(4.42, 0.1, 7.1, 4.55, 9.9, 7.2, M.wood), clamp01(p * 7 - 6), M.wood.right);+ } });++ // ---------- the oven: brick body, dome, arched mouth, hearth ledge, flue up the wall+ const OV = { x0: 6.4, x1: 10.6, y0: 0, y1: 3.2, h: 3.0 };+ box(3, OV.x0, OV.y0, 0, OV.x1, OV.y1, OV.h, M.brick, {+ light: (iso, p) => { // the oven's own face lit by its mouth: a warm halo shape on the brick+ if (p <= 0) return; const c = iso.p(8.5, 3.2, 1.6); iso.ctx.save(); iso.ctx.beginPath(); iso.boxFaces(OV.x0, OV.y0, 0, OV.x1, OV.y1, OV.h, M.brick)[0].pts.forEach(([x, y], i) => (i ? iso.ctx.lineTo(x, y) : iso.ctx.moveTo(x, y))); iso.ctx.clip();+ [[1.9, 0.18], [1.35, 0.22]].forEach(([r, a]) => { iso.ctx.globalAlpha = a * p; iso.ctx.fillStyle = WARM; iso.ctx.beginPath(); iso.ctx.ellipse(c[0], c[1], r * iso.u * 1.1, r * iso.u * 0.8, -0.46, 0, Math.PI * 2); iso.ctx.fill(); });+ iso.ctx.restore();+ },+ detail: (iso, p) => { // brick courses on both faces, joints staggered+ const rows = 9, n = Math.floor(rows * 2 * p);+ for (let k = 0; k < Math.min(rows, n); k++) { const z = ((k + 1) * OV.h) / (rows + 1); iso.line(iso.p(OV.x0, OV.y1, z), iso.p(OV.x1, OV.y1, z), M.brick.right, 1.2, 0.7); iso.line(iso.p(OV.x1, OV.y0, z), iso.p(OV.x1, OV.y1, z), "#6c3320", 1.2, 0.7); }+ for (let k = 0; k < Math.max(0, n - rows); k++) { const z0 = (k * OV.h) / (rows + 1), z1 = ((k + 1) * OV.h) / (rows + 1); for (let x = OV.x0 + (k % 2 ? 0.35 : 0.7); x < OV.x1; x += 0.7) { if (x > 7.55 && x < 9.45 && z0 < 2.6) continue; iso.line(iso.p(x, OV.y1, z0), iso.p(x, OV.y1, z1), M.brick.right, 1.2, 0.7); } for (let y = OV.y0 + (k % 2 ? 0.35 : 0.7); y < OV.y1; y += 0.7) iso.line(iso.p(OV.x1, y, z0), iso.p(OV.x1, y, z1), "#6c3320", 1.2, 0.7); }+ },+ });+ I.push({ stage: 3, make: (iso, p) => dome(iso, 8.5, 1.6, OV.h, 2.0, 1.5, 1.5, M.brick, p) });+ // flue: from the dome's crown up the back wall and out through the cut+ box(3, 8.05, 0, 4.2, 8.95, 0.85, 11.6, M.brick, { light: undefined, detail: (iso, p) => { const n = Math.floor(16 * p); for (let k = 0; k < n; k++) { const z = 4.6 + k * 0.45; iso.line(iso.p(8.05, 0.85, z), iso.p(8.95, 0.85, z), M.brick.right, 1, 0.6); iso.line(iso.p(8.95, 0, z), iso.p(8.95, 0.85, z), "#6c3320", 1, 0.6); } } });+ // the mouth: an arch in the +y face, the fire inside it (the light)+ I.push({ stage: 3, make: (iso, p) => {+ const arch = archPts(iso, 8.5, OV.y1, 0.95, 0.95, 1.55), inner = archPts(iso, 8.5, OV.y1 - 0.01, 0.8, 1.05, 1.35);+ iso.make([{ pts: arch, fill: "#3a1d14" }], p, "#2a140e");+ if (p >= 1) iso.poly(inner, "#5a2616");+ }, light: (iso, p) => {+ if (p <= 0) return; // fire: floor of embers, flames, a boule baking at the back, all flat shapes+ const inner = archPts(iso, 8.5, OV.y1 - 0.01, 0.8, 1.05, 1.35); iso.ctx.save(); iso.ctx.beginPath(); inner.forEach(([x, y], i) => (i ? iso.ctx.lineTo(x, y) : iso.ctx.moveTo(x, y))); iso.ctx.clip();+ const b = iso.p(8.5, OV.y1, 1.05), s = iso.u;+ iso.poly([[b[0] - s * 0.9, b[1] + 4], [b[0] - s * 0.9, b[1] - s * 0.5 * p], [b[0] + s * 0.9, b[1] - s * 0.9 * p], [b[0] + s * 0.9, b[1] + 4]], EMBER);+ if (p > 0.3) { iso.poly([[b[0] + s * 0.05, b[1]], [b[0] + s * 0.35, b[1] - s * 1.3], [b[0] + s * 0.55, b[1] - s * 0.7], [b[0] + s * 0.75, b[1] - s * 1.55], [b[0] + s * 0.9, b[1]]], WARM); }+ if (p > 0.5) { iso.poly([[b[0] + s * 0.3, b[1]], [b[0] + s * 0.5, b[1] - s * 0.85], [b[0] + s * 0.7, b[1] - s * 0.3], [b[0] + s * 0.8, b[1]]], HOT); }+ if (p > 0.7) { const q = iso.p(8.1, OV.y1 - 0.6, 1.05); iso.ctx.fillStyle = "#7a3a1c"; iso.ctx.beginPath(); iso.ctx.ellipse(q[0], q[1], s * 0.38, s * 0.24, 0, Math.PI, 0); iso.ctx.fill(); iso.ctx.fillStyle = "#b8612a"; iso.ctx.beginPath(); iso.ctx.ellipse(q[0] + s * 0.06, q[1] - 1, s * 0.26, s * 0.16, 0, Math.PI, 0); iso.ctx.fill(); }+ if (p > 0.85) { iso.poly([[b[0] - s * 0.85, b[1] + 4], [b[0] - s * 0.85, b[1] - s * 0.18], [b[0] + s * 0.85, b[1] - s * 0.3], [b[0] + s * 0.85, b[1] + 4]], CORE); }+ iso.ctx.restore();+ } });+ box(3, 7.5, 3.2, 0.92, 9.5, 3.75, 1.07, M.stone); // hearth ledge++ // ---------- floor light and shadows: poured after the room is built, under everything on the floor+ I.push({ stage: 5, make: () => {}, light: (iso, p) => {+ if (p <= 0) return; // the glow on the floor: three flat bands, spreading from the mouth as they're laid+ const c: [number, number] = [8.5, 3.75]; const bands: [number, number, string][] = [[5.2, 0.13, WARM], [3.6, 0.16, WARM], [2.2, 0.2, HOT]];+ iso.ctx.save(); iso.ctx.beginPath(); [[0, 0], [12, 0], [12, 10], [0, 10]].forEach(([x, y], i) => { const q = iso.p(x, y, 0); if (i) iso.ctx.lineTo(q[0], q[1]); else iso.ctx.moveTo(q[0], q[1]); }); iso.ctx.clip();+ bands.forEach(([r, a, col], k) => { const t = clamp01(p * 3 - k * 0.6); if (t <= 0) return; const pts: [number, number, number][] = []; for (let i = 0; i <= 24; i++) { const th = (i / 24) * Math.PI; pts.push([c[0] + Math.cos(th) * r * t, c[1] + Math.sin(th) * r * 0.85 * t, 0]); } iso.face(pts, col, a); });+ // cast shadows thrown away from the mouth: the baker's, the table's, the rack's (flat, crisp)+ const sh = (pts: [number, number][], a: number) => { if (p < 0.5) return; iso.face(pts.map(([x, y]) => [x, y, 0] as [number, number, number]), "#1a1420", a * clamp01((p - 0.5) * 2)); };+ sh([[7.85, 5.1], [8.5, 4.85], [8.6, 7.4], [8.0, 8.1], [7.5, 7.5]], 0.34); // the baker+ sh([[4.9, 7.6], [7.7, 7.6], [7.9, 9.8], [4.3, 10]], 0.3); // under/behind the table+ iso.ctx.restore();+ } });++ // ---------- table with dough+ I.push({ stage: 3, make: (iso, p) => {+ const legs = [[4.95, 5.85], [7.45, 5.85], [4.95, 7.35], [7.45, 7.35]].map(([x, y]) => iso.boxFaces(x, y, 0, x + 0.22, y + 0.22, 1.75, M.wood));+ legs.forEach((l, k) => iso.make(l, clamp01(p * 5 - k), M.wood.right));+ iso.make(iso.boxFaces(4.9, 5.8, 1.75, 7.7, 7.6, 1.95, { ...M.wood, top: "#c99a68" }), clamp01(p * 5 - 4), M.wood.right);+ }, light: (iso, p) => { if (p > 0) iso.face([[7.7, 5.8, 1.75], [7.7, 7.6, 1.75], [7.7, 7.6, 1.95], [7.7, 5.8, 1.95]], WARM, 0.35 * p); }, detail: (iso, p) => {+ if (p <= 0) return; const r = rngLite(3), n = Math.floor(40 * p); // flour dusted across the top+ for (let k = 0; k < n; k++) { const x = 5.1 + r() * 2.4, y = 6.0 + r() * 1.4; iso.face([[x, y, 1.951], [x + 0.12, y, 1.951], [x + 0.12, y + 0.12, 1.951], [x, y + 0.12, 1.951]], "#f1e7d2", 0.8); }+ } });+ I.push({ stage: 4, make: (iso, p) => { // dough balls and a rolling pin+ [[5.5, 6.3], [6.1, 6.25], [5.6, 6.95], [6.25, 6.9]].forEach(([x, y], k) => { if (clamp01(p * 5 - k) > 0) dough(iso, x, y, 1.95, 0.27); });+ if (p > 0.8) iso.make(iso.boxFaces(6.8, 6.1, 1.95, 7.02, 7.3, 2.15, { top: "#d7ae7c", left: "#b88d5c", right: "#9a7248" }), clamp01((p - 0.8) * 5), "#9a7248");+ } });+ // ---------- ladder to the loft+ I.push({ stage: 3, make: (iso, p) => {+ const rail = (y: number) => [iso.p(6.1, y, 0), iso.p(6.1, y + 0.12, 0), iso.p(4.62, y + 0.12, 6.4), iso.p(4.62, y, 6.4)];+ iso.make([{ pts: rail(8.55), fill: M.wood.left }], clamp01(p * 3), M.wood.right);+ for (let k = 1; k <= 8; k++) { const t = k / 9; if (clamp01(p * 3 - 1 - t) <= 0) continue; const x = 6.1 - 1.48 * t, z = 6.4 * t; iso.make(iso.boxFaces(x - 0.05, 8.6, z - 0.05, x + 0.05, 9.28, z + 0.05, M.wood), 1, M.wood.right); }+ iso.make([{ pts: rail(9.28), fill: M.wood.top }], clamp01(p * 3 - 2), M.wood.right);+ } });+ // ---------- a basket of baguettes standing in the light, waiting for the shop to open+ I.push({ stage: 4, make: (iso, p) => {+ if (p <= 0) return; const bx = 10.9, by = 8.9, r = 0.55, hB = 0.9;+ const W: Mat = { top: "#8a6a44", left: "#b58a57", right: "#94703f" };+ iso.make(iso.boxFaces(bx - r, by - r, 0, bx + r, by + r, hB, W), clamp01(p * 2), W.right);+ const sticks: [number, number, number][] = [[-0.25, -0.2, 0.2], [0.1, -0.3, -0.15], [0.25, 0.1, 0.1], [-0.1, 0.25, -0.2], [0.0, 0.0, 0.05]];+ sticks.forEach(([dx, dy, lean], k) => { if (clamp01(p * 2 - 1 - k * 0.15) <= 0) return; const a = iso.p(bx + dx, by + dy, hB - 0.2), b = iso.p(bx + dx + lean, by + dy - lean * 0.5, hB + 1.9); const w = iso.u * 0.17;+ iso.poly([[a[0] - w, a[1]], [b[0] - w, b[1]], [b[0] + w, b[1]], [a[0] + w, a[1]]], M.crust.left); iso.poly([[a[0], a[1]], [b[0], b[1]], [b[0] + w, b[1]], [a[0] + w, a[1]]], M.crust.right);+ iso.ctx.fillStyle = M.crust.top; iso.ctx.beginPath(); iso.ctx.ellipse(b[0], b[1], w, w * 0.6, 0, 0, Math.PI * 2); iso.ctx.fill();+ for (let c = 1; c <= 3; c++) { const t = c / 4.2; iso.line([a[0] + (b[0] - a[0]) * t - w * 0.7, a[1] + (b[1] - a[1]) * t + 2], [a[0] + (b[0] - a[0]) * t + w * 0.2, a[1] + (b[1] - a[1]) * t - 3], "#f2d19a", 1.2); } });+ iso.face([[bx - r, by + r, hB * 0.45], [bx + r, by + r, hB * 0.45], [bx + r, by + r, hB * 0.55], [bx - r, by + r, hB * 0.55]], "#7d5c36"); // woven band+ }, light: (iso, p) => { if (p > 0) warmBox(iso, 10.35, 8.35, 0, 11.45, 9.45, 0.9, p); } });+ // ---------- the baker, last: nearest the camera of everything he overlaps+ I.push({ stage: 4, make: (iso, p) => baker(iso, 8.2, 5.0, p, 0), light: (iso, p) => { if (p > 0) baker(iso, 8.2, 5.0, 1, p); } });+ return I;+};++// ---------------------------------------------------------------- props+const rngLite = (seed: number) => { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };+const archPts = (iso: Iso, cx: number, y: number, hw: number, z0: number, zSpring: number): P2[] => {+ const pts: P2[] = [iso.p(cx - hw, y, z0), iso.p(cx + hw, y, z0)];+ for (let i = 0; i <= 12; i++) { const a = (i / 12) * Math.PI; pts.push(iso.p(cx + Math.cos(a) * hw, y, zSpring + Math.sin(a) * hw * 0.8)); }+ return pts;+};+// A dome under the cube rule: the half turned to +x in the right tone, the half turned to +y in+// the left tone (the meridian between them projects to a vertical line through the crown), and+// the cap that faces up in the top tone. Three flat planes, one silhouette.+const dome = (iso: Iso, cx: number, cy: number, z0: number, rx: number, ry: number, rz: number, m: Mat, p: number) => {+ if (p <= 0) return; const ctx = iso.ctx, ring = (e: number, n = 48) => Array.from({ length: n }, (_, i) => { const a = (i / n) * Math.PI * 2; return iso.p(cx + Math.cos(a) * Math.cos(e) * rx, cy + Math.sin(a) * Math.cos(e) * ry, z0 + Math.sin(e) * rz); });+ const pts: P2[] = []; for (let j = 0; j <= 12; j++) pts.push(...ring((j / 12) * (Math.PI / 2), 36));+ const hull = convexHull(pts), ys = hull.map((q) => q[1]), y0 = Math.min(...ys), y1 = Math.max(...ys), mid = iso.p(cx, cy, z0)[0];+ ctx.save(); if (p < 1) { ctx.beginPath(); ctx.rect(-1e4, y1 - (y1 - y0 + 2) * p, 2e4, 1e4); ctx.clip(); }+ iso.poly(hull, m.left);+ ctx.save(); ctx.beginPath(); ctx.rect(mid, -1e4, 1e4, 2e4); ctx.clip(); iso.poly(hull, m.right); ctx.restore();+ const cap = ring(0.95); ctx.save(); ctx.beginPath(); hull.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.clip();+ const capHull = convexHull([...cap, ...ring(1.25, 24), iso.p(cx, cy, z0 + rz)]); iso.poly(capHull, m.top); ctx.restore();+ ctx.restore();+};+const convexHull = (pts: P2[]): P2[] => {+ const q = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]), 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 q) { while (lo.length >= 2 && cr(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); }+ for (let i = q.length - 1; i >= 0; i--) { const p = q[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), ...up.slice(0, -1)];+};+// Flat warm light on a box: the +x face and the top take one tint each if they can see the+// mouth, stepped by distance (three bands), never a gradient.+const MOUTH: [number, number, number] = [8.5, 3.6, 1.7];+const warmStep = (d: number) => (d < 3.5 ? 0.4 : d < 5.5 ? 0.27 : d < 8.5 ? 0.15 : 0);+const warmBox = (iso: Iso, x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, p: number) => {+ if (p <= 0) return; const [lx, ly, lz] = MOUTH;+ const cx = (y0 + y1) / 2 > ly - 0.4 && x1 < lx ? warmStep(Math.hypot(lx - x1, ly - (y0 + y1) / 2, lz - (z0 + z1) / 2)) : 0;+ if (cx > 0) iso.face([[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], WARM, cx * p);+ const ct = (y0 + y1) / 2 > ly - 0.4 && z1 < lz + 0.6 ? warmStep(Math.hypot(lx - (x0 + x1) / 2, ly - (y0 + y1) / 2, lz - z1)) : 0;+ if (ct > 0) iso.face([[x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]], WARM, ct * p);+};+const loaf = (iso: Iso, x0: number, y0: number, z0: number, x1: number, y1: number, z1: number) => {+ const m = M.crust; iso.make(iso.boxFaces(x0, y0, z0, x1, y1, z1 - 0.08, m), 1, m.right);+ iso.face([[x0 + 0.05, y0 + 0.04, z1 - 0.08], [x1 - 0.05, y0 + 0.04, z1 - 0.08], [x1 - 0.1, y1 - 0.04, z1], [x0 + 0.1, y1 - 0.04, z1]], m.top);+ for (let k = 1; k <= 3; k++) { const x = x0 + ((x1 - x0) * k) / 4; iso.line(iso.p(x - 0.08, y0 + 0.1, z1), iso.p(x + 0.08, y1 - 0.1, z1), "#f2d19a", 1.3); } // scoring cuts+};+const boule = (iso: Iso, x: number, y: number, z: number, r: number) => {+ const c = iso.p(x, y, z), u = iso.u; const ctx = iso.ctx;+ ctx.fillStyle = M.crust.right; ctx.beginPath(); ctx.ellipse(c[0], c[1] - r * u * 0.45, r * u * 1.35, r * u * 0.95, 0, 0, Math.PI * 2); ctx.fill();+ ctx.fillStyle = M.crust.left; ctx.beginPath(); ctx.ellipse(c[0] - r * u * 0.25, c[1] - r * u * 0.55, r * u * 1.05, r * u * 0.8, 0, 0, Math.PI * 2); ctx.fill();+ ctx.fillStyle = M.crust.top; ctx.beginPath(); ctx.ellipse(c[0] - r * u * 0.1, c[1] - r * u * 0.85, r * u * 0.85, r * u * 0.5, 0, 0, Math.PI * 2); ctx.fill();+ ctx.strokeStyle = "#f2d19a"; ctx.lineWidth = 1.3; ctx.beginPath(); ctx.moveTo(c[0] - r * u * 0.55, c[1] - r * u * 0.85); ctx.lineTo(c[0] + r * u * 0.35, c[1] - r * u * 0.85); ctx.stroke();+};+const dough = (iso: Iso, x: number, y: number, z: number, r: number) => {+ const c = iso.p(x, y, z), u = iso.u, ctx = iso.ctx;+ ctx.fillStyle = "#d9cbb0"; ctx.beginPath(); ctx.ellipse(c[0], c[1] - r * u * 0.3, r * u * 1.3, r * u * 0.72, 0, 0, Math.PI * 2); ctx.fill();+ ctx.fillStyle = "#f1e6cf"; ctx.beginPath(); ctx.ellipse(c[0] - r * u * 0.15, c[1] - r * u * 0.45, r * u * 0.95, r * u * 0.5, 0, 0, Math.PI * 2); ctx.fill();+};+const sack = (iso: Iso, x: number, y: number, z: number, p: number) => {+ if (p <= 0) return; const m = M.sack, w = 0.55, d = 0.75, h = 1.05;+ iso.make(iso.boxFaces(x - w, y - d, z, x + w, y + d, z + h * 0.8, m), p, m.right);+ if (p < 1) return;+ iso.face([[x - w, y - d, z + h * 0.8], [x + w, y - d, z + h * 0.8], [x + w * 0.6, y - d * 0.3, z + h], [x - w * 0.6, y - d * 0.3, z + h]], m.top);+ iso.face([[x - w, y + d, z + h * 0.8], [x + w, y + d, z + h * 0.8], [x + w * 0.6, y + d * 0.3, z + h], [x - w * 0.6, y + d * 0.3, z + h]], m.top);+ iso.face([[x - w * 0.6, y - d * 0.3, z + h], [x + w * 0.6, y - d * 0.3, z + h], [x + w * 0.6, y + d * 0.3, z + h], [x - w * 0.6, y + d * 0.3, z + h]], "#efe2c4");+ iso.line(iso.p(x + w, y - d * 0.2, z + h * 0.35), iso.p(x + w, y + d * 0.2, z + h * 0.35), "#8f7d58", 2); // stencil band+};++// ---------------------------------------------------------------- the baker+// Screen-space figure over his foot point, authored at u = 36 facing +x-local and MIRRORED, so he+// faces screen lower-left (world +y) toward the table. 7.5 heads: head 21 px, chin at 1 head,+// shoulders ~1.4, elbows ~3, wrists and crotch ~4, knees ~5.6, soles at 7.5. Weight on both feet,+// the near foot a little forward. The oven is behind him (screen upper right), so his BACK edge+// (local -x) takes the warm light; his front sits in the cool night ambient.+const baker = (iso: Iso, x: number, y: number, p: number, lit: number) => {+ const f = iso.p(x, y, 0), k = iso.u / 36, ctx = iso.ctx;+ const S = (pts: P2[]): P2[] => pts.map(([a, b]) => [f[0] - a * k, f[1] + b * k]);+ const shape = (pts: P2[], col: string, a = 1) => iso.poly(S(pts), col, a);+ const ell = (cx: number, cy: number, rx: number, ry: number, col: string) => { ctx.fillStyle = col; ctx.beginPath(); ctx.ellipse(f[0] - cx * k, f[1] + cy * k, rx * k, ry * k, 0, 0, Math.PI * 2); ctx.fill(); };+ ctx.save();+ if (p < 1) { ctx.beginPath(); ctx.rect(-1e4, f[1] - 185 * k, 2e4, 190 * k * p); ctx.clip(); } // painted top down, as a figure is filled+ const skin = "#c98d6c", skinD = "#9a654e", white = "#d9d6d2", whiteD = "#a9a9b6", whiteDD = "#8c8c9c", apron = "#e4e0d8", trou = "#384058", trouD = "#282d40", shoe = "#241c1c", hair = "#3f2c22", wood = "#a27a50", woodD = "#7a5a3a";+ if (!lit) {+ // far leg (his left, behind) and shoe; then the near leg, foot turned out a little+ shape([[-9, -76], [1, -76], [0, -42], [-1, -9], [-8, -9], [-10, -42]], trouD);+ shape([[-10, -9], [-1, -9], [8, -4], [9, 0], [-10, 0]], shoe);+ shape([[-1, -78], [11, -76], [10, -42], [9, -6], [1, -6], [0, -42]], trou);+ shape([[0, -6], [9, -6], [19, -1], [20, 3], [0, 3]], shoe);+ // chef's jacket: back half in shade, front half lighter, 3/4 so the near side is wider+ shape([[-14, -127], [15, -129], [18, -110], [16, -78], [-12, -76], [-16, -102]], whiteD);+ shape([[-5, -128], [15, -129], [18, -110], [16, -78], [-2, -77], [-3, -102]], white);+ // apron: bib to knees, the near edge swinging forward with the turn+ shape([[-7, -115], [9, -116], [10, -96], [16, -47], [-9, -45], [-7, -96]], apron);+ shape([[-7, -115], [-2, -115], [-3, -96], [-3, -45], [-9, -45], [-7, -96]], whiteD);+ shape([[-13, -97], [16, -98], [16, -94], [-13, -93]], whiteDD); // waist tie+ ell(12, -121, 1.3, 1.3, whiteDD); ell(12, -111, 1.3, 1.3, whiteDD); // jacket buttons above the bib+ // neck, head three-quarter toward the table, hair, ear, nose+ shape([[-3, -130], [5, -130], [5, -136], [-3, -136]], skinD);+ shape([[-8, -140], [-6, -153], [3, -157], [10, -152], [12, -145], [11, -139], [7, -134], [0, -133], [-6, -135]], skin);+ shape([[-8, -140], [-6, -153], [-1, -156], [-2, -146], [-4, -135]], skinD);+ shape([[11, -146], [14.5, -142.5], [11.5, -140.5]], skinD); // nose+ shape([[4, -148], [7, -148], [7, -146.6], [4, -146.6]], "#3a2a24"); // eye (brow shadow)+ shape([[5, -138], [9, -138.4], [8.6, -137.2], [5, -136.9]], skinD); // mouth+ shape([[-9, -144], [-7, -155], [2, -158], [4, -154], [-3, -151], [-5, -142]], hair);+ shape([[-1, -146], [2, -146], [2, -141], [-1, -141]], skinD); // ear+ // toque: band, then the pleated puff, its turned side in shade+ shape([[-8, -153], [10, -155], [10, -161], [-8, -159]], white);+ shape([[-12, -160], [-9, -175], [1, -181], [12, -175], [14, -161], [10, -160], [-8, -158]], apron);+ shape([[-12, -160], [-9, -175], [-4, -178], [-4, -159]], whiteD);+ [[-1, -178], [5, -178]].forEach(([a, b]) => shape([[a, b], [a + 1.2, b], [a + 1.6, -161], [a + 0.4, -161]], whiteD)); // pleats+ // far arm: forearm reaching forward under the handle+ shape([[-11, -124], [-4, -124], [5, -100], [16, -93], [14, -87], [-1, -94], [-13, -106]], whiteD);+ shape([[14, -94], [21, -91], [21, -85], [14, -87]], skinD);+ // the peel: handle from behind his hip out past his hands, blade forward and flat (a 2:1 plane)+ shape([[-24, -104], [80, -52], [79, -48], [-25, -100]], wood);+ shape([[70, -58], [104, -41], [86, -32], [52, -49]], "#b58e62");+ shape([[52, -49], [86, -32], [86, -29], [52, -46]], woodD);+ // the boule on the blade, cube-rule tones like every other loaf+ ell(78, -48, 13, 8.5, M.crust.right); ell(76, -50, 11, 7, M.crust.left); ell(77, -53, 8, 4.5, M.crust.top);+ iso.line([f[0] - 72 * k, f[1] - 53 * k], [f[0] - 82 * k, f[1] - 53 * k], "#f2d19a", 1.3 * k);+ // near arm: shoulder, elbow bent at the hip, forearm forward, hand closed round the handle+ shape([[8, -128], [18, -125], [19, -106], [30, -86], [26, -80], [11, -100], [9, -112]], white);+ shape([[26, -84], [34, -80], [35, -75], [30, -72], [25, -76]], skin);+ shape([[27, -78], [34, -76], [33, -73], [28, -74]], skinD); // fingers wrapped under the handle+ shape([[31, -83], [34.5, -82], [34, -80], [31, -80.5]], skinD); // thumb over the top+ } else {+ // the oven behind him: a flat warm edge down every surface that faces it (his back)+ const a = 0.9 * lit, L = "#ffcf94";+ shape([[-14, -127], [-10, -127], [-12, -102], [-9, -77], [-12, -76], [-16, -102]], L, a); // jacket back+ shape([[-11, -124], [-8, -124], [-10, -107], [-13, -106]], L, a * 0.8); // far arm back+ shape([[-9, -144], [-7, -155], [-5, -156], [-7, -145]], "#e0a070", a); // back of the hair+ shape([[-12, -160], [-9, -175], [-6, -177], [-9, -160]], "#ffe0b0", a); // toque+ shape([[-9, -76], [-7, -76], [-8, -42], [-7, -9], [-9, -9], [-10, -42]], "#5a5462", a); // back of the far leg+ shape([[-9, -45], [-7, -45], [-6, -96], [-7, -96]], "#ffe0b0", a * 0.7); // apron edge+ shape([[-24, -104], [-10, -97], [-10, -95], [-25, -100]], "#d9a870", a); // handle end+ }+ ctx.restore();+};++// ---------------------------------------------------------------- timeline + render+const STAGES = [[4, 40], [40, 100], [100, 170], [170, 250], [250, 330], [330, 390], [390, 450]]; // grid, massing, walls, interiors, props, light, details+export const isometric: Film = {+ meta: { title: "Isometric · the night bake", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "bake", start: 0, end: N, draw: (ctx: Ctx, fr, env) => {+ const W = env.W, H = env.H, u = Math.min(W, H) / 29.5, iso = new Iso(ctx, u, W / 2 - 1.0 * u, H / 2 + 2.3 * u);+ const f = fr >= N - HOLD ? N : fr;+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = BG; ctx.fillRect(0, 0, W, H);+ // 0: the iso grid, lines ruled one after another across the ground plane+ { const p = span(f, STAGES[0][0], STAGES[0][1]), n = 46, R = 23; for (let k = 0; k < n; k++) { const t = clamp01(p * n * 0.5 - k * 0.5); if (t <= 0) break; const i = k >> 1, d = (k & 1) ? 1 : 0, c = i - R + 5; const a = d ? iso.p(c, -R + 5, -0.6) : iso.p(-R + 5, c, -0.6), b = d ? iso.p(c, R + 5, -0.6) : iso.p(R + 5, c, -0.6); iso.line(a, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], GRID, 1); } }+ // 1: massing blocks, construction lines of the big solids+ { const p = span(f, STAGES[1][0], STAGES[1][1]); const blocks: [number, number, number, number, number, number][] = [[-0.6, -0.6, -0.6, 12, 10, 0], [-0.6, -0.6, 0, 12, 0, 11], [-0.6, 0, 0, 0, 10, 11], [6.4, 0, 0, 10.6, 3.2, 3.0], [0, 0, 5.8, 4.6, 10, 6.3], [4.9, 5.8, 1.75, 7.7, 7.6, 1.95]];+ blocks.forEach((b, k) => { const t = clamp01(p * blocks.length - k * 0.8); if (t <= 0) return; const fs = iso.boxFaces(...b, { top: MASS, left: MASS, right: MASS }); ctx.globalAlpha = 0.22; fs.forEach((q) => iso.poly(q.pts, MASS, 0.18 * clamp01(t * 3))); ctx.globalAlpha = 1; fs.forEach((q) => { ctx.save(); ctx.beginPath(); q.pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); ctx.clip(); const L = q.pts.length; for (let i = 0; i < L; i++) { const tt = clamp01(t * L - i); if (tt > 0) { const a = q.pts[i], c = q.pts[(i + 1) % L]; iso.line(a, [a[0] + (c[0] - a[0]) * tt, a[1] + (c[1] - a[1]) * tt], MASS, 2.4); } } ctx.restore(); }); }); }+ // 2..6: every item in painter's order, each at its own progress in its stage+ const items = cachedScene(env), byStage = [0, 0, 0, 0, 0, 0, 0], idx = new Map<Item, number>();+ items.forEach((it) => idx.set(it, byStage[it.stage]++));+ const lightItems = items.filter((it) => it.light), detItems = items.filter((it) => it.detail);+ const prog = (st: number, k: number, n: number) => { const [a, b] = STAGES[st], L = b - a, w = Math.min(L, (L / n) * 2.2); return span(f, a + ((L - w) * k) / Math.max(1, n - 1), a + ((L - w) * k) / Math.max(1, n - 1) + w); };+ items.forEach((it) => {+ it.make(iso, prog(it.stage, idx.get(it)!, byStage[it.stage]));+ if (it.light) it.light(iso, prog(5, lightItems.indexOf(it), lightItems.length));+ if (it.detail) it.detail(iso, prog(6, detItems.indexOf(it), detItems.length));+ });+ } }],+};+const cachedScene = (env: { cache: Map<string, unknown> }) => { let s = env.cache.get("isometric/scene") as Item[] | undefined; if (!s) { s = scene(); env.cache.set("isometric/scene", s); } return s; };++export const STYLE = { id: "isometric", name: "Isometric cutaway", family: "digital", medium: "flat vector planes on a true 2:1 isometric grid, three tones per material, crisp edges, pen-tool order", nearest: "koi", hero: "a two-floor bakery cutaway at night, lit by its oven, the baker turning with a fresh loaf" };diff --git a/engine/src/canvas-core/isometricKit.ts b/engine/src/canvas-core/isometricKit.tsnew file mode 100644index 0000000..8a6a649--- /dev/null+++ b/engine/src/canvas-core/isometricKit.ts@@ -0,0 +1,54 @@+// ISOMETRIC KIT. True 2:1 isometric (dimetric) projection and the pen-tool marks of a flat+// vector iso illustration: planes with three face tones per material, crisp edges, no blur.+//+// World: x runs to screen lower-right, y to screen lower-left, z up. One unit of x or y moves+// (u, u/2) on screen: every horizontal edge is a 2:1 line. One unit of z moves 1.2247u up (the+// true vertical of a 30-degree-elevation dimetric view), so a cube reads as a cube.+// Visible faces of an axis box are its top (+z), its left face (+y) and its right face (+x).+import type { Ctx } from "./core";++export type P3 = [number, number, number];+export type P2 = [number, number];+export type Mat = { top: string; left: string; right: string };+export const ZK = 1.2247;++export class Iso {+ constructor(public ctx: Ctx, public u: number, public ox: number, public oy: number) {}+ p(x: number, y: number, z: number): P2 { return [this.ox + (x - y) * this.u, this.oy + ((x + y) * this.u) / 2 - z * ZK * this.u]; }+ // ---- raw marks+ poly(pts: P2[], fill: string, alpha = 1) { const c = this.ctx; c.globalAlpha = alpha; c.fillStyle = fill; c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill(); c.globalAlpha = 1; }+ line(a: P2, b: P2, color: string, w: number, alpha = 1) { const c = this.ctx; c.globalAlpha = alpha; c.strokeStyle = color; c.lineWidth = w; c.lineCap = "butt"; c.beginPath(); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); c.stroke(); c.globalAlpha = 1; }+ // a plane given as world points, filled flat+ face(pts: P3[], fill: string, alpha = 1) { this.poly(pts.map((q) => this.p(...q)), fill, alpha); }+ // the three visible faces of a box+ boxFaces(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, m: Mat): { pts: P2[]; fill: string }[] {+ const P = (x: number, y: number, z: number) => this.p(x, y, z);+ return [+ { pts: [P(x0, y1, z0), P(x1, y1, z0), P(x1, y1, z1), P(x0, y1, z1)], fill: m.left }, // +y face+ { pts: [P(x1, y0, z0), P(x1, y1, z0), P(x1, y1, z1), P(x1, y0, z1)], fill: m.right }, // +x face+ { pts: [P(x0, y0, z1), P(x1, y0, z1), P(x1, y1, z1), P(x0, y1, z1)], fill: m.top }, // top+ ];+ }+ // A plane being MADE: the pen traces its outline (kept inside the plane), then the fill+ // sweeps down from the traced top edge. p in [0,1]; at 1 only the clean fill remains.+ make(faces: { pts: P2[]; fill: string }[], p: number, edge: string) {+ if (p <= 0) return; const c = this.ctx;+ if (p >= 1) { faces.forEach((f) => this.poly(f.pts, f.fill)); return; }+ const pe = Math.min(1, p / 0.45), pf = Math.max(0, (p - 0.45) / 0.55);+ faces.forEach((f) => {+ const ys = f.pts.map((q) => q[1]), y0 = Math.min(...ys), y1 = Math.max(...ys);+ if (pf > 0) { c.save(); c.beginPath(); c.rect(-1e4, y0 - 1, 2e4, (y1 - y0 + 2) * pf); c.clip(); this.poly(f.pts, f.fill); c.restore(); }+ // traced outline: length-proportional progress round the perimeter, clipped to the plane+ c.save(); c.beginPath(); f.pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.clip();+ const segs = f.pts.map((a, i) => [a, f.pts[(i + 1) % f.pts.length]] as [P2, P2]), L = segs.reduce((s, [a, b]) => s + Math.hypot(b[0] - a[0], b[1] - a[1]), 0);+ let left = L * pe; c.strokeStyle = edge; c.lineWidth = 3; c.beginPath();+ for (const [a, b] of segs) { if (left <= 0) break; const l = Math.hypot(b[0] - a[0], b[1] - a[1]), t = Math.min(1, left / l); c.moveTo(a[0], a[1]); c.lineTo(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t); left -= l; }+ c.stroke(); c.restore();+ });+ }+}++export const clamp01 = (t: number) => (t <= 0 ? 0 : t >= 1 ? 1 : t);+export const ease = (t: number) => { t = clamp01(t); return t >= 1 ? 1 : 1 - (1 - t) ** 2; };+// progress of an item scheduled [a, b) in frames+export const span = (f: number, a: number, b: number) => (f >= b ? 1 : f <= a ? 0 : (f - a) / (b - a));diff --git a/engine/src/canvas-core/koi.ts b/engine/src/canvas-core/koi.tsindex fa12547..30fb4fe 100644--- a/engine/src/canvas-core/koi.ts+++ b/engine/src/canvas-core/koi.ts@@ -1,6 +1,7 @@import { Gfx, PENCIL, rng, type Ctx, type Env, type P } from "./core";import type { Film } from "./film";-import { blob, body, clipped, fillShape, ink, lerpP, mix, profile, smooth, type Body } from "./gallery";+import { area, blob, body, clipped, fillShape, ink, lerpP, mix, profile, resample, smooth, type Body, type InkOpts } from "./gallery";+import { cut, part, stagger, streakClip, streaks } from "./koiDrawKit";// KOI · marker comic. Bold cel fills with a hard shadow edge, one heavy confident contour that// thickens away from the light, and a single dramatic C-curve for the whole fish.@@ -17,6 +18,24 @@ const WATER = "#137582", WATER_D = "#0c5360", WATER_L = "#3aa6ad";const WHITE = "#fdf8ee", WHITE_S = "#c9d6e0", HI = "#ec4a22", HI_S = "#b72c1a", SUMI = "#1b1830";const FIN = "#f7efe4", FIN_S = "#d5dde2";+// THE PROCESS HOOK (koiDraw). drawKoi takes an optional clock: progress 0..1 for each (element,+// pass) of a marker comic being made: "pencil" lay-in, "flat" cel fills laid in marker streaks,+// "shade" hard shadow shapes, "detail" (scales, rays, gel-pen whites), "line" the heavy contour.+// With no clock every gate is 1 and every branch below takes the ORIGINAL call, byte for byte.+export type KoiClock = (el: string, pass: string) => number;+const ALL: KoiClock = () => 1;+// a flat laid by a chisel marker: draw fn only where the marker has been by p+const lay = (g: Gfx, p: number, shapes: P[][], fn: () => void, seed: number, w = 30, ang = -0.5, reach = 1e9) => {+ if (p >= 1) return fn(); if (p <= 0) return;+ const c = g.cur; c.save(); streakClip(c, streaks(shapes, w, ang, seed, reach), p); fn(); c.restore();+};+// the contour grows along its centreline; a closed one is drawn open until it closes+const inkP = (g: Gfx, center: P[], color: string, o: InkOpts, alpha: number | undefined, q: number) => {+ if (q >= 1) return alpha === undefined ? ink(g, center, color, o) : ink(g, center, color, o, alpha); if (q <= 0) return;+ const path = o.closed ? [...center, center[0]] : center, side = o.closed ? (area(center) > 0 ? -1 : 1) : o.side;+ ink(g, cut(path, q), color, { ...o, closed: false, side, taper: [o.closed ? 0.04 : (o.taper?.[0] ?? 0.12), 0.08] }, alpha ?? 1);+};+const koiBody = (): Body => body([[300, 222], [404, 292], [502, 408], [556, 556], [534, 694], [468, 792]],profile([[0, 0], [0.012, 27], [0.035, 46], [0.08, 64], [0.16, 80], [0.27, 90], [0.4, 88], [0.55, 78], [0.7, 60], [0.82, 40], [0.92, 26], [1, 22]]),@@ -51,66 +70,89 @@ const tail = (b: Body): { shape: P[]; rays: P[][] } => {return { shape, rays };};-const water = (g: Gfx) => {+const water = (g: Gfx, k: KoiClock = ALL) => {+ const fl = k("water", "flat"), dt = k("water", "detail");g.group("plain", () => {- fillShape(g, [[0, 0], [1080, 0], [1080, 1080], [0, 1080]], WATER_D);+ const sq: P[] = [[0, 0], [1080, 0], [1080, 1080], [0, 1080]], b1 = blob(560, 540, 610, 470, 401, 0.1, 20, -0.75), b2 = blob(520, 520, 400, 290, 402, 0.12, 18, -0.9);+ lay(g, part(fl, 0, 3), [sq], () => fillShape(g, sq, WATER_D), 4001, 64, -0.62, 300);// the colourist's flats: a lit body of water through the middle, deep water in the corners- fillShape(g, blob(560, 540, 610, 470, 401, 0.1, 20, -0.75), WATER);- fillShape(g, blob(520, 520, 400, 290, 402, 0.12, 18, -0.9), mix(WATER, WATER_L, 0.22));+ lay(g, part(fl, 1, 3), [b1], () => fillShape(g, b1, WATER), 4002, 60, -0.62, 300);+ lay(g, part(fl, 2, 3), [b2], () => fillShape(g, b2, mix(WATER, WATER_L, 0.22)), 4003, 56, -0.62, 280);const r = rng(311);- for (let i = 0; i < 12; i++) { const x = 60 + r() * 960, y = 60 + r() * 960, l = 70 + r() * 150, a = -0.42 + (r() - 0.5) * 0.12; ink(g, smooth([[x, y], [x + Math.cos(a) * l * 0.5, y + Math.sin(a) * l * 0.5 + 3], [x + Math.cos(a) * l, y + Math.sin(a) * l]], false, 6), WATER_L, { w: 5 + r() * 5, shadow: 0, taper: [0.4, 0.4], seed: 500 + i }, 0.45); }+ for (let i = 0; i < 12; i++) { const x = 60 + r() * 960, y = 60 + r() * 960, l = 70 + r() * 150, a = -0.42 + (r() - 0.5) * 0.12; const ln = smooth([[x, y], [x + Math.cos(a) * l * 0.5, y + Math.sin(a) * l * 0.5 + 3], [x + Math.cos(a) * l, y + Math.sin(a) * l]], false, 6); inkP(g, ln, WATER_L, { w: 5 + r() * 5, shadow: 0, taper: [0.4, 0.4], seed: 500 + i }, 0.45, part(dt, i, 12)); }});};-const lilyPad = (g: Gfx, cx: number, cy: number, rr: number, notch: number, seed: number) => {+export const padShape = (cx: number, cy: number, rr: number, notch: number, seed: number): P[] => {const r = rng(seed), rim: P[] = [];for (let i = 0; i <= 40; i++) { const a = notch + 0.2 + (i / 40) * (Math.PI * 2 - 0.4); rim.push([cx + Math.cos(a) * rr * (1 + (r() - 0.5) * 0.03), cy + Math.sin(a) * rr * 0.93 * (1 + (r() - 0.5) * 0.03)]); }- const pad: P[] = [[cx, cy], ...rim];+ return [[cx, cy], ...rim];+};+const lilyPad = (g: Gfx, cx: number, cy: number, rr: number, notch: number, seed: number, k: KoiClock = ALL, el = "pad") => {+ const pad = padShape(cx, cy, rr, notch, seed), rim = pad.slice(1);+ const fl = k(el, "flat"), sh = k(el, "shade"), dt = k(el, "detail"), ln = k(el, "line");g.group("plain", () => {- fillShape(g, pad.map(([x, y]) => [x + 16, y + 22] as P), "#0a3f49", 0.55); // its shadow on the water- fillShape(g, pad, "#2f9a4f");- clipped(g, pad, () => { fillShape(g, pad.map(([x, y]) => [x - 20, y - 18] as P), "#56bb5c"); fillShape(g, blob(cx - rr * 0.35, cy - rr * 0.35, rr * 0.35, rr * 0.16, seed + 3, 0.2, 12, -0.6), "#9ee07f", 0.8); });- for (let i = 0; i < 11; i++) { const a = notch + 0.35 + (i / 10) * (Math.PI * 2 - 0.7); ink(g, smooth([[cx, cy], [cx + Math.cos(a) * rr * 0.5, cy + Math.sin(a) * rr * 0.46], [cx + Math.cos(a + 0.05) * rr * 0.9, cy + Math.sin(a + 0.05) * rr * 0.84]], false, 6), "#1c6a3a", { w: 2.4, seed: seed + i, shadow: 0, taper: [0.1, 0.5] }, 0.7); }- ink(g, pad.slice(1), INK, { w: 5.5, light: LIGHT, shadow: 0.9, seed: seed + 20, taper: [0.02, 0.02] });- ink(g, [rim[rim.length - 1], [cx, cy], rim[0]], INK, { w: 4.5, light: LIGHT, shadow: 0.9, seed: seed + 21, taper: [0.08, 0.08] });+ const shadow = pad.map(([x, y]) => [x + 16, y + 22] as P);+ lay(g, sh, [shadow], () => fillShape(g, shadow, "#0a3f49", 0.55), seed + 71, 26, 0.9); // its shadow on the water+ const cel = () => { fillShape(g, pad, "#2f9a4f"); clipped(g, pad, () => { fillShape(g, pad.map(([x, y]) => [x - 20, y - 18] as P), "#56bb5c"); fillShape(g, blob(cx - rr * 0.35, cy - rr * 0.35, rr * 0.35, rr * 0.16, seed + 3, 0.2, 12, -0.6), "#9ee07f", 0.8); }); };+ if (sh >= 1) cel(); else { lay(g, fl, [pad], () => fillShape(g, pad, "#56bb5c"), seed + 72, 30, -0.5); lay(g, sh, [pad], cel, seed + 73, 24, 0.7); }+ for (let i = 0; i < 11; i++) { const a = notch + 0.35 + (i / 10) * (Math.PI * 2 - 0.7); inkP(g, smooth([[cx, cy], [cx + Math.cos(a) * rr * 0.5, cy + Math.sin(a) * rr * 0.46], [cx + Math.cos(a + 0.05) * rr * 0.9, cy + Math.sin(a + 0.05) * rr * 0.84]], false, 6), "#1c6a3a", { w: 2.4, seed: seed + i, shadow: 0, taper: [0.1, 0.5] }, 0.7, part(dt, i, 11)); }+ inkP(g, rim, INK, { w: 5.5, light: LIGHT, shadow: 0.9, seed: seed + 20, taper: [0.02, 0.02] }, undefined, part(ln, 0, 1.25));+ inkP(g, [rim[rim.length - 1], [cx, cy], rim[0]], INK, { w: 4.5, light: LIGHT, shadow: 0.9, seed: seed + 21, taper: [0.08, 0.08] }, undefined, stagger(ln, 0.8, 0.2));});};-const waterLily = (g: Gfx, cx: number, cy: number, s: number, seed: number) => {- const r = rng(seed);+const waterLily = (g: Gfx, cx: number, cy: number, s: number, seed: number, kc: KoiClock = ALL, el = "lily") => {+ const r = rng(seed), fl = kc(el, "flat"), shd = kc(el, "shade"), dt = kc(el, "detail"), ln = kc(el, "line");+ let j = 0; // petals are laid in the order they stack: back row firstconst petal = (a: number, len: number, wid: number, col: string, sh: string, k: number) => {const tip: P = [cx + Math.cos(a) * len, cy + Math.sin(a) * len], nx = -Math.sin(a), ny = Math.cos(a);const shape = smooth([[cx + nx * 3, cy + ny * 3], [cx + Math.cos(a) * len * 0.45 + nx * wid, cy + Math.sin(a) * len * 0.45 + ny * wid], tip, [cx + Math.cos(a) * len * 0.45 - nx * wid, cy + Math.sin(a) * len * 0.45 - ny * wid], [cx - nx * 3, cy - ny * 3]], true, 6);- fillShape(g, shape, sh);- clipped(g, shape, () => fillShape(g, shape.map(([x, y]) => [x - 5 - nx * 4 * k, y - 6 - ny * 4 * k] as P), col));- ink(g, shape, INK, { w: 3.2, closed: true, light: LIGHT, shadow: 0.8, seed: seed + Math.round(a * 100) });+ const pf = part(fl, j, 21), ps = part(shd, j, 20), pl = part(ln, j, 21); j++;+ const cel = () => { fillShape(g, shape, sh); clipped(g, shape, () => fillShape(g, shape.map(([x, y]) => [x - 5 - nx * 4 * k, y - 6 - ny * 4 * k] as P), col)); };+ if (ps >= 1) cel(); else { lay(g, pf, [shape], () => fillShape(g, shape, col), seed + j * 7, 12, a + 1.57); lay(g, ps, [shape], cel, seed + j * 7 + 3, 10, a); }+ inkP(g, shape, INK, { w: 3.2, closed: true, light: LIGHT, shadow: 0.8, seed: seed + Math.round(a * 100) }, undefined, pl);};g.group("plain", () => {for (let i = 0; i < 8; i++) petal(i * 0.785 + 0.2 + (r() - 0.5) * 0.1, 70 * s, 22 * s, "#ffc3d6", "#e886a6", 1);for (let i = 0; i < 7; i++) petal(i * 0.9 + 0.55 + (r() - 0.5) * 0.1, 54 * s, 18 * s, "#ffe0ea", "#f2a2bd", -1);for (let i = 0; i < 5; i++) petal(i * 1.26 + 0.1, 34 * s, 13 * s, "#fff1f5", "#f6bfd0", 1);- fillShape(g, blob(cx, cy, 15 * s, 13 * s, seed + 9, 0.15, 12), "#ffcc2e");- ink(g, blob(cx, cy, 15 * s, 13 * s, seed + 9, 0.15, 12), INK, { w: 2.6, closed: true, seed: seed + 10 });- for (let i = 0; i < 14; i++) { const a = i * 0.45, d = 6 + (i % 3) * 3; fillShape(g, blob(cx + Math.cos(a) * d * s, cy + Math.sin(a) * d * s, 2.2, 2.2, seed + 30 + i, 0.1, 8), "#c98a00"); }+ const eye = blob(cx, cy, 15 * s, 13 * s, seed + 9, 0.15, 12);+ lay(g, part(fl, 20, 21), [eye], () => fillShape(g, blob(cx, cy, 15 * s, 13 * s, seed + 9, 0.15, 12), "#ffcc2e"), seed + 90, 9, 0.3);+ inkP(g, blob(cx, cy, 15 * s, 13 * s, seed + 9, 0.15, 12), INK, { w: 2.6, closed: true, seed: seed + 10 }, undefined, part(ln, 20, 21));+ for (let i = 0; i < 14; i++) { const a = i * 0.45, d = 6 + (i % 3) * 3; if (part(dt, i, 14) >= 1) fillShape(g, blob(cx + Math.cos(a) * d * s, cy + Math.sin(a) * d * s, 2.2, 2.2, seed + 30 + i, 0.1, 8), "#c98a00"); }});};-const ripples = (g: Gfx, cx: number, cy: number, seed: number) => {+const ripples = (g: Gfx, cx: number, cy: number, seed: number, kc: KoiClock = ALL) => {// surface rings, broken where the light catches them: the one place the water shows its skin- const r = rng(seed);+ const r = rng(seed), dt = kc("ripples", "detail");g.group("plain", () => {[58, 104, 156].forEach((rad, k) => {let a = r() * 6;- for (let s = 0; s < 5; s++) { const span = 0.55 + r() * 0.6, pts: P[] = []; for (let i = 0; i <= 12; i++) { const t = a + (i / 12) * span; pts.push([cx + Math.cos(t) * rad * 1.35, cy + Math.sin(t) * rad * 0.62]); } ink(g, pts, "#d9fbf6", { w: 4.4 - k * 1.1, shadow: 0, taper: [0.3, 0.3], seed: seed + k * 10 + s }, 0.85 - k * 0.18); a += span + 0.35 + r() * 0.5; }+ for (let s = 0; s < 5; s++) { const span = 0.55 + r() * 0.6, pts: P[] = []; for (let i = 0; i <= 12; i++) { const t = a + (i / 12) * span; pts.push([cx + Math.cos(t) * rad * 1.35, cy + Math.sin(t) * rad * 0.62]); } inkP(g, pts, "#d9fbf6", { w: 4.4 - k * 1.1, shadow: 0, taper: [0.3, 0.3], seed: seed + k * 10 + s }, 0.85 - k * 0.18, part(dt, k * 5 + s, 15)); a += span + 0.35 + r() * 0.5; }});});};-export const drawKoi = (ctx: Ctx, _frame: number, env: Env) => {- const g = new Gfx(ctx, env, 0, PENCIL);- ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);- water(g);+// the lay-in, in non-photo blue: the gesture of the spine first, then the masses, then the parts+const BLUE = "#6b98cc";+const pencilLayIn = (g: Gfx, k: KoiClock, b: Body, fins: { shape: P[] }[], cau: { shape: P[] }, pads: P[][], lily: [number, number, number]) => {+ const fish = k("fish", "pencil"), pk = k("pads", "pencil"), lk = k("lily", "pencil");+ const n = b.outline.length / 2, left = b.outline.slice(0, n), right = b.outline.slice(n).reverse();+ const eyes = [-1, 1].map((sd) => { const e = b.at(0.085, sd * 0.8); return Array.from({ length: 9 }, (_, i) => [e[0] + Math.cos(i * 0.8) * 14, e[1] + Math.sin(i * 0.8) * 12] as P); });+ const fishStrokes: P[][] = [b.spine, left, right, cau.shape, ...fins.map((f) => f.shape), ...eyes];+ const padStrokes: P[][] = pads.map((p) => p.slice(1));+ const [lx, ly, ls] = lily, lilyStrokes: P[][] = [Array.from({ length: 15 }, (_, i) => [lx + Math.cos(i * 0.47) * 76 * ls, ly + Math.sin(i * 0.47) * 72 * ls] as P), ...Array.from({ length: 8 }, (_, i) => { const a = i * 0.785 + 0.2; return [[lx, ly], [lx + Math.cos(a) * 70 * ls, ly + Math.sin(a) * 70 * ls]] as P[]; })];+ g.group("ink", () => {+ const run = (list: P[][], p: number, seed: number) => list.forEach((s, i) => { const q = part(p, i, list.length); if (q > 0) g.pen(resample(s, Math.max(3, Math.min(40, Math.round(s.length / 5)))), { w: 1.25, color: BLUE, seed: seed + i, wobble: 1.8, opacity: 0.9, progress: q }); });+ run(fishStrokes, fish, 6100); run(padStrokes, pk, 6200); run(lilyStrokes, lk, 6300);+ });+};+export const drawKoi = (ctx: Ctx, _frame: number, env: Env, clock?: KoiClock) => {+ const g = new Gfx(ctx, env, 0, PENCIL), k = clock ?? ALL;+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);const b = koiBody();// pectorals on the outside of the curve spread wide; the inside one is tucked and foreshortenedconst pecR = fin(b.at(0.17, 0.9), b.at(0.285, 0.9), b.at(0.33, 2.85), 70, 16, 71, 9);@@ -119,98 +161,114 @@ export const drawKoi = (ctx: Ctx, _frame: number, env: Env) => {const pelL = fin(b.at(0.54, -0.9), b.at(0.6, -0.9), b.at(0.67, -1.8), 26, -5, 74, 6);const cau = tail(b);const fins = [pecR, pecL, pelR, pelL];+ if (clock) { // the process only: a bare sheet of marker paper, and the lay-in on it+ ctx.fillStyle = "#fbf9f3"; ctx.fillRect(0, 0, 1080, 1080);+ pencilLayIn(g, k, b, fins, cau, [padShape(905, 205, 168, 2.3, 3100), padShape(890, 905, 120, 3.6, 3300), padShape(120, 640, 88, 0.2, 3400)], [880, 195, 1.15]);+ }+ water(g, k);// the fish's shadow on the pond floor, flat and hard, down-right away from the light- g.group("plain", () => [b.outline, cau.shape, ...fins.map((f) => f.shape)].forEach((s) => fillShape(g, s.map(([x, y]) => [x + 30, y + 40] as P), "#083b45", 0.5)));+ const floor = [b.outline, cau.shape, ...fins.map((f) => f.shape)].map((s) => s.map(([x, y]) => [x + 30, y + 40] as P));+ g.group("plain", () => lay(g, k("floor", "shade"), floor, () => floor.forEach((s) => fillShape(g, s, "#083b45", 0.5)), 5001, 34, 0.9));// fins under the body: translucent, cel-shaded, a black base on the pectoralsg.group("plain", () => {fins.forEach((f, i) => {- fillShape(g, f.shape, FIN_S, 0.88);- clipped(g, f.shape, () => {- fillShape(g, f.shape.map(([x, y]) => [x - 9, y - 11] as P), FIN, 0.92);- if (i < 2) fillShape(g, blob(...(i === 0 ? b.at(0.25, 1.35) : b.at(0.245, -1.25)), i === 0 ? 46 : 32, i === 0 ? 30 : 22, 80 + i, 0.2, 12, i === 0 ? 1.0 : -0.8), SUMI, 0.95); // motoguro: black at the base of the pectorals- });- f.rays.forEach((ray, k) => ink(g, ray, mix(INK, FIN_S, 0.35), { w: 1.7, shadow: 0, taper: [0.05, 0.5], seed: 900 + i * 40 + k }, 0.75));- ink(g, f.shape, INK, { w: 4.2, closed: true, light: LIGHT, shadow: 0.85, seed: 700 + i * 7 });+ const el = `fin${i}`, fl = k(el, "flat"), sh = k(el, "shade"), dt = k(el, "detail"), ln = k(el, "line");+ const moto = () => { if (i < 2) fillShape(g, blob(...(i === 0 ? b.at(0.25, 1.35) : b.at(0.245, -1.25)), i === 0 ? 46 : 32, i === 0 ? 30 : 22, 80 + i, 0.2, 12, i === 0 ? 1.0 : -0.8), SUMI, 0.95); }; // motoguro: black at the base of the pectorals+ const cel = () => { fillShape(g, f.shape, FIN_S, 0.88); clipped(g, f.shape, () => { fillShape(g, f.shape.map(([x, y]) => [x - 9, y - 11] as P), FIN, 0.92); moto(); }); };+ if (sh >= 1) cel();+ else { lay(g, part(fl, 0, 2), [f.shape], () => fillShape(g, f.shape, FIN, 0.92), 5100 + i, 18, -0.9); lay(g, part(fl, 1, 2), [f.shape], () => clipped(g, f.shape, moto), 5110 + i, 14, -0.9); lay(g, sh, [f.shape], cel, 5120 + i, 13, 0.7); }+ f.rays.forEach((ray, kk) => inkP(g, ray, mix(INK, FIN_S, 0.35), { w: 1.7, shadow: 0, taper: [0.05, 0.5], seed: 900 + i * 40 + kk }, 0.75, part(dt, kk, f.rays.length)));+ inkP(g, f.shape, INK, { w: 4.2, closed: true, light: LIGHT, shadow: 0.85, seed: 700 + i * 7 }, undefined, ln);});});// the body: shade cel underneath, the lit white pushed toward the light, then the markings- const bs = b.outline;+ const bs = b.outline, bsL = bs.map(([x, y]) => [x + LIGHT[0] * 22, y + LIGHT[1] * 22] as P);+ const bfl = k("body", "flat"), bsh = k("body", "shade");g.group("plain", () => {- fillShape(g, bs, WHITE_S);+ if (bsh >= 1) fillShape(g, bs, WHITE_S);+ else { lay(g, bfl, [bs], () => fillShape(g, bs, WHITE), 5201, 34, -0.35); lay(g, bsh, [bs], () => { fillShape(g, bs, WHITE_S); clipped(g, bs, () => fillShape(g, bsL, WHITE)); }, 5202, 24, 0.62); }clipped(g, bs, () => {- fillShape(g, bs.map(([x, y]) => [x + LIGHT[0] * 22, y + LIGHT[1] * 22] as P), WHITE);+ if (bsh >= 1) fillShape(g, bsL, WHITE);// red hi: head crown, a saddle across the back, a patch toward the tail. Crisp back edges.+ const hf = k("hi", "flat"), hs = k("hi", "shade");const patches: [number, number, number, number, number][] = [[0.105, -0.05, 0.075, 0.95, 11], [0.36, -0.25, 0.1, 1.2, 12], [0.47, 0.35, 0.07, 0.9, 13], [0.66, -0.1, 0.085, 1.15, 14], [0.82, 0.3, 0.05, 0.9, 15]];- patches.forEach(([t, s, dt, ds, seed]) => {+ patches.forEach(([t, s, dt, ds, seed], pi) => {const r = rng(seed * 17), pts: P[] = [];- for (let i = 0; i < 16; i++) { const a = (i / 16) * Math.PI * 2, k = 0.8 + r() * 0.35; pts.push(b.at(t + Math.cos(a) * dt * k, s + Math.sin(a) * ds * k)); }- const sh = smooth(pts, true, 6);- fillShape(g, sh, HI_S);- clipped(g, sh, () => fillShape(g, bs.map(([x, y]) => [x + LIGHT[0] * 22, y + LIGHT[1] * 22] as P), HI));+ for (let i = 0; i < 16; i++) { const a = (i / 16) * Math.PI * 2, kk = 0.8 + r() * 0.35; pts.push(b.at(t + Math.cos(a) * dt * kk, s + Math.sin(a) * ds * kk)); }+ const sh = smooth(pts, true, 6), ps = part(hs, pi, 5);+ const cel = () => { fillShape(g, sh, HI_S); clipped(g, sh, () => fillShape(g, bsL, HI)); };+ if (ps >= 1) cel(); else { lay(g, part(hf, pi, 5), [sh], () => fillShape(g, sh, HI), 5300 + pi, 24, -0.35); lay(g, ps, [sh], cel, 5310 + pi, 18, 0.62); }});// sumi: a few black spots, never on the head- [[0.3, 0.55, 0.028, 0.32, 31], [0.55, -0.55, 0.03, 0.3, 32], [0.61, 0.42, 0.018, 0.22, 33], [0.78, -0.2, 0.026, 0.4, 34], [0.43, 0.02, 0.016, 0.18, 35]].forEach(([t, s, dt, ds, seed]) => {- const r = rng(seed), pts: P[] = []; for (let i = 0; i < 12; i++) { const a = (i / 12) * Math.PI * 2, k = 0.8 + r() * 0.4; pts.push(b.at(t + Math.cos(a) * dt * k, s + Math.sin(a) * ds * k)); }- fillShape(g, smooth(pts, true, 5), SUMI);+ const sf = k("sumi", "flat");+ ([[0.3, 0.55, 0.028, 0.32, 31], [0.55, -0.55, 0.03, 0.3, 32], [0.61, 0.42, 0.018, 0.22, 33], [0.78, -0.2, 0.026, 0.4, 34], [0.43, 0.02, 0.016, 0.18, 35]] as number[][]).forEach(([t, s, dt, ds, seed], si) => {+ const r = rng(seed), pts: P[] = []; for (let i = 0; i < 12; i++) { const a = (i / 12) * Math.PI * 2, kk = 0.8 + r() * 0.4; pts.push(b.at(t + Math.cos(a) * dt * kk, s + Math.sin(a) * ds * kk)); }+ const sp = smooth(pts, true, 5); lay(g, part(sf, si, 5), [sp], () => fillShape(g, sp, SUMI), 5400 + si, 12, -0.3);});// scales: a loose lattice of arcs, strongest on the lit back, gone into the shade- const r = rng(55);+ const r = rng(55), sc = k("scales", "detail");for (let t = 0.2; t < 0.93; t += 0.034) for (let s = -0.75; s <= 0.8; s += 0.3) {const tt = t + (Math.round(s / 0.3) % 2 ? 0.017 : 0), ss = s + (r() - 0.5) * 0.06, p = b.at(tt, ss), q = b.at(tt + 0.014, ss - 0.13), u = b.at(tt + 0.014, ss + 0.13), m = b.at(tt + 0.022, ss);const lit = ss < 0.35 && !(r() < 0.3);- if (lit) ink(g, smooth([q, m, u], false, 5), "#2a1f3a", { w: 1.5, shadow: 0, taper: [0.3, 0.3], seed: 2000 + Math.round(t * 1000 + s * 50) }, 0.28);+ if (lit) inkP(g, smooth([q, m, u], false, 5), "#2a1f3a", { w: 1.5, shadow: 0, taper: [0.3, 0.3], seed: 2000 + Math.round(t * 1000 + s * 50) }, 0.28, stagger(sc, ((tt - 0.2) / 0.75) * 0.85, 0.15));void p;}// the wet highlight along the back, and a glint on the head- [[0.2, 0.3, -0.6, 7], [0.335, 0.42, -0.64, 6], [0.46, 0.5, -0.66, 4.5], [0.58, 0.6, -0.66, 3]].forEach(([t0, t1, sv, w], k) => { const pts: P[] = []; for (let i = 0; i <= 8; i++) pts.push(b.at(t0 + ((t1 - t0) * i) / 8, sv)); ink(g, pts, "#ffffff", { w, shadow: 0, taper: [0.35, 0.45], seed: 1800 + k }, 0.9); });- fillShape(g, blob(...b.at(0.075, -0.35), 22, 9, 91, 0.1, 10, -0.7), "#ffffff", 0.85);+ const hl = k("gloss", "detail");+ [[0.2, 0.3, -0.6, 7], [0.335, 0.42, -0.64, 6], [0.46, 0.5, -0.66, 4.5], [0.58, 0.6, -0.66, 3]].forEach(([t0, t1, sv, w], kk) => { const pts: P[] = []; for (let i = 0; i <= 8; i++) pts.push(b.at(t0 + ((t1 - t0) * i) / 8, sv)); inkP(g, pts, "#ffffff", { w, shadow: 0, taper: [0.35, 0.45], seed: 1800 + kk }, 0.9, part(hl, kk, 5)); });+ const glint = blob(...b.at(0.075, -0.35), 22, 9, 91, 0.1, 10, -0.7);+ lay(g, part(hl, 4, 5), [glint], () => fillShape(g, blob(...b.at(0.075, -0.35), 22, 9, 91, 0.1, 10, -0.7), "#ffffff", 0.85), 5501, 8, 0);});// dorsal fin down the spine: a narrow flutter of translucent fin with ray ticksconst df: P[] = [], dfr: P[] = [];for (let i = 0; i <= 16; i++) { const f = i / 16, t = 0.36 + f * 0.3, h = Math.pow(Math.sin(Math.min(1, f * 2.6) * Math.PI / 2), 1.2) * (1 - f * 0.78); df.push(b.at(t, 0.0)); dfr.push(b.at(t + 0.04 * h, h * 0.72 + Math.sin(i * 1.4) * 0.02 * h)); }- const dorsal = [...smooth(df, false, 3), ...smooth(dfr, false, 3).reverse()];- fillShape(g, dorsal.map(([x, y]) => [x + 6, y + 8] as P), "#2a1f3a", 0.18); // the fin's own shadow on the back- fillShape(g, dorsal, FIN_S, 0.95);- clipped(g, dorsal, () => fillShape(g, dorsal.map(([x, y]) => [x - 6, y - 7] as P), FIN, 0.95));- for (let i = 1; i < 16; i += 2) ink(g, [df[i], lerpP(df[i], dfr[i], 0.5), dfr[i]], mix(INK, FIN_S, 0.4), { w: 1.4, shadow: 0, taper: [0.1, 0.5], seed: 1300 + i }, 0.7);- ink(g, dorsal, INK, { w: 3.4, closed: true, light: LIGHT, shadow: 0.8, seed: 1400 });+ const dorsal = [...smooth(df, false, 3), ...smooth(dfr, false, 3).reverse()], dsh = dorsal.map(([x, y]) => [x + 6, y + 8] as P);+ const dfl = k("dorsal", "flat"), dsd = k("dorsal", "shade"), ddt = k("dorsal", "detail"), dln = k("dorsal", "line");+ lay(g, dsd, [dsh], () => fillShape(g, dsh, "#2a1f3a", 0.18), 5601, 10, 0.4); // the fin's own shadow on the back+ const dcel = () => { fillShape(g, dorsal, FIN_S, 0.95); clipped(g, dorsal, () => fillShape(g, dorsal.map(([x, y]) => [x - 6, y - 7] as P), FIN, 0.95)); };+ if (dsd >= 1) dcel(); else { lay(g, dfl, [dorsal], () => fillShape(g, dorsal, FIN, 0.95), 5602, 10, 0.3); lay(g, dsd, [dorsal], dcel, 5603, 9, -0.6); }+ for (let i = 1; i < 16; i += 2) inkP(g, [df[i], lerpP(df[i], dfr[i], 0.5), dfr[i]], mix(INK, FIN_S, 0.4), { w: 1.4, shadow: 0, taper: [0.1, 0.5], seed: 1300 + i }, 0.7, part(ddt, (i - 1) / 2, 8));+ inkP(g, dorsal, INK, { w: 3.4, closed: true, light: LIGHT, shadow: 0.8, seed: 1400 }, undefined, dln);// head: gill covers, eyes set into the sides, nostrils, barbels+ const hln = k("head", "line"), efl = k("eyes", "flat"), edt = k("eyes", "detail");[-1, 1].forEach((sd) => {+ const hi = sd < 0 ? 0 : 1;const gill: P[] = []; for (let i = 0; i <= 6; i++) gill.push(b.at(0.155 - Math.sin((i / 6) * Math.PI) * 0.03, sd * (0.98 - i * 0.1)));- ink(g, gill, INK, { w: 3.4, shadow: 0, taper: [0.08, 0.7], seed: 1500 + sd });- const e = b.at(0.085, sd * 0.8), ew = sd > 0 ? 12 : 10;- fillShape(g, blob(e[0], e[1], ew + 3, ew, 1600 + sd, 0.05, 12), "#e6cf8c");- fillShape(g, blob(e[0] + 1, e[1] + 1, ew * 0.78, ew * 0.74, 1610 + sd, 0.05, 12), "#1a1427");- fillShape(g, blob(e[0] - 3, e[1] - 4, 3.2, 2.6, 1620 + sd, 0.05, 8), "#ffffff");- ink(g, blob(e[0], e[1], ew + 3, ew, 1600 + sd, 0.05, 12), INK, { w: 3, closed: true, light: LIGHT, shadow: 0.7, seed: 1630 + sd });- fillShape(g, blob(...b.at(0.03, sd * 0.36), 4, 3, 1640 + sd, 0.1, 8), "#3a1e22");+ inkP(g, gill, INK, { w: 3.4, shadow: 0, taper: [0.08, 0.7], seed: 1500 + sd }, undefined, part(hln, hi * 4, 8));+ const e = b.at(0.085, sd * 0.8), ew = sd > 0 ? 12 : 10, iris = blob(e[0], e[1], ew + 3, ew, 1600 + sd, 0.05, 12);+ lay(g, part(efl, hi * 2, 4), [iris], () => fillShape(g, blob(e[0], e[1], ew + 3, ew, 1600 + sd, 0.05, 12), "#e6cf8c"), 5700 + hi, 7, 0.3);+ lay(g, part(efl, hi * 2 + 1, 4), [iris], () => fillShape(g, blob(e[0] + 1, e[1] + 1, ew * 0.78, ew * 0.74, 1610 + sd, 0.05, 12), "#1a1427"), 5710 + hi, 6, -0.3);+ if (part(edt, hi * 2, 4) >= 1) fillShape(g, blob(e[0] - 3, e[1] - 4, 3.2, 2.6, 1620 + sd, 0.05, 8), "#ffffff");+ inkP(g, blob(e[0], e[1], ew + 3, ew, 1600 + sd, 0.05, 12), INK, { w: 3, closed: true, light: LIGHT, shadow: 0.7, seed: 1630 + sd }, undefined, part(hln, hi * 4 + 1, 8));+ if (part(edt, hi * 2 + 1, 4) >= 1) fillShape(g, blob(...b.at(0.03, sd * 0.36), 4, 3, 1640 + sd, 0.1, 8), "#3a1e22");const m = b.at(0.006, sd * 0.5), m2 = b.at(-0.02, sd * 1.2), m3 = b.at(-0.035, sd * 1.9);- ink(g, smooth([m, lerpP(m2, b.at(-0.01, sd * 1.1), 0.5), m3], false, 8), INK, { w: 3, shadow: 0, taper: [0.02, 0.9], seed: 1650 + sd });+ inkP(g, smooth([m, lerpP(m2, b.at(-0.01, sd * 1.1), 0.5), m3], false, 8), INK, { w: 3, shadow: 0, taper: [0.02, 0.9], seed: 1650 + sd }, undefined, part(hln, hi * 4 + 2, 8));const k0 = b.at(0.02, sd * 0.78), k1 = b.at(0.0, sd * 1.25);- ink(g, smooth([k0, lerpP(k0, k1, 0.5), k1], false, 6), INK, { w: 2.4, shadow: 0, taper: [0.02, 0.9], seed: 1660 + sd });+ inkP(g, smooth([k0, lerpP(k0, k1, 0.5), k1], false, 6), INK, { w: 2.4, shadow: 0, taper: [0.02, 0.9], seed: 1660 + sd }, undefined, part(hln, hi * 4 + 3, 8));});});// the tail goes on over the body's end, so fin and peduncle are one continuous piece+ const tf = k("tail", "flat"), tsd = k("tail", "shade"), tdt = k("tail", "detail"), tln = k("tail", "line"), bln = k("body", "line");g.group("plain", () => {- fillShape(g, cau.shape, FIN_S, 0.9);- clipped(g, cau.shape, () => fillShape(g, cau.shape.map(([x, y]) => [x - 10, y - 12] as P), FIN, 0.93));- cau.rays.forEach((ray, k) => ink(g, ray, mix(INK, FIN_S, 0.35), { w: 1.7, shadow: 0, taper: [0.05, 0.5], seed: 1100 + k }, 0.72));+ const tcel = () => { fillShape(g, cau.shape, FIN_S, 0.9); clipped(g, cau.shape, () => fillShape(g, cau.shape.map(([x, y]) => [x - 10, y - 12] as P), FIN, 0.93)); };+ if (tsd >= 1) tcel(); else { lay(g, tf, [cau.shape], () => fillShape(g, cau.shape, FIN, 0.93), 5801, 22, 0.35); lay(g, tsd, [cau.shape], tcel, 5802, 16, -0.8); }+ cau.rays.forEach((ray, kk) => inkP(g, ray, mix(INK, FIN_S, 0.35), { w: 1.7, shadow: 0, taper: [0.05, 0.5], seed: 1100 + kk }, 0.72, part(tdt, kk, cau.rays.length)));const n = b.outline.length / 2, L = b.outline.slice(0, n), R = b.outline.slice(n).reverse(), cut = Math.round(n * 0.965);const open = [...L.slice(0, cut).reverse(), ...R.slice(0, cut)];- ink(g, open, INK, { w: 6.4, light: LIGHT, shadow: 0.95, seed: 1700, side: -1, taper: [0.06, 0.06], min: 0.3 });+ inkP(g, open, INK, { w: 6.4, light: LIGHT, shadow: 0.95, seed: 1700, side: -1, taper: [0.06, 0.06], min: 0.3 }, undefined, bln);const tailEdge = cau.shape.slice(3, cau.shape.length - 3);- ink(g, tailEdge, INK, { w: 4.4, light: LIGHT, shadow: 0.85, seed: 1710, side: -1, taper: [0.04, 0.04], min: 0.3 });+ inkP(g, tailEdge, INK, { w: 4.4, light: LIGHT, shadow: 0.85, seed: 1710, side: -1, taper: [0.04, 0.04], min: 0.3 }, undefined, tln);});- ripples(g, 300, 196, 2100);- lilyPad(g, 905, 205, 168, 2.3, 3100);- waterLily(g, 880, 195, 1.15, 3200);- lilyPad(g, 890, 905, 120, 3.6, 3300);- lilyPad(g, 120, 640, 88, 0.2, 3400);+ ripples(g, 300, 196, 2100, k);+ lilyPad(g, 905, 205, 168, 2.3, 3100, k, "pad0");+ waterLily(g, 880, 195, 1.15, 3200, k);+ lilyPad(g, 890, 905, 120, 3.6, 3300, k, "pad1");+ lilyPad(g, 120, 640, 88, 0.2, 3400, k, "pad2");g.paper("paper", 0.05);};diff --git a/engine/src/canvas-core/koiDraw.ts b/engine/src/canvas-core/koiDraw.tsnew file mode 100644index 0000000..d0ff2d8--- /dev/null+++ b/engine/src/canvas-core/koiDraw.ts@@ -0,0 +1,43 @@+import type { Film } from "./film";+import { drawKoi } from "./koi";+import { cueClock, sequence } from "./koiDrawKit";++// KOI · the marker comic, drawn. The koi plate made the way a comic colourist makes it with+// alcohol markers and a brush pen on bleedproof marker paper:+// 1. a light lay-in in non-photo blue: the spine's gesture first, then the masses, then the parts;+// 2. flat cel fills, lightest first, each laid in parallel chisel-marker passes, back and forth,+// starting and stopping past the pencil line (the contour will hide the overshoot); the pond+// goes in LAST around the finished fish, broad and fast, the way you fill a background;+// 3. the hard shadow shapes, a darker marker over each flat on the side away from the light,+// and the cast shadows on the pond floor;+// 4. the details: scale arcs, fin rays, water streaks, surface rings, gel-pen whites;+// 5. the heavy contour LAST, one confident brush-pen stroke per edge, fat away from the light.+// The marker is opaque here (the pencil vanishes under it), so each element is drawn in its own+// stacking order every frame and only its extent grows: a fin laid before the body still sits+// under it. From the hold on, the frame IS drawKoi with no clock: the plate, pixel for pixel.++const W = 1080, H = 1080, HOLD = 30, N = 540;+const F = (el: string, pass: string, n: number): [string, string, number] => [el, pass, n];+const plan = sequence(4, [+ F("fish", "pencil", 48), F("pads", "pencil", 14), F("lily", "pencil", 10), 5,+ F("body", "flat", 16), F("hi", "flat", 22), F("sumi", "flat", 8), F("eyes", "flat", 6),+ F("fin0", "flat", 7), F("fin1", "flat", 6), F("fin2", "flat", 5), F("fin3", "flat", 5), F("dorsal", "flat", 5), F("tail", "flat", 9),+ F("pad0", "flat", 9), F("pad1", "flat", 7), F("pad2", "flat", 6), F("lily", "flat", 14), F("water", "flat", 36), 3,+ F("floor", "shade", 10), F("fin0", "shade", 4), F("fin1", "shade", 4), F("fin2", "shade", 4), F("fin3", "shade", 4), F("body", "shade", 10), F("hi", "shade", 10),+ F("dorsal", "shade", 4), F("tail", "shade", 6), F("pad0", "shade", 5), F("pad1", "shade", 4), F("pad2", "shade", 4), F("lily", "shade", 9), 4,+ F("scales", "detail", 14), F("fin0", "detail", 4), F("fin1", "detail", 4), F("fin2", "detail", 4), F("fin3", "detail", 4), F("dorsal", "detail", 4), F("tail", "detail", 8),+ F("water", "detail", 6), F("ripples", "detail", 8), F("gloss", "detail", 6), F("eyes", "detail", 3), F("lily", "detail", 3),+ F("pad0", "detail", 3), F("pad1", "detail", 3), F("pad2", "detail", 2),+ F("body", "line", 22), F("fin0", "line", 8), F("fin1", "line", 7), F("fin2", "line", 5), F("fin3", "line", 5), F("tail", "line", 9), F("dorsal", "line", 6),+ F("head", "line", 12), F("pad0", "line", 9), F("pad1", "line", 7), F("pad2", "line", 6), F("lily", "line", 11),+]);+// the grid check: the drawing must finish exactly where the hold begins+if (plan.end !== N - HOLD) throw new Error(`koiDraw: process ends at ${plan.end}, the hold starts at ${N - HOLD}`);++export const STYLE = { id: "koiDraw", name: "Marker comic, drawn", family: "marker comic", medium: "alcohol markers and a brush pen over non-photo-blue pencil on bleedproof marker paper", nearest: "koi", hero: "a Sanke koi turning under lily pads" };++export const koiDraw: Film = {+ meta: { title: "Koi · marker comic, drawn", W, H, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "draw", start: 0, end: N, draw: (ctx, f, env) => (f >= N - HOLD ? drawKoi(ctx, 0, env) : drawKoi(ctx, 0, env, cueClock(plan.cues, f))) }],+};diff --git a/engine/src/canvas-core/koiDrawKit.ts b/engine/src/canvas-core/koiDrawKit.tsnew file mode 100644index 0000000..859751b--- /dev/null+++ b/engine/src/canvas-core/koiDrawKit.ts@@ -0,0 +1,95 @@+// KOI DRAW KIT. Process primitives for plates that are seen being MADE: a marker laying a flat in+// parallel chisel strokes, a line growing along its centreline, and a cue table that turns a frame+// into per-(element, pass) progress. Pure geometry; randomness only from rng(seed).+import { rng, type Ctx, type P } from "./core";+import { clamp } from "./gallery";++// k-th of n sequential sub-steps inside a pass whose progress is p. Exactly 1 once p is 1.+export const part = (p: number, k: number, n: number) => (p >= 1 ? 1 : clamp(p * n - k));+// an item that starts at `start` (0..1 of its pass) and takes `dur` of it+export const stagger = (p: number, start: number, dur: number) => (p >= 1 ? 1 : clamp((p - start) / dur));++// the first q of a polyline, by arc length. q >= 1 returns the very same array.+export const cut = (s: P[], q: number): P[] => {+ if (q >= 1) return s;+ const cum = [0]; for (let i = 1; i < s.length; i++) cum.push(cum[i - 1] + Math.hypot(s[i][0] - s[i - 1][0], s[i][1] - s[i - 1][1]));+ const want = cum[cum.length - 1] * Math.max(0, q), out: P[] = [s[0]];+ for (let i = 1; i < s.length; i++) {+ if (cum[i] <= want) { out.push(s[i]); continue; }+ const f = (want - cum[i - 1]) / (cum[i] - cum[i - 1] || 1); out.push([s[i - 1][0] + (s[i][0] - s[i - 1][0]) * f, s[i - 1][1] + (s[i][1] - s[i - 1][1]) * f]); break;+ }+ return out.length > 1 ? out : [s[0], s[0]];+};++// ---------------------------------------------------------------- a marker laying a flat+// A chisel marker fills a shape in parallel passes, back and forth, each one starting just outside+// one edge and running out just past the other (the contour, inked last, hides the overshoot).+export type Streak = { v0: number; v1: number; u0: number; u1: number; dir: 1 | -1 };+export type Streaks = { c: number; s: number; w: number; list: Streak[]; len: number[]; total: number };+// `reach` caps a pass at what a wrist covers: a wide area is filled as blocks of short passes,+// block after block, and the leading edge is the ragged line of stroke ends, never a straight wipe.+export const streaks = (shapes: P[][], width: number, angle: number, seed: number, reach = 1e9): Streaks => {+ const c = Math.cos(angle), s = Math.sin(angle), r = rng(seed), gap = width * 0.74, rows: Streak[] = [];+ const uv = shapes.map((sh) => sh.map(([x, y]) => [x * c + y * s, -x * s + y * c] as P));+ let vmin = 1e9, vmax = -1e9; uv.forEach((sh) => sh.forEach(([, v]) => { vmin = Math.min(vmin, v); vmax = Math.max(vmax, v); }));+ let k = 0;+ for (let v = vmin + gap * 0.45; v < vmax + gap * 0.5; v += gap) {+ let lo = 1e9, hi = -1e9;+ const probe = (vv: number) => uv.forEach((sh) => { for (let i = 0; i < sh.length; i++) { const a = sh[i], b = sh[(i + 1) % sh.length]; if ((a[1] - vv) * (b[1] - vv) > 0 || a[1] === b[1]) continue; const u = a[0] + ((b[0] - a[0]) * (vv - a[1])) / (b[1] - a[1]); lo = Math.min(lo, u); hi = Math.max(hi, u); } });+ probe(Math.min(v, vmax - 0.5)); probe(Math.max(vmin + 0.5, v - gap * 0.45)); probe(Math.min(vmax - 0.5, v + gap * 0.45));+ if (lo > hi) continue;+ const tilt = (r() - 0.5) * gap * 0.22, over = width * 0.35;+ rows.push({ v0: v - tilt, v1: v + tilt, u0: lo - over * (0.6 + r() * 0.6), u1: hi + over * (0.6 + r() * 0.6), dir: k % 2 ? -1 : 1 }); k++;+ }+ let list = rows;+ if (reach < 1e9) {+ let u0 = 1e9, u1 = -1e9; rows.forEach((t) => { u0 = Math.min(u0, t.u0); u1 = Math.max(u1, t.u1); });+ const nb = Math.max(1, Math.ceil((u1 - u0) / reach)), bw = (u1 - u0) / nb, cuts = rows.map(() => Array.from({ length: nb + 1 }, (_, b) => (b === 0 ? -1e9 : b === nb ? 1e9 : u0 + b * bw + (r() - 0.5) * bw * 0.35)));+ list = [];+ for (let b = 0; b < nb; b++) rows.forEach((t, i) => { const a = Math.max(t.u0, cuts[i][b] - width * 0.3), e = Math.min(t.u1, cuts[i][b + 1] + width * 0.3); if (e - a > width * 0.3) list.push({ ...t, u0: a, u1: e, dir: (i + b) % 2 ? -1 : 1 }); });+ }+ const len = list.map((t) => (t.u1 - t.u0) + width * 1.6); // a lift and a return between passes+ return { c, s, w: width, list, len, total: len.reduce((a, b) => a + b, 0) };+};+// Clip the current surface to the part of the flat the marker has laid by progress p. Every+// ribbon is wound the same way, so the union is a nonzero fill with no holes where passes overlap.+export const streakClip = (cx: Ctx, st: Streaks, p: number) => {+ const { c, s, w } = st, xy = (u: number, v: number): P => [u * c - v * s, u * s + v * c];+ let t = clamp(p) * st.total; cx.beginPath();+ for (let i = 0; i < st.list.length && t > 0; i++) {+ const k = st.list[i], L = st.len[i], f = clamp(t / (L - w * 1.6)); t -= L;+ const a = k.dir > 0 ? k.u0 : k.u1, b = a + (k.dir > 0 ? 1 : -1) * (k.u1 - k.u0) * f, lo = Math.min(a, b), hi = Math.max(a, b);+ const vAt = (u: number) => k.v0 + ((k.v1 - k.v0) * (u - k.u0)) / (k.u1 - k.u0 || 1), sk = w * 0.28; // the chisel's slanted end+ const n = 6, top: P[] = [], bot: P[] = [];+ for (let j = 0; j <= n; j++) { const u = lo + ((hi - lo) * j) / n, v = vAt(u); top.push(xy(u + sk * 0.5, v - w / 2)); bot.push(xy(u - sk * 0.5, v + w / 2)); }+ const ring = [...top, ...bot.reverse()];+ ring.forEach(([x, y], j) => (j ? cx.lineTo(x, y) : cx.moveTo(x, y))); cx.closePath();+ }+ cx.clip();+};++// where the marker (or brush) is at progress p: for a visible tool cursor+export const streakTip = (st: Streaks, p: number): P => {+ const { c, s, w } = st; let t = clamp(p) * st.total;+ for (let i = 0; i < st.list.length; i++) { const k = st.list[i], L = st.len[i], f = clamp(t / (L - w * 1.6)); if (t <= L || i === st.list.length - 1) { const u = k.dir > 0 ? k.u0 + (k.u1 - k.u0) * f : k.u1 - (k.u1 - k.u0) * f, v = k.v0 + (k.v1 - k.v0) * ((u - k.u0) / (k.u1 - k.u0 || 1)); return [u * c - v * s, u * s + v * c]; } t -= L; }+ return [0, 0];+};++// ---------------------------------------------------------------- a cue table+// [element, pass, start, end] in frames. Progress is 0 before start, exactly 1 from end on, and+// eased like a hand in between (a quick attack, a settle into the last stroke).+export type Cue = [string, string, number, number];+export const cueClock = (cues: Cue[], frame: number) => {+ const map = new Map<string, [number, number]>(); cues.forEach(([e, p, a, b]) => map.set(`${e}|${p}`, [a, b]));+ return (el: string, pass: string): number => {+ const w = map.get(`${el}|${pass}`); if (!w) throw new Error(`cue table has no ${el}|${pass}`); // a missing cue would draw that mark finished at frame 0+ if (frame >= w[1]) return 1; if (frame <= w[0]) return 0;+ const t = (frame - w[0]) / (w[1] - w[0]); return t < 1 ? t * t * (3 - 2 * t) * 0.35 + t * 0.65 : 1;+ };+};+// lay out a sequence of [element, pass, frames] (or a numeric pause) back to back from `from`+export const sequence = (from: number, steps: ([string, string, number] | number)[]): { cues: Cue[]; end: number } => {+ let t = from; const cues: Cue[] = [];+ steps.forEach((s) => { if (typeof s === "number") { t += s; return; } cues.push([s[0], s[1], t, t + s[2]]); t += s[2]; });+ return { cues, end: t };+};diff --git a/engine/src/canvas-core/lesson.ts b/engine/src/canvas-core/lesson.tsnew file mode 100644index 0000000..77a489e--- /dev/null+++ b/engine/src/canvas-core/lesson.ts@@ -0,0 +1,99 @@+// LESSON OUTPUTS from one drawing score: a captioned timelapse film, a step sheet, and a "final"+// film that renders the finished drawing cold (no cache, no schedule) for the identity gate.+// Captions are drawn as pen strokes with drafting.ts: no font is ever loaded, no fillText.+import { Gfx, PENCIL, type Ctx, type Env } from "./core";+import { letter, width } from "./drafting";+import type { Film } from "./film";+import { PHASE_NAME, all, before, only, paperGrain, progressAt, renderArt, schedule, type Score, type Timing, type View } from "./drawingScore";++export type LessonLook = { ink: string; muted: string; accent: string; band: string };+const DEFAULT_LOOK: LessonLook = { ink: "#2f2a2b", muted: "#6d6462", accent: "#3f6fb8", band: "#ece5d6" };++// greedy word wrap against the drafting hand's own advance widths+export const wrap = (text: string, cap: number, maxW: number): string[] => {+ const out: string[] = []; let line = "";+ for (const w of text.toUpperCase().split(/\s+/).filter(Boolean)) { const t = line ? `${line} ${w}` : w; if (width(t, cap) > maxW && line) { out.push(line); line = w; } else line = t; }+ if (line) out.push(line); return out;+};+const pen = (ctx: Ctx, env: Env) => new Gfx(ctx, env, 0, { ...PENCIL, wobble: 0.4, rough: 0.5 });++// write lines on, one after another; `p` is 0..1 over the whole block+const block = (g: Gfx, lines: { t: string; cap: number; col: string; w: number; gap: number; slant?: number }[], x: number, y: number, p: number, seed: number) => {+ const cost = lines.map((l) => l.t.length), tot = cost.reduce((a, b) => a + b, 0) || 1; let acc = 0, yy = y;+ lines.forEach((l, i) => { const a = acc / tot, b = (acc + cost[i]) / tot, q = p >= 1 ? 1 : Math.max(0, Math.min(1, (p - a) / (b - a || 1))); acc += cost[i]; if (q > 0) letter(g, l.t, x, yy, { cap: l.cap, color: l.col, seed: seed + i * 7, w: l.w, progress: q, slant: l.slant ?? 0.12 }); yy += l.cap + l.gap; });+};++// ---------------------------------------------------------------- the timelapse+export type LessonFilmOpts = { W?: number; art?: number; timing?: Partial<Timing>; look?: Partial<LessonLook>; outro?: string };+export const lessonTiming = (o: Partial<Timing> = {}): Timing => ({ intro: 75, captionLead: 20, pause: 25, hold: 75, rate: 38, minStep: 90, maxStep: 330, grid: 15, ...o });+export const lessonFilm = (build: () => Score, o: LessonFilmOpts = {}): Film & { plan: () => ReturnType<typeof schedule>; final: Film } => {+ const W = o.W ?? 1080, art = o.art ?? 1080, bandH = 300, H = art + bandH, look = { ...DEFAULT_LOOK, ...o.look };+ let S0: Score | null = null; const score = () => (S0 ??= build()); // the score is pure data: building it once per page is safe+ const T = lessonTiming(o.timing);+ const planOf = () => schedule(score(), T);+ const P0 = planOf(), total = P0.total;+ const view = (env: Env): View => { const S = score(), k = Math.min(W / S.W, art / S.H) * env.scale, w = Math.round(S.W * k), h = Math.round(S.H * k); return { x: Math.round((W * env.scale - w) / 2), y: Math.round((art * env.scale - h) / 2), w, h }; };+ const band = (ctx: Ctx, env: Env, frame: number, final: boolean) => {+ const S = score(), P = P0, g = pen(ctx, env);+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = look.band; ctx.fillRect(0, art, W, bandH); ctx.restore();+ g.pen([[40, art + 14], [W / 2, art + 12.5], [W - 40, art + 14]], { w: 1.1, color: look.muted, seed: 3, opacity: 0.5, retrace: false, boil: 0 });+ const x = 56, maxW = W - 112;+ let k = -1; for (let i = 0; i < P.steps.length; i++) if (frame >= P.steps[i].start) k = i;+ if (final || frame >= P.steps[P.steps.length - 1].end) { // the close+ block(g, [{ t: S.title.toUpperCase(), cap: 26, col: look.ink, w: 2.3, gap: 22 }, ...wrap(o.outro ?? "Finished. Now draw it again from memory: the second one teaches more than the first.", 17, maxW).map((t) => ({ t, cap: 17, col: look.muted, w: 1.6, gap: 13 }))], x, art + 58, final ? 1 : Math.min(1, (frame - P.steps[P.steps.length - 1].end) / 40), 900);+ return;+ }+ if (k < 0) { // the title card+ const lines = [{ t: S.title.toUpperCase(), cap: 30, col: look.ink, w: 2.6, gap: 22 }, { t: S.medium.toUpperCase(), cap: 16, col: look.accent, w: 1.5, gap: 16 }, ...(S.note ? wrap(S.note, 15, maxW).map((t) => ({ t, cap: 15, col: look.muted, w: 1.4, gap: 11 })) : [])];+ block(g, lines, x, art + 58, Math.min(1, frame / Math.max(1, T.intro - 15)), 700); return;+ }+ const st = S.steps[k], ps = P.steps[k], p = Math.min(1, (frame - ps.start) / Math.max(20, (ps.markEnd - ps.start) * 0.45));+ const head = `STEP ${k + 1} OF ${S.steps.length} - ${PHASE_NAME[st.phase].toUpperCase()}`;+ block(g, [{ t: head, cap: 14, col: look.accent, w: 1.4, gap: 16 }, { t: st.title.toUpperCase(), cap: 25, col: look.ink, w: 2.2, gap: 18 }, ...wrap(st.caption, 17, maxW).map((t) => ({ t, cap: 17, col: look.muted, w: 1.55, gap: 12 }))], x, art + 46, p, 100 + k * 50);+ };+ const draw = (ctx: Ctx, frame: number, env: Env, final: boolean) => {+ const S = score(), v = view(env);+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = S.paper; ctx.fillRect(0, 0, W * env.scale, H * env.scale); ctx.restore();+ renderArt(ctx, env, S, final ? all() : progressAt(P0, frame), v, final ? {} : { cache: "film" });+ band(ctx, env, frame, final);+ paperGrain(ctx, env, 0.05);+ };+ return {+ meta: { title: score().title, W, H, fps: 30, bpm: 120, durationFrames: total, raster: "cpu" },+ assets: { images: {} },+ shots: [{ id: "lesson", start: 0, end: total, draw: (ctx, f, env) => draw(ctx, f, env, false) }],+ plan: () => P0,+ // the cold path: every mark at progress 1, no prefix cache, no schedule+ final: { meta: { title: `${score().title} (final)`, W, H, fps: 30, bpm: 120, durationFrames: 30, raster: "cpu" }, assets: { images: {} }, shots: [{ id: "final", start: 0, end: 30, draw: (ctx: Ctx, _f: number, env: Env) => draw(ctx, total - 1, env, true) }] },+ } as Film & { plan: () => ReturnType<typeof schedule>; final: Film };+};++// ---------------------------------------------------------------- the step sheet+// Every step as a panel: earlier marks pale under a paper veil, the step's new marks strong, and+// under it the step's caption. Read top-left to bottom-right, like the brick booklet.+export const lessonSheet = (build: () => Score, o: { cols?: number; panel?: number; look?: Partial<LessonLook>; crop?: [number, number, number, number] } = {}): Film => {+ const look = { ...DEFAULT_LOOK, ...o.look }, cols = o.cols ?? 4, pw = o.panel ?? 470, capH = 215, gap = 34, head = 190;+ let S0: Score | null = null; const score = () => (S0 ??= build());+ const n = score().steps.length, rows = Math.ceil(n / cols), W = cols * pw + (cols + 1) * gap, H = head + rows * (pw + capH) + (rows + 1) * gap - 10;+ const draw = (ctx: Ctx, _f: number, env: Env) => {+ const S = score(), k = env.scale, g = pen(ctx, env);+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = look.band; ctx.fillRect(0, 0, W * k, H * k); ctx.restore();+ block(g, [{ t: S.title.toUpperCase(), cap: 34, col: look.ink, w: 3, gap: 20 }, { t: `${S.medium.toUpperCase()} - ${S.steps.length} STEPS`, cap: 16, col: look.accent, w: 1.5, gap: 14 }, ...(S.note ? wrap(S.note, 14, W - 2 * gap).map((t) => ({ t, cap: 14, col: look.muted, w: 1.3, gap: 10 })) : [])], gap + 4, 42, 1, 11);+ S.steps.forEach((st, i) => {+ const cx = gap + (i % cols) * (pw + gap), cy = head + gap + Math.floor(i / cols) * (pw + capH + gap);+ // the crop (a design-space box) fills the panel, so a small subject is not lost in margin+ const [c0, c1, c2, c3] = o.crop ?? [0, 0, S.W, S.H], sc = Math.min(pw / (c2 - c0), pw / (c3 - c1)), ox = cx + (pw - (c2 - c0) * sc) / 2 - c0 * sc, oy = cy + (pw - (c3 - c1) * sc) / 2 - c1 * sc;+ const v: View = { x: Math.round(ox * k), y: Math.round(oy * k), w: Math.round(S.W * sc * k), h: Math.round(S.H * sc * k) }, R = [Math.round(cx * k), Math.round(cy * k), Math.round(pw * k), Math.round(pw * k)] as const;+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.beginPath(); ctx.rect(R[0], R[1], R[2], R[3]); ctx.clip(); ctx.fillStyle = S.paper; ctx.fillRect(R[0], R[1], R[2], R[3]);+ renderArt(ctx, env, S, before(S, i), v, { paper: false });+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 0.68; ctx.fillStyle = S.paper; ctx.fillRect(R[0], R[1], R[2], R[3]); ctx.globalAlpha = 1; // earlier marks go pale+ renderArt(ctx, env, S, only(S, i), v, { paper: false });+ ctx.restore();+ ([[[cx, cy], [cx + pw, cy + 0.6]], [[cx + pw, cy], [cx + pw - 0.4, cy + pw]], [[cx + pw, cy + pw], [cx + 0.5, cy + pw - 0.3]], [[cx, cy + pw], [cx, cy]]] as [number, number][][]).forEach((l, j) => g.pen(l, { w: 0.9, color: look.muted, seed: 20 + i * 4 + j, opacity: 0.5, retrace: false, boil: 0, taper: 0.3, wobble: 0.3 }));+ const lines = [{ t: `${i + 1}`, cap: 30, col: look.accent, w: 2.6, gap: -30 }, { t: ` ${st.title.toUpperCase()}`, cap: 17, col: look.ink, w: 1.7, gap: 8 }, { t: ` ${PHASE_NAME[st.phase].toUpperCase()}`, cap: 11, col: look.accent, w: 1.1, gap: 16 }, ...wrap(st.caption, 13, pw - 6).map((t) => ({ t, cap: 13, col: look.muted, w: 1.25, gap: 9 }))];+ block(g, lines, cx + 2, cy + pw + 22, 1, 300 + i * 40);+ });+ paperGrain(ctx, env, 0.04);+ };+ return { meta: { title: `${score().title} (step sheet)`, W, H, fps: 30, bpm: 120, durationFrames: 30, raster: "cpu" }, assets: { images: {} }, shots: [{ id: "sheet", start: 0, end: 30, draw }] };+};diff --git a/engine/src/canvas-core/lessonCat.ts b/engine/src/canvas-core/lessonCat.tsnew file mode 100644index 0000000..f587fce--- /dev/null+++ b/engine/src/canvas-core/lessonCat.ts@@ -0,0 +1,222 @@+// LESSON: HOW TO DRAW A CAT SITTING, in graphite pencil. A basic-drawing lesson from a plain+// request, written as a drawing score (drawingScore.ts): blue construction first, a checked and+// corrected ear, the outline committed in graphite, the blue lifted, then value masses, details+// and the darkest accents last.+//+// MEDIUM, physically: an HB graphite pencil on warm cartridge paper, and a blue col-erase pencil+// for construction (it erases cleanly and does not smear under graphite). Graphite deposits on+// the paper's tooth, so light pressure leaves the valleys white and pressing harder fills them.+// Tone is hatching in one diagonal (lower left to upper right, the natural swing of a right hand),+// cross-hatched only in the deepest darks. A kneaded eraser lifts the blue and leaves a ghost.+//+// SUBJECT: a domestic short-haired cat sitting, three-quarter view, head turned toward us and a+// little to our left, tail wrapped round the front paws. Anatomy that makes it read as a cat and+// not an icon: the head is a slightly flattened ball, wider than tall, with the eyes ON the middle+// line of the head and the ears set on the top corners (not on top, not on the sides); the ear is+// a rounded triangle about as tall as the gap between the eyes is wide; the muzzle is two small+// puffs under a short nose; the chest is an egg tipped back; the haunch (the folded hind leg) is+// the biggest mass in the drawing and sits BESIDE the chest, not under it; the front legs are+// straight columns that come down from the chest to small oval paws; the hind foot lies flat along+// the ground in front of the haunch; the tail comes from the base of the spine behind the haunch.+// REFERENCE (from knowledge): sitting domestic cats in three-quarter view; the standard teaching+// construction of head ball + chest egg + haunch circle used in animal-drawing primers. The+// proportions are measured in head heights, which is what the lesson teaches.+// LIGHT: from the upper left. Shade side: under the chin, the right of the chest, the lower right+// of the haunch, the tail's underside. Cast shadow falls to the lower right, on the floor.+import { type P } from "./core";+import { ScoreBuilder, type Score } from "./drawingScore";+import { contour, edgeDist, ellR, ellipsePts, eraserPath, guideLine, hatch, inter, minus, polyR, scribbleDot, sketchEllipse, stroke, union } from "./drawingMarks";+import { lessonFilm } from "./lesson";++const BLUE = "#4f7fcc", LEAD = "#3b3638", DARK = "#221d20", PAPER = "#f5f0e6";+const HATCH = -0.95; // the right hand's diagonal+const G = (seed: number) => ({ w: 2.1, col: BLUE, a: 0.62, seed }); // construction pencil++// ---------------------------------------------------------------- the cat, as geometry+const HEAD = { cx: 430, cy: 330, rx: 97, ry: 86 };+const CHEST = { cx: 445, cy: 560, rx: 100, ry: 150, rot: -0.12 };+const HAUNCH = { cx: 612, cy: 748, r: 146 };+const GROUND = 905;++const headOutline: P[] = [[352, 286], [336, 322], [338, 358], [352, 388], [378, 410], [414, 419], [452, 412], [488, 392], [512, 362], [522, 326], [514, 290]];+const crown: P[] = [[402, 253], [428, 246], [452, 250]];+const farEar: P[] = [[354, 288], [347, 238], [352, 203], [376, 222], [402, 253]];+const nearEar: P[] = [[452, 250], [478, 214], [502, 190], [512, 236], [514, 290]];+const wrongEar: P[] = [[462, 252], [480, 190], [492, 134], [503, 200], [506, 282]]; // too tall, too narrow: the classic first try+const back: P[] = [[516, 300], [532, 338], [546, 382], [566, 428], [582, 470], [612, 522], [658, 574], [708, 622], [746, 690], [762, 764], [752, 832], [722, 884]]; // nape, shoulder blade, back, over the haunch+const chestFront: P[] = [[392, 420], [366, 452], [350, 510], [348, 574], [362, 626], [376, 660]];+const farLeg: P[] = [[376, 660], [383, 740], [386, 820], [382, 872]];+const nearLegF: P[] = [[438, 640], [445, 740], [449, 820], [447, 876]];+const nearLegB: P[] = [[494, 642], [497, 740], [497, 820], [495, 876]];+const belly: P[] = [[497, 700], [516, 742], [530, 800], [528, 860], [518, 884]];+const thigh: P[] = [[548, 660], [590, 622], [650, 612], [705, 640]];+const farPaw: P[] = [[366, 884], [372, 874], [390, 870], [408, 874], [414, 886], [400, 893], [378, 893]];+const nearPaw: P[] = [[438, 890], [446, 876], [468, 872], [490, 876], [500, 888], [486, 897], [455, 898]];+const hindFoot: P[] = [[514, 886], [540, 877], [572, 876], [592, 884], [584, 896], [548, 898], [520, 896]];+const tailOut: P[] = [[744, 850], [786, 872], [796, 900], [764, 918], [700, 924], [610, 922], [540, 918], [498, 914], [476, 906]];+const tailIn: P[] = [[722, 880], [752, 890], [750, 902], [700, 908], [610, 908], [540, 905], [500, 902], [476, 906]];++// ---------------------------------------------------------------- the lesson+export const catScore = (): Score => {+ const b = new ScoreBuilder({ id: "cat", title: "How to draw a cat sitting", medium: "Graphite pencil, HB and 2B, with a blue col-erase pencil and a kneaded eraser", W: 1080, H: 1080, paper: PAPER, toothAngle: -0.6 })+ .layer("guides", 0, 1, "blue construction: erased before shading").layer("wrong", 0, 1, "the first ear, isolated so it can be erased alone")+ .layer("line", 0).layer("tone", 1).layer("dark", 2);+ b.part("gesture", "gesture and ground").part("head", "head", ["gesture"]).part("chest", "chest", ["head"]).part("haunch", "haunch", ["chest"])+ .part("face", "face", ["head"]).part("ears", "ears", ["head"]).part("legs", "front legs and paws", ["chest"]).part("hind", "hind foot", ["haunch"]).part("tail", "tail", ["haunch"]).part("shadow", "cast shadow", ["legs"]);++ // 1. placement+ b.step("s1", "placement", {+ title: "Place it and measure",+ caption: "One curve for the lean of the back, a floor line, and ticks for the height: this cat is about four heads tall.",+ look: "Before any cat, decide how big it is and where it sits. Mark the top of the ears and the floor first, then divide the height into head units.",+ how: "Hold the pencil far back and draw from the shoulder. Blue col-erase pencil, very light: none of these lines will survive.",+ mistake: "Starting with an eye. Details drawn first fix the size of everything else, and the cat never fits the page.",+ });+ b.add("gesture.floor", "gesture", "guides", "guide", guideLine([230, GROUND], [860, GROUND], G(11)));+ b.add("gesture.lean", "gesture", "guides", "guide", stroke([[424, 236], [470, 300], [560, 420], [660, 560], [730, 690], [752, 800], [735, 880]], { w: 2.3, col: BLUE, a: 0.62 }));+ [196, 376, 556, 736, GROUND].forEach((y, i) => b.add(`gesture.tick${i}`, "gesture", "guides", "guide", guideLine([252, y], [282, y], G(20 + i))));+ b.add("gesture.height", "gesture", "guides", "guide", guideLine([267, 196], [267, GROUND], { ...G(26), a: 0.45 }));++ // 2. big shapes+ b.step("s2", "shapes", {+ title: "Three masses",+ caption: "A ball for the head, an egg tipped back for the chest, and a big circle for the haunch, the largest shape of all.",+ look: "The haunch is about one and a half heads across and sits BESIDE the chest, behind it. Check that the chest egg leans back along your curve.",+ how: "Draw each shape in one loose loop that goes round a little more than once. Let the second pass correct the first; do not scrub.",+ mistake: "Drawing the body as one sausage. A sitting cat folds: without the haunch mass it reads as a bottle with ears.",+ });+ b.add("head.ball", "head", "guides", "guide", sketchEllipse(HEAD.cx, HEAD.cy, HEAD.rx, HEAD.ry, G(31)));+ b.add("chest.egg", "chest", "guides", "guide", sketchEllipse(CHEST.cx, CHEST.cy, CHEST.rx, CHEST.ry, { ...G(32), rot: CHEST.rot }));+ b.add("haunch.circle", "haunch", "guides", "guide", sketchEllipse(HAUNCH.cx, HAUNCH.cy, HAUNCH.r, HAUNCH.r * 0.97, G(33)));+ b.add("chest.neck", "chest", "guides", "guide", stroke([[370, 405], [362, 440], [356, 470]], { w: 2, col: BLUE, a: 0.55 }));+ b.add("chest.nape", "chest", "guides", "guide", stroke([[505, 312], [535, 360], [548, 420]], { w: 2, col: BLUE, a: 0.55 }));++ // 3. construction+ b.step("s3", "construction", {+ title: "Build the parts",+ caption: "Cross lines on the head ball, triangles for ears, a small oval muzzle, straight tubes for the front legs, and the tail's path.",+ look: "The eye line runs across the MIDDLE of the head, not near the top. The centre line curves round the ball because the head is turned.",+ how: "Wrap the cross lines round the ball as if drawing on an orange. Legs are two straight columns; paws are flat ovals on the floor line.",+ mistake: "Eyes placed high on the head, or ears stuck on the sides. Both make a cat look like a bear or an owl.",+ });+ b.add("face.centre", "face", "guides", "guide", stroke([[430, 244], [412, 290], [405, 340], [412, 400], [418, 418]], { w: 2, col: BLUE, a: 0.6 }));+ b.add("face.eyeline", "face", "guides", "guide", stroke([[336, 318], [380, 332], [430, 336], [480, 330], [522, 318]], { w: 2, col: BLUE, a: 0.6 }));+ b.add("face.muzzle", "face", "guides", "guide", sketchEllipse(418, 386, 42, 27, { ...G(41), turns: 1.1 }));+ b.add("ears.far", "ears", "guides", "guide", stroke([[354, 290], [351, 204], [404, 254]], { w: 2, col: BLUE, a: 0.6, smooth: false }));+ b.add("ears.nearWrong", "ears", "wrong", "guide", stroke([wrongEar[0], wrongEar[2], wrongEar[4]], { w: 2, col: BLUE, a: 0.6, smooth: false }));+ b.add("legs.far", "legs", "guides", "guide", stroke([[382, 640], [388, 760], [388, 876]], { w: 2, col: BLUE, a: 0.55 }));+ b.add("legs.nearF", "legs", "guides", "guide", stroke([[440, 640], [446, 760], [448, 878]], { w: 2, col: BLUE, a: 0.55 }));+ b.add("legs.nearB", "legs", "guides", "guide", stroke([[494, 640], [498, 760], [496, 878]], { w: 2, col: BLUE, a: 0.55 }));+ b.add("legs.farPaw", "legs", "guides", "guide", sketchEllipse(390, 884, 26, 11, { ...G(44), turns: 1.05 }));+ b.add("legs.nearPaw", "legs", "guides", "guide", sketchEllipse(469, 886, 32, 12, { ...G(45), turns: 1.05 }));+ b.add("hind.foot", "hind", "guides", "guide", sketchEllipse(553, 887, 40, 10, { ...G(46), turns: 1.05 }));+ b.add("tail.path", "tail", "guides", "guide", stroke([[742, 846], [790, 884], [760, 914], [640, 918], [520, 912], [476, 906]], { w: 2.2, col: BLUE, a: 0.6 }));++ // 4. check and correct+ b.step("s4", "construction", {+ title: "Check, then correct",+ caption: "Measure before you commit. The ear is too tall: it should be about as tall as the eyes are apart. Lift it and redraw.",+ look: "Compare ear height with the distance between the eyes, and ear width with its height. Cat ears are nearly as wide at the base as they are tall.",+ how: "Hold the pencil at arm's length as a ruler, or just compare two lengths by eye. Press the kneaded eraser, do not rub.",+ mistake: "Correcting after shading. Once graphite goes over a wrong line it will not lift cleanly; fix proportions while it is all blue.",+ });+ b.add("ears.measure", "ears", "guides", "guide", guideLine([380, 348], [448, 348], { ...G(51), a: 0.5 }));+ b.erase("ears.lift", "ears", "wrong", eraserPath([456, 128, 512, 290], { seed: 52, bite: 22 }), { width: 24, ghost: 0.08 });+ b.add("ears.near", "ears", "guides", "correction", stroke([[452, 252], [502, 190], [514, 290]], { w: 2.1, col: BLUE, a: 0.62, smooth: false }), { supersedes: "ears.nearWrong" });++ // 5. commit the outline, then lift the blue+ b.step("s5", "construction", {+ title: "Commit to the outline",+ caption: "Now the graphite line, following the blue. Press harder on the shadow side, go light where the light hits, then lift the blue.",+ look: "The outline is not one wire. It thickens under the chin, the belly and the haunch, and almost disappears along the lit top of the back.",+ how: "Short overlapping strokes, each starting a little inside the last. Rotate the paper so every stroke pulls toward you.",+ mistake: "Tracing every blue line. Leave out the construction: no circles show through a cat's fur.",+ });+ const lit = (x: number, y: number) => 0.55 + 0.9 * Math.max(0, Math.min(1, (x - 360) / 420 + (y - 300) / 900)); // weight grows away from the upper-left light+ const C = (name: string, part: string, pts: P[], seed: number, w = 2.3, keep = lit, closed = false) => b.addAll(`${part}.${name}`, part, "line", "line", contour(pts, { w, col: LEAD, a: 0.9, seed, keep: (x, y) => keep(x, y), closed }));+ C("outline", "head", headOutline, 61); C("crown", "head", crown, 62, 2); C("far", "ears", farEar, 63, 2.1); C("near", "ears", nearEar, 64, 2.2);+ C("front", "chest", chestFront, 65, 2.2); C("back", "haunch", back, 66, 2.3, (x, y) => (y < 560 ? 0.25 + (y - 300) / 520 : lit(x, y)));+ C("far", "legs", farLeg, 67, 2.2); C("nearF", "legs", nearLegF, 68, 2.2); C("nearB", "legs", nearLegB, 69, 2.5); C("belly", "haunch", belly, 70, 2.5); C("thigh", "haunch", thigh, 71, 1.7, () => 0.6);+ C("farPaw", "legs", farPaw, 72, 2.1, () => 1, true); C("nearPaw", "legs", nearPaw, 73, 2.2, () => 1, true); C("foot", "hind", hindFoot, 74, 2.2, () => 1, true);+ C("out", "tail", tailOut, 75, 2.4); C("in", "tail", tailIn, 76, 2.1);+ b.erase("gesture.lift", "gesture", "guides", eraserPath([220, 180, 880, 930], { seed: 77, bite: 42 }), { width: 46, ghost: 0.06 });++ // 6. value masses+ b.step("s6", "values", {+ title: "Shadow masses",+ caption: "Light comes from the upper left. Hatch the shade side as whole shapes: under the chin, right of the chest, the haunch, the floor.",+ look: "Squint. Find the three or four biggest dark shapes and ignore the fur. The cast shadow on the floor falls to the right and hugs the paws.",+ how: "Parallel strokes in one diagonal, laid side by side in patches. Build darker by going over again, not by pressing hard on the first pass.",+ mistake: "Outlining the shadow and colouring it in, or shading every part the same grey. Keep the lit side almost bare paper.",+ });+ const headShape = [...headOutline], chestShape: P[] = [[392, 420], [366, 452], [350, 510], [348, 574], [362, 626], [376, 660], [383, 740], [386, 820], [382, 872], [447, 876], [495, 876], [518, 884], [528, 860], [530, 800], [516, 742], [497, 700], [548, 660], [590, 622], [540, 470], [516, 300], [488, 392], [452, 412]];+ const haunchShape: P[] = [[612, 522], [658, 574], [708, 622], [746, 690], [762, 764], [752, 832], [722, 884], [612, 890], [548, 880], [528, 860], [530, 800], [516, 742], [510, 690], [548, 640], [575, 580]];+ const sideShape: P[] = [[516, 300], [532, 338], [546, 382], [566, 428], [582, 470], [612, 522], [575, 580], [548, 640], [510, 690], [497, 700], [494, 642], [470, 560], [488, 392]];+ const H = (name: string, part: string, reg: ReturnType<typeof polyR>, dens: (x: number, y: number) => number, seed: number, o: { gap?: number; len?: number; a?: number; w?: number; ang?: number; layer?: string } = {}) =>+ b.addAll(`${part}.${name}`, part, o.layer ?? "tone", "fill", hatch(reg, { ang: o.ang ?? HATCH, gap: o.gap ?? 5.2, len: o.len ?? 34, w: o.w ?? 1.9, col: LEAD, a: o.a ?? 0.55, seed, dens }));+ const clampD = (v: number) => Math.max(0, Math.min(1, v));+ H("chin", "head", polyR([[372, 398], [414, 422], [470, 410], [500, 388], [520, 440], [470, 470], [390, 460]]), (x, y) => clampD(0.95 - (y - 410) / 90) * clampD((x - 360) / 60), 81);+ H("cheek", "head", polyR(headShape), (x, y) => clampD(((x - 470) / 60) * 0.55 + (y - 360) / 200) * 0.7, 82, { gap: 6.5 });+ // the side of the body turns away from the light: a gentle half-tone that deepens toward the back+ H("side", "chest", polyR(sideShape), (x, y) => clampD(0.12 + (x - 480) / 260 + (y - 420) / 900) * 0.62, 83, { gap: 6.2 });+ // the pocket between the near leg, the belly and the haunch: the deepest shade on the body+ H("pocket", "chest", polyR([[494, 642], [510, 690], [516, 742], [530, 800], [528, 860], [518, 884], [496, 878], [497, 760]]), (x, y) => clampD(0.55 + (y - 660) / 300), 88, { gap: 4.4 });+ // the haunch is a ball lit from the upper left: tone grows with distance from its light spot+ H("mass", "haunch", polyR(haunchShape), (x, y) => { const d = Math.hypot(x - 575, y - 640); return clampD((d - 55) / 190) * 0.95; }, 84);+ H("under", "tail", polyR([...tailOut, ...[...tailIn].reverse()]), (x) => clampD(0.55 + (x - 480) / 700), 85, { gap: 4.5, len: 22 });+ H("floor", "shadow", minus(ellR(650, 912, 238, 24), polyR([...tailOut, ...[...tailIn].reverse()]), polyR(nearPaw), polyR(hindFoot)), (x) => clampD(0.9 - Math.abs(x - 640) / 260), 86, { ang: -0.12, gap: 4.2, len: 40, a: 0.45 });+ H("ears", "ears", union(polyR([[360, 282], [356, 220], [392, 252]]), polyR([[466, 250], [500, 202], [506, 282]])), () => 0.8, 87, { gap: 4, len: 20 });++ // 7. edges and details+ b.step("s7", "edges", {+ title: "Face and fur",+ caption: "Almond eyes on the eye line, a small nose where the centre line ends, a short Y for the mouth. Flick fur at the chest.",+ look: "The eyes sit one eye-width apart. The far eye is narrower because it turns away. Fur shows only at the edges: the ruff, the cheeks, the tail tip.",+ how: "Draw the eye shape, shade the iris lightly and leave a small white highlight on the same side for both eyes. Fur flicks go in the direction the hair grows.",+ mistake: "Round cartoon eyes with a dot. A cat's eye is an almond with a vertical slit pupil, and the upper lid is darker than the lower.",+ });+ const eye = (id: string, cx: number, cy: number, w: number, h: number, seed: number) => {+ const top: P[] = [[cx - w / 2, cy + 2], [cx - w / 4, cy - h / 2], [cx + w / 4, cy - h / 2 - 1], [cx + w / 2, cy - 2]], bot: P[] = [[cx - w / 2, cy + 2], [cx - w / 5, cy + h / 2], [cx + w / 4, cy + h / 2 - 1], [cx + w / 2, cy - 2]];+ b.addAll(`face.${id}Lid`, "face", "line", "line", contour(top, { w: 2.6, col: DARK, a: 0.95, seed, seg: 90 }));+ b.addAll(`face.${id}Low`, "face", "line", "line", contour(bot, { w: 1.5, col: LEAD, a: 0.8, seed: seed + 1, seg: 90 }));+ b.addAll(`face.${id}Iris`, "face", "tone", "fill", hatch(minus(ellR(cx, cy, w * 0.42, h * 0.42), ellR(cx - w * 0.14, cy - h * 0.15, 3.2, 3.2)), { ang: HATCH, gap: 2.6, len: 12, w: 1.4, col: LEAD, a: 0.5, seed: seed + 2 }));+ };+ eye("farEye", 379, 331, 40, 20, 91); eye("nearEye", 453, 331, 48, 23, 95);+ b.addAll("face.nose", "face", "line", "line", contour([[406, 366], [420, 364], [432, 367], [420, 380], [406, 366]], { w: 2, col: DARK, a: 0.9, seed: 99, seg: 40, smooth: false }));+ b.add("face.philtrum", "face", "line", "line", stroke([[420, 380], [419, 392]], { w: 1.8, col: LEAD, a: 0.85 }));+ b.add("face.mouthL", "face", "line", "line", stroke([[419, 392], [408, 400], [396, 398]], { w: 1.8, col: LEAD, a: 0.85 }));+ b.add("face.mouthR", "face", "line", "line", stroke([[419, 392], [432, 401], [446, 398]], { w: 1.8, col: LEAD, a: 0.85 }));+ b.addAll("ears.innerFar", "ears", "line", "line", contour([[362, 280], [357, 226], [388, 250]], { w: 1.4, col: LEAD, a: 0.7, seed: 101 }));+ b.addAll("ears.innerNear", "ears", "line", "line", contour([[468, 248], [500, 206], [506, 276]], { w: 1.4, col: LEAD, a: 0.7, seed: 102 }));+ // fur: short flicks in the direction of growth, only where an edge turns (ruff, cheek, tail tip)+ const flicks = (name: string, part: string, base: P[], dir: P, n: number, seed: number, L = 16) => { const out = []; let r = seed; for (let i = 0; i < n; i++) { const t = (i + 0.5) / n, k = Math.floor(t * (base.length - 1)), f = t * (base.length - 1) - k, a = base[k], c = base[Math.min(base.length - 1, k + 1)], x = a[0] + (c[0] - a[0]) * f, y = a[1] + (c[1] - a[1]) * f; r = (r * 9301 + 49297) % 233280; const j = r / 233280; out.push(stroke([[x, y], [x + dir[0] * L * (0.7 + j * 0.6) * 0.5 + (j - 0.5) * 3, y + dir[1] * L * (0.7 + j * 0.6) * 0.5], [x + dir[0] * L * (0.7 + j * 0.6), y + dir[1] * L * (0.7 + j * 0.6)]], { w: 1.5, col: LEAD, a: 0.75 })); } return b.addAll(`${part}.${name}`, part, "line", "line", out); };+ flicks("ruff", "chest", [[392, 424], [372, 450], [358, 488], [352, 526]], [-0.55, 0.85], 11, 7, 18);+ flicks("cheekL", "head", [[338, 340], [342, 370], [356, 392]], [-0.8, 0.5], 5, 11, 14);+ flicks("cheekR", "head", [[516, 350], [506, 376], [490, 394]], [0.8, 0.55], 4, 13, 13);+ flicks("tip", "tail", [[480, 904], [492, 910], [504, 914]], [-0.9, -0.2], 4, 17, 12);+ // tabby markings: the M on the brow and a few bands on the tail: they wrap round the form, so they curve+ b.addAll("face.brow", "face", "tone", "line", [stroke([[392, 290], [400, 272], [408, 292]], { w: 2, col: LEAD, a: 0.6 }), stroke([[416, 288], [420, 266], [428, 288]], { w: 2, col: LEAD, a: 0.6 }), stroke([[436, 290], [446, 270], [452, 294]], { w: 2, col: LEAD, a: 0.6 })]);+ b.addAll("tail.bands", "tail", "tone", "line", [[560, 906, 918], [620, 907, 921], [680, 906, 921], [740, 896, 914]].map(([x, y0, y1]) => stroke([[x, y0], [x - 4, (y0 + y1) / 2], [x - 1, y1]], { w: 4.2, col: LEAD, a: 0.55 })));++ // 8. accents+ b.step("s8", "accents", {+ title: "Darkest darks last",+ caption: "Pupils, nostrils, the corner of the mouth and the line where the paws touch the floor. Then whiskers: light, fast, curved.",+ look: "Only a few spots get the darkest dark. They pull the eye to the face and pin the cat to the floor.",+ how: "Switch to the 2B and press. Whiskers go last in single quick strokes that start at the muzzle and lift off; stop when in doubt.",+ mistake: "Heavy whiskers drawn slowly. Six light curved flicks read better than twelve dark straight ones.",+ });+ b.add("face.farPupil", "face", "dark", "fill", scribbleDot(381, 332, 3.2, 9.5, { w: 2.6, col: DARK, a: 0.95, seed: 111 }));+ b.add("face.nearPupil", "face", "dark", "fill", scribbleDot(455, 332, 3.8, 11, { w: 2.8, col: DARK, a: 0.95, seed: 112 }));+ b.add("face.nostril", "face", "dark", "fill", scribbleDot(419, 371, 6, 3.5, { w: 2.4, col: DARK, a: 0.9, seed: 113 }));+ b.addAll("shadow.contact", "shadow", "dark", "fill", hatch(union(ellR(468, 898, 36, 5), ellR(392, 894, 28, 4.5), ellR(572, 900, 46, 4.5)), { ang: -0.1, gap: 2.4, len: 18, w: 1.6, col: DARK, a: 0.8, seed: 114 }));+ b.addAll("chest.crease", "chest", "dark", "line", contour([[400, 424], [440, 428], [476, 414]], { w: 2.2, col: DARK, a: 0.75, seed: 115, seg: 50 }));+ const whisk = (x: number, y: number, dx: number, dy: number, bend: number) => stroke([[x, y], [x + dx * 0.5, y + dy * 0.5 - bend], [x + dx, y + dy]], { w: 1.25, col: LEAD, a: 0.7 });+ b.addAll("face.whiskers", "face", "dark", "line", [whisk(400, 386, -92, -8, 6), whisk(400, 392, -96, 10, 5), whisk(402, 398, -80, 26, 3), whisk(440, 386, 96, -10, 6), whisk(440, 392, 100, 8, 5), whisk(438, 398, 84, 26, 3)]);+ void inter; void edgeDist; void ellipsePts;+ return b.build();+};++export const lessonCat = lessonFilm(catScore, { outro: "Finished. Now draw it again from memory, bigger: the second cat teaches you more than the first." });++export const LESSON = { score: catScore, sheet: "lessonCatSheet", final: "lessonCatFinal" };diff --git a/engine/src/canvas-core/lessonCatFinal.ts b/engine/src/canvas-core/lessonCatFinal.tsnew file mode 100644index 0000000..3f71ac5--- /dev/null+++ b/engine/src/canvas-core/lessonCatFinal.ts@@ -0,0 +1,4 @@+// The cat lesson's finished drawing rendered cold (no replay cache, no schedule): the identity gate's other half.+import { lessonCat } from "./lessonCat";++export const lessonCatFinal = lessonCat.final;diff --git a/engine/src/canvas-core/lessonCatSheet.ts b/engine/src/canvas-core/lessonCatSheet.tsnew file mode 100644index 0000000..ae5d67c--- /dev/null+++ b/engine/src/canvas-core/lessonCatSheet.ts@@ -0,0 +1,5 @@+// The cat lesson's step sheet: one panel per step, earlier marks pale, the step's marks strong.+import { catScore } from "./lessonCat";+import { lessonSheet } from "./lesson";++export const lessonCatSheet = lessonSheet(catScore, { crop: [180, 150, 960, 950] });diff --git a/engine/src/canvas-core/lighthouse.ts b/engine/src/canvas-core/lighthouse.tsindex 069cba8..b11a421 100644--- a/engine/src/canvas-core/lighthouse.ts+++ b/engine/src/canvas-core/lighthouse.ts@@ -47,7 +47,7 @@ const glitter = (x: number, y: number) => { const col = clamp(1 - Math.abs(x - Sconst foam = (x: number, y: number) => sea(x, y) && shore(x, y) < Math.max(0, fractal(61, x, y, 0.035, 0.05, 3) - 0.38) * 70 + (fractal(62, x, y, 0.2, 0.2, 2) > 0.62 ? 5 : 0); // broken, bunched where the swell breaks// ---------------------------------------------------------------- the three plates-const yellowPlate = (g: Gfx) => drum(g, REG.yellow, () => {+export const yellowPlate = (g: Gfx) => drum(g, REG.yellow, () => {const all = { x0: 0, y0: 0, x1: W, y1: W };// sky: warmer toward the horizon and the sun, the beam laid in as lightscreen(g, all, PITCH, ANG.yellow, (x, y) => { if (y >= HY || occluded(x, y) || inSun(x, y)) return 0; return 0.12 + 0.62 * Math.pow(y / HY, 1.6) + 0.5 * Math.exp(-Math.pow(sunD(x, y) / 260, 2)) + 0.45 * beam(x, y); }, INK.yellow);@@ -62,7 +62,7 @@ const yellowPlate = (g: Gfx) => drum(g, REG.yellow, () => {[[150, 532, 26, 22], [212, 532, 26, 22]].forEach(([x, y, w, h]) => fillShape(g, [[x, y], [x + w, y], [x + w, y + h], [x, y + h]], INK.yellow));});-const pinkPlate = (g: Gfx) => drum(g, REG.pink, () => {+export const pinkPlate = (g: Gfx) => drum(g, REG.pink, () => {const all = { x0: 0, y0: 0, x1: W, y1: W };// sky: a band of pink across the middle of the dusk, deeper round the sunscreen(g, all, PITCH, ANG.pink, (x, y) => { if (y >= HY || occluded(x, y)) return 0; if (inSun(x, y)) return 0.18 + 0.7 * clamp((y - (SUN[1] - SR * 0.3)) / (SR * 0.9)); return 0.3 * (1 - y / HY) + 0.6 * Math.exp(-Math.pow((y - 430) / 170, 2)) + 0.35 * Math.exp(-Math.pow(sunD(x, y) / 220, 2)) + 0.08; }, INK.pink);@@ -79,7 +79,7 @@ const pinkPlate = (g: Gfx) => drum(g, REG.pink, () => {ROCKS.forEach((rk) => screen(g, all, PITCH, ANG.pink, (x) => { const b = rk.reduce((m, p) => Math.max(m, p[0]), -1e9), a = rk.reduce((m, p) => Math.min(m, p[0]), 1e9); return 0.15 + 0.6 * clamp((x - a) / (b - a)); }, INK.pink, rk));});-const bluePlate = (g: Gfx) => drum(g, REG.blue, () => {+export const bluePlate = (g: Gfx) => drum(g, REG.blue, () => {const all = { x0: 0, y0: 0, x1: W, y1: W };// sky: night coming down from the top, pulled back where the beam cuts throughscreen(g, all, PITCH, ANG.blue, (x, y) => { if (y >= HY || occluded(x, y) || inSun(x, y)) return 0; return (0.05 + 0.66 * Math.pow(1 - y / HY, 1.4)) * (1 - 0.8 * beam(x, y)); }, INK.blue);diff --git a/engine/src/canvas-core/lighthouseDraw.ts b/engine/src/canvas-core/lighthouseDraw.tsnew file mode 100644index 0000000..bb6edfb--- /dev/null+++ b/engine/src/canvas-core/lighthouseDraw.ts@@ -0,0 +1,71 @@+import { Gfx, type Ctx, type Env, type Layer } from "./core";+import type { Film } from "./film";+import { INK, LITHO, PAPER, drum } from "./riso";+import { bluePlate, drawLighthouse, pinkPlate, yellowPlate } from "./lighthouse";++// LIGHTHOUSE AT SUNSET · the print being pulled, drum by drum.+//+// A risograph prints one ink per drum, and a two- or three-colour print is the SAME sheet fed+// through the machine again with the next drum loaded. So the process here is not drawing, it is+// three passes through the press. Frame 0 is the bare sheet (its stock tooth and the trim marks+// already on it). Then the yellow drum: the sheet feeds leading-edge first, and the ink lands at+// the nip, a straight front travelling down the sheet with the drum's shadow riding just ahead of+// it. A breath while the drum is swapped. Pink goes down over the dry yellow at its own+// registration offset, and every overprint is BORN at the nip line: the sky turns coral, the sun+// orange, the turf nothing yet. Swap. Blue last, the key plate: the dusk violet, the green of the+// turf, the shadow side of every form and the crayon key lines all arrive in one sweep. Each+// ink's swatch in the colour bar at the foot prints with its own drum. The last frame is+// `drawLighthouse` itself, so the finished piece is the lighthouse still, byte for byte.+//+// Motion grammar: the only moving thing is the nip line, constant speed like a real feed (short+// ease at the ends as the sheet is gripped and released); never a fade.++const N = 330;+// ---------------------------------------------------------------- the cue table (frames)+const CUE = { yellow: [0, 95], pink: [100, 195], blue: [200, 295], done: 295 } as const; /* passes on the 5-frame event grid; a 5-frame breath while the drum is swapped */+const check = () => { const all = [...CUE.yellow, ...CUE.pink, ...CUE.blue, CUE.done]; if (all.some((f) => f % 5)) throw new Error("lighthouseDraw: cue off the beat grid"); if (CUE.done > N - 30) throw new Error("lighthouseDraw: hold shorter than 30 frames"); };+check();++const PLATES = [yellowPlate, pinkPlate, bluePlate], SWATCH = [INK.yellow, INK.pink, INK.blue];++// The sheet after k passes. Mirrors plateMarks exactly, except that a swatch prints only once its+// drum has run. The held finish is drawn by drawLighthouse itself on the main canvas, so the last+// frames are the lighthouse still byte for byte (state 3 is its offscreen twin for the blue pass).+const state = (env: Env, k: number): Layer => {+ const key = `lighthouseDraw:state:${k}:${env.W}x${env.H}@${env.scale}`; let L = env.cache.get(key) as Layer | undefined;+ if (L) return L;+ const W = env.W, H = env.H; L = env.canvas(Math.round(W * env.scale), Math.round(H * env.scale));+ const g = new Gfx(L.ctx, env, 0, LITHO), c = L.ctx;+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = PAPER; c.fillRect(0, 0, W, H);+ for (let i = 0; i < k; i++) PLATES[i](g);+ g.group("plain", () => { const x = g.cur; x.strokeStyle = "#1b1b1b"; x.lineWidth = 1.1; [[26, 26], [W - 26, 26], [26, H - 26], [W - 26, H - 26]].forEach(([px, py]) => { x.beginPath(); x.arc(px, py, 7, 0, Math.PI * 2); x.moveTo(px - 12, py); x.lineTo(px + 12, py); x.moveTo(px, py - 12); x.lineTo(px, py + 12); x.stroke(); }); }, { alpha: 0.9 });+ if (k > 0) drum(g, [0, 0], () => SWATCH.slice(0, k).forEach((col, i) => { const x = g.cur; x.fillStyle = col; x.fillRect(W / 2 - SWATCH.length * 16 + i * 32, H - 34, 28, 14); }));+ g.paper("paper", 0.26); g.paper("coldpress", 0.22);+ env.cache.set(key, L); return L;+};++// the nip line's position through one pass, 0..1 of the sheet; gripped and released gently+const feed = (u: number) => { const a = 0.08; if (u <= 0) return 0; if (u >= 1) return 1; const v = u < a ? (u * u) / (2 * a) : u > 1 - a ? 1 - ((1 - u) * (1 - u)) / (2 * a) : u - a / 2; return v / (1 - a / 2); };++const draw = (ctx: Ctx, f: number, env: Env) => {+ if (f >= CUE.done) return drawLighthouse(ctx, 0, env); // the finished print: the still, exactly+ const passes = [CUE.yellow, CUE.pink, CUE.blue];+ let done = 0; while (done < 3 && f >= passes[done][1]) done++;+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale);+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(state(env, done).canvas, 0, 0);+ const p = passes[done]; if (!p || f < p[0]) return; // between passes: the drum is being swapped+ const u = feed((f - p[0]) / (p[1] - p[0])), shade = 46 * env.scale, y = Math.round(u * DH); /* the nip is on the sheet from the first frame of the pass to the last */+ if (y > 0) ctx.drawImage(state(env, done + 1).canvas, 0, 0, DW, y, 0, 0, DW, y);+ // the drum's shadow on the sheet, just ahead of the nip: the one sign of the machine+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0);+ const gr = ctx.createLinearGradient(0, y, 0, y + shade); gr.addColorStop(0, "rgba(40,30,40,0.2)"); gr.addColorStop(0.25, "rgba(40,30,40,0.09)"); gr.addColorStop(1, "rgba(40,30,40,0)");+ ctx.fillStyle = gr; ctx.fillRect(0, y, DW, shade); ctx.restore();+};++export const lighthouseDraw: Film = {+ meta: { title: "Lighthouse at sunset · the print, drum by drum", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "press", start: 0, end: N, draw }],+};++export const STYLE = { id: "lighthouseDraw", name: "Risograph, pulled drum by drum", family: "print", medium: "soy ink forced through a stencil master wrapped on a rotating drum, one drum per colour, the same sheet fed through once per ink", nearest: "lighthouse", hero: "lighthouse at sunset" };diff --git a/engine/src/canvas-core/lowPoly.ts b/engine/src/canvas-core/lowPoly.tsnew file mode 100644index 0000000..92a0484--- /dev/null+++ b/engine/src/canvas-core/lowPoly.ts@@ -0,0 +1,205 @@+import { fractal, rng, type Ctx, type Env, type Layer, type P } from "./core";+import type { Film } from "./film";+import { clamp01, onGrid } from "./scrapbookKit";++// A MOUNTAIN LAKE AT DAWN · low-poly, 3D drawn in code.+//+// MEDIUM, physically: there is none, and that is the point of the style. A scene MODELLED as+// triangle meshes (a heightfield of lake, shores and two mountain ranges; pines as stacked+// six-sided cones; a canoe lofted from cross-sections; rocks as jittered polyhedra), PROJECTED by+// hand through a pinhole camera (no 3D engine: a translate, one pitch rotation and a divide), and+// FLAT-SHADED: every triangle is one colour, from its normal against ONE light, the low sun, plus+// a cool sky ambient, then hazed toward the dawn by its distance. Drawn by PAINTER'S SORT, far to+// near. The mark is the facet: a hard-edged triangle, no line, no gradient, no texture.+// Reflections are the same meshes mirrored in the water plane, drawn only where water is visible+// (a mask made by the same painter's pass) and broken by horizontal ripple cuts.+// ORDER, as a modeller works: the empty viewport; the wireframe (terrain swept from the far+// ranges to the near shore, then the pines, the rocks, the canoe); the faces shading in back to+// front in exactly painter's order (sky, far range, near range, shores, trees, canoe); the water+// facets; the reflections; last the ripple cuts and the sun's glitter path.+// LIGHT: the sun just clearing a notch in the far range, left of centre, 6 degrees up: slopes+// that face it go peach and rose, the rest stay blue-violet; snow on the high faces.+// NOT any other plate: every other plate is a hand's mark on a surface; this one is geometry, and+// its only texture is the triangulation. Reference, from memory: dawn over a lake in the Canadian+// Rockies (a pink-lit range, snow on the upper faces, dark spruce shores, still water).++const N = 450;+const W = 1080, H = 1080, F = 880, CX = 540, CY = 540;+const CAM = { x: 0, y: 3.4, z: -4 }, PITCH = 0.035, CP = Math.cos(PITCH), SP = Math.sin(PITCH);+type V = [number, number, number];+const view = ([x, y, z]: V): V => { const X = x - CAM.x, Y = y - CAM.y, Z = z - CAM.z; return [X, Y * CP + Z * SP, Z * CP - Y * SP]; };+const proj = (v: V): P => { const [X, Y, Z] = view(v); return [CX + (F * X) / Z, CY - (F * Y) / Z]; };+const HORIZON = CY - F * Math.tan(PITCH);+const sub = (a: V, b: V): V => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const cross = (a: V, b: V): V => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const norm = (a: V): V => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };+const dot = (a: V, b: V) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+const smoothstep = (a: number, b: number, x: number) => { const t = clamp01((x - a) / (b - a)); return t * t * (3 - 2 * t); };++// ---------------------------------------------------------------- light and colour+const SUN_DIR: V = norm([-0.78, 0.11, 0.62]); // toward the sun: left, low, beyond the lake+const SUN_SCREEN: P = [372, 408];+const hex = (h: string): V => [parseInt(h.slice(1, 3), 16) / 255, parseInt(h.slice(3, 5), 16) / 255, parseInt(h.slice(5, 7), 16) / 255];+const rgb = (c: V) => `rgb(${c.map((v) => Math.round(255 * clamp01(v))).join(",")})`;+const mixV = (a: V, b: V, t: number): V => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+const AMB: V = [0.5, 0.52, 0.8], SUNC: V = [1.35, 0.82, 0.62], HAZE: V = hex("#c79aa6");+const shade = (base: V, n: V, dist: number, ambK = 1): V => { const d = Math.max(0, dot(n, SUN_DIR)), sky = 0.55 + 0.45 * Math.max(0, n[1]); const c: V = [base[0] * (AMB[0] * sky * ambK + SUNC[0] * d), base[1] * (AMB[1] * sky * ambK + SUNC[1] * d), base[2] * (AMB[2] * sky * ambK + SUNC[2] * d)]; return mixV(c, HAZE, 1 - Math.exp(-Math.max(0, dist - 8) / 85)); };++// ---------------------------------------------------------------- the land+const lakeCX = (z: number) => 1.2 + 2.5 * Math.sin(z * 0.07) - 1.6 * Math.exp(-z / 8);+const lakeHW = (z: number) => { const hw = 4.8 + 0.24 * Math.min(z, 50) + 3.2 * Math.exp(-z / 7); return z <= 50 ? hw : z < 58 ? hw * Math.sqrt(Math.max(0, 1 - ((z - 50) / 8) ** 2)) : -2; };+const ridged = (seed: number, x: number, z: number, f: number) => { const v = 1 - Math.abs(2 * fractal(seed, x, z, f, f, 4) - 1); return v * v; };+const height = (x: number, z: number): number => {+ const d = Math.abs(x - lakeCX(z)) - lakeHW(z);+ let h = d > 0 ? Math.min(d * 0.42, 2.6) + fractal(7, x, z, 0.11, 0.11, 3) * 3.2 * smoothstep(0, 9, d) : -1.2;+ h += 6.5 * smoothstep(54, 66, z) * ridged(11, x, z, 0.075) + 1.5 * smoothstep(52, 60, z);+ h += 17 * smoothstep(74, 90, z) * ridged(23, x + 40, z, 0.045) * (0.7 + 0.3 * fractal(5, x, z, 0.02, 0.02, 2)) + 4 * smoothstep(70, 84, z);+ // the notch the sun clears: a saddle in the far range just left of centre+ const nx = (x + 22) / 10; h -= 9 * Math.exp(-nx * nx) * smoothstep(70, 90, z);+ return h;+};+type Face = { v: V[]; s: P[]; col: string; z: number; kind: "land" | "water" | "obj"; mir?: P[]; mcol?: string; order?: number; group: number };+const faceOf = (v: V[], base: V, kind: Face["kind"], group: number, ambK = 1, cull = false): Face | null => {+ let n = norm(cross(sub(v[1], v[0]), sub(v[2], v[0]))); const c: V = [(v[0][0] + v[1][0] + v[2][0]) / 3, (v[0][1] + v[1][1] + v[2][1]) / 3, (v[0][2] + v[1][2] + v[2][2]) / 3];+ const toCam = sub([CAM.x, CAM.y, CAM.z], c); if (dot(n, toCam) < 0) { if (cull) return null; n = [-n[0], -n[1], -n[2]]; }+ const dist = Math.hypot(...toCam), col = shade(base, n, dist, ambK);+ const f: Face = { v, s: v.map(proj), col: rgb(col), z: view(c)[2], kind, group };+ if (kind !== "water" && v.some((p) => p[1] > 0.01)) { f.mir = v.map(([x, y, z]) => proj([x, -Math.max(0, y), z])); f.mcol = rgb(mixV(col, hex("#35406a"), 0.28).map((q) => q * 0.82) as V); }+ return f;+};+const build = () => {+ const r = rng(77), faces: Face[] = [];+ // a perspective-friendly grid: columns widen with distance, rows grow ~12% each+ const zs: number[] = [0]; while (zs[zs.length - 1] < 118) { const z = zs[zs.length - 1]; zs.push(z + 0.55 + 0.115 * z); }+ const COLS = 44, grid: V[][] = zs.map((z, i) => Array.from({ length: COLS + 1 }, (_, j) => { const u = -1 + (2 * (j + (j > 0 && j < COLS ? (r() - 0.5) * 0.6 : 0))) / COLS, zz = i > 0 && i < zs.length - 1 ? z + (r() - 0.5) * 0.5 * (zs[i + 1] - zs[i - 1]) / 2 : z, x = u * (7 + 0.66 * zz), h = height(x, zz); return [x, Math.max(0, h), zz] as V; }));+ const raw = zs.map((z, i) => grid[i].map(([x, , zz]) => height(x, zz)));+ for (let i = 0; i < zs.length - 1; i++) for (let j = 0; j < COLS; j++) {+ const a = grid[i][j], b = grid[i][j + 1], c = grid[i + 1][j + 1], d = grid[i + 1][j], ha = raw[i][j], hb = raw[i][j + 1], hc = raw[i + 1][j + 1], hd = raw[i + 1][j];+ const tris: [V[], number[]][] = r() < 0.5 ? [[[a, b, c], [ha, hb, hc]], [[a, c, d], [ha, hc, hd]]] : [[[a, b, d], [ha, hb, hd]], [[b, c, d], [hb, hc, hd]]];+ for (const [t, hs] of tris) {+ const mx = Math.max(...hs), avgY = (t[0][1] + t[1][1] + t[2][1]) / 3, zc = (t[0][2] + t[1][2] + t[2][2]) / 3;+ if (mx <= 0) { const far = clamp01((zc - 4) / 55), base = mixV(hex("#2c3561"), hex("#d9a3a8"), far ** 1.3); const k = 0.96 + r() * 0.08; faces.push({ v: t, s: t.map(proj), col: rgb(base.map((q) => q * k) as V), z: view([t[0][0], 0, zc])[2], kind: "water", group: 0 }); continue; }+ const n = norm(cross(sub(t[1], t[0]), sub(t[2], t[0]))), up = Math.abs(n[1]);+ const base = Math.min(...hs) < 0.25 ? hex("#6a6553") : avgY > 11 && up > 0.6 ? hex("#f4eef4") : avgY > 7 || up < 0.55 ? hex(zc > 66 ? "#7d7894" : "#6a6275") : hex(zc > 50 ? "#3f5a50" : "#2e4a3c");+ const f = faceOf(t, base.map((q) => q * (0.95 + r() * 0.1)) as V, "land", 1); if (f) faces.push(f);+ }+ }+ // pines: drifts along both shores, bare rests between; six-sided cone tiers on a trunk+ const pines: V[] = [];+ for (let k = 0; k < 4000 && pines.length < 150; k++) { const z = 9 + r() * 54, x = (r() - 0.5) * (18 + z * 1.1), d = Math.abs(x - lakeCX(z)) - lakeHW(z); if (d < 1.2 || d > 16 || height(x, z) > 5) continue; if (fractal(31, x, z, 0.16, 0.16, 2) < 0.5 + (z > 48 ? -0.06 : 0.02)) continue; if (pines.some((p) => Math.hypot(p[0] - x, p[2] - z) < 1.1 + z * 0.02)) continue; pines.push([x, height(x, z), z]); }+ pines.forEach(([x, y, z], pi) => {+ const hgt = 2.4 + r() * 2.6 + z * 0.02, rot = r() * 1.05, sides = 6, g = 2 + pi;+ const trunk: V[] = Array.from({ length: 4 }, (_, i) => { const a = rot + (i / 4) * 6.28; return [x + Math.cos(a) * 0.12, y, z + Math.sin(a) * 0.12] as V; });+ for (let i = 0; i < 4; i++) { const a = trunk[i], b = trunk[(i + 1) % 4], a2: V = [a[0], y + hgt * 0.25, a[2]], b2: V = [b[0], y + hgt * 0.25, b[2]]; [faceOf([a, b, b2], hex("#4a3426"), "obj", g, 1, true), faceOf([a, b2, a2], hex("#4a3426"), "obj", g, 1, true)].forEach((f) => f && faces.push(f)); }+ for (let t = 0; t < 3; t++) {+ const y0 = y + hgt * (0.18 + t * 0.24), y1 = y0 + hgt * (0.42 - t * 0.04), rad = hgt * (0.34 - t * 0.085), apex: V = [x, y1, z];+ const ring: V[] = Array.from({ length: sides }, (_, i) => { const a = rot + t * 0.5 + (i / sides) * 6.28, rr = rad * (0.85 + r() * 0.3); return [x + Math.cos(a) * rr, y0 - 0.05 * r(), z + Math.sin(a) * rr] as V; });+ for (let i = 0; i < sides; i++) { const f = faceOf([ring[i], ring[(i + 1) % sides], apex], hex(t === 2 ? "#2b5244" : "#23463b"), "obj", g, 1.1, true); if (f) faces.push(f); }+ }+ });+ // the canoe: lofted from 13 stations, bow and stern rising, an open hull you can see into+ const C0: V = [1.6, 0, 8.6], yaw = 0.95, L = 4.8, B = 0.9, cy = Math.cos(yaw), sy = Math.sin(yaw);+ const at = (u: number, lat: number, y: number): V => { const lx = u * L / 2, lz = lat; return [C0[0] + lx * cy - lz * sy, y, C0[2] + lx * sy + lz * cy]; };+ const ST = 13, sts = Array.from({ length: ST }, (_, i) => { const u = -1 + (2 * i) / (ST - 1), w = (B / 2) * Math.pow(Math.max(0, 1 - u * u), 0.55), s = 0.32 + 0.22 * u ** 4; return { u, w, s }; });+ const ring = (st: { u: number; w: number; s: number }): V[] => [at(st.u, -st.w, st.s), at(st.u, -st.w * 0.96, st.s * 0.5), at(st.u, -st.w * 0.82, 0.02), at(st.u, st.w * 0.82, 0.02), at(st.u, st.w * 0.96, st.s * 0.5), at(st.u, st.w, st.s)];+ const inner = (st: { u: number; w: number; s: number }): V[] => [at(st.u, -st.w * 0.9, st.s - 0.02), at(st.u, -st.w * 0.6, 0.12), at(st.u, st.w * 0.6, 0.12), at(st.u, st.w * 0.9, st.s - 0.02)];+ const HULL = hex("#b3392b"), WOOD = hex("#c98a4b"), RAIL = hex("#8a5a32"), cg = 300;+ for (let i = 0; i < ST - 1; i++) {+ const A = ring(sts[i]), Bq = ring(sts[i + 1]), IA = inner(sts[i]), IB = inner(sts[i + 1]), um = (sts[i].u + sts[i + 1].u) / 2;+ const keel = at(um, 0, 0.25), outside = (v: V[]) => { const c: V = [(v[0][0] + v[1][0] + v[2][0]) / 3, (v[0][1] + v[1][1] + v[2][1]) / 3, (v[0][2] + v[1][2] + v[2][2]) / 3]; let n = norm(cross(sub(v[1], v[0]), sub(v[2], v[0]))); if (dot(n, sub(c, keel)) < 0) n = [-n[0], -n[1], -n[2]]; return dot(n, sub([CAM.x, CAM.y, CAM.z], c)) > 0 ? faceOf(v, HULL, "obj", cg) : null; };+ for (let k = 0; k < 5; k++) { [outside([A[k], A[k + 1], Bq[k + 1]]), outside([A[k], Bq[k + 1], Bq[k]])].forEach((f) => f && faces.push(f)); }+ const axis = at(um, 0, 0.7), inside = (v: V[]) => { const c: V = [(v[0][0] + v[1][0] + v[2][0]) / 3, (v[0][1] + v[1][1] + v[2][1]) / 3, (v[0][2] + v[1][2] + v[2][2]) / 3]; let n = norm(cross(sub(v[1], v[0]), sub(v[2], v[0]))); if (dot(n, sub(axis, c)) < 0) n = [-n[0], -n[1], -n[2]]; if (dot(n, sub([CAM.x, CAM.y, CAM.z], c)) <= 0) return null; const f = faceOf(v, WOOD, "obj", cg, 1.3); if (f) delete f.mir; return f; }; /* the water mirrors the hull's underside, never its inside */ // an inner wall is seen only from the side it faces+ for (let k = 0; k < 3; k++) { [inside([IA[k + 1], IA[k], IB[k]]), inside([IA[k + 1], IB[k], IB[k + 1]])].forEach((f) => f && faces.push(f)); }+ [[A[0], IA[0], IB[0], Bq[0]], [A[5], Bq[5], IB[3], IA[3]]].forEach(([p, q, s2, t2]) => { [faceOf([p, q, s2], RAIL, "obj", cg), faceOf([p, s2, t2], RAIL, "obj", cg)].forEach((f) => f && faces.push(f)); });+ }+ // two thwarts and a paddle laid across them+ [-0.35, 0.3].forEach((u) => { const st = sts.find((s) => Math.abs(s.u - u) < 0.09) ?? sts[6], a = at(u, -st.w * 0.9, st.s - 0.06), b = at(u, st.w * 0.9, st.s - 0.06), a2 = at(u + 0.03, -st.w * 0.9, st.s - 0.06), b2 = at(u + 0.03, st.w * 0.9, st.s - 0.06); [faceOf([a, b, b2], RAIL, "obj", cg), faceOf([a, b2, a2], RAIL, "obj", cg)].forEach((f) => f && faces.push(f)); });+ const pa = at(-0.42, -0.95, 0.4), pb = at(0.2, 0.62, 0.36), pw: V = [0.04 * sy, 0, -0.04 * cy]; [faceOf([pa, pb, [pb[0] + pw[0], pb[1] + 0.03, pb[2] + pw[2]]], hex("#e0b27a"), "obj", cg), faceOf([pa, [pb[0] + pw[0], pb[1] + 0.03, pb[2] + pw[2]], [pa[0] + pw[0], pa[1] + 0.03, pa[2] + pw[2]]], hex("#e0b27a"), "obj", cg)].forEach((f) => f && faces.push(f));+ const blade: V[] = [pb, at(0.34, 0.8, 0.34), at(0.36, 0.62, 0.35), at(0.22, 0.5, 0.36)]; [faceOf([blade[0], blade[1], blade[2]], hex("#e0b27a"), "obj", cg), faceOf([blade[0], blade[2], blade[3]], hex("#e0b27a"), "obj", cg)].forEach((f) => f && faces.push(f));++ // painter's sort: far to near. The canoe is drawn as one group after the land it floats on.+ const land = faces.filter((f) => f.kind !== "water" && f.group !== cg).sort((a, b) => b.z - a.z), canoe = faces.filter((f) => f.group === cg).sort((a, b) => b.z - a.z), water = faces.filter((f) => f.kind === "water").sort((a, b) => b.z - a.z);+ const solid = [...land, ...canoe]; solid.forEach((f, i) => (f.order = i)); water.forEach((f, i) => (f.order = i));+ // the wireframe, in the order a modeller builds it: terrain far to near, then trees, rocks, canoe+ const wireOrder = [...faces.filter((f) => f.group <= 1).sort((a, b) => b.z - a.z), ...faces.filter((f) => f.group > 1 && f.group < 200).sort((a, b) => a.group - b.group), ...faces.filter((f) => f.group >= 200 && f.group < 300), ...canoe];+ // unique edges, each revealed with the first face that owns it; hidden once all its faces are filled+ const emap = new Map<string, { a: P; b: P; rank: number; faces: Face[] }>();+ wireOrder.forEach((f, i) => { for (let k = 0; k < 3; k++) { const a = f.s[k], b = f.s[(k + 1) % 3], ka = `${a[0].toFixed(2)},${a[1].toFixed(2)}`, kb = `${b[0].toFixed(2)},${b[1].toFixed(2)}`, key = ka < kb ? ka + "|" + kb : kb + "|" + ka; const e = emap.get(key); if (e) e.faces.push(f); else emap.set(key, { a, b, rank: i, faces: [f] }); } });+ const edges = [...emap.values()].sort((x, y) => x.rank - y.rank);+ return { solid, water, wireOrder, edges, all: faces };+};+type Scene = ReturnType<typeof build>;+const scene = (env: Env): Scene => { let s = env.cache.get("lowPoly:scene") as Scene | undefined; if (!s) { s = build(); env.cache.set("lowPoly:scene", s); } return s; };++// ---------------------------------------------------------------- the sky (2D facets) and the sun+const skyFaces = (() => {+ const r = rng(91), cols = 14, rows = 7, pts: P[][] = [];+ for (let i = 0; i <= rows; i++) { const y = -10 + ((HORIZON + 34) * i) / rows; pts.push(Array.from({ length: cols + 1 }, (_, j) => [-10 + (1100 * j) / cols + (j && j < cols ? (r() - 0.5) * 50 : 0), y + (i && i < rows ? (r() - 0.5) * 40 : 0)] as P)); }+ const out: { s: P[]; col: string }[] = [];+ const colAt = (x: number, y: number) => { const t = clamp01(y / (HORIZON + 20)), ds = Math.hypot(x - SUN_SCREEN[0], (y - SUN_SCREEN[1]) * 1.6) / 700; let c = t < 0.45 ? mixV(hex("#262c5c"), hex("#5b4f8a"), t / 0.45) : t < 0.8 ? mixV(hex("#5b4f8a"), hex("#d98f98"), (t - 0.45) / 0.35) : mixV(hex("#d98f98"), hex("#f6bf92"), (t - 0.8) / 0.2); c = mixV(c, hex("#ffd9a8"), clamp01(0.75 - ds) * 0.8 * t); const k = 0.97 + r() * 0.06; return rgb(c.map((q) => q * k) as V); };+ for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++) { const a = pts[i][j], b = pts[i][j + 1], c = pts[i + 1][j + 1], d = pts[i + 1][j]; const tris = (i + j) % 2 ? [[a, b, c], [a, c, d]] : [[a, b, d], [b, c, d]]; tris.forEach((t) => { const cx = (t[0][0] + t[1][0] + t[2][0]) / 3, cy = (t[0][1] + t[1][1] + t[2][1]) / 3; out.push({ s: t, col: colAt(cx, cy) }); }); }+ // three faceted clouds, their undersides lit rose by the sun below the horizon+ ([[720, 190, 150, 30], [890, 260, 90, 20], [210, 150, 120, 24]] as [number, number, number, number][]).forEach(([x, y, w, h], ci) => { const n = 7, top: P[] = Array.from({ length: n + 1 }, (_, k) => [x - w + (2 * w * k) / n, y - h * Math.sin((Math.PI * k) / n) * (0.7 + r() * 0.6)] as P), bot: P[] = Array.from({ length: n + 1 }, (_, k) => [x - w * 0.9 + (1.8 * w * k) / n, y + h * 0.35 * Math.sin((Math.PI * k) / n)] as P); for (let k = 0; k < n; k++) { out.push({ s: [top[k], top[k + 1], bot[k]], col: rgb(mixV(hex("#8f7aa8"), hex("#f0a6a0"), 0.25 + 0.15 * ((k + ci) % 3))) }); out.push({ s: [top[k + 1], bot[k + 1], bot[k]], col: rgb(mixV(hex("#8f7aa8"), hex("#ffc3a0"), 0.55 + 0.12 * (k % 2))) }); } });+ return out;+})();+const sunFacets = (() => { const rings: { s: P[]; col: string }[] = []; [[150, "#f7c79a", 0.35], [100, "#fbd7a6", 0.45], [66, "#ffe6b8", 0.6]].forEach(([R, c, a]) => { rings.push({ s: Array.from({ length: 12 }, (_, i) => { const t = (i / 12) * 6.28 + 0.13; return [SUN_SCREEN[0] + Math.cos(t) * (R as number), SUN_SCREEN[1] + Math.sin(t) * (R as number) * 0.9] as P; }), col: `rgba(${hex(c as string).map((v) => Math.round(v * 255)).join(",")},${a})` }); }); rings.push({ s: Array.from({ length: 10 }, (_, i) => { const t = (i / 10) * 6.28; return [SUN_SCREEN[0] + Math.cos(t) * 30, SUN_SCREEN[1] + Math.sin(t) * 30] as P; }), col: "#fff3d6" }); return rings; })();+const stars: P[] = [[120, 60], [310, 96], [610, 44], [860, 80], [980, 150], [470, 130]];++// ---------------------------------------------------------------- drawing+const fillTri = (c: Ctx, s: P[], col: string) => { c.fillStyle = col; c.beginPath(); c.moveTo(s[0][0], s[0][1]); for (let i = 1; i < s.length; i++) c.lineTo(s[i][0], s[i][1]); c.closePath(); c.fill(); c.strokeStyle = col; c.lineWidth = 0.6; c.stroke(); }; // a hairline of the same colour closes the antialias seams between facets+const CUE = { wire: [5, 110], sky: [115, 140], faces: [140, 290], water: [295, 335], refl: [340, 395], ripple: [395, 420] } as const;+onGrid("lowPoly", Object.values(CUE).flat() as number[], N);+const prog = (f: number, [a, b]: readonly [number, number]) => (f >= b ? 1 : clamp01((f - a) / (b - a)));++const layerOf = (env: Env, key: string): Layer => { const DW = Math.round(W * env.scale), DH = Math.round(H * env.scale), k = `lowPoly:${key}:${DW}`; let L = env.cache.get(k) as Layer | undefined; if (!L) { L = env.canvas(DW, DH); env.cache.set(k, L); } return L; };+// where water is visible: the painter's pass again, water white, anything solid erasing it+const waterMask = (env: Env, sc: Scene): Layer => {+ const k = `lowPoly:maskDone:${env.scale}`, L = layerOf(env, "mask"); if (env.cache.get(k)) return L;+ const c = L.ctx; c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.clearRect(0, 0, W, H);+ const all = [...sc.water.map((f) => ({ f, w: true })), ...sc.solid.map((f) => ({ f, w: false }))].sort((a, b) => b.f.z - a.f.z);+ // the canoe is drawn after the land it floats on: keep it last here as well+ all.sort((a, b) => (a.f.group === 300 ? 1 : 0) - (b.f.group === 300 ? 1 : 0) || b.f.z - a.f.z);+ for (const { f, w } of all) { c.globalCompositeOperation = w ? "source-over" : "destination-out"; fillTri(c, f.s, "#ffffff"); }+ c.globalCompositeOperation = "source-over"; env.cache.set(k, true); return L;+};++export const drawLowPoly = (ctx: Ctx, f: number, env: Env) => {+ const sc = scene(env), s = env.scale;+ ctx.setTransform(s, 0, 0, s, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";+ // the empty viewport: a dark modelling grid+ ctx.fillStyle = "#171a26"; ctx.fillRect(0, 0, W, H); ctx.strokeStyle = "#23283a"; ctx.lineWidth = 1; ctx.beginPath(); for (let x = 0; x <= W; x += 60) { ctx.moveTo(x, 0); ctx.lineTo(x, H); } for (let y = 0; y <= H; y += 60) { ctx.moveTo(0, y); ctx.lineTo(W, y); } ctx.stroke();+ const pSky = prog(f, CUE.sky), pFace = prog(f, CUE.faces), pWater = prog(f, CUE.water), pRefl = prog(f, CUE.refl), pRip = prog(f, CUE.ripple);+ // sky facets, top to bottom (the farthest thing there is), then the sun, then stars+ if (pSky > 0) { const n = Math.floor(pSky * skyFaces.length); const order = skyFaces.map((q, i) => ({ q, i, y: (q.s[0][1] + q.s[1][1] + q.s[2][1]) / 3 })).sort((a, b) => a.y - b.y); order.slice(0, n).forEach(({ q }) => fillTri(ctx, q.s, q.col)); if (pSky >= 1) { sunFacets.forEach((q) => { ctx.fillStyle = q.col; ctx.beginPath(); q.s.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); ctx.fill(); }); ctx.fillStyle = "#fff4e0"; stars.forEach(([x, y], i) => { const k = 1.2 + (i % 3) * 0.5; ctx.beginPath(); ctx.moveTo(x, y - k * 2); ctx.lineTo(x + k * 0.6, y); ctx.lineTo(x, y + k * 2); ctx.lineTo(x - k * 0.6, y); ctx.closePath(); ctx.fill(); }); } }+ // solid faces, painter's order+ const nSolid = Math.floor(pFace * sc.solid.length); for (let i = 0; i < nSolid; i++) fillTri(ctx, sc.solid[i].s, sc.solid[i].col);+ // water facets, far to near. They sit under everything solid, so each is drawn and then the+ // solid faces nearer than it are laid again over it only where they overlap: simpler and exact,+ // we draw water into its own layer and cut it with the solid mask.+ if (pWater > 0) {+ const Wl = layerOf(env, "water"), wc = Wl.ctx; wc.setTransform(s, 0, 0, s, 0, 0); wc.globalCompositeOperation = "source-over"; wc.clearRect(0, 0, W, H);+ const nW = pWater >= 1 ? sc.water.length : Math.floor(pWater * sc.water.length); for (let i = 0; i < nW; i++) fillTri(wc, sc.water[i].s, sc.water[i].col);+ // reflections: the mirrored meshes, far to near, darkened toward the water+ if (pRefl > 0) { const mir = sc.solid.filter((q) => q.mir), nR = pRefl >= 1 ? mir.length : Math.floor(pRefl * mir.length); for (let i = 0; i < nR; i++) fillTri(wc, mir[i].mir!, mir[i].mcol!); }+ // ripple cuts: thin bands where the surface is stirred show the plain water colour again+ if (pRip > 0) { const r = rng(404); wc.globalAlpha = 0.9; for (let y = HORIZON + 8, k = 0; y < H; y += 9 + (y - HORIZON) * 0.1, k++) { const vis = clamp01(pRip * 1.3 - (y - HORIZON) / (H - HORIZON) * 0.3); if (vis <= 0) continue; const th = 0.8 + (y - HORIZON) * 0.012; for (let x = -20 + r() * 120; x < W; x += 120 + r() * 260) { const l = (20 + r() * 90) * vis; const t = clamp01((y - HORIZON) / 500); wc.fillStyle = rgb(mixV(hex("#d9a3a8"), hex("#2c3561"), t ** 0.8)); wc.fillRect(x, y, l, th); } } wc.globalAlpha = 1;+ // the sun's glitter path: short bright dashes in a column under it, widening toward us+ const g = rng(405); wc.fillStyle = "#ffe7bf"; for (let y = HORIZON + 3; y < 760; y += 3 + (y - HORIZON) * 0.05) { const spread = 8 + (y - HORIZON) * 0.35, n = Math.max(1, Math.floor((1 - (y - HORIZON) / 300) * 4 * pRip)); for (let k = 0; k < n; k++) { const x = SUN_SCREEN[0] + (g() - 0.5) * 2 * spread, l = 4 + g() * 14 * (1 - (y - HORIZON) / 320); if (l > 1) wc.fillRect(x - l / 2, y, l, 1.2 + (y - HORIZON) * 0.006); } } }+ const M = waterMask(env, sc); wc.save(); wc.setTransform(1, 0, 0, 1, 0, 0); wc.globalCompositeOperation = "destination-in"; wc.drawImage(M.canvas as CanvasImageSource, 0, 0); wc.restore(); wc.globalCompositeOperation = "source-over";+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(Wl.canvas as CanvasImageSource, 0, 0); ctx.restore();+ }+ // wireframe over whatever is not yet a face, in cyan, drawn edge by edge+ const pWire = prog(f, CUE.wire); if (pWire > 0 && pRefl < 1) {+ const E = sc.edges, n = pWire * sc.wireOrder.length; ctx.strokeStyle = "rgba(130,210,255,0.5)"; ctx.lineWidth = 0.7; ctx.beginPath();+ const nWater = pWater >= 1 ? sc.water.length : Math.floor(pWater * sc.water.length), filled = (q: Face) => q.order! < (q.kind === "water" ? nWater : nSolid);+ for (const e of E) { if (e.rank >= n) break; if (e.faces.every(filled)) continue; const part = clamp01(n - e.rank); ctx.moveTo(e.a[0], e.a[1]); ctx.lineTo(e.a[0] + (e.b[0] - e.a[0]) * part, e.a[1] + (e.b[1] - e.a[1]) * part); }+ ctx.stroke();+ }+};++export const lowPoly: Film = {+ meta: { title: "A mountain lake at dawn · low-poly", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },+ assets: { images: {} },+ shots: [{ id: "lowPoly", start: 0, end: N, draw: (ctx, f, env) => drawLowPoly(ctx, f, env) }],+};+export const STYLE = { id: "lowPoly", name: "Low-poly", family: "3D in code", medium: "triangle meshes projected by hand through a pinhole camera, each facet flat-shaded by its normal against one low sun, painter-sorted far to near; no 3D engine", nearest: "none (the only geometry plate); closest in spirit riso's flat inks", hero: "A mountain lake at dawn: pink-lit range, spruce shores, a red canoe, reflections" };diff --git a/engine/src/canvas-core/mascotHero.ts b/engine/src/canvas-core/mascotHero.tsnew file mode 100644index 0000000..179e328--- /dev/null+++ b/engine/src/canvas-core/mascotHero.ts@@ -0,0 +1,71 @@+// MASCOT HERO. Bit (storybook plate) in his meadow on a landing-page hero, watching the visitor.+//+// The idea in one sentence: the little wind-up robot is the page's most attentive reader, so he+// looks where you look and gets visibly excited about the button you are about to press.+// - his eyes follow the pointer anywhere on the page; his head follows a beat later (eyes lead);+// - hover or TAB to a bound button: he turns to it, lifts the near arm to present it, brows up,+// antenna bulb brightens (every hover reaction has a keyboard-focus equivalent);+// - press: he winds up (a crouch, eyes wide); click "start": he jumps and cheers with pencil+// twinkles; click "tour": he waves hello; poke Bit himself: he giggles;+// - untouched, he breathes, blinks, his key turns and his pencil line boils: never a dead second.+// Loop: 480 ticks (8 s). Every idle motion's period divides it.+import type { Env, P } from "./core";+import { blit, usePaper } from "./bake";+import { attend, bakeBit, CHEER, cheer, drawBit2, FACE, idle, LOOP, meadowSprite, restPose, SHEETS, toSheet, type BitPose } from "./bitRig";+import { attentionOf, centre, clip, reactionSeed, type Discrete, type InputState, type Piece } from "./input";++const FACE_S = toSheet(FACE);+const SHOULDER_S = (side: number) => toSheet([side * 50, -114]);+// the lift that points an arm at a target, or 0 if the target is on the other side+const pointLift = (d: Discrete, side: number): number => {+ const a = attentionOf(d); if (!a || a === "self" || !d.rects[a]) return 0;+ const c = centre(d.rects[a]), sh = SHOULDER_S(side);+ if ((c[0] - sh[0]) * side <= 0) return 0;+ const phi = (Math.atan2(c[1] - sh[1], (c[0] - sh[0]) * side) * 180) / Math.PI; // angle in the right arm's frame+ return Math.max(0.2, Math.min(0.6, (62 - phi) / 177));+};++export const mascotHero: Piece = {+ meta: { title: "Bit, watching", W: 560, H: 560, loop: LOOP, alt: "A pencil-and-watercolour wind-up robot in a meadow, who watches your pointer and cheers when you press Get started." },+ input: {+ springs: {+ look: { omega: 0.3, target: (d) => lookAt(d) }, // eyes: quick+ head: { omega: 0.11, target: (d) => lookAt(d) }, // head: a beat behind the eyes+ armL: { omega: 0.16, target: (d) => pointLift(d, -1) },+ armR: { omega: 0.16, target: (d) => pointLift(d, 1) },+ excite: { omega: 0.09, target: (d) => { const a = attentionOf(d); return a && a !== "self" ? 1 : 0; } },+ },+ },+ bake: function* (env) { yield "paper"; usePaper(env, SHEETS); yield "meadow"; bg(env); yield* bakeBit(env); },+ draw: (ctx, t, env, s) => {+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";+ usePaper(env, SHEETS); /* the sheet is baked into every sprite (bake.ts): no per-frame multiply */+ blit(ctx, bg(env));+ drawBit2(ctx, env, pose(t, s));+ },+};++const lookAt = (d: Discrete): P => { const a = attentionOf(d); if (a && a !== "self" && d.rects[a]) return centre(d.rects[a]); return d.pointer ?? FACE_S; };+const bg = (env: Env) => meadowSprite(env);+const tri = (u: number) => (u < 0.5 ? u * 2 : 2 - u * 2);++export const pose = (t: number, s: InputState): BitPose => {+ const p = restPose(), R = s.reduced;+ if (!R) { idle(p, t); attend(p, s.spring.look as P, s.spring.head as P); p.armL = s.spring.armL as number; p.armR = s.spring.armR as number; }+ const ex = s.spring.excite as number, a = s.attention;+ p.glow += ex * 0.9;+ if (a && a !== "self") { p.brows = "up"; p.mouth = a === "start" ? "grin" : "smile"; if (a === "tour" && !R) p.tilt += 5 * ex; }+ if (s.pressed && s.pressed !== "self") { p.mouth = "o"; p.brows = "up"; if (!R) p.squash = 0.965; }+ // reactions: fixed-length clips on the grid, restarted by each new click+ const ch = clip(s, "click:start", CHEER), wave = clip(s, "click:tour", 64), poke = clip(s, "click:self", 48);+ if (ch) cheer(p, ch.f, reactionSeed(s, "click:start"), R);+ else if (wave) {+ const f = wave.f; p.eyes = "happy"; p.mouth = "smile"; p.brows = "up"; p.blush = 1;+ if (!R) { p.armR = 0.56 + 0.09 * Math.sin((2 * Math.PI * f) / 16); p.tilt = 7 * Math.sin((Math.PI * f) / 64); p.look = [2, -1]; }+ } else if (poke) {+ const f = poke.f; p.eyes = "squint"; p.mouth = "grin"; p.blush = 1; p.heart = tri((f % 16) / 16);+ if (!R) { p.tilt = 6 * Math.sin((2 * Math.PI * f) / 12) * (1 - f / 48); p.squash = 1 - 0.03 * tri((f % 12) / 12); p.key += Math.floor(f / 2); }+ }+ if (R && (ch || wave || poke)) { const c = (ch ?? wave ?? poke)!, len = ch ? CHEER : wave ? 64 : 48; p.faceFade = Math.min(1, c.f / 8, (len - c.f) / 8); }+ return p;+};diff --git a/engine/src/canvas-core/midCentury.ts b/engine/src/canvas-core/midCentury.tsnew file mode 100644index 0000000..c0a0012--- /dev/null+++ b/engine/src/canvas-core/midCentury.ts@@ -0,0 +1,233 @@+import { displace, fractal, Gfx, rng, type Ctx, type Env, type Medium, type P } from "./core";+import type { Film } from "./film";+import { clamp, lerp, mix, smooth } from "./gallery";+import { streakClip, streaks } from "./koiDrawKit";++// MID-CENTURY GOUACHE · a hillside village, and a girl flying a kite.+//+// MEDIUM, physically: designer's gouache on warm illustration board, the way 1950s-60s picture+// books were painted (the Provensens, Mary Blair, Sasek). Gouache is OPAQUE and dries MATTE: a+// shape is laid in flat with a loaded flat brush, strokes visible only at its ragged edge; a+// lighter colour can go straight over a darker one. Then a nearly dry brush is dragged across+// the flats, so the bristles skip the board's tooth and leave broken parallel streaks (grass,+// cloud edges, weather on walls). Last, a loose brush-and-ink line goes on top, printed on its+// own plate in the book, so it sits OFF REGISTER from the colour: the line wanders past the edge+// of the shape it describes, and leaves edges out where the colour already says it.+// MARKS: flat opaque shapes with brushed, slightly ragged edges; dry-brush bristle streaks that+// break up as the brush runs out; a loose, thin, slightly thick-thin ink line, open contours.+// ORDER: flat colour shapes BIG TO SMALL (sky and hills, the village, houses, trees, the kite,+// the girl's dress, skin, hair, the smallest things last), then the dry brush, then the line.+// PALETTE: limited and bold, one key: warm board, mustard, tomato, turquoise, olive, deep+// green-black, pink, cream.+// LIGHT: sun high on the left. Every house shows a darker right side, the girl throws a flat+// shadow down the hill to the right.+// SUBJECT & REFERENCE (from knowledge): an eight-year-old girl, six heads tall (head 54 px of+// 324): shoulders at 1.3 heads, crotch at 3.1, knees at 4.5, ankles at 5.8. Weight on the+// straight back leg, the front leg stepping forward with the knee bent FORWARD; the kite arm+// raised with the elbow flexed outward-down (upper arm ~1 head, forearm ~0.9), the fist closed+// round the string with the thumb over it; the balance arm back and down, hand open, palm down,+// four fingers and a thumb. Three-quarter view looking up-right at the kite; A-line dress with+// a Peter Pan collar and puff sleeves, white socks, Mary Janes (1950s children's clothing).+// Wind from the left: the hem, the bow tails and the kite tail all stream right. The village is+// an Italian/Provencal hill town stacked up a slope: tall narrow houses, a church and spire,+// cypresses.+// NOT ITS NEIGHBOUR (cut-paper fox): no torn fibres and no lifting pieces; painted edges, dry+// brush, and a line that floats off the colour.++const W = 1080, H = 1080, N = 540, HOLD = 30;+const T = { paint: [4, 262], dry: [268, 352], line: [358, N - HOLD - 2] } as const;+const C = { board: "#f1e1b8", cloud: "#fbf2dc", far2: "#98c1ad", far: "#4f8f86", vill: "#a6a340", villD: "#8b8a32", fore: "#4c8c52", foreD: "#356a3e", cream: "#f5e8c8", pink: "#e8a296", ochre: "#e2a73a", turq: "#56aba2", white: "#f7efdc", tomato: "#d2462a", teal: "#244e4a", brown: "#7a4a33", dark: "#2b2724", cyp: "#2d5a40", tree: "#6f8a2e", skin: "#eab28c", hair: "#2a201b", blush: "#e78578", red: "#cf3f27", mustard: "#e9ae34", ink: "#1d1a17" };+const BRUSH: Medium = { nib: 1.15, taper: 1, pressure: 0.85, retrace: false, wobble: 1.4, rough: 0.35 };+const REG: P = [5, -4]; // the line plate's misregistration against the colour++type Sh = { pts: P[]; col: string; ang: number };+type Dry = { path: P[]; w: number; col: string; seed: number };+type Ln = { pts: P[]; w: number; seed: number };+type Scene = { shapes: Sh[]; dry: Dry[]; lines: Ln[]; order: number[]; paintT: [number, number][]; dryT: [number, number][]; lineT: [number, number][] };++// ---------------------------------------------------------------- geometry+const sm = (a: P[], closed = true, per = 6) => smooth(a, closed, per);+const area = (s: P[]) => Math.abs(s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2);+const ell = (cx: number, cy: number, rx: number, ry: number, rot = 0, n = 18): P[] => Array.from({ length: n }, (_, i) => { const a = (i / n) * Math.PI * 2, x = Math.cos(a) * rx, y = Math.sin(a) * ry; return [cx + x * Math.cos(rot) - y * Math.sin(rot), cy + x * Math.sin(rot) + y * Math.cos(rot)] as P; });+const plen = (s: P[]) => s.reduce((a, p, i) => (i ? a + Math.hypot(p[0] - s[i - 1][0], p[1] - s[i - 1][1]) : 0), 0);+// a limb on a jointed centreline: radius per joint, a soft muscle bulge between+const limb = (c: P[], r: number[], bulge = 0): { poly: P[]; a: P[]; b: P[] } => {+ const s = sm(c, false, 10), n = s.length, A: P[] = [], B: P[] = [];+ s.forEach((p, i) => { const t = i / (n - 1), seg = Math.min(r.length - 2, Math.floor(t * (r.length - 1))), f = t * (r.length - 1) - seg, rr = lerp(r[seg], r[seg + 1], f) + bulge * Math.sin(Math.PI * clamp((t - 0.5) * 2)) , q = s[Math.min(n - 1, i + 1)], o = s[Math.max(0, i - 1)], dx = q[0] - o[0], dy = q[1] - o[1], l = Math.hypot(dx, dy) || 1; A.push([p[0] - (dy / l) * rr, p[1] + (dx / l) * rr]); B.push([p[0] + (dy / l) * rr, p[1] - (dx / l) * rr]); });+ return { poly: [...A, ...[...B].reverse()], a: A, b: B };+};+// a hand in its own frame: u along the forearm, v across it+const frame = (wrist: P, elbow: P) => { const dx = wrist[0] - elbow[0], dy = wrist[1] - elbow[1], l = Math.hypot(dx, dy); const a: P = [dx / l, dy / l], n: P = [-a[1], a[0]]; return (u: number, v: number): P => [wrist[0] + a[0] * u + n[0] * v, wrist[1] + a[1] * u + n[1] * v]; };+const capsuleUV = (F: (u: number, v: number) => P, u0: number, v0: number, u1: number, v1: number, r: number): P[] => { const a = F(u0, v0), b = F(u1, v1), ang = Math.atan2(b[1] - a[1], b[0] - a[0]), out: P[] = []; for (let i = 0; i <= 6; i++) { const t = ang + Math.PI / 2 + (i / 6) * Math.PI; out.push([a[0] + Math.cos(t) * r, a[1] + Math.sin(t) * r]); } for (let i = 0; i <= 6; i++) { const t = ang - Math.PI / 2 + (i / 6) * Math.PI; out.push([b[0] + Math.cos(t) * r, b[1] + Math.sin(t) * r]); } return out; };++const buildScene = (): Scene => {+ const shapes: Sh[] = [], dry: Dry[] = [], lines: Ln[] = [], r = rng(1957);+ const S = (pts: P[], col: string, ang = 0) => shapes.push({ pts, col, ang });+ const L = (pts: P[], w = 2, seed = lines.length + 1) => lines.push({ pts, w, seed: 300 + seed });+ const D = (path: P[], w: number, col: string) => dry.push({ path, w, col, seed: 700 + dry.length });+ const ridge = (top: P[], base: number): P[] => { const t = sm(top, false, 8); return [...t, [t[t.length - 1][0], base], [t[0][0], base]]; };++ // clouds and hills: the big flats+ const cloud = (x: number, y: number, s: number): P[] => [...sm([[x - 130 * s, y], [x - 100 * s, y - 22 * s], [x - 50 * s, y - 30 * s], [x - 20 * s, y - 52 * s], [x + 30 * s, y - 50 * s], [x + 60 * s, y - 26 * s], [x + 110 * s, y - 20 * s], [x + 140 * s, y]], false, 6), [x, y + 4]];+ S(cloud(240, 170, 1), C.cloud); S(cloud(600, 104, 0.7), C.cloud);+ S(ridge([[-20, 560], [180, 520], [420, 546], [640, 492], [860, 440], [1100, 420]], H), C.far2, 0.2);+ S(ridge([[-20, 616], [150, 584], [330, 600], [520, 566], [700, 528], [900, 480], [1100, 464]], H), C.far, 0.25);+ const ys = (x: number) => 735 - (x - 420) * 0.4;+ // a meadow between the far hills and her hill, with a hedgerow of round trees on its crest+ S(ridge([[-20, 690], [110, 684], [240, 700], [330, 730], [420, 780]], H), "#c7b24c", -0.1);+ S(ridge([[340, 790], [420, ys(420) - 40], [600, ys(600) - 40], [800, ys(800) - 40], [1000, ys(1000) - 40], [1100, ys(1100) - 40]], H), C.vill, -0.38);+ // the village, back row first, each house a front face, a darker right side, a roof, windows+ const house = (x: number, base: number, w: number, h: number, wall: string, roof: string, gable: boolean, k: number) => {+ const side = w * 0.3, lift = side * 0.5, top = base - h;+ S([[x + w, base], [x + w + side, base - lift], [x + w + side, top - lift], [x + w, top]], mix(wall, C.dark, 0.3), 1.57);+ S([[x, base], [x + w, base], [x + w, top], [x, top]], wall, 1.57);+ if (gable) { S([[x - 4, top + 1], [x + w / 2, top - w * 0.55], [x + w + 4, top + 1]], roof, 0.4); S([[x + w / 2, top - w * 0.55], [x + w + side + 3, top - lift - w * 0.5], [x + w + side + 4, top - lift + 1], [x + w + 4, top + 1]], mix(roof, C.dark, 0.3), 0.4); }+ else S([[x - 3, top + 2], [x + w + side + 3, top - lift + 2], [x + w + side + 3, top - lift - 9], [x - 3, top - 8]], roof, 0.1);+ const nw = 1 + (k % 3), rows = h > 70 ? 2 : 1;+ for (let j = 0; j < rows; j++) for (let i = 0; i < nw; i++) { const wx = x + (w * (i + 0.5)) / nw - 5 + 2, wy = top + 14 + j * 30 - 2; S([[wx, wy], [wx + 10, wy], [wx + 10, wy + 15], [wx, wy + 15]], C.dark, 1.57); }+ // the line: two or three sides only, never the whole box+ L([[x, top + 3], [x, base]], 1.5); L(gable ? [[x - 4, top + 1], [x + w / 2, top - w * 0.55], [x + w + side + 3, top - lift - w * 0.5]] : [[x - 3, top - 8], [x + w + side + 3, top - lift - 9]], 1.6);+ if (k % 2) L([[x + w, top], [x + w, base]], 1.3);+ D([[x + 4, top + 8], [x + 6, base - 4]], w * 0.5, mix(wall, "#ffffff", 0.35));+ };+ const walls = [C.cream, C.pink, C.ochre, C.turq, C.white], roofs = [C.tomato, C.teal, C.brown, C.tomato];+ const cyp = (x: number, base: number, h: number) => { S(sm([[x, base], [x - 9, base - h * 0.35], [x - 6, base - h * 0.75], [x, base - h], [x + 6, base - h * 0.75], [x + 9, base - h * 0.35]]), C.cyp, 1.57); L([[x + 2, base - h + 6], [x + 7, base - h * 0.5], [x + 6, base - 6]], 1.2); };+ [560, 624, 700, 770, 842, 908, 976, 1044].forEach((x, i) => { if (x === 700) return; house(x, ys(x) - 20, 46 + (i % 3) * 6, 70 + ((i * 7) % 4) * 8, walls[(i + 2) % 5], roofs[i % 4], i % 3 !== 1, i); });+ // the church: tall nave, a turquoise spire, one round window+ { const x = 692, base = ys(700) - 20, w = 46, h = 118, top = base - h; S([[x + w, base], [x + w + 14, base - 7], [x + w + 14, top - 7], [x + w, top]], mix(C.white, C.dark, 0.3), 1.57); S([[x, base], [x + w, base], [x + w, top], [x, top]], C.white, 1.57); S([[x - 2, top], [x + w / 2, top - 96], [x + w + 2, top]], C.turq, 0.3); S([[x + w / 2, top - 96], [x + w + 15, top - 7], [x + w + 2, top]], mix(C.turq, C.dark, 0.3), 0.3); S(ell(x + w / 2 + 2, top + 26, 8, 8), C.dark); S([[x + 16, base - 34], [x + 30, base - 34], [x + 30, base], [x + 16, base]], C.brown, 1.57); L([[x - 2, top], [x + w / 2, top - 96], [x + w + 15, top - 7]], 1.6); L([[x, top], [x, base]], 1.5); L([[x + w / 2 + 2, top - 108], [x + w / 2 + 2, top - 94]], 1.4); L([[x + w / 2 - 4, top - 102], [x + w / 2 + 8, top - 102]], 1.4); }+ [505, 646, 730, 870, 1006].forEach((x, i) => cyp(x, ys(x) + 36, 62 + (i % 2) * 20));+ [470, 530, 592, 656, 736, 806, 874, 944, 1018].forEach((x, i) => house(x, ys(x) + 36, 48 + (i % 2) * 8, 60 + ((i * 5) % 3) * 12, walls[i % 5], roofs[(i + 1) % 4], i % 4 !== 2, i + 3));+ [[118, 668, 20], [150, 676, 16], [236, 690, 18]].forEach(([x, y, rr]) => { S([[x - 2, y + rr], [x + 3, y + rr], [x + 3, y + rr + 16], [x - 2, y + rr + 16]], C.brown, 1.57); S(ell(x, y, rr, rr * 1.05), C.tree, 0.8); L([[x - rr * 0.6, y - rr * 0.5], [x, y - rr * 1.02], [x + rr * 0.8, y - rr * 0.4]], 1.3); });+ // the near hill, the girl's shadow down it+ S(ridge([[-20, 836], [120, 822], [260, 815], [350, 813], [460, 818], [640, 848], [860, 896], [1100, 948]], H), C.fore, -0.1);+ S(sm([[300, 815], [420, 815], [540, 836], [590, 848], [500, 850], [380, 830], [316, 820]]), C.foreD, 0.1);++ // the kite, a diamond of four gores, and its tail of bows+ const kc: P = [828, 206], ka = 0.36, K = (x: number, y: number): P => [kc[0] + x * Math.cos(ka) - y * Math.sin(ka), kc[1] + x * Math.sin(ka) + y * Math.cos(ka)];+ const kt = K(0, -72), kr = K(50, -8), kb = K(0, 86), kl = K(-50, -8), k0 = K(0, -8);+ S([kt, kr, k0], C.mustard, 0.4); S([kr, kb, k0], C.red, 0.4); S([kb, kl, k0], C.mustard, 0.4); S([kl, kt, k0], C.red, 0.4);+ const tail = sm([kb, [kb[0] + 20, kb[1] + 50], [kb[0] - 6, kb[1] + 100], [kb[0] + 26, kb[1] + 150], [kb[0] + 60, kb[1] + 186]], false, 8);+ [0.2, 0.4, 0.6, 0.8, 0.97].forEach((t, i) => { const p = tail[Math.round(t * (tail.length - 1))], c = i % 2 ? C.turq : C.red; S([[p[0], p[1]], [p[0] - 11, p[1] - 7], [p[0] - 11, p[1] + 7]], c, 0); S([[p[0], p[1]], [p[0] + 11, p[1] - 7], [p[0] + 11, p[1] + 7]], c, 0); });+ L([kt, kr, kb, kl, kt], 1.8); L([kt, kb], 1.4); L([kl, kr], 1.4); L(tail, 1.2);++ // THE GIRL. Hair and dress, skin, then the smallest things+ const armR = limb([[368, 570], [402, 534], [417, 489]], [6.3, 5.2, 4.3], 0.6), armL = limb([[306, 578], [285, 613], [266, 643]], [6.3, 5.2, 4.3], 0.5);+ const legB = limb([[322, 646], [316, 730], [308, 800]], [9.5, 6.8, 5], 1.4), legF = limb([[348, 646], [373, 726], [389, 800]], [9.5, 6.8, 5], 1.4);+ const sockB = limb([[312, 770], [308, 801]], [6.4, 5.8]), sockF = limb([[385, 771], [389, 801]], [6.4, 5.8]);+ S(legB.poly, C.skin, 1.5); S(legF.poly, C.skin, 1.4); S(sockB.poly, C.white, 0); S(sockF.poly, C.white, 0);+ const shoeB: P[] = sm([[300, 797], [316, 796], [331, 802], [338, 809], [334, 815], [306, 815], [299, 810]]), shoeF: P[] = sm([[381, 797], [397, 796], [413, 802], [420, 809], [416, 815], [387, 815], [380, 810]]);+ S(shoeB, C.dark, 0); S(shoeF, C.dark, 0);+ S(armL.poly, C.skin, 2.1); S(armR.poly, C.skin, -1.2);+ const dress: P[] = sm([[330, 555], [318, 558], [306, 565], [301, 580], [299, 600], [293, 630], [285, 662], [279, 687], [300, 692], [320, 687], [339, 692], [359, 685], [379, 688], [399, 679], [414, 672], [397, 652], [385, 624], [377, 598], [373, 577], [369, 565], [357, 557], [346, 554]]);+ S(dress, C.red, 1.45);+ S(ell(305, 576, 13, 14, 0.3), C.red, 0); S(ell(371, 571, 13, 12, -0.5), C.red, 0);+ S(sm([[328, 555], [319, 560], [321, 569], [333, 569], [338, 562], [343, 569], [355, 568], [357, 559], [348, 555]]), C.white, 0);+ S([[332, 538], [344, 538], [345, 557], [331, 557]], C.skin, 1.57);+ const head: P[] = sm([[318, 509], [322, 497], [334, 490], [349, 492], [359, 501], [363, 513], [362, 525], [356, 535], [346, 542], [334, 542], [324, 535], [318, 523]]);+ S(head, C.skin, 1.57);+ const hair: P[] = sm([[358, 496], [346, 488], [332, 487], [318, 493], [309, 505], [306, 520], [308, 536], [312, 547], [321, 550], [325, 541], [322, 528], [326, 516], [334, 508], [346, 504], [358, 506], [363, 503]]);+ S(hair, C.hair, 0.6);+ S(ell(326, 523, 4.2, 6.2, 0.1), C.skin, 0);+ // the bow at the back of her head, its tails streaming right in the wind+ S([[315, 494], [301, 484], [299, 499]], C.turq, 0); S([[315, 494], [306, 505], [318, 505]], C.turq, 0); S([[315, 493], [333, 482], [350, 478], [334, 488]], C.turq, 0);+ S(ell(350, 527, 6, 4.5), C.blush, 0);+ // hands: the kite hand a fist round the string, thumb over it; the balance hand open, palm down+ const fist: P[] = sm([[409, 489], [406, 477], [408, 466], [414, 459], [422, 458], [429, 462], [431, 471], [430, 481], [425, 489]]);+ S(fist, C.skin, 0);+ const F = frame([266, 643], [285, 613]), palm: P[] = sm([F(0, -6.2), F(3, -7.4), F(14, -7.8), F(16, 0), F(14, 7.4), F(3, 6.6), F(0, 5.6)]);+ const fingers = [[-5.9, 15, -0.14], [-2, 17, -0.05], [2, 16.5, 0.04], [5.8, 13.5, 0.12]].map(([v, len, sp]) => capsuleUV(F, 13, v, 13 + len, v + len * sp, 1.75));+ const thumb = capsuleUV(F, 4, 6.2, 12, 12.5, 2);+ S(palm, C.skin, 0); fingers.forEach((f) => S(f, C.skin, 0)); S(thumb, C.skin, 0);+ S(ell(351, 513, 2.3, 3, 0.2, 10), C.dark, 0); // the eye, looking up at the kite++ // wildflowers in two drifts on her hill, the last and smallest things painted+ const flower = (x: number, y: number, c: string, k: number) => { for (let i = 0; i < 5; i++) { const a = (i / 5) * Math.PI * 2 + k; S(ell(x + Math.cos(a) * 4.2, y + Math.sin(a) * 3.2, 3, 2.4, a, 8), c, 0); } S(ell(x, y, 2, 1.8, 0, 8), C.mustard, 0); };+ for (let i = 0; i < 16; i++) { const u = r(), cx = i < 9 ? 70 + u * 200 : 620 + u * 220, cy = i < 9 ? 900 + r() * 120 : 940 + r() * 90; flower(cx, cy, i % 3 ? C.white : C.pink, r() * 3); }+ // dry brush: sky, clouds, hills, grass, the dress's shade side+ [[60, 196, 250], [380, 132, 200], [720, 300, 220], [40, 420, 300], [460, 470, 160]].forEach(([x, y, l]) => D([[x, y], [x + l, y - 4]], 24, mix(C.board, "#ffffff", 0.5)));+ D([[130, 166], [330, 164]], 12, C.board); D([[540, 100], [650, 98]], 9, C.board);+ for (let i = 0; i < 6; i++) { const x = 20 + i * 120 + r() * 40, y = 600 + r() * 60 - i * 18; D([[x, y], [x + 120, y - 30]], 16, mix(C.far, C.dark, 0.25)); }+ for (let i = 0; i < 8; i++) { const x = 420 + i * 82, y = ys(x) - 30 + r() * 30; D([[x, y + 10], [x + 70, y - 18]], 14, C.villD); }+ // grass: flicks in drifts, dense along the crest and in the near corner, bare between+ const tuft = (cx: number, cy: number, n: number, sp: number) => { for (let i = 0; i < n; i++) { const x = cx + (r() - 0.5) * sp * 2, y = cy + (r() - 0.3) * sp * 0.5, l = 22 + r() * 18; D([[x, y + l * 0.5], [x + 4 + r() * 8, y - l * 0.5]], 12 + r() * 6, r() < 0.55 ? mix(C.fore, "#e2ecac", 0.45) : C.foreD); } };+ tuft(150, 850, 9, 110); tuft(560, 880, 6, 70); tuft(90, 990, 8, 90); tuft(820, 960, 7, 90); tuft(420, 1010, 5, 60); tuft(990, 1030, 5, 60);+ D([[380, 600], [398, 668]], 16, mix(C.red, C.dark, 0.3)); D([[365, 578], [372, 610]], 10, mix(C.red, C.dark, 0.3));++ // THE LINE, off register. The girl first, then the kite and its string, then the birds+ const hL = (pts: P[], w = 2.1) => L(pts, w);+ hL([[318, 509], [322, 497], [334, 490], [349, 492], [359, 501], [363, 513], [363, 519], [367, 523], [362, 527], [360, 532], [355, 538], [346, 542], [336, 542]], 2); // face contour with the nose+ hL([[346, 505], [358, 506], [363, 503]], 1.6); hL([[309, 505], [306, 520], [308, 536], [313, 548], [321, 550], [325, 541]], 1.9);+ hL([[344, 507], [349, 504], [355, 505]], 1.4); hL([[347, 535], [351, 537], [355, 535]], 1.4); hL([[323, 518], [327, 516], [329, 522], [326, 528]], 1.3);+ hL([[318, 558], [306, 565], [301, 580], [299, 600], [293, 630], [285, 662], [279, 687]], 2); hL([[279, 687], [300, 692], [320, 687], [339, 692], [359, 685], [379, 688], [399, 679], [414, 672]], 2.1); hL([[369, 565], [373, 577], [377, 598], [385, 624], [397, 652], [414, 672]], 2);+ hL([[321, 569], [333, 569], [338, 562], [343, 569], [355, 568]], 1.5);+ hL(armR.a.filter((_, i) => i % 2 === 0), 1.6); hL(armR.b.filter((_, i) => i % 2 === 0).slice(3), 1.6); hL(armL.a.filter((_, i) => i % 2 === 0).slice(2), 1.6); hL(armL.b.filter((_, i) => i % 2 === 0), 1.6);+ hL([[408, 466], [414, 459], [422, 458], [429, 462], [431, 471], [430, 481], [425, 489]], 1.6); hL([[410, 468], [414, 462], [419, 465], [423, 460], [428, 463]], 1.2); hL([[425, 474], [430, 475]], 1.1); hL([[424, 480], [429, 481]], 1.1); hL([[427, 470], [436, 466], [438, 472], [431, 477]], 1.3); // fist: knuckles, thumb over the string+ hL([F(0, -6.2), F(14, -7.8), F(28, -8.3)], 1.3); hL([F(3, 6.6), F(12, 12.5)], 1.2); hL([F(14, 6.8), F(27, 7.4)], 1.2);+ hL(legB.a.filter((_, i) => i % 2 === 0).slice(4), 1.7); hL(legB.b.filter((_, i) => i % 2 === 0).slice(3), 1.7); hL(legF.a.filter((_, i) => i % 2 === 0).slice(4), 1.7); hL(legF.b.filter((_, i) => i % 2 === 0).slice(3), 1.7);+ hL([[372, 721], [375, 726], [372, 731]], 1.2); // the front knee+ hL([[303, 772], [320, 770]], 1.4); hL([[377, 772], [394, 770]], 1.4); // sock tops+ hL([[316, 796], [331, 802], [338, 809], [334, 815], [306, 815], [299, 810]], 1.6); hL([[397, 796], [413, 802], [420, 809], [416, 815], [387, 815], [380, 810]], 1.6); hL([[304, 801], [318, 799]], 1.1); hL([[385, 801], [399, 799]], 1.1);+ hL([[301, 484], [315, 494], [299, 499]], 1.3); hL([[315, 493], [333, 482], [350, 478]], 1.2);+ L(sm([[423, 459], [520, 402], [640, 318], [770, 248], [826, 214]], false, 8), 1.1); // the string, sagging a little+ [[600, 150, 1], [640, 128, 0.8], [668, 162, 0.9]].forEach(([x, y, s]) => L([[x - 12 * s, y - 5 * s], [x - 5 * s, y - 2 * s], [x, y + 3 * s], [x + 6 * s, y - 3 * s], [x + 13 * s, y - 6 * s]], 1.4));++ // TIME. Paint big to small; dry brush in the order listed; line in the order listed+ const order = shapes.map((_, i) => i).sort((a, b) => area(shapes[b].pts) - area(shapes[a].pts));+ const span = (ws: number[], a: number, b: number): [number, number][] => { const tot = ws.reduce((x, y) => x + y, 0); let t = 0; return ws.map((w) => { const s: [number, number] = [a + ((b - a) * t) / tot, a + ((b - a) * (t + w)) / tot]; t += w; return s; }); };+ const pw = order.map((i) => 1.4 + Math.sqrt(area(shapes[i].pts)) / 22), pt = span(pw, T.paint[0], T.paint[1]), paintT: [number, number][] = shapes.map(() => [0, 0]);+ order.forEach((i, k) => (paintT[i] = pt[k]));+ const dryT = span(dry.map((d) => 1 + plen(d.path) / 70), T.dry[0], T.dry[1]);+ const lineT = span(lines.map((l) => 1.6 + plen(l.pts) / 60 + (l.pts.length < 5 && plen(l.pts) < 30 ? 0.8 : 0)), T.line[0], T.line[1]);+ return { shapes, dry, lines, order, paintT, dryT, lineT };+};++// ---------------------------------------------------------------- marks+// gouache edge: the flat brush leaves a slightly ragged boundary, sized to the shape+// (a polygon keeps its corners: a house is cut with a flat brush, not rounded into a pebble)+const dens = (s: P[]): P[] => s.flatMap((a, i) => { const b = s[(i + 1) % s.length], n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 4)); return Array.from({ length: n }, (_, k) => [a[0] + ((b[0] - a[0]) * k) / n, a[1] + ((b[1] - a[1]) * k) / n] as P); });+const edge = (s: Sh, i: number): P[] => { const a = Math.sqrt(area(s.pts)), amp = clamp(a * 0.011, 0.3, 2.6); return displace(dens(s.pts), amp, 0.11, 2, 40 + i); };+const trace = (c: Ctx, pts: P[]) => { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); };+// dry brush: bristles side by side, each broken where it skips the board's tooth, more and more+// as the brush runs out toward the end of the stroke+const dryBrush = (c: Ctx, d: Dry, q: number) => {+ const [a, b] = [d.path[0], d.path[d.path.length - 1]], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l, nb = Math.max(5, Math.round(d.w / 2.2)), steps = Math.max(6, Math.round(l / 3)), r = rng(d.seed);+ c.strokeStyle = d.col; c.lineWidth = 1.7; c.lineCap = "round"; c.globalAlpha = 0.85; c.beginPath();+ for (let k = 0; k < nb; k++) {+ const v = (k / (nb - 1) - 0.5) * d.w + (r() - 0.5) * 1.2, start = r() * 0.08, dens = 0.2 + r() * 0.14; let on = false;+ for (let j = 0; j <= steps * q; j++) {+ const t = j / steps; if (t < start) continue;+ const skip = fractal(d.seed + k, t * l * 0.35, k * 3.1, 1, 1, 2) < dens + t * 0.35, x = a[0] + dx * t + nx * v, y = a[1] + dy * t + ny * v;+ if (skip) { on = false; continue; } if (!on) { c.moveTo(x, y); on = true; } else c.lineTo(x, y);+ }+ }+ c.stroke(); c.globalAlpha = 1;+};++export const drawMidCentury = (ctx: Ctx, f: number, env: Env) => {+ const key = "midCentury:scene"; let sc = env.cache.get(key) as Scene | undefined; if (!sc) { sc = buildScene(); env.cache.set(key, sc); }+ const ek = "midCentury:edges"; let edges = env.cache.get(ek) as P[][] | undefined; if (!edges) { edges = sc.shapes.map((s, i) => edge(s, i)); env.cache.set(ek, edges); }+ const fin = f >= N - HOLD, at = (w: [number, number]) => (fin || f >= w[1] ? 1 : f <= w[0] ? 0 : (f - w[0]) / (w[1] - w[0]));+ const g = new Gfx(ctx, env, 0, BRUSH);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ ctx.fillStyle = C.board; ctx.fillRect(0, 0, W, H); // the bare board+ // flats, drawn in stacking order, each laid by the brush where it has been+ sc.shapes.forEach((s, i) => {+ const q = at(sc!.paintT[i]); if (q <= 0) return;+ ctx.save(); ctx.fillStyle = s.col;+ if (q < 1) { const a = Math.sqrt(area(s.pts)); streakClip(ctx, streaks([edges![i]], clamp(a / 5, 5, 58), s.ang, 60 + i, clamp(a * 0.9, 60, 340)), q); }+ trace(ctx, edges![i]); ctx.fill(); ctx.restore();+ });+ sc.dry.forEach((d, i) => { const q = at(sc!.dryT[i]); if (q > 0) dryBrush(ctx, d, q); });+ // the line plate, off register+ const lq = sc.lines.map((l, i) => at(sc!.lineT[i]));+ if (lq.some((q) => q > 0)) { g.push(REG[0], REG[1], 1); g.group("plain", () => sc!.lines.forEach((l, i) => { if (lq[i] > 0) g.pen(l.pts, { w: l.w, color: C.ink, seed: l.seed, wobble: 0.9, opacity: 0.92, progress: lq[i] >= 1 ? 1 : lq[i] }); })); g.pop(); }+ g.paper("coldpress", 0.16); // the board's tooth, under everything and through it+};++export const STYLE = { id: "midCentury", name: "Mid-century gouache", family: "1950s-60s storybook", medium: "opaque matte designer's gouache on warm illustration board, a dry brush dragged over the flats, a loose brush-and-ink line printed off register", nearest: "fox", hero: "a hillside village where a girl flies a kite" };++export const midCentury: Film = {+ meta: { title: "Mid-century gouache · the kite", W, H, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "board", start: 0, end: N, draw: drawMidCentury }],+};diff --git a/engine/src/canvas-core/miraComic.ts b/engine/src/canvas-core/miraComic.tsnew file mode 100644index 0000000..393385d--- /dev/null+++ b/engine/src/canvas-core/miraComic.ts@@ -0,0 +1,55 @@+// MIRA, MARKER COMIC. The same character module as the storybook sheet, in koi.ts's hand: flat+// cels, hard shadows, a brush-marker contour that swells away from the light. One panel: she is+// up on her crate, low angle, screwing a bulb back into the lamp that went out. Posed, not redrawn.+import { Gfx, PENCIL, type Ctx, type Env, type P } from "./core";+import type { Film } from "./film";+import { V3, add, camera, lensPx, project } from "./character/math3";+import { order, toPart } from "./character/build";+import { renderMarker, COMIC_INK } from "./character/render/marker";+import { blob, fillShape, ink, smooth } from "./gallery";+import { letter } from "./drafting";+import { mira } from "./characters/mira";+import { MIRA_MARKER } from "./characters/mira/palettes";+import { crate, reachOnCrate, screwdriver } from "./characters/mira/poses";+import { rng } from "./core";++const W = 1080, H = 1350;+const PAL = { ...MIRA_MARKER, crate: { base: "#c7773f", shade: "#8e4a20" }, toolRed: { base: "#ee3524", shade: "#b0170c" } };++export const drawMiraComic = (ctx: Ctx, frame: number, env: Env) => {+ const g = new Gfx(ctx, env, frame, PENCIL), yaw = -35;+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ const bulb: V3 = [-0.02, 1.9, 0.26];+ const p = reachOnCrate(yaw, add(bulb, [0.0, -0.1, 0.0]));+ // low angle, 30 mm: the crate and boots big, the head small against the ceiling+ const cam = camera([0.62, 0.5, 1.6], [0.02, 1.18, 0.05], lensPx(26, W), W * 0.5, H * 0.5);+ // ---- the room: a flat cel wall, a halftone burst behind her, the lamp on its cord+ g.group("plain", () => {+ fillShape(g, [[0, 0], [W, 0], [W, H], [0, H]], "#7fd3e8");+ const r = rng(9), c = project(cam, bulb);+ for (let i = 0; i < 26; i++) { const a = (i / 26) * Math.PI * 2 + r() * 0.1, a2 = a + 0.08; fillShape(g, [[c.x, c.y], [c.x + Math.cos(a) * 1600, c.y + Math.sin(a) * 1600], [c.x + Math.cos(a2) * 1600, c.y + Math.sin(a2) * 1600]], "#b6ecf5", 0.8); }+ const far = [[-4, 0, -2.5], [4, 0, -2.5]].map((q) => { const s = project(cam, q as V3); return [s.x, s.y] as P; }), fl: P[] = [...far, [W + 20, H + 20], [-20, H + 20]]; // the floor runs from its far edge to under the lens+ fillShape(g, fl, "#e0845a"); fillShape(g, fl.map(([x, y]) => [x, y + 6] as P), "#c96a45", 0.5);+ // the cord and the lamp shade+ const top = project(cam, [bulb[0], 3, bulb[2]]), socket = project(cam, add(bulb, [0, 0.09, 0])), b = project(cam, bulb);+ ink(g, [[top.x, top.y], [socket.x, socket.y]], COMIC_INK, { w: 5, shadow: 0 });+ const shade = smooth([[socket.x - 70, socket.y + 34], [socket.x - 36, socket.y - 18], [socket.x + 36, socket.y - 18], [socket.x + 70, socket.y + 34]], false, 8);+ fillShape(g, [...shade, [socket.x, socket.y + 44]], "#2f3f86"); ink(g, shade, COMIC_INK, { w: 6, shadow: 0.6 });+ fillShape(g, blob(b.x, b.y + 6, 30, 36, 3, 0.05, 14), "#fff5b8"); ink(g, blob(b.x, b.y + 6, 30, 36, 3, 0.05, 14), COMIC_INK, { w: 5, closed: true, shadow: 0.6 });+ });+ // ---- Mira and her crate, one scene, painted far to near+ const s = mira.toScene(p, cam), props = [...crate(yaw), ...screwdriver(p)].map((bp) => toPart(cam, bp));+ renderMarker(g, { ...s, parts: order([...s.parts, ...props]) }, PAL, { weight: 1.1 });+ // ---- the balloon and the panel+ g.group("plain", () => {+ const bx = 70, by = 70, bw = 470, bh = 150, tail: P[] = [[bx + 330, by + bh - 6], [bx + 420, by + bh + 90], [bx + 380, by + bh - 4]];+ fillShape(g, blob(bx + bw / 2, by + bh / 2, bw / 2, bh / 2, 21, 0.03, 20), "#ffffff"); fillShape(g, tail, "#ffffff");+ ink(g, blob(bx + bw / 2, by + bh / 2, bw / 2, bh / 2, 21, 0.03, 20), COMIC_INK, { w: 5, closed: true, shadow: 0.5 });+ ink(g, [tail[0], tail[1], tail[2]], COMIC_INK, { w: 4.5, shadow: 0.3, taper: [0.1, 0.1] });+ });+ letter(g, "ALMOST...", 140, 104, { cap: 40, color: COMIC_INK, seed: 5, w: 5.2, opacity: 1 });+ letter(g, "ONE MORE TURN", 120, 158, { cap: 30, color: COMIC_INK, seed: 6, w: 4.6, opacity: 1 });+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); c.strokeStyle = COMIC_INK; c.lineWidth = 16; c.strokeRect(8, 8, W - 16, H - 16); });+ g.paper("paper", 0.1);+};+export const miraComic: Film = { meta: { title: "Mira, marker comic", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "panel", start: 0, end: 1, draw: drawMiraComic }] };diff --git a/engine/src/canvas-core/miraEveryHand.ts b/engine/src/canvas-core/miraEveryHand.tsnew file mode 100644index 0000000..c9c222e--- /dev/null+++ b/engine/src/canvas-core/miraEveryHand.ts@@ -0,0 +1,60 @@+// MIRA IN EVERY HAND: the sheet. Nine tiles, one pose, one camera, one character module; under+// each tile the identity result for THAT hand (features that survived, palette roles inside+// their hue families, and for the grid hands the silhouette IoU). Tiles are drawn at full size by+// their own draw functions into an offscreen surface and set down, exactly as the style gallery.+import { GRAPHITE, Gfx, PENCIL, type Ctx, type Env } from "./core";+import type { Film } from "./film";+import { letter } from "./drafting";+import { HANDS, TH, TW, everyScene } from "./miraTile";+import { MIRA_FEATURES, MIRA_ROLES } from "./characters/mira";+import { MIRA_BRICK, MIRA_MARKER, MIRA_PENCIL, MIRA_PIXEL, MIRA_RISO, MIRA_SCRATCH, MIRA_STORYBOOK, MIRA_SUMI, MIRA_WOODCUT } from "./characters/mira/palettes";+import { gridFeatures, sceneFeatures } from "./character/identity";+import { paletteChecks, risoColour } from "./character/check";+import { DRUM } from "./character/render/riso";+import { pixelGrid } from "./character/render/pixel";+import { brickGrid } from "./character/render/brick";++const GUT = 44, LAB = 190, HEAD = 230, COLS = 3;+const W = COLS * TW + (COLS + 1) * GUT, H = HEAD + 3 * (TH + LAB) + 4 * GUT, SHEET = "#ece6da", MUTED = "#7a7066";++// the colour each hand actually puts down for each role+export const HAND_COLOURS = (): Record<string, Record<string, string>> => {+ const drum = Object.fromEntries(Object.entries(DRUM).map(([k, v]) => [k, v.col]));+ const base = (p: Record<string, { base: string }>) => Object.fromEntries(Object.entries(p).map(([k, v]) => [k, v.base]));+ const ramp0 = (p: Record<string, [string, string]>) => Object.fromEntries(Object.entries(p).map(([k, v]) => [k, v[0]]));+ return {+ woodcut: MIRA_WOODCUT, brick: ramp0(MIRA_BRICK.roles), pixel: ramp0(MIRA_PIXEL.roles), scratch: { ...MIRA_SCRATCH, hair: MIRA_SCRATCH.hair },+ pencil: base(MIRA_PENCIL), sumi: { ...Object.fromEntries(Object.entries(MIRA_SUMI).map(([k, v]) => [k, v[0]])), hair: "#3a2a24", glasses: "#c8412c" },+ marker: base(MIRA_MARKER), riso: Object.fromEntries(Object.entries(MIRA_RISO).map(([k, v]) => [k, risoColour(v.inks, drum)])), storybook: base(MIRA_STORYBOOK),+ };+};+export const handIdentity = (id: string) => {+ const s = everyScene(), grid = id === "pixel" ? pixelGrid(s, TW, TH, 10) : id === "brick" ? brickGrid(s, TW, TH, 15) : null;+ const feats = grid ? gridFeatures(grid, s) : sceneFeatures(s, MIRA_FEATURES);+ const cols = HAND_COLOURS()[id], roles = Object.fromEntries(Object.entries(MIRA_ROLES).filter(([r]) => cols[r])) as typeof MIRA_ROLES;+ const pal = paletteChecks("mira", roles, { [id]: cols });+ return { feats, pal };+};++export const drawMiraEveryHand = (ctx: Ctx, _f: number, env: Env) => {+ const s = env.scale; ctx.setTransform(s, 0, 0, s, 0, 0); ctx.fillStyle = SHEET; ctx.fillRect(0, 0, W, H);+ const sub: Env = { W: TW, H: TH, scale: s, cache: env.cache, canvas: env.canvas, image: env.image }, L = env.canvas(Math.round(TW * s), Math.round(TH * s)), g = new Gfx(ctx, env, 0, PENCIL);+ const scene = everyScene();+ HANDS.forEach((h, i) => {+ const col = i % COLS, row = Math.floor(i / COLS), x = GUT + col * (TW + GUT), y = HEAD + GUT + row * (TH + LAB + GUT);+ L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.globalAlpha = 1; L.ctx.globalCompositeOperation = "source-over"; L.ctx.clearRect(0, 0, L.canvas.width, L.canvas.height);+ h.draw(L.ctx, sub, scene);+ ctx.setTransform(s, 0, 0, s, 0, 0); ctx.fillStyle = "rgba(60,45,30,0.12)"; ctx.fillRect(x + 6, y + 9, TW, TH);+ ctx.imageSmoothingEnabled = h.id !== "pixel"; ctx.drawImage(L.canvas as CanvasImageSource, 0, 0, L.canvas.width, L.canvas.height, x, y, TW, TH); ctx.imageSmoothingEnabled = true;+ ctx.strokeStyle = "rgba(42,37,33,0.35)"; ctx.lineWidth = 1; ctx.strokeRect(x + 0.5, y + 0.5, TW - 1, TH - 1);+ const idn = handIdentity(h.id), okF = idn.feats.filter((f) => f.ok).length, okP = idn.pal.filter((p) => p.ok).length;+ letter(g, `${String(i + 1).padStart(2, "0")} ${h.name}`, x, y + TH + 26, { cap: 28, color: GRAPHITE, seed: 900 + i, w: 2.6 });+ letter(g, h.note.toUpperCase(), x, y + TH + 70, { cap: 15, color: MUTED, seed: 920 + i, w: 1.5 });+ letter(g, `IDENTITY ${okF}/${idn.feats.length} PALETTE ROLES ${okP}/${idn.pal.length} IN FAMILY`, x, y + TH + 104, { cap: 17, color: okF === idn.feats.length && okP === idn.pal.length ? "#3d6b3a" : "#b3372a", seed: 940 + i, w: 1.8 });+ const miss = idn.feats.filter((f) => !f.ok).map((f) => f.feature), iou = idn.feats.find((f) => f.feature === "silhouette");+ letter(g, (miss.length ? "MISSING: " + miss.join(", ").toUpperCase() : "ALL FEATURES PRESENT") + (iou ? ` ${iou.got.toUpperCase()}` : " SAME SCENE GEOMETRY"), x, y + TH + 138, { cap: 14, color: MUTED, seed: 960 + i, w: 1.4 });+ });+ letter(g, "MIRA IN EVERY HAND", GUT, 60, { cap: 60, color: GRAPHITE, seed: 1, w: 4.6 });+ letter(g, "ONE CHARACTER MODULE, ONE POSE, ONE CAMERA. EACH HAND MAKES HER IN ITS OWN MARKS; BRICKS AND PIXELS REBUILD HER IN THEIR OWN UNITS.", GUT, 150, { cap: 19, color: MUTED, seed: 2, w: 1.7 });+};+export const miraEveryHand: Film = { meta: { title: "Mira in every hand", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "sheet", start: 0, end: 1, draw: drawMiraEveryHand }] };diff --git a/engine/src/canvas-core/miraRiso.ts b/engine/src/canvas-core/miraRiso.tsnew file mode 100644index 0000000..8f75ce1--- /dev/null+++ b/engine/src/canvas-core/miraRiso.ts@@ -0,0 +1,42 @@+// MIRA, RISOGRAPH. The same character module in lighthouse.ts's hand: three drums (yellow,+// fluorescent pink, blue) overprinted by multiply through their own registration, tone as+// halftone screens, knockouts to bare paper, a blue litho-crayon line. A poster: she sits on+// her crate holding a gear up to the light. Her roles are recipes of drums (MIRA_RISO).+import { Gfx, PENCIL, type Ctx, type Env, type P, halftone, oval } from "./core";+import type { Film } from "./film";+import { camera, lensPx, project } from "./character/math3";+import { order, toPart } from "./character/build";+import { renderRiso } from "./character/render/riso";+import { letter } from "./drafting";+import { mira } from "./characters/mira";+import { MIRA_RISO } from "./characters/mira/palettes";+import { crate, gearInPinch, gearToEye } from "./characters/mira/poses";++const W = 1080, H = 1350, PAPER = "#f5efe2";+const RECIPES = { ...MIRA_RISO, crate: { inks: [["pink", 0.45], ["yellow", 0.7], ["blue", 0.12]] as [string, number][], shadeInk: "blue", shadeTone: 0.35 } };++export const drawMiraRiso = (ctx: Ctx, frame: number, env: Env) => {+ const g = new Gfx(ctx, env, frame, PENCIL), yaw = -50;+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H);+ const p = gearToEye(yaw), cam = camera([-0.35, 0.75, 2.05], [0.05, 0.56, 0], lensPx(40, W), W * 0.54, H * 0.6);+ const s = mira.toScene(p, cam), props = [...crate(yaw), gearInPinch(p)].map((b) => toPart(cam, b));+ renderRiso(g, env, { ...s, parts: order([...s.parts, ...props]) }, RECIPES, {+ pitch: 6,+ before: (d) => {+ // a pink sun behind her (screened darker toward its lower edge), a blue floor, the title in blue+ const sun = oval(560, 470, 360, 360, 40), c = d.pink; c.save(); c.beginPath(); sun.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.clip(); c.fillStyle = "#000"; c.beginPath();+ halftone({ x0: 180, y0: 100, x1: 940, y1: 850 }, 7, 62, (_x, y) => 0.25 + 0.55 * ((y - 110) / 740)).forEach(([x, y, r]) => { c.moveTo(x + r, y); c.arc(x, y, r, 0, Math.PI * 2); }); c.fill(); c.restore();+ const fy = project(cam, [0, 0, 0]).y, b = d.blue; b.fillStyle = "#000"; b.beginPath();+ halftone({ x0: 0, y0: fy - 30, x1: W, y1: H }, 7, 12, (_x, y) => 0.18 + 0.5 * Math.min(1, (y - fy + 30) / 400)).forEach(([x, y, r]) => { b.moveTo(x + r, y); b.arc(x, y, r, 0, Math.PI * 2); }); b.fill();+ const prev = g.cur; g.cur = b;+ letter(g, "MIRA", 70, 70, { cap: 120, color: "#000", seed: 3, w: 11, opacity: 1 });+ letter(g, "SMALL INVENTOR, BIG IDEAS", 76, 230, { cap: 30, color: "#000", seed: 4, w: 3.4, opacity: 1 });+ g.cur = d.yellow; letter(g, "NO. 1", 880, 1250, { cap: 44, color: "#000", seed: 5, w: 5, opacity: 1 }); g.cur = prev;+ [[980, 120], [920, 190], [1010, 230]].forEach(([x, y]) => { const q: P[] = oval(x, y, 9, 9, 10); b.beginPath(); q.forEach(([a, e], i) => (i ? b.lineTo(a, e) : b.moveTo(a, e))); b.fill(); });+ },+ });+ // what the printer leaves in the margin+ g.group("plain", () => { const c = g.cur; g.touch(0, 0, W, H); c.strokeStyle = "#1b1b1b"; c.lineWidth = 1.1; [[26, 26], [W - 26, 26], [26, H - 26], [W - 26, H - 26]].forEach(([x, y]) => { c.beginPath(); c.arc(x, y, 7, 0, Math.PI * 2); c.moveTo(x - 12, y); c.lineTo(x + 12, y); c.moveTo(x, y - 12); c.lineTo(x, y + 12); c.stroke(); }); }, { alpha: 0.9 });+ g.paper("paper", 0.26); g.paper("coldpress", 0.14);+};+export const miraRiso: Film = { meta: { title: "Mira, risograph", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "poster", start: 0, end: 1, draw: drawMiraRiso }] };diff --git a/engine/src/canvas-core/miraSheet.ts b/engine/src/canvas-core/miraSheet.tsnew file mode 100644index 0000000..6fe7287--- /dev/null+++ b/engine/src/canvas-core/miraSheet.ts@@ -0,0 +1,89 @@+// MIRA'S MODEL SHEET, v1.0.0: the character's specimen plate and its ONE approval artifact.+// Turnaround (front, three-quarter, profile, back), six expressions, six poses, six hands and a+// scale line-up, in storybook pencil + watercolour. Every figure on it is mira.toScene(pose):+// nothing on this sheet is drawn by hand for the sheet.+import { GRAPHITE, Gfx, PENCIL, type Ctx, type Env, type P } from "./core";+import type { Film } from "./film";+import { Camera, add, apply, camera, project } from "./character/math3";+import type { Pose, Scene } from "./character/types";+import { renderStorybook } from "./character/render/storybook";+import { letter } from "./drafting";+import { mira, MIRA_VERSION, MIRA_FEATURES } from "./characters/mira";+import { MIRA_STORYBOOK } from "./characters/mira/palettes";+import { MIRA_DIMS, base, crate, crouch, gear, reachUp, relaxed, screwdriver, sitCrate, strapStand, walkContact, wave } from "./characters/mira/poses";+import { theo, THEO_PALETTE } from "./characters/theo";+import { relaxed as theoRelaxed } from "./characters/theo/poses";+import { EXPRESSIONS } from "./character/human/head";+import { rigFor } from "./character/human/figure";+import { MIRA_SPEC } from "./characters/mira";+import { order, toPart, type BlobPart } from "./character/build";++const W = 3600, H = 4500, SHEET = "#f7f1e3", MUTED = "#8a7f72";+const PAL = { ...MIRA_STORYBOOK, crate: { base: "#c9955e", shade: "#94683d" }, toolRed: { base: "#d8443a", shade: "#a52f28" }, ...THEO_PALETTE, skin: MIRA_STORYBOOK.skin, hair: MIRA_STORYBOOK.hair, nail: MIRA_STORYBOOK.nail };+const label = (g: Gfx, t: string, x: number, y: number, cap = 26, color = GRAPHITE, align: "left" | "center" = "left") => letter(g, t, x, y, { cap, color, seed: t.length * 7 + Math.round(x), w: cap / 11, opacity: 0.9, align });+const fullCam = (cx: number, floorY: number, figPx: number, height = 1.3, elev = 0): Camera => { const d = 12, f = (figPx * d) / height; return camera([0, height * 0.52 + elev, d], [0, height * 0.52, 0], f, cx, floorY - figPx * 0.52); };+const withProps = (s: Scene, cam: Camera, props: BlobPart[]): Scene => ({ ...s, parts: order([...s.parts, ...props.map((b) => toPart(cam, b))]) });+const cell = (ctx: Ctx, env: Env, g: Gfx, x: number, y: number, w: number, h: number, fn: () => void) => {+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip(); fn(); ctx.restore();+ g.group("ink", () => ([[[x, y], [x + w, y]], [[x + w, y], [x + w, y + h]], [[x + w, y + h], [x, y + h]], [[x, y + h], [x, y]]] as P[][]).forEach((l, i) => g.pen(l, { w: 1.1, color: MUTED, seed: x + y + i, wobble: 0.5, opacity: 0.45, retrace: false })));+};++export const drawMiraSheet = (ctx: Ctx, frame: number, env: Env) => {+ const g = new Gfx(ctx, env, frame, PENCIL);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = SHEET; ctx.fillRect(0, 0, W, H);+ label(g, `MIRA / MODEL SHEET / V${MIRA_VERSION}`, 90, 60, 50);+ label(g, "NINE-YEAR-OLD INVENTOR. STORYBOOK CANON 5.2 HEADS (A DECLARED ENLARGEMENT OF A REAL 6.2-HEAD CHILD), 1.30 M", 90, 134, 20, MUTED);+ label(g, "EVERY FIGURE HERE IS MIRA.TOSCENE(POSE) FROM ONE MODULE. SHOTS POSE HER; NOTHING REDRAWS HER.", 90, 168, 20, MUTED);+ // ---- turnaround, with head rules+ label(g, "1 TURNAROUND", 90, 240, 30);+ const turnCams = [0, 1, 2, 3].map((i) => fullCam(470 + i * 740, 1330, 980));+ g.group("ink", () => { for (let i = 0; i <= 5; i++) { const hgt = Math.min(i, 5.2) * MIRA_DIMS.hh, y = project(turnCams[0], [0, hgt, 0]).y; g.pen([[150, y], [3060, y]], { w: 0.9, color: "#9aa3b5", seed: 300 + i, wobble: 0.4, opacity: 0.5, retrace: false }); label(g, String(i), 110, y - 9, 14, "#9aa3b5"); } const yt = project(turnCams[0], [0, 5.2 * MIRA_DIMS.hh, 0]).y; g.pen([[150, yt], [3060, yt]], { w: 1.1, color: "#9aa3b5", seed: 309, wobble: 0.4, opacity: 0.55, retrace: false }); label(g, "5.2", 96, yt - 9, 14, "#9aa3b5"); });+ [0, 40, 90, 180].forEach((yaw, i) => { renderStorybook(g, mira.toScene(relaxed(yaw), turnCams[i]), PAL); label(g, ["FRONT", "THREE-QUARTER", "PROFILE", "BACK"][i], 470 + i * 740, 1370, 22, MUTED, "center"); });+ // the identity card: what must be present in every shot+ label(g, "IDENTITY", 3150, 300, 24);+ const wrap = (s: string, n: number) => s.split(" ").reduce<string[]>((a, w) => { const l = a[a.length - 1]; if (l !== undefined && (l + " " + w).length <= n) a[a.length - 1] = l + " " + w; else a.push(w); return a; }, []);+ MIRA_FEATURES.forEach((f, i) => { label(g, f.id.toUpperCase(), 3150, 350 + i * 118, 18); wrap(f.note.toUpperCase(), 28).slice(0, 3).forEach((ln, k) => label(g, ln, 3150, 380 + i * 118 + k * 20, 12, MUTED)); });+ // ---- expressions+ label(g, "2 EXPRESSIONS", 90, 1450, 30);+ ["neutral", "happy", "laughing", "surprised", "worried", "determined"].forEach((ex, i) => {+ const x = 120 + i * 560;+ cell(ctx, env, g, x, 1510, 520, 560, () => { const p = base(i % 2 ? 22 : -18, { headTilt: [0, 4, -6, 0, 5, -3][i] }, EXPRESSIONS[ex]), r = rigFor(MIRA_SPEC, p), t = add(r.joints.head, [0, 0.07, 0]), cam = camera(add(t, [0, 0.03, 1.6]), t, 2300, x + 260, 1790); renderStorybook(g, mira.toScene(p, cam), PAL); });+ label(g, ex.toUpperCase(), x + 260, 2090, 20, MUTED, "center");+ });+ // ---- poses+ label(g, "3 POSES", 90, 2180, 30);+ const poses: [string, Pose, BlobPart[]][] = [["WEIGHT ON ONE LEG", strapStand(-25), []], ["WALKING, CONTACT", walkContact(70), []], ["ON TIPTOE, REACHING", reachUp(30), []], ["SITTING ON A CRATE", sitCrate(-40), crate(-40)], ["CROUCHED, TINKERING", crouch(35), []], ["WAVING", wave(-15, 0.8), []]];+ poses.forEach(([name, p, props], i) => {+ const x = 330 + i * 560, cam = fullCam(x, 3060, 760);+ const extra = name.startsWith("CROUCHED") ? [...screwdriver(p), ...gear(p)] : props;+ renderStorybook(g, withProps(mira.toScene(p, cam), cam, extra), PAL);+ label(g, name, x, 3100, 18, MUTED, "center");+ });+ // ---- hands+ label(g, "4 HANDS (RIGHT)", 90, 3200, 30);+ const handPoses: [string, string][] = [["RELAXED", "relaxed"], ["OPEN", "open"], ["POINT", "point"], ["FIST", "fist"], ["GRIP", "grip"], ["PINCH", "pinch"]];+ handPoses.forEach(([name, hp], i) => {+ const x = 120 + (i % 3) * 700, y = 3260 + Math.floor(i / 3) * 600;+ cell(ctx, env, g, x, y, 660, 540, () => {+ const p: Pose = { ...base(0, { shoulderRaiseR: 70, shoulderSwingR: 80, elbowR: 70, pronationR: 30, shoulderTwistR: -10 }), hands: { L: "relaxed", R: hp } };+ const r = rigFor(MIRA_SPEC, p), hc = apply(r.hand.R, [0, -0.4 * MIRA_DIMS.hand, 0]), cam = camera(add(hc, [-0.07, 0.1, 0.24]), hc, 1050, x + 330, y + 270);+ const props = hp === "grip" ? screwdriver(p) : [];+ const s = withProps(mira.toScene(p, cam), cam, props);+ renderStorybook(g, { ...s, parts: s.parts.filter((q) => /^(palm|thumb|index|middle|ring|little)R$|^driver/.test(q.id)), ground: null }, PAL);+ });+ label(g, name, x + 330, y + 555, 18, MUTED, "center");+ });+ // ---- scale line-up+ label(g, "5 SCALE", 2250, 3200, 30);+ cell(ctx, env, g, 2250, 3260, 1250, 1140, () => {+ const cam = (cx: number) => { const d = 16, f = (860 * d) / 1.78; return camera([0, 0.9, d], [0, 0.9, 0], f, cx, 4200 - 860 * 0.9 / 1.78); };+ const cm = cam(2600), ct = cam(3060);+ g.group("ink", () => { [0, 1.3, 1.78].forEach((hgt, i) => { const y = project(cm, [0, hgt, 0]).y; g.pen([[2280, y], [3470, y]], { w: 0.9, color: "#9aa3b5", seed: 500 + i, wobble: 0.4, opacity: 0.5, retrace: false }); }); });+ renderStorybook(g, mira.toScene(relaxed(15, { smile: 0.4 }), cm), PAL);+ renderStorybook(g, theo.toScene(theoRelaxed(-15), ct), PAL);+ label(g, "MIRA 1.30 M", 2600, 4250, 18, MUTED, "center"); label(g, "5.2 HEADS", 2600, 4278, 14, MUTED, "center");+ label(g, "THEO 1.78 M", 3060, 4250, 18, MUTED, "center"); label(g, "7.5 HEADS", 3060, 4278, 14, MUTED, "center");+ });+ g.paper("paper", 0.12); g.paper("coldpress", 0.12);+};+export const miraSheet: Film = { meta: { title: "Mira model sheet", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "sheet", start: 0, end: 1, draw: drawMiraSheet }] };diff --git a/engine/src/canvas-core/miraTile.ts b/engine/src/canvas-core/miraTile.tsnew file mode 100644index 0000000..ea99dd6--- /dev/null+++ b/engine/src/canvas-core/miraTile.ts@@ -0,0 +1,47 @@+// MIRA IN EVERY HAND: one pose, one camera, one Scene from the one character module, and nine+// hands that each make her in their own marks. Line hands (storybook, marker, riso, woodcut,+// scratchboard, sumi-e, coloured pencil) draw her contour their way; pixel art and toy bricks+// RE-EXPRESS her in their units (a sprite; a studs-out build with round red tiles for glasses).+// Each shot is one tile at full size; miraEveryHand.ts lays them out as one sheet.+import { Gfx, PENCIL, type Ctx, type Env, halftone } from "./core";+import type { Film } from "./film";+import { camera, project } from "./character/math3";+import type { Scene } from "./character/types";+import { renderStorybook } from "./character/render/storybook";+import { renderMarker } from "./character/render/marker";+import { renderRiso } from "./character/render/riso";+import { renderWoodcut } from "./character/render/woodcut";+import { renderScratch } from "./character/render/scratch";+import { renderSumi } from "./character/render/sumi";+import { renderPencil } from "./character/render/pencil";+import { renderPixel } from "./character/render/pixel";+import { renderBrick } from "./character/render/brick";+import { mira } from "./characters/mira";+import { MIRA_BRICK, MIRA_MARKER, MIRA_PENCIL, MIRA_PIXEL, MIRA_RISO, MIRA_SCRATCH, MIRA_STORYBOOK, MIRA_SUMI, MIRA_WOODCUT } from "./characters/mira/palettes";+import { wave } from "./characters/mira/poses";++export const TW = 900, TH = 1200;+export const EVERY_POSE = wave(-20, 0.8);+export const everyCam = () => camera([0, 0.8, 5.2], [0, 0.7, 0], 3500, TW / 2, TH * 0.5);+export const everyScene = (): Scene => mira.toScene(EVERY_POSE, everyCam());+export const HORIZON = () => project(everyCam(), [0, 0, -2.4]).y;++type Hand = { id: string; name: string; note: string; draw: (ctx: Ctx, env: Env, s: Scene) => void };+const plain = (ctx: Ctx, env: Env, col: string) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = col; ctx.fillRect(0, 0, env.W, env.H); };+export const HANDS: Hand[] = [+ { id: "woodcut", name: "WOODCUT", note: "ukiyo-e: colour blocks, key-block knife line", draw: (ctx, env, s) => renderWoodcut(new Gfx(ctx, env, 0, PENCIL), env, s, MIRA_WOODCUT, { horizon: HORIZON(), sky: "#3b5f8f", ground: "#d9c8a0" }) },+ { id: "brick", name: "TOY BRICK", note: "studs-out build, round tiles for eyes and glasses", draw: (ctx, env, s) => renderBrick(new Gfx(ctx, env, 0, PENCIL), env, s, MIRA_BRICK, { cell: 15, horizon: HORIZON() }) },+ { id: "pixel", name: "PIXEL ART", note: "a sprite: ramps, outline, features as single pixels", draw: (ctx, env, s) => renderPixel(new Gfx(ctx, env, 0, PENCIL), env, s, MIRA_PIXEL, { cell: 10, horizon: HORIZON() }) },+ { id: "scratch", name: "SCRATCHBOARD", note: "scraped cross-contour, tinted", draw: (ctx, env, s) => renderScratch(new Gfx(ctx, env, 0, PENCIL), env, s, MIRA_SCRATCH, { horizon: HORIZON() }) },+ { id: "pencil", name: "COLOURED PENCIL", note: "hatched local colour, cross-hatched shade", draw: (ctx, env, s) => renderPencil(new Gfx(ctx, env, 0, PENCIL), env, s, MIRA_PENCIL, { horizon: HORIZON(), ground: "#7fae6a" }) },+ { id: "sumi", name: "SUMI-E", note: "ink and light colour, brush contours", draw: (ctx, env, s) => renderSumi(new Gfx(ctx, env, 0, PENCIL), env, s, MIRA_SUMI, { horizon: HORIZON() }) },+ { id: "marker", name: "MARKER COMIC", note: "flat cels, hard shadow, swelling ink", draw: (ctx, env, s) => { plain(ctx, env, "#8fd6e6"); const g = new Gfx(ctx, env, 0, PENCIL), c = g.cur; g.group("plain", () => { g.touch(0, 0, env.W, env.H); c.fillStyle = "#6cc2d4"; c.beginPath(); halftone({ x0: 0, y0: 0, x1: env.W, y1: env.H }, 16, 45, (_x, y) => 0.15 + 0.35 * (y / env.H)).forEach(([x, y, r]) => { c.moveTo(x + r, y); c.arc(x, y, r, 0, Math.PI * 2); }); c.fill(); c.fillStyle = "#f2c9a0"; c.fillRect(0, HORIZON(), env.W, env.H); }); renderMarker(g, s, MIRA_MARKER, { weight: 1.1 }); } },+ { id: "riso", name: "RISOGRAPH", note: "three drums, halftone, knockouts", draw: (ctx, env, s) => { plain(ctx, env, "#f5efe2"); const g = new Gfx(ctx, env, 0, PENCIL); renderRiso(g, env, s, MIRA_RISO, { before: (d) => { const b = d.blue, h = HORIZON(); b.fillStyle = "#000"; b.beginPath(); halftone({ x0: 0, y0: h, x1: env.W, y1: env.H }, 8, 12, (_x, y) => 0.12 + 0.4 * Math.min(1, (y - h) / 300)).forEach(([x, y, r]) => { b.moveTo(x + r, y); b.arc(x, y, r, 0, Math.PI * 2); }); b.fill(); } }); g.paper("paper", 0.24); g.paper("coldpress", 0.1); } },+ { id: "storybook", name: "STORYBOOK", note: "pencil and watercolour (the approved sheet's hand)", draw: (ctx, env, s) => { plain(ctx, env, "#fbf6ea"); const g = new Gfx(ctx, env, 0, PENCIL); g.group("paint", () => g.wash([[30, HORIZON()], [env.W - 30, HORIZON() - 10], [env.W - 20, env.H - 40], [40, env.H - 30]], "#a9cfa6", { alpha: 0.5, seed: 4 })); renderStorybook(g, s, MIRA_STORYBOOK); g.paper("paper", 0.12); } },+];++export const miraTile: Film = {+ meta: { title: "Mira, one hand per tile", W: TW, H: TH, fps: 30, bpm: 120, durationFrames: HANDS.length * 15 },+ assets: { images: {} },+ shots: HANDS.map((h, i) => ({ id: h.id, start: i * 15, end: i * 15 + 15, draw: (ctx: Ctx, _f: number, env: Env) => h.draw(ctx, env, everyScene()) })),+};diff --git a/engine/src/canvas-core/miraTriptych.ts b/engine/src/canvas-core/miraTriptych.tsnew file mode 100644index 0000000..fe01421--- /dev/null+++ b/engine/src/canvas-core/miraTriptych.ts@@ -0,0 +1,37 @@+// IDENTITY TRIPTYCH: one pose, one camera, one Scene, three hands. The geometry handed to each+// renderer is byte-identical (the character gate asserts it); only the marks change. If she+// reads as three different girls here, the hands are wrong, not the character.+import { GRAPHITE, Gfx, PENCIL, type Ctx, type Env } from "./core";+import type { Film } from "./film";+import { camera } from "./character/math3";+import { renderStorybook } from "./character/render/storybook";+import { renderMarker } from "./character/render/marker";+import { renderRiso } from "./character/render/riso";+import { letter } from "./drafting";+import { mira } from "./characters/mira";+import { MIRA_MARKER, MIRA_RISO, MIRA_STORYBOOK } from "./characters/mira/palettes";+import { wave } from "./characters/mira/poses";++const PW = 900, PH = 1200, GUT = 40, W = PW * 3 + GUT * 4, H = PH + 220;++export const drawMiraTriptych = (ctx: Ctx, frame: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = "#ece6da"; ctx.fillRect(0, 0, W, H);+ const pose = wave(-20, 0.8), sub: Env = { W: PW, H: PH, scale: env.scale, cache: env.cache, canvas: env.canvas, image: env.image };+ const L = env.canvas(Math.round(PW * env.scale), Math.round(PH * env.scale));+ const cam = camera([0, 0.8, 5.2], [0, 0.7, 0], 3500, PW / 2, PH * 0.52), scene = mira.toScene(pose, cam);+ const hands: [string, string, (g: Gfx, e: Env) => void][] = [+ ["STORYBOOK", "#fbf6ea", (g) => renderStorybook(g, scene, MIRA_STORYBOOK)],+ ["MARKER COMIC", "#8fd6e6", (g) => renderMarker(g, scene, MIRA_MARKER)],+ ["RISOGRAPH", "#f5efe2", (g, e) => renderRiso(g, e, scene, MIRA_RISO)],+ ];+ const top = new Gfx(ctx, env, frame, PENCIL);+ hands.forEach(([name, paper, draw], i) => {+ L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.globalAlpha = 1; L.ctx.globalCompositeOperation = "source-over"; L.ctx.clearRect(0, 0, L.canvas.width, L.canvas.height);+ L.ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); L.ctx.fillStyle = paper; L.ctx.fillRect(0, 0, PW, PH);+ const g = new Gfx(L.ctx, sub, frame, PENCIL); draw(g, sub); g.paper("paper", 0.12);+ const x = GUT + i * (PW + GUT); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.drawImage(L.canvas as CanvasImageSource, 0, 0, L.canvas.width, L.canvas.height, x, 140, PW, PH);+ letter(top, name, x + PW / 2, PH + 170, { cap: 30, color: GRAPHITE, seed: 40 + i, w: 2.8, align: "center" });+ });+ letter(top, "MIRA V1.0.0 / ONE POSE, ONE SCENE, THREE HANDS", GUT, 50, { cap: 40, color: GRAPHITE, seed: 7, w: 3.4 });+};+export const miraTriptych: Film = { meta: { title: "Mira identity triptych", W, H, fps: 30, bpm: 120, durationFrames: 1 }, assets: { images: {} }, shots: [{ id: "triptych", start: 0, end: 1, draw: drawMiraTriptych }] };diff --git a/engine/src/canvas-core/miraWalk.ts b/engine/src/canvas-core/miraWalk.tsnew file mode 100644index 0000000..dc32656--- /dev/null+++ b/engine/src/canvas-core/miraWalk.ts@@ -0,0 +1,93 @@+// MIRA WALKS IN. 8 s at 30 fps, storybook pencil + watercolour. She walks in from the left on a+// diagonal toward us, heel strikes landing on the beat (120 bpm = a step every 15 frames), brings+// her feet together, turns her head to the camera with a blink, and waves.+//+// Everything is posed from the one character module; the walk comes from footsteps+// (character/human/walk.ts), so a planted foot never slides. One cue table holds every frame+// number, checked at load against the 15-frame beat grid.+import { Gfx, PENCIL, type Ctx, type Env, oval } from "./core";+import type { Film } from "./film";+import { V3, add, camera, dot, lensPx, mul, mv, norm, project, sub } from "./character/math3";+import { rigFor } from "./character/human/figure";+import { MIRA_SPEC } from "./characters/mira";+import type { Pose } from "./character/types";+import { renderStorybook } from "./character/render/storybook";+import { mira } from "./characters/mira";+import { MIRA_STORYBOOK } from "./characters/mira/palettes";+import { MIRA_DIMS, base } from "./characters/mira/poses";+import { planWalk, walkAt } from "./character/human/walk";++const W = 1920, H = 1080, FPS = 30, N = 240;+// ---- the cue table: every event on the grid (beats of 15 frames, events on multiples of 5)+export const CUES = { walkIn: 0, lastStep: 105, feetTogether: 120, settled: 135, headTurn: 135, blink: 145, armUp: 180, waveStart: 195, hi: 200, waveEnd: 240 } as const;+Object.entries(CUES).forEach(([k, f]) => { if (f % 5) throw new Error(`cue ${k} at ${f} is off the 5-frame event grid`); });+[CUES.walkIn, CUES.feetTogether, CUES.headTurn, CUES.armUp, CUES.waveStart].forEach((f) => { if (f % 15) throw new Error(`beat cue at ${f} is off the 15-frame beat`); });++const YAW = 70, DIR: V3 = [Math.sin((YAW * Math.PI) / 180), 0, Math.cos((YAW * Math.PI) / 180)];+const PLAN = planWalk({ t0: CUES.walkIn, s0: 0, step: 0.4, cycle: 30, n: 8, first: "L", lateral: 0.065 });+const S_END = PLAN.rootS(1e6), ORIGIN: V3 = mul(DIR, -S_END); // she stops at the world origin+const EYE0: V3 = [0.55, 0.82, 4.6], TARGET: V3 = [-0.05, 0.63, 0];+const ease = (u: number) => { const t = Math.max(0, Math.min(1, u)); return t * t * (3 - 2 * t); };+const span = (f: number, a: number, b: number) => ease((f - a) / (b - a));++export const miraAt = (f: number): Pose => {+ const w = walkAt(MIRA_DIMS, PLAN, f, base(YAW, {}, {}), { origin: ORIGIN, dir: DIR });+ const p = w.pose, j = { ...p.joints };+ // after the stop: breathing, the head coming round to camera, then the wave+ const settle = span(f, CUES.lastStep, CUES.settled), turn = span(f, CUES.headTurn, CUES.headTurn + 30), up = span(f, CUES.armUp, CUES.armUp + 16);+ const breath = Math.sin(((f - CUES.settled) / 45) * Math.PI * 2) * settle;+ j.spineBend = (j.spineBend ?? 0) + 1.2 * breath;+ j.spineTwist = (j.spineTwist ?? 0) - 16 * turn; j.neckTwist = (j.neckTwist ?? 0) - 26 * turn; j.headTurn = -8 * turn;+ j.headTilt = 7 * up + 2 * breath * (1 - up);+ // the wave: the upper arm lifts, then the forearm rocks at 2 Hz; the hand follows 3 frames late+ const rock = (ff: number) => Math.sin(((ff - CUES.waveStart) / 15) * Math.PI * 2) * span(ff, CUES.waveStart - 5, CUES.waveStart + 5);+ const lerp = (a: number, b: number, t: number) => a + (b - a) * t;+ // she waves with her LEFT hand: the far arm, so from this camera the hand clears her face+ j.shoulderRaiseL = lerp(j.shoulderRaiseL ?? 12, 124, up); j.shoulderSwingL = lerp(j.shoulderSwingL ?? 20, 12, up); j.shoulderTwistL = 34 * up;+ j.elbowL = lerp(j.elbowL ?? 16, 62, up) + 16 * rock(f); j.pronationL = 25 * up; j.wristDevL = -10 * rock(f - 3); j.clavLiftL = 12 * up;+ j.spineSide = 4 * up; j.shoulderRaiseR = lerp(j.shoulderRaiseR ?? 12, 10, up);+ // a wave SHOWS the palm: turn the forearm (within its range) until the palm faces the lens+ if (up > 0) {+ let best = 0, bestDot = -2;+ for (let pr = -80; pr <= 80; pr += 5) { const r = rigFor(MIRA_SPEC, { ...p, joints: { ...j, pronationL: pr } }), n = mv(r.hand.L.R, [-1, 0, 0]), d = dot(n, norm(sub(EYE0, r.joints.wristL))); if (d > bestDot) { bestDot = d; best = pr; } }+ j.pronationL = 25 * (1 - up) + best * up;+ }+ // the face: a blink rides the head turn; the smile grows; she says "hi"+ const blink = f >= CUES.blink && f < CUES.blink + 5 ? Math.sin(((f - CUES.blink) / 5) * Math.PI) : 0;+ const hi = f >= CUES.hi && f < CUES.hi + 18 ? Math.sin(((f - CUES.hi) / 18) * Math.PI) : 0;+ const ex = { smile: 0.25 + 0.7 * turn, cheek: 0.6 * turn, lidLower: 0.2 * turn, browRaise: 0.35 * up, lidUpper: blink, mouthOpen: 0.45 * hi, lookX: -0.35 * turn * 0 };+ return { ...p, joints: j, expression: ex, hands: { R: "relaxed", L: up > 0.5 ? "wave" : { relaxed: 1 - up * 2 + 1e-3, wave: up * 2 + 1e-3 } }, aux: { bagSwing: 9 * Math.sin(2 * Math.PI * w.phase * 2 - 0.9) * w.amp + 6 * Math.exp(-(f - CUES.feetTogether) / 12) * Math.sin((f - CUES.feetTogether) / 3.5) * (f > CUES.feetTogether ? 1 : 0) } };+};++const drawWorld = (g: Gfx, cam: ReturnType<typeof camera>) => {+ const P = (v: V3) => { const q = project(cam, v); return [q.x, q.y] as [number, number]; };+ g.group("paint", () => {+ g.wash([[-40, -40], [W + 40, -40], [W + 40, P([0, 0, -9])[1] + 10], [-40, P([0, 0, -9])[1] + 10]], "#cfe2ee", { alpha: 0.55, seed: 2, dx: 0, dy: 0, shrink: 1, rim: false });+ g.wash(oval(W * 0.72, 180, 170, 140, 10), "#fbe7a8", { alpha: 0.5, seed: 3 });+ // a low garden wall far behind, then the lawn, then a path on the diagonal she walks+ const wall = [P([-12, 0, -6]), P([12, 0, -6]), P([12, 0.9, -6]), P([-12, 0.9, -6])];+ g.wash(wall, "#e7b89a", { alpha: 0.55, seed: 4, dx: 2, dy: 1, shrink: 1, rim: true });+ g.wash([P([-12, 0, -6]), P([12, 0, -6]), P([12, 0, 4.2]), P([-12, 0, 4.2])], "#a8cf9c", { alpha: 0.62, seed: 5, dx: 0, dy: 0, shrink: 1, rim: false });+ const a = add(ORIGIN, mul(DIR, -1)), b = add(ORIGIN, mul(DIR, S_END + 2)), side: V3 = [DIR[2] * 0.45, 0, -DIR[0] * 0.45];+ g.wash([P(add(a, side)), P(add(b, side)), P(add(b, mul(side, -1))), P(add(a, mul(side, -1)))], "#e9dcc3", { alpha: 0.75, seed: 6, dx: 0, dy: 0, shrink: 1, rim: true });+ // a puddle she stops beside, catching the sky+ const pc: V3 = [0.55, 0, 0.55], pud = Array.from({ length: 12 }, (_, i) => { const t = (i / 12) * Math.PI * 2; return P(add(pc, [Math.cos(t) * 0.45, 0, Math.sin(t) * 0.24])); });+ g.wash(pud, "#9dbfd8", { alpha: 0.7, seed: 7, dx: 0, dy: 0, shrink: 1, rim: true });+ });+ g.group("ink", () => {+ const hz = P([0, 0, -6]);+ g.pen([[-20, hz[1] + 2], [W * 0.5, hz[1] - 3], [W + 20, hz[1] + 1]], { w: 1.4, seed: 9, opacity: 0.5, wobble: 2 });+ [[-1.7, -2.4], [1.9, -3.2], [-3.4, -1.1], [2.8, 0.9], [-0.9, 1.8]].forEach(([x, z], i) => { const q = P([x, 0, z]); g.pen([[q[0], q[1]], [q[0] + 4, q[1] - 16], [q[0] + 7, q[1] - 26]], { w: 1.8, color: "#5f8f62", seed: 20 + i, retrace: false }); g.pen([[q[0] + 10, q[1]], [q[0] + 12, q[1] - 13], [q[0] + 17, q[1] - 20]], { w: 1.6, color: "#5f8f62", seed: 30 + i, retrace: false }); });+ });+};++export const drawMiraWalk = (ctx: Ctx, f: number, env: Env) => {+ const g = new Gfx(ctx, env, f, PENCIL);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = "#fbf6ea"; ctx.fillRect(0, 0, W, H);+ // the camera creeps in a little over the whole film: never quite a hold+ const u = f / (N - 1), eye: V3 = add(EYE0, [-0.1 * u, -0.03 * u, -0.45 * u]), cam = camera(eye, add(TARGET, [0.08 * u, 0.02 * u, 0]), lensPx(46, W), W * 0.5, H * 0.52);+ drawWorld(g, cam);+ renderStorybook(g, mira.toScene(miraAt(f), cam), MIRA_STORYBOOK);+ g.paper("paper", 0.12); g.vignette("rgba(90,50,50,0.08)"); g.paper("coldpress", 0.16);+};+export const miraWalk: Film = { meta: { title: "Mira walks in", W, H, fps: FPS, bpm: 120, durationFrames: N }, assets: { images: {} }, shots: [{ id: "walkIn", start: 0, end: N, draw: drawMiraWalk }] };diff --git a/engine/src/canvas-core/moonPhases.ts b/engine/src/canvas-core/moonPhases.tsindex 7fb867f..d5f31dd 100644--- a/engine/src/canvas-core/moonPhases.ts+++ b/engine/src/canvas-core/moonPhases.ts@@ -11,6 +11,11 @@ import { blob, clamp, fillShape, hatchRuns, inside, lerpP, smooth } from "./gall// of dust either side of itself. Behind it all, the ghosts of lessons not quite erased. A wooden// frame, a ledge with a stub of chalk and a felt eraser.+// OPTIONAL CLOCK (for moonPhasesDraw, the board being written): progress 0..1 of each named mark.+// Absent, every mark is finished and the still is byte-identical to the plate without it.+export type Clock = (id: string) => number;+const done: Clock = () => 1;+const CHALK_M: Medium = { nib: 2.1, taper: 0.55, pressure: 0.95, retrace: true, wobble: 1.4, rough: 1.2 };const CHALK = "#f4f0e6", YEL = "#f6e6a4", BLUE = "#a9d3e8", PINK = "#f3c1cf";const B0 = 34, B1 = 1046, LEDGE = 958; // the board's inner edges@@ -20,15 +25,22 @@ const chalk = (g: Gfx, draw: (dust: boolean) => void, dustAlpha = 0.2) => {g.group("plain", () => draw(true), { blur: 3.2, alpha: dustAlpha });g.group("plain", () => draw(false), { textures: ["pencilTooth", "risoSpeck"] });};-const line = (g: Gfx, dust: boolean, pts: P[], w: number, color: string, seed: number, op = 0.92, wob = 1) =>- g.pen(pts, { w: dust ? w * 2.6 : w, color, seed, wobble: wob, boil: 0, opacity: op, retrace: !dust, taper: 1 });+const line = (g: Gfx, dust: boolean, pts: P[], w: number, color: string, seed: number, op = 0.92, wob = 1, progress = 1) =>+ g.pen(pts, { w: dust ? w * 2.6 : w, color, seed, wobble: wob, boil: 0, opacity: op, retrace: !dust, taper: 1, progress });// the side of the chalk dragged back and forth: a scumble, clipped to a shape, thinning where `keep` says so-const scumble = (g: Gfx, dust: boolean, region: P[], color: string, o: { angle: number; gap: number; w: number; alpha: number; seed: number; keep?: (x: number, y: number) => boolean }) => {- const { angle, gap, w, alpha, seed, keep = () => true } = o, r = rng(seed);+const scumble = (g: Gfx, dust: boolean, region: P[], color: string, o: { angle: number; gap: number; w: number; alpha: number; seed: number; keep?: (x: number, y: number) => boolean; progress?: number }) => {+ const { angle, gap, w, alpha, seed, keep = () => true, progress = 1 } = o, r = rng(seed);+ if (progress <= 0) return;let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; region.forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); });const c = g.cur; g.touch(x0 - 12, y0 - 12, x1 + 12, y1 + 12);c.save(); c.lineCap = "round"; c.lineJoin = "round"; c.strokeStyle = color; c.lineWidth = dust ? w * 2.2 : w;- hatchRuns({ x0, y0, x1, y1 }, angle, gap, (x, y) => inside(region, x, y) && keep(x, y), 4, seed).forEach((run) => {+ const runs = hatchRuns({ x0, y0, x1, y1 }, angle, gap, (x, y) => inside(region, x, y) && keep(x, y), 4, seed);+ if (progress < 1) { // the drags so far, the last one part-way: a scumble is laid down drag by drag+ const upto = progress * runs.length;+ runs.forEach((run, i) => { if (i > upto) return; const pts = run.filter((_, k, a) => k % 2 === 0 || k === a.length - 1), m = i + 1 > upto ? Math.max(2, Math.ceil(pts.length * (upto - i))) : pts.length; c.globalAlpha = alpha * (0.86 + r() * 0.2); c.beginPath(); pts.slice(0, m).forEach(([x, y], k) => (k ? c.lineTo(x + (r() - 0.5) * 1.5, y + (r() - 0.5) * 1.5) : c.moveTo(x, y))); c.stroke(); });+ c.restore(); return;+ }+ runs.forEach((run) => {c.globalAlpha = alpha * (0.86 + r() * 0.2); c.beginPath(); // a steady hand: grain comes from the board, not from stripes of pressurerun.filter((_, k, a) => k % 2 === 0 || k === a.length - 1).forEach(([x, y], k) => (k ? c.lineTo(x + (r() - 0.5) * 1.5, y + (r() - 0.5) * 1.5) : c.moveTo(x, y)));c.stroke();@@ -39,7 +51,9 @@ const scumble = (g: Gfx, dust: boolean, region: P[], color: string, o: { angle:// ---------------------------------------------------------------- one moon// `lit` is the illuminated fraction. The terminator is half an ellipse whose width is// r * (1 - 2 * lit): a crescent's bulges toward the lit limb, a gibbous moon's away from it.-const moon = (g: Gfx, cx: number, cy: number, r: number, lit: number, waxing: boolean, seed: number) => {+const moon = (g: Gfx, cx: number, cy: number, r: number, lit: number, waxing: boolean, seed: number, ck: Clock = done) => {+ const q = (part: string) => ck(`m${seed}.${part}`);+ if (q("face") <= 0) return;const s = waxing ? 1 : -1, tx = r * (1 - 2 * lit), N = 40;const disk: P[] = Array.from({ length: 72 }, (_, i) => [cx + Math.cos((i / 72) * Math.PI * 2) * r, cy + Math.sin((i / 72) * Math.PI * 2) * r]);const limb: P[] = [], term: P[] = [];@@ -47,26 +61,26 @@ const moon = (g: Gfx, cx: number, cy: number, r: number, lit: number, waxing: bofor (let i = 0; i <= N; i++) { const a = Math.PI / 2 - (i / N) * Math.PI; term.push([cx + s * Math.cos(a) * tx, cy + Math.sin(a) * r]); }const litShape = [...limb, ...term];const mare = (x: number, y: number) => fractal(seed, (x - cx) * 60 / r, (y - cy) * 60 / r, 0.03, 0.03, 3) + (fractal(seed + 3, x, y, 0.45, 0.45, 2) - 0.5) * 0.16 < 0.52 + (lit > 0.95 ? 0.06 : 0); // where the chalk skipped: the dark seas, their edges crumbling- if (lit > 0.9) g.group("plain", () => g.glow(cx, cy, r * 1.1, "#fff6e0", 0.2)); // the full moon, smudged out with a finger+ if (lit > 0.9 && q("glow") > 0) g.group("plain", () => { const p = q("glow"); if (p >= 1) g.glow(cx, cy, r * 1.1, "#fff6e0", 0.2); else { const c = g.cur; c.save(); c.beginPath(); c.moveTo(cx, cy); c.arc(cx, cy, r * 2.2, -Math.PI / 2, -Math.PI / 2 + p * Math.PI * 2); c.closePath(); c.clip(); g.glow(cx, cy, r * 1.1, "#fff6e0", 0.2); c.restore(); } }); // the full moon, smudged out with a finger, round and roundchalk(g, (dust) => {- if (dust) scumble(g, dust, disk, CHALK, { angle: 0.7, gap: 5, w: 5, alpha: 0.32, seed: seed + 1 }); // earthshine: chalk rubbed into the board with a finger+ if (dust) scumble(g, dust, disk, CHALK, { angle: 0.7, gap: 5, w: 5, alpha: 0.32, seed: seed + 1, progress: q("face") }); // earthshine: chalk rubbed into the board with a fingerconst lc = lit > 0.9 ? "#f8f0d6" : CHALK;- scumble(g, dust, litShape, lc, { angle: -0.9 + (seed % 5) * 0.12, gap: 3, w: 4.4, alpha: 0.4, seed: seed + 2 }); // the whole lit face, evenly- scumble(g, dust, litShape, lc, { angle: 0.75 + (seed % 3) * 0.1, gap: 3.2, w: 4.2, alpha: 0.42, seed: seed + 8, keep: (x, y) => !mare(x, y) }); // the highlands built up across it: the seas are just less chalk- scumble(g, dust, litShape, CHALK, { angle: 0.5, gap: 5, w: 3.6, alpha: 0.45, seed: seed + 3, keep: (x, y) => Math.hypot(x - cx, y - cy) > r * 0.62 && (x - cx) * s > -r * 0.2 }); // the limb, gone over again- if (!dust) {+ scumble(g, dust, litShape, lc, { angle: -0.9 + (seed % 5) * 0.12, gap: 3, w: 4.4, alpha: 0.4, seed: seed + 2, progress: q("face") }); // the whole lit face, evenly+ scumble(g, dust, litShape, lc, { angle: 0.75 + (seed % 3) * 0.1, gap: 3.2, w: 4.2, alpha: 0.42, seed: seed + 8, keep: (x, y) => !mare(x, y), progress: q("high") }); // the highlands built up across it: the seas are just less chalk+ scumble(g, dust, litShape, CHALK, { angle: 0.5, gap: 5, w: 3.6, alpha: 0.45, seed: seed + 3, keep: (x, y) => Math.hypot(x - cx, y - cy) > r * 0.62 && (x - cx) * s > -r * 0.2, progress: q("limb2") }); // the limb, gone over again+ if (!dust && q("craters") > 0) {const cr = rng(seed + 4);- for (let k = 0; k < 5; k++) { const a = cr() * Math.PI * 2, d = cr() * r * 0.75, px = cx + Math.cos(a) * d, py = cy + Math.sin(a) * d; if (!inside(litShape, px, py)) continue; const rr = 3 + cr() * r * 0.09; line(g, dust, Array.from({ length: 9 }, (_, i) => [px + Math.cos((i / 8) * Math.PI * 2) * rr, py + Math.sin((i / 8) * Math.PI * 2) * rr * 0.9] as P), 0.9, CHALK, seed + 10 + k, 0.55, 0.3); }+ for (let k = 0; k < 5; k++) { const a = cr() * Math.PI * 2, d = cr() * r * 0.75, px = cx + Math.cos(a) * d, py = cy + Math.sin(a) * d; if (!inside(litShape, px, py)) continue; const rr = 3 + cr() * r * 0.09; line(g, dust, Array.from({ length: 9 }, (_, i) => [px + Math.cos((i / 8) * Math.PI * 2) * rr, py + Math.sin((i / 8) * Math.PI * 2) * rr * 0.9] as P), 0.9, CHALK, seed + 10 + k, 0.55, 0.3, Math.min(1, Math.max(0, q("craters") * 5 - k))); }}- line(g, dust, limb.filter((_, i) => i % 3 === 0 || i === N), 2.3, CHALK, seed + 5, 0.95); // the lit limb, firm+ line(g, dust, limb.filter((_, i) => i % 3 === 0 || i === N), 2.3, CHALK, seed + 5, 0.95, 1, q("limb")); // the lit limb, firmconst back: P[] = []; for (let i = 0; i <= N; i++) { const a = Math.PI / 2 + (i / N) * Math.PI; back.push([cx + s * Math.cos(a) * r, cy + Math.sin(a) * r]); }- line(g, dust, back.filter((_, i) => i % 3 === 0 || i === N), 1.3, CHALK, seed + 6, 0.45); // the dark limb, barely- if (lit < 0.97) line(g, dust, term.filter((_, i) => i % 4 === 0 || i === N), 1.1, CHALK, seed + 7, 0.5, 0.5);+ line(g, dust, back.filter((_, i) => i % 3 === 0 || i === N), 1.3, CHALK, seed + 6, 0.45, 1, q("back")); // the dark limb, barely+ if (lit < 0.97) line(g, dust, term.filter((_, i) => i % 4 === 0 || i === N), 1.1, CHALK, seed + 7, 0.5, 0.5, q("term"));});};// ---------------------------------------------------------------- the board-const board = (g: Gfx, ctx: Ctx) => {+const board = (g: Gfx, ctx: Ctx, ck?: Clock) => {const gr = ctx.createRadialGradient(540, 470, 60, 540, 470, 720);gr.addColorStop(0, "#35493f"); gr.addColorStop(0.62, "#27352f"); gr.addColorStop(1, "#1b2622");ctx.fillStyle = gr; ctx.fillRect(0, 0, 1080, 1080);@@ -74,9 +88,14 @@ const board = (g: Gfx, ctx: Ctx) => {// the ghosts of erased lessons: wide swipes of haze, and old writing not quite goneg.group("plain", () => {const r = rng(5);- for (let i = 0; i < 9; i++) { const cx = 120 + r() * 840, cy = 120 + r() * 760, rr = 120 + r() * 160, a0 = r() * 6; const pts: P[] = []; for (let k = 0; k <= 12; k++) { const a = a0 + (k / 12) * 2.2; pts.push([cx + Math.cos(a) * rr, cy + Math.sin(a) * rr * 0.55]); } g.pen(pts, { w: 40 + r() * 30, color: CHALK, seed: 6 + i, wobble: 3, boil: 0, opacity: 0.05, retrace: false, taper: 0.4 }); }+ for (let i = 0; i < 9; i++) { const cx = 120 + r() * 840, cy = 120 + r() * 760, rr = 120 + r() * 160, a0 = r() * 6; const pts: P[] = []; for (let k = 0; k <= 12; k++) { const a = a0 + (k / 12) * 2.2; pts.push([cx + Math.cos(a) * rr, cy + Math.sin(a) * rr * 0.55]); } g.pen(pts, { w: 40 + r() * 30, color: CHALK, seed: 6 + i, wobble: 3, boil: 0, opacity: 0.05, retrace: false, taper: 0.4, progress: ck ? ck(`swipe${i}`) : 1 }); }}, { blur: 9 });- g.group("plain", () => { letter(g, "HOMEWORK P 42", 140, 780, { cap: 28, color: CHALK, seed: 40, opacity: 0.12 }); letter(g, "NEWTON", 700, 796, { cap: 26, color: CHALK, seed: 41, opacity: 0.1 }); }, { blur: 2.4 });+ if (!ck) { g.group("plain", () => { letter(g, "HOMEWORK P 42", 140, 780, { cap: 28, color: CHALK, seed: 40, opacity: 0.12 }); letter(g, "NEWTON", 700, 796, { cap: 26, color: CHALK, seed: 41, opacity: 0.1 }); }, { blur: 2.4 }); return; }+ // yesterday's lesson as the teacher finds it, and the felt eraser sweeping it off left to right:+ // behind the eraser, the ghost; ahead of it, the writing still fresh+ const wx = 60 + ck("wipe") * 960, cut = (fn: () => void, left: boolean) => { const c = g.cur; c.save(); c.beginPath(); if (left) c.rect(0, 0, wx, 1080); else c.rect(wx, 0, 1080 - wx, 1080); c.clip(); fn(); c.restore(); };+ g.group("plain", () => cut(() => { letter(g, "HOMEWORK P 42", 140, 780, { cap: 28, color: CHALK, seed: 40, opacity: 0.12 }); letter(g, "NEWTON", 700, 796, { cap: 26, color: CHALK, seed: 41, opacity: 0.1 }); }, true), { blur: 2.4 });+ if (wx < 1020) g.group("plain", () => cut(() => { letter(g, "HOMEWORK P 42", 140, 780, { cap: 28, color: CHALK, seed: 40, opacity: 0.8 }); letter(g, "NEWTON", 700, 796, { cap: 26, color: CHALK, seed: 41, opacity: 0.78 }); letter(g, "3RD LAW", 700, 850, { cap: 30, color: CHALK, seed: 42, opacity: 0.8 }); }, false), { textures: ["pencilTooth", "risoSpeck"] });};const frame = (g: Gfx) => {@@ -103,7 +122,7 @@ const frame = (g: Gfx) => {};// ---------------------------------------------------------------- the lesson-const lesson = (g: Gfx) => {+const lesson = (g: Gfx, ck: Clock = done) => {const phases: { lit: number; waxing: boolean; label: [string, string] }[] = [{ lit: 0.22, waxing: true, label: ["WAXING", "CRESCENT"] }, { lit: 0.5, waxing: true, label: ["FIRST", "QUARTER"] }, { lit: 0.8, waxing: true, label: ["WAXING", "GIBBOUS"] },{ lit: 1, waxing: true, label: ["FULL", ""] },@@ -113,37 +132,37 @@ const lesson = (g: Gfx) => {// stars first, so the moons sit over themchalk(g, (dust) => {const r = rng(500);- for (let i = 0; i < 70; i++) { const x = 60 + r() * 960, y = 60 + r() * 860, ok = [0, 1, 2, 3, 4, 5, 6].every((k) => { const [mx, my, mr] = at(k); return Math.hypot(x - mx, y - my) > mr + 34 && Math.abs(y - (my + mr + 48)) > 32 || Math.abs(x - mx) > 70; }) && !(y < 180 && x > 170 && x < 910); if (!ok) continue; const big = r() < 0.12; if (big) { const s = 7 + r() * 5; line(g, dust, [[x - s, y], [x + s, y]], 1.4, CHALK, 501 + i, 0.85, 0.2); line(g, dust, [[x, y - s], [x, y + s]], 1.4, CHALK, 601 + i, 0.85, 0.2); } else fillShape(g, blob(x, y, 1 + r() * 1.6, 1 + r() * 1.4, 700 + i, 0.2, 6), CHALK, 0.5 + r() * 0.4); }+ for (let i = 0; i < 70; i++) { const st = ck(`star${i}`), x = 60 + r() * 960, y = 60 + r() * 860, ok = [0, 1, 2, 3, 4, 5, 6].every((k) => { const [mx, my, mr] = at(k); return Math.hypot(x - mx, y - my) > mr + 34 && Math.abs(y - (my + mr + 48)) > 32 || Math.abs(x - mx) > 70; }) && !(y < 180 && x > 170 && x < 910); if (!ok) continue; const big = r() < 0.12; if (big) { const s = 7 + r() * 5; line(g, dust, [[x - s, y], [x + s, y]], 1.4, CHALK, 501 + i, 0.85, 0.2, Math.min(1, st * 2)); line(g, dust, [[x, y - s], [x, y + s]], 1.4, CHALK, 601 + i, 0.85, 0.2, Math.max(0, st * 2 - 1)); } else { const sh = blob(x, y, 1 + r() * 1.6, 1 + r() * 1.4, 700 + i, 0.2, 6), a = 0.5 + r() * 0.4; if (st > 0) fillShape(g, sh, CHALK, a); } }// the Plough, low on the left, dotted and joined in blue chalkconst dip: P[] = [[112, 846], [168, 822], [220, 830], [266, 858], [278, 910], [352, 916], [360, 862]];- dip.slice(0, 7).forEach(([x, y], i) => fillShape(g, blob(x, y, 3.4, 3.4, 800 + i, 0.15, 8), CHALK, 0.95));- line(g, dust, [...dip.slice(0, 5)], 1, BLUE, 810, 0.6, 0.4); line(g, dust, [dip[4], dip[5], dip[6], dip[3]], 1, BLUE, 811, 0.6, 0.4);+ dip.slice(0, 7).forEach(([x, y], i) => { if (ck(`dip${i}`) > 0) fillShape(g, blob(x, y, 3.4, 3.4, 800 + i, 0.15, 8), CHALK, 0.95); });+ line(g, dust, [...dip.slice(0, 5)], 1, BLUE, 810, 0.6, 0.4, ck("dipA")); line(g, dust, [dip[4], dip[5], dip[6], dip[3]], 1, BLUE, 811, 0.6, 0.4, ck("dipB"));}, 0.18);- phases.forEach((p, i) => { const [x, y, r] = at(i); moon(g, x, y, r, p.lit, p.waxing, 1000 + i * 37); });+ phases.forEach((p, i) => { const [x, y, r] = at(i); moon(g, x, y, r, p.lit, p.waxing, 1000 + i * 37, ck); });chalk(g, (dust) => {// the title, underlined twice in yellow the way a teacher does when it matters- letter(g, "PHASES OF THE MOON", 540, 86, { cap: 44, color: CHALK, seed: 20, align: "center", w: 2.6, opacity: 0.95 });- line(g, dust, [[300, 152], [540, 148], [782, 154]], 2.4, YEL, 21, 0.9, 1.2); line(g, dust, [[330, 164], [560, 161], [760, 166]], 1.8, YEL, 22, 0.75, 1.4);+ letter(g, "PHASES OF THE MOON", 540, 86, { cap: 44, color: CHALK, seed: 20, align: "center", w: 2.6, opacity: 0.95, progress: ck("title") });+ line(g, dust, [[300, 152], [540, 148], [782, 154]], 2.4, YEL, 21, 0.9, 1.2, ck("under1")); line(g, dust, [[330, 164], [560, 161], [760, 166]], 1.8, YEL, 22, 0.75, 1.4, ck("under2"));// the arrow of the month over the moonsconst arc: P[] = []; for (let k = 0; k <= 16; k++) { const f = k / 16, s = Math.sin(f * Math.PI); arc.push([150 + f * 780, 470 - s * 196]); }- line(g, dust, smooth(arc.filter((_, k) => k % 2 === 0), false, 3), 1.6, BLUE, 30, 0.85, 1);+ line(g, dust, smooth(arc.filter((_, k) => k % 2 === 0), false, 3), 1.6, BLUE, 30, 0.85, 1, ck("arc"));const tip = arc[16], pre = arc[15], a = Math.atan2(tip[1] - pre[1], tip[0] - pre[0]);- line(g, dust, [[tip[0] - Math.cos(a - 0.5) * 20, tip[1] - Math.sin(a - 0.5) * 20], tip, [tip[0] - Math.cos(a + 0.5) * 20, tip[1] - Math.sin(a + 0.5) * 20]], 1.8, BLUE, 31, 0.9, 0.3);- letter(g, "29.5 DAYS", 540, 230, { cap: 17, color: BLUE, seed: 32, align: "center", w: 1.7, opacity: 0.85 });+ line(g, dust, [[tip[0] - Math.cos(a - 0.5) * 20, tip[1] - Math.sin(a - 0.5) * 20], tip, [tip[0] - Math.cos(a + 0.5) * 20, tip[1] - Math.sin(a + 0.5) * 20]], 1.8, BLUE, 31, 0.9, 0.3, ck("arrow"));+ letter(g, "29.5 DAYS", 540, 230, { cap: 17, color: BLUE, seed: 32, align: "center", w: 1.7, opacity: 0.85, progress: ck("days") });// the labels under each moon, and a note about the far side, circled in pink- phases.forEach((p, i) => { const [x, y, r] = at(i); letter(g, p.label[0], x, y + r + 26, { cap: 13, color: CHALK, seed: 40 + i * 3, align: "center", w: 1.35, opacity: 0.85 }); if (p.label[1]) letter(g, p.label[1], x, y + r + 48, { cap: 13, color: CHALK, seed: 41 + i * 3, align: "center", w: 1.35, opacity: 0.85 }); });- letter(g, "SAME FACE", 870, 842, { cap: 16, color: PINK, seed: 70, align: "center", w: 1.6, opacity: 0.9 });- letter(g, "ALWAYS", 870, 868, { cap: 16, color: PINK, seed: 71, align: "center", w: 1.6, opacity: 0.9 });- line(g, dust, Array.from({ length: 11 }, (_, k) => { const a2 = -0.3 + (k / 10) * Math.PI * 2.1; return [870 + Math.cos(a2) * 92, 858 + Math.sin(a2) * 42] as P; }), 1.4, PINK, 72, 0.8, 1.5);+ phases.forEach((p, i) => { const [x, y, r] = at(i); letter(g, p.label[0], x, y + r + 26, { cap: 13, color: CHALK, seed: 40 + i * 3, align: "center", w: 1.35, opacity: 0.85, progress: ck(`lab${i}a`) }); if (p.label[1]) letter(g, p.label[1], x, y + r + 48, { cap: 13, color: CHALK, seed: 41 + i * 3, align: "center", w: 1.35, opacity: 0.85, progress: ck(`lab${i}b`) }); });+ letter(g, "SAME FACE", 870, 842, { cap: 16, color: PINK, seed: 70, align: "center", w: 1.6, opacity: 0.9, progress: ck("note1") });+ letter(g, "ALWAYS", 870, 868, { cap: 16, color: PINK, seed: 71, align: "center", w: 1.6, opacity: 0.9, progress: ck("note2") });+ line(g, dust, Array.from({ length: 11 }, (_, k) => { const a2 = -0.3 + (k / 10) * Math.PI * 2.1; return [870 + Math.cos(a2) * 92, 858 + Math.sin(a2) * 42] as P; }), 1.4, PINK, 72, 0.8, 1.5, ck("ring"));}, 0.22);void lerpP; void clamp;};-export const drawMoonPhases = (ctx: Ctx, _frame: number, env: Env) => {+export const drawMoonPhases = (ctx: Ctx, _frame: number, env: Env, ck?: Clock) => {const g = new Gfx(ctx, env, 0, CHALK_M);ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);- board(g, ctx);- lesson(g);+ board(g, ctx, ck);+ lesson(g, ck);frame(g);};diff --git a/engine/src/canvas-core/moonPhasesDraw.ts b/engine/src/canvas-core/moonPhasesDraw.tsnew file mode 100644index 0000000..483e75c--- /dev/null+++ b/engine/src/canvas-core/moonPhasesDraw.ts@@ -0,0 +1,65 @@+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import { drawMoonPhases, type Clock } from "./moonPhases";++// MOON PHASES · the lesson being written. The chalkboard plate, drawn in the order a teacher+// works a board: the felt eraser first, sweeping yesterday's lesson off left to right and leaving+// its ghosts in wide arcs of haze; then the title, underlined twice; the month's arrow and its+// label; then the moons one at a time, each scumbled with the side of the chalk (the whole face,+// then the highlands built up across it, then the lit limb worked a second time), craters tapped+// in, the firm limb line, the faint dark limb and the terminator, and its label written under it+// before the next one starts; the full moon smudged round with a finger. Stars are dotted in+// last, the Plough joined in blue, and the pink note circled. Every stroke carries its dust with it.+//+// The plate itself (moonPhases.ts) takes an optional Clock; without one it draws the finished+// board byte for byte, so the last 30 frames here are the still.++const N = 540, HOLD = 30;+// ONE cue table: [id, start, end] in frames, all on the 5-frame grid. `parts` split a cue evenly.+type Cue = { id: string; a: number; b: number; parts?: string[] };+const moonCues = (i: number, a: number): Cue[] => {+ const m = `m${1000 + i * 37}`, full = i === 3;+ return [+ { id: `${m}.face`, a, b: a + 10 }, { id: `${m}.high`, a: a + 10, b: a + 15 }, { id: `${m}.limb2`, a: a + 15, b: a + 20 },+ { id: `${m}.craters`, a: a + 20, b: a + 25 }, { id: `${m}.lines`, a: a + 25, b: a + 30, parts: [`${m}.limb`, `${m}.limb`, `${m}.back`, `${m}.term`] },+ { id: `lab${i}a`, a: a + 30, b: a + 35 }, full ? { id: `${m}.glow`, a: a + 35, b: a + 40 } : { id: `lab${i}b`, a: a + 35, b: a + 40 },+ ];+};+const CUES: Cue[] = [+ { id: "wipe", a: 5, b: 55 },+ ...Array.from({ length: 9 }, (_, i): Cue => ({ id: `swipe${i}`, a: 5 + i * 5, b: 20 + i * 5 })), // the eraser's arcs, following it across+ { id: "title", a: 60, b: 95 }, { id: "under1", a: 95, b: 100 }, { id: "under2", a: 100, b: 105 },+ { id: "arc", a: 105, b: 120 }, { id: "arrow", a: 120, b: 125 }, { id: "days", a: 125, b: 140 },+ ...Array.from({ length: 7 }, (_, i) => moonCues(i, 140 + i * 40)).flat(),+ { id: "stars", a: 420, b: 460, parts: Array.from({ length: 70 }, (_, i) => `star${i}`) },+ { id: "dips", a: 460, b: 470, parts: Array.from({ length: 7 }, (_, i) => `dip${i}`) }, { id: "dipA", a: 470, b: 475 }, { id: "dipB", a: 475, b: 480 },+ { id: "note1", a: 480, b: 490 }, { id: "note2", a: 490, b: 500 }, { id: "ring", a: 500, b: 510 },+];+((): void => { // the checker runs at load: on the grid, inside the film, finished before the hold+ for (const c of CUES) if (c.a % 5 || c.b % 5 || c.b <= c.a || c.b > N - HOLD) throw new Error(`moonPhasesDraw: cue ${c.id} (${c.a}-${c.b}) is off the grid or past the hold`);+ if (N % 15) throw new Error("moonPhasesDraw: duration off the beat");+})();+// id -> [start, end] for every mark, parts spread across their cue (a part named twice gets both slots)+const SPANS: Map<string, [number, number]> = (() => {+ const m = new Map<string, [number, number]>();+ for (const c of CUES) {+ if (!c.parts) { m.set(c.id, [c.a, c.b]); continue; }+ const n = c.parts.length, d = (c.b - c.a) / n;+ c.parts.forEach((p, k) => { const s = c.a + k * d, e = s + d, o = m.get(p); m.set(p, o ? [Math.min(o[0], s), Math.max(o[1], e)] : [s, e]); });+ }+ return m;+})();+const clockAt = (f: number): Clock => (id) => { const s = SPANS.get(id); if (!s) return 1; if (f >= s[1]) return 1; if (f <= s[0]) return 0; return (f - s[0]) / (s[1] - s[0]); };++export const drawMoonPhasesDraw = (ctx: Ctx, f: number, env: Env) => {+ if (f >= N - HOLD) return drawMoonPhases(ctx, f, env); // the finished board: the still, pixel for pixel+ drawMoonPhases(ctx, f, env, clockAt(f));+};++export const moonPhasesDraw: Film = {+ meta: { title: "Moon phases · the lesson being written", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "lesson", start: 0, end: N, draw: drawMoonPhasesDraw }],+};++export const STYLE = { id: "moonPhasesDraw", name: "Chalkboard, written on", family: "chalk", medium: "soft white and coloured chalk on a slate-green board, side-of-chalk scumble, felt eraser, finger smudge", nearest: "moonPhases", hero: "the phases of the moon, taught" };diff --git a/engine/src/canvas-core/music/dsp.ts b/engine/src/canvas-core/music/dsp.tsnew file mode 100644index 0000000..55bda99--- /dev/null+++ b/engine/src/canvas-core/music/dsp.ts@@ -0,0 +1,88 @@+// DSP building blocks. Everything is a pure function of its inputs plus an rng() handed in by+// the caller; stateful filters are legal because a whole buffer renders in one call.+export type Rng = () => number;+export const TAU = Math.PI * 2;+export const db = (x: number) => Math.pow(10, x / 20);+export const clamp = (x: number, a: number, b: number) => (x < a ? a : x > b ? b : x);+/** Equal-power pan, p in -1..1 -> [gL, gR]. */+export const pan = (p: number): [number, number] => { const a = ((clamp(p, -1, 1) + 1) * Math.PI) / 4; return [Math.cos(a), Math.sin(a)]; };+/** Gaussian from a seeded uniform source. */+export const gauss = (r: Rng) => { let u = r(); if (u < 1e-12) u = 1e-12; return Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * r()); };++/** Zavalishin TPT state-variable filter; set() may be called per sample for sweeps. */+export class SVF {+ private ic1 = 0; private ic2 = 0; private g = 0; private k = 0; private a1 = 0; private a2 = 0; private a3 = 0;+ lp = 0; bp = 0; hp = 0;+ constructor(private sr: number, f = 1000, q = 0.707) { this.set(f, q); }+ set(f: number, q: number) { this.g = Math.tan((Math.PI * clamp(f, 5, this.sr * 0.49)) / this.sr); this.k = 1 / q; this.a1 = 1 / (1 + this.g * (this.g + this.k)); this.a2 = this.g * this.a1; this.a3 = this.g * this.a2; }+ tick(x: number) { const v3 = x - this.ic2, v1 = this.a1 * this.ic1 + this.a2 * v3, v2 = this.ic2 + this.a2 * this.ic1 + this.a3 * v3; this.ic1 = 2 * v1 - this.ic1; this.ic2 = 2 * v2 - this.ic2; this.lp = v2; this.bp = v1; this.hp = x - this.k * v1 - v2; return v2; }+}+/** RBJ biquad (direct form I). */+export class Biquad {+ private x1 = 0; private x2 = 0; private y1 = 0; private y2 = 0; b0 = 1; b1 = 0; b2 = 0; a1 = 0; a2 = 0;+ static make(sr: number, type: "lp" | "hp" | "bp" | "peak" | "lowshelf" | "highshelf", f: number, q: number, gainDb = 0) {+ const bq = new Biquad(), w = (TAU * f) / sr, c = Math.cos(w), s = Math.sin(w), al = s / (2 * q), A = Math.pow(10, gainDb / 40);+ let b0 = 1, b1 = 0, b2 = 0, a0 = 1, a1 = 0, a2 = 0;+ if (type === "lp") { b0 = (1 - c) / 2; b1 = 1 - c; b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else if (type === "hp") { b0 = (1 + c) / 2; b1 = -(1 + c); b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else if (type === "bp") { b0 = al; b1 = 0; b2 = -al; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else if (type === "peak") { b0 = 1 + al * A; b1 = -2 * c; b2 = 1 - al * A; a0 = 1 + al / A; a1 = -2 * c; a2 = 1 - al / A; }+ else { const sq = 2 * Math.sqrt(A) * al, sh = type === "lowshelf" ? 1 : -1;+ b0 = A * ((A + 1) - sh * (A - 1) * c + sq); b1 = sh * 2 * A * ((A - 1) - sh * (A + 1) * c); b2 = A * ((A + 1) - sh * (A - 1) * c - sq);+ a0 = (A + 1) + sh * (A - 1) * c + sq; a1 = -sh * 2 * ((A - 1) + sh * (A + 1) * c); a2 = (A + 1) + sh * (A - 1) * c - sq; }+ bq.b0 = b0 / a0; bq.b1 = b1 / a0; bq.b2 = b2 / a0; bq.a1 = a1 / a0; bq.a2 = a2 / a0; return bq;+ }+ tick(x: number) { const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2; this.x2 = this.x1; this.x1 = x; this.y2 = this.y1; this.y1 = y; return y; }+ run(buf: Float32Array) { for (let i = 0; i < buf.length; i++) buf[i] = this.tick(buf[i]); return buf; }+}+export const onePoleCoef = (sr: number, f: number) => 1 - Math.exp((-TAU * f) / sr);++/** PolyBLEP residual for band-limited saw/pulse. */+export const blep = (t: number, dt: number) => { if (t < dt) { t /= dt; return t + t - t * t - 1; } if (t > 1 - dt) { t = (t - 1) / dt; return t * t + t + t + 1; } return 0; };++/** Add a mono signal into a stereo pair with gains. */+export const addPan = (L: Float32Array, R: Float32Array, i0: number, sig: Float32Array | Float64Array, len: number, p: number, g: number) => {+ const [gl, gr] = pan(p); const n = Math.min(len, L.length - i0);+ for (let i = Math.max(0, -i0); i < n; i++) { const v = sig[i] * g; L[i0 + i] += v * gl; R[i0 + i] += v * gr; }+};++/**+ * A small room: early reflections (decorrelated taps per side, each darker than the last) plus a+ * short 8-line feedback delay network for the diffuse tail. Returns the WET signal only.+ * size ~ room scale, rt60 in seconds, damp = high-frequency loss in the tail (0..1).+ */+export const room = (L: Float32Array, R: Float32Array, sr: number, o: { er: number; late: number; rt60: number; predelay: number; hp: number; lp: number; seed: number; rng: Rng }) => {+ const n = L.length, wL = new Float32Array(n), wR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n), r = o.rng;+ // send filter: high-passed (no mud) and low-passed+ const inL = Float32Array.from(L), inR = Float32Array.from(R);+ Biquad.make(sr, "hp", o.hp, 0.7).run(inL); Biquad.make(sr, "hp", o.hp, 0.7).run(inR);+ Biquad.make(sr, "lp", o.lp, 0.7).run(inL); Biquad.make(sr, "lp", o.lp, 0.7).run(inR);+ // early reflections: 7 taps per side, 6-38 ms, alternating polarity, decreasing gain+ for (const [src, dst, side] of [[inL, wL, 0], [inR, wR, 1], [inR, wL, 2], [inL, wR, 3]] as const) {+ let acc = 0; const k = onePoleCoef(sr, 5200);+ for (let t = 0; t < 7; t++) {+ const ms = 6 + t * 4.6 + r() * 3 + side * 0.7, d = Math.round((ms / 1000) * sr), g = (o.er * (side < 2 ? 1 : 0.55) * Math.pow(0.8, t) * (t % 2 ? -1 : 1)) / 2.2;+ acc = 0; for (let i = d; i < n; i++) { acc += k * (src[i - d] - acc); dst[i] += acc * g; }+ }+ }+ if (o.late > 0) {+ const N = 8, lens = [1123, 1289, 1447, 1597, 1777, 1913, 2053, 2239].map((x) => Math.round((x * sr) / 48000 * (0.7 + 0.3 * r())));+ const bufs = lens.map((l) => new Float32Array(l)), idx = new Array(N).fill(0), lp = new Array(N).fill(0);+ const gains = lens.map((l) => Math.pow(10, (-3 * l) / (sr * o.rt60))), dampK = onePoleCoef(sr, 3200);+ const pd = Math.round(o.predelay * sr), out = new Float64Array(N), h = new Float64Array(N);+ for (let i = 0; i < n; i++) {+ const xl = i >= pd ? inL[i - pd] : 0, xr = i >= pd ? inR[i - pd] : 0;+ for (let j = 0; j < N; j++) out[j] = bufs[j][idx[j]];+ // Hadamard-ish mix (fast Walsh on 8)+ h.set(out);+ for (let s = 1; s < N; s <<= 1) for (let j = 0; j < N; j += s << 1) for (let q = j; q < j + s; q++) { const a = h[q], b = h[q + s]; h[q] = a + b; h[q + s] = a - b; }+ for (let j = 0; j < N; j++) {+ let v = (h[j] / Math.sqrt(N)) * gains[j];+ lp[j] += dampK * (v - lp[j]); v = lp[j];+ bufs[j][idx[j]] = v + (j % 2 ? xr : xl) * 0.5; idx[j] = (idx[j] + 1) % lens[j];+ }+ tL[i] = (out[0] - out[2] + out[4] - out[6]) * o.late * 0.5; tR[i] = (out[1] - out[3] + out[5] - out[7]) * o.late * 0.5; wL[i] += tL[i]; wR[i] += tR[i];+ }+ }+ return [wL, wR, tL, tR] as const; // full wet, and the late tail alone+};diff --git a/engine/src/canvas-core/music/guards.ts b/engine/src/canvas-core/music/guards.tsnew file mode 100644index 0000000..a34ffeb--- /dev/null+++ b/engine/src/canvas-core/music/guards.ts@@ -0,0 +1,106 @@+// Guards that replace the old bans (spec 08 section 7). Sad music is allowed; formless music is not.+//+// ghost formlessness measured by STRUCTURE, never by darkness. Per window (4 bars, or 8 s when+// the tempo is unknown): onset density, sustained-energy share, reverb-to-dry, cadences.+// A window fails only when ALL four point at "formless". Works on bare audio (a reference+// file): unknown reverb or cadence count AGAINST the file, so a reference can only pass on+// what is measured.+// masking while the melody sounds, its 500 Hz-4 kHz band beats every other layer there by >= 3 dB+// (per bar, on per-role stems)+// reverb reverb return >= 10 dB under the dry mix, per bar+// Thresholds are calibrated so the loved reference (Kevin Ngo piano) PASSES and the ghost fixture+// (slow pad, long tail, no rhythm, no cadence) FAILS; see tools/music.mjs `guards`.+import { onsets, mono, loudness } from "./meter";+import { renderPiece, type Rendered } from "./render";+import { pcOf } from "./theory";+import type { Piece, Role } from "./plan";++export const GHOST = { maxOnsetsPerBeat: 1.0, minSustainedShare: 0.6, reverbWithinDb: -12, windowBars: 4, fallbackWindowS: 8 };++/** Share of energy that is "sustained": 50 ms frames that are not decaying like a struck note (fall < 1.5 dB over 250 ms, i.e. slower than 6 dB/s) and not just after an onset. */+const sustainedShare = (m: Float32Array, sr: number, a: number, b: number, ons: number[]) => {+ const hop = Math.round(0.05 * sr), lag = Math.round(0.25 / 0.05);+ const lv: number[] = [], en: number[] = [];+ for (let i = a; i + hop <= b; i += hop) { let e = 0; for (let j = i; j < i + hop; j++) e += m[j] * m[j]; e /= hop; en.push(e); lv.push(10 * Math.log10(e + 1e-12)); }+ const top = Math.max(...lv); let sus = 0, tot = 0;+ for (let k = lag; k < lv.length; k++) {+ if (lv[k] < top - 45) continue;+ const t = (a + k * hop) / sr, recent = ons.some((o) => t - o >= 0 && t - o < 0.15);+ tot += en[k]; if (!recent && lv[k] - lv[k - lag] > -1.5) sus += en[k]; // held or swelling, not decaying like a struck note+ }+ return tot > 0 ? sus / tot : 0;+};++export type GhostWindow = { from: number; to: number; onsetsPerBeat: number; sustainedShare: number; reverbDb: number | null; cadence: boolean | null; fail: boolean };+export const ghostCheck = (chans: Float32Array[], sr: number, o: { bpm?: number; beatsPerBar?: number; wet?: Float32Array[]; dry?: Float32Array[]; cadences?: number[]; breaths?: [number, number][] } = {}) => {+ const m = mono(chans), dur = m.length / sr, ons = onsets(chans, sr);+ const beat = o.bpm ? 60 / o.bpm : 1, win = o.bpm ? GHOST.windowBars * (o.beatsPerBar ?? 4) * beat : GHOST.fallbackWindowS;+ const windows: GhostWindow[] = [];+ for (let t0 = 0; t0 + Math.min(win, dur) <= dur + 1e-9; t0 += win / 2) {+ const t1 = Math.min(dur, t0 + win), a = Math.round(t0 * sr), b = Math.round(t1 * sr);+ const n = ons.filter((x) => x >= t0 && x < t1).length, opb = n / ((t1 - t0) / beat);+ const ss = sustainedShare(m, sr, a, b, ons);+ let rv: number | null = null;+ if (o.wet && o.dry) { let ew = 0, ed = 0; for (let c = 0; c < o.wet.length; c++) for (let i = a; i < b; i++) { ew += o.wet[c][i] ** 2; ed += o.dry[c][i] ** 2; } rv = 10 * Math.log10((ew + 1e-12) / (ed + 1e-12)); }+ const cad = o.cadences ? o.cadences.some((c) => c >= t0 && c < t1) : null;+ const breath = (o.breaths ?? []).some(([x, y]) => x <= t0 && y >= t1);+ const fail = !breath && opb < GHOST.maxOnsetsPerBeat && ss > GHOST.minSustainedShare && (rv === null || rv > GHOST.reverbWithinDb) && cad !== true;+ windows.push({ from: t0, to: t1, onsetsPerBeat: opb, sustainedShare: ss, reverbDb: rv, cadence: cad, fail });+ if (t1 >= dur) break;+ }+ return { pass: !windows.some((w) => w.fail), failures: windows.filter((w) => w.fail).length, windows };+};++/** Cadence arrivals (seconds): the harmony lands on the section tonic from a chord a fifth above (V-I) or a fourth above (IV-I, plagal). */+export const cadenceTimes = (r: Rendered) => {+ const root = (nm: string) => { const m = /^([A-G](?:b|#)?)/.exec(nm); return m ? pcOf(m[1]) : -1; };+ const key = pcOf(r.piece.plan.sections[0].key.replace(/m$/, "")), ch = r.piece.harmony.slice().sort((a, b) => a.t - b.t), out: number[] = [];+ for (let i = 1; i < ch.length; i++) { const a = root(ch[i - 1].name), b = root(ch[i].name); if (b === key && (a === (key + 7) % 12 || a === (key + 5) % 12 || a === (key + 11) % 12)) out.push(r.perf.sec(ch[i].t)); }+ return out;+};++/** Reverb-to-dry per bar (dB). Pass: every sounding bar >= 10 dB under. */+export const reverbCheck = (r: Rendered, sr: number) => {+ const bpb = r.piece.plan.meter === "3/4" ? 3 : r.piece.plan.meter === "6/8" ? 2 : 4, total = r.piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0), bars: number[] = [];+ for (let b = 0; b < total; b += bpb) {+ const a = Math.round(r.perf.sec(b) * sr), e = Math.min(r.L.length, Math.round(r.perf.sec(b + bpb) * sr)); let ew = 0, ed = 0;+ for (let c = 0; c < 2; c++) for (let i = a; i < e; i++) { ew += r.wet[c][i] ** 2; ed += r.dry[c][i] ** 2; }+ if (ed > 1e-9) bars.push(10 * Math.log10((ew + 1e-12) / ed));+ }+ const worst = Math.max(...bars);+ return { pass: worst <= -10, worstDb: worst, meanDb: bars.reduce((a, b) => a + b, 0) / Math.max(1, bars.length), bars };+};++/** Band energy (dB) of 500 Hz-4 kHz per span, via a 2-pole band-pass pair. */+const bandDb = (L: Float32Array, R: Float32Array, sr: number, spans: [number, number][]) => {+ const x = mono([L, R]), y = new Float32Array(x.length);+ // 2nd-order Butterworth HP at 500 then LP at 4000 (bilinear, simple)+ const biq = (inp: Float32Array, out: Float32Array, type: "hp" | "lp", f: number) => { const w = (2 * Math.PI * f) / sr, c = Math.cos(w), s = Math.sin(w), al = s / (2 * Math.SQRT1_2); const b0 = type === "lp" ? (1 - c) / 2 : (1 + c) / 2, b1 = type === "lp" ? 1 - c : -(1 + c), a0 = 1 + al, a1 = -2 * c, a2 = 1 - al; let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < inp.length; i++) { const v = (b0 * inp[i] + b1 * x1 + b0 * x2 - a1 * y1 - a2 * y2) / a0; x2 = x1; x1 = inp[i]; y2 = y1; y1 = v; out[i] = v; } };+ biq(x, y, "hp", 500); const z = new Float32Array(x.length); biq(y, z, "lp", 4000);+ return spans.map(([a, b]) => { let e = 0; for (let i = Math.round(a * sr); i < Math.min(z.length, Math.round(b * sr)); i++) e += z[i] * z[i]; return 10 * Math.log10(e / Math.max(1, (b - a) * sr) + 1e-15); });+};++/** Masking: per bar where the melody sounds, melody band energy minus the loudest other role's (dB). Pass: >= 3 dB in >= 80 % of those bars. */+export const maskingCheck = (piece: Piece, sr: number, o: { seconds?: number; tempo?: number } = {}) => {+ const roles = [...new Set(piece.parts.flatMap((p) => p.notes.map((n) => n.role)))] as Role[];+ if (!roles.includes("melody")) return null;+ const only = (r: Role) => ({ ...piece, parts: piece.parts.map((p) => ({ ...p, notes: p.notes.filter((n) => n.role === r) })) });+ const base = { seconds: o.seconds, tempo: o.tempo, master: "none" as const };+ const mel = renderPiece(only("melody"), sr, base);+ const bpb = piece.plan.meter === "3/4" ? 3 : piece.plan.meter === "6/8" ? 2 : 4, total = piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0);+ const spans: [number, number][] = []; for (let b = 0; b < total; b += bpb) spans.push([mel.perf.sec(b), mel.perf.sec(b + bpb)]);+ const melNotes = piece.parts.flatMap((p) => p.notes.filter((n) => n.role === "melody"));+ const sounding = spans.map((_, i) => melNotes.some((n) => n.t < (i + 1) * bpb && n.t + n.d > i * bpb));+ const m = bandDb(mel.L, mel.R, sr, spans);+ const others = roles.filter((r) => r !== "melody").map((r) => { const x = renderPiece(only(r), sr, base); return { role: r, db: bandDb(x.L, x.R, sr, spans) }; });+ const margins = spans.map((_, i) => (sounding[i] ? m[i] - Math.max(...others.map((x) => x.db[i]), -300) : NaN)).filter((x) => Number.isFinite(x));+ const ok = margins.filter((x) => x >= 3).length / Math.max(1, margins.length);+ return { pass: ok >= 0.8, shareOfBarsClear: ok, worstMarginDb: Math.min(...margins), meanMarginDb: margins.reduce((a, b) => a + b, 0) / Math.max(1, margins.length) };+};++/** Everything at once for a rendered piece. */+export const guardReport = (r: Rendered, sr: number, seconds: number, o: { masking?: boolean } = {}) => {+ const bpb = r.piece.plan.meter === "3/4" ? 3 : r.piece.plan.meter === "6/8" ? 2 : 4;+ const ghost = ghostCheck([r.L, r.R], sr, { bpm: r.tempo, beatsPerBar: bpb, wet: r.wet, dry: r.dry, cadences: cadenceTimes(r) });+ return { ghost: { pass: ghost.pass, failures: ghost.failures, windows: ghost.windows.length, minOnsetsPerBeat: Math.min(...ghost.windows.map((w) => w.onsetsPerBeat)), maxSustainedShare: Math.max(...ghost.windows.map((w) => w.sustainedShare)) }, reverb: reverbCheck(r, sr), masking: o.masking === false ? null : maskingCheck(r.piece, sr, { seconds, tempo: r.tempo }), lufs: loudness([r.L, r.R], sr).integrated };+};diff --git a/engine/src/canvas-core/music/index.ts b/engine/src/canvas-core/music/index.tsnew file mode 100644index 0000000..8d02f52--- /dev/null+++ b/engine/src/canvas-core/music/index.ts@@ -0,0 +1,18 @@+// anidoodle music: 100 % procedural, notes as data, synthesized in code. No samples, ever.+export * from "./theory";+export * from "./tables";+export * from "./plan";+export * from "./perform";+export * from "./piano";+export * from "./render";+export * from "./meter";+export * from "./guards";+export * from "./score-text";+export * as instruments from "./instruments";+import { nocturne, pianoPhrase8 } from "./pieces/nocturne";+import { musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic } from "./pieces/samplers";+import { marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm } from "./pieces/families";+import { ghostFixture } from "./pieces/fixtures";+export { nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };+/** Named pieces a film (or the tool) can ask for. ghostFixture is a test fixture, never a score. */+export const PIECES = { nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };diff --git a/engine/src/canvas-core/music/instruments.ts b/engine/src/canvas-core/music/instruments.tsnew file mode 100644index 0000000..d7dccf2--- /dev/null+++ b/engine/src/canvas-core/music/instruments.ts@@ -0,0 +1,234 @@+// The non-piano kit. Each instrument: (keys, sr, n, opts, rng) -> [L, R]. Keys are performed+// presses in seconds. Presets are numbers in one place (the constants at the top of each voice).+import { type Rng, TAU, clamp, pan, SVF, Biquad, blep, onePoleCoef, gauss } from "./dsp";+import type { Played } from "./perform";++type Out = { L: Float32Array; R: Float32Array };+type Opts = Record<string, number | boolean | string>;+const num = (o: Opts, k: string, d: number) => (typeof o[k] === "number" ? (o[k] as number) : d);+const f0 = (m: number) => 440 * Math.pow(2, (m - 69) / 12);+const pitchPan = (m: number, w: number) => clamp((m - 64) / 30, -1, 1) * w;++/** Sum of decaying sinusoids, the modal core shared by music box, celesta, mallets and bells. */+const modal = (out: Out, i0: number, modes: [number, number, number][], p: number, sr: number, maxS: number, rel?: { at: number; sigma: number }, atkMs = 2) => {+ const atk = Math.max(1, Math.round((atkMs / 1000) * sr));+ const [gl, gr] = pan(p), n = out.L.length;+ for (const [f, a, tau] of modes) {+ if (f > sr * 0.45 || a <= 0) continue;+ const w = (TAU * f) / sr, cw = Math.cos(w), sw = Math.sin(w), dec = Math.exp(-1 / (tau * sr));+ const decR = rel ? Math.exp(-(1 / tau + rel.sigma) / sr) : dec;+ const len = Math.min(n - i0, Math.ceil(Math.min(maxS, tau * 11) * sr)), relI = rel ? Math.round(rel.at * sr) : Infinity;+ let c = a, s = 0;+ for (let i = 0; i < len; i++) { const y = i < atk ? (s * i) / atk : s; const j = i0 + i; if (j >= 0) { out.L[j] += y * gl; out.R[j] += y * gr; } const d = i < relI ? dec : decR; const c2 = (c * cw - s * sw) * d; s = (c * sw + s * cw) * d; c = c2; }+ }+};++export const musicBox = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ // the recipe numbers, verbatim: partials 1, 2, 3 at 1.0/0.35/0.12, a 5.4f ping dying in 60 ms,+ // 2 ms attack, tau = 0.45 sqrt(440/f)+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.5);+ for (const k of keys) {+ const f = f0(k.p), tau = 0.45 * Math.sqrt(440 / f), i0 = Math.round(k.t * sr), g = k.v * 0.3;+ modal(out, i0, [[f, g, tau], [2 * f, 0.35 * g, tau * 0.8], [3 * f, 0.12 * g, tau * 0.6], [5.4 * f, 0.08 * g, 0.06 / 4]], pitchPan(k.p, w), sr, 8);+ }+ return out;+};+/** The recipe's DING: partials 1, 2, 3, 4.2, tau 1.2 s, doubled an octave down. */+export const bell = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.3);+ for (const k of keys) { const i0 = Math.round(k.t * sr), g = k.v * 0.25;+ for (const f of [f0(k.p), f0(k.p) / 2]) modal(out, i0, [[f, g, 1.2], [2 * f, 0.5 * g, 0.75], [3 * f, 0.3 * g, 0.5], [4.2 * f, 0.16 * g, 0.3]], pitchPan(k.p, w), sr, 9, undefined, 1.5); }+ return out;+};+export const celesta = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.5);+ for (const k of keys) {+ const f = f0(k.p), tau = 0.8 * Math.sqrt(440 / f), i0 = Math.round(k.t * sr), g = Math.pow(k.v, 1.3) * 0.3, h = 0.4 + 0.6 * k.v;+ modal(out, i0, [[f, g, tau], [2 * f, 0.18 * g * h, tau * 0.5], [4.02 * f, 0.07 * g * h, tau * 0.25], [6.9 * f, 0.03 * g * h, 0.03]], pitchPan(k.p, w), sr, 8, { at: k.off - k.t, sigma: 9 });+ }+ return out;+};+/** Marimba / vibraphone: a tuned bar's modes (1 : 3.9 : 9.2 for rosewood, 1 : 4 : 10 for aluminium). */+export const mallets = (keys: Played[], sr: number, n: number, o: Opts, vibes = false): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.6);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), g = Math.pow(k.v, 1.4) * 0.32, h = 0.25 + 0.75 * k.v; // h = mallet hardness+ const t1 = vibes ? 3.2 * Math.pow(440 / f, 0.35) : clamp(0.9 * Math.pow(262 / f, 0.8), 0.18, 2.2);+ const modes: [number, number, number][] = vibes ? [[f, g, t1], [4 * f, 0.22 * g * h, t1 * 0.2], [10 * f, 0.06 * g * h, 0.05]] : [[f, g * 1.15, t1], [3.9 * f, 0.3 * g * h, t1 * 0.22], [9.2 * f, 0.1 * g * h * h, t1 * 0.07]];+ modal(out, i0, modes, pitchPan(k.p, w), sr, 8, vibes ? { at: k.off - k.t, sigma: 6 } : undefined);+ }+ if (vibes) { const r = num(o, "trem", 5.2); for (let i = 0; i < n; i++) { const m = 1 - 0.22 * (0.5 + 0.5 * Math.sin((TAU * r * i) / sr)); out.L[i] *= m; out.R[i] *= m; } }+ return out;+};++/**+ * Extended Karplus-Strong (Jaffe & Smith 1983): a delay line one period long, a two-point loss+ * filter for brightness, an allpass for fine tuning, a pick-position comb on the excitation and a+ * velocity low-pass (a softer pluck is darker). Harp rings long and bright; guitar gets a body.+ */+export const pluck = (keys: Played[], sr: number, n: number, o: Opts, r: Rng, kind: "harp" | "guitar"): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.6);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), P = sr / f, N = Math.floor(P - 0.5), frac = P - N - 0.5;+ const ap = (1 - frac) / (1 + frac); // first-order allpass fractional delay+ const T60 = kind === "harp" ? clamp(4.2 * Math.pow(262 / f, 0.45), 0.8, 8) : clamp(3.2 * Math.pow(262 / f, 0.5), 0.6, 6);+ const S = kind === "harp" ? 0.18 : 0.32; // loss-filter weight (higher = darker)+ const rho = Math.pow(10, -3 / (T60 * f));+ const line = new Float64Array(N + 2);+ // excitation: noise shaped by velocity low-pass and a pick-position comb+ const lp = new SVF(sr, 900 + 6000 * k.v * k.v, 0.6), beta = kind === "harp" ? 0.5 : 0.18, pk = Math.max(1, Math.round(beta * N));+ const exc = new Float64Array(N); for (let i = 0; i < N; i++) exc[i] = lp.tick(gauss(r)); let mean = 0; for (let i = 0; i < N; i++) mean += exc[i] / N;+ for (let i = 0; i < N; i++) line[i] = (exc[i] - mean) - (i >= pk ? exc[i - pk] - mean : 0) * 0.9;+ let peak = 1e-9; for (let i = 0; i < N; i++) peak = Math.max(peak, Math.abs(line[i]));+ const g = (Math.pow(k.v, 1.3) * 0.35) / peak, [gl, gr] = pan(pitchPan(k.p, w));+ const relI = Math.round((k.off - k.t) * sr), len = Math.min(n - i0, Math.ceil(T60 * 1.1 * sr));+ let idx = 0, prev = 0, apx = 0, apy = 0, damp = 1;+ for (let i = 0; i < len; i++) {+ const x = line[idx], nxt = line[(idx + 1) % N];+ const y = ((1 - S) * x + S * nxt) * rho;+ const a = ap * y + apx - ap * apy; apx = y; apy = a; // allpass+ prev = a; line[idx] = a * damp; idx = (idx + 1) % N;+ if (kind === "guitar" && i > relI) damp = 0.985; // finger damping after release+ const j = i0 + i; if (j < n) { const v = x * g * Math.min(1, i / 24); out.L[j] += v * gl; out.R[j] += v * gr; }+ }+ void prev;+ }+ if (kind === "guitar") for (const [f, q, gdb] of [[110, 2.5, 5], [220, 3, 3], [420, 2, 2], [2800, 1, -3]] as const) { Biquad.make(sr, "peak", f, q, gdb).run(out.L); Biquad.make(sr, "peak", f, q, gdb).run(out.R); }+ return out;+};++/** Soft string ensemble: 5 detuned PolyBLEP saws per note, slow bow attack, delayed vibrato, low-pass, high-pass 150 Hz. */+export const strings = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, atk = num(o, "attack", 0.45), rel = num(o, "release", 0.9), w = num(o, "width", 0.8), bright = num(o, "bright", 1);+ const hpL = new SVF(sr, 150, 0.7), hpR = new SVF(sr, 150, 0.7);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + rel * 1.5) * sr));+ const V = 5, dets = [-9, -4.5, 0, 4.2, 8.8], phs = dets.map(() => r()), pans = dets.map((_, i) => pan(((i / (V - 1)) * 2 - 1) * w)), incs = dets.map((d) => (f * Math.pow(2, d / 1200)) / sr);+ const lp = [new SVF(sr, 1000, 0.6), new SVF(sr, 1000, 0.6)], g = Math.pow(k.v, 1.2) * 0.11;+ const vr = 4.8 + r() * 0.8, vph = r() * TAU;+ for (let i = 0; i < len; i++) {+ const t = i / sr;+ const env = t < dur ? 1 - Math.exp(-t / (atk / 3)) : (1 - Math.exp(-dur / (atk / 3))) * Math.exp(-(t - dur) / (rel / 3));+ const vib = 1 + (0.0006 + 0.0022 * clamp((t - 0.35) / 0.6, 0, 1)) * Math.sin(TAU * vr * t + vph);+ let sl = 0, sr_ = 0;+ for (let v = 0; v < V; v++) {+ const inc = incs[v] * vib; let ph = phs[v] + inc; if (ph >= 1) ph -= 1; phs[v] = ph;+ const s = 2 * ph - 1 - blep(ph, inc), pv = pans[v]; sl += s * pv[0]; sr_ += s * pv[1];+ }+ const cut = clamp((500 + 2600 * k.v * bright) * (0.55 + 0.45 * env), 200, 9000);+ if ((i & 31) === 0) { lp[0].set(cut, 0.6); lp[1].set(cut, 0.6); }+ const j = i0 + i; out.L[j] += lp[0].tick(sl) * env * g; out.R[j] += lp[1].tick(sr_) * env * g;+ }+ }+ const bassRole = o.bass === true;+ if (!bassRole) for (let i = 0; i < n; i++) { hpL.tick(out.L[i]); hpR.tick(out.R[i]); out.L[i] = hpL.hp; out.R[i] = hpR.hp; }+ return out;+};++/** Two-operator FM bell (modulator 3.5x) plus the 2.4x "tierce"; index decays faster than loudness. */+export const fmBell = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.5), ratio = num(o, "ratio", 3.5);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), ta = clamp(2.2 * Math.pow(440 / f, 0.4), 0.5, 6), ti = ta * 0.25, I0 = 1.2 + 2.4 * k.v, g = Math.pow(k.v, 1.3) * 0.2;+ const len = Math.min(n - i0, Math.ceil(ta * 7 * sr)), [gl, gr] = pan(pitchPan(k.p, w));+ for (let i = 0; i < len; i++) { const t = i / sr, a = Math.exp(-t / ta) * Math.min(1, t * 1500), I = I0 * Math.exp(-t / ti);+ const y = (Math.sin(TAU * f * t + I * Math.sin(TAU * f * ratio * t)) + 0.3 * Math.sin(TAU * f * 2.4 * t) * Math.exp(-t / (ta * 0.5))) * a * g; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; }+ }+ return out;+};+/** FM electric piano: 1:1 body with a decaying index, a 14:1 tine "bark" on the attack, tremolo, a little drive. */+export const ePiano = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.35), trem = num(o, "trem", 4.6);+ for (const k of keys) {+ const f = f0(k.p) * (1 + (num(o, "detune", 4) / 1200) * (k.p % 2 ? 1 : -1)), i0 = Math.round(k.t * sr), td = clamp(1.9 * Math.pow(262 / f, 0.5), 0.5, 5), dur = k.off - k.t;+ const I0 = 0.6 + 2.2 * k.v, g = Math.pow(k.v, 1.2) * 0.2, len = Math.min(n - i0, Math.ceil((dur + 0.4) * sr)), [gl, gr] = pan(pitchPan(k.p, w));+ for (let i = 0; i < len; i++) {+ const t = i / sr, rel = t < dur ? 1 : Math.exp(-(t - dur) / 0.07), a = Math.exp(-t / td) * rel * Math.min(1, t * 700);+ const I = I0 * Math.exp(-t / 0.4), bark = 0.9 * k.v * Math.exp(-t / 0.012);+ const y = Math.tanh(1.3 * Math.sin(TAU * f * t + I * Math.sin(TAU * f * t) + bark * Math.sin(TAU * f * 14 * t))) * a * g;+ out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr;+ }+ }+ for (let i = 0; i < n; i++) { const m = 0.25 * Math.sin((TAU * trem * i) / sr); out.L[i] *= 1 - m; out.R[i] *= 1 + m; }+ return out;+};++// ---------------------------------------------------------------- chiptune+/** Band-limited pulse, duty 0.125/0.25/0.5, NES-like 4-bit stepped volume, delayed vibrato on long notes. */+export const pulse = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, duty = num(o, "duty", 0.25), [gl, gr] = pan(num(o, "pan", 0));+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.03) * sr)); let ph = 0;+ for (let i = 0; i < len; i++) {+ const t = i / sr, env = t < dur ? 0.62 + 0.38 * Math.exp(-t / 0.09) : Math.max(0, 0.62 * (1 - (t - dur) / 0.03)), vol = Math.round(env * 15) / 15;+ const vib = 1 + (t > 0.25 ? 0.004 * Math.sin(TAU * 6 * (t - 0.25)) : 0), inc = (f * vib) / sr;+ ph += inc; if (ph >= 1) ph -= 1;+ let s = ph < duty ? 1 : -1; s += blep(ph, inc); let q = ph - duty; if (q < 0) q += 1; s -= blep(q, inc);+ const y = (s - (2 * duty - 1)) * vol * k.v * 0.16; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr;+ }+ }+ return out;+};+/** NES triangle: a 32-step staircase, no volume control, so it is either on or off. */+export const triangle = (keys: Played[], sr: number, n: number): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) };+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil((k.off - k.t) * sr)); let ph = 0; const lp = new SVF(sr, 7000, 0.7);+ for (let i = 0; i < len; i++) { ph += f / sr; if (ph >= 1) ph -= 1; const st = Math.floor(ph * 32), tri = st < 16 ? st / 7.5 - 1 : (31 - st) / 7.5 - 1; const e = Math.min(1, i / 48, (len - i) / 48); const y = lp.tick(tri) * 0.2 * e; out.L[i0 + i] += y; out.R[i0 + i] += y; }+ }+ return out;+};+/** NES noise channel: a 15-bit LFSR (long mode for snare/kick, short 93-step mode for hats). */+export const noiseDrum = (keys: Played[], sr: number, n: number): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) };+ for (const k of keys) {+ const kind = k.kind ?? "s", i0 = Math.round(k.t * sr); let reg = 1, acc = 0;+ const rate = kind === "h" ? 32000 : kind === "k" ? 3500 : 11000, dec = kind === "h" ? 0.028 : kind === "k" ? 0.07 : 0.11, short = kind === "h";+ const len = Math.min(n - i0, Math.ceil(dec * 6 * sr)); let out1 = 1;+ for (let i = 0; i < len; i++) {+ acc += rate / sr; while (acc >= 1) { acc -= 1; const bit = (reg ^ (reg >> (short ? 6 : 1))) & 1; reg = (reg >> 1) | (bit << 14); out1 = reg & 1 ? 1 : -1; }+ const t = i / sr, e = Math.round(Math.exp(-t / dec) * 15) / 15;+ let y = out1 * e * k.v * (kind === "h" ? 0.07 : 0.14);+ if (kind === "k") { const fq = 55 + 110 * Math.exp(-t / 0.03); y += Math.sin(TAU * fq * t) * Math.exp(-t / 0.09) * k.v * 0.4; }+ out.L[i0 + i] += y; out.R[i0 + i] += y;+ }+ }+ return out;+};++// ---------------------------------------------------------------- drums and bass (soft kit)+export const kick = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, soft = num(o, "soft", 1);+ for (const k of keys) { const i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil(0.5 * sr)); let ph = 0;+ for (let i = 0; i < len; i++) { const t = i / sr, fq = 48 + (110 + 40 * (1 - soft)) * Math.exp(-t / 0.035); ph += fq / sr;+ const y = Math.tanh(1.6 * Math.sin(TAU * ph) * Math.exp(-t / (0.22 * (0.7 + 0.3 * soft)))) * k.v * 0.5 + Math.sin(TAU * 1300 * t) * Math.exp(-t / 0.004) * 0.04 * k.v; out.L[i0 + i] += y; out.R[i0 + i] += y; } }+ return out;+};+export const snare = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, rim = o.rim === true;+ for (const k of keys) { const i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil(0.35 * sr)), bp = new SVF(sr, rim ? 1800 : 3200, rim ? 3 : 0.8);+ for (let i = 0; i < len; i++) { const t = i / sr, body = (Math.sin(TAU * 185 * t) + 0.5 * Math.sin(TAU * 330 * t)) * Math.exp(-t / 0.045) * (rim ? 0.25 : 0.5);+ bp.tick(gauss(r)); const nz = bp.bp * Math.exp(-t / (rim ? 0.02 : 0.1)) * (rim ? 1.2 : 0.6); const y = (body + nz) * k.v * 0.32; out.L[i0 + i] += y * 0.95; out.R[i0 + i] += y; } }+ return out;+};+export const hat = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, [gl, gr] = pan(num(o, "pan", 0.3));+ for (const k of keys) { const i0 = Math.round(k.t * sr), dec = k.kind === "o" ? 0.2 : 0.03, len = Math.min(n - i0, Math.ceil(dec * 6 * sr)), hp = new SVF(sr, 7200, 0.7);+ for (let i = 0; i < len; i++) { const t = i / sr; hp.tick(gauss(r)); const y = hp.hp * Math.exp(-t / dec) * k.v * 0.09; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; } }+ return out;+};+/** Warm bass: sine + harmonics, a pluck envelope, and a little saturation so phones hear the line (phone rule). */+export const bass = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, drive = num(o, "drive", 1.6);+ for (const k of keys) { const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.1) * sr));+ for (let i = 0; i < len; i++) { const t = i / sr, e = Math.min(1, t * 300) * (0.55 + 0.45 * Math.exp(-t / 0.25)) * (t < dur ? 1 : Math.exp(-(t - dur) / 0.03));+ const y = Math.tanh(drive * (Math.sin(TAU * f * t) + 0.35 * Math.sin(TAU * 2 * f * t) + 0.12 * Math.sin(TAU * 3 * f * t))) / Math.tanh(drive) * e * k.v * 0.3; out.L[i0 + i] += y; out.R[i0 + i] += y; } }+ return out;+};+/** Vinyl: sparse crackle impulses and a low hiss floor. One key spans the texture. */+export const vinyl = (keys: Played[], sr: number, n: number, _o: Opts, r: Rng): Out => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, lp = onePoleCoef(sr, 4000);+ for (const k of keys) { const i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil((k.off - k.t) * sr)); let zl = 0, zr = 0;+ for (let i = 0; i < len; i++) { const pop = r() < 7 / sr ? (r() - 0.5) * 0.5 * k.v : 0; const hiss = gauss(r) * 0.004 * k.v; zl += lp * (hiss + pop - zl); zr += lp * (hiss * 0.8 + pop - zr); out.L[i0 + i] += zl; out.R[i0 + i] += zr; } }+ return out;+};diff --git a/engine/src/canvas-core/music/meter.ts b/engine/src/canvas-core/music/meter.tsnew file mode 100644index 0000000..f70647c--- /dev/null+++ b/engine/src/canvas-core/music/meter.ts@@ -0,0 +1,105 @@+// The deaf composer's instruments. Pure functions over float buffers:+// loudness ITU-R BS.1770-4 K-weighting, 400 ms blocks at 75 % overlap, -70 LUFS absolute and+// -10 LU relative gates; LRA per EBU Tech 3342 (3 s short-term, -20 LU gate, P95 - P10)+// truePeak 4x oversampled (windowed-sinc polyphase), dBTP+// onsets spectral flux with a max-filtered previous frame (SuperFlux-style), adaptive threshold+// centroid magnitude-weighted spectral centroid, averaged over non-silent frames+export const fft = (re: Float64Array, im: Float64Array) => {+ const n = re.length;+ for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; } }+ for (let len = 2; len <= n; len <<= 1) {+ const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang);+ for (let i = 0; i < n; i += len) { let cr = 1, ci = 0; for (let j = 0; j < len / 2; j++) { const a = i + j, b = a + len / 2, xr = re[b] * cr - im[b] * ci, xi = re[b] * ci + im[b] * cr; re[b] = re[a] - xr; im[b] = im[a] - xi; re[a] += xr; im[a] += xi; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; } }+ }+};++const kWeight = (x: Float32Array, sr: number) => {+ // stage 1: high shelf (+4 dB above ~1.7 kHz); stage 2: RLB high-pass ~38 Hz (pyloudnorm's closed form)+ const out = new Float64Array(x.length);+ { const G = 3.999843853973347, Q = 0.7071752369554196, fc = 1681.974450955533, K = Math.tan((Math.PI * fc) / sr), Vh = Math.pow(10, G / 20), Vb = Math.pow(Vh, 0.4996667741545416);+ const a0 = 1 + K / Q + K * K, b0 = (Vh + (Vb * K) / Q + K * K) / a0, b1 = (2 * (K * K - Vh)) / a0, b2 = (Vh - (Vb * K) / Q + K * K) / a0, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < x.length; i++) { const y = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[i]; y2 = y1; y1 = y; out[i] = y; } }+ { const fc = 38.13547087602444, Q = 0.5003270373238773, K = Math.tan((Math.PI * fc) / sr), a0 = 1 + K / Q + K * K, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < out.length; i++) { const xi = out[i], y = xi - 2 * x1 + x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = xi; y2 = y1; y1 = y; out[i] = y; } }+ return out;+};++export const loudness = (chans: Float32Array[], sr: number) => {+ const k = chans.map((c) => kWeight(c, sr)), n = chans[0].length;+ const ms = (a: number, len: number) => { let s = 0; for (const c of k) { let e = 0; for (let i = a; i < a + len && i < n; i++) e += c[i] * c[i]; s += e / len; } return s; };+ const lufs = (z: number) => -0.691 + 10 * Math.log10(Math.max(z, 1e-20));+ // integrated+ const bl = Math.round(0.4 * sr), hop = Math.round(0.1 * sr), blocks: number[] = [];+ for (let a = 0; a + bl <= n; a += hop) blocks.push(ms(a, bl));+ const abs = blocks.filter((z) => lufs(z) > -70), rel = lufs(abs.reduce((a, b) => a + b, 0) / Math.max(1, abs.length)) - 10;+ const gated = abs.filter((z) => lufs(z) > rel), integrated = lufs(gated.reduce((a, b) => a + b, 0) / Math.max(1, gated.length));+ // short-term (3 s) for LRA and max short-term; momentary max+ const sl = Math.round(3 * sr), st: number[] = []; for (let a = 0; a + sl <= n; a += hop) st.push(ms(a, sl));+ const stAbs = st.filter((z) => lufs(z) > -70), stRel = lufs(stAbs.reduce((a, b) => a + b, 0) / Math.max(1, stAbs.length)) - 20;+ const stG = stAbs.map(lufs).filter((l) => l > stRel).sort((a, b) => a - b);+ const pct = (p: number) => (stG.length ? stG[Math.min(stG.length - 1, Math.max(0, Math.round((p / 100) * (stG.length - 1))))] : NaN);+ const shortTerm = st.map(lufs);+ return { integrated, lra: pct(95) - pct(10), shortMax: Math.max(...shortTerm), momentaryMax: Math.max(...blocks.map(lufs)), shortTerm, hopS: 0.1 };+};++export const truePeak = (chans: Float32Array[]) => {+ // 4x polyphase windowed sinc, 16 taps per phase+ const O = 4, T = 16, h: number[][] = [];+ for (let ph = 0; ph < O; ph++) { const row: number[] = []; for (let t = 0; t < T; t++) { const x = t - T / 2 + 1 - ph / O, w = 0.5 + 0.5 * Math.cos((Math.PI * x) / (T / 2)); row.push(x === 0 ? 1 : (Math.sin(Math.PI * x) / (Math.PI * x)) * w); } h.push(row); }+ let peak = 0, sample = 0;+ for (const c of chans) for (let i = 0; i < c.length; i++) {+ const a = Math.abs(c[i]); if (a > sample) sample = a;+ if (a < peak * 0.5) continue; // cheap skip: an inter-sample peak cannot exceed ~2x its neighbours here+ for (let ph = 1; ph < O; ph++) { let s = 0; for (let t = 0; t < T; t++) { const j = i + t - T / 2 + 1; if (j >= 0 && j < c.length) s += c[j] * h[ph][t]; } const v = Math.abs(s); if (v > peak) peak = v; }+ if (a > peak) peak = a;+ }+ return { dbtp: 20 * Math.log10(Math.max(peak, 1e-12)), samplePeakDb: 20 * Math.log10(Math.max(sample, 1e-12)) };+};++const hann = (N: number) => Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));+/** STFT magnitudes of the mono mix. */+const stft = (mono: Float32Array, N: number, hop: number) => {+ const w = hann(N), frames: Float64Array[] = [];+ for (let a = 0; a + N <= mono.length; a += hop) { const re = new Float64Array(N), im = new Float64Array(N); for (let i = 0; i < N; i++) re[i] = mono[a + i] * w[i]; fft(re, im); const m = new Float64Array(N / 2 + 1); for (let k = 0; k <= N / 2; k++) m[k] = Math.hypot(re[k], im[k]); frames.push(m); }+ return frames;+};+export const mono = (chans: Float32Array[]) => { const n = chans[0].length, m = new Float32Array(n); for (const c of chans) for (let i = 0; i < n; i++) m[i] += c[i] / chans.length; return m; };++/** Onset strength of every accepted peak is returned too (`strength`, on a loudness-normalised scale). */+export const onsetsDetail = (chans: Float32Array[], sr: number, delta = 0.07, absFloor = ONSET_FLOOR) => {+ // loudness-normalise to -23 LUFS first, so the absolute floor means the same thing for every file+ const m = mono(chans), lu = loudness([m], sr).integrated, g = Number.isFinite(lu) ? Math.pow(10, (-23 - lu) / 20) : 1;+ for (let i = 0; i < m.length; i++) m[i] *= g;+ const hop = Math.round(sr / 100), N = sr >= 44100 ? 2048 : 1024, frames = stft(m, N, hop);+ // log-compressed bands on a ~24-per-octave filterbank above 30 Hz+ const bins = frames[0].length, edges: number[] = []; for (let f = 30; f < Math.min(16000, sr / 2); f *= Math.pow(2, 1 / 24)) edges.push(Math.round((f / sr) * N));+ const uniq = [...new Set(edges)].filter((b) => b < bins);+ const bands = frames.map((mm) => { const out = new Float64Array(uniq.length - 1); for (let b = 0; b < uniq.length - 1; b++) { let s = 0; for (let k = uniq[b]; k < Math.max(uniq[b] + 1, uniq[b + 1]); k++) s += mm[k]; out[b] = Math.log10(1 + 100 * s); } return out; });+ const raw = new Float64Array(bands.length);+ for (let t = 1; t < bands.length; t++) { let s = 0; const cur = bands[t], prev = bands[t - 1]; for (let b = 0; b < cur.length; b++) { const pm = Math.max(prev[b], b > 0 ? prev[b - 1] : 0, b + 1 < cur.length ? prev[b + 1] : 0); const d = cur[b] - pm; if (d > 0) s += d; } raw[t] = s; }+ let mx = 0; for (const f of raw) mx = Math.max(mx, f); const flux = raw.map((x) => x / (mx || 1));+ const times: number[] = [], strength: number[] = []; let last = -1e9;+ for (let t = 3; t < flux.length - 3; t++) {+ let isMax = true; for (let d = -3; d <= 3; d++) if (flux[t + d] > flux[t]) isMax = false; if (!isMax) continue;+ let mean = 0, c = 0; for (let d = -10; d <= 3; d++) { const j = t + d; if (j >= 0 && j < flux.length) { mean += flux[j]; c++; } } mean /= c;+ if (flux[t] >= mean + delta && raw[t] >= absFloor && (t - last) * hop / sr >= 0.05) { times.push((t * hop) / sr); strength.push(raw[t]); last = t; }+ }+ return { times, strength };+};+/** Absolute onset-strength floor (loudness-normalised flux). Calibrated in METERS.md: real note starts in the loved reference sit far above it, a detuned pad's beating sits below. */+export let ONSET_FLOOR = 4;+export const setOnsetFloor = (x: number) => { ONSET_FLOOR = x; };+export const onsets = (chans: Float32Array[], sr: number, delta = 0.07) => onsetsDetail(chans, sr, delta).times;++export const centroid = (chans: Float32Array[], sr: number) => {+ const N = 2048, frames = stft(mono(chans), N, 512); let emax = 0; const es = frames.map((m) => { let e = 0; for (const x of m) e += x * x; emax = Math.max(emax, e); return e; });+ let sum = 0, c = 0, wsum = 0, wtot = 0;+ frames.forEach((m, i) => { if (es[i] < emax * 1e-5) return; let num = 0, den = 0; for (let k = 1; k < m.length; k++) { num += ((k * sr) / N) * m[k]; den += m[k]; } if (den > 0) { sum += num / den; c++; wsum += (num / den) * es[i]; wtot += es[i]; } });+ return { mean: c ? sum / c : 0, energyWeighted: wtot ? wsum / wtot : 0 };+};++export type Meters = { durationS: number; lufs: number; lra: number; shortMax: number; dbtp: number; samplePeakDb: number; onsetsPerS: number; onsetCount: number; centroidHz: number; centroidEnergyHz: number; lastOnsetS: number; shortTerm: number[] };+export const measure = (chans: Float32Array[], sr: number): Meters => {+ const l = loudness(chans, sr), tp = truePeak(chans), on = onsets(chans, sr), c = centroid(chans, sr), dur = chans[0].length / sr;+ return { durationS: dur, lufs: l.integrated, lra: l.lra, shortMax: l.shortMax, dbtp: tp.dbtp, samplePeakDb: tp.samplePeakDb, onsetsPerS: on.length / dur, onsetCount: on.length, centroidHz: c.mean, centroidEnergyHz: c.energyWeighted, lastOnsetS: on.length ? on[on.length - 1] : 0, shortTerm: l.shortTerm };+};diff --git a/engine/src/canvas-core/music/perform.ts b/engine/src/canvas-core/music/perform.tsnew file mode 100644index 0000000..56783c9--- /dev/null+++ b/engine/src/canvas-core/music/perform.ts@@ -0,0 +1,90 @@+// Performance: written notes (beats) -> played key presses (seconds). This is where "MIDI" stops.+// Rules from music-performance research (Todd 1992; the KTH rule system, Friberg, Bresin and+// Sundberg 2006; Repp on melody lead and pedalling). All randomness from rng(seed), smoothed so+// deviations correlate across a phrase instead of jittering note to note.+import { beatsPerBar, type Piece, type Note, type Role } from "./plan";+import { clamp, gauss } from "./dsp";+import type { KeyPress, PedalSpan } from "./piano";+import { rng as mkRng } from "../core";++export type Played = KeyPress & { role: Role; kind?: string; w: number /* written velocity */ };+export type PerformOpts = { expressive: boolean; flatVelocity?: number };+export type Performance = { parts: { id: string; keys: Played[] }[]; pedal: PedalSpan[]; sec: (beat: number) => number; lastOnset: number; meanLeadMs: number };++const arch = (x: number) => Math.sin(Math.PI * Math.pow(clamp(x, 0, 1), 1.45)); // peaks near 0.62 of the phrase++export const perform = (p: Piece, tempo: number, o: PerformOpts): Performance => {+ const plan = p.plan, bpb = beatsPerBar(plan.meter), pick = plan.pickupBeats ?? 0, phraseB = (plan.phraseBars ?? 4) * bpb;+ const totalBeats = plan.sections.reduce((a, s) => a + s.bars * bpb, 0);+ // section spans and the dynamic level curve+ const spans: { a: number; b: number; dyn: [number, number] }[] = []; { let b = 0; for (const s of plan.sections) { spans.push({ a: b, b: b + s.bars * bpb, dyn: s.dyn }); b += s.bars * bpb; } }+ const level = (b: number) => { for (const s of spans) if (b < s.b) { const x = clamp((b - s.a) / (s.b - s.a), 0, 1); return s.dyn[0] + (s.dyn[1] - s.dyn[0]) * x; } return spans[spans.length - 1].dyn[1]; };+ // caesura: a breath before a sudden hush (next section starts far quieter than this one ended)+ const breaths: { at: number; beats: number }[] = [];+ if (o.expressive) for (let i = 1; i < spans.length; i++) if (spans[i].dyn[0] < 0.6 * spans[i - 1].dyn[1]) breaths.push({ at: spans[i].a, beats: 0.4 });+ // tempo factor per beat (>1 = faster)+ const lastMel = Math.max(...p.parts.flatMap((pt) => pt.notes.map((n) => n.t)));+ const ritBeats = Math.min(2 * bpb, 6, Math.max(1, 0.25 * (totalBeats + pick))), ritFrom = lastMel - ritBeats;+ const factor = (b: number) => {+ if (!o.expressive) return 1;+ const x = ((b + pick) % phraseB) / phraseB;+ const rub = plan.rubato ?? (plan.style === "nocturne" || plan.style === "cinematic" ? 1 : 0), w = plan.ritard ?? 0.55;+ let f = 1 + rub * (0.05 * arch(x) - 0.025);+ if (b > ritFrom && w < 1) { const u = clamp((b - ritFrom) / ritBeats, 0, 1), q = 2.5; f *= Math.pow(1 + (Math.pow(w, q) - 1) * u, 1 / q); }+ return f;+ };+ const step = 1 / 96, b0 = -pick - 1, b1 = totalBeats + 16, spb = 60 / tempo;+ const tab = new Float64Array(Math.ceil((b1 - b0) / step) + 2); let acc = 0;+ for (let i = 0; i < tab.length; i++) { tab[i] = acc; const b = b0 + i * step; acc += (spb / factor(b)) * step; for (const br of breaths) if (Math.abs(b - br.at) < step / 2) acc += br.beats * spb; }+ const lead = pick > 0 ? 0.25 : 0.0; // a hair of silence before the first note+ const secRaw = (b: number) => { const f = (b - b0) / step, i = Math.floor(f), u = f - i; const a = tab[clamp(i, 0, tab.length - 1)], c = tab[clamp(i + 1, 0, tab.length - 1)]; return a + (c - a) * u; };+ const start = secRaw(-pick);+ const sec = (b: number) => secRaw(b) - start + lead;+ const swing = plan.swing ?? 0.5;+ const sw = (b: number) => { if (swing === 0.5) return b; const fl = Math.floor(b), fr = b - fl; return fl + (fr <= 0.5 ? fr * (swing / 0.5) : swing + (fr - 0.5) * ((1 - swing) / 0.5)); };++ const RoleGain: Record<Role, number> = { melody: 1, inner: 0.55, bass: 0.68, accomp: 0.52, color: 0.7, drum: 1 }; // voicing: melody 6-10 dB over the rest+ let leadSum = 0, leadN = 0;+ const parts = p.parts.map((pt, pi) => {+ const hr = mkRng(p.seed * 131 + pi * 17 + 1), grid = pt.opts?.grid === true, isPiano = pt.inst === "piano";+ let tDev = 0, vDev = 0; // AR(1) states+ const notes = pt.notes.slice().sort((a, b) => a.t - b.t || a.p - b.p);+ // group simultaneous onsets (chords) for spread/roll+ const keys: Played[] = [];+ const melodyNext = (n: Note, i: number) => { for (let j = i + 1; j < notes.length; j++) if (notes[j].t > n.t + 1e-6) return notes[j].t; return Infinity; };+ let lastT = -1e9, chordIdx = 0;+ notes.forEach((n, i) => {+ if (Math.abs(n.t - lastT) > 1e-6) { chordIdx = 0; lastT = n.t; if (o.expressive && !grid) { tDev = 0.85 * tDev + Math.sqrt(1 - 0.85 * 0.85) * gauss(hr) * 0.007; vDev = 0.7 * vDev + Math.sqrt(1 - 0.49) * gauss(hr) * 0.035; } } else chordIdx++;+ let t = sec(sw(n.t)), end = sec(sw(n.t + n.d));+ let v: number;+ if (!o.expressive) { v = o.flatVelocity ?? 0.6; }+ else {+ const x = ((n.t + pick) % phraseB) / phraseB, lv = level(n.t);+ const metric = Math.abs(n.t - Math.round(n.t / bpb) * bpb) < 1e-6 ? 1.06 : Math.abs(n.t - Math.round(n.t)) < 1e-6 ? 1 : 0.95;+ const hi = n.role === "melody" ? 1 + 0.06 * ((n.p - 72) / 12) : 1;+ // written v 0.7 = mezzo; section level 0..1 maps to 0.25..0.85 of full velocity+ v = (n.v / 0.7) * (0.25 + 0.6 * lv) * (0.92 + 0.16 * arch(x)) * (grid ? 1 : metric * hi) * (isPiano ? RoleGain[n.role] : 1 / (0.25 + 0.6 * 0.75)) + vDev;+ if (n.t > ritFrom) v *= 1 - 0.18 * clamp((n.t - ritFrom) / ritBeats, 0, 1); // the cadence relaxes+ t += tDev;+ if (n.role === "melody" && isPiano) { const ld = 0.012 + 0.016 * clamp(v, 0, 1); t -= ld; leadSum += ld; leadN++; }+ if (n.roll !== undefined) t += chordIdx * n.roll; else if (chordIdx > 0 && !grid) t += chordIdx * 0.004;+ // legato: melody keys overlap the next note by ~35 ms; accompaniment keys lift a little early (the pedal holds)+ if (n.role === "melody" && isPiano) { const nx = melodyNext(n, i); if (Number.isFinite(nx) && Math.abs(nx - (n.t + n.d)) < 1e-6) end = sec(sw(nx)) + 0.035; }+ else if (isPiano) end = t + (end - t) * 0.92;+ }+ keys.push({ t: Math.max(0, t), off: Math.max(t + 0.03, end), p: n.p, v: clamp(v, 0.03, 1), role: n.role, kind: n.kind, w: n.v });+ });+ return { id: pt.id, keys };+ });+ // pedal: lift just after each harmony change, catch again ~110 ms later (legato pedalling)+ const pedal: PedalSpan[] = [];+ if (o.expressive && p.harmony.length) {+ const ch = p.harmony.slice().sort((a, b) => a.t - b.t);+ for (let i = 0; i < ch.length; i++) {+ const down = sec(sw(ch[i].t)) + 0.11, up = i + 1 < ch.length ? sec(sw(ch[i + 1].t)) + 0.03 : 1e9;+ pedal.push([down, up]);+ }+ }+ const lastOnset = Math.max(...parts.flatMap((pp) => pp.keys.map((k) => k.t)));+ return { parts, pedal, sec: (b) => sec(sw(b)), lastOnset, meanLeadMs: leadN ? (leadSum / leadN) * 1000 : 0 };+};diff --git a/engine/src/canvas-core/music/piano.ts b/engine/src/canvas-core/music/piano.tsnew file mode 100644index 0000000..1e30bda--- /dev/null+++ b/engine/src/canvas-core/music/piano.ts@@ -0,0 +1,163 @@+// A modal, physics-shaped piano (ADVISORY-PLAN 4.1). No samples: every sound below is a sum of+// decaying sinusoids and filtered seeded noise. What each piece models, and where the numbers+// come from, is written next to it; the numbers are starting points confirmed only by a listen.+//+// strings f_n = n f0 sqrt(1 + B n^2), B rising from bass to treble (Fletcher 1964 shape)+// unisons 2-3 strings per key detuned 0.3-1.8 cents: a fast "prompt" decay (strings in+// phase, coupled through the bridge) and a slow beating "aftersound" (Weinreich 1977)+// hammer velocity sets loudness AND the spectrum (a faster hammer = shorter contact =+// brighter); the strike point near 1/8 of the string notches partial ~8+// losses every partial decays at its own rate, faster with frequency; sustain by register+// attack a keybed/hammer knock (low thump + short click) and a soundboard modal body+// dampers key-up or pedal-up engages the felt: fast decay plus a breath of felt noise;+// the top keys (MIDI >= 89) have no dampers, as on a real grand+// pedal sustain pedal holds dampers off; undamped strings whose partials coincide with+// the played notes ring sympathetically; a pedal "halo" feeds the room+// stereo bass left, treble right (player's seat)+import { type Rng, TAU, clamp, pan, onePoleCoef, SVF, gauss } from "./dsp";+import { rng as mkRng } from "../core";++export type PianoOpts = { inharmonic: boolean; multiString: boolean; twoStage: boolean; hammer: boolean; knock: boolean; body: boolean; sympathetic: boolean; damperNoise: boolean; stretch: boolean; pedal: boolean; width: number };+export const PIANO_REAL: PianoOpts = { inharmonic: true, multiString: true, twoStage: true, hammer: true, knock: true, body: true, sympathetic: true, damperNoise: true, stretch: true, pedal: true, width: 0.4 };+/** The contrast baseline: harmonic partials, one string, one-slope decay, fixed spectrum, no pedal. */+export const PIANO_FLAT: PianoOpts = { inharmonic: false, multiString: false, twoStage: false, hammer: false, knock: false, body: false, sympathetic: false, damperNoise: false, stretch: false, pedal: false, width: 0.4 };++/** A performed key press in seconds: onset t, key release `off`, MIDI p, velocity v 0..1. */+export type KeyPress = { t: number; off: number; p: number; v: number };+export type PedalSpan = [number, number];++const f0Of = (m: number, stretch: boolean) => 440 * Math.pow(2, (m - 69) / 12 + (stretch ? (m > 60 ? 0.012 * Math.pow(m - 60, 1.9) : -0.02 * Math.pow(60 - m, 1.6)) / 1200 : 0));+/** Inharmonicity coefficient by key: ~1e-4 in the wound bass, ~5e-4 at C4, ~4e-3 at C7. */+export const inharmonicityB = (m: number) => Math.pow(10, m <= 40 ? -3.8 + 0.015 * (40 - m) : -3.8 + 0.0245 * (m - 40));+/** Aftersound T60 of the fundamental by key (s): ~20 s at C4, ~6 s at C6; the prompt sound is 4x faster. */+const t60After = (m: number) => clamp(20 * Math.pow(2, (-0.9 * (m - 60)) / 12), 1.6, 40);+/** Register trim (dB) so a scale at one velocity reads roughly even; measured by the probe, see METERS.md. */+const regGain = (m: number) => Math.pow(10, (m > 60 ? 0.15 * (m - 60) : 0.03 * (60 - m)) / 20);+const strings = (m: number) => (m < 32 ? 1 : m < 44 ? 2 : 3);++export const renderPiano = (keys: KeyPress[], pedal: PedalSpan[], sr: number, n: number, o: PianoOpts, seed: number) => {+ const L = new Float32Array(n), R = new Float32Array(n), halo = new Float32Array(n), bodyIn = new Float32Array(n);+ const rnd: Rng = mkRng(seed * 31 + 7);+ const pedalAt = (t: number) => o.pedal && pedal.some(([a, b]) => t >= a && t < b);+ const pedalUpAfter = (t: number) => { for (const [a, b] of pedal) if (t >= a && t < b) return b; return t; };+ const sorted = keys.slice().sort((a, b) => a.t - b.t);+ const maxLen = Math.min(n, Math.ceil(32 * sr));+ const buf = new Float64Array(maxLen);++ sorted.forEach((k, idx) => {+ const m = k.p, v = clamp(k.v, 0.02, 1), i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const keyR = mkRng(m * 7919 + seed); // per-KEY constants: the same key always has the same strings+ const f0 = f0Of(m, o.stretch), B = o.inharmonic ? inharmonicityB(m) : 0, S = o.multiString ? strings(m) : 1;+ const detune = Array.from({ length: S }, (_, s) => (S === 1 ? 0 : (s - (S - 1) / 2) * (0.35 + 1.4 * keyR()) / 1200 * Math.LN2));+ const beta = 0.118 + 0.012 * keyR() + (m > 72 ? -0.02 * (m - 72) / 36 : 0);+ // when does the felt land on the strings?+ let damp = o.pedal ? (pedalAt(k.off) ? pedalUpAfter(k.off) : k.off) : k.off;+ if (m >= 89) damp = Infinity;+ // a restrike of the same key stops this instance's strings+ for (let j = idx + 1; j < sorted.length; j++) if (sorted[j].p === m && sorted[j].t > k.t) { damp = Math.min(damp, sorted[j].t + 0.004); break; }+ const t60a = t60After(m), sigA0 = 6.91 / t60a, sigP0 = sigA0 * 4, sigSingle = sigA0 * 2.4;+ const sigD = 6.91 / (0.1 + 0.28 * clamp((60 - m) / 36, 0, 1));+ const dampI = damp === Infinity ? Infinity : Math.round((damp - k.t) * sr);+ const natural = Math.round(Math.min(t60a * 1.05, 32) * sr);+ const len = Math.min(maxLen, n - i0, dampI === Infinity ? natural : Math.min(natural, dampI + Math.round(0.9 * sr)));+ if (len <= 0) return;+ buf.fill(0, 0, len);+ // hammer: loudness and brightness from velocity; contact time shorter when harder+ // felt hardening: above mf a faster hammer mostly buys brightness, less level (exponent 1.55 -> 0.9)+ const loud = v < 0.6 ? Math.pow(v, 1.55) : Math.pow(0.6, 1.55) * Math.pow(v / 0.6, 0.9);+ const fc = o.hammer ? (330 + 3300 * v * v) * Math.pow(f0 / 262, 0.3) : 1300 * Math.pow(f0 / 262, 0.3);+ const nyq = Math.min(0.45 * sr, 15000);+ let a1 = 0;+ for (let p = 1; p <= 90; p++) {+ const fn = p * f0 * Math.sqrt(1 + B * p * p); if (fn > nyq) break;+ const comb = o.hammer ? 0.1 + 0.9 * Math.abs(Math.sin(Math.PI * p * beta)) : 1;+ const ham = 1 / Math.sqrt(1 + Math.pow(fn / fc, 6)) * (o.hammer ? 1 : 1 / Math.pow(p, 0.35));+ const rad = (fn * fn) / (fn * fn + 105 * 105) / Math.sqrt(1 + Math.pow(fn / 6500, 4));+ const A = (comb * ham * rad) / Math.pow(p, 0.9);+ if (p === 1) a1 = Math.max(A, 1e-6);+ if (A < a1 * 2e-4 && p > 3) continue;+ const fac = 1 + 0.8 * Math.pow(fn / 1500, 2) + fn / 4000;+ const ph = TAU * keyR(); // deterministic per key+ const comps: [number, number, number][] = []; // [freq, amp, sigma]+ if (o.twoStage) {+ const wa = 0.2 / (1 + 0.12 * (p - 1));+ comps.push([fn, A * (1 - wa), sigP0 * fac]);+ if (S > 1) { comps.push([fn * Math.exp(detune[0]), (A * wa) / 2, sigA0 * fac]); comps.push([fn * Math.exp(detune[S - 1]), (A * wa) / 2, sigA0 * fac * 1.07]); }+ else comps.push([fn, A * wa, sigA0 * fac]);+ } else {+ const sig = o.multiString ? sigSingle * fac : sigSingle * (1 + 0.5 * (p - 1));+ if (S > 1) for (let s = 0; s < S; s++) comps.push([fn * Math.exp(detune[s]), A / S, sig]);+ else comps.push([fn, A, sig]);+ }+ comps.forEach(([f, amp, sig], ci) => {+ const w = (TAU * f) / sr, cr = Math.cos(w), ci_ = Math.sin(w);+ let re = amp * Math.cos(ph + ci * 1.3), im = amp * Math.sin(ph + ci * 1.3);+ const dec = Math.exp(-sig / sr), decD = Math.exp(-(sig + sigD) / sr);+ const floor = a1 * 1e-5;+ // how long until this component is inaudible (undamped part)+ const lenC = Math.min(len, Math.ceil((Math.log(amp / floor) / sig) * sr) + 1);+ const dI = Math.min(lenC, dampI === Infinity ? lenC : Math.max(0, dampI));+ for (let i = 0; i < dI; i++) { buf[i] += re; const r2 = (re * cr - im * ci_) * dec; im = (re * ci_ + im * cr) * dec; re = r2; }+ if (dI < lenC) { const lenD = Math.min(lenC, dI + Math.ceil((Math.log(Math.max(Math.hypot(re, im), floor * 1.0001) / floor) / (sig + sigD)) * sr) + 1);+ for (let i = dI; i < lenD; i++) { buf[i] += re; const r2 = (re * cr - im * ci_) * decD; im = (re * ci_ + im * cr) * decD; re = r2; } }+ });+ }+ // hammer contact ramp: 2.2 ms (ff) to 4 ms (pp), raised cosine; this is also a gentle low-pass on the attack+ const ramp = Math.max(2, Math.round((o.hammer ? 4.2 - 2.0 * v : 1.5) / 1000 * sr));+ for (let i = 0; i < ramp && i < len; i++) buf[i] *= 0.5 - 0.5 * Math.cos((Math.PI * i) / ramp);+ const REF = 0.37, norm = ((0.22 * loud) / REF) * regGain(m); // fixed scale: register balance comes from the physics, trimmed by regGain+ // knock: a low thump from the action and keybed plus a short click where the hammer lands+ if (o.knock) {+ const kl = Math.min(len, Math.round(0.06 * sr)), sv = new SVF(sr, 2400 + 1600 * v, 0.9);+ for (let i = 0; i < kl; i++) {+ const t = i / sr;+ buf[i] += (0.9 * Math.sin(TAU * 92 * t) * Math.exp(-t / 0.018) + 0.5 * Math.sin(TAU * 205 * t) * Math.exp(-t / 0.011)) * 0.10 * v * REF;+ buf[i] += sv.tick(gauss(rnd)) * Math.exp(-t / 0.0028) * 0.35 * v * v * REF;+ }+ }+ // felt landing on the strings: a breath of low noise at the damp point+ const [gl, gr] = pan(clamp((m - 62) / 34, -1, 1) * o.width);+ if (o.damperNoise && dampI !== Infinity && dampI < len) {+ const sv = new SVF(sr, 500, 0.7), dl = Math.min(len - dampI, Math.round(0.07 * sr));+ for (let i = 0; i < dl; i++) buf[dampI + i] += sv.tick(gauss(rnd)) * Math.sin((Math.PI * i) / dl) * 0.012 * v * REF;+ }+ const inPedal = pedalAt(k.t) || pedalAt(k.t + 0.25);+ for (let i = 0; i < len; i++) {+ const s = buf[i] * norm, j = i0 + i;+ L[j] += s * gl; R[j] += s * gr;+ if (o.body) bodyIn[j] += s * 0.05;+ if (inPedal) halo[j] += s;+ }+ // soundboard excitation: the hammer's force pulse+ if (o.body) { const pl = Math.round((0.0035 - 0.0025 * v) * sr); for (let i = 0; i < pl && i0 + i < n; i++) bodyIn[i0 + i] += Math.sin((Math.PI * i) / pl) * 0.45 * loud * 0.22; }+ // sympathetic strings: open strings whose partials coincide with this note's ring while the pedal is down+ if (o.sympathetic && inPedal) {+ const up = pedalUpAfter(Math.max(k.t, k.t + 0.25));+ const endI = Math.min(n - i0, Math.round((up - k.t) * sr) + Math.round(0.25 * sr), Math.round(10 * sr));+ for (const [off, harmOfGhost, harmOfNote, cpl] of [[-12, 2, 1, 0.07], [-19, 3, 1, 0.05], [-24, 4, 1, 0.035], [12, 1, 2, 0.05], [19, 1, 3, 0.03], [7, 2, 3, 0.03]] as const) {+ const gm = m + off; if (gm < 21 || gm > 108) continue;+ const gf0 = f0Of(gm, o.stretch), gB = o.inharmonic ? inharmonicityB(gm) : 0;+ const f = harmOfGhost * gf0 * Math.sqrt(1 + gB * harmOfGhost * harmOfGhost);+ const noteP = harmOfNote * f0 * Math.sqrt(1 + B * harmOfNote * harmOfNote);+ const mis = Math.abs(f - noteP) / noteP; if (mis > 0.004) continue;+ const sig = 6.91 / t60After(gm) * (1 + 0.8 * Math.pow(f / 1500, 2)), dec = Math.exp(-sig / sr);+ const [pl, pr] = pan(clamp((gm - 62) / 34, -1, 1) * o.width);+ const amp = 0.22 * loud * cpl * (harmOfNote === 1 ? 1 : 0.5), w = (TAU * f) / sr, rise = Math.exp(-1 / (0.18 * sr));+ let e = 1, env = 0; const dampStart = Math.round((up - k.t) * sr), decD = Math.exp(-(sig + 25) / sr);+ let g = 1, c = Math.cos(gm), sn = Math.sin(gm); const cw = Math.cos(w), sw = Math.sin(w);+ for (let i = 0; i < endI; i++) { env = 1 - (e *= rise); const sOut = sn * amp * env * g; L[i0 + i] += sOut * pl; R[i0 + i] += sOut * pr; halo[i0 + i] += sOut; g *= i < dampStart ? dec : decD; const c2 = c * cw - sn * sw; sn = c * sw + sn * cw; c = c2; }+ }+ }+ });+ // soundboard: a bank of ~40 fixed modes excited by the hammer pulses and a trace of the strings+ if (o.body) {+ const br = mkRng(seed * 13 + 101), out = new Float32Array(n);+ for (let k = 0; k < 40; k++) {+ const f = 70 * Math.pow(3600 / 70, (k + br()) / 40), q = 12 + 26 * br(), g = (0.5 + br()) / Math.sqrt(f / 70) * 0.9;+ const sv = new SVF(sr, f, q); for (let i = 0; i < n; i++) { sv.tick(bodyIn[i]); out[i] += sv.bp * g; }+ }+ const hp = onePoleCoef(sr, 60); let z = 0;+ for (let i = 0; i < n; i++) { z += hp * (out[i] - z); const s = (out[i] - z) * 0.16; L[i] += s * 0.95; R[i] += s * 0.85; }+ }+ return { L, R, halo };+};diff --git a/engine/src/canvas-core/music/pieces/families.ts b/engine/src/canvas-core/music/pieces/families.tsnew file mode 100644index 0000000..b3832b5--- /dev/null+++ b/engine/src/canvas-core/music/pieces/families.ts@@ -0,0 +1,118 @@+// First-use samplers for the families that rendered but had no demo, plus the drive/electronic and+// folk/acoustic styles. 8 seconds each (the spec-08 human-listen budget), each a complete musical+// thought with a cadence, each carrying ONE named emotion. Every note written by hand.+import { line, type Piece, type Role } from "../plan";++const L = (t: number, s: string, role: Role, bpb: number, v = 0.7, extra: { roll?: number; kind?: string; pickup?: number } = {}) => line(t, s, { role, v, bpb, ...extra });+const H = (xs: [number, string][]) => xs.map(([t, name]) => ({ t, name }));+const rep = (cell: string, n: number) => Array.from({ length: n }, () => cell).join(" ");++/** Marimba, CURIOUS. D dorian (the B natural is the colour), minimalist: an eighth-note ostinato under a questioning hook. 4/4 at 108. */+export const marimbaCurious = (): Piece => {+ const B = 4;+ const ost = L(0, ["D4:.5 A4:.5 E5:.5 F5:.5 A4:.5 E5:.5 D5:.5 A4:.5", "D4:.5 B4:.5 E5:.5 G5:.5 B4:.5 E5:.5 D5:.5 B4:.5",+ "D4:.5 A4:.5 E5:.5 F5:.5 A4:.5 E5:.5 D5:.5 A4:.5", "[D4 A4]:1"].join(" | "), "accomp", B, 0.55);+ // the hook asks (up to D6, then B natural), answers stepwise down to the tonic+ const hook = L(0, "r:1 A5:.5 C6:.5 D6:1 C6:.5 A5:.5 | B5:1.5 G5:.5 A5:1 r:1 | F5:.5 E5:.5 D5:.5 E5:.5 F5:1 E5:1 | D5:1", "melody", B, 0.8);+ const low = L(0, "D3:2 A2:2 | G2:2 D3:2 | D3:2 A2:2 | D3:1", "bass", B, 0.7);+ return {+ title: "Marimba, curious (D dorian)", seed: 404, tail: 1.2, harmony: H([[0, "Dm"], [4, "G/D"], [8, "Dm"], [12, "Dm"]]),+ plan: { style: "minimalist", tempo: 108, meter: "4/4", ritard: 0.9, sections: [{ id: "a", bars: 4, mood: "curious", key: "D", mode: "dorian", melody: ["ostinato", "hook"], dyn: [0.65, 0.72], ending: "button", repeatable: true }] },+ parts: [+ { id: "ostinato", inst: "marimba", role: "accomp", notes: ost, gainDb: -3 },+ { id: "hook", inst: "marimba", role: "melody", notes: hook, gainDb: 1 },+ { id: "low", inst: "marimba", role: "bass", notes: low, gainDb: -1 },+ { id: "halo", inst: "vibes", role: "color", notes: L(0, "[F4 A4 E5]:4 | [G4 B4 E5]:4 | [F4 A4 E5]:4 | [F4 A4 D5]:1", "color", B, 0.35), gainDb: -12, opts: { trem: 4.5 } },+ ],+ };+};++/** Harp, TENDER. E-flat major lullaby in 6/8 at 66: rolling arpeggios, a rocking melody, I-IV-V7-I. */+export const harpTender = (): Piece => {+ const B = 2, e = (a: string) => a.split(" ").map((n) => `${n}:1/3`).join(" ");+ const arp = L(0, [e("Eb3 Bb3 Eb4 G4 Bb4 G4"), e("Eb3 C4 Ab4 C5 Ab4 Eb4"), e("D3 Bb3 F4 Ab4 F4 Bb3"), e("Eb3 Bb3 Eb4 G4 Bb4 Eb5")].join(" | "), "accomp", B, 0.55);+ const mel = L(0, "G5:1 Bb5:1/3 Ab5:1/3 G5:1/3 | F5:2/3 Eb5:1/3 F5:1/3 Ab5:2/3 | G5:1 F5:1/3 Eb5:1/3 D5:1/3 | Eb5:2", "melody", B, 0.75);+ return {+ title: "Harp, tender (E-flat lullaby)", seed: 55, tail: 1.2, harmony: H([[0, "Eb"], [2, "Ab/Eb"], [4, "Bb7/D"], [6, "Eb"]]),+ plan: { style: "lullaby", tempo: 66, meter: "6/8", sections: [{ id: "a", bars: 4, mood: "tender", key: "Eb", mode: "major", melody: ["arpeggio", "stepwise"], dyn: [0.55, 0.5], ending: "tail", repeatable: true }] },+ parts: [{ id: "arp", inst: "harp", role: "accomp", notes: arp, gainDb: -8 }, { id: "melody", inst: "harp", role: "melody", notes: mel, gainDb: 2 }],+ };+};++/** Guitar (Karplus-Strong), WISTFUL. E dorian fingerpicking, Em - A (the dorian IV) - Em, 4/4 at 84. */+export const guitarWistful = (): Piece => {+ const B = 4;+ const pick = L(0, "E2:.5 G3:.5 B3:.5 E4:.5 B2:.5 G3:.5 B3:.5 E4:.5 | A2:.5 E3:.5 C#4:.5 E4:.5 E2:.5 E3:.5 A3:.5 C#4:.5 | [E2 B2 E3 G3 B3 F#4]:1", "accomp", B, 0.55, { roll: 0.022 });+ const mel = L(0, "B4:1.5 A4:.5 G4:1 F#4:1 | E4:1 C#5:1.5 B4:.5 A4:1 | B4:1", "melody", B, 0.8);+ return {+ title: "Guitar, wistful (E dorian)", seed: 77, tail: 2.0, harmony: H([[0, "Em"], [4, "A"], [8, "Em9"]]),+ plan: { style: "folk", tempo: 84, meter: "4/4", ritard: 0.8, sections: [{ id: "a", bars: 3, mood: "wistful", key: "E", mode: "dorian", melody: ["stepwise"], dyn: [0.6, 0.55], ending: "tail", repeatable: true }] },+ parts: [{ id: "pick", inst: "guitar", role: "accomp", notes: pick, gainDb: -7 }, { id: "melody", inst: "guitar", role: "melody", notes: mel, gainDb: 3 }],+ };+};++/** Celesta, WONDER (curious + awe). F lydian: the B natural of the G/F chord is the magic. 3/4 at 72. */+export const celestaWonder = (): Piece => {+ const B = 3;+ const acc = L(0, "F3:1 [A4 C5]:1 [A4 C5]:1 | F3:1 [G4 B4 D5]:1 [G4 B4 D5]:1 | [F3 C4 A4]:3", "accomp", B, 0.5, { roll: 0.02 });+ const mel = L(0, "C6:.5 A5:.5 F5:.5 A5:.5 C6:.5 E6:.5 | D6:1 B5:1 A5:.5 G5:.5 | A5:3", "melody", B, 0.8);+ return {+ title: "Celesta, wonder (F lydian)", seed: 9, tail: 2.4, harmony: H([[0, "F"], [3, "G/F"], [6, "F"]]),+ plan: { style: "lullaby", tempo: 72, meter: "3/4", sections: [{ id: "a", bars: 3, mood: ["curious", "awe", 0.5], key: "F", mode: "lydian", melody: ["hook", "arpeggio"], dyn: [0.6, 0.55], ending: "tail", repeatable: true }] },+ parts: [{ id: "acc", inst: "celesta", role: "accomp", notes: acc, gainDb: -4 }, { id: "melody", inst: "celesta", role: "melody", notes: mel, gainDb: 1 }],+ };+};++/** FM bell over FM e-piano, HOPEFUL. C major IV-V-vi-V/3 -> I, the bell line climbing in sequence A5 B5 C6 D6 -> E6. 4/4 at 100. */+export const bellsHopeful = (): Piece => {+ const B = 4;+ const bell = L(0, "C5:.5 F5:.5 A5:1 D5:.5 G5:.5 B5:1 | E5:.5 A5:.5 C6:1 D5:.5 G5:.5 D6:1 | E6:2", "melody", B, 0.75);+ const keys = L(0, "[F3 A3 C4 E4]:2 [G3 B3 D4]:2 | [A3 C4 E4]:2 [B2 D4 G4]:2 | [C3 G3 C4 E4]:2", "accomp", B, 0.6, { roll: 0.02 });+ return {+ title: "Bells and e-piano, hopeful (C major)", seed: 31, tail: 2.6, harmony: H([[0, "Fmaj7"], [2, "G"], [4, "Am"], [6, "G/B"], [8, "C"]]),+ plan: { style: "cinematic", tempo: 100, meter: "4/4", ritard: 0.85, sections: [{ id: "a", bars: 3, mood: "hopeful", key: "C", mode: "major", melody: ["sequence"], dyn: [0.5, 0.8], ending: "tail", repeatable: true }] },+ parts: [{ id: "bell", inst: "fmBell", role: "melody", notes: bell, gainDb: 0 }, { id: "keys", inst: "ePiano", role: "accomp", notes: keys, gainDb: -2, opts: { trem: 3.5 } }],+ };+};++/** Drive / electronic, DRIVE. A minor i-VI-III-VII at 128: pluck arps and 8th bass from bar 1, the lead hook drops in at bar 3, a stab button. */+export const driveElectronic = (): Piece => {+ const B = 4, a16 = (x: string) => rep(x.split(" ").map((n) => `${n}:.25`).join(" "), 4);+ const pluckL = L(0, [a16("A4 C5 E5 A5"), a16("F4 A4 C5 F5"), a16("E4 G4 C5 E5"), a16("D4 G4 B4 D5"), "[A4 C5 E5]:.5"].join(" | "), "accomp", B, 0.6);+ const bassL = L(0, [rep("A1:.5 A2:.5", 4), rep("F1:.5 F2:.5", 4), rep("C2:.5 C3:.5", 4), rep("G1:.5 G2:.5", 4), "A1:.5"].join(" | "), "bass", B, 0.85);+ const lead = L(8, "E5:.75 D5:.25 C5:.5 E5:.5 G5:1.5 E5:.5 | D5:.75 C5:.25 B4:.5 D5:.5 G5:1 B4:1 | A5:.5", "melody", B, 0.8);+ const pad = L(0, "[A3 C4 E4]:4 | [F3 A3 C4]:4 | [G3 C4 E4]:4 | [G3 B3 D4]:4", "color", B, 0.45);+ const kick = L(0, [rep("C4:1", 4), rep("C4:1", 4), rep("C4:1", 4), rep("C4:1", 4), "C4:.5"].join(" | "), "drum", B, 0.9);+ const clap = L(0, "r:1 C4:1 r:1 C4:1 | r:1 C4:1 r:1 C4:1 | r:1 C4:1 r:1 C4:1 | r:1 C4:1 r:1 C4:.5 C4:.5", "drum", B, 0.7);+ const hats = L(0, [1, 2, 3, 4].map(() => rep("r:.5 C4:.5", 4)).join(" | "), "drum", B, 0.7, { kind: "o" });+ return {+ title: "Drive / electronic (A minor)", seed: 128, tail: 0.5, harmony: H([[0, "Am"], [4, "F"], [8, "C"], [12, "G"], [16, "Am"]]),+ plan: { style: "drive", tempo: 128, meter: "4/4", ritard: 1, sections: [{ id: "a", bars: 5, mood: "drive", key: "A", mode: "aeolian", melody: ["hook", "arpeggio", "ostinato"], dyn: [0.8, 0.9], ending: "button", repeatable: true }] },+ parts: [+ { id: "pluck", inst: "strings", role: "accomp", notes: pluckL, gainDb: -6, opts: { attack: 0.004, release: 0.09, bright: 1.5, width: 0.9, grid: true } },+ { id: "bass", inst: "bass", role: "bass", notes: bassL, gainDb: -2, opts: { drive: 2.4, grid: true } },+ { id: "lead", inst: "strings", role: "melody", notes: lead, gainDb: 0, opts: { attack: 0.012, release: 0.15, bright: 1.8, width: 0.4, grid: true } },+ { id: "pad", inst: "strings", role: "color", notes: pad, gainDb: -10, opts: { attack: 0.35, release: 0.4, grid: true } },+ { id: "kick", inst: "kick", role: "drum", notes: kick, gainDb: 0, send: 0, opts: { soft: 0.3, grid: true } },+ { id: "clap", inst: "snare", role: "drum", notes: clap, gainDb: -5, send: 0.5, opts: { grid: true } },+ { id: "hat", inst: "hat", role: "drum", notes: hats, gainDb: -9, send: 0.2, opts: { grid: true } },+ ],+ };+};++/** Folk / acoustic, CALM. G mixolydian (F natural on the bVII) in 6/8 at 88: fingerpicked guitar, harp melody, a brushed shaker. */+export const folkCalm = (): Piece => {+ const B = 2, e = (a: string) => a.split(" ").map((n) => `${n}:1/3`).join(" ");+ const pick = L(0, [e("G2 D3 G3 B3 G3 D3"), e("F2 C3 F3 A3 F3 C3"), e("C3 G3 C4 E4 C4 G3"), e("G2 D3 G3 B3 G3 D3"), "[G2 D3 G3 B3 D4 G4]:2"].join(" | "), "accomp", B, 0.55, { roll: 0.02 });+ const mel = L(0, "G4:1/3 B4:1/3 D5:1/3 G5:1 | F5:2/3 E5:1/3 D5:2/3 C5:1/3 | E5:1 C5:1/3 D5:1/3 E5:1/3 | D5:2/3 B4:1/3 A4:2/3 B4:1/3 | G4:2", "melody", B, 0.75);+ const shaker = L(0, [1, 2, 3, 4].map(() => "C4:1/3@1 C4:1/[email protected] C4:1/[email protected] C4:1/[email protected] C4:1/[email protected] C4:1/[email protected]").join(" | "), "drum", B, 0.5);+ return {+ title: "Folk, calm (G mixolydian)", seed: 1971, tail: 1.3, harmony: H([[0, "G"], [2, "F"], [4, "C"], [6, "G"], [8, "G"]]),+ plan: { style: "folk", tempo: 88, meter: "6/8", ritard: 0.8, sections: [{ id: "a", bars: 5, mood: "calm", key: "G", mode: "mixolydian", melody: ["stepwise"], dyn: [0.6, 0.55], ending: "tail", repeatable: true }] },+ parts: [+ { id: "pick", inst: "guitar", role: "accomp", notes: pick, gainDb: -5 },+ { id: "melody", inst: "harp", role: "melody", notes: mel, gainDb: 2 },+ { id: "shaker", inst: "hat", role: "drum", notes: shaker, gainDb: -14, send: 0.3 },+ ],+ };+};diff --git a/engine/src/canvas-core/music/pieces/fixtures.ts b/engine/src/canvas-core/music/pieces/fixtures.tsnew file mode 100644index 0000000..8432cfb--- /dev/null+++ b/engine/src/canvas-core/music/pieces/fixtures.ts@@ -0,0 +1,22 @@+// THE HATED FIXTURE: a deliberate "ghost crying" (the scar in the old recipe): a slow string pad,+// 2-second attacks, whole-bar chords drifting by chromatic mediants with no dominant and no+// cadence, no rhythm layer, a long reverb tail pushed almost level with the dry sound. It exists so+// the ghost guard has something it MUST fail. Never use it in a film.+import { line, type Piece } from "../plan";++export const ghostFixture = (): Piece => {+ const pad = line(0, "[C4 E4 G4 B4]:8 | [Eb4 G4 Bb4 D5]:8 | [Ab3 C4 Eb4 G4]:8 | [E4 G#4 B4 D#5]:8", { role: "accomp", v: 0.6, bpb: 8 });+ const low = line(0, "C3:8 | Eb3:8 | Ab2:8 | E3:8", { role: "bass", v: 0.5, bpb: 8 });+ const sigh = line(0, "r:4 G5:4 | r:6 F5:2 | r:8 | r:4 D#5:4", { role: "melody", v: 0.4, bpb: 8 });+ return {+ title: "Ghost fixture (hated: slow pad, long tail, no rhythm, no cadence)", seed: 13, tail: 3,+ harmony: [[0, "Cmaj7"], [8, "Ebmaj7"], [16, "Abmaj7"], [24, "Emaj7"]].map(([t, name]) => ({ t: t as number, name: name as string })),+ plan: { style: "ambient", tempo: 60, meter: "4/4", ritard: 1, space: { er: 0.5, late: 1.1, rt60: 5, hp: 150 },+ sections: [{ id: "drift", bars: 8, mood: "calm", key: "C", mode: "major", melody: ["drone"], dyn: [0.5, 0.5], ending: "tail" }] },+ parts: [+ { id: "pad", inst: "strings", role: "accomp", notes: pad, opts: { attack: 2.2, release: 3, bright: 0.6 }, send: 1.6 },+ { id: "low", inst: "strings", role: "bass", notes: low, opts: { attack: 2.5, release: 3, bass: true, bright: 0.4 }, send: 1.6 },+ { id: "sigh", inst: "strings", role: "melody", notes: sigh, opts: { attack: 1.5, release: 2.5 }, send: 1.8, gainDb: -3 },+ ],+ };+};diff --git a/engine/src/canvas-core/music/pieces/nocturne.ts b/engine/src/canvas-core/music/pieces/nocturne.tsnew file mode 100644index 0000000..4e0b0b7--- /dev/null+++ b/engine/src/canvas-core/music/pieces/nocturne.ts@@ -0,0 +1,113 @@+// "Window Light", a nocturne in A-flat major with F-minor colour. Composed note by note.+//+// THE HOOK is a rising sixth that falls back by step: Eb4 -> C5, Bb4, Ab4. It opens the theme,+// returns a step higher over IV, climbs an octave in bar 5, becomes the climax in bar 10 (Eb5 ->+// C6, the same sixth an octave up) and is said once more, pianissimo, in bar 12.+//+// bar 0 intro Ab the left hand alone, p+// bars 1-4 theme (Q) Ab Eb/G Db/F Eb bass walks down Ab G F Eb; half cadence+// bars 5-8 theme (A) Ab/C Fm Db Eb7 Ab the line climbs to F5 then falls home+// bars 9-10 build Fm Db | Eb F-minor colour, melody in octaves, f.+// The octave basses are STAGGERED: they answer+// an eighth after the melody's downbeat, so the+// climax C6 strikes alone (the peak stays musical)+// bar 11 HUSH Fm deceptive: V goes to vi, pp, sudden (~2/3)+// bars 12-15 coda Db Dbm Bbm7 Eb7 Ab the hook once more, high and quiet; the Fb+// of the borrowed iv is the ache; ii-V-I home+//+// The loved reference (Kevin Ngo's Claude piano, NOTES.md) builds ~12 dB to about 2/3 and drops to+// a quiet close; this piece is built on that SHAPE, in its key, with its own tune.+//+// Fitting: the intro is optional (the climax never is), theme+build repeat as a group (variations: the theme+// comes back doubled in octaves, then an octave higher), and under ~25 s the plan falls back to+// its short form, the 8-second phrase, which itself repeats.+import { line, type Piece } from "../plan";++const BPB = 3;+const mel = (t: number, s: string, v = 0.7, pickup?: number) => line(t, s, { role: "melody", v, bpb: BPB, pickup });+const inner = (t: number, s: string, v = 0.7) => line(t, s, { role: "inner", v, bpb: BPB });+const bass = (t: number, s: string, v = 0.7, pickup?: number) => line(t, s, { role: "bass", v, bpb: BPB, roll: 0.03, pickup });+const lh = (t: number, s: string, v = 0.7) => line(t, s, { role: "accomp", v, bpb: BPB, roll: 0.035 });+const H = (xs: [number, string][]) => xs.map(([t, name]) => ({ t, name }));++export const nocturne = (): Piece => {+ const melody = [+ ...mel(2, "Eb4:1", 0.66, 1), // the pickup, in the intro bar+ ...mel(3, [+ "C5:2 Bb4:.5 Ab4:.5", // 1 Ab+ "Bb4:2 Eb4:1", // 2 Eb/G (Eb4 = the hook's pickup again)+ "Db5:2 C5:.5 Bb4:.5", // 3 Db/F (the hook a step higher)+ "G4:.5 Ab4:.5 Bb4:1 Eb4:1", // 4 Eb half cadence on 2 over V+ "Eb5:2 Db5:.5 C5:.5", // 5 Ab/C (the hook an octave wide)+ "Ab4:1 C5:1 F5:1", // 6 Fm climbing to the phrase's high point+ "Eb5:1.5 Db5:.5 C5:.5 Bb4:.5", // 7 Db | Eb7 falling home+ "Ab4:2 C5:1", // 8 Ab cadence; C5 is the pickup into the build+ "Ab5:1.5 G5:.5 F5:.5 Eb5:.5", // 9 Fm | Db (octaves below); Eb5 lifts into the climax+ "C6:[email protected] Bb5:.5 Ab5:.5 G5:.5", // 10 Eb CLIMAX: the hook's sixth, Eb5 -> C6 (a full rolled chord, below)+ "Ab5:2 r:.5 Eb5:.5", // 11 Fm HUSH (deceptive); Eb5 picks up the hook+ "C6:2 Bb5:.5 Ab5:.5", // 12 Db the hook, pianissimo, over Db maj7 colour+ "Ab5:1 Fb5:1 Eb5:1", // 13 Dbm borrowed iv: Fb, the F-minor ache+ "Db5:1.5 C5:.5 Bb4:1", // 14 Bbm7 | Eb7+ "Ab4:3", // 15 Ab home+ ].join(" | ")),+ ];+ // octave doubling in the build, softer (an inner voice); the climax C6 itself is NOT doubled+ const octaves = inner(27, "r:1.5 G4:.5 F4:.5 r:.5 | r:1.5 Bb4:.5 Ab4:.5 G4:.5", 0.8); // joins after each downbeat, never on it+ // the climax is a CHORD, not one hammer: C6 on top of a rolled Eb5-Ab5 (C6 over Eb is the sweet 13th).+ // Spreading the climax's energy over three staggered keys keeps its loudness and lowers its peak.+ const climaxChord = line(30, "[Eb5 Ab5]:1.5", { role: "inner", v: 0.62, bpb: BPB, roll: 0.045, pickup: 1.5 });+ const rhInner = [...climaxChord, ...inner(15, "Ab4:2 r:1 | r:3 | F4:1.5 G4:1.5 | Eb4:2 r:1", 0.62), ...inner(45, "[C4 Eb4]:3", 0.55)];+ const bassLine = [+ ...bass(0, [+ "Ab2:3", "Ab2:3", "G2:3", "F2:3", "Eb2:3", // 0-4 (keys held, the pedal sustains)+ "C3:3", "F2:3", "Db2:1.5 Eb2:1.5", "Ab2:3", // 5-8+ "r:.5 [F1 F2]:[email protected] [Db2 Db3]:[email protected]", // 9 the bass ANSWERS: an eighth after the melody's downbeat+ "r:.5 [Eb1 Eb2]:[email protected]", // 10 C6 strikes alone; the Eb octave answers it+ "[F2 C3 Ab3]:3", "[Db2 Ab2 F3]:3", "[Db2 Ab2 Fb3]:3", "[Bb1 F2]:1.5 [Eb2 Bb2]:1.5", "[Ab1 Eb2 Ab2 Eb3 Ab3]:3", // 11-15 rolled+ ].join(" | "), 0.7),+ ];+ const accomp = lh(0, [+ "r:1 Eb3:1 C4:1", "r:1 Eb3:1 C4:1", "r:1 Eb3:1 Bb3:1", "r:1 Db3:1 Ab3:1", "r:1 Bb2:1 G3:1", // 0-4+ "r:.5 Eb3:.5 Ab3:.5 C4:.5 Ab3:.5 Eb3:.5", // 5 Ab/C eighths: the pulse quickens with the answer+ "r:.5 C3:.5 Ab3:.5 C4:.5 Ab3:.5 C3:.5", // 6 Fm+ "r:.5 Ab2:.5 F3:.5 r:.5 Db3:.5 G3:.5", // 7 Db | Eb7+ "r:.5 Eb3:.5 Ab3:.5 C4:.5 Ab3:.5 Eb3:.5", // 8 Ab+ "r:.5 C3:.5 Ab3:.5 r:.5 Ab2:.5 F3:.5", // 9 Fm | Db+ "r:.5 Bb2:.5 G3:.5 Bb3:.5 G3:.5 Db4:.5", // 10 Eb(7)+ "r:2 C4:1", "r:2 Ab3:1", "r:2 Ab3:1", // 11-13: the hush, single notes+ "r:.5 Db3:.5 Ab3:.5 r:.5 Db3:.5 G3:.5", // 14 Bbm7 | Eb7+ "r:3",+ ].join(" | "), 0.7);+ const harmony = H([[0, "Ab"], [3, "Ab"], [6, "Eb/G"], [9, "Db/F"], [12, "Eb"], [15, "Ab/C"], [18, "Fm"], [21, "Db"], [22.5, "Eb7"], [24, "Ab"],+ [27, "Fm"], [28.5, "Db"], [30, "Eb"], [31.5, "Eb"], [33, "Fm"], [36, "Db"], [39, "Dbm"], [42, "Bbm7"], [43.5, "Eb7"], [45, "Ab"]]);+ return {+ title: "Window Light (nocturne in A-flat)", seed: 1618, tail: 1.6, harmony, shortForm: pianoPhrase8,+ plan: {+ style: "nocturne", tempo: 68, meter: "3/4", phraseBars: 4,+ sections: [+ { id: "intro", bars: 1, mood: "tender", key: "Ab", mode: "major", melody: ["stepwise"], dyn: [0.36, 0.38], optional: true },+ { id: "theme", bars: 8, mood: "tender", key: "Ab", mode: "major", melody: ["hook", "stepwise"], dyn: [0.4, 0.64], repeatable: true, pickup: 1, variations: ["octaveDouble", "octaveUp"] },+ { id: "build", bars: 2, mood: ["tender", "romantic", 0.5], key: "Ab", mode: "major", melody: ["hook", "sequence"], dyn: [0.68, 0.9], repeatable: true, pickup: 1 },+ { id: "coda", bars: 5, mood: ["tender", "melancholy", 0.4], key: "Ab", mode: "major", melody: ["themeTransformation"], dyn: [0.36, 0.28], ending: "tail" },+ ],+ },+ parts: [+ { id: "rh", inst: "piano", role: "melody", notes: [...melody, ...octaves, ...rhInner] },+ { id: "lh", inst: "piano", role: "accomp", notes: [...bassLine, ...accomp] },+ ],+ };+};++/** (a) 8 seconds: the hook and a full cadence, pickup + 2 bars + the final chord. 3/4, 66 bpm. Also the nocturne's short form. */+export const pianoPhrase8 = (): Piece => {+ const m = [...line(-1, "Eb4:1 | C5:2 Bb4:.5 Ab4:.5 | Eb5:1.5 Db5:.5 C5:.5 Bb4:.5 | Ab4:3", { role: "melody", v: 0.72, bpb: 3, pickup: 1 }),+ ...line(6, "[C4 Eb4]:3", { role: "inner", v: 0.55, bpb: 3, roll: 0.02 })];+ const l = [...line(0, "Ab2:3 | Db2:1.5 Eb2:1.5 | [Ab1 Eb2 Ab2 Eb3]:3", { role: "bass", v: 0.7, bpb: 3, roll: 0.03 }),+ ...line(0, "r:1 Eb3:1 C4:1 | r:.5 Ab2:.5 F3:.5 r:.5 Db3:.5 G3:.5 | r:3", { role: "accomp", v: 0.7, bpb: 3 })];+ return {+ title: "Window Light, the phrase", seed: 1618, tail: 1.3,+ harmony: H([[0, "Ab"], [3, "Db"], [4.5, "Eb7"], [6, "Ab"]]),+ plan: { style: "nocturne", tempo: 66, meter: "3/4", pickupBeats: 1, phraseBars: 3, ritard: 0.72, sections: [{ id: "phrase", bars: 3, mood: "tender", key: "Ab", mode: "major", melody: ["hook", "stepwise"], dyn: [0.42, 0.5], ending: "tail", repeatable: true, variations: ["octaveDouble", "octaveUp", "same"] }] },+ parts: [{ id: "rh", inst: "piano", role: "melody", notes: m }, { id: "lh", inst: "piano", role: "accomp", notes: l }],+ };+};diff --git a/engine/src/canvas-core/music/pieces/samplers.ts b/engine/src/canvas-core/music/pieces/samplers.tsnew file mode 100644index 0000000..75794c4--- /dev/null+++ b/engine/src/canvas-core/music/pieces/samplers.ts@@ -0,0 +1,120 @@+// Five 8-second first-use samplers (spec 08 section 11): one per style x mood, each a complete+// musical thought with a cadence, not a sound-design loop. Every note written by hand.+import { line, type Piece, type Role } from "../plan";++const L = (t: number, s: string, role: Role, bpb: number, v = 0.7, extra: { roll?: number; kind?: string; pickup?: number } = {}) => line(t, s, { role, v, bpb, ...extra });+const H = (xs: [number, string][]) => xs.map(([t, name]) => ({ t, name }));++/** Music box, JOY. D major, 12/8 at 120 (the recipe's own grid), I-IV-V-I, pentatonic hook, bell on the last downbeat. */+export const musicBoxJoy = (): Piece => {+ const B = 4;+ // melody: the hook is a long-short-short skip (F#-A-B-A); bar 2 repeats its rhythm a fourth up, bar 3 answers on the dominant+ const melody = L(0, "F#5:1 A5:2/3 B5:1/3 A5:1 F#5:1 | B5:1 D6:2/3 B5:1/3 G5:2 | A5:1 B5:2/3 A5:1/3 E5:1 C#6:1 | D6:1", "melody", B, 0.75);+ // rolling 1-5-3-5 arpeggio on the triplets (4-note cell over 3-note groups: a gentle hemiola)+ const arpBar = (r: string, f: string, t: string) => Array.from({ length: 12 }, (_, i) => `${[r, f, t, f][i % 4]}:1/3`).join(" ");+ const arp = L(0, [arpBar("D5", "A5", "F#5"), arpBar("D5", "G5", "B5"), arpBar("C#5", "A5", "E5"), "D5:1/3 A5:1/3 F#5:1/3"].join(" | "), "accomp", B, 0.5); // up an octave: brightness+ const bassL = L(0, "D3:2 F#3:2 | G3:2 D3:2 | E3:2 C#3:2 | D3:1", "bass", B, 0.62); // the recipe's bass register, C3-G3+ const sparkle = L(8, "A6:1 B6:2/3 A6:1/3 E6:1 C#7:1 | D7:1", "color", B, 0.3);+ const bell = L(12, "D6:1", "color", B, 0.8);+ return {+ title: "Music box, joy", seed: 7, tail: 2,+ harmony: H([[0, "D"], [4, "G"], [8, "A"], [12, "D"]]),+ plan: { style: "musicBox", tempo: 120, meter: "12/8", ritard: 0.8, sections: [{ id: "a", bars: 4, mood: "joy", key: "D", mode: "major", melody: ["hook", "arpeggio"], dyn: [0.75, 0.85], ending: "button", repeatable: true }] },+ parts: [+ { id: "melody", inst: "musicBox", role: "melody", notes: melody, opts: { grid: true } },+ { id: "arp", inst: "musicBox", role: "accomp", notes: arp, gainDb: -11, opts: { grid: true } },+ { id: "bass", inst: "musicBox", role: "bass", notes: bassL, gainDb: -8, opts: { grid: true } },+ { id: "sparkle", inst: "musicBox", role: "color", notes: sparkle, gainDb: -6, opts: { grid: true } },+ { id: "bell", inst: "bell", role: "color", notes: bell },+ ],+ };+};++/** Piano, MELANCHOLY. D minor, 3/4 at 63. i - iv6 - V7 (harmonic-minor C#) - i. A stepwise line that rises to G5 and sighs home. */+export const minorPianoMelancholy = (): Piece => {+ // the high point G5 (bar 2) strikes alone: its bass Bb2 is anticipated an eighth early and held+ const melody = [...L(0, "D5:1.5 E5:.5 F5:1 | G5:1 F5:.5 E5:.5 C#5:1 | D5:3", "melody", 3, 0.72),+ ...L(0, "r:1 A4:2 | Bb4:2 A4:1 | F4:3", "inner", 3, 0.55)];+ const lh = [...L(0, "D2:2.5 r:.5 | r:2 A2:1 | D2:3", "bass", 3, 0.7), ...L(2.5, "Bb2:2.5", "bass", 3, 0.66, { pickup: 2.5 }),+ ...L(0, "r:.5 A2:.5 F3:.5 A3:.5 D4:.5 r:.5 | r:.5 D3:.5 G3:.5 D3:.5 E3:.5 [G3 C#4]:.5 | r:.5 A2:.5 F3:.5 A3:.5 D4:1", "accomp", 3, 0.7, { roll: 0.02 })];+ return {+ title: "Piano, melancholy (D minor)", seed: 29, tail: 1.8,+ harmony: H([[0, "Dm"], [3, "Gm/Bb"], [5, "A7"], [6, "Dm"]]),+ plan: { style: "nocturne", tempo: 63, meter: "3/4", phraseBars: 3, sections: [{ id: "a", bars: 3, mood: "melancholy", key: "D", mode: "aeolian", melody: ["stepwise"], dyn: [0.4, 0.36], ending: "tail" }] },+ parts: [{ id: "rh", inst: "piano", role: "melody", notes: melody }, { id: "lh", inst: "piano", role: "accomp", notes: lh }],+ };+};++/** Cinematic strings + piano, AWE. C with a lydian II (D/C: the #4 F#) then a chromatic-mediant arrival on E major. 4/4 at 72. */+export const cinematicAwe = (): Piece => {+ const B = 4;+ // strings: Cadd9 -> D/C (the lydian #4, F#, in the top voice) -> E major held through the arrival+ const hi = [...L(0, "[C4 G4 D5 E5]:4 | [D4 A4 F#5]:2", "accomp", B, 0.7), ...L(6, "[E4 B4 E5 G#5]:4", "accomp", B, 0.7)];+ const low = [...L(0, "[C2 C3]:4 | [C2 C3]:2", "bass", B, 0.7), ...L(6, "[E2 E3]:4", "bass", B, 0.7)];+ // harp shimmer: rising eighths over the swell; the piano rolls the arrival chord wide+ const shimmer = L(0, "C5:.5 G5:.5 D6:.5 E6:.5 G6:.5 E6:.5 D6:.5 G5:.5 | D5:.5 A5:.5 E6:.5 F#6:.5 B6:.5 G#6:.5 E6:.5 B5:.5", "color", B, 0.55);+ const arrival = L(6, "[E1 E2 B2 G#3 E4]:2", "bass", B, 0.85, { roll: 0.05 });+ const bell = L(6, "[E6 B6]:2", "color", B, 0.5);+ return {+ title: "Cinematic, awe", seed: 88, tail: 2.6,+ harmony: H([[0, "Cadd9"], [4, "D/C"], [6, "E"]]),+ plan: { style: "cinematic", tempo: 72, meter: "4/4", ritard: 0.85, sections: [{ id: "a", bars: 2, mood: "awe", key: "C", mode: "lydian", melody: ["arpeggio", "drone"], dyn: [0.3, 0.95], ending: "tail" }] },+ parts: [+ { id: "strings", inst: "strings", role: "accomp", notes: hi, opts: { attack: 1.1, release: 1.6, bright: 0.9 }, gainDb: -4 },+ { id: "cellos", inst: "strings", role: "bass", notes: low, opts: { attack: 0.9, release: 1.6, bass: true, bright: 0.6 }, gainDb: -3 },+ { id: "harp", inst: "harp", role: "color", notes: shimmer, gainDb: 2 }, // the shimmer is the rhythm layer (2 onsets a beat): it must be heard+ { id: "piano", inst: "piano", role: "bass", notes: arrival, gainDb: 0 },+ { id: "bell", inst: "fmBell", role: "color", notes: bell, gainDb: -8 },+ ],+ };+};++/** Chiptune, PLAYFUL. C major, 4/4 at 140. Call (bar 1, high) and response (bar 2, low); 16th arps fake the chords; 4 voices. */+export const chiptunePlayful = (): Piece => {+ const B = 4;+ const lead = L(0, "E5:.5 G5:.5 C6:.75 B5:.25 C6:.5 G5:.5 E5:1 | A4:.5 C5:.5 E5:.5 A5:.5 G5:1 E5:1 | F5:.5 A5:.5 C6:.75 B5:.25 A5:.5 F5:.5 D5:1 | G5:.5 B5:.5 D6:.5 B5:.5 G5:.5 A5:.25 B5:.25 r:1 | C6:1.5", "melody", B, 0.85);+ const arp16 = (a: string, b: string, c: string, d: string) => Array.from({ length: 16 }, (_, i) => `${[a, b, c, d][i % 4]}:.25`).join(" ");+ const arps = L(0, [arp16("C4", "E4", "G4", "C5"), arp16("A3", "C4", "E4", "A4"), arp16("F3", "A3", "C4", "F4"), arp16("G3", "B3", "D4", "G4"), "C4:.25 E4:.25 G4:.25 C5:.25"].join(" | "), "accomp", B, 0.55);+ const oct = (a: string, b: string) => Array.from({ length: 8 }, (_, i) => `${i % 2 ? b : a}:.5`).join(" ");+ const tri = L(0, [oct("C2", "C3"), oct("A1", "A2"), oct("F2", "F3"), oct("G2", "G3"), "C2:1.5"].join(" | "), "bass", B, 1);+ const kick = L(0, "C4:1 r:1 C4:.5 C4:.5 r:1 | C4:1 r:1 C4:1 r:1 | C4:1 r:1 C4:.5 C4:.5 r:1 | C4:1 r:1 C4:1 r:1 | C4:1", "drum", B, 0.9, { kind: "k" });+ const snare = L(0, "r:1 C4:1 r:1 C4:1 | r:1 C4:1 r:1 C4:1 | r:1 C4:1 r:1 C4:1 | r:1 C4:1 r:1 C4:.25 C4:.25 C4:.25 C4:.25 | C4:1.5", "drum", B, 0.75, { kind: "s" });+ const hats = L(0, [..."1234"].map(() => Array.from({ length: 8 }, () => "C4:.5").join(" ")).join(" | "), "drum", B, 0.6, { kind: "h" });+ return {+ title: "Chiptune, playful", seed: 1985, tail: 1.1,+ harmony: H([[0, "C"], [4, "Am"], [8, "F"], [12, "G"], [16, "C"]]),+ plan: { style: "chiptune", tempo: 140, meter: "4/4", ritard: 1, sections: [{ id: "a", bars: 5, mood: "playful", key: "C", mode: "major", melody: ["hook", "callResponse"], dyn: [0.8, 0.9], ending: "button", repeatable: true }] },+ parts: [+ { id: "lead", inst: "pulse", role: "melody", notes: lead, opts: { duty: 0.25, pan: -0.15, grid: true } },+ { id: "arp", inst: "pulse", role: "accomp", notes: arps, opts: { duty: 0.125, pan: 0.25, grid: true }, gainDb: -5 },+ { id: "tri", inst: "triangle", role: "bass", notes: tri, gainDb: 1, opts: { grid: true } },+ { id: "noise", inst: "noiseDrum", role: "drum", notes: [...kick, ...snare, ...hats], gainDb: -2, opts: { grid: true } },+ ],+ };+};++/** Lo-fi e-piano, NOSTALGIC. F major, 4/4 at 80, swing 58 %. Fmaj9 - Dm9 | Bbmaj7 - C9sus | Fmaj9. */+export const lofiNostalgic = (): Piece => {+ const B = 4;+ const chords = L(0, "[A3 C4 E4 G4]:1.5 [A3 C4 E4 G4]:.5 [F3 A3 C4 E4]:2 | [A3 D4 F4]:1.5 [A3 D4 F4]:.5 [Bb3 D4 E4 G4]:2 | [A3 C4 E4 G4]:3", "accomp", B, 0.62, { roll: 0.018 });+ const melody = L(0, "r:.5 C5:.5 E5:1 D5:.5 C5:.5 A4:1 | r:.5 F5:.5 D5:1 E5:.5 D5:.5 C5:1 | A4:3", "melody", B, 0.72);+ const bassL = L(0, "F2:1.5 F2:.5 D2:2 | Bb1:1.5 Bb1:.5 C2:2 | F2:3", "bass", B, 0.8);+ const kick = L(0, "C4:1 r:1.5 C4:1 r:.5 | C4:1 r:1.5 C4:1 r:.5 | C4:1", "drum", B, 0.8);+ const rim = L(0, "r:1 C4:1 r:1 C4:1 | r:1 C4:1 r:1 C4:1 | r:1", "drum", B, 0.6);+ const hats = L(0, "C4:.5@1 C4:[email protected] C4:.5@1 C4:[email protected] C4:.5@1 C4:[email protected] C4:.5@1 C4:[email protected] | C4:.5@1 C4:[email protected] C4:.5@1 C4:[email protected] C4:.5@1 C4:[email protected] C4:.5@1 C4:[email protected] | C4:.5", "drum", B, 0.55);+ const crackle = L(0, "C4:4 | C4:4 | C4:3", "color", B, 1);+ return {+ title: "Lo-fi, nostalgic", seed: 1978, tail: 2.2,+ harmony: H([[0, "Fmaj9"], [2, "Dm9"], [4, "Bbmaj7"], [6, "C9sus"], [8, "Fmaj9"]]),+ plan: { style: "lofi", tempo: 80, meter: "4/4", swing: 0.58, ritard: 0.85, sections: [{ id: "a", bars: 3, mood: "nostalgic", key: "F", mode: "major", melody: ["stepwise", "hook"], dyn: [0.6, 0.6], ending: "tail", repeatable: true }] },+ parts: [+ { id: "keys", inst: "ePiano", role: "accomp", notes: chords, gainDb: -5, opts: { detune: 5 } },+ { id: "lead", inst: "ePiano", role: "melody", notes: melody, gainDb: 4, opts: { detune: 6, width: 0.2 } },+ { id: "bass", inst: "bass", role: "bass", notes: bassL, gainDb: -2 },+ { id: "kick", inst: "kick", role: "drum", notes: kick, gainDb: -4, send: 0.2 },+ { id: "rim", inst: "snare", role: "drum", notes: rim, opts: { rim: true }, gainDb: -6, send: 0.5 },+ { id: "hat", inst: "hat", role: "drum", notes: hats, gainDb: -8, send: 0.2 },+ { id: "vinyl", inst: "vinyl", role: "color", notes: crackle, gainDb: -2, send: 0 },+ ],+ };+};diff --git a/engine/src/canvas-core/music/plan.ts b/engine/src/canvas-core/music/plan.tsnew file mode 100644index 0000000..f0f9153--- /dev/null+++ b/engine/src/canvas-core/music/plan.ts@@ -0,0 +1,123 @@+// MusicPlan and notes as data (spec 08 section 2), a small bar-checked notation so a composer+// writes real lines instead of arrays of numbers, the plan validator, and `arrange`, which fits+// a piece to ANY film duration (tempo inside the style's range, then repeat or drop sections).+import { midi, type ModeId, MODES, detectMode, pcOf } from "./theory";+import { MOODS, STYLES, REFUSED_BLENDS, type MoodId, type StyleId, type MelodyType } from "./tables";++export type Meter = "3/4" | "4/4" | "6/8" | "12/8";+export const beatsPerBar = (m: Meter) => (m === "3/4" ? 3 : m === "4/4" ? 4 : m === "6/8" ? 2 : 4);++export type Role = "melody" | "inner" | "bass" | "accomp" | "color" | "drum";+/** t, d in beats from the piece start; p = MIDI; v = written velocity 0..1 (performance shapes it). */+export type Note = { t: number; d: number; p: number; v: number; role: Role; roll?: number; kind?: string };+export type InstId = "piano" | "musicBox" | "bell" | "celesta" | "marimba" | "vibes" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "pulse" | "triangle" | "noiseDrum" | "kick" | "snare" | "hat" | "bass" | "vinyl";+export type Part = { id: string; inst: InstId; role: Role; notes: Note[]; gainDb?: number; pan?: number; opts?: Record<string, number | boolean | string>; send?: number };+export type Section = {+ id: string; bars: number; mood: MoodId | [MoodId, MoodId, number]; key: string; mode: ModeId; melody: MelodyType[];+ /** loudness level at start and end of the section, 0..1 (performance maps it to velocity) */+ dyn: [number, number]; ending?: "button" | "tail" | "hardOut"; repeatable?: boolean; optional?: boolean;+ /** melody beats before the downbeat that belong to this section (re-emitted wherever it is placed) */ pickup?: number;+ /** how repeats differ, cycled */ variations?: Variation[];+};+export type MusicPlan = { style: StyleId; tempo: number; meter: Meter; sections: Section[]; pickupBeats?: number; swing?: number; phraseBars?: number; sync?: string[];+ /** tempo-arch depth per phrase (1 = +-2.5 %); final ritard end-tempo ratio (1 = none) */ rubato?: number; ritard?: number;+ /** room override (the guards' bad fixture uses it; films normally take the style's room) */ space?: { er?: number; late?: number; rt60?: number; hp?: number } };+export type Chord = { t: number; name: string };+export type Piece = { title: string; plan: MusicPlan; parts: Part[]; harmony: Chord[]; tail: number; seed: number;+ /** a shorter complete form of the same music, chosen automatically when the film is too short for this one */ shortForm?: () => Piece };++// ---------------------------------------------------------------- notation+// "Eb4:1 | C5:2 Bb4:.5 Ab4:.5 | [Ab2 Eb3]:1 r:2 | G5:1/[email protected] ..." ; a token is NOTE:DUR[@VEL] or+// [CHORD]:DUR[@VEL] or r:DUR. Every complete bar must sum to the meter: a wrong bar throws.+const dur = (s: string) => { if (s.includes("/")) { const [a, b] = s.split("/").map(Number); return a / b; } return Number(s); };+export const line = (start: number, src: string, o: { role: Role; v?: number; bpb: number; pickup?: number; roll?: number; kind?: string }): Note[] => {+ const out: Note[] = []; let t = start; const bars = src.split("|").map((b) => b.trim()).filter((b, i, a) => b.length || (i > 0 && i < a.length - 1));+ bars.forEach((bar, bi) => {+ let sum = 0;+ for (const tok of bar.split(/\s+(?![^\[]*\])/).filter(Boolean)) {+ const m = /^(\[[^\]]+\]|[^:]+):([0-9./]+)(?:@([0-9.]+))?$/.exec(tok); if (!m) throw new Error(`bad token "${tok}" in "${bar}"`);+ const d = dur(m[2]), vel = (o.v ?? 0.7) * (m[3] ? Number(m[3]) : 1);+ if (m[1] !== "r") {+ const names = m[1].startsWith("[") ? m[1].slice(1, -1).trim().split(/\s+/) : [m[1]];+ for (const nm of names) out.push({ t, d, p: midi(nm), v: vel, role: o.role, roll: names.length > 1 ? o.roll ?? 0.012 : undefined, kind: o.kind });+ }+ t += d; sum += d;+ }+ const first = bi === 0, last = bi === bars.length - 1;+ const ok = Math.abs(sum - o.bpb) < 1e-6 || (first && o.pickup !== undefined && Math.abs(sum - o.pickup) < 1e-6) || (last && sum <= o.bpb + 1e-6);+ if (!ok) throw new Error(`bar ${bi} sums to ${sum} beats, meter wants ${o.bpb}: "${bar}"`);+ });+ return out;+};++// ---------------------------------------------------------------- validation (spec 08 sections 3, 5, 7)+export const planProblems = (p: Piece): string[] => {+ const probs: string[] = [], plan = p.plan, st = STYLES[plan.style], bpb = beatsPerBar(plan.meter);+ if (!st) probs.push(`unknown style ${plan.style}`);+ else if (plan.tempo < st.tempo[0] * 0.85 || plan.tempo > st.tempo[1] * 1.15) probs.push(`tempo ${plan.tempo} far outside style ${st.id} ${st.tempo.join("-")}`);+ let b0 = -(plan.pickupBeats ?? 0);+ for (const s of plan.sections) {+ const ids = Array.isArray(s.mood) ? [s.mood[0], s.mood[1]] : [s.mood];+ for (const id of ids) if (!MOODS[id]) probs.push(`${s.id}: unknown mood ${id}`);+ if (Array.isArray(s.mood) && REFUSED_BLENDS.some(([a, b]) => (a === s.mood[0] && b === s.mood[1]) || (a === s.mood[1] && b === s.mood[0]))) probs.push(`${s.id}: refused blend ${s.mood[0]}+${s.mood[1]}`);+ if (!MODES[s.mode]) probs.push(`${s.id}: unknown mode ${s.mode}`);+ const lo = b0, hi = b0 + s.bars * bpb + (b0 < 0 ? plan.pickupBeats ?? 0 : 0);+ const notes = p.parts.flatMap((pt) => pt.notes).filter((n) => n.t >= lo && n.t < hi && n.role !== "drum");+ if (notes.length) {+ const top = detectMode(notes, [s.mode, "major", "aeolian", "dorian", "mixolydian", "lydian"]);+ const want = pcOf(s.key.replace(/m$/, ""));+ const hit = top.slice(0, 2).some((c) => pcOf(c.tonic) === want && c.mode === s.mode) || top.slice(0, 2).some((c) => c.mode === s.mode);+ if (!hit) probs.push(`${s.id}: declared ${s.key} ${s.mode}, notes measure ${top.map((c) => `${c.tonic} ${c.mode}`).join(" / ")}`);+ }+ b0 = hi;+ }+ // voice guard: no close thirds below C3 in piano parts (nocturne style guard)+ for (const pt of p.parts) if (pt.inst === "piano") {+ const by = new Map<number, number[]>(); for (const n of pt.notes) { const k = Math.round(n.t * 96); by.set(k, [...(by.get(k) ?? []), n.p]); }+ for (const [k, ps] of by) { ps.sort((a, b) => a - b); for (let i = 1; i < ps.length; i++) if (ps[i] < 48 && ps[i] - ps[i - 1] <= 4) probs.push(`close third below C3 at beat ${k / 96}`); }+ }+ return probs;+};++// ---------------------------------------------------------------- fit to any duration+/** Section beat spans [start, end) in piece beats (pickup lives before 0 and belongs to section 0). */+export const sectionSpans = (plan: MusicPlan) => { const bpb = beatsPerBar(plan.meter); let b = 0; return plan.sections.map((s, i) => { const a = i === 0 ? -(plan.pickupBeats ?? 0) : b; b += s.bars * bpb; return { s, a, b: b }; }); };++export type Variation = "same" | "octaveDouble" | "octaveUp" | "thin";+/** Apply a repeat variation to one section's notes. */+const vary = (notes: Note[], v: Variation): Note[] => {+ if (v === "octaveDouble") return [...notes, ...notes.filter((n) => n.role === "melody").map((n) => ({ ...n, p: n.p - 12, role: "inner" as Role, v: n.v * 0.8 }))];+ if (v === "octaveUp") return notes.map((n) => (n.role === "melody" ? { ...n, p: n.p + 12, v: n.v * 0.9 } : n));+ if (v === "thin") return notes.filter((n) => n.role !== "accomp" || Math.abs(n.t - Math.round(n.t)) < 1e-6);+ return notes;+};++/**+ * Rebuild a piece from a list of section indices (repeat/drop), shifting notes and chords.+ * A section's `pickup` (melody beats before its downbeat) travels with it: wherever the section+ * lands, the last `pickup` beats of melody before it are replaced by the section's own pickup.+ * Repeats cycle through the section's `variations` so a returning theme is never a photocopy.+ */+export const resequence = (p: Piece, order: number[]): Piece => {+ const spans = sectionSpans(p.plan); const parts = p.parts.map((pt) => ({ ...pt, notes: [] as Note[] })); const harmony: Chord[] = []; const sections: Section[] = [];+ let cursor = 0; const bpb = beatsPerBar(p.plan.meter), seen = new Map<number, number>();+ order.forEach((si, k) => {+ const sec = p.plan.sections[si], sp = spans[si], start = si === 0 ? 0 : sp.a, len = sec.bars * bpb, shift = cursor - start;+ const rep = seen.get(si) ?? 0; seen.set(si, rep + 1);+ const vr: Variation = rep > 0 && sec.variations?.length ? sec.variations[(rep - 1) % sec.variations.length] : "same";+ const pk = si === 0 ? p.plan.pickupBeats ?? 0 : sec.pickup ?? 0;+ p.parts.forEach((pt, j) => {+ const body = pt.notes.filter((n) => n.t >= start && n.t < sp.b).map((n) => ({ ...n, t: n.t + shift }));+ if (pk > 0) {+ if (k > 0) parts[j].notes = parts[j].notes.filter((n) => !(n.role === "melody" && n.t >= cursor - pk - 1e-9));+ parts[j].notes.push(...vary(pt.notes.filter((n) => n.role === "melody" && n.t >= start - pk && n.t < start).map((n) => ({ ...n, t: n.t + shift })), vr));+ }+ parts[j].notes.push(...vary(body, vr));+ });+ for (const c of p.harmony) if (c.t >= (si === 0 ? -1e9 : start) && c.t < sp.b) harmony.push({ ...c, t: c.t + shift });+ sections.push({ ...sec, id: rep ? `${sec.id}#${rep}${vr === "same" ? "" : `(${vr})`}` : sec.id });+ cursor += len;+ });+ const pickupBeats = order[0] === 0 ? p.plan.pickupBeats : p.plan.sections[order[0]].pickup ?? 0;+ return { ...p, parts, harmony, plan: { ...p.plan, sections, pickupBeats } };+};diff --git a/engine/src/canvas-core/music/render.ts b/engine/src/canvas-core/music/render.tsnew file mode 100644index 0000000..ee0cdec--- /dev/null+++ b/engine/src/canvas-core/music/render.ts@@ -0,0 +1,146 @@+// Piece -> performance -> one stem per part -> room -> master. Pure in (piece, sampleRate, opts).+// Gentle styles: one static gain to -16 LUFS, true peak <= -1 dBTP, never a compressor (if the+// ceiling can't be met by gain alone the loudness goes down, spec 08 section 9). Dense styles:+// -14 LUFS through a look-ahead true-peak limiter.+import { type Piece, type Part, resequence, beatsPerBar } from "./plan";+import { perform, type Performance, type Played } from "./perform";+import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";+import * as I from "./instruments";+import { room, Biquad, db } from "./dsp";+import { loudness, truePeak } from "./meter";+import { STYLES } from "./tables";+import { rng as mkRng } from "../core";++export type RenderOpts = { expressive?: boolean; piano?: PianoOpts; flatVelocity?: number; seconds?: number; tempo?: number; master?: "auto" | "gentle" | "dense" | "none"; stems?: boolean; only?: (p: Part) => boolean };+/** dry = the pre-room mix; wet = the room's late tail (for music-box: its single reflection). Kept so the guards can measure reverb-to-dry per bar. */+export type Rendered = { L: Float32Array; R: Float32Array; perf: Performance; tempo: number; gainDb: number; masterMode: string; stems: Record<string, [Float32Array, Float32Array]>; piece: Piece; dry: [Float32Array, Float32Array]; wet: [Float32Array, Float32Array] };++const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) => {+ const o = pt.opts ?? {}, r = mkRng(seed);+ switch (pt.inst) {+ case "musicBox": return I.musicBox(keys, sr, n, o);+ case "bell": return I.bell(keys, sr, n, o);+ case "celesta": return I.celesta(keys, sr, n, o);+ case "marimba": return I.mallets(keys, sr, n, o);+ case "vibes": return I.mallets(keys, sr, n, o, true);+ case "harp": return I.pluck(keys, sr, n, o, r, "harp");+ case "guitar": return I.pluck(keys, sr, n, o, r, "guitar");+ case "strings": return I.strings(keys, sr, n, o, r);+ case "fmBell": return I.fmBell(keys, sr, n, o);+ case "ePiano": return I.ePiano(keys, sr, n, o);+ case "pulse": return I.pulse(keys, sr, n, o);+ case "triangle": return I.triangle(keys, sr, n);+ case "noiseDrum": return I.noiseDrum(keys, sr, n);+ case "kick": return I.kick(keys, sr, n, o);+ case "snare": return I.snare(keys, sr, n, o, r);+ case "hat": return I.hat(keys, sr, n, o, r);+ case "bass": return I.bass(keys, sr, n, o);+ case "vinyl": return I.vinyl(keys, sr, n, o, r);+ default: throw new Error(`no instrument ${pt.inst}`);+ }+};++export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rendered => {+ const expressive = o.expressive ?? true, tempo = o.tempo ?? piece.plan.tempo, style = STYLES[piece.plan.style];+ const perf = perform(piece, tempo, { expressive, flatVelocity: o.flatVelocity });+ const n = o.seconds ? Math.round(o.seconds * sr) : Math.ceil((perf.lastOnset + piece.tail) * sr);+ const L = new Float32Array(n), R = new Float32Array(n), haloL = new Float32Array(n), stems: Record<string, [Float32Array, Float32Array]> = {};+ const sends: [Float32Array, Float32Array, number][] = [];+ piece.parts.forEach((pt, pi) => {+ if (o.only && !o.only(pt)) return;+ const keys = perf.parts[pi].keys; if (!keys.length) return;+ let sL: Float32Array, sR: Float32Array;+ if (pt.inst === "piano") { const r = renderPiano(keys, perf.pedal, sr, n, o.piano ?? PIANO_REAL, piece.seed + pi); sL = r.L; sR = r.R; if ((o.piano ?? PIANO_REAL).pedal) for (let i = 0; i < n; i++) haloL[i] += r.halo[i] * db(pt.gainDb ?? 0); }+ else { const r = voice(pt, keys, sr, n, piece.seed * 101 + pi); sL = r.L; sR = r.R; }+ const g = db(pt.gainDb ?? 0);+ if (pt.pan) { const a = Math.max(0, pt.pan), b = Math.max(0, -pt.pan); for (let i = 0; i < n; i++) { sL[i] *= 1 - a * 0.6; sR[i] *= 1 - b * 0.6; } }+ for (let i = 0; i < n; i++) { sL[i] *= g; sR[i] *= g; L[i] += sL[i]; R[i] += sR[i]; }+ if (o.stems) stems[pt.id] = [sL, sR];+ sends.push([sL, sR, pt.send ?? 1]);+ });+ // ---- space+ const rng = mkRng(piece.seed * 7 + 5), dry: [Float32Array, Float32Array] = [Float32Array.from(L), Float32Array.from(R)];+ let wet: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)];+ const sp = piece.plan.space;+ if (style.id === "musicBox" && !sp) { // the recipe: ONE early reflection, 30 ms late, 14 dB down, no tail+ const d = Math.round(0.03 * sr), g = db(-14); for (let i = d; i < n; i++) { wet[0][i] = dry[0][i - d] * g; wet[1][i] = dry[1][i - d] * g * 0.9; L[i] += wet[0][i]; R[i] += wet[1][i]; }+ } else if (style.reverb !== "none" || sp) {+ const sL = new Float32Array(n), sR = new Float32Array(n);+ for (const [a, b, s] of sends) for (let i = 0; i < n; i++) { sL[i] += a[i] * s; sR[i] += b[i] * s; }+ const hall = style.reverb === "hall";+ for (let i = 0; i < n; i++) { sL[i] += haloL[i] * 0.35; sR[i] += haloL[i] * 0.35; } // pedal halo: undamped strings ring into the room+ const [wL, wR, tL, tR] = room(sL, sR, sr, { er: sp?.er ?? (hall ? 0.35 : 0.45), late: sp?.late ?? (hall ? 0.3 : 0.2), rt60: sp?.rt60 ?? (hall ? 2.3 : 1.5), predelay: hall ? 0.035 : 0.022, hp: sp?.hp ?? 300, lp: hall ? 7000 : 6000, seed: piece.seed, rng });+ for (let i = 0; i < n; i++) { L[i] += wL[i]; R[i] += wR[i]; }+ wet = [tL, tR]; // the guards measure the late tail: early reflections (< 40 ms) fuse with the direct sound (precedence effect)+ }+ // ---- master: DC/rumble high-pass (4th-order Butterworth at 30 Hz), lo-fi tone, end fade+ for (const q of [0.5412, 1.3066]) { Biquad.make(sr, "hp", 30, q).run(L); Biquad.make(sr, "hp", 30, q).run(R); }+ if (style.id === "lofi") { for (const c of [L, R]) { Biquad.make(sr, "lp", 8500, 0.6).run(c); Biquad.make(sr, "highshelf", 5000, 0.7, -3).run(c); for (let i = 0; i < n; i++) c[i] = Math.tanh(c[i] * 1.2) / 1.2; } }+ const fade = Math.min(n, Math.round(0.25 * sr)); for (let i = 0; i < fade; i++) { const g = 0.5 - 0.5 * Math.cos((Math.PI * i) / fade); L[n - 1 - i] *= g; R[n - 1 - i] *= g; }+ let gainDb = 0, masterMode = o.master ?? "auto";+ if (masterMode === "auto") masterMode = style.master;+ if (masterMode !== "none") {+ const target = masterMode === "dense" ? -14 : -16;+ gainDb = target - loudness([L, R], sr).integrated;+ for (let i = 0; i < n; i++) { L[i] *= db(gainDb); R[i] *= db(gainDb); }+ const tp = truePeak([L, R]).dbtp;+ if (tp > -1) {+ if (masterMode === "gentle") { const cut = tp + 1.05; gainDb -= cut; for (let i = 0; i < n; i++) { L[i] *= db(-cut); R[i] *= db(-cut); } }+ else { limiter(L, R, sr, db(-1.3)); const again = target - loudness([L, R], sr).integrated; if (again > 0) { const g = db(Math.min(again, 1)); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } limiter(L, R, sr, db(-1.3)); } }+ }+ }+ return { L, R, perf, tempo, gainDb, masterMode, stems, piece, dry, wet };+};++/** Look-ahead peak limiter (1.5 ms look-ahead, 120 ms release), used by dense styles only. */+const limiter = (L: Float32Array, R: Float32Array, sr: number, ceil: number) => {+ const n = L.length, la = Math.round(0.0015 * sr), rel = Math.exp(-1 / (0.12 * sr)), need = new Float32Array(n);+ for (let i = 0; i < n; i++) { const a = Math.max(Math.abs(L[i]), Math.abs(R[i])) * 1.12; need[i] = a > ceil ? ceil / a : 1; } // 1.12: inter-sample margin+ const g = new Float32Array(n); let cur = 1;+ for (let i = n - 1; i >= 0; i--) { let m = 1; for (let j = i; j < Math.min(n, i + la); j++) m = Math.min(m, need[j]); g[i] = m; }+ for (let i = 0; i < n; i++) { cur = g[i] < cur ? g[i] : 1 - (1 - cur) * rel; if (cur > g[i]) cur = g[i]; L[i] *= cur; R[i] *= cur; }+};++/**+ * Fit a piece to ANY duration. Candidate forms = every subset of `optional` sections dropped x the+ * `repeatable` group (contiguous repeatable sections, with their variations) repeated 0..n times.+ * For each, the tempo that lands the last onset at (seconds - tail) is solved; the form whose tempo+ * sits inside the style's range and closest to the written tempo wins. If no full form fits and the+ * piece has a `shortForm`, that is fitted instead. The tail absorbs the rest. Nothing in a piece+ * hard-codes the film's length.+ */+export const fitToDuration = (piece: Piece, seconds: number): { piece: Piece; tempo: number; order: number[]; form: string } => {+ const st = STYLES[piece.plan.style], T0 = piece.plan.tempo, lo = Math.max(st.tempo[0] * 0.9, T0 * 0.82), hi = Math.min(st.tempo[1] * 1.1, T0 * 1.18);+ const secs = piece.plan.sections, want = seconds - piece.tail;+ const solve = (p: Piece) => { let tempo = T0; for (let k = 0; k < 5; k++) tempo *= perform(p, tempo, { expressive: true }).lastOnset / want; return tempo; };+ const opt = secs.map((s, i) => (s.optional ? i : -1)).filter((i) => i >= 0);+ const grp = secs.map((s, i) => (s.repeatable ? i : -1)).filter((i) => i >= 0);+ let best: { p: Piece; tempo: number; order: number[]; cost: number } | null = null, anyTooShort = false;+ for (let mask = 0; mask < 1 << opt.length; mask++) {+ const dropped = opt.filter((_, j) => mask & (1 << j));+ // ra = extra statements of the first repeatable section in place (A A B), rg = repeats of the whole group (A B A B)+ for (let ra = 0; ra <= (grp.length > 1 ? 2 : 0); ra++) for (let rg = 0; rg <= (grp.length ? 64 : 0); rg++) {+ let order = secs.map((_, i) => i);+ for (let k = 0; k < rg; k++) { const at = order.lastIndexOf(grp[grp.length - 1]); order = [...order.slice(0, at + 1), ...grp, ...order.slice(at + 1)]; }+ for (let k = 0; k < ra; k++) { const at = order.indexOf(grp[0]); order = [...order.slice(0, at + 1), grp[0], ...order.slice(at + 1)]; }+ order = order.filter((i) => !dropped.includes(i));+ if (!order.length) break;+ const p = mask === 0 && ra === 0 && rg === 0 ? piece : resequence(piece, order), tempo = solve(p);+ if (tempo > hi) break; // more repeats only make it longer+ if (tempo < lo) { anyTooShort = true; continue; }+ // dropping music costs more than a tempo nudge; back-to-back restatements cost a little+ const cost = Math.abs(Math.log(tempo / T0)) + 0.06 * dropped.length + 0.01 * rg + 0.025 * ra;+ if (!best || cost < best.cost) best = { p, tempo, order, cost };+ }+ }+ if (best) return { piece: { ...best.p, plan: { ...best.p.plan, tempo: best.tempo } }, tempo: best.tempo, order: best.order, form: "full" };+ if (!anyTooShort && piece.shortForm) { const f = fitToDuration(piece.shortForm(), seconds); return { ...f, form: `short form (${f.form})` }; }+ const tempo = anyTooShort ? lo : hi;+ return { piece: { ...piece, plan: { ...piece.plan, tempo } }, tempo, order: secs.map((_, i) => i), form: anyTooShort ? "full, tail extended" : "full, tail cut" };+};++/** What a Film's `audio(sampleRate)` returns: [L, R] at exactly the film's length. */+export const filmAudio = (piece: Piece, seconds: number) => (sr: number): [Float32Array, Float32Array] => {+ const fit = fitToDuration(piece, seconds), r = renderPiece(fit.piece, sr, { seconds, tempo: fit.tempo });+ return [r.L, r.R];+};diff --git a/engine/src/canvas-core/music/score-text.ts b/engine/src/canvas-core/music/score-text.tsnew file mode 100644index 0000000..df29053--- /dev/null+++ b/engine/src/canvas-core/music/score-text.ts@@ -0,0 +1,23 @@+// The text score a human reads (spec 08 section 10): at each section head the style, mood, key+// and mode; then bar by bar the chords and the melody's note names with durations in beats.+import { beatsPerBar, sectionSpans, type Piece } from "./plan";+import { spellerFor } from "./theory";++export const scoreText = (p: Piece): string => {+ const bpb = beatsPerBar(p.plan.meter), out: string[] = [`${p.title} | style ${p.plan.style}, ${p.plan.meter} at ${p.plan.tempo} bpm`];+ const mel = p.parts.flatMap((pt) => pt.notes.filter((n) => n.role === "melody")).sort((a, b) => a.t - b.t);+ const pick = p.plan.pickupBeats ?? 0;+ for (const { s, a, b } of sectionSpans(p.plan)) {+ const mood = Array.isArray(s.mood) ? `${s.mood[0]}+${s.mood[1]} (${s.mood[2]})` : s.mood;+ out.push(`== ${s.id}: ${mood}, ${s.key} ${s.mode}, melody ${s.melody.join("/")}, dynamics ${s.dyn[0]} -> ${s.dyn[1]}${s.ending ? `, ending ${s.ending}` : ""}`);+ const nm = spellerFor(s.key, s.mode);+ const first = Math.floor((a + (a < 0 ? 0 : 0)) / bpb), last = Math.ceil(b / bpb);+ for (let bar = Math.max(first, a < 0 ? -1 : first); bar < last; bar++) {+ const lo = bar === -1 ? -pick : bar * bpb, hi = (bar + 1) * bpb;+ const chords = p.harmony.filter((c) => c.t >= lo && c.t < hi).map((c) => c.name).join(" ");+ const notes = mel.filter((n) => n.t >= lo && n.t < hi).map((n) => `${nm(n.p)}:${+n.d.toFixed(3)}`).join(" ");+ out.push(` ${String(bar < 0 ? "pk" : bar).padStart(3)} | ${chords.padEnd(16)} | ${notes}`);+ }+ }+ return out.join("\n");+};diff --git a/engine/src/canvas-core/music/tables.ts b/engine/src/canvas-core/music/tables.tsnew file mode 100644index 0000000..d86db96--- /dev/null+++ b/engine/src/canvas-core/music/tables.ts@@ -0,0 +1,65 @@+// The spec-08 tables as DATA: moods (section 5), styles (section 6), melody types (section 4).+// A film names rows; it never writes adjectives. Every row starts `unconfirmed` until a human+// has listened to 8 seconds of it (spec 08 section 11): the listener's words go in `confirmedBy`.+import type { ModeId } from "./theory";++export type MelodyType = "arpeggio" | "stepwise" | "hook" | "ostinato" | "drone" | "callResponse" | "counterMelody" | "sequence" | "themeTransformation";+export type Family = "piano" | "musicBox" | "celesta" | "mallets" | "pluck" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "chip" | "drums" | "organ" | "bass";+export type Range = [number, number];+export type Mood = {+ id: MoodId; modes: ModeId[]; tempo: Range; meters: string[]; harmonicRhythmBars: Range; register: Range;+ onsetsPerBeat: Range; attackMs: Range; lra: Range; centroidHz: Range | null; families: Family[]; melody: MelodyType[];+ master: "gentle" | "dense"; confirmedBy?: { date: string; words: string };+};+export type MoodId = "joy" | "playful" | "tender" | "wistful" | "melancholy" | "hopeful" | "curious" | "tension" | "dread" | "awe" | "triumph" | "drive" | "calm" | "nostalgic" | "romantic";++// centroid null = report only (spec 08 drive row; ADVISORY 4.1: piano brightness is never gated).+export const MOODS: Record<MoodId, Mood> = {+ joy: { id: "joy", modes: ["major", "mixolydian", "majorPentatonic"], tempo: [110, 150], meters: ["4/4", "12/8"], harmonicRhythmBars: [1, 1], register: [72, 96], onsetsPerBeat: [2, 4], attackMs: [2, 10], lra: [4, 8], centroidHz: [1800, 6000], families: ["musicBox", "mallets", "pluck", "piano"], melody: ["arpeggio", "hook"], master: "gentle" },+ playful: { id: "playful", modes: ["major", "blues", "majorPentatonic"], tempo: [120, 160], meters: ["4/4"], harmonicRhythmBars: [0.25, 0.5], register: [60, 90], onsetsPerBeat: [2, 4], attackMs: [2, 5], lra: [6, 10], centroidHz: [1500, 6000], families: ["pluck", "mallets", "fmBell", "bass", "chip"], melody: ["hook", "callResponse"], master: "dense" },+ tender: { id: "tender", modes: ["major", "lydian"], tempo: [60, 80], meters: ["3/4", "6/8"], harmonicRhythmBars: [1, 2], register: [64, 84], onsetsPerBeat: [1, 2], attackMs: [5, 30], lra: [6, 12], centroidHz: null, families: ["piano", "harp", "strings", "organ"], melody: ["stepwise", "counterMelody"], master: "gentle" },+ wistful: { id: "wistful", modes: ["dorian", "major"], tempo: [70, 95], meters: ["6/8", "4/4"], harmonicRhythmBars: [1, 1], register: [64, 86], onsetsPerBeat: [1.5, 3], attackMs: [5, 20], lra: [6, 10], centroidHz: [1000, 2000], families: ["piano", "musicBox", "strings"], melody: ["stepwise", "themeTransformation"], master: "gentle" },+ melancholy: { id: "melancholy", modes: ["aeolian", "harmonicMinor"], tempo: [50, 72], meters: ["3/4", "4/4"], harmonicRhythmBars: [1, 2], register: [55, 80], onsetsPerBeat: [0.75, 1.5], attackMs: [20, 80], lra: [8, 14], centroidHz: null, families: ["piano", "strings"], melody: ["stepwise", "drone"], master: "gentle" },+ hopeful: { id: "hopeful", modes: ["melodicMinor", "major"], tempo: [80, 110], meters: ["4/4"], harmonicRhythmBars: [1, 1], register: [60, 88], onsetsPerBeat: [1.5, 3], attackMs: [10, 40], lra: [8, 12], centroidHz: null, families: ["piano", "strings", "fmBell"], melody: ["sequence", "stepwise"], master: "gentle" },+ curious: { id: "curious", modes: ["dorian", "lydian", "wholeTone"], tempo: [80, 110], meters: ["4/4", "6/8"], harmonicRhythmBars: [1, 2], register: [60, 84], onsetsPerBeat: [1, 2], attackMs: [2, 10], lra: [6, 10], centroidHz: [1000, 2000], families: ["pluck", "celesta", "fmBell"], melody: ["ostinato", "hook"], master: "gentle" },+ tension: { id: "tension", modes: ["harmonicMinor", "phrygian"], tempo: [90, 130], meters: ["4/4"], harmonicRhythmBars: [2, 4], register: [48, 72], onsetsPerBeat: [2, 4], attackMs: [2, 10], lra: [10, 16], centroidHz: [800, 1500], families: ["strings", "drums", "bass"], melody: ["ostinato", "drone"], master: "dense" },+ dread: { id: "dread", modes: ["phrygian", "aeolian", "locrian"], tempo: [50, 80], meters: ["4/4"], harmonicRhythmBars: [4, 4], register: [36, 60], onsetsPerBeat: [0.5, 1.5], attackMs: [50, 200], lra: [12, 18], centroidHz: [0, 1000], families: ["bass", "piano", "strings"], melody: ["drone"], master: "gentle" },+ awe: { id: "awe", modes: ["lydian", "major"], tempo: [60, 90], meters: ["4/4", "3/4"], harmonicRhythmBars: [2, 2], register: [72, 100], onsetsPerBeat: [1, 3], attackMs: [5, 400], lra: [10, 16], centroidHz: null, families: ["fmBell", "strings", "harp", "organ", "piano"], melody: ["arpeggio", "drone", "themeTransformation"], master: "gentle" },+ triumph: { id: "triumph", modes: ["major", "aeolian"], tempo: [100, 140], meters: ["4/4"], harmonicRhythmBars: [1, 1], register: [60, 90], onsetsPerBeat: [3, 6], attackMs: [2, 10], lra: [6, 10], centroidHz: [1500, 6000], families: ["drums", "strings", "organ"], melody: ["hook", "themeTransformation"], master: "dense" },+ drive: { id: "drive", modes: ["aeolian", "dorian", "mixolydian"], tempo: [110, 140], meters: ["4/4"], harmonicRhythmBars: [1, 1], register: [60, 86], onsetsPerBeat: [4, 8], attackMs: [1, 5], lra: [4, 8], centroidHz: null, families: ["drums", "bass", "pluck"], melody: ["hook", "arpeggio", "ostinato"], master: "dense" },+ calm: { id: "calm", modes: ["mixolydian", "majorPentatonic", "major"], tempo: [60, 90], meters: ["6/8", "3/4"], harmonicRhythmBars: [2, 2], register: [60, 84], onsetsPerBeat: [1, 2], attackMs: [5, 30], lra: [4, 8], centroidHz: [1000, 2000], families: ["guitar", "fmBell"], melody: ["stepwise", "drone"], master: "gentle" },+ nostalgic: { id: "nostalgic", modes: ["major"], tempo: [70, 95], meters: ["4/4"], harmonicRhythmBars: [0.5, 1], register: [60, 84], onsetsPerBeat: [1.5, 3], attackMs: [5, 20], lra: [6, 10], centroidHz: [900, 1600], families: ["ePiano", "drums", "bass"], melody: ["stepwise", "hook"], master: "dense" },+ romantic: { id: "romantic", modes: ["major", "aeolian"], tempo: [60, 85], meters: ["3/4", "4/4"], harmonicRhythmBars: [1, 1], register: [60, 88], onsetsPerBeat: [1, 2.5], attackMs: [10, 60], lra: [8, 14], centroidHz: [1000, 2000], families: ["piano", "strings"], melody: ["stepwise", "counterMelody"], master: "gentle" },+};++/** Blends the gate refuses (spec 08 section 5): use consecutive sections instead. */+export const REFUSED_BLENDS: [MoodId, MoodId][] = [["joy", "dread"], ["playful", "melancholy"], ["calm", "tension"]];+export const ARCS: Record<string, MoodId[]> = { rise: ["melancholy", "hopeful", "triumph"], turn: ["joy", "tension", "joy"], fallAndReturn: ["tender", "melancholy", "tender"], wonder: ["curious", "awe"], comic: ["playful", "tension", "playful"] };++export type StyleId = "musicBox" | "nocturne" | "drive" | "cinematic" | "chiptune" | "lofi" | "folk" | "minimalist" | "jazz" | "lullaby" | "ambient";+export type Style = { id: StyleId; tempo: Range; meters: string[]; families: Family[]; moods: MoodId[]; master: "gentle" | "dense"; arrangement: string; guards: string[]; reverb: "none" | "room" | "hall"; swing?: Range };+export const STYLES: Record<StyleId, Style> = {+ musicBox: { id: "musicBox", tempo: [110, 130], meters: ["12/8"], families: ["musicBox", "fmBell"], moods: ["joy", "curious", "tender", "playful", "wistful"], master: "gentle", reverb: "room", arrangement: "melody -> +bass -> +arp -> +octave sparkle -> bell", guards: ["pluck-only instruments", "more notes, never longer notes"] },+ nocturne: { id: "nocturne", tempo: [50, 72], meters: ["3/4", "6/8"], families: ["piano", "strings"], moods: ["tender", "melancholy", "wistful", "romantic"], master: "gentle", reverb: "room", arrangement: "left-hand broken chords spanning a tenth, right-hand stepwise theme", guards: ["rubato <= 8% of a beat", "no close thirds below C3"] },+ drive: { id: "drive", tempo: [110, 140], meters: ["4/4"], families: ["drums", "bass", "pluck", "strings"], moods: ["drive", "triumph", "tension", "awe"], master: "dense", reverb: "hall", arrangement: "riser, breath, drop", guards: ["phone rule: every low part has content above 500 Hz"] },+ cinematic: { id: "cinematic", tempo: [60, 120], meters: ["4/4", "3/4"], families: ["strings", "piano", "harp", "fmBell", "drums"], moods: ["awe", "triumph", "melancholy", "tension", "hopeful"], master: "gentle", reverb: "hall", arrangement: "layered by register slot; crescendos over 4-8 bars", guards: ["max 4 families at once outside climaxes"] },+ chiptune: { id: "chiptune", tempo: [120, 160], meters: ["4/4"], families: ["chip"], moods: ["joy", "playful", "drive", "tension"], master: "dense", reverb: "none", arrangement: "2 pulses, triangle bass, noise drums; fast arpeggios fake chords", guards: ["<= 4 voices", "no reverb", "PolyBLEP pulses"] },+ lofi: { id: "lofi", tempo: [70, 90], meters: ["4/4"], families: ["ePiano", "drums", "bass"], moods: ["nostalgic", "calm", "wistful"], master: "dense", reverb: "room", swing: [0.55, 0.62], arrangement: "4 or 8 bar loop with small variations", guards: ["no 2 consecutive identical 8-bar blocks", "master low-pass <= 9 kHz allowed"] },+ folk: { id: "folk", tempo: [80, 120], meters: ["6/8", "3/4", "4/4"], families: ["guitar", "harp", "fmBell"], moods: ["calm", "wistful", "joy", "nostalgic"], master: "gentle", reverb: "room", arrangement: "fingerpicked pattern + lead", guards: ["strum spread 10-30 ms low to high"] },+ minimalist: { id: "minimalist", tempo: [100, 140], meters: ["4/4", "12/8"], families: ["mallets", "piano"], moods: ["curious", "tension", "awe"], master: "gentle", reverb: "room", arrangement: "interlocking ostinatos; one change every 8-16 bars", guards: ["a change at least every 16 bars"] },+ jazz: { id: "jazz", tempo: [90, 180], meters: ["4/4"], families: ["piano", "bass", "drums"], moods: ["playful", "nostalgic", "romantic", "curious"], master: "gentle", reverb: "room", swing: [0.6, 0.67], arrangement: "walking bass on quarters, comping off the beat", guards: ["7th chords required"] },+ lullaby: { id: "lullaby", tempo: [60, 75], meters: ["3/4", "6/8"], families: ["musicBox", "celesta", "piano", "harp"], moods: ["tender", "calm"], master: "gentle", reverb: "room", arrangement: "melody + gentle arp, nothing percussive", guards: ["minor lullaby flagged for the human check"] },+ ambient: { id: "ambient", tempo: [50, 80], meters: ["4/4"], families: ["strings", "fmBell", "organ"], moods: ["awe", "calm", "dread"], master: "gentle", reverb: "hall", arrangement: "slow evolution", guards: ["melodic motif at least every 8 bars", "composite ghost check"] },+};++export const MELODY_TYPES: Record<MelodyType, { construction: string; guards: string }> = {+ arpeggio: { construction: "chord tones in a fixed pattern, one per subdivision", guards: "follows every chord change; range <= 17" },+ stepwise: { construction: "step ratio >= 0.7; leaps onto chord tones, stepped back", guards: "range <= 12 per phrase; one high point, in the second half" },+ hook: { construction: "a 2-5 note cell with a distinctive rhythm, repeated and varied", guards: "repetition index 0.4-0.75; returns in the final section" },+ ostinato: { construction: "a fixed 1-2 bar pattern bent to chord tones", guards: "something above it changes every 8 bars" },+ drone: { construction: "tonic or fifth held or re-struck under moving harmony", guards: "re-articulated every 4 bars" },+ callResponse: { construction: "question off the tonic answered on it, new register or instrument", guards: "answer within 1 bar" },+ counterMelody: { construction: "moves when the main line holds, mostly contrary", guards: "shared onsets <= 50%" },+ sequence: { construction: "a 1-2 bar cell repeated a step up or down", guards: "max 3 repeats, then break" },+ themeTransformation: { construction: "the main theme re-cut for a new mood", guards: "contour correlation >= 0.8" },+};diff --git a/engine/src/canvas-core/music/theory.ts b/engine/src/canvas-core/music/theory.tsnew file mode 100644index 0000000..f20e846--- /dev/null+++ b/engine/src/canvas-core/music/theory.ts@@ -0,0 +1,65 @@+// Pitch maths and the MODES table (spec 08 section 3). Pure data and pure functions.+export type ModeId =+ | "major" | "aeolian" | "harmonicMinor" | "melodicMinor" | "dorian" | "phrygian" | "lydian"+ | "mixolydian" | "majorPentatonic" | "minorPentatonic" | "blues" | "wholeTone" | "locrian";++export type Mode = { id: ModeId; intervals: number[]; color: string; use: string; guard: string };++// Intervals are semitones above the tonic. `color` is the degree that makes the mode read as itself.+export const MODES: Record<ModeId, Mode> = {+ major: { id: "major", intervals: [0, 2, 4, 5, 7, 9, 11], color: "3, 7", use: "joy, arrival, sunlight; the music-box default", guard: "section 7 only" },+ aeolian: { id: "aeolian", intervals: [0, 2, 3, 5, 7, 8, 10], color: "b3, b6", use: "sadness, longing, gravity, night", guard: "tonic clarity" },+ harmonicMinor: { id: "harmonicMinor", intervals: [0, 2, 3, 5, 7, 8, 11], color: "raised 7 over V", use: "drama, fate, cadences inside minor", guard: "augmented step b6-7 only as a passing figure, max 2 per phrase" },+ melodicMinor: { id: "melodicMinor", intervals: [0, 2, 3, 5, 7, 9, 11], color: "raised 6 and 7", use: "hopeful minor, yearning lines that climb", guard: "rising lines only; falling lines revert to aeolian" },+ dorian: { id: "dorian", intervals: [0, 2, 3, 5, 7, 9, 10], color: "natural 6", use: "bittersweet, sad but moving forward, folk", guard: "natural 6 in the first 4 bars" },+ phrygian: { id: "phrygian", intervals: [0, 1, 3, 5, 7, 8, 10], color: "b2", use: "menace, heat, the villain's shadow", guard: "b2 resolves to 1 within 2 beats; max 8 bars unless dread" },+ lydian: { id: "lydian", intervals: [0, 2, 4, 6, 7, 9, 11], color: "#4", use: "wonder, flight, magic", guard: "#4 in the first 4 bars; never rest on #4" },+ mixolydian: { id: "mixolydian", intervals: [0, 2, 4, 5, 7, 9, 10], color: "b7", use: "pastoral, easygoing, sunny rock", guard: "b7 in the first 4 bars" },+ majorPentatonic: { id: "majorPentatonic", intervals: [0, 2, 4, 7, 9], color: "no half steps", use: "innocence, lullaby, chiptune melodies", guard: "one non-pentatonic harmony change per 16 bars" },+ minorPentatonic: { id: "minorPentatonic", intervals: [0, 3, 5, 7, 10], color: "b3, b7", use: "cool, soulful, sad without pain", guard: "same 16-bar rule" },+ blues: { id: "blues", intervals: [0, 3, 5, 6, 7, 10], color: "b5", use: "swagger, comedy, jazz and lo-fi colour", guard: "b5 passing only, <= 1/8 note" },+ wholeTone: { id: "wholeTone", intervals: [0, 2, 4, 6, 8, 10], color: "no tonic pull", use: "dream, confusion, magic transition", guard: "max 4 bars, then a real tonic" },+ locrian: { id: "locrian", intervals: [0, 1, 3, 5, 6, 8, 10], color: "b5 over the tonic", use: "never a section mode", guard: "one-bar colour only" },+};++export type PitchClass = "C" | "C#" | "Db" | "D" | "D#" | "Eb" | "E" | "F" | "F#" | "Gb" | "G" | "G#" | "Ab" | "A" | "A#" | "Bb" | "B" | "Cb" | "Fb" | "E#" | "B#";+const PC: Record<string, number> = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };++/** "Ab4" -> 68, "C#6" -> 85, "Fb3" -> 52 (spelling kept for readable scores, value is what sounds). */+export const midi = (name: string): number => {+ const m = /^([A-G])(bb|b|#|x)?(-?\d)$/.exec(name.trim());+ if (!m) throw new Error(`bad note name "${name}"`);+ const acc = m[2] === "b" ? -1 : m[2] === "bb" ? -2 : m[2] === "#" ? 1 : m[2] === "x" ? 2 : 0;+ return 12 * (Number(m[3]) + 1) + PC[m[1]] + acc;+};+export const pcOf = (name: string): number => { const m = /^([A-G])(bb|b|#|x)?$/.exec(name); if (!m) throw new Error(`bad pitch class "${name}"`); return (PC[m[1]] + (m[2] === "b" ? -1 : m[2] === "#" ? 1 : m[2] === "bb" ? -2 : m[2] === "x" ? 2 : 0) + 12) % 12; };+export const hz = (m: number) => 440 * Math.pow(2, (m - 69) / 12);+const NAMES = ["C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];+const SHARPS = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];+export const nameOf = (m: number, sharp = false) => `${(sharp ? SHARPS : NAMES)[((m % 12) + 12) % 12]}${Math.floor(m / 12) - 1}`;+/** Spell with sharps in sharp keys, and the raised leading tone of a minor key as a sharp. */+export const spellerFor = (key: string, mode: ModeId) => {+ const t = pcOf(key.replace(/m$/, "")), sharpMajor = [7, 2, 9, 4, 11, 6, 1].includes(t), minor = mode === "aeolian" || mode === "harmonicMinor" || mode === "melodicMinor" || mode === "dorian";+ const sharpKey = minor ? [4, 11, 6, 1, 8].includes(t) : mode === "lydian" ? [0, 7, 2, 9, 4].includes(t) : sharpMajor;+ return (m: number) => nameOf(m, sharpKey || (minor && ((m - t + 12) % 12 === 11)));+};++/** Scale degree (1-based, may exceed the mode length: wraps into higher octaves) to MIDI. */+export const degree = (tonicMidi: number, mode: ModeId, deg: number): number => {+ const iv = MODES[mode].intervals, k = deg - 1, oct = Math.floor(k / iv.length), i = ((k % iv.length) + iv.length) % iv.length;+ return tonicMidi + 12 * oct + iv[i];+};++/** Detect the best-matching key and mode from a duration-weighted pitch-class histogram (spec 08 section 10). */+export const detectMode = (notes: { p: number; d: number }[], modes: ModeId[] = ["major", "aeolian", "dorian", "mixolydian", "lydian", "phrygian"]) => {+ const h = new Array(12).fill(0); for (const n of notes) h[((n.p % 12) + 12) % 12] += n.d;+ const tot = h.reduce((a, b) => a + b, 0) || 1;+ const res: { tonic: string; mode: ModeId; score: number }[] = [];+ for (let t = 0; t < 12; t++) for (const md of modes) {+ const iv = new Set(MODES[md].intervals.map((x) => (x + t) % 12));+ let inS = 0; for (let k = 0; k < 12; k++) if (iv.has(k)) inS += h[k];+ // in-scale share, plus a tonic and fifth weight so relative modes separate+ res.push({ tonic: NAMES[t], mode: md, score: inS / tot + 0.35 * (h[t] / tot) + 0.12 * (h[(t + 7) % 12] / tot) });+ }+ return res.sort((a, b) => b.score - a.score).slice(0, 3);+};diff --git a/engine/src/canvas-core/paintedOil.ts b/engine/src/canvas-core/paintedOil.tsnew file mode 100644index 0000000..e4a215c--- /dev/null+++ b/engine/src/canvas-core/paintedOil.ts@@ -0,0 +1,328 @@+import { Gfx, rng, fractal, type Medium, type P } from "./core";+import type { Film } from "./film";+import { bounds, clamp, inside, mix, profile } from "./gallery";+import { fit, runProcess, timeline, type Proc } from "./sumiEKit";+import { darken, fill, lighten, oilStroke, weave, type OStroke } from "./paintedOilKit";++// TWO PEARS AND A COPPER POT BY A WINDOW · oil on canvas.+//+// MEDIUM, physically: oil paint on a stretched linen canvas, primed white, then toned with a thin+// rub of burnt sienna and umber (the imprimatura). Hog-bristle flats and filberts, loaded with+// paint that is lean (thinned) in the first passes and fat (straight from the tube) in the last.+// THE MARK: a flat bristle stroke. It lands square and full, drags as the paint runs out (the+// outer bristles first) and breaks into streaks over the layer below. Bristles leave grooves down+// its length and shove ridges up at both edges: the ridge turned to the window catches a thin+// light, the far one a thin dark. Highlights are impasto: short, thick dabs that stand off the+// canvas, ridged, with a hairline shadow on the side away from the light.+// THE EDGE: found on the lit side (the object's colour is clipped crisply against the ground+// already laid), lost in shadow (the shadow colour is dragged out into the dark wall wet into wet+// until there is no line at all). Turning edges are blended wet into wet: a stroke loaded with+// one value picks up the next as it crosses the form, so each stroke carries two colours.+// ORDER: toned ground; a thin burnt-umber drawing with a small brush; the dark masses blocked in+// with a big brush and lean paint; then the mid tones; then the lights; then the impasto highlights+// and the last dark accents (stems, the pot's mouth, contact shadows) and the lost-edge drags.+// PALETTE: a Chardin kitchen palette: raw and burnt umber, burnt sienna, yellow ochre, a little+// terre verte and Naples yellow, lead white; copper is burnt sienna, cadmium orange and white;+// the pears yellow ochre, terre verte and Naples yellow with a sienna blush.+// CANVAS: plain-weave linen, the thread bumps multiplied through everything, strongest where the+// paint is thin.+// LIGHT: one north window just out of frame left, a little above the table: everything is lit from the+// left; cast shadows fall to the right along the table.+// SUBJECT and STRUCTURE: a hammered copper cooking pot, a body of revolution (rolled rim, shoulder,+// belly widest a third of the way down, a narrower foot), two ear handles riveted at the shoulder;+// copper is a mirror, so it shows the window as a narrow bright band left of centre, the dark room+// elsewhere, and the warm table in its lower belly. Two Williams (Bartlett) pears: asymmetric+// bulb, a waisted neck set off-axis, a woody stem, the calyx a dry dark star at the blossom end;+// one stands, one lies on its side in front of the pot. Lambert shading toward the one window,+// a core shadow, warm reflected light from the table in the shadow side, cast shadows.+// REFERENCE (from knowledge): Chardin's kitchen still lifes (the copper cauldron and cistern+// pictures) for the copper's reflections and the dark warm room; Manet's late small still lifes+// for the loaded, dragged bristle mark; the Williams pear's botanical form.++// SIZE HIERARCHY (the painter's, and the plate's first rule): the wall and table are laid with a+// big flat in few broad directional passes, the toned ground left showing between them; the pot+// and pears with a medium brush that follows their form; a small brush only for accents.++const OIL_M: Medium = { nib: 1, taper: 1, pressure: 1, retrace: false, wobble: 0, rough: 0 };+const W = 1080, H = 1080;+const N = 540; // 18 s; the last 30 frames are the finished painting+const L3 = (() => { const v = [-0.72, -0.42, 0.55], l = Math.hypot(...v); return v.map((x) => x / l); })(); // the window, as a light vector++// ---------------------------------------------------------------- colour+const ramp = (stops: string[], t: number) => { const f = clamp(t) * (stops.length - 1), i = Math.min(stops.length - 2, Math.floor(f)); return mix(stops[i], stops[i + 1], f - i); };+const COPPER = ["#100503", "#260a04", "#4e1b0b", "#8a3514", "#c9621c", "#ea9636", "#f8d488"]; // near-black red-brown to saturated orange-gold+const PEAR = ["#243019", "#3b4a26", "#62702e", "#949539", "#c2b248", "#e0cf78", "#f3e9b8"]; // cool green shadow to warm yellow light+const WALL = ["#18130d", "#241d15", "#33291d", "#463a2a", "#5c4e3a", "#74654c"];+const TABLE = ["#2a1c10", "#46301b", "#6a4828", "#94673a", "#b98852", "#d6aa72"];+const UMBER = "#4a2c1a", TONE = "#9a6a44";++// ---------------------------------------------------------------- structure+const TABLE_BACK = 660, TABLE_FRONT = 940, WIN_X = -40; // the window itself is out of frame, left: only its light arrives+const ell = (cx: number, cy: number, rx: number, ry: number, a0: number, a1: number, n: number): P[] => Array.from({ length: n + 1 }, (_, i) => { const a = a0 + ((a1 - a0) * i) / n; return [cx + Math.cos(a) * rx, cy + Math.sin(a) * ry] as P; });+// The eye is a little above the table, so every horizontal circle is an ellipse that opens as it+// drops further below eye level: the rim at 0.17, the foot at 0.205. Rim, hoops and foot all use it.+const OPEN = (y: number) => 0.17 + (0.035 * (y - 508)) / 282;+// the pot: radius at each height, about a vertical axis+const AX = 660, RIM_Y = 508, FOOT_Y = 790;+const PROFILE: [number, number][] = [[508, 150], [530, 146], [556, 160], [585, 176], [620, 188], [652, 192], [690, 188], [730, 176], [765, 158], [790, 140]];+const R = (y: number) => { if (y <= PROFILE[0][0]) return PROFILE[0][1]; for (let i = 1; i < PROFILE.length; i++) if (y <= PROFILE[i][0]) { const [y0, r0] = PROFILE[i - 1], [y1, r1] = PROFILE[i], f = (y - y0) / (y1 - y0); return r0 + (r1 - r0) * (f * f * (3 - 2 * f)); } return PROFILE[PROFILE.length - 1][1]; };+const RIM_RY = 150 * OPEN(RIM_Y), FOOT_RY = 140 * OPEN(FOOT_Y);+const POT: P[] = (() => {+ const right: P[] = [], left: P[] = [];+ for (let y = RIM_Y; y <= FOOT_Y; y += 6) { right.push([AX + R(y), y]); left.push([AX - R(y), y]); }+ return [...ell(AX, RIM_Y, 150, RIM_RY, Math.PI, 2 * Math.PI, 30), ...right, ...ell(AX, FOOT_Y, 140, FOOT_RY, 0, Math.PI, 24), ...left.reverse()];+})();+const MOUTH = ell(AX, RIM_Y + 1, 137, 137 * OPEN(RIM_Y), 0, 2 * Math.PI, 40);+// ear handles riveted at the shoulder: loops standing out sideways, so they are seen nearly flat+const HANDLE_L: P[] = [[AX - R(556) + 2, 556], [474, 551], [454, 564], [457, 590], [476, 603], [AX - R(600) + 2, 600]];+const HANDLE_R: P[] = HANDLE_L.map(([x, y]) => [2 * AX - x, y] as P);++// the pears as bodies of revolution: a spherical bulb, then a waist and neck along an axis+type Pear = { C: P; d: P; rb: number; neck: [number, number][]; lean: number };+const unit = (x: number, y: number): P => { const l = Math.hypot(x, y); return [x / l, y / l]; };+// Williams pear standing: a slightly off-axis neck, the right shoulder fuller than the left+const PA: Pear = { C: [388, 806], d: unit(0.13, -1), rb: 82, neck: [[0, 82], [34, 74], [70, 50], [98, 36], [124, 29], [138, 22], [146, 9]], lean: 0.05 };+// the same pear lying down, blossom end toward us: its bulb nearly round, the neck turning away+// to the back right, so foreshortened to about half its length+const PB: Pear = { C: [578, 874], d: unit(1, -0.42), rb: 62, neck: [[0, 62], [24, 57], [48, 43], [66, 31], [82, 24], [94, 17], [100, 7]], lean: 0 };+const pearR = (p: Pear, s: number) => (s <= 0 ? Math.sqrt(Math.max(0, p.rb * p.rb - s * s)) : profile(p.neck)(s));+const pearTop = (p: Pear) => p.neck[p.neck.length - 1][0];+const nrm = (p: Pear): P => [-p.d[1], p.d[0]];+const pearAt = (p: Pear, s: number, q: number): P => { const n = nrm(p); return [p.C[0] + p.d[0] * s + n[0] * q, p.C[1] + p.d[1] * s + n[1] * q]; };+const outline = (p: Pear): P[] => { const L: P[] = [], Rr: P[] = []; for (let s = -p.rb; s <= pearTop(p); s += 3) { const r = pearR(p, s), k = s > 0 ? p.lean : 0; L.push(pearAt(p, s, -r * (1 - k))); Rr.push(pearAt(p, s, r * (1 + k))); } return [...L, ...Rr.reverse()]; };+const PEAR_A = outline(PA), PEAR_B = outline(PB);+const pearLocal = (p: Pear, x: number, y: number) => { const dx = x - p.C[0], dy = y - p.C[1], n = nrm(p); return { s: dx * p.d[0] + dy * p.d[1], q: dx * n[0] + dy * n[1] }; };+const pearNormal = (p: Pear, x: number, y: number) => {+ const { s, q } = pearLocal(p, x, y), r = Math.max(4, pearR(p, s)), u = clamp(q / r, -1, 1), n = nrm(p);+ const a = s <= 0 ? clamp(s / p.rb, -1, 1) * Math.sqrt(1 - u * u) : -clamp((pearR(p, s + 3) - pearR(p, s - 3)) / 6, -1, 1) * Math.sqrt(1 - u * u) * 0.8;+ const z = Math.sqrt(Math.max(0.02, 1 - u * u - a * a)), v = [n[0] * u + p.d[0] * a, n[1] * u + p.d[1] * a, z], l = Math.hypot(v[0], v[1], v[2]);+ return [v[0] / l, v[1] / l, v[2] / l];+};+const SHADOWS: P[][] = [+ ell(496, 880, 112, 15, 0, 2 * Math.PI, 30), // pear A's, falling right, under pear B+ ell(724, 918, 104, 14, 0, 2 * Math.PI, 30), // pear B's+ ell(878, 797, 180, 33, 0, 2 * Math.PI, 36), // the pot's, running off into the dark right+];+const SHADOW_FROM = [400, 628, 760]; // where each shadow leaves its object: darkest there+const inShadow = (x: number, y: number) => SHADOWS.findIndex((s) => inside(s, x, y));++// ---------------------------------------------------------------- the light model+const dot = (n: number[]) => n[0] * L3[0] + n[1] * L3[1] + n[2] * L3[2];+// Copper, the way a painter sees it rather than a renderer: a warm orange body where it turns to+// the window, a dark core, a band of warm reflected light at the shadow edge from the table, the+// shoulder darker (it reflects the dark room above), the lower belly warmed by the table. The cool+// window reflections and the specular are laid as separate, deliberate strokes, not computed.+// hard value shapes, as metal has: the lit side saturated orange-gold, a quick turn, a near-black core and shadow side+// with one dark band inside the lit side: the dark room reflected between window and wall+const COPPER_ACROSS = profile([[-1, 0.26], [-0.86, 0.5], [-0.66, 0.66], [-0.5, 0.6], [-0.36, 0.34], [-0.24, 0.36], [-0.12, 0.54], [-0.02, 0.4], [0.1, 0.1], [0.3, 0.03], [0.7, 0.02], [0.88, 0.13], [1, 0.05]]);+const copperI = (x: number, y: number) => { const nx = clamp((x - AX) / R(y), -1, 1); return clamp(COPPER_ACROSS(nx) - (y < 565 ? 0.12 * (565 - y) / 57 : 0) + (y > 715 && nx < 0.1 ? 0.05 * (y - 715) / 75 : 0)); };+const copper = (x: number, y: number) => {+ if (inside(MOUTH, x, y)) { const inner = clamp((x - AX + 10) / 120); return ramp(COPPER, 0.01 + 0.3 * inner * inner * inner); } // the far inner wall, lit through the mouth+ const c = ramp(COPPER, copperI(x, y));+ return c;+};+const pearCol = (p: Pear, blush: [number, number, number] | null, shade: (x: number, y: number) => number) => (x: number, y: number) => {+ const n = pearNormal(p, x, y), d = dot(n), bounce = n[0] > 0.3 && n[1] > 0.1 ? 0.12 * n[1] : 0;+ const I = clamp((0.08 + 0.84 * Math.max(0, d) + bounce) * shade(x, y));+ let c = ramp(PEAR, I * 0.9);+ if (bounce > 0.02) c = mix(c, "#7a6428", 0.3); // warm light back up from the table+ if (blush) { const k = clamp(1 - Math.hypot(x - blush[0], y - blush[1]) / blush[2]); if (k > 0) c = mix(c, "#b04428", 0.45 * k * k); }+ return c;+};+const pearI = (p: Pear, x: number, y: number) => clamp(0.08 + 0.84 * Math.max(0, dot(pearNormal(p, x, y))));+const shadeB = (x: number) => (x < 552 ? 0.62 : 1); // pear A's shadow over pear B's blossom end+const pearA = pearCol(PA, [352, 842, 34], () => 1);+const pearB = pearCol(PB, [566, 900, 18], shadeB);+// the wall: darker the further from the window, a slow lift at mid-height where the light lands+const wallI = (x: number, y: number) => clamp(0.64 - 0.56 * Math.pow(clamp(x / W), 0.7) + 0.06 * Math.exp(-((y - 420) ** 2) / (2 * 220 ** 2)));+const tableI = (x: number, y: number) => {+ let I = 0.9 - 0.6 * (x / W) - 0.2 * (1 - (y - TABLE_BACK) / (TABLE_FRONT - TABLE_BACK));+ const k = inShadow(x, y); if (k >= 0) I = Math.min(I, 0.04 + 0.22 * clamp((x - SHADOW_FROM[k]) / 180)); // the shadow's core is at the object, fading outward+ return clamp(I);+};++// ---------------------------------------------------------------- stroke paths that follow the forms+const WALL_R: P[] = [[WIN_X - 4, -40], [W + 40, -40], [W + 40, TABLE_BACK + 8], [WIN_X - 4, TABLE_BACK + 8]];+const TABLE_R: P[] = [[-40, TABLE_BACK - 4], [W + 40, TABLE_BACK - 4], [W + 40, TABLE_FRONT + 4], [-40, TABLE_FRONT + 4]];+const FRONT_R: P[] = [[-40, TABLE_FRONT - 2], [W + 40, TABLE_FRONT - 2], [W + 40, H + 40], [-40, H + 40]];+const steep = (x: number, y: number) => -1.2 + (fractal(91, x, y, 0.002, 0.002, 1) - 0.5) * 0.3; // the wall: steep diagonal passes, top right to bottom left+// a hoop round the pot at the height of (x, y): the stroke curves round the belly like a lathe line+const potHoop = (x: number, y: number, len: number, flip: boolean): P[] | null => {+ const r = R(y), e = OPEN(y) * 1.9, u = clamp((x - AX) / r, -0.999, 0.999), th = Math.acos(u), yc = y - e * r * Math.sin(th), dth = len / (2 * r);+ const at = (t: number): P => [AX + R(yc) * Math.cos(t), yc + e * R(yc) * Math.sin(t)];+ const a = flip ? th + dth : th - dth, b = flip ? th - dth : th + dth; return [at(a), at((a + b) / 2), at(b)];+};+// a hoop round a pear: the cross-section circle at that point of its axis, seen a little from above+const pearHoop = (p: Pear) => (x: number, y: number, len: number, flip: boolean): P[] | null => {+ const { s, q } = pearLocal(p, x, y), r = Math.max(6, pearR(p, s)), th = Math.acos(clamp(q / r, -0.999, 0.999)), dth = Math.min(1.4, len / (2 * r)), e = 0.62;+ const at = (t: number): P => pearAt(p, s - e * r * (Math.sin(t) - Math.sin(th)), r * 0.98 * Math.cos(t));+ const a = flip ? th + dth : th - dth, b = flip ? th - dth : th + dth; return [at(a), at((a + b) / 2), at(b)];+};+// PEARS IN PLANES, the way a painter models a fruit: four value planes, each a flat mixed colour+// (core shadow, reflected light, half tone, light), laid with a few broad strokes that follow the+// surface, then small strokes dragged across each plane edge wet into wet. No gradient, no bands.+const PLANE_V = [0.14, 0.3, 0.54, 0.82];+const planeOf = (p: Pear, shade: (x: number) => number) => (x: number, y: number) => {+ const n = pearNormal(p, x, y), I = pearI(p, x, y) * shade(x);+ if (I >= 0.62) return 3; if (I >= 0.36) return 2; return n[0] > 0.3 && n[1] > 0.05 && I < 0.3 ? 1 : 0;+};+const planeCol = (p: Pear, blush: [number, number, number] | null, shade: (x: number) => number) => { const pl = planeOf(p, shade); return (x: number, y: number) => {+ const k = pl(x, y); let c = ramp(PEAR, PLANE_V[k] * 0.95 + (fractal(77, x, y, 0.02, 0.02, 1) - 0.5) * 0.05);+ if (k === 1) c = mix(c, "#7a6428", 0.35); // warm light back up from the table+ if (blush && k >= 2) { const b = clamp(1 - Math.hypot(x - blush[0], y - blush[1]) / blush[2]); if (b > 0) c = mix(c, "#b04428", 0.5 * b); }+ return c;+}; };+// a stroke laid ON the surface: up the axis on the neck; on the bulb a curved diagonal, travelling+// round and along at once, the way a brush follows a fruit's curvature+const surf = (p: Pear) => (x: number, y: number, len: number, flip: boolean): P[] | null => {+ const { s, q } = pearLocal(p, x, y), r = Math.max(6, pearR(p, s)), u = clamp(q / r, -0.999, 0.999), th = Math.acos(u), top = pearTop(p) - 6;+ const S = (t: number) => clamp(s + t, -p.rb + 4, top);+ if (s > 24) return [-1, 0, 1].map((t) => { const ss = S((t * len) / 2); return pearAt(p, ss, u * pearR(p, ss)); });+ const a = len * 0.36, b = ((len * 0.36) / r) * (u < 0 ? 1 : -1) * (flip ? 1 : 0.7), e = 0.4;+ return [-1, 0, 1].map((t) => { const ss = S(t * a), tt = th + t * b; return pearAt(p, ss - e * r * (Math.sin(tt) - Math.sin(th)), pearR(p, ss) * Math.cos(tt)); });+};+// the blending strokes: short drags straight across each plane edge, carrying one plane's paint into the next+const blends = (p: Pear, outlinePts: P[], col: (x: number, y: number) => string, shade: (x: number) => number, seed: number): OStroke[] => {+ const pl = planeOf(p, shade), r = rng(seed), out: OStroke[] = [], b = bounds(outlinePts), I = (x: number, y: number) => pearI(p, x, y) * shade(x);+ for (let y = b.y0; y < b.y1; y += 9) for (let x = b.x0; x < b.x1; x += 9) {+ const px = x + (r() - 0.5) * 8, py = y + (r() - 0.5) * 8, keep = r(); if (!inside(outlinePts, px, py)) continue;+ const gx = I(px + 2, py) - I(px - 2, py), gy = I(px, py + 2) - I(px, py - 2), gl = Math.hypot(gx, gy); if (gl < 1e-4) continue;+ const ux = gx / gl, uy = gy / gl, a: P = [px - ux * 12, py - uy * 12], c: P = [px + ux * 12, py + uy * 12];+ if (pl(a[0], a[1]) === pl(c[0], c[1]) || keep > 0.55) continue;+ out.push({ ctrl: [a, [px - uy * 2, py + ux * 2], c], w: 10, c0: col(a[0], a[1]), c1: col(c[0], c[1]), load: 1, dry: 0.3, impasto: 0.15, jit: 0.03, soft: 0.25, seed: seed * 100 + out.length });+ }+ return out;+};+// objects shrunk a few px toward their middles: the background may run just under their edges+const inset = (pts: P[], k: number): P[] => { let cx = 0, cy = 0; pts.forEach(([x, y]) => { cx += x; cy += y; }); cx /= pts.length; cy /= pts.length; return pts.map(([x, y]) => { const d = Math.hypot(x - cx, y - cy) || 1; return [cx + (x - cx) * (1 - k / d), cy + (y - cy) * (1 - k / d)] as P; }); };+const shift = (pts: P[], dx: number, dy: number): P[] => pts.map(([x, y]) => [x + dx, y + dy] as P);+const HOLES = [POT, PEAR_A, PEAR_B].map((p) => inset(p, 3)); // not the handles: the wall shows through their loops++// EDGES: an object's paint is clipped to its outline on the side facing the window (found edge)+// but allowed to spill past it on the shadow side (the outline plus a copy shifted away from the+// light), so the shadow side's dark is dragged over the equally dark ground and the edge is lost.+type Clip = { keep?: P[][]; out?: P[][] };+type Stage = { name: string; clip?: Clip; strokes: OStroke[]; per: number }; // per = frames per stroke+const BG: Clip = { out: HOLES };+const lost = (pts: P[], dx = 9, dy = 3): Clip => ({ keep: [pts, shift(pts, dx, dy)] });+const stages = (): Stage[] => {+ const S: Stage[] = [];+ // 1. the toned ground: a thin rub of sienna-umber scrubbed over the white priming+ const tr = rng(3), toning: OStroke[] = [];+ for (let i = 0; i < 16; i++) { const y = -40 + i * 76 + tr() * 30, a = (i % 2 ? 0.12 : -0.1) + (tr() - 0.5) * 0.1; toning.push({ ctrl: [[-80, y - a * 600], [W / 2, y + (tr() - 0.5) * 40], [W + 80, y + a * 600]], w: 150, c0: mix(TONE, "#7e5636", tr() * 0.5), c1: mix(TONE, "#a87a50", tr() * 0.5), load: 1.1, dry: 0.5, impasto: 0, alpha: 0.82, jit: 0.06, seed: 10 + i }); }+ S.push({ name: "tone", strokes: toning, per: 2.6 });+ // 2. the drawing: thin burnt umber, a small round brush, searching lines+ const ln = (ctrl: P[], seed: number, w = 3.2, alpha = 0.78): OStroke => ({ ctrl, w, c0: UMBER, load: 1, dry: 0.15, impasto: 0, alpha, seed });+ const part = (pts: P[], a: number, b: number) => pts.slice(Math.floor(pts.length * a), Math.ceil(pts.length * b));+ const drawing: OStroke[] = [+ ln([[0, TABLE_BACK], [540, TABLE_BACK + 2], [W, TABLE_BACK - 1]], 40, 2.6), ln([[0, TABLE_FRONT], [540, TABLE_FRONT + 1], [W, TABLE_FRONT]], 41, 3),+ ln(part(POT, 0, 0.3), 45), ln(part(POT, 0.28, 0.55), 46), ln(part(POT, 0.53, 0.78), 47), ln(part(POT, 0.76, 1), 48), ln(MOUTH.slice(0, 22), 49, 2.6), ln(MOUTH.slice(20), 50, 2.6),+ ln(HANDLE_L, 51, 2.6), ln(HANDLE_R, 52, 2.6),+ ln(part(PEAR_A, 0, 0.52), 53), ln(part(PEAR_A, 0.48, 1), 54), ln([pearAt(PA, 140, 0), pearAt(PA, 158, 4), pearAt(PA, 172, 12)], 55, 3.6),+ ln(part(PEAR_B, 0, 0.52), 56), ln(part(PEAR_B, 0.48, 1), 57), ln([pearAt(PB, 80, 0), pearAt(PB, 94, -4), pearAt(PB, 106, -10)], 58, 3.6),+ ...SHADOWS.map((s, i) => ({ ctrl: [s[0], s[8], s[15]] as P[], w: 12, c0: UMBER, load: 0.9, dry: 0.6, impasto: 0, alpha: 0.4, seed: 60 + i })),+ { ctrl: [[836, 560], [850, 660], [820, 760]], w: 22, c0: UMBER, load: 0.9, dry: 0.7, impasto: 0, alpha: 0.4, seed: 64 },+ ];+ S.push({ name: "drawing", strokes: drawing, per: 2.4 });+ // 3. the dark masses: the BIG flat, few broad passes, lean paint, ground peeking between+ S.push({ name: "wall", clip: BG, per: 2, strokes: fill({ region: WALL_R, step: 96, len: 340, w: 130, dir: steep, seed: 100, load: 1.05, dry: 0.42, impasto: 0.04, bend: 0.12, jit: 0.035, soft: 0.25, color: (x, y) => ramp(WALL, wallI(x, y)), sweep: 0 }) });+ S.push({ name: "front", per: 1.6, strokes: fill({ region: FRONT_R, step: 80, len: 380, w: 96, dir: () => 0.015, seed: 110, load: 1.05, dry: 0.4, impasto: 0.05, jit: 0.035, soft: 0.25, color: (x) => ramp(TABLE, 0.02 + 0.14 * (1 - x / W)) }) });+ S.push({ name: "table", clip: BG, per: 1.6, strokes: fill({ region: TABLE_R, step: 58, len: 360, w: 74, dir: () => 0.008, seed: 120, load: 1.05, dry: 0.4, impasto: 0.05, bend: 0.03, jit: 0.035, soft: 0.25, color: (x, y) => ramp(TABLE, tableI(x, y) * 0.8), sweep: 0 }) });+ // the pot's and pears' shadow sides, medium brush, strokes wrapping the forms+ S.push({ name: "pot dark", clip: lost(POT), per: 0.4, strokes: fill({ region: POT, step: 34, len: 300, w: 44, dir: () => 0, path: potHoop, seed: 130, dry: 0.3, impasto: 0.08, jit: 0.03, soft: 0.3, color: (x, y) => (inside(MOUTH, x, y) || copperI(x, y) > 0.3 ? null : copper(x, y)), sweep: 0 }) });+ S.push({ name: "mouth", clip: { keep: [MOUTH] }, per: 0.6, strokes: fill({ region: inset(MOUTH, -6), step: 14, len: 110, w: 20, dir: () => 0, seed: 135, dry: 0.2, impasto: 0.08, jit: 0.06, color: (x, y) => copper(x, y), sweep: 0 }) });+ const colA = planeCol(PA, [350, 842, 30], () => 1), colB = planeCol(PB, [564, 902, 16], shadeB), plA = planeOf(PA, () => 1), plB = planeOf(PB, shadeB);+ S.push({ name: "pear A shadow planes", clip: lost(PEAR_A, 7, 3), per: 0.8, strokes: fill({ region: inset(PEAR_A, -4), step: 19, len: 74, w: 26, dir: () => 0, path: surf(PA), seed: 150, dry: 0.2, impasto: 0.12, jit: 0.03, soft: 0.25, color: (x, y) => (plA(x, y) <= 1 ? colA(x, y) : null), sweep: 3.14 }) });+ S.push({ name: "pear B shadow planes", clip: lost(PEAR_B, 7, 3), per: 0.8, strokes: fill({ region: inset(PEAR_B, -4), step: 17, len: 64, w: 22, dir: () => 0, path: surf(PB), seed: 160, dry: 0.2, impasto: 0.12, jit: 0.03, soft: 0.25, color: (x, y) => (plB(x, y) <= 1 ? colB(x, y) : null), sweep: 3.14 }) });+ // 4. the window as light, the mid tones: the wall's glow near the window laid over the dark in+ // broad scumbles, the table's lit plane, the forms' half tones+ S.push({ name: "wall glow", clip: BG, per: 2, strokes: fill({ region: [[-40, -40], [560, -40], [460, TABLE_BACK + 8], [-40, TABLE_BACK + 8]], step: 92, len: 300, w: 110, dir: steep, seed: 180, load: 0.95, dry: 0.6, impasto: 0.04, bend: 0.12, jit: 0.035, soft: 0.25, color: (x, y) => ramp(WALL, clamp(wallI(x, y) + 0.16 * clamp(1 - x / 560))), sweep: 0 }) });+ S.push({ name: "handles", per: 1.4, strokes: [HANDLE_L, HANDLE_R].map((h, i) => ({ ctrl: h, w: 12, c0: ramp(COPPER, i ? 0.06 : 0.5), c1: ramp(COPPER, i ? 0.03 : 0.3), load: 1.1, dry: 0.15, impasto: 0.35, seed: 140 + i })) });+ S.push({ name: "table light", clip: BG, per: 1.3, strokes: fill({ region: TABLE_R, step: 44, len: 300, w: 52, dir: () => 0.008, seed: 190, dry: 0.45, impasto: 0.1, bend: 0.03, jit: 0.04, soft: 0.25, color: (x, y) => { const I = tableI(x, y); return I < 0.45 ? null : ramp(TABLE, I); }, sweep: 0 }) });+ S.push({ name: "pot body", clip: lost(POT), per: 0.4, strokes: fill({ region: POT, step: 28, len: 260, w: 36, dir: () => 0, path: potHoop, seed: 200, dry: 0.35, impasto: 0.12, jit: 0.03, soft: 0.3, color: (x, y) => (!inside(MOUTH, x, y) && copperI(x, y) > 0.2 ? copper(x, y) : null), sweep: 0 }) });+ S.push({ name: "pear A half tone", clip: lost(PEAR_A, 7, 3), per: 0.8, strokes: fill({ region: PEAR_A, step: 18, len: 70, w: 25, dir: () => 0, path: surf(PA), seed: 210, dry: 0.2, impasto: 0.18, jit: 0.03, soft: 0.25, color: (x, y) => (plA(x, y) === 2 ? colA(x, y) : null), sweep: 3.14 }) });+ S.push({ name: "pear B half tone", clip: lost(PEAR_B, 7, 3), per: 0.8, strokes: fill({ region: PEAR_B, step: 16, len: 60, w: 21, dir: () => 0, path: surf(PB), seed: 220, dry: 0.2, impasto: 0.18, jit: 0.03, soft: 0.25, color: (x, y) => (plB(x, y) === 2 ? colB(x, y) : null), sweep: 3.14 }) });+ // cast shadows laid back into the lit table: dark and crisp where each thing meets the table, fading out+ SHADOWS.forEach((sh, i) => S.push({ name: `cast shadow ${i}`, clip: BG, per: 0.7, strokes: fill({ region: sh, step: 13, len: 90, w: 18, dir: () => 0.01, seed: 235 + i, dry: 0.35, impasto: 0.08, bend: 0.04, jit: 0.04, color: (x, y) => ramp(TABLE, tableI(x, y) * 0.9), sweep: 0 }) }));+ // 5. the lights: the forms' lit planes, fatter paint, still following the form+ S.push({ name: "pot light", clip: { keep: [POT] }, per: 0.6, strokes: fill({ region: POT, step: 24, len: 200, w: 26, dir: () => 0, path: potHoop, seed: 240, dry: 0.4, impasto: 0.22, jit: 0.03, soft: 0.3, color: (x, y) => (!inside(MOUTH, x, y) && copperI(x, y) > 0.6 ? copper(x, y) : null), sweep: 0 }) });+ S.push({ name: "pear A light plane", clip: { keep: [PEAR_A] }, per: 0.9, strokes: fill({ region: PEAR_A, step: 18, len: 62, w: 23, dir: () => 0, path: surf(PA), seed: 250, dry: 0.22, impasto: 0.3, jit: 0.03, soft: 0.25, color: (x, y) => (plA(x, y) === 3 ? colA(x, y) : null), sweep: 3.14 }) });+ S.push({ name: "pear B light plane", clip: { keep: [PEAR_B] }, per: 0.9, strokes: fill({ region: PEAR_B, step: 16, len: 54, w: 20, dir: () => 0, path: surf(PB), seed: 260, dry: 0.22, impasto: 0.3, jit: 0.03, soft: 0.25, color: (x, y) => (plB(x, y) === 3 ? colB(x, y) : null), sweep: 3.14 }) });+ S.push({ name: "pear edges blended", clip: { keep: [PEAR_A, PEAR_B] }, per: 0.7, strokes: [...blends(PA, PEAR_A, colA, () => 1, 265), ...blends(PB, PEAR_B, colB, shadeB, 266)] });+ // 6. the window in the copper, the lip, the specular, the accents: the small brush, deliberate strokes+ const arc = (y: number, nx0: number, nx1: number) => { const r = R(y), e = OPEN(y) * 1.9, t0 = Math.acos(nx0), t1 = Math.acos(nx1); return [0, 0.5, 1].map((k) => { const t = t0 + (t1 - t0) * k; return [AX + r * Math.cos(t), y + e * r * (Math.sin(t) - 1)] as P; }); };+ const st = (ctrl: P[], w: number, c0: string, seed: number, c1 = c0, imp = 0.5, dry = 0.25, load = 1.1): OStroke => ({ ctrl, w, c0, c1, load, dry, impasto: imp, jit: 0.05, seed });+ S.push({ name: "window in the copper", per: 4, strokes: [+ // three confident strokes of cool sky, each following the belly round, warming as they turn into the copper+ st(arc(598, -0.6, -0.26), 11, "#c6cdca", 300, "#dc9c70", 0.45, 0.55, 1), st(arc(636, -0.64, -0.2), 13, "#d6dbd5", 301, "#e4a678", 0.5, 0.5, 1.05), st(arc(680, -0.58, -0.3), 9, "#b3bdbb", 302, "#c9855a", 0.4, 0.65, 0.95),+ ] });+ // the metal: two pale-gold reflection bands dragged down the belly's curve (the lit wall beside+ // the window, seen in the copper), one broad band near the lit limb, clear of the sky strokes+ const band = (nx: number, y0: number, y1: number): P[] => [y0, (y0 + y1) / 2, y1].map((y) => [AX + nx * R(y), y] as P);+ S.push({ name: "gold bands", clip: { keep: [POT] }, per: 5, strokes: [+ { ctrl: band(-0.8, 560, 748), w: 20, c0: "#f3cd80", c1: "#e39a3a", load: 1.05, dry: 0.55, impasto: 0.35, jit: 0.04, soft: 0.35, seed: 290 },+ ] });+ S.push({ name: "lip", per: 3, strokes: [+ // the inner lip of the far rim, turned up to the light: one bright line+ st(ell(AX, RIM_Y + 1, 136, 136 * OPEN(RIM_Y), Math.PI * 1.12, Math.PI * 1.7, 16), 3.5, "#f7cf86", 284, "#d9913e", 0.6, 0.2, 1.1),+ // the rolled lip, one ellipse at eye level: the back lip dark against the mouth, the front lip lit on the window side+ st(ell(AX, RIM_Y, 146, 146 * OPEN(RIM_Y), Math.PI * 1.04, Math.PI * 1.96, 16), 5, "#6a2c14", 280, "#3a160a", 0.3, 0.15, 1),+ st(ell(AX, RIM_Y, 147, 147 * OPEN(RIM_Y) + 1, Math.PI * 0.97, Math.PI * 0.03, 22), 8, "#e39a5c", 281, "#3e170a", 0.55, 0.1, 1.1),+ st([[AX - 118, RIM_Y + 15], [AX - 92, RIM_Y + 21], [AX - 60, RIM_Y + 24.5]], 4.5, "#f6d7a8", 282, "#e8b47e", 0.8, 0.3),+ st([[476, 551], [460, 556], [454, 572]], 4, "#e0a46e", 283, "#a8582a", 0.7, 0.3),+ ] });+ S.push({ name: "specular", per: 6, strokes: [+ ({ ctrl: [[586, 632], [591, 630.6], [596, 630.4]], w: 7, c0: "#fffdf6", c1: "#fff6e2", load: 1.4, dry: 0, impasto: 1, jit: 0.01, soft: 0, seed: 305 }), // the one sharp glint of the window, thick+ st([[344, 772], [349, 765], [356, 761]], 5.5, "#f2eabc", 306, "#e0d38c", 0.8, 0.3, 1.2), // pear A's lit shoulder+ st([[545, 846], [550, 840], [557, 837]], 5, "#efe6b4", 307, "#dccd84", 0.8, 0.3, 1.2), // pear B's+ ] });+ S.push({ name: "accents", per: 3, strokes: [+ // stems, woody, dark, a lit edge; the calyx a dry dark star at the lying pear's blossom end+ st([pearAt(PA, 140, 0), pearAt(PA, 156, 3), pearAt(PA, 172, 12)], 5.5, "#3a2412", 320, "#6a4424", 0.4, 0.2, 1),+ st([pearAt(PB, 78, 0), pearAt(PB, 92, -3), pearAt(PB, 104, -9)], 5, "#3a2412", 321, "#6a4424", 0.4, 0.2, 1),+ st([pearAt(PB, -52, -8), pearAt(PB, -56, 2)], 5, "#2a2010", 322, "#2a2010", 0.5, 0.6, 1), st([pearAt(PB, -50, 4), pearAt(PB, -57, -4)], 4, "#3a2e14", 323, "#3a2e14", 0.5, 0.6, 1),+ st([pearAt(PA, 150, 1), pearAt(PA, 158, 4)], 2.5, "#8a6440", 324, "#8a6440", 0.3, 0.2, 1),+ ] });+ S.push({ name: "contact", clip: BG, per: 2, strokes: [+ // the crisp dark where each thing presses on the table, tucked under it+ st([[336, 874], [390, 887], [444, 876]], 10, "#1e140b", 325, "#2e1f12", 0.08, 0.45, 1), st([[548, 924], [594, 934], [640, 922]], 9, "#1e140b", 326, "#2e1f12", 0.08, 0.45, 1),+ st([[740, 812], [772, 806], [800, 798]], 10, "#1e140b", 327, "#2e1f12", 0.08, 0.45, 1),+ ] });+ return S;+};++// ---------------------------------------------------------------- the process+const ground = (g: Gfx) => {+ const c = g.cur, e = g.env; c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.fillStyle = "#efe8da"; c.fillRect(0, 0, e.W, e.H); // lead-white priming+ weave(g, 0.55);+};+const finish = (g: Gfx) => weave(g, 0.3);+const withClip = (g: Gfx, clip: Clip | undefined, fn: () => void) => {+ if (!clip) return fn();+ const c = g.cur; c.save(); c.beginPath();+ if (clip.keep) { clip.keep.forEach((p) => { c.moveTo(p[0][0], p[0][1]); p.forEach(([x, y]) => c.lineTo(x, y)); c.closePath(); }); c.clip("nonzero"); }+ else { c.rect(-50, -50, W + 100, H + 100); (clip.out ?? []).forEach((p) => { c.moveTo(p[0][0], p[0][1]); p.forEach(([x, y]) => c.lineTo(x, y)); c.closePath(); }); c.clip("evenodd"); }+ fn(); c.restore();+};+const build = (k: number): Proc => {+ const tl = timeline(10, k, true);+ stages().forEach((st, si) => {+ const B = Math.max(1, Math.round(2 / st.per)); // a batch is about two frames of work+ for (let a = 0; a < st.strokes.length; a += B) {+ const batch = st.strokes.slice(a, a + B);+ tl.add(batch.length * st.per, (g, p) => withClip(g, st.clip, () => { const f = p * batch.length; batch.forEach((s, i) => { if (p >= 1 || i < Math.floor(f)) oilStroke(g, s, 1); else if (i === Math.floor(f)) oilStroke(g, s, f - i); }); }));+ }+ tl.wait(si < 2 ? 12 : 5);+ });+ return { id: "paintedOil", medium: OIL_M, ground, ops: tl.ops, finish };+};+const PROC = fit(build, N - 31), END = PROC.ops[PROC.ops.length - 1].t1;++export const STYLE = { id: "paintedOil", name: "Oil on canvas", family: "paint", medium: "opaque oil paint with hog-bristle brushes on a toned linen canvas, lean block-in to fat impasto", nearest: "ranunculus", hero: "two pears and a copper pot by a window" };++export const paintedOil: Film = {+ meta: { title: "Two pears and a copper pot · oil", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },+ assets: { images: {} },+ shots: [{ id: "paint", start: 0, end: N, draw: (ctx, f, env) => runProcess(PROC, ctx, Math.min(f, END), env) }],+};+export { lighten, darken };diff --git a/engine/src/canvas-core/paintedOilKit.ts b/engine/src/canvas-core/paintedOilKit.tsnew file mode 100644index 0000000..541b350--- /dev/null+++ b/engine/src/canvas-core/paintedOilKit.ts@@ -0,0 +1,132 @@+// PAINTED OIL KIT. What oil paint needs that the core does not have: a canvas-weave tile, a+// loaded flat bristle stroke with ridged edges and relief, and a region filler that lays strokes+// along a form's direction field with the colour the light model asks for at each end.+import { Gfx, rng, fractal, type Env, type Layer, type P } from "./core";+import { bounds, clamp, inside, mix, resample, smooth } from "./gallery";++// ---------------------------------------------------------------- the canvas+// Plain-weave linen: warp and weft threads ~3.4 px apart, each crossing a small rounded bump,+// the thread over on top alternating. A multiply tile (1 = thread top, darker in the valleys),+// periodic so it repeats without a seam, built once per scale.+const WEAVE = 34, THREADS = 10;+const weaveTile = (env: Env): Layer => {+ const key = `paintedOil:weave:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const n = Math.round(WEAVE * env.scale); L = env.canvas(n, n); const img = L.ctx.createImageData(n, n), d = img.data, cell = WEAVE / THREADS;+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {+ const lx = x / env.scale, ly = y / env.scale, i = Math.floor(lx / cell), j = Math.floor(ly / cell), fx = lx / cell - i, fy = ly / cell - j;+ const warpOver = (i + j) % 2 === 0, slub = fractal(71, lx, ly, 0.06, 0.02, 2, WEAVE) * 0.5 + fractal(72, lx, ly, 0.02, 0.06, 2, WEAVE) * 0.5;+ const across = warpOver ? fx : fy, along = warpOver ? fy : fx;+ const round = Math.sin(Math.PI * clamp(across * 1.08 - 0.04)), bump = 0.72 + 0.28 * Math.sin(Math.PI * along);+ let v = 0.62 + 0.38 * Math.pow(round, 0.6) * bump; // the thread's top catches light, its sides and the gaps sink+ v += (warpOver ? -0.06 : 0.06) * (fx - 0.5); // lit from the left: the left flank of every bump is lighter+ v *= 0.92 + 0.12 * slub;+ const g = Math.round(255 * clamp(v)), k = (y * n + x) * 4; d[k] = g; d[k + 1] = Math.round(g * 0.985); d[k + 2] = Math.round(g * 0.95); d[k + 3] = 255;+ }+ L.ctx.putImageData(img, 0, 0); env.cache.set(key, L); return L;+};+export const weave = (g: Gfx, alpha: number) => { const m = g.main, t = weaveTile(g.env); m.save(); m.setTransform(1, 0, 0, 1, 0, 0); m.globalCompositeOperation = "multiply"; m.globalAlpha = alpha; m.fillStyle = m.createPattern(t.canvas as CanvasImageSource, "repeat")!; m.fillRect(0, 0, Math.round(g.env.W * g.env.scale), Math.round(g.env.H * g.env.scale)); m.restore(); m.setTransform(g.env.scale, 0, 0, g.env.scale, 0, 0); };++// ---------------------------------------------------------------- the bristle stroke+export const LIGHT: P = [-0.9, -0.44]; // window light, from the left and a little above+const LIFT = "#fff3dc", SINK = "#1b0f08";+export const lighten = (c: string, k: number) => mix(c, LIFT, clamp(k));+export const darken = (c: string, k: number) => mix(c, SINK, clamp(k));+export type OStroke = {+ ctrl: P[]; w: number; c0: string; c1?: string; // the colour it was loaded with, and what it has picked up by the end (wet into wet)+ load?: number; dry?: number; // paint on the brush at touch-down; how fast it runs out (0 = never)+ impasto?: number; // 0 lean paint lying flat .. 1 a thick ridged dab standing off the canvas+ alpha?: number; // < 1 only for thin, lean paint (toning, the umber drawing)+ jit?: number; // how much the bristles differ in value (a big soft flat barely streaks)+ soft?: number; // 0 lands square (a fresh flat) .. 0.3 feathered in: the brush slid into the stroke, hairs touching down one after another+ seed: number;+};+// progress < 1 lays the first part of the stroke only: the brush is still travelling+export const oilStroke = (g: Gfx, s: OStroke, travel = 1) => {+ if (travel <= 0) return;+ const { w, c0, c1 = c0, load = 1, dry = 0.35, impasto = 0.3, seed } = s, r = rng(seed * 13 + 5);+ const sm = smooth(s.ctrl, false, 8); let len = 0; for (let i = 1; i < sm.length; i++) len += Math.hypot(sm[i][0] - sm[i - 1][0], sm[i][1] - sm[i - 1][1]);+ const n = Math.max(5, Math.round(len / 2.2)), pts = resample(sm, n), last = Math.max(1, Math.min(n - 1, Math.round((n - 1) * travel)));+ const nr: P[] = pts.map((_, i) => { const a = pts[Math.max(0, i - 1)], b = pts[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1; return [-dy / l, dx / l]; });+ const nb = Math.max(5, Math.min(26, Math.round(w / 2.3))), prof = (t: number) => (t < 0.08 ? 0.9 + 1.4 * t : t > 0.8 ? 1 - (t - 0.8) * 1.4 : 1) * (1 + 0.05 * Math.sin(t * 9 + seed));+ const c = g.cur, touch = (p: P, pad: number) => g.touch(p[0] - pad, p[1] - pad, p[0] + pad, p[1] + pad);+ // where each hair has paint: the flat brush lands square and full, runs out along its length,+ // the outer hairs first, and a dragged-out end breaks into streaks+ const hairs = Array.from({ length: nb }, (_, b) => ({ u: -1 + (2 * (b + 0.5)) / nb + (r() - 0.5) * (0.8 / nb), tone: (r() - 0.5) * (s.jit ?? 0.14), load: load * (0.85 + 0.3 * r()), end: 1 - r() * 0.1, start: (s.soft ?? 0.1) * r() * (0.35 + 0.65 * Math.abs(-1 + (2 * (b + 0.5)) / nb)) }));+ const has = (h: (typeof hairs)[number], hi: number, i: number) => { const t = i / (n - 1); if (t > h.end || t < h.start) return false; const rem = h.load - dry * t * (1 + 0.5 * Math.abs(h.u)); return rem * 1.6 > fractal(seed * 7 + hi, t * len * 0.05, hi * 0.9, 1, 1, 2) + 0.1; };+ const at = (i: number, u: number, W = w * prof(i / (n - 1))): P => [pts[i][0] + nr[i][0] * (u * W) / 2, pts[i][1] + nr[i][1] * (u * W) / 2];+ const body = (flat?: string) => {+ c.lineCap = "round"; c.lineJoin = "round";+ hairs.forEach((h, hi) => {+ let run: number[] = [];+ const flush = () => {+ for (let a = 0; a + 1 < run.length; a += 5) {+ const seg = run.slice(a, Math.min(run.length, a + 6)), t = seg[Math.floor(seg.length / 2)] / (n - 1), base = mix(c0, c1, clamp(t * 1.15));+ c.strokeStyle = flat ?? (h.tone > 0 ? lighten(base, h.tone) : darken(base, -h.tone)); c.lineWidth = Math.max(0.8, ((w * prof(t)) / nb) * 1.9);+ c.beginPath(); seg.forEach((i, k) => { const p = at(i, h.u); k ? c.lineTo(p[0], p[1]) : c.moveTo(p[0], p[1]); }); c.stroke();+ }+ run = [];+ };+ for (let i = 0; i <= last; i++) { if (has(h, hi, i)) { run.push(i); touch(at(i, h.u), 3 + w / nb); } else flush(); }+ flush();+ });+ };+ const thin = (s.alpha ?? 1) < 1;+ if (thin) g.group("plain", () => body(), { alpha: s.alpha }); else {+ // relief: a thick dab stands off the canvas and throws a hairline shadow away from the window+ if (impasto > 0.5) { c.save(); c.translate(0.9 * impasto, 0.8 * impasto); c.globalAlpha = 0.16 * impasto; body(darken(c0, 0.7)); c.restore(); c.globalAlpha = 1; }+ body();+ }+ if (impasto <= 0.05) return;+ // the ridges: paint shoved to both edges of the brush. The edge turned to the window catches a+ // light line, the far edge a dark one; a few bristle grooves run down the middle+ const lit = (side: number, i: number) => (nr[i][0] * side * LIGHT[0] + nr[i][1] * side * LIGHT[1]) > 0;+ c.lineCap = "round";+ [-1, 1].forEach((side) => {+ const h = side < 0 ? hairs[0] : hairs[nb - 1], hi = side < 0 ? 0 : nb - 1; let run: number[] = [];+ const flush = () => {+ for (let a = 0; a + 1 < run.length; a += 5) {+ const seg = run.slice(a, Math.min(run.length, a + 6)), i0 = seg[Math.floor(seg.length / 2)], t = i0 / (n - 1), base = mix(c0, c1, clamp(t * 1.15)), L = lit(side, i0);+ c.strokeStyle = L ? lighten(base, 0.22 + 0.35 * impasto) : darken(base, 0.25 + 0.3 * impasto); c.globalAlpha = clamp(0.35 + 0.6 * impasto); c.lineWidth = 0.9 + 1.1 * impasto;+ c.beginPath(); seg.forEach((i, k) => { const p = at(i, side * 0.94); k ? c.lineTo(p[0], p[1]) : c.moveTo(p[0], p[1]); }); c.stroke();+ }+ run = [];+ };+ for (let i = 0; i <= last; i++) { if (has(h, hi, i)) run.push(i); else flush(); }+ flush();+ });+ for (let k = 0; k < 2 + Math.round(impasto * 3); k++) {+ const u = -0.7 + r() * 1.4, i0 = Math.floor(r() * 0.3 * last), i1 = Math.min(last, i0 + Math.round(last * (0.3 + r() * 0.6)));+ c.globalAlpha = 0.18 + 0.3 * impasto; c.lineWidth = 0.7; c.strokeStyle = darken(c0, 0.35); c.beginPath(); for (let i = i0; i <= i1; i++) { const p = at(i, u); i === i0 ? c.moveTo(p[0], p[1]) : c.lineTo(p[0], p[1]); } c.stroke();+ c.strokeStyle = lighten(c0, 0.3); c.beginPath(); for (let i = i0; i <= i1; i++) { const p = at(i, u - 0.09); i === i0 ? c.moveTo(p[0], p[1]) : c.lineTo(p[0], p[1]); } c.stroke();+ }+ // where the brush lifted the paint piles up across the stroke end+ if (travel >= 1 && impasto > 0.25) {+ const i = Math.round(last * 0.97), a = at(i, -0.85), b = at(i, 0.85), m: P = [(a[0] + b[0]) / 2 + (pts[i][0] - pts[Math.max(0, i - 3)][0]) * 0.6, (a[1] + b[1]) / 2 + (pts[i][1] - pts[Math.max(0, i - 3)][1]) * 0.6];+ c.globalAlpha = 0.45 * impasto; c.lineWidth = 1.2 + impasto; c.strokeStyle = lighten(c1, 0.35); c.beginPath(); c.moveTo(a[0], a[1]); c.quadraticCurveTo(m[0], m[1], b[0], b[1]); c.stroke();+ }+ c.globalAlpha = 1;+};++// ---------------------------------------------------------------- filling a region with strokes+export type Pass = {+ region: P[]; // where the stroke centres go+ step: number; len: number; w: number; // spacing of stroke centres, stroke length and width+ dir: (x: number, y: number) => number; // stroke angle (radians) at a point: the direction the form asks for+ color: (x: number, y: number) => string | null; // what colour the light model wants here; null = this pass leaves it alone+ seed: number; load?: number; dry?: number; impasto?: number; bend?: number; sweep?: number; jit?: number; soft?: number; // sweep = angle the painter works across the area+ path?: (x: number, y: number, len: number, flip: boolean) => P[] | null; // a stroke that follows the form's own curve (overrides dir)+};+export const fill = (p: Pass): OStroke[] => {+ const b = bounds(p.region), r = rng(p.seed), out: { s: OStroke; k: number }[] = [], sw = p.sweep ?? 0.35;+ for (let y = b.y0; y <= b.y1; y += p.step * 0.86) for (let x = b.x0 - ((Math.round(y / p.step) % 2) * p.step) / 2; x <= b.x1; x += p.step) {+ const px = x + (r() - 0.5) * p.step * 0.9, py = y + (r() - 0.5) * p.step * 0.9, jl = r(), jb = r(), ja = r();+ if (!inside(p.region, px, py)) continue;+ const a = p.dir(px, py) + (ja - 0.5) * 0.25, L = p.len * (0.75 + 0.5 * jl), dx = Math.cos(a), dy = Math.sin(a), bend = (jb - 0.5) * (p.bend ?? 0.18) * L;+ const own = p.path?.(px, py, L, jb < 0.5) ?? null;+ const ctrl: P[] = own ?? [[px - (dx * L) / 2, py - (dy * L) / 2], [px - dy * bend, py + dx * bend], [px + (dx * L) / 2, py + (dy * L) / 2]], p0 = ctrl[0], p2 = ctrl[ctrl.length - 1];+ const c0 = p.color(p0[0], p0[1]) ?? p.color(px, py), c1 = p.color(p2[0], p2[1]) ?? c0;+ if (!c0 || !p.color(px, py)) continue;+ out.push({ s: { ctrl, w: p.w * (0.85 + 0.3 * r()), c0, c1: c1 ?? c0, load: p.load ?? 1, dry: p.dry ?? 0.35, impasto: p.impasto ?? 0.3, jit: p.jit, soft: p.soft, seed: p.seed * 1000 + out.length }, k: px * Math.cos(sw) + py * Math.sin(sw) + (r() - 0.5) * p.step * 3 });+ }+ return out.sort((u, v) => u.k - v.k).map((o) => o.s);+};diff --git a/engine/src/canvas-core/paperCraft.ts b/engine/src/canvas-core/paperCraft.tsnew file mode 100644index 0000000..806bab3--- /dev/null+++ b/engine/src/canvas-core/paperCraft.ts@@ -0,0 +1,235 @@+import { Gfx, rng, type Ctx, type Env, type Medium, type P } from "./core";+import type { Film } from "./film";+import { bounds, mix, smooth } from "./gallery";+import { clamp01, fibres, onGrid, path, scissor, staged, tear, type Step } from "./scrapbookKit";++// A SEASIDE TOWN IN A TOY THEATRE · mixed-media paper collage, stop-motion on twos.+//+// MEDIUM, physically. A cardboard toy theatre stood on a kraft-paper table, built from three+// kinds of paper. (1) COLOURED AND PATTERNED PAPERS, scissor-cut or torn: plain sugar paper for+// the deep sea, printed papers for the rest (a wave print, a dot print for the headland, a stone+// print for the quay, a diamond print on the proscenium, newsprint for the boat). (2) GOUACHE+// CUT-OUTS: flat opaque paint laid in visible brush strokes on white card, cut out with a white+// margin left round them like a sticker (the sun, the lighthouse, the houses, the gull). (3) Card+// itself: every piece has THICKNESS, a darker cut edge showing down-right of its face, and it+// stands a finger's width in front of the flat behind it, so it throws a soft shadow whose+// distance says how far apart the flats are.+// MARK / EDGE / ORDER. Mark: the brush stroke of gouache and the printed motif, never a drawn+// line. Edge: scissor-crisp or torn, then the card's own cut edge, then the white sticker margin.+// Order: the theatre is set on the table, then the scene is built from the back: the sky drop is+// flown in, the sun lowered on its stick, clouds hung, the headland slid in from the wing, the+// lighthouse pushed up, the sea rows and the quay slid in, the houses stood up one by one, the+// boat pushed on along its wave, the gull set on its post, the ground row, the curtains and the+// valance last.+// MOTION GRAMMAR. Stop-motion ON TWOS: every pose is held for two frames. Each piece is moved by+// hand: it travels held above the stack (its shadow wide and far), then lands with a small+// damped jiggle (a few degrees, a pixel or two of bounce) and is still. The final second is the+// still.+// NOT fox (cut paper): fox has no paint, no pattern and no depth between layers; this is painted+// and printed paper in a stage space with real gaps between flats. Light: the sun, upper left.+// Reference, from memory: Pollock's and Webb's Victorian toy theatres (proscenium, wings, ground+// rows, flown drops), a herring gull's side profile, the folded-newspaper boat.++const N = 390;+const PEN: Medium = { nib: 1, taper: 0.3, pressure: 0.3, retrace: false, wobble: 0.4, rough: 0.3 };+const WHITE = "#fbf9f2";++// ---------------------------------------------------------------- paint and print (all clipped to the piece)+type R = () => number;+const gouache = (c: Ctx, shape: P[], color: string, seed: number, o: { dir?: number; len?: number; w?: number; vary?: number; dens?: number } = {}) => {+ const { dir = 0, len = 44, w = 13, vary = 0.1, dens = 1 } = o, r = rng(seed), b = bounds(shape), area = (b.x1 - b.x0) * (b.y1 - b.y0);+ c.fillStyle = color; path(c, shape); c.fill();+ c.save(); path(c, shape); c.clip(); c.lineCap = "round";+ const n = Math.max(6, Math.round((area / (len * w)) * 1.6 * dens));+ for (let i = 0; i < n; i++) { const x = b.x0 + r() * (b.x1 - b.x0), y = b.y0 + r() * (b.y1 - b.y0), a = dir + (r() - 0.5) * 0.35, l = len * (0.6 + r() * 0.7), k = r(); c.strokeStyle = k < 0.5 ? mix(color, "#ffffff", vary * (0.5 + r())) : mix(color, "#1d2430", vary * (0.4 + r())); c.globalAlpha = 0.28 + r() * 0.25; c.lineWidth = w * (0.6 + r() * 0.6); c.beginPath(); c.moveTo(x - Math.cos(a) * l / 2, y - Math.sin(a) * l / 2); c.quadraticCurveTo(x + (r() - 0.5) * 6, y + (r() - 0.5) * 6, x + Math.cos(a) * l / 2, y + Math.sin(a) * l / 2); c.stroke(); }+ c.restore(); c.globalAlpha = 1;+};+// painted shade: darker strokes laid along one side of a shape (the side away from the sun)+const shadeSide = (c: Ctx, shape: P[], color: string, seed: number, side: P, depth: number, dir = Math.PI / 2) => {+ const b = bounds(shape), r = rng(seed); c.save(); path(c, shape); c.clip(); c.lineCap = "round";+ for (let i = 0; i < 16; i++) { const u = r(), x = side[0] > 0 ? b.x1 - r() * depth : side[0] < 0 ? b.x0 + r() * depth : b.x0 + u * (b.x1 - b.x0), y = side[1] > 0 ? b.y1 - r() * depth : side[1] < 0 ? b.y0 + r() * depth : b.y0 + u * (b.y1 - b.y0), l = 16 + r() * 26; c.strokeStyle = color; c.globalAlpha = 0.3 + r() * 0.25; c.lineWidth = 5 + r() * 7; c.beginPath(); c.moveTo(x - Math.cos(dir) * l / 2, y - Math.sin(dir) * l / 2); c.lineTo(x + Math.cos(dir) * l / 2, y + Math.sin(dir) * l / 2); c.stroke(); }+ c.restore(); c.globalAlpha = 1;+};+const print = (c: Ctx, shape: P[], fn: (b: { x0: number; y0: number; x1: number; y1: number }) => void) => { c.save(); path(c, shape); c.clip(); fn(bounds(shape)); c.restore(); c.globalAlpha = 1; };+// a printed wave motif in rows: rows of small arcs, a little misregistered like cheap printing+const wavePrint = (c: Ctx, shape: P[], col: string, gap = 22, sw = 2) => print(c, shape, (b) => { c.strokeStyle = col; c.lineWidth = sw; c.globalAlpha = 0.55; for (let y = b.y0 + 8, row = 0; y < b.y1 + 10; y += gap, row++) { c.beginPath(); for (let x = b.x0 - 30 + (row % 2) * 15; x < b.x1 + 30; x += 30) { c.moveTo(x, y); c.quadraticCurveTo(x + 7.5, y - 7, x + 15, y); } c.stroke(); } });+const dotPrint = (c: Ctx, shape: P[], col: string, gap = 14, rad = 2.2) => print(c, shape, (b) => { c.fillStyle = col; c.globalAlpha = 0.8; for (let y = b.y0, row = 0; y < b.y1 + gap; y += gap * 0.87, row++) for (let x = b.x0 + (row % 2) * gap * 0.5; x < b.x1 + gap; x += gap) { c.beginPath(); c.arc(x, y, rad, 0, 6.28); c.fill(); } });+const diamondPrint = (c: Ctx, shape: P[], col: string, gap = 26) => print(c, shape, (b) => { c.fillStyle = col; c.globalAlpha = 0.5; for (let y = b.y0, row = 0; y < b.y1 + gap; y += gap / 2, row++) for (let x = b.x0 + (row % 2) * gap / 2; x < b.x1 + gap; x += gap) { c.beginPath(); c.moveTo(x, y - 4); c.lineTo(x + 3, y); c.lineTo(x, y + 4); c.lineTo(x - 3, y); c.closePath(); c.fill(); } c.globalAlpha = 0.18; c.strokeStyle = col; c.lineWidth = 0.8; for (let d = b.x0 - (b.y1 - b.y0); d < b.x1; d += gap) { c.beginPath(); c.moveTo(d, b.y0); c.lineTo(d + (b.y1 - b.y0), b.y1); c.stroke(); c.beginPath(); c.moveTo(d + (b.y1 - b.y0), b.y0); c.lineTo(d, b.y1); c.stroke(); } });+const stonePrint = (c: Ctx, shape: P[], base: string, seed: number) => print(c, shape, (b) => { const r = rng(seed); for (let y = b.y0, row = 0; y < b.y1; y += 17, row++) for (let x = b.x0 - (row % 2) * 16; x < b.x1; ) { const w = 26 + r() * 16; c.fillStyle = mix(base, r() < 0.5 ? "#ffffff" : "#3b3226", 0.06 + r() * 0.14); c.globalAlpha = 1; c.beginPath(); c.roundRect(x + 1.5, y + 1.5, w - 3, 14, 4); c.fill(); x += w; } });+const newsPrint = (c: Ctx, shape: P[], seed: number) => print(c, shape, (b) => { const r = rng(seed); c.fillStyle = "#4a4640"; c.globalAlpha = 0.5; for (let col = b.x0 + 4; col < b.x1; col += 36) for (let y = b.y0 + 4; y < b.y1; y += 4.2) { if (r() < 0.06) { y += 6; continue; } const l = 20 + r() * 12; c.fillRect(col, y, l, 1.3); } c.globalAlpha = 0.7; c.fillRect(b.x0 + 16, b.y0 + 30, 60, 5); });+const woodPrint = (c: Ctx, shape: P[], col: string, seed: number) => print(c, shape, (b) => { const r = rng(seed); c.strokeStyle = col; c.lineWidth = 1; c.globalAlpha = 0.35; for (let y = b.y0; y < b.y1; y += 3 + r() * 4) { c.beginPath(); c.moveTo(b.x0, y); for (let x = b.x0; x <= b.x1; x += 40) c.lineTo(x, y + Math.sin(x * 0.013 + y) * 1.6); c.stroke(); } c.globalAlpha = 0.5; c.strokeStyle = mix(col, "#000000", 0.2); for (let x = b.x0 + 60 + r() * 60; x < b.x1; x += 90 + r() * 90) { c.beginPath(); c.moveTo(x, b.y0); c.lineTo(x, b.y1); c.stroke(); } });++// ---------------------------------------------------------------- pieces+// `cut` = the outline of the piece's card (with `border` for a sticker's white margin, made by+// stroking the outline round, which is the true margin a pair of scissors leaves); `face` paints+// it at rest; `depth` = the gap to the flat behind, which sets the shadow.+type Piece = { hole?: boolean; id: string; at: [number, number]; from: P; pivot: P; cut: P[][]; border?: number; edge: string; depth: number; face: (c: Ctx) => void };+const cutPath = (c: Ctx, pc: Piece, dx = 0, dy = 0, grow = 0) => { c.save(); c.translate(dx, dy); c.beginPath(); pc.cut.forEach((s) => { s.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }); c.fill(pc.hole ? "evenodd" : "nonzero"); if (pc.border || grow) { c.lineJoin = "round"; c.lineWidth = 2 * ((pc.border ?? 0) + grow); c.strokeStyle = c.fillStyle; c.stroke(); } c.restore(); };+// pose of a hand-moved piece on twos: travel held high, land, a damped jiggle, rest+type Pose = { dx: number; dy: number; rot: number; lift: number };+const REST: Pose = { dx: 0, dy: 0, rot: 0, lift: 0 };+const poseAt = (pc: Piece, f: number): Pose => {+ const [s, d] = pc.at, f2 = f - (f % 2); if (f >= s + d) return REST;+ const u = clamp01((f2 - s) / d), r = rng(pc.id.length * 131 + Math.round(f2)), seed = pc.id.charCodeAt(0) + pc.id.length;+ if (u < 0.62) { const v = u / 0.62, e = 1 - (1 - v) ** 2; return { dx: pc.from[0] * (1 - e) + (r() - 0.5) * 1.4, dy: pc.from[1] * (1 - e) + (r() - 0.5) * 1.4, rot: (seed % 2 ? 1 : -1) * 0.04 * (1 - e), lift: 1 - 0.6 * e }; }+ const v = (u - 0.62) / 0.38, damp = Math.exp(-4 * v) * (1 - v);+ return { dx: 0, dy: -2.2 * Math.abs(Math.sin(v * 9)) * damp, rot: (seed % 2 ? 1 : -1) * 0.035 * Math.sin(v * 13 + 0.6) * damp, lift: 0.4 * (1 - v) };+};+const drawPiece = (ctx: Ctx, env: Env, pc: Piece, f: number, p: number) => {+ const q = p >= 1 ? REST : poseAt(pc, f), xf = (c: Ctx) => { c.translate(pc.pivot[0] + q.dx, pc.pivot[1] + q.dy); c.rotate(q.rot); c.translate(-pc.pivot[0], -pc.pivot[1]); };+ // the shadow on the flat behind: wider and farther while the piece is held up+ const g = new Gfx(ctx, env, 0, PEN), sd = pc.depth * (1 + 2.2 * q.lift), all = pc.cut.flat();+ const box = (c: Ctx) => { if (pc.hole) return; c.beginPath(); c.rect(BOX.x0, BOX.y0, BOX.x1 - BOX.x0, BOX.y1 - BOX.y0); c.clip(); }; // the theatre's side walls hide a flat until it is on stage+ g.group("plain", () => { const c = g.cur; c.save(); box(c); xf(c); c.fillStyle = "#2a1c10"; cutPath(c, pc, sd * 0.6, sd); c.restore(); const b = bounds(all), m = (pc.border ?? 0) + sd * 2 + 60; g.touch(b.x0 - m, b.y0 - m, b.x1 + m, b.y1 + m); }, { blur: 2 + sd * 0.5, alpha: 0.36 - 0.1 * q.lift });+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.save(); box(ctx); xf(ctx);+ ctx.fillStyle = pc.edge; cutPath(ctx, pc, 1.2, 1.9); // the card's cut edge, down-right+ if (pc.border) { ctx.fillStyle = WHITE; cutPath(ctx, pc); ctx.fillStyle = "rgba(120,110,90,0.25)"; ctx.save(); ctx.lineWidth = 0.8; ctx.strokeStyle = "rgba(120,110,90,0.3)"; ctx.restore(); }+ pc.face(ctx); ctx.restore();+};++// ---------------------------------------------------------------- the scene, back to front+const OPEN = { x0: 150, y0: 200, x1: 930, y1: 852 }, BOX = { x0: 72, y0: 100, x1: 1008, y1: 948 };+const scallop = (x0: number, x1: number, y: number, amp: number, per: number, ph: number, bottom: number, seed: number): P[] => { const r = rng(seed), top: P[] = []; for (let x = x0; x <= x1 + 1; x += per / 8) top.push([x, y - amp * Math.abs(Math.sin(((x - x0) / per) * Math.PI + ph)) + (r() - 0.5) * 1.2]); return [...top, [x1, bottom], [x0, bottom]]; };++const sky: Piece = { id: "sky", at: [30, 20], from: [0, -420], pivot: [540, 520], edge: "#3f6f86", depth: 3, cut: [[[OPEN.x0 - 10, OPEN.y0 - 30], [OPEN.x1 + 10, OPEN.y0 - 30], [OPEN.x1 + 10, OPEN.y1], [OPEN.x0 - 10, OPEN.y1]]],+ face: (c) => { const s = sky.cut[0]; const gr = c.createLinearGradient(0, OPEN.y0, 0, 600); gr.addColorStop(0, "#5f9dc4"); gr.addColorStop(1, "#cfe3e6"); c.fillStyle = gr; path(c, s); c.fill(); const r = rng(5); c.save(); path(c, s); c.clip(); c.lineCap = "round"; for (let i = 0; i < 150; i++) { const y = OPEN.y0 - 20 + r() * 420, x = OPEN.x0 + r() * (OPEN.x1 - OPEN.x0), t = clamp01((y - OPEN.y0) / 400); c.strokeStyle = mix(mix("#5f9dc4", "#cfe3e6", t), r() < 0.5 ? "#ffffff" : "#2d5f86", 0.12 + r() * 0.1); c.globalAlpha = 0.35; c.lineWidth = 12 + r() * 14; c.beginPath(); c.moveTo(x - 50, y + (r() - 0.5) * 4); c.quadraticCurveTo(x, y + (r() - 0.5) * 8, x + 50 + r() * 40, y + (r() - 0.5) * 4); c.stroke(); } c.restore(); c.globalAlpha = 1; } };++const SUN: P = [470, 336];+const stick: Piece = { id: "stick", at: [50, 16], from: [0, -300], pivot: [SUN[0], 200], edge: "#8a6a40", depth: 6, cut: [[[SUN[0] - 4, 150], [SUN[0] + 4, 150], [SUN[0] + 4, SUN[1] - 40], [SUN[0] - 4, SUN[1] - 40]]], face: (c) => { c.fillStyle = "#d8b37a"; path(c, stick.cut[0]); c.fill(); c.fillStyle = "#b88c52"; c.fillRect(SUN[0] + 1, 150, 3, SUN[1] - 190); } };+const sunRays = (k: number): P[] => Array.from({ length: 24 }, (_, i) => { const a = (i / 24) * Math.PI * 2 - Math.PI / 2, rr = i % 2 ? 50 : 76 - (i % 4 === 0 ? 0 : 8); return [SUN[0] + Math.cos(a) * rr * k, SUN[1] + Math.sin(a) * rr * k] as P; });+const sun: Piece = { id: "sun", at: [50, 16], from: [0, -300], pivot: [SUN[0], 200], edge: "#c9b99a", depth: 6, border: 7, cut: [sunRays(1)],+ face: (c) => { gouache(c, sunRays(1), "#f29a2e", 11, { dir: 0.3, len: 30, w: 10, vary: 0.14 }); const disc: P[] = Array.from({ length: 40 }, (_, i) => { const a = (i / 40) * 6.28; return [SUN[0] + Math.cos(a) * 46, SUN[1] + Math.sin(a) * 46] as P; }); gouache(c, disc, "#f7c343", 12, { dir: -0.6, len: 26, w: 9, vary: 0.12 }); const hi: P[] = Array.from({ length: 20 }, (_, i) => { const a = (i / 20) * 6.28; return [SUN[0] - 14 + Math.cos(a) * 16, SUN[1] - 14 + Math.sin(a) * 12] as P; }); gouache(c, hi, "#fde39a", 13, { dir: -0.6, len: 14, w: 6, vary: 0.05 }); shadeSide(c, disc, "#e0822a", 14, [1, 1], 16, -0.6); } };+// a scissor-cut cloud: flat underside, a run of rounded bumps on top+const cloudShape = (cx: number, cy: number, w: number, h: number, seed: number): P[] => { const r = rng(seed), pts: P[] = [[cx + w / 2, cy]], n = 4 + Math.floor(r() * 2); for (let i = 0; i <= n; i++) { const x = cx + w / 2 - (w * i) / n, hh = h * (0.45 + 0.55 * Math.sin((Math.PI * (i + 0.5)) / (n + 1))) * (0.8 + r() * 0.3); for (let k = 0; k <= 6; k++) { const a = (k / 6) * Math.PI, rr = w / n / 2; pts.push([x - rr + Math.cos(a) * rr, cy - hh * 0.5 - Math.sin(a) * hh * 0.55]); } } pts.push([cx - w / 2, cy]); return pts.map(([x, y], i) => [x, i === 0 || i === pts.length - 1 ? y : y]) as P[]; };+const cloud = (id: string, cx: number, cy: number, w: number, h: number, seed: number, at: [number, number]): Piece => { const s = scissor(cloudShape(cx, cy, w, h, seed), seed, 0.7); return { id, at, from: [0, -260], pivot: [cx, cy], edge: "#b9c4c8", depth: 7, cut: [s], face: (c) => { gouache(c, s, "#f6f4ec", seed, { len: 30, w: 10, vary: 0.05 }); shadeSide(c, s, "#b9c7d3", seed + 1, [0, 1], h * 0.28, 0.1); } }; };+const cloud1 = cloud("cloud1", 640, 336, 170, 70, 21, [65, 12]), cloud2 = cloud("cloud2", 812, 400, 110, 48, 22, [75, 12]);++const HEAD: P[] = smooth([[130, 640], [130, 468], [196, 446], [268, 436], [334, 452], [404, 490], [470, 540], [540, 600], [560, 640]], false, 6);+const headland: Piece = { id: "headland", at: [85, 16], from: [-440, 0], pivot: [300, 540], edge: "#4e6e38", depth: 8, cut: [tear(HEAD, 1.6, 31)],+ face: (c) => { const s = headland.cut[0]; c.fillStyle = "#7fa25a"; path(c, s); c.fill(); fibres(c, s, "#7fa25a", 32, 0.6, 0.2); dotPrint(c, s, "#a6c77a", 13, 2); const band = tear(smooth([[130, 640], [130, 530], [240, 520], [360, 540], [470, 580], [560, 640]], false, 5), 2, 33); c.fillStyle = "#5c8546"; path(c, band); c.fill(); fibres(c, band, "#5c8546", 34, 0.6, 0.2); } };+const LH: P = [318, 478];+const lhTower: P[] = [[LH[0] - 18, LH[1]], [LH[0] + 18, LH[1]], [LH[0] + 12, LH[1] - 86], [LH[0] - 12, LH[1] - 86]];+const lhCut: P[] = [[LH[0] - 20, LH[1] + 2], [LH[0] + 20, LH[1] + 2], [LH[0] + 14, LH[1] - 88], [LH[0] + 16, LH[1] - 90], [LH[0] + 12, LH[1] - 112], [LH[0] + 2, LH[1] - 126], [LH[0] - 2, LH[1] - 126], [LH[0] - 12, LH[1] - 112], [LH[0] - 16, LH[1] - 90], [LH[0] - 14, LH[1] - 88]];+const lighthouse: Piece = { id: "lighthouse", at: [100, 12], from: [0, 150], pivot: LH, edge: "#b9ad94", depth: 5, border: 5, cut: [lhCut],+ face: (c) => { gouache(c, lhTower, "#f3efe6", 41, { dir: Math.PI / 2, len: 20, w: 7, vary: 0.05 }); [[0.18, 0.36], [0.56, 0.74]].forEach(([a, b], i) => { const band: P[] = [[LH[0] - 18 + 6 * a, LH[1] - 86 * a], [LH[0] + 18 - 6 * a, LH[1] - 86 * a], [LH[0] + 18 - 6 * b, LH[1] - 86 * b], [LH[0] - 18 + 6 * b, LH[1] - 86 * b]]; gouache(c, band, "#cf3b2e", 42 + i, { len: 14, w: 6, vary: 0.1 }); }); shadeSide(c, lhTower, "#8f8a80", 44, [1, 0], 10, Math.PI / 2);+ c.fillStyle = "#2c2c30"; c.fillRect(LH[0] - 16, LH[1] - 92, 32, 5); gouache(c, [[LH[0] - 10, LH[1] - 110], [LH[0] + 10, LH[1] - 110], [LH[0] + 10, LH[1] - 92], [LH[0] - 10, LH[1] - 92]], "#f7d35c", 45, { len: 8, w: 4 }); c.strokeStyle = "#2c2c30"; c.lineWidth = 2; for (const x of [-10, -3, 4, 10]) { c.beginPath(); c.moveTo(LH[0] + x, LH[1] - 110); c.lineTo(LH[0] + x, LH[1] - 92); c.stroke(); }+ gouache(c, [[LH[0] - 13, LH[1] - 110], [LH[0] + 13, LH[1] - 110], [LH[0] + 3, LH[1] - 124], [LH[0] - 3, LH[1] - 124]], "#cf3b2e", 46, { len: 10, w: 5 }); c.fillStyle = "#2c2c30"; c.fillRect(LH[0] - 5, LH[1] - 22, 10, 22); c.fillStyle = "#6b8fb0"; c.fillRect(LH[0] - 3, LH[1] - 60, 6, 9); } };++const sea = (id: string, y: number, amp: number, per: number, color: string, seed: number, at: [number, number], fromX: number, depth: number, decorate?: (c: Ctx, s: P[]) => void): Piece => { const s = scissor(scallop(OPEN.x0 - 14, OPEN.x1 + 14, y, amp, per, seed * 0.7, OPEN.y1 + 4, seed), seed, 0.5); return { id, at, from: [fromX, 0], pivot: [540, y + 60], edge: mix(color, "#0b1a2a", 0.45), depth, cut: [s], face: (c) => { c.fillStyle = color; path(c, s); c.fill(); fibres(c, s, color, seed + 1, 0.7, 0.18); decorate?.(c, s); } }; };+const seaBack = sea("seaBack", 580, 5, 44, "#2c5d8a", 51, [110, 16], 900, 6);++// the quay and its houses+const quay: Piece = { id: "quay", at: [125, 14], from: [520, 0], pivot: [750, 640], edge: "#6d6150", depth: 9, cut: [[[590, 588], [900, 588], [900, 720], [590, 720]]],+ face: (c) => { const s = quay.cut[0]; c.fillStyle = "#b5a791"; path(c, s); c.fill(); stonePrint(c, s, "#b5a791", 61); c.fillStyle = "#8a7d69"; c.fillRect(590, 588, 310, 9); fibres(c, s, "#b5a791", 62, 0.6, 0.15); } };+type House = { x: number; w: number; h: number; wall: string; roof: string; kind: "gable" | "step" | "hip"; win: number; chim?: number };+const HOUSES: House[] = [+ { x: 626, w: 64, h: 118, wall: "#e9a19c", roof: "#b9412f", kind: "gable", win: 2, chim: 0.7 }, { x: 686, w: 58, h: 152, wall: "#e8b54a", roof: "#56606b", kind: "gable", win: 3 },+ { x: 746, w: 66, h: 108, wall: "#9ec4d6", roof: "#c0643c", kind: "hip", win: 2, chim: 0.25 }, { x: 806, w: 58, h: 140, wall: "#f0ebdf", roof: "#56606b", kind: "step", win: 3 },+ { x: 862, w: 54, h: 100, wall: "#a9c08d", roof: "#b9412f", kind: "gable", win: 2 },+];+const houseParts = (hs: House) => {+ const y0 = 590, wy = y0 - hs.h, x0 = hs.x - hs.w / 2, x1 = hs.x + hs.w / 2, rh = hs.kind === "hip" ? 26 : 38;+ const wall: P[] = [[x0, y0], [x1, y0], [x1, wy], [x0, wy]];+ const roof: P[] = hs.kind === "step" ? [[x0, wy], [x0, wy - 10], [x0 + 9, wy - 10], [x0 + 9, wy - 20], [x0 + 18, wy - 20], [x0 + 18, wy - 30], [hs.x - 5, wy - 30], [hs.x - 5, wy - 40], [hs.x + 5, wy - 40], [hs.x + 5, wy - 30], [x1 - 18, wy - 30], [x1 - 18, wy - 20], [x1 - 9, wy - 20], [x1 - 9, wy - 10], [x1, wy - 10], [x1, wy]] : hs.kind === "hip" ? [[x0 - 4, wy + 2], [x1 + 4, wy + 2], [x1 - 12, wy - rh], [x0 + 12, wy - rh]] : [[x0 - 5, wy + 2], [x1 + 5, wy + 2], [hs.x, wy - rh]];+ const chim: P[] | null = hs.chim !== undefined ? (() => { const cx = x0 + hs.w * hs.chim, top = wy - rh * 0.8 - 14; return [[cx - 5, wy - 6], [cx + 5, wy - 6], [cx + 5, top], [cx - 5, top]] as P[]; })() : null;+ return { wall, roof, chim, y0, wy, x0, x1 };+};+const house = (hs: House, i: number): Piece => {+ const pt = houseParts(hs), sil: P[] = [...pt.wall.slice(0, 2), ...pt.roof.slice().reverse().filter((_, k, a) => k < a.length), ...[]];+ const cut: P[][] = [[[pt.x0, pt.y0], [pt.x1, pt.y0], [pt.x1, pt.wy]], pt.roof, ...(pt.chim ? [pt.chim] : [])]; void sil;+ const body: P[] = [[pt.x0, pt.y0], [pt.x1, pt.y0], [pt.x1, pt.wy], [pt.x0, pt.wy]];+ return { id: `house${i}`, at: [140 + i * 10, 14], from: [0, 170], pivot: [hs.x, 590], edge: "#bdb29a", depth: 5, border: 5, cut: [body, pt.roof, ...(pt.chim ? [pt.chim] : [])],+ face: (c) => {+ if (pt.chim) gouache(c, pt.chim, "#a8553a", 70 + i, { dir: Math.PI / 2, len: 10, w: 5 });+ gouache(c, body, hs.wall, 71 + i, { dir: Math.PI / 2, len: 30, w: 9, vary: 0.1 });+ shadeSide(c, body, mix(hs.wall, "#2b2a40", 0.35), 72 + i, [1, 0], 11, Math.PI / 2);+ gouache(c, pt.roof, hs.roof, 73 + i, { dir: 0.2, len: 20, w: 7, vary: 0.14 });+ c.save(); path(c, body); c.clip(); c.globalAlpha = 0.35; c.fillStyle = "#2b2a40"; c.fillRect(pt.x0, pt.wy, hs.w, 7); c.restore(); c.globalAlpha = 1; // the eave's shadow on the wall+ // windows: painted panes with white frames, a door at the foot+ const r = rng(80 + i), cols = 2, rows = hs.win, ww = hs.w * 0.24, wh = 17, gx = hs.w / (cols + 1), gy = (hs.h - 48) / rows;+ for (let rr = 0; rr < rows; rr++) for (let cc = 0; cc < cols; cc++) { const x = pt.x0 + gx * (cc + 1) - ww / 2, y = pt.wy + 12 + gy * rr + (gy - wh) / 2; c.fillStyle = WHITE; c.fillRect(x - 2, y - 2, ww + 4, wh + 4); c.fillStyle = r() < 0.2 ? "#f3d27a" : "#35506b"; c.fillRect(x, y, ww, wh); c.fillStyle = WHITE; c.fillRect(x + ww / 2 - 0.8, y, 1.6, wh); c.fillRect(x, y + wh / 2 - 0.8, ww, 1.6); }+ const dx = i % 2 ? pt.x0 + hs.w * 0.62 : pt.x0 + hs.w * 0.3; c.fillStyle = WHITE; c.fillRect(dx - 9, pt.y0 - 32, 18, 32); gouache(c, [[dx - 7, pt.y0], [dx + 7, pt.y0], [dx + 7, pt.y0 - 30], [dx - 7, pt.y0 - 30]], ["#2f5f8a", "#7a3b2e", "#3d6b4f", "#b8412f", "#2f5f8a"][i], 90 + i, { dir: Math.PI / 2, len: 10, w: 4 });+ } };+};+const houses = HOUSES.map(house);+const seaMid = sea("seaMid", 700, 10, 74, "#3d7db0", 55, [205, 16], -900, 8, (c, s) => wavePrint(c, s, "#cfe6f2", 22, 2));++// the newspaper boat: hull and sail folded from one sheet; fold facets catch the light differently+const BT: P = [470, 700];+const boatHullL: P[] = [[BT[0] - 86, BT[1] - 2], [BT[0], BT[1] - 2], [BT[0], BT[1] + 40], [BT[0] - 56, BT[1] + 40]];+const boatHullR: P[] = [[BT[0], BT[1] - 2], [BT[0] + 86, BT[1] - 2], [BT[0] + 56, BT[1] + 40], [BT[0], BT[1] + 40]];+const sailL: P[] = [[BT[0] - 50, BT[1] - 2], [BT[0], BT[1] - 94], [BT[0], BT[1] - 2]], sailR: P[] = [[BT[0], BT[1] - 94], [BT[0] + 50, BT[1] - 2], [BT[0], BT[1] - 2]];+const boat: Piece = { id: "boat", at: [225, 22], from: [-420, 6], pivot: [BT[0], BT[1] + 30], edge: "#a39a86", depth: 7, cut: [[...boatHullL.slice(0, 1), [BT[0] - 50, BT[1] - 2], [BT[0], BT[1] - 94], [BT[0] + 50, BT[1] - 2], boatHullR[1], boatHullR[2], boatHullL[3]]],+ face: (c) => { const r = rng(9); [[sailL, "#efe9d8"], [sailR, "#cfc7b2"], [boatHullL, "#e6dfcb"], [boatHullR, "#c4bba5"]].forEach(([s, col], i) => { c.fillStyle = col as string; path(c, s as P[]); c.fill(); newsPrint(c, s as P[], 100 + i); c.globalAlpha = 1; }); c.strokeStyle = "rgba(90,80,60,0.45)"; c.lineWidth = 1; [[[BT[0], BT[1] - 94], [BT[0], BT[1] + 40]], [[BT[0] - 86, BT[1] - 2], [BT[0] + 86, BT[1] - 2]]].forEach(([a, b]) => { c.beginPath(); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); c.stroke(); }); c.fillStyle = "rgba(255,255,255,0.35)"; c.beginPath(); c.moveTo(BT[0] - 48, BT[1] - 6); c.lineTo(BT[0] - 3, BT[1] - 88); c.lineTo(BT[0] - 3, BT[1] - 70); c.closePath(); c.fill(); void r; } };+const seaFront = sea("seaFront", 776, 15, 118, "#4ba2a3", 57, [250, 16], 900, 9, (c, s) => { const r = rng(58); c.save(); path(c, s); c.clip(); c.lineCap = "round"; const top = s.slice(0, -2); for (let i = 0; i < top.length; i++) { const [x, y] = top[i]; if (r() > 0.42) continue; const k = 1 + Math.floor(r() * 3); for (let j = 0; j < k; j++) { const ox = (r() - 0.5) * 14, oy = 3 + r() * 9, l = 4 + r() * 10; c.strokeStyle = WHITE; c.globalAlpha = 0.55 + r() * 0.35; c.lineWidth = 3 + r() * 4; c.beginPath(); c.moveTo(x + ox, y + oy); c.lineTo(x + ox + l, y + oy + (r() - 0.5) * 3); c.stroke(); } } c.restore(); c.globalAlpha = 1; });++// the gull on a mooring post, front right+const POST: P = [790, 742];+const post: Piece = { id: "post", at: [270, 12], from: [0, 200], pivot: [POST[0], 860], edge: "#5a4028", depth: 6, border: 4, cut: [[[POST[0] - 11, POST[1]], [POST[0] + 11, POST[1] - 2], [POST[0] + 12, 862], [POST[0] - 12, 862]]],+ face: (c) => { const s = post.cut[0]; gouache(c, s, "#8b6440", 111, { dir: Math.PI / 2, len: 40, w: 6, vary: 0.15 }); shadeSide(c, s, "#4b3320", 112, [1, 0], 7, Math.PI / 2); c.fillStyle = "#d9c08a"; c.fillRect(POST[0] - 12, POST[1] + 34, 24, 5); c.fillRect(POST[0] - 12, POST[1] + 42, 24, 4); } };+// herring gull, left profile: bill, forehead, crown, nape, mantle, folded wing with black+// primaries, tail, belly, breast, throat; legs from the belly to the post top+const GS = 1.05, G = ([x, y]: P): P => [POST[0] + x * GS, POST[1] + y * GS];+const gullBody = smooth(([[-30, -54], [-26, -66], [-17, -74], [-6, -73], [2, -64], [12, -55], [30, -46], [50, -38], [36, -30], [16, -21], [-4, -22], [-18, -30], [-26, -42]] as P[]).map(G), true, 5);+const gullWing = smooth(([[-6, -57], [14, -54], [34, -46], [56, -37], [44, -35], [26, -33], [6, -37], [-6, -46]] as P[]).map(G), true, 4);+const gullTips: P[] = ([[36, -45], [56, -37], [44, -35], [34, -36]] as P[]).map(G);+const gullBill: P[] = ([[-27, -63], [-48, -57], [-44, -54], [-28, -55]] as P[]).map(G);+const gull: Piece = { id: "gull", at: [280, 12], from: [30, -220], pivot: POST, edge: "#bdb7aa", depth: 5, border: 5, cut: [gullBody, gullBill, ([[-3, -24], [3, -24], [4, 0], [-4, 0]] as P[]).map(G)],+ face: (c) => {+ c.strokeStyle = "#e28a6f"; c.lineWidth = 2.6; c.lineCap = "round"; [[-2, 5], [4, 9]].forEach(([a, b]) => { const p = G([a, -24]), q = G([b * 0.3, 0]); c.beginPath(); c.moveTo(p[0], p[1]); c.lineTo(q[0], q[1]); c.stroke(); c.beginPath(); c.moveTo(q[0] - 4, q[1]); c.lineTo(q[0] + 4, q[1]); c.stroke(); });+ gouache(c, gullBody, "#f6f5f0", 121, { dir: 0.3, len: 14, w: 5, vary: 0.04 }); shadeSide(c, gullBody, "#c9cdd2", 122, [0, 1], 10, 0.25);+ gouache(c, gullWing, "#9aa3ad", 123, { dir: 0.35, len: 14, w: 5, vary: 0.1 }); gouache(c, gullTips, "#25262a", 124, { dir: 0.4, len: 8, w: 4, vary: 0.05 });+ c.fillStyle = WHITE; [[46, -38], [40, -40]].forEach(([x, y]) => { const q = G([x, y]); c.beginPath(); c.arc(q[0], q[1], 1.6, 0, 6.28); c.fill(); });+ gouache(c, gullBill, "#f0c23a", 125, { len: 6, w: 3 }); const sp = G([-40, -55.5]); c.fillStyle = "#d8412f"; c.beginPath(); c.arc(sp[0], sp[1], 2, 0, 6.28); c.fill();+ const e = G([-18, -66]); c.fillStyle = "#f3d25a"; c.beginPath(); c.arc(e[0], e[1], 2.6, 0, 6.28); c.fill(); c.fillStyle = "#16161a"; c.beginPath(); c.arc(e[0], e[1], 1.3, 0, 6.28); c.fill();+ } };++const beach: Piece = { id: "beach", at: [295, 14], from: [-380, 0], pivot: [320, 840], edge: "#9c8154", depth: 7, cut: [tear(smooth([[170, 870], [170, 806], [236, 790], [316, 798], [392, 822], [460, 856], [470, 870]], false, 5), 1.8, 131)],+ face: (c) => { const s = beach.cut[0]; c.fillStyle = "#e1c996"; path(c, s); c.fill(); fibres(c, s, "#e1c996", 132, 0.7, 0.2); print(c, s, (b) => { const r = rng(133); for (let i = 0; i < 260; i++) { c.fillStyle = r() < 0.5 ? "#b99a62" : "#f4e6c4"; c.globalAlpha = 0.7; c.fillRect(b.x0 + r() * (b.x1 - b.x0), b.y0 + r() * (b.y1 - b.y0), 1.6, 1.6); } }); [[246, 814, 13, 8, "#9aa0a3"], [284, 822, 9, 6, "#c7b8a4"], [330, 826, 11, 7, "#8d8278"]].forEach(([x, y, rx, ry, col], i) => { const peb: P[] = Array.from({ length: 16 }, (_, k) => { const a = (k / 16) * 6.28; return [(x as number) + Math.cos(a) * (rx as number), (y as number) + Math.sin(a) * (ry as number)] as P; }); gouache(c, peb, col as string, 134 + i, { len: 8, w: 4 }); shadeSide(c, peb, "#5b5650", 137 + i, [1, 1], 5, 0.3); }); } };+const floor: Piece = { id: "floor", at: [5, 20], from: [0, -120], pivot: [540, 900], edge: "#6b4424", depth: 4, cut: [[[OPEN.x0 - 20, 832], [OPEN.x1 + 20, 832], [OPEN.x1 + 20, 870], [OPEN.x0 - 20, 870]]], face: (c) => { const s = floor.cut[0]; c.fillStyle = "#b07a45"; path(c, s); c.fill(); woodPrint(c, s, "#6d4524", 141); } };++// curtains and valance: red paper painted in folds, a gold cord+const curtainShape = (sg: number): P[] => { const x0 = sg < 0 ? OPEN.x0 - 6 : OPEN.x1 + 6, k = sg < 0 ? 1 : -1; return smooth([[x0, OPEN.y0 - 6], [x0 + k * 104, OPEN.y0 - 6], [x0 + k * 84, 380], [x0 + k * 46, 560], [x0 + k * 22, 610], [x0 + k * 40, 700], [x0 + k * 62, OPEN.y1 + 4], [x0, OPEN.y1 + 4]], false, 6); };+const curtain = (sg: number): Piece => { const s = curtainShape(sg); return { id: sg < 0 ? "curtainL" : "curtainR", at: [sg < 0 ? 315 : 320, 18], from: [sg * 220, 0], pivot: [sg < 0 ? OPEN.x0 : OPEN.x1, 400], edge: "#6b1a18", depth: 10, cut: [s],+ face: (c) => { gouache(c, s, "#b8302c", sg < 0 ? 151 : 152, { dir: Math.PI / 2, len: 70, w: 10, vary: 0.18, dens: 1.4 }); c.save(); path(c, s); c.clip(); const r = rng(153 + sg); for (let i = 0; i < 5; i++) { const x = (sg < 0 ? OPEN.x0 : OPEN.x1) + sg * -1 * (12 + i * 18); c.strokeStyle = i % 2 ? "#7c1c1a" : "#d9574a"; c.globalAlpha = 0.45; c.lineWidth = 6 + r() * 4; c.beginPath(); c.moveTo(x, OPEN.y0); c.quadraticCurveTo(x + sg * (18 + i * 6), 500, (sg < 0 ? OPEN.x0 : OPEN.x1) + sg * -1 * (30 + i * 4), 610); c.lineTo((sg < 0 ? OPEN.x0 : OPEN.x1) + sg * -1 * (36 + i * 8), OPEN.y1); c.stroke(); } c.restore(); c.globalAlpha = 1; const tie: P = [(sg < 0 ? OPEN.x0 : OPEN.x1) - sg * 36, 604]; c.strokeStyle = "#e1b54a"; c.lineWidth = 6; c.lineCap = "round"; c.beginPath(); c.moveTo(tie[0] - 26, tie[1] - 8); c.quadraticCurveTo(tie[0], tie[1] + 10, tie[0] + 28, tie[1] - 6); c.stroke(); c.fillStyle = "#e1b54a"; c.beginPath(); c.arc(tie[0] + sg * 6, tie[1] + 14, 6, 0, 6.28); c.fill(); } }; };+const valShape = (): P[] => { const pts: P[] = [[OPEN.x0 - 10, OPEN.y0 - 30], [OPEN.x1 + 10, OPEN.y0 - 30]]; const n = 9, w = (OPEN.x1 - OPEN.x0 + 20) / n; for (let i = n; i >= 1; i--) { const x1 = OPEN.x0 - 10 + i * w; for (let k = 0; k <= 8; k++) { const a = (k / 8) * Math.PI; pts.push([x1 - w / 2 + Math.cos(a) * w / 2, OPEN.y0 + 44 + Math.sin(a) * 18]); } } return pts; };+const valance: Piece = { id: "valance", at: [335, 16], from: [0, -200], pivot: [540, OPEN.y0], edge: "#6b1a18", depth: 10, cut: [valShape()],+ face: (c) => { const s = valance.cut[0]; gouache(c, s, "#b8302c", 161, { dir: 0, len: 60, w: 10, vary: 0.16, dens: 1.2 }); c.save(); path(c, s); c.clip(); c.strokeStyle = "#e1b54a"; c.lineWidth = 5; c.beginPath(); path(c, s.map(([x, y]) => [x, y - 5] as P), true); c.stroke(); c.restore(); c.fillStyle = "#e1b54a"; const n = 9, w = (OPEN.x1 - OPEN.x0 + 20) / n; for (let i = 0; i < n - 1; i++) { const x = OPEN.x0 - 10 + (i + 1) * w; c.beginPath(); c.arc(x, OPEN.y0 + 48, 6, 0, 6.28); c.fill(); } } };++// the proscenium: patterned card, gold trim, a painted shell crest; it throws its own shadow into the stage+const PRO_OUT: P[] = smooth([[70, 950], [70, 120], [360, 120], [440, 92], [540, 40], [640, 92], [720, 120], [1010, 120], [1010, 950]], false, 5);+const PRO_IN: P[] = [[OPEN.x0, OPEN.y1], [OPEN.x0, OPEN.y0 + 30], ...smooth([[OPEN.x0, OPEN.y0 + 30], [540, OPEN.y0 - 6], [OPEN.x1, OPEN.y0 + 30]], false, 10).slice(1, -1), [OPEN.x1, OPEN.y0 + 30], [OPEN.x1, OPEN.y1]];+const proscenium: Piece = { hole: true, id: "pros", at: [5, 20], from: [0, -160], pivot: [540, 1000], edge: "#173b3e", depth: 5, cut: [PRO_OUT, PRO_IN],+ face: (c) => {+ // its shadow falls onto the stage behind, along the inner top and left: from the sun, upper left+ c.save(); path(c, PRO_IN); c.clip(); c.fillStyle = "rgba(20,14,8,0.28)"; c.beginPath(); c.rect(OPEN.x0 - 40, OPEN.y0 - 60, OPEN.x1 - OPEN.x0 + 80, OPEN.y1 - OPEN.y0 + 100); path(c, PRO_IN.map(([x, y]) => [x + 16, y + 22] as P)); c.fill("evenodd"); c.restore();+ const ring = () => { c.beginPath(); [PRO_OUT, PRO_IN].forEach((s) => { s.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); }); };+ c.fillStyle = "#2f6f73"; ring(); c.fill("evenodd");+ c.save(); ring(); c.clip("evenodd"); diamondPrint(c, PRO_OUT, "#e6c56a", 26); c.restore();+ c.save(); ring(); c.clip("evenodd"); fibres(c, PRO_OUT, "#2f6f73", 171, 0.5, 0.15); c.restore();+ // gold trim round the opening: a strip of metallic paper with painted beads+ c.strokeStyle = "#d9ae4a"; c.lineWidth = 14; c.lineJoin = "round"; path(c, PRO_IN.map(([x, y]) => [x + (x < 540 ? -7 : 7), y + (y > 800 ? 7 : -7)] as P), false); c.stroke();+ c.strokeStyle = "#f2d78a"; c.lineWidth = 3; path(c, PRO_IN.map(([x, y]) => [x + (x < 540 ? -10 : 10), y + (y > 800 ? 10 : -10)] as P), false); c.stroke();+ const r = rng(172); c.fillStyle = "#9c6f22"; for (let y = OPEN.y0 + 40; y < OPEN.y1; y += 22) [OPEN.x0 - 7, OPEN.x1 + 7].forEach((x) => { c.beginPath(); c.arc(x + (r() - 0.5), y, 2.4, 0, 6.28); c.fill(); });+ // the stage-front apron below the opening+ const apron: P[] = [[OPEN.x0 - 30, OPEN.y1 + 18], [OPEN.x1 + 30, OPEN.y1 + 18], [OPEN.x1 + 30, 932], [OPEN.x0 - 30, 932]]; c.fillStyle = "#b8302c"; path(c, apron); c.fill(); fibres(c, apron, "#b8302c", 173, 0.5, 0.2); print(c, apron, (b) => { c.fillStyle = "#f0dcb0"; c.globalAlpha = 0.5; for (let x = b.x0 + 8; x < b.x1; x += 16) c.fillRect(x, b.y0 + 12, 3, b.y1 - b.y0 - 24); }); c.fillStyle = "#e1b54a"; c.fillRect(OPEN.x0 - 30, OPEN.y1 + 18, OPEN.x1 - OPEN.x0 + 60, 6); c.fillRect(OPEN.x0 - 30, 926, OPEN.x1 - OPEN.x0 + 60, 6);+ // the crest: a painted scallop shell on a cream cartouche+ const cart: P[] = Array.from({ length: 30 }, (_, i) => { const a = (i / 30) * 6.28; return [540 + Math.cos(a) * 62, 118 + Math.sin(a) * 44] as P; }); c.fillStyle = WHITE; c.beginPath(); path(c, cart); c.lineWidth = 10; c.strokeStyle = WHITE; c.stroke(); c.fill();+ gouache(c, cart, "#f1e2c2", 174, { len: 16, w: 6, vary: 0.06 }); const shell: P[] = [[540, 146]]; for (let k = 0; k <= 16; k++) { const a = Math.PI + (k / 16) * Math.PI; shell.push([540 + Math.cos(a) * 40, 138 + Math.sin(a) * 40 * (0.85 + 0.15 * Math.abs(Math.sin(k * Math.PI / 2)))]); } gouache(c, shell, "#e58f6f", 175, { dir: -Math.PI / 2, len: 16, w: 5 }); c.strokeStyle = "#b85a44"; c.lineWidth = 2.2; for (let k = 1; k < 8; k++) { const a = Math.PI + (k / 8) * Math.PI; c.beginPath(); c.moveTo(540, 144); c.lineTo(540 + Math.cos(a) * 36, 138 + Math.sin(a) * 34); c.stroke(); }+ } };++// ---------------------------------------------------------------- the table (frame 0) and the order+const table = (ctx: Ctx, env: Env) => { const { W, H } = env; ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = "#b8905f"; ctx.fillRect(0, 0, W, H); fibres(ctx, [[0, 0], [W, 0], [W, H], [0, H]], "#b8905f", 201, 1.2, 0.3); };+const post2 = (ctx: Ctx, env: Env) => { const g = new Gfx(ctx, env, 0, PEN); g.paper("paper", 0.12); g.vignette("rgba(60,36,14,0.32)"); };+const PAINTER: Piece[] = [sky, stick, sun, cloud1, cloud2, lighthouse, headland, seaBack, quay, ...houses, seaMid, boat, seaFront, post, gull, beach, floor, curtain(-1), curtain(1), valance, proscenium];+onGrid("paperCraft", PAINTER.map((p) => p.at[0]), N);+PAINTER.forEach((p) => { if (p.at[0] + p.at[1] > N - 30) throw new Error(`paperCraft: ${p.id} lands inside the hold`); });+const steps: Step[] = [{ id: "table", start: -1, end: 0, draw: (c, e) => table(c, e) }, ...PAINTER.map((pc): Step => ({ id: pc.id, start: pc.at[0], end: pc.at[0] + pc.at[1], draw: (c, e, p, f) => drawPiece(c, e, pc, f, p) }))];++export const drawPaperCraft = staged("paperCraft", steps, post2);+export const paperCraft: Film = {+ meta: { title: "A seaside town in a toy theatre · paper collage on twos", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },+ assets: { images: {} },+ shots: [{ id: "paperCraft", start: 0, end: N, draw: (ctx, f, env) => drawPaperCraft(ctx, f, env) }],+};+export const STYLE = { id: "paperCraft", name: "Toy-theatre paper collage", family: "collage", medium: "a cardboard toy theatre: patterned and sugar papers cut and torn, gouache-painted cut-outs with a white sticker margin, every piece with a card edge and a gap to the flat behind", nearest: "fox", hero: "A seaside town on a toy-theatre stage: sea rows, harbour houses, a newspaper boat, a sun on a stick" };diff --git a/engine/src/canvas-core/pixelArt.ts b/engine/src/canvas-core/pixelArt.tsnew file mode 100644index 0000000..e031443--- /dev/null+++ b/engine/src/canvas-core/pixelArt.ts@@ -0,0 +1,238 @@+// PIXEL ART · "the pounce". A cat mid-leap after fireflies in a moonlit garden.+//+// MEDIUM (physical): pixels are LAID, not drawn. A 120 x 120 grid of cells, each exactly one of+// sixteen palette colours declared below, blown up by a whole number with smoothing off. No+// anti-aliasing, no taper, no wobble, no paper: the machine crispness every other plate fights+// is the medium here. A half tint is a 2x2 ordered dither, never an alpha blend.+// MARKS: the single cell (pencil tool), the bucket fill, the dither cluster. EDGE: the staircase,+// kept clean: consistent run lengths along a curve (1-1-2-2-3, never 2-1-3), no doubled corners,+// no orphan cells. ORDER (how a pixel artist works, and how the film plays): flat mid-colour+// blocking with the pencil + bucket -> line cleanup of the silhouettes -> shading clusters and+// the sky's dither bands -> highlights and moon rim light -> fireflies and their glow dither LAST.+// Each pass advances in cels held for 3 frames (a 10 fps feel, 3 divides the 15-frame beat).+// PALETTE: sixteen, below. GROUND: the empty screen (colour 0).+// LIGHT: the fireflies are the light. The moon behind upper left gives only a cool rim along the+// cat's back and the hedge top, so the cat reads as a near-silhouette lit warm where it meets+// the fireflies (paw, whiskers, eyeshine).+// SUBJECT + REALISM: a domestic cat in a rising leap, side view facing right (reference: from+// knowledge of Muybridge's cat plates and the common leap: hind legs fully extended behind at+// push-off, spine stretched, forelegs reaching forward-up with the paws opening, ears pricked+// forward, tail trailing as a counterweight). Long lean body, small head (about a fifth of body+// length), ears triangular with the far ear showing behind.+// NOT ITS NEAREST NEIGHBOUR (koi, marker comic): no contour stroke at all, no thick-thin, no hard+// cel shadow painted as a shape: the cell is the mark, the staircase the edge, the dither the tone.+import type { Film } from "./film";+import { blit, celPlan, cleanMask, limb, PixelDraft } from "./pixelArtKit";++export const PALETTE = [+ "#07080f", // 0 void+ "#10152b", // 1 deep sky+ "#1a2446", // 2 sky+ "#283a66", // 3 low sky+ "#3f5b8c", // 4 moon haze+ "#8ea9d0", // 5 cool rim, stars+ "#e8eef5", // 6 moon+ "#0c1a17", // 7 lawn+ "#16302a", // 8 foliage dark+ "#255040", // 9 foliage mid+ "#5b8f47", // 10 leaf lit by a firefly+ "#1c1626", // 11 cat body+ "#3a2c42", // 12 cat lit fur+ "#a86424", // 13 glow outer+ "#f0b848", // 14 glow+ "#fff4bf", // 15 firefly core+];+const G = 120;+type Pt = [number, number];++// ---------------------------------------------------------------- the cat, in grid coordinates+// Authored in a body frame: u runs hip -> shoulder along the spine, v is perpendicular, + toward+// the belly. The spine is pitched 16 degrees up: a rising leap, the head lifted a further 12.+const HIP: Pt = [38, 64], TH = (16 * Math.PI) / 180, du: Pt = [Math.cos(TH), -Math.sin(TH)], dv: Pt = [Math.sin(TH), Math.cos(TH)];+const US = 0.8; // the spine's length, tuned by eye against the head+const B = (u: number, v: number): Pt => [HIP[0] + u * US * du[0] + v * dv[0], HIP[1] + u * US * du[1] + v * dv[1]];+const bp = (pts: Pt[]): Pt[] => pts.map(([u, v]) => B(u, v));+const CAT = {+ farFore: limb([[67, 57], [76, 61], [84, 49], [86.4, 45]], 2.2, 1.5),+ farPaw: <Pt[]>[[84, 45.6], [85.4, 42.4], [87.6, 41.8], [89, 43.6], [88, 46.4], [85.6, 47]],+ farHind: bp(limb([[0, 0.5], [-5, 9], [-12, 13], [-19, 16.5]], 3.8, 1.1)),+ tail: bp(limb([[-2, -3], [-7, -5], [-11, -9], [-13, -14], [-12, -18.5], [-9.4, -21.2]], 1.9, 1.3)),+ torso: bp([[-3, -3.6], [2, -5.4], [10, -5.1], [18, -4.7], [26, -5.1], [33, -6], [38, -6.6], [42, -7.2], [45.4, -8.6], [48, -3], [46.4, 1.2], [43.6, 5.4], [39.6, 7.8], [34, 8.2], [27, 7], [20, 5.3], [14, 4.5], [8, 4.9], [3, 5.7], [-1, 4.7], [-3.6, 1]]),+ nearFore: limb([[69, 57], [80.5, 59], [89, 42], [90.6, 38.4]], 2.6, 1.6),+ nearPaw: <Pt[]>[[88.2, 39], [89, 35.2], [90.6, 33.6], [92.8, 34], [94, 36.4], [93, 39.4], [90.6, 40.6]],+ throat: [[66, 50], [72, 47.5], [77, 50.5], [79, 55], [74, 57.5], [67, 57]] as Pt[],+ nearHind: bp(limb([[1.5, 1.5], [-4, 8.2], [-12, 10.8], [-20, 12.8]], 4.7, 1.2)),+};+// The head is laid by hand, cell by cell, the way a pixel artist does a face: a formula cannot+// place an ear tip or an eye. Profile facing right, chin lifted toward the fireflies, both ears+// pricked forward (far ear behind, near ear with its thin inner skin), eye, nose, mouth line.+// '#' fur 'w' inner ear (lit through) 'E' eye 'e' eye shine 'n' nose 'd' mouth / jaw shadow+const HEAD = [+ "...........#........",+ "....#.....##........",+ "...##....#w#........",+ "...#w#..##w#........",+ "..##w#.###w#........",+ "..#ww####ww##.......",+ "...############.....",+ "..###############...",+ ".#################..",+ ".#######Ee#########.",+ ".##################.",+ "..##################",+ "..#################n",+ "...###############d.",+ "...##############d..",+ "..##############d...",+ ".##############.....",+ "##############......",+];+const HA: Pt = [65, 34]; // sprite anchor (top-left cell)+const headCells = (() => { const m = new Map<number, string>(); HEAD.forEach((r, j) => [...r].forEach((ch, i) => { if (ch !== ".") m.set((HA[1] + j) * 120 + HA[0] + i, ch); })); return m; })();+const TARGET: Pt = [99, 27]; // the firefly the paws are closing on+const FIREFLIES: { x: number; y: number; big: boolean }[] = [ // a drift: the cluster the cat is after, then strays with bare sky between+ { x: TARGET[0], y: TARGET[1], big: true }, { x: 104, y: 22, big: false }, { x: 101, y: 41, big: false },+ { x: 84, y: 16, big: false }, { x: 12, y: 60, big: false }, { x: 30, y: 97, big: false }, { x: 108, y: 90, big: false },+];++const author = (): PixelDraft => {+ const d = new PixelDraft(G, G, 0);+ const fillPoly = (pts: Pt[], c: number, kind: "fill" | "pencil" = "fill") => { d.begin(kind); PixelDraft.cover(pts, G, G).forEach((i) => d.px(i % G, (i / G) | 0, c)); };+ const mask = (polys: Pt[][]) => { const m = new Uint8Array(G * G); polys.forEach((p) => PixelDraft.cover(p, G, G).forEach((i) => (m[i] = 1))); return m; };+ const at = (m: Uint8Array, x: number, y: number) => (x < 0 || y < 0 || x >= G || y >= G ? 0 : m[y * G + x]);+ const HORIZON = 96, mx = 22, my = 21, mR = 10;++ // ================= PASS 0: blocking in flat mid colours (pencil the edge, bucket the mass)+ d.setPass(0);+ d.begin("fill"); d.rect(0, 0, G, HORIZON, 2); // sky, one bucket+ d.begin("pencil"); d.line(0, HORIZON, G - 1, HORIZON, 7); d.begin("fill"); d.rect(0, HORIZON + 1, G, G - HORIZON - 1, 7); // horizon, lawn+ const hedgeTop: Pt[] = [[0, 86], [5, 84], [11, 85], [16, 82], [23, 83], [29, 85], [35, 84], [41, 86], [47, 85], [53, 87], [60, 85], [66, 82], [73, 83], [80, 85], [87, 84], [93, 81], [100, 82], [107, 84], [113, 82], [120, 83]];+ d.begin("pencil"); for (let i = 0; i + 1 < hedgeTop.length; i++) d.line(...hedgeTop[i], Math.min(G - 1, hedgeTop[i + 1][0]), hedgeTop[i + 1][1], 8);+ fillPoly([...hedgeTop, [120, HORIZON], [0, HORIZON]], 8);+ d.begin("pencil"); for (let a = 0; a < 64; a++) d.px(mx + Math.cos((a / 64) * Math.PI * 2) * mR, my + Math.sin((a / 64) * Math.PI * 2) * mR, 6);+ d.begin("fill"); for (let y = -mR; y <= mR; y++) for (let x = -mR; x <= mR; x++) if (x * x + y * y <= mR * mR + mR * 0.8) d.px(mx + x, my + y, 6);+ // the cat, blocked coarse (2x2 cells) in bands, the way a first silhouette goes down+ const exact = cleanMask(mask(Object.values(CAT)), G, G), under = d.buf.slice();+ headCells.forEach((_, i) => (exact[i] = 1));+ const coarse = new Uint8Array(G * G);+ for (let y = 0; y < G; y += 2) for (let x = 0; x < G; x += 2) { const n = at(exact, x, y) + at(exact, x + 1, y) + at(exact, x, y + 1) + at(exact, x + 1, y + 1); if (n >= 2) coarse[y * G + x] = coarse[y * G + x + 1] = coarse[(y + 1) * G + x] = coarse[(y + 1) * G + x + 1] = 1; }+ for (let y = 0; y < G; y += 4) { d.begin("fill"); for (let yy = y; yy < y + 4; yy++) for (let x = 0; x < G; x++) if (coarse[yy * G + x]) d.px(x, yy, 11); }+ // foreground grasses: tall blades at both corners, single-cell pencil lines on clean slopes+ const blades: [Pt, Pt][] = [[[3, 119], [5, 99]], [[6, 119], [10, 102]], [[9, 119], [9, 105]], [[12, 119], [17, 108]], [[1, 119], [0, 104]],+ [[108, 119], [104, 101]], [[111, 119], [111, 98]], [[114, 119], [118, 103]], [[117, 119], [119, 108]], [[105, 119], [99, 108]]];+ blades.forEach(([a, b]) => { d.begin("pencil"); d.line(...a, ...b, 8); d.line(a[0] + 1, a[1], (a[0] + b[0]) / 2 + 1, (a[1] + b[1]) / 2 + 2, 8); });++ // ================= PASS 1: cleanup. The silhouette swept once round, cells taken off and put on.+ d.setPass(1);+ const cc = B(20, 0), fix: { i: number; c: number; a: number }[] = [];+ for (let i = 0; i < G * G; i++) if (coarse[i] !== exact[i]) { const x = i % G, y = (i / G) | 0; fix.push({ i, c: exact[i] ? 11 : under[i], a: Math.atan2(y - cc[1], x - cc[0]) }); }+ fix.sort((p, q) => p.a - q.a);+ for (let k = 0; k < fix.length; k += 12) { d.begin("pencil"); fix.slice(k, k + 12).forEach((f) => d.px(f.i % G, (f.i / G) | 0, f.c)); }++ // ================= PASS 2: shading clusters+ d.setPass(2);+ // sky: deep at the zenith, lifting toward the horizon in 2x2 ordered steps (never a blend)+ d.begin("cluster"); for (let y = 0; y < 46; y++) for (let x = 0; x < G; x++) { const lv = y < 38 ? 4 : y < 40 ? 3 : y < 42 ? 2 : y < 44 ? 1 : 0; if (lv && PixelDraft.dith(x, y, lv) && d.get(x, y) === 2) d.px(x, y, 1); }+ d.begin("cluster"); for (let y = 62; y < HORIZON; y++) for (let x = 0; x < G; x++) { const lv = y > 76 ? 4 : y > 74 ? 3 : y > 72 ? 2 : y > 70 ? 1 : 0; if (lv && PixelDraft.dith(x, y, lv) && d.get(x, y) === 2) d.px(x, y, 3); }+ // moon: the maria as irregular authored clusters, and the terminator side a shade down+ const maria = ["..##..", ".####.", "#####.", ".###..", "..#..."], mar2 = [".##", "###", "##."], mar3 = ["##.", ".##"];+ const stamp = (rows: string[], x0: number, y0: number, c: number) => { d.begin("cluster"); rows.forEach((r, j) => [...r].forEach((ch, i) => { if (ch === "#" && d.get(x0 + i, y0 + j) === 6) d.px(x0 + i, y0 + j, c); })); };+ stamp(maria, 15, 15, 5); stamp(mar2, 23, 22, 5); stamp(mar3, 18, 25, 5); stamp(["#"], 26, 15, 5);+ d.begin("cluster"); for (let y = -mR; y <= mR; y++) for (let x = -mR; x <= mR; x++) { const r = Math.hypot(x, y); if (d.get(mx + x, my + y) === 6 && x + y > 6 && r > mR - 3 && PixelDraft.dith(mx + x, my + y, r > mR - 1.5 ? 4 : 2)) d.px(mx + x, my + y, 5); }+ // cat: body frame lets form follow the animal. Far limbs sink into the void colour; the belly+ // and underside of every limb turn away from both lights and go dark in a two-cell band.+ const vOf = (x: number, y: number) => (x + 0.5 - HIP[0]) * dv[0] + (y + 0.5 - HIP[1]) * dv[1];+ const cellSet = (p: Pt[]) => { const s = new Set(PixelDraft.cover(p, G, G)); return (i: number) => s.has(i) && exact[i] === 1; };+ const near = [CAT.torso, CAT.throat, CAT.nearFore, CAT.nearPaw, CAT.nearHind, CAT.tail].map(cellSet), isNear = (i: number) => headCells.has(i) || near.some((f) => f(i));+ d.begin("cluster"); headCells.forEach((ch, i) => { if (ch === "n" || ch === "d") d.px(i % G, (i / G) | 0, 0); });+ d.begin("cluster"); for (let i = 0; i < G * G; i++) if (exact[i] && !isNear(i)) d.px(i % G, (i / G) | 0, 0);+ d.begin("cluster"); for (let i = 0; i < G * G; i++) if (exact[i] && isNear(i)) { const x = i % G, y = (i / G) | 0; const o1 = !at(exact, x + 1, y + 1) || !at(exact, x, y + 1), o2 = !at(exact, x + 1, y + 2) || !at(exact, x, y + 2) || !at(exact, x + 2, y + 2); if (o1 || (o2 && PixelDraft.dith(x, y, 2))) if (vOf(x, y) > 1.5) d.px(x, y, 0); }+ // near hind thigh: its front edge against the flank, so the leg reads over the body+ d.begin("cluster"); { const th = cellSet(CAT.nearHind); for (let i = 0; i < G * G; i++) if (th(i)) { const x = i % G, y = (i / G) | 0; if (!th((y - 1) * G + x + 1) && exact[(y - 1) * G + x + 1] && d.get(x, y) === 11) d.px(x, y, 0); } }+ // hedge: every lump's moon-side shoulder in mid green, clusters that follow the lump+ for (let k = 0; k + 1 < hedgeTop.length; k++) {+ const [x0, y0] = hedgeTop[k], [x1, y1] = hedgeTop[k + 1]; if (y1 > y0) continue; d.begin("cluster"); // only lumps rising to the right face the moon's side... and the viewer+ for (let x = x0; x < x1; x++) { const top = y0 + ((y1 - y0) * (x - x0)) / (x1 - x0); for (let y = Math.ceil(top) + 1; y < top + 5; y++) if (d.get(x, y) === 8 && PixelDraft.dith(x, y, y - top < 2.5 ? 4 : 2)) d.px(x, y, 9); }+ }+ for (let k = 0; k + 1 < hedgeTop.length; k++) { const [x0, y0] = hedgeTop[k], [x1, y1] = hedgeTop[k + 1]; if (y1 <= y0) continue; d.begin("cluster"); for (let x = x0 + 1; x < x1 - 1; x++) { const top = y0 + ((y1 - y0) * (x - x0)) / (x1 - x0); for (let y = Math.ceil(top) + 2; y < top + 4; y++) if (d.get(x, y) === 8 && PixelDraft.dith(x, y, 1)) d.px(x, y, 9); } }+ // lawn: the cat's moon shadow thrown forward-right of the leap, dithered at its soft end+ d.begin("cluster"); for (let y = 100; y < 108; y++) for (let x = 36; x < 84; x++) { const u = (x - 60) / 24, v = (y - 103.5) / 3.6, r = u * u + v * v; if (r < 1 && PixelDraft.dith(x, y, r < 0.4 ? 4 : r < 0.75 ? 2 : 1)) d.px(x, y, 0); }+ // the lawn itself: mown stripes as sparse dither, darker toward the viewer+ d.begin("cluster"); for (let y = HORIZON + 1; y < G; y++) for (let x = 0; x < G; x++) if (d.get(x, y) === 7 && y < 102 && PixelDraft.dith(x, y, 1) && ((x >> 3) + (y >> 1)) % 3 === 0) d.px(x, y, 8);+ // clover tufts on the lawn, blade clusters with bare lawn between+ ([[24, 113], [44, 116], [70, 112], [88, 117], [52, 108]] as Pt[]).forEach(([tx, ty], k) => { d.begin("cluster"); for (let b = -2; b <= 2; b++) d.line(tx + b, ty, tx + b + Math.sign(b) * (1 + (k % 2)), ty - 3 + Math.abs(b), 8); });++ // ================= PASS 3: highlights and the moon's rim light+ d.setPass(3);+ d.begin("cluster"); for (let y = my - 16; y <= my + 16; y++) for (let x = mx - 16; x <= mx + 16; x++) { const r = Math.hypot(x - mx, y - my); if (r > mR + 0.9 && r < mR + 4 && PixelDraft.dith(x, y, r < mR + 2 ? 2 : 1) && d.get(x, y) !== 6) d.px(x, y, 4); }+ // cat rim: every body cell whose up-left side is open sky catches the moon (the back, the+ // crown, the ear rims, the tail's top). Swept from tail to nose like one pass of the pencil.+ const rim: { x: number; y: number; t: number }[] = [];+ for (let i = 0; i < G * G; i++) if (exact[i]) { const x = i % G, y = (i / G) | 0; if (!at(exact, x - 1, y - 1) && (!at(exact, x, y - 1) || !at(exact, x - 1, y)) && vOf(x, y) < 1) rim.push({ x, y, t: x - y }); }+ rim.sort((a, b) => a.t - b.t);+ for (let k = 0; k < rim.length; k += 6) { d.begin("pencil"); rim.slice(k, k + 6).forEach((e) => d.px(e.x, e.y, 5)); }+ // lit fur just inside the rim, broken like fur rather than drawn like a stroke+ d.begin("cluster"); rim.forEach((e, k) => { if (at(exact, e.x + 1, e.y + 1) && d.get(e.x + 1, e.y + 1) === 11 && k % 4 !== 2) d.px(e.x + 1, e.y + 1, 12); if (k % 3 === 0 && at(exact, e.x + 1, e.y + 2) && d.get(e.x + 1, e.y + 2) === 11) d.px(e.x + 1, e.y + 2, 12); });+ // hedge crown: moon catches the rising shoulders, sparingly+ d.begin("cluster"); for (let k = 0; k + 1 < hedgeTop.length; k++) { const [x0, y0] = hedgeTop[k], [x1, y1] = hedgeTop[k + 1]; if (y1 > y0 || k % 2) continue; for (let x = x0; x < Math.min(x1, x0 + 3); x++) { const top = Math.ceil(y0 + ((y1 - y0) * (x - x0)) / (x1 - x0)); d.px(x, top, 5); } }+ // grass blade tips catch the moon+ d.begin("cluster"); blades.forEach(([, b]) => { d.px(b[0], b[1], 5); });+ // stars: a few, drifted into the dark sky away from the moon, bare rests between+ ([[48, 6], [63, 13], [79, 4], [104, 9], [114, 23], [57, 33], [7, 46], [96, 58], [41, 18]] as Pt[]).forEach(([x, y]) => { d.begin("pencil"); d.px(x, y, 5); });+ // moonflowers on the hedge face, open to the sky+ ([[38, 90], [45, 93], [57, 89], [90, 91], [96, 88]] as Pt[]).forEach(([x, y]) => { d.begin("cluster"); d.px(x, y, 6); d.px(x - 1, y, 5); d.px(x + 1, y, 5); d.px(x, y - 1, 5); d.px(x, y + 1, 9); });++ // ================= PASS 4: fireflies, then the light they throw; glow dither last of all+ d.setPass(4);+ const isCat = (x: number, y: number) => at(exact, x, y) === 1;+ const warmLeaf = (x: number, y: number, r: number) => { for (let yy = -r; yy <= r; yy++) for (let xx = -r; xx <= r; xx++) { const q = Math.hypot(xx, yy); if (q > r) continue; const c = d.get(x + xx, y + yy); if (c === 8 && PixelDraft.dith(x + xx, y + yy, q < r * 0.55 ? 2 : 1)) d.px(x + xx, y + yy, 9); else if (c === 9 && q < r * 0.7) d.px(x + xx, y + yy, 10); } };+ // glow stamps, authored: core, a lit ring, then a falloff that thins cell by cell (Y glow, o outer, : sparse outer)+ const GLOW_BIG = ["....:....", "..:...:..", "...oYo...", ".:oYCYo:.", "..YCCCY..", ".:oYCYo:.", "...oYo...", "..:...:..", "....:...."];+ const GLOW_SMALL = ["..:..", ".oYo.", ":YCY:", ".oYo.", "..:.."];+ FIREFLIES.forEach(({ x, y, big }) => {+ const st = big ? GLOW_BIG : GLOW_SMALL, h = (st.length - 1) / 2;+ const put = (want: string, c: number) => st.forEach((r, j) => [...r].forEach((ch, i) => { const X = x + i - h, Y = y + j - h; if (ch === want && !isCat(X, Y) && d.get(X, Y) !== 6) d.px(X, Y, c); }));+ d.begin("pencil"); put("C", 15);+ d.begin("cluster"); put("Y", 14);+ d.begin("cluster"); put("o", 13); put(":", 13);+ d.begin("cluster"); warmLeaf(x, y, big ? 9 : 6);+ });+ // warm light where the cat faces the cluster: paws, forearms, the muzzle; then the inner ear+ // (thin skin, lit through) and the eye's shine: the fireflies are the only warm thing in the night+ d.begin("cluster");+ for (let i = 0; i < G * G; i++) if (exact[i]) { const x = i % G, y = (i / G) | 0, q = Math.hypot(x - TARGET[0], y - TARGET[1]); if (q < 18 && (!isCat(x + 1, y) || !isCat(x + 1, y - 1) || !isCat(x, y - 1))) d.px(x, y, q < 10 ? 14 : 13); }+ d.begin("cluster"); headCells.forEach((ch, i) => { if (ch === "w") d.px(i % G, (i / G) | 0, 13); });+ d.begin("pencil"); headCells.forEach((ch, i) => { if (ch === "E" || ch === "e") d.px(i % G, (i / G) | 0, ch === "E" ? 14 : 15); });+ d.begin("pencil"); d.line(HA[0] + 17, HA[1] + 11, HA[0] + 21, HA[1] + 9, 5); d.begin("pencil"); d.line(HA[0] + 16, HA[1] + 13, HA[0] + 20, HA[1] + 14, 4); // whiskers, silver in the moon+ d.end();+ return d;+};++const N = 450, HOLD = 30, CEL = 3;+const cached = (env: { cache: Map<string, unknown> }) => {+ let v = env.cache.get("pixelArt/draft") as { d: PixelDraft; plan: number[] } | undefined;+ if (!v) {+ const d = author(), raw = celPlan(d, [36, 22, 30, 22, 20], 4), cels = Math.floor((N - HOLD - 1) / CEL);+ // fit the plan to the cels the film has: stretch or squeeze by resampling, keeping the end exact+ const plan = Array.from({ length: cels }, (_, c) => raw[Math.min(raw.length - 1, Math.round((c * (raw.length - 1)) / (cels - 1)))]);+ v = { d, plan }; env.cache.set("pixelArt/draft", v);+ }+ return v;+};++export const pixelArt: Film = {+ meta: { title: "Pixel art · the pounce", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{+ id: "pounce", start: 0, end: N, draw: (ctx, f, env) => {+ const { d, plan } = cached(env);+ let n: number;+ if (f === 0) n = 0; else if (f >= N - HOLD) n = d.ops.length; else n = plan[Math.min(plan.length - 1, Math.floor((f - 1) / CEL))];+ const buf = new Uint8Array(G * G); // frame 0 ground = colour 0+ for (let k = 0; k < n; k++) { const o = d.ops[k]; buf[o >> 4] = o & 15; }+ blit(ctx, buf, G, G, PALETTE, Math.round(env.W * env.scale), Math.round(env.H * env.scale), PALETTE[0]);+ },+ }],+};++export const STYLE = { id: "pixelArt", name: "Pixel art", family: "digital", medium: "a 120x120 grid of cells, each one of 16 declared palette colours, laid one cell at a time and blown up by a whole number, no smoothing", nearest: "koi", hero: "a cat mid-pounce after fireflies in a moonlit garden" };diff --git a/engine/src/canvas-core/pixelArtKit.ts b/engine/src/canvas-core/pixelArtKit.tsnew file mode 100644index 0000000..256f9e8--- /dev/null+++ b/engine/src/canvas-core/pixelArtKit.ts@@ -0,0 +1,105 @@+// PIXEL ART KIT. A palette-indexed grid that RECORDS every pixel an artist lays, in order, so the+// finished picture and the process that made it come from the same list. Plain TypeScript, pure.+//+// A draft is a list of ops (cell index, palette index), grouped into strokes; a stroke belongs to a+// pass (blocking, cleanup, shading, highlights, fireflies...). `replay(n)` gives the grid after the+// first n ops. `blit` paints a grid onto the canvas as whole cells: integer cell size, integer+// offsets, fillRect only, so every device pixel is exactly one palette colour (no AA, no smoothing).+import type { Ctx } from "./core";++export type Stroke = { pass: number; kind: "fill" | "pencil" | "cluster"; a: number; b: number }; // ops [a, b)++export class PixelDraft {+ readonly buf: Uint8Array; ops: number[] = []; strokes: Stroke[] = [];+ private pass = 0; private open: Stroke | null = null;+ constructor(readonly G: number, readonly H: number, ground: number) { this.buf = new Uint8Array(G * H).fill(ground); }+ // ---- recording+ setPass(p: number) { this.end(); this.pass = p; }+ begin(kind: Stroke["kind"]) { this.end(); this.open = { pass: this.pass, kind, a: this.ops.length, b: this.ops.length }; }+ end() { if (this.open) { this.open.b = this.ops.length; if (this.open.b > this.open.a) this.strokes.push(this.open); this.open = null; } }+ get(x: number, y: number) { return x < 0 || y < 0 || x >= this.G || y >= this.H ? -1 : this.buf[y * this.G + x]; }+ px(x: number, y: number, c: number) {+ x = Math.round(x); y = Math.round(y);+ if (x < 0 || y < 0 || x >= this.G || y >= this.H) return;+ const i = y * this.G + x; if (this.buf[i] === c) return; // an invisible op is not a mark+ this.buf[i] = c; this.ops.push(i * 16 + c);+ }+ // ---- marks, all palette-only+ rect(x0: number, y0: number, w: number, h: number, c: number) { for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) this.px(x, y, c); }+ // Bresenham: one pixel per step on the major axis, never a double+ line(x0: number, y0: number, x1: number, y1: number, c: number) {+ x0 = Math.round(x0); y0 = Math.round(y0); x1 = Math.round(x1); y1 = Math.round(y1);+ const dx = Math.abs(x1 - x0), dy = -Math.abs(y1 - y0), sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1; let e = dx + dy;+ for (;;) { this.px(x0, y0, c); if (x0 === x1 && y0 === y1) break; const e2 = 2 * e; if (e2 >= dy) { e += dy; x0 += sx; } if (e2 <= dx) { e += dx; y0 += sy; } }+ }+ // cells whose centre is inside the polygon (even-odd), row by row+ static cover(pts: [number, number][], G: number, H: number): number[] {+ const out: number[] = [];+ for (let y = 0; y < H; y++) {+ const yc = y + 0.5, xs: number[] = [];+ for (let i = 0; i < pts.length; i++) { const [x0, y0] = pts[i], [x1, y1] = pts[(i + 1) % pts.length]; if ((y0 <= yc) !== (y1 <= yc)) xs.push(x0 + ((yc - y0) / (y1 - y0)) * (x1 - x0)); }+ xs.sort((a, b) => a - b);+ for (let k = 0; k + 1 < xs.length; k += 2) for (let x = Math.max(0, Math.ceil(xs[k] - 0.5)); x <= Math.min(G - 1, Math.floor(xs[k + 1] - 0.5)); x++) out.push(y * G + x);+ }+ return out;+ }+ // 2x2 ordered dither: level 0..4 of colour b over the cell's colour a (2 = the checker half tint)+ static bayer = [[0, 2], [3, 1]];+ static dith(x: number, y: number, level: number) { return PixelDraft.bayer[y & 1][x & 1] < level; }+}++// thick polyline -> closed polygon (a limb, a stem, a tail), radius tapering r0 -> r1+export const limb = (pts: [number, number][], r0: number, r1: number): [number, number][] => {+ const L: [number, number][] = [], R: [number, number][] = [];+ pts.forEach((p, i) => {+ const a = pts[Math.max(0, i - 1)], b = pts[Math.min(pts.length - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, r = r0 + ((r1 - r0) * i) / (pts.length - 1);+ L.push([p[0] - (dy / l) * r, p[1] + (dx / l) * r]); R.push([p[0] + (dy / l) * r, p[1] - (dx / l) * r]);+ });+ return [...L, ...R.reverse()];+};++// Cell mask cleanup, the pixel artist's pass over a blocked silhouette: remove one-cell nubs+// (a cell with at most one 4-neighbour inside) and fill one-cell notches (an empty cell with three+// or more 4-neighbours inside), repeated to rest. Returns the cleaned mask.+export const cleanMask = (m: Uint8Array, G: number, H: number): Uint8Array => {+ const o = m.slice(); const at = (x: number, y: number) => (x < 0 || y < 0 || x >= G || y >= H ? 0 : o[y * G + x]);+ for (let pass = 0, changed = true; changed && pass < 6; pass++) {+ changed = false;+ for (let y = 0; y < H; y++) for (let x = 0; x < G; x++) {+ const n = at(x - 1, y) + at(x + 1, y) + at(x, y - 1) + at(x, y + 1), i = y * G + x;+ if (o[i] && n <= 1) { o[i] = 0; changed = true; } else if (!o[i] && n >= 3) { o[i] = 1; changed = true; }+ }+ }+ return o;+};++// Timeline: every stroke gets a number of cels by its kind and size, passes get their budget, a+// beat of rest sits between passes. Returns ops-applied per cel (monotone, ends at ops.length).+export const celPlan = (d: PixelDraft, budgets: number[], rest: number): number[] => {+ const plan: number[] = [0];+ budgets.forEach((budget, p) => {+ const ss = d.strokes.filter((s) => s.pass === p); if (!ss.length) return;+ const w = ss.map((s) => (s.kind === "fill" ? 1 : s.kind === "cluster" ? 1 + Math.sqrt(s.b - s.a) * 0.35 : 1 + Math.sqrt(s.b - s.a) * 0.8));+ const sw = w.reduce((a, b) => a + b, 0);+ ss.forEach((s, k) => {+ const cels = Math.max(1, Math.round((budget * w[k]) / sw));+ for (let c = 1; c <= cels; c++) plan.push(s.a + Math.round(((s.b - s.a) * c) / cels));+ });+ for (let r = 0; r < rest; r++) plan.push(plan[plan.length - 1]);+ });+ return plan;+};++// Paint an indexed grid as whole cells, one fillRect per horizontal run. cell = integer device px.+export const blit = (ctx: Ctx, buf: Uint8Array, G: number, H: number, palette: string[], devW: number, devH: number, letterbox: string) => {+ const cell = Math.floor(Math.min(devW / G, devH / H)), ox = Math.floor((devW - cell * G) / 2), oy = Math.floor((devH - cell * H) / 2);+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; ctx.imageSmoothingEnabled = false;+ ctx.fillStyle = letterbox; ctx.fillRect(0, 0, devW, devH);+ for (let y = 0; y < H; y++) {+ let x = 0;+ while (x < G) {+ const c = buf[y * G + x]; let e = x + 1; while (e < G && buf[y * G + e] === c) e++;+ ctx.fillStyle = palette[c]; ctx.fillRect(ox + x * cell, oy + y * cell, (e - x) * cell, cell); x = e;+ }+ }+};diff --git a/engine/src/canvas-core/pocketWatch.ts b/engine/src/canvas-core/pocketWatch.tsindex 467c68d..cb21175 100644--- a/engine/src/canvas-core/pocketWatch.ts+++ b/engine/src/canvas-core/pocketWatch.ts@@ -21,10 +21,29 @@ const W = ([x, y]: P): P => { const yy = y * SQ, c = Math.cos(ROT), s = Math.sinconst polar = (r: number, a: number): P => [Math.sin(a) * r, -Math.cos(a) * r]; // a = 0 at twelve, clockwiseconst ring = (r: number, n = 90, c: P = [0, 0]): P[] => Array.from({ length: n }, (_, i) => W([c[0] + polar(r, (i / n) * Math.PI * 2)[0], c[1] + polar(r, (i / n) * Math.PI * 2)[1]]));+// ---------------------------------------------------------------- the drawing clock (optional)+// pocketWatchDraw hangs a clock on the Gfx: every visible mark asks it how far along it is, by+// KIND (the pass it belongs to). No clock = the hero, byte for byte (every progress is 1).+export type Kind = "build" | "line" | "detail" | "h1" | "h2" | "h3" | "fill";+export type Clock = (kind: Kind, len: number, part?: string) => number; // part: which object the mark belongs to, so a pass can be scheduled object by object+const clockOf = (g: Gfx) => (g as Gfx & { clock?: Clock }).clock;+const plen = (pts: P[]) => { 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]); return L; };+const prog = (g: Gfx, kind: Kind, pts: P[], part?: string) => { const c = clockOf(g); return c ? c(kind, plen(pts), part) : 1; };+// a solid ink area (a hand, a boss) is scribbled in: at progress < 1 only a band swept across the+// shape's long side shows. PAPER knock-outs are never gated: they only restore the sheet.+const inked = (g: Gfx, pts: P[], kind: Kind, draw: () => void) => {+ const p = prog(g, kind, pts); if (p <= 0) return; if (p >= 1) return draw();+ const b = bounds(pts), c = g.cur, wide = b.x1 - b.x0 >= b.y1 - b.y0; c.save(); c.beginPath();+ if (wide) c.rect(b.x0 - 2, b.y0 - 2, (b.x1 - b.x0 + 4) * p, b.y1 - b.y0 + 4); else c.rect(b.x0 - 2, b.y0 - 2, b.x1 - b.x0 + 4, (b.y1 - b.y0 + 4) * p);+ c.clip(); draw(); c.restore();+};+const fillK = (g: Gfx, pts: P[], color: string, alpha = 1, kind: Kind = "fill") => (color === PAPER ? fillShape(g, pts, color, alpha) : inked(g, pts, kind, () => fillShape(g, pts, color, alpha)));+// ---------------------------------------------------------------- the biro-const stroke = (g: Gfx, pts: P[], o: { w?: number; op?: number; seed: number; wob?: number; blob?: boolean; retrace?: boolean }) => {- const { w = 1.1, op = 0.86, seed, wob = 0.35, blob = false, retrace = false } = o;- g.pen(pts, { w, color: BIRO, seed, wobble: wob, boil: 0, taper: 1, opacity: op, retrace });+const stroke = (g: Gfx, pts: P[], o: { w?: number; op?: number; seed: number; wob?: number; blob?: boolean; retrace?: boolean; kind?: Kind; part?: string }) => {+ const { w = 1.1, op = 0.86, seed, wob = 0.35, retrace = false, kind = "line" } = o, progress = prog(g, kind, pts, o.part), blob = (o.blob ?? false) && progress >= 1;+ if (progress <= 0) return;+ g.pen(pts, { w, color: BIRO, seed, wobble: wob, boil: 0, taper: 1, opacity: op, retrace, progress });if (blob) { // a firm stroke leaves a bead of ink where the ball stops, a smaller one where it startedconst e = pts[pts.length - 1], s0 = pts[0], c = g.cur, r = rng(seed * 7);g.touch(e[0] - 4, e[1] - 4, e[0] + 4, e[1] + 4); g.touch(s0[0] - 3, s0[1] - 3, s0[0] + 3, s0[1] + 3);@@ -33,13 +52,16 @@ const stroke = (g: Gfx, pts: P[], o: { w?: number; op?: number; seed: number; wo}};// hatching: tone lives in where strokes are. Runs are cut into hand-length strokes with a flick.-const hatch = (g: Gfx, region: P[], angle: number, gap: number, keep: (x: number, y: number) => boolean, seed: number, op = 0.62) => {- const b = bounds(region), r = rng(seed);- hatchRuns(b, angle, gap, (x, y) => inside(region, x, y) && keep(x, y), 2.5, seed).forEach((run, k) => {+const hatch = (g: Gfx, region: P[], angle: number, gap: number, keep: (x: number, y: number) => boolean, seed: number, op = 0.62, kind: Kind = "h1", part?: string, hidden?: (x: number, y: number) => boolean) => {+ const b = bounds(region), r = rng(seed), runs = () => hatchRuns(b, angle, gap, (x, y) => inside(region, x, y) && keep(x, y), 2.5, seed);+ // with a clock the same runs are needed every frame: they are a pure function of this call site+ const cache = clockOf(g) ? g.env.cache : null, key = `pw:hatch:${seed}:${angle}:${gap}:${Math.round(b.x0)}:${Math.round(b.y0)}`;+ const rs = cache ? ((cache.get(key) as P[][] | undefined) ?? (cache.set(key, runs()), cache.get(key) as P[][])) : runs();+ rs.forEach((run, k) => {let i = 0;while (i < run.length - 1) {const n = Math.min(run.length - 1 - i, 8 + Math.floor(r() * 22)), seg = run.slice(i, i + n + 1);- if (seg.length > 1) { const a = seg[0], z = seg[seg.length - 1], m = lerpP(a, z, 0.5), bow = (r() - 0.5) * 1.6; stroke(g, [a, [m[0] + bow, m[1] - bow], z], { w: 0.82, op: op * (0.75 + r() * 0.35), seed: seed * 1000 + k * 37 + i, wob: 0.25 }); }+ if (seg.length > 1) { const a = seg[0], z = seg[seg.length - 1], m = lerpP(a, z, 0.5), bow = (r() - 0.5) * 1.6; stroke(g, [a, [m[0] + bow, m[1] - bow], z], { w: 0.82, op: op * (0.75 + r() * 0.35), seed: seed * 1000 + k * 37 + i, wob: 0.25, kind, part: cache && hidden && hidden(m[0], m[1]) ? "hidden" : part }); }i += n + (r() < 0.25 ? 1 : 0);}});@@ -74,10 +96,10 @@ const numeral = (g: Gfx, txt: string, a: number, h: number, seed: number) => {const gl = glyphs[ch], cx = x + gl.w / 2;gl.strokes.forEach(([p, q, thick]) => {const A = at(cx + p[0], p[1]), B = at(cx + q[0], q[1]);- stroke(g, [A, lerpP(A, B, 0.5), B], { w: 1.05, op: 0.92, seed: seed + k++, wob: 0.15 });- if (thick) { const o = 0.035; stroke(g, [at(cx + p[0] + o, p[1]), at(cx + (p[0] + q[0]) / 2 + o, 0), at(cx + q[0] + o, q[1])], { w: 1.05, op: 0.9, seed: seed + k++, wob: 0.15 }); }+ stroke(g, [A, lerpP(A, B, 0.5), B], { w: 1.05, op: 0.92, seed: seed + k++, wob: 0.15, kind: "detail" });+ if (thick) { const o = 0.035; stroke(g, [at(cx + p[0] + o, p[1]), at(cx + (p[0] + q[0]) / 2 + o, 0), at(cx + q[0] + o, q[1])], { w: 1.05, op: 0.9, seed: seed + k++, wob: 0.15, kind: "detail" }); }});- [-0.5, 0.5].forEach((v) => { const sx = gl.w / 2 + 0.07; stroke(g, [at(cx - sx, v), at(cx + sx, v)], { w: 0.9, op: 0.85, seed: seed + k++, wob: 0.1 }); });+ [-0.5, 0.5].forEach((v) => { const sx = gl.w / 2 + 0.07; stroke(g, [at(cx - sx, v), at(cx + sx, v)], { w: 0.9, op: 0.85, seed: seed + k++, wob: 0.1, kind: "detail" }); });x += gl.w + gap;}};@@ -87,15 +109,15 @@ const breguet = (g: Gfx, a: number, len: number, moonR: number, moonAt: number,const d: P = [Math.sin(a), -Math.cos(a)], n: P = [Math.cos(a), Math.sin(a)], p = (t: number, s: number): P => { const q = W([d[0] * t + n[0] * s, d[1] * t + n[1] * s]); return [q[0] + off[0], q[1] + off[1]]; };const tail = -len * 0.18, m = len * moonAt;const blade = [p(tail, width * 1.1), p(0, width), p(m - moonR * 1.1, width * 0.55), p(m - moonR * 1.1, -width * 0.55), p(0, -width), p(tail, -width * 1.1)];- fillShape(g, blade, BIRO, 0.9 * alpha);+ fillK(g, blade, BIRO, 0.9 * alpha);const moon: P[] = [], hole: P[] = [];for (let i = 0; i < 28; i++) { const t = (i / 28) * Math.PI * 2; moon.push(p(m + Math.cos(t) * moonR, Math.sin(t) * moonR)); hole.push(p(m + moonR * 0.12 + Math.cos(t) * moonR * 0.56, Math.sin(t) * moonR * 0.56)); }const c = g.cur, bb = bounds(moon); g.touch(bb.x0 - 2, bb.y0 - 2, bb.x1 + 2, bb.y1 + 2);- c.fillStyle = BIRO; c.globalAlpha = 0.9 * alpha; c.beginPath(); moon.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); hole.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill("evenodd"); c.globalAlpha = 1;- fillShape(g, [p(m + moonR * 0.9, width * 0.5), p(len, 0.4), p(m + moonR * 0.9, -width * 0.5)], BIRO, 0.9 * alpha);+ inked(g, moon, "fill", () => { c.fillStyle = BIRO; c.globalAlpha = 0.9 * alpha; c.beginPath(); moon.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); hole.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill("evenodd"); c.globalAlpha = 1; });+ fillK(g, [p(m + moonR * 0.9, width * 0.5), p(len, 0.4), p(m + moonR * 0.9, -width * 0.5)], BIRO, 0.9 * alpha);if (alpha < 1) return;- stroke(g, [p(tail, 0), p(len * 0.5, 0), p(len, 0)], { w: 0.9, op: 0.5, seed, wob: 0.1 });- stroke(g, [p(m + moonR * 0.95, 0), p(len, 0)], { w: 0.8, op: 0.9, seed: seed + 1, wob: 0.05, blob: true });+ stroke(g, [p(tail, 0), p(len * 0.5, 0), p(len, 0)], { w: 0.9, op: 0.5, seed, wob: 0.1, kind: "fill" });+ stroke(g, [p(m + moonR * 0.95, 0), p(len, 0)], { w: 0.8, op: 0.9, seed: seed + 1, wob: 0.05, blob: true, kind: "fill" });};// ---------------------------------------------------------------- the chain@@ -111,34 +133,36 @@ const chain = (g: Gfx, start: P, seed: number) => {const o: P[] = [], iN: P[] = [];for (let i = 0; i < 24; i++) { const a = (i / 24) * Math.PI * 2; o.push([p[0] + t[0] * Math.cos(a) * L + n[0] * Math.sin(a) * Wd, p[1] + t[1] * Math.cos(a) * L + n[1] * Math.sin(a) * Wd]); iN.push([p[0] + t[0] * Math.cos(a) * L * 0.6 + n[0] * Math.sin(a) * Wd * 0.34, p[1] + t[1] * Math.cos(a) * L * 0.6 + n[1] * Math.sin(a) * Wd * 0.34]); }// its shadow on the table, down and right- hatch(g, o.map(([x, y]) => [x + 5, y + 7] as P), -0.95, 2.6, () => true, seed + k * 3, 0.5);+ hatch(g, o.map(([x, y]) => [x + 5, y + 7] as P), -0.95, 2.6, () => true, seed + k * 3, 0.5, "h1", "chain");fillShape(g, o, PAPER);if (face) fillShape(g, iN, PAPER);- hatch(g, o, 0.6, 2.8, (x, y) => ((x - p[0]) * LIGHT[0] + (y - p[1]) * LIGHT[1]) < -1 && !(face && inside(iN, x, y)), seed + k * 3 + 1, 0.72);- stroke(g, [...o.slice(0, 13)], { w: 1.05, op: 0.9, seed: seed + k * 5 + 2, wob: 0.2, retrace: true });- stroke(g, [...o.slice(12), o[0]], { w: 1.05, op: 0.9, seed: seed + k * 5 + 3, wob: 0.2, retrace: true, blob: r() < 0.5 });- if (face) stroke(g, [...iN, iN[0]], { w: 0.95, op: 0.85, seed: seed + k * 5 + 4, wob: 0.15 });+ hatch(g, o, 0.6, 2.8, (x, y) => ((x - p[0]) * LIGHT[0] + (y - p[1]) * LIGHT[1]) < -1 && !(face && inside(iN, x, y)), seed + k * 3 + 1, 0.72, "h2", "chain");+ stroke(g, [...o.slice(0, 13)], { w: 1.05, op: 0.9, seed: seed + k * 5 + 2, wob: 0.2, retrace: true, part: "chain" });+ stroke(g, [...o.slice(12), o[0]], { w: 1.05, op: 0.9, seed: seed + k * 5 + 3, wob: 0.2, retrace: true, blob: r() < 0.5, part: "chain" });+ if (face) stroke(g, [...iN, iN[0]], { w: 0.95, op: 0.85, seed: seed + k * 5 + 4, wob: 0.15, part: "chain" });d += face ? 27 : 23; k++;}};-export const drawPocketWatch = (ctx: Ctx, _frame: number, env: Env) => {+export const drawPocketWatch = (ctx: Ctx, _frame: number, env: Env, clock?: Clock) => {const g = new Gfx(ctx, env, 0, BIRO_M);+ if (clock) (g as Gfx & { clock?: Clock }).clock = clock;ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);ctx.fillStyle = PAPER; ctx.fillRect(0, 0, 1080, 1080);const caseF = ring(R_CASE, 120), caseB = caseF.map(([x, y]) => [x + TH[0], y + TH[1]] as P);g.group("plain", () => {// construction first, the way the sketch was started: centre lines and a looser ellipse- stroke(g, [W([-340, 0]), W([0, 0]), W([340, 0])], { w: 0.8, op: 0.16, seed: 1, wob: 0.6 });- stroke(g, [W([0, -400]), W([0, 0]), W([0, 340])], { w: 0.8, op: 0.16, seed: 2, wob: 0.6 });- stroke(g, ring(R_CASE + 14, 40).map(([x, y]) => [x - 4, y + 3] as P), { w: 0.8, op: 0.13, seed: 3, wob: 1.2 });+ stroke(g, [W([-340, 0]), W([0, 0]), W([340, 0])], { kind: "build", w: 0.8, op: 0.16, seed: 1, wob: 0.6 });+ stroke(g, [W([0, -400]), W([0, 0]), W([0, 340])], { kind: "build", w: 0.8, op: 0.16, seed: 2, wob: 0.6 });+ stroke(g, ring(R_CASE + 14, 40).map(([x, y]) => [x - 4, y + 3] as P), { kind: "build", w: 0.8, op: 0.13, seed: 3, wob: 1.2 });// the watch's shadow on the table: cross-hatched, heaviest where the case touches downconst shadow = ring(R_CASE, 90).map(([x, y]) => [x + 46, y + 40] as P);const sd = (x: number, y: number) => Math.hypot(x - C[0] - 46, y - C[1] - 40) / R_CASE;- hatch(g, shadow, -0.95, 4.6, () => true, 101, 0.55);- hatch(g, shadow, 0.55, 4.8, (x, y) => sd(x, y) < 0.97 && (x - C[0]) + (y - C[1]) > 60, 102, 0.5);+ const under = (x: number, y: number) => inside(caseF, x, y) || inside(caseB, x, y); /* shadow strokes the case will cover: the clock spends no time on them */+ hatch(g, shadow, -0.95, 4.6, () => true, 101, 0.55, "h1", undefined, under);+ hatch(g, shadow, 0.55, 4.8, (x, y) => sd(x, y) < 0.97 && (x - C[0]) + (y - C[1]) > 60, 102, 0.5, "h2", undefined, under);chain(g, W([10, -R_CASE - 108]), 300);// the case side, a sliver of cylinder: short strokes that follow its curve, dense in the shade@@ -151,7 +175,7 @@ export const drawPocketWatch = (ctx: Ctx, _frame: number, env: Env) => {if (facing < 4) continue; // only the side turned toward us shows its bandconst shade = 1 - bezelTone(f[0], f[1]);if (i % (shade > 0.55 ? 1 : shade > 0.3 ? 2 : 4)) continue;- stroke(g, [lerpP(f, b2, 0.05), lerpP(f, b2, 1.02)], { w: 0.85, op: 0.55 + shade * 0.35, seed: 400 + i, wob: 0.1 });+ stroke(g, [lerpP(f, b2, 0.05), lerpP(f, b2, 1.02)], { w: 0.85, op: 0.55 + shade * 0.35, seed: 400 + i, wob: 0.1, kind: "h1" });}{ const n = caseB.length, vis = (i: number) => { const f = caseF[i], dx = f[0] - C[0], dy = f[1] - C[1], l = Math.hypot(dx, dy); return (dx / l) * TH[0] + (dy / l) * TH[1] > 2; };let s0 = 0; while (vis(s0) || !vis((s0 + 1) % n)) s0 = (s0 + 1) % n; // the first index where the visible arc begins@@ -162,52 +186,52 @@ export const drawPocketWatch = (ctx: Ctx, _frame: number, env: Env) => {const bez: P[] = [...caseF, caseF[0], ...ring(R_BEZ, 120).reverse(), ring(R_BEZ, 120)[119]];const bezIn = ring(R_BEZ, 60);const inBez = (x: number, y: number) => { const q = Math.hypot((x - C[0]), (y - C[1])); return q > R_BEZ * 0.93 && q < R_CASE * 1.0; };- hatch(g, caseF, -0.9, 3.6, (x, y) => inBez(x, y) && !inside(bezIn, x, y) && bezelTone(x, y) < 0.72, 111, 0.66);- hatch(g, caseF, 0.62, 3.8, (x, y) => inBez(x, y) && !inside(bezIn, x, y) && bezelTone(x, y) < 0.42, 112, 0.62);- hatch(g, caseF, 0.05, 4.0, (x, y) => inBez(x, y) && !inside(bezIn, x, y) && bezelTone(x, y) < 0.24, 113, 0.6);+ hatch(g, caseF, -0.9, 3.6, (x, y) => inBez(x, y) && !inside(bezIn, x, y) && bezelTone(x, y) < 0.72, 111, 0.66, "h1");+ hatch(g, caseF, 0.62, 3.8, (x, y) => inBez(x, y) && !inside(bezIn, x, y) && bezelTone(x, y) < 0.42, 112, 0.62, "h2");+ hatch(g, caseF, 0.05, 4.0, (x, y) => inBez(x, y) && !inside(bezIn, x, y) && bezelTone(x, y) < 0.24, 113, 0.6, "h3");void bez;- for (let i = 0; i < 180; i++) { const a = (i / 180) * Math.PI * 2, p0 = W(polar(R_CASE, a)), p1 = W(polar(R_CASE - 11, a)); stroke(g, [p0, p1], { w: 0.75, op: 0.35 + 0.5 * (1 - bezelTone(p0[0], p0[1])), seed: 500 + i, wob: 0.05 }); }+ for (let i = 0; i < 180; i++) { const a = (i / 180) * Math.PI * 2, p0 = W(polar(R_CASE, a)), p1 = W(polar(R_CASE - 11, a)); stroke(g, [p0, p1], { w: 0.75, op: 0.35 + 0.5 * (1 - bezelTone(p0[0], p0[1])), seed: 500 + i, wob: 0.05, kind: "detail" }); }stroke(g, caseF.slice(0, 61), { w: 1.25, op: 0.9, seed: 510, wob: 0.3, retrace: true, blob: true });stroke(g, [...caseF.slice(60), caseF[0], caseF[1]], { w: 1.25, op: 0.9, seed: 511, wob: 0.3, retrace: true, blob: true });- stroke(g, [...ring(R_CASE - 12, 100), ring(R_CASE - 12, 100)[0]], { w: 0.8, op: 0.55, seed: 512, wob: 0.2 });+ stroke(g, [...ring(R_CASE - 12, 100), ring(R_CASE - 12, 100)[0]], { w: 0.8, op: 0.55, seed: 512, wob: 0.2, kind: "detail" });stroke(g, [...ring(R_BEZ, 110), ring(R_BEZ, 110)[0], ring(R_BEZ, 110)[1]], { w: 1.15, op: 0.9, seed: 513, wob: 0.2, retrace: true });// the dial: paper, a soft bezel shadow and a crystal reflection in single hatching, one glare left bareconst dial = ring(R_BEZ, 110);- hatch(g, dial, -0.9, 4.4, (x, y) => dialTone(x, y) < 0.86, 121, 0.5);- hatch(g, dial, 0.6, 4.6, (x, y) => dialTone(x, y) < 0.62, 122, 0.5);+ hatch(g, dial, -0.9, 4.4, (x, y) => dialTone(x, y) < 0.86, 121, 0.5, "h1");+ hatch(g, dial, 0.6, 4.6, (x, y) => dialTone(x, y) < 0.62, 122, 0.5, "h2");[R_TRACK, R_TRACK2].forEach((rr, k) => stroke(g, [...ring(rr, 110), ring(rr, 110)[0], ring(rr, 110)[1]], { w: 0.95, op: 0.88, seed: 130 + k, wob: 0.15 }));- for (let i = 0; i < 60; i++) { const a = (i / 60) * Math.PI * 2, five = i % 5 === 0; stroke(g, [W(polar(R_TRACK - 1, a)), W(polar(five ? R_TRACK2 - 6 : R_TRACK2 + 1, a))], { w: five ? 1.3 : 0.85, op: 0.9, seed: 140 + i, wob: 0.04 }); }+ for (let i = 0; i < 60; i++) { const a = (i / 60) * Math.PI * 2, five = i % 5 === 0; stroke(g, [W(polar(R_TRACK - 1, a)), W(polar(five ? R_TRACK2 - 6 : R_TRACK2 + 1, a))], { w: five ? 1.3 : 0.85, op: 0.9, seed: 140 + i, wob: 0.04, kind: "detail" }); }const labels = ["XII", "I", "II", "III", "IIII", "V", "VI", "VII", "VIII", "IX", "X", "XI"];labels.forEach((t, i) => { if (i === 6) return; numeral(g, t, (i / 12) * Math.PI * 2, 34, 1000 + i * 20); }); // six is taken by the seconds dial// sub-seconds, sunk into the dial: a shadowed step on its upper-left rimconst sub = ring(R_SUB, 70, SUB);- hatch(g, sub, 0.6, 3.4, (x, y) => { const c0 = W(SUB), dx = x - c0[0], dy = y - c0[1], l = Math.hypot(dx, dy) || 1; return l > R_SUB * 0.72 && (dx / l) * LIGHT[0] + (dy / l) * LIGHT[1] > 0.1; }, 150, 0.7);+ hatch(g, sub, 0.6, 3.4, (x, y) => { const c0 = W(SUB), dx = x - c0[0], dy = y - c0[1], l = Math.hypot(dx, dy) || 1; return l > R_SUB * 0.72 && (dx / l) * LIGHT[0] + (dy / l) * LIGHT[1] > 0.1; }, 150, 0.7, "h2");stroke(g, [...sub, sub[0], sub[1]], { w: 1.05, op: 0.9, seed: 151, wob: 0.12, retrace: true });- stroke(g, [...ring(R_SUB - 9, 60, SUB), ring(R_SUB - 9, 60, SUB)[0]], { w: 0.75, op: 0.7, seed: 152, wob: 0.1 });- for (let i = 0; i < 60; i++) { const a = (i / 60) * Math.PI * 2, c0 = SUB, p0 = polar(R_SUB - 1, a), p1 = polar(i % 5 ? R_SUB - 6 : R_SUB - 10, a); stroke(g, [W([c0[0] + p0[0], c0[1] + p0[1]]), W([c0[0] + p1[0], c0[1] + p1[1]])], { w: i % 5 ? 0.6 : 0.9, op: 0.85, seed: 160 + i, wob: 0.02 }); }+ stroke(g, [...ring(R_SUB - 9, 60, SUB), ring(R_SUB - 9, 60, SUB)[0]], { w: 0.75, op: 0.7, seed: 152, wob: 0.1, kind: "detail" });+ for (let i = 0; i < 60; i++) { const a = (i / 60) * Math.PI * 2, c0 = SUB, p0 = polar(R_SUB - 1, a), p1 = polar(i % 5 ? R_SUB - 6 : R_SUB - 10, a); stroke(g, [W([c0[0] + p0[0], c0[1] + p0[1]]), W([c0[0] + p1[0], c0[1] + p1[1]])], { w: i % 5 ? 0.6 : 0.9, op: 0.85, seed: 160 + i, wob: 0.02, kind: "detail" }); }const sa = 2.35, s0 = W(SUB), s1 = W([SUB[0] + polar(R_SUB - 8, sa)[0], SUB[1] + polar(R_SUB - 8, sa)[1]]), s2 = W([SUB[0] - polar(12, sa)[0], SUB[1] - polar(12, sa)[1]]);- stroke(g, [s2, s0, s1], { w: 1.0, op: 0.95, seed: 170, wob: 0.03, blob: true });- fillShape(g, ring(3, 12, SUB), BIRO, 0.9);+ stroke(g, [s2, s0, s1], { w: 1.0, op: 0.95, seed: 170, wob: 0.03, blob: true, kind: "fill" });+ fillK(g, ring(3, 12, SUB), BIRO, 0.9);// the hands at ten past ten, each throwing a hair of shadow onto the dialconst hourA = (10 + 8 / 60) / 12 * Math.PI * 2, minA = (8 / 60) * Math.PI * 2;breguet(g, hourA, 138, 15, 0.7, 5.2, 180, 0.16, [5, 6]); breguet(g, minA, 206, 13, 0.76, 4.2, 190, 0.16, [6, 7]);breguet(g, hourA, 138, 15, 0.7, 5.2, 180);breguet(g, minA, 206, 13, 0.76, 4.2, 190);- fillShape(g, ring(11, 16), BIRO, 0.95); fillShape(g, ring(4.5, 12), PAPER); fillShape(g, ring(2, 8), BIRO, 0.9);+ fillK(g, ring(11, 16), BIRO, 0.95); fillK(g, ring(4.5, 12), PAPER); fillK(g, ring(2, 8), BIRO, 0.9);// pendant, crown and bow at twelveconst pend = [W([-24, -R_CASE + 6]), W([-17, -R_CASE - 26]), W([17, -R_CASE - 26]), W([24, -R_CASE + 6])];fillShape(g, pend, PAPER);- hatch(g, pend, 0.6, 3, (x, y) => (x - W([0, -R_CASE - 10])[0]) > -4, 200, 0.7);+ hatch(g, pend, 0.6, 3, (x, y) => (x - W([0, -R_CASE - 10])[0]) > -4, 200, 0.7, "h1");stroke(g, [pend[0], pend[1], pend[2], pend[3]], { w: 1.1, op: 0.92, seed: 201, wob: 0.15, retrace: true });const crown: P[] = [W([-21, -R_CASE - 26]), W([-21, -R_CASE - 64]), W([21, -R_CASE - 64]), W([21, -R_CASE - 26])];fillShape(g, crown, PAPER);- for (let i = -18; i <= 18; i += 3.2) stroke(g, [W([i, -R_CASE - 28]), W([i, -R_CASE - 62])], { w: 0.8, op: i > 2 ? 0.9 : 0.55, seed: 210 + Math.round(i * 10), wob: 0.05 }); // the knurling+ for (let i = -18; i <= 18; i += 3.2) stroke(g, [W([i, -R_CASE - 28]), W([i, -R_CASE - 62])], { w: 0.8, op: i > 2 ? 0.9 : 0.55, seed: 210 + Math.round(i * 10), wob: 0.05, kind: "detail" }); // the knurlingstroke(g, [...crown, crown[0]], { w: 1.15, op: 0.92, seed: 220, wob: 0.12, retrace: true });const bowC: P = [0, -R_CASE - 78], bowO = ring(52, 70, bowC).filter((_, i) => i < 30 || i > 40), bowI = ring(41, 70, bowC).filter((_, i) => i < 30 || i > 40);- hatch(g, [...ring(52, 70, bowC), ...ring(41, 70, bowC).reverse()], -0.9, 3, (x, y) => { const c0 = W(bowC); return (x - c0[0]) + (y - c0[1]) > -6; }, 230, 0.7);+ hatch(g, [...ring(52, 70, bowC), ...ring(41, 70, bowC).reverse()], -0.9, 3, (x, y) => { const c0 = W(bowC); return (x - c0[0]) + (y - c0[1]) > -6; }, 230, 0.7, "h1");stroke(g, bowO, { w: 1.2, op: 0.92, seed: 231, wob: 0.2, retrace: true, blob: true });stroke(g, bowI, { w: 1.05, op: 0.85, seed: 232, wob: 0.2, retrace: true });});diff --git a/engine/src/canvas-core/pocketWatchDraw.ts b/engine/src/canvas-core/pocketWatchDraw.tsnew file mode 100644index 0000000..19f21b0--- /dev/null+++ b/engine/src/canvas-core/pocketWatchDraw.ts@@ -0,0 +1,77 @@+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import { drawPocketWatch, type Clock, type Kind } from "./pocketWatch";++// POCKET WATCH · drawn in biro. The ballpoint plate, watched being made.+//+// MEDIUM. One blue ballpoint on cream cartridge paper: a steel ball rolling oil-based ink, so+// the line is near-constant in weight, it cannot be lifted or thinned, and tone comes only from+// WHERE strokes are laid (single hatch, cross-hatch, a third direction in the deepest darks).+// A firm stroke leaves a bead of ink where the ball stops. Nothing is erased.+// ORDER (the way a biro sketcher works, because a pen cannot take a mark back):+// 1. construction: two faint centre lines and a loose ellipse, barely pressed;+// 2. contours: the case, back arc, bezel and track rings, chain links, crown, pendant, bow;+// 3. detail: reeding, minute track, numerals, the sub-dial ticks, the crown's knurling;+// 4. tone, first layer: one direction everywhere there is any shade (table shadow, the case+// side, the bezel's cylinder, the dial's bezel shadow, the chain);+// 5. tone, cross layer, only where it is darker; 6. the third direction in the deepest darks;+// 7. the solid blacks last: the Breguet hands scribbled in, their hair shadows, the boss.+// A beat of pause between passes: the hand sits back and looks before the next layer.+// PACE. Each pass is laid down in the plate's own draw order (it already travels round the+// watch), a mark's time is 4 + length^0.85 frames-units, so long strokes go fast per pixel and+// short fiddly ones slow; a mark never takes less than a few frames. The ball stops, THEN the+// bead appears. Solid areas grow as a band across them, never fade.+// REALISM. Everything drawn is pocketWatch.ts's authored watch (open face, reeded bezel, IIII,+// Breguet moon hands at ten past ten, sunk sub-seconds, crown, pendant, bow, curb chain; light+// from upper left), and the last frame is that plate byte for byte.++export const STYLE = { id: "pocketWatchDraw", name: "Ballpoint sketch, drawn on", family: "pen & ink", medium: "one blue ballpoint on cream cartridge paper: constant line, tone by hatch placement, ink beads where the ball stops", nearest: "pocketWatch", hero: "a pocket watch lying on a table, drawn stroke by stroke" };++const N = 450, HOLD = 30;+// THE CUE TABLE. Every frame number of the film. [kind, start, end, shortest mark in frames]+const CUES: [Kind, number, number, number][] = [+ ["build", 0, 25, 12],+ ["line", 35, 110, 6],+ ["detail", 120, 180, 4],+ ["h1", 190, 305, 3],+ ["h2", 315, 370, 3],+ ["h3", 380, 395, 3],+ ["fill", 400, 420, 5],+];+(() => { // the grid checker, at load+ const bad: string[] = []; let prev = 0;+ CUES.forEach(([k, a, b, d]) => { if (a % 5 || b % 5) bad.push(`${k} off the 5-frame grid`); if (a < prev || b <= a) bad.push(`${k} out of order`); if (b - a < d) bad.push(`${k} shorter than one mark`); prev = b; });+ if (prev > N - HOLD) bad.push("drawing runs into the hold"); if (N % 15 || N < 300 || N > 540) bad.push("duration off the beat grid");+ if (bad.length) throw new Error("pocketWatchDraw cues: " + bad.join("; "));+})();++// The schedule: one [start, duration] per mark, in the plate's paint order. Built once from a+// recording pass (a clock that answers 0 draws nothing but counts every mark it is asked about).+type Sched = { s: Float64Array; d: Float64Array };+const schedule = (env: Env, ctx: Ctx): Sched => {+ const key = "pwDraw:sched"; let S = env.cache.get(key) as Sched | undefined; if (S) return S;+ const marks: [Kind, number, string][] = []; drawPocketWatch(ctx, 0, env, (k, l, part) => (marks.push([k, l, part ?? "watch"]), 0));+ const s = new Float64Array(marks.length), d = new Float64Array(marks.length);+ CUES.forEach(([kind, a, b, dmin]) => {+ const mine = marks.map((m, i) => (m[0] === kind ? i : -1)).filter((i) => i >= 0), idx = [...mine.filter((i) => marks[i][2] !== "chain"), ...mine.filter((i) => marks[i][2] === "chain")], /* the watch first, its chain after: paint order stays the plate's, only the TIME changes */ cost = idx.map((i) => (marks[i][2] === "hidden" ? 0 : 4 + Math.pow(marks[i][1], 0.85))), /* a stroke the case will cover takes no time: nobody watches it */ total = cost.reduce((x, y) => x + y, 0) || 1, span = b - a;+ let acc = 0; idx.forEach((i, j) => { const dur = Math.min(span, Math.max(dmin, (span * cost[j]) / total)); s[i] = a + ((span - dur) * acc) / total; d[i] = dur; acc += cost[j]; });+ });+ S = { s, d }; env.cache.set(key, S); return S;+};+const at = (S: Sched, f: number): Clock => { let i = 0; return () => { const p = (f - S.s[i]) / S.d[i]; i++; return p >= 1 ? 1 : p <= 0 ? 0 : p; }; };++const draw = (ctx: Ctx, f: number, env: Env) => {+ if (f < N - HOLD) return drawPocketWatch(ctx, 0, env, at(schedule(env, ctx), f));+ // the hold: the finished plate. Drawn straight onto the frame once per scale, then its exact pixels+ // are copied (an offscreen redraw antialiases differently on some rasterisers; a pixel copy cannot)+ const key = `pwDraw:done:${env.scale}`, img = env.cache.get(key) as ImageData | undefined, w = Math.round(env.W * env.scale), h = Math.round(env.H * env.scale);+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ if (img) return ctx.putImageData(img, 0, 0);+ drawPocketWatch(ctx, 0, env); ctx.setTransform(1, 0, 0, 1, 0, 0); env.cache.set(key, ctx.getImageData(0, 0, w, h));+};++export const pocketWatchDraw: Film = {+ meta: { title: "Pocket watch · drawn in biro", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "draw", start: 0, end: N, draw }],+};diff --git a/engine/src/canvas-core/ranunculusDraw.ts b/engine/src/canvas-core/ranunculusDraw.tsnew file mode 100644index 0000000..9d7854a--- /dev/null+++ b/engine/src/canvas-core/ranunculusDraw.ts@@ -0,0 +1,154 @@+// RANUNCULUS · drawn. The pencil & watercolour plate, made the way a botanical illustrator makes it.+//+// MEDIUM: an HB pencil and pan watercolour on cold-press paper, the same hand as `ranunculus.ts`.+// ORDER, the point of this film:+// (1) pencil lay-in: a loose envelope for the bloom and its centre, the stem's gesture, the axis of+// each leaf, then the lips of the outer three rings, all light enough to live under paint;+// (2) first light washes: one pale wash per mass (bloom, heart, stem, leaves, calyx), each spreading+// from where the brush touched and stopping short of its outline;+// (3) form: every petal shaded toward the ONE light (upper left), outer ring first, working in to+// the tight centre, exactly as the hero plate paints them (same seeds, same control points);+// (4) graphite over the paint: lips, veins, stem and leaf contours, each line stopping where a petal+// painted later sits over it (a hand does not draw what it cannot see).+// The geometry is the hero's, re-authored here so `ranunculus.ts` stays byte-identical. The last+// frame is NOT the hero's pixels: the hero interleaves paint and graphite petal by petal and has no+// lay-in; this one lays all pencil before paint and all graphite after it, as the medium is worked.+import { Gfx, PENCIL, arc, displace, fractal as _f, jitter, line, oval, rng, sample, tube, type Ctx, type Env, type P } from "./core";+import type { Film } from "./film";+import { checkOps, schedule, staged, type Op } from "./brokenColourKit";++const N = 450, HOLD = N - 30;+const META = { title: "Ranunculus · drawn", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" as const };+const K = META.W / 1080; // the hero was authored on a 1080 sheet++// ---------------------------------------------------------------- the hero's geometry, verbatim+type Petal = { shape: P[]; hi: P[]; lip: P[]; veins: { pts: P[]; seed: number }[]; seed: number; tier: number; base: P; reach: number };+const petalGeo = (radius: number, angle: number, width: number, depth: number, seed: number, tier: number): Petal => {+ const r = rng(seed), cx = 531 + (r() - 0.5) * 14, cy = 391 + (r() - 0.5) * 12;+ const place = ([x, y]: P): P => [cx + Math.cos(angle) * y - Math.sin(angle) * x, cy + (Math.sin(angle) * y + Math.cos(angle) * x) * 0.87];+ const lip = arc(0, radius - depth * 0.28, width, depth * 0.45, Math.PI, 0, 9).map(([x, y], i): P => [x, y + Math.sin(i * 1.8 + seed) * depth * 0.045]);+ const shape = [...lip, [width * 0.73, radius - depth * 0.61], [width * 0.15, radius - depth], [-width * 0.63, radius - depth * 0.7]] as P[];+ const hi = [...lip.slice(1, 8), [0, radius - depth * 0.17]].map((p) => place(p as P));+ const veins = [0, 1, 2].map((j) => { const x = (j - 1) * width * 0.42; return { pts: line([x * 0.45, radius - depth * 0.69], [x, radius - depth * 0.06], (r() - 0.5) * 7).map(place), seed: seed + 10 + j }; });+ return { shape: shape.map(place), hi, lip: lip.map(place), veins, seed, tier, base: place([0, radius - depth * 0.85]), reach: depth * 1.35 + width };+};+const PETAL_COLORS = ["#f7ddd2", "#f4cbbb", "#efb8a8", "#e8a491", "#df907f", "#d88071", "#c77364"];+const petals = (() => {+ const r = rng(7321), out: Petal[] = [];+ const rings = [+ { radius: 252, count: 11, width: 99, depth: 150 }, { radius: 211, count: 13, width: 77, depth: 116 }, { radius: 171, count: 14, width: 62, depth: 94 },+ { radius: 134, count: 14, width: 49, depth: 74 }, { radius: 100, count: 12, width: 38, depth: 58 }, { radius: 70, count: 11, width: 28, depth: 42 }, { radius: 43, count: 9, width: 21, depth: 31 },+ ];+ rings.forEach((ring, tier) => {+ const offset = tier * 0.39 + 0.14;+ for (let i = 0; i < ring.count; i++) {+ const a = offset + (i * Math.PI * 2) / ring.count + (r() - 0.5) * 0.15;+ const rad = ring.radius * (0.95 + r() * 0.1), wid = ring.width * (0.88 + r() * 0.24), dep = ring.depth * (0.92 + r() * 0.16);+ out.push(petalGeo(rad, a, wid, dep, 1000 + tier * 500 + i * 25, tier));+ }+ });+ for (let i = 0; i < 5; i++) out.push(petalGeo(20 - i * 2, i * 2.4, 12 - i, 17, 6000 + i * 25, 6));+ return out;+})();+type Leaf = { edge: P[]; mid: P[]; ribs: P[][]; seed: number; origin: P };+const leafGeo = (origin: P, direction: number, size: number, seed: number): Leaf => {+ const place = ([x, y]: P): P => [origin[0] + (x * Math.cos(direction) - y * Math.sin(direction)) * size, origin[1] + (x * Math.sin(direction) + y * Math.cos(direction)) * size];+ const edge: P[] = [[0, 0], [28, -22], [35, -51], [52, -37], [78, -65], [81, -38], [116, -39], [101, -17], [147, 0], [105, 12], [113, 31], [80, 25], [73, 52], [50, 31], [30, 39], [22, 17]];+ return { edge: edge.map(place), mid: line([0, 0], [139, 0], -3).map(place), ribs: [[35, -45], [77, -57], [111, -34], [71, 45], [107, 27]].map(([x, y]) => line([x * 0.56, 0], [x, y], 3).map(place)), seed, origin };+};+const LEAVES = [leafGeo([541, 760], -2.55, 1.25, 40), leafGeo([549, 698], -0.57, 1.02, 60)];+const STEM: P[] = [[547, 548], [557, 645], [539, 756], [517, 880], [524, 991]], STALK = tube(STEM, 8, 4, true), CALYX = oval(543, 548, 48, 34, 10);+// the outline g.form actually fills, so a later petal can hide an earlier line exactly where its paint sits+const formEdge = (pts: P[], seed: number) => displace(sample(jitter(pts, 1.2, seed), true, 8), 13, 0.022, 3, 5);+const bbox = (s: P[]) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; s.forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }); return [x0, y0, x1, y1]; };+const hit = (a: number[], b: number[]) => a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];+const covers = petals.map((p) => { const e = formEdge(p.shape, p.seed); return { e, box: bbox(e) }; });+const calyxCover = (() => { const e = formEdge(CALYX, 90); return { e, box: bbox(e) }; })();++// ---------------------------------------------------------------- how marks are made+const gfx = (ctx: Ctx, env: Env) => { const g = new Gfx(ctx, env, 0, PENCIL); g.push(0, 0, K); return g; };+const done = (g: Gfx) => g.pop();+// a wet front: the brush touched at `at`, the pigment runs outward along a ragged edge+const spread = (g: Gfx, at: P, shape: P[], p: number, seed: number, fn: () => void) => {+ if (p >= 1) return fn();+ const reach = (Math.max(...shape.map(([x, y]) => Math.hypot(x - at[0], y - at[1]))) + 10) / 0.75, c = g.cur, R = reach * Math.pow(p, 0.75), pts: P[] = Array.from({ length: 28 }, (_, i) => { const a = (i / 28) * Math.PI * 2, k = 0.75 + 0.5 * _f(seed, Math.cos(a) * 40 + 100, Math.sin(a) * 40 + 100, 0.05, 0.05, 2); return [at[0] + Math.cos(a) * R * k, at[1] + Math.sin(a) * R * k]; });+ c.save(); c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.clip(); fn(); c.restore();+};+// graphite that stops under paint laid after it+const hidden = (g: Gfx, lineBox: number[], later: { e: P[]; box: number[] }[]) => {+ const c = g.cur; c.save(); c.globalCompositeOperation = "destination-out"; c.globalAlpha = 0.94; c.fillStyle = "#000";+ later.forEach(({ e, box }) => { if (!hit(box, lineBox)) return; c.beginPath(); e.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill(); });+ c.restore();+};+const LAY = "#8a7f86";+// a ring's silhouette: the crown of every lip in that ring, walked round the centre (a scalloped mass, never a disc)+const silhouette = (tier: number): P[] => petals.filter((p) => p.tier === tier).map((p) => p.lip[4]).sort((a, b) => Math.atan2(a[1] - 391, a[0] - 531) - Math.atan2(b[1] - 391, b[0] - 531));++const build = (): Op[] => {+ const ops: Op[] = [], add = (marks: ((ctx: Ctx, env: Env, p: number) => void)[], f0: number, f1: number, dur: number, pace?: (u: number) => number) => { const t = schedule(marks.length, f0, f1, dur, pace); marks.forEach((d, i) => ops.push({ ...t[i], draw: d })); };+ const pencil = (pts: P[], o: Parameters<Gfx["pen"]>[1]) => (ctx: Ctx, env: Env, p: number) => { const g = gfx(ctx, env); g.group("ink", () => g.pen(pts, { ...o, progress: p })); done(g); };+ // (1) lay-in+ const lay: ((ctx: Ctx, env: Env, p: number) => void)[] = [+ pencil(oval(531, 393, 262, 232, 16, -2.6), { closed: true, w: 0.85, color: LAY, opacity: 0.42, seed: 3, wobble: 3, boil: 0, retrace: false }),+ pencil(oval(533, 391, 62, 52, 10, -2.2), { closed: true, w: 0.75, color: LAY, opacity: 0.4, seed: 4, wobble: 2, boil: 0, retrace: false }),+ pencil(STEM, { w: 0.9, color: LAY, opacity: 0.45, seed: 5, wobble: 1.5, boil: 0, retrace: false }),+ ...LEAVES.map((l, i) => pencil(l.mid, { w: 0.75, color: LAY, opacity: 0.42, seed: 6 + i, wobble: 1, boil: 0, retrace: false })),+ ...petals.filter((p) => p.tier <= 2).map((p) => pencil(p.lip, { w: 0.7, color: LAY, opacity: 0.4, seed: p.seed + 7, wobble: 1.2, boil: 0, retrace: false })),+ ];+ add(lay, 0.5, 80, 6, (u) => Math.pow(u, 1.15));+ // (2) first light washes, one per mass, each short of its outline+ const wash = (pts: P[], color: string, alpha: number, at: P, _reach: number, seed: number) => (ctx: Ctx, env: Env, p: number) => { const g = gfx(ctx, env); g.group("paint", () => spread(g, at, pts, p, seed, () => g.wash(pts, color, { alpha, seed, dx: -2, dy: -2, shrink: 0.93 }))); done(g); };+ add([+ wash(silhouette(0), "#f6d6c6", 0.34, [420, 250], 470, 301),+ wash(silhouette(3), "#efb3a0", 0.28, [500, 350], 200, 302),+ wash(STALK, "#c6cea6", 0.4, [547, 560], 460, 303),+ ...LEAVES.map((l, i) => wash(l.edge, "#c9d2aa", 0.4, l.origin, 200, 304 + i)),+ wash(CALYX, "#c4cc9e", 0.4, [520, 530], 90, 306),+ ], 79, 160, 20);+ // (3) form toward the one light, in the hero's order and with the hero's calls+ const form = (at: P, shape: P[], seed: number, fn: (g: Gfx) => void) => (ctx: Ctx, env: Env, p: number) => { const g = gfx(ctx, env); g.group("paint", () => spread(g, at, shape, p, seed, () => fn(g))); done(g); };+ add([+ form([547, 560], STALK, 21, (g) => g.form(STALK, "#a6b48b", "#708776", { seed: 21, light: [-3, -1] })),+ ...LEAVES.map((l) => form(l.origin, l.edge, l.seed, (g) => g.form(l.edge, "#a4b28b", "#637f70", { seed: l.seed, light: [-3, -4], alpha: 0.9 }))),+ form([520, 530], CALYX, 90, (g) => g.form(CALYX, "#abb68b", "#6f8069", { seed: 90, light: [-4, -5] })),+ ...petals.map((pt) => form(pt.base, pt.shape, pt.seed, (g) => {+ g.form(pt.shape, PETAL_COLORS[pt.tier], pt.tier < 3 ? "#ce8c8a" : "#ac6667", { seed: pt.seed, light: [-3.2, -4.6], alpha: 0.94 });+ g.wash(pt.hi, "#fff2dc", { seed: pt.seed + 1, alpha: 0.28, dx: -1, dy: -1, shrink: 0.91, rim: false });+ })),+ ], 159, 336, 9, (u) => u * 0.6 + u * u * 0.4);+ // (4) graphite over the paint+ const later = (i: number) => covers.slice(i + 1);+ const graphite = (i: number) => (ctx: Ctx, env: Env, p: number) => {+ const pt = petals[i], g = gfx(ctx, env);+ g.group("ink", () => {+ g.pen(pt.lip, { seed: pt.seed + 2, w: 0.88, opacity: 0.43, color: "#726262", wobble: 0.65, boil: 0, taper: 1, retrace: true, progress: Math.min(1, p * 1.6) });+ if (p > 0.45) pt.veins.forEach((v, j) => g.pen(v.pts, { seed: v.seed, w: 0.48, opacity: 0.17, color: "#986b69", wobble: 0.35, boil: 0, retrace: false, progress: Math.min(1, Math.max(0, (p - 0.45 - j * 0.12) / 0.3)) }));+ hidden(g, bbox([...pt.lip, ...pt.veins.flatMap((v) => v.pts)]).map((v, k) => v + (k < 2 ? -6 : 6)), later(i));+ });+ done(g);+ };+ const leafLine = (l: Leaf) => (ctx: Ctx, env: Env, p: number) => {+ const g = gfx(ctx, env), s = l.seed;+ g.group("ink", () => {+ g.pen(l.edge, { seed: s + 1, closed: true, w: 0.95, opacity: 0.45, wobble: 0.65, boil: 0, color: "#5f6a5c", progress: Math.min(1, p * 1.5) });+ if (p > 0.5) { g.pen(l.mid, { seed: s + 2, w: 0.9, opacity: 0.55, boil: 0, progress: Math.min(1, (p - 0.5) * 4) }); l.ribs.forEach((rb, i) => g.pen(rb, { seed: s + 3 + i, w: 0.55, opacity: 0.35, boil: 0, retrace: false, progress: Math.min(1, Math.max(0, (p - 0.6 - i * 0.06) / 0.12)) })); }+ hidden(g, bbox(l.edge), [calyxCover, ...covers]);+ });+ done(g);+ };+ add([+ (ctx, env, p) => { const g = gfx(ctx, env); g.group("ink", () => { g.pen(STALK, { seed: 22, closed: true, w: 0.95, opacity: 0.53, wobble: 0.6, boil: 0, progress: p }); hidden(g, bbox(STALK), [calyxCover, ...covers]); }); done(g); },+ ...LEAVES.map(leafLine),+ ...petals.map((_, i) => graphite(i)),+ ], 335, HOLD, 8, (u) => u * 0.8 + u * u * 0.2);+ return checkOps(ops, HOLD);+};++const KEY = "ranunculusDraw:ops:v1";+const ops = (cache: Map<string, unknown>) => () => { let o = cache.get(KEY) as Op[] | undefined; if (!o) { o = build(); cache.set(KEY, o); } return o; };+export const drawRanunculusDraw = (ctx: Ctx, frame: number, env: Env) => staged("ranunculusDraw", ops(env.cache),+ (c, e) => { c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.fillStyle = "#fffaf3"; c.fillRect(0, 0, e.W, e.H); },+ (c, e) => { const g = new Gfx(c, e, 0, PENCIL); g.paper("paper", 0.12); g.paper("coldpress", 0.18); })(ctx, frame, env);++export const STYLE = { id: "ranunculusDraw", name: "Pencil & watercolour, drawn", family: "watercolour", medium: "HB pencil and pan watercolour on cold-press paper, laid in, washed, formed, then graphite over the paint", nearest: "ranunculus", hero: "a ranunculus in bloom" };+export const ranunculusDraw: Film = { meta: META, assets: { images: {} }, shots: [{ id: "ranunculusDraw", start: 0, end: N, draw: drawRanunculusDraw }] };diff --git a/engine/src/canvas-core/rubberHose.ts b/engine/src/canvas-core/rubberHose.tsnew file mode 100644index 0000000..7bfcc5d--- /dev/null+++ b/engine/src/canvas-core/rubberHose.ts@@ -0,0 +1,204 @@+import { Gfx, PENCIL, type Ctx, type Env, type Layer, type P } from "./core";+import type { Film } from "./film";+import { clamp, lerp, smooth } from "./gallery";+import { capsule, cb, ell, filmPrint, inkCel, INK, noodle, paintFills, place, qb, rect, schedule, wob, type Part } from "./rubberHoseKit";++// RUBBER HOSE · a coffee pot dances on the counter, 1930s studio cartoon.+//+// MEDIUM, physically: an animation drawing in non-photo-blue pencil on punched bond, traced in+// India ink with a crow-quill / brush held at ONE pressure onto a clear cel (the line is uniform,+// never thick-thin; it wobbles a little because it is a hand), painted on the BACK of the cel in+// flat opaque greys (so the ink always sits on top of the paint), photographed on black-and-white+// stock and printed: warm silver toning, grain that changes every frame, lamp flicker, dust,+// a sprocket scratch, gate weave, the rounded corners of the projector's aperture.+// MARKS: one-weight ink contours that stop where a nearer shape starts; solid black noodle limbs+// with NO elbow (one smooth arc shoulder to wrist); white four-digit gloves with three stitch+// lines and a flared cuff; pie-cut pupils (a wedge missing where the shine would be); flat grey+// fills with no modelling at all; cast shadows as translucent flat shapes, no ink.+// ORDER: blue pencil rough (line of action first, then masses, then parts) -> ink (character,+// then set) -> paint (flooded region by region, character first) -> the film pull-down: the+// drawing is threaded through the gate and comes back as a print -> motion-first: two seconds of+// the dance, on twos, that lands back on the key pose -> the hold, which IS the still.+// PALETTE: greys only, a 1930s black-and-white cartoon: ink #16130f, paper whites, five greys.+// LIGHT: one window, upper left. Shine on the pot's upper-left shoulder; the pot's and the cup's+// flat shadows thrown to the right on the tiles; contact shadows under the feet (the kicked foot's+// shadow is small and separate: it is in the air).+// SUBJECT & REFERENCE (from knowledge): a 1930s enamel stovetop coffee pot (tapered body,+// rolled rim, domed lid with a ball knob, gooseneck spout, C-handle), drawn with the conventions+// of Fleischer/Iwerks-era rubber-hose animation (Bimbo, early Mickey, "Swing You Sinners!"): the+// object IS the head and torso, a face on its body, noodle limbs from its sides, big oval shoes.+// Kitchen: 1930s tile backsplash with a dark border course, a scalloped window valance, a cup.+// NOT ITS NEIGHBOUR: the marker comic (koi) is modelled cel colour with a thick-thin contour;+// this is a one-weight line, no modelling, greys, and a film print.++const W = 1080, H = 1080;+const T = { pen: [4, 92], ink: [98, 232], fill: [238, 324], pull: [330, 345], dance: [345, 405] } as const;+const N = 435; // dance ends at 405; the last 30 frames are the still+const G = { wall: "#cbc5b8", glass: "#f1ede3", valance: "#8e887d", tile: "#e2ded3", border: "#55514b", top: "#8a857b", edge: "#4a4742", cab: "#b3ada1", panel: "#a39d91", pot: "#7f7a71", lid: "#5d5952", white: "#f6f3ea", tongue: "#8f897f", shine: "#ebe7dc", cup: "#ece8de", saucer: "#d3cec3", coffee: "#3a3631", paper: "#f5f2e8" };++// ---------------------------------------------------------------- the character, posed+type Pose = { o: P; tilt: number; sq: number; hL: P; aL: number; bL: number; hR: P; aR: number; bR: number; fL: P; sL: number; lL: number; fR: P; sR: number; lR: number };+const K0: Pose = { o: [470, 735], tilt: -0.1, sq: 1, hL: [258, 468], aL: -0.62, bL: 46, hR: [712, 628], aR: 1.3, bR: -42, fL: [410, 783], sL: 0, lL: 16, fR: [642, 736], sR: -0.38, lR: -42 };+const K1: Pose = { o: [456, 735], tilt: 0.1, sq: 0.92, hL: [236, 652], aL: -1.62, bL: -34, hR: [688, 432], aR: 0.5, bR: 40, fL: [302, 740], sL: 0.36, lL: 44, fR: [522, 783], sR: 0, lR: -14 };+const K2: Pose = { o: [470, 735], tilt: -0.06, sq: 0.94, hL: [300, 440], aL: -0.22, bL: 32, hR: [660, 438], aR: 0.3, bR: -30, fL: [412, 783], sL: 0, lL: 14, fR: [656, 712], sR: -0.52, lR: -56 };+const K3: Pose = { o: [460, 735], tilt: 0.07, sq: 0.95, hL: [228, 598], aL: -1.32, bL: -26, hR: [724, 560], aR: 1.52, bR: 26, fL: [318, 744], sL: 0.26, lL: 40, fR: [526, 783], sR: 0, lR: -12 };+const KEYS = [K0, K1, K2, K3, K0];+const ease = (t: number) => t * t * (3 - 2 * t);+// dance frame d in 0..60 (animated on twos) -> pose; d = 0 and d = 60 are exactly K0+const danced = (d: number): Pose => {+ if (d <= 0 || d >= 60) return K0;+ const q = d - (d % 2), seg = Math.min(3, Math.floor(q / 15)), t = (q - seg * 15) / 15, a = KEYS[seg], b = KEYS[seg + 1], e = ease(t), hop = Math.sin(Math.PI * t);+ const L = (x: number, y: number) => lerp(x, y, e), LP = (x: P, y: P): P => [L(x[0], y[0]), L(x[1], y[1])];+ // the body leads, the limbs follow a couple of frames behind on the same arc (overlap, never unison)+ const f = ease(clamp((t - 0.12) / 0.88)), LF = (x: P, y: P): P => [lerp(x[0], y[0], f), lerp(x[1], y[1], f)], Lf = (x: number, y: number) => lerp(x, y, f);+ return { o: [L(a.o[0], b.o[0]), L(a.o[1], b.o[1]) - 26 * hop], tilt: L(a.tilt, b.tilt), sq: L(a.sq, b.sq) + 0.08 * hop, hL: LF(a.hL, b.hL), aL: Lf(a.aL, b.aL), bL: Lf(a.bL, b.bL), hR: LF(a.hR, b.hR), aR: Lf(a.aR, b.aR), bR: Lf(a.bR, b.bR), fL: LP(a.fL, b.fL), sL: L(a.sL, b.sL), lL: L(a.lL, b.lL), fR: LP(a.fR, b.fR), sR: L(a.sR, b.sR), lR: L(a.lR, b.lR) };+};++// body-local geometry: origin at the bottom centre of the pot, y up is negative+const BODY = smooth([[-92, -262], [-113, -200], [-125, -110], [-121, -30], [-104, -2], [0, 4], [104, -2], [121, -30], [125, -110], [113, -200], [92, -262], [0, -265]], true, 6);+const RIM = smooth([[-100, -262], [-97, -277], [0, -279], [97, -277], [100, -262], [0, -257]], true, 5);+const LID = smooth([[-84, -270], [-72, -298], [-38, -318], [0, -324], [38, -318], [72, -298], [84, -270], [0, -266]], true, 5);+const KNOB = ell(0, -338, 17, 15, 0, 20);+const SPOUT_C: P[] = [[92, -104], [148, -128], [176, -188], [198, -254], [228, -296]];+const tubeOf = (c: P[], r0: number, r1: number): P[] => { const s = smooth(c, false, 6), L: P[] = [], R: P[] = []; s.forEach((p, i) => { const q = s[Math.min(s.length - 1, i + 1)], o = s[Math.max(0, i - 1)], dx = q[0] - o[0], dy = q[1] - o[1], l = Math.hypot(dx, dy) || 1, r = lerp(r0, r1, i / (s.length - 1)); L.push([p[0] - (dy / l) * r, p[1] + (dx / l) * r]); R.push([p[0] + (dy / l) * r, p[1] - (dx / l) * r]); }); return [...L, ...R.reverse()]; };+const SPOUT = tubeOf(SPOUT_C, 31, 12);+const HANDLE = tubeOf([[-94, -238], [-150, -244], [-180, -192], [-172, -128], [-114, -94]], 13, 13);+const EYE = (x: number) => ell(x, -190, 24, 34, 0, 26);+// pie-cut pupil: an oval with a wedge taken out of its upper left, where the shine would be+const PUPIL = (x: number): P[] => { const cx = x + 6, cy = -181, out: P[] = [[cx, cy]]; for (let i = 0; i <= 22; i++) { const a = -1.85 + (i / 22) * (Math.PI * 2 - 0.8); out.push([cx + Math.cos(a) * 13, cy + Math.sin(a) * 21]); } return out; };+const MOUTH: P[] = [...cb([-60, -130], [-30, -124], [26, -124], [58, -134], 10), ...cb([58, -134], [50, -76], [-44, -72], [-60, -130], 14).slice(1)];+const TONGUE: P[] = [...cb([-30, -88], [-20, -110], [28, -112], [36, -90], 10), ...cb([36, -90], [20, -80], [-16, -78], [-30, -88], 8).slice(1)];+const SHINE: P[] = smooth([[-97, -222], [-88, -238], [-82, -206], [-86, -150], [-97, -138], [-104, -176]], true, 5);+// a white glove, wrist at the origin, digits pointing up: flared cuff, palm, three fingers, thumb+const GLOVE: P[][] = [smooth([[-17, -10], [-21, -28], [-15, -45], [0, -49], [15, -45], [20, -28], [17, -10]], true, 5), capsule([-12, -38], [-17, -72], 7.6), capsule([1, -40], [2, -81], 7.9), capsule([13, -38], [19, -69], 7.3), capsule([-15, -22], [-37, -40], 7.6), smooth([[-20, 4], [0, 7], [20, 4], [17, -13], [0, -10], [-17, -13]], true, 5)];+const STITCH: P[][] = [[[-7, -17], [-6, -33]], [[1, -17], [1, -35]], [[9, -17], [9, -32]]];+// a big oval shoe, ankle at the origin, toe pointing +x+const SHOE: P[] = smooth([[-18, -10], [-4, -15], [20, -14], [42, -20], [62, -10], [66, 7], [52, 21], [0, 22], [-22, 18], [-27, 4]], true, 6);++const scene = (ps: Pose, phase: number, boil: number): Part[] => {+ const sx = 1 / Math.sqrt(ps.sq), sy = ps.sq, B = (pts: P[]) => place(pts, ps.o, ps.tilt, sx, sy), w = (pts: P[], k: number) => wob(pts, 2.2, boil * 31 + k);+ const bodyW = B(BODY), tip = B([[228, -296]])[0], shL = B([[-116, -66]])[0], shR = B([[116, -66]])[0], hipL = B([[-50, -6]])[0], hipR = B([[50, -6]])[0];+ const glove = (h: P, a: number, mir: boolean) => GLOVE.map((s) => place(s, h, a, 1, 1, mir)), stitch = (h: P, a: number, mir: boolean) => STITCH.map((s) => place(s, h, a, 1, 1, mir));+ const shoe = (f: P, a: number, mir: boolean) => place(SHOE, f, mir ? -a : a, 1, 1, mir);+ // steam: three tapered wisps rising and curling off the spout; periodic in `phase`+ const wisp = (k: number): P[] => {+ // each wisp leaves the spout's mouth, rises in a lazy S that fans away from its neighbours, and+ // rolls into a curl at the top; the S travels up the wisp as `phase` runs 0..1 (periodic)+ const o: P = [tip[0] + 6 + k * 7, tip[1] - 10 - k * 3], c: P[] = [], hgt = 120 + k * 46, dir = k === 1 ? -1 : 1;+ for (let i = 0; i <= 16; i++) { const s = i / 16; c.push([o[0] + s * 22 + s * s * (k - 1) * 58 + Math.sin((s * 1.25 - phase) * Math.PI * 2 + k * 1.9) * (4 + 17 * s), o[1] - s * hgt]); }+ const e = c[c.length - 1], e0 = c[c.length - 2], a0 = Math.atan2(e[1] - e0[1], e[0] - e0[0]);+ for (let i = 1; i <= 10; i++) { const a = a0 + dir * (i / 10) * 4.4, r = 17 - i * 1.2; const cx = e[0] + Math.cos(a0 + dir * Math.PI / 2) * 17, cy = e[1] + Math.sin(a0 + dir * Math.PI / 2) * 17; c.push([cx + Math.cos(a - dir * Math.PI / 2) * r, cy + Math.sin(a - dir * Math.PI / 2) * r]); }+ const s = smooth(c, false, 3), Lp: P[] = [], Rp: P[] = [];+ s.forEach((p, i) => { const q = s[Math.min(s.length - 1, i + 1)], o2 = s[Math.max(0, i - 1)], dx = q[0] - o2[0], dy = q[1] - o2[1], l = Math.hypot(dx, dy) || 1, t = i / (s.length - 1), r = 2.5 + (10 - k * 1.5) * Math.sin(Math.PI * Math.min(1, t * 1.05)) * (1 - 0.25 * t); Lp.push([p[0] - (dy / l) * r, p[1] + (dx / l) * r]); Rp.push([p[0] + (dy / l) * r, p[1] - (dx / l) * r]); });+ return [...Lp, ...Rp.reverse()];+ };+ // flat shadows, thrown right by the window: the pot's on the tiles, the cup's, the feet on the counter+ const potShadow = place(BODY, [ps.o[0] + 78, ps.o[1] + 6], ps.tilt + 0.05, sx * 1.02, sy * 0.96);+ const footShadow = (f: P) => { const h = clamp((783 - f[1]) / 60); return ell(f[0] + (f === ps.fL ? -14 : 22) + h * 16, 806, 52 * (1 - 0.45 * h), 9 * (1 - 0.4 * h), 0, 20); };+ const tiles: P[][] = []; for (let x = 66; x < W; x += 66) tiles.push([[x, 585], [x, 780]]); [650, 715].forEach((y) => tiles.push([[0, y], [W, y]]));+ const scal: P[] = [[92, 96], [320, 96], [320, 128]]; for (let i = 0; i <= 6; i++) { const x0 = 320 - (i * 228) / 7, x1 = 320 - ((i + 1) * 228) / 7; scal.push(...qb([x0, 128], [(x0 + x1) / 2, 150], [x1, 128], 6).slice(1)); }+ const cupBody: P[] = [...cb([806, 724], [806, 772], [826, 800], [866, 800], 10), ...cb([866, 800], [906, 800], [926, 772], [926, 724], 10).slice(1), ...ell(866, 724, 60, 13, 0, 24).filter(([, y]) => y < 724).reverse()];+ const cupHandle = tubeOf([[922, 740], [956, 740], [956, 770], [916, 786]], 7, 6);+ const parts: Part[] = [+ // the set+ { fills: [{ pts: rect(0, 0, W, 562), col: G.wall, rank: 5 }], outline: [], ow: 0, orank: 0, details: [] },+ { fills: [{ pts: rect(92, 96, 320, 392), col: G.glass, rank: 4 }], outline: [rect(92, 96, 320, 392)], ow: 4.5, orank: 4, details: [{ pts: [[206, 128], [206, 392]], w: 7, rank: 4 }, { pts: [[92, 250], [320, 250]], w: 7, rank: 4 }, { pts: [[80, 392], [332, 392], [332, 404], [80, 404]], w: 4.5, closed: true, rank: 4 }] },+ { fills: [{ pts: scal, col: G.valance, rank: 4 }], outline: [scal], ow: 4.5, orank: 4, details: [] },+ { fills: [{ pts: rect(0, 562, W, 586), col: G.border, rank: 5 }, { pts: rect(0, 586, W, 780), col: G.tile, rank: 5 }], outline: [], ow: 0, orank: 4, details: [{ pts: [[0, 562], [W, 562]], w: 4.5, rank: 4 }, { pts: [[0, 586], [W, 586]], w: 4, rank: 4 }, ...tiles.map((t) => ({ pts: t, w: 3, rank: 4 }))] },+ { fills: [{ pts: potShadow, col: "#000000", alpha: 0.24, rank: 6 }, { pts: [[926, 726], [990, 734], [990, 800], [930, 800]], col: "#000000", alpha: 0.2, rank: 6 }], outline: [], ow: 0, orank: 0, details: [], knock: false },+ { fills: [{ pts: rect(0, 780, W, 826), col: G.top, rank: 5 }, { pts: rect(0, 826, W, 850), col: G.edge, rank: 5 }], outline: [rect(-10, 780, W + 10, 850)], ow: 4.5, orank: 4, details: [{ pts: [[0, 826], [W, 826]], w: 4, rank: 4 }] },+ { fills: [{ pts: rect(0, 850, W, H), col: G.cab, rank: 5 }, { pts: rect(70, 886, 500, 1080), col: G.panel, rank: 5 }, { pts: rect(580, 886, 1010, 1080), col: G.panel, rank: 5 }, { pts: ell(470, 968, 11, 11), col: INK, rank: 5 }, { pts: ell(610, 968, 11, 11), col: INK, rank: 5 }], outline: [], ow: 0, orank: 4, details: [{ pts: rect(70, 886, 500, 1100), w: 4.5, closed: true, rank: 4 }, { pts: rect(580, 886, 1010, 1100), w: 4.5, closed: true, rank: 4 }, { pts: [[540, 850], [540, 1080]], w: 4.5, rank: 4 }, { pts: ell(470, 968, 11, 11), w: 3.5, closed: true, rank: 4 }, { pts: ell(610, 968, 11, 11), w: 3.5, closed: true, rank: 4 }] },+ // the cup the pot is dancing for: a saucer, a cup, its handle, the empty dark inside+ { fills: [{ pts: ell(866, 804, 84, 15, 0, 30), col: G.saucer, rank: 3 }], outline: [ell(866, 804, 84, 15, 0, 30)], ow: 4.5, orank: 3, details: [] },+ { fills: [{ pts: cupHandle, col: G.cup, rank: 3 }], outline: [cupHandle], ow: 4.5, orank: 3, details: [] },+ { fills: [{ pts: cupBody, col: G.cup, rank: 3 }, { pts: ell(866, 724, 60, 13, 0, 28), col: G.coffee, rank: 3 }], outline: [cupBody, ell(866, 724, 60, 13, 0, 28)], ow: 4.5, orank: 3, details: [] },+ { fills: [{ pts: footShadow(ps.fL), col: "#000000", alpha: 0.3, rank: 2 }, { pts: footShadow(ps.fR), col: "#000000", alpha: 0.3, rank: 2 }], outline: [], ow: 0, orank: 0, details: [], knock: false },+ // the character, back to front+ { fills: [{ pts: B(HANDLE), col: G.pot, rank: 1 }], outline: [w(B(HANDLE), 1)], ow: 7, orank: 1, details: [] },+ { fills: [{ pts: B(SPOUT), col: G.pot, rank: 1 }], outline: [w(B(SPOUT), 2)], ow: 7, orank: 1, details: [{ pts: w(B(ell(229, -297, 9, 15, 0.62, 16)), 3), w: 5, closed: true, rank: 1 }] },+ { fills: [], outline: [], ow: 0, orank: 2, details: [{ pts: w(noodle(hipL, ps.fL, ps.lL), 4), w: 20, rank: 2 }, { pts: w(noodle(hipR, ps.fR, ps.lR), 5), w: 20, rank: 2 }] },+ { fills: [{ pts: shoe(ps.fL, ps.sL, true), col: INK, rank: 1 }, { pts: place(ell(44, -6, 10, 5, -0.3, 14), ps.fL, -ps.sL, 1, 1, true), col: G.white, rank: 1 }], outline: [w(shoe(ps.fL, ps.sL, true), 6)], ow: 7, orank: 2, details: [] },+ { fills: [{ pts: shoe(ps.fR, ps.sR, false), col: INK, rank: 1 }, { pts: place(ell(44, -6, 10, 5, -0.3, 14), ps.fR, ps.sR), col: G.white, rank: 1 }], outline: [w(shoe(ps.fR, ps.sR, false), 7)], ow: 7, orank: 2, details: [] },+ { fills: [], outline: [], ow: 0, orank: 2, details: [{ pts: w(noodle(shL, ps.hL, ps.bL), 8), w: 19, rank: 2 }, { pts: w(noodle(shR, ps.hR, ps.bR), 9), w: 19, rank: 2 }] },+ { fills: glove(ps.hL, ps.aL, true).map((s) => ({ pts: s, col: G.white, rank: 1 })), outline: glove(ps.hL, ps.aL, true).map((s, k) => w(s, 10 + k)), ow: 6, orank: 2, details: [...stitch(ps.hL, ps.aL, true).map((s) => ({ pts: s, w: 4, rank: 2 })), { pts: place([[-17, -13], [0, -10], [17, -13]], ps.hL, ps.aL, 1, 1, true), w: 4, rank: 2 }] },+ { fills: glove(ps.hR, ps.aR, false).map((s) => ({ pts: s, col: G.white, rank: 1 })), outline: glove(ps.hR, ps.aR, false).map((s, k) => w(s, 20 + k)), ow: 6, orank: 2, details: [...stitch(ps.hR, ps.aR, false).map((s) => ({ pts: s, w: 4, rank: 2 })), { pts: place([[-17, -13], [0, -10], [17, -13]], ps.hR, ps.aR), w: 4, rank: 2 }] },+ { fills: [{ pts: B(LID), col: G.lid, rank: 1 }], outline: [w(B(LID), 30)], ow: 7, orank: 1, details: [] },+ { fills: [{ pts: bodyW, col: G.pot, touch: B([[-20, -150]])[0], rank: 1 }, { pts: B(SHINE), col: G.shine, rank: 1 }], outline: [w(bodyW, 31)], ow: 7, orank: 1, details: [] },+ { fills: [{ pts: B(RIM), col: G.lid, rank: 1 }], outline: [w(B(RIM), 32)], ow: 7, orank: 1, details: [] },+ { fills: [{ pts: B(KNOB), col: INK, rank: 1 }, { pts: B(ell(-5, -343, 5, 4, 0, 10)), col: G.white, rank: 1 }], outline: [w(B(KNOB), 33)], ow: 7, orank: 1, details: [] },+ { fills: [{ pts: B(EYE(-33)), col: G.white, rank: 1 }, { pts: B(EYE(31)), col: G.white, rank: 1 }, { pts: B(PUPIL(-33)), col: INK, rank: 1 }, { pts: B(PUPIL(31)), col: INK, rank: 1 }], outline: [w(B(EYE(-33)), 34), w(B(EYE(31)), 35)], ow: 6, orank: 1, details: [{ pts: w(B(PUPIL(-33)), 36), w: 3, closed: true, rank: 1 }, { pts: w(B(PUPIL(31)), 37), w: 3, closed: true, rank: 1 }, { pts: w(B(qb([-58, -236], [-38, -256], [-14, -240])), 38), w: 6, rank: 1 }, { pts: w(B(qb([12, -240], [34, -258], [56, -238])), 39), w: 6, rank: 1 }] },+ { fills: [{ pts: B(MOUTH), col: INK, rank: 1 }, { pts: B(TONGUE), col: G.tongue, rank: 1 }], outline: [w(B(MOUTH), 40)], ow: 6, orank: 1, details: [{ pts: w(B(qb([-70, -142], [-72, -128], [-62, -118])), 42), w: 5, rank: 1 }, { pts: w(B(qb([68, -146], [72, -132], [62, -122])), 43), w: 5, rank: 1 }] },+ ...[0, 1, 2].map((k): Part => ({ fills: [{ pts: wisp(k), col: G.white, rank: 2 }], outline: [w(wisp(k), 50 + k)], ow: 4.5, orank: 2, details: [] })),+ ];+ return parts;+};++// ---------------------------------------------------------------- the rough, in blue pencil+const BLUE = "#6d9bd2";+const pencil = (g: Gfx, p: number) => {+ const ps = K0, B = (pts: P[]) => place(pts, ps.o, ps.tilt);+ const strokes: P[][] = [+ qb(ps.fL, [468, 560], ps.hL, 10), // the line of action, foot to waving hand+ B(ell(0, -140, 124, 142, 0, 16)).concat([B(ell(0, -140, 124, 142, 0, 16))[0]]), B(qb([-92, -268], [0, -330], [92, -268], 8)),+ B([[-96, -104], [-176, -180], [-100, -238]]), B(SPOUT_C),+ B(ell(-33, -196, 26, 36, 0, 12)).concat([B(ell(-33, -196, 26, 36, 0, 12))[0]]), B(ell(31, -196, 26, 36, 0, 12)).concat([B(ell(31, -196, 26, 36, 0, 12))[0]]), B(qb([-60, -130], [0, -40], [58, -134], 8)),+ noodle(B([[-116, -66]])[0], ps.hL, ps.bL, 8), ell(ps.hL[0] - 10, ps.hL[1] - 34, 30, 30, 0, 12).concat([ell(ps.hL[0] - 10, ps.hL[1] - 34, 30, 30, 0, 12)[0]]),+ noodle(B([[116, -66]])[0], ps.hR, ps.bR, 8), ell(ps.hR[0] + 30, ps.hR[1] - 10, 30, 30, 0, 12).concat([ell(ps.hR[0] + 30, ps.hR[1] - 10, 30, 30, 0, 12)[0]]),+ noodle(B([[-50, -6]])[0], ps.fL, ps.lL, 8), noodle(B([[50, -6]])[0], ps.fR, ps.lR, 8),+ ell(ps.fL[0] - 22, ps.fL[1] + 4, 42, 20, 0, 12).concat([ell(ps.fL[0] - 22, ps.fL[1] + 4, 42, 20, 0, 12)[0]]), ell(ps.fR[0] + 22, ps.fR[1] - 6, 42, 20, -0.38, 12).concat([ell(ps.fR[0] + 22, ps.fR[1] - 6, 42, 20, -0.38, 12)[0]]),+ [[664, 400], [650, 330], [690, 280], [660, 220]], // steam, where it will curl+ [[0, 781], [W, 781]], [[0, 826], [W, 826]], [[0, 586], [W, 586]], rect(92, 96, 320, 392).concat([[92, 96]]),+ ell(866, 760, 64, 44, 0, 12).concat([ell(866, 760, 64, 44, 0, 12)[0]]),+ ];+ g.group("ink", () => strokes.forEach((s, i) => { const q = p >= 1 ? 1 : clamp(p * strokes.length * 1.15 - i * 1.15); if (q > 0) g.pen(s, { w: 1.3, color: BLUE, seed: 900 + i, wobble: 2.2, opacity: 0.85, progress: q }); }));+};++// ---------------------------------------------------------------- frames+type Surf = { X: Layer; F: Layer; K: Layer; Y: Layer };+const surfaces = (env: Env): Surf => {+ const key = `rubberHose:surf:${env.scale}`; let s = env.cache.get(key) as Surf | undefined; if (s) return s;+ const mk = () => env.canvas(Math.round(W * env.scale), Math.round(H * env.scale)); s = { X: mk(), F: mk(), K: mk(), Y: mk() }; env.cache.set(key, s); return s;+};+const fresh = (L: Layer, env: Env) => { const c = L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; c.clearRect(0, 0, L.canvas.width, L.canvas.height); c.setTransform(env.scale, 0, 0, env.scale, 0, 0); return c; };+const blit = (c: Ctx, L: Layer, env: Env, dx = 0, dy = 0) => { c.save(); c.setTransform(1, 0, 0, 1, Math.round(dx * env.scale), Math.round(dy * env.scale)); c.drawImage(L.canvas as CanvasImageSource, 0, 0); c.restore(); };+const k = (f: number, w: readonly [number, number]) => clamp((f - w[0]) / (w[1] - w[0]));++// the cel on its paper: rough, ink, paint, at the given stage progress+const drawCel = (env: Env, pose: Pose, phase: number, boil: number, penP: number, inkP: number, fillP: number): Layer => {+ const S = surfaces(env), parts = scene(pose, phase, boil), sch = schedule(scene(K0, 0, 0));+ const x = fresh(S.X, env); x.fillStyle = G.paper; x.fillRect(0, 0, W, H);+ if (penP > 0 && fillP < 1) pencil(new Gfx(x, env, 0, PENCIL), penP);+ if (fillP > 0) paintFills(fresh(S.F, env), parts, sch.fill, fillP), blit(x, S.F, env);+ if (inkP > 0) inkCel(fresh(S.K, env), parts, sch.ink, inkP), blit(x, S.K, env);+ return S.X;+};+const pegHoles = (c: Ctx) => { c.save(); c.fillStyle = "#2a2622"; [[540, 30, 12, 12], [410, 30, 30, 8], [670, 30, 30, 8]].forEach(([x, y, rx, ry]) => { c.beginPath(); ell(x, y, rx, ry, 0, 20).forEach(([px, py], i) => (i ? c.lineTo(px, py) : c.moveTo(px, py))); c.fill(); }); c.restore(); };+const printed = (env: Env, cel: Layer, seed: number): Layer => { const S = surfaces(env), y = fresh(S.Y, env); blit(y, cel, env); filmPrint(y, env, seed); return S.Y; };++export const drawRubberHose = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ if (f >= T.dance[1]) { blit(ctx, printed(env, drawCel(env, K0, 0, 0, 1, 1, 1), 0), env); return; } // the still+ if (f >= T.pull[1]) { // the dance, on twos, projected+ const d = f - T.dance[0], q = d - (d % 2), r = (n: number) => { const x = Math.sin((q + 1) * 12.9898 + n * 78.233) * 43758.5453; return x - Math.floor(x); };+ ctx.fillStyle = "#0b0907"; ctx.fillRect(0, 0, W, H);+ blit(ctx, printed(env, drawCel(env, danced(d), q / 60, q > 0 ? 1 + q / 2 : 0, 1, 1, 1), 1 + d), env, (r(1) - 0.5) * 3, (r(2) - 0.5) * 3.4);+ return;+ }+ const cel = drawCel(env, K0, 0, 0, k(f, T.pen), k(f, T.ink), k(f, T.fill));+ if (f < T.pull[0]) { blit(ctx, cel, env); pegHoles(ctx); return; }+ // the pull-down: the drawing is threaded through the gate and comes back down as a print+ const t = k(f, T.pull), e = t >= 1 ? 1 : 1 - Math.pow(1 - t, 3) * (1 - 2.2 * t * (1 - t)), BAR = 56, y0 = -(H + BAR) * (1 - e);+ ctx.fillStyle = "#0b0907"; ctx.fillRect(0, 0, W, H);+ blit(ctx, printed(env, cel, 1 + (f - T.pull[0])), env, 0, y0);+ ctx.save(); ctx.translate(0, y0 + H + BAR); blit(ctx, cel, env, 0, y0 + H + BAR); pegHoles(ctx); ctx.restore();+};++export const STYLE = { id: "rubberHose", name: "Rubber hose", family: "1930s cartoon", medium: "India ink at one pressure on a clear cel over a blue-pencil rough, flat grey paint on the back, photographed and printed on black-and-white film", nearest: "koi", hero: "a coffee pot mid-dance-step on a kitchen counter, steam curling" };++export const rubberHose: Film = {+ meta: { title: "Rubber hose · the dancing coffee pot", W, H, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "cel", start: 0, end: N, draw: drawRubberHose }],+};+// line of action and still pose are the same drawing: a render of the pose table is its own check+void INK;diff --git a/engine/src/canvas-core/rubberHoseKit.ts b/engine/src/canvas-core/rubberHoseKit.tsnew file mode 100644index 0000000..0cd70f1--- /dev/null+++ b/engine/src/canvas-core/rubberHoseKit.ts@@ -0,0 +1,111 @@+// RUBBER HOSE KIT. The cel-and-film machinery for the 1930s plate: a scene is a z-ordered list of+// PARTS; each part has painted fills (the back of the cel), a union outline, and ink details. The+// inker's line is uniform (a brush-held pen at one pressure) with a slight wobble, and it stops+// where a nearer shape sits: every part knocks its own interior out of the ink beneath it.+// Also: the film look (toning, per-frame grain, flicker, dust, gate weave, the rounded gate).+import { fractal, rng, type Ctx, type Env, type Layer, type P } from "./core";+import { clamp } from "./gallery";+import { cut } from "./koiDrawKit";++export type Fill = { pts: P[]; col: string; alpha?: number; touch?: P; rank: number };+export type Line = { pts: P[]; w: number; closed?: boolean; rank: number; col?: string };+export type Part = { fills: Fill[]; outline: P[][]; ow: number; orank: number; details: Line[]; knock?: boolean };++// ---------------------------------------------------------------- geometry+export const cb = (a: P, c1: P, c2: P, b: P, n = 16): P[] => Array.from({ length: n + 1 }, (_, i) => { const t = i / n, u = 1 - t; return [u * u * u * a[0] + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t * t * t * b[0], u * u * u * a[1] + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t * t * t * b[1]] as P; });+export const qb = (a: P, c: P, b: P, n = 16): P[] => Array.from({ length: n + 1 }, (_, i) => { const t = i / n, u = 1 - t; return [u * u * a[0] + 2 * u * t * c[0] + t * t * b[0], u * u * a[1] + 2 * u * t * c[1] + t * t * b[1]] as P; });+export const ell = (cx: number, cy: number, rx: number, ry: number, rot = 0, n = 28): P[] => Array.from({ length: n }, (_, i) => { const a = (i / n) * Math.PI * 2, x = Math.cos(a) * rx, y = Math.sin(a) * ry; return [cx + x * Math.cos(rot) - y * Math.sin(rot), cy + x * Math.sin(rot) + y * Math.cos(rot)] as P; });+export const capsule = (a: P, b: P, r: number, n = 10): P[] => {+ const ang = Math.atan2(b[1] - a[1], b[0] - a[0]), out: P[] = [];+ for (let i = 0; i <= n; i++) { const t = ang + Math.PI / 2 + (i / n) * Math.PI; out.push([a[0] + Math.cos(t) * r, a[1] + Math.sin(t) * r]); }+ for (let i = 0; i <= n; i++) { const t = ang - Math.PI / 2 + (i / n) * Math.PI; out.push([b[0] + Math.cos(t) * r, b[1] + Math.sin(t) * r]); }+ return out;+};+export const rect = (x0: number, y0: number, x1: number, y1: number): P[] => [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];+// a noodle: a quadratic arc from a to b, bowed `bend` px off the chord (rubber hose has no elbow)+export const noodle = (a: P, b: P, bend: number, n = 18): P[] => { const dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1; return qb(a, [(a[0] + b[0]) / 2 - (dy / l) * bend, (a[1] + b[1]) / 2 + (dx / l) * bend], b, n); };+// place local points: mirror, squash (sx, sy), rotate, translate+export const place = (pts: P[], o: P, ang = 0, sx = 1, sy = 1, mirror = false): P[] => { const c = Math.cos(ang), s = Math.sin(ang); return pts.map(([x0, y0]) => { const x = (mirror ? -x0 : x0) * sx, y = y0 * sy; return [o[0] + x * c - y * s, o[1] + x * s + y * c] as P; }); };+// the inker's slight wobble: a slow displacement field, reseeded per drawing when animated+export const wob = (pts: P[], amp: number, seed: number): P[] => { const ox = (seed * 97.31) % 5000, oy = (seed * 57.17) % 5000; return pts.map(([x, y]) => [x + (fractal(1930, x + ox, y + oy, 0.035, 0.035, 2) - 0.5) * amp, y + (fractal(1931, x + oy, y + ox, 0.035, 0.035, 2) - 0.5) * amp]); }; // two noise tables only: a new drawing samples elsewhere in them+const len = (s: P[]) => s.reduce((a, p, i) => (i ? a + Math.hypot(p[0] - s[i - 1][0], p[1] - s[i - 1][1]) : a), 0);+const polyArea = (s: P[]) => Math.abs(s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2);++// ---------------------------------------------------------------- the schedule of marks+// Each stage is one sequence: marks of lower rank first, then z order; a mark's time is its+// length (lines: long ones go fast per px, a fixed lift for each) or its size (fills).+export type Schedule = Map<string, [number, number]>;+export const schedule = (parts: Part[]): { ink: Schedule; fill: Schedule } => {+ const inkItems: [string, number, number, number][] = [], fillItems: [string, number, number, number][] = [];+ parts.forEach((pt, z) => {+ pt.outline.forEach((o, i) => inkItems.push([`${z}:o${i}`, pt.orank, z * 100 + i, 5 + len(o) / 55]));+ pt.details.forEach((d, i) => inkItems.push([`${z}:d${i}`, d.rank, z * 100 + 50 + i, 4 + len(d.pts) / 55]));+ pt.fills.forEach((f, i) => fillItems.push([`${z}:f${i}`, f.rank, z * 100 + i, 0.8 + Math.sqrt(polyArea(f.pts)) / 30]));+ });+ const lay = (items: [string, number, number, number][]): Schedule => {+ items.sort((a, b) => a[1] - b[1] || a[2] - b[2]); const tot = items.reduce((a, b) => a + b[3], 0), m: Schedule = new Map(); let t = 0;+ items.forEach(([k, , , w]) => { m.set(k, [t / tot, (t + w) / tot]); t += w; }); return m;+ };+ return { ink: lay(inkItems), fill: lay(fillItems) };+};+const at = (m: Schedule, k: string, p: number) => { if (p >= 1) return 1; const w = m.get(k)!; return clamp((p - w[0]) / (w[1] - w[0])); };++// ---------------------------------------------------------------- painting the cel+const trace = (c: Ctx, pts: P[], close = true) => { c.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) c.lineTo(pts[i][0], pts[i][1]); if (close) c.closePath(); };+export const INK = "#16130f";+// fills: paint flooded from where the brush touched, stopped by the inked line+export const paintFills = (c: Ctx, parts: Part[], sch: Schedule, p: number) => {+ parts.forEach((pt, z) => pt.fills.forEach((f, i) => {+ const q = at(sch, `${z}:f${i}`, p); if (q <= 0) return;+ c.save(); c.globalAlpha = f.alpha ?? 1; c.fillStyle = f.col;+ if (q < 1) {+ const t = f.touch ?? f.pts.reduce((a, b) => [a[0] + b[0] / f.pts.length, a[1] + b[1] / f.pts.length] as P, [0, 0] as P);+ const R = Math.max(...f.pts.map(([x, y]) => Math.hypot(x - t[0], y - t[1]))) * (1 - (1 - q) ** 2) + 2;+ c.beginPath(); for (let k = 0; k <= 40; k++) { const a = (k / 40) * Math.PI * 2, rr = R * (1 + 0.06 * Math.sin(a * 5 + z)); k ? c.lineTo(t[0] + Math.cos(a) * rr, t[1] + Math.sin(a) * rr) : c.moveTo(t[0] + Math.cos(a) * rr, t[1] + Math.sin(a) * rr); } c.clip();+ }+ c.beginPath(); trace(c, f.pts); c.fill(); c.restore();+ }));+};+// ink: nearer parts knock out what they cover; a union outline is stroked double and its own+// interior removed, so overlapping pieces (glove fingers, a cuff) read as ONE silhouette+export const inkCel = (c: Ctx, parts: Part[], sch: Schedule, p: number) => {+ c.lineCap = "round"; c.lineJoin = "round";+ parts.forEach((pt, z) => {+ const knock = () => { if (pt.knock === false) return; c.save(); c.globalCompositeOperation = "destination-out"; c.fillStyle = "#000"; c.beginPath(); (pt.outline.length ? pt.outline : pt.fills.filter((f) => (f.alpha ?? 1) >= 1).map((f) => f.pts)).forEach((o) => trace(c, o)); c.fill("nonzero"); c.restore(); };+ knock();+ if (pt.outline.length) {+ c.strokeStyle = INK;+ pt.outline.forEach((o, i) => { const q = at(sch, `${z}:o${i}`, p); if (q <= 0) return; c.lineWidth = pt.ow * 2; c.beginPath(); trace(c, q >= 1 ? o : cut([...o, o[0]], q), q >= 1); c.stroke(); });+ knock();+ }+ pt.details.forEach((d, i) => { const q = at(sch, `${z}:d${i}`, p); if (q <= 0) return; c.strokeStyle = d.col ?? INK; c.lineWidth = d.w; c.beginPath(); trace(c, q >= 1 ? d.pts : cut(d.closed ? [...d.pts, d.pts[0]] : d.pts, q), !!d.closed && q >= 1); c.stroke(); });+ });+};++// ---------------------------------------------------------------- film+// a grain tile: independent speckle per device pixel, mid-grey centred, built once per scale+export const grainTile = (env: Env): Layer => {+ const key = `rubberHose:grain:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const n = Math.round(256 * env.scale); L = env.canvas(n, n); const img = L.ctx.createImageData(n, n), d = img.data, r = rng(1931);+ for (let i = 0; i < n * n; i++) { const v = (r() + r() + r()) / 3, g = Math.round(clamp(0.5 + (v - 0.5) * 2.2) * 255); d[i * 4] = d[i * 4 + 1] = d[i * 4 + 2] = g; d[i * 4 + 3] = 255; }+ L.ctx.putImageData(img, 0, 0); env.cache.set(key, L); return L;+};+// the print: toned, grained, flickering, dusty, vignetted by the lamp, cut to the rounded gate.+// `seed` picks this frame's grain, dust and flicker; the still uses seed 0.+export const filmPrint = (c: Ctx, env: Env, seed: number) => {+ const { W, H } = env, r = rng(7000 + seed * 13);+ c.save();+ c.globalCompositeOperation = "multiply"; c.fillStyle = "#ecdfc6"; c.fillRect(0, 0, W, H); // a warm silver print+ const g = grainTile(env), pat = c.createPattern(g.canvas as CanvasImageSource, "repeat")!;+ c.globalCompositeOperation = "overlay"; c.globalAlpha = 0.34; c.setTransform(1, 0, 0, 1, Math.floor(r() * 256 * env.scale), Math.floor(r() * 256 * env.scale)); c.fillStyle = pat; c.fillRect(-256 * env.scale, -256 * env.scale, (W + 512) * env.scale, (H + 512) * env.scale);+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.globalAlpha = 1;+ c.globalCompositeOperation = "source-over"; c.fillStyle = `rgba(20,14,8,${(0.02 + r() * 0.05).toFixed(3)})`; c.fillRect(0, 0, W, H); // the lamp flickers+ // dust on the print: black flecks (dirt on the positive) and white ones (dirt on the negative)+ const nd = 5 + Math.floor(r() * 5);+ for (let i = 0; i < nd; i++) { const x = r() * W, y = r() * H, s = 1 + r() * 2.6, dark = r() < 0.6; c.fillStyle = dark ? "rgba(18,12,8,0.7)" : "rgba(255,250,236,0.75)"; c.beginPath(); ell(x, y, s, s * (0.5 + r()), r() * 3, 8).forEach(([px, py], k) => (k ? c.lineTo(px, py) : c.moveTo(px, py))); c.fill(); }+ if (r() < 0.55) { const x = r() * W, y = r() * H, a = r() * 6; c.strokeStyle = "rgba(20,14,8,0.55)"; c.lineWidth = 1; c.beginPath(); trace(c, qb([x, y], [x + Math.cos(a) * 30, y + Math.sin(a) * 30 + 12], [x + Math.cos(a + 1) * 44, y + Math.sin(a + 1) * 40]), false); c.stroke(); } // a hair+ const sx = W * (0.62 + r() * 0.3); c.strokeStyle = "rgba(255,250,236,0.35)"; c.lineWidth = 1.2; c.beginPath(); c.moveTo(sx, 0); c.lineTo(sx + (r() - 0.5) * 6, H); c.stroke(); // the scratch the sprocket made+ const vg = c.createRadialGradient(W * 0.48, H * 0.44, W * 0.2, W / 2, H / 2, W * 0.78); vg.addColorStop(0, "rgba(0,0,0,0)"); vg.addColorStop(1, "rgba(22,14,6,0.55)"); c.fillStyle = vg; c.fillRect(0, 0, W, H);+ c.fillStyle = "#0b0907"; c.beginPath(); c.rect(0, 0, W, H); const m = 16, R = 46; c.moveTo(m + R, m); c.arcTo(m, m, m, m + R, R); c.arcTo(m, H - m, m + R, H - m, R); c.arcTo(W - m, H - m, W - m, H - m - R, R); c.arcTo(W - m, m, W - m - R, m, R); c.closePath(); c.fill("evenodd"); // the projector's gate+ c.restore();+};diff --git a/engine/src/canvas-core/score.ts b/engine/src/canvas-core/score.tsindex 7f4902c..4560b20 100644--- a/engine/src/canvas-core/score.ts+++ b/engine/src/canvas-core/score.ts@@ -1,14 +1,39 @@-// A tiny pure-JS score for the fixtures film: plucks on the beat, a bell on the last cut.-// No Web Audio, no Node APIs: just maths into two Float32Arrays, so it runs under ANY backend.-export const fixturesScore = (fps: number, bpm: number, frames: number) => (sr: number): [Float32Array, Float32Array] => {- const n = Math.ceil((frames / fps) * sr), L = new Float32Array(n), R = new Float32Array(n), beat = 60 / bpm;- const note = (t0: number, hz: number, dur: number, gain: number, pan: number, bell = false) => {- const i0 = Math.floor(t0 * sr), len = Math.floor(dur * sr);- for (let i = 0; i < len && i0 + i < n; i++) { const t = i / sr, env = Math.exp(-t * (bell ? 2.2 : 7)) * Math.min(1, t * 400), v = (Math.sin(2 * Math.PI * hz * t) + (bell ? 0.5 * Math.sin(2 * Math.PI * hz * 2.76 * t) + 0.25 * Math.sin(2 * Math.PI * hz * 5.4 * t) : 0.3 * Math.sin(2 * Math.PI * hz * 2 * t))) * env * gain; L[i0 + i] += v * (1 - pan); R[i0 + i] += v * pan; }- };- const scale = [261.63, 329.63, 392.0, 329.63, 293.66, 349.23, 440.0, 349.23, 392.0, 523.25];- for (let b = 0; b * beat < frames / fps; b++) { note(b * beat, scale[b % scale.length], 0.5, 0.22, 0.35 + 0.3 * (b % 2)); if (b % 2 === 0) note(b * beat, scale[b % scale.length] / 2, 0.7, 0.16, 0.5); }- note(6 * beat, 1046.5, 2.2, 0.2, 0.5, true); // DING on the cut into the last shot- for (let i = 0; i < n; i++) { L[i] = Math.tanh(L[i] * 1.4); R[i] = Math.tanh(R[i] * 1.4); }- return [L, R];-};+// The scaffold score: a two-section MusicPlan on the music module, so every new film starts with the+// breadth visible (spec 08 section 12). Section A: music box, JOY, C major, I-IV-V-I. Section B: the+// same box turns WISTFUL in D dorian (same notes, new home; the B natural is the colour). Notes are+// data; the plan fits ANY film length (tempo, then repeats); pure in (frames, sampleRate).+//+// CHANGE NOTE: until the music module landed, this file was 14 lines of sine plucks on a fixed+// C-major arpeggio plus a bell. Nothing imported it, so no shipped film changes sound. The worked+// butterfly film keeps its own score (example/.../alive/score.ts), untouched: it sounds the same.+import { line, type Piece } from "./music/plan";+import { filmAudio } from "./music/render";++const B = 4; // 12/8: four dotted-quarter beats a bar, triplet subdivisions+const arp = (r: string, f: string, t: string) => Array.from({ length: 12 }, (_, i) => `${[r, f, t, f][i % 4]}:1/3`).join(" ");++export const fixturesPiece = (bpm = 120): Piece => ({+ title: "Fixtures: joy, then wistful", seed: 3, tail: 1.6,+ harmony: [[0, "C"], [4, "F"], [8, "G"], [12, "C"], [16, "Dm"], [20, "G/D"], [24, "Dm"], [28, "Dm"]].map(([t, name]) => ({ t: t as number, name: name as string })),+ plan: {+ style: "musicBox", tempo: bpm, meter: "12/8", ritard: 0.85,+ sections: [+ { id: "joy", bars: 4, mood: "joy", key: "C", mode: "major", melody: ["hook", "arpeggio"], dyn: [0.75, 0.8], repeatable: true },+ { id: "wistful", bars: 4, mood: "wistful", key: "D", mode: "dorian", melody: ["themeTransformation"], dyn: [0.7, 0.6], ending: "button", repeatable: true, optional: true },+ ],+ },+ parts: [+ // the hook (E-G-A-G), answered; then the same hook re-seated on D dorian+ { id: "melody", inst: "musicBox", role: "melody", opts: { grid: true }, notes: line(0, [+ "E5:1 G5:2/3 A5:1/3 G5:1 E5:1", "A5:1 C6:2/3 A5:1/3 F5:2", "G5:1 A5:2/3 G5:1/3 D5:1 B5:1", "C6:4",+ "F5:1 A5:2/3 B5:1/3 A5:1 F5:1", "B5:1 D6:2/3 B5:1/3 G5:2", "A5:1 B5:2/3 A5:1/3 E5:1 F5:1", "D5:4"].join(" | "), { role: "melody", v: 0.75, bpb: B }) },+ { id: "arp", inst: "musicBox", role: "accomp", gainDb: -7, opts: { grid: true }, notes: line(0, [+ arp("C5", "G5", "E5"), arp("C5", "A5", "F5"), arp("B4", "G5", "D5"), arp("C5", "G5", "E5"),+ arp("D5", "A5", "F5"), arp("D5", "B5", "G5"), arp("D5", "A5", "F5"), "D5:1/3 A5:1/3 F5:1/3"].join(" | "), { role: "accomp", v: 0.5, bpb: B }) },+ { id: "bass", inst: "musicBox", role: "bass", gainDb: -8, opts: { grid: true }, notes: line(0, "C3:2 G3:2 | F3:2 C3:2 | G3:2 D3:2 | C3:4 | D3:2 A3:2 | G3:2 D3:2 | D3:2 A3:2 | D3:1", { role: "bass", v: 0.62, bpb: B }) },+ { id: "bell", inst: "bell", role: "color", notes: line(28, "D6:1", { role: "color", v: 0.7, bpb: B }) },+ ],+});++/** A film's `audio`: exactly the film's length at any sample rate. The same signature as before. */+export const fixturesScore = (fps: number, bpm: number, frames: number) => filmAudio(fixturesPiece(bpm), frames / fps);diff --git a/engine/src/canvas-core/scrapbook.ts b/engine/src/canvas-core/scrapbook.tsnew file mode 100644index 0000000..280ae5c--- /dev/null+++ b/engine/src/canvas-core/scrapbook.ts@@ -0,0 +1,303 @@+import { Gfx, fractal, rng, type Ctx, type Env, type Medium, type P } from "./core";+import type { Film } from "./film";+import { bounds, mix, smooth } from "./gallery";+import { bee, rose, type Engraving } from "./scrapbookEngraving";+import { GLYPHS, advance, clamp01, easeOut, engrave, fibres, glyph, handWrite, measure, onGrid, path, rect, scissor, shadowOf, staged, tear, typed, type Face, type Step } from "./scrapbookKit";++// HOW A HONEYBEE FINDS FLOWERS · archival scrapbook explainer.+//+// MEDIUM, physically. A page from an old field-notes album: rag paper gone to parchment, foxed+// with rust spots where the iron in the sheet oxidised, darker toward its handled edges, folded+// once. On it, cards torn from other stock are laid down and held with yellowing cellulose tape+// or pegged to a twine line with a wooden clothespin. The pictures are COPPERPLATE ENGRAVINGS:+// every tone is a burin line that swells where it is pressed and comes to a point where it+// lifts, contour-hatched round the form, cross-hatched only in the darks, cast shadows ruled in+// horizontal lines; afterwards a few areas are hand-tinted with a thin wash, as plates were.+// Words come from three hands: a TYPEWRITER (slab-serif monospace strikes, each its own ink+// density, the ribbon printing faintly double), RANSOM-NOTE titles (each letter cut from a+// different printed page: a paper tile with its own colour, face, weight and tilt, pasted with a+// small lift), and a red HAND for annotation. A rubber stamp goes on last.+// MARK / EDGE / ORDER. Mark: the tapering burin line; the struck character; the cut tile. Edge:+// torn deckle on the cards, scissor-crisp on the tiles, no drawn outline round anything that is+// paper. Order: page, cards down and taped, engravings cut line by line (contour, shading passes,+// cross-hatch, fur, shadow), hand tint, captions typed, titles pasted letter by letter, the dance+// diagram drawn, the chart plotted and annotated, the stamp.+// NOT its neighbours: fox (cut paper) has no line and no type; pocketWatch (ballpoint) builds tone+// from a constant-width biro; mellan (engraving) is one spiral. Here tone is many swelling lines+// that follow the form, on collaged ephemera.+// PALETTE: parchment #e8d6b2, sepia-black ink #2a2019, teal #4f8f8a, dusty pink #d9a5a0, stamp+// red #b8322a, navy #22335a, mustard #d6a13c. LIGHT: one lamp, upper left: cards, tiles and+// clothespin shadow down-right; the engravings are shaded to it.+// SUBJECT: the forager (focal, largest), the flower she finds, the dance that tells the hive+// where it is, and the evidence that run length encodes distance.++const INK = "#2a2019", NAVY = "#22335a", RED = "#b8322a", REDPEN = "#c23a2a", TEAL = "#4f8f8a", PINK = "#d9a5a0", MUSTARD = "#d6a13c", PARCH = "#e8d6b2";+const PEN: Medium = { nib: 1, taper: 0.35, pressure: 0.35, retrace: false, wobble: 0.5, rough: 0.35 };+const N = 510;++// ---------------------------------------------------------------- the cue table (every frame number)+const CUE = {+ beeCard: [10, 30], beeTape1: [30, 35], beeTape2: [35, 40],+ chartCard: [40, 55], chartTape: [55, 60],+ waggleCard: [60, 75], waggleTape: [75, 80],+ string: [80, 90], flowerCard: [90, 105], peg: [100, 110],+ tag: [110, 120], tagType: [120, 135],+ bee: [[140, 165], [165, 195], [195, 220], [220, 245], [245, 265], [265, 285], [285, 295]],+ rose: [[295, 305], [305, 325], [325, 335], [335, 345], [345, 350]],+ tint: [350, 365], cap1: [360, 380], cap2: [370, 385],+ strip1: [385, 390], strip1Type: [390, 395], honey: [395, 420], strip2: [415, 420], strip2Type: [420, 425], flowers: [425, 445],+ waggle: [445, 470], chart: [455, 480], notes: [475, 490], stamp: [490, 495],+} as const;+onGrid("scrapbook", Object.values(CUE).flat(2) as number[], N);++// ---------------------------------------------------------------- the cards+type Card = { cx: number; cy: number; w: number; h: number; rot: number; color: string; seed: number; from: P; torn: number };+const CARDS = {+ bee: { cx: 300, cy: 560, w: 500, h: 470, rot: -0.028, color: "#f2eadb", seed: 11, from: [-40, 70], torn: 2.4 },+ chart: { cx: 300, cy: 942, w: 470, h: 205, rot: 0.024, color: "#efe5cf", seed: 12, from: [30, 80], torn: 2.2 },+ waggle: { cx: 812, cy: 850, w: 440, h: 360, rot: -0.02, color: "#c9d9d5", seed: 13, from: [80, 60], torn: 2.6 },+ flower: { cx: 772, cy: 488, w: 268, h: 330, rot: 0.045, color: "#f1ebe0", seed: 14, from: [0, -60], torn: 2 },+} satisfies Record<string, Card>;+const toPage = (cd: Card, [x, y]: P, dx = 0, dy = 0): P => { const c = Math.cos(cd.rot), s = Math.sin(cd.rot); return [cd.cx + dx + x * c - y * s, cd.cy + dy + x * s + y * c]; };+const cardXf = (c: Ctx, env: Env, cd: Card) => { c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.translate(cd.cx, cd.cy); c.rotate(cd.rot); };+const cardShape = (cd: Card) => tear(rect(cd.w, cd.h), cd.torn, cd.seed);+const drawCard = (ctx: Ctx, env: Env, cd: Card, p: number) => {+ const e = easeOut(p), dx = cd.from[0] * (1 - e), dy = cd.from[1] * (1 - e), lift = 1 + 6 * (1 - e) * (1 - e);+ const g = new Gfx(ctx, env, 0, PEN), sh = cardShape(cd).map((q) => toPage(cd, q, dx, dy));+ shadowOf(g, [sh], [2.5 * lift, 4 * lift], 3 + 2.5 * lift, 0.34 / Math.sqrt(lift));+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ ctx.fillStyle = cd.color; path(ctx, sh); ctx.fill();+ fibres(ctx, sh, cd.color, cd.seed + 5, 0.8, 0.28);+ ctx.strokeStyle = mix(cd.color, "#7a5a30", 0.35); ctx.globalAlpha = 0.35; ctx.lineWidth = 1.2; path(ctx, sh); ctx.stroke(); ctx.globalAlpha = 1; // the handled, darkened deckle+};+// cellulose tape: yellowed, translucent, a torn zig-zag at each end, laid from one end+const tape = (ctx: Ctx, env: Env, at: P, ang: number, len: number, p: number, seed: number) => {+ if (p <= 0) return; const r = rng(seed), L = len * easeOut(p), h = 30, c = Math.cos(ang), s = Math.sin(ang), T = ([x, y]: P): P => [at[0] + x * c - y * s, at[1] + x * s + y * c];+ const top: P[] = [], bot: P[] = []; for (let k = 0; k <= 5; k++) { top.push([-len / 2 + (r() - 0.5) * 3, -h / 2 + (k * h) / 5]); }+ const endX = -len / 2 + L; for (let k = 5; k >= 0; k--) bot.push([endX + (k % 2 ? 3 : -2) * (p >= 1 ? 1 : 0), -h / 2 + (k * h) / 5]);+ const sh = [...top, ...bot].map(T); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ const g = new Gfx(ctx, env, 0, PEN); shadowOf(g, [sh], [1, 1.5], 1.5, 0.12); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ ctx.globalAlpha = 0.5; ctx.fillStyle = "#efe0a8"; path(ctx, sh); ctx.fill();+ ctx.globalAlpha = 0.28; ctx.fillStyle = "#fffbe8"; path(ctx, ([[-len / 2 + 4, -h / 2 + 4], [endX - 4, -h / 2 + 4], [endX - 4, -h / 2 + 8], [-len / 2 + 4, -h / 2 + 9]] as P[]).map(T)); ctx.fill(); // the sheen along one edge+ ctx.globalAlpha = 0.18; ctx.strokeStyle = "#8a6a2a"; ctx.lineWidth = 0.7; for (let k = 0; k < 3; k++) { const x = -len / 2 + 12 + r() * (L - 20); if (x < endX - 6) { ctx.beginPath(); const a = T([x, -h / 2 + 2]), b = T([x + (r() - 0.5) * 10, h / 2 - 2]); ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); ctx.stroke(); } } // crinkles+ ctx.globalAlpha = 1;+};++// ---------------------------------------------------------------- the page+const page = (ctx: Ctx, env: Env) => {+ const { W, H } = env, r = rng(301); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ ctx.fillStyle = PARCH; ctx.fillRect(0, 0, W, H);+ // uneven age: broad pale and dark clouds, never a gradient you can see the centre of+ for (let i = 0; i < 14; i++) { const x = r() * W, y = r() * H, R = 120 + r() * 260, gr = ctx.createRadialGradient(x, y, 0, x, y, R), col = r() < 0.55 ? "#f4e7c9" : "#caa874"; gr.addColorStop(0, col); gr.addColorStop(1, col + "00"); ctx.globalAlpha = 0.28; ctx.fillStyle = gr; ctx.fillRect(x - R, y - R, R * 2, R * 2); }+ // handled edges darken; the corners most+ const eg = (x0: number, y0: number, x1: number, y1: number) => { const gr = ctx.createLinearGradient(x0, y0, x1, y1); gr.addColorStop(0, "rgba(120,78,30,0.34)"); gr.addColorStop(1, "rgba(120,78,30,0)"); ctx.globalAlpha = 1; ctx.fillStyle = gr; ctx.fillRect(0, 0, W, H); };+ eg(0, 0, 60, 0); eg(W, 0, W - 70, 0); eg(0, 0, 0, 55); eg(0, H, 0, H - 80);+ // a tide mark from an old spill, lower right, under where the chart will sit+ ctx.globalAlpha = 0.16; ctx.strokeStyle = "#9a6a30"; ctx.lineWidth = 2.2; path(ctx, smooth(Array.from({ length: 16 }, (_, i) => { const a = (i / 16) * 6.28, k = 1 + (fractal(9, Math.cos(a) * 2, Math.sin(a) * 2, 0.8, 0.8, 2) - 0.5) * 0.25; return [610 + Math.cos(a) * 150 * k, 1010 + Math.sin(a) * 118 * k] as P; }), true, 6)); ctx.stroke();+ // the fold: a pale ridge and its dark valley across the page+ ctx.globalAlpha = 0.22; ctx.strokeStyle = "#fff6df"; ctx.lineWidth = 3; ctx.beginPath(); ctx.moveTo(0, 604); ctx.bezierCurveTo(300, 600, 700, 609, W, 603); ctx.stroke();+ ctx.globalAlpha = 0.16; ctx.strokeStyle = "#7a5424"; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(0, 606.5); ctx.bezierCurveTo(300, 602.5, 700, 611.5, W, 605.5); ctx.stroke();+ // foxing: rust spots in drifts (right margin, the lower-left corner, a scatter at the fold), bare elsewhere+ const drift = (cx: number, cy: number, sx: number, sy: number, n: number, big: number) => { for (let i = 0; i < n; i++) { const x = cx + (r() + r() - 1) * sx, y = cy + (r() + r() - 1) * sy, s = (0.6 + r() * r() * big) * 2.2; ctx.globalAlpha = 0.18 + r() * 0.25; ctx.fillStyle = "#a4652a"; path(ctx, smooth(Array.from({ length: 7 }, (_, k) => { const a = (k / 7) * 6.28; return [x + Math.cos(a) * s * (0.8 + r() * 0.4), y + Math.sin(a) * s * (0.8 + r() * 0.4)] as P; }), true, 4)); ctx.fill(); if (s > 3) { ctx.globalAlpha *= 0.5; ctx.beginPath(); ctx.arc(x, y, s * 2.2, 0, 6.28); ctx.fill(); } } };+ drift(1045, 360, 30, 220, 38, 3); drift(60, 1010, 70, 60, 34, 4); drift(540, 610, 160, 12, 16, 1.5); drift(980, 60, 60, 30, 10, 2);+ ctx.globalAlpha = 1;+};+const post = (ctx: Ctx, env: Env) => { const g = new Gfx(ctx, env, 0, PEN); g.paper("paper", 0.1); g.vignette("rgba(96,62,24,0.30)"); };++// ---------------------------------------------------------------- the engravings (cut once, cached)+const eng = (env: Env, id: "bee" | "rose"): Engraving => { const k = `scrapbook:eng:${id}`; let e = env.cache.get(k) as Engraving | undefined; if (!e) { e = id === "bee" ? bee(-8, -34, 28, 0.9) : rose(-4, -58, 84); env.cache.set(k, e); } return e; };+const cutPass = (ctx: Ctx, env: Env, cd: Card, id: "bee" | "rose", pass: number, p: number) => { cardXf(ctx, env, cd); engrave(ctx, eng(env, id).passes[pass], p, INK); };+// a hand tint: a thin wash that spreads from where the brush touched, multiplied over the lines+const tint = (ctx: Ctx, env: Env, cd: Card, id: "bee" | "rose", p: number) => {+ const g = new Gfx(ctx, env, 0, PEN), t = eng(env, id).tint;+ g.group("paint", () => { const c = g.cur; t.forEach((w, i) => { const q = clamp01(p * 1.6 - i * 0.08); if (q <= 0) return; const sh = w.shape.map((v) => toPage(cd, v)), b = bounds(sh), R = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) * easeOut(q); c.save(); c.beginPath(); c.arc(b.x0 + (b.x1 - b.x0) * 0.3, b.y0 + (b.y1 - b.y0) * 0.35, R, 0, 6.28); c.clip(); c.globalAlpha = w.alpha; c.fillStyle = w.color; path(c, sh); c.fill(); c.globalAlpha = w.alpha * 0.5; c.strokeStyle = w.color; c.lineWidth = 2; c.stroke(); c.restore(); g.touch(b.x0 - 4, b.y0 - 4, b.x1 + 4, b.y1 + 4); }); c.globalAlpha = 1; }, { blend: "multiply" });+};++// ---------------------------------------------------------------- ransom-note titles+type Tile = { ch: string; x: number; y: number; cap: number; face: Face; bg: string; fg: string; rot: number; seed: number; news: boolean };+const FACES: Face[] = [+ { weight: 0.2 }, { weight: 0.15, serif: 0.9 }, { weight: 0.12, outline: "" }, { weight: 0.14, slant: 0.22 }, { weight: 0.075, serif: 0.7, wide: 0.78 },+ { weight: 0.17, wide: 1.25 }, { weight: 0.16, cap: "round", join: "round" }, { weight: 0.11, serif: 1.0, slant: 0.12 },+];+const PAIRS: [string, string][] = [[NAVY, "#f3ead6"], [TEAL, "#1c1a18"], ["#f1e9d8", "#1c1a18"], [PINK, NAVY], [RED, "#f6ecd9"], [MUSTARD, "#1c1a18"], ["#d8d2c4", "#1c1a18"], ["#1d1b19", "#efe6d0"], ["#e9c9b4", RED]];+const ransom = (word: string, x0: number, y0: number, capBase: number, seed: number): Tile[] => {+ const r = rng(seed), out: Tile[] = []; let x = x0, lastP = -1, lastF = -1;+ [...word].forEach((ch, i) => {+ let pi = Math.floor(r() * PAIRS.length); if (pi === lastP) pi = (pi + 3) % PAIRS.length; let fi = Math.floor(r() * FACES.length); if (fi === lastF) fi = (fi + 2) % FACES.length; lastP = pi; lastF = fi;+ const [bg, fg] = PAIRS[pi], face = { ...FACES[fi] }; if (face.outline !== undefined) face.outline = bg;+ const cap = capBase * (0.84 + r() * 0.3), gw = ((GLYPHS[ch]?.w ?? 4) * (face.wide ?? 1) + 6 * (face.slant ?? 0)) * (cap / 6), w = gw + cap * (0.5 + r() * 0.25);+ out.push({ ch, x: x + w / 2, y: y0 + (r() - 0.5) * capBase * 0.22, cap, face, bg, fg, rot: (r() - 0.5) * 0.2, seed: seed * 10 + i, news: r() < 0.4 });+ x += w + 3 + r() * 6;+ });+ return out;+};+const tileShape = (t: Tile): P[] => { const gw = ((GLYPHS[t.ch]?.w ?? 4) * (t.face.wide ?? 1) + 6 * (t.face.slant ?? 0)) * (t.cap / 6), r = rng(t.seed), w = gw + t.cap * 0.55, h = t.cap * (1.5 + r() * 0.2); return scissor([[-w / 2 + (r() - 0.5) * 4, -h / 2 + (r() - 0.5) * 4], [w / 2 + (r() - 0.5) * 4, -h / 2 + (r() - 0.5) * 4], [w / 2 + (r() - 0.5) * 4, h / 2 + (r() - 0.5) * 4], [-w / 2 + (r() - 0.5) * 4, h / 2 + (r() - 0.5) * 4]], t.seed, 0.8); };+const drawTile = (ctx: Ctx, env: Env, t: Tile, p: number) => {+ if (p <= 0) return; const e = easeOut(p), lift = 1 + 5 * (1 - e) * (1 - e), dx = -6 * (1 - e), dy = -12 * (1 - e), rot = t.rot + 0.25 * (1 - e) * (t.seed % 2 ? 1 : -1);+ const c = Math.cos(rot), s = Math.sin(rot), T = ([x, y]: P): P => [t.x + dx + x * c - y * s, t.y + dy + x * s + y * c], sh = tileShape(t).map(T);+ const g = new Gfx(ctx, env, 0, PEN); shadowOf(g, [sh], [1.5 * lift, 2.5 * lift], 1.5 + lift, 0.4 / Math.sqrt(lift));+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = t.bg; path(ctx, sh); ctx.fill(); fibres(ctx, sh, t.bg, t.seed, 0.6, 0.18);+ ctx.translate(t.x + dx, t.y + dy); ctx.rotate(rot);+ if (t.news) { const r = rng(t.seed + 9), b = bounds(tileShape(t)); ctx.save(); path(ctx, tileShape(t)); ctx.clip(); ctx.globalAlpha = 0.3; ctx.fillStyle = t.fg; for (let y = b.y0 + 3; y < b.y1; y += 5) { let x = b.x0 + 2; while (x < b.x1) { const l = 3 + r() * 14; ctx.fillRect(x, y, l, 1.4); x += l + 3; } } ctx.restore(); ctx.globalAlpha = 1; ctx.fillStyle = t.bg; ctx.globalAlpha = 0.8; const gw = measure(t.ch, t.cap, t.face); ctx.fillRect(-gw / 2 - t.cap * 0.12, -t.cap * 0.62, gw + t.cap * 0.24, t.cap * 1.24); ctx.globalAlpha = 1; } // cut from a column of print: the letter sits on a cleared patch+ const gw = ((GLYPHS[t.ch]?.w ?? 4) * (t.face.wide ?? 1) + 6 * (t.face.slant ?? 0)) * (t.cap / 6);+ glyph(ctx, t.ch, -gw / 2, -t.cap / 2, t.cap, t.face, t.fg);+};+// a typed strip: a slip of white paper, the words struck one character at a time+type Strip = { text: string; x: number; y: number; cap: number; rot: number; color: string; seed: number };+const stripShape = (st: Strip): P[] => { const w = measure(st.text, st.cap, { weight: 0.1, mono: 4.2, track: 0.9 }) + st.cap * 1.6, h = st.cap * 2.3; return tear(rect(w, h), 1.2, st.seed); };+const drawStrip = (ctx: Ctx, env: Env, st: Strip, p: number, typedN: number) => {+ if (p <= 0) return; const e = easeOut(p), lift = 1 + 4 * (1 - e) * (1 - e), dy = -14 * (1 - e), c = Math.cos(st.rot), s = Math.sin(st.rot), T = ([x, y]: P): P => [st.x + x * c - y * s, st.y + dy + x * s + y * c], sh = stripShape(st).map(T);+ const g = new Gfx(ctx, env, 0, PEN); shadowOf(g, [sh], [1.5 * lift, 2.5 * lift], 1.5 + lift, 0.36 / Math.sqrt(lift));+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = st.color; path(ctx, sh); ctx.fill(); fibres(ctx, sh, st.color, st.seed, 0.6, 0.15);+ if (typedN > 0) { ctx.translate(st.x, st.y + dy); ctx.rotate(st.rot); const w = measure(st.text, st.cap, { weight: 0.1, mono: 4.2, track: 0.9 }); typed(ctx, st.text, -w / 2, -st.cap / 2, st.cap, "#221d1a", st.seed, typedN); }+};+const TAG: Strip = { text: "§3 FORAGING", x: 150, y: 58, cap: 15, rot: -0.012, color: "#f4efe4", seed: 71 };+const S1: Strip = { text: "HOW A", x: 150, y: 150, cap: 20, rot: -0.03, color: "#f7f2e8", seed: 72 };+const S2: Strip = { text: "FINDS", x: 360, y: 250, cap: 20, rot: 0.025, color: "#f7f2e8", seed: 73 };+const HONEY = ransom("HONEYBEE", 238, 148, 50, 91);+const FLOWERS = ransom("FLOWERS", 452, 246, 48, 94);++// ---------------------------------------------------------------- the string and the peg+const STRING: P[] = [[560, 312], [700, 322], [860, 324], [1000, 314], [1090, 306]];+const fillC = (g: Gfx, x: number, y: number, r: number, col: string) => { const c = g.cur; c.fillStyle = col; c.beginPath(); c.arc(x, y, r, 0, 6.28); c.fill(); g.touch(x - r, y - r, x + r, y + r); };+const drawString = (ctx: Ctx, env: Env, p: number) => {+ const g = new Gfx(ctx, env, 0, PEN), s = smooth(STRING, false, 12);+ g.group("plain", () => { g.pen(s.map(([x, y]) => [x + 1.5, y + 3] as P), { w: 2, color: "#3b2a14", seed: 3, wobble: 0, boil: 0, taper: 0, opacity: 0.35, retrace: false, progress: p }); }, { blur: 1.5 });+ if (p > 0) { const [px, py] = STRING[0]; g.group("plain", () => fillC(g, px + 3, py + 4, 6.5, "#3b2a14"), { blur: 2, alpha: 0.4 }); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); const gr = ctx.createRadialGradient(px - 2, py - 2, 0.5, px, py, 6.5); gr.addColorStop(0, "#f3dc9a"); gr.addColorStop(0.5, "#c49a45"); gr.addColorStop(1, "#7a5a22"); ctx.fillStyle = gr; ctx.beginPath(); ctx.arc(px, py, 6.5, 0, 6.28); ctx.fill(); }+ g.pen(s, { w: 2.1, color: "#7a6446", seed: 4, wobble: 0.3, boil: 0, taper: 0, opacity: 1, retrace: false, progress: p });+ // the twist of the twine: little diagonal ticks along it+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.strokeStyle = "#4c3a24"; ctx.lineWidth = 0.7; ctx.globalAlpha = 0.6; const n = Math.floor((s.length - 1) * p);+ for (let i = 2; i < n; i += 3) { const [x, y] = s[i]; ctx.beginPath(); ctx.moveTo(x - 1.2, y - 1.2); ctx.lineTo(x + 1.2, y + 1.2); ctx.stroke(); } ctx.globalAlpha = 1;+};+const drawPeg = (ctx: Ctx, env: Env, p: number) => {+ if (p <= 0) return; const e = easeOut(p), at = toPage(CARDS.flower, [0, -CARDS.flower.h / 2 + 10]), x = at[0], y = at[1] - 26 - 40 * (1 - e), a = 0.05;+ const c = Math.cos(a), s = Math.sin(a), T = ([u, v]: P): P => [x + u * c - v * s, y + u * s + v * c];+ const half = (sg: number): P[] => [[sg * 1, -40], [sg * 10, -40], [sg * 11, -30], [sg * 9, -6], [sg * 12, 14], [sg * 11, 40], [sg * 1, 40]].map(([u, v]) => T([u, v] as P));+ const g = new Gfx(ctx, env, 0, PEN); shadowOf(g, [half(-1), half(1)], [4, 6], 3, 0.35);+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ [-1, 1].forEach((sg) => { const sh = half(sg); ctx.fillStyle = sg < 0 ? "#d9b88a" : "#c9a577"; path(ctx, sh); ctx.fill(); ctx.strokeStyle = "#8a6a44"; ctx.lineWidth = 0.6; ctx.globalAlpha = 0.5; for (let k = 0; k < 3; k++) { const u = sg * (3 + k * 2.6); ctx.beginPath(); const a1 = T([u, -38]), b1 = T([u + sg * 0.8, 38]); ctx.moveTo(a1[0], a1[1]); ctx.quadraticCurveTo((a1[0] + b1[0]) / 2 + sg, (a1[1] + b1[1]) / 2, b1[0], b1[1]); ctx.stroke(); } ctx.globalAlpha = 0.8; ctx.strokeStyle = "#6b4e2c"; path(ctx, sh); ctx.stroke(); ctx.globalAlpha = 1; });+ // the steel spring: a coil across both prongs+ ctx.strokeStyle = "#5b5f63"; ctx.lineWidth = 1.6; for (let k = 0; k < 4; k++) { const a1 = T([-12, -4 + k * 2.6]), b1 = T([12, -2 + k * 2.6]); ctx.beginPath(); ctx.moveTo(a1[0], a1[1]); ctx.lineTo(b1[0], b1[1]); ctx.stroke(); }+ ctx.strokeStyle = "#c9ccd0"; ctx.lineWidth = 0.6; for (let k = 0; k < 4; k++) { const a1 = T([-11, -4.6 + k * 2.6]), b1 = T([11, -2.6 + k * 2.6]); ctx.beginPath(); ctx.moveTo(a1[0], a1[1]); ctx.lineTo(b1[0], b1[1]); ctx.stroke(); }+};++// ---------------------------------------------------------------- the waggle-dance card (drawn in navy pen)+type Stroke = { pts: P[]; w: number; color: string; dash?: boolean };+const waggleStrokes = (): Stroke[] => {+ const S: Stroke[] = [], deg = 40, a = (deg * Math.PI) / 180, dir: P = [Math.sin(a), -Math.cos(a)], nrm: P = [Math.cos(a), Math.sin(a)];+ // left: on the vertical comb. A few cells of comb in the corner, the UP arrow, the dance+ const hex = (cx: number, cy: number, R: number): P[] => Array.from({ length: 7 }, (_, i) => [cx + Math.cos((i / 6) * 6.28 + 0.52) * R, cy + Math.sin((i / 6) * 6.28 + 0.52) * R] as P);+ [[-190, 140], [-168, 153], [-146, 140], [-190, 114], [-168, 127], [-124, 153], [-212, 127]].forEach(([x, y]) => S.push({ pts: hex(x, y, 12.5), w: 0.8, color: "#6f8a90" }));+ S.push({ pts: [[-200, 90], [-200, -120]], w: 1.4, color: NAVY, dash: true }); S.push({ pts: [[-207, -108], [-200, -122], [-193, -108]], w: 1.4, color: NAVY });+ const c: P = [-100, 6], L = 70, A: P = [c[0] - dir[0] * L, c[1] - dir[1] * L], Bp: P = [c[0] + dir[0] * L, c[1] + dir[1] * L];+ // the return loops first (dashed), then the waggle run: a zig-zag, the bee's body shaking side to side+ const loop = (sg: number): P[] => { const pts: P[] = []; for (let k = 0; k <= 16; k++) { const u = (k / 16) * Math.PI, rr = L * 1.02; pts.push([c[0] + dir[0] * Math.cos(u) * rr + nrm[0] * Math.sin(u) * rr * 0.72 * sg, c[1] + dir[1] * Math.cos(u) * rr + nrm[1] * Math.sin(u) * rr * 0.72 * sg]); } return pts; };+ S.push({ pts: loop(1), w: 1.3, color: NAVY, dash: true }); S.push({ pts: loop(-1), w: 1.3, color: NAVY, dash: true });+ [1, -1].forEach((sg) => { const l = loop(sg), m = l[8], q = l[9], dx = q[0] - m[0], dy = q[1] - m[1], ll = Math.hypot(dx, dy), ux = dx / ll, uy = dy / ll; S.push({ pts: [[m[0] - ux * 7 - uy * 5, m[1] - uy * 7 + ux * 5], [m[0] + ux * 3, m[1] + uy * 3], [m[0] - ux * 7 + uy * 5, m[1] - uy * 7 - ux * 5]], w: 1.3, color: NAVY }); });+ const zz: P[] = []; for (let k = 0; k <= 16; k++) { const u = k / 16, amp = k === 0 || k === 16 ? 0 : (k % 2 ? 7 : -7); zz.push([A[0] + (Bp[0] - A[0]) * u + nrm[0] * amp, A[1] + (Bp[1] - A[1]) * u + nrm[1] * amp]); }+ S.push({ pts: zz, w: 2.1, color: NAVY });+ S.push({ pts: [[Bp[0] - dir[0] * 11 - nrm[0] * 7, Bp[1] - dir[1] * 11 - nrm[1] * 7], [Bp[0] + dir[0] * 4, Bp[1] + dir[1] * 4], [Bp[0] - dir[0] * 11 + nrm[0] * 7, Bp[1] - dir[1] * 11 + nrm[1] * 7]], w: 2, color: NAVY });+ // right: in the field. Hive, sun, the bearing to the flowers+ const hv: P = [60, 118], sun: P = [60, -112];+ const skep: P[] = []; for (let k = 0; k <= 14; k++) { const u = Math.PI + (k / 14) * Math.PI; skep.push([hv[0] + Math.cos(u) * 20, hv[1] + 4 + Math.sin(u) * 24]); } S.push({ pts: skep, w: 1.5, color: NAVY });+ S.push({ pts: [[hv[0] - 23, hv[1] + 4], [hv[0] + 23, hv[1] + 4]], w: 1.5, color: NAVY }); [-12, -3, 6].forEach((dy) => S.push({ pts: [[hv[0] - 18 + Math.abs(dy) * 0.2, hv[1] + dy - 6], [hv[0] + 18 - Math.abs(dy) * 0.2, hv[1] + dy - 6]], w: 0.9, color: NAVY }));+ S.push({ pts: [[hv[0], hv[1] - 20], sun], w: 1.3, color: NAVY, dash: true });+ const sunC: P[] = []; for (let k = 0; k <= 20; k++) { const u = (k / 20) * 6.28; sunC.push([sun[0] + Math.cos(u) * 12, sun[1] + Math.sin(u) * 12]); } S.push({ pts: sunC, w: 1.5, color: NAVY });+ for (let k = 0; k < 8; k++) { const u = (k / 8) * 6.28 + 0.2; S.push({ pts: [[sun[0] + Math.cos(u) * 17, sun[1] + Math.sin(u) * 17], [sun[0] + Math.cos(u) * 24, sun[1] + Math.sin(u) * 24]], w: 1.2, color: NAVY }); }+ const fl: P = [hv[0] + dir[0] * 150, hv[1] - 20 + dir[1] * 150];+ S.push({ pts: [[hv[0], hv[1] - 20], fl], w: 1.8, color: NAVY });+ S.push({ pts: [[fl[0] - dir[0] * 12 - nrm[0] * 6, fl[1] - dir[1] * 12 - nrm[1] * 6], fl, [fl[0] - dir[0] * 12 + nrm[0] * 6, fl[1] - dir[1] * 12 + nrm[1] * 6]], w: 1.8, color: NAVY });+ // a drift of small flowers where the bearing lands+ [[10, -6], [24, 8], [-6, 12], [30, -14], [16, 22]].forEach(([dx, dy], i) => { const q: P = [fl[0] + dx + 6, fl[1] + dy + 8]; for (let k = 0; k < 5; k++) { const u = (k / 5) * 6.28 + i; S.push({ pts: [q, [q[0] + Math.cos(u) * 4.5, q[1] + Math.sin(u) * 4.5]], w: 1.3, color: TEAL }); } });+ // the two angles, in the red hand+ const arc = (o: P, r: number): P[] => { const pts: P[] = []; for (let k = 0; k <= 10; k++) { const u = -Math.PI / 2 + (k / 10) * a; pts.push([o[0] + Math.cos(u) * r, o[1] + Math.sin(u) * r]); } return pts; };+ S.push({ pts: [[c[0], c[1] + 10], [c[0], c[1] - 86]], w: 1, color: REDPEN, dash: true });+ S.push({ pts: arc(c, 40), w: 1.6, color: REDPEN }); S.push({ pts: arc([hv[0], hv[1] - 20], 54), w: 1.6, color: REDPEN });+ S.push({ pts: [[0, -128], [0, 128]], w: 0.8, color: "#7d9a9c", dash: true });+ return S;+};+const dashes = (pts: P[], on = 7, off = 5): P[][] => { const out: P[][] = []; let cur: P[] = [], acc = 0, draw = true; for (let i = 1; i < pts.length; i++) { const a = pts[i - 1], b = pts[i], L = Math.hypot(b[0] - a[0], b[1] - a[1]); let t = 0; if (draw && !cur.length) cur.push(a); while (t < L) { const lim = draw ? on : off, step = Math.min(lim - acc, L - t); t += step; acc += step; const p: P = [a[0] + ((b[0] - a[0]) * t) / L, a[1] + ((b[1] - a[1]) * t) / L]; if (draw) cur.push(p); if (acc >= lim - 1e-9) { acc = 0; if (draw) { if (cur.length > 1) out.push(cur); cur = []; } else cur = [p]; draw = !draw; } } } if (draw && cur.length > 1) out.push(cur); return out; };+const penStrokes = (g: Gfx, cd: Card, strokes: Stroke[], p: number, seed: number) => {+ const n = p >= 1 ? strokes.length : p * strokes.length;+ strokes.forEach((s, i) => { const q = n >= i + 1 ? 1 : clamp01(n - i); if (q <= 0) return; const pts = s.pts.map((v) => toPage(cd, v)); if (s.dash) { const parts = dashes(pts.length > 2 ? smooth(pts, false, 6) : pts), m = q >= 1 ? parts.length : Math.floor(parts.length * q); parts.slice(0, m).forEach((d, k) => g.pen(d, { w: s.w, color: s.color, seed: seed + i * 13 + k, wobble: 0.2, boil: 0, taper: 0.2, opacity: 0.95, retrace: false })); } else g.pen(pts, { w: s.w, color: s.color, seed: seed + i * 13, wobble: 0.35, boil: 0, taper: 0.4, opacity: 0.95, retrace: false, progress: q }); });+};+const WAGGLE_LABELS: [string, number, number, number][] = [["UP", -224, -140, 11], ["ON THE COMB", -190, 168, 11], ["IN THE FIELD", 44, 168, 11], ["SUN", 82, -118, 11], ["HIVE", 88, 112, 11], ["FLOWERS", 116, -52, 10]];++// ---------------------------------------------------------------- the chart+const BARS: [string, number][] = [["0.5", 0.55], ["1", 1.05], ["2", 1.9], ["3", 2.6]];+const CH = { ox: -150, oy: 62, x1: 200, top: -52, px: 32, bx: [-96, -12, 72, 156], bw: 44 };+const drawChart = (ctx: Ctx, env: Env, p: number) => {+ const cd = CARDS.chart, g = new Gfx(ctx, env, 0, PEN), P2 = (v: P) => toPage(cd, v);+ const ax = clamp01(p / 0.3), bars = clamp01((p - 0.3) / 0.7);+ g.pen([P2([CH.ox, CH.top]), P2([CH.ox, CH.oy])], { w: 1.6, color: NAVY, seed: 81, wobble: 0.2, boil: 0, taper: 0.1, retrace: false, progress: clamp01(ax * 2) });+ g.pen([P2([CH.ox, CH.oy]), P2([CH.x1, CH.oy])], { w: 1.6, color: NAVY, seed: 82, wobble: 0.2, boil: 0, taper: 0.1, retrace: false, progress: clamp01(ax * 2 - 1) });+ [1, 2, 3].forEach((v, i) => { if (ax >= 1) g.pen([P2([CH.ox - 6, CH.oy - v * CH.px]), P2([CH.ox, CH.oy - v * CH.px])], { w: 1.2, color: NAVY, seed: 83 + i, wobble: 0.1, boil: 0, taper: 0, retrace: false }); });+ // bars are inked upward from the axis, one after another; the ink breaks on the paper's tooth+ g.group("plain", () => { const c = g.cur; BARS.forEach(([, v], i) => { const q = clamp01(bars * BARS.length - i); if (q <= 0) return; const h = v * CH.px * easeOut(q), x = CH.bx[i]; c.fillStyle = RED; path(c, [P2([x - CH.bw / 2, CH.oy - 1]), P2([x + CH.bw / 2, CH.oy - 1]), P2([x + CH.bw / 2, CH.oy - h]), P2([x - CH.bw / 2, CH.oy - h])]); c.fill(); const b = bounds([P2([x - CH.bw / 2, CH.oy]), P2([x + CH.bw / 2, CH.oy - h])]); g.touch(b.x0 - 2, b.y0 - 2, b.x1 + 2, b.y1 + 2); }); }, { textures: ["risoSpeck", "risoMottle"], blend: "multiply", alpha: 0.92 });+ cardXf(ctx, env, cd);+ if (ax >= 1) { [1, 2, 3].forEach((v) => typed(ctx, `${v}`, CH.ox - 20, CH.oy - v * CH.px - 5, 10, "#221d1a", 50 + v)); BARS.forEach(([k], i) => { const w = measure(k, 10, { weight: 0.1, mono: 4.2, track: 0.9 }); typed(ctx, k, CH.bx[i] - w / 2, CH.oy + 8, 10, "#221d1a", 60 + i); }); typed(ctx, "KM", CH.x1 - 8, CH.oy + 8, 10, "#221d1a", 70); typed(ctx, "SEC", CH.ox - 28, CH.top - 18, 10, "#221d1a", 71); }+ typed(ctx, "WAGGLE RUN VS DISTANCE", -212, -88, 12, "#221d1a", 72, Math.floor(clamp01(p * 3) * 22));+};+const drawNotes = (ctx: Ctx, env: Env, p: number) => {+ const cd = CARDS.chart, g = new Gfx(ctx, env, 0, PEN), P2 = (v: P) => toPage(cd, v);+ // the trend through the bar tops, a loop round the 1 km bar, and the reading in the red hand+ const tops: P[] = BARS.map(([, v], i) => [CH.bx[i], CH.oy - v * CH.px - 7]);+ const q1 = clamp01(p * 3), q2 = clamp01(p * 3 - 1), q3 = clamp01(p * 3 - 2);+ dashes(smooth(tops.map(P2), false, 6), 6, 4).forEach((d, k, arr) => { const m = q1 * arr.length; if (k < m) g.pen(d, { w: 1.6, color: REDPEN, seed: 90 + k, wobble: 0.3, boil: 0, taper: 0.2, retrace: false }); });+ const lp: P[] = []; for (let k = 0; k <= 22; k++) { const u = -0.4 + (k / 22) * 6.9, rr = 30 + k * 0.4; lp.push(P2([CH.bx[1] + Math.cos(u) * rr * 0.95, CH.oy - 1.05 * CH.px + 2 + Math.sin(u) * rr * 0.62])); }+ g.pen(lp, { w: 1.8, color: REDPEN, seed: 97, wobble: 0.6, boil: 0, taper: 0.6, retrace: false, progress: q2 });+ if (q3 > 0) { const base = P2([-52, -60]); handWrite(g, "~1 SEC PER KM", base[0], base[1], 15, REDPEN, 98, q3, 0.2, 1.9); }+};++// ---------------------------------------------------------------- the stamp+const drawStamp = (ctx: Ctx, env: Env, p: number) => {+ const x = 966, y = 100, rot = -0.14, w = 184, h = 74, g = new Gfx(ctx, env, 0, PEN), c0 = Math.cos(rot), s0 = Math.sin(rot);+ // a rubber stamp is rocked on: it meets the paper at one end first+ const reach = -w / 2 - 10 + (w + 20) * easeOut(clamp01(p * 1.5));+ g.group("plain", () => {+ const c = g.cur; c.save(); c.translate(x, y); c.rotate(rot); c.beginPath(); c.rect(-w / 2 - 12, -h / 2 - 12, reach + w / 2 + 12, h + 24); c.clip();+ c.strokeStyle = RED; c.lineWidth = 3.2; c.strokeRect(-w / 2, -h / 2, w, h); c.lineWidth = 1.2; c.strokeRect(-w / 2 + 6, -h / 2 + 6, w - 12, h - 12);+ const big: Face = { weight: 0.17, serif: 0.6, wide: 1.05, track: 1.5 }, tw = measure("SPECIMEN", 23, big); let cx = -tw / 2; [..."SPECIMEN"].forEach((ch) => { glyph(c, ch, cx, -h / 2 + 13, 23, big, RED); cx += advance(ch, big) * (23 / 6); });+ const sm: Face = { weight: 0.11, track: 1.6 }, sw = measure("APIS MELLIFERA · L.", 10, sm); cx = -sw / 2; [..."APIS MELLIFERA · L."].forEach((ch) => { glyph(c, ch, cx, h / 2 - 22, 10, sm, RED); cx += advance(ch, sm) * (10 / 6); });+ c.restore(); g.touch(x - w, y - w, x + w, y + w);+ }, { textures: ["risoSpeck", "risoMottle"], blend: "multiply", alpha: 0.88 });+ void c0; void s0;+};++// ---------------------------------------------------------------- the steps, in painter order+const TAPES: [keyof typeof CARDS, P, number, number, readonly [number, number]][] = [+ ["bee", [-236, -222], -0.7, 96, CUE.beeTape1], ["bee", [232, -224], 0.66, 96, CUE.beeTape2],+ ["chart", [0, -104], 0.02, 84, CUE.chartTape], ["waggle", [-206, -170], -0.74, 90, CUE.waggleTape],+];+const card = (id: keyof typeof CARDS, cue: readonly [number, number]): Step => ({ id: `card-${id}`, start: cue[0], end: cue[1], draw: (c, e, p) => drawCard(c, e, CARDS[id], p) });+const steps: Step[] = [+ { id: "page", start: -1, end: 0, draw: (c, e) => page(c, e) },+ card("bee", CUE.beeCard), card("chart", CUE.chartCard), card("waggle", CUE.waggleCard),+ ...TAPES.map(([id, at, ang, len, cue], i): Step => ({ id: `tape${i}`, start: cue[0], end: cue[1], draw: (c, e, p) => { const cd = CARDS[id]; tape(c, e, toPage(cd, at), ang + cd.rot, len, p, 40 + i); } })),+ { id: "string", start: CUE.string[0], end: CUE.string[1], draw: (c, e, p) => drawString(c, e, p) },+ card("flower", CUE.flowerCard),+ { id: "peg", start: CUE.peg[0], end: CUE.peg[1], draw: (c, e, p) => drawPeg(c, e, p) },+ { id: "tag", start: CUE.tag[0], end: CUE.tagType[1], draw: (c, e, p, f) => drawStrip(c, e, TAG, p >= 1 ? 1 : clamp01((f - CUE.tag[0]) / 10), p >= 1 ? Infinity : Math.floor(clamp01((f - CUE.tagType[0]) / (CUE.tagType[1] - CUE.tagType[0])) * TAG.text.length)) },+ ...CUE.bee.map((cue, i): Step => ({ id: `bee${i}`, start: cue[0], end: cue[1], draw: (c, e, p) => cutPass(c, e, CARDS.bee, "bee", i, p) })),+ ...CUE.rose.map((cue, i): Step => ({ id: `rose${i}`, start: cue[0], end: cue[1], draw: (c, e, p) => cutPass(c, e, CARDS.flower, "rose", i, p) })),+ { id: "tint", start: CUE.tint[0], end: CUE.tint[1], draw: (c, e, p) => { tint(c, e, CARDS.bee, "bee", p); tint(c, e, CARDS.flower, "rose", clamp01(p * 1.2 - 0.2)); } },+ { id: "cap1", start: CUE.cap1[0], end: CUE.cap1[1], draw: (c, e, p) => { cardXf(c, e, CARDS.bee); const t = "FIG. 1 APIS MELLIFERA, THE FORAGER"; typed(c, t, -226, 196, 12, "#221d1a", 31, p >= 1 ? Infinity : Math.floor(p * t.length)); } },+ { id: "cap2", start: CUE.cap2[0], end: CUE.cap2[1], draw: (c, e, p) => { cardXf(c, e, CARDS.flower); const t = "FIG. 2 ROSA CANINA"; typed(c, t, -112, 140, 11, "#221d1a", 32, p >= 1 ? Infinity : Math.floor(p * t.length)); } },+ { id: "strip1", start: CUE.strip1[0], end: CUE.strip1Type[1], draw: (c, e, p, f) => drawStrip(c, e, S1, p >= 1 ? 1 : clamp01((f - CUE.strip1[0]) / 5), p >= 1 ? Infinity : Math.floor(clamp01((f - CUE.strip1Type[0]) / 5) * S1.text.length)) },+ ...HONEY.map((t, i): Step => ({ id: `h${i}`, start: CUE.honey[0] + i * 3, end: CUE.honey[0] + i * 3 + 4, draw: (c, e, p) => drawTile(c, e, t, p) })),+ { id: "strip2", start: CUE.strip2[0], end: CUE.strip2Type[1], draw: (c, e, p, f) => drawStrip(c, e, S2, p >= 1 ? 1 : clamp01((f - CUE.strip2[0]) / 5), p >= 1 ? Infinity : Math.floor(clamp01((f - CUE.strip2Type[0]) / 5) * S2.text.length)) },+ ...FLOWERS.map((t, i): Step => ({ id: `f${i}`, start: CUE.flowers[0] + i * 3, end: CUE.flowers[0] + i * 3 + 4, draw: (c, e, p) => drawTile(c, e, t, p) })),+ { id: "waggle", start: CUE.waggle[0], end: CUE.waggle[1], draw: (c, e, p) => { const cd = CARDS.waggle, g = new Gfx(c, e, 0, PEN); penStrokes(g, cd, waggleStrokes(), p, 200); cardXf(c, e, cd); const t = "FIG. 3 THE WAGGLE DANCE"; typed(c, t, -206, -160, 12, "#221d1a", 33, p >= 1 ? Infinity : Math.floor(clamp01(p * 2) * t.length)); if (p > 0.6) { const q = clamp01((p - 0.6) / 0.4); WAGGLE_LABELS.forEach(([s, x, y, cap], i) => typed(c, s, x, y, cap, NAVY, 34 + i, q >= 1 ? Infinity : Math.floor(q * s.length))); } if (p >= 0.9) { const g2 = new Gfx(c, e, 0, PEN), a = toPage(cd, [-86, -76]), b = toPage(cd, [68, 22]); handWrite(g2, "40°", a[0], a[1], 13, REDPEN, 41, clamp01((p - 0.9) * 10), 0.2, 1.7); handWrite(g2, "40°", b[0], b[1], 13, REDPEN, 42, clamp01((p - 0.9) * 10), 0.2, 1.7); } } },+ { id: "chart", start: CUE.chart[0], end: CUE.chart[1], draw: (c, e, p) => drawChart(c, e, p) },+ { id: "notes", start: CUE.notes[0], end: CUE.notes[1], draw: (c, e, p) => drawNotes(c, e, p) },+ { id: "stamp", start: CUE.stamp[0], end: CUE.stamp[1], draw: (c, e, p) => drawStamp(c, e, p) },+];++export const drawScrapbook = staged("scrapbook", steps, post);+export const scrapbook: Film = {+ meta: { title: "How a honeybee finds flowers · archival scrapbook", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },+ assets: { images: {} },+ shots: [{ id: "scrapbook", start: 0, end: N, draw: (ctx, f, env) => drawScrapbook(ctx, f, env) }],+};+export const STYLE = { id: "scrapbook", name: "Archival scrapbook", family: "collage + print", medium: "foxed rag-paper album page; torn cards, cellulose tape, a clothespin on twine; copperplate engravings hand-tinted; typewriter, ransom-note cut letters, red pen, rubber stamp", nearest: "fox", hero: "How a honeybee finds flowers: the forager, the rose, the waggle dance, the evidence" };+void MUSTARD; void rng;diff --git a/engine/src/canvas-core/scrapbookEngraving.ts b/engine/src/canvas-core/scrapbookEngraving.tsnew file mode 100644index 0000000..876a45c--- /dev/null+++ b/engine/src/canvas-core/scrapbookEngraving.ts@@ -0,0 +1,258 @@+// SCRAPBOOK ENGRAVINGS: the two copperplate spot illustrations of the honeybee page, as lists of+// burin cuts in the order an engraver cuts them (contours, then the shading passes part by part,+// then cross-hatching in the darks, then fur and detail, the cast shadow last).+//+// Realism, stated. A worker honeybee (Apis mellifera), dorsal view in flight, three-quarter turned+// so nothing is mirrored: head wider than long with large kidney-shaped compound eyes on its sides+// and three ocelli on the vertex; elbowed antennae (a long scape, then a ringed flagellum); a+// round, densely furred thorax carrying two wing pairs, the forewing longer and overlapping the+// hindwing's leading edge, venation with a long marginal cell at the tip and three submarginal+// cells; a narrow waist; an abdomen of six visible tergites, each with a pale felted hair band at+// its base and a dark hind margin; three pairs of jointed legs (femur, tibia, a five-part tarsus+// with claws), the hind tibia flattened into a pollen basket that carries a load (she is a+// returning forager). References consulted from memory: 19th-century natural-history plates of+// the honeybee (Cheshire's "Bees and Bee-keeping" style dorsal plates), standard hymenopteran+// wing-venation diagrams, and macro photographs of corbicula pollen loads.+// The flower is a dog rose (Rosa canina): five broad heart-notched petals, imbricate, cupped, on a+// tilted face, a ring of many stamens round a flat disc of styles, a prickled stem and a pinnate+// leaf with serrate leaflets. Light: one lamp, upper left, for both.+import { rng, fractal, type P } from "./core";+import { profile, resample, smooth } from "./gallery";+import { cutLine, dense, occluder, type Cut, type Occluder, clamp01 } from "./scrapbookKit";++const L3 = (() => { const v = [-0.52, -0.64, 0.56], l = Math.hypot(v[0], v[1], v[2]); return v.map((x) => x / l); })();++// a two-sided frame hung on a spine: at(t, s), s > 0 uses hp, s < 0 uses hn+export type Frame = { at: (t: number, s: number) => P; nrm: (t: number) => P; tan: (t: number) => P; hw: (t: number, s: number) => number; outline: P[]; len: number };+export const frame = (ctrl: P[], hp: (t: number) => number, hn: (t: number) => number = hp, n = 90): Frame => {+ const sp = resample(smooth(ctrl, false, 12), n), nr: P[] = sp.map((_, i) => { const a = sp[Math.max(0, i - 1)], b = sp[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1; return [-dy / l, dx / l]; });+ let len = 0; for (let i = 1; i < n; i++) len += Math.hypot(sp[i][0] - sp[i - 1][0], sp[i][1] - sp[i - 1][1]);+ const pick = (arr: P[], t: number): P => { const f = clamp01(t) * (n - 1), i = Math.floor(f), k = Math.min(n - 1, i + 1), u = f - i; return [arr[i][0] + (arr[k][0] - arr[i][0]) * u, arr[i][1] + (arr[k][1] - arr[i][1]) * u]; };+ const hw = (t: number, s: number) => (s >= 0 ? hp(t) : hn(t));+ const at = (t: number, s: number): P => { const p = pick(sp, t), q = pick(nr, t), w = hw(t, s); return [p[0] + q[0] * w * s, p[1] + q[1] * w * s]; };+ const L: P[] = [], R: P[] = []; for (let i = 0; i <= 60; i++) { const t = i / 60; L.push(at(t, 1)); R.push(at(t, -1)); }+ return { at, nrm: (t) => pick(nr, t), tan: (t) => { const q = pick(nr, t); return [q[1], -q[0]]; }, hw, outline: [...L, ...R.reverse()], len };+};+const K = (k: [number, number][]) => profile(k);++// shading of a rounded tube at (t, s): the normal leans out across s and toward the ends+const tubeShade = (f: Frame, t: number, s: number, round = 0.7): number => {+ const q = f.nrm(t), tg = f.tan(t), e = 2 * t - 1, ek = Math.sign(e) * Math.pow(Math.abs(e), 5) * round, sc = Math.max(-1, Math.min(1, s));+ let nx = q[0] * sc + tg[0] * ek, ny = q[1] * sc + tg[1] * ek; const nz = Math.sqrt(Math.max(0.02, 1 - sc * sc - ek * ek)), l = Math.hypot(nx, ny, nz); nx /= l; ny /= l;+ const lam = Math.max(0, nx * L3[0] + ny * L3[1] + (nz / l) * L3[2]);+ return 1 - (0.1 + 0.9 * lam);+};+const combine = (a: number, b: number) => 1 - (1 - a) * (1 - b);+const toneW = (tone: number, wMax: number, lo = 0.14) => wMax * Math.pow(clamp01((tone - lo) / (1 - lo)), 0.85);++// transverse rings across a tube (constant t), bowed toward `bowDir` so the segment reads convex+const rings = (f: Frame, t0: number, t1: number, gap: number, tone: (t: number, s: number) => number, wMax: number, occ: Occluder[], bow = 0.14, sExt = 1.02): Cut[] => {+ const n = Math.max(2, Math.round(((t1 - t0) * f.len) / gap)), out: Cut[] = [];+ for (let i = 0; i <= n; i++) {+ const t = t0 + ((t1 - t0) * i) / n, tg = f.tan(t), hwM = (f.hw(t, 1) + f.hw(t, -1)) / 2, pts: P[] = [], ss: number[] = [];+ for (let k = 0; k <= 24; k++) { const s = -sExt + (2 * sExt * k) / 24, p = f.at(t, s), b = (1 - s * s) * hwM * bow; pts.push([p[0] + tg[0] * b, p[1] + tg[1] * b]); ss.push(s); }+ const d = dense(pts, 1.8), m = d.length;+ out.push(cutLine(d, (_x, _y, j) => toneW(tone(t, -sExt + (2 * sExt * j) / (m - 1)), wMax), occ, 1.8));+ }+ return out;+};+// longitudinal lines (constant s): the cross-hatch that goes in only where the tone is deep+const along = (f: Frame, s0: number, s1: number, gap: number, t0: number, t1: number, tone: (t: number, s: number) => number, wMax: number, lo: number, occ: Occluder[]): Cut[] => {+ const hwM = (f.hw(0.5, 1) + f.hw(0.5, -1)) / 2, n = Math.max(1, Math.round(((s1 - s0) * hwM) / gap)), out: Cut[] = [];+ for (let i = 0; i <= n; i++) {+ const s = s0 + ((s1 - s0) * i) / n, pts: P[] = [];+ for (let k = 0; k <= 30; k++) pts.push(f.at(t0 + ((t1 - t0) * k) / 30, s));+ const d = dense(pts, 1.8), m = d.length;+ out.push(cutLine(d, (_x, _y, j) => toneW(tone(t0 + ((t1 - t0) * j) / (m - 1), s), wMax, lo), occ, 1.8));+ }+ return out;+};+// a contour, heavier on the side turned from the light+const contour = (pts: P[], w0: number, w1: number, occ: Occluder[], closed = true): Cut => {+ const d = dense(closed ? [...pts, pts[0], pts[1]] : pts, 1.6), n = d.length;+ let cx = 0, cy = 0; d.forEach(([x, y]) => { cx += x; cy += y; }); cx /= n; cy /= n;+ return cutLine(d, (x, y, i) => { const a = d[Math.max(0, i - 1)], b = d[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1; let ox = dy / l, oy = -dx / l; if (ox * (x - cx) + oy * (y - cy) < 0) { ox = -ox; oy = -oy; } const away = clamp01(-(ox * L3[0] + oy * L3[1]) / Math.hypot(L3[0], L3[1]) * 0.5 + 0.5); return w0 + (w1 - w0) * away * away; }, occ, 1.6);+};+const open = (pts: P[], w: number, occ: Occluder[] = [], taper = true): Cut => cutLine(smooth(pts, false, 8), (_x, _y, i, n) => w * (taper ? 0.55 + 0.45 * Math.sin((Math.PI * (i + 0.5)) / n) : 1), occ, 1.6);+// short fur flicks: from a seed point along a direction, tapered, width from tone+const flick = (p: P, dir: number, len: number, w: number, curl: number): Cut => { const pts: P[] = []; for (let k = 0; k <= 5; k++) { const u = k / 5, a = dir + curl * u; pts.push([p[0] + Math.cos(a) * len * u, p[1] + Math.sin(a) * len * u]); } return { pts, w: pts.map((_, i) => w * Math.sin((Math.PI * (i + 0.7)) / 6.4)) }; };++// ---------------------------------------------------------------- the bee+export type Engraving = { passes: Cut[][]; tint: { shape: P[]; color: string; alpha: number }[]; bounds: P[] };+export const bee = (ox: number, oy: number, deg: number, sc: number): Engraving => {+ const a = (deg * Math.PI) / 180, ca = Math.cos(a), sa = Math.sin(a), B = ([x, y]: P): P => [ox + (x * ca - y * sa) * sc, oy + (x * sa + y * ca) * sc], BB = (ps: P[]) => ps.map(B);+ const r = rng(4242);+ // parts, drawn from the back of the stack forward+ const abd = frame(BB([[0, 50], [3, 108], [8, 168], [13, 226]]), K([[0, 13], [0.1, 33], [0.3, 46], [0.55, 46], [0.78, 35], [0.93, 17], [1, 4]]));+ const thx = frame(BB([[0, -46], [1, 0], [0, 50]]), K([[0, 22], [0.18, 43], [0.5, 52], [0.82, 45], [1, 20]]));+ const head = frame(BB([[0, -44], [-1, -76], [0, -108]]), K([[0, 24], [0.14, 42], [0.42, 47], [0.74, 36], [1, 13]]));+ const scale = (f: number) => f * sc;+ const oAbd = occluder(abd.outline), oThx = occluder(thx.outline), oHead = occluder(head.outline);+ // legs: femur, tibia, basitarsus + four small tarsomeres, claw. [attach, knee, ankle, foot]+ type Leg = { j: P[]; w: [number, number, number]; hind?: boolean };+ const legs: Leg[] = [+ // every leg leaves the underside of the THORAX (fore, mid, hind pairs), so each is hidden where+ // it enters under the thorax's edge; knees of the fore and mid legs bend forward and out, the+ // hind femur runs back and the tibia (the pollen basket) trails back along the abdomen+ { j: [[-18, -30], [-54, -50], [-62, -90], [-52, -122]], w: [6, 5, 3] }, { j: [[20, -28], [58, -44], [72, -82], [86, -108]], w: [6, 5, 3] },+ { j: [[-28, -2], [-80, 10], [-106, 56], [-124, 92]], w: [6.5, 5.5, 3.2] }, { j: [[30, 0], [84, 4], [116, 42], [142, 66]], w: [6.5, 5.5, 3.2] },+ { j: [[-22, 26], [-68, 60], [-86, 120], [-78, 168]], w: [7, 9, 4], hind: true }, { j: [[24, 26], [68, 64], [94, 124], [102, 174]], w: [7, 9, 4], hind: true },+ ];+ const bodyOcc = [oAbd, oThx, oHead];+ const legPasses: Cut[] = [], legContours: Cut[] = [], pollen: P[][] = [], legOutlines: P[][] = [];+ legs.forEach((lg, li) => {+ const J = BB(lg.j);+ const segs: [P, P, number, number][] = [[J[0], J[1], lg.w[0] * 1.1, lg.w[0] * 0.8], [J[1], J[2], lg.w[1] * 0.75, lg.w[1] * (lg.hind ? 1.25 : 0.9)], [J[2], [J[2][0] + (J[3][0] - J[2][0]) * 0.42, J[2][1] + (J[3][1] - J[2][1]) * 0.42], lg.w[2] * (lg.hind ? 1.5 : 1.1), lg.w[2] * 0.9]];+ segs.forEach(([p0, p1, w0, w1], si) => {+ const mid: P = [(p0[0] + p1[0]) / 2 + (r() - 0.5) * 3, (p0[1] + p1[1]) / 2 + (r() - 0.5) * 3], f = frame([p0, mid, p1], (t) => scale(w0 + (w1 - w0) * t) * (0.85 + 0.3 * Math.sin(Math.PI * t)), undefined, 30);+ legOutlines.push(f.outline);+ legContours.push(contour(f.outline, 0.7, 1.5, bodyOcc));+ legPasses.push(...along(f, -0.85, 0.85, 2.2, 0.04, 0.96, (t, s) => combine(tubeShade(f, t, s, 0.5), 0.5), 1.15, 0.2, bodyOcc));+ for (let k = 0; k < 5; k++) { const t = 0.15 + k * 0.17, sd = k % 2 ? 1 : -1, p = f.at(t, sd * 1.02), q = f.nrm(t); legPasses.push(flick(p, Math.atan2(q[1] * sd, q[0] * sd) + 0.7 * sd, scale(4 + r() * 3), 0.55, 0.3)); }+ // the fringe of long hairs on the hind tibia's edges: the pollen basket's rim+ if (lg.hind && si === 1) for (let k = 0; k < 11; k++) { const t = 0.12 + k * 0.075; [1, -1].forEach((sd) => { const p = f.at(t, sd * 1.05), q = f.nrm(t); legPasses.push(flick(p, Math.atan2(q[1] * sd, q[0] * sd) + 0.5, scale(7 + r() * 4), 0.7, 0.4)); }); }+ if (lg.hind && si === 1) { const c = f.at(0.55, li % 2 ? -0.1 : 0.1), rr = scale(12); pollen.push(Array.from({ length: 24 }, (_, i) => { const u = (i / 24) * Math.PI * 2, k = 1 + (fractal(li + 90, Math.cos(u) * 2, Math.sin(u) * 2, 0.7, 0.7, 2) - 0.5) * 0.3; return [c[0] + Math.cos(u) * rr * 1.15 * k, c[1] + Math.sin(u) * rr * k] as P; })); }+ });+ // the small tarsomeres as a beaded chain, then the claw+ const t0 = segs[2][1], end = J[3]; legContours.push(cutLine(dense([t0, end], 1.5), (_x, _y, i, n) => scale(3.2 - 1.4 * (i / n)) * (0.75 + 0.25 * Math.abs(Math.sin((i / n) * Math.PI * 4))), bodyOcc, 1.5));+ const dx = end[0] - t0[0], dy = end[1] - t0[1], l = Math.hypot(dx, dy); [0.5, -0.5].forEach((da) => { const an = Math.atan2(dy, dx) + da; legContours.push(open([end, [end[0] + Math.cos(an) * scale(6), end[1] + Math.sin(an) * scale(6)], [end[0] + Math.cos(an + da * 1.4) * scale(9), end[1] + Math.sin(an + da * 1.4) * scale(9)]], 1.1, bodyOcc)); });+ void l;+ });+ // pollen load: stipple, dense in the shade, then a broken rim+ const pollenCuts: Cut[] = [];+ pollen.forEach((sh, i) => { const rr = rng(700 + i); let cx = 0, cy = 0; sh.forEach(([x, y]) => { cx += x; cy += y; }); cx /= sh.length; cy /= sh.length; for (let k = 0; k < 140; k++) { const u = rr() * Math.PI * 2, d = Math.sqrt(rr()), p: P = [cx + Math.cos(u) * d * scale(13), cy + Math.sin(u) * d * scale(11.5)], tone = clamp01(0.35 + ((p[0] - cx) * -L3[0] + (p[1] - cy) * -L3[1]) / scale(20)); if (rr() < tone) pollenCuts.push(flick(p, rr() * 6.28, 1.6, 1.1, 0)); } pollenCuts.push(contour(sh, 0.3, 1.2, [])); });++ // abdomen: six tergites. Tone = form shading + a dark hind margin on each; the felt band at+ // each base is left pale and cut later as fur+ const terg = [0.1, 0.25, 0.41, 0.57, 0.72, 0.86, 1];+ const pig = (t: number) => { for (let i = 0; i < terg.length - 1; i++) if (t >= terg[i] && t < terg[i + 1]) { const u = (t - terg[i]) / (terg[i + 1] - terg[i]); return u < 0.28 ? 0.02 : u > 0.62 ? 0.62 : 0.3; } return 0.5; };+ const abdTone = (t: number, s: number) => combine(tubeShade(abd, t, s, 0.9), pig(t));+ const abdCuts = rings(abd, 0.03, 0.99, 3.0, abdTone, 1.75, [oThx], 0.2);+ const abdCross = along(abd, -0.95, 0.95, 3.6, 0.05, 0.98, abdTone, 1.1, 0.55, [oThx]);+ const tergLines = terg.slice(1, -1).map((t) => { const pts: P[] = []; for (let k = 0; k <= 24; k++) { const s = -1 + k / 12, p = abd.at(t, s), tg = abd.tan(t), b = (1 - s * s) * abd.hw(t, 1) * 0.2; pts.push([p[0] + tg[0] * b, p[1] + tg[1] * b]); } return cutLine(pts, (x, y, i, n) => 0.8 + 1.1 * clamp01(i / n), [oThx], 1.6); });+ // felt bands: short flicks laid backward across each tergite base+ const felt: Cut[] = []; terg.slice(0, -2).forEach((t0, i) => { const t1 = t0 + (terg[i + 1] - t0) * 0.3; for (let k = 0; k < 26; k++) { const t = t0 + r() * (t1 - t0), s = (r() - 0.5) * 1.9, p = abd.at(t, s), tg = abd.tan(t); felt.push(flick(p, Math.atan2(tg[1], tg[0]) + s * 0.5, scale(5 + r() * 3), 0.55 + 0.5 * tubeShade(abd, t, s), 0.3)); } });++ // thorax: form rings under a pelt of flicks radiating from the centre; the fur breaks the silhouette+ const thxTone = (t: number, s: number) => combine(tubeShade(thx, t, s, 0.9), 0.35);+ const thxCuts = rings(thx, 0.04, 0.96, 3.4, thxTone, 1.4, [oHead], 0.25);+ const fur: Cut[] = []; const c0 = thx.at(0.5, 0);+ for (let k = 0; k < 330; k++) { const t = r(), s = (r() * 2 - 1) * 1.08, p = thx.at(t, s); if (oHead && occHit(oHead, p)) continue; const dir = Math.atan2(p[1] - c0[1], p[0] - c0[0]) + (r() - 0.5) * 0.7, tone = thxTone(clamp01(t), s); fur.push(flick(p, dir, scale(5 + r() * 5), 0.4 + 0.95 * tone, (r() - 0.5) * 0.9)); }+ // tegulae: the little scale over each wing root+ const teg = [[-38, -18], [38, -20]].map((q) => contour(Array.from({ length: 12 }, (_, i) => { const u = (i / 12) * 6.28; return B([q[0] + Math.cos(u) * 7, q[1] + Math.sin(u) * 5]); }), 0.6, 1.2, []));++ // head: face rings, big eyes cross-hatched dark with a lit spot left bare, ocelli, mandibles+ const headTone = (t: number, s: number) => combine(tubeShade(head, t, s, 0.6), 0.4);+ const eyeL: P[] = [], eyeR: P[] = []; for (let i = 0; i <= 16; i++) { const t = 0.06 + (i / 16) * 0.74; eyeL.push(head.at(t, 1.03)); eyeR.push(head.at(t, -1.03)); } for (let i = 16; i >= 0; i--) { const u = i / 16, t = 0.06 + u * 0.74, d = 0.12 + 0.36 * Math.pow(Math.sin(Math.PI * u), 0.8); eyeL.push(head.at(t, 1.03 - d)); eyeR.push(head.at(t, -(1.03 - d))); } const eyeLs = smooth(eyeL, true, 3), eyeRs = smooth(eyeR, true, 3); eyeL.length = 0; eyeL.push(...eyeLs); eyeR.length = 0; eyeR.push(...eyeRs);+ const oEyes = [occluder(eyeL), occluder(eyeR)];+ const headCuts = rings(head, 0.05, 0.97, 3.2, headTone, 1.5, oEyes, 0.12);+ const eyeCuts: Cut[] = [];+ [eyeL, eyeR].forEach((ey, ei) => {+ const b = ey.reduce((m, [x, y]) => ({ x0: Math.min(m.x0, x), y0: Math.min(m.y0, y), x1: Math.max(m.x1, x), y1: Math.max(m.y1, y) }), { x0: 1e9, y0: 1e9, x1: -1e9, y1: -1e9 }), cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, hl: P = [cx - (b.x1 - b.x0) * 0.12, cy - (b.y1 - b.y0) * 0.16];+ const inEye = occluder(ey);+ [0.7, -0.5].forEach((ang, pass) => { const ca2 = Math.cos(ang), sa2 = Math.sin(ang), R = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) / 2; for (let v = -R; v <= R; v += 2.2) { const pts: P[] = []; for (let u = -R; u <= R; u += 1.5) pts.push([cx + u * ca2 - v * sa2, cy + u * sa2 + v * ca2]); eyeCuts.push(cutLine(pts, (x, y) => { if (!occHit(inEye, x, y)) return 0; const dh = Math.hypot(x - hl[0], y - hl[1]) / (R * 0.4); return (pass ? 1.0 : 1.25) * clamp01((dh - 0.22) * 2.2) * (ei ? 1.1 : 0.95); }, [], 1.5)); } });+ eyeCuts.push(contour(ey, 0.9, 1.9, []));+ });+ const ocelli = [[0, -58], [-8, -52], [8, -52]].map((q) => contour(Array.from({ length: 10 }, (_, i) => { const u = (i / 10) * 6.28; return B([q[0] + Math.cos(u) * 3, q[1] + Math.sin(u) * 3]); }), 0.6, 1, []));+ const mand = [open(BB([[-9, -104], [-13, -113], [-7, -118]]), 1.6), open(BB([[9, -104], [14, -112], [8, -118]]), 1.6)];+ const headFur: Cut[] = []; for (let k = 0; k < 60; k++) { const t = 0.05 + r() * 0.5, s = (r() - 0.5) * 1.1, p = head.at(t, s); if (oEyes.some((o) => occHit(o, p))) continue; headFur.push(flick(p, Math.atan2(-head.tan(t)[1], -head.tan(t)[0]) + (r() - 0.5) * 1.2, scale(4 + r() * 3), 0.5 + 0.6 * headTone(t, s), 0.4)); }+ // antennae: scape, elbow, a ringed flagellum+ const ant = ([[[-9, -104], [-18, -118], [-21, -130]], [[-21, -130], [-32, -146], [-50, -159], [-68, -164]]] as P[][]).concat([[[9, -104], [19, -116], [24, -128]], [[24, -128], [29, -150], [40, -170], [50, -186]]]);+ const antCuts: Cut[] = []; ant.forEach((seg, i) => { const pts = BB(seg); antCuts.push(open(pts, scale(i % 2 ? 2.4 : 3.2), [], false)); if (i % 2) { const d = dense(smooth(pts, false, 8), 5); d.slice(1, -1).forEach((p, k) => { const q = d[k + 2], dx = q[0] - p[0], dy = q[1] - p[1], l = Math.hypot(dx, dy) || 1; antCuts.push({ pts: [[p[0] - (dy / l) * 1.8, p[1] + (dx / l) * 1.8], [p[0] + (dy / l) * 1.8, p[1] - (dx / l) * 1.8]], w: [0.7, 0.7] }); }); } });++ // wings: outline, veins, a whisper of membrane lines toward the trailing edge+ type Wing = { ctrl: P[]; lead: (t: number) => number; trail: (t: number) => number; veins: P[][]; flip: boolean };+ const FW = [[[0.02, 0.85], [0.3, 0.88], [0.62, 0.9]], [[0.6, 0.9], [0.8, 0.86], [0.95, 0.6], [0.9, 0.45], [0.75, 0.55], [0.6, 0.72], [0.6, 0.9]], [[0.03, 0.35], [0.3, 0.5], [0.6, 0.72]], [[0.03, -0.05], [0.3, -0.05], [0.52, 0.0], [0.68, 0.12], [0.8, 0.3], [0.9, 0.45]], [[0.3, 0.5], [0.3, -0.05]], [[0.45, 0.6], [0.47, -0.02]], [[0.68, 0.66], [0.72, 0.17]], [[0.03, -0.45], [0.28, -0.5], [0.5, -0.55]], [[0.5, -0.55], [0.52, 0.0]], [[0.03, -0.75], [0.2, -0.85]]] as P[][];+ const HW = [[[0.02, 0.85], [0.3, 0.9], [0.55, 0.9]], [[0.03, 0.2], [0.4, 0.25], [0.62, 0.35]], [[0.03, -0.35], [0.38, -0.4]], [[0.4, 0.25], [0.38, -0.4]]] as P[][];+ const wings: Wing[] = [+ { ctrl: [[-30, 6], [-82, 16], [-146, 46]], lead: K([[0, 3], [0.2, 9], [0.6, 11], [0.9, 8], [1, 0]]), trail: K([[0, 5], [0.2, 15], [0.5, 19], [0.8, 15], [0.95, 7], [1, 0]]), veins: HW, flip: false },+ { ctrl: [[30, 4], [88, 10], [150, 30]], lead: K([[0, 3], [0.2, 9], [0.6, 11], [0.9, 8], [1, 0]]), trail: K([[0, 5], [0.2, 15], [0.5, 19], [0.8, 15], [0.95, 7], [1, 0]]), veins: HW, flip: true },+ { ctrl: [[-34, -22], [-102, -24], [-198, -2]], lead: K([[0, 4], [0.2, 11], [0.6, 14], [0.9, 11], [1, 0]]), trail: K([[0, 6], [0.15, 18], [0.45, 25], [0.75, 23], [0.93, 12], [1, 0]]), veins: FW, flip: false },+ { ctrl: [[34, -22], [106, -36], [200, -26]], lead: K([[0, 4], [0.2, 11], [0.6, 14], [0.9, 11], [1, 0]]), trail: K([[0, 6], [0.15, 18], [0.45, 25], [0.75, 23], [0.93, 12], [1, 0]]), veins: FW, flip: true },+ ];+ const wingCuts: Cut[] = [], wingOut: P[][] = [];+ wings.forEach((wg) => {+ // leading edge = +v. For a wing whose spine runs right the frame's +s is the trailing side, so flip.+ const f = frame(BB(wg.ctrl), (t) => scale(wg.flip ? wg.trail(t) : wg.lead(t)), (t) => scale(wg.flip ? wg.lead(t) : wg.trail(t)), 60), V = ([t, v]: P): P => f.at(t, wg.flip ? -v : v);+ wingOut.push(f.outline);+ wingCuts.push(contour(f.outline, 0.45, 0.9, []));+ wg.veins.forEach((vn, i) => { const pts = vn.map(V); wingCuts.push(cutLine(dense(pts.length > 2 ? smooth(pts, false, 6) : pts, 1.6), (_x, _y, k, n) => (i === 0 ? 1.5 : 1.05) * (1 - 0.45 * (k / n)), [], 1.6)); });+ for (let k = 0; k < 7; k++) { const v = -0.25 - k * 0.1, t0 = 0.35 + r() * 0.2, pts: P[] = []; for (let j = 0; j <= 14; j++) pts.push(V([t0 + (0.96 - t0) * (j / 14), v * (1 - 0.3 * (j / 14))])); wingCuts.push(cutLine(pts, (_x, _y, j, n) => 0.42 * Math.sin((Math.PI * (j + 0.5)) / n), [], 1.8)); }+ });++ // contours of the body parts (legs have theirs above)+ const contours = [contour(abd.outline, 0.8, 1.9, [oThx]), contour(head.outline, 0.7, 1.6, oEyes)];++ // cast shadow on the card: horizontal lines under the offset silhouette, feathered at its edge+ const sil = [abd.outline, thx.outline, head.outline, ...wingOut, ...legOutlines, ...pollen];+ const off: P = [scale(40), scale(56)], shadowPolys = sil.map((s) => occluder(s.map(([x, y]) => [x + off[0], y + off[1]] as P))), silOcc = sil.map(occluder);+ const all = sil.flat(), bx0 = Math.min(...all.map((p) => p[0])) + off[0] - 10, bx1 = Math.max(...all.map((p) => p[0])) + off[0] + 10, by0 = Math.min(...all.map((p) => p[1])) + off[1], by1 = Math.max(...all.map((p) => p[1])) + off[1];+ const shade: Cut[] = []; const inS = (x: number, y: number) => shadowPolys.some((o) => occHit(o, x, y));+ for (let y = by0; y <= by1; y += 3.8) { const pts: P[] = []; for (let x = bx0; x <= bx1; x += 2) pts.push([x, y]); shade.push(cutLine(pts, (x, yy) => { if (!inS(x, yy)) return 0; let k = 0; for (const [dx, dy] of [[7, 0], [-7, 0], [0, 7], [0, -7]]) if (inS(x + dx, yy + dy)) k++; return 0.25 + 0.6 * (k / 4) ** 2; }, silOcc, 2)); }++ return {+ passes: [+ [...contours, ...legContours, ...wingCuts.slice(0, 0)], // 1 contours+ [...abdCuts, ...tergLines], // 2 the abdomen+ [...thxCuts, ...headCuts, ...teg, ...ocelli, ...mand], // 3 thorax and head+ [...legPasses, ...antCuts], // 4 legs, antennae+ wingCuts, // 5 wings+ [...abdCross, ...eyeCuts, ...fur, ...felt, ...headFur, ...pollenCuts], // 6 cross-hatch, eyes, fur, pollen+ shade, // 7 cast shadow+ ],+ tint: [...pollen.map((s) => ({ shape: s, color: "#d99a2b", alpha: 0.55 })), { shape: abd.outline, color: "#c98a3c", alpha: 0.22 }, { shape: thx.outline, color: "#a8743a", alpha: 0.16 }],+ bounds: sil.flat(),+ };+};+const occHit = (o: Occluder, x: number | P, y?: number) => { const px = typeof x === "number" ? x : x[0], py = typeof x === "number" ? y! : x[1]; if (px < o.b.x0 || px > o.b.x1 || py < o.b.y0 || py > o.b.y1) return false; let k = false; const pts = o.pts; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[i], b = pts[j]; if (a[1] > py !== b[1] > py && px < ((b[0] - a[0]) * (py - a[1])) / (b[1] - a[1]) + a[0]) k = !k; } return k; };++// ---------------------------------------------------------------- the dog rose+export const rose = (cx: number, cy: number, R: number): Engraving => {+ const r = rng(515), squash = 0.8, Pp = ([u, v]: P): P => [cx + u, cy + v * squash]; // flower plane -> card (a face tilted back)+ type Petal = { a: number; len: number; wide: number; curl: number };+ const petals: Petal[] = [-96, -22, 50, 118, 192].map((d, i) => ({ a: ((d + (r() - 0.5) * 10) * Math.PI) / 180, len: R * (0.92 + r() * 0.12), wide: 0.95 + r() * 0.12, curl: i % 2 ? 1 : -1 }));+ // back petals first: the upper ones lie farther away on a face tilted back+ const order = petals.map((p, i) => ({ p, i, z: Math.sin(p.a) })).sort((x, y) => x.z - y.z);+ const frames = order.map(({ p }) => { const c = Math.cos(p.a), s = Math.sin(p.a), drift = 0.12 * p.curl, ctrl: P[] = [0.1, 0.5, 1].map((u) => { const a2 = p.a + drift * u; return [Math.cos(a2) * p.len * u, Math.sin(a2) * p.len * u] as P; }); void c; void s; return { p, f: frame(ctrl, K([[0, 5], [0.25, 25 * p.wide], [0.65, 47 * p.wide], [0.88, 49 * p.wide], [1, 36 * p.wide]])) }; });+ // a heart-notched petal outline in the plane, then projected+ const petalOutline = (f: Frame): P[] => { const o: P[] = []; for (let i = 0; i <= 30; i++) o.push(f.at((i / 30) * 0.93, 1)); o.push(f.at(0.99, 0.6), f.at(1.0, 0.3), f.at(0.93, 0), f.at(1.0, -0.3), f.at(0.99, -0.6)); for (let i = 30; i >= 0; i--) o.push(f.at((i / 30) * 0.93, -1)); return o.map(Pp); };+ const outs = frames.map(({ f }) => petalOutline(f));+ const occs = outs.map(occluder), disc = Array.from({ length: 28 }, (_, i) => { const u = (i / 28) * 6.28; return Pp([Math.cos(u) * R * 0.2, Math.sin(u) * R * 0.2]); }), oDisc = occluder(disc);+ const petalCuts: Cut[] = [], petalCont: Cut[] = [];+ frames.forEach(({ p, f }, k) => {+ const front = [...occs.slice(k + 1), oDisc];+ const facing = Math.sin(p.a); // lower petals face the viewer and catch less of the upper-left light+ const tone = (t: number, s: number) => clamp01(0.08 + 0.6 * Math.pow(1 - t, 2.2) + 0.28 * Math.pow(Math.abs(s), 3) + 0.14 * facing + 0.12 * Math.max(0, Math.cos(p.a) * 0.8) + (s * p.curl > 0.4 ? 0.12 : 0));+ for (let i = 0; i <= 22; i++) { const s = -0.94 + (1.88 * i) / 22, pts: P[] = []; for (let j = 0; j <= 20; j++) { const t = 0.06 + (0.88 * j) / 20, bend = Math.sin(Math.PI * t) * 3 * s; pts.push(Pp([f.at(t, s)[0] + f.nrm(t)[0] * bend, f.at(t, s)[1] + f.nrm(t)[1] * bend])); } const m = dense(pts, 1.8).length; petalCuts.push(cutLine(pts, (_x, _y, j) => toneW(tone(0.06 + (0.88 * j) / (m - 1), s), 1.35, 0.16), front, 1.8)); }+ petalCont.push(contour(outs[k], 0.6, 1.5, front));+ // a cupped rim: a second line just inside the upper edge where it turns+ const rim: P[] = []; for (let i = 3; i <= 27; i++) rim.push(f.at((i / 30) * 0.93, p.curl * 0.86)); petalCont.push(cutLine(rim.map(Pp), (_x, _y, j, n) => 0.9 * Math.sin((Math.PI * (j + 0.5)) / n), front, 1.6));+ });+ // stamens: filaments leaning out from the disc, each with an anther flick; disc stippled+ const stam: Cut[] = [];+ for (let i = 0; i < 64; i++) { const u = (i / 64) * 6.28 + (r() - 0.5) * 0.12, r0 = R * 0.17, r1 = R * (0.32 + r() * 0.16), bow = (r() - 0.5) * 0.25, p0 = Pp([Math.cos(u) * r0, Math.sin(u) * r0]), pm = Pp([Math.cos(u + bow) * (r0 + r1) / 2, Math.sin(u + bow) * (r0 + r1) / 2]), p1 = Pp([Math.cos(u + bow * 1.5) * r1, Math.sin(u + bow * 1.5) * r1]); stam.push(cutLine(smooth([p0, pm, p1], false, 6), (_x, _y, j, n) => 0.45 + 0.3 * (j / n), [], 1.4)); stam.push(flick(p1, u + 1.2, 3.4, 2.2, 0.5)); }+ for (let i = 0; i < 90; i++) { const u = r() * 6.28, d = Math.sqrt(r()) * R * 0.17, p = Pp([Math.cos(u) * d, Math.sin(u) * d]); if (r() < 0.35 + 0.5 * clamp01((p[0] - cx + p[1] - cy) / (R * 0.3) + 0.5)) stam.push(flick(p, r() * 6.28, 1.6, 1.2, 0)); }+ stam.push(contour(disc, 0.5, 1, []));+ // stem with prickles, a pinnate leaf of three serrate leaflets with a midrib and veins+ const petalOcc = [...occs, oDisc];+ const stemPts: P[] = [[cx + 4, cy + R * 0.5], [cx + 10, cy + R * 1.0], [cx - 4, cy + R * 1.45], [cx - 16, cy + R * 1.9]];+ const stemF = frame(stemPts, () => 3.6);+ const stem: Cut[] = [contour(stemF.outline, 0.6, 1.4, petalOcc), ...rings(stemF, 0.05, 0.98, 3.2, (t, s) => tubeShade(stemF, t, s, 0.2), 0.9, petalOcc, 0.05)];+ [0.35, 0.62, 0.84].forEach((t, i) => { const p = stemF.at(t, i % 2 ? 1 : -1), q = stemF.nrm(t), sg = i % 2 ? 1 : -1; stem.push(cutLine([p, [p[0] + q[0] * sg * 6 - 2, p[1] + q[1] * sg * 6 - 3]], (_x, _y, j, n) => 2.2 * (1 - j / n), [], 1)); });+ const leafCuts: Cut[] = [];+ const rachis: P[] = [stemF.at(0.55, 1), [cx + R * 0.5, cy + R * 1.15], [cx + R * 0.95, cy + R * 1.2]];+ leafCuts.push(open(rachis, 1.4));+ const leaflet = (base: P, dir: number, len: number, w: number, seed: number) => {+ const ctrl: P[] = [0, 0.5, 1].map((u) => [base[0] + Math.cos(dir + 0.1 * u) * len * u, base[1] + Math.sin(dir + 0.1 * u) * len * u] as P), f = frame(ctrl, K([[0, 2], [0.3, w], [0.6, w * 1.02], [0.9, w * 0.5], [1, 0.5]]));+ const o: P[] = []; for (let i = 0; i <= 40; i++) { const t = i / 40, tooth = i % 2 ? 1.12 : 0.95; o.push(f.at(t, tooth)); } for (let i = 40; i >= 0; i--) { const t = i / 40, tooth = i % 2 ? 1.12 : 0.95; o.push(f.at(t, -tooth)); }+ leafCuts.push(contour(o, 0.6, 1.3, petalOcc)); leafCuts.push(cutLine([f.at(0.02, 0), f.at(0.5, 0), f.at(0.95, 0)], (_x, _y, j, n) => 1.0 * (1 - 0.6 * j / n), petalOcc, 1.5));+ for (let i = 1; i < 9; i++) { const t = i / 9.5; [1, -1].forEach((sd) => { const pts: P[] = []; for (let j = 0; j <= 8; j++) { const u = j / 8; pts.push(f.at(Math.min(1, t + u * 0.12), sd * u * 0.92)); } leafCuts.push(cutLine(pts, (_x, _y, j, n) => (sd < 0 ? 0.95 : 0.55) * Math.sin((Math.PI * (j + 0.5)) / n), petalOcc, 1.4)); if (sd < 0) { const q: P[] = []; for (let j = 0; j <= 8; j++) { const u = j / 8; q.push(f.at(Math.min(1, t + 0.05 + u * 0.12), -u * 0.9)); } leafCuts.push(cutLine(q, (_x, _y, j, n) => 0.6 * Math.sin((Math.PI * (j + 0.5)) / n), petalOcc, 1.4)); } }); }+ void seed;+ };+ leaflet(rachis[1], -0.9, R * 0.42, R * 0.13, 1); leaflet(rachis[1], 0.9, R * 0.4, R * 0.12, 2); leaflet(rachis[2], 0.05, R * 0.5, R * 0.15, 3);+ // a small cast shadow of the bloom on the card, down and right+ const offR: P = [R * 0.22, R * 0.3], sh = outs.map((o) => occluder(o.map(([x, y]) => [x + offR[0], y + offR[1]] as P))), shade: Cut[] = [];+ const allP = outs.flat(), x0 = Math.min(...allP.map((p) => p[0])) + offR[0], x1 = Math.max(...allP.map((p) => p[0])) + offR[0], y0 = Math.min(...allP.map((p) => p[1])) + offR[1], y1 = Math.max(...allP.map((p) => p[1])) + offR[1];+ for (let y = y0; y <= y1; y += 3.6) { const pts: P[] = []; for (let x = x0; x <= x1; x += 2) pts.push([x, y]); shade.push(cutLine(pts, (x, yy) => (sh.some((o) => occHit(o, x, yy)) ? 0.55 : 0), [...petalOcc], 2)); }+ return { passes: [[...petalCont], petalCuts, stam, [...stem, ...leafCuts], shade], tint: outs.map((o) => ({ shape: o, color: "#e39aa2", alpha: 0.3 })).concat([{ shape: disc, color: "#e0b83a", alpha: 0.5 }]), bounds: allP };+};diff --git a/engine/src/canvas-core/scrapbookKit.ts b/engine/src/canvas-core/scrapbookKit.tsnew file mode 100644index 0000000..d80ebd2--- /dev/null+++ b/engine/src/canvas-core/scrapbookKit.ts@@ -0,0 +1,171 @@+// SCRAPBOOK KIT. What the archival-ephemera plate needs and core.ts does not have:+// staged() a drawing-process film runner: an ordered list of steps (painter order), each with a+// frame window; every step that is finished, together with all steps before it, is+// baked into ONE rolling base bitmap, so a frame only redraws what is still moving.+// paper torn and scissor-cut edges, fibres and uneven dye, lifted with a soft shadow.+// type a stroke glyph table (capitals, figures, a few signs) set as PRINTED type: slab+// serifs, weight, slant, width and outline are properties of a face, and a face is+// stroked with the canvas pen (never fillText). Typewriter, ransom-note and hand faces.+// burin the copperplate line: a centreline whose width swells with tone and tapers to a+// point at each end, breaking into the paper where the tone falls below a threshold.+// Everything pure: rng(seed) only, no filters, no assets. Candidates for promotion to core.+import { Gfx, fractal, rng, sample, type Ctx, type Env, type Layer, type P } from "./core";+import { bounds, mix, resample } from "./gallery";++export const clamp01 = (v: number) => (v <= 0 ? 0 : v >= 1 ? 1 : v);+export const ease = (t: number) => { const x = clamp01(t); return x >= 1 ? 1 : x * x * (3 - 2 * x); };+export const easeOut = (t: number) => { const x = clamp01(t); return x >= 1 ? 1 : 1 - (1 - x) * (1 - x) * (1 - x); };++// ---------------------------------------------------------------- the process runner+export type Step = { id: string; start: number; end: number; draw: (ctx: Ctx, env: Env, p: number, f: number) => void };+// start < end; p = (f - start) / (end - start) clamped, exactly 1 at or past `end`. A step whose+// end <= 0 is part of frame 0 (the bare ground). `post` runs over everything every frame.+export const staged = (id: string, steps: Step[], post?: (ctx: Ctx, env: Env, f: number) => void) => {+ for (let i = 0; i < steps.length; i++) if (!(steps[i].end > steps[i].start)) throw new Error(`${id}: step ${steps[i].id} has no length`);+ return (ctx: Ctx, f: number, env: Env) => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale);+ let k = 0; while (k < steps.length && steps[k].end <= f) k++;+ // the base holds steps [0, k) fully drawn. Its value is a pure function of (k, scale), and+ // the stored k says which prefix it is, so the key is honest; it only ever rolls forward.+ const key = `${id}:base:${DW}x${DH}`; let c = env.cache.get(key) as { k: number; L: Layer } | undefined;+ if (!c) { c = { k: 0, L: env.canvas(DW, DH) }; env.cache.set(key, c); }+ if (c.k > k) { c.L.ctx.setTransform(1, 0, 0, 1, 0, 0); c.L.ctx.clearRect(0, 0, DW, DH); c.k = 0; }+ for (let i = c.k; i < k; i++) { reset(c.L.ctx); steps[i].draw(c.L.ctx, env, 1, f); }+ c.k = k;+ reset(ctx); ctx.drawImage(c.L.canvas as CanvasImageSource, 0, 0);+ for (let i = k; i < steps.length; i++) { const s = steps[i]; if (f < s.start) continue; const p = f >= s.end ? 1 : clamp01((f - s.start) / (s.end - s.start)); reset(ctx); s.draw(ctx, env, p, f); }+ reset(ctx); post?.(ctx, env, f); reset(ctx);+ };+};+const reset = (c: Ctx) => { c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; };+// every frame on the beat grid, checked at load+export const onGrid = (id: string, frames: number[], dur: number) => { frames.forEach((f) => { if (f % 5 && f > 0) throw new Error(`${id}: cue ${f} is off the 5-frame event grid`); if (f > dur) throw new Error(`${id}: cue ${f} past the end`); }); };++// ---------------------------------------------------------------- paper+const nrmC = (s: P[]): P[] => s.map((_, i) => { const a = s[(i - 1 + s.length) % s.length], b = s[(i + 1) % s.length], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1; return [dy / l, -dx / l]; });+const ring = (s: P[]) => s.reduce((a, p, i) => a + Math.hypot(p[0] - s[(i + 1) % s.length][0], p[1] - s[(i + 1) % s.length][1]), 0);+// a torn edge: the outline resampled finely and bitten by high-frequency noise; `grow` pushes it+// out so the white core of the sheet shows past the dyed face+export const tear = (shape: P[], amp: number, seed: number, grow = 0): P[] => {+ const s = resample([...shape, shape[0]], Math.max(24, Math.round(ring(shape) / 2.4))).slice(0, -1), nr = nrmC(s), r = rng(seed);+ return s.map(([x, y], i) => { const d = (fractal(seed, x, y, 0.08, 0.08, 3) - 0.5) * amp * 2.2 + (r() - 0.5) * amp * 0.7 + grow; return [x + nr[i][0] * d, y + nr[i][1] * d]; });+};+export const scissor = (shape: P[], seed: number, amt = 0.6): P[] => { const s = resample([...shape, shape[0]], Math.max(16, Math.round(ring(shape) / 5))).slice(0, -1), r = rng(seed); return s.map(([x, y]) => [x + (r() - 0.5) * amt, y + (r() - 0.5) * amt]); };+export const path = (c: Ctx, pts: P[], close = true) => { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); if (close) c.closePath(); };+export const rect = (w: number, h: number, cx = 0, cy = 0): P[] => [[cx - w / 2, cy - h / 2], [cx + w / 2, cy - h / 2], [cx + w / 2, cy + h / 2], [cx - w / 2, cy + h / 2]];+// uneven dye, a few fibres and the odd inclusion, clipped to the sheet (raw ctx, current transform)+export const fibres = (c: Ctx, shape: P[], color: string, seed: number, density = 1, blotch = 0.22) => {+ const b = bounds(shape), r = rng(seed), area = (b.x1 - b.x0) * (b.y1 - b.y0);+ c.save(); path(c, shape); c.clip();+ for (let i = 0; i < 6; i++) { const x = b.x0 + r() * (b.x1 - b.x0), y = b.y0 + r() * (b.y1 - b.y0), rx = 30 + r() * 110, g = c.createRadialGradient(x, y, 0, x, y, rx); const col = r() < 0.5 ? mix(color, "#ffffff", 0.25) : mix(color, "#6b4a22", 0.14); g.addColorStop(0, col); g.addColorStop(1, col + "00"); c.globalAlpha = blotch; c.fillStyle = g; c.fillRect(x - rx, y - rx, rx * 2, rx * 2); }+ c.lineCap = "round"; const n = Math.round((area / 1100) * density);+ for (let i = 0; i < n; i++) { const x = b.x0 + r() * (b.x1 - b.x0), y = b.y0 + r() * (b.y1 - b.y0), a = r() * Math.PI, l = 2 + r() * 7; c.strokeStyle = r() < 0.6 ? mix(color, "#fffdf4", 0.5) : mix(color, "#3a2410", 0.28); c.globalAlpha = 0.18 + r() * 0.25; c.lineWidth = 0.4 + r() * 0.5; c.beginPath(); c.moveTo(x, y); c.quadraticCurveTo(x + Math.cos(a) * l * 0.5 + (r() - 0.5) * 2, y + Math.sin(a) * l * 0.5 + (r() - 0.5) * 2, x + Math.cos(a) * l, y + Math.sin(a) * l); c.stroke(); }+ c.restore(); c.globalAlpha = 1;+};+// a soft shadow of `shapes` on whatever is under them: drawn on its own layer and softened+export const shadowOf = (g: Gfx, shapes: P[][], off: P, blur: number, alpha: number, color = "#3b2a14", xf?: (c: Ctx) => void) => {+ g.group("plain", () => { const c = g.cur; c.save(); xf?.(c); c.fillStyle = color; for (const s of shapes) { path(c, s.map(([x, y]) => [x + off[0], y + off[1]] as P)); c.fill(); } c.restore(); shapes.forEach((s) => { const b = bounds(s); g.touch(b.x0 - 80, b.y0 - 80, b.x1 + 80, b.y1 + 80); }); }, { blur, alpha });+};++// ---------------------------------------------------------------- type+// Glyphs on a 4 x 6 cell, y down (after drafting.ts). l = straight polylines, c = curves.+type Glyph = { l?: P[][]; c?: P[][]; w?: number };+const O: P[] = [[1.3, 0.1], [0.2, 1.3], [0.2, 4.7], [1.3, 5.9], [2.7, 5.9], [3.8, 4.7], [3.8, 1.3], [2.7, 0.1], [1.3, 0.1]];+export const GLYPHS: Record<string, Glyph> = {+ A: { l: [[[0, 6], [2, 0], [4, 6]], [[0.8, 3.9], [3.2, 3.9]]] }, B: { l: [[[0, 0], [0, 6]]], c: [[[0, 0], [2.6, 0], [3.5, 0.8], [3.5, 2.2], [2.6, 3], [0, 3]], [[2.6, 3], [3.8, 3.8], [3.8, 5.1], [2.8, 6], [0, 6]]] },+ C: { c: [[[3.8, 1.2], [2.8, 0.1], [1.3, 0.1], [0.2, 1.3], [0.2, 4.7], [1.3, 5.9], [2.8, 5.9], [3.8, 4.8]]] }, D: { l: [[[0, 0], [0, 6]]], c: [[[0, 0], [2.3, 0], [3.8, 1.5], [3.8, 4.5], [2.3, 6], [0, 6]]] },+ E: { l: [[[3.6, 0], [0, 0], [0, 6], [3.7, 6]], [[0, 3], [2.8, 3]]] }, F: { l: [[[3.6, 0], [0, 0], [0, 6]], [[0, 3], [2.8, 3]]] },+ G: { c: [[[3.8, 1.2], [2.8, 0.1], [1.3, 0.1], [0.2, 1.3], [0.2, 4.7], [1.3, 5.9], [2.8, 5.9], [3.8, 4.8]]], l: [[[3.8, 4.9], [3.8, 3.2], [2.2, 3.2]]] },+ H: { l: [[[0, 0], [0, 6]], [[4, 0], [4, 6]], [[0, 3], [4, 3]]] }, I: { l: [[[1, 0], [1, 6]]], w: 2 }, J: { c: [[[3.4, 0], [3.4, 4.8], [2.4, 5.9], [1.2, 5.9], [0.2, 4.8]]] },+ K: { l: [[[0, 0], [0, 6]], [[3.8, 0], [0, 3.7]], [[1.4, 2.5], [3.9, 6]]] }, L: { l: [[[0, 0], [0, 6], [3.6, 6]]] }, M: { l: [[[0, 6], [0, 0], [2.3, 3.8], [4.6, 0], [4.6, 6]]], w: 4.6 },+ N: { l: [[[0, 6], [0, 0], [4, 6], [4, 0]]] }, O: { c: [O] }, P: { l: [[[0, 0], [0, 6]]], c: [[[0, 0], [2.7, 0], [3.7, 0.9], [3.7, 2.4], [2.7, 3.3], [0, 3.3]]] },+ Q: { c: [O], l: [[[2.4, 4.2], [4.1, 6.3]]] }, R: { l: [[[0, 0], [0, 6]], [[2, 3.3], [3.9, 6]]], c: [[[0, 0], [2.7, 0], [3.7, 0.9], [3.7, 2.4], [2.7, 3.3], [0, 3.3]]] },+ S: { c: [[[3.7, 1], [2.7, 0.1], [1.2, 0.1], [0.3, 1], [0.3, 2.1], [1.2, 2.9], [2.8, 3.2], [3.7, 4], [3.7, 5], [2.8, 5.9], [1.2, 5.9], [0.2, 5]]] }, T: { l: [[[0, 0], [4, 0]], [[2, 0], [2, 6]]] },+ U: { c: [[[0, 0], [0, 4.7], [1.2, 5.9], [2.8, 5.9], [4, 4.7], [4, 0]]] }, V: { l: [[[0, 0], [2, 6], [4, 0]]] }, W: { l: [[[0, 0], [1.2, 6], [2.5, 2], [3.8, 6], [5, 0]]], w: 5 },+ X: { l: [[[0, 0], [4, 6]], [[4, 0], [0, 6]]] }, Y: { l: [[[0, 0], [2, 3.1], [4, 0]], [[2, 3.1], [2, 6]]] }, Z: { l: [[[0, 0], [4, 0], [0, 6], [4, 6]]] },+ "0": { c: [[[1.3, 0.1], [0.4, 1.2], [0.4, 4.8], [1.3, 5.9], [2.5, 5.9], [3.4, 4.8], [3.4, 1.2], [2.5, 0.1], [1.3, 0.1]]], w: 3.6 }, "1": { l: [[[0.6, 1.2], [1.8, 0], [1.8, 6]]], w: 2.6 },+ "2": { c: [[[0.3, 1.3], [1.1, 0.2], [2.7, 0.2], [3.5, 1.1], [3.5, 2.2], [0.3, 6]]], l: [[[0.3, 6], [3.7, 6]]], w: 3.7 }, "3": { c: [[[0.4, 0.9], [1.3, 0.1], [2.8, 0.1], [3.5, 1], [3.5, 2.1], [2.6, 3], [1.7, 3]], [[2.6, 3], [3.7, 3.8], [3.7, 5.1], [2.8, 5.9], [1.2, 5.9], [0.3, 5.1]]], w: 3.7 },+ "4": { l: [[[2.8, 6], [2.8, 0], [0.1, 4.3], [3.9, 4.3]]], w: 3.9 }, "5": { l: [[[3.5, 0], [0.7, 0], [0.4, 2.8]]], c: [[[0.4, 2.8], [2.5, 2.5], [3.6, 3.6], [3.6, 5], [2.7, 5.9], [1, 5.9], [0.2, 5.1]]], w: 3.7 },+ "6": { c: [[[3.2, 0.4], [1.5, 0.2], [0.4, 1.4], [0.3, 4.7], [1.2, 5.9], [2.6, 5.9], [3.5, 5], [3.5, 3.8], [2.6, 2.9], [1.2, 2.9], [0.3, 3.8]]], w: 3.7 }, "7": { l: [[[0.3, 0], [3.6, 0], [1.5, 6]]], w: 3.6 },+ "8": { c: [[[1.9, 0.1], [3, 0.4], [3.5, 1.3], [3.3, 2.2], [1.9, 3], [0.5, 2.2], [0.3, 1.3], [0.8, 0.4], [1.9, 0.1]], [[1.9, 3], [3.4, 3.7], [3.7, 4.6], [3.3, 5.5], [1.9, 5.9], [0.5, 5.5], [0.1, 4.6], [0.4, 3.7], [1.9, 3]]], w: 3.8 },+ "9": { c: [[[3.5, 2.5], [2.6, 3.2], [1.2, 3.2], [0.3, 2.3], [0.3, 1.1], [1.2, 0.1], [2.6, 0.1], [3.5, 1.1], [3.5, 4.6], [2.5, 5.8], [0.7, 5.8]]], w: 3.7 },+ "-": { l: [[[0.6, 3.2], [3, 3.2]]], w: 3.4 }, ".": { l: [[[0.7, 5.5], [0.9, 5.9]]], w: 1.8 }, ",": { l: [[[0.9, 5.4], [0.5, 6.8]]], w: 1.8 }, ":": { l: [[[0.7, 2], [0.9, 2.4]], [[0.7, 5.4], [0.9, 5.8]]], w: 1.8 }, "/": { l: [[[0.2, 6.4], [3.2, -0.2]]], w: 3.4 },+ "=": { l: [[[0.4, 2.3], [3.4, 2.3]], [[0.4, 4.1], [3.4, 4.1]]], w: 3.8 }, "~": { c: [[[0.2, 3.6], [0.9, 2.7], [1.7, 3.1], [2.4, 3.6], [3.1, 3.4], [3.7, 2.6]]], w: 3.9 },+ "°": { c: [[[1, -0.1], [0.3, 0.5], [0.4, 1.4], [1.1, 1.8], [1.8, 1.3], [1.8, 0.4], [1, -0.1]]], w: 2.4 }, "·": { l: [[[0.7, 3.0], [0.9, 3.35]]], w: 1.8 },+ "§": { c: [[[3.1, 0.7], [2.4, 0.05], [1.3, 0.1], [0.6, 0.8], [0.9, 1.7], [2.5, 2.4], [3.3, 3.3], [3.0, 4.2], [2.1, 4.5]], [[1.8, 1.55], [0.8, 2.1], [0.6, 3.0], [1.4, 3.7], [2.9, 4.4], [3.3, 5.2], [2.7, 5.9], [1.5, 5.95], [0.8, 5.3]]], w: 3.8 },+ "(": { c: [[[2, -0.4], [0.8, 1.6], [0.8, 4.6], [2, 6.6]]], w: 2.4 }, ")": { c: [[[0.4, -0.4], [1.6, 1.6], [1.6, 4.6], [0.4, 6.6]]], w: 2.4 },+ "'": { l: [[[0.9, -0.2], [0.7, 1.6]]], w: 1.8 }, "+": { l: [[[0.4, 3.2], [3.4, 3.2]], [[1.9, 1.7], [1.9, 4.7]]], w: 3.8 },+ " ": { w: 2.6 },+};+export type Face = { weight: number; slant?: number; wide?: number; serif?: number; outline?: string; cap?: CanvasLineCap; join?: CanvasLineJoin; mono?: number; track?: number };+const glyphOf = (ch: string) => GLYPHS[ch] ?? GLYPHS[ch.toUpperCase()] ?? GLYPHS["-"];+export const advance = (ch: string, face: Face) => ((face.mono ?? glyphOf(ch).w ?? 4) * (face.wide ?? 1) + (face.track ?? 1.3));+export const measure = (text: string, cap: number, face: Face) => [...text].reduce((a, ch) => a + advance(ch, face), 0) * (cap / 6) - (face.track ?? 1.3) * (cap / 6);+// the pen paths of one glyph in cell units, serifs included, as stroke lists+const glyphStrokes = (ch: string, face: Face): P[][] => {+ const gl = glyphOf(ch), out: P[][] = [], sf = face.serif ?? 0;+ (gl.l ?? []).forEach((st) => {+ out.push(st);+ if (sf) [0, st.length - 1].forEach((e) => { const p = st[e], q = st[e === 0 ? 1 : st.length - 2]; if ((p[1] <= 0.05 || p[1] >= 5.95) && Math.abs(q[0] - p[0]) < Math.abs(q[1] - p[1]) * 0.8) out.push([[p[0] - sf, p[1]], [p[0] + sf, p[1]]]); });+ });+ (gl.c ?? []).forEach((st) => out.push(sample(st, false, 6)));+ return out;+};+// set one glyph at (x, y) = top-left of the cap height, in the current transform+export const glyph = (c: Ctx, ch: string, x: number, y: number, cap: number, face: Face, color: string, alpha = 1) => {+ const s = cap / 6, sl = face.slant ?? 0, wd = face.wide ?? 1, cx = face.mono ? ((face.mono - (glyphOf(ch).w ?? 4)) / 2) : 0;+ const T = ([px, py]: P): P => [x + ((px + cx) * wd + (6 - py) * sl) * s, y + py * s];+ const strokes = glyphStrokes(ch, face);+ c.lineCap = face.cap ?? "butt"; c.lineJoin = face.join ?? "miter"; c.miterLimit = 3; c.globalAlpha = alpha;+ const run = (w: number, col: string) => { c.lineWidth = w; c.strokeStyle = col; strokes.forEach((st) => { c.beginPath(); st.forEach((p, i) => { const q = T(p); if (i) c.lineTo(q[0], q[1]); else c.moveTo(q[0], q[1]); }); c.stroke(); }); };+ if (face.outline) { run(face.weight * cap + cap * 0.14, color); run(face.weight * cap, face.outline); } else run(face.weight * cap, color);+ c.globalAlpha = 1;+};+export const TYPEWRITER: Face = { weight: 0.1, serif: 0.55, mono: 4.2, track: 0.9, cap: "butt", join: "round" };+// typed: each strike its own density and a hair off the line, the ribbon printing double faintly.+// `n` = how many characters have been struck (typing is one character at a time).+export const typed = (c: Ctx, text: string, x: number, y: number, cap: number, color: string, seed: number, n = Infinity) => {+ const r = rng(seed), s = cap / 6; let cx = x;+ [...text].forEach((ch, i) => { const dens = 0.72 + r() * 0.28, dy = (r() - 0.5) * cap * 0.06, dx = (r() - 0.5) * cap * 0.03; if (i < n && ch !== " ") { glyph(c, ch, cx + dx + 0.35, y + dy + 0.25, cap, TYPEWRITER, color, dens * 0.3); glyph(c, ch, cx + dx, y + dy, cap, TYPEWRITER, color, dens); } cx += advance(ch, TYPEWRITER) * s; });+};+// a hand-lettered line in a stroke pen (annotation): Gfx pen, so it tapers and wobbles like ink+export const handWrite = (g: Gfx, text: string, x: number, y: number, cap: number, color: string, seed: number, progress = 1, slant = 0.22, w = 2.2) => {+ const s = cap / 6, r = rng(seed * 17 + 3); let cx = x; const all: P[][] = [];+ [...text].forEach((ch) => { const k = 1 + (r() - 0.5) * 0.12, dy = (r() - 0.5) * cap * 0.1, T = ([px, py]: P): P => [cx + (px + (6 - py) * slant) * s * k, y + dy + py * s * k]; glyphStrokes(ch, {} as Face).forEach((st) => all.push(st.map(T))); cx += ((glyphOf(ch).w ?? 4) * 0.92 + 1.1) * s; });+ let left = progress >= 1 ? Infinity : progress * all.length;+ all.forEach((st, i) => { const p = left === Infinity ? 1 : clamp01(left); if (left !== Infinity) left -= 1; if (p > 0) g.pen(st, { w, color, seed: seed + i * 7, wobble: 0.45, boil: 0, taper: 0.5, opacity: 0.92, retrace: false, progress: p }); });+};++// ---------------------------------------------------------------- the burin+export type Cut = { pts: P[]; w: number[] };+// fill one tapering ribbon; the ends come to a point over `tip` samples, as a graver lifts+const ribbonFill = (c: Ctx, s: P[], w: number[], tip = 3) => {+ const n = s.length, L: P[] = [], R: P[] = [];+ for (let i = 0; i < n; i++) {+ const a = s[Math.max(0, i - 1)], b = s[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, e = Math.min(1, (i + 0.6) / tip, (n - i - 0.4) / tip), h = (w[i] * e) / 2;+ L.push([s[i][0] - (dy / l) * h, s[i][1] + (dx / l) * h]); R.push([s[i][0] + (dy / l) * h, s[i][1] - (dx / l) * h]);+ }+ c.beginPath(); L.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); for (let i = n - 1; i >= 0; i--) c.lineTo(R[i][0], R[i][1]); c.closePath(); c.fill();+};+// cut one line: runs where the width is above `min`, each tapering to a point. `upto` 0..1 cuts+// only the first part of it: the graver travelling.+export const burin = (c: Ctx, cut: Cut, min = 0.16, upto = 1) => {+ const m = upto >= 1 ? cut.pts.length : Math.max(0, Math.floor(cut.pts.length * upto)); let run: number[] = [];+ const flush = () => { if (run.length >= 2) ribbonFill(c, run.map((i) => cut.pts[i]), run.map((i) => cut.w[i])); run = []; };+ for (let i = 0; i < m; i++) { if (cut.w[i] > min) run.push(i); else flush(); }+ flush();+};+// draw cuts[0 .. p * cuts.length): whole lines, and the one in progress partly+export const engrave = (c: Ctx, cuts: Cut[], p: number, color: string, min = 0.16) => {+ c.fillStyle = color; const n = p >= 1 ? cuts.length : p * cuts.length, whole = Math.floor(n);+ for (let i = 0; i < whole; i++) burin(c, cuts[i], min);+ if (whole < cuts.length && n > whole) burin(c, cuts[whole], min, n - whole);+};+// a polyline resampled to ~`step` spacing: burin widths need evenly spaced samples+export const dense = (pts: P[], step = 2): P[] => { 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]); return resample(pts, Math.max(2, Math.round(L / step) + 1)); };+export const inPoly = (pts: P[], x: number, y: number) => { let k = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[i], b = pts[j]; if (a[1] > y !== b[1] > y && x < ((b[0] - a[0]) * (y - a[1])) / (b[1] - a[1]) + a[0]) k = !k; } return k; };+export type Occluder = { pts: P[]; b: { x0: number; y0: number; x1: number; y1: number } };+export const occluder = (pts: P[]): Occluder => ({ pts, b: bounds(pts) });+export const hidden = (occ: Occluder[], x: number, y: number) => occ.some((o) => x >= o.b.x0 && x <= o.b.x1 && y >= o.b.y0 && y <= o.b.y1 && inPoly(o.pts, x, y));+// a cut from a centreline and a width function, zeroed where something in front covers it+export const cutLine = (pts: P[], width: (x: number, y: number, i: number, n: number) => number, occ: Occluder[] = [], step = 2): Cut => { const d = dense(pts, step); return { pts: d, w: d.map(([x, y], i) => (hidden(occ, x, y) ? 0 : width(x, y, i, d.length))) }; };diff --git a/engine/src/canvas-core/scratchboard.ts b/engine/src/canvas-core/scratchboard.tsnew file mode 100644index 0000000..6323923--- /dev/null+++ b/engine/src/canvas-core/scratchboard.ts@@ -0,0 +1,188 @@+import { Gfx, PENCIL, rng, sample, type Ctx, type Env, type Layer, type P } from "./core";+import type { Film } from "./film";+import { BODY, EAR_F, EAR_N, EYE_F, EYE_N, HEAD, MOON, NOSE_LEATHER, TUFT_F, TUFT_N, eyeOutline, insidePoly, lynxField, type Eye, type LynxField } from "./scratchboardKit";++// LYNX IN MOONLIGHT · scratchboard. A board of white china clay under a coat of black India ink.+// Nothing is added: every mark is the ink SCRAPED AWAY with a steel knife or a scratch nib, so+// every mark is white on black and the picture is found by removing the dark. The knife cuts a+// clean-edged line that is widest where it bites in and tapers as it lifts; the clay chips a hair+// at the edges. Fur is a tapered white flick cut in the direction the hair grows; hatching runs+// parallel to the form; a second, crossing set of cuts gives the mid tones; the lights are cut so+// densely they become bold scraped areas, and the brightest are scraped flat with the blade.+//+// ORDER. The knife reveals from black: first the contour highlights where the moon catches the+// edges (ears, the lit cheek and ruff, the crown, the far shoulder); then a sparse layer of fur+// flicks everywhere the light reaches, only to set the direction of the coat; then the light+// mass is built, mid tones first, the crossing cuts, then the lights until they close up; last+// the details: the nose leather hatched, the irises, the whiskers, and the catchlights.+//+// PALETTE. Black board (#0c0b0a) and the clay's warm white. No colour, no grey ink: grey is only+// how close together the white cuts are.+// LIGHT. A low moon off the upper right. It rakes across the face: the right cheek, ruff and ear+// catch it, the left side of the face falls away into the board, and the head throws its shadow+// down across the throat and the near shoulder. The only white on the far side is what the moon+// grazes and what a little skylight lifts.+// SUBJECT & REFERENCE: see scratchboardKit.ts (lynx anatomy, markings, and the fields).++const N = 480, HOLD = 30;+// THE CUE TABLE: every frame number of the film. Events on multiples of 5.+const CUES = { rim: [0, 100], direction: [100, 230], mids: [230, 305], cross: [305, 345], lights: [345, 415], detail: [415, 445], catchlight: [445, 450], hold: N - HOLD } as const;+(() => { const bad = Object.entries(CUES).flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).filter((f) => f % 5 || f < 0 || f > N).map((f) => `${k}:${f}`)); if (bad.length || N % 15) throw new Error("scratchboard cue off the grid: " + bad.join(",")); })();++export const BOARD = "#0c0b0a", CLAY = "#ebe5d8";+const TAU = Math.PI * 2, clamp = (v: number, a = 0, b = 1) => (v < a ? a : v > b ? b : v);++// A cut: a centreline and a width profile. `t0..t1` is when the knife makes it (frames).+export type Cut = { pts: P[]; w: number[]; t0: number; t1: number; alpha: number; fill?: boolean };++// ---------------------------------------------------------------- field sampling+const fieldAt = (F: LynxField) => {+ const idx = (x: number, y: number) => Math.max(0, Math.min(F.gh - 1, Math.floor(y / F.G))) * F.gw + Math.max(0, Math.min(F.gw - 1, Math.floor(x / F.G)));+ const bil = (arr: Float32Array, x: number, y: number) => { const fx = x / F.G - 0.5, fy = y / F.G - 0.5, i = Math.max(0, Math.min(F.gw - 2, Math.floor(fx))), j = Math.max(0, Math.min(F.gh - 2, Math.floor(fy))), a = clamp(fx - i), b = clamp(fy - j), q = j * F.gw + i; return (arr[q] * (1 - a) + arr[q + 1] * a) * (1 - b) + (arr[q + F.gw] * (1 - a) + arr[q + F.gw + 1] * a) * b; };+ const dir = (x: number, y: number): P => { const fx = x / F.G - 0.5, fy = y / F.G - 0.5, i = Math.max(0, Math.min(F.gw - 2, Math.floor(fx))), j = Math.max(0, Math.min(F.gh - 2, Math.floor(fy))), a = clamp(fx - i), b = clamp(fy - j), q = j * F.gw + i; let cx = 0, cy = 0; [[q, (1 - a) * (1 - b)], [q + 1, a * (1 - b)], [q + F.gw, (1 - a) * b], [q + F.gw + 1, a * b]].forEach(([k, w]) => { if (F.part[k]) { cx += Math.cos(F.ang[k]) * w; cy += Math.sin(F.ang[k]) * w; } }); const l = Math.hypot(cx, cy) || 1; return [cx / l, cy / l]; };+ return { part: (x: number, y: number) => F.part[idx(x, y)], tone: (x: number, y: number) => (F.part[idx(x, y)] ? bil(F.tone, x, y) : 0), len: (x: number, y: number) => bil(F.len, x, y), dir };+};++// ---------------------------------------------------------------- building every cut, once+const buildCuts = (env: Env): Cut[] => {+ const key = `scratch:cuts:${env.W}`; let C = env.cache.get(key) as Cut[] | undefined; if (C) return C;+ const W = env.W, H = env.H, k = W / 1080, F = lynxField(W, H), fa = fieldAt(F), r = rng(4711);+ const ml = Math.hypot(...MOON), LX = MOON[0] / ml, LY = MOON[1] / ml, lxy = Math.hypot(LX, LY), ux = LX / lxy, uy = LY / lxy;+ const S = (pts: P[]) => pts.map(([x, y]) => [x * k, y * k] as P);+ const cuts: { c: Cut; phase: number; order: number }[] = [];+ const taper = (n: number, w0: number, a = 0.12, b = 0.75) => Array.from({ length: n }, (_, i) => { const t = n > 1 ? i / (n - 1) : 0; return w0 * Math.sqrt(clamp(t / a)) * Math.pow(clamp((1 - t) / b), 0.8) + 0.05; });++ // 1 CONTOUR HIGHLIGHTS: along each silhouette where it faces the moon, a knife line just inside the edge+ const rims = (outline: P[], inset: number, wmax: number, minFace: number, only?: (p: P) => boolean) => {+ const s = sample(S(outline), true, 10), n = s.length, area = s.reduce((a, p, i) => a + p[0] * s[(i + 1) % n][1] - s[(i + 1) % n][0] * p[1], 0), out = area > 0 ? 1 : -1;+ const face = s.map((p, i) => { const a = s[(i - 1 + n) % n], b = s[(i + 1) % n], tx = b[0] - a[0], ty = b[1] - a[1], l = Math.hypot(tx, ty) || 1, nx = (ty / l) * out, ny = (-tx / l) * out; return { nx, ny, f: nx * ux + ny * uy }; });+ let run: P[] = [], fs: number[] = [];+ const flush = () => { if (run.length > 6) { let i = 0; while (i < run.length - 3) { const m = Math.min(run.length - i, 6 + Math.floor(r() * 9)), seg = run.slice(i, i + m), fav = fs.slice(i, i + m).reduce((a, b) => a + b, 0) / m; cuts.push({ c: { pts: seg, w: taper(seg.length, wmax * (0.6 + 0.6 * fav), 0.2, 0.4), t0: 0, t1: 0, alpha: 0.97 }, phase: 0, order: cuts.length }); i += m - 1 - (r() < 0.5 ? 1 : 0); } } run = []; fs = []; };+ s.forEach((p, i) => { const { nx, ny, f } = face[i]; const q: P = [p[0] - nx * inset * k + (r() - 0.5), p[1] - ny * inset * k + (r() - 0.5)]; if (f > minFace && (!only || only(p)) && fa.part(q[0], q[1])) { run.push(q); fs.push(f); } else flush(); });+ flush();+ };+ rims(EAR_N, 2.5, 1.6, 0.05); rims(EAR_F, 2.5, 2.0, 0.0);+ // on fur the contour highlight is not a line: it is a row of short bright flicks cut along the lie of the hair, right at the lit edge+ const rimFur = (outline: P[], minFace: number, only: (p: P) => boolean) => {+ const s = sample(S(outline), true, 24), n = s.length, area = s.reduce((a, p, i) => a + p[0] * s[(i + 1) % n][1] - s[(i + 1) % n][0] * p[1], 0), out = area > 0 ? 1 : -1;+ s.forEach((p, i) => { const a = s[(i - 1 + n) % n], b = s[(i + 1) % n], tx = b[0] - a[0], ty = b[1] - a[1], l = Math.hypot(tx, ty) || 1, nx = (ty / l) * out, ny = (-tx / l) * out, f = nx * ux + ny * uy; if (f < minFace || ny > 0.35 || p[0] > W - 8 || p[1] > H - 8 || !only(p) || r() > 0.85) return; /* not along the underside: the moon cannot reach it */+ const d = 2 + r() * 7, x = p[0] - nx * d, y = p[1] - ny * d; if (!fa.part(x, y)) return; const [fx, fy] = fa.dir(x, y), L = Math.max(5, fa.len(x, y) * (0.35 + 0.45 * r())), ang = Math.atan2(fy + ny * 0.35, fx + nx * 0.35) + (r() - 0.5) * 0.3, pts: P[] = [];+ for (let q = 0; q <= 6; q++) pts.push([x + Math.cos(ang) * L * q / 6 + (r() - 0.5) * 0.4, y + Math.sin(ang) * L * q / 6 + (r() - 0.5) * 0.4]);+ cuts.push({ c: { pts, w: taper(pts.length, 1.1 + 1.1 * f, 0.15, 0.8), t0: 0, t1: 0, alpha: 0.97 }, phase: 0, order: cuts.length }); });+ };+ rimFur(HEAD, 0.2, (p) => p[0] > 600 * k || p[1] > 420 * k); rimFur(BODY, 0.25, (p) => p[1] < 1060 * k && p[0] > 780 * k);+ [TUFT_N, TUFT_F].forEach((t, ti) => [-1.6, 0, 1.4].forEach((o, j) => { const pts = sample(S(t.map(([x, y], i) => [x + o * (1 - i / 3) + (ti ? 1.2 : 0.6), y] as P)), false, 8); cuts.push({ c: { pts, w: taper(pts.length, ti ? 1.3 : 0.9, 0.1, 0.9), t0: 0, t1: 0, alpha: ti ? 0.95 : 0.7 }, phase: 0, order: cuts.length }); })); // tufts: black hair, only its lit edge caught+ // the lit ridges inside the silhouette: the right edge of the nose bridge, the far brow, the top of the far whisker pad+ ([[[584, 430], [588, 470], [592, 506]], [[616, 392], [642, 386], [668, 392]], [[590, 560], [614, 556], [640, 560]], [[608, 604], [590, 618], [566, 626]]] as P[][]).forEach((pl) => { const pts = sample(S(pl), false, 8); cuts.push({ c: { pts, w: taper(pts.length, 1.4, 0.15, 0.6), t0: 0, t1: 0, alpha: 0.9 }, phase: 0, order: cuts.length }); });++ // 2 FUR: variable-radius Poisson seeds (density follows tone), each a streamline flick along the coat+ const cell = 1.3, gw = Math.ceil(W / cell), gh = Math.ceil(H / cell), grid = new Int32Array(gw * gh).fill(-1), xs: number[] = [], ys: number[] = [], ds: number[] = [];+ const wOf = (t: number) => (t < 0.03 ? 0 : 0.34 + 2.3 * Math.pow(t, 1.6)); // the knife bites wider where the light is stronger+ const spacing = (x: number, y: number) => { const t = fa.tone(x, y); if (t < 0.06) return 0; const L = Math.max(4, fa.len(x, y)), w0 = wOf(t), area = L * w0 * 0.5, cov = Math.pow(t, 1.15) * (0.85 + 0.5 * t * t); return clamp(Math.sqrt((0.9 * area) / cov), 1.9, 26); };+ const ok = (x: number, y: number, d: number) => { const reach = Math.ceil((d * 1.2) / cell), gx = Math.floor(x / cell), gy = Math.floor(y / cell); for (let j = Math.max(0, gy - reach); j <= Math.min(gh - 1, gy + reach); j++) for (let i = Math.max(0, gx - reach); i <= Math.min(gw - 1, gx + reach); i++) { const q = grid[j * gw + i]; if (q < 0) continue; const dx = xs[q] - x, dy = ys[q] - y, m = 0.5 * (d + ds[q]); if (dx * dx + dy * dy < m * m) return false; } return true; };+ const add = (x: number, y: number, d: number) => { const q = xs.length; xs.push(x); ys.push(y); ds.push(d); grid[Math.floor(y / cell) * gw + Math.floor(x / cell)] = q; return q; };+ const grow = (q0: number) => { const act = [q0]; while (act.length) { const ai = Math.floor(r() * act.length), q = act[ai]; let found = false; for (let t = 0; t < 16; t++) { const a = r() * TAU, rr = ds[q] * (1 + r()), x = xs[q] + Math.cos(a) * rr, y = ys[q] + Math.sin(a) * rr; if (x < 1 || y < 1 || x >= W - 1 || y >= H - 1) continue; const p = fa.part(x, y); if (!p || p === 4 || p === 5) continue; const d = spacing(x, y); if (!d || !ok(x, y, d)) continue; act.push(add(x, y, d)); found = true; } if (!found) { act[ai] = act[act.length - 1]; act.pop(); } } };+ for (let y = 4; y < H; y += 9) for (let x = 4; x < W; x += 9) { const px = x + (r() - 0.5) * 6, py = y + (r() - 0.5) * 6, p = fa.part(px, py); if (!p || p === 4 || p === 5) continue; const d = spacing(px, py); if (d && ok(px, py, d)) grow(add(px, py, d)); }+ const flick = (x0: number, y0: number, L: number, bend: number, dev: number): P[] => {+ const pts: P[] = [[x0, y0]]; let x = x0, y = y0, s = 0; const step = Math.max(1.2, L / 14);+ while (s < L) { const [dx, dy] = fa.dir(x, y), a = Math.atan2(dy, dx) + dev + bend * (s / L); x += Math.cos(a) * step; y += Math.sin(a) * step; s += step; const p = fa.part(x, y); if (p === 4 || p === 5) break; pts.push([x, y]); }+ return pts;+ };+ xs.forEach((x, i) => {+ const y = ys[i], t = fa.tone(x, y), L = Math.max(4, fa.len(x, y)) * (0.7 + r() * 0.6), rank = r();+ const pts = flick(x, y, L, (r() - 0.5) * 0.5, (r() - 0.5) * 0.24); if (pts.length < 2) return;+ const w0 = wOf(t), tp = taper(pts.length, 1), w = pts.map((p, j) => tp[j] * wOf(fa.tone(p[0], p[1]))); // a hair that crosses a dark bar thins out as it crosses it+ cuts.push({ c: { pts, w, t0: 0, t1: 0, alpha: 0.9 + 0.08 * r() }, phase: rank < 0.34 ? 1 : t < 0.5 ? 2 : 4, order: 0 });+ // 3 CROSS-HATCH for the mid tones: a shorter, straighter cut across the lie of the fur+ const mid = clamp(1 - Math.abs(t - 0.38) / 0.22);+ if (mid > 0 && r() < 0.6 * mid) { const [dx, dy] = fa.dir(x, y), a = Math.atan2(dy, dx) + (r() < 0.5 ? 0.62 : -0.62), l = L * 0.5, cx = x + dx * L * 0.3, cy = y + dy * L * 0.3; const cp = [[cx - Math.cos(a) * l / 2, cy - Math.sin(a) * l / 2], [cx, cy], [cx + Math.cos(a) * l / 2, cy + Math.sin(a) * l / 2]] as P[]; cuts.push({ c: { pts: cp, w: taper(3, 0.75 * w0, 0.2, 0.6), t0: 0, t1: 0, alpha: 0.85 }, phase: 3, order: 0 }); }+ });++ // 4 DETAIL. Nose leather: parallel cuts that follow its dome, lit toward the moon, nostrils left black+ const nose = S(NOSE_LEATHER), nb = { x0: 530 * k, x1: 604 * k, y0: 512 * k, y1: 560 * k };+ for (let yy = nb.y0 + 1; yy < nb.y1; yy += 1.9 * k) { const run: P[] = []; for (let xx = nb.x0; xx <= nb.x1; xx += 1.5 * k) { const yb = yy + Math.pow((xx - 567 * k) / (38 * k), 2) * 6 * k, lit = clamp(0.2 + ((xx - 560 * k) * ux - (yb - 520 * k) * -uy) / (40 * k)), nostril = Math.hypot((xx - 553 * k) / 7, (yb - 544 * k) / 4) < k || Math.hypot((xx - 582 * k) / 7, (yb - 543 * k) / 4) < k; if (insidePoly(nose, xx, yb) && !nostril && lit + 0.35 * (1 - (yb - nb.y0) / (nb.y1 - nb.y0)) > 0.3 + 0.3 * r()) run.push([xx, yb]); else if (run.length) { if (run.length > 2) cuts.push({ c: { pts: run.slice(), w: taper(run.length, 0.8, 0.2, 0.5), t0: 0, t1: 0, alpha: 0.8 }, phase: 5, order: 0 }); run.length = 0; } } if (run.length > 2) cuts.push({ c: { pts: run.slice(), w: taper(run.length, 0.8, 0.2, 0.5), t0: 0, t1: 0, alpha: 0.8 }, phase: 5, order: 0 }); }+ // irises: wide round moonlight pupils, the iris a ring of radial cuts, lit on the side AWAY from the catchlight+ const iris = (e: Eye, bright: number, seed: number) => {+ const out = S(eyeOutline(e, 56)), c: P = [e.pupil[0] * k, e.pupil[1] * k], pr = e.pr * k, rr = rng(seed), litA = Math.atan2(uy * -1, ux * -1);+ for (let i = 0; i < 90; i++) { const a = (i / 90) * TAU + (rr() - 0.5) * 0.05, g = 0.2 + 0.8 * Math.pow(Math.max(0, Math.cos(a - litA)), 1.4); if (rr() > g * bright + 0.12) continue; const pts: P[] = []; for (let d = pr + 1.4; d < pr + 30 * k; d += 1.2) { const p: P = [c[0] + Math.cos(a) * d, c[1] + Math.sin(a) * d]; if (!insidePoly(out, p[0], p[1])) break; pts.push(p); } if (pts.length > 2) { const inner = pts.slice(0, Math.max(2, pts.length - 2)); cuts.push({ c: { pts: inner, w: taper(inner.length, 0.55 + 0.4 * g * bright, 0.2, 0.4), t0: 0, t1: 0, alpha: 0.85 }, phase: 6, order: 0 }); } }+ };+ iris(EYE_N, 0.55, 81); iris(EYE_F, 1, 82);+ // whiskers: long, fine, slightly curved, from the spot rows out past the ruff; brow whiskers above each eye+ const whisk = (from: P, to: P, sag: number, w: number, al: number) => { const m: P = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2 + sag], pts = sample(S([from, m, to]), false, 18); cuts.push({ c: { pts, w: taper(pts.length, w, 0.05, 0.95), t0: 0, t1: 0, alpha: al }, phase: 7, order: 0 }); };+ [[498, 574, 318, 566, 14], [502, 584, 300, 616, 18], [506, 594, 330, 668, 18], [496, 566, 350, 526, 10]].forEach(([x0, y0, x1, y1, s]) => whisk([x0, y0], [x1, y1], s, 0.95, 0.6));+ [[634, 572, 870, 552, 14], [636, 580, 886, 600, 18], [632, 588, 866, 648, 20], [628, 595, 830, 690, 16], [636, 564, 840, 508, 10]].forEach(([x0, y0, x1, y1, s]) => whisk([x0, y0], [x1, y1], s, 1.25, 0.95));+ [[470, 396, 400, 326, -8], [490, 392, 440, 312, -6], [650, 392, 716, 318, -8], [634, 390, 672, 308, -6]].forEach(([x0, y0, x1, y1, s]) => whisk([x0, y0], [x1, y1], s, 0.9, 0.85));+ // catchlights: the moon in each cornea, scraped flat with the blade. Last cut of all.+ [[EYE_F, 1], [EYE_N, 0.7]].forEach(([e0, sc]) => { const e = e0 as Eye, s = sc as number, c: P = [(e.pupil[0] + e.pr * 0.5) * k, (e.pupil[1] - e.pr * 0.5) * k], R = 5.2 * s * k, pts: P[] = Array.from({ length: 9 }, (_, i) => { const a = (i / 9) * TAU; return [c[0] + Math.cos(a) * R * (1 + 0.12 * Math.sin(a * 2)), c[1] + Math.sin(a) * R * 0.85] as P; }); cuts.push({ c: { pts, w: [], t0: 0, t1: 0, alpha: 0.98, fill: true }, phase: 8, order: 0 }); const c2: P = [(e.pupil[0] - e.pr * 0.55) * k, (e.pupil[1] + e.pr * 0.6) * k], p2: P[] = Array.from({ length: 7 }, (_, i) => [c2[0] + Math.cos((i / 7) * TAU) * 1.6 * s * k, c2[1] + Math.sin((i / 7) * TAU) * 1.3 * s * k] as P); cuts.push({ c: { pts: p2, w: [], t0: 0, t1: 0, alpha: 0.8, fill: true }, phase: 8, order: 0 }); });++ // SCHEDULE: within a phase the hand works region by region (patches, snaking), then the timeline+ const PATCH = 96 * k, patch = (p: P) => { const py = Math.floor(p[1] / PATCH), px = Math.floor(p[0] / PATCH); return py * 64 + (py % 2 ? 63 - px : px); };+ const win: [number, number][] = [[CUES.rim[0], CUES.rim[1]], [CUES.direction[0], CUES.direction[1]], [CUES.mids[0], CUES.mids[1]], [CUES.cross[0], CUES.cross[1]], [CUES.lights[0], CUES.lights[1]], [CUES.detail[0], CUES.detail[0] + 10], [CUES.detail[0] + 5, CUES.detail[0] + 15], [CUES.detail[0] + 10, CUES.detail[1]], [CUES.catchlight[0], CUES.catchlight[1]]];+ for (let ph = 0; ph < win.length; ph++) {+ const list = cuts.filter((c) => c.phase === ph); if (!list.length) continue;+ if (ph > 0) list.sort((a, b) => patch(a.c.pts[0]) - patch(b.c.pts[0]) || a.c.pts[0][1] - b.c.pts[0][1]);+ const [a, b] = win[ph], lens = list.map((c) => { let l = 0; for (let i = 1; i < c.c.pts.length; i++) l += Math.hypot(c.c.pts[i][0] - c.c.pts[i - 1][0], c.c.pts[i][1] - c.c.pts[i - 1][1]); return l; });+ if (ph === 0 || ph === 7) { // the long knife lines are watched being cut: time ~ length, long strokes quicker per pixel+ const cost = lens.map((l) => 1.5 + Math.pow(l, 0.7)), tot = cost.reduce((x, y) => x + y, 0); let t = a;+ list.forEach((c, i) => { const d = ((b - a) * cost[i]) / tot; c.c.t0 = t; c.c.t1 = t + Math.max(d, 0.5); t += d; });+ } else list.forEach((c, i) => { const f = a + ((b - a) * (i + 1)) / list.length; c.c.t0 = f - 1; c.c.t1 = f; });+ }+ C = cuts.map((c) => c.c).sort((x, y) => x.t1 - y.t1);+ env.cache.set(key, C);+ return C;+};++// ---------------------------------------------------------------- the knife+export const ribbon = (c0: Cut, prog = 1): P[] => {+ let c = c0;+ if (prog < 1) { const n0 = c0.pts.length, u = (n0 - 1) * prog, i = Math.floor(u), f = u - i, a = c0.pts[i], b = c0.pts[Math.min(n0 - 1, i + 1)]; c = { ...c0, pts: [...c0.pts.slice(0, i + 1), [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f]], w: [...c0.w.slice(0, i + 1), c0.w[Math.min(n0 - 1, i + 1)] ?? 0.5] }; prog = 1; } /* the tip travels continuously, not point to point */+ const n = c.pts.length, m = prog >= 1 ? n : Math.max(2, Math.floor(n * prog) + 1), L: P[] = [], R: P[] = [];+ for (let i = 0; i < Math.min(m, n); i++) { const a = c.pts[Math.max(0, i - 1)], b = c.pts[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, w = (c.w[i] ?? 0.5) / 2 * (prog < 1 && i === m - 1 ? 0.4 : 1); L.push([c.pts[i][0] - (dy / l) * w, c.pts[i][1] + (dx / l) * w]); R.push([c.pts[i][0] + (dy / l) * w, c.pts[i][1] - (dx / l) * w]); }+ return [...L, ...R.reverse()];+};+export const trace = (path: Path2D, pts: P[]) => { path.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) path.lineTo(pts[i][0], pts[i][1]); path.closePath(); };+const CHUNK = 500;+const cutRange = (ctx: Ctx, env: Env, C: Cut[], from: number, to: number) => {+ ctx.fillStyle = CLAY;+ for (let a = from; a < to; a += CHUNK) {+ const b = Math.min(to, a + CHUNK);+ for (const hi of [0, 1]) { // two alpha classes: a fine hair cut is a touch greyer than a bold one+ const pk = `scratch:path:${a}:${b}:${hi}`; let path = env.cache.get(pk) as Path2D | undefined;+ if (!path) { path = new Path2D(); for (let i = a; i < b; i++) if ((C[i].alpha > 0.9 ? 1 : 0) === hi) trace(path, C[i].fill ? C[i].pts : ribbon(C[i])); if (b - a === CHUNK) env.cache.set(pk, path); }+ ctx.globalAlpha = hi ? 0.97 : 0.8; ctx.fill(path);+ }+ }+ ctx.globalAlpha = 1;+};++const layerOf = (env: Env, key: string): Layer => { let L = env.cache.get(key) as Layer | undefined; if (!L) { L = env.canvas(Math.round(env.W * env.scale), Math.round(env.H * env.scale)); env.cache.set(key, L); } return L; };++export const drawScratchboard = (ctx: Ctx, frame: number, env: Env) => {+ const C = buildCuts(env), DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), f = Math.min(frame, CUES.hold);+ const fk = `scratch:final:${env.scale}`, done = f >= CUES.hold;+ if (done && env.cache.has(fk)) { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage((env.cache.get(fk) as Layer).canvas as CanvasImageSource, 0, 0); return; }+ let lo = 0, hi = C.length; while (lo < hi) { const m = (lo + hi) >> 1; if (C[m].t1 <= f) lo = m + 1; else hi = m; }+ const n = done ? C.length : lo;+ // everything already cut sits on a checkpoint layer that is a pure function of its cut count+ const CK = 4000, c = Math.floor(n / CK) * CK;+ const ck = (m: number): Layer => { const key = `scratch:ck:${m}:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L; L = env.canvas(DW, DH); L.ctx.setTransform(1, 0, 0, 1, 0, 0); if (m > CK) L.ctx.drawImage(ck(m - CK).canvas as CanvasImageSource, 0, 0); L.ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); cutRange(L.ctx, env, C, m - CK, m); env.cache.set(key, L); return L; };+ const S = layerOf(env, `scratch:work:${env.scale}`), sc = S.ctx;+ sc.setTransform(1, 0, 0, 1, 0, 0); sc.globalCompositeOperation = "source-over"; sc.globalAlpha = 1; sc.clearRect(0, 0, DW, DH);+ if (c > 0) sc.drawImage(ck(c).canvas as CanvasImageSource, 0, 0);+ sc.setTransform(env.scale, 0, 0, env.scale, 0, 0); cutRange(sc, env, C, c, n);+ if (!done) { sc.fillStyle = CLAY; for (let i = n; i < C.length && C[i].t0 < f; i++) { const p = (f - C[i].t0) / (C[i].t1 - C[i].t0); if (p <= 0 || C[i].fill) continue; const path = new Path2D(); trace(path, ribbon(C[i], p)); sc.globalAlpha = C[i].alpha > 0.9 ? 0.97 : 0.8; sc.fill(path); } sc.globalAlpha = 1; } // the cuts the knife is in the middle of+ const out = done ? layerOf(env, fk) : null, o = out ? out.ctx : ctx;+ o.setTransform(1, 0, 0, 1, 0, 0); o.globalAlpha = 1; o.globalCompositeOperation = "source-over"; o.fillStyle = BOARD; o.fillRect(0, 0, DW, DH);+ o.globalAlpha = 0.55; o.drawImage(S.canvas as CanvasImageSource, 0, 0); o.globalAlpha = 1; // the cut, clean+ new Gfx(sc, env, 0, PENCIL).tooth(S as never, "draftTooth", [0, 0, DW, DH]); // and the clay chipping at its edges, so a cut is never a vector line+ o.drawImage(S.canvas as CanvasImageSource, 0, 0);+ if (out) { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(out.canvas as CanvasImageSource, 0, 0); }+};++export const scratchboard: Film = {+ meta: { title: "Lynx in moonlight · scratchboard", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "scratchboard", start: 0, end: N, draw: drawScratchboard }],+};++export const STYLE = { id: "scratchboard", name: "Scratchboard", family: "ink", medium: "white china clay under black India ink; every mark is ink scraped away with a knife or scratch nib", nearest: "mellan", hero: "a lynx, head and shoulders, in moonlight" };diff --git a/engine/src/canvas-core/scratchboardKit.ts b/engine/src/canvas-core/scratchboardKit.tsnew file mode 100644index 0000000..9703521--- /dev/null+++ b/engine/src/canvas-core/scratchboardKit.ts@@ -0,0 +1,163 @@+// SCRATCHBOARD KIT. The lynx as FIELDS, no marks: where the animal is (part), how much moonlight+// reaches each point of its fur (tone: 0 = the board stays black, 1 = scraped to white clay),+// which way the fur lies there (ang), and how long the hair is (len). The plate cuts marks from them.+//+// Anatomy (Eurasian lynx, Lynx lynx; head and shoulders, turned ~15 degrees to the viewer's right,+// chin a touch up toward a moon off the upper right). Tall triangular ears set at the top corners+// of the skull, black-rimmed, white hair filling the openings, each ending in a long black tuft.+// A broad flat forehead with dark vertical streaks; large wide-set almond eyes, the inner corner+// lower and drawn down toward the nose, ringed above and below in pale fur, a dark line running+// from the outer corner back into the cheek; in moonlight the pupils are wide and round. A broad+// nose bridge, a small nose leather with slit nostrils, a black lip line that drops from the+// philtrum; puffed white whisker pads carrying rows of dark spots; a small white chin. The facial+// ruff: long hair that flares from below the ears and hangs in two barred, pointed sideburns+// either side of the chin; thick neck fur, a pale throat, the heavy shoulder mass below.+// Reference: from knowledge of lynx portrait photographs (Lynx lynx, Lynx canadensis) and+// scratchboard wildlife portraiture (fur as tapered white flicks cut in the direction of growth).+import { sample, type P } from "./core";++export type LynxField = { W: number; H: number; G: number; gw: number; gh: number; tone: Float32Array; ang: Float32Array; len: Float32Array; part: Uint8Array };+// part: 0 board, 1 head, 2 ear, 3 body, 4 eye (never scraped by fur), 5 nose leather (hatched, not furred)+const clamp = (v: number, a = 0, b = 1) => (v < a ? a : v > b ? b : v);+const sstep = (a: number, b: number, v: number) => { const t = clamp((v - a) / (b - a)); return t * t * (3 - 2 * t); };++// ---------------------------------------------------------------- authored shapes (1080 space)+// the head with its ruff, clockwise from the near (left) ear's outer base+export const HEAD: P[] = [[400, 342], [384, 374], [352, 410], [322, 452], [306, 500], [308, 548], [320, 600], [338, 650], [360, 700], [382, 746], [408, 722], [446, 724], [480, 750], [512, 722], [546, 706], [566, 712], [588, 706], [622, 728], [654, 748], [686, 722], [724, 736], [748, 690], [760, 650], [768, 610], [786, 560], [798, 506], [794, 456], [778, 410], [758, 376], [742, 348], [700, 302], [640, 282], [566, 276], [494, 284], [440, 302], [412, 322]];+export const EAR_N: P[] = [[392, 352], [392, 290], [396, 230], [403, 184], [410, 156], [418, 152], [440, 188], [466, 236], [492, 290], [440, 306]];+export const EAR_F: P[] = [[642, 290], [670, 236], [698, 190], [716, 158], [724, 152], [732, 176], [738, 232], [744, 296], [748, 356], [700, 304]];+export const TUFT_N: P[] = [[414, 156], [410, 124], [403, 96], [392, 66]], TUFT_F: P[] = [[722, 156], [727, 124], [734, 96], [746, 68]];+export const BODY: P[] = [[330, 500], [312, 600], [282, 700], [224, 800], [124, 900], [10, 970], [-30, 990], [-30, 1110], [1110, 1110], [1110, 940], [1060, 900], [960, 820], [880, 730], [830, 640], [796, 540], [700, 700], [566, 720], [430, 700]];+// eyes as four authored points each: inner corner, top of the lid, outer corner, bottom of the lid+export type Eye = { inner: P; top: P; outer: P; bottom: P; pupil: P; pr: number };+export const EYE_N: Eye = { inner: [528, 448], top: [484, 415], outer: [438, 420], bottom: [486, 460], pupil: [485, 437], pr: 16 };+export const EYE_F: Eye = { inner: [602, 446], top: [638, 413], outer: [680, 416], bottom: [642, 456], pupil: [641, 434], pr: 14.5 };+export const NOSE: P = [566, 536];+export const NOSE_LEATHER: P[] = [[540, 522], [566, 516], [594, 520], [598, 532], [584, 548], [567, 556], [550, 548], [536, 534]];+export const MOON: [number, number, number] = [0.84, -0.46, 0.3]; // to the moon: upper right, low: it rakes across the face++export const eyeOutline = (e: Eye, n = 40): P[] => sample([e.inner, [(e.inner[0] + e.top[0]) / 2, e.top[1] + 4], e.top, [(e.top[0] + e.outer[0]) / 2, (e.top[1] + e.outer[1]) / 2 - 2], e.outer, [(e.outer[0] + e.bottom[0]) / 2, e.bottom[1] - 3], e.bottom, [(e.bottom[0] + e.inner[0]) / 2, e.bottom[1] - 1]], true, Math.ceil(n / 8));++// ---------------------------------------------------------------- grid helpers+const fillPoly = (grid: Uint8Array, gw: number, gh: number, G: number, pts0: P[], val: number) => {+ const pts = sample(pts0, true, 8);+ for (let j = 0; j < gh; j++) {+ const y = j * G + G / 2, xs: number[] = [];+ for (let i = 0, k = pts.length - 1; i < pts.length; k = i++) { const a = pts[i], b = pts[k]; if ((a[1] > y) !== (b[1] > y)) xs.push(a[0] + ((y - a[1]) * (b[0] - a[0])) / (b[1] - a[1])); }+ xs.sort((a, b) => a - b);+ for (let q = 0; q + 1 < xs.length; q += 2) for (let i = Math.max(0, Math.ceil((xs[q] - G / 2) / G)); i <= Math.min(gw - 1, Math.floor((xs[q + 1] - G / 2) / G)); i++) grid[j * gw + i] = val;+ }+};+const distIn = (m: Uint8Array, gw: number, gh: number, test: (v: number) => boolean): Float32Array => {+ const d = new Float32Array(gw * gh), BIG = 1e6;+ for (let i = 0; i < d.length; i++) d[i] = test(m[i]) ? BIG : 0;+ for (let j = 0; j < gh; j++) for (let i = 0; i < gw; i++) { const k = j * gw + i; if (!d[k]) continue; let v = d[k]; if (i) v = Math.min(v, d[k - 1] + 1); if (j) v = Math.min(v, d[k - gw] + 1); if (i && j) v = Math.min(v, d[k - gw - 1] + 1.414); if (j && i < gw - 1) v = Math.min(v, d[k - gw + 1] + 1.414); d[k] = v; }+ for (let j = gh - 1; j >= 0; j--) for (let i = gw - 1; i >= 0; i--) { const k = j * gw + i; if (!d[k]) continue; let v = d[k]; if (i < gw - 1) v = Math.min(v, d[k + 1] + 1); if (j < gh - 1) v = Math.min(v, d[k + gw] + 1); if (i < gw - 1 && j < gh - 1) v = Math.min(v, d[k + gw + 1] + 1.414); if (j < gh - 1 && i) v = Math.min(v, d[k + gw - 1] + 1.414); d[k] = v; }+ return d;+};+export const segDist = (x: number, y: number, pl: P[]) => { let best = 1e9; for (let i = 1; i < pl.length; i++) { const a = pl[i - 1], b = pl[i], dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy || 1, t = clamp(((x - a[0]) * dx + (y - a[1]) * dy) / l2), d = Math.hypot(a[0] + dx * t - x, a[1] + dy * t - y); if (d < best) best = d; } return best; };+const gauss = (x: number, y: number, c: P, sx: number, sy: number, rot = 0) => { const dx = x - c[0], dy = y - c[1], cs = Math.cos(rot), sn = Math.sin(rot), u = (dx * cs + dy * sn) / sx, v = (-dx * sn + dy * cs) / sy; return Math.exp(-(u * u + v * v)); };+export const insidePoly = (pts: P[], x: number, y: number) => { let k = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const a = pts[i], b = pts[j]; if (a[1] > y !== b[1] > y && x < ((b[0] - a[0]) * (y - a[1])) / (b[1] - a[1]) + a[0]) k = !k; } return k; };++// ---------------------------------------------------------------- fur flow: hand-placed anchors, inverse-distance weighted+// [x, y, angle in degrees (0 = right, 90 = down), weight]+const FLOW: [number, number, number, number][] = [+ [566, 480, -90, 1.4], [566, 420, -90, 1.2], [566, 360, -92, 1], [520, 340, -105, 1], [612, 338, -78, 1], [470, 330, -120, 1], [660, 320, -60, 1], [566, 300, -90, 1], // bridge and forehead, fanning to the ears+ [520, 400, -150, 1], [610, 398, -30, 1], // over the brows+ [430, 470, 175, 1], [460, 500, 165, 1], [680, 466, 5, 1], [650, 500, 15, 1], // cheeks run back from the eyes+ [380, 500, 112, 1.3], [360, 570, 96, 1.3], [390, 640, 72, 1.2], [450, 684, 52, 1.1], [500, 660, 70, 1], // near ruff: out, down, and in toward the chin+ [750, 480, 68, 1.3], [760, 560, 86, 1.3], [792, 500, 82, 1.6], [792, 560, 94, 1.6], [772, 624, 112, 1.4], [318, 520, 98, 1.6], [326, 600, 82, 1.4], [730, 640, 108, 1.2], [680, 680, 128, 1.1], [640, 660, 110, 1], // far ruff+ [520, 580, 150, 1], [612, 578, 30, 1], [566, 612, 90, 1], // whisker pads sweep out and down, chin down+ [566, 740, 90, 1], [470, 780, 100, 1], [680, 780, 80, 1], [566, 900, 90, 1], // throat and chest+ [340, 460, 130, 1], [250, 600, 130, 1], [140, 740, 142, 1], [260, 860, 112, 1], [120, 960, 115, 1], [400, 900, 100, 1], // neck and near shoulder+ [820, 700, 60, 1], [920, 790, 40, 1], [1000, 880, 60, 1], [780, 900, 85, 1], // far shoulder+ [420, 250, -80, 1.3], [400, 210, -86, 1], [445, 280, -60, 1], [712, 240, -84, 1.3], [700, 280, -110, 1], [736, 270, -92, 1], // ears: base toward the tip+];+const LEN: [number, number, number][] = [+ [566, 536, 5], [566, 470, 8], [566, 380, 11], [566, 300, 13], [485, 436, 5], [640, 434, 5], [520, 575, 8], [612, 572, 8], [566, 612, 10],+ [440, 480, 20], [690, 476, 20], [360, 540, 50], [400, 650, 58], [770, 520, 44], [730, 640, 52], [566, 690, 34], [566, 820, 40], [300, 560, 34], [160, 760, 30], [300, 920, 26], [900, 800, 30],+ [420, 240, 11], [712, 240, 11],+];+const idw = (pts: number[][], x: number, y: number, f: (p: number[], w: number) => void) => { for (const p of pts) { const d2 = (x - p[0]) ** 2 + (y - p[1]) ** 2 + 400; f(p, (p[3] ?? 1) / (d2 * d2)); } };++// MARKINGS, evaluated once per grid cell inside their own box: [kind, geometry, width/size, amount]+type Mark = { box: [number, number, number, number]; f: (x: number, y: number, a: number) => number };+const lineM = (pl: P[], w: number, dark: number): Mark => { const xs = pl.map((p) => p[0]), ys = pl.map((p) => p[1]); return { box: [Math.min(...xs) - w, Math.min(...ys) - w, Math.max(...xs) + w, Math.max(...ys) + w], f: (x, y, a) => { const d = segDist(x, y, pl); return d < w ? a * (1 - dark * sstep(w, w * 0.3, d)) : a; } }; };+const spotM = (c: P, r: number, dark: number): Mark => ({ box: [c[0] - r, c[1] - r, c[0] + r, c[1] + r], f: (x, y, a) => { const d = Math.hypot(x - c[0], y - c[1]); return d < r ? a * (1 - dark * sstep(r, r * 0.35, d)) : a; } });+const paleM = (c: P, sx: number, sy: number, to: number): Mark => ({ box: [c[0] - sx * 2.2, c[1] - sy * 2.2, c[0] + sx * 2.2, c[1] + sy * 2.2], f: (x, y, a) => a + (to - a) * clamp(gauss(x, y, c, sx, sy) * 1.7) });+const HEAD_MARKS: Mark[] = [+ paleM([566, 576], 64, 34, 1.05), paleM([566, 624], 34, 24, 1.05), // white whisker pads, white chin+ paleM([484, 466], 44, 13, 1.05), paleM([642, 462], 40, 13, 1.05), paleM([486, 400], 40, 11, 0.95), paleM([640, 398], 36, 11, 0.95), paleM([352, 560], 40, 110, 0.75), paleM([774, 560], 34, 100, 0.8), /* the ruff's pale hair between its bars */ // pale fur above and below each eye+ lineM([[442, 426], [420, 446], [398, 478], [386, 516]], 10, 0.85), lineM([[676, 424], [700, 444], [720, 474], [730, 510]], 9, 0.8), // the dark line back from each eye's outer corner+ ...[[[540, 384], [534, 340], [530, 300]], [[556, 382], [555, 336], [554, 290]], [[578, 382], [580, 336], [582, 290]], [[594, 384], [602, 342], [608, 302]]].map((pl) => lineM(pl as P[], 6, 0.75)), // forehead streaks+ ...[[[330, 470], [328, 540], [350, 620], [386, 690]], [[362, 480], [366, 552], [392, 624], [440, 690]], [[780, 470], [780, 540], [760, 612], [716, 668]], [[750, 482], [752, 552], [730, 616], [684, 672]]].map((pl) => lineM(pl as P[], 12, 0.88)), // the ruff's two bars each side+ lineM([[566, 556], [566, 576], [548, 590], [522, 596], [506, 592]], 3, 0.95), lineM([[566, 576], [586, 590], [610, 594], [624, 588]], 3, 0.95), // lip line+ ...Array.from({ length: 12 }, (_, i) => { const r = Math.floor(i / 4), c = i % 4; return [spotM([530 - c * 11 - r * 3, 568 + r * 9 + c * 1.5], 2.4, 0.9), spotM([602 + c * 11 + r * 3, 566 + r * 9 + c * 1.5], 2.4, 0.9)]; }).flat(), // whisker-spot rows+ ...[[420, 520], [436, 552], [404, 548], [700, 520], [684, 548], [712, 552], [540, 330], [596, 332]].map((c) => spotM(c as P, 5, 0.4)), // faint cheek and crown spots+];+// smooth a grid in place (separable box, a few passes): anatomy has no creases+const blurGrid = (g: Float32Array, gw: number, gh: number, r: number, passes: number) => {+ const tmp = new Float32Array(g.length);+ for (let p = 0; p < passes; p++) {+ for (let j = 0; j < gh; j++) { let acc = 0; const row = j * gw; for (let i = -r; i <= r; i++) acc += g[row + Math.max(0, Math.min(gw - 1, i))]; for (let i = 0; i < gw; i++) { tmp[row + i] = acc / (2 * r + 1); acc += g[row + Math.min(gw - 1, i + r + 1)] - g[row + Math.max(0, i - r)]; } }+ for (let i = 0; i < gw; i++) { let acc = 0; for (let j = -r; j <= r; j++) acc += tmp[Math.max(0, Math.min(gh - 1, j)) * gw + i]; for (let j = 0; j < gh; j++) { g[j * gw + i] = acc / (2 * r + 1); acc += tmp[Math.min(gh - 1, j + r + 1) * gw + i] - tmp[Math.max(0, j - r) * gw + i]; } }+ }+};++export const lynxField = (W: number, H: number): LynxField => {+ const G = 2, gw = Math.ceil(W / G), gh = Math.ceil(H / G), n = gw * gh, k = W / 1080;+ const S = (pts: P[]) => pts.map(([x, y]) => [x * k, y * k] as P);+ const part = new Uint8Array(n), tone = new Float32Array(n), ang = new Float32Array(n), len = new Float32Array(n);+ fillPoly(part, gw, gh, G, S(BODY), 3); fillPoly(part, gw, gh, G, S(EAR_N), 2); fillPoly(part, gw, gh, G, S(EAR_F), 2); fillPoly(part, gw, gh, G, S(HEAD), 1);+ const dHead = distIn(part, gw, gh, (v) => v === 1), dBody = distIn(part, gw, gh, (v) => v === 3 || v === 1), dEar = distIn(part, gw, gh, (v) => v === 2);+ const eN = S(eyeOutline(EYE_N)), eF = S(eyeOutline(EYE_F)), nl = S(NOSE_LEATHER);+ // HEIGHT: smooth anatomical masses (gaussians, so no mass shows an edge), rolled off at each silhouette+ const h = new Float32Array(n);+ for (let j = 0; j < gh; j++) for (let i = 0; i < gw; i++) {+ const q = j * gw + i, x = (i * G + 1) / k, y = (j * G + 1) / k, p = part[q]; if (!p) continue;+ if (p === 2) { const ed = dEar[q] * G; h[q] = 160 + 12 * sstep(0, 16, ed) - 10 * gauss(x, y, x < 560 ? [430, 262] : [706, 262], 20, 46); continue; } // the ear: a thin cupped plate+ const body = 130 * Math.sqrt(sstep(0, 240, dBody[q] * G));+ if (p === 3) { h[q] = body; continue; }+ const rim = Math.sqrt(sstep(0, 110, dHead[q] * G));+ let v = 90 * gauss(x, y, [566, 400], 170, 150) + 150 * gauss(x, y, [566, 470], 240, 270); // the skull, and the whole head's roundness+ v += 58 * gauss(x, y, [566, 560], 62, 48) + 18 * gauss(x, y, [522, 574], 30, 22) + 18 * gauss(x, y, [612, 572], 30, 22); // muzzle and whisker pads+ v += 22 * gauss(x, y, [566, 470], 22, 55); // nose bridge+ v += 12 * gauss(x, y, [484, 404], 40, 12, -0.15) + 12 * gauss(x, y, [640, 402], 36, 12, 0.15); // brows+ v -= 16 * gauss(x, y, [485, 438], 34, 20) + 14 * gauss(x, y, [640, 436], 30, 20); // sockets+ v += 22 * gauss(x, y, [440, 486], 70, 55) + 22 * gauss(x, y, [690, 482], 60, 55); // cheeks+ v += 14 * gauss(x, y, [566, 616], 30, 22); // chin+ h[q] = Math.max(body, 70 + 70 * rim + v * (0.35 + 0.65 * rim));+ }+ blurGrid(h, gw, gh, 4, 2);+ const at = (i: number, j: number) => h[Math.max(0, Math.min(gh - 1, j)) * gw + Math.max(0, Math.min(gw - 1, i))];+ const ml = Math.hypot(...MOON), lx = MOON[0] / ml, ly = MOON[1] / ml, lz = MOON[2] / ml, lxy = Math.hypot(lx, ly), dx = lx / lxy, dy = ly / lxy, rise = lz / lxy;+ for (let j = 0; j < gh; j++) for (let i = 0; i < gw; i++) {+ const q = j * gw + i, p = part[q]; if (!p) continue;+ const x = (i * G + 1) / k, y = (j * G + 1) / k;+ const hx = (at(i + 1, j) - at(i - 1, j)) / (2 * G), hy = (at(i, j + 1) - at(i, j - 1)) / (2 * G);+ let nx = -hx, ny = -hy, nz = 1; const nn = Math.hypot(nx, ny, nz); nx /= nn; ny /= nn; nz /= nn;+ const lam = clamp((nx * lx + ny * ly + nz * lz + 0.3) / 1.3), /* wrapped: fur scatters light a little past the terminator */ side = Math.hypot(nx, ny) || 1, rim = Math.pow(1 - nz, 1.5) * clamp((nx * dx + ny * dy) / side);+ const sky = 0.16 * Math.max(0, -nx * 0.5 + nz * 0.8); // a little cold skylight from the front-left: the shadow side is not a hole+ let sh = 0; for (let t = 3; t < 300; t += 3) { const ii = Math.round(i + (dx * t) / G), jj = Math.round(j + (dy * t) / G); if (ii < 0 || jj < 0 || ii >= gw || jj >= gh) break; sh = Math.max(sh, clamp((h[jj * gw + ii] - h[q] - t * rise) / (24 + t * 0.9))); if (sh >= 1) break; }+ // ALBEDO: the lynx's own markings+ let a = p === 3 ? 0.1 : 0.42;+ if (p === 1) for (const m of HEAD_MARKS) if (x >= m.box[0] && x <= m.box[2] && y >= m.box[1] && y <= m.box[3]) a = m.f(x, y, a);+ if (p === 2) { const ed = dEar[q] * G, inner = gauss(x, y, x < 560 ? [446, 280] : [700, 282], 22, 36); a = 0.22 + 0.72 * inner; if (ed < 6) a = 0.06; } // black ear rim, white hair filling the opening+ if (p === 3) a *= sstep(1100, 780, y) * (0.6 + 0.4 * sstep(300, 700, x)); // the coat turns away and down into the dark below the portrait+ if (p === 3) { const f = Math.sin(x * 0.05 + Math.sin(y * 0.031) * 2.2) * Math.sin(y * 0.055 + x * 0.013); if (f > 0.55) a *= 0.75; } // faint body spots+ const lit = p === 2 ? 0.8 : Math.pow(lam, 1.2) * 2.15 * (1 - 0.9 * sh);+ const back = Math.pow(1 - nz, 2) * clamp(-nx / side - 0.25) * clamp(1 - 2 * Math.max(0, ny / side)) * (p === 3 ? 0.4 : 1); // the sky behind the animal just rims its shadow side, enough to find the silhouette+ const white = clamp((a - 0.75) / 0.3) * 0.22; // white fur carries a little light even turned from the moon+ let t = a * (0.05 + lit + (p === 3 ? 0 : sky) + 0.9 * back) + white + 0.55 * rim * (1 - sh) * (p === 2 ? 0.4 : 1);+ if (y > 400 && y < 470 && x > 430 && x < 690 && (insidePoly(eN, x, y) || insidePoly(eF, x, y))) { part[q] = 4; t = 0; }+ else if (y > 505 && y < 565 && x > 530 && x < 605 && insidePoly(nl, x, y)) { part[q] = 5; }+ tone[q] = clamp(t);+ let sx = 0, sy = 0, ws = 0; idw(FLOW, x, y, (pp, w) => { const r = (pp[2] * Math.PI) / 180; sx += Math.cos(r) * w; sy += Math.sin(r) * w; ws += w; });+ const nd = Math.hypot(x - NOSE[0], y - (NOSE[1] + 24)), radial = p === 1 && y > NOSE[1] ? Math.exp(-((nd / 70) ** 2)) : 0; // the muzzle fur radiates from under the nose+ ang[q] = Math.atan2((sy / ws) * (1 - radial) + ((y - NOSE[1] - 24) / (nd || 1)) * radial, (sx / ws) * (1 - radial) + ((x - NOSE[0]) / (nd || 1)) * radial);+ let ls = 0, lw = 0; idw(LEN, x, y, (pp, w) => { ls += pp[2] * w; lw += w; }); len[q] = (ls / lw) * k;+ }+ return { W, H, G, gw, gh, tone, ang, len, part };+};+// the tone raster at full size, for looking at (debug only)+export const lynxTone = (W: number, H: number) => { const F = lynxField(W, H), raster = new Float32Array(W * H); for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const q = Math.min(F.gh - 1, y >> 1) * F.gw + Math.min(F.gw - 1, x >> 1); raster[y * W + x] = F.part[q] ? 1 - F.tone[q] : 1; } return { raster }; };diff --git a/engine/src/canvas-core/scrollHero.ts b/engine/src/canvas-core/scrollHero.tsnew file mode 100644index 0000000..6395298--- /dev/null+++ b/engine/src/canvas-core/scrollHero.ts@@ -0,0 +1,182 @@+// SCROLL HERO. The storybook plate draws itself as you scroll, the way a picture-book page is made.+//+// The idea in one sentence: reading down the page IS the illustrator's hand, so scroll progress is+// the pencil, then the brush, then the final line, and scrolling back up un-draws it.+// 1 PENCIL construction ovals, then a light sketch of everything, Bit head first and down;+// 2 PAINT every wash and form, each spreading from where the brush touched;+// 3 LINE full-weight graphite over the dry paint, head first again;+// done the plate, pixel for pixel. A pencil (or brush) sits at the nib the whole way.+//+// HOW, and why it is cheap enough for a web page. The plate's calls are run ONCE at mount through a+// Gfx that records every mark it makes (pen centreline, wash outline, raw-drawn box) in device px,+// and paints four whole stage images: the sheet, the sketch, the painting, the finished plate. A+// stroke is then a MASK: its patch of the next stage image, revealed along its centreline (pens)+// or out from the point the brush touched (washes). Completed strokes are composited, in order,+// onto an accumulator whose contents are a pure function of how many strokes are done (the cache+// key), so scrolling back rebuilds it from the sheet and lands on the same pixels. Each frame is+// one blit, one partial patch and a tool sprite. Scroll is sprung (input spring "p") so a wheel's+// jumps become a hand's pace. Reduced motion: the finished plate, no tool.+import { GRAPHITE, TINT, jitter, sample, type Ctx, type Env, type Layer, type P, Gfx } from "./core";+import { bake, blit, multiply, type Sprite } from "./bake";+import { meadow, sheetSprite, splatter } from "./bitRig";+import { SHADE, drawBit } from "./storybook";+import { scrollSpan, type Piece } from "./input";++const POSE = { look: 1, tilt: 6, lean: 3, handL: [-80, -58] as P, handR: [94, -178] as P }, SEED = 3, BOB = Math.sin(SEED) * 2;+const LOOP = 120;++// ---------------------------------------------------------------- the plate, re-authored (drawStorybook builds its own Gfx)+type Op = { kind: string; gi: number; type: "pen" | "shape" | "box"; pts: [number, number][]; w: number; bit: boolean };+const devPts = (c: Ctx, pts: P[]): [number, number][] => { const m = c.getTransform(); return pts.map(([x, y]) => [m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f]); };+const devScale = (c: Ctx) => { const m = c.getTransform(); return Math.hypot(m.a, m.b); };+type PenO = NonNullable<Parameters<Gfx["pen"]>[1]>;+class Pass extends Gfx {+ mode: "final" | "sketch" | "paint" = "final"; ops: Op[] | null = null; gi = -1; gk = ""; bit = false;+ group(kind: "ink" | "paint" | "plain", fn: () => void, opts: Parameters<Gfx["group"]>[2] = {}) {+ this.gi++; this.gk = kind;+ if (this.mode === "sketch" && kind !== "ink") return;+ if (this.mode === "paint" && kind === "ink") return;+ super.group(kind, fn, this.mode === "sketch" ? { ...opts, alpha: (opts.alpha ?? 1) * 0.4 } : opts);+ }+ private rec(type: Op["type"], pts: [number, number][], w: number) { this.ops?.push({ kind: this.gk, gi: this.gi, type, pts, w, bit: this.bit }); }+ pen(pts: P[], o: PenO = {}) {+ if (this.ops) { const { w = 3.4, seed = 1, closed = false, wobble = 1.1, boil = 0.55 } = o, ctrl = closed ? [...pts, pts[0], pts[1]] : pts; this.rec("pen", devPts(this.cur, sample(jitter(jitter(ctrl, wobble * this.medium.wobble, seed), boil, seed * 911))), w * this.medium.nib * devScale(this.cur)); }+ super.pen(pts, this.mode === "sketch" ? { ...o, w: (o.w ?? 3.4) * 0.7, retrace: false } : o);+ }+ wash(pts: P[], color: string, o: Parameters<Gfx["wash"]>[2] = {}) { this.rec("shape", devPts(this.cur, pts), 13 * devScale(this.cur)); super.wash(pts, color, o); }+ form(pts: P[], color: string, shade: string, o: Parameters<Gfx["form"]>[3] = {}) { this.rec("shape", devPts(this.cur, pts), 14 * devScale(this.cur)); super.form(pts, color, shade, o); }+ fill(pts: P[], color: string, alpha = 1) { this.rec("shape", devPts(this.cur, pts), 3 * devScale(this.cur)); super.fill(pts, color, alpha); }+ touch(x0: number, y0: number, x1: number, y1: number) { this.rec("box", devPts(this.cur, [[x0, y0], [x1, y1]]), 2 * devScale(this.cur)); super.touch(x0, y0, x1, y1); }+}+const scene = (g: Pass, base = true) => { meadow(g, { splatter: false, vignette: false, base }); g.bit = true; g.push(272, 492 + BOB * 2.75, 2.75 * (560 / 1080)); drawBit(g, 0, SEED, POSE); g.pop(); g.bit = false; splatter(g); };+// one stage image: the scene in a mode, then the sheet (vignette + paper) over it+const stage = (env: Env, mode: "blank" | "sketch" | "paint" | "final", ops?: Op[]) => {+ const sheet = sheetSprite(env); /* baked first: bakes share one scratch surface */+ return bake(env, `scroll:stage:${mode}`, (g0) => {+ const g = new Pass(g0.main, env, 0, g0.medium); g.ops = ops ?? null;+ if (mode === "blank") { const m = g.main; m.setTransform(env.scale, 0, 0, env.scale, 0, 0); m.fillStyle = "#fbf6ea"; m.fillRect(0, 0, env.W, env.H); }+ else if (mode === "final") scene(g);+ else {+ g.mode = "sketch"; scene(g);+ if (mode === "paint") { g.mode = "paint"; g.gi = -1; scene(g, false); } /* the washes go over the sketch, as on paper */+ }+ g.vignette("rgba(90,50,50,0.11)"); multiply(g.main, sheet);+ }, { full: true });+};++// ---------------------------------------------------------------- the timeline: strokes in the order a hand makes them+type Stroke = { op: Op; src: "sketch" | "paint" | "final"; t0: number; t1: number; box: [number, number, number, number]; len: number };+type Plan = { strokes: Stroke[]; T: number; ops: Op[] };+const lenOf = (pts: [number, number][]) => { 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]); return L; };+const boxOf = (env: Env, op: Op): [number, number, number, number] => {+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of op.pts) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }+ const pad = (op.type === "pen" ? op.w / 2 + 3 * env.scale : op.w) + 2;+ return [Math.max(0, Math.floor(x0 - pad)), Math.max(0, Math.floor(y0 - pad)), Math.min(Math.round(env.W * env.scale), Math.ceil(x1 + pad)), Math.min(Math.round(env.H * env.scale), Math.ceil(y1 + pad))];+};+const plan = (env: Env): Plan => {+ const key = "scroll:plan"; let p = env.cache.get(key) as Plan | undefined; if (p) return p;+ const ops: Op[] = []; stage(env, "blank"); stage(env, "final", ops);+ const k = env.scale, ink = ops.filter((o) => o.kind === "ink"), paint = ops.filter((o) => o.kind !== "ink");+ const construction = ink.filter((o) => o.gi === 1).slice(0, 4); // the four loose underdrawing marks+ const top = (o: Op) => Math.min(...o.pts.map((q) => q[1]));+ const bitInk = ink.filter((o) => o.bit).map((o, i) => ({ o, i, y: Math.floor(top(o) / (34 * k)) })).sort((a, b) => a.y - b.y || a.i - b.i).map((x) => x.o); // head first, down+ const sceneInk = ink.filter((o) => !o.bit && !construction.includes(o));+ // each phase gets a fixed share of the scroll, matching the page's steps; inside a phase, a stroke's+ // share grows with the square root of its length (long strokes go fast, fiddly ones slow)+ const phases: [Op[], Stroke["src"], number][] = [[construction, "sketch", 0.1], [[...bitInk, ...sceneInk], "sketch", 0.27], [paint, "paint", 0.25], [[...bitInk, ...sceneInk], "final", 0.3]];+ const GAP = 0.02, strokes: Stroke[] = []; let t = 0;+ const weight = (op: Op) => { const L = op.type === "pen" ? lenOf(op.pts) / k : op.type === "shape" ? Math.sqrt(Math.max(1, areaOf(op.pts))) / k : 6; return op.type === "pen" ? 0.5 + Math.sqrt(L) / 7 : op.type === "shape" ? 0.8 + L / 90 : 0.35; };+ phases.forEach(([list, src, share]) => { const total = list.reduce((a, o) => a + weight(o), 0) || 1; list.forEach((op) => { const d = (weight(op) / total) * share; strokes.push({ op, src, t0: t, t1: t + d, box: boxOf(env, op), len: 0 }); t += d; }); t += GAP; });+ p = { strokes, T: t, ops }; env.cache.set(key, p); return p;+};+const areaOf = (pts: [number, number][]) => { let a = 0; for (let i = 0; i < pts.length; i++) { const [x0, y0] = pts[i], [x1, y1] = pts[(i + 1) % pts.length]; a += x0 * y1 - x1 * y0; } return Math.abs(a) / 2; };++// ---------------------------------------------------------------- masks and patches+const cut = (pts: [number, number][], u: number): [number, number][] => {+ if (u >= 1) return pts; const L = lenOf(pts) * u; let acc = 0; const out: [number, number][] = [pts[0]];+ for (let i = 1; i < pts.length; i++) { const d = Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]); if (acc + d >= L) { const f = d ? (L - acc) / d : 0; out.push([pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * f, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * f]); return out; } acc += d; out.push(pts[i]); }+ return out;+};+const touchAt = (s: Stroke): [number, number] => (s.op.type === "box" ? [(s.op.pts[0][0] + s.op.pts[1][0]) / 2, (s.op.pts[0][1] + s.op.pts[1][1]) / 2] : s.op.pts.reduce((a, q) => (q[1] + q[0] * 0.3 < a[1] + a[0] * 0.3 ? q : a), s.op.pts[0])); // the brush lands top-left+const mask = (c: Ctx, s: Stroke, u: number, env: Env) => {+ const op = s.op; c.fillStyle = c.strokeStyle = "#000"; c.lineCap = c.lineJoin = "round";+ if (op.type === "pen") { const q = cut(op.pts, u); c.lineWidth = op.w + 3 * env.scale; c.beginPath(); q.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); if (q.length === 1) c.lineTo(q[0][0] + 0.01, q[0][1]); c.stroke(); return; }+ if (op.type === "box") { const [[x0, y0], [x1, y1]] = op.pts; c.fillRect(Math.min(x0, x1) - op.w, Math.min(y0, y1) - op.w, Math.abs(x1 - x0) + 2 * op.w, Math.abs(y1 - y0) + 2 * op.w); }+ else { c.lineWidth = op.w * 2; c.beginPath(); op.pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill(); c.stroke(); }+ if (u < 1) { const [cx, cy] = touchAt(s), b = s.box, R = Math.max(...[[b[0], b[1]], [b[2], b[1]], [b[0], b[3]], [b[2], b[3]]].map(([x, y]) => Math.hypot(x - cx, y - cy))); c.globalCompositeOperation = "destination-in"; c.beginPath(); c.arc(cx, cy, Math.max(0.5, R * (1 - (1 - u) ** 2)), 0, Math.PI * 2); c.fill(); c.globalCompositeOperation = "source-over"; }+};+// the stroke's region of its stage image, cut out by its mask, into `L` at the stroke's box+const cutOut = (L: Layer, s: Stroke, u: number, env: Env, ox: number, oy: number) => {+ const c = L.ctx, b = s.box, w = b[2] - b[0], h = b[3] - b[1];+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; c.clearRect(ox, oy, w, h);+ c.save(); c.beginPath(); c.rect(ox, oy, w, h); c.clip(); c.setTransform(1, 0, 0, 1, ox - b[0], oy - b[1]); mask(c, s, u, env);+ c.globalCompositeOperation = "source-in"; c.setTransform(1, 0, 0, 1, 0, 0); c.drawImage(stage(env, s.src).c, b[0], b[1], w, h, ox, oy, w, h); c.restore();+};+const patch = (env: Env, i: number): Sprite => {+ const key = `scroll:patch:${i}`, hit = env.cache.get(key) as Sprite | undefined; if (hit) return hit;+ const s = plan(env).strokes[i], w = Math.max(1, s.box[2] - s.box[0]), h = Math.max(1, s.box[3] - s.box[1]), L = env.canvas(w, h); cutOut(L, s, 1, env, 0, 0);+ const sp: Sprite = { c: L.canvas as CanvasImageSource, x: s.box[0], y: s.box[1], w, h }; env.cache.set(key, sp); return sp;+};+// the accumulator: the sheet plus the first n patches, in order. Its pixels are a function of n alone.+type Acc = { L: Layer; n: number };+const accumulate = (env: Env, n: number): Layer => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale); let a = env.cache.get("scroll:acc") as Acc | undefined;+ if (!a) { a = { L: env.canvas(DW, DH), n: -1 }; env.cache.set("scroll:acc", a); }+ if (a.n > n || a.n < 0) { const c = a.L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "copy"; c.drawImage(stage(env, "blank").c, 0, 0); c.globalCompositeOperation = "source-over"; a.n = 0; }+ for (; a.n < n; a.n++) blit(a.L.ctx, patch(env, a.n));+ return a.L;+};++// ---------------------------------------------------------------- the tools, drawn in the plate's hand+const along = (tip: P, ang: number) => (u: number, v: number): P => [tip[0] + Math.cos(ang) * u - Math.sin(ang) * v, tip[1] + Math.sin(ang) * u + Math.cos(ang) * v];+const TOOL_TIP: P = [280, 330], TOOL_ANG = (-58 * Math.PI) / 180;+const band = (f: (u: number, v: number) => P, u0: number, u1: number, w0: number, w1: number, n = 6): P[] => { const L: P[] = [], R: P[] = []; for (let i = 0; i <= n; i++) { const u = u0 + ((u1 - u0) * i) / n, w = w0 + ((w1 - w0) * i) / n; L.push(f(u, -w)); R.push(f(u, w)); } return [...L, ...R.reverse()]; };+const pencil = (env: Env) => bake(env, "scroll:tool:pencil", (g) => {+ const f = along(TOOL_TIP, TOOL_ANG), body = band(f, 34, 132, 8, 8), wood = band(f, 9, 34, 2.4, 8), rub = band(f, 144, 160, 8, 7.2, 4), fer = band(f, 131, 145, 8.6, 8.6, 3);+ g.group("paint", () => { g.form(body, TINT.butter, SHADE.butter, { seed: 501, light: [-2, -3] }); g.form(wood, "#f3d2ad", "#d9ad83", { seed: 502, light: [-2, -2] }); g.form(fer, "#d6d0c8", "#9d958c", { seed: 503, light: [-1, -2] }); g.form(rub, TINT.rose, SHADE.rose, { seed: 504, light: [-2, -2] }); });+ g.group("ink", () => {+ g.fill(band(f, -1, 10, 0.4, 2.6, 3), GRAPHITE);+ [body, wood, fer, rub].forEach((b, i) => g.pen(b, { closed: true, w: 2, seed: 510 + i, wobble: 0.3, boil: 0.2, taper: 0.4 }));+ g.pen([f(36, 2.5), f(130, 2.5)], { w: 1.2, seed: 520, wobble: 0.2, opacity: 0.45, retrace: false }); g.pen([f(135, -8), f(135, 8)], { w: 1.3, seed: 521, opacity: 0.6, retrace: false }); g.pen([f(140, -8), f(140, 8)], { w: 1.3, seed: 522, opacity: 0.6, retrace: false });+ });+});+const brush = (env: Env) => bake(env, "scroll:tool:brush", (g) => {+ const f = along(TOOL_TIP, TOOL_ANG), hair = [f(-1, 0), f(8, -4), f(22, -6.5), f(34, -5.5), f(34, 5.5), f(22, 6.5), f(8, 4)] as P[], fer = band(f, 33, 56, 5.8, 5.8, 3), handle = band(f, 55, 176, 5.2, 7, 8);+ g.group("paint", () => { g.form(hair, "#7b5b46", "#4f3a2e", { seed: 531, light: [-1, -2] }); g.wash(band(f, 0, 12, 1, 4, 3), "#6fa874", { alpha: 0.9, seed: 532, dx: 0, dy: 0, shrink: 1, rim: false }); g.form(fer, "#d6d0c8", "#9d958c", { seed: 533, light: [-1, -2] }); g.form(handle, "#c9566b", "#9c3d50", { seed: 534, light: [-2, -3] }); });+ g.group("ink", () => [hair, fer, handle].forEach((b, i) => g.pen(b, { closed: true, w: 1.9, seed: 540 + i, wobble: 0.3, boil: 0.2, taper: 0.4 })));+});++// ---------------------------------------------------------------- the piece+export const scrollHero: Piece = {+ meta: { title: "Bit, drawn as you scroll", W: 560, H: 560, loop: LOOP, alt: "A storybook illustration of a small wind-up robot in a meadow, drawn in pencil and watercolour as you scroll down the page." },+ input: { springs: { p: { omega: 0.12, target: (d) => d.scroll } } },+ bake: function* (env) {+ yield "sheet"; sheetSprite(env); yield "stages"; stage(env, "blank"); yield "plan"; const pl = plan(env); yield "sketch"; stage(env, "sketch"); yield "paint"; stage(env, "paint");+ yield "tools"; pencil(env); brush(env);+ for (let i = 0; i < pl.strokes.length; i++) { patch(env, i); if (i % 8 === 7) yield `patch${i}`; }+ },+ draw: (ctx, t, env, s) => {+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";+ const pl = plan(env), bob = Math.sin((2 * Math.PI * t) / LOOP), k = env.scale;+ const p = s.reduced ? 1 : scrollSpan(s.spring.p as number, 0.02, 0.96);+ if (p >= 1) { blit(ctx, stage(env, "final")); if (!s.reduced) tool(ctx, env, pencil(env), [500, 520], 2 * bob, 12); return; }+ const time = p * pl.T, S = pl.strokes;+ let lo = 0, hi = S.length; while (lo < hi) { const m = (lo + hi) >> 1; if (S[m].t1 <= time) lo = m + 1; else hi = m; } // lo = strokes finished+ blit(ctx, { c: accumulate(env, lo).canvas as CanvasImageSource, x: 0, y: 0, w: 0, h: 0 });+ let nib: P = S[0] ? [S[0].op.pts[0][0] / k, S[0].op.pts[0][1] / k] : [280, 280], painting = false;+ const cur = S[lo];+ if (cur && time > cur.t0) {+ const u = Math.min(1, (time - cur.t0) / (cur.t1 - cur.t0)), tmp = scratch(env); cutOut(tmp, cur, u, env, 0, 0);+ const w = cur.box[2] - cur.box[0], h = cur.box[3] - cur.box[1]; ctx.drawImage(tmp.canvas as CanvasImageSource, 0, 0, w, h, cur.box[0], cur.box[1], w, h);+ painting = cur.src === "paint"; nib = tipOf(cur, u, k, t);+ } else if (lo > 0) { const prev = S[lo - 1]; painting = prev.src === "paint" && (!cur || cur.src === "paint"); nib = tipOf(prev, 1, k, t); if (cur && !painting && prev.src !== cur.src) nib = [cur.op.pts[0][0] / k, cur.op.pts[0][1] / k]; }+ tool(ctx, env, painting ? brush(env) : pencil(env), nib, 1.5 * bob, 0);+ },+};+const scratch = (env: Env): Layer => { const key = "scroll:tmp"; let L = env.cache.get(key) as Layer | undefined; if (!L) { L = env.canvas(Math.round(env.W * env.scale), Math.round(env.H * env.scale)); env.cache.set(key, L); } return L; };+const tipOf = (s: Stroke, u: number, k: number, t: number): P => {+ if (s.op.type === "pen") { const q = cut(s.op.pts, u), e = q[q.length - 1]; return [e[0] / k, e[1] / k]; }+ const [cx, cy] = touchAt(s), b = s.box, r = (Math.min(b[2] - b[0], b[3] - b[1]) / 2) * Math.min(1, u) * 0.8, a = u * 9 + t * 0.02; return [(cx + Math.cos(a) * r) / k, (cy + Math.sin(a) * r) / k];+};+// the tool with its tip at `nib` (sheet px), bobbing; `lift` raises it off the paper+const tool = (ctx: Ctx, env: Env, sp: Sprite, nib: P, bob: number, lift: number) => blit(ctx, sp, (nib[0] - TOOL_TIP[0]) * env.scale, (nib[1] - TOOL_TIP[1] - lift + bob) * env.scale);diff --git a/engine/src/canvas-core/stipple.ts b/engine/src/canvas-core/stipple.tsnew file mode 100644index 0000000..a90f91e--- /dev/null+++ b/engine/src/canvas-core/stipple.ts@@ -0,0 +1,165 @@+import { Gfx, PENCIL, rng, type Ctx, type Env } from "./core";+import type { Film } from "./film";+import { NAUT, shellTone, type Tone } from "./stippleKit";++// NAUTILUS · pen-and-ink stipple. A technical pen (0.25 mm, one size, never changed) touched+// straight down onto hot-press bristol, thousands of times. Nothing is drawn with a line: there+// is no outline, no hatching, no wash. Every tone is the NUMBER of dots in a square centimetre,+// and every edge is only the place where that number changes. The pen is held a little off+// vertical, so each dot is a touch oval and a touch ragged; now and then the nib drags a tail as+// it lifts, and now and then it is running dry and the dot comes up grey.+//+// DISTRIBUTION. Weighted-Voronoi stippling (Secord, NPAR 2002) places dots so that density+// follows tone and no two dots crowd: a blue-noise field whose spacing is ~1.5 px / tone^0.64.+// It is built here as variable-radius Poisson-disk sampling (Bridson) over a 1-px tone raster,+// which gives the same no-clump, density = tone field without a GPU Lloyd loop.+//+// ORDER. The stippler works the darkest masses first (the cast shadow, the deep shadow inside+// the body chamber and each chamber's shaded wall), then walks out into the mid tones, then a+// few sparse passes over the lit nacre last. Each pass moves across the sheet in patches the way+// a hand does, not in a raster.+//+// PAPER. Bright hot-press bristol, a faint tooth. Ink: carbon black, a hair warm.+// LIGHT. One lamp, upper left, ~42 degrees up. It rakes into each cut chamber: the wall nearest+// the lamp throws its shadow across the chamber floor, the far wall is lit, nacre flashes where+// the floor turns to the lamp. The shell throws a cast shadow down-right on the table.+//+// SUBJECT & REFERENCE. Nautilus pompilius shell, sawn in the median plane and laid cut face up+// (the classic sectioned-shell specimen). Structure from knowledge of sectioned shells and+// Raup's coiling model: a logarithmic spiral whose whorl expands ~3x per revolution, involute+// (each whorl sits on the one before), a large body chamber (~1/3 whorl) open at the aperture,+// then ~11 camerae per whorl divided by thin septa that are concave toward the aperture, so in+// section every septum bows back toward the apex; a central siphuncle threads the septa, with+// short septal necks pointing back (adapically). Inner whorls shrink to a dot at the umbilicus.++const N = 450, HOLD = 30;+// THE CUE TABLE. Every frame number of the film. Events on multiples of 5, one shot, the hold last.+const CUES = { first: 0, passesEnd: N - HOLD, hold: N - HOLD } as const;+const PASSES = 6; // key bands: darkest masses ... light nacre+(() => { for (const [k, v] of Object.entries(CUES)) if (v % 5 || v < 0 || v > N) throw new Error(`stipple cue ${k}=${v} off the 5-frame grid`); if (N % 15) throw new Error("stipple: duration off the beat"); })();++const INK = "#15120e", PAPER = "#fbfaf5";+const DOT = 1.22; // the nib's radius in px at 1080: one pen, one size++type Dot = { x: number; y: number; t: number; pass: number; key: number };+type Stip = { dots: Dot[]; shape: Float32Array; alpha: Uint8Array; start: number[] };++// ---------------------------------------------------------------- the dot field (built once, cached)+const build = (env: Env): Stip => {+ const key = `stipple:dots:${env.W}x${env.H}`; let S = env.cache.get(key) as Stip | undefined; if (S) return S;+ const W = env.W, H = env.H, tone: Tone = shellTone(W, H);+ const T = tone.raster, at = (x: number, y: number) => { const i = (y | 0) * W + (x | 0); return x < 0 || y < 0 || x >= W || y >= H ? 0 : T[i]; };+ const MIN_T = 0.022, spacing = (t: number) => 1.5 / Math.pow(Math.max(t, MIN_T), 0.64);+ // variable-radius Poisson disk (Bridson), seeded from a jittered lattice so islands of tone are all reached+ const cell = 1.35, gw = Math.ceil(W / cell), gh = Math.ceil(H / cell), grid = new Int32Array(gw * gh).fill(-1);+ const xs: number[] = [], ys: number[] = [], rs: number[] = [], r = rng(20260925);+ const ok = (x: number, y: number, d: number) => {+ const reach = Math.ceil((d * 1.25) / cell), gx = Math.floor(x / cell), gy = Math.floor(y / cell);+ for (let j = Math.max(0, gy - reach); j <= Math.min(gh - 1, gy + reach); j++) for (let i = Math.max(0, gx - reach); i <= Math.min(gw - 1, gx + reach); i++) {+ const k = grid[j * gw + i]; if (k < 0) continue; const dx = xs[k] - x, dy = ys[k] - y, m = 0.5 * (d + rs[k]); if (dx * dx + dy * dy < m * m) return false;+ }+ return true;+ };+ const add = (x: number, y: number, d: number) => { const k = xs.length; xs.push(x); ys.push(y); rs.push(d); grid[Math.floor(y / cell) * gw + Math.floor(x / cell)] = k; return k; };+ const grow = (k0: number) => {+ const active = [k0];+ while (active.length) {+ const ai = Math.floor(r() * active.length), k = active[ai]; let found = false;+ for (let n = 0; n < 18; n++) {+ const a = r() * Math.PI * 2, d0 = rs[k], rr = d0 * (1 + r()), x = xs[k] + Math.cos(a) * rr, y = ys[k] + Math.sin(a) * rr;+ if (x < 1 || y < 1 || x >= W - 1 || y >= H - 1) continue; const t = at(x, y); if (t < MIN_T) continue;+ const d = spacing(t); if (!ok(x, y, d)) continue; active.push(add(x, y, d)); found = true;+ }+ if (!found) { active[ai] = active[active.length - 1]; active.pop(); }+ }+ };+ for (let y = 3; y < H; y += 7) for (let x = 3; x < W; x += 7) { const px = x + (r() - 0.5) * 5, py = y + (r() - 0.5) * 5, t = at(px, py); if (t < MIN_T) continue; const d = spacing(t); if (ok(px, py, d)) grow(add(px, py, d)); }++ // ORDER: key = how light the dot's tone is, plus a random rank, so the dark masses go in first+ // and later passes both reach into mid tone and densify what is already dark.+ const PATCH = 84, dots: Dot[] = xs.map((x, i) => { const t = at(x, ys[i]), u = r(); return { x, y: ys[i], t, pass: 0, key: (1 - t) + 0.42 * u }; });+ let lo = 1e9, hi = -1e9; dots.forEach((d) => { lo = Math.min(lo, d.key); hi = Math.max(hi, d.key); });+ dots.forEach((d) => { d.pass = Math.min(PASSES - 1, Math.floor(((d.key - lo) / (hi - lo + 1e-9)) ** 1.25 * PASSES)); });+ // within a pass the hand works patch by patch, top-left to bottom-right in a snake+ const patchOf = (d: Dot) => { const py = Math.floor(d.y / PATCH), px0 = Math.floor(d.x / PATCH), px = py % 2 ? 100 - px0 : px0; return py * 128 + px; };+ dots.sort((a, b) => a.pass - b.pass || patchOf(a) - patchOf(b) || a.key - b.key);+ const start: number[] = []; for (let p = 0, i = 0; p <= PASSES; p++) { while (i < dots.length && dots[i].pass < p) i++; start.push(i); }+ // each dot's shape: a slightly oval, slightly ragged 7-gon, the nib tilted ~35 degrees+ const V = 7, shape = new Float32Array(dots.length * V * 2), alpha = new Uint8Array(dots.length), tilt = -0.62;+ dots.forEach((d, i) => {+ const s = rng(i * 7919 + 17), rad = DOT * (0.9 + s() * 0.24), el = 1.06 + s() * 0.12, ph = s() * 6.283, h2 = s() * 0.1, h3 = s() * 0.08, tail = s() < 0.035;+ alpha[i] = s() < 0.04 ? 150 : 236 + Math.floor(s() * 19); // a few from a nib running dry+ for (let v = 0; v < V; v++) {+ const a = (v / V) * Math.PI * 2, k = 1 + h2 * Math.sin(2 * a + ph) + h3 * Math.sin(3 * a + ph * 1.7);+ let ex = Math.cos(a) * rad * k * el, ey = Math.sin(a) * rad * k;+ if (tail && v === 0) ex += rad * 1.3; // the nib dragged a hair as it lifted+ shape[(i * V + v) * 2] = d.x + ex * Math.cos(tilt) - ey * Math.sin(tilt); shape[(i * V + v) * 2 + 1] = d.y + ex * Math.sin(tilt) + ey * Math.cos(tilt);+ }+ });+ S = { dots, shape, alpha, start }; env.cache.set(key, S);+ return S;+};++// ---------------------------------------------------------------- when each dot goes down+// frames per pass in proportion to its dots; the hand never stops, one pass runs into the next+const schedule = (S: Stip) => {+ const counts = Array.from({ length: PASSES }, (_, p) => S.start[p + 1] - S.start[p]), total = counts.reduce((a, b) => a + b, 0);+ const gap = 0, span = CUES.passesEnd - CUES.first - gap * (PASSES - 1), win: [number, number][] = []; let f = CUES.first;+ counts.forEach((c) => { const len = Math.max(20, Math.round(((span - 20 * PASSES) * c) / total) + 20); win.push([f, f + len]); f += len + gap; });+ const k = (CUES.passesEnd - CUES.first) / (f - gap - CUES.first); return win.map(([a, b]) => [CUES.first + (a - CUES.first) * k, CUES.first + (b - CUES.first) * k] as [number, number]);+};+// how many dots are down at frame f: within a pass the hand starts slow, finds its rhythm, finishes the last patch quicker+const countAt = (S: Stip, f: number): number => {+ if (f >= CUES.hold) return S.dots.length;+ const win = schedule(S); let n = 0;+ win.forEach(([a, b], p) => { const c = S.start[p + 1] - S.start[p], u = Math.max(0, Math.min(1, (f - a) / (b - a))), e = u < 1 ? u * u * (3 - 2 * u) * 0.35 + u * 0.65 : 1; n += Math.floor(c * e); });+ return n;+};++// ---------------------------------------------------------------- the pen+const CHUNK = 600;+const inkDots = (ctx: Ctx, env: Env, S: Stip, n: number) => inkRange(ctx, env, S, 0, n);+const inkRange = (ctx: Ctx, env: Env, S: Stip, from: number, n: number) => {+ // completed chunks are cached as Path2D: the pixels of a chunk depend only on its index+ const V = 7, fillRange = (a: number, b: number, cls: number) => {+ const pk = `stipple:path:${a}:${b}:${cls}`; let path = env.cache.get(pk) as Path2D | undefined;+ if (!path) { path = new Path2D(); for (let i = a; i < b; i++) { if ((S.alpha[i] < 200 ? 1 : 0) !== cls) continue; const o = i * V * 2; path.moveTo(S.shape[o], S.shape[o + 1]); for (let v = 1; v < V; v++) path.lineTo(S.shape[o + v * 2], S.shape[o + v * 2 + 1]); path.closePath(); } if (b - a === CHUNK) env.cache.set(pk, path); }+ ctx.globalAlpha = cls ? 0.6 : 0.95; ctx.fill(path);+ };+ ctx.fillStyle = INK;+ for (let a = from; a < n; a += CHUNK) { const b = Math.min(n, a + CHUNK); fillRange(a, b, 0); fillRange(a, b, 1); }+ ctx.globalAlpha = 1;+};++const sheet = (ctx: Ctx, env: Env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, env.W, env.H); };+// hot-press bristol: almost no tooth. The core's paper tile, barely there, over dots and sheet alike.+const tooth = (ctx: Ctx, env: Env) => { new Gfx(ctx, env, 0, PENCIL).paper("paper", 0.05); };++export const drawStipple = (ctx: Ctx, frame: number, env: Env) => {+ const S = build(env), n = countAt(S, frame);+ if (n >= S.dots.length) { // the finished plate: one cached bitmap for the hold+ const k = `stipple:final:${env.scale}`; let L = env.cache.get(k) as ReturnType<Env["canvas"]> | undefined;+ if (!L) { L = env.canvas(Math.round(env.W * env.scale), Math.round(env.H * env.scale)); sheet(L.ctx, env); inkDots(L.ctx, env, S, n); tooth(L.ctx, env); env.cache.set(k, L); }+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas as CanvasImageSource, 0, 0); return;+ }+ // mid-process: the dots already down live on a checkpoint layer (a pure function of its dot+ // count), and only the newest few thousand are filled fresh, so a late frame costs a blit+ const CK = 4800, c = Math.floor(n / CK) * CK, layer = (m: number): ReturnType<Env["canvas"]> => {+ const k = `stipple:ck:${m}:${env.scale}`; let L = env.cache.get(k) as ReturnType<Env["canvas"]> | undefined; if (L) return L;+ L = env.canvas(Math.round(env.W * env.scale), Math.round(env.H * env.scale)); const lc = L.ctx; lc.setTransform(1, 0, 0, 1, 0, 0);+ if (m > CK) lc.drawImage(layer(m - CK).canvas as CanvasImageSource, 0, 0);+ lc.setTransform(env.scale, 0, 0, env.scale, 0, 0); inkRange(lc, env, S, m - CK, m); env.cache.set(k, L); return L;+ };+ sheet(ctx, env);+ if (c > 0) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(layer(c).canvas as CanvasImageSource, 0, 0); ctx.restore(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); }+ inkRange(ctx, env, S, c, n); tooth(ctx, env);+};++export const stipple: Film = {+ meta: { title: "Nautilus · stipple", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "stipple", start: 0, end: N, draw: drawStipple }],+};++export const STYLE = { id: "stipple", name: "Pen-and-ink stipple", family: "ink", medium: "one 0.25 mm technical pen dotted straight down onto hot-press bristol; tone is dot density only", nearest: "mellan", hero: "a nautilus shell sawn in half, chambers lit from the upper left, cast shadow in dots" };+void NAUT;diff --git a/engine/src/canvas-core/stippleKit.ts b/engine/src/canvas-core/stippleKit.tsnew file mode 100644index 0000000..473ee1d--- /dev/null+++ b/engine/src/canvas-core/stippleKit.ts@@ -0,0 +1,125 @@+// STIPPLE KIT. The sectioned nautilus as a TONE FIELD: no drawing here, only the question+// "how much ink belongs at this point?", answered from the shell's real structure and one lamp.+// The stipple plate turns this raster into dots.+//+// Geometry (median section of Nautilus pompilius):+// outer wall R(phi) = A * exp(B * phi), B = ln 3 / 2pi (whorl expansion ~3 per turn), phi <= 0+// a whorl at angle phi spans radii [R(phi - 2pi), R(phi)]: involute, it sits on the last one+// s in [0,1]: 0 on the dorsal (inner) side of the tube, 1 on the ventral (outer) wall+// septa every DELTA of phi, each bowed back toward the apex in its middle+// the last BODY of phi is the open body chamber; the aperture is the end of the tube+import { fractal } from "./core";++export const NAUT = {+ A: 0.418, // outer radius at the aperture, fraction of W+ B: Math.log(3) / (2 * Math.PI),+ POLE: [0.415, 0.405] as [number, number],+ SENSE: -1, // screen angle runs against phi: the coil grows counter-clockwise+ TH0: 0.52, // screen angle of the aperture (radians, y down)+ BODY: 2 * Math.PI * 0.36, // body chamber, a third of a whorl and a bit+ DELTA: (2 * Math.PI) / 11, // camerae per whorl+ BOW: 0.5, // how far a septum bows back at its middle, in chamber lengths+ SIPH: 0.47, // the siphuncle's place across the tube+ WIDTH: 0.44, // tube half-width (depth below the cut) as a fraction of its in-plane height+ RMIN: 7, // inside this radius the protoconch whorls are below the pen's resolution+};+export type Tone = { raster: Float32Array };++const L = (() => { const x = -0.6, y = -0.66, z = 1.0, l = Math.hypot(x, y, z); return [x / l, y / l, z / l]; })(); // to the lamp: upper left, ~48 degrees up+const LXY = Math.hypot(L[0], L[1]), UL: [number, number] = [L[0] / LXY, L[1] / LXY], COT = LXY / L[2];+const Hh = (() => { const x = L[0], y = L[1], z = L[2] + 1, l = Math.hypot(x, y, z); return [x / l, y / l, z / l]; })(); // half vector for the nacre's flash+const TAU = Math.PI * 2, clamp = (v: number, a = 0, b = 1) => (v < a ? a : v > b ? b : v);++// kind: 0 paper, 1 cut face (wall, septum, neck), 2 chamber floor, 3 siphuncle trough, 4 outer rim sliver, 5 umbilical core+type Hit = { kind: number; id: number; s: number; q: number; h: number; r: number; th: number; v: number; body: boolean; phi: number };+const septumBow = (s: number) => NAUT.BOW * Math.sin(Math.PI * Math.pow(clamp(s), 0.85));+const apertureAt = (s: number) => -0.1 * s * s + 0.05 * (1 - s); // the lip: a shallow ventral sinus++const locate = (W: number, x: number, y: number, o: Hit): Hit => {+ const A = NAUT.A * W, px = NAUT.POLE[0] * W, py = NAUT.POLE[1] * W, dx = x - px, dy = y - py, r = Math.hypot(dx, dy), th = Math.atan2(dy, dx);+ o.r = r; o.th = th; o.kind = 0; o.id = 0; o.body = false;+ if (r < NAUT.RMIN) { o.kind = 5; return o; }+ const u = Math.log(r / A) / NAUT.B, pth = NAUT.SENSE * (th - NAUT.TH0);+ let phi = pth + TAU * Math.ceil((u - pth) / TAU); if (phi < u) phi += TAU;+ const R1 = A * Math.exp(NAUT.B * phi), R0 = R1 / 3, h = R1 - R0, s = (r - R0) / h;+ o.phi = phi; o.s = s; o.h = h;+ const lip = apertureAt(clamp(s));+ if (phi > lip) { // beyond the last whorl: paper, or the rounded outer surface seen as a sliver+ const Rin = R0, rim = 3 + 0.016 * Rin, beyond = r - Rin; // the whorl inside is the outermost one here+ const ph2 = phi - TAU; if (ph2 <= apertureAt(0.99) && beyond < rim && beyond >= 0) { o.kind = 4; o.phi = ph2; o.q = beyond / rim; return o; }+ return o;+ }+ const tw = 0.026 * R1 + 1.1, td = 0.006 * R1 + 0.7, lipPx = (lip - phi) * r;+ if (R1 - r < tw || r - R0 < td || lipPx < tw * 0.9) { o.kind = 1; return o; } // outer wall, dorsal layer, the aperture's lip+ const last = -NAUT.BODY, v = (phi + NAUT.DELTA * septumBow(s) - last) / NAUT.DELTA, D = NAUT.DELTA;+ o.v = v;+ const ts = 0.0042 * R1 + 1.25;+ if (v > 0) { o.body = true; o.id = 1; o.q = v; if (v * D * r < ts) { o.kind = 1; return o; } o.kind = 2; return o; }+ const c = Math.floor(v), q = v - c; o.id = c - 10; o.q = q;+ if (Math.min(q, 1 - q) * D * r * 0.93 < ts) { o.kind = 1; return o; }+ // the siphuncle: a trough (the tube cut open) with its wall, and the septal neck pointing back from each septum+ const ds = Math.abs(s - NAUT.SIPH) * h, rho = 0.036 * h + 1.6;+ if (ds < rho) { o.kind = 3; return o; }+ if (ds < rho + 2.1 + (q > 0.72 ? 1.6 + 0.016 * h : 0)) { o.kind = 1; return o; } // connecting ring; thicker where it is the neck+ o.kind = 2; return o;+};++// depth of the chamber floor below the cut, and its gradient across (s, q)+const depthSQ = (s: number, q: number, h: number, body: boolean, r: number): number => {+ const ss = clamp(s), across = Math.sqrt(Math.max(0, 1 - Math.pow(2 * Math.pow(ss, 1.08) - 1, 2)));+ const along = body ? Math.sqrt(clamp((q * NAUT.DELTA * r) / (0.32 * h))) : Math.sqrt(Math.max(0, 1 - Math.pow(Math.abs(2 * q - 1), 2.6)));+ return NAUT.WIDTH * h * across * along;+};++export const shellTone = (W: number, H: number): Tone => {+ const raster = new Float32Array(W * H), hit: Hit = { kind: 0, id: 0, s: 0, q: 0, h: 0, r: 0, th: 0, v: 0, body: false, phi: 0 }, h2: Hit = { ...hit };+ const A = NAUT.A * W, D = NAUT.DELTA;+ // THE CAST SHADOW. The half shell lies on its flank with the cut face as its flat top, so every+ // point of the section is the same height above the table: half the shell's width (~0.5 of its+ // diameter, so a quarter). The shadow is the silhouette swept away from the lamp by up to+ // HT * cot(elevation); its far edge is soft because the flank rolls under toward the table.+ const G = 3, gw = Math.ceil(W / G), gh = Math.ceil(H / G), solid = new Uint8Array(gw * gh);+ for (let j = 0; j < gh; j++) for (let i = 0; i < gw; i++) { locate(W, i * G + 1, j * G + 1, hit); solid[j * gw + i] = hit.kind ? 1 : 0; }+ const HT = 0.2 * A * 1.58, TMAX = HT * COT;+ const inS = (x: number, y: number) => { const i = Math.round((x - 1) / G), j = Math.round((y - 1) / G); return i >= 0 && j >= 0 && i < gw && j < gh && solid[j * gw + i] === 1; };+ const shadow = new Float32Array(gw * gh);+ for (let j = 0; j < gh; j++) for (let i = 0; i < gw; i++) {+ if (solid[j * gw + i]) continue; const x = i * G + 1, y = j * G + 1; let near = -1;+ for (let t = 1.5; t < TMAX + 40; t += 1.5) if (inS(x + UL[0] * t, y + UL[1] * t)) { near = t; break; }+ if (near < 0) continue;+ const f = near / TMAX, body = clamp((1.12 - f) / 0.5), contact = Math.exp(-near / 9);+ shadow[j * gw + i] = clamp(body * (0.5 - 0.14 * f) + 0.32 * contact);+ }+ const shAt = (x: number, y: number) => { const fx = (x - 1) / G, fy = (y - 1) / G, i = Math.floor(fx), j = Math.floor(fy), a = fx - i, b = fy - j, g = (ii: number, jj: number) => (ii < 0 || jj < 0 || ii >= gw || jj >= gh ? 0 : shadow[jj * gw + ii]); return (g(i, j) * (1 - a) + g(i + 1, j) * a) * (1 - b) + (g(i, j + 1) * (1 - a) + g(i + 1, j + 1) * a) * b; };+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {+ const k = y * W + x; locate(W, x + 0.5, y + 0.5, hit); let t = 0;+ switch (hit.kind) {+ case 0: t = shAt(x, y); break;+ case 5: t = 0.42; break;+ case 1: t = 0.035 + (fractal(71, x, y, 0.02, 0.05, 2) - 0.5) * 0.05; break; // sawn, polished nacre: the lightest thing on the sheet+ case 3: t = 0.66; break;+ case 4: { // the rounded outside of the shell, turning away+ const nx = Math.cos(hit.th), ny = Math.sin(hit.th), face = clamp(-(nx * UL[0] + ny * UL[1]) * 0.5 + 0.5), stripe = hit.phi < -1.4 ? clamp(Math.sin(hit.phi * 7.5 + 2.2 * fractal(9, x, y, 0.03, 0.03, 2)) * 3 - 1.6) : 0;+ t = clamp(0.1 + 0.55 * face * face + 0.3 * stripe + 0.25 * hit.q); break; }+ default: {+ const { s, q, h, body, r } = hit, e = 0.02, d0 = depthSQ(s, q, h, body, r);+ const ds_ = (depthSQ(s + e, q, h, body, r) - depthSQ(s - e, q, h, body, r)) / (2 * e * h), dq_ = (depthSQ(s, q + e, h, body, r) - depthSQ(s, q - e, h, body, r)) / (2 * e * D * r);+ const c = Math.cos(hit.th), sn = Math.sin(hit.th), tx = -sn * NAUT.SENSE, ty = c * NAUT.SENSE;+ let nx = ds_ * c + dq_ * tx, ny = ds_ * sn + dq_ * ty, nz = 1; const nl = Math.hypot(nx, ny, nz); nx /= nl; ny /= nl; nz /= nl;+ const lam = clamp(nx * L[0] + ny * L[1] + nz * L[2]);+ // is this floor point in the shadow of the rim nearer the lamp? follow the ray up to the cut plane+ locate(W, x + 0.5 + L[0] / L[2] * d0, y + 0.5 + L[1] / L[2] * d0, h2);+ const lit = h2.kind === 2 && h2.id === hit.id ? 1 : 0;+ const spec = Math.pow(clamp(nx * Hh[0] + ny * Hh[1] + nz * Hh[2]), 60) * lit;+ const deep = clamp(d0 / (NAUT.WIDTH * h));+ t = lit ? 0.1 + 0.62 * Math.pow(1 - clamp(lam / L[2]), 1.15) + 0.08 * deep - 0.5 * spec * (body ? 1 : 0) : 0.66 + 0.24 * deep - 0.1 * (1 - lam);+ // the innermost camerae are too small for the pen to model: a stippler gives each one a+ // plain dark cup, lighter on the far side, and lets the pale septa carry the spiral+ const small = clamp((60 - h) / 35); t = t * (1 - small) + small * (0.62 - 0.3 * clamp((q - 0.45) / 0.5));+ t = clamp(t);+ }+ }+ raster[k] = t;+ }+ return { raster };+};diff --git a/engine/src/canvas-core/storybook.ts b/engine/src/canvas-core/storybook.tsindex 9aaa08b..b590223 100644--- a/engine/src/canvas-core/storybook.ts+++ b/engine/src/canvas-core/storybook.ts@@ -3,7 +3,7 @@// control points, so any difference you see is the MEDIUM, not the drawing.import { Env, GRAPHITE, Gfx, P, PENCIL, TINT, arc, heart, line, oval, rng, tube, turn, Ctx } from "./core";-const SHADE = { white: "#c9d2e4", rose: "#cf8291", denim: "#52739f", butter: "#d9b24f" };+export const SHADE = { white: "#c9d2e4", rose: "#cf8291", denim: "#52739f", butter: "#d9b24f" };const at = (o: P, pts: P[]): P[] => pts.map(([x, y]) => [o[0] + x, o[1] + y]);const dir = (a: P, b: P) => Math.atan2(b[1] - a[1], b[0] - a[0]);const HEAD: P[] = [[-70, -40], [-52, -58], [-10, -65], [34, -63], [62, -51], [75, -22], [77, 14], [67, 44], [34, 58], [-8, 61], [-46, 56], [-70, 39], [-79, 6], [-78, -20]];@@ -19,7 +19,7 @@ const handShape = (pose: Pose, k: number) => {pts.push(on(1.15, R), on(1.9, R * 0.98), [5 * k, 11 * k], [0, 7.5 * k]);return { pts, valleys, c };};-const hand = (g: Gfx, wrist: P, angle: number, pose: Pose, seed: number) => {+export const hand = (g: Gfx, wrist: P, angle: number, pose: Pose, seed: number) => {const flip = Math.cos(angle) < 0 ? -1 : 1, place = (pts: P[]): P[] => turn(pts.map(([x, y]) => [wrist[0] + x, wrist[1] + y * flip] as P), wrist[0], wrist[1], (angle * 180) / Math.PI);const h = handShape(pose, 1), shape = place(h.pts), cuff = place([[-7, -9.5], [3, -10.5], [4, 0], [3, 10.5], [-7, 9.5], [-8, 0]]);g.group("paint", () => { g.form(shape, TINT.white, SHADE.white, { seed, light: [-3, -4] }); g.form(cuff, TINT.rose, SHADE.rose, { seed: seed + 1, light: [-2, -3] }); });@@ -30,7 +30,7 @@ const hand = (g: Gfx, wrist: P, angle: number, pose: Pose, seed: number) => {[-0.45, 0.45].forEach((t, i) => g.pen(place(line([-5.5, t * 9], [2, t * 9.6])), { w: 1.6, seed: seed + 8 + i, wobble: 0.2, opacity: 0.65, retrace: false }));});};-const limb = (g: Gfx, from: P, to: P, bend: number, r: number, seed: number) => {+export const limb = (g: Gfx, from: P, to: P, bend: number, r: number, seed: number) => {const mid = line(from, to, bend)[1], shape = tube([from, mid, to], r, r * 0.86, false);const along = (t: number): P => { const a = t < 0.5 ? from : mid, b = t < 0.5 ? mid : to, u = t < 0.5 ? t * 2 : (t - 0.5) * 2; return [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u]; };g.group("paint", () => g.form(shape, TINT.white, SHADE.white, { seed, light: [-3, -3] }));diff --git a/engine/src/canvas-core/storybookDraw.ts b/engine/src/canvas-core/storybookDraw.tsnew file mode 100644index 0000000..2ec1c39--- /dev/null+++ b/engine/src/canvas-core/storybookDraw.ts@@ -0,0 +1,150 @@+// STORYBOOK · Bit, drawn. The storybook pencil + watercolour character, made the way a picture-book+// illustrator makes a character page.+//+// MEDIUM: a soft graphite pencil and pan watercolour on warm cold-press paper (the hand of `storybook.ts`).+// ORDER, the point of this film:+// (1) construction: blue-grey pencil, barely there. The head and body as two loose ovals, the gesture+// line through them, the shoulder line, the face cross (centre line + eye line), the arm gestures+// to each hand, the footprint. These stay in the finished page, as they do in real picture books;+// (2) pencil: a light graphite drawing of Bit over the construction, head first and working down,+// every contour drawn stroke by stroke (the same strokes the final line will retrace);+// (3) washes: the sheet's warm ground, sky, the peach of the light, the grass and its shadow, the four+// flowers, then Bit himself back to front (legs, boots, arms, body, antenna, head, cheeks), each+// wash spreading from where the brush touched and stopping short of its line;+// (4) the final line: full-weight graphite over the dry paint, head first again, then the ground+// line, the grass, the pebbles and the flower stems; last, paint flicked off the brush.+// LIGHT: one light, upper left (every form in drawBit is lit from [-x, -y]); cast shadow = the hatched+// and washed pool under his boots.+// The character is `storybook.ts`'s drawBit, called unchanged: a Gfx subclass decides which of its+// groups draw in each pass and how far along each stroke is. storybook.ts is not modified and has no+// host page, so nothing existing can change. The scene is re-authored here from drawStorybook's calls.+import { Gfx, PENCIL, TINT, oval, rng, turn, type Ctx, type Env, type Layer, type P } from "./core";+import type { Film } from "./film";+import { drawBit } from "./storybook";+import { checkOps, schedule, staged, type Op } from "./brokenColourKit";++const N = 450, HOLD = N - 30;+const META = { title: "Storybook · Bit, drawn", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" as const };+const SHEET = 560; // drawStorybook was composed on a 560 sheet+const POSE = { look: 1, tilt: 6, lean: 3, handL: [-80, -58] as P, handR: [94, -178] as P }, SEED = 3;+const BOB = Math.sin(SEED) * 2, ACTOR: [number, number, number] = [272, 492 + BOB * 2.75, 2.75 * (SHEET / 1080)];+const U = "#8d90a6";++// ---------------------------------------------------------------- a Gfx that draws one group of drawBit+type Mode = "census" | "sketch" | "paint" | "line";+type Rec = { kind: string; box: number[]; pens: number };+class Phase extends Gfx {+ mode: Mode = "census"; sel = -1; prog = 1; recs: Rec[] = []; scratch: Ctx | null = null;+ private gi = -1; private pi = 0;+ private note(pts: P[]) { const b = this.recs[this.gi]?.box; if (!b) return; for (const [x, y] of pts) { b[0] = Math.min(b[0], x); b[1] = Math.min(b[1], y); b[2] = Math.max(b[2], x); b[3] = Math.max(b[3], y); } }+ group(kind: "ink" | "paint" | "plain", fn: () => void, opts: Parameters<Gfx["group"]>[2] = {}) {+ const i = ++this.gi;+ if (this.mode === "census") { this.recs.push({ kind, box: [1e9, 1e9, -1e9, -1e9], pens: 0 }); const prev = this.cur; this.cur = this.scratch!; fn(); this.cur = prev; return; }+ if (i !== this.sel) return;+ this.pi = 0;+ if (this.mode === "paint") { if (kind !== "ink") super.group(kind, () => this.wet(fn), opts); return; }+ if (kind === "ink") super.group(kind, fn, this.mode === "sketch" ? { ...opts, alpha: (opts.alpha ?? 1) * 0.36 } : opts);+ }+ // the brush touched near the upper left of the shape (toward the light) and the pigment runs out from there+ private wet(fn: () => void) {+ if (this.prog >= 1) return fn();+ const [x0, y0, x1, y1] = this.recs[this.sel].box, at: P = [x0 + (x1 - x0) * 0.3, y0 + (y1 - y0) * 0.3], R = (Math.hypot(Math.max(at[0] - x0, x1 - at[0]), Math.max(at[1] - y0, y1 - at[1])) + 6) / 0.8 * Math.pow(this.prog, 0.8) + 2, c = this.cur, r = rng(this.sel * 17 + 5);+ c.save(); c.beginPath(); for (let k = 0; k < 20; k++) { const a = (k / 20) * Math.PI * 2, rr = R * (0.8 + 0.35 * r()); k ? c.lineTo(at[0] + Math.cos(a) * rr, at[1] + Math.sin(a) * rr) : c.moveTo(at[0] + Math.cos(a) * rr, at[1] + Math.sin(a) * rr); } c.closePath(); c.clip(); fn(); c.restore();+ }+ pen(pts: P[], o: Parameters<Gfx["pen"]>[1] = {}) {+ if (this.mode === "census") { this.note(pts); this.recs[this.gi].pens++; return; }+ const k = this.pi++, p = Math.min(1, this.prog * this.recs[this.gi].pens - k);+ if (p <= 0) return;+ super.pen(pts, { ...o, progress: Math.min(o.progress ?? 1, p), w: (o.w ?? 3.4) * (this.mode === "sketch" ? 0.62 : 1) });+ }+ form(pts: P[], color: string, shade: string, o: Parameters<Gfx["form"]>[3] = {}) { if (this.mode === "census") return this.note(pts); super.form(pts, color, shade, o); }+ wash(pts: P[], color: string, o: Parameters<Gfx["wash"]>[2] = {}) { if (this.mode === "census") return this.note(pts); super.wash(pts, color, o); }+ // The glow is a gradient. Painting a gradient into a POOLED layer changes how Chromium later rasterises+ // pencil strokes into that same layer (1/255 on every stroke, measured), so frame order would leak into+ // pixels. The gradient is painted on its own surface and copied in; the pool never sees a gradient.+ glow(cx: number, cy: number, r: number, color: string, opacity: number) {+ if (this.mode === "census") return this.note([[cx - r, cy - r], [cx + r, cy + r]]);+ const env = this.env, DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), key = `storybookDraw:glow:${DW}x${DH}`;+ let G = env.cache.get(key) as Layer | undefined; if (!G) { G = env.canvas(DW, DH); env.cache.set(key, G); }+ const c = this.cur, t = c.getTransform(), g = G.ctx;+ g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, DW, DH); g.setTransform(t.a, t.b, t.c, t.d, t.e, t.f);+ const grd = g.createRadialGradient(cx, cy, 0, cx, cy, r * 1.7), a = (v: number) => Math.round(255 * Math.max(0, Math.min(1, v * opacity))).toString(16).padStart(2, "0");+ [[0, 1], [0.35, 0.9], [0.6, 0.55], [0.8, 0.2], [1, 0]].forEach(([k, v]) => grd.addColorStop(k, color + a(v)));+ g.fillStyle = grd; g.fillRect(cx - r * 2, cy - r * 2, r * 4, r * 4);+ this.touch(cx - r * 1.8, cy - r * 1.8, cx + r * 1.8, cy + r * 1.8);+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.drawImage(G.canvas as CanvasImageSource, 0, 0); c.restore();+ }+}+const onSheet = (g: Gfx, env: Env) => g.push(0, 0, env.W / SHEET);+const census = (env: Env): Rec[] => {+ const key = "storybookDraw:census:v1"; let recs = env.cache.get(key) as Rec[] | undefined; if (recs) return recs;+ const s = env.canvas(1, 1), g = new Phase(s.ctx, env, 0, PENCIL); g.scratch = s.ctx;+ drawBit(g, 0, SEED, POSE); env.cache.set(key, g.recs); return g.recs;+};+const bitGroup = (mode: Mode, i: number) => (ctx: Ctx, env: Env, p: number) => {+ const g = new Phase(ctx, env, 0, PENCIL); g.recs = census(env); g.mode = mode; g.sel = i; g.prog = p;+ onSheet(g, env); g.push(...ACTOR); drawBit(g, 0, SEED, POSE); g.pop(); g.pop();+};+// a plain op on the sheet (or on Bit's own coordinates), progress handed to `fn`+const sheet = (fn: (g: Gfx, p: number) => void, actor = false) => (ctx: Ctx, env: Env, p: number) => { const g = new Gfx(ctx, env, 0, PENCIL); onSheet(g, env); if (actor) g.push(...ACTOR); fn(g, p); if (actor) g.pop(); g.pop(); };+const spread = (g: Gfx, at: P, reach: number, p: number, seed: number, fn: () => void) => {+ if (p >= 1) return fn();+ const c = g.cur, r = rng(seed), R = reach * Math.pow(p, 0.8) + 2; c.save(); c.beginPath();+ for (let k = 0; k < 20; k++) { const a = (k / 20) * Math.PI * 2, rr = R * (0.8 + 0.35 * r()); k ? c.lineTo(at[0] + Math.cos(a) * rr, at[1] + Math.sin(a) * rr) : c.moveTo(at[0] + Math.cos(a) * rr, at[1] + Math.sin(a) * rr); }+ c.closePath(); c.clip(); fn(); c.restore();+};++const FLOWERS: [number, number, string, number][] = [[64, 440, "#f2899c", 50], [488, 430, "#c7b3e0", 60], [446, 452, "#f5b98a", 70], [98, 462, "#f3d577", 80]];+const build = (env: Env): Op[] => {+ const ops: Op[] = [], add = (marks: ((ctx: Ctx, env: Env, p: number) => void)[], f0: number, f1: number, dur: number, pace?: (u: number) => number) => { const t = schedule(marks.length, f0, f1, dur, pace); marks.forEach((d, i) => ops.push({ ...t[i], draw: d })); };+ const recs = census(env), ink = recs.map((r, i) => ({ ...r, i })).filter((r) => r.kind === "ink"), paint = recs.map((r, i) => ({ ...r, i })).filter((r) => r.kind !== "ink");+ const topDown = [...ink].sort((a, b) => a.box[1] - b.box[1]);+ const pen = (pts: P[], o: Parameters<Gfx["pen"]>[1], actor = false) => sheet((g, p) => g.group("ink", () => g.pen(pts, { ...o, progress: p })), actor);+ // (1) construction+ const hc: P = [POSE.lean * 0.6, -200], H = (pts: P[]) => turn(pts.map(([x, y]) => [hc[0] + x, hc[1] + y] as P), hc[0], hc[1], POSE.tilt);+ add([+ pen(turn(oval(300, 214, 128, 104, 12), 300, 214, 6), { closed: true, w: 1.4, color: U, seed: 9, opacity: 0.45, wobble: 2 }),+ pen(oval(292, 392, 86, 92, 10), { closed: true, w: 1.4, color: U, seed: 10, opacity: 0.42, wobble: 2 }),+ pen([[318, 96], [300, 214], [288, 400], [286, 500]], { w: 1.3, color: U, seed: 11, opacity: 0.42 }),+ pen([[170, 232], [300, 214], [432, 196]], { w: 1.3, color: U, seed: 12, opacity: 0.4 }),+ pen(H([[-4, -66], [0, 0], [4, 64]]), { w: 1.6, color: U, seed: 13, opacity: 0.4, wobble: 1 }, true),+ pen(H([[-78, 4], [0, 8], [78, 4]]), { w: 1.6, color: U, seed: 14, opacity: 0.4, wobble: 1 }, true),+ pen([[-50, -28], [-68, -44], [-80, -58]], { w: 1.5, color: U, seed: 15, opacity: 0.38, wobble: 1 }, true),+ pen([[50, -28], [76, -100], [94, -178]], { w: 1.5, color: U, seed: 16, opacity: 0.38, wobble: 1 }, true),+ pen(oval(0, 0, 62, 9, 10), { closed: true, w: 1.5, color: U, seed: 17, opacity: 0.36, wobble: 1 }, true),+ ], 0.5, 58, 8);+ // (2) the pencil drawing, head first+ add(topDown.map((r) => bitGroup("sketch", r.i)), 57, 150, 10);+ // (3) washes: the sheet, then the flowers, then Bit back to front+ const wash = (pts: P[], color: string, alpha: number, seed: number, at: P, _reach: number) => sheet((g, p) => g.group("paint", () => spread(g, at, (Math.max(...pts.map(([x, y]) => Math.hypot(x - at[0], y - at[1]))) + 16) / 0.8, p, seed, () => g.wash(pts, color, { alpha, seed }))));+ add([+ wash([[40, 46], [170, 36], [300, 42], [430, 34], [522, 44], [528, 170], [520, 300], [526, 430], [518, 488], [400, 480], [280, 490], [150, 482], [42, 490], [34, 380], [42, 250], [36, 130]], "#f3d9b4", 0.62, 2, [60, 60], 720),+ wash(oval(170, 150, 150, 105, 9), "#a9cdea", 0.24, 3, [80, 90], 260),+ wash(oval(420, 330, 120, 150, 9), "#f2b9a0", 0.26, 4, [340, 210], 260),+ wash(oval(318, 96, 80, 70, 8), TINT.glow, 0.5, 5, [270, 50], 160),+ wash([[34, 470], [150, 452], [300, 460], [430, 450], [530, 466], [524, 530], [300, 538], [44, 530]], "#9cc79a", 0.62, 6, [40, 465], 520),+ wash([[60, 486], [200, 474], [330, 480], [330, 500], [190, 506], [70, 504]], "#6fa874", 0.35, 7, [70, 488], 280),+ wash(oval(292, 494, 124, 13, 10), "#7d6fa8", 0.42, 8, [180, 490], 260),+ ], 149, 212, 16);+ add(FLOWERS.map(([x, y, c, seed]) => sheet((g, p) => g.group("paint", () => spread(g, [x - 6, y - 6], 40, p, seed, () => { const flat = { dx: 3, dy: 2, shrink: 0.94, rim: true }; [0, 1, 2, 3, 4].forEach((i) => g.wash(oval(x + Math.cos(i * 1.256 + 0.4) * 9, y + Math.sin(i * 1.256 + 0.4) * 9, 7.5, 7.5, 6), c, { alpha: 0.85, seed: seed + i, ...flat })); g.wash(oval(x, y, 3.4, 3.4, 5), TINT.butter, { alpha: 0.95, seed: seed + 6, ...flat }); })))), 211, 236, 8);+ add(paint.map((r) => bitGroup("paint", r.i)), 235, 300, 8);+ // (4) the final line, head first, then the ground, the grass and the pebbles, then the flower stems+ add(topDown.map((r) => bitGroup("line", r.i)), 299, 372, 8, (u) => u * 0.85 + u * u * 0.15);+ add([+ pen([[36, 470], [150, 454], [300, 461], [430, 452], [530, 468]], { w: 2, seed: 13, opacity: 0.55 }),+ ...[[66, 0], [84, 1], [104, 0], [128, 1], [430, 0], [452, 1], [474, 0], [500, 1]].map(([x, k], i) => pen([[x, 472], [x + (k ? 5 : -4), 456 - (i % 3) * 4], [x + (k ? 9 : -8), 444 - (i % 3) * 5]], { w: 1.9, color: "#5f8f62", seed: 20 + i, retrace: false })),+ ...[[176, 512, 9, 5], [396, 516, 11, 6], [232, 524, 6, 4]].map(([x, y, a, b], i) => pen(oval(x, y, a, b, 7), { closed: true, w: 1.6, seed: 40 + i, opacity: 0.6 })),+ ], 371, 393, 3);+ add(FLOWERS.map(([x, y, , seed]) => sheet((g, p) => g.group("ink", () => { g.pen([[x, y + 9], [x + 2, y + 24], [x - 1, y + 40]], { w: 1.8, color: "#6f9b6a", seed: seed + 7, retrace: false, progress: Math.min(1, p * 2) }); if (p > 0.5) g.pen(oval(x, y, 16, 16, 9), { closed: true, w: 1.5, seed: seed + 8, opacity: 0.6, wobble: 2, progress: (p - 0.5) * 2 }); }))), 392, 406, 4);+ // paint flicked off the brush: every drop lands at once in its flick, the flicks one after another+ add([[5, 26, [50, 60, 510, 470], "#e9a887", 3], [8, 12, [60, 380, 500, 520], "#6fa874", 2.6]].map(([sd, n, box, col, rmax]) => sheet((g, p) => g.group("paint", () => { const c = g.cur, r = rng(sd as number), bx = box as number[]; for (let i = 0; i < (n as number); i++) { const x = bx[0] + r() * (bx[2] - bx[0]), y = bx[1] + r() * (bx[3] - bx[1]), k = r(), a = 0.5 * (0.5 + r() * 0.5); if (i >= Math.ceil((n as number) * p)) continue; g.touch(x - 5, y - 5, x + 5, y + 5); c.globalAlpha = a; c.fillStyle = col as string; c.beginPath(); c.arc(x, y, 0.5 + k * k * (rmax as number), 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; }))), 405, HOLD, 5);+ return checkOps(ops, HOLD);+};++const KEY = "storybookDraw:ops:v1";+export const drawStorybookDraw = (ctx: Ctx, frame: number, env: Env) => staged("storybookDraw", () => { let o = env.cache.get(KEY) as Op[] | undefined; if (!o) { o = build(env); env.cache.set(KEY, o); } return o; },+ (c, e) => { c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.fillStyle = "#fbf6ea"; c.fillRect(0, 0, e.W, e.H); },+ (c, e) => { const g = new Gfx(c, e, 0, PENCIL); g.paper("paper", 0.13); g.vignette("rgba(90,50,50,0.11)"); g.paper("coldpress", 0.2); })(ctx, frame, env);++export const STYLE = { id: "storybookDraw", name: "Storybook pencil + watercolour, drawn", family: "watercolour", medium: "soft graphite and pan watercolour on warm cold-press: construction, pencil, washes, final line", nearest: "storybook", hero: "Bit, the wind-up robot, waving" };+export const storybookDraw: Film = { meta: META, assets: { images: {} }, shots: [{ id: "storybookDraw", start: 0, end: N, draw: drawStorybookDraw }] };diff --git a/engine/src/canvas-core/sumiE.ts b/engine/src/canvas-core/sumiE.tsnew file mode 100644index 0000000..3484321--- /dev/null+++ b/engine/src/canvas-core/sumiE.ts@@ -0,0 +1,268 @@+import { Gfx, rng, fractal, type Medium, type P } from "./core";+import type { Film } from "./film";+import { clamp, lerpP, resample, smooth } from "./gallery";+import { brush, strokeDraw, timeline, runProcess, tone, JIAO, NONG, ZHONG, DAN, QING, type Brush, type Proc } from "./sumiEKit";++// BAMBOO IN WIND, A SPARROW · sumi-e (水墨, ink painting on xuan paper).+//+// MEDIUM, physically: one soft goat-and-wolf-hair brush, loaded once from an inkstone and+// reloaded rarely, on unsized xuan (rice) paper that drinks ink the instant it touches. Nothing+// can be corrected or covered: every mark is one gesture, laid once.+// THE MARK: a brush of real hairs. Each hair holds its own ink and spends it with travel, the+// edge hairs first, so a stroke starts wet and dense and ends in dry-brush: "flying white" (飞白),+// streaks of bare paper running WITH the stroke, and split hairs splaying at the lift. Where the+// brush slows (touch-down, the pause at a bamboo node, the lift) the ink bleeds into the paper+// fibres: a soft halo and fine feathers wicking outward. That halo is the tell of absorbent paper.+// THE EDGE: soft-feathered where wet, broken and bristled where dry. Never a clean outline.+// TONE: only by dilution, the five inks (墨分五色): scorched, thick, heavy, light, clear. The front+// stalk is thick ink, the stalk behind it light, the farthest clear: depth is dilution.+// ORDER (the Mustard Seed Garden manual's bamboo order): stalks first, each in single upward+// strokes one segment at a time, the brush pausing and lifting at every node; then the nodes in+// darker ink; then the branches from the nodes; then the leaves in pressed-lifted strokes, in+// groups (个 three, 介 four), front leaves thick, back leaves light; then the bird (beak, eye,+// head, back, wing, tail, belly, feet, the manual's own order for birds); then dry accents; the+// seal is stamped last.+// PAPER: warm unbleached xuan, long fibres and bark flecks in the sheet, no tooth to speak of.+// LIGHT: diffuse daylight from the upper left. Sumi-e carries light by leaving paper, not by+// cast shadow: the sparrow's lit crown and back are the brush's dry lift, its belly is bare paper+// with one clear-ink wash on the underside away from the light.+// SUBJECT: two stalks of bamboo (Phyllostachys, the painter's bamboo) and a third far behind,+// bowed right by a wind from the left, leaves streaming downwind. A Eurasian tree sparrow+// (Passer montanus, the sparrow of Chinese bird-and-flower painting) grips a side branch, facing+// INTO the wind, feathers sleeked: the one still thing in a moving picture.+// REFERENCE (from knowledge): the bamboo plates of the Mustard Seed Garden Manual (芥子园画传):+// segment proportions (short at the base, longest mid-stalk), node strokes, leaf groups and+// "wind bamboo" (风竹) leaf angles; Wu Zhen and Zheng Banqiao's wind bamboo for the bowing stalk;+// Qi Baishi's sparrows for the stroke economy: chestnut cap, black ear spot on a white cheek,+// black bib, streaked mantle, barred wing, belly left as paper.+// SEAL: cinnabar paste, a baiwen (white-line) seal: the characters are cut INTO the stone, so they+// print as paper inside red. The glyphs are an invented seal-script mark, deliberately not text.++const SUMI_M: Medium = { nib: 1, taper: 1, pressure: 1, retrace: false, wobble: 0, rough: 0 };+const PAPER = "#f3ede0";+const W = 1080, H = 1080; // the frame; everything below is authored in these units+const N = 510; // 17 s at 30 fps; the last 30 frames are the finished painting++// ---------------------------------------------------------------- the paper+const ground = (g: Gfx) => {+ const c = g.cur, e = g.env; c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.fillStyle = PAPER; c.fillRect(0, 0, e.W, e.H);+ // the sheet: long fibres laid in the vat, and flecks of bark that were never beaten out+ g.group("plain", () => {+ const k = g.cur, r = rng(501); k.lineCap = "round";+ for (let i = 0; i < 340; i++) {+ const x = r() * e.W, y = r() * e.H, a = (fractal(502, x, y, 0.004, 0.004, 2) - 0.5) * 5, L = 18 + r() * 70, bend = (r() - 0.5) * 0.5;+ k.strokeStyle = r() < 0.5 ? "#d9cfbc" : "#fbf7ee"; k.globalAlpha = 0.35 + r() * 0.35; k.lineWidth = 0.4 + r() * 0.6;+ k.beginPath(); k.moveTo(x, y); k.quadraticCurveTo(x + Math.cos(a + bend) * L * 0.5, y + Math.sin(a + bend) * L * 0.5, x + Math.cos(a) * L, y + Math.sin(a) * L); k.stroke();+ }+ for (let i = 0; i < 26; i++) { const x = r() * e.W, y = r() * e.H, a = r() * 6.28, L = 1.5 + r() * 4; k.strokeStyle = "#8f806b"; k.globalAlpha = 0.25 + r() * 0.3; k.lineWidth = 0.6 + r() * 0.5; k.beginPath(); k.moveTo(x, y); k.lineTo(x + Math.cos(a) * L, y + Math.sin(a) * L); k.stroke(); }+ k.globalAlpha = 1; g.touch(0, 0, e.W, e.H);+ });+};+const finish = (g: Gfx) => { g.paper("paper", 0.1); g.paper("coldpress", 0.045); };++// ---------------------------------------------------------------- stalks+type Stalk = { ctrl: P[]; w0: number; w1: number; ink: number; segs: number[]; gap: number; seed: number; load: number; dry: number };+// Wind from the left: every stalk bows right, more toward its top. Segments are shortest at the+// base, longest mid-stalk, shorter again near the crown, as the manual measures them.+const A: Stalk = { ctrl: [[708, 1100], [700, 900], [700, 700], [714, 500], [742, 300], [782, 120], [826, -30]], w0: 31, w1: 24, ink: NONG, segs: [62, 104, 138, 162, 176, 178, 170, 160, 150], gap: 9, seed: 10, load: 1.05, dry: 0.3 };+const B: Stalk = { ctrl: [[862, 1100], [864, 900], [876, 700], [900, 520], [940, 370], [992, 250], [1040, 170]], w0: 21, w1: 15, ink: DAN, segs: [58, 96, 130, 150, 160, 150, 132, 120], gap: 7, seed: 20, load: 1, dry: 0.3 };+const C: Stalk = { ctrl: [[990, 1100], [996, 950], [1012, 800], [1040, 660], [1080, 540], [1110, 470]], w0: 15, w1: 11, ink: QING, segs: [80, 120, 140, 150, 150], gap: 6, seed: 30, load: 1, dry: 0.22 };+const path = (s: Stalk) => { const p = resample(smooth(s.ctrl, false, 16), 900); const cum = [0]; for (let i = 1; i < p.length; i++) cum.push(cum[i - 1] + Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1])); return { p, cum }; };+const at = (pp: { p: P[]; cum: number[] }, s: number): { pt: P; tan: P } => {+ const { p, cum } = pp; let i = 1; while (i < p.length - 1 && cum[i] < s) i++;+ const f = clamp((s - cum[i - 1]) / (cum[i] - cum[i - 1] || 1)), pt = lerpP(p[i - 1], p[i], f), dx = p[i][0] - p[i - 1][0], dy = p[i][1] - p[i - 1][1], l = Math.hypot(dx, dy) || 1;+ return { pt, tan: [dx / l, dy / l] };+};+// one stalk as brush strokes: each segment one upward stroke, pressed flat at both ends (the+// knuckle), with a slow point at each end that bleeds; the brush drying as it climbs, reloaded+// halfway (the second breath of ink)+const stalkStrokes = (s: Stalk) => {+ const pp = path(s), out: { b: Brush; len: number }[] = [], nodes: { pt: P; tan: P; w: number }[] = [];+ let pos = 0; const total = pp.cum[pp.cum.length - 1];+ s.segs.forEach((L, i) => {+ if (pos >= total - 10) return;+ const s0 = pos, s1 = Math.min(total, pos + L), w = s.w0 + (s.w1 - s.w0) * (s0 / total), ctrl: P[] = [];+ for (let k = 0; k <= 4; k++) ctrl.push(at(pp, s0 + ((s1 - s0) * k) / 4).pt);+ const fresh = i === 0 || i === Math.ceil(s.segs.length / 2);+ out.push({ len: s1 - s0, b: { ctrl, w, ink: s.ink, press: [[0, 0.98], [0.04, 1.1], [0.14, 0.93], [0.5, 0.9], [0.86, 0.93], [0.965, 1.08], [1, 0.96]], load: s.load * (fresh ? 1.05 : 0.95 - 0.07 * (i % 3)), dry: s.dry * (0.8 + 0.3 * (i % 3)), edge: 0.45, split: 0.3, bleed: 0.7, slow: [[0.01, 0.45], [0.99, 0.3]], seed: s.seed * 100 + i } });+ pos = s1 + s.gap;+ if (pos < total - 10) nodes.push({ ...at(pp, s1 + s.gap / 2), w });+ });+ return { strokes: out, nodes };+};+// the node: a short dark stroke bridging the gap, like a shallow 乙, pressed at both ends+const nodeStroke = (n: { pt: P; tan: P; w: number }, ink: number, seed: number): Brush => {+ const [x, y] = n.pt, up: P = [n.tan[0] * -1, n.tan[1] * -1], nm: P = [-up[1], up[0]], h = n.w / 2 + 3, q = (a: number, b: number): P => [x + nm[0] * a + up[0] * b, y + nm[1] * a + up[1] * b];+ return { ctrl: [q(-h, -1.5), q(-h * 0.35, 2.5), q(h * 0.3, 2), q(h, -2)], w: Math.max(4, n.w * 0.22), ink, press: [[0, 0.8], [0.12, 1.05], [0.5, 0.55], [0.88, 1], [1, 0.6]], load: 1, dry: 0.1, edge: 0, split: 0.2, bleed: 0.8, slow: [[0.02, 0.4], [0.98, 0.4]], hairs: 12, seed };+};++// ---------------------------------------------------------------- branches and leaves+const twig = (ctrl: P[], w: number, ink: number, seed: number): Brush => ({ ctrl, w, ink, press: [[0, 0.9], [0.1, 1], [0.5, 0.8], [0.9, 0.55], [1, 0.3]], load: 0.95, dry: 0.12, edge: 0.1, split: 0.3, bleed: 0.6, slow: [[0.01, 0.6]], hairs: 10, seed });+// a leaf: the tip touches, presses to full width by a third of the way, lifts to a point. Wind+// leaves are long and flat, bent a little by the air; `bend` is how far they curve (px, signed).+const leaf = (base: P, deg: number, len: number, w: number, bend: number, ink: number, seed: number, load = 1): Brush => {+ const a = (deg * Math.PI) / 180, d: P = [Math.cos(a), Math.sin(a)], n: P = [-d[1], d[0]], q = (t: number, s: number): P => [base[0] + d[0] * len * t + n[0] * s, base[1] + d[1] * len * t + n[1] * s];+ return { ctrl: [q(0, 0), q(0.28, bend * 0.55), q(0.62, bend), q(0.86, bend * 0.8), q(1, bend * 0.45)], w, ink, press: [[0, 0.1], [0.08, 0.5], [0.28, 1], [0.55, 0.88], [0.82, 0.42], [1, 0.02]], load, dry: 0.1, edge: -0.35, split: 0.55, bleed: 0.55, slow: [[0.03, 0.55]], seed };+};+type Cluster = { twigs: { ctrl: P[]; w: number }[]; leaves: [P, number, number, number, number][]; ink: number; seed: number }; // leaf: base, angle, length, width, bend+const CLUSTERS: Cluster[] = [+ // crown of the front stalk: a 个 group and two more, streaming right over the empty sky+ { ink: NONG, seed: 400, twigs: [{ ctrl: [[770, 186], [812, 158], [858, 140], [902, 136]], w: 6 }, { ctrl: [[818, 154], [846, 118], [876, 96]], w: 4 }],+ leaves: [[[902, 136], -6, 176, 27, -10], [[900, 138], 12, 166, 26, 8], [[898, 140], 28, 146, 24, 12], [[876, 96], -16, 150, 22, -6], [[874, 98], 4, 132, 21, 6], [[846, 146], 44, 128, 22, 10]] },+ // upper middle: a 介 group off the node above the bird, the densest dark of the picture+ { ink: NONG, seed: 420, twigs: [{ ctrl: [[736, 356], [788, 334], [846, 322], [900, 322]], w: 6.5 }, { ctrl: [[790, 334], [820, 360], [844, 372]], w: 4 }],+ leaves: [[[900, 322], -10, 170, 28, -8], [[898, 324], 6, 180, 29, 6], [[896, 326], 20, 162, 27, 12], [[894, 328], 36, 140, 25, 14], [[844, 372], 30, 146, 24, 10], [[842, 374], 52, 120, 22, 12]] },+ // lower right on the front stalk: heavy ink, turned further down by the gust+ { ink: ZHONG, seed: 440, twigs: [{ ctrl: [[712, 472], [760, 468], [806, 474], [846, 486]], w: 5.5 }],+ leaves: [[[846, 486], 8, 150, 25, 8], [[844, 488], 26, 140, 24, 12], [[842, 490], 44, 124, 22, 12]] },+ // the stalk behind: light ink, its crown leaves and one branch reaching off the right edge+ { ink: DAN, seed: 460, twigs: [{ ctrl: [[1000, 214], [1030, 206], [1052, 208]], w: 4 }, { ctrl: [[892, 540], [936, 532], [980, 536]], w: 4.5 }],+ leaves: [[[1040, 172], -14, 130, 21, -6], [[1044, 176], 6, 124, 20, 6], [[1050, 210], 24, 118, 20, 8], [[980, 536], 6, 140, 22, 6], [[978, 538], 22, 130, 21, 10], [[976, 540], 40, 118, 20, 10], [[974, 542], 58, 100, 18, 8]] },+ // the farthest stalk: clear ink, two leaves, the air between us and it+ { ink: QING, seed: 480, twigs: [{ ctrl: [[1032, 690], [1060, 690], [1084, 700]], w: 3.5 }],+ leaves: [[[1030, 692], 20, 110, 18, 6], [[1028, 694], 40, 100, 17, 8]] },+];+// the sparrow's branch: out of the front stalk's node, reaching left into the empty half, its+// leaf group at the tip blown back downwind under the bird+const PERCH: P = [528, 586];+const BRANCH: P[] = [[703, 612], [652, 596], [590, 587], [520, 586], [456, 592], [420, 600]];+const BRANCH_LEAVES: [P, number, number, number, number][] = [[[424, 600], 22, 128, 23, 10], [[426, 602], 42, 118, 22, 12], [[428, 604], 62, 100, 20, 10]];+const LOW = { twig: [[702, 836], [744, 830], [786, 836]] as P[], leaves: [[[786, 836], 16, 136, 23, 8], [[784, 838], 36, 120, 22, 12]] as [P, number, number, number, number][] };++// ---------------------------------------------------------------- the sparrow+// Authored in its own frame: origin where the toes grip the branch, x to its tail, y up is+// negative, facing LEFT into the wind. Body tilted ~25 degrees, tail down behind the branch.+const S = 1.62;+const LOWER = 6; // the body settles onto the branch: everything but the toes sits this much lower than authored+const sp = (pts: [number, number][], dy = LOWER): P[] => pts.map(([x, y]) => [PERCH[0] + x * S, PERCH[1] + (y + dy) * S]);+const bird = (ink: number, ctrl: [number, number][], w: number, press: [number, number][], seed: number, o: Partial<Brush> = {}): Brush => ({ ctrl: sp(ctrl), w: w * S, ink, press, load: 1, dry: 0.16, edge: 0, split: 0.4, bleed: 0.5, slow: [[0.02, 0.4]], hairs: Math.max(8, Math.round(w * 1.3)), seed, ...o });+const TAPER: [number, number][] = [[0, 0.5], [0.25, 1], [0.7, 0.8], [1, 0.1]];+const DAB: [number, number][] = [[0, 0.7], [0.3, 1], [0.7, 1], [1, 0.6]];+const SWELL: [number, number][] = [[0, 0.35], [0.22, 1], [0.75, 0.92], [1, 0.3]];+// Qi Baishi's economy: every part of the bird is a single stroke of the loaded brush, and none of+// it is laid into wet paper, so nothing melts into a smooth gradient. Where the brush ran dry the+// paper shows through in streaks; where it paused the ink bled a halo into the fibres; that is all.+const SPARROW: Brush[] = [+ // beak: two hairlines of scorched ink, the upper longer, flicked from the face outward+ bird(JIAO, [[-59, -73], [-66, -71.5], [-73, -68.5]], 4, [[0, 1], [0.6, 0.7], [1, 0.1]], 700, { dry: 0.05, bleed: 0.25, slow: [], hairs: 8 }),+ bird(JIAO, [[-59, -66.5], [-65, -66.8], [-70, -67.5]], 2.8, [[0, 1], [1, 0.1]], 701, { dry: 0.05, bleed: 0.25, slow: [], hairs: 6 }),+ // the head: ONE loaded dab of thick ink, pressed down over the crown and dragged back to the+ // nape, where the brush is already starting to run dry+ bird(NONG, [[-46.5, -84.0], [-42.2, -86.7], [-37.1, -86.5], [-33.0, -83.4], [-31.5, -78.5], [-32.3, -74.9]], 17, [[0, 0.5], [0.2, 1], [0.7, 1], [1, 0.5]], 703, { load: 1.1, dry: 0.45, streak: true, edge: 0.2, split: 0.7, bleed: 0.9, slow: [[0.05, 0.7]] }),+ // the eye: one tiny scorched dot at the edge of the cap+ bird(JIAO, [[-51, -73.8], [-52.2, -73], [-51.8, -71.6], [-50.4, -72], [-50.6, -73.4]], 2.4, [[0, 1], [1, 1]], 702, { dry: 0, bleed: 0.2, slow: [], hairs: 6 }),+ // the black ear spot and the bib: two small touches of the tip+ bird(ZHONG, [[-40, -68], [-35.5, -67], [-31.5, -69.5]], 3.6, [[0, 0.5], [0.4, 1], [1, 0.1]], 704, { dry: 0.2, bleed: 0.5, slow: [[0.1, 0.4]], hairs: 6 }),+ bird(NONG, [[-59.5, -62.5], [-57, -57], [-54, -52]], 6, [[0, 0.7], [0.35, 1], [1, 0.15]], 705, { dry: 0.1, bleed: 0.6, hairs: 8 }),+ // the back: the brush laid on its side and pressed, dragged from nape to rump; it breaks into+ // dry-brush streaks halfway, which is the streaked mantle+ bird(ZHONG, [[-30, -80], [-10, -79], [10, -73], [27, -62]], 20, [[0, 0.45], [0.18, 1], [0.8, 0.9], [1, 0.35]], 706, { load: 1, dry: 0.7, streak: true, edge: 0.4, split: 0.9, bleed: 0.7 }),+ // two quick dark dashes into the mantle for the black streaks+ bird(NONG, [[-16, -79], [-8, -77.5], [0, -75]], 2.2, [[0, 0.4], [0.3, 1], [1, 0.1]], 707, { dry: 0.5, bleed: 0.3, hairs: 5 }), bird(NONG, [[3, -74.5], [11, -70.5], [17, -66]], 2, [[0, 0.4], [0.3, 1], [1, 0.1]], 708, { dry: 0.5, bleed: 0.3, hairs: 5 }),+ // the wing: two pressed side-brush strokes, a sliver of bare paper left between them for the+ // white wing bar, the lower one paler and drier+ bird(ZHONG, [[-27, -66], [-9, -61], [11, -55], [28, -48]], 17, [[0, 0.5], [0.2, 1], [0.8, 0.85], [1, 0.3]], 710, { load: 1, dry: 0.6, streak: true, edge: 0.35, split: 0.9, bleed: 0.6 }),+ bird(0.48, [[-17, -50], [3, -45.5], [23, -40.5], [38, -36.5]], 13, [[0, 0.45], [0.25, 1], [1, 0.25]], 711, { load: 0.95, dry: 0.8, streak: true, edge: 0.3, split: 0.95, bleed: 0.5 }),+ // the flight feathers: two hairlines of thick ink to the wingtip+ bird(NONG, [[6, -54], [28, -45], [50, -35.5]], 3, [[0, 0.6], [0.3, 1], [1, 0.1]], 712, { dry: 0.25, bleed: 0.3, hairs: 6 }), bird(NONG, [[11, -48.5], [31, -40.5], [49, -32.5]], 2.6, [[0, 0.6], [0.3, 1], [1, 0.1]], 713, { dry: 0.3, bleed: 0.3, hairs: 6 }),+ // tail: two strokes from the rump down behind the branch, the second nearly dry+ bird(NONG, [[31, -50], [46, -41], [60, -31], [72, -21]], 8.5, [[0, 0.8], [0.3, 1], [1, 0.2]], 715, { dry: 0.6, streak: true, split: 0.9, bleed: 0.4 }),+ bird(ZHONG, [[29, -45], [43, -35], [56, -25], [66, -15]], 7.5, [[0, 0.8], [0.3, 1], [1, 0.15]], 716, { load: 0.95, dry: 0.8, streak: true, split: 0.95, bleed: 0.3 }),+ // the breast: one light hairline down the front, open where the light falls+ bird(DAN, [[-58.5, -58], [-57.5, -47], [-51.5, -36]], 2, [[0, 0.3], [0.5, 1], [1, 0.2]], 717, { dry: 0.1, bleed: 0.3, slow: [], hairs: 5 }),+ // the belly: one pale, well-diluted stroke along the underside, away from the light; laid on+ // dry paper, so its body stays a brushmark and only its slow ends bleed into the fibres+ bird(QING, [[-48, -34], [-34, -25.5], [-14, -21.5], [8, -23.5], [24, -30]], 10, [[0, 0.35], [0.2, 1], [0.75, 0.8], [1, 0.2]], 719, { load: 1, dry: 0.5, streak: true, edge: -0.2, split: 0.8, bleed: 1.2, slow: [[0.04, 1]] }),+];+// legs and toes in scorched ink, authored on the branch itself (not lowered): the short legs+// come out of the belly feathers, the front toes wrap over the branch, the hind toe grips behind+const toe = (ctrl: [number, number][], w: number, seed: number): Brush => ({ ...bird(JIAO, ctrl, w, [[0, 0.9], [0.7, 1], [1, 0.35]], seed, { dry: 0.05, bleed: 0.2, slow: [] }), ctrl: sp(ctrl, 0) });+const FEET: Brush[] = [+ toe([[-9, -13], [-8, -6], [-7, -0.5]], 1.6, 730), toe([[4, -13], [5, -6], [6, -0.5]], 1.6, 731),+ toe([[-7, -0.5], [-13, 0.6], [-17.5, 3.5]], 1.4, 732), toe([[6, -0.5], [0, 0.8], [-3.5, 4]], 1.4, 733), toe([[-7, -0.5], [-1.5, 2], [1.5, 5.5]], 1.3, 734), toe([[6, -0.5], [10, 1.5], [12, 5]], 1.2, 735),+];++// ---------------------------------------------------------------- dry accents+// moss dots (点苔) at the stalk foot and a dry scrub of ground: an almost empty brush dragged flat+const ACCENTS: Brush[] = [+ // a tuft of dry grass at the front stalk's foot: three quick upward flicks from an almost empty brush+ ...([[[654, 1090], [646, 1060], [630, 1034]], [[668, 1090], [666, 1062], [672, 1040]], [[742, 1090], [752, 1066], [770, 1048]], [[756, 1092], [770, 1074], [792, 1066]]] as P[][]).map((ctrl, i): Brush => ({ ctrl, w: 6, ink: NONG, press: [[0, 1], [0.5, 0.7], [1, 0.05]], load: 0.55, dry: 0.3, edge: 0.3, split: 0.9, bleed: 0.1, slow: [], hairs: 9, seed: 800 + i })),+ // moss dots (点苔): scorched, pressed and lifted, where the stalks leave the ground+ ...([[684, 1052], [700, 1064], [728, 1058], [846, 1066], [884, 1062], [870, 1078]] as P[]).map(([x, y], i): Brush => ({ ctrl: [[x, y], [x + 2.5, y + 1.8]], w: 6 + (i % 3) * 2, ink: JIAO, press: [[0, 0.9], [1, 0.8]], load: 1, dry: 0, edge: 0, split: 0, bleed: 0.8, slow: [[0.5, 0.5]], hairs: 10, seed: 810 + i })),+];++// ---------------------------------------------------------------- the seal+// cinnabar paste pressed from a carved stone: a red block with a worn, chipped border; the+// glyph strokes are cut into the stone, so they print as paper. Pressed once, at the end.+const SEAL = { x: 118, y: 896, s: 70 };+const GLYPHS: [number, number][][][] = [+ [[[0.12, 0.16], [0.88, 0.16]], [[0.5, 0.16], [0.5, 0.88]], [[0.16, 0.46], [0.84, 0.46]], [[0.2, 0.62], [0.2, 0.86], [0.8, 0.86], [0.8, 0.62]]],+ [[[0.16, 0.1], [0.16, 0.9]], [[0.16, 0.3], [0.86, 0.3], [0.86, 0.9]], [[0.44, 0.3], [0.44, 0.7], [0.68, 0.7]], [[0.16, 0.9], [0.62, 0.9]]],+ [[[0.1, 0.2], [0.9, 0.2]], [[0.3, 0.2], [0.3, 0.55], [0.7, 0.55], [0.7, 0.2]], [[0.5, 0.55], [0.5, 0.9]], [[0.14, 0.76], [0.86, 0.76]]],+ [[[0.18, 0.14], [0.82, 0.14], [0.82, 0.86], [0.18, 0.86], [0.18, 0.4], [0.6, 0.4], [0.6, 0.64], [0.4, 0.64]]],+];+const seal = (g: Gfx, press: number) => {+ if (press <= 0) return;+ const { x, y, s } = SEAL, r = rng(900);+ g.group("plain", () => {+ const k = g.cur; g.touch(x - 4, y - 4, x + s + 4, y + s + 4);+ // the block, its edge worn uneven by years of pressing+ k.fillStyle = "#b8352b"; k.globalAlpha = 0.92; k.beginPath();+ const edge: P[] = []; for (let i = 0; i < 40; i++) { const t = i / 10, side = Math.floor(t), f = t - side, j = (fractal(901, i, 0, 0.7, 0.7, 2) - 0.5) * 2.2; edge.push(side === 0 ? [x + s * f, y + j] : side === 1 ? [x + s + j, y + s * f] : side === 2 ? [x + s * (1 - f), y + s + j] : [x + j, y + s * (1 - f)]); }+ edge.forEach(([a, b], i) => (i ? k.lineTo(a, b) : k.moveTo(a, b))); k.closePath(); k.fill();+ // the carving: cut into the stone, knife-square ends, prints as paper+ k.globalCompositeOperation = "destination-out"; k.globalAlpha = 1; k.lineCap = "square"; k.lineJoin = "miter";+ const cell = (s - 12) / 2, order = [[1, 0], [1, 1], [0, 0], [0, 1]]; // seals read right column first, top to bottom+ GLYPHS.forEach((gl, gi) => { const [cx, cy] = order[gi], ox = x + 6 + cx * cell, oy = y + 6 + cy * cell; gl.forEach((line) => { k.lineWidth = cell * 0.13 * (0.9 + r() * 0.25); k.beginPath(); line.forEach(([u, v], i) => { const px = ox + cell * (0.08 + u * 0.84) + (r() - 0.5) * 0.8, py = oy + cell * (0.08 + v * 0.84) + (r() - 0.5) * 0.8; i ? k.lineTo(px, py) : k.moveTo(px, py); }); k.stroke(); }); });+ // the border line inside the block, and where it chipped+ k.lineWidth = 1.6; k.strokeRect(x + 3.2, y + 3.2, s - 6.4, s - 6.4);+ k.lineWidth = 1; for (let i = 0; i < 3; i++) { const a = r() * 4, px = a < 1 ? x + a * s : a < 2 ? x + s : a < 3 ? x + (a - 2) * s : x, py = a < 1 ? y : a < 2 ? y + (a - 1) * s : a < 3 ? y + s : y + (a - 3) * s; k.beginPath(); k.arc(px, py, 1.6 + r() * 2.2, 0, 6.28); k.fill(); }+ // paste pressed unevenly: where the stamp met the paper hardest the red is solid, elsewhere it breaks+ for (let i = 0; i < 90; i++) { const px = x + r() * s, py = y + r() * s, lighter = fractal(902, px, py, 0.06, 0.06, 2); if (lighter < 0.52) continue; k.globalAlpha = (lighter - 0.5) * 1.4; k.beginPath(); k.arc(px, py, 0.5 + r() * 1.3, 0, 6.28); k.fill(); }+ k.globalCompositeOperation = "source-over"; k.globalAlpha = 1;+ }, { blend: "multiply", alpha: clamp(0.35 + 0.65 * press), textures: ["risoSpeck"] });+};++// ---------------------------------------------------------------- the process+const build = (k: number): Proc => {+ const tl = timeline(8, k);+ const dur = (len: number, speed: number, min = 3) => Math.max(min, len / speed);+ // 1. the stalks, front first, each climbing segment by segment with a pause at every node+ const sA = stalkStrokes(A), sB = stalkStrokes(B), sC = stalkStrokes(C);+ [sA, sB, sC].forEach((st, si) => { st.strokes.forEach(({ b, len }) => { tl.add(dur(len, [24, 30, 34][si]) + 2, strokeDraw(b)); tl.wait(1); }); tl.wait(6); });+ // 2. the nodes, darker, bottom up, one flick each+ [[sA, JIAO], [sB, ZHONG], [sC, DAN]].forEach(([st, ink], si) => { (st as typeof sA).nodes.forEach((n, i) => tl.add(2.4, strokeDraw(nodeStroke(n, ink as number, 600 + si * 20 + i)))); });+ tl.wait(6);+ // 3. branches out of the nodes, quick and thin+ const twigs: Brush[] = [...CLUSTERS.flatMap((c, ci) => c.twigs.map((t, i) => twig(t.ctrl, t.w, Math.min(1, c.ink + 0.12), c.seed + 50 + i))), twig(BRANCH, 7, NONG, 650), twig(LOW.twig, 5, ZHONG, 651)];+ twigs.forEach((b) => tl.add(4, strokeDraw(b)));+ tl.wait(6);+ // 4. leaves: front groups in thick ink, then the heavy, then the light and clear ones behind+ const leafOps = (lv: [P, number, number, number, number][], ink: number, seed: number) => lv.map(([p, a, l, w, bd], i) => { const r = rng(seed * 3 + i); return leaf([p[0] - 6 + r() * 12, p[1] - 4 + r() * 8], a + (r() - 0.5) * 6, l * (0.9 + r() * 0.2), w, bd + (r() - 0.5) * 14, clamp(ink + (r() - 0.5) * 0.1), seed + i, 1 - (i % 3) * 0.06); });+ const groups: Brush[][] = [...CLUSTERS.map((c) => leafOps(c.leaves, c.ink, c.seed)), leafOps(BRANCH_LEAVES, ZHONG, 660), leafOps(LOW.leaves, ZHONG, 670)];+ groups.forEach((gr) => { gr.forEach((b) => tl.add(4.2, strokeDraw(b))); tl.wait(3); });+ tl.wait(6);+ // 5. the sparrow, in the manual's order, fiddly strokes slower than the leaves+ [...SPARROW, ...FEET].forEach((b) => tl.add(5, strokeDraw(b)));+ tl.wait(6);+ // 6. dry accents+ ACCENTS.forEach((b, i) => tl.add(i < 2 ? 7 : 2.5, strokeDraw(b)));+ tl.wait(8);+ // 7. the seal, pressed: the paste takes in the moment of pressure, then sits+ tl.add(6, (g, p) => seal(g, p));+ return { id: "sumiE", medium: SUMI_M, ground, ops: tl.ops, finish };+};+// author at a hand's pace, then fit: the whole process must finish 30 frames before the end+const RAW = build(1), RAW_END = RAW.ops[RAW.ops.length - 1].t1;+const PROC = build(Math.min(1, (N - 31 - 8) / (RAW_END - 8)));+const END = PROC.ops[PROC.ops.length - 1].t1;+if (END > N - 30) throw new Error(`sumiE: process ends at frame ${END}, needs to end by ${N - 30}`);++export const STYLE = { id: "sumiE", name: "Sumi-e ink painting", family: "ink", medium: "one loaded soft brush of sumi ink, five dilutions, on unsized absorbent xuan paper, with a cinnabar seal", nearest: "wren", hero: "bamboo in wind with a tree sparrow" };++export const sumiE: Film = {+ meta: { title: "Bamboo in wind · sumi-e", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },+ assets: { images: {} },+ shots: [{ id: "paint", start: 0, end: N, draw: (ctx, f, env) => runProcess(PROC, ctx, Math.min(f, END), env) }],+};+export { brush, tone };diff --git a/engine/src/canvas-core/sumiEKit.ts b/engine/src/canvas-core/sumiEKit.tsnew file mode 100644index 0000000..84ffa51--- /dev/null+++ b/engine/src/canvas-core/sumiEKit.ts@@ -0,0 +1,141 @@+// SUMI-E KIT. Two things the core does not have yet, both candidates for promotion:+//+// 1. runProcess: a still that draws itself as a list of timed marks ("ops"). Finished ops are+// painted once onto a cached surface whose key is (id, scale, how many ops are finished), and+// the cache is only ever EXTENDED (ops k..k' drawn on top) or rebuilt from the ground, so a+// cached frame and a cold frame are the same pixels. The ops still in the hand are drawn live+// at their progress, then `finish` (paper, sizing) goes over everything, every frame.+// 2. brush: one loaded brush of real hairs. Each hair carries its own ink load, spends it with+// travel (edge hairs faster), and skips where the paper's tooth wins once it runs low, so a+// stroke shifts from wet-dark to dry-brush ("flying white", split hairs) along its length.+// Slow points (touch-down, node pauses, lift) bleed into the paper fibres.+import { Gfx, rng, fractal, type Ctx, type Env, type Layer, type Medium, type P } from "./core";+import { clamp, mix, profile, resample, smooth } from "./gallery";++// ---------------------------------------------------------------- the process runner+export type Op = { t0: number; t1: number; draw: (g: Gfx, p: number) => void };+export type Proc = { id: string; medium: Medium; ground: (g: Gfx) => void; ops: Op[]; finish?: (g: Gfx) => void };+export const prog = (f: number, t0: number, t1: number) => (f >= t1 ? 1 : f <= t0 ? 0 : (f - t0) / (t1 - t0)); // exactly 1 at and past the end+export const runProcess = (pr: Proc, ctx: Ctx, f: number, env: Env) => {+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale), ops = pr.ops;+ let k = 0; while (k < ops.length && ops[k].t1 <= f) k++;+ const key = `${pr.id}:done:${env.scale}:${DW}x${DH}`; let C = env.cache.get(key) as { k: number; L: Layer } | undefined;+ const on = (L: Layer) => { L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.globalAlpha = 1; L.ctx.globalCompositeOperation = "source-over"; return new Gfx(L.ctx, env, 0, pr.medium); };+ if (!C || C.k > k) { const L = C?.L ?? env.canvas(DW, DH); L.ctx.setTransform(1, 0, 0, 1, 0, 0); L.ctx.clearRect(0, 0, DW, DH); pr.ground(on(L)); C = { k: 0, L }; env.cache.set(key, C); }+ if (C.k < k) { const g = on(C.L); for (let i = C.k; i < k; i++) ops[i].draw(g, 1); C.k = k; }+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; ctx.drawImage(C.L.canvas as CanvasImageSource, 0, 0);+ const g = new Gfx(ctx, env, 0, pr.medium);+ for (let i = k; i < ops.length; i++) if (ops[i].t0 < f || ops[i].t1 <= f) ops[i].draw(g, prog(f, ops[i].t0, ops[i].t1));+ pr.finish?.(g);+};+// fit a process authored at a hand's pace into the frames available: the largest stretch k <= 1+// whose last op ends by `last` (many one-frame ops do not scale linearly, so search for it)+export const fit = (build: (k: number) => Proc, last: number): Proc => {+ const end = (p: Proc) => p.ops[p.ops.length - 1].t1; let lo = 0.05, hi = 1, best = build(1);+ if (end(best) <= last) return best;+ for (let i = 0; i < 24; i++) { const k = (lo + hi) / 2, p = build(k); if (end(p) <= last) { lo = k; best = p; } else hi = k; }+ if (end(best) > last) throw new Error(`${best.id}: the process cannot be fitted to end by frame ${last}`);+ return best;+};+// lay ops end to end: a cursor that hands out [t0, t1) windows with pauses between passes+// `k` stretches every duration and pause, so a process authored at a hand's pace can be fitted to the film+// `frac`: op windows may be fractions of a frame (a brush can lay several quick marks in one+// frame); otherwise every op gets at least one whole frame.+export const timeline = (start: number, k = 1, frac = false) => { let t = start; const ops: Op[] = []; return { ops, at: () => t, wait: (n: number) => { t += n * k; }, add: (dur: number, draw: Op["draw"]) => {+ if (frac) { const t0 = t; t += dur * k; ops.push({ t0, t1: t, draw }); return t; }+ const t0 = Math.round(t); t = Math.max(t0 + 1, t + dur * k); ops.push({ t0, t1: Math.round(t) > t0 ? Math.round(t) : t0 + 1, draw }); return t; } }; };++// ---------------------------------------------------------------- ink+// Five inks (墨分五色) are one stick of ink at five dilutions: scorched, thick, heavy, light,+// clear. Diluted sumi goes a little cool and blue as the carbon thins out; it never goes brown.+export const INK_BLACK = "#0f0d0c", INK_COOL = "#39414a";+export const tone = (v: number) => ({ color: mix(INK_BLACK, INK_COOL, clamp(1 - v) * 0.85), alpha: clamp(0.08 + 0.92 * Math.pow(clamp(v), 0.95)) });+export const JIAO = 1, NONG = 0.82, ZHONG = 0.6, DAN = 0.38, QING = 0.2;++export type Brush = {+ ctrl: P[]; // hand-placed control points of the stroke's centreline+ w: number; // full-press width, px+ press: [number, number][]; // pressure knots [t, 0..1.1] along the stroke+ ink: number; // dilution: 1 scorched .. 0.2 clear+ load?: number; // how much ink the brush carries at touch-down (1 = freshly loaded)+ dry?: number; // ink spent per 100 px of travel+ edge?: number; // >0 edge hairs carry more ink (side-laid brush), <0 the tip carries it+ split?: number; // how far dry hairs splay apart (0..1)+ bleed?: number; // how much the wet parts feather into the fibres+ wet?: number; // 0 laid on dry paper (crisp) .. 1 laid into a damp sheet (the whole edge goes soft)+ streak?: boolean; // a half-loaded brush: hairs hold very different amounts, so it breaks into streaks early and stays broken+ slow?: [number, number][]; // slow points [t, strength]: touch-down, pause, lift: they bleed+ hairs?: number; seed: number;+};+type Hair = { u: number; load: number };+const hairsOf = (b: Brush): Hair[] => {+ const n = b.hairs ?? Math.max(10, Math.min(46, Math.round(b.w * 1.25))), r = rng(b.seed * 7 + 3), e = b.edge ?? 0, L = b.load ?? 1, out: Hair[] = [];+ const v = b.streak ? 0.75 : 0.28; for (let i = 0; i < n; i++) { const u = -1 + (2 * (i + 0.5)) / n + (r() - 0.5) * (1.6 / n); out.push({ u, load: L * (1 + e * (u * u - 0.33)) * (1 - v / 2 + v * r()) }); }+ return out;+};+export const brushPath = (b: Brush) => { const s = smooth(b.ctrl, false, 10); let len = 0; for (let i = 1; i < s.length; i++) len += Math.hypot(s[i][0] - s[i - 1][0], s[i][1] - s[i - 1][1]); const n = Math.max(8, Math.round(len / 1.6)); return { pts: resample(s, n), len, n }; };++// draw the stroke up to `travel` (0..1 of its length). `soak` grows the bleed at slow points: a+// point the brush has passed keeps drinking ink into the fibres for a moment after it leaves.+export const brush = (g: Gfx, b: Brush, travel = 1, soak = 1) => {+ if (travel <= 0) return;+ const { pts, len, n } = brushPath(b), pr = profile(b.press), hs = hairsOf(b), T = tone(b.ink), dry = (b.dry ?? 0.25) / 100, split = b.split ?? 0.5, c = g.cur;+ const last = Math.max(1, Math.min(n - 1, Math.round((n - 1) * travel)));+ const nr: P[] = pts.map((_, i) => { const a = pts[Math.max(0, i - 1)], q = pts[Math.min(n - 1, i + 1)], dx = q[0] - a[0], dy = q[1] - a[1], l = Math.hypot(dx, dy) || 1; return [-dy / l, dx / l]; });+ const wid = (i: number) => b.w * pr(i / (n - 1));+ // 1. the bleed: slow points and the wet body feather into the paper, soft, under the crisp hairs+ const bl = b.bleed ?? 0.6;+ if (bl > 0) g.group("plain", () => {+ c.globalCompositeOperation = "source-over";+ const k = g.cur; k.fillStyle = T.color;+ (b.slow ?? []).forEach(([t, s], j) => {+ const i = Math.round(t * (n - 1)); if (i > last) return;+ const grow = clamp(soak * (i === last ? 0.6 : 1)), r0 = wid(i) * (0.5 + 0.35 * s) * (0.55 + 0.45 * Math.sqrt(grow)) + 2.5 * s, [x, y] = pts[i], rr = rng(b.seed * 31 + j);+ k.globalAlpha = T.alpha * 0.34 * s * bl; k.beginPath();+ for (let a = 0; a < 18; a++) { const th = (a / 18) * Math.PI * 2, f = 1 + (fractal(b.seed + j * 5, Math.cos(th) * 2 + 9, Math.sin(th) * 2 + 9, 0.9, 0.9, 2) - 0.5) * 0.7; const px = x + Math.cos(th) * r0 * f, py = y + Math.sin(th) * r0 * f; a ? k.lineTo(px, py) : k.moveTo(px, py); }+ k.closePath(); k.fill(); g.touch(x - r0 * 1.4, y - r0 * 1.4, x + r0 * 1.4, y + r0 * 1.4);+ // the feathers: ink wicking out along single fibres, the tell of absorbent paper+ k.strokeStyle = T.color; k.lineWidth = 0.55; k.lineCap = "round";+ for (let q = 0; q < Math.round(10 + 14 * s); q++) { const th = rr() * Math.PI * 2, d0 = r0 * (0.75 + rr() * 0.3), d1 = d0 + (2 + rr() * 7 * s) * Math.sqrt(grow), bend = (rr() - 0.5) * 0.6; k.globalAlpha = T.alpha * (0.25 + rr() * 0.3) * bl; k.beginPath(); k.moveTo(x + Math.cos(th) * d0, y + Math.sin(th) * d0); const ex = x + Math.cos(th + bend * 0.2) * d1, ey = y + Math.sin(th + bend * 0.2) * d1; k.lineTo(ex, ey); k.stroke(); g.touch(ex - 2, ey - 2, ex + 2, ey + 2); }+ });+ // the wet body: a halo a hair wider than the stroke wherever the brush was still wet+ k.globalAlpha = T.alpha * 0.16 * bl; k.beginPath();+ const L: P[] = [], R: P[] = [];+ for (let i = 0; i <= last; i++) { const wet = clamp((b.load ?? 1) - dry * (i / (n - 1)) * len * 1.2), h = (wid(i) / 2) * (0.9 + 0.25 * wet) + 1.6 * wet; L.push([pts[i][0] + nr[i][0] * h, pts[i][1] + nr[i][1] * h]); R.push([pts[i][0] - nr[i][0] * h, pts[i][1] - nr[i][1] * h]); }+ [...L, ...R.reverse()].forEach(([x, y], i) => (i ? k.lineTo(x, y) : k.moveTo(x, y))); k.closePath(); k.fill(); L.forEach(([x, y]) => g.touch(x - 3, y - 3, x + 3, y + 3)); R.forEach(([x, y]) => g.touch(x - 3, y - 3, x + 3, y + 3));+ k.globalAlpha = 1;+ }, { blend: "multiply", blur: 1.4 + 1.6 * Math.min(1.5, bl) + 3 * (b.wet ?? 0) });+ // 2. the hairs: each one lays its own line while it has ink, skipping where it runs dry. They+ // are drawn as ONE opaque mark and laid down at the ink's tone, because ink does not stack+ // with itself inside a single stroke; it stacks only where a second stroke crosses the first.+ g.group("plain", () => {+ const k = g.cur; k.strokeStyle = T.color; k.lineCap = "round"; k.lineJoin = "round";+ const tipLen = Math.min(len * 0.2, b.w * 0.45);+ hs.forEach((h, hi) => {+ let run: { p: P; w: number; q: number }[] = [];+ const flush = () => {+ for (let a = 0; a + 1 < run.length; a += 4) {+ const seg = run.slice(a, Math.min(run.length, a + 5)); let w = 0, q = 0; seg.forEach((s) => { w += s.w; q += s.q; }); w /= seg.length; q /= seg.length;+ k.lineWidth = w; k.beginPath(); seg.forEach((s, i) => (i ? k.lineTo(s.p[0], s.p[1]) : k.moveTo(s.p[0], s.p[1]))); k.stroke();+ }+ run = [];+ };+ for (let i = 0; i <= last; i++) {+ const s = (i / (n - 1)) * len, rem = h.load - dry * s * (1 + 0.7 * Math.abs(h.u)), q = clamp(rem * (b.streak ? 1.25 : 2.1));+ // the brush is a cone: its tip touches first and leaves last, so outer hairs start later and lift sooner+ const tipIn = tipLen * Math.pow(Math.abs(h.u), 1.6) * (0.8 + 0.4 * h.load), tipOut = tipLen * 0.7 * Math.pow(Math.abs(h.u), 1.6);+ if (s < tipIn || s > len - tipOut) { flush(); continue; }+ const nz = fractal(b.seed * 13 + hi, s * 0.045, hi * 0.83, 1, 1, 2), present = q * 1.3 > nz + 0.06;+ if (!present) { flush(); continue; }+ const W = wid(i), spl = (fractal(b.seed * 17 + hi, s * 0.02, hi * 0.5, 1, 1, 2) - 0.5) * split * (1 - q) * b.w * 0.7;+ const off = h.u * (W / 2) * (1 + 0.12 * (1 - q)) + spl, p: P = [pts[i][0] + nr[i][0] * off, pts[i][1] + nr[i][1] * off];+ run.push({ p, w: Math.max(0.45, (W / hs.length) * 2.3 * (0.75 + 0.25 * q)), q });+ g.touch(p[0] - 3, p[1] - 3, p[0] + 3, p[1] + 3);+ }+ flush();+ });+ k.globalAlpha = 1;+ }, { blend: "multiply", alpha: T.alpha * (1 - 0.35 * (b.wet ?? 0)), blur: b.wet ? 0.6 + 2.6 * b.wet : undefined });+};+// a stroke's op body: touch down (slow point bleeds), travel, lift, then keep soaking a moment+export const strokeDraw = (b: Brush) => (g: Gfx, p: number) => { const travel = clamp((p - 0.12) / 0.7), soak = clamp(p / 0.12) * 0.55 + clamp((p - 0.82) / 0.18) * 0.45; brush(g, b, p >= 1 ? 1 : Math.max(0.02, travel), p >= 1 ? 1 : soak); };diff --git a/engine/src/canvas-core/toyBrick.ts b/engine/src/canvas-core/toyBrick.tsnew file mode 100644index 0000000..5600f9f--- /dev/null+++ b/engine/src/canvas-core/toyBrick.ts@@ -0,0 +1,235 @@+// TOY BRICK · "the tug". A brick-built harbour tugboat on a baseplate, built step by step.+//+// MEDIUM (physical): moulded ABS toy bricks, rendered. Zero hand marks: flat plastic fills in+// the part's real colour (a fixed table of real toy-brick colours), one tone per face by the+// cube rule (top +0.10, lit side 0, far side -0.22), a thin bevel highlight where a top meets a+// side, dark seam hairlines where one part meets the next, studs as real cylinders (12 LDU wide,+// 4 high) with a highlight crescent toward the light and a shadow crescent away from it, and a+// soft ground shadow on the baseplate. Proportions are real: 1 stud = 20 LDU, brick 24, plate 8.+// MARKS: the part. Nothing is stroked by a hand; a part is placed.+// ORDER (the film, instruction-booklet grammar): the bare backdrop, then the baseplate drops in,+// then step by step, bottom up and back to front inside a layer, each part falls straight down+// its insertion axis, ghosted while it travels, and seats with a one-frame press-fit. The parts+// of the current step carry the booklet's yellow outline until the next step begins. A short+// settle (the whole model pressed home) and the finished model holds.+// PALETTE: real toy-brick colours only (spec 13 rule 9 table): Blue water, Light/Dark Bluish Grey+// quay, Red + Black hull, Reddish Brown deck, White superstructure, Yellow funnel, Medium Azure+// glass, Orange crates. BACKDROP: one flat studio colour.+// LIGHT: one key light from the upper left, a little in front: +Z faces lit, +X faces in shade,+// ground shadows thrown back and right.+// SUBJECT + REALISM: a harbour tug (reference, from knowledge: low wide hull with high bow and a+// heavy bow fender, tall wheelhouse forward of midships with windows all round, a squat funnel+// aft of it, towing bitts on the long low aft deck, a mast with a light), moored off a stone quay+// with bollards, a lamp and cargo crates. Look-alike parts, no buildability claim (spec 13-C a).+// NOT ITS NEAREST NEIGHBOUR (fox, cut-paper collage): no torn edge, no lift shadow per piece, no+// hand; the look is manufactured plastic and the process is assembly, not drawing.+import type { Ctx, Env, Layer } from "./core";+import type { Film } from "./film";+import { aabb, BRICK, Cam, drawPart, LIGHT, order, Part, PLATE, shade, STUD, STUD_H } from "./toyBrickKit";++void BRICK;+const C = { blue: "#1E5AA8", lbg: "#969696", dbg: "#646464", red: "#B40000", black: "#1B2A34", white: "#F4F4F4", yellow: "#FAC80A", brown: "#5F3109", azure: "#68C3E2", orange: "#D67923", tan: "#D7BA8C" };+const BACKDROP = "#E7E4DE", OUTLINE = "#FAC80A";+const N = 540, HOLD = 30, FALL = 10, DROP = 190; // frames; LDU a part falls from++// ---------------------------------------------------------------- the model, in build order+const model = (): Part[] => {+ const P: Part[] = []; let step = 0;+ const rect = (x0: number, z0: number, x1: number, z1: number): [number, number][] => [[x0, z0], [x1, z0], [x1, z1], [x0, z1]];+ const add = (foot: [number, number][], y0: number, h: number, color: string, studs = true, kind: Part["kind"] = "prism") => P.push({ id: P.length, color, kind, foot, y0, h, studs, step });+ const next = () => step++;+ // a rectangular course split into 2-wide rows of bricks, lengths staggered per course (running bond)+ const course = (x0: number, z0: number, x1: number, z1: number, y0: number, h: number, color: string, lens: number[], shift: number) => {+ for (let z = z0, r = 0; z < z1; z += 2, r++) { let x = x0; const L = [...lens.slice((r + shift) % lens.length), ...lens.slice(0, (r + shift) % lens.length)]; for (const l of L) { if (x >= x1) break; const e = Math.min(x1, x + l); add(rect(x, z, e, Math.min(z1, z + 2)), y0, h, color); x = e; } }+ };+ // 1: the baseplate+ add(rect(0, 0, 24, 18), -0.4, 0.4, C.blue); next();+ // 2-3: the quay, two courses, then its coping and a paved top+ course(0, 0, 24, 4, 0, 3, C.lbg, [6, 4, 8, 6], 0); next();+ course(0, 0, 24, 4, 3, 3, C.lbg, [4, 8, 6, 6], 1); next();+ for (let x = 0; x < 24; x += 6) add(rect(x, 0, x + 6, 3), 6, 1, C.lbg);+ for (let x = 0; x < 24; x += 8) add(rect(x, 3, x + 8, 4), 6, 1, C.dbg, false); next();+ // 4-6: the hull, three courses; the bow is a wedge, black as the tug's bow fender from course 2+ const bow: [number, number][] = [[17, 8], [20, 10.5], [20, 11.5], [17, 14]];+ course(4, 8, 17, 14, 0, 3, C.black, [4, 4, 3, 2], 0); add(bow, 0, 3, C.black); next();+ course(4, 8, 17, 14, 3, 3, C.red, [2, 4, 4, 3], 1); add(bow, 3, 3, C.black); next();+ course(4, 8, 17, 14, 6, 3, C.red, [3, 2, 4, 4], 2); add(bow, 6, 3, C.black); next();+ // 7: the deck: a black rubbing strake round the edge, reddish-brown planking inside+ add(rect(4, 8, 17, 9), 9, 1, C.black); add(rect(4, 9, 5, 14), 9, 1, C.black); add(rect(5, 13, 17, 14), 9, 1, C.black); add(bow, 9, 1, C.black);+ add(rect(5, 9, 11, 13), 9, 1, C.brown); add(rect(11, 9, 17, 13), 9, 1, C.brown); next();+ // 8-9: the deckhouse aft of midships, then the funnel on it+ add(rect(7, 9, 11, 11), 10, 3, C.white); add(rect(7, 11, 11, 13), 10, 3, C.white);+ add(rect(7, 9, 9, 13), 13, 3, C.white); add(rect(9, 9, 11, 13), 13, 3, C.white); next();+ add(rect(8, 10, 10, 12), 16, 3, C.yellow); add(rect(8, 10, 10, 12), 19, 3, C.yellow); add(rect(8, 10, 10, 12), 22, 1, C.black); next();+ // 10-11: the wheelhouse, two courses, then the window course with glass on the two faces we see+ add(rect(11, 9, 15, 11), 10, 3, C.white); add(rect(11, 11, 15, 13), 10, 3, C.white);+ add(rect(11, 9, 13, 13), 13, 3, C.white); add(rect(13, 9, 15, 13), 13, 3, C.white); next();+ add(rect(11, 9, 12, 10), 16, 3, C.white); add(rect(12, 9, 14, 10), 16, 3, C.white); add(rect(14, 9, 15, 10), 16, 3, C.white);+ add(rect(11, 10, 12, 12), 16, 3, C.white); add(rect(12, 10, 14, 12), 16, 3, C.white);+ add(rect(14, 10, 15, 12), 16, 3, C.azure); add(rect(11, 12, 12, 13), 16, 3, C.white); add(rect(12, 12, 14, 13), 16, 3, C.azure); add(rect(14, 12, 15, 13), 16, 3, C.white); next();+ // 12: roof with overhang, mast, searchlight+ add(rect(10, 8, 15, 13), 19, 1, C.dbg); next(); // roof, overhanging aft and to port only+ add(rect(12, 10, 13, 11), 20, 3, C.lbg, false, "round"); add(rect(12, 10, 13, 11), 23, 3, C.lbg, false, "round"); add(rect(12, 10, 13, 11), 26, 3, C.lbg, false, "round"); add(rect(12, 10, 13, 11), 29, 1, C.red, true, "round");+ add(rect(13, 11, 14, 12), 20, 1, C.yellow, true, "round"); next();+ // 13: towing bitts aft, a bollard on the foredeck+ add(rect(5, 9, 6, 10), 10, 3, C.dbg, true, "round"); add(rect(5, 12, 6, 13), 10, 3, C.dbg, true, "round"); add(rect(17, 10, 18, 11), 10, 2, C.black, true, "round"); next();+ // 14: the quay furniture: bollards, the harbour lamp, crates+ add(rect(6, 2, 7, 3), 7, 2, C.black, true, "round"); add(rect(15, 2, 16, 3), 7, 2, C.black, true, "round");+ add(rect(16, 0, 18, 2), 7, 3, C.orange); add(rect(18, 0, 20, 2), 7, 3, C.brown); add(rect(17, 0, 19, 2), 10, 3, C.orange);+ add(rect(21, 1, 22, 2), 7, 3, C.dbg, false, "round"); add(rect(21, 1, 22, 2), 10, 3, C.dbg, false, "round"); add(rect(21, 1, 22, 2), 13, 3, C.dbg, false, "round"); add(rect(21, 1, 22, 2), 16, 2, C.yellow, true, "round"); next();+ // 15: the water: a bow wave and the wake, flat tiles on the baseplate+ add(rect(20, 9, 22, 10), 0, 1, C.white, false); add(rect(20, 12, 22, 13), 0, 1, C.white, false); add(rect(21, 10, 22, 12), 0, 1, C.azure, false);+ add(rect(1, 10, 3, 12), 0, 1, C.white, false); add(rect(0, 9, 2, 10), 0, 1, C.azure, false); add(rect(0, 12, 2, 13), 0, 1, C.azure, false);+ return P;+};++// ---------------------------------------------------------------- schedule: one cue table+// Each step starts on a beat; its parts land on the 5-frame event grid, one or two per slot.+type Sched = { land: number[]; stepStart: number[]; stepEnd: number[]; settle: number };+const schedule = (P: Part[]): Sched => {+ const land = new Array(P.length).fill(0), steps = Math.max(...P.map((p) => p.step)) + 1, stepStart: number[] = [], stepEnd: number[] = [];+ land[0] = 20; stepStart[0] = 0; stepEnd[0] = 20; let t = 20;+ for (let s = 1; s < steps; s++) {+ // a step starts on a beat; its parts seat in at most four 5-frame slots, so a step is two beats+ const ids = P.filter((p) => p.step === s).map((p) => p.id), per = Math.ceil(ids.length / 4);+ const start = Math.ceil((t + 5) / 15) * 15; stepStart[s] = start;+ ids.forEach((id, k) => (land[id] = start + FALL + 5 * Math.floor(k / per)));+ t = Math.max(...ids.map((id) => land[id])); stepEnd[s] = t;+ }+ return { land, stepStart, stepEnd, settle: Math.ceil((t + 5) / 5) * 5 };+};++// ---------------------------------------------------------------- render+const build = (env: Env) => {+ let v = env.cache.get("toyBrick/build") as { P: Part[]; S: Sched; fit: [number, number, number] } | undefined;+ if (!v) {+ const P = model(), S = schedule(P);+ // fit the finished model into the frame (pure: from geometry only)+ const probe = new Cam(1, 0, 0); let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;+ P.forEach((p) => { const b = aabb(p); for (const X of [b.x0, b.x1]) for (const Y of [b.y0, b.y1]) for (const Z of [b.z0, b.z1]) { const q = probe.p(X, Y, Z); x0 = Math.min(x0, q[0]); x1 = Math.max(x1, q[0]); y0 = Math.min(y0, q[1]); y1 = Math.max(y1, q[1]); } });+ const s = Math.min((env.W * 0.86) / (x1 - x0), (env.H * 0.8) / (y1 - y0));+ v = { P, S, fit: [s, env.W / 2 - ((x0 + x1) / 2) * s, env.H / 2 - ((y0 + y1) / 2) * s + env.H * 0.02] };+ env.cache.set("toyBrick/build", v);+ }+ return v;+};+const layer = (env: Env, key: string): Layer => { let L = env.cache.get(key) as Layer | undefined; if (!L) { L = env.canvas(Math.round(env.W * env.scale), Math.round(env.H * env.scale)); env.cache.set(key, L); } return L; };+const HAIR = 0.7;++// the soft shadow of a set of parts on the baseplate (Y = 0): each part's box swept along the+// light onto the plane, filled small and drawn back up (the only blur, and no filter)+const shadowOf = (c: Ctx, cam: Cam, parts: { p: Part; dy: number }[], k: number) => {+ const sx = -LIGHT[0] / LIGHT[1], sz = -LIGHT[2] / LIGHT[1];+ c.fillStyle = "#000";+ parts.forEach(({ p, dy }) => {+ const b = aabb(p, dy); if (b.y0 < -0.5) return; const pts: [number, number][] = [];+ for (const Y of [b.y0, b.y1 - (p.studs ? STUD_H : 0)]) for (const X of [b.x0, b.x1]) for (const Z of [b.z0, b.z1]) { const q = cam.p(X + sx * Y, 0, Z + sz * Y); pts.push([q[0] * k, q[1] * k]); }+ const h = hull(pts); c.beginPath(); h.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill();+ });+};+const hull = (pts: [number, number][]) => {+ const q = [...pts].sort((a, b) => a[0] - b[0] || a[1] - b[1]), cr = (o: number[], a: number[], b: number[]) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);+ const lo: [number, number][] = [], up: [number, number][] = [];+ for (const p of q) { while (lo.length >= 2 && cr(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); }+ for (let i = q.length - 1; i >= 0; i--) { const p = q[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), ...up.slice(0, -1)];+};++const drawFrame = (ctx: Ctx, fr: number, env: Env) => {+ const { P, S, fit } = build(env), f = fr >= N - HOLD ? N - 1 : fr, sc = env.scale, W = Math.round(env.W * sc), H = Math.round(env.H * sc);+ const cam = new Cam(fit[0], fit[1], fit[2]);+ // the settle: the whole model pressed home, 1 LDU down and back, after the last part seats+ const settle = f >= S.settle && f < S.settle + 6 ? [0, 0.6, 1, 1, 0.6, 0.25][f - S.settle] : 0;+ const state = P.map((p) => { const L = S.land[p.id]; if (f < L - FALL) return null; if (f >= L) return { p, dy: (f === L ? -0.5 : 0) - (p.id > 0 ? settle : 0), moving: false, t: 1 };+ const t = (f - (L - FALL)) / FALL, e = 1 - (1 - t) ** 3; return { p, dy: DROP * (1 - e) * (p.id === 0 ? 2 : 1), moving: true, t }; });+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = BACKDROP; ctx.fillRect(0, 0, W, H);+ // the settle moves the finished model rigidly: two cached layers (plate + shadow, parts) and a+ // translate, instead of re-sorting and redrawing every part for six frames+ if (settle > 0) {+ const kb = `${sc}`, done = P.map((p) => ({ p, dy: 0 })), rest = done.filter((s) => s.p.id !== 0);+ let SL = env.cache.get("toyBrick/settle") as { key: string; base: Layer; parts: Layer } | undefined;+ if (!SL || SL.key !== kb) {+ const base = env.canvas(W, H), parts = env.canvas(W, H); base.ctx.setTransform(sc, 0, 0, sc, 0, 0); parts.ctx.setTransform(sc, 0, 0, sc, 0, 0);+ paintBase(base.ctx, env, cam, P[0], 0); paintShadow(base.ctx, env, cam, rest, 0.34);+ order(rest, cam).forEach((i) => drawPart(parts.ctx, cam, rest[i].p, 0, HAIR));+ SL = { key: kb, base, parts }; env.cache.set("toyBrick/settle", SL);+ }+ ctx.drawImage(SL.base.canvas, 0, 0); ctx.drawImage(SL.parts.canvas, 0, settle * 0.86603 * cam.s * sc); return;+ }+ const live = state.filter((s): s is NonNullable<typeof s> => !!s);+ if (!live.length) return;+ // settled = landed and not in its seating frame and not pressed; those are cacheable+ const stat = live.filter((s) => !s.moving && s.dy === 0), key = `${sc}|${stat.map((s) => s.p.id).join(",")}`;+ const base = stat.find((s) => s.p.id === 0);+ // --- the static layer: baseplate shadow on the backdrop, baseplate, parts' ground shadow, parts+ const L = layer(env, "toyBrick/static");+ if (env.cache.get("toyBrick/staticKey") !== key) {+ const c = L.ctx; c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, W, H); c.setTransform(sc, 0, 0, sc, 0, 0);+ if (base) paintBase(c, env, cam, base.p, 0);+ const rest = stat.filter((s) => s.p.id !== 0);+ if (base && rest.length) paintShadow(c, env, cam, rest, 0.34);+ order(rest.map((s) => ({ p: s.p, dy: 0 })), cam).forEach((i) => drawPart(c, cam, rest[i].p, 0, HAIR));+ env.cache.set("toyBrick/staticKey", key);+ }+ ctx.drawImage(L.canvas, 0, 0);+ // --- whatever is moving or seating, then any settled part that stands in front of it+ const dyn = live.filter((s) => s.moving || s.dy !== 0);+ if (!dyn.length) { outline(ctx, sc, cam, live, S, f); return; }+ ctx.setTransform(sc, 0, 0, sc, 0, 0);+ const all = [...stat.filter((s) => s.p.id !== 0), ...dyn.filter((s) => s.p.id !== 0)], ord = order(all.map((s) => ({ p: s.p, dy: s.dy })), cam);+ const baseDyn = dyn.find((s) => s.p.id === 0); if (baseDyn) paintBase(ctx, env, cam, baseDyn.p, baseDyn.dy, baseDyn.moving ? ghost(baseDyn.t) : 1);+ // ground shadows of parts falling onto the baseplate grow and sharpen as they come down+ dyn.forEach((s) => { if (s.p.id === 0 || s.p.y0 > 0 || !base) return; paintShadow(ctx, env, cam, [s], 0.34 * Math.min(1, 0.25 + 0.75 * s.t)); });+ let seen = false;+ const firstDyn = ord.findIndex((i) => all[i].moving || all[i].dy !== 0);+ ord.forEach((i, k) => {+ const s = all[i]; if (k < firstDyn) return;+ if (s.moving || s.dy !== 0) { seen = true; drawGhost(ctx, env, cam, s.p, s.dy, s.moving ? ghost(s.t) : 1); return; }+ if (seen) drawPart(ctx, cam, s.p, 0, HAIR); // a settled part in front of something moving+ });+ outline(ctx, sc, cam, live, S, f);+};+const ghost = (t: number) => 0.35 + 0.65 * Math.min(1, t / 0.6);+const drawGhost = (ctx: Ctx, env: Env, cam: Cam, p: Part, dy: number, a: number) => {+ if (a >= 1) { drawPart(ctx, cam, p, dy, HAIR); return; }+ const T = layer(env, "toyBrick/ghost"), c = T.ctx, sc = env.scale; c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, T.canvas.width, T.canvas.height); c.setTransform(sc, 0, 0, sc, 0, 0);+ drawPart(c, cam, p, dy, HAIR); ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = a; ctx.drawImage(T.canvas, 0, 0); ctx.restore();+};+const paintBase = (c: Ctx, env: Env, cam: Cam, p: Part, dy: number, a = 1) => {+ // the baseplate's own soft shadow on the backdrop, then the plate+ const k = 1 / 6, S = layer(env, "toyBrick/softBase"), sc = env.scale, w = Math.ceil((env.W * sc) * k), h = Math.ceil((env.H * sc) * k);+ const s = S.ctx; s.setTransform(1, 0, 0, 1, 0, 0); s.clearRect(0, 0, w + 2, h + 2); s.setTransform(sc * k, 0, 0, sc * k, 0, 0); s.fillStyle = "#000";+ const b = aabb(p, dy), q = [cam.p(b.x0, b.y0 - 2, b.z0), cam.p(b.x1, b.y0 - 2, b.z0), cam.p(b.x1, b.y0 - 2, b.z1), cam.p(b.x0, b.y0 - 2, b.z1)];+ s.beginPath(); q.forEach(([x, y], i) => (i ? s.lineTo(x + 10, y + 16) : s.moveTo(x + 10, y + 16))); s.closePath(); s.fill();+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 0.22 * a; c.imageSmoothingEnabled = true; c.drawImage(S.canvas, 0, 0, w, h, 0, 0, w / k, h / k); c.restore();+ const B = env.cache.get("toyBrick/basePix") as { L: Layer; key: string } | undefined, bk = `${sc}`;+ if (dy === 0 && a >= 1) {+ let BL = B; if (!BL || BL.key !== bk) { const Lb = env.canvas(Math.round(env.W * sc), Math.round(env.H * sc)); Lb.ctx.setTransform(sc, 0, 0, sc, 0, 0); drawPart(Lb.ctx, cam, p, 0, HAIR); BL = { L: Lb, key: bk }; env.cache.set("toyBrick/basePix", BL); }+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.drawImage(BL.L.canvas, 0, 0); c.restore();+ } else drawGhost(c, env, cam, p, dy, a);+};+const paintShadow = (c: Ctx, env: Env, cam: Cam, parts: { p: Part; dy: number }[], a: number) => {+ const k = 1 / 5, S = layer(env, "toyBrick/soft"), sc = env.scale, w = Math.ceil(env.W * sc * k), h = Math.ceil(env.H * sc * k), s = S.ctx;+ s.setTransform(1, 0, 0, 1, 0, 0); s.clearRect(0, 0, w + 2, h + 2); s.setTransform(sc * k, 0, 0, sc * k, 0, 0); shadowOf(s, cam, parts, 1);+ // contact darkness: the footprint itself, a second time, a little stronger+ c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.imageSmoothingEnabled = true; c.globalAlpha = a; c.drawImage(S.canvas, 0, 0, w, h, 0, 0, w / k, h / k); c.restore();+};+// booklet grammar: the parts of the step being built carry a yellow outline until the next step+const outline = (ctx: Ctx, sc: number, cam: Cam, live: { p: Part; dy: number; moving: boolean }[], S: Sched, f: number) => {+ let cur = -1; for (let s = 1; s < S.stepStart.length; s++) if (f >= S.stepStart[s]) cur = s;+ if (cur < 1) return; const nextStart = S.stepStart[cur + 1] ?? S.settle; if (f >= nextStart) return;+ ctx.save(); ctx.setTransform(sc, 0, 0, sc, 0, 0); ctx.strokeStyle = OUTLINE; ctx.lineWidth = 2; ctx.lineJoin = "round";+ live.forEach(({ p, dy, moving }) => { if (p.step !== cur || moving) return; const b = aabb(p, dy), pts: [number, number][] = []; for (const X of [b.x0, b.x1]) for (const Y of [b.y0, b.y1 - (p.studs ? 0 : 0)]) for (const Z of [b.z0, b.z1]) pts.push(cam.p(X, Y, Z));+ const h = hull(pts); ctx.beginPath(); h.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); ctx.stroke(); });+ ctx.restore();+};++export const toyBrick: Film = {+ meta: { title: "Toy brick · the tug", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },+ assets: { images: {} },+ shots: [{ id: "build", start: 0, end: N, draw: drawFrame }],+};+void PLATE; void STUD; void shade;++export const STYLE = { id: "toyBrick", name: "Toy brick", family: "rendered", medium: "moulded ABS toy bricks, rendered flat-plastic in orthographic view: face tones by the cube rule, bevel highlights, seam hairlines, real studs, a soft ground shadow", nearest: "fox", hero: "a brick-built harbour tugboat on a baseplate" };+export const toyBrickCues = () => schedule(model());diff --git a/engine/src/canvas-core/toyBrickKit.ts b/engine/src/canvas-core/toyBrickKit.tsnew file mode 100644index 0000000..b78253d--- /dev/null+++ b/engine/src/canvas-core/toyBrickKit.ts@@ -0,0 +1,123 @@+// TOY BRICK KIT. Studded toy bricks as geometry, rendered flat-plastic in orthographic view.+// Units: LDU (1 stud pitch = 20, plate = 8, brick = 24, stud d = 12, stud h = 4), so the 5:6+// brick proportion is right by construction. Parts are prisms over a convex footprint (studs on+// every whole stud cell inside it) or 1x1 rounds. Painter's order is solved per frame by+// pairwise separating axes on the parts' boxes; no z-buffer.+import type { Ctx } from "./core";++export const STUD = 20, PLATE = 8, BRICK = 24, STUD_R = 6, STUD_H = 4;+export type V3 = [number, number, number];+export type Part = {+ id: number; color: string; kind: "prism" | "round";+ foot: [number, number][]; // footprint, studs (x along X, z along Z), convex, CCW seen from above+ y0: number; h: number; // bottom in plates, height in plates+ studs: boolean; step: number; alpha?: number;+};++// ---------------------------------------------------------------- colour+const hex = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));+export const shade = (h: string, t: number) => { const c = hex(h).map((v) => Math.round(t >= 0 ? v + (255 - v) * t : v * (1 + t))); return `rgb(${c[0]},${c[1]},${c[2]})`; };++// ---------------------------------------------------------------- camera: ortho, azimuth 45, elevation 30+export class Cam {+ constructor(public s: number, public ox: number, public oy: number) {}+ p(X: number, Y: number, Z: number): [number, number] { return [this.ox + (X - Z) * 0.70711 * this.s, this.oy + (X + Z) * 0.35355 * this.s - Y * 0.86603 * this.s]; }+}+// light (toward the light), from the upper left and a little in front: +Z faces are the lit sides+export const LIGHT: V3 = (() => { const v: V3 = [-0.25, 1, 0.55]; const l = Math.hypot(...v); return v.map((c) => c / l) as V3; })();++// world box of a part, in LDU, with a vertical offset dy (LDU)+export const aabb = (p: Part, dy = 0) => {+ const xs = p.foot.map((q) => q[0] * STUD), zs = p.foot.map((q) => q[1] * STUD);+ return { x0: Math.min(...xs), x1: Math.max(...xs), z0: Math.min(...zs), z1: Math.max(...zs), y0: p.y0 * PLATE + dy, y1: (p.y0 + p.h) * PLATE + dy + (p.studs ? STUD_H : 0) };+};++// stud cells: whole cells inside the footprint+const inside = (foot: [number, number][], x: number, z: number) => { for (let i = 0; i < foot.length; i++) { const [ax, az] = foot[i], [bx, bz] = foot[(i + 1) % foot.length]; if ((bx - ax) * (z - az) - (bz - az) * (x - ax) < -1e-9) return false; } return true; };+export const studCells = (p: Part): [number, number][] => {+ if (!p.studs) return []; if (p.kind === "round") { const [x, z] = p.foot[0]; return [[x + 0.5, z + 0.5]]; }+ const xs = p.foot.map((q) => q[0]), zs = p.foot.map((q) => q[1]), out: [number, number][] = [];+ for (let x = Math.floor(Math.min(...xs)); x < Math.max(...xs); x++) for (let z = Math.floor(Math.min(...zs)); z < Math.max(...zs); z++)+ if ([[x, z], [x + 1, z], [x, z + 1], [x + 1, z + 1]].every(([a, b]) => inside(p.foot, a, b))) out.push([x + 0.5, z + 0.5]);+ return out.sort((a, b) => a[0] + a[1] - (b[0] + b[1])); // back to front+};++// ---------------------------------------------------------------- drawing one part+const polyPath = (c: Ctx, pts: [number, number][]) => { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); };+const ellipse = (c: Ctx, x: number, y: number, rx: number, ry: number) => { c.beginPath(); c.ellipse(x, y, rx, ry, 0, 0, Math.PI * 2); };++// tone for a vertical face with outward normal (nx, nz): +Z lit side ~0, +X dark side ~-0.22+const sideTone = (nx: number, nz: number) => -0.11 - 0.11 * (nx - nz);++export const drawPart = (c: Ctx, cam: Cam, p: Part, dy: number, hair: number) => {+ const Y0 = p.y0 * PLATE + dy, Y1 = (p.y0 + p.h) * PLATE + dy, s = cam.s, col = p.color;+ if (p.kind === "round") { const [x, z] = p.foot[0]; cylinder(c, cam, (x + 0.5) * STUD, Y0, Y1, (z + 0.5) * STUD, STUD * 0.48, col, hair); if (p.studs) stud(c, cam, (x + 0.5) * STUD, Y1, (z + 0.5) * STUD, col, hair); return; }+ const F = p.foot.map(([x, z]) => [x * STUD, z * STUD] as [number, number]), n = F.length;+ const seam = shade(col, -0.45), bev = shade(col, 0.32);+ // side faces that look at the camera (outward normal has +X or +Z)+ const faces: { pts: [number, number][]; t: number; a: [number, number]; b: [number, number] }[] = [];+ for (let i = 0; i < n; i++) {+ const a = F[i], b = F[(i + 1) % n], ex = b[0] - a[0], ez = b[1] - a[1], l = Math.hypot(ex, ez), nx = ez / l, nz = -ex / l; // CCW from above: outward = (ez, -ex)+ if (nx + nz <= 1e-6) continue;+ faces.push({ pts: [cam.p(a[0], Y0, a[1]), cam.p(b[0], Y0, b[1]), cam.p(b[0], Y1, b[1]), cam.p(a[0], Y1, a[1])], t: sideTone(nx, nz), a, b });+ }+ faces.forEach((f) => { polyPath(c, f.pts); c.fillStyle = shade(col, f.t); c.fill(); c.strokeStyle = shade(col, f.t); c.lineWidth = 0.6; c.stroke(); });+ const top = F.map(([x, z]) => cam.p(x, Y1, z)); polyPath(c, top); c.fillStyle = shade(col, 0.1); c.fill();+ // bevels: a light strip along every top edge that meets a visible side, and the vertical corners+ c.lineCap = "round";+ faces.forEach((f) => { const a = cam.p(f.a[0], Y1, f.a[1]), b = cam.p(f.b[0], Y1, f.b[1]); c.strokeStyle = bev; c.lineWidth = Math.max(1, 0.9 * s); c.beginPath(); c.moveTo(a[0], a[1] + 0.5 * s); c.lineTo(b[0], b[1] + 0.5 * s); c.stroke(); });+ for (let i = 0; i < faces.length; i++) for (let j = 0; j < faces.length; j++) if (i !== j && faces[i].b === faces[j].a) { const q0 = cam.p(faces[i].b[0], Y0, faces[i].b[1]), q1 = cam.p(faces[i].b[0], Y1, faces[i].b[1]); c.strokeStyle = shade(col, faces[i].t + 0.16); c.lineWidth = Math.max(1, 0.7 * s); c.beginPath(); c.moveTo(q0[0], q0[1]); c.lineTo(q1[0], q1[1]); c.stroke(); }+ // seams: a dark hairline round the silhouette of the side faces (where this part meets the next)+ c.strokeStyle = seam; c.lineWidth = hair; faces.forEach((f) => { c.beginPath(); c.moveTo(f.pts[0][0], f.pts[0][1]); c.lineTo(f.pts[1][0], f.pts[1][1]); c.moveTo(f.pts[3][0], f.pts[3][1]); c.lineTo(f.pts[2][0], f.pts[2][1]); c.stroke(); });+ if (faces.length) { const fl = faces[0], la = faces[faces.length - 1]; c.beginPath(); c.moveTo(fl.pts[0][0], fl.pts[0][1]); c.lineTo(fl.pts[3][0], fl.pts[3][1]); c.moveTo(la.pts[1][0], la.pts[1][1]); c.lineTo(la.pts[2][0], la.pts[2][1]); c.stroke(); }+ c.globalAlpha = 0.55; polyPath(c, top); c.stroke(); c.globalAlpha = 1;+ studCells(p).forEach(([x, z]) => stud(c, cam, x * STUD, Y1, z * STUD, col, hair));+};++// a stud: soft shadow crescent on the top it stands on, cylinder side lit left / dark right, top+// ellipse, a highlight crescent toward the light. Axis-aligned ellipses: rx = r*s, ry = r*s/2.+export const stud = (c: Ctx, cam: Cam, X: number, Y: number, Z: number, col: string, hair: number) => {+ const s = cam.s, r = STUD_R * s, b = cam.p(X, Y, Z), t = cam.p(X, Y + STUD_H, Z), hh = b[1] - t[1];+ c.fillStyle = shade(col, -0.2); c.globalAlpha = 0.55; ellipse(c, b[0] + r * 0.35, b[1] + r * 0.12, r * 1.02, r * 0.52); c.fill(); c.globalAlpha = 1;+ c.fillStyle = shade(col, -0.12); c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, 0, Math.PI); c.lineTo(t[0] - r, t[1]); c.ellipse(t[0], t[1], r, r / 2, 0, Math.PI, 0, true); c.closePath(); c.fill();+ c.fillStyle = shade(col, 0.02); c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, Math.PI * 0.55, Math.PI); c.lineTo(t[0] - r, t[1]); c.lineTo(t[0] - r * 0.3, t[1] + r * 0.48); c.closePath(); c.fill();+ c.fillStyle = shade(col, -0.3); c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, 0, Math.PI * 0.3); c.lineTo(t[0] + r * 0.62, t[1] + r * 0.4); c.lineTo(t[0] + r, t[1]); c.closePath(); c.fill();+ c.fillStyle = shade(col, 0.14); ellipse(c, t[0], t[1], r, r / 2); c.fill();+ c.strokeStyle = shade(col, 0.5); c.lineWidth = Math.max(1, 0.8 * s); c.lineCap = "round"; c.beginPath(); c.ellipse(t[0], t[1], r * 0.82, r * 0.4, 0, Math.PI * 1.08, Math.PI * 1.62); c.stroke();+ c.strokeStyle = shade(col, -0.45); c.lineWidth = hair * 0.8; c.globalAlpha = 0.5; c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, 0, Math.PI); c.stroke(); c.globalAlpha = 1;+ void hh;+};+// a 1x1 round: a cylinder with the same tone rule as the studs+export const cylinder = (c: Ctx, cam: Cam, X: number, Y0: number, Y1: number, Z: number, R: number, col: string, hair: number) => {+ const s = cam.s, r = R * s, b = cam.p(X, Y0, Z), t = cam.p(X, Y1, Z);+ c.fillStyle = shade(col, -0.11); c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, 0, Math.PI); c.lineTo(t[0] - r, t[1]); c.ellipse(t[0], t[1], r, r / 2, 0, Math.PI, 0, true); c.closePath(); c.fill();+ c.fillStyle = shade(col, 0.0); c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, Math.PI * 0.6, Math.PI); c.lineTo(t[0] - r, t[1]); c.lineTo(t[0] - r * 0.35, t[1]); c.lineTo(b[0] - r * 0.35, b[1] + r * 0.47); c.closePath(); c.fill();+ c.fillStyle = shade(col, -0.26); c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, 0, Math.PI * 0.28); c.lineTo(t[0] + r * 0.6, t[1] + r * 0.4); c.lineTo(t[0] + r, t[1]); c.closePath(); c.fill();+ c.strokeStyle = shade(col, 0.28); c.lineWidth = Math.max(1, 0.8 * s); c.beginPath(); c.moveTo(b[0] - r * 0.62, b[1] + r * 0.39); c.lineTo(t[0] - r * 0.62, t[1] + r * 0.39); c.stroke();+ c.fillStyle = shade(col, 0.1); ellipse(c, t[0], t[1], r, r / 2); c.fill();+ c.strokeStyle = shade(col, 0.34); c.lineWidth = Math.max(1, 0.9 * s); c.beginPath(); c.ellipse(t[0], t[1], r * 0.92, r * 0.44, 0, Math.PI * 0.95, Math.PI * 1.7); c.stroke();+ c.strokeStyle = shade(col, -0.45); c.lineWidth = hair; c.beginPath(); c.ellipse(b[0], b[1], r, r / 2, 0, 0, Math.PI); c.stroke();+};++// ---------------------------------------------------------------- painter's order+// B must be drawn after A if B is nearer along the first axis that separates them (X, then Z,+// then Y). Only pairs whose screen boxes overlap get an edge. Kahn's sort, ties by build order.+export const order = (parts: { p: Part; dy: number }[], cam: Cam): number[] => {+ const n = parts.length, bb = parts.map(({ p, dy }) => aabb(p, dy));+ const sb = bb.map((b) => { const xs: number[] = [], ys: number[] = []; for (const X of [b.x0, b.x1]) for (const Y of [b.y0, b.y1]) for (const Z of [b.z0, b.z1]) { const q = cam.p(X, Y, Z); xs.push(q[0]); ys.push(q[1]); } return [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)]; });+ const after: number[][] = Array.from({ length: n }, () => []), indeg = new Array(n).fill(0), E = 0.01;+ for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {+ const a = sb[i], b = sb[j]; if (a[1] <= b[0] || b[1] <= a[0] || a[3] <= b[2] || b[3] <= a[2]) continue;+ const A = bb[i], B = bb[j]; let front = -1;+ if (A.x1 <= B.x0 + E) front = j; else if (B.x1 <= A.x0 + E) front = i;+ else if (A.z1 <= B.z0 + E) front = j; else if (B.z1 <= A.z0 + E) front = i;+ else if (A.y1 - STUD_H * (parts[i].p.studs ? 1 : 0) <= B.y0 + E) front = j; else if (B.y1 - STUD_H * (parts[j].p.studs ? 1 : 0) <= A.y0 + E) front = i;+ if (front < 0) continue; const back = front === i ? j : i; after[back].push(front); indeg[front]++;+ }+ const out: number[] = [], ready: number[] = []; for (let i = 0; i < n; i++) if (!indeg[i]) ready.push(i);+ while (out.length < n) {+ if (!ready.length) { for (let i = 0; i < n; i++) if (indeg[i] > 0 && !out.includes(i)) { indeg[i] = 0; ready.push(i); break; } } // a cycle: break it by build order+ ready.sort((a, b) => a - b); const k = ready.shift()!; out.push(k); for (const m of after[k]) if (--indeg[m] === 0) ready.push(m);+ }+ return out;+};diff --git a/engine/src/canvas-core/woodcut.ts b/engine/src/canvas-core/woodcut.tsnew file mode 100644index 0000000..1bdd408--- /dev/null+++ b/engine/src/canvas-core/woodcut.ts@@ -0,0 +1,238 @@+import { rng, sample, type Ctx, type Env, type Layer, type P } from "./core";+import type { Film } from "./film";+import { bokashi, carved, clamp, fillAll, gouged, grain, path, rubMask, rubPath, washi } from "./woodcutKit";++// HERONS IN RAIN ON THE DRUM BRIDGE · ukiyo-e colour woodblock (nishiki-e).+//+// MEDIUM, physically: water-based pigment and rice paste brushed onto carved cherry blocks and+// printed by hand onto damp kozo washi, one block per colour, the sheet laid each time against+// the KENTO (an L-shaped notch and a straight guide cut in the block's margin) and rubbed from+// behind with a baren. The KEYBLOCK carries the black line (sumi): each line is a ridge left+// standing between two knife cuts, so its width steps and wanders where the carver re-set the+// knife and every end is a flat chisel cut, never the swell-and-taper of a brush or pen. Each+// COLOUR BLOCK prints a flat where the wood was left standing; big flats show the plank's grain+// and the speckle where the baren rubbed thin (goma-zuri). BOKASHI is the graded wipe: the+// printer wipes the inked block with a damp cloth so the colour runs from full to nothing.+//+// MARKS: carved line, flat colour, grain, bokashi. EDGE: the keyline's hard knife edge; colour+// flats land a hair off their keylines (kento registration is good, never perfect), so a thread+// of paper or an overlap shows at some edges. ORDER: keyblock first; then the colour blocks,+// lightest to darkest; the bokashi blocks last. PALETTE: sumi #1f1b18, usuzumi sky #c6c1b0,+// kihada yellow #d49c3a, heron grey #9fa4a4, far bank #adaf9c, wood #a77a4a, water #9ab5c4,+// near bank #7d8a73, rain grey #8a8983, bokashi bero-ai #2c4a78 and sumi-indigo #3a4557.+// PAPER: warm kozo washi with long curling bast fibres, the margin left bare, the kento pressed+// into it blind.+//+// NOT RISOGRAPH, NOT HALFTONE: no screen, no dots, no overprinted flat inks mixing into new+// colours. Colour is FLAT and shaped by the knife; tone is only bokashi; line is only the key.+//+// SUBJECT, REFERENCE (from knowledge): two grey herons (Ardea cinerea) in rain on the rail of a+// taiko-bashi (a steep wooden drum bridge), after the way Hiroshige crops a bridge large and lets+// rain cross the whole sheet in fine carved diagonals ("Sudden Shower over Shin-Ohashi", 1857),+// and his bird-and-flower prints of herons. Anatomy: dagger bill longer than the head; a black+// stripe from the eye running back into nape plumes; white face and neck with black streaks down+// its front; long pale plumes hanging from the lower neck; grey mantle and folded wing with a+// black patch at the bend and black primaries at the rear; long legs with the intertarsal joint+// bending BACK; three long front toes and a hind toe gripping the rail. One stands alert at the+// crest, neck up in its S; the other hunches further down the slope on one leg, neck sunk into+// its shoulders, as herons do in rain. Both face left, into the wind; the rain drives from the+// upper left. The bridge: kasagi top rail, a nuki mid-rail, posts, the keta deck girder with its+// beam ends, piles and a tie beam into the river; a far bank of trees lost in rain; reeds.+// LIGHT: flat rain light from above. Form comes from bokashi, not a cast shadow: the sky darkens+// to the top, the river deepens toward us, and the underside of the bridge throws a dark band of+// shade down onto the water beneath it (the cast shadow of the piece).++const W0 = 1080, M = 54, IN = { x0: M, y0: M, x1: W0 - M, y1: W0 - M };+const SUMI = "#1f1b18", SKY = "#c6c1b0", YELLOW = "#d49c3a", GREY = "#9fa4a4", FAR = "#adaf9c", WOOD = "#a77a4a", WATER = "#9ab5c4", NEAR = "#7d8a73", RAIN = "#8a8983", AI = "#2c4a78", INDIGO = "#3a4557", UNDER = "#3f3a3c";++// ---------------------------------------------------------------- the bridge+const Y = (x: number) => 470 + 0.0006 * (x - 380) * (x - 380); // the kasagi's centreline+const POSTS = [96, 246, 404, 560, 716, 876], PILES = [150, 430, 700, 972], WL = 956, SHORE = 548;+const band = (a: number, b: number, x0 = 20, x1 = 1060): P[] => { const top: P[] = [], bot: P[] = []; for (let x = x0; x <= x1; x += 8) { top.push([x, Y(x) + a]); bot.push([x, Y(x) + b]); } return [...top, ...bot.reverse()]; };+const edge = (off: number, x0 = 20, x1 = 1060): P[] => { const o: P[] = []; for (let x = x0; x <= x1; x += 24) o.push([x, Y(x) + off]); return o; };+const box = (x0: number, y0: number, x1: number, y1: number): P[] => [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];+const KASAGI = band(-11, 11), NUKI = band(64, 76), KETA = band(150, 196);+const postBox = (x: number) => box(x - 9, Y(x) + 11, x + 9, Y(x) + 150);+const pileBox = (x: number) => box(x - 14, Y(x) + 196, x + 14, WL);+const TIE: P[] = box(20, 852, 930, 870);+const BRACES: P[][] = PILES.slice(0, -1).map((x, i) => { const a: P = [x + 14, Y(x) + 214], b: P = [PILES[i + 1] - 14, 852]; const nx = -(b[1] - a[1]), ny = b[0] - a[0], l = Math.hypot(nx, ny), h = 7; return [[a[0] + (nx / l) * h, a[1] + (ny / l) * h], [b[0] + (nx / l) * h, b[1] + (ny / l) * h], [b[0] - (nx / l) * h, b[1] - (ny / l) * h], [a[0] - (nx / l) * h, a[1] - (ny / l) * h]]; });+const BEAMS = Array.from({ length: 17 }, (_, i) => 70 + i * 60);+const BRIDGE: P[][] = [KASAGI, NUKI, KETA, ...BEAMS.map((x) => box(x - 6, Y(x) + 194, x + 6, Y(x) + 209)), ...POSTS.map(postBox), ...PILES.map(pileBox), TIE, ...BRACES];++// ---------------------------------------------------------------- the herons (local: feet at 0,0, facing left)+type Heron = { strokes: [P[], number][]; solids: P[][]; outline: P[]; grey: P[]; legs: P[][]; toes: P[][]; eye: P; bill: P[] };+const seg = (pts: P[]) => sample(pts, false, 6);+const heronA = (): Heron => {+ const billTop: P[] = [[-116, -271], [-98, -275], [-82, -279], [-70, -283]], billBot: P[] = [[-116, -271], [-98, -270], [-82, -269], [-70, -267]];+ const head: P[] = [[-70, -283], [-62, -289], [-50, -289], [-42, -282]], neckBack: P[] = [[-42, -282], [-33, -266], [-24, -246], [-17, -222], [-15, -198], [-8, -176], [2, -162]];+ const back: P[] = [[2, -162], [20, -156], [42, -142], [62, -126], [80, -112], [94, -103]], under: P[] = [[94, -103], [70, -95], [48, -89], [24, -85]];+ const belly: P[] = [[24, -85], [6, -80], [-12, -84], [-30, -97], [-42, -114], [-46, -132]], neckFront: P[] = [[-70, -267], [-63, -256], [-54, -238], [-45, -216], [-44, -194], [-49, -172], [-50, -152], [-46, -132]];+ const wingEdge: P[] = [[-10, -152], [4, -134], [26, -116], [52, -106], [78, -102]];+ const outline = [...seg(billTop), ...seg(head), ...seg(neckBack), ...seg(back), ...seg(under), ...seg(belly), ...seg([...neckFront].reverse()), ...seg([...billBot].reverse())];+ return {+ strokes: [[billTop, 2.6], [billBot, 2.4], [head, 3.0], [neckBack, 3.2], [back, 3.8], [under, 3.0], [belly, 3.4], [neckFront, 3.0], [wingEdge, 2.8],+ [[[-47, -182], [-53, -164], [-55, -144]], 1.6], [[[-45, -178], [-49, -158], [-49, -138]], 1.5], [[[-42, -175], [-43, -156], [-40, -139]], 1.4], [[[-49, -188], [-57, -170], [-61, -150]], 1.5],+ [[[4, -148], [22, -134], [36, -125]], 1.5], [[[16, -153], [36, -139], [52, -128]], 1.5], [[[30, -146], [50, -132], [66, -121]], 1.4]],+ solids: [[[-67, -282], [-52, -286], [-36, -283], [-12, -281], [14, -284], [-8, -277], [-34, -276], [-56, -278]], [[44, -118], [66, -111], [94, -103], [70, -99], [48, -104]], [[-13, -155], [-3, -159], [5, -149], [-5, -142]],+ ...[0.3, 0.42, 0.54, 0.66, 0.78].map((t) => { const i = Math.round(t * 6), p = neckFront[i], q = neckFront[i + 1]; const x = p[0] + (q[0] - p[0]) * 0.5 + 6, y = p[1] + (q[1] - p[1]) * 0.5; return [[x, y - 6], [x + 2.6, y - 5], [x + 1.8, y + 6], [x - 0.6, y + 5]] as P[]; })],+ outline, grey: [...seg([[-16, -200], [-8, -176], [2, -162]]), ...seg(back), ...seg([[94, -103], [78, -102]]), ...seg([...wingEdge].reverse()), ...seg([[-10, -152], [-14, -170], [-16, -200]])], /* mantle and folded wing; breast, flank and neck stay white paper */+ legs: [[[1, -2], [6, -24], [8, -46]], [[8, -46], [4, -66], [-3, -84]], [[13, -2], [17, -24], [20, -44]], [[20, -44], [16, -64], [11, -84]]],+ toes: [[[1, 0], [-12, 2], [-24, 6]], [[1, 0], [-9, 5], [-15, 11]], [[1, 0], [10, 3]], [[13, 0], [2, 3], [-8, 7]], [[13, 0], [22, 2]]], eye: [-58, -281],+ bill: [...seg(billTop), ...seg([...billBot].reverse())],+ };+};+// the second heron RESTS: neck folded right down so the head sits on its shoulders and the+// folded neck bulges out in front as a pouch of plumes, bill level, on one leg, the other tucked up+const heronB = (): Heron => {+ const billTop: P[] = [[-82, -163], [-66, -167], [-50, -171], [-39, -174]], billBot: P[] = [[-82, -163], [-64, -163], [-50, -164], [-39, -165]];+ const head: P[] = [[-39, -174], [-33, -181], [-22, -184], [-11, -179]], back: P[] = [[-11, -179], [-5, -167], [5, -157], [23, -146], [47, -130], [67, -112], [86, -93]];+ const front: P[] = [[-39, -165], [-47, -158], [-52, -145], [-51, -128], [-45, -111], [-31, -96], [-12, -86], [10, -83]], under: P[] = [[86, -93], [62, -87], [36, -83], [10, -83]];+ const wingEdge: P[] = [[-7, -151], [4, -128], [24, -108], [50, -96], [72, -92]];+ const outline = [...seg(billTop), ...seg(head), ...seg(back), ...seg(under), ...seg([...front].reverse()), ...seg([...billBot].reverse())];+ return {+ strokes: [[billTop, 2.5], [billBot, 2.3], [head, 3.0], [back, 3.8], [front, 3.3], [under, 2.8], [wingEdge, 3.0],+ [[[-49, -141], [-55, -123], [-57, -104]], 1.5], [[[-46, -135], [-50, -116], [-48, -100]], 1.4], [[[-51, -149], [-59, -133], [-63, -114]], 1.5],+ [[[6, -150], [24, -134], [38, -124]], 1.4], [[[20, -150], [40, -134], [56, -120]], 1.4], [[[34, -142], [52, -126], [66, -112]], 1.3]],+ solids: [[[-35, -178], [-22, -182], [-10, -179], [8, -173], [24, -166], [6, -171], [-12, -175], [-31, -176]], [[46, -115], [68, -105], [86, -93], [64, -91], [48, -100]], [[-9, -153], [0, -157], [6, -147], [-3, -141]],+ ...[[-46, -155], [-49, -145], [-50, -134]].map(([x, y]) => [[x + 5, y - 5], [x + 7.5, y - 4], [x + 6.5, y + 5], [x + 4, y + 4]] as P[])],+ outline, grey: [...seg(back), ...seg([[86, -93], [72, -92]]), ...seg([...wingEdge].reverse()), ...seg([[-7, -151], [-11, -179]])],+ legs: [[[2, -2], [6, -26], [8, -50]], [[8, -50], [4, -67], [-1, -84]]],+ toes: [[[2, 0], [-10, 2], [-21, 6]], [[2, 0], [-7, 5], [-13, 10]], [[2, 0], [12, 3]]], eye: [-29, -175],+ bill: [...seg(billTop), ...seg([...billBot].reverse())],+ };+};+const place = (h: Heron, x: number, y: number, s: number): Heron => {+ const t = (p: P): P => [x + p[0] * s, y + p[1] * s], T = (a: P[]) => a.map(t);+ return { strokes: h.strokes.map(([p, w]) => [T(p), w * s]), solids: h.solids.map(T), outline: T(h.outline), grey: T(h.grey), legs: h.legs.map(T), toes: h.toes.map(T), eye: t(h.eye), bill: T(h.bill) };+};+const A = place(heronA(), 330, Y(330) - 11, 1.02), B = place(heronB(), 860, Y(860) - 11, 1.08);+const HERONS = [A, B];+const legRibbons = (h: Heron) => h.legs.map((l, i) => carved(l, i % 2 ? 7.5 : 5, 700 + i, { step: 0.05, tail: 0.9 }));++// ---------------------------------------------------------------- the far bank, the reeds, the rain+const FARBANK: P[] = (() => { const r = rng(801), top: P[] = []; for (let x = IN.x0 - 10; x <= IN.x1 + 10; x += 6) { const clump = Math.abs(Math.sin(x * 0.031 + 1.3)) ** 0.6 * 20 + Math.abs(Math.sin(x * 0.083)) ** 0.5 * 8, pine = x > 600 && x < 700 ? 30 * Math.exp(-(((x - 650) / 22) ** 2)) : 0; top.push([x, 512 - clump - pine - r() * 2]); } return [...top, [IN.x1 + 10, SHORE], [IN.x0 - 10, SHORE]]; })();+const REEDS: P[] = (() => { const r = rng(811), top: P[] = [[720, SHORE + 4]]; for (let x = 730; x <= IN.x1 + 10; x += 7) top.push([x, SHORE - 6 - r() * 10], [x + 3, SHORE - 18 - r() * 34], [x + 5, SHORE - 6 - r() * 8]); return [...top, [IN.x1 + 10, SHORE + 14], [720, SHORE + 12]]; })();+const rain = (seed: number, n: number, dir: P, lo: number, hi: number, w0: number, w1: number): [P[], number][] => {+ const r = rng(seed), l = Math.hypot(dir[0], dir[1]), d: P = [dir[0] / l, dir[1] / l], out: [P[], number][] = [];+ for (let i = 0; out.length < n && i < n * 6; i++) {+ const x = IN.x0 - 120 + r() * (IN.x1 - IN.x0 + 120), y = IN.y0 - 60 + r() * (IN.y1 - IN.y0), sheetOfRain = 0.5 + 0.5 * Math.sin(x * 0.012 - y * 0.004 + seed);+ if (r() > 0.25 + 0.75 * sheetOfRain) continue; // drifts of rain with thinner gaps between+ const onBird = HERONS.some((h) => { const b = h.outline; let c = false; for (let a = 0, j = b.length - 1; a < b.length; j = a++) if (b[a][1] > y !== b[j][1] > y && x < ((b[j][0] - b[a][0]) * (y - b[a][1])) / (b[j][1] - b[a][1]) + b[a][0]) c = !c; return c; });+ if (onBird && r() < 0.8) continue; // the carver spared the birds' heads and backs+ const L = lo + r() * (hi - lo); out.push([[[x, y], [x + d[0] * L, y + d[1] * L]], w0 + r() * (w1 - w0)]);+ }+ return out;+};+const RAIN_K = rain(821, 230, [0.2, 1], 40, 240, 1.0, 1.5), RAIN_G = rain(822, 150, [0.25, 1], 70, 300, 1.8, 2.6);+const RIPPLES: P[][] = (() => { const r = rng(831), out: P[][] = []; for (let i = 0; i < 400 && out.length < 120; i++) { const t = Math.pow(r(), 1.5), y = SHORE + 14 + t * (IN.y1 - SHORE - 20), x = IN.x0 + 10 + r() * (IN.x1 - IN.x0 - 20), L = 8 + t * 34; if (BRIDGE.some((b) => { let c = false; for (let a = 0, j = b.length - 1; a < b.length; j = a++) if (b[a][1] > y !== b[j][1] > y && x < ((b[j][0] - b[a][0]) * (y - b[a][1])) / (b[j][1] - b[a][1]) + b[a][0]) c = !c; return c; })) continue; out.push([[x - L / 2, y], [x, y - 1.5 - t * 2], [x + L / 2, y]]); } return out; })();++// ---------------------------------------------------------------- the blocks+// Each block is the wood left standing for one colour. Drawn in 1080-space onto a full-size layer.+type Block = { id: string; color: string; alpha: number; reg: P; grain: number; seed: number; cut: (c: Ctx) => void };+const knock = (c: Ctx, shapes: P[][]) => { c.save(); c.globalCompositeOperation = "destination-out"; fillAll(c, shapes, "#000"); c.restore(); }; // carve away: those areas print nothing from this block+const birds = () => HERONS.map((h) => h.outline);+const BLOCKS: Block[] = [+ { id: "key", color: SUMI, alpha: 0.95, reg: [0, 0], grain: 0.06, seed: 1, cut: (c) => {+ const k = (pts: P[], w: number, s: number, o = {}) => fillAll(c, [carved(pts, w, s, o)], SUMI);+ // the frame line round the picture+ k([[IN.x0, IN.y0], [IN.x1, IN.y0]], 3.2, 11, { smooth: false }); k([[IN.x1, IN.y0], [IN.x1, IN.y1]], 3.2, 12, { smooth: false }); k([[IN.x1, IN.y1], [IN.x0, IN.y1]], 3.2, 13, { smooth: false }); k([[IN.x0, IN.y1], [IN.x0, IN.y0]], 3.2, 14, { smooth: false });+ c.save(); path(c, [[IN.x0, IN.y0], [IN.x1, IN.y0], [IN.x1, IN.y1], [IN.x0, IN.y1]]); c.clip();+ // the bridge: every timber's edges, grain lines along the rails, the beam ends in the girder+ [-11, 11, 64, 76, 150, 196].forEach((o, i) => k(edge(o), o === 11 || o === 196 ? 3.0 : 2.4, 30 + i));+ POSTS.forEach((x, i) => { k([[x - 9, Y(x) + 11], [x - 9, Y(x) + 150]], 2.6, 40 + i, { smooth: false }); k([[x + 9, Y(x) + 11], [x + 9, Y(x) + 150]], 2.2, 50 + i, { smooth: false }); });+ PILES.forEach((x, i) => { k([[x - 14, Y(x) + 196], [x - 14, WL]], 2.8, 60 + i, { smooth: false }); k([[x + 14, Y(x) + 196], [x + 14, WL]], 2.4, 70 + i, { smooth: false }); [-1, 1].forEach((sd, j) => k([[x + sd * 16, WL + 2], [x + sd * 28, WL + 1], [x + sd * 40, WL + 3]], 1.6, 76 + i * 2 + j, { tail: 0.5 })); /* where each pile goes into the river, the water rings it */ });+ k([[20, 852], [930, 852]], 2.4, 80, { smooth: false }); k([[20, 870], [930, 870]], 2.6, 81, { smooth: false }); k([[930, 852], [930, 870]], 2.2, 82, { smooth: false });+ BRACES.forEach((b, i) => { k([b[0], b[1]], 2.2, 90 + i, { smooth: false }); k([b[3], b[2]], 2.2, 95 + i, { smooth: false }); });+ BEAMS.forEach((x, i) => { const y = Y(x) + 196; k([[x - 6, y], [x - 6, y + 13], [x + 6, y + 13], [x + 6, y]], 1.8, 100 + i, { smooth: false }); }); // the ends of the deck's cross-beams, standing out under the girder+ const r = rng(120); for (let i = 0; i < 16; i++) { const x0 = 40 + r() * 900, L = 60 + r() * 160, o = r() < 0.5 ? -4 + r() * 8 : 166 + r() * 22; k(edge(o, x0, x0 + L), 1.1, 130 + i, { tail: 0.4 }); } // grain carved along the kasagi and the girder+ // water: ripples, and the far bank's waterline broken by the rain+ RIPPLES.forEach((p, i) => k(p, 1.3 + (p[0][1] - SHORE) / 300, 200 + i, { tail: 0.5 }));+ // the herons: contours, then the black of crest, primaries, shoulder and neck streaks+ HERONS.forEach((h, j) => { h.strokes.forEach(([p, w], i) => k(p, w, 300 + j * 50 + i)); fillAll(c, h.solids.map((s, i) => gouged(s, 400 + j * 20 + i, true, 0.6)), SUMI);+ h.legs.forEach((l, i) => k(l.map(([x, y]) => [x + 2.2, y] as P), 1.5, 460 + j * 10 + i, { tail: 0.7 })); h.toes.forEach((t, i) => k(t, 2.4, 480 + j * 10 + i, { tail: 0.6 }));+ c.strokeStyle = SUMI; c.lineWidth = 1.3; c.beginPath(); c.arc(h.eye[0], h.eye[1], 3.1, 0, Math.PI * 2); c.stroke(); c.fillStyle = SUMI; c.beginPath(); c.arc(h.eye[0] - 0.5, h.eye[1], 1.3, 0, Math.PI * 2); c.fill(); });+ // the rain: fine carved diagonals across everything+ RAIN_K.forEach(([p, w], i) => k(p, w, 1000 + i, { smooth: false, step: 0.2, tail: 0.6 }));+ c.restore();+ } },+ { id: "sky", color: SKY, alpha: 0.9, reg: [1.5, -1], grain: 0.34, seed: 2, cut: (c) => { fillAll(c, [box(IN.x0, IN.y0, IN.x1, SHORE + 2)], SKY); knock(c, [...BRIDGE, ...birds()]); } },+ { id: "yellow", color: YELLOW, alpha: 0.92, reg: [-1, 1.5], grain: 0.05, seed: 3, cut: (c) => { HERONS.forEach((h) => { fillAll(c, [h.bill], YELLOW); fillAll(c, legRibbons(h), YELLOW); fillAll(c, h.toes.map((t, i) => carved(t, 4, 600 + i)), YELLOW); c.fillStyle = YELLOW; c.beginPath(); c.arc(h.eye[0], h.eye[1], 3.2, 0, Math.PI * 2); c.fill(); }); } },+ { id: "farbank", color: FAR, alpha: 0.85, reg: [-1.5, 0.5], grain: 0.18, seed: 5, cut: (c) => { c.save(); path(c, FARBANK); c.clip(); const g = c.createLinearGradient(0, 470, 0, SHORE); g.addColorStop(0, FAR); g.addColorStop(0.6, FAR); g.addColorStop(1, FAR + "55"); c.fillStyle = g; c.fillRect(0, 400, W0, 200); c.restore(); knock(c, [...BRIDGE, ...birds()]); } },+ { id: "heron", color: GREY, alpha: 0.88, reg: [2, 1], grain: 0.1, seed: 4, cut: (c) => { HERONS.forEach((h) => fillAll(c, [h.grey], GREY)); } },+ { id: "wood", color: WOOD, alpha: 0.9, reg: [1, 2], grain: 0.3, seed: 6, cut: (c) => { c.save(); path(c, [[IN.x0, IN.y0], [IN.x1, IN.y0], [IN.x1, IN.y1], [IN.x0, IN.y1]]); c.clip(); fillAll(c, BRIDGE, WOOD); c.restore(); knock(c, birds()); } },+ { id: "near", color: NEAR, alpha: 0.9, reg: [1.5, -1.5], grain: 0.12, seed: 8, cut: (c) => { fillAll(c, [REEDS], NEAR); knock(c, [...BRIDGE, ...birds()]); } },+ { id: "water", color: WATER, alpha: 0.88, reg: [-2, 1], grain: 0.34, seed: 7, cut: (c) => { fillAll(c, [box(IN.x0, SHORE, IN.x1, IN.y1)], WATER); knock(c, BRIDGE.filter((b) => b !== KASAGI && b !== NUKI)); } },+ { id: "rain", color: RAIN, alpha: 0.75, reg: [0, 0], grain: 0.05, seed: 9, cut: (c) => { c.save(); path(c, [[IN.x0, IN.y0], [IN.x1, IN.y0], [IN.x1, IN.y1], [IN.x0, IN.y1]]); c.clip(); RAIN_G.forEach(([p, w], i) => fillAll(c, [carved(p, w, 2000 + i, { smooth: false, tail: 0.6 })], RAIN)); c.restore(); } },+ { id: "bokSky", color: INDIGO, alpha: 0.9, reg: [0.5, 0], grain: 0.26, seed: 10, cut: (c) => { bokashi(c, IN.x0, IN.x1, IN.y0, 250, INDIGO, 841, box(IN.x0, IN.y0, IN.x1, 320)); knock(c, birds()); } },+ { id: "bokWater", color: AI, alpha: 0.9, reg: [-1, 1], grain: 0.26, seed: 11, cut: (c) => { bokashi(c, IN.x0, IN.x1, IN.y1, 790, AI, 842, box(IN.x0, 700, IN.x1, IN.y1)); knock(c, BRIDGE.filter((b) => b !== KASAGI && b !== NUKI)); } },+ { id: "under", color: UNDER, alpha: 0.85, reg: [1, 1], grain: 0.2, seed: 12, cut: (c) => { // the bridge's shade on the river beneath it, and the girder's underside+ const shade: P[] = [...edge(196), [1060, WL + 30], [20, WL + 30]];+ c.save(); path(c, shade); c.clip(); for (let x = 20; x < 1060; x += 6) { const top = Y(x) + 190, g = c.createLinearGradient(0, top, 0, top + 220); g.addColorStop(0, UNDER + "ff"); g.addColorStop(0.3, UNDER + "c8"); g.addColorStop(1, UNDER + "00"); c.fillStyle = g; c.fillRect(x, top, 6.5, 230); } c.restore();+ c.save(); path(c, KETA); c.clip(); for (let x = 20; x < 1060; x += 6) { const bot = Y(x) + 196, g = c.createLinearGradient(0, bot, 0, bot - 30); g.addColorStop(0, UNDER + "cc"); g.addColorStop(1, UNDER + "00"); c.fillStyle = g; c.fillRect(x, bot - 32, 6.5, 33); } c.restore();+ PILES.forEach((x, i) => { const r = rng(850 + i); c.fillStyle = UNDER + "aa"; for (let y = WL + 4; y < WL + 66; y += 6 + r() * 5) { const w = 13 * (1 - (y - WL) / 80) + r() * 5; c.fillRect(x - w + (r() - 0.5) * 6, y, w * 2, 2.5 + r() * 2); } }); // the piles' broken reflections+ knock(c, [...PILES.map(pileBox), TIE, ...BRACES]);+ } },+];++const blockLayer = (env: Env, b: Block): Layer => {+ const key = `woodcut:block:${b.id}:${env.W}x${env.H}@${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const k = env.scale, s = (env.W / W0) * k; L = env.canvas(Math.round(env.W * k), Math.round(env.H * k)); const c = L.ctx;+ c.setTransform(s, 0, 0, s, b.reg[0] * s, b.reg[1] * s); c.save(); c.beginPath(); c.rect(IN.x0 - 2 - b.reg[0], IN.y0 - 2 - b.reg[1], IN.x1 - IN.x0 + 4, IN.y1 - IN.y0 + 4); c.clip(); b.cut(c); c.restore(); /* the block is only as big as the picture */+ grain(c, env, b.grain, [b.seed * 97 % 512, b.seed * 211 % 512], ((b.seed % 3) - 1) * 0.004);+ env.cache.set(key, L); return L;+};++// the blind kento impressions in the bottom margin, pressed in with the first pull+const kento = (c: Ctx, env: Env) => {+ const s = (env.W / W0) * env.scale; c.save(); c.setTransform(s, 0, 0, s, 0, 0); c.lineWidth = 1.2;+ const mark = (pts: P[]) => { c.strokeStyle = "rgba(255,252,240,0.8)"; c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x - 0.8, y - 0.8) : c.moveTo(x - 0.8, y - 0.8))); c.stroke(); c.strokeStyle = "rgba(120,100,70,0.35)"; c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x + 0.8, y + 0.8) : c.moveTo(x + 0.8, y + 0.8))); c.stroke(); };+ mark([[IN.x1 - 30, IN.y1 + 26], [IN.x1, IN.y1 + 26], [IN.x1, IN.y1 + 8]]); mark([[IN.x0 + 150, IN.y1 + 26], [IN.x0 + 214, IN.y1 + 26]]);+ c.restore();+};++// ---------------------------------------------------------------- the pulls (the film)+const PAUSE = 5, START = 0; /* a breath between pulls while the next block is inked */+const RUB: Record<string, number> = { key: 70, sky: 35, yellow: 10, farbank: 15, heron: 10, wood: 40, near: 10, water: 40, rain: 15, bokSky: 30, bokWater: 30, under: 20 }; /* a small block is a quick pull */+const PULLS = (() => { let t = START; return BLOCKS.map((b, i) => { const p = { b, start: t, end: t + RUB[b.id] }; t = p.end + (i < BLOCKS.length - 1 ? PAUSE : 0); return p; }); })();+const DONE = PULLS[PULLS.length - 1].end, N = Math.ceil((DONE + 30) / 15) * 15;+(() => { if (PULLS.some((p) => p.start % 5 || p.end % 5) || N % 15) throw new Error("woodcut: pulls off the grid"); if (N > 540 || N < 300) throw new Error("woodcut: duration out of range"); })();++// the sheet after the first n pulls (cached; only the newest is kept)+const sheet = (env: Env, n: number): Layer => {+ const key = `woodcut:sheet:${n}:${env.W}x${env.H}@${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ for (const ck of [...env.cache.keys()]) if (ck.startsWith("woodcut:sheet:") && Math.abs(Number(ck.split(":")[2]) - n) > 1) env.cache.delete(ck);+ const DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale);+ L = env.canvas(DW, DH); const c = L.ctx; c.setTransform(1, 0, 0, 1, 0, 0);+ if (n > 0) c.drawImage(sheet(env, n - 1).canvas, 0, 0); else c.drawImage(washi(env).canvas, 0, 0);+ if (n > 0) { const b = BLOCKS[n - 1]; c.globalCompositeOperation = "multiply"; c.globalAlpha = b.alpha; c.drawImage(blockLayer(env, b).canvas, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; if (n === 1) kento(c, env); }+ env.cache.set(key, L); return L;+};++const PAD = 250;+const draw = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ let n = 0; while (n < PULLS.length && f >= PULLS[n].end) n++;+ ctx.drawImage(sheet(env, n).canvas, 0, 0);+ const p = PULLS[n]; if (!p || f < p.start) return;+ // the pull in progress: the baren working down the back of the sheet, the colour coming through where it has passed+ const u = (f - p.start) / (p.end - p.start), /* frame 0 is the bare sheet */ s = (env.W / W0) * env.scale, DW = Math.round(env.W * env.scale), DH = Math.round(env.H * env.scale);+ const mk = `woodcut:mask:${DW}x${DH}`, m = (env.cache.get(mk) as Layer | undefined) ?? (() => { const t = env.canvas(DW, DH); env.cache.set(mk, t); return t; })(), c = m.ctx;+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "source-over"; c.clearRect(0, 0, DW, DH);+ c.setTransform(s, 0, 0, s, 0, 0); rubMask(c, rubPath(blockBox(p.b), PAD), u, PAD, p.b.seed * 7);+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = "source-in"; c.drawImage(blockLayer(env, p.b).canvas, 0, 0); c.globalCompositeOperation = "source-over";+ ctx.globalCompositeOperation = "multiply"; ctx.globalAlpha = p.b.alpha; ctx.drawImage(m.canvas, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";+};+// the part of the sheet each block covers: the printer rubs only over the block+const blockBox = (b: Block) => {+ const all: P[] = b.id === "yellow" || b.id === "heron" ? HERONS.flatMap((h) => [...h.outline, ...h.toes.flat()]) : b.id === "near" ? REEDS : b.id === "farbank" ? FARBANK : b.id === "bokSky" ? box(IN.x0, IN.y0, IN.x1, 300) : b.id === "bokWater" ? box(IN.x0, 760, IN.x1, IN.y1) : b.id === "under" ? box(IN.x0, 640, IN.x1, WL + 80) : b.id === "wood" ? box(IN.x0, 440, IN.x1, IN.y1) : b.id === "sky" ? box(IN.x0, IN.y0, IN.x1, SHORE) : b.id === "water" ? box(IN.x0, SHORE, IN.x1, IN.y1) : box(IN.x0, IN.y0, IN.x1, IN.y1);+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; all.forEach(([x, y]) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); });+ return { x0: clamp(x0 - 20, 0, W0), y0: clamp(y0 - 20, 0, W0), x1: clamp(x1 + 20, 0, W0), y1: clamp(y1 + 20, 0, W0) };+};++export const woodcut: Film = {+ meta: { title: "Herons in rain on the drum bridge · ukiyo-e woodblock", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" }, /* twelve full-size block layers: keep every surface in software so no page antialiases differently */+ assets: { images: {} },+ shots: [{ id: "pulls", start: 0, end: N, draw }],+};++export const STYLE = { id: "woodcut", name: "Ukiyo-e colour woodblock", family: "print", medium: "water-based pigment printed by baren from hand-carved cherry blocks onto damp kozo washi: a sumi keyblock, flat colour blocks, bokashi wipes", nearest: "lighthouse", hero: "two grey herons in rain on a wooden drum bridge" };diff --git a/engine/src/canvas-core/woodcutKit.ts b/engine/src/canvas-core/woodcutKit.tsnew file mode 100644index 0000000..171183d--- /dev/null+++ b/engine/src/canvas-core/woodcutKit.ts@@ -0,0 +1,126 @@+// WOODCUT KIT (ukiyo-e colour woodblock). What a cherry-wood block, a knife and a baren need+// that the core does not have:+// carved() a keyblock line as the KNIFE leaves it: two separate cuts either side of a ridge,+// so the width steps and wanders instead of swelling like a brush, and every end is+// a chisel cut (flat, oblique), never a round or tapered pen end;+// gouged() a solid black area whose edge is a knife edge;+// grainTile the plank's figure: long wavy growth rings that print as streaks in a flat;+// washi() kozo paper: warm, soft, long curling fibres, a faint cloud;+// rub() the baren's path over the back of the sheet, as a coverage mask that grows;+// bokashi() a graded wipe on the block: full at one edge, gone by the other, with the+// uneven edge of a damp cloth.+// Doctrine borrowed from spec 02 (knockouts): a colour block is PRINTED where it is cut, so a+// shape that two blocks share is built once from the shared seeded geometry before either block+// uses it; highlights are uncut wood (bare paper), never a pale ink.+import { fractal, rng, sample, type Ctx, type Env, type Layer, type P } from "./core";++export const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));+export const smoothstep = (a: number, b: number, v: number) => { const t = clamp((v - a) / (b - a)); return t * t * (3 - 2 * t); };+export const path = (c: Ctx, pts: P[]) => { c.beginPath(); pts.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); };++// arc-length resample of a polyline+export const even = (s: P[], step: number): P[] => {+ const out: P[] = [s[0]]; let carry = 0;+ for (let i = 1; i < s.length; i++) { const a = s[i - 1], b = s[i], L = Math.hypot(b[0] - a[0], b[1] - a[1]); let d = step - carry; while (d <= L) { const t = d / L; out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); d += step; } carry = L - (d - step); }+ const last = s[s.length - 1]; if (Math.hypot(last[0] - out[out.length - 1][0], last[1] - out[out.length - 1][1]) > step * 0.3) out.push(last);+ return out;+};++// ---------------------------------------------------------------- the knife's line+// `pts` are control points; the centreline is a Catmull-Rom through them. Width: `w`, stepping+// by up to +-`step` where the carver re-set the knife (every 12-30 px), wandering slowly between.+// Each side is its own cut, so the two edges wobble independently (a fraction of a pixel).+// Ends: cut flat at an oblique angle, the angle and hand of each chosen by the seed.+export const carved = (ctrl: P[], w: number, seed: number, o: { step?: number; wander?: number; tail?: number; smooth?: boolean } = {}): P[] => {+ const { step = 0.16, wander = 0.14, tail = 0.8, smooth = true } = o, r = rng(seed);+ const c = even(smooth && ctrl.length > 2 ? sample(ctrl, false, 8) : ctrl, 1.4), n = c.length;+ if (n < 2) return [];+ const L: P[] = [], R: P[] = []; let seg = 0, next = 12 + r() * 18, lvl = 1 + (r() - 0.5) * 2 * step, acc = 0;+ for (let i = 0; i < n; i++) {+ if (i) acc += Math.hypot(c[i][0] - c[i - 1][0], c[i][1] - c[i - 1][1]);+ if (acc > next) { next = acc + 12 + r() * 18; lvl = 1 + (r() - 0.5) * 2 * step; seg++; }+ const a = c[Math.max(0, i - 1)], b = c[Math.min(n - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], l = Math.hypot(dx, dy) || 1, nx = -dy / l, ny = dx / l;+ const t = i / (n - 1), ends = Math.min(1, t * (n - 1) / 3, (1 - t) * (n - 1) / 3), end = tail + (1 - tail) * ends; // a knife end barely thins: it is CUT+ const wv = (w / 2) * lvl * end * (1 + wander * (fractal(seed, acc * 0.05, 0, 1, 1, 2) - 0.5) * 2);+ const jl = (fractal(seed + 3, acc * 0.4, 0, 1, 1, 1) - 0.5) * 0.5, jr = (fractal(seed + 5, acc * 0.4, 0, 1, 1, 1) - 0.5) * 0.5;+ L.push([c[i][0] + nx * (wv + jl), c[i][1] + ny * (wv + jl)]); R.push([c[i][0] - nx * (wv + jr), c[i][1] - ny * (wv + jr)]);+ }+ // chisel ends: slide one corner along the stroke so the end is a flat oblique facet+ const chisel = (i: number, j: number, k: number) => { const d = [c[j][0] - c[i][0], c[j][1] - c[i][1]], l = Math.hypot(d[0], d[1]) || 1, s = (r() < 0.5 ? 1 : -1) * w * (0.35 + r() * 0.5); (s > 0 ? L : R)[k] = [(s > 0 ? L : R)[k][0] + (d[0] / l) * Math.abs(s), (s > 0 ? L : R)[k][1] + (d[1] / l) * Math.abs(s)]; };+ chisel(0, Math.min(2, n - 1), 0); chisel(n - 1, Math.max(0, n - 3), n - 1);+ void seg; return [...L, ...R.reverse()];+};+// a solid carved area: its outline bitten by the knife at a small scale+export const gouged = (ctrl: P[], seed: number, closed = true, amp = 0.8): P[] => {+ const s = even(closed ? sample(ctrl, true, 8) : ctrl, 1.5);+ return s.map(([x, y]) => [x + (fractal(seed, x, y, 0.35, 0.35, 1) - 0.5) * amp, y + (fractal(seed + 9, x, y, 0.35, 0.35, 1) - 0.5) * amp] as P);+};+// fill a list of polygons on the current surface+export const fillAll = (c: Ctx, polys: P[][], color: string) => { c.fillStyle = color; c.beginPath(); for (const p of polys) { if (p.length < 3) continue; p.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); } c.fill("nonzero"); };++// ---------------------------------------------------------------- the wood and the paper+// the plank's figure: growth rings as long wavy streaks, tileable, alpha = where pigment is thin.+export const grainTile = (env: Env): Layer => {+ const key = `woodcut:grain:${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const n = 512, k = env.scale, dn = Math.round(n * k); L = env.canvas(dn, dn); const img = L.ctx.createImageData(dn, dn), d = img.data;+ for (let y = 0; y < dn; y++) for (let x = 0; x < dn; x++) {+ const lx = x / k, ly = y / k, warp = (fractal(501, lx, ly, 1 / 128, 1 / 64, 2, n) - 0.5) * 34, ring = Math.sin((ly + warp) * 0.5 + (fractal(502, lx, ly, 1 / 256, 1 / 16, 3, n) - 0.5) * 26); /* growth rings: uneven spacing, some close, some wide */+ const fleck = fractal(503, lx, ly, 0.9, 0.9, 1, n), v = clamp((ring - 0.55) * 2.2) * 0.75 + clamp((fleck - 0.64) * 5) * 0.8;+ const p = (y * dn + x) * 4; d[p] = d[p + 1] = d[p + 2] = 0; d[p + 3] = 255 * clamp(v);+ }+ L.ctx.putImageData(img, 0, 0); env.cache.set(key, L); return L;+};+// knock a block's pigment thin along its grain (and where the baren skipped: goma-zuri speckle)+export const grain = (c: Ctx, env: Env, strength: number, shift: P, rot = 0) => {+ if (strength <= 0) return; const t = grainTile(env), k = env.scale;+ c.save(); c.setTransform(Math.cos(rot), Math.sin(rot), -Math.sin(rot), Math.cos(rot), shift[0] * k, shift[1] * k); c.globalCompositeOperation = "destination-out"; c.globalAlpha = strength;+ c.fillStyle = c.createPattern(t.canvas, "repeat")!; c.fillRect(-shift[0] * k - 200 * k, -shift[1] * k - 200 * k, (env.W + 400) * k, (env.H + 400) * k); c.restore();+};+export const WASHI = "#efe6d1";+export const washi = (env: Env): Layer => {+ const key = `woodcut:washi:${env.W}x${env.H}@${env.scale}`; let L = env.cache.get(key) as Layer | undefined; if (L) return L;+ const W = env.W, H = env.H, k = env.scale, DW = Math.round(W * k), DH = Math.round(H * k); L = env.canvas(DW, DH); const c = L.ctx;+ c.setTransform(1, 0, 0, 1, 0, 0); c.fillStyle = WASHI; c.fillRect(0, 0, DW, DH);+ const img = c.getImageData(0, 0, DW, DH), d = img.data;+ for (let y = 0; y < DH; y++) for (let x = 0; x < DW; x++) { const v = fractal(511, x / k, y / k, 0.004, 0.004, 3) - 0.5, p = (y * DW + x) * 4, o = v * 12; d[p] += o; d[p + 1] += o; d[p + 2] += o * 1.3; }+ c.putImageData(img, 0, 0); c.setTransform(k, 0, 0, k, 0, 0);+ const r = rng(513);+ for (let i = 0; i < (W * H) / 2600; i++) { // kozo: long, soft, curling bast fibres lying in the sheet+ const x = r() * W, y = r() * H, len = 14 + Math.pow(r(), 2) * 70, a = r() * 6.283, b1 = (r() - 0.5) * 2, b2 = (r() - 0.5) * 2, pale = r() < 0.7;+ c.strokeStyle = pale ? `rgba(255,252,242,${0.35 + r() * 0.35})` : `rgba(150,128,96,${0.1 + r() * 0.14})`; c.lineWidth = 0.4 + r() * 0.6;+ c.beginPath(); c.moveTo(x, y); c.bezierCurveTo(x + Math.cos(a + b1) * len * 0.35, y + Math.sin(a + b1) * len * 0.35, x + Math.cos(a + b2) * len * 0.7, y + Math.sin(a + b2) * len * 0.7, x + Math.cos(a) * len, y + Math.sin(a) * len); c.stroke();+ }+ env.cache.set(key, L); return L;+};++// ---------------------------------------------------------------- the baren+// The printer lays the damp sheet on the inked block (against the kento) and rubs its back with+// the baren in overlapping zig-zag strokes, working down the block. Pigment transfers where the+// baren has passed. `rubPath` returns that path over a block's box; `rubMask` draws the swept+// area up to `u` (0..1) as a coverage mask, the pad's edge a little ragged.+export const rubPath = (b: { x0: number; y0: number; x1: number; y1: number }, pad: number): P[] => {+ const band = pad * 0.72, rows = Math.max(1, Math.ceil((b.y1 - b.y0) / band)), out: P[] = [];+ for (let i = 0; i < rows; i++) { const y = b.y0 + band * (i + 0.5), l = b.x0 - pad * 0.2, rr = b.x1 + pad * 0.2; out.push(i % 2 ? [rr, y] : [l, y], i % 2 ? [l, y + band * 0.15] : [rr, y + band * 0.15]); }+ return out;+};+export const rubMask = (c: Ctx, pts: P[], u: number, pad: number, seed: number) => {+ if (u <= 0) return; const s = even(pts, 3), n = Math.max(1, Math.round((s.length - 1) * clamp(u)));+ c.fillStyle = "#000"; c.beginPath();+ for (let i = 0; i <= n && i < s.length; i++) { const [x, y] = s[i], rr = (pad / 2) * (0.9 + 0.2 * fractal(seed, x, y, 0.05, 0.05, 1)); c.moveTo(x + rr, y); c.arc(x, y, rr, 0, Math.PI * 2); }+ c.fill();+};++// ---------------------------------------------------------------- bokashi+// Ichimonji bokashi: the printer wipes the inked block with a damp cloth so the pigment runs+// from full at one edge to nothing a hand's width away. The fade is not a clean gradient: the+// cloth leaves its edge wavering across the block.+export const bokashi = (c: Ctx, x0: number, x1: number, yFull: number, yGone: number, color: string, seed: number, clip?: P[]) => {+ c.save(); if (clip) { path(c, clip); c.clip(); }+ const dir = Math.sign(yGone - yFull) || 1, span = Math.abs(yGone - yFull), steps = Math.ceil((x1 - x0) / 6);+ for (let i = 0; i < steps; i++) {+ const x = x0 + i * 6, wob = (fractal(seed, x, 0, 0.012, 0.012, 3) - 0.5) * span * 0.35, g = c.createLinearGradient(0, yFull, 0, yGone + wob * dir);+ g.addColorStop(0, color); g.addColorStop(0.45, color + "b0"); g.addColorStop(1, color + "00"); c.fillStyle = g;+ c.fillRect(x, Math.min(yFull, yGone + wob * dir) - (dir > 0 ? 400 : 0), 6.6, span + Math.abs(wob) + 400);+ }+ c.restore();+};diff --git a/engine/src/canvas-core/wrenDraw.ts b/engine/src/canvas-core/wrenDraw.tsnew file mode 100644index 0000000..d65ecbb--- /dev/null+++ b/engine/src/canvas-core/wrenDraw.ts@@ -0,0 +1,188 @@+import { Gfx, rng, tube, type Medium, type P } from "./core";+import type { Film } from "./film";+import { blob, bounds, clamp, clipped, fillShape, lerpP, mix, smooth } from "./gallery";+import { drawWren } from "./wren";+import { fit, runProcess, timeline, type Op, type Proc } from "./sumiEKit";++// WREN ON A TWIG · drawing itself. The ink & line-wash plate (wren.ts) made the way a line-wash+// painter makes it: ALL the washes first, then the pen over them, then the spatter.+//+// A wash is laid as a bead: the loaded brush touches the top of the shape and the bead of wet+// paint is pulled DOWN it, a darker line of pigment riding the wet front; once the shape is+// covered the pigment settles and pools along the bottom edge; where a second, wetter drop+// touched the damp body it pushes a backrun outward, its pale middle growing and its crinkled+// dark rim riding the edge. Then the flexible nib: each line grows along its path, thick where it+// pressed, hair-thin where it lifted, contours left open. Last, the pen is shaken and spatters.+//+// wren.ts is NOT modified: its plate functions are private and its hero md5 must not move. This+// file re-authors the same geometry as timed marks, in the line-wash order. Because that order+// composites the bird's washes before the twig's ink (the still does the twig whole, then the+// bird), the finished process differs from the still by a few overlap pixels; the last 30+// frames are therefore drawWren itself, the still byte for byte.++const INK_M: Medium = { nib: 1.7, taper: 1, pressure: 1.75, retrace: false, wobble: 1.35, rough: 0.6 };+const INK = "#16131f", PAPER = "#fbf8f0";+const BROWN = "#a0693a", DARKB = "#5e3a20", BUFF = "#e6c794", RUFOUS = "#b8733a", UMBER = "#6e4a2c", SAP = "#6f8f3e", HAW = "#c3262d";+const N = 540;++// ---------------------------------------------------------------- wet media, with a clock+// p = 1 is wren's wash exactly. Below 1: the bead travels down (spread), the pigment settles to+// the bottom edge (settle), and the backrun opens (bloom), in that overlapping order.+type WetO = { alpha: number; seed: number; pool?: number; bloom?: P | null; bloomR?: number };+const wetBody = (g: Gfx, pts: P[], color: string, o: WetO, settle: number, bloomK: number) => {+ const { alpha, seed, pool = 0.55, bloom = null, bloomR = 22 } = o, b = bounds(pts);+ g.wash(pts, color, { alpha, seed, dx: 7, dy: 6, shrink: 1.07, rim: true });+ if (settle > 0) clipped(g, pts, () => {+ const c = g.cur, top = 0.45 + 0.35 * (1 - settle), gr = c.createLinearGradient(0, b.y0 + (b.y1 - b.y0) * top, 0, b.y1 + 2), a = alpha * pool * settle;+ gr.addColorStop(0, color + "00"); gr.addColorStop(0.75, color + Math.round(255 * a * 0.6).toString(16).padStart(2, "0")); gr.addColorStop(1, color + Math.round(255 * clamp(a * 1.3)).toString(16).padStart(2, "0"));+ c.fillStyle = gr; c.fillRect(b.x0 - 20, b.y0, b.x1 - b.x0 + 40, b.y1 - b.y0 + 20);+ });+ if (bloom && bloomK > 0) {+ const k = Math.sqrt(bloomK), bl0 = blob(bloom[0], bloom[1], bloomR, bloomR * 0.8, seed + 7, 0.32, 18), bl = bl0.map(([x, y]) => [bloom[0] + (x - bloom[0]) * k, bloom[1] + (y - bloom[1]) * k] as P);+ fillShape(g, bl, PAPER, 0.42);+ const c = g.cur; c.strokeStyle = mix(color, INK, 0.25); c.globalAlpha = alpha * 0.9; c.lineWidth = 1.6; c.beginPath(); bl.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.stroke(); c.globalAlpha = 1;+ }+};+// wren's own wet(), byte for byte, for a finished wash+const wetFull = (g: Gfx, pts: P[], color: string, o: WetO) => {+ const { alpha, seed, pool = 0.55, bloom = null, bloomR = 22 } = o, b = bounds(pts);+ g.group("paint", () => {+ g.wash(pts, color, { alpha, seed, dx: 7, dy: 6, shrink: 1.07, rim: true });+ clipped(g, pts, () => {+ const c = g.cur, gr = c.createLinearGradient(0, b.y0 + (b.y1 - b.y0) * 0.45, 0, b.y1 + 2);+ gr.addColorStop(0, color + "00"); gr.addColorStop(0.75, color + Math.round(255 * alpha * pool * 0.6).toString(16).padStart(2, "0")); gr.addColorStop(1, color + Math.round(255 * clamp(alpha * pool * 1.3)).toString(16).padStart(2, "0"));+ c.fillStyle = gr; c.fillRect(b.x0 - 20, b.y0, b.x1 - b.x0 + 40, b.y1 - b.y0 + 20);+ });+ if (bloom) {+ const bl = blob(bloom[0], bloom[1], bloomR, bloomR * 0.8, seed + 7, 0.32, 18);+ fillShape(g, bl, PAPER, 0.42);+ const c = g.cur; c.strokeStyle = mix(color, INK, 0.25); c.globalAlpha = alpha * 0.9; c.lineWidth = 1.6; c.beginPath(); bl.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.stroke(); c.globalAlpha = 1;+ }+ });+};+// the travelling bead: everything above a wobbling front is wet; the front itself carries a+// darker line of pigment+const beadFront = (b: { x0: number; y0: number; x1: number; y1: number }, t: number, seed: number): P[] => { const y = b.y0 - 14 + (b.y1 - b.y0 + 40) * t, out: P[] = []; for (let x = b.x0 - 30; x <= b.x1 + 30; x += 8) out.push([x, y + 5 * Math.sin(x * 0.045 + seed) + 3 * Math.sin(x * 0.13 + seed * 2)]); return out; };+const wetOp = (pts: P[], color: string, o: WetO) => (g: Gfx, p: number) => {+ if (p >= 1) return wetFull(g, pts, color, o);+ const spread = clamp(p / 0.55), settle = clamp((p - 0.4) / 0.45), bloomK = clamp((p - 0.7) / 0.3), b = bounds(pts);+ g.group("paint", () => {+ const c = g.cur, front = beadFront(b, spread, o.seed);+ c.save(); c.beginPath(); c.moveTo(b.x0 - 40, b.y0 - 60); c.lineTo(b.x1 + 40, b.y0 - 60); for (let i = front.length - 1; i >= 0; i--) c.lineTo(front[i][0], front[i][1]); c.closePath(); c.clip();+ wetBody(g, pts, color, o, settle, bloomK);+ c.restore();+ if (spread < 1) clipped(g, pts, () => { c.strokeStyle = color; c.globalAlpha = o.alpha * 0.55; c.lineWidth = 3.2; c.lineJoin = "round"; c.beginPath(); front.forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.stroke(); c.globalAlpha = 1; });+ });+};+const bgOp = (g: Gfx, p: number) => {+ // one loose wash behind the bird, cool, with a warm drop let into it lower down while it was+ // wet: laid top to bottom as one bead across the sheet+ const draw = () => {+ g.wash(blob(560, 500, 330, 250, 10, 0.3, 22, -0.35), "#9fb3c8", { alpha: 0.28, seed: 10, dx: 0, dy: 6, shrink: 1 });+ g.wash(blob(440, 700, 230, 120, 11, 0.35, 18, -0.2), "#d8b98a", { alpha: 0.25, seed: 11, dx: 0, dy: 4, shrink: 1 });+ g.wash(blob(700, 330, 120, 90, 12, 0.35, 16, 0.3), "#b8c7d6", { alpha: 0.22, seed: 12, dx: 0, dy: 4, shrink: 1 });+ };+ g.group("paint", () => {+ if (p >= 1) return draw();+ const c = g.cur, front = beadFront({ x0: 180, y0: 200, x1: 950, y1: 850 }, p, 3);+ c.save(); c.beginPath(); c.moveTo(-50, -50); c.lineTo(1130, -50); for (let i = front.length - 1; i >= 0; i--) c.lineTo(front[i][0], front[i][1]); c.closePath(); c.clip(); draw(); c.restore();+ });+};+// the pen: one loose stroke, growing along its path+const penOp = (pts: P[], w: number, seed: number, op = 0.95, wob = 0.9) => (g: Gfx, p: number) => g.group("plain", () => g.pen(pts, { w, color: INK, seed, wobble: wob, boil: 0, taper: 1, opacity: op, retrace: false, progress: p }));+const dabOp = (pts: P[], color: string, alpha = 1) => (g: Gfx, p: number) => { if (p > 0) g.group("plain", () => fillShape(g, pts, color, alpha)); };++// ---------------------------------------------------------------- the geometry (wren.ts, verbatim)+const twigLine: P[] = [[40, 806], [250, 752], [470, 712], [640, 690], [820, 652], [1080, 594]];+const side: P[] = [[792, 658], [846, 604], [884, 540], [930, 506]];+const lower: P[] = [[268, 748], [236, 806], [214, 868]];+const BODY: P[] = [[394, 450], [428, 416], [482, 420], [560, 448], [614, 494], [620, 536], [606, 582], [578, 624], [528, 650], [468, 634], [418, 590], [396, 540], [390, 492]];+const TAIL: P[] = [[590, 506], [606, 468], [626, 418], [646, 368], [662, 330], [690, 336], [684, 382], [664, 434], [644, 486], [622, 528]];+const WING: P[] = [[472, 476], [530, 468], [584, 500], [620, 552], [610, 584], [566, 598], [516, 580], [484, 540]];+const BELLY: P[] = [[410, 560], [452, 604], [506, 630], [560, 624], [548, 596], [488, 580], [440, 548]];+const leafOf = (base: P, ang: number, len: number, seed: number) => {+ const r = rng(seed), d: P = [Math.cos(ang), Math.sin(ang)], n: P = [-d[1], d[0]], at = (t: number, s: number): P => [base[0] + d[0] * t * len + n[0] * s * len, base[1] + d[1] * t * len + n[1] * s * len];+ const edge = [at(0, 0), at(0.2, 0.14), at(0.38, 0.3), at(0.5, 0.22), at(0.62, 0.34), at(0.78, 0.2), at(1, 0.02), at(0.8, -0.2), at(0.64, -0.3), at(0.5, -0.2), at(0.35, -0.28), at(0.18, -0.13)];+ const shape = smooth(edge, true, 5), color = mix(SAP, "#3f6c5e", r() * 0.4);+ return { shape, color, seed, mid: [at(0, 0), at(0.55, 0.01 * (r() - 0.5)), at(0.95, 0)] as P[], veins: [0.3, 0.5, 0.7].map((t, k) => [at(t, 0), at(t + 0.12, (k % 2 ? 1 : -1) * 0.22)] as P[]) };+};+const LEAVES = [leafOf([884, 540], -1.9, 96, 40), leafOf([860, 580], -0.25, 110, 41), leafOf([930, 506], -0.75, 88, 42), leafOf([1010, 612], -1.1, 80, 43), leafOf([236, 800], 2.2, 84, 44)];+const HAWS: P[] = [[318, 772], [344, 786], [300, 796], [330, 810], [356, 812], [312, 822]];++// ---------------------------------------------------------------- the process+const build = (k: number): Proc => {+ const tl = timeline(8, k, true), A = (d: number, fn: Op["draw"]) => tl.add(d, fn);+ // 1. washes: background, then the twig, its leaves and haws, then the bird, light to dark+ A(40, bgOp); tl.wait(10);+ A(18, wetOp(tube(twigLine, 17, 6, true), UMBER, { alpha: 0.62, seed: 30, pool: 0.8 })); A(9, wetOp(tube(side, 7, 3, true), UMBER, { alpha: 0.55, seed: 31 })); A(8, wetOp(tube(lower, 7, 3, true), UMBER, { alpha: 0.55, seed: 32 }));+ LEAVES.forEach((l) => A(8, wetOp(l.shape, l.color, { alpha: 0.6, seed: l.seed, pool: 0.7 })));+ HAWS.forEach(([x, y], i) => A(4, wetOp(blob(x, y, 12, 12.5, 60 + i, 0.06, 12), HAW, { alpha: 0.85, seed: 60 + i, pool: 0.9 })));+ A(4, (g, p) => { if (p > 0) g.group("plain", () => HAWS.forEach(([x, y], i) => fillShape(g, blob(x - 4, y - 5, 3.4, 2.6, 70 + i, 0.1, 8), PAPER, 0.9))); }); // highlights lifted out with a damp brush+ tl.wait(8);+ A(14, wetOp(smooth(TAIL, true, 8), UMBER, { alpha: 0.62, seed: 200, pool: 0.4 }));+ A(22, wetOp(smooth(BODY, true, 8), BROWN, { alpha: 0.55, seed: 201, pool: 0.75, bloom: [548, 470], bloomR: 20 }));+ A(12, wetOp(smooth(BELLY, true, 8), BUFF, { alpha: 0.5, seed: 202, pool: 0.3 }));+ A(10, wetOp(blob(520, 460, 70, 26, 203, 0.2, 12, 0.35), RUFOUS, { alpha: 0.35, seed: 204, pool: 0.2 }));+ A(14, wetOp(smooth(WING, true, 8), DARKB, { alpha: 0.45, seed: 205, pool: 0.6 }));+ A(3, dabOp(smooth([[398, 446], [430, 436], [470, 440], [494, 452], [470, 450], [432, 448], [402, 456]], true, 6), mix(BUFF, PAPER, 0.5), 0.9));+ A(8, wetOp(smooth([[398, 462], [428, 454], [466, 460], [490, 474], [462, 472], [428, 470], [400, 472]], true, 6), DARKB, { alpha: 0.55, seed: 206, pool: 0.2 }));+ tl.wait(14);+ // 2. the pen over the washes: the bird first (the focal thing), contour open where the light eats it+ const pen = (pts: P[], w: number, seed: number, op = 0.95, wob = 0.9, d?: number) => { 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]); A(d ?? Math.max(1.6, 1.2 + L / 70), penOp(pts, w, seed, op, wob)); };+ const b = smooth(BODY, true, 6), n = b.length;+ pen(b.slice(Math.round(n * 0.0), Math.round(n * 0.2)), 2.4, 300, 0.9); pen(b.slice(Math.round(n * 0.25), Math.round(n * 0.4)), 2.2, 301, 0.8);+ pen(b.slice(Math.round(n * 0.44), Math.round(n * 0.78)), 4.6, 302, 0.96); pen(b.slice(Math.round(n * 0.52), Math.round(n * 0.72)).map(([x, y]) => [x + 3, y + 4] as P), 2.2, 304, 0.55, 1.6);+ pen(b.slice(Math.round(n * 0.76), Math.round(n * 0.99)), 3.6, 303, 0.95);+ // the bill, the gape, the eyestripe and the eye+ A(2, dabOp([[397, 460], [362, 450], [364, 462], [397, 472]], "#d9806a", 0.8));+ pen([[400, 452], [376, 443], [346, 439]], 3.2, 370, 0.97, 0.15); pen([[398, 459], [374, 451], [348, 441]], 1.6, 371, 0.9, 0.15); pen([[400, 477], [378, 472], [352, 467]], 2.8, 372, 0.97, 0.15);+ pen([[402, 462], [432, 460], [470, 466], [492, 474]], 2.2, 375, 0.7, 0.4); pen([[392, 478], [398, 496], [404, 520]], 1.1, 373, 0.5, 0.4);+ A(3, (g, p) => { if (p > 0) g.group("plain", () => { fillShape(g, blob(432, 461, 7.2, 7, 380, 0.05, 10), INK); fillShape(g, blob(429.5, 458.5, 2.2, 2, 381, 0.05, 8), PAPER); }); });+ const r2 = rng(305); for (let i = 0; i < 9; i++) { const x = 420 + r2() * 90, y = 520 + r2() * 90; pen([[x, y], [x + 6, y + 5], [x + 9, y + 12]], 1.3, 306 + i, 0.4, 0.5, 1.2); }+ // tail and its barring, the wing, the covert spots, the flank+ const t = smooth(TAIL, true, 6), m = t.length;+ pen(t.slice(0, Math.round(m * 0.55)), 2.4, 310, 0.88); pen(t.slice(Math.round(m * 0.5), m - 2), 3.6, 311, 0.93);+ for (let i = 0; i < 9; i++) { const f = 0.12 + i * 0.1, a = lerpP(TAIL[1], TAIL[4], f), c = lerpP(TAIL[9], TAIL[6], f); pen([lerpP(a, c, 0.06), lerpP(lerpP(a, c, 0.5), [a[0] - 3, a[1] + 3], 0.3), lerpP(a, c, 0.94)], 1.5, 320 + i, 0.8, 0.4, 1.3); }+ const w2 = smooth(WING, true, 6), q = w2.length;+ pen(w2.slice(Math.round(q * 0.12), Math.round(q * 0.64)), 3.4, 330, 0.93); pen(w2.slice(Math.round(q * 0.6), Math.round(q * 0.9)), 2.2, 331, 0.8);+ for (let i = 0; i < 7; i++) { const x = 548 + i * 9, y = 526 + i * 7; pen([[x - 8, y - 12], [x - 2, y - 4], [x + 6, y + 6]], 1.6, 340 + i, 0.85, 0.3, 1.3); }+ const sp: P[] = [[486, 490], [503, 503], [519, 488], [534, 506], [552, 497], [568, 512], [512, 518]];+ sp.forEach(([x, y], i) => { A(1.2, dabOp(blob(x, y, 3.2, 2.2, 350 + i, 0.2, 8), PAPER, 0.95)); pen([[x - 5, y + 3], [x, y + 5], [x + 5, y + 3]], 0.9, 356 + i, 0.8, 0.2, 1.2); });+ for (let i = 0; i < 6; i++) { const x = 548 + i * 10, y = 596 + (i % 2) * 5; pen([[x - 7, y], [x, y + 4], [x + 7, y + 1]], 1.0, 360 + i, 0.55, 0.3, 1.2); }+ // legs and toes wrapped round the twig+ [[498, 640, 486, 700], [534, 644, 540, 696]].forEach(([x0, y0, x1, y1], i) => {+ A(1.5, dabOp([[x0 - 4, y0], [x0 + 4, y0], [x1 + 3, y1], [x1 - 3, y1]], "#b98468", 0.75));+ pen([[x0, y0], [lerpP([x0, y0], [x1, y1], 0.5)[0] + 2, lerpP([x0, y0], [x1, y1], 0.5)[1]], [x1, y1]], 2.6, 390 + i, 0.95, 0.2);+ pen([[x1, y1], [x1 - 14, y1 + 2], [x1 - 22, y1 + 12]], 1.6, 392 + i, 0.95, 0.2); pen([[x1, y1], [x1 - 4, y1 + 8], [x1 - 10, y1 + 18]], 1.5, 394 + i, 0.9, 0.2); pen([[x1, y1], [x1 + 12, y1 + 4], [x1 + 16, y1 + 14]], 1.5, 396 + i, 0.9, 0.2);+ });+ tl.wait(8);+ // 3. the twig: bark edges (the top one left open where the light hits), thorns, ticks, leaves, haws+ const top = twigLine.map(([x, y], i) => [x, y - lerpP([17, 0], [6, 0], i / (twigLine.length - 1))[0]] as P), bot = twigLine.map(([x, y], i) => [x, y + lerpP([17, 0], [6, 0], i / (twigLine.length - 1))[0]] as P);+ pen(top.slice(0, 3), 1.7, 80, 0.8); pen(top.slice(3), 1.5, 81, 0.75); pen(bot.slice(0, 4), 2.6, 82); pen(bot.slice(3), 2.2, 83);+ pen(side.map(([x, y]) => [x + 4, y + 3] as P), 1.9, 84); pen(lower.map(([x, y]) => [x + 4, y] as P), 1.9, 85);+ const r = rng(86);+ [[150, 770, -1], [410, 716, -1], [700, 676, 1], [960, 616, -1], [590, 700, 1]].forEach(([x, y, s], i) => pen([[x - 6, y], [x + 2, y + (s as number) * 14], [x + 7, y]], 1.4, 87 + i, 0.9, 0.3, 1.3));+ for (let i = 0; i < 16; i++) { const tt = r(), p = lerpP(twigLine[Math.floor(tt * 4)], twigLine[Math.floor(tt * 4) + 1], (tt * 4) % 1); pen([[p[0] - 5, p[1] - 2 + r() * 6], [p[0] + 6, p[1] + r() * 5]], 0.9, 100 + i, 0.55, 0.3, 1); }+ LEAVES.forEach((l, i) => { pen(l.shape.filter((_, k) => k % 2 === 0), 1.3, 120 + i, 0.8, 0.7); pen(l.mid, 1.1, 130 + i, 0.7, 0.3); l.veins.forEach((v, k) => pen(v, 0.7, 140 + i * 5 + k, 0.55, 0.2, 1)); });+ HAWS.forEach(([x, y], i) => { const bl = blob(x, y, 12, 12.5, 60 + i, 0.06, 12); pen(bl.slice(Math.floor(bl.length * 0.35)).concat(bl.slice(0, 2)), 1.3, 160 + i, 0.85, 0.4, 1.4); A(1, dabOp(blob(x + 1, y + 11, 2.2, 1.8, 170 + i, 0.1, 6), INK, 0.8)); });+ pen([[300, 752], [312, 764], [318, 772]], 1, 180, 0.8, 0.2); pen([[336, 752], [340, 772], [344, 786]], 1, 181, 0.8, 0.2); pen([[322, 752], [324, 790], [330, 810]], 1, 182, 0.8, 0.2);+ tl.wait(10);+ // 4. the pen shaken: spatters, flicked one after another away from the bird+ const rs = rng(13), dots: P[][] = []; for (let i = 0; i < 22; i++) { const x = 160 + rs() * 820, y = 280 + rs() * 640, big = rs() < 0.25; if (Math.hypot(x - 510, y - 530) < 170) continue; dots.push(blob(x, y, big ? 3.6 : 1.4 + rs(), big ? 3 : 1.2 + rs() * 0.8, 20 + i, 0.3, 8)); void (0.7 + rs() * 0.3); }+ const rs2 = rng(13), alphas: number[] = []; for (let i = 0; i < 22; i++) { const x = 160 + rs2() * 820, y = 280 + rs2() * 640; rs2(); rs2(); rs2(); if (Math.hypot(x - 510, y - 530) < 170) continue; alphas.push(0.7 + rs2() * 0.3); }+ A(12, (g, p) => { const n2 = p >= 1 ? dots.length : Math.floor(dots.length * p); if (n2 > 0) g.group("plain", () => dots.slice(0, n2).forEach((d, i) => fillShape(g, d, INK, alphas[i]))); });+ const ground = (g: Gfx) => { const c = g.cur, e = g.env; c.setTransform(e.scale, 0, 0, e.scale, 0, 0); c.fillStyle = PAPER; c.fillRect(0, 0, e.W, e.H); };+ return { id: "wrenDraw", medium: INK_M, ground, ops: tl.ops, finish: (g) => { g.paper("coldpress", 0.16); g.paper("paper", 0.08); } };+};+const PROC = fit(build, N - 32), END = PROC.ops[PROC.ops.length - 1].t1; // one frame of the finished process, then the still++// the hold is the still itself, drawn fresh: caching it on an offscreen surface and copying it+// back was measured NOT byte-identical (offscreen and on-screen canvases rasterise differently),+// so the 30 held frames pay the still's own draw cost (~130 ms) to stay exact+export const STYLE = { id: "wrenDraw", name: "Ink & line-wash, drawn", family: "ink", medium: "watercolour washes laid as a travelling bead, then a flexible steel nib in iron-gall-dark ink, on cold-press paper", nearest: "wren", hero: "a Eurasian wren singing on a hawthorn twig" };++export const wrenDraw: Film = {+ meta: { title: "Wren on a twig · drawing itself", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: N },+ assets: { images: {} },+ shots: [{ id: "draw", start: 0, end: N, draw: (ctx, f, env) => (f >= N - 30 ? drawWren(ctx, 0, env) : runProcess(PROC, ctx, Math.min(f, END), env)) }],+};diff --git a/engine/src/hosts/demos/form-mascot.html b/engine/src/hosts/demos/form-mascot.htmlnew file mode 100644index 0000000..1d3eb68--- /dev/null+++ b/engine/src/hosts/demos/form-mascot.html@@ -0,0 +1,84 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Join the Paper Club · a form with a friend</title>+<meta name="description" content="An anidoodle interactive demo: a hand-drawn mascot that reads along, looks away for your password, and cheers when you sign up.">+<style>+ :root { --paper: #fbf6ea; --ink: #3d3437; --ink-soft: #6b5f62; --rose: #c9566b; --rose-soft: #f2899c; --butter: #f3d577; --sage: #5f8f62; --line: rgba(61,52,55,.2); --err: #b33a4f; }+ * { box-sizing: border-box; }+ body { margin: 0; min-height: 100vh; color: var(--ink); background: radial-gradient(1200px 600px at 80% -10%, #fff3d6, transparent 60%), var(--paper); font: 16px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; display: grid; place-items: center; padding: 28px 18px; -webkit-font-smoothing: antialiased; }+ .serif { font-family: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif; }+ .card { width: min(1020px, 100%); display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); background: #fffdf7; border: 2px solid var(--ink); border-radius: 26px; box-shadow: 8px 8px 0 var(--butter); overflow: hidden; }+ form { padding: 40px 40px 34px; display: flex; flex-direction: column; gap: 16px; }+ .kicker { font-size: 13px; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-soft); }+ h1 { font-size: 38px; line-height: 1.05; margin: 2px 0 4px; letter-spacing: -.02em; font-weight: 600; }+ .sub { margin: 0 0 6px; color: var(--ink-soft); }+ label { display: grid; gap: 6px; font-weight: 600; font-size: 14.5px; }+ .field { position: relative; }+ input { width: 100%; font: 17px/1.2 ui-sans-serif, system-ui, sans-serif; padding: 14px 16px; border: 2px solid var(--line); border-radius: 14px; background: #fff; color: var(--ink); transition: border-color .15s ease, box-shadow .15s ease; }+ input:focus { outline: none; border-color: var(--ink); box-shadow: 0 0 0 4px rgba(243,213,119,.55); }+ input[aria-invalid="true"] { border-color: var(--err); }+ .pw input { padding-right: 96px; }+ .reveal { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); font: 600 13px/1 ui-sans-serif, system-ui, sans-serif; padding: 9px 11px; border-radius: 10px; border: 1.5px solid var(--line); background: #fbf6ea; color: var(--ink); cursor: pointer; }+ .reveal[aria-pressed="true"] { background: var(--butter); border-color: var(--ink); }+ .reveal:focus-visible, .submit:focus-visible { outline: 3px solid var(--butter); outline-offset: 2px; }+ .msg { min-height: 22px; font-size: 14.5px; color: var(--err); margin: 0; }+ .msg.ok { color: var(--sage); }+ .submit { margin-top: 6px; font: 700 17px/1 ui-sans-serif, system-ui, sans-serif; padding: 17px 22px; border-radius: 999px; border: 2px solid var(--ink); background: var(--ink); color: var(--paper); cursor: pointer; box-shadow: 4px 4px 0 var(--rose-soft); transition: transform .15s ease, box-shadow .15s ease, background .2s ease; }+ .submit:hover { transform: translate(-2px, -2px); box-shadow: 6px 6px 0 var(--rose-soft); }+ .submit:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--rose-soft); }+ .submit[disabled] { opacity: .8; cursor: progress; }+ .submit.done { background: var(--sage); border-color: var(--sage); box-shadow: 4px 4px 0 var(--butter); }+ .fine { font-size: 13px; color: var(--ink-soft); margin: 4px 0 0; }+ .art { background: #fbf6ea; border-left: 2px solid var(--ink); display: flex; flex-direction: column; justify-content: center; }+ .art ani-doodle { display: block; }+ .art p { margin: 0; padding: 0 24px 22px; font-size: 13.5px; color: var(--ink-soft); text-align: center; }+ @media (max-width: 820px) { .card { grid-template-columns: 1fr; } .art { order: -1; border-left: 0; border-bottom: 2px solid var(--ink); } .art ani-doodle { max-width: 340px; margin: 0 auto; } form { padding: 28px 22px; } }+</style>+</head>+<body>+ <main class="card">+ <form id="f" novalidate>+ <span class="kicker">The Paper Club</span>+ <h1 class="serif">Join us. Bit will keep you company.</h1>+ <p class="sub">A monthly letter of hand-drawn things. No spam, one robot.</p>+ <label>Your name <input id="name" name="name" autocomplete="name" data-anidoodle="name" placeholder="Ada"></label>+ <label>Email <input id="email" name="email" type="email" autocomplete="email" data-anidoodle="email" placeholder="[email protected]"></label>+ <label>Password+ <span class="field pw"><input id="password" name="password" type="password" autocomplete="new-password" data-anidoodle="password" placeholder="8 characters or more">+ <button type="button" class="reveal" data-anidoodle="reveal" aria-pressed="false" aria-controls="password">Show</button></span>+ </label>+ <p class="msg" id="msg" role="status" aria-live="polite"></p>+ <button class="submit" data-anidoodle="submit" type="submit">Create my account</button>+ <p class="fine">Bit only ever sees how long your answers are and where your cursor is, never what you type.</p>+ </form>+ <div class="art">+ <ani-doodle piece="form-mascot"></ani-doodle>+ <p>He reads along. He looks away for passwords.</p>+ </div>+ </main>+ <script>+ const $ = (id) => document.getElementById(id), bit = () => document.querySelector("ani-doodle");+ const f = $("f"), msg = $("msg"), pw = $("password"), rv = document.querySelector(".reveal"), btn = document.querySelector(".submit");+ let state = "idle";+ const set = (s) => { state = s; bit()?.setState(s); };+ // the toggle keeps focus in the password field, so Bit stays covering his eyes unless he is caught peeking+ rv.addEventListener("mousedown", (e) => e.preventDefault());+ rv.addEventListener("click", () => { const on = rv.getAttribute("aria-pressed") !== "true"; rv.setAttribute("aria-pressed", String(on)); rv.textContent = on ? "Hide" : "Show"; pw.type = on ? "text" : "password"; if (state === "idle" || state === "peek") set(on ? "peek" : "idle"); });+ f.addEventListener("input", (e) => { e.target.removeAttribute("aria-invalid"); if (state === "error") { msg.textContent = ""; set(rv.getAttribute("aria-pressed") === "true" ? "peek" : "idle"); } });+ f.addEventListener("submit", (e) => {+ e.preventDefault(); if (state === "busy" || state === "success") return;+ const bad = [];+ if (!$("name").value.trim()) bad.push(["name", "Bit would love to know your name."]);+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test($("email").value)) bad.push(["email", "That email doesn't look quite right."]);+ if (pw.value.length < 8) bad.push(["password", "Passwords need 8 characters or more."]);+ if (bad.length) { bad.forEach(([id]) => $(id).setAttribute("aria-invalid", "true")); msg.className = "msg"; msg.textContent = bad[0][1]; set("error"); return; }+ msg.className = "msg"; msg.textContent = ""; btn.disabled = true; btn.textContent = "Winding up..."; set("busy");+ setTimeout(() => { set("success"); btn.disabled = false; btn.classList.add("done"); btn.textContent = "Welcome aboard!"; msg.className = "msg ok"; msg.textContent = "You're in. Check your inbox for a hand-drawn hello."; }, 1100);+ });+ </script>+<!--anidoodle-->+</body>+</html>diff --git a/engine/src/hosts/demos/mascot-hero.html b/engine/src/hosts/demos/mascot-hero.htmlnew file mode 100644index 0000000..4388c7d--- /dev/null+++ b/engine/src/hosts/demos/mascot-hero.html@@ -0,0 +1,92 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Tinker & Ink · a hero that watches back</title>+<meta name="description" content="An anidoodle interactive demo: a hand-drawn mascot who follows your pointer and your keyboard focus.">+<style>+ :root { --paper: #fbf6ea; --paper-2: #f4ead6; --ink: #3d3437; --ink-soft: #6b5f62; --rose: #c9566b; --rose-soft: #f2899c; --butter: #f3d577; --sage: #6fa874; --line: rgba(61,52,55,.18); }+ * { box-sizing: border-box; }+ html { background: var(--paper); }+ body { margin: 0; color: var(--ink); background: var(--paper); font: 17px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; -webkit-font-smoothing: antialiased; }+ .serif { font-family: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif; }+ a { color: inherit; }+ nav { max-width: 1160px; margin: 0 auto; padding: 22px 28px; display: flex; align-items: center; gap: 28px; }+ .brand { font-weight: 700; font-size: 20px; letter-spacing: -.01em; display: flex; align-items: center; gap: 10px; text-decoration: none; }+ .brand i { width: 14px; height: 14px; border-radius: 50%; background: var(--butter); box-shadow: 0 0 0 2px var(--ink); display: inline-block; }+ nav .links { display: flex; gap: 22px; margin-left: auto; font-size: 15px; color: var(--ink-soft); }+ nav .links a { text-decoration: none; }+ nav .links a:hover { color: var(--ink); text-decoration: underline; text-underline-offset: 4px; }+ .hero { max-width: 1160px; margin: 0 auto; padding: 24px 28px 40px; display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); gap: 40px; align-items: center; }+ .eyebrow { display: inline-flex; gap: 8px; align-items: center; font-size: 13px; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-soft); padding: 6px 12px; border: 1.5px dashed var(--line); border-radius: 999px; }+ h1 { font-size: clamp(40px, 5.4vw, 68px); line-height: 1.02; letter-spacing: -.025em; margin: 18px 0 18px; font-weight: 600; }+ h1 em { font-style: italic; color: var(--rose); }+ .lede { font-size: 19px; color: var(--ink-soft); max-width: 34ch; margin: 0 0 30px; }+ .ctas { display: flex; flex-wrap: wrap; gap: 14px; align-items: center; }+ .btn { font: 600 17px/1 ui-sans-serif, system-ui, sans-serif; padding: 16px 26px; border-radius: 999px; border: 2px solid var(--ink); cursor: pointer; transition: transform .15s ease, box-shadow .15s ease, background .15s ease; }+ .btn.primary { background: var(--ink); color: var(--paper); box-shadow: 4px 4px 0 var(--rose-soft); }+ .btn.primary:hover, .btn.primary:focus-visible { transform: translate(-2px, -2px); box-shadow: 6px 6px 0 var(--rose-soft); }+ .btn.primary:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 var(--rose-soft); }+ .btn.ghost { background: transparent; color: var(--ink); }+ .btn.ghost:hover, .btn.ghost:focus-visible { background: #fff8e3; }+ .btn:focus-visible { outline: 3px solid var(--butter); outline-offset: 3px; }+ .hint { margin-top: 26px; font-size: 14px; color: var(--ink-soft); display: flex; gap: 8px; align-items: center; }+ .hint kbd { font: 600 12px/1 ui-monospace, monospace; padding: 3px 6px; border: 1.5px solid var(--line); border-bottom-width: 3px; border-radius: 6px; background: #fff; }+ .stage { position: relative; }+ .stage ani-doodle { display: block; max-width: 540px; margin-left: auto; border-radius: 6px; }+ .toast { position: fixed; left: 50%; bottom: 28px; transform: translate(-50%, 220%); visibility: hidden; background: var(--ink); color: var(--paper); padding: 14px 20px; border-radius: 14px; font-size: 15px; transition: transform .35s cubic-bezier(.2,.9,.3,1.2); box-shadow: 4px 4px 0 var(--butter); }+ .toast.on { transform: translate(-50%, 0); visibility: visible; }+ .features { max-width: 1160px; margin: 0 auto; padding: 10px 28px 70px; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 22px; }+ .card { border: 1.5px solid var(--line); border-radius: 18px; padding: 22px 22px 20px; background: linear-gradient(#fffdf6, #fbf6ea); transition: border-color .2s ease, transform .2s ease; }+ .card:hover, .card:focus-visible { border-color: var(--ink); transform: translateY(-3px); outline: none; }+ .card h3 { margin: 0 0 6px; font-size: 21px; }+ .card p { margin: 0; color: var(--ink-soft); font-size: 15.5px; }+ .dot { width: 30px; height: 30px; border-radius: 50%; margin-bottom: 14px; border: 2px solid var(--ink); }+ footer { max-width: 1160px; margin: 0 auto; padding: 24px 28px 40px; color: var(--ink-soft); font-size: 13.5px; border-top: 1.5px dashed var(--line); }+ @media (max-width: 860px) {+ .hero { grid-template-columns: 1fr; gap: 10px; }+ .stage { order: -1; }+ .stage ani-doodle { margin: 0 auto; max-width: 420px; }+ .features { grid-template-columns: 1fr; }+ nav .links { display: none; }+ }+</style>+</head>+<body>+ <nav>+ <a class="brand serif" href="#"><i></i>Tinker & Ink</a>+ <div class="links"><a href="#">Work</a><a href="#">Studio</a><a href="#">Pricing</a><a href="#">Journal</a></div>+ </nav>++ <header class="hero">+ <div>+ <span class="eyebrow">Illustrated onboarding · made by hand</span>+ <h1 class="serif">Give your product a <em>friend</em> who is paying attention.</h1>+ <p class="lede">Characters drawn in pencil and watercolour, living on your page. They notice people. People notice them.</p>+ <div class="ctas">+ <button class="btn primary" data-anidoodle="start" id="start">Get started, it's free</button>+ <button class="btn ghost" data-anidoodle="tour">Take the tour</button>+ </div>+ <p class="hint">He is watching your pointer. <kbd>Tab</kbd> works too, and so does poking him.</p>+ </div>+ <div class="stage">+ <ani-doodle piece="mascot-hero"></ani-doodle>+ </div>+ </header>++ <section class="features">+ <div class="card" tabindex="0" data-anidoodle="f1"><div class="dot" style="background:#a9cdea"></div><h3 class="serif">Drawn, not generated</h3><p>Every mark is a pencil stroke in code: one source, the same pixels on every screen.</p></div>+ <div class="card" tabindex="0" data-anidoodle="f2"><div class="dot" style="background:#f3d577"></div><h3 class="serif">Watches, politely</h3><p>Pointer, keyboard focus and touch, with a pause button and a calm mode for reduced motion.</p></div>+ <div class="card" tabindex="0" data-anidoodle="f3"><div class="dot" style="background:#f2899c"></div><h3 class="serif">Weighs almost nothing</h3><p>No images, no fonts, no framework. One small module and a custom element.</p></div>+ </section>++ <footer>Tinker & Ink is a made-up studio. The robot is Bit, from the anidoodle storybook plate, drawn entirely in code.</footer>++ <div class="toast" role="status" aria-live="polite" id="toast">You're in. Bit is thrilled.</div>+ <script>+ document.getElementById("start").addEventListener("click", () => { const t = document.getElementById("toast"); t.classList.add("on"); clearTimeout(window.__toast); window.__toast = setTimeout(() => t.classList.remove("on"), 2400); });+ </script>+<!--anidoodle-->+</body>+</html>diff --git a/engine/src/hosts/demos/scroll-hero.html b/engine/src/hosts/demos/scroll-hero.htmlnew file mode 100644index 0000000..ac19301--- /dev/null+++ b/engine/src/hosts/demos/scroll-hero.html@@ -0,0 +1,74 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>How a picture-book page is made · drawn as you scroll</title>+<meta name="description" content="An anidoodle interactive demo: a storybook illustration that draws itself, pencil, paint and line, as you scroll.">+<style>+ :root { --paper: #fbf6ea; --ink: #3d3437; --ink-soft: #6b5f62; --rose: #c9566b; --butter: #f3d577; --sky: #a9cdea; --sage: #6fa874; --line: rgba(61,52,55,.18); }+ * { box-sizing: border-box; }+ body { margin: 0; color: var(--ink); background: var(--paper); font: 18px/1.65 "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif; -webkit-font-smoothing: antialiased; }+ .sans { font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }+ nav { max-width: 1180px; margin: 0 auto; padding: 22px 28px; display: flex; justify-content: space-between; align-items: center; font-size: 15px; }+ nav b { font-size: 19px; letter-spacing: -.01em; }+ nav span { color: var(--ink-soft); }+ .intro { max-width: 1180px; margin: 0 auto; padding: 8vh 28px 6vh; }+ .intro small { display: block; font: 600 13px/1 ui-sans-serif, system-ui, sans-serif; letter-spacing: .1em; text-transform: uppercase; color: var(--ink-soft); margin-bottom: 18px; }+ .intro h1 { font-size: clamp(42px, 6.4vw, 86px); line-height: .98; letter-spacing: -.03em; margin: 0; font-weight: 600; max-width: 12ch; }+ .intro h1 em { color: var(--rose); }+ .intro p { max-width: 44ch; color: var(--ink-soft); font-size: 20px; margin: 22px 0 0; }+ .cue { margin-top: 34px; display: inline-flex; gap: 10px; align-items: center; font: 600 14px/1 ui-sans-serif, system-ui, sans-serif; color: var(--ink-soft); }+ .cue i { width: 22px; height: 34px; border: 2px solid var(--ink-soft); border-radius: 12px; position: relative; }+ .cue i::after { content: ""; position: absolute; left: 50%; top: 6px; width: 4px; height: 7px; margin-left: -2px; border-radius: 2px; background: var(--ink-soft); animation: wheel 1.6s ease-in-out infinite; }+ @keyframes wheel { 50% { transform: translateY(8px); opacity: .3; } }+ @media (prefers-reduced-motion: reduce) { .cue i::after { animation: none; } }+ #track { max-width: 1180px; margin: 0 auto; padding: 0 28px; display: grid; grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); gap: 48px; }+ .steps article { min-height: 92vh; display: flex; flex-direction: column; justify-content: center; padding: 10vh 0; }+ .steps .n { font: 700 13px/1 ui-sans-serif, system-ui, sans-serif; letter-spacing: .12em; text-transform: uppercase; display: inline-flex; align-items: center; gap: 10px; color: var(--ink-soft); }+ .steps .n::before { content: ""; width: 26px; height: 26px; border-radius: 50%; border: 2px solid var(--ink); background: var(--c, #fff); }+ .steps h2 { font-size: clamp(30px, 3.4vw, 44px); line-height: 1.08; letter-spacing: -.02em; margin: 14px 0 12px; font-weight: 600; }+ .steps p { margin: 0; color: var(--ink-soft); max-width: 40ch; }+ .sticky { position: sticky; top: 7vh; height: 86vh; display: flex; align-items: center; }+ .sticky ani-doodle { display: block; width: min(100%, 78vh); margin-left: auto; border-radius: 4px; box-shadow: 0 1px 0 rgba(61,52,55,.06), 0 30px 60px -30px rgba(61,52,55,.35); }+ .outro { max-width: 760px; margin: 0 auto; padding: 16vh 28px 12vh; text-align: center; }+ .outro h2 { font-size: clamp(32px, 4vw, 52px); letter-spacing: -.02em; line-height: 1.05; margin: 0 0 14px; font-weight: 600; }+ .outro p { color: var(--ink-soft); margin: 0 auto; max-width: 46ch; }+ footer { text-align: center; padding: 0 28px 48px; font: 13.5px/1.5 ui-sans-serif, system-ui, sans-serif; color: var(--ink-soft); }+ @media (max-width: 860px) {+ #track { grid-template-columns: 1fr; gap: 0; }+ .sticky { order: -1; top: 0; height: auto; padding: 10px 0; background: var(--paper); z-index: 2; }+ .sticky ani-doodle { width: min(100%, 46vh); margin: 0 auto; }+ .steps article { min-height: 70vh; }+ }+</style>+</head>+<body>+ <nav class="sans"><b class="serif">Marginalia Press</b><span>Picture books, made slowly</span></nav>++ <header class="intro">+ <small>How a page gets made</small>+ <h1>Every picture starts with a <em>line</em>.</h1>+ <p>Scroll down and this page will draw one of ours for you, the way an illustrator does: pencil first, then paint, then the line that holds it all together.</p>+ <div class="cue"><i></i> Scroll to draw. Scroll back to undraw.</div>+ </header>++ <section id="track">+ <div class="steps">+ <article style="--c: #d9dbe6"><span class="n">Step one</span><h2>Loose ovals, and a line through them.</h2><p>Before anything has a face, it has a gesture. Two ovals for the head and body, a line for how he stands, a line for where the ground is. Nobody will notice these later. Everyone would notice without them.</p></article>+ <article style="--c: #eee7d8"><span class="n">Step two</span><h2>A light pencil pass, head first.</h2><p>The drawing goes down faintly, so it can still change its mind. Head first, because the face decides everything else; then down, one stroke at a time.</p></article>+ <article style="--c: #a9cdea"><span class="n">Step three</span><h2>Washes, from where the brush lands.</h2><p>Sky, warm light, grass, then the robot himself, back to front. Watercolour never quite fills its outline, and that is the charm.</p></article>+ <article style="--c: #f3d577"><span class="n">Step four</span><h2>The final line, over dry paint.</h2><p>Full-weight graphite, head first again. This is the pass that makes it look finished, and the one that is hardest to fake.</p></article>+ <article style="--c: #f2899c"><span class="n">Done</span><h2>Hello, Bit.</h2><p>The finished page is the very same picture as our printed plate, pixel for pixel. Scroll back up and the pencil will take it apart again.</p></article>+ </div>+ <div class="sticky"><ani-doodle piece="scroll-hero" scroll-track="#track"></ani-doodle></div>+ </section>++ <section class="outro">+ <h2>No images were harmed in the making of this page.</h2>+ <p>The illustration is drawn in code: every pencil stroke, every wash, the paper grain. The page downloads no pictures and no fonts; it is one file you could email.</p>+ </section>+ <footer>Marginalia Press is a made-up publisher. Bit and the meadow are the anidoodle storybook plate.</footer>+<!--anidoodle-->+</body>+</html>diff --git a/engine/src/hosts/interactive.ts b/engine/src/hosts/interactive.tsnew file mode 100644index 0000000..4f8ddcc--- /dev/null+++ b/engine/src/hosts/interactive.ts@@ -0,0 +1,239 @@+// THE INTERACTIVE HOST. Everything with a clock or a DOM lives here; the art (a Piece) never sees+// either. The host's whole job is to turn a person into an append-only InputLog, and to draw+//+// piece.draw(ctx, tick, env, stateAt(tick, log, piece.input))+//+// at 60 Hz ticks. Replaying that log anywhere draws the same frames (tools/replay.mjs proves it).+//+// mount(el, piece, opts) -> Controller no framework, no dependency+// define({ name: piece }) -> <ani-doodle piece="name" scroll-track="#sel" state="idle">+//+// Page binding: any element with data-anidoodle="<name>" is a target. Pointer enter/leave, press,+// click (mouse, touch, pen, or Enter/Space from the keyboard), keyboard focus, and typing (length+// and caret) on it go into the log, with its rectangle in piece coordinates. controller.setState()+// logs a UI state ("busy", "success", "error"...). Everything else the page does is its own.+import type { Ctx, Env, Layer } from "../canvas-core/core";+import { stats as bakeStats } from "../canvas-core/bake";+import { HZ, restState, stateAt, type InputEvent, type InputLog, type InputState, type Piece } from "../canvas-core/input";++export type MountOptions = {+ root?: ParentNode; // where data-anidoodle targets are looked for (default: document)+ scrollTrack?: HTMLElement | string | null; // input.scroll = progress of this element through the viewport+ pauseControl?: boolean; // a visible pause button (default true)+ maxScale?: number; // cap on device px per logical px (default 3)+ reducedMotion?: "auto" | boolean; // default "auto": follows prefers-reduced-motion+ state?: string; // initial UI state+ clock?: () => number; // ms. Default performance.now; the recorder injects a manual one+ sampleEvery?: number; // debug: hash every Nth drawn frame (replay gate)+ syncTiming?: boolean; // debug: force raster after each draw so frame time is real+ raster?: "gpu" | "cpu"; // see surfaceFor+};+export type Sample = { tick: number; scale: number; hash: string };+export type Controller = {+ el: HTMLElement; canvas: HTMLCanvasElement; piece: Piece; ready: Promise<void>;+ setState(name: string): void; pause(): void; play(): void; readonly paused: boolean; destroy(): void;+ // tooling (replay gate, recorder): none of these are needed to use a piece+ log(): InputLog; tick(): number; scale(): number; state(tick?: number): InputState;+ render(tick: number, log: InputLog, scale?: number, cold?: boolean): number; renderRest(tick: number, scale?: number): void; hash(): string;+ renderNow(): void; samples(): Sample[]; stats(): Record<string, unknown>; envs(): { live: Env; last: Env | null };+};++// raster "cpu" (willReadFrequently) is for the gate: Chromium silently moves a GPU canvas to software+// after its first readback, and the two antialias differently, so hashing a GPU canvas compares two+// renderers. Pages ship "gpu" (the default); the replay gate forces "cpu" through window.__ANI_RASTER__.+const surfaceFor = (cpu: boolean) => (w: number, h: number): Layer => {+ const c = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(w, h) : Object.assign(document.createElement("canvas"), { width: w, height: h });+ return { canvas: c, ctx: c.getContext("2d", cpu ? { willReadFrequently: true } : undefined) as unknown as Ctx } as Layer;+};+let surface = surfaceFor(false);+const newEnv = (piece: Piece, scale: number): Env => ({ W: piece.meta.W, H: piece.meta.H, scale, cache: new Map(), canvas: surface });+const q = (v: number, step: number) => Math.round(v / step) * step;+const fnv = (d: Uint8ClampedArray) => { let h = 0x811c9dc5; for (let i = 0; i < d.length; i++) { h ^= d[i]; h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(16).padStart(8, "0"); };+const pct = (a: number[], p: number) => { if (!a.length) return 0; const s = [...a].sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };++declare global { interface Window { __anidoodle?: Controller[]; __ANI_CLOCK__?: () => number; __ANI_RASTER__?: "gpu" | "cpu"; __ANI_SAMPLE__?: number; __ANI_SYNC__?: boolean } }++export const mount = (el: HTMLElement, piece: Piece, opts: MountOptions = {}): Controller => {+ const { W, H } = piece.meta, root = opts.root ?? document, clock = opts.clock ?? window.__ANI_CLOCK__ ?? (() => performance.now());+ const canvas = document.createElement("canvas");+ canvas.setAttribute("role", "img"); canvas.setAttribute("aria-label", piece.meta.alt);+ Object.assign(canvas.style, { display: "block", width: "100%", height: "auto", aspectRatio: `${W} / ${H}`, opacity: "0", transition: "opacity .4s ease", touchAction: "manipulation" });+ if (getComputedStyle(el).position === "static") el.style.position = "relative";+ el.appendChild(canvas);+ const cpu = (opts.raster ?? window.__ANI_RASTER__) === "cpu"; surface = surfaceFor(cpu);+ opts = { ...opts, sampleEvery: opts.sampleEvery ?? window.__ANI_SAMPLE__, syncTiming: opts.syncTiming ?? window.__ANI_SYNC__ };+ const ctx = canvas.getContext("2d", { alpha: false, willReadFrequently: cpu }) as CanvasRenderingContext2D;++ // ---------------------------------------------------------------- clock and log+ const log: InputLog = [];+ let t0 = 0, started = false, paused = false, pausedAt = 0, pausedTotal = 0, lastDrawn = -1, destroyed = false;+ const clockTick = () => (started ? Math.floor(((paused ? pausedAt : clock()) - t0 - pausedTotal) * HZ / 1000) : 0);+ // rule 2 of input.ts: an event takes effect after every tick already drawn+ const push = (e: Omit<InputEvent, "tick">) => {+ const ev: InputEvent = { tick: Math.max(lastDrawn + 1, clockTick()), ...e }, last = log[log.length - 1];+ const merge = last && last.tick === ev.tick && last.type === ev.type && last.target === ev.target && (ev.type === "move" || ev.type === "scroll" || ev.type === "rect" || ev.type === "key" || ev.type === "view");+ if (merge) log[log.length - 1] = ev; else log.push(ev);+ wake();+ };++ // ---------------------------------------------------------------- geometry: client px -> piece px+ const box = () => canvas.getBoundingClientRect();+ const toPiece = (cx: number, cy: number, r = box()): [number, number] => [q(((cx - r.left) * W) / (r.width || 1), 0.25), q(((cy - r.top) * H) / (r.height || 1), 0.25)];+ const targets = new Map<Element, string>(), rects = new Map<string, string>(), fields = new Map<string, string>();+ const scan = () => { targets.clear(); root.querySelectorAll("[data-anidoodle]").forEach((t) => targets.set(t, t.getAttribute("data-anidoodle") || "target")); };+ const nameOf = (t: EventTarget | null) => { for (let n = t as Element | null; n; n = n.parentElement) { const k = targets.get(n); if (k) return { el: n, name: k }; } return null; };+ const track = () => (typeof opts.scrollTrack === "string" ? document.querySelector(opts.scrollTrack) : opts.scrollTrack) as HTMLElement | null;+ let lastScroll = "";+ const poll = () => {+ const r = box(); if (!r.width) return;+ targets.forEach((name, t) => {+ const b = t.getBoundingClientRect(), [x, y] = toPiece(b.left, b.top, r), [x1, y1] = toPiece(b.right, b.bottom, r), k = `${x},${y},${x1},${y1}`;+ if (rects.get(name) !== k) { rects.set(name, k); push({ type: "rect", target: name, x, y, w: x1 - x, h: y1 - y }); }+ });+ const tk = track(); if (tk) {+ const b = tk.getBoundingClientRect(), vh = window.innerHeight, span = b.height - vh;+ const p = span > 1 ? -b.top / span : (vh - b.top) / (vh + b.height), v = Math.max(0, Math.min(1, q(p, 1e-4))).toFixed(4);+ if (v !== lastScroll) { lastScroll = v; push({ type: "scroll", value: Number(v) }); }+ }+ };++ // ---------------------------------------------------------------- scale, envs, baking+ const maxScale = opts.maxScale ?? 3;+ const wantScale = () => { const w = box().width || W; return Math.max(0.5, Math.min(maxScale, q((w * (window.devicePixelRatio || 1)) / W, 0.25))); };+ let env = newEnv(piece, wantScale()), pending: { env: Env; gen: Iterator<unknown> } | null = null, bakeMs = 0;+ const size = (e: Env) => { canvas.width = Math.round(W * e.scale); canvas.height = Math.round(H * e.scale); };+ const step = (gen: Iterator<unknown>, budget: number) => { const t = performance.now(); while (performance.now() - t < budget) if (gen.next().done) { bakeMs += performance.now() - t; return true; } bakeMs += performance.now() - t; return false; };+ let rescaleTimer = 0;+ const rescale = () => { const s = wantScale(); if (s === env.scale && !pending) return; if (pending?.env.scale === s) return; clearTimeout(rescaleTimer); rescaleTimer = window.setTimeout(() => { if (s === env.scale) { pending = null; return; } const e = newEnv(piece, s); pending = { env: e, gen: (piece.bake?.(e) ?? [])[Symbol.iterator]() }; wake(); }, 180); };++ // ---------------------------------------------------------------- the frame+ const frameTimes: number[] = [], samples: Sample[] = [];+ let drawn = 0;+ const hash = () => fnv(ctx.getImageData(0, 0, canvas.width, canvas.height).data);+ const draw = (tick: number) => {+ const s = stateAt(tick, log, piece.input), t = performance.now();+ piece.draw(ctx, tick, env, s);+ if (opts.syncTiming) ctx.getImageData(0, 0, 1, 1);+ frameTimes.push(performance.now() - t); if (frameTimes.length > 3600) frameTimes.shift();+ lastDrawn = tick; drawn++;+ if (opts.sampleEvery && drawn % opts.sampleEvery === 0) samples.push({ tick, scale: env.scale, hash: hash() });+ };+ let raf = 0, visible = true, polls = 0;+ const running = () => started && !paused && visible && !destroyed && document.visibilityState === "visible";+ const loop = () => {+ raf = 0; if (destroyed) return;+ if (pending && step(pending.gen, 6)) { env = pending.env; pending = null; size(env); push({ type: "view", value: env.scale }); draw(Math.max(lastDrawn, clockTick())); }+ if (++polls % 30 === 0) { poll(); rescale(); }+ const tick = clockTick(); if (tick > lastDrawn) draw(tick);+ if (running() || pending) raf = requestAnimationFrame(loop);+ };+ const wake = () => { if (!raf && (running() || pending)) raf = requestAnimationFrame(loop); };++ // ---------------------------------------------------------------- listeners+ const on = <K extends keyof WindowEventMap>(t: EventTarget, type: K | string, fn: (e: Event) => void, o: AddEventListenerOptions = { passive: true }) => { t.addEventListener(type, fn, o); offs.push(() => t.removeEventListener(type, fn, o)); };+ const offs: (() => void)[] = [];+ let pressed: Element | null = null, hovered: Element | null = null;+ on(window, "pointermove", (e) => { const p = e as PointerEvent; const [x, y] = toPiece(p.clientX, p.clientY); push({ type: "move", x, y, value: p.pointerType || "mouse" }); });+ on(document, "pointerout", (e) => { if (!(e as PointerEvent).relatedTarget) push({ type: "leave" }); });+ on(window, "blur", () => push({ type: "leave" }));+ on(window, "pointerover", (e) => { const h = nameOf(e.target); if (h?.el === hovered) return; if (hovered) push({ type: "exit", target: targets.get(hovered) }); hovered = h?.el ?? null; if (h) push({ type: "enter", target: h.name }); });+ on(window, "pointerdown", (e) => { const p = e as PointerEvent; if (p.pointerType !== "mouse") { const [x, y] = toPiece(p.clientX, p.clientY); push({ type: "move", x, y, value: p.pointerType }); } /* a tap has no pointermove before it */ const h = nameOf(e.target), self = e.target === canvas; if (!h && !self) return; pressed = h?.el ?? canvas; push({ type: "down", target: h?.name ?? "self" }); });+ on(window, "pointerup", (e) => {+ const p = e as PointerEvent, h = nameOf(e.target), onIt = pressed && (pressed === canvas ? e.target === canvas : !!h && h.el === pressed);+ if (pressed) push(onIt ? { type: "up", target: pressed === canvas ? "self" : targets.get(pressed) } : { type: "cancel" }); pressed = null;+ if (p.pointerType === "touch") { if (hovered) push({ type: "exit", target: targets.get(hovered) }); hovered = null; push({ type: "leave" }); } // a finger that lifts is not hovering anything+ });+ on(window, "pointercancel", () => { if (pressed) push({ type: "cancel" }); pressed = null; });+ on(window, "click", (e) => { if ((e as MouseEvent).detail !== 0) return; const h = nameOf(e.target); if (!h) return; push({ type: "down", target: h.name }); push({ type: "up", target: h.name }); }); // Enter / Space+ on(window, "focusin", (e) => { const h = nameOf(e.target); if (!h) return; const el2 = e.target as Element; if (el2.matches?.(":focus-visible") || el2.matches?.("input,textarea,select")) push({ type: "focus", target: h.name }); });+ on(window, "focusout", (e) => { const h = nameOf(e.target); if (h) push({ type: "blur", target: h.name }); });+ const measure = document.createElement("canvas").getContext("2d")!;+ const typed = (e: Event) => {+ const h = nameOf(e.target), inp = e.target as HTMLInputElement; if (!h || !inp.matches?.("input,textarea")) return;+ const cs = getComputedStyle(inp), len = inp.value.length, text = inp.type === "password" ? "•".repeat(len) : inp.value;+ measure.font = cs.font || `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;+ const b = inp.getBoundingClientRect(), pl = parseFloat(cs.paddingLeft) + parseFloat(cs.borderLeftWidth), pr = parseFloat(cs.paddingRight) + parseFloat(cs.borderRightWidth);+ const cx = Math.min(b.right - pr, b.left + pl + measure.measureText(text.slice(0, inp.selectionStart ?? len)).width - inp.scrollLeft), [x, y] = toPiece(cx, b.top + b.height / 2), k = `${len},${x},${y}`;+ if (fields.get(h.name) === k) return; fields.set(h.name, k); push({ type: "key", target: h.name, value: len, x, y });+ };+ ["input", "keyup", "focusin", "select"].forEach((t) => on(window, t, typed));+ let pollQueued = false;+ const queuePoll = () => { if (pollQueued) return; pollQueued = true; requestAnimationFrame(() => { pollQueued = false; poll(); rescale(); }); };+ on(window, "scroll", queuePoll); on(window, "resize", queuePoll);+ const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(queuePoll) : null; ro?.observe(canvas);+ const mq = window.matchMedia?.("(prefers-reduced-motion: reduce)");+ const reduced = () => (opts.reducedMotion === undefined || opts.reducedMotion === "auto" ? !!mq?.matches : opts.reducedMotion);+ if (mq && (opts.reducedMotion ?? "auto") === "auto") { const f = () => push({ type: "motion", value: reduced() ? "reduce" : "full" }); mq.addEventListener?.("change", f); offs.push(() => mq.removeEventListener?.("change", f)); }+ const io = typeof IntersectionObserver !== "undefined" ? new IntersectionObserver((es) => { visible = es.some((x) => x.isIntersecting); wake(); }) : null; io?.observe(canvas);+ on(document, "visibilitychange", () => wake());++ // ---------------------------------------------------------------- pause control (WCAG 2.2.2)+ let btn: HTMLButtonElement | null = null;+ const paint = () => { if (!btn) return; btn.setAttribute("aria-pressed", String(paused)); btn.setAttribute("aria-label", paused ? "Play animation" : "Pause animation"); btn.dataset.state = paused ? "paused" : "playing"; btn.textContent = paused ? "\u25B6" : "\u2759\u2759"; };+ if (opts.pauseControl !== false) {+ btn = document.createElement("button"); btn.type = "button"; btn.className = "ani-doodle-pause";+ Object.assign(btn.style, { position: "absolute", right: "10px", bottom: "10px", width: "34px", height: "34px", borderRadius: "50%", border: "1.5px solid rgba(61,52,55,.55)", background: "rgba(251,246,234,.85)", color: "#3d3437", cursor: "pointer", font: "600 12px/1 system-ui, sans-serif", display: "grid", placeItems: "center", padding: "0" });+ btn.addEventListener("click", (e) => { e.stopPropagation(); if (paused) api.play(); else api.pause(); });+ el.appendChild(btn); paint();+ }++ // ---------------------------------------------------------------- start: log the initial configuration at tick 0, bake, show+ scan();+ push({ type: "motion", value: reduced() ? "reduce" : "full" });+ if (opts.state) push({ type: "state", value: opts.state });+ poll(); push({ type: "view", value: env.scale });+ const ready = (async () => {+ size(env);+ const gen = (piece.bake?.(env) ?? [])[Symbol.iterator]();+ await new Promise<void>((res) => { const go = () => (destroyed || step(gen, 12) ? res() : requestAnimationFrame(go)); go(); });+ started = true; t0 = clock(); draw(0); canvas.style.opacity = "1"; wake();+ })();++ const api: Controller = {+ el, canvas, piece, ready,+ setState: (name) => push({ type: "state", value: name }),+ pause: () => { if (paused) return; pausedAt = clock(); paused = true; paint(); },+ play: () => { if (!paused) return; pausedTotal += clock() - pausedAt; paused = false; paint(); wake(); },+ get paused() { return paused; },+ destroy: () => { destroyed = true; offs.forEach((f) => f()); ro?.disconnect(); io?.disconnect(); if (raf) cancelAnimationFrame(raf); canvas.remove(); btn?.remove(); const all = window.__anidoodle; if (all) all.splice(all.indexOf(api), 1); },+ log: () => log.map((e) => ({ ...e })),+ tick: () => lastDrawn, scale: () => env.scale,+ state: (tick = lastDrawn) => stateAt(tick, log, piece.input),+ // Draw `tick` of an arbitrary log at an arbitrary scale into this canvas (the live loop should be+ // paused). cold = a brand-new env: every sprite re-baked on demand, nothing carried over.+ render: (tick, lg, scale = env.scale, cold = false) => {+ const e = cold ? newEnv(piece, scale) : scale === env.scale ? env : (replayEnvs.get(scale) ?? replayEnvs.set(scale, newEnv(piece, scale)).get(scale)!);+ if (canvas.width !== Math.round(W * scale)) { canvas.width = Math.round(W * scale); canvas.height = Math.round(H * scale); }+ lastEnv = e; const t = performance.now(); piece.draw(ctx, tick, e, stateAt(tick, lg, piece.input)); ctx.getImageData(0, 0, 1, 1); return performance.now() - t;+ },+ // the untouched piece, from restState (built without the reducer): the plain loop+ renderRest: (tick, scale = env.scale) => { const e = scale === env.scale ? env : (replayEnvs.get(scale) ?? replayEnvs.set(scale, newEnv(piece, scale)).get(scale)!); if (canvas.width !== Math.round(W * scale)) { canvas.width = Math.round(W * scale); canvas.height = Math.round(H * scale); } piece.draw(ctx, tick, e, restState(tick, piece.input)); },+ hash,+ renderNow: () => { poll(); const tk = clockTick(); if (started && tk > lastDrawn) draw(tk); },+ samples: () => samples.slice(), envs: () => ({ live: env, last: lastEnv }),+ stats: () => ({ bakeMs: Math.round(bakeMs), sprites: bakeStats.baked, spriteMB: +(bakeStats.bytes / 1048576).toFixed(1), frames: frameTimes.length, p50: +pct(frameTimes, 0.5).toFixed(2), p95: +pct(frameTimes, 0.95).toFixed(2), max: +pct(frameTimes, 1).toFixed(2), scale: env.scale, log: log.length }),+ };+ const replayEnvs = new Map<number, Env>(); let lastEnv: Env | null = null;+ (window.__anidoodle ??= []).push(api);+ return api;+};++// <ani-doodle piece="name" scroll-track="#selector" state="idle" paused>+export const define = (pieces: Record<string, Piece>, tag = "ani-doodle") => {+ if (typeof customElements === "undefined" || customElements.get(tag)) return;+ customElements.define(tag, class extends HTMLElement {+ static observedAttributes = ["state", "paused"];+ controller: Controller | null = null;+ connectedCallback() {+ if (this.controller) return;+ const name = this.getAttribute("piece") ?? Object.keys(pieces)[0], piece = pieces[name];+ if (!piece) { this.textContent = `ani-doodle: no piece "${name}" (have: ${Object.keys(pieces).join(", ")})`; return; }+ if (!this.style.display) this.style.display = "block";+ this.controller = mount(this, piece, { scrollTrack: this.getAttribute("scroll-track"), state: this.getAttribute("state") ?? undefined, pauseControl: !this.hasAttribute("no-pause") });+ if (this.hasAttribute("paused")) this.controller.pause();+ }+ disconnectedCallback() { this.controller?.destroy(); this.controller = null; }+ attributeChangedCallback(n: string, _o: string | null, v: string | null) { if (!this.controller) return; if (n === "state" && v) this.controller.setState(v); if (n === "paused") (v === null ? this.controller.play() : this.controller.pause()); }+ setState(s: string) { this.controller?.setState(s); }+ });+};diff --git a/engine/src/hosts/page-adaptAquarelle.ts b/engine/src/hosts/page-adaptAquarelle.tsnew file mode 100644index 0000000..569a6ca--- /dev/null+++ b/engine/src/hosts/page-adaptAquarelle.ts@@ -0,0 +1,4 @@+import { adaptAquarelle } from "../canvas-core/adaptAquarelle";+import { mountFilm } from "./page";++mountFilm(adaptAquarelle);diff --git a/engine/src/hosts/page-adaptScrapbook.ts b/engine/src/hosts/page-adaptScrapbook.tsnew file mode 100644index 0000000..e5c5c84--- /dev/null+++ b/engine/src/hosts/page-adaptScrapbook.ts@@ -0,0 +1,4 @@+import { adaptScrapbook } from "../canvas-core/adaptScrapbook";+import { mountFilm } from "./page";++mountFilm(adaptScrapbook);diff --git a/engine/src/hosts/page-bakerSheet.ts b/engine/src/hosts/page-bakerSheet.tsnew file mode 100644index 0000000..93783e5--- /dev/null+++ b/engine/src/hosts/page-bakerSheet.ts@@ -0,0 +1,4 @@+import { bakerSheet } from "../canvas-core/bakerSheet";+import { mountFilm } from "./page";++mountFilm(bakerSheet);diff --git a/engine/src/hosts/page-balloonDraw.ts b/engine/src/hosts/page-balloonDraw.tsnew file mode 100644index 0000000..dbc1bd5--- /dev/null+++ b/engine/src/hosts/page-balloonDraw.ts@@ -0,0 +1,4 @@+import { balloonDraw } from "../canvas-core/balloonDraw";+import { mountFilm } from "./page";++mountFilm(balloonDraw);diff --git a/engine/src/hosts/page-blueprint.ts b/engine/src/hosts/page-blueprint.tsnew file mode 100644index 0000000..c1def27--- /dev/null+++ b/engine/src/hosts/page-blueprint.ts@@ -0,0 +1,4 @@+import { blueprint } from "../canvas-core/blueprint";+import { mountFilm } from "./page";++mountFilm(blueprint);diff --git a/engine/src/hosts/page-brokenColour.ts b/engine/src/hosts/page-brokenColour.tsnew file mode 100644index 0000000..0ff2ed4--- /dev/null+++ b/engine/src/hosts/page-brokenColour.ts@@ -0,0 +1,4 @@+import { brokenColour } from "../canvas-core/brokenColour";+import { mountFilm } from "./page";++mountFilm(brokenColour);diff --git a/engine/src/hosts/page-charcoalErasure.ts b/engine/src/hosts/page-charcoalErasure.tsnew file mode 100644index 0000000..9e5e5fc--- /dev/null+++ b/engine/src/hosts/page-charcoalErasure.ts@@ -0,0 +1,4 @@+import { charcoalErasure } from "../canvas-core/charcoalErasure";+import { mountFilm } from "./page";++mountFilm(charcoalErasure);diff --git a/engine/src/hosts/page-colouredPencil.ts b/engine/src/hosts/page-colouredPencil.tsnew file mode 100644index 0000000..501cbd2--- /dev/null+++ b/engine/src/hosts/page-colouredPencil.ts@@ -0,0 +1,4 @@+import { colouredPencil } from "../canvas-core/colouredPencil";+import { mountFilm } from "./page";++mountFilm(colouredPencil);diff --git a/engine/src/hosts/page-embroidery.ts b/engine/src/hosts/page-embroidery.tsnew file mode 100644index 0000000..83a497f--- /dev/null+++ b/engine/src/hosts/page-embroidery.ts@@ -0,0 +1,4 @@+import { embroidery } from "../canvas-core/embroidery";+import { mountFilm } from "./page";++mountFilm(embroidery);diff --git a/engine/src/hosts/page-figureSheet.ts b/engine/src/hosts/page-figureSheet.tsnew file mode 100644index 0000000..c4cc0d9--- /dev/null+++ b/engine/src/hosts/page-figureSheet.ts@@ -0,0 +1,4 @@+import { figureSheet } from "../canvas-core/figureSheet";+import { mountFilm } from "./page";++mountFilm(figureSheet);diff --git a/engine/src/hosts/page-flatVector.ts b/engine/src/hosts/page-flatVector.tsnew file mode 100644index 0000000..008632a--- /dev/null+++ b/engine/src/hosts/page-flatVector.ts@@ -0,0 +1,4 @@+import { flatVector } from "../canvas-core/flatVector";+import { mountFilm } from "./page";++mountFilm(flatVector);diff --git a/engine/src/hosts/page-folkTale.ts b/engine/src/hosts/page-folkTale.tsnew file mode 100644index 0000000..32ede8c--- /dev/null+++ b/engine/src/hosts/page-folkTale.ts@@ -0,0 +1,4 @@+import { folkTale } from "../canvas-core/folkTale";+import { mountFilm } from "./page";++mountFilm(folkTale);diff --git a/engine/src/hosts/page-foxDraw.ts b/engine/src/hosts/page-foxDraw.tsnew file mode 100644index 0000000..f4ba359--- /dev/null+++ b/engine/src/hosts/page-foxDraw.ts@@ -0,0 +1,4 @@+import { foxDraw } from "../canvas-core/foxDraw";+import { mountFilm } from "./page";++mountFilm(foxDraw);diff --git a/engine/src/hosts/page-halftone.ts b/engine/src/hosts/page-halftone.tsnew file mode 100644index 0000000..2db22ea--- /dev/null+++ b/engine/src/hosts/page-halftone.ts@@ -0,0 +1,4 @@+import { halftone } from "../canvas-core/halftone";+import { mountFilm } from "./page";++mountFilm(halftone);diff --git a/engine/src/hosts/page-isometric.ts b/engine/src/hosts/page-isometric.tsnew file mode 100644index 0000000..3ed4dba--- /dev/null+++ b/engine/src/hosts/page-isometric.ts@@ -0,0 +1,4 @@+import { isometric } from "../canvas-core/isometric";+import { mountFilm } from "./page";++mountFilm(isometric);diff --git a/engine/src/hosts/page-koiDraw.ts b/engine/src/hosts/page-koiDraw.tsnew file mode 100644index 0000000..cb60660--- /dev/null+++ b/engine/src/hosts/page-koiDraw.ts@@ -0,0 +1,4 @@+import { koiDraw } from "../canvas-core/koiDraw";+import { mountFilm } from "./page";++mountFilm(koiDraw);diff --git a/engine/src/hosts/page-lessonCat.ts b/engine/src/hosts/page-lessonCat.tsnew file mode 100644index 0000000..c2ef020--- /dev/null+++ b/engine/src/hosts/page-lessonCat.ts@@ -0,0 +1,4 @@+import { lessonCat } from "../canvas-core/lessonCat";+import { mountFilm } from "./page";++mountFilm(lessonCat);diff --git a/engine/src/hosts/page-lessonCatFinal.ts b/engine/src/hosts/page-lessonCatFinal.tsnew file mode 100644index 0000000..c505f23--- /dev/null+++ b/engine/src/hosts/page-lessonCatFinal.ts@@ -0,0 +1,4 @@+import { lessonCatFinal } from "../canvas-core/lessonCatFinal";+import { mountFilm } from "./page";++mountFilm(lessonCatFinal);diff --git a/engine/src/hosts/page-lessonCatSheet.ts b/engine/src/hosts/page-lessonCatSheet.tsnew file mode 100644index 0000000..0156900--- /dev/null+++ b/engine/src/hosts/page-lessonCatSheet.ts@@ -0,0 +1,4 @@+import { lessonCatSheet } from "../canvas-core/lessonCatSheet";+import { mountFilm } from "./page";++mountFilm(lessonCatSheet);diff --git a/engine/src/hosts/page-lighthouseDraw.ts b/engine/src/hosts/page-lighthouseDraw.tsnew file mode 100644index 0000000..9ee13e7--- /dev/null+++ b/engine/src/hosts/page-lighthouseDraw.ts@@ -0,0 +1,4 @@+import { lighthouseDraw } from "../canvas-core/lighthouseDraw";+import { mountFilm } from "./page";++mountFilm(lighthouseDraw);diff --git a/engine/src/hosts/page-lowPoly.ts b/engine/src/hosts/page-lowPoly.tsnew file mode 100644index 0000000..eecef4e--- /dev/null+++ b/engine/src/hosts/page-lowPoly.ts@@ -0,0 +1,4 @@+import { lowPoly } from "../canvas-core/lowPoly";+import { mountFilm } from "./page";++mountFilm(lowPoly);diff --git a/engine/src/hosts/page-midCentury.ts b/engine/src/hosts/page-midCentury.tsnew file mode 100644index 0000000..95674a8--- /dev/null+++ b/engine/src/hosts/page-midCentury.ts@@ -0,0 +1,4 @@+import { midCentury } from "../canvas-core/midCentury";+import { mountFilm } from "./page";++mountFilm(midCentury);diff --git a/engine/src/hosts/page-miraComic.ts b/engine/src/hosts/page-miraComic.tsnew file mode 100644index 0000000..f7bb4ca--- /dev/null+++ b/engine/src/hosts/page-miraComic.ts@@ -0,0 +1,4 @@+import { miraComic } from "../canvas-core/miraComic";+import { mountFilm } from "./page";++mountFilm(miraComic);diff --git a/engine/src/hosts/page-miraEveryHand.ts b/engine/src/hosts/page-miraEveryHand.tsnew file mode 100644index 0000000..0639641--- /dev/null+++ b/engine/src/hosts/page-miraEveryHand.ts@@ -0,0 +1,4 @@+import { miraEveryHand } from "../canvas-core/miraEveryHand";+import { mountFilm } from "./page";++mountFilm(miraEveryHand);diff --git a/engine/src/hosts/page-miraRiso.ts b/engine/src/hosts/page-miraRiso.tsnew file mode 100644index 0000000..24bf8a6--- /dev/null+++ b/engine/src/hosts/page-miraRiso.ts@@ -0,0 +1,4 @@+import { miraRiso } from "../canvas-core/miraRiso";+import { mountFilm } from "./page";++mountFilm(miraRiso);diff --git a/engine/src/hosts/page-miraSheet.ts b/engine/src/hosts/page-miraSheet.tsnew file mode 100644index 0000000..e2a16cf--- /dev/null+++ b/engine/src/hosts/page-miraSheet.ts@@ -0,0 +1,4 @@+import { miraSheet } from "../canvas-core/miraSheet";+import { mountFilm } from "./page";++mountFilm(miraSheet);diff --git a/engine/src/hosts/page-miraTile.ts b/engine/src/hosts/page-miraTile.tsnew file mode 100644index 0000000..b573f0e--- /dev/null+++ b/engine/src/hosts/page-miraTile.ts@@ -0,0 +1,4 @@+import { miraTile } from "../canvas-core/miraTile";+import { mountFilm } from "./page";++mountFilm(miraTile);diff --git a/engine/src/hosts/page-miraTriptych.ts b/engine/src/hosts/page-miraTriptych.tsnew file mode 100644index 0000000..7641a83--- /dev/null+++ b/engine/src/hosts/page-miraTriptych.ts@@ -0,0 +1,4 @@+import { miraTriptych } from "../canvas-core/miraTriptych";+import { mountFilm } from "./page";++mountFilm(miraTriptych);diff --git a/engine/src/hosts/page-miraWalk.ts b/engine/src/hosts/page-miraWalk.tsnew file mode 100644index 0000000..7901614--- /dev/null+++ b/engine/src/hosts/page-miraWalk.ts@@ -0,0 +1,4 @@+import { miraWalk } from "../canvas-core/miraWalk";+import { mountFilm } from "./page";++mountFilm(miraWalk);diff --git a/engine/src/hosts/page-moonPhasesDraw.ts b/engine/src/hosts/page-moonPhasesDraw.tsnew file mode 100644index 0000000..9e31f00--- /dev/null+++ b/engine/src/hosts/page-moonPhasesDraw.ts@@ -0,0 +1,4 @@+import { moonPhasesDraw } from "../canvas-core/moonPhasesDraw";+import { mountFilm } from "./page";++mountFilm(moonPhasesDraw);diff --git a/engine/src/hosts/page-paintedOil.ts b/engine/src/hosts/page-paintedOil.tsnew file mode 100644index 0000000..0968070--- /dev/null+++ b/engine/src/hosts/page-paintedOil.ts@@ -0,0 +1,4 @@+import { paintedOil } from "../canvas-core/paintedOil";+import { mountFilm } from "./page";++mountFilm(paintedOil);diff --git a/engine/src/hosts/page-paperCraft.ts b/engine/src/hosts/page-paperCraft.tsnew file mode 100644index 0000000..30bc8ab--- /dev/null+++ b/engine/src/hosts/page-paperCraft.ts@@ -0,0 +1,4 @@+import { paperCraft } from "../canvas-core/paperCraft";+import { mountFilm } from "./page";++mountFilm(paperCraft);diff --git a/engine/src/hosts/page-pixelArt.ts b/engine/src/hosts/page-pixelArt.tsnew file mode 100644index 0000000..ba61908--- /dev/null+++ b/engine/src/hosts/page-pixelArt.ts@@ -0,0 +1,4 @@+import { pixelArt } from "../canvas-core/pixelArt";+import { mountFilm } from "./page";++mountFilm(pixelArt);diff --git a/engine/src/hosts/page-pocketWatchDraw.ts b/engine/src/hosts/page-pocketWatchDraw.tsnew file mode 100644index 0000000..31f5a9e--- /dev/null+++ b/engine/src/hosts/page-pocketWatchDraw.ts@@ -0,0 +1,4 @@+import { pocketWatchDraw } from "../canvas-core/pocketWatchDraw";+import { mountFilm } from "./page";++mountFilm(pocketWatchDraw);diff --git a/engine/src/hosts/page-ranunculusDraw.ts b/engine/src/hosts/page-ranunculusDraw.tsnew file mode 100644index 0000000..7d29f88--- /dev/null+++ b/engine/src/hosts/page-ranunculusDraw.ts@@ -0,0 +1,4 @@+import { ranunculusDraw } from "../canvas-core/ranunculusDraw";+import { mountFilm } from "./page";++mountFilm(ranunculusDraw);diff --git a/engine/src/hosts/page-rubberHose.ts b/engine/src/hosts/page-rubberHose.tsnew file mode 100644index 0000000..42ef590--- /dev/null+++ b/engine/src/hosts/page-rubberHose.ts@@ -0,0 +1,4 @@+import { rubberHose } from "../canvas-core/rubberHose";+import { mountFilm } from "./page";++mountFilm(rubberHose);diff --git a/engine/src/hosts/page-scrapbook.ts b/engine/src/hosts/page-scrapbook.tsnew file mode 100644index 0000000..e3fccc6--- /dev/null+++ b/engine/src/hosts/page-scrapbook.ts@@ -0,0 +1,4 @@+import { scrapbook } from "../canvas-core/scrapbook";+import { mountFilm } from "./page";++mountFilm(scrapbook);diff --git a/engine/src/hosts/page-scratchboard.ts b/engine/src/hosts/page-scratchboard.tsnew file mode 100644index 0000000..42574a6--- /dev/null+++ b/engine/src/hosts/page-scratchboard.ts@@ -0,0 +1,4 @@+import { scratchboard } from "../canvas-core/scratchboard";+import { mountFilm } from "./page";++mountFilm(scratchboard);diff --git a/engine/src/hosts/page-stipple.ts b/engine/src/hosts/page-stipple.tsnew file mode 100644index 0000000..64957da--- /dev/null+++ b/engine/src/hosts/page-stipple.ts@@ -0,0 +1,4 @@+import { stipple } from "../canvas-core/stipple";+import { mountFilm } from "./page";++mountFilm(stipple);diff --git a/engine/src/hosts/page-storybookDraw.ts b/engine/src/hosts/page-storybookDraw.tsnew file mode 100644index 0000000..7eafde2--- /dev/null+++ b/engine/src/hosts/page-storybookDraw.ts@@ -0,0 +1,4 @@+import { storybookDraw } from "../canvas-core/storybookDraw";+import { mountFilm } from "./page";++mountFilm(storybookDraw);diff --git a/engine/src/hosts/page-sumiE.ts b/engine/src/hosts/page-sumiE.tsnew file mode 100644index 0000000..df3ef9b--- /dev/null+++ b/engine/src/hosts/page-sumiE.ts@@ -0,0 +1,4 @@+import { sumiE } from "../canvas-core/sumiE";+import { mountFilm } from "./page";++mountFilm(sumiE);diff --git a/engine/src/hosts/page-toyBrick.ts b/engine/src/hosts/page-toyBrick.tsnew file mode 100644index 0000000..1ea1187--- /dev/null+++ b/engine/src/hosts/page-toyBrick.ts@@ -0,0 +1,4 @@+import { toyBrick } from "../canvas-core/toyBrick";+import { mountFilm } from "./page";++mountFilm(toyBrick);diff --git a/engine/src/hosts/page-woodcut.ts b/engine/src/hosts/page-woodcut.tsnew file mode 100644index 0000000..9766791--- /dev/null+++ b/engine/src/hosts/page-woodcut.ts@@ -0,0 +1,4 @@+import { woodcut } from "../canvas-core/woodcut";+import { mountFilm } from "./page";++mountFilm(woodcut);diff --git a/engine/src/hosts/page-wrenDraw.ts b/engine/src/hosts/page-wrenDraw.tsnew file mode 100644index 0000000..fbf531a--- /dev/null+++ b/engine/src/hosts/page-wrenDraw.ts@@ -0,0 +1,4 @@+import { wrenDraw } from "../canvas-core/wrenDraw";+import { mountFilm } from "./page";++mountFilm(wrenDraw);diff --git a/engine/src/hosts/page.ts b/engine/src/hosts/page.tsindex 85ee84a..f2924cf 100644--- a/engine/src/hosts/page.ts+++ b/engine/src/hosts/page.ts@@ -22,9 +22,9 @@ export const mountFilm = (film: Film) => {const seek = (frame: number) => { const t0 = performance.now(); const shot = renderFrame(film, ctx, frame, env); ctx.getImageData(0, 0, 1, 1); current = frame; return { shot, ms: performance.now() - t0 }; }; // getImageData forces the deferred raster so the timing is realconst hash = () => { const d = ctx.getImageData(0, 0, canvas.width, canvas.height).data; let h = 0x811c9dc5; for (let i = 0; i < d.length; i++) { h ^= d[i]; h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(16); };const b64 = (u8: Uint8Array) => { let s = ""; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode(...u8.subarray(i, i + 0x8000)); return btoa(s); };- const audio = (sr: number) => { if (!film.audio) return null; const [L, R] = film.audio(sr), pcm = new Int16Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = Math.max(-1, Math.min(1, L[i])) * 32767; pcm[i * 2 + 1] = Math.max(-1, Math.min(1, R[i])) * 32767; } return { sampleRate: sr, frames: L.length, pcm16: b64(new Uint8Array(pcm.buffer)) }; };+ const audio = (sr: number) => { if (!film.audio) return null; const [L, R] = film.audio(sr); if (L.length !== R.length) throw new Error("audio channels have different lengths"); const pcm = new Float32Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; } return { sampleRate: sr, frames: L.length, float32: b64(new Uint8Array(pcm.buffer)) }; };const warm = () => film.shots.forEach((s) => { seek(s.start); seek(s.start + ((s.end - s.start) >> 1)); }); // first + middle frame of every shot: builds tiles, pre-allocates the layer pool- window.FILM = { meta: film.meta, ready, mount, seek, hash, audio, warm, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };+ window.FILM = { meta: { ...film.meta, shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };// ---- the player: click or space to play, arrows to step, ?frame=N to open on a frameready.then(() => {diff --git a/engine/styles.gen.json b/engine/styles.gen.jsonnew file mode 100644index 0000000..b811370--- /dev/null+++ b/engine/styles.gen.json@@ -0,0 +1,374 @@+[+ {+ "id": "balloon",+ "name": "Crayon",+ "family": "dry media",+ "medium": "wax crayon on toothed paper: back-and-forth scribble fills that skip the valleys, a darker crayon on the shade side, a white one burnishing the highlight, a fat contour gone over twice",+ "nearest": "moonPhases",+ "hero": "a hot-air balloon",+ "module": "engine/src/canvas-core/balloon.ts",+ "drawFilm": "balloonDraw",+ "samples": "anidoodle-research/samples/balloon/",+ "source": "legacy"+ },+ {+ "id": "blueprint",+ "name": "Cyanotype blueprint",+ "family": "technical drawing",+ "medium": "ruling pen and spring-bow compass in white ink on Prussian-blue cyanotype stock",+ "nearest": "pocketWatch",+ "hero": "a watch movement's going train, plan and section A-A",+ "module": "engine/src/canvas-core/blueprint.ts",+ "drawFilm": "blueprint",+ "samples": "anidoodle-research/samples/blueprint/",+ "source": "scanned"+ },+ {+ "id": "brokenColour",+ "name": "Broken colour",+ "family": "oil",+ "medium": "opaque oil dabs from a loaded flat hog brush on primed linen, unmixed colours side by side for the eye to mix",+ "nearest": "ranunculus",+ "hero": "a small harbour at sunrise",+ "module": "engine/src/canvas-core/brokenColour.ts",+ "drawFilm": "brokenColour",+ "samples": "anidoodle-research/samples/brokenColour/",+ "source": "scanned"+ },+ {+ "id": "charcoalErasure",+ "name": "Charcoal, erased and redrawn",+ "family": "dry media",+ "medium": "vine and compressed charcoal on heavy rag paper, stumped, lifted with a kneaded eraser, redrawn over its own residue",+ "nearest": "pocketWatch",+ "hero": "one oak through four seasons on one sheet",+ "module": "engine/src/canvas-core/charcoalErasure.ts",+ "drawFilm": "charcoalErasure",+ "samples": "anidoodle-research/samples/charcoalErasure/",+ "source": "scanned"+ },+ {+ "id": "colouredPencil",+ "name": "Coloured pencil",+ "family": "dry media",+ "medium": "wax coloured pencils hatched in one diagonal on toothy cream cartridge paper, hues layered, darks cross-hatched",+ "nearest": "balloon (crayon)",+ "hero": "a wind-up tin robot mending a music box while a crow steals a screw",+ "module": "engine/src/canvas-core/colouredPencil.ts",+ "drawFilm": "colouredPencil",+ "samples": "anidoodle-research/samples/colouredPencil/",+ "source": "scanned"+ },+ {+ "id": "embroidery",+ "name": "Hand embroidery",+ "family": "textile",+ "medium": "stranded cotton floss stitched through natural plain-weave linen in a beech hoop",+ "nearest": "fox",+ "hero": "a botanical wreath with a honeybee",+ "module": "engine/src/canvas-core/embroidery.ts",+ "drawFilm": "embroidery",+ "samples": "anidoodle-research/samples/embroidery/",+ "source": "scanned"+ },+ {+ "id": "flatVector",+ "name": "Flat vector",+ "family": "modern flat illustration",+ "medium": "pen-tool paths in a vector app, flat fills that land when a path closes, long-shadow shapes with a transparency ramp, a raster grain brush over the shade sides",+ "nearest": "fox",+ "hero": "a regatta of small sailboats on a bay under hills, the leader rounding the mark",+ "module": "engine/src/canvas-core/flatVector.ts",+ "drawFilm": "flatVector",+ "samples": "anidoodle-research/samples/flatVector/",+ "source": "scanned"+ },+ {+ "id": "folkTale",+ "name": "Folk-tale storybook",+ "family": "paint",+ "medium": "gouache and watercolour over an HB pencil drawing on cream cartridge: opaque, dry-brushed paint in the foreground thinning to a pale wash and then to bare pencil in the distance",+ "nearest": "storybook",+ "hero": "a boy carrying a rooster through a village kitchen garden at the edge of a birch wood",+ "module": "engine/src/canvas-core/folkTale.ts",+ "drawFilm": "folkTale",+ "samples": "anidoodle-research/samples/folkTale/",+ "source": "scanned"+ },+ {+ "id": "fox",+ "name": "Cut-paper collage",+ "family": "collage",+ "medium": "zero drawn lines: torn pieces with a white fibrous edge, scissor pieces crisp, each lifting a soft shadow off the piece below",+ "nearest": "lighthouse",+ "hero": "a fox at dusk",+ "module": "engine/src/canvas-core/fox.ts",+ "drawFilm": "foxDraw",+ "samples": "anidoodle-research/samples/fox/",+ "source": "legacy"+ },+ {+ "id": "halftone",+ "name": "Newsprint halftone",+ "family": "print",+ "medium": "web-offset newspaper print: black on a 45 degree AM screen plus one orange spot at 15 degrees, oil ink gaining into unbleached groundwood newsprint",+ "nearest": "lighthouse",+ "hero": "a steam train crossing a stone viaduct at golden hour",+ "module": "engine/src/canvas-core/halftone.ts",+ "drawFilm": "halftone",+ "samples": "anidoodle-research/samples/halftone/",+ "source": "scanned"+ },+ {+ "id": "isometric",+ "name": "Isometric cutaway",+ "family": "digital",+ "medium": "flat vector planes on a true 2:1 isometric grid, three tones per material, crisp edges, pen-tool order",+ "nearest": "koi",+ "hero": "a two-floor bakery cutaway at night, lit by its oven, the baker turning with a fresh loaf",+ "module": "engine/src/canvas-core/isometric.ts",+ "drawFilm": "isometric",+ "samples": "anidoodle-research/samples/isometric/",+ "source": "scanned"+ },+ {+ "id": "koi",+ "name": "Marker comic",+ "family": "marker comic",+ "medium": "alcohol-marker cel fills with a hard shadow edge under one heavy contour that thickens away from the light",+ "nearest": "lighthouse",+ "hero": "a Sanke koi turning under lily pads",+ "module": "engine/src/canvas-core/koi.ts",+ "drawFilm": "koiDraw",+ "samples": "anidoodle-research/samples/koi/",+ "source": "legacy"+ },+ {+ "id": "lighthouse",+ "name": "Risograph",+ "family": "print",+ "medium": "soy ink, one layer per drum multiplied through its own registration offset; every other colour an overprint, tone a halftone screen per ink angle, white is bare paper",+ "nearest": "fox",+ "hero": "a lighthouse at sunset",+ "module": "engine/src/canvas-core/lighthouse.ts",+ "drawFilm": "lighthouseDraw",+ "samples": "anidoodle-research/samples/lighthouse/",+ "source": "legacy"+ },+ {+ "id": "lowPoly",+ "name": "Low-poly",+ "family": "3D in code",+ "medium": "triangle meshes projected by hand through a pinhole camera, each facet flat-shaded by its normal against one low sun, painter-sorted far to near; no 3D engine",+ "nearest": "none (the only geometry plate); closest in spirit riso's flat inks",+ "hero": "A mountain lake at dawn: pink-lit range, spruce shores, a red canoe, reflections",+ "module": "engine/src/canvas-core/lowPoly.ts",+ "drawFilm": "lowPoly",+ "samples": "anidoodle-research/samples/lowPoly/",+ "source": "scanned"+ },+ {+ "id": "mellan",+ "name": "Single-line engraving",+ "family": "engraving",+ "medium": "one unbroken engraved line whose width follows a procedural tone field: the whole picture is a single stroke",+ "nearest": "pocketWatch",+ "hero": "a moon spiralled out of one line",+ "module": "engine/src/canvas-core/mellan.ts",+ "drawFilm": "mellanUnspool",+ "samples": "anidoodle-research/samples/mellan/",+ "source": "legacy"+ },+ {+ "id": "midCentury",+ "name": "Mid-century gouache",+ "family": "1950s-60s storybook",+ "medium": "opaque matte designer's gouache on warm illustration board, a dry brush dragged over the flats, a loose brush-and-ink line printed off register",+ "nearest": "fox",+ "hero": "a hillside village where a girl flies a kite",+ "module": "engine/src/canvas-core/midCentury.ts",+ "drawFilm": "midCentury",+ "samples": "anidoodle-research/samples/midCentury/",+ "source": "scanned"+ },+ {+ "id": "moonPhases",+ "name": "Chalkboard",+ "family": "chalk",+ "medium": "side-of-the-chalk scumble on a slate board, lit limbs worked twice, every stroke broken by the board's tooth with dust either side, ghosts of old lessons",+ "nearest": "balloon",+ "hero": "the phases of the moon",+ "module": "engine/src/canvas-core/moonPhases.ts",+ "drawFilm": "moonPhasesDraw",+ "samples": "anidoodle-research/samples/moonPhases/",+ "source": "legacy"+ },+ {+ "id": "paintedOil",+ "name": "Oil on canvas",+ "family": "paint",+ "medium": "opaque oil paint with hog-bristle brushes on a toned linen canvas, lean block-in to fat impasto",+ "nearest": "ranunculus",+ "hero": "two pears and a copper pot by a window",+ "module": "engine/src/canvas-core/paintedOil.ts",+ "drawFilm": "paintedOil",+ "samples": "anidoodle-research/samples/paintedOil/",+ "source": "scanned"+ },+ {+ "id": "paperCraft",+ "name": "Toy-theatre paper collage",+ "family": "collage",+ "medium": "a cardboard toy theatre: patterned and sugar papers cut and torn, gouache-painted cut-outs with a white sticker margin, every piece with a card edge and a gap to the flat behind",+ "nearest": "fox",+ "hero": "A seaside town on a toy-theatre stage: sea rows, harbour houses, a newspaper boat, a sun on a stick",+ "module": "engine/src/canvas-core/paperCraft.ts",+ "drawFilm": "paperCraft",+ "samples": "anidoodle-research/samples/paperCraft/",+ "source": "scanned"+ },+ {+ "id": "pixelArt",+ "name": "Pixel art",+ "family": "digital",+ "medium": "a 120x120 grid of cells, each one of 16 declared palette colours, laid one cell at a time and blown up by a whole number, no smoothing",+ "nearest": "koi",+ "hero": "a cat mid-pounce after fireflies in a moonlit garden",+ "module": "engine/src/canvas-core/pixelArt.ts",+ "drawFilm": "pixelArt",+ "samples": "anidoodle-research/samples/pixelArt/",+ "source": "scanned"+ },+ {+ "id": "pocketWatch",+ "name": "Ballpoint sketch",+ "family": "pen & ink",+ "medium": "one blue ballpoint on cream cartridge, near-constant weight; tone only from where the hatching sits, plus the blob where a firm stroke stops",+ "nearest": "wren",+ "hero": "a pocket watch lying on a table",+ "module": "engine/src/canvas-core/pocketWatch.ts",+ "drawFilm": "pocketWatchDraw",+ "samples": "anidoodle-research/samples/pocketWatch/",+ "source": "legacy"+ },+ {+ "id": "ranunculus",+ "name": "Pencil & watercolour",+ "family": "watercolour",+ "medium": "graphite and pan watercolour on cold-press: washes that never quite fill their outline, form shaded toward one light, graphite over the paint",+ "nearest": "storybook",+ "hero": "a ranunculus in bloom",+ "module": "engine/src/canvas-core/ranunculus.ts",+ "drawFilm": "ranunculusDraw",+ "samples": "anidoodle-research/samples/ranunculus/",+ "source": "legacy"+ },+ {+ "id": "rubberHose",+ "name": "Rubber hose",+ "family": "1930s cartoon",+ "medium": "India ink at one pressure on a clear cel over a blue-pencil rough, flat grey paint on the back, photographed and printed on black-and-white film",+ "nearest": "koi",+ "hero": "a coffee pot mid-dance-step on a kitchen counter, steam curling",+ "module": "engine/src/canvas-core/rubberHose.ts",+ "drawFilm": "rubberHose",+ "samples": "anidoodle-research/samples/rubberHose/",+ "source": "scanned"+ },+ {+ "id": "scrapbook",+ "name": "Archival scrapbook",+ "family": "collage + print",+ "medium": "foxed rag-paper album page; torn cards, cellulose tape, a clothespin on twine; copperplate engravings hand-tinted; typewriter, ransom-note cut letters, red pen, rubber stamp",+ "nearest": "fox",+ "hero": "How a honeybee finds flowers: the forager, the rose, the waggle dance, the evidence",+ "module": "engine/src/canvas-core/scrapbook.ts",+ "drawFilm": "scrapbook",+ "samples": "anidoodle-research/samples/scrapbook/",+ "source": "scanned"+ },+ {+ "id": "scratchboard",+ "name": "Scratchboard",+ "family": "ink",+ "medium": "white china clay under black India ink; every mark is ink scraped away with a knife or scratch nib",+ "nearest": "mellan",+ "hero": "a lynx, head and shoulders, in moonlight",+ "module": "engine/src/canvas-core/scratchboard.ts",+ "drawFilm": "scratchboard",+ "samples": "anidoodle-research/samples/scratchboard/",+ "source": "scanned"+ },+ {+ "id": "stipple",+ "name": "Pen-and-ink stipple",+ "family": "ink",+ "medium": "one 0.25 mm technical pen dotted straight down onto hot-press bristol; tone is dot density only",+ "nearest": "mellan",+ "hero": "a nautilus shell sawn in half, chambers lit from the upper left, cast shadow in dots",+ "module": "engine/src/canvas-core/stipple.ts",+ "drawFilm": "stipple",+ "samples": "anidoodle-research/samples/stipple/",+ "source": "scanned"+ },+ {+ "id": "storybook",+ "name": "Storybook pencil + watercolour",+ "family": "watercolour",+ "medium": "storybook graphite and gentle pan watercolour, drawn for a recurring character",+ "nearest": "ranunculus",+ "hero": "Bit, waving, in storybook pencil and watercolour",+ "module": "engine/src/canvas-core/storybook.ts",+ "drawFilm": "storybookDraw",+ "samples": "anidoodle-research/samples/storybook/",+ "source": "legacy"+ },+ {+ "id": "sumiE",+ "name": "Sumi-e ink painting",+ "family": "ink",+ "medium": "one loaded soft brush of sumi ink, five dilutions, on unsized absorbent xuan paper, with a cinnabar seal",+ "nearest": "wren",+ "hero": "bamboo in wind with a tree sparrow",+ "module": "engine/src/canvas-core/sumiE.ts",+ "drawFilm": "sumiE",+ "samples": "anidoodle-research/samples/sumiE/",+ "source": "scanned"+ },+ {+ "id": "toyBrick",+ "name": "Toy brick",+ "family": "rendered",+ "medium": "moulded ABS toy bricks, rendered flat-plastic in orthographic view: face tones by the cube rule, bevel highlights, seam hairlines, real studs, a soft ground shadow",+ "nearest": "fox",+ "hero": "a brick-built harbour tugboat on a baseplate",+ "module": "engine/src/canvas-core/toyBrick.ts",+ "drawFilm": "toyBrick",+ "samples": "anidoodle-research/samples/toyBrick/",+ "source": "scanned"+ },+ {+ "id": "woodcut",+ "name": "Ukiyo-e colour woodblock",+ "family": "print",+ "medium": "water-based pigment printed by baren from hand-carved cherry blocks onto damp kozo washi: a sumi keyblock, flat colour blocks, bokashi wipes",+ "nearest": "lighthouse",+ "hero": "two grey herons in rain on a wooden drum bridge",+ "module": "engine/src/canvas-core/woodcut.ts",+ "drawFilm": "woodcut",+ "samples": "anidoodle-research/samples/woodcut/",+ "source": "scanned"+ },+ {+ "id": "wren",+ "name": "Ink & line-wash",+ "family": "ink",+ "medium": "wet washes first that flood past the line and settle along each shape's bottom edge, backruns, then a flexible nib thick on the press and hair-thin on the lift",+ "nearest": "ranunculus",+ "hero": "a wren",+ "module": "engine/src/canvas-core/wren.ts",+ "drawFilm": "wrenDraw",+ "samples": "anidoodle-research/samples/wren/",+ "source": "legacy"+ }+]diff --git a/engine/styles.legacy.json b/engine/styles.legacy.jsonnew file mode 100644index 0000000..5dfd8d6--- /dev/null+++ b/engine/styles.legacy.json@@ -0,0 +1,96 @@+{+ "note": "Style records for the hands that predate `export const STYLE`. When a module grows its own STYLE export the scanned record wins on an id collision, and once every entry here has one, this file can go.",+ "styles": [+ {+ "id": "ranunculus",+ "name": "Pencil & watercolour",+ "family": "watercolour",+ "medium": "graphite and pan watercolour on cold-press: washes that never quite fill their outline, form shaded toward one light, graphite over the paint",+ "nearest": "storybook",+ "hero": "a ranunculus in bloom"+ },+ {+ "id": "koi",+ "name": "Marker comic",+ "family": "marker comic",+ "medium": "alcohol-marker cel fills with a hard shadow edge under one heavy contour that thickens away from the light",+ "nearest": "lighthouse",+ "hero": "a Sanke koi turning under lily pads"+ },+ {+ "id": "pocketWatch",+ "name": "Ballpoint sketch",+ "family": "pen & ink",+ "medium": "one blue ballpoint on cream cartridge, near-constant weight; tone only from where the hatching sits, plus the blob where a firm stroke stops",+ "nearest": "wren",+ "hero": "a pocket watch lying on a table"+ },+ {+ "id": "balloon",+ "name": "Crayon",+ "family": "dry media",+ "medium": "wax crayon on toothed paper: back-and-forth scribble fills that skip the valleys, a darker crayon on the shade side, a white one burnishing the highlight, a fat contour gone over twice",+ "nearest": "moonPhases",+ "hero": "a hot-air balloon"+ },+ {+ "id": "wren",+ "name": "Ink & line-wash",+ "family": "ink",+ "medium": "wet washes first that flood past the line and settle along each shape's bottom edge, backruns, then a flexible nib thick on the press and hair-thin on the lift",+ "nearest": "ranunculus",+ "hero": "a wren"+ },+ {+ "id": "moonPhases",+ "name": "Chalkboard",+ "family": "chalk",+ "medium": "side-of-the-chalk scumble on a slate board, lit limbs worked twice, every stroke broken by the board's tooth with dust either side, ghosts of old lessons",+ "nearest": "balloon",+ "hero": "the phases of the moon"+ },+ {+ "id": "fox",+ "name": "Cut-paper collage",+ "family": "collage",+ "medium": "zero drawn lines: torn pieces with a white fibrous edge, scissor pieces crisp, each lifting a soft shadow off the piece below",+ "nearest": "lighthouse",+ "hero": "a fox at dusk"+ },+ {+ "id": "lighthouse",+ "name": "Risograph",+ "family": "print",+ "medium": "soy ink, one layer per drum multiplied through its own registration offset; every other colour an overprint, tone a halftone screen per ink angle, white is bare paper",+ "nearest": "fox",+ "hero": "a lighthouse at sunset"+ },+ {+ "id": "mellan",+ "name": "Single-line engraving",+ "family": "engraving",+ "medium": "one unbroken engraved line whose width follows a procedural tone field: the whole picture is a single stroke",+ "nearest": "pocketWatch",+ "hero": "a moon spiralled out of one line",+ "film": "mellanUnspool"+ },+ {+ "id": "storybook",+ "name": "Storybook pencil + watercolour",+ "family": "watercolour",+ "medium": "storybook graphite and gentle pan watercolour, drawn for a recurring character",+ "nearest": "ranunculus",+ "hero": "Bit, waving, in storybook pencil and watercolour"+ },+ {+ "id": "blueprint",+ "name": "Cyanotype blueprint",+ "family": "technical drawing",+ "medium": "ruling pen in white ink on Prussian-blue cyanotype stock: draftTooth and blueMottle tiles, inkGroup halos, inclined gothic lettering",+ "nearest": "pocketWatch",+ "hero": "the clockwork butterfly, the blueprint act of the worked film",+ "module": "example/src/canvas-core/mechanicalLepidoptera.ts",+ "film": null+ }+ ]+}diff --git a/engine/test/fixtures/ctx-filter.mjs b/engine/test/fixtures/ctx-filter.mjsnew file mode 100644index 0000000..ec731ba--- /dev/null+++ b/engine/test/fixtures/ctx-filter.mjs@@ -0,0 +1 @@+export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: (frame) => { const ctx = {}; ctx.filter = "blur(1px)"; return frame; } };diff --git a/engine/test/fixtures/dead-loop.mjs b/engine/test/fixtures/dead-loop.mjsnew file mode 100644index 0000000..798895e--- /dev/null+++ b/engine/test/fixtures/dead-loop.mjs@@ -0,0 +1 @@+export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: () => "same" };diff --git a/engine/test/fixtures/declared-hold.mjs b/engine/test/fixtures/declared-hold.mjsnew file mode 100644index 0000000..8e34913--- /dev/null+++ b/engine/test/fixtures/declared-hold.mjs@@ -0,0 +1 @@+export default { expected: "PASS", meta: { fps: 4, durationFrames: 8, holds: [[6, 8]] }, render: (frame) => Math.min(frame, 5) };diff --git a/engine/test/fixtures/math-random.mjs b/engine/test/fixtures/math-random.mjsnew file mode 100644index 0000000..199700d--- /dev/null+++ b/engine/test/fixtures/math-random.mjs@@ -0,0 +1 @@+export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: (frame) => `${frame}-${Math.random()}` };diff --git a/engine/test/fixtures/on-twos.mjs b/engine/test/fixtures/on-twos.mjsnew file mode 100644index 0000000..ceab668--- /dev/null+++ b/engine/test/fixtures/on-twos.mjs@@ -0,0 +1 @@+export default { expected: "PASS", meta: { fps: 4, durationFrames: 8, onTwos: true }, render: (frame) => Math.floor(frame / 2) };diff --git a/engine/test/fixtures/order-cache.mjs b/engine/test/fixtures/order-cache.mjsnew file mode 100644index 0000000..105aacf--- /dev/null+++ b/engine/test/fixtures/order-cache.mjs@@ -0,0 +1 @@+export default { expected: "FAIL", meta: { fps: 4, durationFrames: 8 }, render: (frame, cache) => { if (!cache.has("first")) cache.set("first", frame); return `${frame}:${cache.get("first")}`; } };diff --git a/engine/tools/adapters/README.md b/engine/tools/adapters/README.mdindex 502bebb..c09ca46 100644--- a/engine/tools/adapters/README.md+++ b/engine/tools/adapters/README.md@@ -21,7 +21,7 @@ the same. A session is:info(), // -> film.metaframe(n, w), // -> { png: Buffer, shot, drawMs }hash(n, w), // -> stable hex digest of the drawn pixels- audio(sampleRate), // -> { sampleRate, frames, pcm16 } | null+ audio(sampleRate), // -> { sampleRate, frames, float32 } | null (interleaved stereo)artifact(), // -> { path, kind, bytes, checks: [{ok,label,detail}] } | nullclose() }```diff --git a/engine/tools/adapters/remotion.mjs b/engine/tools/adapters/remotion.mjsindex 13b84ba..5779d5d 100644--- a/engine/tools/adapters/remotion.mjs+++ b/engine/tools/adapters/remotion.mjs@@ -39,11 +39,12 @@ const loadFilm = async (film) => {return (await import("data:text/javascript;base64," + Buffer.from(out).toString("base64"))).film;};-const pcm16 = (film, sr) => {+const float32 = (film, sr) => {if (!film.audio) return null;- const [L, R] = film.audio(sr), pcm = new Int16Array(L.length * 2);- for (let i = 0; i < L.length; i++) { pcm[i * 2] = Math.max(-1, Math.min(1, L[i])) * 32767; pcm[i * 2 + 1] = Math.max(-1, Math.min(1, R[i])) * 32767; }- return { sampleRate: sr, frames: L.length, pcm16: Buffer.from(pcm.buffer).toString("base64") };+ const [L, R] = film.audio(sr), pcm = new Float32Array(L.length * 2);+ if (L.length !== R.length) throw new Error("audio channels have different lengths");+ for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; }+ return { sampleRate: sr, frames: L.length, float32: Buffer.from(pcm.buffer).toString("base64") };};// Bundling is per FILM, not per session: the gate opens an adapter many times in one process and@@ -104,12 +105,12 @@ export const open = async (film, opts = {}) => {return {workers: browsers.length,- info: () => data.meta,+ info: () => ({ ...data.meta, shots: data.shots.map(({ id, start, end }) => ({ id, start, end })) }),frame: async (n, w = 0) => { const r = await still(n, w); return { png: r.png, shot: (data.shots.find((s) => n >= s.start && n < s.end) ?? {}).id ?? null, drawMs: r.drawMs }; },// Hashed through the PNG the renderer wrote: that file IS what this backend produces, so// hashing anything else would be grading something the backend does not actually deliver.hash: async (n, w = 0) => createHash("sha256").update((await still(n, w)).png).digest("hex").slice(0, 16),- audio: async (sr) => pcm16(data, sr),+ audio: async (sr) => float32(data, sr),artifact: () => null, /* like playwright: a means to an MP4, not a deliverable of its own */close: async () => { for (const b of browsers) await b.close({ silent: true }); },};diff --git a/engine/tools/analyze-style.mjs b/engine/tools/analyze-style.mjsnew file mode 100644index 0000000..9938c00--- /dev/null+++ b/engine/tools/analyze-style.mjs@@ -0,0 +1,276 @@+// ANALYZE A STYLE. Read a reference image the user brought and print what its HAND is doing:+// palette, value, line, fill texture, stroke length, speckle, halftone, edges, then the nearest+// existing plates with reasons.+//+// node tools/analyze-style.mjs <image> [--json out/profile.json] [--max 1400] [--signatures tools/style-signatures.json]+// node tools/analyze-style.mjs --calibrate <plate-still.png>... --out tools/style-signatures.json+//+// READ THIS BEFORE TRUSTING A NUMBER. Every statistic here measures the PICTURE, and a picture is+// subject + composition + lighting + medium all at once. A reference that is mostly empty paper+// reads "light key, few edges" whatever hand drew it; text reads as "line". These are+// DIAGNOSTICS that tell you where to look, never a verdict. The verdict is the medium recipe you+// write in words and a side-by-side of a DIFFERENT subject drawn in that hand+// (references/workflows/adapt-a-style.md). Nothing here can certify "not a copy" either: that is+// the no-copy rule, kept by construction (new subject, new composition), not by a threshold.+//+// Tools read the reference; the art core never does. Decoding goes through ffmpeg (raw RGBA),+// so any still ffmpeg reads works: png, jpg, webp, a frame of an mp4 (--frame N).+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const HERE = dirname(fileURLToPath(import.meta.url));+const VAL = new Set(["json", "max", "signatures", "out", "frame", "exclude", "crop"]);+const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+const die = (m) => { console.error(`analyze-style: ${m}`); process.exit(1); };+if (!pos.length) die("usage: node tools/analyze-style.mjs <image> [--json out.json] | --calibrate <stills...> --out tools/style-signatures.json");++// ---------------------------------------------------------------- decode+const decode = (file) => {+ if (!existsSync(file)) die(`no such file: ${file}`);+ const probe = execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]).toString().trim().split("\n")[0].split(",").map(Number);+ let [w, h] = probe; if (!w || !h) die(`ffprobe could not size ${file}`);+ if (opt.crop) { const c = opt.crop.split(",").map(Number); w = c[2]; h = c[3]; }+ const vf = [opt.frame ? `select=eq(n\\,${Number(opt.frame)})` : "", opt.crop ? `crop=${opt.crop.split(",").slice(2, 4).join(":")}:${opt.crop.split(",").slice(0, 2).join(":")}` : ""].filter(Boolean), pre = vf.length ? ["-vf", vf.join(",")] : [];+ const raw = execFileSync("ffmpeg", ["-v", "error", "-i", file, ...pre, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgba", "-"], { maxBuffer: 1 << 30 });+ if (raw.length < w * h * 4) die(`decoded ${raw.length} bytes, expected ${w * h * 4}`);+ return { w, h, rgba: raw, sha256: createHash("sha256").update(readFileSync(file)).digest("hex") };+};++// ---------------------------------------------------------------- colour science (OKLab, Ottosson 2020)+const lin = (c) => { c /= 255; return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };+const LIN = Float32Array.from({ length: 256 }, (_, i) => lin(i));+const toLab = (r, g, b) => {+ const R = LIN[r], G = LIN[g], B = LIN[b];+ const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B), m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B), s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];+};+const toRgb = (L, a, b) => {+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3, m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3, s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;+ const R = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, G = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, B = -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s;+ const e = (c) => Math.round(255 * Math.max(0, Math.min(1, c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055)));+ return [e(R), e(G), e(B)];+};+const hex = ([r, g, b]) => "#" + [r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("");+const rng = (seed) => { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };++// ---------------------------------------------------------------- image plumbing+const toPlanes = ({ w, h, rgba }) => { // composite alpha over white, then OKLab planes+ const n = w * h, L = new Float32Array(n), A = new Float32Array(n), B = new Float32Array(n);+ for (let i = 0; i < n; i++) { const al = rgba[i * 4 + 3] / 255, f = (c) => Math.round(c * al + 255 * (1 - al)); const [l, a, b] = toLab(f(rgba[i * 4]), f(rgba[i * 4 + 1]), f(rgba[i * 4 + 2])); L[i] = l; A[i] = a; B[i] = b; }+ return { w, h, L, A, B };+};+const shrink = (P, max) => { // area-average down so the long side is <= max+ const k = Math.max(1, Math.ceil(Math.max(P.w, P.h) / max)); if (k === 1) return { ...P, k: 1 };+ const w = Math.floor(P.w / k), h = Math.floor(P.h / k), out = { w, h, k, L: new Float32Array(w * h), A: new Float32Array(w * h), B: new Float32Array(w * h) };+ for (const ch of ["L", "A", "B"]) { const s = P[ch], d = out[ch]; for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let t = 0; for (let j = 0; j < k; j++) for (let i = 0; i < k; i++) t += s[(y * k + j) * P.w + x * k + i]; d[y * w + x] = t / (k * k); } }+ return out;+};+const boxBlur = (src, w, h, r, passes = 3) => { // three box passes ~ a gaussian, separable, edge-clamped+ let a = Float32Array.from(src), b = new Float32Array(src.length);+ for (let p = 0; p < passes; p++) {+ for (let y = 0; y < h; y++) { let s = 0; for (let i = -r; i <= r; i++) s += a[y * w + Math.min(w - 1, Math.max(0, i))]; for (let x = 0; x < w; x++) { b[y * w + x] = s / (2 * r + 1); s += a[y * w + Math.min(w - 1, x + r + 1)] - a[y * w + Math.max(0, x - r)]; } }+ for (let x = 0; x < w; x++) { let s = 0; for (let i = -r; i <= r; i++) s += b[Math.min(h - 1, Math.max(0, i)) * w + x]; for (let y = 0; y < h; y++) { a[y * w + x] = s / (2 * r + 1); s += b[Math.min(h - 1, y + r + 1) * w + x] - b[Math.max(0, y - r) * w + x]; } }+ }+ return a;+};+const bilin = (F, w, h, x, y) => { x = Math.max(0, Math.min(w - 1.001, x)); y = Math.max(0, Math.min(h - 1.001, y)); const x0 = x | 0, y0 = y | 0, fx = x - x0, fy = y - y0, i = y0 * w + x0; return F[i] * (1 - fx) * (1 - fy) + F[i + 1] * fx * (1 - fy) + F[i + w] * (1 - fx) * fy + F[i + w + 1] * fx * fy; };+const pct = (arr, q) => { const s = Float32Array.from(arr).sort(); return s.length ? s[Math.min(s.length - 1, Math.floor(q * s.length))] : NaN; };+const median = (arr) => pct(arr, 0.5);+const r2 = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d;+// image-convention angle: 0 = horizontal, +45 = rising to the right (y is down in pixels)+const angOf = (dx, dy) => { let a = (-Math.atan2(dy, dx) * 180) / Math.PI; while (a <= -90) a += 180; while (a > 90) a -= 180; return a; };++// ---------------------------------------------------------------- 1. palette: k-means in OKLab+const palette = (P, keep, K = 8) => {+ const n = P.w * P.h, step = Math.max(1, Math.floor(n / 60000)), S = [];+ for (let i = 0; i < n; i += step) if (keep[i]) S.push([P.L[i], P.A[i], P.B[i]]);+ const r = rng(7), d2 = (p, c) => (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2 + (p[2] - c[2]) ** 2;+ const C = [S[Math.floor(r() * S.length)].slice()]; // k-means+++ while (C.length < K) { const D = S.map((p) => Math.min(...C.map((c) => d2(p, c)))), tot = D.reduce((a, b) => a + b, 0); let t = r() * tot, i = 0; while (i < D.length - 1 && (t -= D[i]) > 0) i++; C.push(S[i].slice()); }+ const lab = new Int32Array(S.length);+ for (let it = 0; it < 25; it++) {+ const sum = C.map(() => [0, 0, 0, 0]);+ S.forEach((p, i) => { let best = 0, bd = 1e9; C.forEach((c, k) => { const d = d2(p, c); if (d < bd) { bd = d; best = k; } }); lab[i] = best; const s = sum[best]; s[0] += p[0]; s[1] += p[1]; s[2] += p[2]; s[3]++; });+ sum.forEach((s, k) => { if (s[3]) C[k] = [s[0] / s[3], s[1] / s[3], s[2] / s[3]]; });+ }+ let cl = C.map((c, k) => ({ lab: c, share: 0, k })); lab.forEach((k) => cl[k].share++); cl.forEach((c) => (c.share /= S.length));+ // merge near-duplicates (dE_ok < 0.035): k is an upper bound, not a claim about the palette+ cl.sort((a, b) => b.share - a.share); const out = [];+ for (const c of cl) { const m = out.find((o) => Math.sqrt(d2(o.lab, c.lab)) < 0.035); if (m) { const t = m.share + c.share; m.lab = m.lab.map((v, i) => (v * m.share + c.lab[i] * c.share) / t); m.share = t; } else out.push({ ...c }); }+ return out.filter((c) => c.share > 0.002).map((c) => { const [L, a, b] = c.lab, C2 = Math.hypot(a, b); return { hex: hex(toRgb(L, a, b)), L: r2(L), C: r2(C2, 3), hue: Math.round(((Math.atan2(b, a) * 180) / Math.PI + 360) % 360), share: r2(c.share, 3) }; }).sort((a, b) => b.share - a.share);+};++// ---------------------------------------------------------------- 2..8: the measurements+const analyze = (file) => {+ const img = decode(file), full = toPlanes(img), P = shrink(full, Number(opt.max ?? 1400)), { w, h } = P, n = w * h, short = Math.min(w, h);+ // --exclude "x,y,w,h;x,y,w,h" (reference px, after --crop): UI, captions, a photo pasted in: things that are not the hand+ const rects = (opt.exclude ? String(opt.exclude).split(";") : []).map((r) => r.split(",").map(Number)).filter((r) => r.length === 4);+ const keep = new Uint8Array(n).fill(1); for (const [rx, ry, rw, rh] of rects) for (let y = Math.max(0, Math.floor(ry / P.k)); y < Math.min(h, Math.ceil((ry + rh) / P.k)); y++) for (let x = Math.max(0, Math.floor(rx / P.k)); x < Math.min(w, Math.ceil((rx + rw) / P.k)); x++) keep[y * w + x] = 0;+ const kept = []; for (let i = 0; i < n; i++) if (keep[i]) kept.push(i); const nk = kept.length || 1;+ const clear = boxBlur(Float32Array.from(keep), w, h, 6, 1); // a margin round every excluded box: its border is not the hand either+ const ok = (i) => clear[i] > 0.999;+ const L = P.L, Lk = Float32Array.from(kept, (i) => L[i]);+ const pal = palette(P, keep);+ // paper: the biggest field if it dominates, else the biggest LIGHT field; ink: the darkest colour that is really used+ const light = pal.filter((c) => c.L > 0.72), paper = pal[0].share > 0.3 ? pal[0] : (light.sort((a, b) => b.share - a.share)[0] ?? pal[0]);+ const inks = pal.filter((c) => c !== paper && c.share > 0.004).sort((a, b) => a.L - b.L), ink = inks[0] ?? pal[pal.length - 1];+ let chromaSum = 0, chromaN = 0; for (const i of kept) { const c = Math.hypot(P.A[i], P.B[i]); if (Math.abs(P.L[i] - paper.L) > 0.04 || Math.abs(c - paper.C) > 0.02) { chromaSum += c; chromaN++; } }++ // value+ const hist = [0, 0, 0, 0, 0]; for (const v of Lk) hist[Math.min(4, Math.floor(v * 5))]++;+ const meanL = Lk.reduce((a, b) => a + b, 0) / nk, p03 = pct(Lk, 0.03), p97 = pct(Lk, 0.97);+ const value = { key: meanL > 0.75 ? "high" : meanL > 0.5 ? "middle" : "low", meanL: r2(meanL), contrast: r2(p97 - p03), p03: r2(p03), p97: r2(p97), bands: hist.map((v) => r2(v / nk)), bandsNote: "share of pixels in L 0-.2, .2-.4, .4-.6, .6-.8, .8-1" };++ // gradients on a lightly smoothed L+ const Ls = boxBlur(L, w, h, 1, 1), gx = new Float32Array(n), gy = new Float32Array(n), gm = new Float32Array(n);+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) { const i = y * w + x; gx[i] = (Ls[i + 1] - Ls[i - 1]) / 2; gy[i] = (Ls[i + w] - Ls[i - w]) / 2; gm[i] = Math.hypot(gx[i], gy[i]); }++ // edges: transition width = contrast across the edge / gradient at the edge (a step is ~2 px wide at pixel scale)+ const edgeMask = new Uint8Array(n); let hard = 0, soft = 0, lost = 0, rim = 0, rimN = 0;+ for (let y = 9; y < h - 9; y++) for (let x = 9; x < w - 9; x++) {+ const i = y * w + x, g = gm[i]; if (g < 0.012 || !ok(i)) continue;+ const nx = gx[i] / g, ny = gy[i] / g; if (g < bilin(gm, w, h, x + nx, y + ny) || g < bilin(gm, w, h, x - nx, y - ny)) continue; // thin to the ridge+ const hi = bilin(Ls, w, h, x + nx * 8, y + ny * 8), lo = bilin(Ls, w, h, x - nx * 8, y - ny * 8), dL = hi - lo; if (dL < 0.05) continue;+ edgeMask[i] = 1; const width = dL / g;+ if (width < 2.6) hard++; else if (width < 7) soft++; else lost++;+ // pooled rim: on the dark side, is the band right at the edge darker than the body further in?+ if (dL > 0.07) { rimN++; if (bilin(Ls, w, h, x - nx * 10, y - ny * 10) - bilin(Ls, w, h, x - nx * 3, y - ny * 3) > 0.012) rim++; }+ }+ const eN = hard + soft + lost || 1;+ const near = boxBlur(Float32Array.from(edgeMask), w, h, 3, 1); // "near an edge" = inside 3 px of one+ const edges = { density: r2(eN / nk, 4), hard: r2(hard / eN), soft: r2(soft / eN), lost: r2(lost / eN), pooledRim: rimN > 30 ? r2(rim / rimN) : null, note: "hard < 2.6 px transition, soft 2.6-7, lost > 7 (at analysis size); pooledRim = share of strong edges whose dark side is darkest AT the edge (watercolour pigment settling)" };++ // line: thin marks darker than their surroundings, width from the shorter run through each line pixel+ const bg = boxBlur(L, w, h, Math.max(4, Math.round(short / 60))), lineMask = new Uint8Array(n);+ for (let i = 0; i < n; i++) if (bg[i] - L[i] > 0.09) lineMask[i] = 1;+ const runH = new Uint16Array(n), runV = new Uint16Array(n);+ for (let y = 0; y < h; y++) { let x = 0; while (x < w) { if (!lineMask[y * w + x]) { x++; continue; } let e = x; while (e < w && lineMask[y * w + e]) e++; for (let k = x; k < e; k++) runH[y * w + k] = e - x; x = e; } }+ for (let x = 0; x < w; x++) { let y = 0; while (y < h) { if (!lineMask[y * w + x]) { y++; continue; } let e = y; while (e < h && lineMask[e * w + x]) e++; for (let k = y; k < e; k++) runV[k * w + x] = e - y; y = e; } }+ const widths = []; let thin = 0; const thinMax = Math.max(3, short * 0.012);+ for (let i = 0; i < n; i++) if (lineMask[i] && ok(i)) { const wd = Math.min(runH[i], runV[i]); if (wd <= thinMax) { thin++; if (i % 3 === 0) widths.push(wd); } }+ const line = { presence: r2(thin / nk, 4), widthMedianPx: widths.length ? r2(median(widths) * P.k, 1) : null, widthP90Px: widths.length ? r2(pct(widths, 0.9) * P.k, 1) : null, widthVariation: widths.length ? r2((pct(widths, 0.9) - pct(widths, 0.1)) / Math.max(1, median(widths))) : null, note: "presence = share of pixels in thin dark marks; lettering counts as line; widths in reference pixels" };++ // fill texture: structure tensor of the fine grain, AWAY from edges+ const hp = new Float32Array(n); { const b2 = boxBlur(L, w, h, 2); for (let i = 0; i < n; i++) hp[i] = L[i] - b2[i]; }+ // the tensor is built on the GRAIN (L minus its blur), not on L: a smooth wash gradient is perfectly+ // "coherent" and says nothing about which way the pencil or brush moved+ const Jxx = new Float32Array(n), Jxy = new Float32Array(n), Jyy = new Float32Array(n);+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) { const i = y * w + x, hx = (hp[i + 1] - hp[i - 1]) / 2, hy = (hp[i + w] - hp[i - w]) / 2; Jxx[i] = hx * hx; Jxy[i] = hx * hy; Jyy[i] = hy * hy; }+ const tw = Math.max(4, Math.round(short / 120)), bxx = boxBlur(Jxx, w, h, tw), bxy = boxBlur(Jxy, w, h, tw), byy = boxBlur(Jyy, w, h, tw);+ const bins = new Float64Array(36); let cohSum = 0, cohW = 0, cohHigh = 0, cohN = 0; const interior = new Uint8Array(n);+ for (let y = 6; y < h - 6; y += 2) for (let x = 6; x < w - 6; x += 2) {+ const i = y * w + x; if (near[i] > 0.02 || lineMask[i] || !ok(i)) continue; const tr = bxx[i] + byy[i]; if (tr < 4e-7) continue; // below that there is no grain to have a direction+ interior[i] = 1; const coh = Math.sqrt((bxx[i] - byy[i]) ** 2 + 4 * bxy[i] ** 2) / tr, th = 0.5 * Math.atan2(2 * bxy[i], bxx[i] - byy[i]); // gradient direction; strokes run across it+ const sa = angOf(-Math.sin(th), Math.cos(th)), b = Math.min(35, Math.floor((sa + 90) / 5)), wt = coh * Math.sqrt(tr);+ bins[b] += wt; cohSum += coh * Math.sqrt(tr); cohW += Math.sqrt(tr); cohN++; if (coh > 0.5) cohHigh++;+ }+ let pk = 0; bins.forEach((v, i) => { if (v > bins[pk]) pk = i; }); const tot = bins.reduce((a, b) => a + b, 0) || 1; let near15 = 0; for (let d = -3; d <= 3; d++) near15 += bins[(pk + d + 36) % 36];+ const dom = pk * 5 - 90 + 2.5, u = [Math.cos((dom * Math.PI) / 180), -Math.sin((dom * Math.PI) / 180)];+ // stroke length: autocorrelation of the grain along the dominant direction versus across it+ const pts = []; for (let i = 0; i < n; i += 7) if (interior[i]) pts.push(i);+ let v0 = 0; pts.forEach((i) => (v0 += hp[i] * hp[i])); v0 = v0 / (pts.length || 1) || 1e-9;+ const corr = (dx, dy) => { let s = 0, c = 0; for (const i of pts) { const x = i % w, y = (i / w) | 0; if (x + dx < 0 || x + dx >= w - 1 || y + dy < 0 || y + dy >= h - 1) continue; s += hp[i] * bilin(hp, w, h, x + dx, y + dy); c++; } return s / (c || 1) / v0; };+ const reach = (vx, vy) => { for (let d = 1; d <= 60; d++) if (corr(vx * d, vy * d) < 0.3) return d; return 60; };+ const along = reach(u[0], u[1]), across = reach(-u[1], u[0]);+ let fine = 0, lightSpeck = 0, darkSpeck = 0; pts.forEach((i) => { fine += hp[i] * hp[i]; if (hp[i] > 0.035) lightSpeck++; if (hp[i] < -0.035) darkSpeck++; });+ const grain = Math.sqrt(fine / (pts.length || 1)) >= 0.006; // below this the "direction" is quantisation noise+ const texture = { sampled: pts.length, grain, dominantStrokeAngle: grain ? r2(dom, 0) : null, peakShare: grain ? r2(near15 / tot) : null, coherence: grain && cohW ? r2(cohSum / cohW) : null, coherentShare: cohN ? r2(cohHigh / cohN) : null, strokeLengthPx: r2(along * P.k, 0), grainWidthPx: r2(across * P.k, 0), elongation: r2(along / across, 1), grainRms: r2(Math.sqrt(fine / (pts.length || 1)), 3), speckleLight: r2(lightSpeck / (pts.length || 1), 3), speckleDark: r2(darkSpeck / (pts.length || 1), 3),+ note: "measured on interior pixels only (no edges, no lines). dominantStrokeAngle 0 = horizontal, +45 = rising right; peakShare = weight within +-15 deg of it (1/12 = no preference); speckleLight = paper showing through the colour (tooth)" };++ // spectrum at FULL resolution: power-law slope + a halftone lattice if there is one+ const spectrum = fftStats(full, rects);+ return { file: basename(file), sha256: img.sha256, size: [img.w, img.h], analysedAt: [w, h], palette: pal, paper: { hex: paper.hex, L: paper.L, share: paper.share }, ink: { hex: ink.hex, L: ink.L, share: ink.share }, chroma: r2(chromaN ? chromaSum / chromaN : 0, 3), colours: pal.filter((c) => c.share > 0.02).length, value, line, texture, edges, spectrum };+};++// ---------------------------------------------------------------- FFT: slope and halftone lattice+const fft1 = (re, im, N) => { // in place, radix 2+ for (let i = 1, j = 0; i < N; i++) { let bit = N >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } }+ for (let len = 2; len <= N; len <<= 1) { const a = (-2 * Math.PI) / len, wr = Math.cos(a), wi = Math.sin(a); for (let i = 0; i < N; i += len) { let cr = 1, ci = 0; for (let k = 0; k < len / 2; k++) { const ur = re[i + k], ui = im[i + k], vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci, vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr; re[i + k] = ur + vr; im[i + k] = ui + vi; re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; } } }+};+const fftStats = (F, rects = []) => {+ for (const N of [256, 128]) { const r = fftAt(F, rects, N); if (r) return r; }+ return { powerSlope: null, halftone: null, note: "no crop of 128 px clear of exclusions: spectrum skipped" };+};+const fftAt = (F, rects, N) => {+ if (F.w < N || F.h < N) return null;+ // pick the four busiest 256 crops (most variance): halftone lives in the inked parts, not the margins+ const cands = []; for (let y = 0; y + N <= F.h; y += N / 2) for (let x = 0; x + N <= F.w; x += N / 2) { if (rects.some(([rx, ry, rw, rh]) => x < rx + rw && x + N > rx && y < ry + rh && y + N > ry)) continue; let s = 0, s2 = 0, c = 0; for (let j = 0; j < N; j += 4) for (let i = 0; i < N; i += 4) { const v = F.L[(y + j) * F.w + x + i]; s += v; s2 += v * v; c++; } const m = s / c; cands.push({ x, y, v: s2 / c - m * m }); }+ if (!cands.length) return null;+ cands.sort((a, b) => b.v - a.v); const crops = cands.slice(0, 4), pow = new Float64Array(N * N);+ const han = Float32Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (N - 1)));+ for (const c of crops) {+ const re = new Float64Array(N * N), im = new Float64Array(N * N); let m = 0; for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) m += F.L[(c.y + j) * F.w + c.x + i]; m /= N * N;+ for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) re[j * N + i] = (F.L[(c.y + j) * F.w + c.x + i] - m) * han[i] * han[j];+ const rr = new Float64Array(N), ii = new Float64Array(N);+ for (let j = 0; j < N; j++) { for (let i = 0; i < N; i++) { rr[i] = re[j * N + i]; ii[i] = im[j * N + i]; } fft1(rr, ii, N); for (let i = 0; i < N; i++) { re[j * N + i] = rr[i]; im[j * N + i] = ii[i]; } }+ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { rr[j] = re[j * N + i]; ii[j] = im[j * N + i]; } fft1(rr, ii, N); for (let j = 0; j < N; j++) pow[j * N + i] += rr[j] * rr[j] + ii[j] * ii[j]; }+ }+ const at = (u, v) => pow[((v + N) % N) * N + ((u + N) % N)];+ const ring = new Float64Array(N / 2), cnt = new Float64Array(N / 2);+ for (let v = -N / 2; v < N / 2; v++) for (let u = -N / 2; u < N / 2; u++) { const r = Math.round(Math.hypot(u, v)); if (r > 0 && r < N / 2) { ring[r] += at(u, v); cnt[r]++; } }+ // slope of log power against log frequency, 4..100 cycles: ~-2 natural/soft, flatter = grainy/noisy, steeper = smooth washes+ let sx = 0, sy = 0, sxx = 0, sxy = 0, k = 0; for (let r = Math.round(N / 64); r <= Math.round(N * 0.39); r++) { const x = Math.log(r), y = Math.log(ring[r] / cnt[r] + 1e-12); sx += x; sy += y; sxx += x * x; sxy += x * y; k++; }+ const slope = (k * sxy - sx * sy) / (k * sxx - sx * sx);+ // halftone: a lattice is isolated peaks far above their own ring, at two angles 90 (or 60) degrees apart+ const peaks = [];+ for (let v = -N / 2 + 1; v < N / 2 - 1; v++) for (let u = 1; u < N / 2 - 1; u++) {+ const r = Math.hypot(u, v); if (r < N * 0.047 || r > N * 0.46) continue; const p = at(u, v), base = ring[Math.round(r)] / cnt[Math.round(r)];+ if (p < base * 25) continue; let isMax = true; for (let dv = -1; dv <= 1 && isMax; dv++) for (let du = -1; du <= 1; du++) if ((du || dv) && at(u + du, v + dv) > p) { isMax = false; break; }+ if (isMax && Math.abs(u) > 1 && Math.abs(v) > 1) peaks.push({ u, v, r, ratio: p / base }); // skip the axes: window leakage and ruled lines live there+ }+ peaks.sort((a, b) => b.ratio - a.ratio);+ let lattice = null;+ if (peaks.length >= 2) { const a = peaks[0], b = peaks.slice(1).find((q) => Math.abs(q.r - a.r) / a.r < 0.12 && Math.abs(((Math.atan2(q.v, q.u) - Math.atan2(a.v, a.u)) * 180) / Math.PI) % 180 > 50); if (b) lattice = { pitchPx: r2(N / a.r, 1), angles: [angOf(a.u, a.v), angOf(b.u, b.v)].map((x) => r2(x, 0)), strength: r2(Math.min(a.ratio, b.ratio), 0) }; }+ return { powerSlope: r2(slope), halftone: lattice, note: "powerSlope ~ -3 smooth washes, ~ -2 natural texture, flatter than -1.6 grainy/speckled; halftone = FFT lattice (pitch in reference px), null when none" };+};++// ---------------------------------------------------------------- nearest plates+// The features the matcher compares, with the spread over which a difference stops mattering.+const FEATS = { linePresence: 0.05, hard: 0.3, pooledRim: 0.35, coherence: 0.25, peakShare: 0.2, speckleLight: 0.12, chroma: 0.06, paperL: 0.25, contrast: 0.35, colours: 4, halftone: 0.6 };+const featuresOf = (p) => ({ linePresence: p.line.presence, hard: p.edges.hard, pooledRim: p.edges.pooledRim, coherence: p.texture.coherence, peakShare: p.texture.peakShare, speckleLight: p.texture.speckleLight, chroma: p.chroma, paperL: p.paper.L, contrast: p.value.contrast, colours: p.colours, halftone: p.spectrum.halftone ? 1 : 0 });+const NAME = { linePresence: "thin-line share", hard: "hard-edge share", pooledRim: "pooled-rim share", coherence: "stroke coherence", peakShare: "one-direction share", speckleLight: "paper-through-colour", chroma: "chroma", paperL: "ground lightness", contrast: "value contrast", colours: "colours", halftone: "periodic lattice" };+const nearest = (p, sigs) => {+ const f = featuresOf(p);+ return Object.entries(sigs).map(([id, s]) => {+ // a feature the reference has no reading for (no grain, too few edges) is left out, not scored as zero+ const diffs = Object.entries(FEATS).filter(([k]) => f[k] != null && s.features[k] != null).map(([k, spread]) => ({ k, d: Math.abs(f[k] - s.features[k]) / spread, ref: f[k], plate: s.features[k] }));+ const dist = Math.sqrt(diffs.reduce((a, x) => a + Math.min(3, x.d) ** 2, 0) / diffs.length);+ const fmt = (v) => (v == null ? "-" : Number.isInteger(v) ? String(v) : String(r2(v, 3)));+ const shares = diffs.filter((x) => x.d < 0.35).sort((a, b) => a.d - b.d).slice(0, 3).map((x) => `${NAME[x.k]} ${fmt(x.ref)} ~ ${fmt(x.plate)}`);+ const differs = diffs.filter((x) => x.d > 1).sort((a, b) => b.d - a.d).slice(0, 3).map((x) => `${NAME[x.k]} ${fmt(x.ref)} here vs ${fmt(x.plate)}`);+ return { id, module: s.module, dist: r2(dist), medium: s.medium, shares, differs };+ }).sort((a, b) => a.dist - b.dist);+};++// ---------------------------------------------------------------- CLI+if (opt.calibrate) {+ // Build plate signatures from the plates' OWN rendered stills: measured, not guessed.+ const MEDIUM = JSON.parse(readFileSync(resolve(HERE, "style-media.json"), "utf8"));+ const out = {}; for (const f of pos) { const id = basename(f).replace(/(-plate)?(-still)?\.png$/, "").replace(/Draw$/, ""); const p = analyze(resolve(f)); out[id] = { module: `engine/src/canvas-core/${MEDIUM[id]?.module ?? id + ".ts"}`, medium: MEDIUM[id]?.medium ?? "", source: basename(f), sha256: p.sha256, features: featuresOf(p) }; console.log(`${id.padEnd(16)} ${JSON.stringify(out[id].features)}`); }+ const dest = resolve(opt.out ?? resolve(HERE, "style-signatures.json")); writeFileSync(dest, JSON.stringify({ note: "features measured by analyze-style.mjs --calibrate on each plate's own rendered still; subject and composition are baked into these numbers, so treat the match as a hint", plates: out }, null, 1)); console.log(`-> ${dest}`);+ process.exit(0);+}++const p = analyze(resolve(pos[0]));+const sigFile = resolve(opt.signatures ?? resolve(HERE, "style-signatures.json"));+const sigs = existsSync(sigFile) ? JSON.parse(readFileSync(sigFile, "utf8")).plates : {};+p.nearest = nearest(p, sigs).slice(0, 4);++const line = (k, v) => console.log(` ${k.padEnd(14)} ${v}`);+console.log(`STYLE PROFILE ${p.file} ${p.size.join("x")} (analysed at ${p.analysedAt.join("x")}) sha256 ${p.sha256.slice(0, 16)}`);+console.log(`\npalette (OKLab k-means, area share):`);+p.palette.forEach((c) => console.log(` ${c.hex} L ${c.L.toFixed(2)} C ${c.C.toFixed(3)} h ${String(c.hue).padStart(3)} ${(c.share * 100).toFixed(1).padStart(5)}%${c.hex === p.paper.hex ? " <- paper" : c.hex === p.ink.hex ? " <- darkest ink" : ""}`));+line("chroma", `${p.chroma} mean OKLab chroma off the paper; ${p.colours} colours above 2%`);+console.log(`\nvalue:`); line("key", `${p.value.key} (mean L ${p.value.meanL}), contrast ${p.value.contrast} (L ${p.value.p03}..${p.value.p97})`); line("bands", p.value.bands.join(" ") + " (dark .. light)");+console.log(`\nline:`); line("presence", `${(p.line.presence * 100).toFixed(2)}% of pixels in thin dark marks`); line("width", p.line.widthMedianPx == null ? "no line found" : `median ${p.line.widthMedianPx} px, p90 ${p.line.widthP90Px} px, variation ${p.line.widthVariation}`);+console.log(`\nfill texture (interior only, ${p.texture.sampled} samples):`); line("direction", p.texture.grain ? `${p.texture.dominantStrokeAngle} deg, ${(p.texture.peakShare * 100).toFixed(0)}% of the weight within 15 deg of it (8% = none)` : "no measurable grain: the fills are smooth (washes, flat colour or a soft/upscaled image)"); line("coherence", `${p.texture.coherence} mean, ${p.texture.coherentShare} of samples above 0.5`); line("stroke", `~${p.texture.strokeLengthPx} px long x ${p.texture.grainWidthPx} px across (elongation ${p.texture.elongation})`); line("speckle", `light ${p.texture.speckleLight}, dark ${p.texture.speckleDark}, grain rms ${p.texture.grainRms}`);+console.log(`\nedges:`); line("hardness", `hard ${p.edges.hard} soft ${p.edges.soft} lost ${p.edges.lost} (density ${p.edges.density})`); line("pooled rim", p.edges.pooledRim == null ? "too few strong edges" : `${p.edges.pooledRim} of strong edges darkest at the edge`);+console.log(`\nspectrum:`); line("slope", p.spectrum.powerSlope ?? p.spectrum.note); line("lattice", p.spectrum.halftone ? `periodic lattice (a halftone screen, or regular ruling/cross-hatch): pitch ${p.spectrum.halftone.pitchPx} px at ${p.spectrum.halftone.angles.join(" / ")} deg (peak ${p.spectrum.halftone.strength}x its ring)` : "none");+console.log(`\nnearest plates (a HINT: subject and layout are in these numbers too; see adapt-a-style.md):`);+if (!p.nearest.length) console.log(" no signatures: node tools/analyze-style.mjs --calibrate <plate stills...>");+p.nearest.forEach((m, i) => { console.log(` ${i + 1}. ${m.id.padEnd(15)} dist ${m.dist} ${m.medium}`); if (m.shares.length) console.log(` shares: ${m.shares.join("; ")}`); if (m.differs.length) console.log(` differs: ${m.differs.join("; ")}`); });+if (opt.json) { const dest = resolve(opt.json); mkdirSync(dirname(dest), { recursive: true }); writeFileSync(dest, JSON.stringify(p, null, 1)); console.log(`\n-> ${dest}`); }diff --git a/engine/tools/audio.mjs b/engine/tools/audio.mjsnew file mode 100644index 0000000..b6890db--- /dev/null+++ b/engine/tools/audio.mjs@@ -0,0 +1,12 @@+// Interleaved stereo Float32 transport stays unclipped until the final AAC encoder.+export const float32Wav = ({ sampleRate, frames, float32 }) => {+ const pcm = Buffer.from(float32, "base64");+ if (!Number.isSafeInteger(sampleRate) || sampleRate < 1 || pcm.length !== frames * 8) throw new Error("invalid stereo Float32 audio payload");+ const h = Buffer.alloc(44);+ h.write("RIFF", 0); h.writeUInt32LE(36 + pcm.length, 4); h.write("WAVEfmt ", 8);+ h.writeUInt32LE(16, 16); h.writeUInt16LE(3, 20); h.writeUInt16LE(2, 22);+ h.writeUInt32LE(sampleRate, 24); h.writeUInt32LE(sampleRate * 8, 28);+ h.writeUInt16LE(8, 32); h.writeUInt16LE(32, 34);+ h.write("data", 36); h.writeUInt32LE(pcm.length, 40);+ return Buffer.concat([h, pcm]);+};diff --git a/engine/tools/character-check.entry.ts b/engine/tools/character-check.entry.tsnew file mode 100644index 0000000..972e2dc--- /dev/null+++ b/engine/tools/character-check.entry.ts@@ -0,0 +1,90 @@+// Bundled and run by tools/character-check.mjs. Holds Mira and Theo to their invariants, then+// runs the NEGATIVE twins: a gate that has never been seen to fail proves nothing.+import { camera } from "../src/canvas-core/character/math3";+import type { Pose, Scene } from "../src/canvas-core/character/types";+import { CANON } from "../src/canvas-core/character/human/canon";+import { SIDES, limitViolations } from "../src/canvas-core/character/human/skeleton";+import { rigFor, checkPose } from "../src/canvas-core/character/human/figure";+import { canonChecks, featureChecks, handChecks, paletteChecks, poseChecks, risoColour, type Result } from "../src/canvas-core/character/check";+import { mira, MIRA_SPEC, MIRA_FEATURES, MIRA_ROLES } from "../src/canvas-core/characters/mira";+import { MIRA_MARKER, MIRA_RISO, MIRA_STORYBOOK } from "../src/canvas-core/characters/mira/palettes";+import * as MP from "../src/canvas-core/characters/mira/poses";+import { theo, THEO_SPEC } from "../src/canvas-core/characters/theo";+import * as TP from "../src/canvas-core/characters/theo/poses";+import { DRUM } from "../src/canvas-core/character/render/riso";+import { miraAt } from "../src/canvas-core/miraWalk";+import { apply } from "../src/canvas-core/character/math3";+import { HANDS } from "../src/canvas-core/miraTile";+import { handIdentity } from "../src/canvas-core/miraEveryHand";++export const run = () => {+ const out: { section: string; results: Result[] }[] = [], sec = (section: string, results: Result[]) => out.push({ section, results });+ // ---- proportions+ sec("MIRA canon (storybook child, declared stylisation of a 6.2-head nine-year-old)", canonChecks(CANON.storybookChild, MIRA_SPEC.height, 6.2));+ sec("THEO canon (adult, 7.5 heads)", canonChecks(CANON.adult, THEO_SPEC.height));+ // ---- poses: limits, bones, balance, floor+ const crateTop = (yaw: number) => [[-0.17, 0.3, -0.15], [0.17, 0.3, -0.15], [0.17, 0.3, 0.11], [-0.17, 0.3, 0.11]].map((v) => { const a = (yaw * Math.PI) / 180; return [v[0] * Math.cos(a) + v[2] * Math.sin(a), v[1], -v[0] * Math.sin(a) + v[2] * Math.cos(a)] as [number, number, number]; });+ const stoolTop = (yaw: number) => [[-0.15, 0.5, -0.18], [0.15, 0.5, -0.18], [0.15, 0.5, 0.12], [-0.15, 0.5, 0.12]].map((v) => { const a = (yaw * Math.PI) / 180; return [v[0] * Math.cos(a) + v[2] * Math.sin(a), v[1], -v[0] * Math.sin(a) + v[2] * Math.cos(a)] as [number, number, number]; });+ const plantM = (p: Pose) => rigFor(MIRA_SPEC, p), plantT = (p: Pose) => rigFor(THEO_SPEC, p);+ sec("MIRA poses", poseChecks("mira", CANON.storybookChild, MIRA_SPEC.height, [+ ["relaxed", MP.relaxed(0)], ["weightOnOneLeg", MP.strapStand(-25)], ["walkContact", MP.walkContact(70), { dynamic: true }], ["tiptoeReach", MP.reachUp(30)],+ ["sitOnCrate", MP.sitCrate(-40), { seated: crateTop(-40) }], ["crouch", MP.crouch(35)], ["wave", MP.wave(-15, 0.8)], ["gearToEye", MP.gearToEye(-50), { seated: crateTop(-50) }],+ ], plantM));+ sec("THEO poses", poseChecks("theo", CANON.adult, THEO_SPEC.height, [+ ["relaxed", TP.relaxed(0)], ["contrapposto", TP.contra(-30)], ["reachUp", TP.reachUp(-35)], ["sitOnStool", TP.sit(-40), { seated: stoolTop(-40) }], ["holdCup", TP.holdCup()], ["pointAtLens", TP.pointAtCamera([0.05, 1.46, 0.95])],+ ], plantT));+ // ---- hands+ sec("HANDS", [...handChecks("mira", plantM(MP.relaxed(0)), MP.MIRA_DIMS.hand), ...handChecks("theo", plantT(TP.relaxed(0)), TP.THEO_DIMS.hand)]);+ // ---- identity across views+ const cam = camera([0, 0.8, 8], [0, 0.65, 0], 3000, 500, 500), views: [number, Scene][] = [0, 20, 40, 60, 90, 120, 150, 180, -40, -90].map((y) => [y, mira.toScene(MP.relaxed(y), cam)]);+ sec("MIRA identity per view", featureChecks("mira", MIRA_FEATURES, views));+ // the same pose rendered in every hand is the SAME scene geometry: the hands only change marks+ const s1 = JSON.stringify(mira.toScene(MP.wave(-15, 0.8), cam).parts.map((p) => [p.id, p.polys])), s2 = JSON.stringify(mira.toScene(MP.wave(-15, 0.8), cam).parts.map((p) => [p.id, p.polys]));+ sec("MIRA determinism", [{ id: "mira.scene.deterministic", ok: s1 === s2, detail: `scene geometry for one pose, built twice: ${s1 === s2 ? "identical" : "DIFFERENT"} (${s1.length} chars)` }]);+ // ---- palette roles, per hand+ const drum = Object.fromEntries(Object.entries(DRUM).map(([k, v]) => [k, v.col]));+ const risoMap = Object.fromEntries(Object.entries(MIRA_RISO).map(([k, v]) => [k, risoColour(v.inks, drum)]));+ sec("MIRA palette roles in three hands", paletteChecks("mira", MIRA_ROLES, { storybook: Object.fromEntries(Object.entries(MIRA_STORYBOOK).map(([k, v]) => [k, v.base])), marker: Object.fromEntries(Object.entries(MIRA_MARKER).map(([k, v]) => [k, v.base])), riso: risoMap }));+ // ---- the walk+ const walk: Result[] = []; let bad = 0, maxSlide = 0, at = -1, below = 0; let prev: Record<string, [number, number, number]> | null = null;+ for (let f = 0; f < 240; f++) {+ const p = miraAt(f); bad += limitViolations(p.joints).length ? 1 : 0;+ const r = rigFor(MIRA_SPEC, p), d = r.dims, pts: Record<string, [number, number, number]> = {};+ SIDES.forEach((s) => { pts[s + "h"] = apply(r.foot[s], [0, -d.ankleH, -d.heel * 0.9]); pts[s + "b"] = apply(r.toes[s], [0, -d.ankleH * 0.15, 0]); });+ Object.values(pts).forEach((q) => { if (q[1] < -0.004) below++; });+ if (prev) for (const k of Object.keys(pts)) { const a = prev[k], b = pts[k]; if (a[1] < 0.004 && b[1] < 0.004) { const sl = Math.hypot(a[0] - b[0], a[2] - b[2]); if (sl > maxSlide) { maxSlide = sl; at = f; } } }+ prev = pts;+ }+ walk.push({ id: "walk.limits", ok: bad === 0, detail: `${bad} of 240 frames outside the range of motion` });+ walk.push({ id: "walk.plantedFeetStay", ok: maxSlide < 0.004, detail: `a planted heel or ball moves at most ${(maxSlide * 1000).toFixed(1)} mm in a frame (frame ${at}); < 4 mm passes` });+ walk.push({ id: "walk.noFootThroughFloor", ok: below === 0, detail: `${below} foot-point samples more than 4 mm under the floor` });+ sec("MIRA film: the walk, all 240 frames", walk);+ // ---- Mira in every hand: per hand, the features that survived and the palette roles+ const every: Result[] = [];+ for (const h of HANDS) {+ const idn = handIdentity(h.id);+ idn.feats.forEach((f) => every.push({ id: `every.${h.id}.${f.feature}`, ok: f.ok, detail: f.got }));+ const bad = idn.pal.filter((p) => !p.ok);+ every.push({ id: `every.${h.id}.palette`, ok: bad.length === 0, detail: bad.length ? bad.map((b) => b.detail).join(" / ") : `${idn.pal.length} roles inside their hue families` });+ }+ sec("MIRA IN EVERY HAND (one pose, one camera, nine hands)", every);+ // ---- NEGATIVE twins: each must throw or fail+ const neg: Result[] = [];+ const expectThrow = (id: string, fn: () => void) => { try { fn(); neg.push({ id, ok: false, detail: "did NOT throw: the gate is blind here" }); } catch (e) { neg.push({ id, ok: true, detail: `threw as it must: ${String((e as Error).message).split("\n")[1]?.trim() ?? (e as Error).message}` }); } };+ expectThrow("neg.elbow170", () => mira.pose({ ...MP.relaxed(0), joints: { elbowR: 170 } }));+ expectThrow("neg.kneeBackwards", () => theo.pose({ ...TP.relaxed(0), joints: { kneeL: -15 } }));+ expectThrow("neg.wristCone", () => checkPose({ ...MP.relaxed(0), joints: { wristFlexL: 70, wristDevL: 30 } }));+ expectThrow("neg.straightLegKick", () => checkPose({ ...TP.relaxed(0), joints: { hipFlexR: 110, kneeR: 0 } }));+ expectThrow("neg.fingerBentBack", () => checkPose({ ...MP.relaxed(0), hands: { R: { angles: { thumb: [10, 10, 10, 10], index: [0, -45, 0, 0], middle: [0, 0, 0, 0], ring: [0, 0, 0, 0], little: [0, 0, 0, 0] } } } }));+ expectThrow("neg.neckOwl", () => checkPose({ ...MP.relaxed(0), joints: { neckTwist: 60, headTurn: 30 } }));+ // a stiff figure tipped 20 degrees forward from the ankles, planted: only the toes touch, the mass is far out in front+ const toppling: Pose = { ...TP.relaxed(0), pitch: 20, plant: true };+ const bb = poseChecks("neg", CANON.adult, THEO_SPEC.height, [["toppling", toppling]], (p) => rigFor(THEO_SPEC, p)).find((r) => r.id.endsWith("balance"))!;+ neg.push({ id: "neg.fallingOver", ok: !bb.ok, detail: `a stiff figure tipped 20 deg forward must fail balance: ${bb.ok ? "PASSED (gate blind)" : "failed as it must: " + bb.detail}` });+ const badPal = paletteChecks("neg", { coat: MIRA_ROLES.coat }, { wrong: { coat: "#3a7bd5" } })[0];+ neg.push({ id: "neg.coatTurnedBlue", ok: !badPal.ok, detail: `a blue coat must fail the yellow role: ${badPal.ok ? "PASSED (gate blind)" : "failed as it must"}` });+ const noGlasses = featureChecks("neg", MIRA_FEATURES, [[0, { ...views[0][1], parts: views[0][1].parts.filter((p) => p.id !== "glasses") }]])[0];+ neg.push({ id: "neg.glassesMissing", ok: !noGlasses.ok, detail: `a front view without the glasses must fail identity: ${noGlasses.ok ? "PASSED (gate blind)" : noGlasses.detail}` });+ sec("NEGATIVE TWINS (each must be caught)", neg);+ return out;+};diff --git a/engine/tools/character-check.mjs b/engine/tools/character-check.mjsnew file mode 100644index 0000000..7cdafc0--- /dev/null+++ b/engine/tools/character-check.mjs@@ -0,0 +1,19 @@+// CHARACTER GATE. node tools/character-check.mjs [--json out.json]+// Holds every character to its invariants (canon, joint limits, bone lengths, symmetry, hands,+// balance, identity per view, palette roles per hand, the walk's planted feet) and then runs the+// negative twins, which MUST fail. Exit code 1 on any failure. No browser needed: characters are+// pure geometry until a hand draws them.+import { build } from "esbuild";+import { writeFileSync } from "node:fs";++const js = (await build({ entryPoints: ["tools/character-check.entry.ts"], bundle: true, format: "esm", write: false, platform: "neutral" })).outputFiles[0].text;+const { run } = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));+const t0 = process.hrtime.bigint(), res = run(), ms = Number(process.hrtime.bigint() - t0) / 1e6;+let pass = 0, fail = 0;+for (const { section, results } of res) {+ console.log(`\n${section}\n${"-".repeat(Math.min(96, section.length))}`);+ for (const r of results) { r.ok ? pass++ : fail++; console.log(` ${r.ok ? "PASS" : "FAIL"} ${r.id.padEnd(34)} ${r.detail}`); }+}+console.log(`\n${pass} passed, ${fail} failed, in ${ms.toFixed(0)} ms`);+const i = process.argv.indexOf("--json"); if (i > 0) writeFileSync(process.argv[i + 1], JSON.stringify(res, null, 2));+process.exit(fail ? 1 : 0);diff --git a/engine/tools/choreo/form-mascot.mjs b/engine/tools/choreo/form-mascot.mjsnew file mode 100644index 0000000..53246e9--- /dev/null+++ b/engine/tools/choreo/form-mascot.mjs@@ -0,0 +1,14 @@+// ~14 s of someone signing up: name (he reads along), email, password (he covers his eyes), Show+// (caught peeking), submit with a short password (a worried head-shake), fix it, submit (busy, cheer).+export default async (r) => {+ await r.hold(8);+ await r.glide("#name", 20); await r.click(2); await r.type("Ada", 3); await r.hold(4);+ await r.glide("#email", 14); await r.click(2); await r.type("[email protected]", 2); await r.hold(4);+ await r.glide("#password", 14); await r.click(14); await r.type("pencil", 3); await r.hold(6);+ await r.glide(".reveal", 12); await r.click(30); await r.click(6);+ await r.glide(".submit", 16); await r.hold(4); await r.click(46);+ await r.glide("#password", 16); await r.click(2); await r.type("s!", 3); await r.hold(4);+ await r.glide(".submit", 16); await r.hold(2); await r.click(8); // "busy"+ await r.eval(() => new Promise((res) => setTimeout(res, 1200))); // the page's own 1.1 s setTimeout runs on real time+ await r.hold(82);+};diff --git a/engine/tools/choreo/mascot-hero.mjs b/engine/tools/choreo/mascot-hero.mjsnew file mode 100644index 0000000..5929e9a--- /dev/null+++ b/engine/tools/choreo/mascot-hero.mjs@@ -0,0 +1,13 @@+// ~13 s of a visitor on the landing hero: arrive, glance around, hover the tour, hover "Get started",+// click it (the cheer), poke Bit (the giggle), click the tour (the wave).+export default async (r) => {+ await r.hold(12);+ await r.glide({ x: 420, y: 330 }, 24); await r.hold(6);+ await r.glide({ x: 1180, y: 120 }, 22); await r.hold(6);+ await r.glide('[data-anidoodle="tour"]', 26); await r.hold(26);+ await r.glide('[data-anidoodle="start"]', 16); await r.hold(24);+ await r.click(72);+ const c = await r.box("ani-doodle canvas");+ await r.glide({ x: c.x + c.width * 0.49, y: c.y + c.height * 0.62 }, 24); await r.hold(4); await r.click(40);+ await r.glide('[data-anidoodle="tour"]', 22); await r.hold(4); await r.click(50);+};diff --git a/engine/tools/choreo/scroll-hero.mjs b/engine/tools/choreo/scroll-hero.mjsnew file mode 100644index 0000000..dbd9501--- /dev/null+++ b/engine/tools/choreo/scroll-hero.mjs@@ -0,0 +1,12 @@+// ~14 s of a reader: the intro, then down the whole track at a reading pace (pencil, paint, line), a+// little way back up to un-draw, and down to the finished plate.+export default async (r) => {+ const t = await r.eval(() => { const e = document.getElementById("track"); return { top: e.getBoundingClientRect().top + scrollY, h: e.offsetHeight, vh: innerHeight }; });+ const at = (f) => t.top + f * (t.h - t.vh);+ await r.glide({ x: 300, y: 520 }, 14); await r.hold(6);+ await r.scroll(at(0), 28); await r.hold(4);+ await r.scroll(at(0.12), 36); await r.scroll(at(0.4), 62);+ await r.scroll(at(0.66), 58); await r.scroll(at(0.92), 58);+ await r.scroll(at(0.55), 30); await r.hold(4);+ await r.scroll(at(1), 50); await r.hold(36);+};diff --git a/engine/tools/compare.mjs b/engine/tools/compare.mjsnew file mode 100644index 0000000..2428199--- /dev/null+++ b/engine/tools/compare.mjs@@ -0,0 +1,22 @@+// COMPARE. The reference and the new piece side by side, same height, labelled: the step of+// adapt-a-style.md where the agent LOOKS. (Tool output for review, not art: the labels use a+// system font through ffmpeg, which the art core never may.)+// node tools/compare.mjs <reference> <new.png> --out <side-by-side.png> [--left "label"] [--right "label"] [--height 800] [--exclude x,y,w,h]+// --exclude greys out a box of the reference (UI, captions) so the eye reads only the hand.+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync } from "node:fs";+import { dirname, resolve } from "node:path";++const VAL = new Set(["out", "left", "right", "height", "exclude"]);+const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+if (pos.length < 2 || !opt.out) { console.error("usage: node tools/compare.mjs <reference> <new.png> --out <file.png> [--left ..] [--right ..] [--height 800] [--exclude x,y,w,h]"); process.exit(1); }+const H = Number(opt.height ?? 800), hasText = / drawtext /.test(execFileSync("ffmpeg", ["-hide_banner", "-filters"]).toString()), font = hasText ? ["/System/Library/Fonts/Supplemental/Courier New Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"].find(existsSync) : undefined;+if (!font) console.warn("compare: this ffmpeg has no drawtext (or no font): panels are unlabelled, reference LEFT, new RIGHT");+const esc = (s) => s.replace(/\\/g, "\\\\").replace(/:/g, "\\:").replace(/'/g, "\u2019");+const label = (t) => (font && t ? `,drawtext=fontfile='${font}':text='${esc(t)}':x=24:y=34:fontsize=28:fontcolor=0x3a3434` : "");+const ex = opt.exclude ? `drawbox=${opt.exclude.split(",").join(":")}:[email protected]:t=fill,` : "";+const fc = `[0]${ex}scale=-2:${H}:flags=lanczos,pad=iw+40:ih+110:20:90:color=0xf3efe6${label(opt.left ?? "REFERENCE (the hand)")}[a];[1]scale=-2:${H}:flags=lanczos,pad=iw+40:ih+110:20:90:color=0xf3efe6${label(opt.right ?? "NEW SUBJECT, ADAPTED HAND")}[b];[a][b]hstack=inputs=2`;+mkdirSync(dirname(resolve(opt.out)), { recursive: true });+execFileSync("ffmpeg", ["-v", "error", "-y", "-i", resolve(pos[0]), "-i", resolve(pos[1]), "-filter_complex", fc, "-frames:v", "1", resolve(opt.out)]);+console.log(`-> ${resolve(opt.out)}`);diff --git a/engine/tools/deadair.mjs b/engine/tools/deadair.mjsindex b4538b3..ef3259c 100644--- a/engine/tools/deadair.mjs+++ b/engine/tools/deadair.mjs@@ -2,32 +2,27 @@// GATE G-AIR. Decodes the rendered MP4 and measures, per frame, the fraction of pixels that// changed since the previous frame. Two identical frames anywhere, or any window of `win`// frames whose changed area never reaches `min` percent, is dead air and fails.-import { execFileSync, spawnSync } from "node:child_process";+import { execFileSync } from "node:child_process";import { existsSync } from "node:fs";import { resolve } from "node:path";+import { changedArea } from "./motion.mjs";const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };const a0 = process.argv[2];-if (!a0) { console.error("usage: node tools/deadair.mjs <film|path.mp4> [--win 15] [--min 0.5] [--exempt 525:540]"); process.exit(2); }+if (!a0) { console.error("usage: node tools/deadair.mjs <film|path.mp4> [--win frames] [--min 0.5] [--exempt from:to]"); process.exit(2); }const file = resolve(a0.endsWith(".mp4") ? a0 : `out/${a0}.mp4`);if (!existsSync(file)) { console.error(`no such file: ${file}`); process.exit(2); }-const WIN = Number(arg("win", 15)), MIN = Number(arg("min", 0.5)) / 100, THRESH = Number(arg("thresh", 4)), SIZE = Number(arg("size", 270));+const stream = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate", "-of", "json", file])).streams[0];+const [fpsNum, fpsDen] = stream.avg_frame_rate.split("/").map(Number);+const WIN = Number(arg("win", Math.max(2, Math.round(fpsNum / fpsDen / 2)))), MIN = Number(arg("min", 0.5)) / 100, THRESH = Number(arg("thresh", 4)), SIZE = Number(arg("size", 270));const exempt = (arg("exempt", "") || "").split(",").filter(Boolean).map((s) => s.split(":").map(Number));// decode small: 135x135 grey is plenty to see whether anything moved, and it keeps this honest-const W = SIZE, H = SIZE, px = W * H;-const out = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `scale=${W}:${H}`, "-pix_fmt", "gray", "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 });-if (out.status) { console.error(out.stderr.toString()); process.exit(2); }-const buf = out.stdout, n = Math.floor(buf.length / px);+const W = SIZE, H = Math.max(2, Math.round(SIZE * stream.height / stream.width));+const changed = await changedArea(file, W, H, THRESH), n = changed.length;const probe = execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=nb_frames,duration", "-of", "csv=p=0", file]).toString().trim();console.log(`${file}\n ${n} frames decoded at ${W}x${H} grey, threshold ${THRESH}/255 (${probe})`);-const changed = [0];-for (let f = 1; f < n; f++) {- const a = buf.subarray((f - 1) * px, f * px), b = buf.subarray(f * px, (f + 1) * px);- let c = 0; for (let i = 0; i < px; i++) if (Math.abs(a[i] - b[i]) > THRESH) c++;- changed.push(c / px);-}const inExempt = (f) => exempt.some(([a, b]) => f >= a && f < b);const still = [], windows = [];for (let f = 1; f < n; f++) if (changed[f] === 0 && !inExempt(f)) still.push(f);diff --git a/engine/tools/docs-check.mjs b/engine/tools/docs-check.mjsnew file mode 100644index 0000000..73ecb51--- /dev/null+++ b/engine/tools/docs-check.mjs@@ -0,0 +1,80 @@+// DOCS-CHECK. Prose rots where code does not: a style gets added and the READMEs still say nine.+// This is the part of the build that notices. It holds SKILL.md to its own size limits, holds+// every style-count claim in SKILL.md and the six READMEs to the live registry count, and holds+// every references/ or engine/ path SKILL.md cites to the filesystem. The count is measured,+// never typed here.+// node tools/docs-check.mjs+import { existsSync, readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { loadRegistry, ROOT } from "./registry.mjs";++const registry = loadRegistry(), COUNT = registry.length;+let fails = 0;+const say = (ok, label, detail = "") => { if (!ok) fails++; console.log(` ${ok ? "PASS" : "FAIL"} ${label}${detail ? " " + detail : ""}`); };+console.log(`DOCS-CHECK ${ROOT}\n registry: ${COUNT} styles\n`);++// ---------------------------------------------------- 1. SKILL.md holds its own shape+const skillFile = join(ROOT, "SKILL.md"), skill = readFileSync(skillFile, "utf8");+const lines = skill.endsWith("\n") ? skill.split("\n").length - 1 : skill.split("\n").length;+say(lines <= 150, `SKILL.md is ${lines} lines`, "limit 150");+const desc = skill.match(/^---\n[\s\S]*?\n---/)?.[0].match(/^description:\s*(.+)$/m)?.[1].trim();+if (!desc) say(false, "SKILL.md frontmatter has a description");+else { const w = desc.split(/\s+/).length, t = Math.round(w * 1.3); say(t <= 50, `frontmatter description: ${w} words ≈ ${t} tokens`, "limit 50"); }++// ---------------------------------------------------- 2. every claimed style count is true+// A claim is a number sitting next to the word for style. Numbers are digits, or words in the+// file's own language — picked by the README's locale so Spanish "once" (eleven) can never be+// read in an English sentence. Indefinite articles (un, une, a) are not numbers here.+const STYLE_WORD = /(\bstyles?\b|\bestilos?\b|\bstile\b|スタイル|스타일|风格|樣式|样式)/gi;+const WORDS = {+ en: { two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12 },+ es: { dos: 2, tres: 3, cuatro: 4, cinco: 5, seis: 6, siete: 7, ocho: 8, nueve: 9, diez: 10, once: 11, doce: 12 },+ fr: { deux: 2, trois: 3, quatre: 4, cinq: 5, six: 6, sept: 7, huit: 8, neuf: 9, dix: 10, onze: 11, douze: 12 },+ ko: { 둘: 2, 셋: 3, 넷: 4, 다섯: 5, 여섯: 6, 일곱: 7, 여덟: 8, 아홉: 9, 열하나: 11, 열두: 12 },+ cjk: { 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9, 两: 2, 十一: 11, 十二: 12 },+};+const langOf = (f) => (f.match(/README\.([a-z]{2})-/i)?.[1] ?? "en").toLowerCase();+const lexicon = (f) => ({ ...WORDS.en, ...(WORDS[langOf(f)] ?? {}), ...(f.includes("-CN") || f.includes("-JP") ? WORDS.cjk : {}) });+const numRe = (lex) => {+ const lat = Object.keys(lex).filter((k) => /^[a-z]+$/i.test(k)), han = Object.keys(lex).filter((k) => /^[가-힣]+$/.test(k)), cjk = Object.keys(lex).filter((k) => !/^[a-z가-힣]+$/i.test(k));+ return new RegExp(`(\\d[\\d.,]*\\d|\\d)|(\\b(?:${lat.join("|")})\\b)${han.length ? `|((?<![가-힣])(?:${han.join("|")})(?![가-힣]))` : ""}${cjk.length ? `|(${cjk.join("|")})` : ""}`, "gi");+};+const numVal = (tok, lex) => /^\d/.test(tok) ? parseInt(tok.replace(/[.,]/g, ""), 10) : lex[tok.toLowerCase()];++const docs = ["SKILL.md", ...readdirSync(ROOT).filter((f) => /^README.*\.md$/.test(f)).sort()];+const WINDOW = 45;+let claims = 0;+for (const doc of docs) {+ const path = join(ROOT, doc), lex = lexicon(doc), NUM = numRe(lex);+ readFileSync(path, "utf8").split("\n").forEach((line, i) => {+ const spots = [...line.matchAll(STYLE_WORD)].map((m) => [m.index, m.index + m[0].length]);+ if (!spots.length) return;+ const seen = new Set();+ for (const m of line.matchAll(NUM)) {+ const v = numVal(m[0], lex);+ if (v == null || v < 2 || v > 99 || seen.has(v)) continue;+ if (/^\d/.test(m[0])) { const a = line[m.index + m[0].length]; if (a === "." || a === ")" || (line[m.index - 1] === "(" && a === ")")) continue; } // an ordinal or step marker (3., (3)), not a count+ const near = spots.some(([s0, s1]) => Math.max(0, s0 - (m.index + m[0].length), m.index - s1) <= WINDOW);+ if (!near) continue;+ seen.add(v); claims++;+ say(v === COUNT, `${doc}:${i + 1} claims ${v} styles`, `registry has ${COUNT}`);+ }+ });+}+if (!claims) say(false, "found any style-count claim at all", "the check would pass vacuously — that itself is a bug");++// ---------------------------------------------------- 3. every path SKILL.md cites exists+const PATH = /(?:references|engine)\/[A-Za-z0-9._~\/-]+/g;+let cited = 0;+skill.split("\n").forEach((line, i) => {+ for (const m of line.matchAll(PATH)) {+ const p = m[0].replace(/[.,/]+$/, "");+ cited++;+ say(existsSync(join(ROOT, p)), `SKILL.md:${i + 1} ${p}`);+ }+});+if (!cited) say(false, "found any references/ or engine/ path in SKILL.md");++console.log(`\n${fails ? `DOCS: FAIL ${fails} failure${fails === 1 ? "" : "s"}` : "DOCS: PASS"}`);+process.exit(fails ? 1 : 0);diff --git a/engine/tools/emit-interactive.mjs b/engine/tools/emit-interactive.mjsnew file mode 100644index 0000000..5d270b3--- /dev/null+++ b/engine/tools/emit-interactive.mjs@@ -0,0 +1,90 @@+// EMIT, INTERACTIVE. Ship an interactive piece as ONE ES module plus a page that uses it, and prove+// the page is self-contained and alive.+//+// node tools/emit-interactive.mjs <piece> [--page my-page.html] [--out out/<piece>.html] [--module out/<piece>.mjs]+//+// <piece> is a module in src/canvas-core/ exporting a Piece of the same name (see input.ts).+//+// The module (<piece>.mjs) exports { piece, mount, define } and registers <ani-doodle piece="<kebab>">+// when imported, so a site can use either:+// <script type="module" src="bit.mjs"></script> <ani-doodle piece="mascot-hero"></ani-doodle>+// import { mount, piece } from "./bit.mjs"; const c = mount(el, piece); c.setState("success");+// The page (<piece>.html) is --page with its <!--anidoodle--> marker replaced by the module, inlined+// (browsers refuse module imports from file://, and the page must open offline by double-click).+// Without --page you get a plain demo page with two bound buttons.+//+// Verified on the EMITTED files: nothing reaches outside itself (statically, and at run time from+// file:// with every non-file request counted as a failure), the element mounts and bakes, the+// piece moves on its own (two ticks differ), and the sizes are printed, raw and gzipped.+import { build } from "esbuild";+import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { gzipSync } from "node:zlib";+import { detect } from "./detect.mjs";++const VAL = new Set(["out", "module", "page", "title", "shot"]);+const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+const die = (m) => { console.error(`emit-interactive: ${m}`); process.exit(1); };+const name = pos[0] ?? die("usage: node tools/emit-interactive.mjs <piece> [--page page.html] [--out out/x.html] [--module out/x.mjs]");+const kebab = name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();+if (!existsSync(`src/canvas-core/${name}.ts`)) die(`no src/canvas-core/${name}.ts`);+const out = resolve(opt.out ?? `out/${kebab}.html`), modOut = resolve(opt.module ?? out.replace(/\.html$/, ".mjs"));++// ---------------------------------------------------------------- build+const buildModule = async (piece, tag = piece.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase()) => (await build({+ stdin: { contents: `import { mount, define } from "./src/hosts/interactive"; import { ${piece} } from "./src/canvas-core/${piece}"; export const piece = ${piece}; export { mount, define }; define({ ${JSON.stringify(tag)}: ${piece} });`, resolveDir: process.cwd(), loader: "ts" },+ bundle: true, format: "esm", target: "es2020", minify: true, write: false, legalComments: "none",+})).outputFiles[0].text;+const js = await buildModule(name, kebab);+const defaultPage = () => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${opt.title ?? name}</title>+<style>body{margin:0;min-height:100vh;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,480px);gap:32px;align-items:center;padding:32px;box-sizing:border-box;background:#fbf6ea;color:#3d3437;font:16px/1.5 system-ui,sans-serif}button{font:inherit;padding:12px 20px;border-radius:999px;border:2px solid #3d3437;background:#fff;cursor:pointer;margin-right:8px}@media (max-width:760px){body{grid-template-columns:1fr}}</style></head>+<body><div><h1>${opt.title ?? name}</h1><p>Move, hover, tab, click.</p><button data-anidoodle="start">Get started</button><button data-anidoodle="tour">Take the tour</button></div><ani-doodle piece="${kebab}"></ani-doodle>+<!--anidoodle--></body></html>`;+const template = opt.page ? readFileSync(resolve(opt.page), "utf8") : defaultPage();+if (!template.includes("<!--anidoodle-->")) die(`${opt.page} has no <!--anidoodle--> marker to put the module at`);+const html = template.replace("<!--anidoodle-->", () => `<script type="module">${js.replace(/<\/script/gi, "<\\/script")}</script>`);+mkdirSync(dirname(out), { recursive: true }); mkdirSync(dirname(modOut), { recursive: true });+writeFileSync(modOut, js); writeFileSync(out, html);+const kb = (n) => `${(n / 1024).toFixed(1)} KB`;+console.log(`EMIT ${name} -> <ani-doodle piece="${kebab}">`);+console.log(` module ${modOut} ${kb(Buffer.byteLength(js))} (${kb(gzipSync(js).length)} gzip)`);+console.log(` page ${out} ${kb(Buffer.byteLength(html))} (${kb(gzipSync(html).length)} gzip)`);++// ---------------------------------------------------------------- verify+let fails = 0, checks = 0;+const say = (ok, label, detail = "") => { checks++; if (!ok) fails++; console.log(` ${ok ? "PASS" : "FAIL"} ${label}${detail ? " " + detail : ""}`); };+console.log(`\n1. SELF-CONTAINED the files reach outside themselves for nothing\n${"-".repeat(58)}`);+const count = (s, re) => (s.match(re) ?? []).length;+say(count(html, /https?:\/\//g) === 0, "no http(s) reference of any kind", `${count(html, /https?:\/\//g)} found`);+say(count(html, /<(img|audio|video|source|link|iframe)\b/gi) === 0, "no external element (img, audio, video, link, iframe)");+say(count(html, /<[a-z][^>]*\ssrc\s*=/gi) === 0, "no element with a src= attribute");+say(count(html, /@font-face|@import/gi) === 0, "no web font, no css import");+say(count(js, /fetch\(|XMLHttpRequest|importScripts|WebSocket|EventSource/g) === 0, "no network call in the module");+say(count(js, /Math\.random|Date\.now|new Date/g) === 0, "no Math.random or Date in the module (clocks are performance.now, in the host only)");++if (opt["no-verify"]) process.exit(fails ? 1 : 0);+const d = detect(); if (!d.pw.ok || !d.browser.ok) die(`cannot run the page: ${d.report.playwright}; ${d.report.browser}`);+console.log(`\n2. OFFLINE AND ALIVE opened from file://\n${"-".repeat(58)}`);+const browser = await d.pw.lib.chromium.launch({ executablePath: d.browser.executablePath });+const page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });+const errors = [], reached = [];+page.on("pageerror", (e) => errors.push(e.message)); page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });+page.on("request", (r) => { const u = r.url(); if (!/^(file|data|blob):/.test(u)) reached.push(u); });+await page.addInitScript(() => { window.__ANI_RASTER__ = "cpu"; }); /* one renderer for the whole check: see surfaceFor in hosts/interactive.ts */+await page.goto(pathToFileURL(out).href);+const r = await page.evaluate(async () => {+ const t = performance.now(); while (!window.__anidoodle?.length && performance.now() - t < 5000) await new Promise((f) => setTimeout(f, 20));+ const c = window.__anidoodle?.[0]; if (!c) return null; await c.ready; const ms = performance.now() - t;+ c.pause(); const log = c.log(); c.render(0, log); const a = c.hash(); c.render(37, log); const b = c.hash(); c.render(0, log); const a2 = c.hash();+ return { ms, a, b, a2, stats: c.stats(), n: window.__anidoodle.length };+});+say(errors.length === 0, "the page runs clean", errors.slice(0, 3).join("; ") || "no page error");+say(reached.length === 0, "nothing outside file: or data: was requested", reached.slice(0, 3).join("; ") || "0 outside requests");+say(!!r, "an <ani-doodle> mounted and baked", r ? `${r.n} piece(s), ready in ${r.ms.toFixed(0)} ms, ${r.stats.sprites} sprites, ${r.stats.spriteMB} MB at scale ${r.stats.scale}` : "no controller");+if (r) { say(r.a !== r.b, "it moves on its own (tick 0 and tick 37 differ)", `${r.a} / ${r.b}`); say(r.a === r.a2, "and tick 0 drawn again is the same frame", r.a2); }+if (opt.shot) await page.screenshot({ path: resolve(opt.shot) });+await browser.close();+console.log(`\n${"=".repeat(58)}\nEMIT-INTERACTIVE: ${fails ? `FAIL ${fails} of ${checks} checks failed` : `PASS ${checks}/${checks} checks`} ${out}`);+process.exit(fails ? 1 : 0);diff --git a/engine/tools/emit.mjs b/engine/tools/emit.mjsindex 53bebad..2c2cc3d 100644--- a/engine/tools/emit.mjs+++ b/engine/tools/emit.mjs@@ -86,8 +86,8 @@ say(bad.length === 0, `${frames.length} frames across the film hash the same asconst sr = 48000;const [aShip, aGold] = [await shipped.page.evaluate((s) => window.FILM.audio(s), sr), await golden.page.evaluate((s) => window.FILM.audio(s), sr)];-const sameAudio = aShip && aGold && aShip.frames === aGold.frames && aShip.sampleRate === aGold.sampleRate;-say(!!sameAudio, "the page synthesizes the same score, in the page", sameAudio ? `${aShip.frames} samples @ ${aShip.sampleRate} Hz` : "audio missing or different");+const sameAudio = !aShip && !aGold || aShip && aGold && aShip.frames === aGold.frames && aShip.sampleRate === aGold.sampleRate && aShip.float32 === aGold.float32;+say(!!sameAudio, "the page synthesizes the same score, in the page", sameAudio ? (aShip ? `${aShip.frames} samples @ ${aShip.sampleRate} Hz` : "silent film") : "audio missing or different");await browser.close();console.log(`\n${"=".repeat(58)}\nEMIT: ${fails ? `FAIL ${fails} of ${checks} checks failed` : `PASS ${checks}/${checks} checks`} ${out}`);diff --git a/engine/tools/gallery.mjs b/engine/tools/gallery.mjsnew file mode 100644index 0000000..90073dc--- /dev/null+++ b/engine/tools/gallery.mjs@@ -0,0 +1,99 @@+// GALLERY. The style sheet, drawn by the styles themselves: one tile per style, the LAST frame+// of its draw film — the finished piece every draw-on plate holds, and the whole of a still —+// rendered through the same machinery as still.mjs at scale 1. Tiles are labelled only when+// ffmpeg can set text in a system font; when it cannot, the names go in a legend file, because a+// sheet of unnamed tiles is a guessing game.+// node tools/gallery.mjs [--only id,id] [--dry]+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { buildPage } from "./build-page.mjs";+import { detect } from "./detect.mjs";+import * as playwright from "./adapters/playwright.mjs";+import { loadRegistry, ENGINE, ROOT } from "./registry.mjs";++process.chdir(ENGINE); // buildPage and the host pages resolve src/ against cwd, like every tool here+const GALLERY = resolve(ROOT, "assets/gallery");+const CELL = 520, LH = 64;++const VAL = new Set(["only"]);+const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+const die = (m) => { console.error(`gallery: ${m}`); process.exit(1); };++const entries = loadRegistry().filter((s) => s.drawFilm);+const only = opt.only ? String(opt.only).split(",").map((s) => s.trim()) : null;+if (only) { const bad = only.filter((id) => !entries.some((s) => s.id === id)); if (bad.length) die(`--only: no style with a film named ${bad.join(", ")} (have: ${entries.map((s) => s.id).join(", ")})`); }+const tiles = entries.filter((s) => !only || only.includes(s.id));+if (!tiles.length) die("no styles with a draw film");++// Labels need drawtext AND a font file we can name. This ffmpeg has drawbox but no drawtext, so+// on this machine the sheet falls back to the legend; a machine with freetype gets real labels.+const FONTS = ["/System/Library/Fonts/Helvetica.ttc", "/System/Library/Fonts/Supplemental/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/dejavu/DejaVuSans.ttf", "C:/Windows/Fonts/arial.ttf"];+const findFont = (ff) => {+ try { if (!execFileSync(ff, ["-hide_banner", "-filters"], { stdio: ["ignore", "pipe", "ignore"] }).toString().includes("drawtext")) return { ok: false, why: "ffmpeg was built without drawtext (no libfreetype)" }; }+ catch { return { ok: false, why: "could not query ffmpeg's filters" }; }+ const font = FONTS.find((p) => existsSync(p));+ return font ? { ok: true, font } : { ok: false, why: "drawtext exists but no known system font file was found" };+};++// A still.mjs-style probe: bundle the film, read meta, no browser. Enough for --dry to say which+// frame is the last.+const metaOf = async (film) => (await import("data:text/javascript;base64," + Buffer.from((await (await import("esbuild")).build({ stdin: { contents: `export { ${film} as film } from "./src/canvas-core/${film}";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral" })).outputFiles[0].text).toString("base64"))).film.meta;++const cols = Math.ceil(Math.sqrt(tiles.length)), rows = Math.ceil(tiles.length / cols);+const plan = (font) => `grid ${cols}x${rows} of ${CELL}px tiles, ${font.ok ? `labels in ${font.font}` : `no labels (${font.why}) -> LEGEND.md`}`;++if (opt.dry) {+ const font = findFont(process.env.FFMPEG || "ffmpeg");+ console.log(`gallery (dry): ${tiles.length} styles with a film -> ${GALLERY}`);+ for (const s of tiles) {+ const page = existsSync(join(ENGINE, "src/hosts", `page-${s.drawFilm}.ts`));+ const last = page ? String((await metaOf(s.drawFilm)).durationFrames - 1) : "?";+ console.log(` ${s.id.padEnd(14)} film ${s.drawFilm.padEnd(18)} last frame ${last.padEnd(5)} -> assets/gallery/${s.id}.jpg${page ? "" : " (no host page, would be skipped)"}`);+ }+ console.log(` sheet: assets/gallery/styles.jpg ${plan(font)}`);+ process.exit(0);+}++const env = detect();+if (!env.pw.ok || !env.browser.ok) die(`no browser to draw in.\n playwright: ${env.report.playwright}\n browser: ${env.report.browser}\n fix: npm install, then npx playwright-core install chromium`);+if (!env.ffmpeg.ok) die(`no ffmpeg for the sheet.\n ${env.ffmpeg.why}`);+mkdirSync(GALLERY, { recursive: true });++const drawn = [];+for (const s of tiles) {+ if (!existsSync(join(ENGINE, "src/hosts", `page-${s.drawFilm}.ts`))) { console.log(` ${s.id}: draw film '${s.drawFilm}' has no host page yet, skipped`); continue; }+ const page = await buildPage({ entry: `src/hosts/page-${s.drawFilm}.ts`, out: resolve(`dist/${s.drawFilm}.html`), title: s.drawFilm });+ const session = await playwright.open(env, page.out, { scale: 1, workers: 1 });+ const meta = await session.info(), last = meta.durationFrames - 1;+ const f = await session.frame(last, 0);+ await session.close();+ const jpg = join(GALLERY, `${s.id}.jpg`);+ execFileSync(env.ffmpeg.bin, ["-y", "-loglevel", "error", "-i", "pipe:0", "-frames:v", "1", "-q:v", "3", jpg], { input: f.png }); // mjpeg q3 ~= jpeg quality 88+ console.log(` ${s.id.padEnd(14)} ${s.name.padEnd(32)} ${s.drawFilm} frame ${last} draw ${f.drawMs.toFixed(0)} ms -> ${jpg}`);+ drawn.push(s);+}+if (!drawn.length) die("nothing rendered");++const font = findFont(env.ffmpeg.bin), esc = (s) => s.replace(/[\\:',%]/g, "\\$&"), rowH = CELL + (font.ok ? LH : 0);+const inputs = [], parts = drawn.flatMap((s, i) => {+ inputs.push("-i", join(GALLERY, `${s.id}.jpg`));+ return font.ok+ ? [`[${i}:v]scale=${CELL}:${CELL},pad=${CELL}:${rowH}:0:0:color=0xf7f5f0,drawtext=fontfile='${esc(font.font)}':text='${esc(s.name)}':fontsize=22:fontcolor=0x1b1a1a:x=(w-text_w)/2:y=${CELL + 18},format=yuv420p[t${i}]`]+ : [`[${i}:v]scale=${CELL}:${CELL},format=yuv420p[t${i}]`];+});+const cells = cols * rows, ins = drawn.map((_, i) => `[t${i}]`);+for (let b = drawn.length; b < cells; b++) { inputs.push("-f", "lavfi", "-i", `color=c=0xf7f5f0:s=${CELL}x${rowH}`); parts.push(`[${b}:v]format=yuv420p[b${b}]`); ins.push(`[b${b}]`); }+const layout = Array.from({ length: cells }, (_, i) => `${(i % cols) * CELL}_${Math.floor(i / cols) * rowH}`).join("|");+const sheet = join(GALLERY, "styles.jpg");+execFileSync(env.ffmpeg.bin, [...inputs, "-y", "-loglevel", "error", "-filter_complex", `${parts.join(";")};${ins.join("")}xstack=inputs=${cells}:layout=${layout},format=yuv420p[out]`, "-map", "[out]", "-frames:v", "1", "-q:v", "3", sheet]);++if (!font.ok) writeFileSync(join(GALLERY, "LEGEND.md"), [+ "# Gallery legend", "",+ `ffmpeg here cannot draw text (${font.why}), so styles.jpg carries no labels.`,+ `Grid is ${cols} across and ${rows} down, in reading order:`, "",+ ...drawn.map((s, i) => `${i + 1}. **${s.name}** (\`${s.id}\`) — assets/gallery/${s.id}.jpg`), "",+].join("\n"));+console.log(`\nsheet: ${sheet} ${drawn.length} tiles, ${plan(font)}`);diff --git a/engine/tools/gate.mjs b/engine/tools/gate.mjsindex f6bd2b1..f9372b5 100644--- a/engine/tools/gate.mjs+++ b/engine/tools/gate.mjs@@ -13,6 +13,9 @@import { execFileSync, spawnSync } from "node:child_process";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { resolve } from "node:path";+import { readdirSync } from "node:fs";+import { defaultOutput } from "./names.mjs";+import { changedArea } from "./motion.mjs";const VAL = new Set(["adapter", "mp4", "samples", "scale", "workers"]);const pos = [], opt = {};@@ -39,6 +42,20 @@ const FORBIDDEN = [[/from\s+["']react["']/, "react import"], [/from\s+["']remotion["']/, "remotion import"], [/pencil\.tsx/, "pencil.tsx import"],];const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");+const motionViolations = (changed, meta) => {+ const declared = (ranges, f) => ranges?.some(([from, to]) => f >= from && f < to) ?? false;+ const step = meta.step ?? (meta.onTwos ? 2 : 1);+ const explained = (f) => {+ const shotStart = meta.shots?.find((s) => f >= s.start && f < s.end)?.start ?? 0;+ return declared(meta.holds, f) || (step > 1 && (f - shotStart) % step !== 0);+ };+ const drawing = meta.kind === "drawing", floor = drawing ? 0.0002 : 0.005, pause = drawing ? Math.round(meta.fps / 2) : 0; // a hand may rest half a second between passes+ let run = 0; const still = [];+ for (let f = 1; f < changed.length; f++) { run = changed[f] === 0 ? run + 1 : 0; if (changed[f] === 0 && !explained(f) && run > pause) still.push(f); }+ const windowSize = drawing ? Math.max(2, Math.round(meta.fps)) : Math.max(2, Math.round(meta.fps / 2));+ const windows = []; for (let f = 1; f + windowSize <= changed.length; f++) { let m = 0; for (let k = f; k < f + windowSize; k++) m = Math.max(m, changed[k]); if (m < floor && !Array.from({ length: windowSize }, (_, k) => f + k).every((i) => declared(meta.holds, i))) windows.push(f); }+ return { still, windows, windowSize };+};const walk = (dir, out = []) => { for (const e of execFileSync("find", [dir, "-name", "*.ts", "-type", "f"]).toString().trim().split("\n").filter(Boolean)) out.push(e); return out; };const contractScan = () => {@@ -49,28 +66,25 @@ const contractScan = () => {say(hits.length === 0, `no forbidden call in ${files.length} art-core modules`, hits.length ? hits.slice(0, 6).join(" | ") : "Math.random, Date, performance.now, ctx.filter, network, image/font loads: none");const rngSites = files.reduce((a, f) => a + (stripComments(readFileSync(f, "utf8")).match(/\brng\s*\(/g) ?? []).length, 0);const badSeed = files.flatMap((f) => (stripComments(readFileSync(f, "utf8")).match(/rng\s*\(\s*(Date|Math|performance)/g) ?? []));- say(badSeed.length === 0 && rngSites > 0, `all randomness is rng(seed): ${rngSites} seeded call sites`, badSeed.length ? `UNSEEDED: ${badSeed.join(", ")}` : "no seed derived from a clock or Math.random");+ say(badSeed.length === 0, `all randomness is rng(seed): ${rngSites} seeded call sites`, badSeed.length ? `UNSEEDED: ${badSeed.join(", ")}` : "no seed derived from a clock or Math.random");return files.length;};// ---------------------------------------------------------------- 3. dead air, on a real file-const deadAir = (mp4) => {+const deadAir = async (mp4, meta) => {head(3, "DEAD AIR something visibly moves in every second");if (!existsSync(mp4)) { say(false, "an MP4 to measure", `${mp4} not found`); return; }- const W = 270, px = W * W;- const grey = spawnSync("ffmpeg", ["-v", "error", "-i", mp4, "-vf", `scale=${W}:${W}`, "-pix_fmt", "gray", "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 }).stdout;- const n = Math.floor(grey.length / px), changed = [0];- for (let f = 1; f < n; f++) { const A = grey.subarray((f - 1) * px, f * px), B = grey.subarray(f * px, (f + 1) * px); let c = 0; for (let i = 0; i < px; i++) if (Math.abs(A[i] - B[i]) > 4) c++; changed.push(c / px); }- const still = []; for (let f = 1; f < n; f++) if (changed[f] === 0) still.push(f);- const win = []; for (let f = 1; f + 15 <= n; f++) { let m = 0; for (let k = f; k < f + 15; k++) m = Math.max(m, changed[k]); if (m < 0.005) win.push(f); }- const merged = []; win.forEach((f) => { const l = merged[merged.length - 1]; if (l && f <= l[1]) l[1] = f + 15; else merged.push([f, f + 15]); });- // A film may LOCK an early act that is known to fail here. Report it, never launder it.- const A1 = 540, lateStill = still.filter((f) => f >= A1), lateWin = merged.filter(([a]) => a >= A1);- say(lateStill.length === 0, "no identical consecutive frames after the locked act", `${lateStill.length} after frame ${A1}, ${still.length} in the whole file`);- say(lateWin.length === 0, "no 15-frame window under 0.5% changed after the locked act", lateWin.map(([a, b]) => `${a}-${b}`).join(", ") || "none");- const mvt = changed.slice(A1 + 1).sort((a, b) => a - b);- console.log(` ${n} frames measured; after frame ${A1}: median ${(mvt[mvt.length >> 1] * 100).toFixed(2)}% min ${(mvt[0] * 100).toFixed(2)}%`);- if (still.length) console.log(` NOTE: ${still.length} still frames all sit inside the LOCKED Act 1 (locked by decision). Not counted against this gate.`);+ const W = 270, H = Math.max(2, Math.round(W * meta.H / meta.W));+ let changed; try { changed = await changedArea(mp4, W, H); } catch (e) { say(false, "decode MP4", e.message); return; }+ const n = changed.length;+ say(n === meta.durationFrames, "MP4 frame count matches film", `${n}/${meta.durationFrames}`);+ const { still, windows: win, windowSize } = motionViolations(changed, meta);+ const merged = []; win.forEach((f) => { const l = merged[merged.length - 1]; if (l && f <= l[1]) l[1] = f + windowSize; else merged.push([f, f + windowSize]); });+ for (const [from, to, reason] of meta.locked ?? []) console.log(` LOCKED ${from}-${to}: ${reason}; violations remain failures`);+ say(still.length === 0, "no unexplained identical consecutive frames", still.length ? still.slice(0, 20).join(", ") : "none");+ say(merged.length === 0, `no ${windowSize}-frame window under ${meta.kind === "drawing" ? "0.02" : "0.5"}% changed`, merged.map(([a, b]) => `${a}-${b}`).join(", ") || "none");+ const mvt = changed.slice(1).sort((a, b) => a - b);+ console.log(` ${n} frames measured; median ${((mvt[mvt.length >> 1] ?? 0) * 100).toFixed(2)}% min ${((mvt[0] ?? 0) * 100).toFixed(2)}%`);};// ---------------------------------------------------------------- 1. determinism, two ways round@@ -91,7 +105,10 @@ const run = async () => {const s1 = await mod.open(film, { scale: SCALE, workers: 1 });const meta = await s1.info();const N = meta.durationFrames;- const frames = Array.from({ length: SAMPLES }, (_, i) => Math.round((i * (N - 1)) / (SAMPLES - 1)));+ const bounds = [...new Set([0, N - 1, ...(meta.shots ?? []).flatMap((s) => [s.start, s.end - 1])])];+ const extra = Math.max(0, SAMPLES - bounds.length);+ const spread = Array.from({ length: extra }, (_, i) => Math.round(((i + 1) * (N - 1)) / (extra + 1)));+ const frames = [...new Set([...bounds, ...spread])].sort((a, b) => a - b);const h1 = []; for (const f of frames) h1.push(await s1.hash(f, 0)); // forward, one pageconst art = s1.artifact?.() ?? null;const aud1 = await s1.audio(48000);@@ -104,7 +121,7 @@ const run = async () => {const aud2 = await s2.audio(48000);const same = frames.filter((_, i) => h1[i] === h2[i]).length;- say(same === frames.length, `${frames.length} sampled frames hash-identical across 1 page and ${W2} pages, forward vs reversed`, `${same}/${frames.length} frames ${frames[0]}..${frames[frames.length - 1]}`);+ if (same === frames.length) say(true, `${frames.length} sampled frames hash-identical across 1 page and ${W2} pages, forward vs reversed`, `${same}/${frames.length} frames ${frames[0]}..${frames[frames.length - 1]}`);if (same !== frames.length) { // only pay for pixels when the hashes disagreelet worst = Infinity;for (let i = 0; i < frames.length; i++) {@@ -116,7 +133,7 @@ const run = async () => {const v = psnr(a, b); worst = Math.min(worst, v);console.log(` frame ${frames[i]}: PSNR ${v === Infinity ? "inf" : v.toFixed(2)} dB`);}- say(worst > 45, `every differing frame is visually identical (PSNR > 45 dB)`, `min PSNR ${worst === Infinity ? "inf" : worst.toFixed(2)} dB`);+ say(worst > 45, `hash differences within PSNR tolerance (> 45 dB)`, `min PSNR ${worst === Infinity ? "inf" : worst.toFixed(2)} dB`);// A failure is only useful if it says WHERE to look. Redraw the first offender cold, then// again behind each earlier sample, and name the frame that poisons it: that is the signature// of a cache key that does not name everything its pixels depend on.@@ -137,12 +154,12 @@ const run = async () => {// A silent piece (a still, a loop, a logo) has nothing to compare; a score that appears in one// session and not the other is still a failure.if (!aud1 && !aud2) note("no score in this piece", "audio check not applicable");- else say(aud1 && aud2 ? aud1.pcm16 === aud2.pcm16 : false, "the synthesized audio is identical across sessions", aud1 ? `${aud1.frames} samples @ ${aud1.sampleRate} Hz` : "no audio");+ else say(aud1 && aud2 ? aud1.float32 === aud2.float32 : false, "the synthesized audio is identical across sessions", aud1 ? `${aud1.frames} samples @ ${aud1.sampleRate} Hz` : "no audio");await s2.close();const nFiles = contractScan();if (N === 1) { head(3, "DEAD AIR something visibly moves in every second"); note("a still, one frame long", "dead air not applicable"); }- else deadAir(resolve(opt.mp4 ?? `out/${film.replace(/([A-Z])/g, "-$1").toLowerCase()}.mp4`));+ else await deadAir(resolve(opt.mp4 ?? defaultOutput(film)), meta);if (art) {head(4, `ARTIFACT what this adapter delivers`);@@ -154,4 +171,22 @@ const run = async () => {console.log(fails ? `GATE: FAIL ${fails} of ${checks} checks failed` : `GATE: PASS ${checks}/${checks} checks, ${nFiles} modules scanned`);process.exit(fails ? 1 : 0);};-run().catch((e) => { console.error(`\ngate crashed: ${e.message}`); process.exit(2); });+const selfTest = async () => {+ let wrong = 0;+ for (const file of readdirSync("test/fixtures").filter((f) => f.endsWith(".mjs")).sort()) {+ const fixture = (await import(`../test/fixtures/${file}`)).default;+ const { meta, render, expected } = fixture;+ const forbidden = FORBIDDEN.some(([re]) => re.test(stripComments(render.toString())));+ const cache = new Map(), frames = Array.from({ length: meta.durationFrames }, (_, f) => render(f, cache));+ const changed = frames.map((v, i) => i === 0 ? 0 : v === frames[i - 1] ? 0 : 1);+ const motion = motionViolations(changed, meta);+ const reverseCache = new Map(), reversed = frames.map((_, i) => render(frames.length - i - 1, reverseCache)).reverse();+ const orderDependent = frames.some((v, i) => v !== reversed[i]);+ const actual = forbidden || motion.still.length > 0 || motion.windows.length > 0 || orderDependent ? "FAIL" : "PASS";+ if (actual !== expected) wrong++;+ console.log(`${actual === expected ? "PASS" : "FAIL"} ${file}: expected ${expected}, actual ${actual}${forbidden ? " forbidden source" : ""}${motion.still.length ? ` still ${motion.still.join(",")}` : ""}${orderDependent ? " order-dependent" : ""}`);+ }+ console.log(`SELF-TEST: ${wrong ? "FAIL" : "PASS"}`);+ process.exit(wrong ? 1 : 0);+};+(opt["self-test"] ? selfTest() : run()).catch((e) => { console.error(`\ngate crashed: ${e.message}`); process.exit(2); });diff --git a/engine/tools/lesson.mjs b/engine/tools/lesson.mjsnew file mode 100644index 0000000..632d0fd--- /dev/null+++ b/engine/tools/lesson.mjs@@ -0,0 +1,117 @@+// LESSON. Turn a drawing-score lesson module into its three deliverables and gate it.+// node tools/lesson.mjs <lessonFilm> --out <dir> [--ref image.png [--ref-crop x,y,w,h]] [--no-mp4] [--workers 2]+// The module (src/canvas-core/<lessonFilm>.ts) exports the timelapse film and+// export const LESSON = { score: () => Score, sheet: "<sheetFilm>", final: "<finalFilm>", source?: "..." }+// Writes into --out: <name>-steps.png (step sheet), <name>-timelapse.mp4, <name>-contact.png,+// LESSON.md, gates.txt. Gates (spec 14 section 5, the ones a machine can decide):+// schema ids unique, parts/layers resolve, dependencies acyclic and in order, corrections erased first+// identity the timelapse's LAST frame (prefix-cached replay) == the finished drawing rendered cold+// time travel sampled frames hash the same rendered forward, reversed, and each in a freshly mounted page+// fidelity (--ref) value-mass IoU and colour distance of the finished drawing against the user's image+// What no gate here can decide: whether the order reads as a hand working, and whether the teaching+// is right. Watch the timelapse and read the sheet.+import { execFileSync, spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdirSync, writeFileSync } from "node:fs";+import { resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { build } from "esbuild";+import { buildPage } from "./build-page.mjs";+import { detect } from "./detect.mjs";++const VAL = new Set(["out", "ref", "ref-crop", "workers"]);+const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+const die = (m) => { console.error(`lesson: ${m}`); process.exit(1); };+const name = pos[0] ?? die("usage: node tools/lesson.mjs <lessonFilm> --out <dir>");+const outDir = resolve(opt.out ?? `out/${name}`); mkdirSync(outDir, { recursive: true });+const log = []; const say = (s = "") => { console.log(s); log.push(s); };++// ---------------------------------------------------------------- 1. the score, in node+const probe = (await build({ stdin: { contents: `export { LESSON, ${name} as film } from "./src/canvas-core/${name}"; export { validate, PHASE_NAME } from "./src/canvas-core/drawingScore";`, resolveDir: process.cwd(), loader: "ts" }, bundle: true, format: "esm", write: false, platform: "neutral" })).outputFiles[0].text;+const M = await import("data:text/javascript;base64," + Buffer.from(probe).toString("base64"));+const S = M.LESSON.score(), V = M.validate(S), plan = M.film.plan(), fps = M.film.meta.fps, N = M.film.meta.durationFrames;+say(`LESSON ${S.title} (${S.medium})`);+say(`\nschema: ${V.problems.length ? "FAIL" : "PASS"} ${V.stats.marks} marks, ${V.stats.parts} parts, ${V.stats.steps} steps, ${S.layers.length} layers`);+V.problems.forEach((p) => say(` problem: ${p}`)); V.warnings.forEach((w) => say(` warning: ${w}`));+say(` marks per part: ${Object.entries(V.stats.perPart).map(([k, v]) => `${k} ${v}`).join(", ")}`);+say(` order: ${S.steps.map((s, i) => `${i + 1}.${s.phase}`).join(" > ")}`);+say(` film: ${N} frames = ${(N / fps).toFixed(1)} s; steps at ${plan.steps.map((p) => (p.start / fps).toFixed(1) + "s").join(", ")}`);++// ---------------------------------------------------------------- 2. LESSON.md+const t = (f) => { const s = Math.round(f / fps); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };+const md = [`# ${S.title}`, "", `**Medium:** ${S.medium}`, ""];+if (S.note) md.push(`> ${S.note}`, "");+if (M.LESSON.source) md.push(`**Source image:** ${M.LESSON.source}`, "");+md.push(`**Files:** \`${name}-steps.png\` (one panel per step: earlier marks pale, the new ones strong), \`${name}-timelapse.mp4\` (${(N / fps).toFixed(0)} s, captions written on as pen strokes), this file.`, "", `The drawing is a score of ${S.marks.length} marks in ${S.steps.length} steps. Every mark was placed in this order on purpose; the timelapse is that order played back, not a recording of a person drawing.`, "");+S.steps.forEach((st, i) => {+ const parts = [...new Set(st.marks.map((m) => S.marks[m].part))].map((p) => S.parts.find((q) => q.id === p).label);+ md.push(`## ${i + 1}. ${st.title} _(${M.PHASE_NAME[st.phase]}, ${t(plan.steps[i].start)} in the timelapse)_`, "", st.caption, "", `- **Look for:** ${st.look}`, `- **How:** ${st.how}`);+ if (st.mistake) md.push(`- **Common mistake:** ${st.mistake}`);+ md.push(`- **Marks:** ${st.marks.length}, on ${parts.join(", ")}${st.marks.some((m) => S.marks[m].kind === "erase") ? " (includes an eraser pass)" : ""}`, "");+});+md.push("## Layers", "", ...S.layers.map((l) => `- \`${l.id}\`${l.note ? `: ${l.note}` : ""}`), "");+writeFileSync(resolve(outDir, "LESSON.md"), md.join("\n"));+say(`\n-> ${resolve(outDir, "LESSON.md")}`);++// ---------------------------------------------------------------- 3. pages: sheet, identity, time travel+const env = detect(); if (!env.pw.ok || !env.browser.ok) die("no browser: npm install, then npx playwright-core install chromium");+const browser = await env.pw.lib.chromium.launch({ executablePath: env.browser.executablePath });+const ctx = await browser.newContext({ viewport: { width: 640, height: 640 } });+const open = async (film) => { const pg = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film }); const p = await ctx.newPage(); const errs = []; p.on("pageerror", (e) => errs.push(e.message)); await p.goto(pathToFileURL(pg.out).href + "?adapter=playwright"); await p.evaluate(async () => { await window.FILM.ready; window.FILM.mount(1); }); if (errs.length) die(`${film}: ${errs.join("; ")}`); return p; };+const shoot = (p, f) => p.evaluate((n) => { window.FILM.seek(n); return { png: window.FILM.png(), hash: window.FILM.hash() }; }, f);+const md5 = (b64) => createHash("md5").update(Buffer.from(b64, "base64")).digest("hex");++const sheetPage = await open(M.LESSON.sheet), sheet = await shoot(sheetPage, 0);+writeFileSync(resolve(outDir, `${name}-steps.png`), Buffer.from(sheet.png, "base64")); say(`-> ${resolve(outDir, `${name}-steps.png`)} md5 ${md5(sheet.png)}`);++const filmA = await open(name), finalPage = await open(M.LESSON.final);+// warm the replay the way a render does: walk forward through every step end, then take the last frame+for (const s of plan.steps) await shoot(filmA, Math.min(N - 1, Math.round(s.markEnd)));+const last = await shoot(filmA, N - 1), cold = await shoot(finalPage, 0);+writeFileSync(resolve(outDir, `${name}-final.png`), Buffer.from(last.png, "base64"));+say(`\nidentity: ${last.hash === cold.hash ? "PASS" : "FAIL"} timelapse frame ${N - 1} (cached replay) ${last.hash} vs cold render ${cold.hash}`);++const sample = [0, ...plan.steps.flatMap((s) => [Math.round((s.markStart + s.markEnd) / 2), Math.round(s.markEnd)]), N - 1].filter((f, i, a) => f < N && a.indexOf(f) === i);+const filmB = await open(name), fwd = [], rev = [], iso = [];+for (const f of sample) fwd.push((await shoot(filmB, f)).hash);+const filmC = await open(name); for (const f of [...sample].reverse()) rev.unshift((await shoot(filmC, f)).hash);+const filmD = await open(name); for (const f of sample) iso.push(await filmD.evaluate((n) => { window.FILM.mount(1); window.FILM.seek(n); return window.FILM.hash(); }, f)); // a fresh env (empty cache) per frame+const ok = sample.filter((_, i) => fwd[i] === rev[i] && fwd[i] === iso[i]).length;+say(`time travel: ${ok === sample.length ? "PASS" : "FAIL"} ${ok}/${sample.length} sampled frames identical forward, reversed and cold-mounted (frames ${sample.join(", ")})`);+const timing = await filmB.evaluate((f) => window.FILM.seek(f).ms, Math.round(plan.steps[plan.steps.length - 2].markEnd));+say(`draw cost: ${timing.toFixed(0)} ms for a late frame at scale 1`);+await browser.close();++// ---------------------------------------------------------------- 4. fidelity against the user's image (recreate-and-teach)+if (opt.ref) {+ const art = M.film.meta.W; // the art square sits at the top of the lesson frame+ const grab = (file, crop, size = 128) => { const vf = [crop ? `crop=${crop.split(",")[2]}:${crop.split(",")[3]}:${crop.split(",")[0]}:${crop.split(",")[1]}` : null, `scale=${size}:${size}:flags=area`].filter(Boolean).join(","); return execFileSync("ffmpeg", ["-v", "error", "-i", file, "-vf", vf, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: 1 << 26 }); };+ const lin = (c) => { c /= 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; };+ const lab = (r, g, b) => { const R = lin(r), G = lin(g), B = lin(b), l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B), m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B), s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B); return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s]; };+ const labs = (buf) => Array.from({ length: buf.length / 3 }, (_, i) => lab(buf[i * 3], buf[i * 3 + 1], buf[i * 3 + 2]));+ const A = labs(grab(resolve(opt.ref), opt["ref-crop"])), B = labs(grab(resolve(outDir, `${name}-final.png`), `0,0,${art},${art}`));+ // value masses: the reference posterised to its own three values (1-D k-means on L, thresholds halfway+ // between the centres), the same thresholds applied to the recreation. Equal-area tertiles were tried+ // first and rejected: a big flat colour sitting on a tertile boundary splits into noise.+ const Ls = A.map((p) => p[0]).sort((a, b) => a - b); let cen = [Ls[Math.floor(Ls.length / 6)], Ls[Math.floor(Ls.length / 2)], Ls[Math.floor((5 * Ls.length) / 6)]];+ for (let it = 0; it < 30; it++) { const s = [0, 0, 0], n = [0, 0, 0]; for (const L of Ls) { const k = cen.reduce((b, c, j) => (Math.abs(L - c) < Math.abs(L - cen[b]) ? j : b), 0); s[k] += L; n[k]++; } cen = cen.map((c, j) => (n[j] ? s[j] / n[j] : c)); }+ const t1 = (cen[0] + cen[1]) / 2, t2 = (cen[1] + cen[2]) / 2, cls = (L) => (L < t1 ? 0 : L < t2 ? 1 : 2);+ const iou = [0, 1, 2].map((k) => { let i = 0, u = 0; A.forEach((p, j) => { const a = cls(p[0]) === k, b = cls(B[j][0]) === k; if (a && b) i++; if (a || b) u++; }); return u ? i / u : 1; });+ const dE = A.reduce((s, p, j) => s + Math.hypot(p[0] - B[j][0], p[1] - B[j][1], p[2] - B[j][2]), 0) / A.length;+ const mIoU = iou.reduce((a, b) => a + b, 0) / 3;+ say(`\nfidelity vs ${opt.ref}${opt["ref-crop"] ? ` [${opt["ref-crop"]}]` : ""}:\n value-mass IoU dark ${iou[0].toFixed(2)} / mid ${iou[1].toFixed(2)} / light ${iou[2].toFixed(2)}, mean ${mIoU.toFixed(2)} (target >= 0.70 for a recreation)\n mean OKLab dE at 128 px ${(dE * 100).toFixed(1)} (x100; under ~10 reads as the same colours)`);+}++// ---------------------------------------------------------------- 5. the timelapse and its contact sheet+if (!opt["no-mp4"]) {+ const mp4 = resolve(outDir, `${name}-timelapse.mp4`);+ const r = spawnSync(process.execPath, ["tools/render.mjs", name, "--workers", String(opt.workers ?? 2), "--out", mp4], { stdio: ["ignore", "pipe", "inherit"] });+ const tail = r.stdout.toString().trim().split("\n").filter((l) => /budget|determinism|draw median|output|stream|video/.test(l));+ say(`\ntimelapse: ${r.status === 0 ? "rendered" : "FAILED"} -> ${mp4}`); tail.forEach((l) => say(` ${l.trim()}`));+ const picks = plan.steps.map((s) => Math.round(s.markStart + (s.markEnd - s.markStart) * 0.6)); picks.unshift(30); picks.push(N - 1);+ const sel = picks.slice(0, 12).map((f) => `eq(n\\,${f})`).join("+"), cols = 4, rows = Math.ceil(Math.min(12, picks.length) / cols);+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", mp4, "-vf", `select='${sel}',scale=360:-2,tile=${cols}x${rows}:padding=6:color=0xe9e2d2`, "-frames:v", "1", "-vsync", "vfr", resolve(outDir, `${name}-contact.png`)]);+ say(`-> ${resolve(outDir, `${name}-contact.png`)} (frames ${picks.slice(0, 12).join(", ")})`);+}+writeFileSync(resolve(outDir, "gates.txt"), log.join("\n") + "\n");diff --git a/engine/tools/motion.mjs b/engine/tools/motion.mjsnew file mode 100644index 0000000..01ab297--- /dev/null+++ b/engine/tools/motion.mjs@@ -0,0 +1,22 @@+import { spawn } from "node:child_process";++// Read one small grayscale frame at a time. A ten-minute film must not need a gigabyte buffer.+export const changedArea = async (file, width, height, threshold = 4) => {+ const px = width * height, changed = [0];+ const ff = spawn("ffmpeg", ["-v", "error", "-i", file, "-vf", `scale=${width}:${height}`, "-pix_fmt", "gray", "-f", "rawvideo", "-"]);+ let pending = Buffer.alloc(0), previous = null, error = "";+ ff.stderr.on("data", (chunk) => { error += chunk.toString(); });+ const closed = new Promise((resolve, reject) => { ff.on("error", reject); ff.on("close", (code) => code ? reject(new Error(error || `ffmpeg exited ${code}`)) : resolve()); });+ for await (const chunk of ff.stdout) {+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;+ while (pending.length >= px) {+ const frame = pending.subarray(0, px);+ if (previous) { let count = 0; for (let i = 0; i < px; i++) if (Math.abs(frame[i] - previous[i]) > threshold) count++; changed.push(count / px); }+ previous = Buffer.from(frame);+ pending = pending.subarray(px);+ }+ }+ await closed;+ if (pending.length) throw new Error(`incomplete decoded frame: ${pending.length} bytes`);+ return changed;+};diff --git a/engine/tools/music.mjs b/engine/tools/music.mjsnew file mode 100644index 0000000..3df8715--- /dev/null+++ b/engine/tools/music.mjs@@ -0,0 +1,177 @@+#!/usr/bin/env node+// Offline music renderer + meter. Renders a named piece to a 48 kHz 32-bit FLOAT WAV (no PCM16+// clipping on the way) and meters the DECODED file: integrated LUFS (BS.1770-4), LRA (EBU 3342),+// true peak (4x), onsets/s (spectral flux), spectral centroid; plus note-data numbers.+//+// node tools/music.mjs list+// node tools/music.mjs render <piece> <out.wav> [--seconds 45] [--flat] [--tempo 66] [--fit]+// node tools/music.mjs meter <file.wav|file.mp4> [more files]+// node tools/music.mjs samples <outdir> # the whole deliverable set + meters.json + .m4a+// node tools/music.mjs score <piece> # the text score, bar by bar+// node tools/music.mjs probe # piano realism probes+import { build } from "esbuild";+import { execFileSync } from "node:child_process";+import { writeFileSync, readFileSync, existsSync, mkdirSync, unlinkSync } from "node:fs";+import { dirname, join, resolve, basename } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const SR = 48000;+const load = async () => {+ const r = await build({ entryPoints: [join(here, "../src/canvas-core/music/index.ts")], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });+ return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));+};++export const writeWavFloat = (path, L, R, sr = SR) => {+ const n = L.length, data = Buffer.alloc(n * 8), h = Buffer.alloc(58);+ for (let i = 0; i < n; i++) { data.writeFloatLE(L[i], i * 8); data.writeFloatLE(R[i], i * 8 + 4); }+ h.write("RIFF", 0); h.writeUInt32LE(50 + data.length, 4); h.write("WAVE", 8);+ h.write("fmt ", 12); h.writeUInt32LE(18, 16); h.writeUInt16LE(3, 20); h.writeUInt16LE(2, 22); h.writeUInt32LE(sr, 24); h.writeUInt32LE(sr * 8, 28); h.writeUInt16LE(8, 32); h.writeUInt16LE(32, 34); h.writeUInt16LE(0, 36);+ h.write("fact", 38); h.writeUInt32LE(4, 42); h.writeUInt32LE(n, 46); h.write("data", 50); h.writeUInt32LE(data.length, 54);+ writeFileSync(path, Buffer.concat([h, data]));+};+/** Decode ANY file through ffmpeg to float stereo 48 kHz: we meter what a player would decode. */+export const decode = (path) => {+ const buf = execFileSync("ffmpeg", ["-v", "error", "-i", path, "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", "2", "-ar", String(SR), "pipe:1"], { maxBuffer: 1 << 30 });+ const f = new Float32Array(buf.buffer, buf.byteOffset, buf.length / 4), n = f.length / 2, L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }+ return [L, R];+};++/** Independent cross-check: ffmpeg's own ebur128 summary (integrated, LRA, true peak). */+const ffmpegEbu = (path) => {+ const out = execFileSync("sh", ["-c", 'ffmpeg -hide_banner -nostats -i "$1" -vn -af ebur128=peak=true -f null - 2>&1', "sh", path], { encoding: "utf8", maxBuffer: 1 << 28 });+ const sum = out.slice(out.lastIndexOf("Summary:"));+ const g = (re) => { const m = re.exec(sum); return m ? Number(m[1]) : NaN; };+ return { I: g(/I:\s+(-?[\d.]+) LUFS/), LRA: g(/LRA:\s+(-?[\d.]+) LU/), TP: g(/Peak:\s+(-?[\d.]+) dBFS/) };+};+const fmt = (x, d = 1) => (Number.isFinite(x) ? x.toFixed(d) : "n/a");+const noteStats = (M, piece) => {+ const all = piece.parts.flatMap((p) => p.notes.filter((n) => n.role !== "drum"));+ const ps = all.map((n) => n.p), lo = Math.min(...ps), hi = Math.max(...ps);+ return { range: `${M.nameOf(lo)}-${M.nameOf(hi)}`, notes: all.length };+};+const onsetsFromData = (rendered) => {+ const ts = rendered.perf.parts.flatMap((p) => p.keys.map((k) => k.t)).sort((a, b) => a - b); let c = 0, last = -1;+ for (const t of ts) if (t - last > 0.03) { c++; last = t; } return c;+};++const renderOne = (M, spec) => {+ let piece = M.PIECES[spec.piece]();+ let tempo = spec.tempo ?? piece.plan.tempo;+ let form;+ if (spec.fit) { const f = M.fitToDuration(piece, spec.seconds); piece = f.piece; tempo = f.tempo; form = `${f.form}: ${f.piece.plan.sections.map((x) => x.id).join(", ")}`; }+ const opts = { seconds: spec.seconds, tempo };+ if (spec.flat) Object.assign(opts, { expressive: false, piano: M.PIANO_FLAT, flatVelocity: 0.6 });+ const t0 = Date.now(), r = M.renderPiece(piece, SR, opts), ms = Date.now() - t0;+ // determinism: a second render must be bit-identical+ const r2 = M.renderPiece(piece, SR, opts); let same = true; for (let i = 0; i < r.L.length; i += 7) if (r.L[i] !== r2.L[i] || r.R[i] !== r2.R[i]) { same = false; break; }+ return { r, piece, tempo, ms, deterministic: same, form };+};++const voicing = (M, piece, tempo, seconds, flat) => {+ // melody vs everything else, rendered separately, loudness difference in LU (both unmastered)+ const only = (roles) => ({ ...piece, parts: piece.parts.map((p) => ({ ...p, notes: p.notes.filter((n) => roles.includes(n.role)) })) });+ const base = { seconds, tempo, master: "none", ...(flat ? { expressive: false, piano: M.PIANO_FLAT, flatVelocity: 0.6 } : {}) };+ const a = M.renderPiece(only(["melody"]), SR, base), b = M.renderPiece(only(["accomp", "bass", "inner"]), SR, base);+ return M.loudness([a.L, a.R], SR).integrated - M.loudness([b.L, b.R], SR).integrated;+};++/** Per-note voicing: mean level (dB, from the piano's velocity->level law) of melody keys minus accompaniment keys. */+const noteVoicing = (r, piece) => {+ const lv = (v) => 20 * Math.log10(v < 0.6 ? Math.pow(v, 1.55) : Math.pow(0.6, 1.55) * Math.pow(v / 0.6, 0.9));+ const mel = [], acc = []; r.perf.parts.forEach((p, i) => { if (piece.parts[i].inst !== "piano") return; for (const k of p.keys) (k.role === "melody" ? mel : acc).push(lv(k.v)); });+ const mean = (a) => a.reduce((x, y) => x + y, 0) / a.length; return mel.length && acc.length ? mean(mel) - mean(acc) : null;+};+const main = async () => {+ const [cmd, ...args] = process.argv.slice(2);+ const M = await load();+ const flag = (k) => args.includes(k), val = (k, d) => { const i = args.indexOf(k); return i >= 0 ? Number(args[i + 1]) : d; };+ if (cmd === "list") { console.log(Object.keys(M.PIECES).join("\n")); return; }+ if (cmd === "render") {+ const [name, out] = args; const { r, tempo, ms, deterministic, piece } = renderOne(M, { piece: name, seconds: val("--seconds", undefined), tempo: val("--tempo", undefined), flat: flag("--flat"), fit: flag("--fit") });+ writeWavFloat(out, r.L, r.R); const m = M.measure(decode(out), SR);+ console.log(JSON.stringify({ file: out, tempo, renderMs: ms, deterministic, gainDb: r.gainDb, problems: M.planProblems(piece), ...m, shortTerm: undefined }, null, 1)); return;+ }+ if (cmd === "meter") { for (const f of args) { const m = M.measure(decode(f), SR), ff = ffmpegEbu(f); console.log(basename(f), `LUFS ${fmt(m.lufs)} (ffmpeg ${fmt(ff.I)}) LRA ${fmt(m.lra)} (ffmpeg ${fmt(ff.LRA)}) TP ${fmt(m.dbtp)} dBTP (ffmpeg ${fmt(ff.TP)}) onsets/s ${fmt(m.onsetsPerS, 2)} centroid ${fmt(m.centroidHz, 0)} Hz (energy-wtd ${fmt(m.centroidEnergyHz, 0)}) dur ${fmt(m.durationS, 2)} lastOnset ${fmt(m.lastOnsetS, 2)}`); } return; }+ if (cmd === "score") { console.log(M.scoreText(M.PIECES[args[0]]())); return; }+ if (cmd === "probe") { console.log(JSON.stringify(probe(M), null, 1)); return; }+ if (cmd === "samples") {+ const dir = resolve(args[0]);+ const set = [+ { file: "piano-8s", piece: "pianoPhrase8", seconds: 8, tempo: 66, emotion: "tender" },+ { file: "piano-flat-baseline-8s", piece: "pianoPhrase8", seconds: 8, tempo: 66, flat: true, emotion: "(contrast: MIDI-flat)" },+ { file: "nocturne-45s", piece: "nocturne", seconds: 45, fit: true, emotion: "tender -> swelling -> hush" },+ { file: "sampler-musicbox-joy-8s", piece: "musicBoxJoy", seconds: 8, emotion: "joy" },+ { file: "sampler-minor-piano-melancholy-8s", piece: "minorPianoMelancholy", seconds: 8, emotion: "melancholy" },+ { file: "sampler-cinematic-awe-8s", piece: "cinematicAwe", seconds: 8, emotion: "awe" },+ { file: "sampler-chiptune-playful-8s", piece: "chiptunePlayful", seconds: 8, emotion: "playful" },+ { file: "sampler-lofi-nostalgic-8s", piece: "lofiNostalgic", seconds: 8, emotion: "nostalgic" },+ { file: "sampler-marimba-curious-8s", piece: "marimbaCurious", seconds: 8, emotion: "curious" },+ { file: "sampler-harp-tender-8s", piece: "harpTender", seconds: 8, emotion: "tender (lullaby)" },+ { file: "sampler-guitar-wistful-8s", piece: "guitarWistful", seconds: 8, emotion: "wistful" },+ { file: "sampler-celesta-wonder-8s", piece: "celestaWonder", seconds: 8, emotion: "wonder" },+ { file: "sampler-bells-epiano-hopeful-8s", piece: "bellsHopeful", seconds: 8, emotion: "hopeful" },+ { file: "sampler-drive-electronic-8s", piece: "driveElectronic", seconds: 8, emotion: "drive / energy" },+ { file: "sampler-folk-calm-8s", piece: "folkCalm", seconds: 8, emotion: "calm (pastoral)" },+ { file: "fit-theme-15s", piece: "nocturne", seconds: 15, fit: true, emotion: "tender (auto short form)" },+ { file: "fit-theme-60s", piece: "nocturne", seconds: 60, fit: true, emotion: "tender -> swelling -> hush" },+ { file: "fit-theme-180s", piece: "nocturne", seconds: 180, fit: true, emotion: "tender -> swelling -> hush", m4aOnly: true, noMasking: true },+ { file: "fixtures/ghost-fixture-HATED", piece: "ghostFixture", seconds: 35, emotion: "(hated fixture: must FAIL the ghost guard)" },+ ].filter((s) => !args[1] || s.file.includes(args[1]));+ mkdirSync(join(dir, "fixtures"), { recursive: true });+ const results = [];+ for (const s of set) {+ const { r, piece, tempo, ms, deterministic, form } = renderOne(M, s);+ const g = M.guardReport(r, SR, s.seconds, { masking: !s.noMasking });+ const wav = join(dir, s.file + ".wav"); writeWavFloat(wav, r.L, r.R);+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-c:a", "aac", "-b:a", "192k", join(dir, s.file + ".m4a")]);+ const m = M.measure(decode(wav), SR), ff = ffmpegEbu(wav), mm = M.measure(decode(join(dir, s.file + ".m4a")), SR);+ if (s.m4aOnly) unlinkSync(wav);+ const hasPiano = piece.parts.some((p) => p.inst === "piano" && p.notes.some((n) => n.role === "melody"));+ const res = { file: s.file, emotion: s.emotion, form: form ?? "as written", sections: piece.plan.sections.map((x) => x.id).join(","), guards: g, piece: piece.title, style: piece.plan.style, key: piece.plan.sections.map((x) => `${x.key} ${x.mode} (${Array.isArray(x.mood) ? x.mood.slice(0, 2).join("+") : x.mood})`).join(" / "), meter: piece.plan.meter, tempo: +tempo.toFixed(2), renderMs: ms, deterministic,+ gainDb: +r.gainDb.toFixed(2), master: r.masterMode, lufs: m.lufs, ffmpegLufs: ff.I, lra: m.lra, ffmpegLra: ff.LRA, dbtp: m.dbtp, ffmpegTp: ff.TP, samplePeakDb: m.samplePeakDb, onsetsPerS: m.onsetsPerS, dataOnsetsPerS: onsetsFromData(r) / m.durationS,+ centroidHz: m.centroidHz, centroidEnergyHz: m.centroidEnergyHz, durationS: m.durationS, lastOnsetDetectedS: m.lastOnsetS, lastOnsetDataS: r.perf.lastOnset, ...noteStats(M, piece),+ meanMelodyLeadMs: r.perf.meanLeadMs, voicingNoteDb: hasPiano ? noteVoicing(r, piece) : null, pedalChanges: piece.parts.some((p) => p.inst === "piano") && !s.flat ? r.perf.pedal.length : 0, voicingLU: hasPiano ? voicing(M, piece, tempo, s.seconds, s.flat) : null, m4a: { lufs: mm.lufs, dbtp: mm.dbtp }, problems: M.planProblems(piece),+ shortTerm: m.shortTerm.filter((_, i) => i % 10 === 0).map((x) => +x.toFixed(1)) };+ results.push(res);+ console.log(`${s.file}: LUFS ${fmt(m.lufs)} (ff ${fmt(ff.I)}) LRA ${fmt(m.lra)} (ff ${fmt(ff.LRA)}) TP ${fmt(m.dbtp)} (ff ${fmt(ff.TP)}) onsets/s ${fmt(m.onsetsPerS, 2)} [data ${fmt(res.dataOnsetsPerS, 2)}] centroid ${fmt(m.centroidHz, 0)} Hz range ${res.range} tempo ${fmt(tempo, 1)} voicing ${fmt(res.voicingLU)} LU / per-note ${fmt(res.voicingNoteDb)} dB lead ${fmt(res.meanMelodyLeadMs)} ms render ${ms} ms det ${deterministic} problems ${res.problems.length} | ghost ${g.ghost.pass ? "PASS" : "FAIL"} (${g.ghost.failures}/${g.ghost.windows}) reverb ${g.reverb.pass ? "PASS" : "FAIL"} ${fmt(g.reverb.worstDb)} dB masking ${g.masking ? `${g.masking.pass ? "PASS" : "FAIL"} ${Math.round(g.masking.shareOfBarsClear * 100)}%` : "n/a"} | form ${form ?? "-"}`);+ }+ const ref = join(here, "../../../anidoodle-research/refs/kevin-ngo-piano/film.mp4");+ const refPath = [ref, resolve(process.env.HOME ?? "", "CascadeProjects/Prompts/Claude-Skills/anidoodle-research/refs/kevin-ngo-piano/film.mp4")].find(existsSync);+ let reference = null;+ if (refPath) { const dec = decode(refPath), m = M.measure(dec, SR), ff = ffmpegEbu(refPath), gh = M.ghostCheck(dec, SR); reference = { ghost: { pass: gh.pass, failures: gh.failures, windows: gh.windows.map((w) => ({ from: w.from, onsetsPerBeat: +w.onsetsPerBeat.toFixed(2), sustainedShare: +w.sustainedShare.toFixed(2) })) }, file: "kevin-ngo-piano/film.mp4 (reference, measurement only)", lufs: m.lufs, ffmpegLufs: ff.I, lra: m.lra, ffmpegLra: ff.LRA, dbtp: m.dbtp, onsetsPerS: m.onsetsPerS, centroidHz: m.centroidHz, centroidEnergyHz: m.centroidEnergyHz, durationS: m.durationS, lastOnsetDetectedS: m.lastOnsetS, shortTerm: m.shortTerm.filter((_, i) => i % 10 === 0).map((x) => +x.toFixed(1)) };+ console.log(`REFERENCE ghost ${gh.pass ? "PASS" : "FAIL"}: LUFS ${fmt(m.lufs)} (ff ${fmt(ff.I)}) LRA ${fmt(m.lra)} (ff ${fmt(ff.LRA)}) onsets/s ${fmt(m.onsetsPerS, 2)} centroid ${fmt(m.centroidHz, 0)} (energy ${fmt(m.centroidEnergyHz, 0)})`); }+ const prev = existsSync(join(dir, "meters.json")) && args[1] ? JSON.parse(readFileSync(join(dir, "meters.json"), "utf8")) : null;+ const merged = prev ? { ...prev, results: [...prev.results.filter((x) => !results.some((y) => y.file === x.file)), ...results], reference: reference ?? prev.reference } : { generated: "tools/music.mjs samples", sampleRate: SR, results, reference, probe: probe(M) };+ writeFileSync(join(dir, "meters.json"), JSON.stringify(merged, null, 1));+ }+};++/** Piano realism probes (ADVISORY 4.1): single notes, matched loudness where it matters. */+const probe = (M) => {+ const note = (p, v, opts, dur = 3) => { const keys = [{ t: 0.05, off: dur, p, v }]; const { L, R } = M.renderPiano(keys, [], SR, Math.round((dur + 0.5) * SR), opts, 1); return [L, R]; };+ const cents = (arr) => arr;+ const vels = [0.15, 0.3, 0.5, 0.7, 0.9];+ const out = {};+ for (const [label, opts] of [["real", M.PIANO_REAL], ["flat", M.PIANO_FLAT]]) {+ const cs = vels.map((v) => M.centroid(note(60, v, opts, 1.5), SR).energyWeighted);+ const ls = vels.map((v) => M.loudness(note(60, v, opts, 1.5), SR).integrated);+ // decay: RMS in 50 ms windows of a held C4 (mf); slope early (0.1-0.6 s) vs late (2-4 s)+ const [L] = note(60, 0.6, opts, 6), w = Math.round(0.05 * SR), env = [];+ for (let a = 0; a + w < L.length; a += w) { let e = 0; for (let i = a; i < a + w; i++) e += L[i] * L[i]; env.push(10 * Math.log10(e / w + 1e-20)); }+ const slope = (t0, t1) => (env[Math.round(t1 / 0.05)] - env[Math.round(t0 / 0.05)]) / (t1 - t0);+ // beating: std-dev of the late envelope after removing the linear trend (dB)+ const late = env.slice(Math.round(2 / 0.05), Math.round(5 / 0.05)), k = late.length, mx = (k - 1) / 2, my = late.reduce((a, b) => a + b, 0) / k;+ let sxy = 0, sxx = 0; late.forEach((y, i) => { sxy += (i - mx) * (y - my); sxx += (i - mx) ** 2; }); const b1 = sxy / sxx;+ const resid = Math.sqrt(late.reduce((a, y, i) => a + (y - (my + b1 * (i - mx))) ** 2, 0) / k);+ const rank = (a) => a.map((x) => a.filter((y) => y < x).length);+ const rc = rank(cs), rv = rank(vels), n = vels.length, d2 = rc.reduce((a, r, i) => a + (r - rv[i]) ** 2, 0), rho = 1 - (6 * d2) / (n * (n * n - 1));+ out[label] = { centroidByVelocityHz: cs.map((x) => Math.round(x)), loudnessByVelocityLUFS: ls.map((x) => +x.toFixed(1)), spearmanCentroidVsVelocity: new Set(cs.map((x) => Math.round(x))).size === 1 ? "n/a (spectrum does not change with velocity)" : +rho.toFixed(2), decayEarlyDbPerS: +slope(0.1, 0.6).toFixed(1), decayLateDbPerS: +slope(2, 4).toFixed(1), lateEnvelopeWobbleDb: +resid.toFixed(2) };+ }+ out.inharmonicityB = Object.fromEntries([28, 40, 48, 60, 72, 84, 96].map((m) => [M.nameOf(m), +M.inharmonicityB(m).toExponential(2)]));+ void cents;+ return out;+};++main().catch((e) => { console.error(e); process.exit(1); });diff --git a/engine/tools/names.mjs b/engine/tools/names.mjsnew file mode 100644index 0000000..c71f98f--- /dev/null+++ b/engine/tools/names.mjs@@ -0,0 +1 @@+export const defaultOutput = (film) => `out/${film}.mp4`;diff --git a/engine/tools/record-interactive.mjs b/engine/tools/record-interactive.mjsnew file mode 100644index 0000000..bd84679--- /dev/null+++ b/engine/tools/record-interactive.mjs@@ -0,0 +1,75 @@+// RECORD, INTERACTIVE. A screen recording of a person using an interactive page, made frame-exact.+//+// node tools/record-interactive.mjs <page.html> <choreography.mjs> --out out/demo.mp4 [--fps 30] [--size 1280x800]+//+// The page's clock is replaced (window.__ANI_CLOCK__) by one this tool advances by exactly one video+// frame at a time, so the recording is the piece at 30 fps no matter how slow the screenshots are:+// what you see at 0:04.20 is tick 252, exactly. Input is real Playwright input (real pointer, key+// and wheel events, through the page's own listeners); a drawn cursor stands in for the system one,+// which screenshots never show.+//+// A choreography is `export default async (r) => { ... }` using:+// r.glide(target, frames) move the pointer to a selector's centre or {x, y}, eased, over n frames+// r.hold(frames) let time pass+// r.click(frames = 6) press, hold ~3 frames, release, then wait+// r.type(text, perChar = 3) type into whatever has focus+// r.key(name) press one key (Tab, Enter...)+// r.scroll(y, frames) scroll the window to y, eased+// r.eval(fn, arg) run something in the page+// r.box(selector) its bounding box+import { spawn } from "node:child_process";+import { mkdirSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { detect } from "./detect.mjs";++const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+const die = (m) => { console.error(`record-interactive: ${m}`); process.exit(1); };+const [pagePath, choreo] = pos; if (!pagePath || !choreo) die("usage: node tools/record-interactive.mjs <page.html> <choreography.mjs> --out out/x.mp4");+const out = resolve(opt.out ?? "out/interactive.mp4"), FPS = +(opt.fps ?? 30), [VW, VH] = (opt.size ?? "1280x800").split("x").map(Number), DPR = +(opt.dpr ?? 1.5);+const d = detect(); if (!d.pw.ok || !d.browser.ok || !d.ffmpeg.ok) die(JSON.stringify(d.report));++const browser = await d.pw.lib.chromium.launch({ executablePath: d.browser.executablePath });+const page = await browser.newPage({ viewport: { width: VW, height: VH }, deviceScaleFactor: DPR });+const errors = []; page.on("pageerror", (e) => errors.push(e.message));+await page.addInitScript(() => {+ window.__vt = 0; window.__ANI_CLOCK__ = () => window.__vt;+ addEventListener("DOMContentLoaded", () => {+ const c = document.createElement("div"); c.id = "__cursor";+ c.style.cssText = "position:fixed;left:0;top:0;width:22px;height:30px;z-index:2147483647;pointer-events:none;transform:translate(-100px,-100px);transition:none";+ c.innerHTML = '<svg width="22" height="30" viewBox="0 0 22 30"><path d="M2 2 L2 24 L8 18.5 L12.5 28 L16 26.5 L11.6 17.2 L19.5 17.2 Z" fill="#1f1a1b" stroke="#fff" stroke-width="2" stroke-linejoin="round"/></svg>';+ const ring = document.createElement("div"); ring.style.cssText = "position:fixed;left:0;top:0;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:3px solid rgba(201,86,107,.8);z-index:2147483646;pointer-events:none;opacity:0";+ document.body.append(ring, c);+ addEventListener("pointermove", (e) => { c.style.transform = `translate(${e.clientX - 2}px,${e.clientY - 2}px)`; ring.style.left = e.clientX + "px"; ring.style.top = e.clientY + "px"; }, true);+ addEventListener("pointerdown", () => { ring.style.opacity = "1"; ring.style.transform = "scale(.7)"; }, true);+ addEventListener("pointerup", () => { ring.style.opacity = "0"; ring.style.transform = "scale(1)"; }, true);+ });+});+await page.goto(pathToFileURL(resolve(pagePath)).href);+await page.evaluate(async () => { while (!window.__anidoodle?.length) await new Promise((r) => setTimeout(r, 10)); await Promise.all(window.__anidoodle.map((c) => c.ready)); });+await page.waitForTimeout(500); // let the canvas fade-in transition finish (CSS runs on real time)++mkdirSync(dirname(out), { recursive: true });+const ff = spawn(d.ffmpeg.bin, ["-y", "-loglevel", "error", "-f", "image2pipe", "-framerate", String(FPS), "-c:v", "mjpeg", "-i", "-", "-vf", `scale=${VW}:${VH}:flags=lanczos,format=yuv420p`, "-c:v", "libx264", "-preset", "slow", "-crf", "18", "-movflags", "+faststart", out], { stdio: ["pipe", "inherit", "inherit"] });+let frames = 0, mouse = { x: VW / 2, y: VH + 40 };+const frame = async () => {+ await page.evaluate((ms) => { window.__vt += ms; window.__anidoodle.forEach((c) => c.renderNow()); }, 1000 / FPS);+ const jpg = await page.screenshot({ type: "jpeg", quality: 92 }); if (!ff.stdin.write(jpg)) await new Promise((r) => ff.stdin.once("drain", r)); frames++;+};+const ease = (u) => (u < 0.5 ? 4 * u * u * u : 1 - (-2 * u + 2) ** 3 / 2);+const where = async (t) => { if (typeof t !== "string") return t; const h = await page.$(t); if (!h) die(`no element ${t}`); const b = await h.boundingBox(); return { x: b.x + b.width / 2, y: b.y + b.height / 2 }; };+const r = {+ hold: async (n) => { for (let i = 0; i < n; i++) await frame(); },+ glide: async (t, n = 24) => { const to = await where(t), from = { ...mouse }; for (let i = 1; i <= n; i++) { const u = ease(i / n); mouse = { x: from.x + (to.x - from.x) * u, y: from.y + (to.y - from.y) * u + Math.sin(u * Math.PI) * -18 }; await page.mouse.move(mouse.x, mouse.y); await frame(); } },+ click: async (n = 6) => { await page.mouse.down(); await frame(); await frame(); await frame(); await page.mouse.up(); await r.hold(n); },+ type: async (text, per = 3) => { for (const ch of text) { await page.keyboard.type(ch); await r.hold(per); } },+ key: async (k) => { await page.keyboard.press(k); await frame(); },+ scroll: async (y, n = 30) => { const y0 = await page.evaluate(() => scrollY); for (let i = 1; i <= n; i++) { await page.evaluate((v) => scrollTo(0, v), y0 + (y - y0) * ease(i / n)); await frame(); } },+ eval: (fn, arg) => page.evaluate(fn, arg), box: async (s) => (await page.$(s)).boundingBox(), page,+};+await page.mouse.move(mouse.x, mouse.y);+await (await import(pathToFileURL(resolve(choreo)).href)).default(r);+ff.stdin.end(); await new Promise((res) => ff.on("close", res));+await browser.close();+console.log(`RECORD ${out} ${frames} frames = ${(frames / FPS).toFixed(1)} s @ ${FPS} fps, ${VW}x${VH}${errors.length ? " PAGE ERRORS: " + errors.join("; ") : ""}`);diff --git a/engine/tools/registry.mjs b/engine/tools/registry.mjsnew file mode 100644index 0000000..ef578cd--- /dev/null+++ b/engine/tools/registry.mjs@@ -0,0 +1,80 @@+// REGISTRY. The style count can never go stale because nobody counts styles by hand: every new+// plate exports `STYLE` and describes itself, the eleven that predate the export are declared in+// styles.legacy.json, and this writes the merged, sorted truth to styles.gen.json and+// references/styles/INDEX.md. docs-check.mjs and gallery.mjs read the same registry, so prose,+// pictures and code cannot drift apart.+// node tools/registry.mjs+import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++export const ENGINE = resolve(dirname(fileURLToPath(import.meta.url)), "..");+export const ROOT = resolve(ENGINE, "..");+const CORE = join(ENGINE, "src/canvas-core");++// A plate declares itself with one flat literal, `export const STYLE = { id, name, family,+// medium, nearest, hero }`. A regex on the literal is enough — it has no nested braces — and it+// means a plate that does not even bundle yet still shows up in the count instead of silently+// going missing. A literal that will not evaluate is reported, not skipped.+export const loadRegistry = () => {+ const scanned = readdirSync(CORE).filter((f) => f.endsWith(".ts")).map((f) => {+ const m = readFileSync(join(CORE, f), "utf8").match(/export\s+const\s+STYLE\s*=\s*(\{[\s\S]*?\})\s*;/);+ if (!m) return null;+ let style; try { style = new Function(`return (${m[1]})`)(); } catch (e) { throw new Error(`unparseable STYLE in src/canvas-core/${f}: ${e.message}`); }+ for (const k of ["id", "name", "family", "medium", "nearest", "hero"]) if (typeof style[k] !== "string") throw new Error(`src/canvas-core/${f}: STYLE.${k} missing or not a string`);+ return { ...style, source: "scanned" };+ }).filter(Boolean);++ const legacy = JSON.parse(readFileSync(join(ENGINE, "styles.legacy.json"), "utf8")).styles.map((s) => ({ ...s, source: "legacy" }));++ const byId = new Map(), shadowed = [];+ for (const s of legacy) byId.set(s.id, s);+ // A house style (a hand matched from someone's image) or a recreation/study USES a hand; it is not a new one.+ scanned.splice(0, scanned.length, ...scanned.filter((s) => !s.house && !s.recreationOf && !s.study));+ // "<plate>Draw" is the drawing film of an existing hand, not a new hand: fold it into its parent.+ const drawOf = (s) => (s.id.endsWith("Draw") && byId.has(s.id.slice(0, -4)) ? s.id.slice(0, -4) : null);+ for (const s of scanned.filter(drawOf)) byId.set(drawOf(s), { ...byId.get(drawOf(s)), drawFilm: s.id });+ for (const s of scanned.filter((x) => !drawOf(x))) { if (byId.has(s.id)) shadowed.push(s.id); byId.set(s.id, s); } // the plate's own word replaces legacy's memory of it, whole record, `film` and all++ const styles = [...byId.values()].map(enrich).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));+ styles.shadowed = shadowed;+ return styles;+};++const enrich = (s) => {+ // The draw film is the drawing process itself: a <id>Draw.ts plate beats the plain plate, and+ // an explicit `film: null` (a hand that only lives inside a bigger film) is honoured.+ let drawFilm = null;+ const plate = join(CORE, `${s.id}.ts`), host = join(ENGINE, "src/hosts", `page-${s.id}.ts`);+ if (existsSync(join(CORE, `${s.id}Draw.ts`))) drawFilm = `${s.id}Draw`;+ else if (typeof s.film === "string") drawFilm = s.film;+ else if (s.film === null) drawFilm = null;+ else if (existsSync(plate) && existsSync(host) && new RegExp(`export const ${s.id}\\s*:\\s*Film`).test(readFileSync(plate, "utf8"))) drawFilm = s.id;+ const module = existsSync(plate) ? `engine/src/canvas-core/${s.id}.ts` : s.module ?? null;+ return { id: s.id, name: s.name, family: s.family, medium: s.medium, nearest: s.nearest, hero: s.hero, module, drawFilm, samples: `anidoodle-research/samples/${s.id}/`, source: s.source };+};++const writeOutputs = (styles) => {+ const gen = styles.map((s) => ({ id: s.id, name: s.name, family: s.family, medium: s.medium, nearest: s.nearest, hero: s.hero, module: s.module, drawFilm: s.drawFilm, samples: s.samples, source: s.source }));+ writeFileSync(join(ENGINE, "styles.gen.json"), JSON.stringify(gen, null, 2) + "\n");+ const dir = join(ROOT, "references/styles");+ const rows = styles.map((s, i) => `| ${i + 1} | ${s.name} (\`${s.id}\`) | ${s.medium} | ${s.module ? `\`${s.module}\`` : "—"} | ${s.drawFilm ? `\`engine/src/canvas-core/${s.drawFilm}.ts\`` : "—"} | \`${s.samples}\` |`);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "INDEX.md"), [+ "# Style index", "",+ "Generated by `node tools/registry.mjs` (run from `engine/`) out of `export const STYLE`",+ "blocks in `engine/src/canvas-core/` plus `engine/styles.legacy.json`. Do not edit by hand.", "",+ "| # | style | medium | hero module | draw-film module | samples |",+ "|---|---|---|---|---|---|",+ ...rows, "",+ `${styles.length} styles.`, "",+ ].join("\n"));+};++if (import.meta.url === `file://${process.argv[1]}`) {+ const styles = loadRegistry();+ writeOutputs(styles);+ for (const s of styles) console.log(` ${s.id.padEnd(14)} ${s.name.padEnd(32)} ${s.drawFilm ? "film " + s.drawFilm : "no film "}${s.source === "scanned" ? "" : " (legacy)"}`);+ if (styles.shadowed.length) console.log(` note: scanned STYLE replaced legacy record for ${styles.shadowed.join(", ")}`);+ console.log(`\n${styles.length} styles -> engine/styles.gen.json + references/styles/INDEX.md`);+}diff --git a/engine/tools/render.mjs b/engine/tools/render.mjsindex f087ce4..5d48fc8 100644--- a/engine/tools/render.mjs+++ b/engine/tools/render.mjs@@ -14,10 +14,12 @@ import { join, resolve } from "node:path";import { buildPage } from "./build-page.mjs";import { detect } from "./detect.mjs";import * as playwright from "./adapters/playwright.mjs";+import { defaultOutput } from "./names.mjs";+import { float32Wav } from "./audio.mjs";const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };const film = process.argv[2] && !process.argv[2].startsWith("--") ? process.argv[2] : "fixtures";-const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2))))), out = resolve(arg("out", `out/${film}.mp4`));+const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2))))), out = resolve(arg("out", defaultOutput(film)));const env = detect();console.log("backends found:"); for (const [k, v] of Object.entries(env.report)) console.log(` ${k.padEnd(11)} ${v}`);@@ -31,11 +33,11 @@ console.log(`film: "${meta.title}" ${meta.W}x${meta.H} @ ${meta.fps} fps, ${N} f// audio: pure JS in the page -> WAV heremkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = await session.audio(48000);-if (a) { const pcm = Buffer.from(a.pcm16, "base64"), h = Buffer.alloc(44); h.write("RIFF", 0); h.writeUInt32LE(36 + pcm.length, 4); h.write("WAVEfmt ", 8); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(2, 22); h.writeUInt32LE(a.sampleRate, 24); h.writeUInt32LE(a.sampleRate * 4, 28); h.writeUInt16LE(4, 32); h.writeUInt16LE(16, 34); h.write("data", 36); h.writeUInt32LE(pcm.length, 40); writeFileSync(wav, Buffer.concat([h, pcm])); }+if (a) writeFileSync(wav, float32Wav(a));mkdirSync(join(out, ".."), { recursive: true });const input = ["-y", "-loglevel", "error", "-f", "image2pipe", "-framerate", String(meta.fps), "-c:v", "png", "-i", "-"];-const gifFps = Math.min(meta.fps, Number(arg("gif-fps", 15))), width = Number(arg("width", Math.min(640, Math.round(meta.W * scale))));+const gifFps = Math.min(meta.fps, Number(arg("gif-fps", meta.fps))), width = Number(arg("width", Math.round(meta.W * scale)));const size = `scale=${width}:-2:flags=lanczos`;const encode = {gif: [...input, "-vf", `fps=${gifFps},${size},split[a][b];[a]palettegen=stats_mode=full[p];[b][p]paletteuse=dither=sierra2_4a`, "-loop", "0", out],@@ -62,7 +64,7 @@ console.log(` slowest: ${slow}\n budget: 150 ms draw per frame -> ${cost.everyconsole.log(` wall clock: ${wall.toFixed(1)} s for ${N} frames = ${(N / wall).toFixed(1)} fps end to end (build + launch + render + encode)`);// ---- verify: same frame, different order, different page. Standard = visually identical; hash equality is the cheap first test.-const probe = [0, 44, 45, 89, 90, N - 1].filter((n) => n < N), fwd = [], rev = [];+const probe = [...new Set([0, ...meta.shots.flatMap((s) => [s.start, s.end - 1]), ...((k) => Array.from({ length: k }, (_, i) => Math.round(i * (N - 1) / (k - 1 || 1))))(Math.min(6, N)), N - 1])].sort((a, b) => a - b), fwd = [], rev = [];for (const n of probe) fwd.push(await session.hash(n, 0)); for (const n of [...probe].reverse()) rev.unshift(await session.hash(n, session.workers - 1));const same = probe.filter((_, i) => fwd[i] === rev[i]).length;console.log(`\ndeterminism: ${same}/${probe.length} probe frames hash-identical (forward on page 0 vs reversed on page ${session.workers - 1})${same === probe.length ? "" : " -> fall back to PSNR > 45 dB in the Phase 2 gate"}`);diff --git a/engine/tools/replay.mjs b/engine/tools/replay.mjsnew file mode 100644index 0000000..b817cd9--- /dev/null+++ b/engine/tools/replay.mjs@@ -0,0 +1,190 @@+// REPLAY GATE. "A frame is a fact given its input log." This proves it for an emitted interactive page.+//+// node tools/replay.mjs <page.html> [--out report.json] [--seconds 1]+//+// 1 LIVE A real person, scripted: Playwright drives the page in REAL time with a mouse (sweeps,+// hover on every bound target, rapid in/out reversals, press and click), the keyboard+// (Tab through the targets, typing into fields), the wheel (down to the bottom and+// back), a viewport resize WHILE hovering (new DPR scale, re-bake, new rectangles), and+// the page's own setState calls. The live page hashes every 3rd frame it draws.+// 2 TOUCH The same on a touch device: taps and a swipe, no hover.+// 3 REPLAY A FRESH page gets only the recorded log. It redraws every sampled tick in REVERSE+// order, then forward, then COLD (a brand-new env: every sprite re-baked on demand), and+// each must hash exactly as the live page drew it.+// 4 PLAIN An empty log draws the untouched piece: stateAt(t, []) equals restState(t) (built+// without the reducer), the live log's tick-0 configuration changes nothing, and the+// loop closes (tick t and t + loop are the same frame).+// 5 REDUCED prefers-reduced-motion: the idle piece is still (no motion at all), and a scripted+// session still renders.+// 6 BUDGET frame time at DPR 2 on this machine, p50/p95/max, measured two ways: with the raster+// forced (software canvas, honest upper bound) and on the default canvas (JS + command+// recording only). Plus bake time, sprite memory and the bundle size, raw and gzip.+//+// Hashing needs one renderer for the whole comparison: every hashed page is opened with+// window.__ANI_RASTER__ = "cpu" (see hosts/interactive.ts). The budget pass measures both.+import { readFileSync, writeFileSync } from "node:fs";+import { resolve } from "node:path";+import { pathToFileURL } from "node:url";+import { gzipSync } from "node:zlib";+import { detect } from "./detect.mjs";++const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = ["out", "seconds"].includes(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+const die = (m) => { console.error(`replay: ${m}`); process.exit(1); };+const file = resolve(pos[0] ?? die("usage: node tools/replay.mjs <page.html> [--out report.json]"));+const url = pathToFileURL(file).href;+const d = detect(); if (!d.pw.ok || !d.browser.ok) die(`needs playwright and chromium: ${d.report.playwright}; ${d.report.browser}`);+const browser = await d.pw.lib.chromium.launch({ executablePath: d.browser.executablePath, args: ["--disable-background-timer-throttling", "--disable-renderer-backgrounding"] });++let fails = 0, checks = 0; const report = { page: file, checks: [] };+const say = (ok, label, detail = "") => { checks++; if (!ok) fails++; report.checks.push({ ok, label, detail }); console.log(` ${ok ? "PASS" : "FAIL"} ${label}${detail ? " " + detail : ""}`); };+const head = (n, t) => console.log(`\n${n}. ${t}\n${"-".repeat(64)}`);+const wait = (ms) => new Promise((r) => setTimeout(r, ms));++const open = async (ctxOpts, init = {}) => {+ const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2, ...ctxOpts });+ const page = await context.newPage(), errors = [];+ page.on("pageerror", (e) => errors.push(e.message)); page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); });+ await page.addInitScript((o) => { if (o.cpu) window.__ANI_RASTER__ = "cpu"; if (o.sample) window.__ANI_SAMPLE__ = o.sample; if (o.sync) window.__ANI_SYNC__ = true; if (o.manual) { window.__vt = 0; window.__ANI_CLOCK__ = () => window.__vt; } }, init);+ await page.goto(url);+ const readyMs = await page.evaluate(async () => { while (!window.__anidoodle?.length) await new Promise((r) => setTimeout(r, 10)); await window.__anidoodle[0].ready; return performance.now(); }); /* ms since navigation start: what a visitor waits */+ return { context, page, errors, readyMs };+};+const targetsOf = (page) => page.$$eval("[data-anidoodle]", (els) => els.map((e) => ({ name: e.getAttribute("data-anidoodle"), tag: e.tagName.toLowerCase(), type: e.getAttribute("type") ?? "" })));++// ---------------------------------------------------------------- the scripted person+const mouseSession = async (page) => {+ const center = async (sel) => { const h = await page.$(sel); if (!h) return null; await h.scrollIntoViewIfNeeded(); const b = await h.boundingBox(); return b && { x: b.x + b.width / 2, y: b.y + b.height / 2, b }; };+ for (let i = 0; i <= 24; i++) { await page.mouse.move(40 + i * 50, 60 + ((i * 97) % 600)); await wait(16); } // a sweep+ const ts = await targetsOf(page);+ for (const t of ts) {+ const sel = `[data-anidoodle="${t.name}"]`, c = await center(sel); if (!c) continue;+ await page.mouse.move(c.x, c.y, { steps: 6 }); await wait(260); // hover, settle+ for (let k = 0; k < 5; k++) { await page.mouse.move(c.b.x - 30, c.y); await wait(18); await page.mouse.move(c.x, c.y); await wait(18); } // rapid reversals+ if (t.tag === "input" || t.tag === "textarea") { await page.mouse.click(c.x, c.y); await page.keyboard.type(t.type === "email" ? "ada@" : "hello", { delay: 45 }); await wait(150); }+ else if (t.type !== "submit") { await page.mouse.down(); await wait(90); await page.mouse.up(); await wait(350); }+ }+ // a press dragged off its target is a cancel, not a click+ const first = ts.find((t) => t.tag !== "input" && t.type !== "submit"); if (first) { const c = await center(`[data-anidoodle="${first.name}"]`); if (c) { await page.mouse.move(c.x, c.y); await page.mouse.down(); await page.mouse.move(c.x + 400, c.y + 200, { steps: 4 }); await page.mouse.up(); await wait(200); } }+ // the keyboard+ await page.mouse.move(5, 5); await page.evaluate(() => document.activeElement?.blur?.());+ for (let k = 0; k < 5; k++) { await page.keyboard.press("Tab"); await wait(220); }+ await page.keyboard.press("Enter"); await wait(300);+ await page.evaluate(() => window.__anidoodle[0].play()); /* Tab can land on the piece's own pause button, and Enter then (rightly) pauses it */+ // resize WHILE hovering: new scale, a re-bake, new rectangles+ if (first) { const c = await center(`[data-anidoodle="${first.name}"]`); if (c) await page.mouse.move(c.x, c.y); }+ await page.setViewportSize({ width: 720, height: 760 }); await wait(900); /* narrow enough that every demo layout reflows and the canvas changes size */+ if (first) { const c = await center(`[data-anidoodle="${first.name}"]`); if (c) await page.mouse.move(c.x, c.y, { steps: 3 }); } await wait(300);+ await page.setViewportSize({ width: 1280, height: 800 }); await wait(900);+ // the wheel, all the way down and back+ for (let k = 0; k < 16; k++) { await page.mouse.wheel(0, 260); await wait(45); } await wait(250);+ for (let k = 0; k < 16; k++) { await page.mouse.wheel(0, -260); await wait(45); } await wait(250);+ // UI states the page might set+ for (const s of ["busy", "success", "error", "idle"]) { await page.evaluate((st) => window.__anidoodle[0].setState(st), s); await wait(260); }+ await page.mouse.move(640, 400, { steps: 8 }); await wait(400);+};+const touchSession = async (page) => {+ const ts = await targetsOf(page);+ for (const t of ts.slice(0, 4)) { const h = await page.$(`[data-anidoodle="${t.name}"]`); if (!h) continue; await h.scrollIntoViewIfNeeded(); const b = await h.boundingBox(); if (!b) continue; await page.touchscreen.tap(b.x + b.width / 2, b.y + b.height / 2); await wait(420); }+ const cv = await page.$("ani-doodle canvas, canvas"); if (cv) { await cv.scrollIntoViewIfNeeded(); const b = await cv.boundingBox(); await page.touchscreen.tap(b.x + b.width / 2, b.y + b.height * 0.6); await wait(500); }+ await page.evaluate(async () => { for (let k = 0; k < 10; k++) { scrollBy(0, 200); await new Promise((r) => setTimeout(r, 40)); } for (let k = 0; k < 10; k++) { scrollBy(0, -200); await new Promise((r) => setTimeout(r, 40)); } }); await wait(400);+};+const record = async (ctxOpts, session, label) => {+ const s = await open(ctxOpts, { cpu: true, sample: 3 });+ await session(s.page);+ const r = await s.page.evaluate(() => { const c = window.__anidoodle[0]; c.pause(); return { log: c.log(), samples: c.samples(), stats: c.stats() }; });+ await s.context.close();+ const kinds = [...new Set(r.log.map((e) => e.type))].sort(), scales = [...new Set(r.samples.map((x) => x.scale))];+ console.log(` ${label}: ${r.log.length} events (${kinds.join(", ")}), ${r.samples.length} frames hashed live at scale ${scales.join(" + ")}, last tick ${r.log.at(-1)?.tick}`);+ say(s.errors.length === 0, `${label}: the page ran clean`, s.errors.slice(0, 2).join("; "));+ return { ...r, kinds, scales };+};++// ---------------------------------------------------------------- 1 + 2: live+head(1, "LIVE a scripted person, in real time, on a DPR 2 laptop viewport");+const live = await record({}, mouseSession, "mouse+keyboard");+{ const bound = live.log.some((e) => e.type === "rect"), need = bound ? ["enter", "exit", "down", "up", "cancel", "focus", "move", "rect", "view", "state"] : ["move", "view", "state", "scroll"];+ say(need.every((k) => live.kinds.includes(k)), bound ? "the log saw hover, press, click, cancel, keyboard focus, geometry, scale and state" : "no bound targets on this page: the log saw pointer, scale, state and scroll", live.kinds.join(" ")); }+{ const views = [...new Set(live.log.filter((e) => e.type === "view").map((e) => e.value))];+ say(views.length > 1, "the viewport resize changed the device scale mid-session, and the piece re-baked and swapped", `view scales ${views.join(" -> ")}; frames hashed live at ${live.scales.join(" + ")}`); }+say(live.samples.length >= 150, "the live session drew enough frames to mean something", `${live.samples.length} hashed (every 3rd drawn), last tick ${live.log.at(-1)?.tick}`);+head(2, "TOUCH taps and a swipe on a touch screen");+const touch = await record({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 }, deviceScaleFactor: 3 }, touchSession, "touch");+say(touch.log.some((e) => e.type === "move" && e.value === "touch") && touch.kinds.includes("leave"), "touch is logged as touch, and a lifted finger leaves no hover behind", touch.kinds.join(" "));++// ---------------------------------------------------------------- 3: replay+head(3, "REPLAY a fresh page, the log alone: reversed, forward, and cold");+const replay = async (rec, ctxOpts, label) => {+ const s = await open(ctxOpts, { cpu: true, manual: true });+ const out = await s.page.evaluate(({ log, samples }) => {+ const c = window.__anidoodle[0]; c.pause();+ const draw = (x, cold) => { c.render(x.tick, log, x.scale, cold); return c.hash(); };+ const rev = [...samples].reverse().map((x) => draw(x, false)), fwd = samples.map((x) => draw(x, false));+ const coldIdx = samples.map((_, i) => i).filter((i) => i % Math.max(1, Math.floor(samples.length / 12)) === 0), cold = coldIdx.map((i) => draw(samples[i], true));+ return { rev: rev.reverse(), fwd, cold, coldIdx };+ }, rec);+ await s.context.close();+ const n = rec.samples.length, bad = (arr, idx) => arr.map((h, i) => (h === rec.samples[idx ? idx[i] : i].hash ? null : rec.samples[idx ? idx[i] : i].tick)).filter((x) => x !== null);+ const distinct = new Set(rec.samples.map((x) => x.hash)).size;+ say(distinct > n / 4, `${label}: the sampled frames are genuinely different frames`, `${distinct} distinct of ${n}`);+ const r = bad(out.rev), f = bad(out.fwd), c = bad(out.cold, out.coldIdx);+ say(r.length === 0, `${label}: ${n} live frames, replayed in REVERSE, hash identical`, r.length ? `differ at ticks ${r.slice(0, 8).join(", ")}` : "");+ say(f.length === 0, `${label}: and forward`, f.length ? `differ at ticks ${f.slice(0, 8).join(", ")}` : "");+ say(c.length === 0, `${label}: and ${out.cold.length} of them COLD (fresh env, every sprite re-baked)`, c.length ? `differ at ticks ${c.slice(0, 8).join(", ")}` : "");+};+await replay(live, {}, "mouse+keyboard");+await replay(touch, { hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 }, deviceScaleFactor: 3 }, "touch");++// ---------------------------------------------------------------- 4: plain loop+head(4, "PLAIN no input is the plain loop");+{+ const s = await open({}, { cpu: true, manual: true });+ const r = await s.page.evaluate((cfg) => {+ const c = window.__anidoodle[0]; c.pause(); const L = c.piece.meta.loop, ticks = [0, 1, 7, 59, 131, 240, L - 1].filter((t) => t < L), out = [];+ for (const t of ticks) { c.render(t, []); const a = c.hash(); c.renderRest(t); const b = c.hash(); c.render(t, cfg); const g = c.hash(); c.render(t + L, []); const e = c.hash(); out.push({ t, a, b, g, e }); }+ return { L, out, distinct: new Set(out.map((o) => o.a)).size };+ }, live.log.filter((e) => e.tick === 0 && ["motion", "view", "rect", "scroll"].includes(e.type) && !(e.type === "scroll" && e.value !== 0)));+ await s.context.close();+ say(r.out.every((o) => o.a === o.b), "stateAt(t, []) draws exactly restState(t), built without the reducer", `${r.out.length} ticks`);+ say(r.out.every((o) => o.a === o.g), "the live page's tick-0 configuration (rects, scale, motion) changes nothing untouched");+ say(r.out.every((o) => o.a === o.e), `the loop closes: tick t and t + ${r.L} are the same frame`);+ say(r.distinct > 1, "and the untouched piece moves (no dead air)", `${r.distinct} distinct frames of ${r.out.length}`);+}++// ---------------------------------------------------------------- 5: reduced motion+head(5, "REDUCED prefers-reduced-motion");+{+ const s = await open({ reducedMotion: "reduce" }, { cpu: true, sample: 2 });+ await s.page.mouse.move(100, 100, { steps: 4 }); await wait(120);+ const r = await s.page.evaluate(() => { const c = window.__anidoodle[0]; const log = c.log(); c.pause(); const hs = [0, 30, 97, 233].map((t) => { c.render(t, log.filter((e) => e.tick === 0)); return c.hash(); }); return { motion: log.find((e) => e.type === "motion")?.value, hs }; });+ const t0 = Date.now(); await mouseSession(s.page).catch((e) => s.errors.push(String(e))); const secs = (Date.now() - t0) / 1000;+ await s.context.close();+ say(r.motion === "reduce", "the preference reached the log", `motion = ${r.motion}`);+ say(new Set(r.hs).size === 1, "untouched, the piece is still: four ticks, one frame", r.hs.join(" "));+ say(s.errors.length === 0, "a full scripted session renders with reduced motion", `${secs.toFixed(1)} s, ${s.errors.slice(0, 2).join("; ") || "no error"}`);+}++// ---------------------------------------------------------------- 6: budget+head(6, "BUDGET DPR 2, this machine, headless Chromium");+{+ const html = readFileSync(file, "utf8"), m = html.match(/<script type="module">([\s\S]*?)<\/script>/), js = m ? m[1] : "";+ const kb = (n) => (n / 1024).toFixed(1) + " KB";+ const perf = async (init, label) => {+ const s = await open({}, init); await mouseSession(s.page);+ const st = await s.page.evaluate(() => window.__anidoodle[0].stats()); await s.context.close();+ console.log(` ${label.padEnd(44)} p50 ${String(st.p50).padStart(5)} ms p95 ${String(st.p95).padStart(5)} ms max ${String(st.max).padStart(6)} ms (${st.frames} frames)`);+ return { ...st, readyMs: Math.round(s.readyMs) };+ };+ const forced = await perf({ cpu: true, sync: true }, "raster forced (software canvas), per frame");+ const gpu = await perf({}, "default canvas, JS + command recording");+ report.budget = { forced, gpu, moduleBytes: Buffer.byteLength(js), moduleGzip: gzipSync(js).length, pageBytes: Buffer.byteLength(html), pageGzip: gzipSync(html).length };+ console.log(` startup: ready in ${forced.readyMs} ms (bake ${forced.bakeMs} ms, ${forced.sprites} sprites, ${forced.spriteMB} MB of sprites at scale ${forced.scale})`);+ console.log(` bundle: module ${kb(report.budget.moduleBytes)} (${kb(report.budget.moduleGzip)} gzip), whole page ${kb(report.budget.pageBytes)} (${kb(report.budget.pageGzip)} gzip)`);+ say(forced.p95 <= 6, "p95 frame time at DPR 2 is at or under 6 ms with the raster forced", `${forced.p95} ms`);+}++await browser.close();+report.pass = fails === 0; report.summary = `${checks - fails}/${checks}`;+if (opt.out) writeFileSync(resolve(opt.out), JSON.stringify(report, null, 1));+console.log(`\n${"=".repeat(64)}\nREPLAY: ${fails ? `FAIL ${fails} of ${checks} checks failed` : `PASS ${checks}/${checks} checks`} ${file}`);+process.exit(fails ? 1 : 0);diff --git a/engine/tools/scaffold.mjs b/engine/tools/scaffold.mjsindex c8009ae..ee4e64f 100644--- a/engine/tools/scaffold.mjs+++ b/engine/tools/scaffold.mjs@@ -1,6 +1,6 @@// SCAFFOLD. Turn the skill's engine into a working project: a still, a film, or both.//-// node <skill>/engine/tools/scaffold.mjs <dir> [--still myPicture] [--film myFilm] [--example]+// node <skill>/engine/tools/scaffold.mjs <dir> [--still myPicture] [--film myFilm] [--duration seconds] [--size WxH | --format 9x16] [--fps N] [--bpm N] [--example]//// The engine ships as parts, not as a project: `engine/src` holds the portable art core and the// one page host, `example/src` holds the worked butterfly. A film needs them in ONE tree, because@@ -20,14 +20,24 @@ const HERE = dirname(fileURLToPath(import.meta.url));const ENGINE = resolve(HERE, "..");const SKILL = resolve(ENGINE, "..");-const VAL = new Set(["film", "still"]);+const VAL = new Set(["film", "still", "duration", "size", "format", "fps", "bpm"]);const pos = [], opt = {};for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }const die = (m) => { console.error(`scaffold: ${m}`); process.exit(1); };-const target = resolve(pos[0] ?? die("usage: node tools/scaffold.mjs <dir> [--still myPicture] [--film myFilm] [--example]"));+const target = resolve(pos[0] ?? die("usage: node tools/scaffold.mjs <dir> [--still name] [--film name] [--duration seconds] [--size WxH | --format 1x1|9x16|16x9|4x5] [--fps N] [--bpm N] [--example]"));const name = (flag) => { const v = opt[flag] && opt[flag] !== true ? String(opt[flag]) : null; if (v && !/^[a-zA-Z][a-zA-Z0-9]*$/.test(v)) die(`--${flag} '${v}' must be a bare identifier: it becomes a module name and an export name`); return v; };const film = name("film"), still = name("still");if (film && still && film === still) die("--film and --still need different names");+const formats = { "1x1": [1080, 1080], "9x16": [1080, 1920], "16x9": [1920, 1080], "4x5": [1080, 1350] };+if (opt.format && !formats[opt.format]) die("--format must be 1x1, 9x16, 16x9 or 4x5");+if (opt.size && opt.format) die("choose --size or --format");+const size = opt.size ? String(opt.size).match(/^(\d+)x(\d+)$/i)?.slice(1).map(Number) : formats[opt.format ?? "1x1"];+if (!size || size.some((x) => !Number.isSafeInteger(x) || x < 2)) die("--size must be positive WxH dimensions");+const fps = Number(opt.fps ?? 30), bpm = Number(opt.bpm ?? 60), duration = Number(opt.duration ?? 8);+if (!Number.isSafeInteger(fps) || fps < 1) die("--fps must be a positive integer");+if (!Number.isFinite(bpm) || bpm <= 0 || !Number.isInteger(60 * fps / bpm)) die("--bpm must give a whole-frame beat at this fps");+if (!Number.isFinite(duration) || duration <= 0 || !Number.isSafeInteger(Math.round(duration * fps))) die("--duration must be positive seconds with a finite frame count");+const durationFrames = Math.max(1, Math.round(duration * fps));mkdirSync(target, { recursive: true });cpSync(join(ENGINE, "src"), join(target, "src"), { recursive: true });@@ -49,8 +59,7 @@ if (film) {writeFileSync(mod, `import { Ctx, Env, rng } from "./core";import { Film } from "./film";-// 120 bpm at 30 fps is a 15-frame beat. Cuts land on multiples of 15, events on multiples of 5.-const FPS = 30, BPM = 120, BEAT = (60 / BPM) * FPS, DURATION = BEAT * 32;+const FPS = ${fps}, BPM = ${bpm}, DURATION = ${durationFrames};const draw = (ctx: Ctx, local: number, env: Env) => {const W = env.W * env.scale, H = env.H * env.scale, r = rng(1);@@ -68,10 +77,10 @@ const draw = (ctx: Ctx, local: number, env: Env) => {};export const ${film}: Film = {- meta: { title: "${film}", W: 1080, H: 1080, fps: FPS, bpm: BPM, durationFrames: DURATION },+ meta: { title: "${film}", W: ${size[0]}, H: ${size[1]}, fps: FPS, bpm: BPM, durationFrames: DURATION },assets: { images: {} },shots: [{ id: "one", start: 0, end: DURATION, draw }],- // audio: (sampleRate) => [left, right], // see references/music-recipe.md before writing a note+ // audio: (sampleRate) => [left, right], // see references/music/README.md before writing a note};`);writeFileSync(join(target, "src/hosts", `page-${film}.ts`), `import { ${film} } from "../canvas-core/${film}";\nimport { mountFilm } from "./page";\nmountFilm(${film});\n`);@@ -103,6 +112,8 @@ export const draw${still[0].toUpperCase() + still.slice(1)} = (ctx: Ctx, _frame:const g = new Gfx(ctx, env, 0, PENCIL);ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);ctx.fillStyle = "#fbf6ec"; ctx.fillRect(0, 0, env.W, env.H);+ const fit = Math.min(env.W, env.H) / 1080;+ g.push((env.W - 1080 * fit) / 2, (env.H - 1080 * fit) / 2, fit);// 1. the cast shadow first, so the fruit sits ON the table and never floats over itg.group("paint", () => g.wash(oval(600, 772, 190, 34, 16), "#a79db8", { seed: 3, alpha: 0.42, dx: 0, dy: 0, shrink: 1 }));@@ -120,13 +131,14 @@ export const draw${still[0].toUpperCase() + still.slice(1)} = (ctx: Ctx, _frame:g.pen(LEAF, { seed: 13, closed: true, w: 0.9, opacity: 0.55, boil: 0 });g.pen(line([536, 270], [660, 230], -6), { seed: 14, w: 0.6, opacity: 0.45, boil: 0, retrace: false });});+ g.pop();// 4. the sheet itself, over everythingg.paper("paper", 0.12);g.paper("coldpress", 0.18);};export const ${still}: Film = {- meta: { title: "${still}", W: 1080, H: 1080, fps: 30, bpm: 120, durationFrames: 1 },+ meta: { title: "${still}", W: ${size[0]}, H: ${size[1]}, fps: ${fps}, bpm: ${bpm}, durationFrames: 1 },assets: { images: {} },shots: [{ id: "${still}", start: 0, end: 1, draw: draw${still[0].toUpperCase() + still.slice(1)} }],};@@ -138,5 +150,5 @@ const tree = (dir, depth = 0) => readdirSync(dir, { withFileTypes: true }).filteconsole.log(`scaffolded ${target}\n${tree(target)}\n`);console.log(`next:\n cd ${target}\n npm install`);if (still) console.log(` node tools/still.mjs ${still} --out out/${still}.png # the picture; --scale 2 for print size`);-if (film) console.log(` node tools/still.mjs ${film} --out out/look.png # the ONE look still\n node tools/gate.mjs ${film} --mp4 out/${film.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase()}.mp4`);+if (film) console.log(` node tools/still.mjs ${film} --out out/look.png\n node tools/gate.mjs ${film}`);if (opt.example) console.log(` node tools/gate.mjs mechanicalLepidoptera --mp4 out/mechanical-lepidoptera.mp4 # the worked example`);diff --git a/engine/tools/style-media.json b/engine/tools/style-media.jsonnew file mode 100644index 0000000..1e838cf--- /dev/null+++ b/engine/tools/style-media.json@@ -0,0 +1,24 @@+{+ "ranunculus": { "module": "ranunculus.ts", "medium": "pencil & watercolour: washes that miss their outline, graphite over paint" },+ "koi": { "module": "koi.ts", "medium": "marker comic: flat cel fills, hard shadow edge, heavy contour" },+ "pocketWatch": { "module": "pocketWatch.ts", "medium": "ballpoint: one biro, tone from where hatching sits" },+ "balloon": { "module": "balloon.ts", "medium": "crayon: scribble fills that skip the paper's valleys" },+ "wren": { "module": "wren.ts", "medium": "ink & line-wash: washes first, then a flexible nib" },+ "moonPhases": { "module": "moonPhases.ts", "medium": "chalkboard: side-of-chalk scumble on a dark board" },+ "fox": { "module": "fox.ts", "medium": "cut-paper collage: torn pieces, no drawn line" },+ "lighthouse": { "module": "lighthouse.ts", "medium": "risograph: one drum per ink, halftone, overprint" },+ "mellan": { "module": "mellan.ts", "medium": "single-line engraving: one spiral, width = tone" },+ "storybook": { "module": "storybook.ts", "medium": "storybook pencil + watercolour character" },+ "blueprint": { "module": "blueprint.ts", "medium": "cyanotype blueprint: ruling pen on blue" },+ "brokenColour": { "module": "brokenColour.ts", "medium": "broken-colour pastel: separate dabs, optical mixing" },+ "charcoalErasure": { "module": "charcoalErasure.ts", "medium": "charcoal with eraser drawing: lights lifted out" },+ "colouredPencil": { "module": "colouredPencil.ts", "medium": "coloured pencil: one-direction hatching on toothy cream paper" },+ "embroidery": { "module": "embroidery.ts", "medium": "embroidery: stitches on linen" },+ "flatVector": { "module": "flatVector.ts", "medium": "flat vector: geometric fills, no texture" },+ "midCentury": { "module": "midCentury.ts", "medium": "mid-century print: flat shapes, offset, grain" },+ "paperCraft": { "module": "paperCraft.ts", "medium": "paper craft: folded, layered card with depth shadows" },+ "rubberHose": { "module": "rubberHose.ts", "medium": "1930s rubber-hose cartoon: ink line, flat fills" },+ "scrapbook": { "module": "scrapbook.ts", "medium": "vintage scrapbook: torn paper cards, tape, engravings, stamped type" },+ "sumiE": { "module": "sumiE.ts", "medium": "sumi-e: loaded brush, wet-in-wet ink" },+ "halftone": { "module": "halftone.ts", "medium": "halftone print: dot screens" }+}diff --git a/engine/tools/style-signatures.json b/engine/tools/style-signatures.jsonnew file mode 100644index 0000000..9d54d26--- /dev/null+++ b/engine/tools/style-signatures.json@@ -0,0 +1,423 @@+{+ "note": "features measured by analyze-style.mjs --calibrate on each plate's own rendered still; subject and composition are baked into these numbers, so treat the match as a hint",+ "plates": {+ "balloon": {+ "module": "engine/src/canvas-core/balloon.ts",+ "medium": "crayon: scribble fills that skip the paper's valleys",+ "source": "balloonDraw-still.png",+ "sha256": "a1169bd2bece29be0093612953e7d8495776519e0a05ea5a759f65b7eb2a2acc",+ "features": {+ "linePresence": 0.0521,+ "hard": 0.47,+ "pooledRim": 0.44,+ "coherence": 0.65,+ "peakShare": 0.68,+ "speckleLight": 0.139,+ "chroma": 0.101,+ "paperL": 0.84,+ "contrast": 0.48,+ "colours": 8,+ "halftone": 0+ }+ },+ "blueprint": {+ "module": "engine/src/canvas-core/blueprint.ts",+ "medium": "cyanotype blueprint: ruling pen on blue",+ "source": "blueprint-still.png",+ "sha256": "00c6654ca813e01a286638bd853268b6ed56fdbf067b8541bd58c54548f5a4c0",+ "features": {+ "linePresence": 0.0076,+ "hard": 0.79,+ "pooledRim": 0.15,+ "coherence": 0.71,+ "peakShare": 0.47,+ "speckleLight": 0.044,+ "chroma": 0.051,+ "paperL": 0.3,+ "contrast": 0.38,+ "colours": 6,+ "halftone": 0+ }+ },+ "brokenColour": {+ "module": "engine/src/canvas-core/brokenColour.ts",+ "medium": "broken-colour pastel: separate dabs, optical mixing",+ "source": "brokenColour-still.png",+ "sha256": "27b749839a6e9ae84d327844df0da7d160648e4fe9fd2fc041caf55f8a2658cd",+ "features": {+ "linePresence": 0.0221,+ "hard": 0.31,+ "pooledRim": 0.35,+ "coherence": 0.6,+ "peakShare": 0.69,+ "speckleLight": 0.046,+ "chroma": 0.063,+ "paperL": 0.73,+ "contrast": 0.32,+ "colours": 8,+ "halftone": 0+ }+ },+ "charcoalErasure": {+ "module": "engine/src/canvas-core/charcoalErasure.ts",+ "medium": "charcoal with eraser drawing: lights lifted out",+ "source": "charcoalErasure-still.png",+ "sha256": "ac36ecec415e1f67ad407cc099364337bd234975d694b7511e9b1812e0909ab5",+ "features": {+ "linePresence": 0.038,+ "hard": 0.33,+ "pooledRim": 0.36,+ "coherence": 0.15,+ "peakShare": 0.26,+ "speckleLight": 0.043,+ "chroma": 0.015,+ "paperL": 0.7,+ "contrast": 0.35,+ "colours": 7,+ "halftone": 0+ }+ },+ "colouredPencil": {+ "module": "engine/src/canvas-core/colouredPencil.ts",+ "medium": "coloured pencil: one-direction hatching on toothy cream paper",+ "source": "colouredPencil-still.png",+ "sha256": "0860945b292f44f392e411a5d4f14f7705c4590e21e7db519e5558bf4c80e3a2",+ "features": {+ "linePresence": 0.1299,+ "hard": 0.54,+ "pooledRim": 0.45,+ "coherence": 0.68,+ "peakShare": 0.81,+ "speckleLight": 0.051,+ "chroma": 0.04,+ "paperL": 0.92,+ "contrast": 0.49,+ "colours": 8,+ "halftone": 0+ }+ },+ "embroidery": {+ "module": "engine/src/canvas-core/embroidery.ts",+ "medium": "embroidery: stitches on linen",+ "source": "embroidery-still.png",+ "sha256": "b2b5bc1630f8f29bbe82e4820511dc5158e8188942162ea0142c67c2bcbd7aed",+ "features": {+ "linePresence": 0.1237,+ "hard": 0.37,+ "pooledRim": 0.35,+ "coherence": 0.06,+ "peakShare": 0.52,+ "speckleLight": 0.542,+ "chroma": 0.039,+ "paperL": 0.74,+ "contrast": 0.35,+ "colours": 7,+ "halftone": 0+ }+ },+ "flatVector": {+ "module": "engine/src/canvas-core/flatVector.ts",+ "medium": "flat vector: geometric fills, no texture",+ "source": "flatVector-still.png",+ "sha256": "5687a56b660b2beda5f58172d665ecfce448a8134d48356037515909df91016c",+ "features": {+ "linePresence": 0.0161,+ "hard": 0.25,+ "pooledRim": 0.19,+ "coherence": 0.69,+ "peakShare": 0.66,+ "speckleLight": 0.012,+ "chroma": 0.077,+ "paperL": 0.93,+ "contrast": 0.54,+ "colours": 6,+ "halftone": 1+ }+ },+ "fox": {+ "module": "engine/src/canvas-core/fox.ts",+ "medium": "cut-paper collage: torn pieces, no drawn line",+ "source": "foxDraw-still.png",+ "sha256": "a9623300d4391305bed288967943b01cbc39952d6ab738ae9c8e748471a452c9",+ "features": {+ "linePresence": 0.0186,+ "hard": 0.68,+ "pooledRim": 0.18,+ "coherence": 0.64,+ "peakShare": 0.45,+ "speckleLight": 0.005,+ "chroma": 0.074,+ "paperL": 0.88,+ "contrast": 0.51,+ "colours": 8,+ "halftone": 0+ }+ },+ "halftone": {+ "module": "engine/src/canvas-core/halftone.ts",+ "medium": "halftone print: dot screens",+ "source": "halftone-still.png",+ "sha256": "92498c0fb7e1b2c9c8f1c34d69cb5697b2eb2d970e1fbf0191197756d08fae2f",+ "features": {+ "linePresence": 0.2998,+ "hard": 0.31,+ "pooledRim": 0.28,+ "coherence": 0.07,+ "peakShare": 0.35,+ "speckleLight": 0.339,+ "chroma": 0.031,+ "paperL": 0.89,+ "contrast": 0.71,+ "colours": 8,+ "halftone": 1+ }+ },+ "koi": {+ "module": "engine/src/canvas-core/koi.ts",+ "medium": "marker comic: flat cel fills, hard shadow edge, heavy contour",+ "source": "koiDraw-still.png",+ "sha256": "32daa1034d5b873877503b9d8c3ee4ce3222abae8d9f084f8d145f47b218af4c",+ "features": {+ "linePresence": 0.0415,+ "hard": 0.55,+ "pooledRim": 0.44,+ "coherence": 0.8,+ "peakShare": 0.33,+ "speckleLight": 0.024,+ "chroma": 0.085,+ "paperL": 0.52,+ "contrast": 0.66,+ "colours": 8,+ "halftone": 0+ }+ },+ "lighthouse": {+ "module": "engine/src/canvas-core/lighthouse.ts",+ "medium": "risograph: one drum per ink, halftone, overprint",+ "source": "lighthouse-still.png",+ "sha256": "8b53ab98fe2b9638da3a0af2d7740b579570180e83f59e03a513188cbf4f616b",+ "features": {+ "linePresence": 0.1989,+ "hard": 0.6,+ "pooledRim": 0.24,+ "coherence": 0.04,+ "peakShare": 0.29,+ "speckleLight": 0.407,+ "chroma": 0.085,+ "paperL": 0.79,+ "contrast": 0.47,+ "colours": 8,+ "halftone": 1+ }+ },+ "mellan": {+ "module": "engine/src/canvas-core/mellan.ts",+ "medium": "single-line engraving: one spiral, width = tone",+ "source": "mellan-still.png",+ "sha256": "0ce1fd502c013a31d6e64b3741e4a5808c0cd44701f08d061f4cbfadef9b02a9",+ "features": {+ "linePresence": 0.4032,+ "hard": 0.38,+ "pooledRim": 0.08,+ "coherence": 0.91,+ "peakShare": 0.44,+ "speckleLight": 0.605,+ "chroma": 0.015,+ "paperL": 0.94,+ "contrast": 0.75,+ "colours": 8,+ "halftone": 0+ }+ },+ "midCentury": {+ "module": "engine/src/canvas-core/midCentury.ts",+ "medium": "mid-century print: flat shapes, offset, grain",+ "source": "midCentury-still.png",+ "sha256": "0a1b231048d9e97c3cedf3661d531054e7c15051406159dd33059b760e173c0d",+ "features": {+ "linePresence": 0.0243,+ "hard": 0.39,+ "pooledRim": 0.35,+ "coherence": 0.44,+ "peakShare": 0.35,+ "speckleLight": 0.008,+ "chroma": 0.097,+ "paperL": 0.89,+ "contrast": 0.41,+ "colours": 7,+ "halftone": 0+ }+ },+ "moonPhases": {+ "module": "engine/src/canvas-core/moonPhases.ts",+ "medium": "chalkboard: side-of-chalk scumble on a dark board",+ "source": "moonPhasesDraw-still.png",+ "sha256": "43b7d735ecb7622a3f63fd0157789c593fa375d89c511346deb99a867a3ca2bd",+ "features": {+ "linePresence": 0.0324,+ "hard": 0.48,+ "pooledRim": 0.23,+ "coherence": 0.59,+ "peakShare": 0.38,+ "speckleLight": 0.011,+ "chroma": 0.031,+ "paperL": 0.8,+ "contrast": 0.47,+ "colours": 8,+ "halftone": 0+ }+ },+ "paperCraft": {+ "module": "engine/src/canvas-core/paperCraft.ts",+ "medium": "paper craft: folded, layered card with depth shadows",+ "source": "paperCraft-still.png",+ "sha256": "2e97c54d9b679437fa3aa6c505adce425368984147576cf5e7107da7a258f10c",+ "features": {+ "linePresence": 0.0323,+ "hard": 0.5,+ "pooledRim": 0.37,+ "coherence": 0.46,+ "peakShare": 0.45,+ "speckleLight": 0.037,+ "chroma": 0.067,+ "paperL": 0.66,+ "contrast": 0.37,+ "colours": 8,+ "halftone": 1+ }+ },+ "pocketWatch": {+ "module": "engine/src/canvas-core/pocketWatch.ts",+ "medium": "ballpoint: one biro, tone from where hatching sits",+ "source": "pocketWatchDraw-still.png",+ "sha256": "30670dad2ef8e75aa43414e682dead964436c0075001a938a8e93266fa9a9b1c",+ "features": {+ "linePresence": 0.0422,+ "hard": 0.65,+ "pooledRim": 0.38,+ "coherence": 0.53,+ "peakShare": 0.5,+ "speckleLight": 0.015,+ "chroma": 0.041,+ "paperL": 0.95,+ "contrast": 0.22,+ "colours": 4,+ "halftone": 0+ }+ },+ "ranunculus": {+ "module": "engine/src/canvas-core/ranunculus.ts",+ "medium": "pencil & watercolour: washes that miss their outline, graphite over paint",+ "source": "ranunculusDraw-still.png",+ "sha256": "051671d1121ee02cafb9a9ae88703deffa275576ccb2ba164351eef064124e3e",+ "features": {+ "linePresence": 0.0143,+ "hard": 0.51,+ "pooledRim": 0.6,+ "coherence": 0.31,+ "peakShare": 0.27,+ "speckleLight": 0.002,+ "chroma": 0.051,+ "paperL": 0.93,+ "contrast": 0.25,+ "colours": 5,+ "halftone": 0+ }+ },+ "rubberHose": {+ "module": "engine/src/canvas-core/rubberHose.ts",+ "medium": "1930s rubber-hose cartoon: ink line, flat fills",+ "source": "rubberHose-still.png",+ "sha256": "e77fe78b6ee1b32c58e8c875bd1a43fa2006fdd17a82ddaa9fd4d121ff1feb00",+ "features": {+ "linePresence": 0.0764,+ "hard": 0.54,+ "pooledRim": 0.48,+ "coherence": 0.56,+ "peakShare": 0.42,+ "speckleLight": 0.088,+ "chroma": 0.031,+ "paperL": 0.8,+ "contrast": 0.63,+ "colours": 8,+ "halftone": 0+ }+ },+ "scrapbook": {+ "module": "engine/src/canvas-core/scrapbook.ts",+ "medium": "vintage scrapbook: torn paper cards, tape, engravings, stamped type",+ "source": "scrapbook-still.png",+ "sha256": "56b3979ad6846cc8e2cc7301adda2c0d732713e9658b8a20b249c07cae3bca25",+ "features": {+ "linePresence": 0.0643,+ "hard": 0.59,+ "pooledRim": 0.46,+ "coherence": 0.54,+ "peakShare": 0.38,+ "speckleLight": 0.028,+ "chroma": 0.04,+ "paperL": 0.85,+ "contrast": 0.41,+ "colours": 5,+ "halftone": 1+ }+ },+ "storybook": {+ "module": "engine/src/canvas-core/storybook.ts",+ "medium": "storybook pencil + watercolour character",+ "source": "storybookDraw-still.png",+ "sha256": "f3ceba63f6a1e09939bc2b181cc14006bda777b20e1de32d4b3fcfe53f9c71a1",+ "features": {+ "linePresence": 0.0513,+ "hard": 0.5,+ "pooledRim": 0.64,+ "coherence": 0.41,+ "peakShare": 0.31,+ "speckleLight": 0.025,+ "chroma": 0.037,+ "paperL": 0.9,+ "contrast": 0.55,+ "colours": 6,+ "halftone": 0+ }+ },+ "sumiE": {+ "module": "engine/src/canvas-core/sumiE.ts",+ "medium": "sumi-e: loaded brush, wet-in-wet ink",+ "source": "sumiE-still.png",+ "sha256": "be1ee20bbdc6249e855de3aef280eb046201d971bf174ddddf6d4824249f841b",+ "features": {+ "linePresence": 0.0225,+ "hard": 0.3,+ "pooledRim": 0.42,+ "coherence": 0.64,+ "peakShare": 0.25,+ "speckleLight": 0.013,+ "chroma": 0.01,+ "paperL": 0.92,+ "contrast": 0.62,+ "colours": 2,+ "halftone": 0+ }+ },+ "wren": {+ "module": "engine/src/canvas-core/wren.ts",+ "medium": "ink & line-wash: washes first, then a flexible nib",+ "source": "wren-still.png",+ "sha256": "6d432d1e8e447e5f103443e821144353876b46988c3929b07dba081713e59ef4",+ "features": {+ "linePresence": 0.0208,+ "hard": 0.3,+ "pooledRim": 0.48,+ "coherence": 0.31,+ "peakShare": 0.35,+ "speckleLight": 0.006,+ "chroma": 0.022,+ "paperL": 0.93,+ "contrast": 0.38,+ "colours": 5,+ "halftone": 0+ }+ }+ }+}\ No newline at end of filediff --git a/engine/tools/verify-frame-adapter.mjs b/engine/tools/verify-frame-adapter.mjsindex 01c85c3..7c9683d 100644--- a/engine/tools/verify-frame-adapter.mjs+++ b/engine/tools/verify-frame-adapter.mjs@@ -45,11 +45,12 @@ say(Number.isFinite(dur) && dur > 0 && Number.isInteger(dur), "getDurationFramessay(dur === built.meta.durationFrames, "it agrees with the film", `${dur} vs ${built.meta.durationFrames}`);const seek = async (n) => page.evaluate((f) => { window.__hfAdapter.seekFrame(f); return window.FILM.hash(); }, n);-const order = [0, 900, 45, 1409, 300, 1409, 45, 0, 900, 300]; // forward, backward and random, with repeats+const points = [...new Set([0, Math.round(dur / 5), Math.round(dur / 2), Math.round(dur * 4 / 5), dur - 1])];+const order = [...points, ...points.slice().reverse()];const seen = new Map(), mismatch = [];for (const n of order) { const h = await seek(n); if (seen.has(n) && seen.get(n) !== h) mismatch.push(n); seen.set(n, h); }say(mismatch.length === 0, "the same frame gives the same state however it is reached", mismatch.length ? `drifted at ${mismatch.join(", ")}` : `${order.length} seeks, ${seen.size} distinct frames, forward + backward + random`);-say(new Set(seen.values()).size === seen.size, "different frames are genuinely different pixels", `${new Set(seen.values()).size}/${seen.size} distinct hashes`);+say(dur === 1 || new Set(seen.values()).size > 1, "the film has distinct pixels across sampled frames", `${new Set(seen.values()).size}/${seen.size} distinct hashes`);say(errs.length === 0, "no page error while seeking", errs.slice(0, 2).join("; ") || "none");// The real proof: a seek-driven hash must equal what the plain player draws cold for that frame.diff --git a/references/anatomy.md b/references/anatomy.mdnew file mode 100644index 0000000..6e93245--- /dev/null+++ b/references/anatomy.md@@ -0,0 +1,92 @@+# Human anatomy in code++> Structure first, marks last: the rule `butterfly/alive/anatomy.ts` applied to a wing, applied to+> a person. A human drawn from outlines is the road-sign icon of a human. A human built from a+> skeleton, volumes and a camera gets foreshortening, overlap, contact and balance for free, and+> gets every one of them checkable. Code: `engine/src/canvas-core/character/human/`.++**The scar.** The first mannequin we built had arms hanging in a gap beside a box torso: a+wooden doll. Its hands were rakes, its thumb left the wrist as a stick, its pinch never closed, a+nine-year-old's shins were 16% short, and a 37-degree ankle bend and a 46-degree hip slipped into+poses we "tuned by eye". The checks below caught the last four. The eye caught the first three.+You need both.++## The pipeline++| Layer | File | What it owns |+|---|---|---|+| Canon | `canon.ts` | landmark heights in head units per canon ROW (adult 7.5, storybook child 5.2 declared over a real 6.2); heads-by-age and eye-line-by-age tables |+| Skeleton | `skeleton.ts` | bone lengths from the canon; forward kinematics; joint limits and cones; **a pose outside them throws at load** |+| Mannequin | `mannequin.ts` | ribcage egg, pelvis bowl, shoulder girdle, limbs as chains of ellipsoids with muscle profiles |+| Head | `head.ts` | Loomis ball + jaw; features placed ON the face surface; eleven expression parameters |+| Hands | `hands.ts` | 5 digits, 14 phalanges, knuckle arc, thumb from the wrist with thenar mass, pose library, solved pinch |+| Balance, reach | `balance.ts` | centre of mass (Winter segment masses) inside the support polygon; analytic leg IK; numeric reach; contrapposto |+| Walk | `walk.ts` | a walk from footsteps: heel, ankle and forefoot rockers, swing arcs, pelvis bob and counter-rotation |+| Clothing | `clothing.ts` | garments are inflated body blobs cut to length; they turn and swing with the body |++A body part is a UNION of convex polygons (a limb is its blob chain swept pairwise), projected+through a pinhole camera with a real focal length. The outline is every boundary point not inside+a sibling polygon, minus seams where a part grows out of its parent: so an elbow has no seam, but a+forearm crossing its own upper arm still gets its overlap line.++**Mannequin is the checker, not the look (in progress).** Rendering those volumes literally reads as+a mannequin. The drawing layer (`character/design.ts`) keeps the rig as pose source and checker and+draws designed sweeps over it: a gesture curve through the joints, an authored section table, the+silhouette perpendicular to the curve. Mira's clothing and Theo the baker (`characters/theo/baker.ts`,+coloured pencil) use it. Still open: sleeve caps and forearms read tubular, clothing drape from contact+points is partial, anatomical landmarks are not yet expressed as contour breaks on the drawn layer.++## Canon (checked, not asserted)++- Heads tall by age (Loomis): 1 y 4, 3 y 5, 6 y 5.75, 8 y 6, 9 y 6.2, 12 y 7, adult 7.5, heroic 8.+- Eye line: half the head in adults, lower in children (0.44 at nine, 0.38 at one).+- Adult: crotch at half height, elbow at the waist, wrist at the crotch, hand = face, foot = forearm.+- Every canon: limb segments as fractions of (body) height from Winter's anthropometric table:+ upper arm 18.6%, forearm 14.6%, hand 10.8%, thigh 24.5%, shank 24.6%, foot 15.2%, within 16%.+- A stylised canon is a declared row. The storybook child enlarges the head 1.19x and is measured+ against the body height a real 6.2-head child of her height would have.++## Joints++Ranges (AAOS / Norkin & White, rounded): elbow 0-150, knee 0-140, hip flexion -20..125 but only 95+with the knee straight (hamstrings), ankle -45..25, neck total rotation 80, fingers MCP -20..90, PIP+0..110, DIP -5..80. Wrist, neck and shoulder are CONES (an ellipse of combined motion), not boxes.+Anything that solves a pose (leg IK, reach, the walk) either stays inside or throws; an ankle at its+limit lifts the heel instead of folding further, which is what a real heel does.++## Hands, the known weak spot++- Knuckles on an ARC (middle furthest from the wrist, little finger well back); fingers in length+ order middle > ring >= index > little; a web of skin a third of the way up the fingers.+- The thumb's metacarpal is buried in the thenar eminence: the visible thumb leaves the palm at its+ MCP, not the wrist. At rest it lies alongside the index, pointing down and forward.+- Contact is SOLVED, never typed: the pinch pulls thumb pad onto index pad; a grip pulls every+ finger joint onto the cylinder it holds (none inside it); a wave turns the forearm until the palm+ faces the lens.+- Nails on the dorsal face of the distal phalanx, drawn only when that face turns to the camera.++## Poses from reference, built like a teacher builds them++Name the reference you opened (Loomis, Hogarth, Williams, Perry and Burnfield are cited in the+files). Place the feet, solve the legs, carry the centre of mass over the support, send each hand+to a target. Contrapposto: weight foot near the midline, pelvis drops on the free side, shoulders+tilt against it. Tiptoe: toes bend flat to the floor and the mass goes over the balls. A seated+figure's support includes the seat.++## The look-at-it list (no check proves these)++Render the figure sheet and look, at full size, for: arms that hang in a gap (missing shoulder+girdle); rake hands; a thumb from the wrist; a face that turns but whose far eye does not narrow;+a hand that covers the face; a pinch that does not meet; feet that float or sink; a coat that sits+on the lap like a plate; a pointed finger that does not read as aimed. Each of those shipped in a+draft of our figure sheet and was caught only by eye. See `samples/characters/ANATOMY-CRITIQUE.md`+for the ones still open.++## Gate++`node tools/character-check.mjs` : canon ratios, limits for every library pose, bone lengths+constant, left/right symmetry, five digits in length order with the knuckle arc, pinch contact,+balance, feet on (not through) the floor, identity per view, palette hue families per hand, and+for a film the planted feet (no slide over 4 mm a frame). Then its negative twins, each of which+must fail: elbow 170, knee backwards, wrist outside its cone, straight-leg kick, finger bent back,+owl neck, a figure toppling, a blue coat, missing glasses.diff --git a/references/craft-bar.md b/references/craft-bar.mdnew file mode 100644index 0000000..583ffa7--- /dev/null+++ b/references/craft-bar.md@@ -0,0 +1,46 @@+# The craft bar++The test: would a proud human illustrator ship this, or is it mechanical shape-assembly?++| The tell | What passes |+|---|---|+| 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 |+| 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 |+| Gradient sky, disc sun, oval bokeh | Granulating wash, sun as paper left light, lost edges |+| Decoration | Every element has a one-line reason or it is not drawn |+| A row of style vignettes (film) | One arc. The medium changes only when the STORY changes state |+| Things fade or scale in | Marks are MADE, in the order a hand makes them |+| Both sides do the same thing at once | One side leads, by a few frames, never half a cycle |+| A hold | The camera may creep. The subject never stops |+| People with rubber joints, mitten hands, floating feet | A canon (heads tall for the age), joints within their limits, five fingers where seen, weight over the feet (`anatomy.md`) |+| The same character drawn differently shot to shot | One character module; shots pose it, never redraw it (`workflows/character-consistency.md`) |+| A silhouette filled with texture, no mouth line, no toes | Interior contours: mouth, eyelids, nostrils, toes, joins between forms (the detail pass below) |+| A drawing film where the finished picture fades in | Marks made in the medium's order; the last frames are the still (`workflows/drawing-process.md`) |++**No dead air** in anything that moves: something visibly changes in every second, from frame 0.+Check it with the tool AND by eye: a creeping camera changes every pixel and satisfies the tool+while the eye sees a still.+++## The detail pass (run it on every piece before showing it)++A silhouette filled with texture is not a drawing. Before any still, recreation or character is+shown, crop into it at full size and check the interior, because that is where a viewer looks:++- **Faces**: the mouth line and the split of the upper lip, the chin, the nose's outline and+ nostrils, both eyelids and the inner corner of the eye, brow markings, the ear's inner rim.+- **Hands, paws and feet**: every finger or toe separated, knuckles and pads where they show, nails+ or claws, the way the foot meets the ground (contact shadow, weight).+- **Joins between forms**: where a leg meets the body, where an arm crosses the chest, where cloth+ folds at a joint. These are contour lines inside the silhouette, thinner than the outline and+ broken where light hits.+- **Markings and pattern**: stripes, spots, seams and patches follow the form's surface, not the+ picture plane.+- **Recreations from a photo**: trace each of the above from the photo and overlay-check it; tone+ alone never supplies interior lines.++Each medium says it its own way (a carved keyblock line, a scratched cut, a pencil accent, a darker+brick), but none of them may leave it out.diff --git a/references/formats.md b/references/formats.mdindex 921b117..c56fe15 100644--- a/references/formats.md+++ b/references/formats.md@@ -45,7 +45,7 @@ the craft table, then show it.## Films: the story ones30 to 90 seconds, a transformation, a score, the full workflow in `SKILL.md`, the doctrine in-`storytelling.md`, `music-recipe.md` and `working-method.md`. `example/` is the worked one.+`storytelling.md`, `music/README.md` and `working-method.md`. `example/` is the worked one.## Deliveringdiff --git a/references/music/README.md b/references/music/README.mdnew file mode 100644index 0000000..7811b5f--- /dev/null+++ b/references/music/README.md@@ -0,0 +1,198 @@+# Music: composed as data, synthesized in code, measured, then heard once++Every score in anidoodle is **100 % procedural**: you write the notes as data, the engine performs+and synthesizes them in code. No samples, no recordings, no licensed audio, ever. You cannot hear+what you make, so every choice is a number, every number is measured, and a human hears 8 seconds+before anything ships.++Code: `engine/src/canvas-core/music/`. Tool: `engine/tools/music.mjs`. The old music-box recipe+lives on, verbatim, as the default style preset: [`styles/music-box.md`](styles/music-box.md).++## The pipeline++```+MusicPlan + notes (you write) -> perform -> instruments (one stem per part) -> room -> master -> [L, R]+ plan.ts, pieces/*.ts perform.ts piano.ts, instruments.ts dsp.ts render.ts+```++1. **Plan** (`plan.ts`, `tables.ts`, `theory.ts`). A `Piece` = a `MusicPlan` + parts of notes + the+ harmony list.+ - The plan names:+ - one **style**;+ - a tempo and a meter (3/4, 4/4, 6/8, 12/8);+ - **sections**, each with a mood (or a blend `[a, b, w]`), a key and mode, the melody types,+ a dynamic level `[start, end]` 0..1, and an ending;+ - `repeatable` / `optional` / `pickup` / `variations` flags, which let it fit any length.+ - Notes are written in a bar-checked notation. A bar that doesn't add up to the meter throws:+ ```ts+ line(3, "C5:2 Bb4:.5 Ab4:.5 | Bb4:2 Eb4:1 | [Ab1 Eb2 Ab2]:[email protected]", { role: "melody", bpb: 3 })+ ```+ - Roles: `melody`, `inner`, `bass`, `accomp`, `color`, `drum`.+ - Generators may draft. **You compose**:+ - real harmony and voice-leading;+ - a memorable motif and phrases that ask and answer;+ - cadences.+2. **Perform** (`perform.ts`). Beats become seconds and written velocities become played ones. This+ is where "MIDI" stops. For piano:+ - voicing: the melody sits 6-10 dB over the rest;+ - a phrase arch in both dynamics and tempo;+ - the melody leads by 10-30 ms, and chords spread;+ - legato overlap on melody keys;+ - pedal changes just after each harmony change;+ - a kinematic final ritard and a breath before a sudden hush;+ - humanize from `rng(seed)`, smoothed so it correlates across a phrase.++ Parts with `opts.grid` (music box, chiptune, drive) stay mechanical on purpose.+3. **Synthesize.** Each part is an instrument:++ | Instrument | How it's made |+ |---|---|+ | `piano` | Modal, physics-shaped: inharmonic partials, 2-3 detuned strings with two-stage decay, velocity-dependent hammer brightness and strike comb, knock, soundboard modes, dampers, sustain pedal with sympathetic strings, stereo by pitch. See ADVISORY 4.1. |+ | `musicBox`, `bell` | The recipe's numbers |+ | `celesta`, `marimba`, `vibes` | Modal bars |+ | `harp`, `guitar` | Extended Karplus-Strong |+ | `strings` | Detuned PolyBLEP saws, slow bow, delayed vibrato |+ | `fmBell`, `ePiano` | 2-operator FM |+ | `pulse`, `triangle`, `noiseDrum` | NES-style chip voices |+ | `kick`, `snare`, `hat`, `bass`, `vinyl` | Drums, bass and texture |+4. **Room.** The style chooses it:+ - music box: one reflection, no tail;+ - nocturne and lullaby: a small room;+ - cinematic and drive: a hall;+ - chiptune: nothing.+5. **Master.**+ - **Gentle styles:** one static gain to **-16 LUFS**, true peak <= -1 dBTP, never a compressor.+ If the peak blocks the gain, the loudness goes down. The cure is musical (see "Peaks" below).+ - **Dense styles** (chiptune, lo-fi, drive): **-14 LUFS** through a look-ahead true-peak limiter.++A film's `audio` is `filmAudio(piece, seconds)`, which returns `(sampleRate) => [L, R]` at exactly+the film's length. `engine/src/canvas-core/score.ts` is the scaffold example.++## Any length, never hard-coded++`fitToDuration(piece, seconds)` tries every form:+- with some `optional` sections dropped (dropping music costs more than nudging the tempo);+- with the `repeatable` group restated 0..n times, as "A B A B" or "A A B" (restatements take the+ section's `variations`: `octaveDouble`, `octaveUp`, `thin`);+- at the tempo that lands the last note at `seconds - tail`, inside the style's tempo range.++It picks the form whose tempo is closest to the written one. If no full form fits, it falls back to+the piece's `shortForm`. A section's `pickup` travels with it: wherever a section lands, its own+upbeat leads into it.++Example: the nocturne "Window Light" gives+- the short form (the 8-second phrase, restated) at 15 s;+- the full piece at 45 s;+- intro, theme, theme (in octaves), build, coda at 60 s;+- six theme/climax cycles with rotating variations at 180 s.++## Styles (11) and moods (15)++Both are rows of numbers in `tables.ts`. A brief names rows, never adjectives. Each row stays+`unconfirmed` until a human has listened to 8 seconds of it; the listener's words then go into+`confirmedBy`.++| Style | Tempo, meter | Natural moods | Master |+|---|---|---|---|+| musicBox (default) | 110-130, 12/8 | joy, curious, tender, playful, wistful | gentle |+| nocturne (piano) | 50-72, 3/4 or 6/8 | tender, melancholy, wistful, romantic | gentle |+| cinematic | 60-120 | awe, triumph, melancholy, tension, hopeful | gentle |+| lullaby | 60-75, 3/4 or 6/8 | tender, calm | gentle |+| folk | 80-120, 6/8, 3/4, 4/4 | calm, wistful, joy, nostalgic | gentle |+| minimalist | 100-140 | curious, tension, awe | gentle |+| jazz | 90-180, swing | playful, nostalgic, romantic, curious | gentle |+| ambient | 50-80 | awe, calm, dread (highest ghost risk) | gentle |+| chiptune | 120-160 | joy, playful, drive, tension | dense |+| lofi | 70-90, swing 55-62 % | nostalgic, calm, wistful | dense |+| drive | 110-140 | drive, triumph, tension, awe | dense |++Moods: joy, playful, tender, wistful, melancholy, hopeful, curious, tension, dread, awe, triumph,+drive, calm, nostalgic, romantic.+- Each row has columns for:+ - modes and tempo;+ - harmonic rhythm and lead register;+ - onsets per beat and attack;+ - the target LRA and brightness;+ - instrument families and melody types.+- Compatible blends interpolate.+- Refused blends: joy + dread, playful + grief, calm + tension. Use consecutive sections instead.+- Big swings must land on a sync point.++## Keys and modes (13)++major, aeolian, harmonic minor, melodic minor, dorian, phrygian, lydian, mixolydian, major+pentatonic, minor pentatonic, blues, whole-tone, locrian. Intervals, colour notes, uses and+per-mode guards are in `theory.ts`.+- **A mode must be heard.** State its colour note early: dorian's natural 6, lydian's #4,+ mixolydian's b7. Otherwise it reads as plain major or minor.+- **The mode must match the mood.** A mode the film didn't intend reads as the wrong emotion (the+ butterfly scar: meant sunny, heard "sad and eerie"). `planProblems` checks each section's+ declared key and mode against its notes.++Melody types (9): arpeggio, stepwise, hook, ostinato, drone, call and response, counter-melody,+sequence, theme transformation.++## How to plan a score++1. **Spot the film.** Find its 3-5 true sync points, and an arc per section (for example tender, then+ swelling, then a sudden hush at about 2/3, then a soft close).+2. **Pick one style.** Give each section a mood, a key and a mode.+3. **Write the motif first.** A 2-5 note cell with its own rhythm. Then build the harmony under it,+ with voice-leading by step. Then the phrases:+ - the question ends off the tonic;+ - the answer ends on it, straight away;+ - the high point falls in the second half of the phrase.+4. **Arrange.** Add density, not length (more notes, never longer notes). Let the motif return:+ transformed, at the climax, and at the close.+5. **Print the score and meter it:**+ ```+ node tools/music.mjs score <piece>+ node tools/music.mjs render <piece> out.wav --seconds 45 --fit+ ```+6. **8 seconds to a human.** Include the most important mood change.++**Peaks are a composing problem.** Octaves in both hands landing on one downbeat make a true peak+that caps a gentle master. Fix it in the notes:+- stagger the bass by an eighth;+- spread the climax over a rolled chord;+- don't double the climax note.++Never fix it with a compressor.++## The guards (`guards.ts`): sad is allowed, formless is not++| Guard | Rule | Where it runs |+|---|---|---|+| **ghost** | Per window (4 bars, or 8 s when the tempo is unknown), FAIL only if ALL of these hold: onsets < 1 per beat, sustained-energy share > 60 %, reverb tail within 12 dB of dry, and no cadence. The window is exempt if it is a declared breath. | Bare audio too. On a reference file, unknown reverb and cadence count against it. |+| **reverb** | The late tail sits >= 10 dB under the dry mix in every bar. | Rendered pieces |+| **masking** | While the melody sounds, its 500 Hz-4 kHz band beats every other role by >= 3 dB in >= 80 % of bars. | Rendered pieces, per-role stems |+| **plan** | The declared mode matches the notes; no close thirds below C3 in the piano. | Note data |++How the ghost guard measures:+- "Sustained" means 50 ms frames that aren't decaying like a struck note (falling slower than+ 6 dB/s) and aren't just after an onset.+- Onsets come from loudness-normalised spectral flux with an absolute floor of 4.0. Real note starts+ in the loved reference sit at 8-62; a detuned pad's beating sits at 2-3.4.++**Calibration** (`node tools/music.mjs samples`, see the samples' METERS.md):++| File | Onsets per window | Sustained share | Ghost |+|---|---|---|---|+| Loved Kevin Ngo piano (audio only) | 1.00-1.88 | 0.26-0.45 | PASSES |+| Hated ghost fixture (`pieces/fixtures.ts`: slow pad, 5 s tail, drifting maj7 chords, no cadence) | 0.00 | 0.79-0.90 | FAILS every window |++The fixture also fails reverb (+8 dB) and masking (0 %). A guard ships only if every loved piece+passes it and every hated piece fails it.++Brightness is reported, never gated: the loved piano's centroid is ~600 Hz.++## The 8-second human listen++Meters prove we aren't obviously wrong. Only an ear says right.+- **Per film:** one 8-second sample before scoring. It contains the most important mood change.+- **First use of a style, a family or a mood row:** 8 seconds of it, once. The listener's words are+ stored in the row.+- **Mismatch rule:** if the listener names a different emotion from the one declared, the row is+ wrong, not the listener. Change the numbers, re-measure, re-listen.+- **Honesty rule:** passing meters is not a timbre or emotion claim. If no human listened, the+ delivery says so.diff --git a/references/music-recipe.md b/references/music/styles/music-box.mdsimilarity index 90%rename from references/music-recipe.mdrename to references/music/styles/music-box.mdindex 3c9f1ff..8bfba70 100644--- a/references/music-recipe.md+++ b/references/music/styles/music-box.md@@ -1,3 +1,13 @@+# Style preset: music-box (the default)++> The original anidoodle music recipe, kept **verbatim** below as one style preset among the eleven+> in `engine/src/canvas-core/music/tables.ts` (`STYLES.musicBox`). Its numbers are what the+> `musicBox` and `bell` instruments implement. Its ban list is now the rule for THIS preset only;+> for every other style the bans became measured guards (see `../README.md`, "Guards"). The scar+> story is kept because it is why the guards exist.++---+# The music recipe> Doctrine earned making MECHANICAL LEPIDOPTERA, the worked example in `example/`. Every rulediff --git a/references/styles/INDEX.md b/references/styles/INDEX.mdnew file mode 100644index 0000000..75644ce--- /dev/null+++ b/references/styles/INDEX.md@@ -0,0 +1,40 @@+# Style index++Generated by `node tools/registry.mjs` (run from `engine/`) out of `export const STYLE`+blocks in `engine/src/canvas-core/` plus `engine/styles.legacy.json`. Do not edit by hand.++| # | style | medium | hero module | draw-film module | samples |+|---|---|---|---|---|---|+| 1 | Crayon (`balloon`) | wax crayon on toothed paper: back-and-forth scribble fills that skip the valleys, a darker crayon on the shade side, a white one burnishing the highlight, a fat contour gone over twice | `engine/src/canvas-core/balloon.ts` | `engine/src/canvas-core/balloonDraw.ts` | `anidoodle-research/samples/balloon/` |+| 2 | Cyanotype blueprint (`blueprint`) | ruling pen and spring-bow compass in white ink on Prussian-blue cyanotype stock | `engine/src/canvas-core/blueprint.ts` | `engine/src/canvas-core/blueprint.ts` | `anidoodle-research/samples/blueprint/` |+| 3 | Broken colour (`brokenColour`) | opaque oil dabs from a loaded flat hog brush on primed linen, unmixed colours side by side for the eye to mix | `engine/src/canvas-core/brokenColour.ts` | `engine/src/canvas-core/brokenColour.ts` | `anidoodle-research/samples/brokenColour/` |+| 4 | Charcoal, erased and redrawn (`charcoalErasure`) | vine and compressed charcoal on heavy rag paper, stumped, lifted with a kneaded eraser, redrawn over its own residue | `engine/src/canvas-core/charcoalErasure.ts` | `engine/src/canvas-core/charcoalErasure.ts` | `anidoodle-research/samples/charcoalErasure/` |+| 5 | Coloured pencil (`colouredPencil`) | wax coloured pencils hatched in one diagonal on toothy cream cartridge paper, hues layered, darks cross-hatched | `engine/src/canvas-core/colouredPencil.ts` | `engine/src/canvas-core/colouredPencil.ts` | `anidoodle-research/samples/colouredPencil/` |+| 6 | Hand embroidery (`embroidery`) | stranded cotton floss stitched through natural plain-weave linen in a beech hoop | `engine/src/canvas-core/embroidery.ts` | `engine/src/canvas-core/embroidery.ts` | `anidoodle-research/samples/embroidery/` |+| 7 | Flat vector (`flatVector`) | pen-tool paths in a vector app, flat fills that land when a path closes, long-shadow shapes with a transparency ramp, a raster grain brush over the shade sides | `engine/src/canvas-core/flatVector.ts` | `engine/src/canvas-core/flatVector.ts` | `anidoodle-research/samples/flatVector/` |+| 8 | Folk-tale storybook (`folkTale`) | gouache and watercolour over an HB pencil drawing on cream cartridge: opaque, dry-brushed paint in the foreground thinning to a pale wash and then to bare pencil in the distance | `engine/src/canvas-core/folkTale.ts` | `engine/src/canvas-core/folkTale.ts` | `anidoodle-research/samples/folkTale/` |+| 9 | Cut-paper collage (`fox`) | zero drawn lines: torn pieces with a white fibrous edge, scissor pieces crisp, each lifting a soft shadow off the piece below | `engine/src/canvas-core/fox.ts` | `engine/src/canvas-core/foxDraw.ts` | `anidoodle-research/samples/fox/` |+| 10 | Newsprint halftone (`halftone`) | web-offset newspaper print: black on a 45 degree AM screen plus one orange spot at 15 degrees, oil ink gaining into unbleached groundwood newsprint | `engine/src/canvas-core/halftone.ts` | `engine/src/canvas-core/halftone.ts` | `anidoodle-research/samples/halftone/` |+| 11 | Isometric cutaway (`isometric`) | flat vector planes on a true 2:1 isometric grid, three tones per material, crisp edges, pen-tool order | `engine/src/canvas-core/isometric.ts` | `engine/src/canvas-core/isometric.ts` | `anidoodle-research/samples/isometric/` |+| 12 | Marker comic (`koi`) | alcohol-marker cel fills with a hard shadow edge under one heavy contour that thickens away from the light | `engine/src/canvas-core/koi.ts` | `engine/src/canvas-core/koiDraw.ts` | `anidoodle-research/samples/koi/` |+| 13 | Risograph (`lighthouse`) | soy ink, one layer per drum multiplied through its own registration offset; every other colour an overprint, tone a halftone screen per ink angle, white is bare paper | `engine/src/canvas-core/lighthouse.ts` | `engine/src/canvas-core/lighthouseDraw.ts` | `anidoodle-research/samples/lighthouse/` |+| 14 | Low-poly (`lowPoly`) | triangle meshes projected by hand through a pinhole camera, each facet flat-shaded by its normal against one low sun, painter-sorted far to near; no 3D engine | `engine/src/canvas-core/lowPoly.ts` | `engine/src/canvas-core/lowPoly.ts` | `anidoodle-research/samples/lowPoly/` |+| 15 | Single-line engraving (`mellan`) | one unbroken engraved line whose width follows a procedural tone field: the whole picture is a single stroke | `engine/src/canvas-core/mellan.ts` | `engine/src/canvas-core/mellanUnspool.ts` | `anidoodle-research/samples/mellan/` |+| 16 | Mid-century gouache (`midCentury`) | opaque matte designer's gouache on warm illustration board, a dry brush dragged over the flats, a loose brush-and-ink line printed off register | `engine/src/canvas-core/midCentury.ts` | `engine/src/canvas-core/midCentury.ts` | `anidoodle-research/samples/midCentury/` |+| 17 | Chalkboard (`moonPhases`) | side-of-the-chalk scumble on a slate board, lit limbs worked twice, every stroke broken by the board's tooth with dust either side, ghosts of old lessons | `engine/src/canvas-core/moonPhases.ts` | `engine/src/canvas-core/moonPhasesDraw.ts` | `anidoodle-research/samples/moonPhases/` |+| 18 | Oil on canvas (`paintedOil`) | opaque oil paint with hog-bristle brushes on a toned linen canvas, lean block-in to fat impasto | `engine/src/canvas-core/paintedOil.ts` | `engine/src/canvas-core/paintedOil.ts` | `anidoodle-research/samples/paintedOil/` |+| 19 | Toy-theatre paper collage (`paperCraft`) | a cardboard toy theatre: patterned and sugar papers cut and torn, gouache-painted cut-outs with a white sticker margin, every piece with a card edge and a gap to the flat behind | `engine/src/canvas-core/paperCraft.ts` | `engine/src/canvas-core/paperCraft.ts` | `anidoodle-research/samples/paperCraft/` |+| 20 | Pixel art (`pixelArt`) | a 120x120 grid of cells, each one of 16 declared palette colours, laid one cell at a time and blown up by a whole number, no smoothing | `engine/src/canvas-core/pixelArt.ts` | `engine/src/canvas-core/pixelArt.ts` | `anidoodle-research/samples/pixelArt/` |+| 21 | Ballpoint sketch (`pocketWatch`) | one blue ballpoint on cream cartridge, near-constant weight; tone only from where the hatching sits, plus the blob where a firm stroke stops | `engine/src/canvas-core/pocketWatch.ts` | `engine/src/canvas-core/pocketWatchDraw.ts` | `anidoodle-research/samples/pocketWatch/` |+| 22 | Pencil & watercolour (`ranunculus`) | graphite and pan watercolour on cold-press: washes that never quite fill their outline, form shaded toward one light, graphite over the paint | `engine/src/canvas-core/ranunculus.ts` | `engine/src/canvas-core/ranunculusDraw.ts` | `anidoodle-research/samples/ranunculus/` |+| 23 | Rubber hose (`rubberHose`) | India ink at one pressure on a clear cel over a blue-pencil rough, flat grey paint on the back, photographed and printed on black-and-white film | `engine/src/canvas-core/rubberHose.ts` | `engine/src/canvas-core/rubberHose.ts` | `anidoodle-research/samples/rubberHose/` |+| 24 | Archival scrapbook (`scrapbook`) | foxed rag-paper album page; torn cards, cellulose tape, a clothespin on twine; copperplate engravings hand-tinted; typewriter, ransom-note cut letters, red pen, rubber stamp | `engine/src/canvas-core/scrapbook.ts` | `engine/src/canvas-core/scrapbook.ts` | `anidoodle-research/samples/scrapbook/` |+| 25 | Scratchboard (`scratchboard`) | white china clay under black India ink; every mark is ink scraped away with a knife or scratch nib | `engine/src/canvas-core/scratchboard.ts` | `engine/src/canvas-core/scratchboard.ts` | `anidoodle-research/samples/scratchboard/` |+| 26 | Pen-and-ink stipple (`stipple`) | one 0.25 mm technical pen dotted straight down onto hot-press bristol; tone is dot density only | `engine/src/canvas-core/stipple.ts` | `engine/src/canvas-core/stipple.ts` | `anidoodle-research/samples/stipple/` |+| 27 | Storybook pencil + watercolour (`storybook`) | storybook graphite and gentle pan watercolour, drawn for a recurring character | `engine/src/canvas-core/storybook.ts` | `engine/src/canvas-core/storybookDraw.ts` | `anidoodle-research/samples/storybook/` |+| 28 | Sumi-e ink painting (`sumiE`) | one loaded soft brush of sumi ink, five dilutions, on unsized absorbent xuan paper, with a cinnabar seal | `engine/src/canvas-core/sumiE.ts` | `engine/src/canvas-core/sumiE.ts` | `anidoodle-research/samples/sumiE/` |+| 29 | Toy brick (`toyBrick`) | moulded ABS toy bricks, rendered flat-plastic in orthographic view: face tones by the cube rule, bevel highlights, seam hairlines, real studs, a soft ground shadow | `engine/src/canvas-core/toyBrick.ts` | `engine/src/canvas-core/toyBrick.ts` | `anidoodle-research/samples/toyBrick/` |+| 30 | Ukiyo-e colour woodblock (`woodcut`) | water-based pigment printed by baren from hand-carved cherry blocks onto damp kozo washi: a sumi keyblock, flat colour blocks, bokashi wipes | `engine/src/canvas-core/woodcut.ts` | `engine/src/canvas-core/woodcut.ts` | `anidoodle-research/samples/woodcut/` |+| 31 | Ink & line-wash (`wren`) | wet washes first that flood past the line and settle along each shape's bottom edge, backruns, then a flexible nib thick on the press and hair-thin on the lift | `engine/src/canvas-core/wren.ts` | `engine/src/canvas-core/wrenDraw.ts` | `anidoodle-research/samples/wren/` |++31 styles.diff --git a/references/styles/blueprint.md b/references/styles/blueprint.mdnew file mode 100644index 0000000..749cfb2--- /dev/null+++ b/references/styles/blueprint.md@@ -0,0 +1,50 @@+# Cyanotype blueprint (`blueprint.ts`, kit in `blueprintKit.ts`)++**Medium, physically.** A ruling pen and a spring-bow compass loaded with white ink on+Prussian-blue cyanotype stock. The stock never exposed evenly: brighter where the arc lamp+stood, mottled (`blueMottle`), two old fold lines, dust. The ink breaks up on the tooth of the+sheet (`draftTooth`) and white on blue blooms, so every line gets a faint halo (`inkGroup`).++**The marks.** Ruled lines that are never dead straight (a 0.6 px bow, seeded). Compass circles+that ARE true round (`circle`: the compass does not wobble, the freehand does). Chain lines,+long dash then short dash, for centres and pitch circles (`chain`, `chainRing`). Section lining+at 45 degrees that starts and stops just inside each part (`hatch`), adjacent parts lined in+opposing directions, thin sections filled solid, shafts and pinions never sectioned. Filled+arrowheads. Single-stroke inclined gothic capitals from `drafting.ts`; dimension figures read+from the bottom of the sheet (unidirectional).++**Edge.** A thin, even pen line with a slight taper where the nib lifts. No tone except section+lining. No light and no cast shadow: an orthographic drawing has none, and faking one breaks the+medium.++**Line hierarchy.** Visible outlines heavy white (1.4 to 1.9); section lining, pitch circles,+dimensions and leaders thin cyan (0.75 to 1); construction and projection lines thinner, dim+cyan, left on the sheet as real drafting leaves them.++**Order of marks.** Bare sheet. Border ruled stroke by stroke, then zone marks. Title-block box+ruled (early). Construction: centre lines, line of centres, pitch circles swung, projection lines+dropped, datum lines across. Ruling-pen outlines: the plate, then each wheel from the top of the+stack down, rim and teeth first, crossings window by window, each pinion before the wheel it+rides on (a lower wheel is clipped by the METAL of every part above it, never by its+crossings). Section outlines, then section lining. Details. Dimensions (witness lines, dimension+line, arrows, figure). Tables, notes, balloons. The title-block lettering last, the title itself+the very last stroke.++**Palette.** Ground `#123a63`, white ink `#f1f7fb`, cyan `#a7d8ec`, dim `#7fbcd8`.++**Not its nearest neighbour (pocketWatch, ballpoint).** Ballpoint builds TONE from where hatch+sits on a lit form; the blueprint has no light at all, and its only tone is a convention+(section lining). Ballpoint lines are freehand and continuous; here circles are compass-true,+lines are ruled, and centres are broken chain lines. The ground is the negative (white on blue),+and the sheet carries a drawing office's furniture: border zones, title block, scale, notes.++**Motion grammar.** A drafting office has no camera moves and nothing ever fades: the nib travels+along each stroke (`progress`), compass circles swing from where the needle-leg starts, section+lines run on one stroke at a time, lettering is written stroke by stroke. Long ruled strokes are+fast, lettering is slow. Finished parts are flattened onto one cached surface keyed by how many+parts are finished, so only the stroke being drawn costs anything.++**Realism for a mechanism.** Name the kinematics, not just the parts: every mesh sits at centre+distance = module x (Z1 + Z2) / 2; a wheel tooth is phased onto the line of centres with a pinion+GAP facing it; pinion leaves have parallel flanks and deep roots; the train ratio is stated and+true (64/8 x 60/8 = 60, the seconds arbor).diff --git a/references/styles/brokenColour.md b/references/styles/brokenColour.mdnew file mode 100644index 0000000..3f28238--- /dev/null+++ b/references/styles/brokenColour.md@@ -0,0 +1,47 @@+# Broken colour (`brokenColour.ts`, kit in `brokenColourKit.ts`)++**Medium, physically.** Oil straight from the tube on a lead-white primed linen, one sitting,+out of doors. A flat hog-bristle brush, loaded and put down ONCE: it lands blunt, pushes a ridge+of paint up along one side (lighter), leaves a groove on the other (darker), and drags thin where+it lifts; big strokes break into dry bristle tails. Colours are not mixed into the colour of the+thing: two or three unmixed colours sit side by side and the eye mixes them. The linen weave+(`weave`, a seeded plain-weave tile) is multiplied last and shows in the thin lay-in and the gaps.++**The marks.** Short, separate, opaque dabs (`brush` kind 0). Their colour is SAMPLED from an+analytic colour field (`field(u, v)`: the motif as smooth colour, regions, stroke direction and+dab size), then broken: hue +-0.03, value +-0.07, saturation up. Complementary accents are+dropped in by rule, never scattered evenly: orange/rose into blue shadow, violet/lilac into gold.+Directions follow the plane: water flat and long, sky varied (patches hatched up-right,+down-right or flat, lying along the cloud banks, turning part way round the sun), town low and+level, hulls along the hull, figures upright. Masts, oars, placement lines: one pull of a rigger+(kind 1). The lay-in: a thin scrubbed stroke of separate bristles (kind 2).++**Edge.** No outlines anywhere. A form ends where its dabs stop. Boats are dark dabs against+light dabs; edges are found only on the sunlit rims and lost into the haze elsewhere. The sun+is dabs too: cream-yellow core laid every which way, orange round it, orange and pink breaking+its edge into the halo. A clean circle is a craft-bar failure.++**Order of marks.** (1) thin warm imprimatura, scrubbed, alternating direction; (2) placement in+thinned ultramarine; (3) masses in big dabs whose colour is the AVERAGE of a wide neighbourhood+(boats blocked in with their own dark); (4) broken dabs everywhere, sky to water, visited along+a smooth order field (never per-cell random: that leaves vertical seams); (5) boats, masts,+town, sun restated along their forms; (6) accents; (7) reflections as horizontal bars, sun path+then boats; (8) oars and the last sparkles on the crests.++**Palette.** High key. Lead white, cadmium orange and red, chrome yellow, rose madder, cobalt+violet, ultramarine, viridian. No black: the darkest dark is ultramarine + rose.++**Light.** One low sun behind the subject; contre-jour silhouettes with warm rims on the sun side;+reflections stretch DOWN and break into bars (each ripple sees another slice of sky).++**Not its neighbours.** Not pencil & watercolour (`ranunculus`): nothing is transparent, there is+no line and no wash that misses its outline; colour is placed, not flooded. Not an oil impasto+plate that models form dark-to-light: here form comes from temperature, not value.++**Motion grammar.** A still that paints itself (`staged`): every dab is pulled along its length in+2-4 frames, passes abut (the next starts one frame before the last ends), the order field makes+the painting advance in an irregular front, never a scanline. Finished prefix cached; frame+order cannot change pixels.++**Gotchas paid for.** `smoothstep(t, 0.3t, x)` with t = 0 divides by zero and paints a full-height+column: guard it. A per-patch random draw order leaves vertical seams wherever two patches meet.diff --git a/references/styles/charcoalErasure.md b/references/styles/charcoalErasure.mdnew file mode 100644index 0000000..e183c1a--- /dev/null+++ b/references/styles/charcoalErasure.md@@ -0,0 +1,40 @@+# Charcoal, erased and redrawn (`charcoalErasure.ts`)++**Medium, physically.** Willow vine charcoal (a soft grey stick that skates over the tooth and dusts+off at a breath) and compressed charcoal (black, crisp, bites into the paper and barely erases), on+one sheet of heavy cream rag paper with a strong tooth. A paper stump rubs tone into the valleys; a+kneaded eraser lifts light back out, and never lifts all of it.++**The marks.**+- The stick's point for structure: vine first (light, powdery, broken by the tooth), compressed last (black, crisp).+- The SIDE of the stick for tone: broad parallel drags clipped to a region (`sideMarks`).+- The stump: a wide, soft zigzag rub (`zigzag` + `rubMark`, blurred group, `ce_blend` tooth) that turns drags into atmosphere.+- The kneaded eraser: the same rub with `destination-out` on the charcoal layer, partial alpha and a streak tile, so erased light is streaky in the drag direction and always leaves grey residue.++**Edge.** Vine: powdery, bitten. Compressed: crisp. Stumped tone: no edge at all. Erased edge: streaky.++**Order.** Tone the sheet (sky), lift the light (the sun) with the eraser, lay the subject in with+vine, build the structure, accents in compressed, ground and cast shadow, lift highlights. Then the+signature: **erase and redraw**. Every change is rubbed out with the kneaded eraser (partly), re-toned,+and redrawn on top of its own residue. Nothing is ever fully gone.++**Palette.** One warm black (`#1b1917`) on cream (`#ece5d5`). Value only.++**Paper.** A felt-marked sheet tile multiplied under the charcoal, and the paper tooth multiplied OVER+it, so the grain shows through the blacks. Charcoal lives on its own transparent layer so the eraser+can remove it; the paper is never erased.++**What makes it NOT its neighbour** (`pocketWatch`, ballpoint): tone is rubbed and lifted, never+hatched; the eraser is a drawing tool; the sheet carries its own history.++**Motion grammar.** The film IS the erase-redraw cycle. Every pass is a list of marks laid one after+another (`runPass`); a stroke grows from where the stick touched, tone arrives drag by drag, the stump+and eraser travel their zigzags. A breath (12% of a pass) between passes. Finished passes are cached as+layers keyed by pass index + scale + size, so a frame only draws the pass in progress.++**The hero.** An open-grown English oak through four seasons on one sheet, whole, left of centre, on a+ground line in the lower third, with bare paper round it. The sun is upper right, lifted from a small+feathered haze (never a toned sheet). Each season the old sun is re-toned and a new one lifted; the+shadow falls lower left (long in winter, a pool in summer, long and low in autumn). Erasures stay+local to what changed, so the final still shows faint earlier states of the same tree: the summer mass+as a whisper, and the calm winter branches under the wind-bent autumn twigs.diff --git a/references/styles/colouredPencil.md b/references/styles/colouredPencil.mdnew file mode 100644index 0000000..81c00d7--- /dev/null+++ b/references/styles/colouredPencil.md@@ -0,0 +1,46 @@+# Coloured pencil (`colouredPencil.ts`, kit `colouredPencilKit.ts`)++**Medium, physically.** Wax-based coloured pencils, sharp but not needle-fine, on cream cartridge+paper with a real tooth. The lead only lands on the ridges of the sheet, so every passage of+colour is speckled with the cream of the valleys. Pressing harder fills more valleys. Wax layers+sit on top of each other, and a second hue hatched over the first mixes optically.++**The mark.** A short, straight, slightly bowed hatch stroke: pressure comes in fast and lifts off+in a long flick. Strokes go side by side in strips, almost all in ONE dominant diagonal (lower-left+to upper-right, `ANG = -1.02`). Tone comes from pressure (stroke alpha plus the tooth level of+the pass) and from stacking passes, never from a flat fill.++**The edge.** Mostly none: an edge is where the hatching stops, with a stroke or two running+over it. A few thin, broken contours in a darker pencil (sepia-graphite) go on LAST, heavier on+the shade side and lost where the light is.++**Order of marks** (one pass each, replayed in this order by the film):+1. faint graphite lay-in: construction lines ruled freehand that run past the corners+2. big local-colour passes, light to dark: wall, sky, wood, then each object+3. second-hue layering over the first (violet over dusk blue, blue over teal, red-brown over ochre)+4. darks: cast shadows and deep places CROSS-hatched in a second direction (`X2`), never filled+5. contours, rivets, feather edges, grain+6. the lamp's halo: yellow over paper that was deliberately left near-bare++**Palette.** Cream paper `#f3ecdc`. Dusk blue and violet wall, indigo-to-rose sky, ochre and+red-brown wood, mahogany and felt red box, teal tin with blue over it, brick-red enamel, a+graphite-black crow with a blue-violet sheen, yellow and amber light.++**Paper.** One tooth field per sheet, slightly streaked along the hatch diagonal. Every pass is+punched by the SAME field at one of three pressure thresholds (light, medium, burnished), so the+valleys stay cream through all the layers. That shared field is what makes it read as pencil.++**Form.** One light. Colour thickens toward the edge of every form (`edgeDist` in the density+field). Solid forms keep a paler band on their TOP face. Cast shadows are hand-placed from the+lamp's position.++**Not crayon (balloon).** Crayon is a fat, waxy back-and-forth scribble with round ends, a white+crayon burnish and a fat contour gone over twice. Coloured pencil is fine, parallel, one-direction+hatching with speckled tooth, hue layering, cross-hatched darks and sparse thin contours.+**Not ballpoint (pocketWatch).** Ballpoint is one colour with tone only from where the lines+sit. Here tone comes from pressure and colour layering.++**Motion grammar.** The film is the drawing. Frame 0 is the bare sheet. Each pass lays its marks+in order, strip by strip, at a pace set by stroke length plus a fixed cost for every lift of the+pencil. There is a 5-frame beat between passes. Finished passes are cached as one composite and+the pass in hand is redrawn up to the mark the hand has reached. The last 35 frames are the still.diff --git a/references/styles/embroidery.md b/references/styles/embroidery.mdnew file mode 100644index 0000000..c9d61a5--- /dev/null+++ b/references/styles/embroidery.md@@ -0,0 +1,40 @@+# Hand embroidery (`embroidery.ts`)++**Medium, physically.** Six-stranded cotton floss split to two or three strands (one gold thread for+accents), worked with a crewel needle through natural plain-weave linen stretched drum-tight in a+beech hoop with a brass screw clamp.++**The marks.** A stitch is a length of twisted thread between two holes (`St`: a, b, width, colour).+- Stem stitch (overlapping, slanted: a rope) for stems; two rows for a main stem.+- Split stitch (each stitch coming up through the last) for the edges fills butt against.+- Satin laid side by side ACROSS a form, direction following it: across a petal, round an abdomen. Spans past ~9 mm are split at the axis.+- Fishbone: from a leaf's edge to its midrib, slanting to the tip, alternating sides.+- Long-and-short: rows from an edge toward a target, the first row alternating long and short, the thread stepping from colour A to colour B.+- French knots (a bead with its wraps and one glint) for flower centres, lavender, stamens, pollen.+- Running stitch for a flight line; single straight stitches for legs and wing veins.++**Edge.** The edge of every shape is the ends of its stitches: a row of pinches into the cloth. No+drawn outline; outlines are thread too.++**Rendering a stitch.** Pinched ends, a lit side and a shade side (one named light, upper left), slanted+grooves where the strands twist with a glint on each twist, and a hair of cast shadow down-right.+Sheen strength depends on the stitch's angle to the light, which is why stitch direction reads as form.++**Order.** Stems (stem stitch), stalks, split-stitch edges; then fills (leaves, shaded leaves, poppy,+daisies, forget-me-nots); then knots; then the bee, last; the needle is parked in the cloth.++**Palette.** Oatmeal linen; sage, olive, moss greens; white and shell; butter and ochre; cornflower;+two lavenders; poppy coral to oxblood; bee gold and umber; silver for wings.++**Ground.** The linen is computed per device pixel: warp over weft and weft over warp at alternating+crossings, each thread a rounded cord that rises where it passes over, slubs, the odd darker thread,+pin-holes between. Slack cloth outside the hoop in soft folds. The hoop's ring casts its shadow onto+the cloth inside at upper left and outside at lower right.++**What makes it NOT its neighbour** (`fox`, cut paper): nothing is a flat piece; every mark is a line+with a direction, and tone comes from stitch direction, not from fills.++**Motion grammar.** Stitches are made one by one: each grows from the hole it came up through toward+the hole it goes down, with the needle at its head and the working thread trailing from the eye; a+knot shows its wraps going round before it is pulled down into a bead. A stitch takes a moment plus a+little per millimetre; a knot takes three wraps. Checkpoint layers every 180 stitches keep frames cheap.diff --git a/references/styles/flatVector.md b/references/styles/flatVector.mdnew file mode 100644index 0000000..9f11647--- /dev/null+++ b/references/styles/flatVector.md@@ -0,0 +1,19 @@+# Flat vector (modern flat illustration)++Module: `engine/src/canvas-core/flatVector.ts`. Hero: a regatta of small sailboats on a bay under hills; the leader rounds the orange mark.++**Medium, physically.** The pen tool in a vector app. Each shape is a closed path of hand-placed anchors (corner anchors for sails and hulls, smooth ones for hills and water); its single flat fill lands the instant the path closes. Long shadows are separate shapes with a linear transparency ramp. Texture is a raster grain brush painted over the shade side of a shape, clipped to it.++**The marks.** Anchor, anchor, anchor, close, fill. No strokes anywhere: an edge exists only where two fills meet, and it is mathematically crisp. Depth from overlapping planes and atmospheric colour (lilac -> sage -> deep teal).++**Order.** Background planes (sky, clouds, far and mid hills, the bay's bands, the sun's glitter) -> midground (shore, town, headland, lighthouse, foreground rocks) -> the boats (wake, hull, sails, boom, mast, bow wave), buoy, chop -> long shadows and shade facets -> grain brush, shape by shape.++**Palette.** 13 swatches in one key: warm cream sky, lilac/sage/teal hills, three blues, coral, mustard, navy, bone.++**Light.** Low sun off-frame LEFT: glitter runs off the left edge, right-facing slopes and rock facets are in shade, every shadow is thrown right and ramps to nothing.++**Not cut paper (fox).** No torn fibres, no lift shadow under every piece, no drawn line. Edges are perfect; the only shadows are cast.++**Process UI.** While a path is being drawn: the blue path, white square anchors, the current anchor filled with its bezier handles. The UI is not a mark; it is gone when the path closes.++**Cost.** Finished grain per shape is cached in its own bbox surface; only in-progress grain is recomputed.diff --git a/references/styles/folkTale.md b/references/styles/folkTale.mdnew file mode 100644index 0000000..ddf8fdd--- /dev/null+++ b/references/styles/folkTale.md@@ -0,0 +1,72 @@+# Folk-tale storybook painting++Module: `engine/src/canvas-core/folkTale.ts` (kit: `folkTaleKit.ts`, process runner from `sumiEKit.ts`).+Hero: a boy carrying a rooster along the path through a village kitchen garden at the edge of a birch wood.+Format: 16:9, 1920 x 1080 (W and H from `meta`).++**The tradition.** Russian folk-tale book illustration in the storybook-painting manner: gouache and+watercolour over a full pencil drawing, where the painting is carried only as far forward as it+is needed and the back of the picture is left as the bare drawing.++**The medium, physically.** An HB graphite drawing on warm cream cartridge paper, then paint:+opaque gouache (body colour) laid with a half-dry round brush in the foreground, and thin,+transparent watercolour washes in the middle distance. The cream sheet shows through everywhere+the paint is thin, which gives the whole picture its glow.++**Depth is the medium.** This is the signature, and the rule every mark follows. Each mark takes+a depth `d`, from 0 at the viewer's feet to 1 at the horizon:+- **Foreground (d ≈ 0):** opaque, saturated, textured. Leaves have two-tone halves split at the+ midrib, a brush lay-in pulled out along the side veins, painted veins and dry-brush flecks.+ Sunflower rays are laid one at a time, each one creased and streaked. Grass is thousands of+ single blades, clumped.+- **Middle distance (d ≈ 0.3 to 0.6):** colour is mixed toward the warm haze (`far()`), the paint+ thins, the texture drops out, and the paint stops short of its own pencil line. Big middle+ things (the cottage, the haystack, the mid birches) dissolve into their drawing through a+ gradient mask (`faded()`).+- **Far (d ≥ 0.9):** no paint at all. Onion domes, bell tower, post mill, log houses and trees+ are pencil line on the cream sheet, the trees as scalloped crowns.+- **The golden haze** is a soft warm band laid over the middle distance before the foreground is+ painted, so the near things stand in front of the light.++**The mark.** In pencil, a soft line whose weight and darkness breathe with the pressure of the+hand, lighter where it lands and lifts, gone over a second time slightly off. In paint, an opaque+fill with a wobbling brush-cut edge, dry-brush drags inside it (three or four bristle lines that+break), and a slightly darker rim where the gouache settles.++**The edge.** In the foreground the edge is crisp and a little darker. In the middle it is soft,+and the paint misses the line. At the back the edge is the pencil line itself.++**Order.** Bare sheet → the whole scene in pencil, big shapes first (horizon and village, birch+trunks, haystack, cottage, fence, path, figure, garden, sunflowers, leaves) → the sky glow → the+meadow, back to front → the birch wood from far (line only) to near (paint) → the cottage,+thinning out into its drawing → the haystack → the golden haze → the middle sunflowers → the+wattle fence → the birch canopy → the path → the middle grass and daisies → the boy and his+rooster (trousers and bast shoes, shirt, tail, bird, head and comb, hands, head, face last) →+foreground grass → pumpkin leaves, pumpkins, tendrils → the big sunflowers → dog-rose,+bellflowers, burdock → a front fringe of grass → near daisies → the seeding umbels.++**Palette.** Cream paper `#f4edda`, warm haze `#f2e9c9`, sap and olive greens, yellow ochre,+cadmium yellow and orange (sunflowers, pumpkins), vermilion (the shirt and the comb), cobalt+violet (bellflowers), burnt umber, and graphite `#6f665a` for the line.++**Characters.** Warm caricature. Round heads with rosy cheeks (a soft radial blush), dot eyes with+a catchlight, a button nose, a small smile. Big, simple costume shapes carry the folk pattern: an+embroidered hem and placket, a sash with tassels, leg wrappings laced with bast, woven bast shoes.+Proportions stay true to age: the boy is about six, a little under six heads tall.++**Not its nearest neighbour (`storybook`, pencil and gentle watercolour).** `storybook` paints+everything at the same thin transparency. `folkTale` changes the medium with distance: opaque,+dry-brushed gouache at the front, a pale wash in the middle, bare pencil at the back. Its+foreground is dense with separately painted leaves, rays and blades, where `storybook` lays+washes that pool.++**Motion grammar.** The drawing is made. The pencil lay-in comes first, each line paced by its+length. Then the paint goes on from back to front: big washes sweep across behind a noisy wet+front (`reveal()`), leaves grow out from their stalks and then take their veins, sunflower rays+land one by one before the disc is laid, and grass is laid clump by clump. There is a short+pause between passes. Nothing fades or scales in. The last 30 frames hold the finished still.++**Kit primitives written for this plate** (candidates for core): `pencil`/`sketch`, `gouache`,+`reveal`, `faded` (+ `ramp`/`radial` masks), `leaf`/`lineLeaf`, `petal`/`sunflower`, `daisy`,+`bell`, `dogRose`, `umbel`, `grass` (clumped, with skip regions), `limb`/`lineLimb`, `pumpkin`,+`gourdLeaf`, `tendril`.diff --git a/references/styles/foxDraw.md b/references/styles/foxDraw.mdnew file mode 100644index 0000000..81f07fd--- /dev/null+++ b/references/styles/foxDraw.md@@ -0,0 +1,12 @@+# Cut-paper collage, laid down (`foxDraw.ts` over `fox.ts`)++The fox plate made the way a collage artist makes it, bottom of the stack up. `fox.ts` gained an+optional `Stage` (per piece: settled, not yet placed, or held in the hand with an offset and a+lift) threaded through its layer function; without one its output is byte-identical to the still+(md5 checked before and after). Frame 0 is the bare backing board. Four passes with a beat of+rest between: sky and dusk bands, hill and pines tier by tier, the fox from the far sweep of the+brush forward to the glint in its eye, then leaves and grass. Each piece travels held above the+stack (its shadow wide, far and soft), is lowered and pressed, and the shadow pulls in tight.+Big full-bleed sheets slide in from their own edge fast; small pieces are fiddly and slow. When+every layer is down the frame is drawn exactly as `fox` draws it, so the held last second is the+hero still byte for byte.diff --git a/references/styles/halftone.md b/references/styles/halftone.mdnew file mode 100644index 0000000..ebf9b09--- /dev/null+++ b/references/styles/halftone.md@@ -0,0 +1,38 @@+# Newsprint halftone (`halftone.ts`, `halftoneScene.ts`, `halftoneKit.ts`)++**Medium.** A web-offset newspaper press. The photograph is broken by a contact screen into an+AM halftone: dots on a fixed grid, their AREA carrying the tone. Two plates only: black on the+45 degree screen and one warm orange spot on its own screen at 15 (30 degrees apart, so they+rosette, never moire). Oil ink on unbleached groundwood newsprint.++**Marks.** Only dots. No line anywhere: every edge is where dot size changes. Dots are area-true+(`sqrt(t / pi)`), swell past 70% until they join into a solid with pinholes, and GAIN in the+midtones where their edge is longest; each is an irregular heptagon bitten by a per-dot hash,+with a soft halo of spread ink under it (a blurred copy of the same dots). Highlights under ~4%+drop out to bare paper; shadows plug.++**Edge.** The photo's rectangle on a sheet with a bare newsprint margin. The spot is laid a hair+wide (paper fan-out across the web) and off register, so a thin orange lip shows at dark edges.++**Order.** Build the ORIGINAL first (`halftoneScene.ts`): a pinhole camera over real structure in+metres, painted into two float separations (black density, spot density) with per-pixel sky, fells,+walled pasture and beck, canvas-painted viaduct and train (material id in the blue channel for+stone courses), and a steam plume as a union of shaded billows with a march toward the sun for+self-shadow. Then screen each separation into dots. The spot is a WARMTH, not a colour: only the+sunlit stone, the plume's lit rim and the glow carry much of it.++**Palette.** Black #1d1a17, spot orange #e86a2c, newsprint #e6dfcc.++**Paper.** Newsprint: a slow grey-cream pulp cloud, short dark groundwood fibres, pale surface+fibres, the odd bark shive.++**Not risograph.** Riso is flat stencil drums of bright soy ink overprinting into new colours,+hand-cut shapes, spot tints. This is a photograph: a continuous tone per ink, only dot size,+dull oil ink, gain and fibre, one warm spot in a grey world. No shapes, only tone.++**Motion grammar (make-ready).** The delivery pile at the end of the press. On every beat a new+sheet is thrown on top (slides in from the head of the sheet, lands in 6 frames with its shadow+on the sheet below). The first sheets carry the spot unit alone, coming up to colour: thin and+streaked along the feed where the rollers starve, evening out ink key by ink key across the width+(smoothly, the oscillators smear the keys). Then the black unit comes up over it the same way.+Last, the pressman nudges the spot into register over a few sheets; the final sheet is the still.diff --git a/references/styles/isometric.md b/references/styles/isometric.mdnew file mode 100644index 0000000..e3761b0--- /dev/null+++ b/references/styles/isometric.md@@ -0,0 +1,17 @@+# Isometric cutaway · `isometric.ts`++**Medium, physically.** A flat vector illustration on a true 2:1 isometric (dimetric) grid, built the way an iso illustrator works in a pen-tool program. World x -> screen (u, u/2), y -> (-u, u/2), z -> (0, -1.2247u): every horizontal edge is a 2:1 line, every vertical is vertical, a cube reads as a cube (`Iso` in `isometricKit.ts`).++**The mark.** The plane: pen-traced outline (kept inside the plane), then a flat fill. The 2:1 hairline. The flat light shape.++**The edge.** Vector-crisp. No contour line: tone meets tone. Each material has exactly three tones (top lightest, +y face middle, +x face darkest); curved things obey the same cube rule (a dome is three flat regions split on the meridian that projects vertical, plus an up-facing cap).++**Order.** Iso grid ruled across the ground -> massing blocks (translucent construction boxes, strokes clipped inside so none survives) -> walls and floors -> interiors (oven, loft, racks, table, ladder) -> props (bread, sacks, the baker) -> light and shadow -> details (tile joints, brick courses, plank lines, plaster speckle, window stars, flour).++**Palette & light.** Night-cool ambient on warm materials (everything but the bread is stepped a notch into the dark), so the only saturated warmth is the oven. The oven mouth is the one light: faces that can see it take ONE flat warm tint stepped in three distance bands (`warmBox`), the floor pool is three flat bands, cast shadows are single flat shapes thrown away from the mouth. No gradients anywhere.++**Figures.** Authored in screen space over the projected foot point, 7.5 heads, three tones per garment, the rim of warm light on the side that faces the source.++**Not its neighbour.** `koi` inks a thick-thin contour by hand; here there is no line and no hand at all, the projection is the style and the order is construction-first.++**Motion grammar.** Construction time-lapse: things are laid in painter's order but revealed stage by stage; a plane is traced then filled top-down; light is poured last. Camera never moves in the process film.diff --git a/references/styles/koiDraw.md b/references/styles/koiDraw.mdnew file mode 100644index 0000000..7310997--- /dev/null+++ b/references/styles/koiDraw.md@@ -0,0 +1,9 @@+# Marker comic, drawn (koiDraw)++Module: `engine/src/canvas-core/koiDraw.ts` over `koi.ts` (optional `KoiClock` 4th argument to `drawKoi`; without it every branch takes the original call, and the plate's md5 is unchanged: 1x dfd5350f5c2b94d030d7c62e34d2dc7d, 2x 27ebed84ad3a09aac4336d124d6e2707).++**Process.** Non-photo-blue lay-in (spine gesture, masses, parts) -> flat cel fills lightest first, each laid in back-and-forth chisel-marker passes that start and stop past the pencil line; a wide area (the pond) is filled in blocks of short passes, so its leading edge is ragged, never a wipe -> hard shadow shapes and floor shadows -> details (scale arcs, fin rays, streaks, rings, gel-pen whites) -> the heavy brush-pen contour LAST, each stroke growing along its centreline.++**Stacking.** Every element is drawn in its own z order every frame and only its extent grows, so a fin laid before the body still sits under it. The marker is opaque here: pencil vanishes under it.++**Kit.** `koiDrawKit.ts`: `streaks`/`streakClip` (a marker or brush laying a flat), `cut` (a line's first q by arc length), `part`/`stagger`, `sequence`/`cueClock` (a strict cue table: a missing cue throws instead of drawing that mark finished at frame 0).diff --git a/references/styles/lighthouseDraw.md b/references/styles/lighthouseDraw.mdnew file mode 100644index 0000000..48bc414--- /dev/null+++ b/references/styles/lighthouseDraw.md@@ -0,0 +1,13 @@+# Risograph, pulled drum by drum (`lighthouseDraw.ts` over `lighthouse.ts`)++A riso print is not drawn, it is fed: the same sheet goes through the machine once per ink, a+different drum loaded each time. `lighthouse.ts` only gained `export` on its three plate+functions (md5 of the hero still checked before and after: unchanged). Frame 0 is the bare sheet+with its trim marks. Yellow first: the ink lands at the nip, a straight front travelling down the+sheet at constant feed speed (a short grip and release at the ends) with the drum's shadow riding+just ahead of it. A breath while the drum is swapped. Pink over the dry yellow at its own+registration offset, so every overprint is born at the nip line (coral sky, orange sun). Swap.+Blue last, the key plate: dusk violet, green turf, the shadow side of every form and the crayon+key lines arrive in one sweep. Each ink's swatch in the colour bar prints with its own drum. The+held finish is `drawLighthouse` itself, so the last second is the hero still byte for byte.+Motion grammar: the only moving thing is the nip line. Never a fade.diff --git a/references/styles/lowPoly.md b/references/styles/lowPoly.mdnew file mode 100644index 0000000..d43d9d2--- /dev/null+++ b/references/styles/lowPoly.md@@ -0,0 +1,35 @@+# Low-poly (`lowPoly.ts`)++**Medium, physically.** None, by design: a scene MODELLED as triangle meshes, PROJECTED by hand+through a pinhole camera (a translate, one pitch rotation, a divide: no 3D engine), FLAT-SHADED+(each triangle one colour from its normal against one light plus a cool sky ambient, hazed toward+the dawn by distance), and drawn by PAINTER'S SORT, far to near.++**The mark.** The facet: a hard-edged triangle. No line in the finished picture (a same-colour+hairline only closes antialias seams), no gradient, no texture. The triangulation IS the texture,+so the grid is built perspective-friendly (columns widen with distance, rows grow ~12%) and+jittered, which keeps facets about the same size on screen.++**Meshes.** A heightfield: lake basin (clamped to the water plane, so water is just faces of the+same grid), shores, a low front range, a high back range with a notch the sun clears, snow on+high faces that face up. Pines: a trunk and three six-sided cone tiers, placed in drifts with+bare rests. A canoe lofted from 13 cross-sections: outer hull culled by its outward normal, inner+walls by their inward one, thwarts, a paddle. The sky is 2D facets (a jittered grid, coloured by+height and distance to the sun), faceted clouds lit from below, a faceted sun glow.++**Reflections.** The same meshes mirrored in the water plane, darkened toward the water, drawn+only where water is visible (a mask built by the same painter's pass: water white, solid faces+erasing), then broken by horizontal ripple cuts; a glitter path of short dashes under the sun.++**Order of marks.** The empty viewport (dark grid). The wireframe, edge by edge: terrain swept+from the far ranges to the near shore, then trees, then the canoe. The faces shading in exactly+in painter's order: sky top-down, then far to near. Water facets far to near. Reflections far to+near. Ripple cuts and glitter last.++**Palette.** Dawn: indigo `#262c5c` to violet `#5b4f8a` to rose `#d98f98` to peach `#f6bf92`;+sun-facing slopes peach-rose, the rest blue-violet; spruce `#23463b`; canoe red `#b3392b`.++**Not its neighbours.** Every other plate is a hand's mark on a surface; this is geometry.++**Motion grammar.** A modeller's viewport: lines are laid then covered by faces; nothing slides.+If a camera ever moves, re-project every frame (never scale the bitmap) and keep facets flat.diff --git a/references/styles/midCentury.md b/references/styles/midCentury.mdnew file mode 100644index 0000000..dd217c6--- /dev/null+++ b/references/styles/midCentury.md@@ -0,0 +1,17 @@+# Mid-century gouache (1950s-60s storybook)++Module: `engine/src/canvas-core/midCentury.ts`. Hero: a hillside village where a girl flies a kite.++**Medium, physically.** Opaque, matte designer's gouache on warm illustration board (Provensens, Mary Blair, Sasek). A flat brush lays each shape in, visible only at its slightly ragged edge; a nearly dry brush is dragged over the flats so the bristles skip the board's tooth; a loose brush-and-ink line goes on last, on its own plate, OFF REGISTER from the colour.++**The marks.** Flat opaque shapes whose edges are displaced geometry sized to the shape (polygons keep their corners: a house is cut, not rounded); dry-brush bristle streaks that break up as the brush runs out; a thin, slightly thick-thin line with open contours that wanders past the colour (plate offset +5, -4).++**Order.** Flat shapes BIG TO SMALL (sorted by area; the stacking order stays, so a house fills in around a hill already painted) -> dry brush (sky, clouds, hills, walls, dress shade, grass drifts) -> the line (the girl first, then kite, string, village, birds).++**Palette.** Warm board, mustard, tomato, turquoise, olive, deep green-black, pink, cream.++**Light.** Sun high left: darker right sides on every house and spire, the girl's flat shadow runs down the hill to the right.++**The human.** Eight years old, six heads (54 px head, 324 px figure): shoulders 1.3 heads, crotch 3.1, knees 4.5, ankles 5.8. Weight on the straight back leg; the front knee bends forward. Kite arm raised, elbow flexed outward-down, fist round the string with the thumb over it; balance arm back, hand open palm down, four fingers and a thumb. A-line dress, Peter Pan collar, puff sleeves, white socks, Mary Janes. Wind from the left: hem, bow tails, kite tail stream right.++**Not cut paper (fox).** Painted edges and dry brush instead of torn fibres and lifted pieces, and a line that floats off the colour.diff --git a/references/styles/moonPhasesDraw.md b/references/styles/moonPhasesDraw.mdnew file mode 100644index 0000000..da8cc8f--- /dev/null+++ b/references/styles/moonPhasesDraw.md@@ -0,0 +1,21 @@+# Chalkboard, written on (`moonPhasesDraw.ts`)++The draw-on version of the chalkboard plate (`moonPhases.ts`, recipe in `styles.md`). The plate takes+an optional `Clock` (`(id) => progress`); without one it draws the finished board byte for byte+(verified: md5 unchanged at scale 1 and 2), so the film's last 30 frames are the still.++**Order, as a teacher works a board.** The felt eraser first: yesterday's lesson ("HOMEWORK P 42",+"NEWTON / 3RD LAW") is swept off left to right, behind the eraser only the ghost remains, and the wide+arcs of haze grow as it goes. Then the title, underlined twice in yellow; the month's arc and arrowhead+in blue and "29.5 DAYS"; then each moon in turn: the whole lit face scumbled with the side of the chalk,+the highlands built up across it (the maria are just less chalk), the lit limb worked a second time,+craters tapped in, the firm limb line, the faint dark limb, the terminator, and its label written under+it before the next moon starts; the full moon is smudged round with a finger. Stars dotted in last, the+Plough dotted and joined in blue, the pink note written and circled.++**Motion grammar.** Scumbles arrive drag by drag (the last drag part-way); lines grow along the stroke+with their dust; letters are written stroke by stroke (`drafting.ts` progress). One cue table on the+5-frame grid, checked at load.++**Frame 0** is the board as the teacher finds it: yesterday's lesson still on it. The ghosts are made+by erasing it, which is what ghosts on a real board are.diff --git a/references/styles/paintedOil.md b/references/styles/paintedOil.mdnew file mode 100644index 0000000..9df941f--- /dev/null+++ b/references/styles/paintedOil.md@@ -0,0 +1,52 @@+# Oil on canvas++Module: `engine/src/canvas-core/paintedOil.ts` (kit: `paintedOilKit.ts`, process runner from `sumiEKit.ts`).+Hero: two pears and a copper pot by a window (the window just out of frame, left).++**The medium, physically.** Oil paint on stretched plain-weave linen, primed with lead white, then+toned with a thin rub of burnt sienna and umber (the imprimatura). Hog-bristle flats and+filberts. The paint is lean (thinned) in the early passes and fat (straight from the tube) at the end.++**The mark.** A flat bristle stroke (`oilStroke`). It lands square and fully loaded. Each bristle+lays its own line, varying a few percent in value, so every stroke is streaked along its length.+As the paint runs out, the outer bristles break first, and the end of the stroke drags into+streaks over the layer beneath. Each stroke carries two colours: the colour it was loaded with,+and the one it picks up by the end (wet into wet), sampled from the light model at both ends.++**The edge.** Ridges: paint is shoved up at both edges of the brush. The ridge turned to the window+catches a thin light line, and the far ridge a thin dark one. Bristle grooves run down the middle,+and paint piles across the end where the brush lifted. Impasto highlights are short, thick dabs+that stand off the canvas, with a hairline cast shadow away from the light. Object edges are found+on the lit side (clipped crisply against the ground already laid) and lost in shadow. There, the+value of the shadow side is brought to the value of the dark wall, so no line is left to find.++**Order.** White priming → toning rub → thin burnt-umber drawing (small round brush, searching+lines, shadow shapes scrubbed in) → dark masses everywhere with a big brush and lean paint → mid+tones → lights with a smaller brush and fatter paint → impasto highlights → final dark accents+(stems, calyx, contact shadows). Background strokes never cross the objects (an even-odd clip), so+each object keeps its own passes.++**Size hierarchy.** A big flat (~130 px) lays the wall in few steep diagonal passes, with the toned ground left between them. Broad horizontals lay the table. A medium brush follows each form. A small brush does the accents only. Strokes feather in (`soft`), so no stroke starts as a square slab.++**Form and direction.** Strokes follow each form's own structure. The copper pot is painted in hoops+round its belly: one eye-level ellipse ratio (0.17 at the rim, 0.205 at the foot), with the stroke curvature+exaggerated as a painter would. It carries a warm body, a dark core and warm reflected light; the window's sky is 3 cool+strokes that follow the curvature, plus one specular dab. The pears are bodies of revolution (bulb and neck on+an axis), their strokes wrapping each cross-section; the lying one is foreshortened, with its neck turning away. The table is laid along the grain, and the wall is scumbled on a drifting diagonal.++**Palette.** A Chardin kitchen palette: umbers, burnt sienna, yellow ochre, terre verte, Naples+yellow, lead white. The copper is a mirror model: it shows a narrow window band left of centre,+painted as a painter reads it (body, core, reflected light, cool sky strokes), not computed as a mirror.++**Canvas.** A plain-weave linen tile (`weave`), 10 threads per 34 px, each crossing a lit bump. It+is multiplied at 0.55 into the ground and at 0.3 over the finished paint.++**Not its nearest neighbour (`ranunculus`, pencil & watercolour).** Watercolour is transparent: it+is laid light to dark, it never covers, and the paper is the white. Oil is opaque: it is laid dark+to light, every pass covers the one before, the white is lead-white paint, and the texture is the+paint's own relief (ridges, impasto) over canvas weave, not granulation on paper.++**Motion grammar.** The painting is being made. Each pass works across its area in a sweep. A+stroke is laid along its path at a hand's pace, and several quick marks fit in one frame+(fractional op windows) during the block-in. The impasto dabs are slower. There is a beat of+pause between passes. Nothing fades or scales in.diff --git a/references/styles/paperCraft.md b/references/styles/paperCraft.mdnew file mode 100644index 0000000..86aa325--- /dev/null+++ b/references/styles/paperCraft.md@@ -0,0 +1,37 @@+# Toy-theatre paper collage (`paperCraft.ts`)++**Medium, physically.** A cardboard toy theatre stood on a kraft-paper table, built from three+kinds of paper. Coloured and PRINTED papers, scissor-cut or torn: plain sugar paper for the deep+sea, printed papers for the rest (a wave print, a dot print, a stone print, a diamond print,+newsprint). GOUACHE CUT-OUTS: flat opaque paint laid in visible brush strokes on white card, cut+out with a white margin left round them like a sticker (sun, lighthouse, houses, gull, post).+And card itself: every piece has THICKNESS, a darker cut edge showing down-right of its face.++**The marks.** The gouache brush stroke (`gouache`: a flat base, then broad strokes a shade+lighter and darker in one direction, clipped), a painted shade laid along the side away from the+sun (`shadeSide`), and the printed motif (`wavePrint`, `dotPrint`, `diamondPrint`, `stonePrint`,+`newsPrint`, `woodPrint`). No drawn line anywhere.++**Edge.** Scissor-crisp or torn; then the card's cut edge (an offset copy in a darker tone); then+the white sticker margin, made by stroking the outline with a round join, which is exactly the+margin scissors leave. The margin never follows a concave detail too closely.++**Depth.** The flats stand apart. Each piece throws a soft shadow onto the flat behind whose+offset is the gap between them (`depth`); the proscenium throws its shadow into the stage along+the inner top and left. Flats are clipped to the theatre box: they slide in behind its walls.++**Order of marks.** Table (frame 0). The theatre (proscenium and floor) set down. Then the scene,+back to front: sky drop flown in, sun lowered on its stick, clouds, lighthouse pushed up behind+the headland, headland slid in from the wing, sea rows and quay slid in, houses stood up one by+one, the newspaper boat pushed on along its wave, front sea, post and gull, beach ground row,+curtains swung in, valance lowered.++**Palette.** Kraft `#b8905f`; proscenium teal `#2f6f73` with gold `#e1b54a`; theatre red `#b8302c`;+sea `#2c5d8a` / `#3d7db0` / `#4ba2a3`; gouache pastels for the houses. Light: the sun, upper left.++**Not its neighbour.** `fox` is cut paper with no paint, no print and no space between layers.+This is painted and printed paper in a stage space with real gaps, and it moves like stop-motion.++**Motion grammar.** STOP-MOTION ON TWOS: every pose is held for two frames. A piece travels held+above the stack (shadow wide and far, a hair of hand jitter), lands, jiggles (a few degrees, a+pixel or two of bounce, damped) and is still. Ink and paint never move.diff --git a/references/styles/pixelArt.md b/references/styles/pixelArt.mdnew file mode 100644index 0000000..aee573a--- /dev/null+++ b/references/styles/pixelArt.md@@ -0,0 +1,17 @@+# Pixel art · `pixelArt.ts`++**Medium, physically.** Cells, laid one at a time on a 120 x 120 grid (square format), each cell exactly one of sixteen palette colours declared up front (`PALETTE`), the grid blown up by a whole number with smoothing off (`blit` in `pixelArtKit.ts`: integer cell size, one `fillRect` per run, nothing else touches the canvas). No anti-aliasing, taper, wobble, texture tile or paper: machine crispness is the medium.++**The mark.** The single cell (pencil), the bucket fill, the dither cluster. A half tint is a 2x2 ordered dither (`PixelDraft.dith`), never an alpha blend. Glows are authored stamps (core, lit ring, falloff that thins cell by cell), not checker circles.++**The edge.** The staircase, kept clean: consistent run lengths along a curve, no doubled corners, no orphan cells (`cleanMask` removes one-cell nubs and fills one-cell notches). Faces, ears and eyes are laid by hand as an ASCII sprite (`HEAD`); a formula cannot place an ear tip.++**Order.** Blocking in flat mid colours (pencil the edge, bucket the mass; the subject first goes down coarse, in 2x2 cells) -> line cleanup (the silhouette swept once round, cells taken off and put on) -> shading clusters and the sky's dither bands -> highlights and rim light -> the light sources and their glow dither LAST. A beat of rest between passes.++**Palette & light.** Sixteen colours: four night blues, moon white and its cool rim, three greens plus one firefly-lit leaf, two cat darks, three glow warms. The fireflies are the light (warm edges on the paw, muzzle, inner ear, eyeshine); the moon only rims the cat's back cool.++**Not its neighbour.** `koi` (marker comic) makes a contour stroke, thick-thin, and a painted cel shadow. Here there is no stroke at all: the cell is the mark, the staircase the edge, the dither the tone.++**Motion grammar.** Cels held for 3 frames (3 divides the 15-frame beat), a 10 fps feel. The process film replays the recorded op list: every cell the finished still contains was laid, in order, by a pass (`celPlan`). For character loops: pose-to-pose phases, whole-cell teleports between authored poses, never tweened positions.++**Gate.** Every pixel of a rendered frame is a palette colour (checked by decoding the still: 0 off-palette pixels at scale 2).diff --git a/references/styles/pocketWatchDraw.md b/references/styles/pocketWatchDraw.mdnew file mode 100644index 0000000..3378920--- /dev/null+++ b/references/styles/pocketWatchDraw.md@@ -0,0 +1,17 @@+# Ballpoint sketch, drawn on (`pocketWatchDraw`)++The `pocketWatch` plate, filmed while the biro makes it. The last frame is the plate, byte for byte.++**Medium.** One blue ballpoint (#23379f) on cream cartridge paper (#f6f2e6). A steel ball rolls oil ink: the line weight barely changes, it cannot be thinned or lifted, and nothing can be erased. Where a firm stroke stops, the ball leaves a bead of ink.++**Marks.** Only lines. Tone comes from where the hatching sits: one direction, then a cross layer, then a third direction in the deepest darks. The only solid blacks are the Breguet hands and the centre boss, scribbled in.++**Edge.** Every edge is a line. The glare on the crystal is paper that was never hatched.++**Order.** (1) Construction: two faint centre lines and a loose ellipse. (2) Contours: case, back arc, bezel and track rings, sub-dial, pendant, crown and bow, then the chain. (3) Detail: reeding, minute track, IIII numerals, sub-dial ticks, knurling. (4) The first tone layer everywhere there is shade. (5) The cross layer where it is darker. (6) The third direction in the darkest places. (7) The solid blacks: the hands, their hair shadows and the boss. A pen cannot take a mark back, so a sketcher commits to the contour before any tone. The hands come last because they sit on top of everything.++**Palette and paper.** One ink and one paper, with the `paper` tile multiplied at 0.07.++**Not its neighbour.** This is not pencil: there is no smudge, no erased lay-in and no pressure-driven weight. It is not ink and line-wash: there is no wash and no flexible nib. Against the still `pocketWatch`, the difference is the ORDER of the marks.++**Motion grammar.** Each mark is gated by a clock that knows its pass (`build/line/detail/h1/h2/h3/fill`). Marks paint in the plate's own order, so the finished frame cannot drift, and the clock only decides WHEN each one happens. Time per mark is 4 + length^0.85 cost units: long strokes cover more pixels per frame, while short fiddly ones take longer per pixel. Hatching overlaps like a time-lapse. There is a 10-frame pause between passes. Strokes the case will cover take no time. A bead appears only once the stroke is finished. A solid area grows as a band swept across it and never fades in. Watch before chain.diff --git a/references/styles/ranunculusDraw.md b/references/styles/ranunculusDraw.mdnew file mode 100644index 0000000..bf992ee--- /dev/null+++ b/references/styles/ranunculusDraw.md@@ -0,0 +1,22 @@+# Pencil & watercolour, drawn (`ranunculusDraw.ts`)++**Medium.** HB pencil and pan watercolour on cold-press, the hand of `ranunculus.ts`, whose+geometry, seeds and calls this film reuses verbatim (re-authored, so the hero stays byte-identical).++**Order of marks.** (1) Pencil lay-in, light enough to live under paint: bloom envelope, heart,+stem gesture, leaf axes, lips of the outer three rings. (2) First light washes, one per mass: the+bloom's wash follows the ring's scalloped silhouette (lip crowns walked round the centre, never a+disc), each wash spreads from where the brush touched along a ragged wet front and stops short+of its outline. (3) Form toward the one light (upper left): stem, leaves, calyx, then petals+outer ring to centre, each a wet front growing from the petal base. (4) Graphite over the paint:+lips and veins, stem and leaf contours; every line is ERASED where a petal painted later sits+over it (`destination-out` of the later petals' actual form outlines), because a hand does not+draw what it cannot see.++**Why the last frame is not the hero's pixels.** The hero interleaves paint and graphite petal by+petal and has no lay-in. Worked in the medium's order, the finish is the same flower with a+faint lay-in under the paint and all graphite on top.++**Motion grammar.** Pencil fast and light, washes slow (20 frames each), petals quicker as they+get smaller, graphite brisk. Wet fronts are sized to their shape so the front is still moving on+the op's last frame.diff --git a/references/styles/rubberHose.md b/references/styles/rubberHose.mdnew file mode 100644index 0000000..707d2ac--- /dev/null+++ b/references/styles/rubberHose.md@@ -0,0 +1,19 @@+# Rubber hose (1930s studio cartoon)++Module: `engine/src/canvas-core/rubberHose.ts` (+ `rubberHoseKit.ts`). Hero: a coffee pot mid-dance-step on a kitchen counter, steam curling.++**Medium, physically.** A blue-pencil rough on punched animation bond; traced in India ink at ONE pressure onto a clear cel; painted on the BACK of the cel in flat opaque greys; photographed and printed on black-and-white film.++**The marks.** A uniform ink line (no thick-thin) with a slight hand wobble, reseeded per drawing when animated (line boil on twos). Contours stop where a nearer shape starts: every part knocks its own interior out of the ink beneath it, and a union outline is stroked double then has its interior removed, so a glove of six overlapping pieces reads as one silhouette. Limbs are solid black noodles: one quadratic arc from shoulder to wrist, no elbow. White four-digit gloves, three stitch lines, flared cuff. Pie-cut pupils. Big oval shoes with one shine.++**Edge.** Hard and even. Paint never modelled; cast shadows are translucent flat shapes with no ink.++**Order.** Rough (line of action first, then masses, then parts) -> ink (character, then set) -> paint, flooded region by region from where the brush touched (character first) -> the pull-down: the drawing is threaded down through the projector gate and comes back as a print -> two seconds of dance on twos that lands on the key pose -> the hold (= the still).++**Palette.** Greys only: ink #16130f, paper whites, five greys; the print is toned warm (multiply #ecdfc6).++**Film.** Per-frame grain tile offset (soft overlay), lamp flicker, dust (dark = positive, light = negative), a hair, a sprocket scratch, a vignette from the lamp, the rounded gate. Gate weave (+/-1.7 px) only while projecting motion; the still uses seed 0 and no weave.++**Not the marker comic.** koi is modelled cel colour with a contour that thickens away from the light; this is one line weight, no modelling, greys, and a film print.++**Motion grammar.** On twos. Key poses on the beat (15 frames), the body leads and the limbs follow ~2 frames behind on the same arc, a hop of ~26 px between keys with stretch in the air and squash on landing. Loops land exactly on the key pose.diff --git a/references/styles/scrapbook.md b/references/styles/scrapbook.mdnew file mode 100644index 0000000..ed40c9b--- /dev/null+++ b/references/styles/scrapbook.md@@ -0,0 +1,47 @@+# Archival scrapbook (`scrapbook.ts`, kit in `scrapbookKit.ts`, engravings in `scrapbookEngraving.ts`)++**Medium, physically.** A page from an old field-notes album: rag paper gone to parchment, foxed+with rust spots (drifts at the right margin, the lower-left corner and along the fold, bare+elsewhere), darker toward the handled edges, folded once, a faint tide mark. On it, cards torn+from other stock (deckle edges, darkened rims), held with yellowed cellulose tape or pegged to+a twine line with a wooden clothespin. The pictures are COPPERPLATE ENGRAVINGS, afterwards hand+tinted with thin wash. Words come from a typewriter, from ransom-note cut letters, and a red pen.+A rubber stamp goes on last.++**The marks.**+- *Burin line* (`burin`, `engrave`): a centreline whose width swells with the tone under it and+ comes to a point at both ends; where the tone drops below a threshold the line breaks into+ the paper, so highlights are bare. Contour hatching follows the form (rings across a tube,+ lines along a petal); cross-hatching only where the tone is deep; fur as short tapered flicks;+ a stipple for pollen; cast shadows ruled as horizontal lines feathered at the edge. Tone is a+ normal-vs-light model on each part's own frame (`frame`, `tubeShade`), occlusion by testing+ each sample against the parts in front (`occluder`), so hidden lines are never cut.+- *Struck character* (`typed`): slab-serif monospace from a stroke glyph table, each strike its+ own density and a hair off the line, the ribbon printing faintly double.+- *Cut letter* (`ransom`): each letter a scissor-cut paper tile with its own colour pair, face+ (heavy, slab, outline, italic, condensed, wide, rounded), size and tilt; some cut from a column+ of print, the letter on a cleared patch. Glyphs are STROKED paths, never `fillText`.+- *Red pen* (`handWrite`, `g.pen`): tapered, wobbling annotation: a dashed trend, a loop, the reading.+- *Stamp*: double-bordered, ink broken by `risoSpeck` + `risoMottle`, multiplied.++**Edge.** Torn (cards), scissor-crisp (tiles), no drawn outline round anything that is paper.+Every paper lifts a little and throws a soft shadow down-right.++**Order of marks.** Page (frame 0). Cards laid down one by one (held high, shadow far, then+pressed), each taped; the twine, the flower card, the peg. The section tag, typed. The bee cut:+contours, abdomen, thorax and head, legs and antennae, wings, cross-hatch + eyes + fur + pollen,+cast shadow. The rose: contours, petals, stamens, stem and leaf, shadow. Hand tint (wash spreads+from where the brush touched). Captions typed. Title strips typed, ransom letters pasted one by+one. The waggle diagram in pen. The chart plotted (axes, bars inked upward), then annotated.+The stamp, rocked on from one end.++**Palette.** Parchment `#e8d6b2`, sepia-black ink `#2a2019`, teal `#4f8f8a`, dusty pink `#d9a5a0`,+stamp red `#b8322a`, navy `#22335a`, mustard `#d6a13c`. One lamp, upper left.++**Not its neighbours.** `fox` (cut paper) has no line and no type. `pocketWatch` builds tone from+a constant-width biro. `mellan` is one spiral. Here tone is many swelling lines that follow the+form, on collaged ephemera, and the words are part of the picture.++**Motion grammar.** A desk worked in real time: paper moves (slides and presses), ink never+moves once made. Lines are cut one after another, the current one travelling; letters strike one+at a time; tiles drop with a small tilt and settle.diff --git a/references/styles/scratchboard.md b/references/styles/scratchboard.mdnew file mode 100644index 0000000..63ca32d--- /dev/null+++ b/references/styles/scratchboard.md@@ -0,0 +1,15 @@+# Scratchboard · `scratchboard.ts`++**Medium, physically.** A board of white china clay under a coat of black India ink. Nothing is added: every mark is ink scraped away with a steel knife or scratch nib, so every mark is white on black and the picture is found by removing the dark. A cut is widest where the blade bites in and tapers as it lifts; the clay chips a hair at its edges (the `draftTooth` tile over a clean copy of the cuts).++**The marks.** Fur as tapered white flicks cut in the direction the hair grows (streamlines of a hand-placed flow field, length from a hand-placed hair-length field); each flick's width follows the tone along its length, so a hair crossing a dark marking thins out as it crosses it. Parallel hatching follows form on hairless surfaces (nose leather, irises as radial cuts). A shorter crossing set of cuts at ±35° gives the mid tones. Lights are cut so densely they close up into bold scraped areas; catchlights are scraped flat with the blade.++**The edge.** Lit contours are a row of short bright flicks cut along the lie of the hair (on skin edges such as ears, a clean knife line). Shadow-side edges are lost into the board, rimmed only faintly by the sky.++**Order.** The knife reveals from black: contour highlights where the moon catches the edges; a sparse layer of flicks everywhere the light reaches, to set the lie of the coat; then the light mass is built: mid tones, the crossing cuts, the lights until they close; last the details (nose hatch, irises, whiskers) and the catchlights.++**Palette & board.** #0c0b0a board, #ebe5d8 clay. No grey ink: grey is only how close together the white cuts are.++**Not its neighbour.** `mellan` and `pocketWatch` add dark marks to light paper; here every mark removes dark, the ground is black, and tone rises with the number and width of cuts. Hatching exists but fur flicks dominate.++**Motion grammar.** Frame 0 is the black board. Long knife lines are watched being cut (a tip travelling along the line); fur flicks arrive whole, many per frame, region by region. Nothing fades; nothing is ever re-inked.diff --git a/references/styles/stipple.md b/references/styles/stipple.mdnew file mode 100644index 0000000..fea3c16--- /dev/null+++ b/references/styles/stipple.md@@ -0,0 +1,15 @@+# Stipple (pen-and-ink dots) · `stipple.ts`++**Medium, physically.** One technical pen (0.25 mm), never changed, touched straight down onto hot-press bristol thousands of times. No line, no hatch, no wash. The pen is held a touch off vertical, so each dot is slightly oval and slightly ragged; now and then it drags a hair of tail as it lifts, now and then it runs dry and a dot comes up grey.++**The mark.** A dot of one size. Tone is only how many dots sit in a square centimetre (weighted-Voronoi / Secord 2002 distribution: blue noise, no clumps, spacing ~1.5 px / tone^0.64 at 1080). Built as variable-radius Poisson-disk sampling over a 1-px tone raster computed from the subject's real structure and one lamp (`stippleKit.ts`).++**The edge.** There are no contours. An edge is where dot density changes; in full light the edge is simply lost (the upper-left rim of the shell).++**Order.** Darkest masses first (chamber shadows, the body chamber's cast shadow, contact shadow), then out into the mid tones, then a few sparse passes over the lit nacre. Each pass works across the sheet in patches (a snake of ~84 px cells), not in a raster. A beat of rest between passes.++**Palette & paper.** Carbon black a hair warm (#15120e) on bright bristol (#fbfaf5); the core `paper` tile at 5%, nothing else.++**Not its neighbour.** `mellan` is one continuous line whose width carries tone; `pocketWatch` builds tone with hatching directions. Stipple has no direction at all: the only variable is density.++**Motion grammar.** Marks arrive; nothing moves. A film is the stippler's time-lapse: dots accumulate pass by pass (~100 per frame), the dark masses establish the drawing before any light tone exists. Never fade dots in; never move them.diff --git a/references/styles/storybookDraw.md b/references/styles/storybookDraw.mdnew file mode 100644index 0000000..611068c--- /dev/null+++ b/references/styles/storybookDraw.md@@ -0,0 +1,21 @@+# Storybook pencil + watercolour, drawn (`storybookDraw.ts`)++**Medium.** Soft graphite and pan watercolour on warm cold-press, the hand of `storybook.ts`.+The character is `drawBit`, called UNCHANGED through `Phase`, a `Gfx` subclass that decides which+of its groups draw in each pass and how far along each stroke is (a census pass records every+group's kind, bounding box and stroke count once).++**Order of marks.** (1) Construction in blue-grey: head and body ovals, gesture line, shoulder+line, the face cross, arm gestures, the footprint; left in the finished page as picture books+do. (2) A light pencil drawing of Bit, head first and down (groups ordered by the top of their+box), every contour drawn stroke by stroke at 0.36 alpha, 0.62 width. (3) Washes: the sheet's+warm ground, sky, peach light, grass, shadow, four flowers, then Bit back to front in+`drawBit`'s own order (legs, boots, arms, hands, body, collar, antenna glow, bulb, head,+cheeks), each spreading from the upper-left of its shape (toward the light). (4) The final line+at full weight, head first, then ground line, grass, pebbles, flower stems; last, paint flicked+off the brush.++**Gotcha paid for.** A gradient (`g.glow`) painted into a POOLED layer changes how Chromium later+rasterises pencil strokes into that same layer: 1/255 on every stroke pixel, so frame order+leaked into pixels (5/6, then 4/8 probe frames differed). The glow is painted on its own cached+surface and copied in; the pool never sees a gradient. Now 8/8 identical.diff --git a/references/styles/sumiE.md b/references/styles/sumiE.mdnew file mode 100644index 0000000..6206126--- /dev/null+++ b/references/styles/sumiE.md@@ -0,0 +1,52 @@+# Sumi-e (ink painting on xuan)++Module: `engine/src/canvas-core/sumiE.ts` (kit: `sumiEKit.ts`). Hero: bamboo in wind with a tree sparrow.++**The medium, physically.** One soft goat-and-wolf-hair brush, loaded from an inkstone, on unsized+xuan paper that drinks ink the moment it touches. Nothing is corrected or covered: every mark is+one gesture, laid once.++**The mark.** A brush of real hairs (`brush()` in the kit). Each hair carries its own ink load and+spends it with travel, edge hairs first. Loaded, the hairs merge into one solid mark; running dry,+they skip where the paper wins, which gives flying white (飞白): bare-paper streaks running *with*+the stroke, and split hairs splaying at the lift. The brush is a cone: outer hairs touch down later+and lift sooner, so ends are pointed or rounded, never square.++**The edge.** Soft and feathered where wet: at every slow point (touch-down, the pause at a node,+the lift) the ink bleeds into the fibres as a halo with fine feathers wicking outward. Broken and+bristled where dry. `wet` > 0 lays a stroke into damp paper and softens the whole edge (the+sparrow's belly wash). There is never a drawn outline.++**Tone.** Only by dilution, the five inks: scorched (1), thick (0.82), heavy (0.6), light (0.38),+clear (0.2). Dilute sumi goes a little cool, never brown. A single stroke never stacks with itself+(it is rendered as one opaque mark, then laid at its tone); ink darkens only where a second stroke+crosses the first, which is why overlapping leaves show darker lozenges.++**Order.** The Mustard Seed Garden order: stalks first, each in single upward strokes one segment+at a time, the brush pausing and lifting at every node (segments short at the base, longest+mid-stalk); nodes in darker ink; branches out of the nodes; leaves as pressed-lifted strokes in+groups, front leaves thick ink, back leaves light; the bird in the manual's order (beak, eye, head,+back, wing, tail, belly, feet); dry accents (grass flicks, moss dots); the seal stamped last.++**Palette.** One ink stick, five dilutions, and one cinnabar seal (`#b8352b`, multiplied, with the+glyphs cut in so they print as paper). The glyphs are an invented seal-script mark, not text.++**Paper.** Warm unbleached xuan `#f3ede0`, long vat fibres and bark flecks drawn as geometry in+the ground, `paper` at 0.1 and `coldpress` at 0.045 multiplied over everything. No tooth.++**Not its nearest neighbour (`wren`, ink & line-wash).** Wren washes colour first and then draws+a flexible-nib LINE round the forms; sumi-e has no line and no colour: the form IS the brush+stroke, one gesture per leaf, and tone comes only from dilution. Wren's washes pool at the+bottom edge of a shape; sumi-e ink bleeds at slow points of the brush's path, and dries into+flying white along its length.++**Motion grammar.** The film is the painting being made: a stroke grows along its path at a+hand's pace (long stalk segments fast, bird strokes slower), a slow point keeps soaking after the+brush leaves it (the halo grows over a few frames), a beat of pause between passes, the seal+pressed in one short press. Nothing fades or scales in.++**Kit primitives (candidates for core).** `runProcess` + `timeline` (a still that draws itself as+timed ops over an extend-only done-cache) and `brush` (hair-model stroke with ink load, flying+white and fibre bleed). Films built on them should set `meta.raster: "cpu"`: the extra cached+surface otherwise pushes Chromium into mixing GPU and software rasterisation, and frames stop+being identical across render orders.diff --git a/references/styles/toyBrick.md b/references/styles/toyBrick.mdnew file mode 100644index 0000000..be92545--- /dev/null+++ b/references/styles/toyBrick.md@@ -0,0 +1,17 @@+# Toy brick · `toyBrick.ts`++**Medium, physically.** Moulded ABS toy bricks, rendered in orthographic view (azimuth 45, elevation 30). Zero hand marks. Real units (`toyBrickKit.ts`): 1 stud pitch = 20 LDU, brick 24, plate 8, stud 12 wide and 4 high, so the 5:6 brick proportion is right by construction. Never name the trademark anywhere.++**The mark.** The part. Flat plastic fill in a real toy-brick colour (fixed table, spec 13 rule 9), one tone per face by the cube rule (top +0.10, lit +Z side 0, far +X side -0.22), a bevel highlight where a top meets a visible side and down each visible vertical corner, a dark seam hairline where one part meets the next, studs as real cylinders (shadow crescent on the top they stand on, lit left / dark right side band, top ellipse, highlight crescent toward the light).++**The edge.** Crisp plastic edges, softened only by the bevel strip. The only blur in the plate is the ground shadow: each part's box swept along the light onto the baseplate, filled at 1/5 size and drawn back up.++**Order.** Instruction-booklet grammar: bare backdrop, the baseplate drops in, then step by step (each step starts on a beat, parts seat in at most four 5-frame slots), bottom up and back to front inside a course; parts fall straight down their insertion axis on an ease-out, ghosted from 35% alpha while travelling, seat with a one-frame 0.5 LDU press-fit. The current step's parts wear the booklet's yellow outline until the next step begins. A short settle (the whole model pressed home, 1 LDU) and the hold.++**Painter's order.** No z-buffer: per frame, parts are ordered by pairwise separating axes on their boxes (X, then Z, then Y), only for pairs whose screen boxes overlap (Kahn's sort). Settled parts are cached as one layer keyed by the exact set of settled ids; anything moving is drawn over it, followed by every settled part that stands in front of it.++**Palette & backdrop.** Blue water baseplate, Light/Dark Bluish Grey quay, Red + Black hull, Reddish Brown deck, White superstructure, Medium Azure glass, Yellow funnel, Orange/Reddish Brown crates. One flat studio backdrop colour.++**Not its neighbour.** `fox` (cut-paper collage) is torn paper with a lift shadow per piece and a hand behind every edge; here the look is manufactured and the process is assembly, not drawing.++**Motion grammar.** Rigid: no squash, no stretch, no bounce. Take-apart is the build reversed frame for frame.diff --git a/references/styles/woodcut.md b/references/styles/woodcut.mdnew file mode 100644index 0000000..54ba076--- /dev/null+++ b/references/styles/woodcut.md@@ -0,0 +1,36 @@+# Ukiyo-e colour woodblock (`woodcut.ts`, `woodcutKit.ts`)++**Medium.** Water-based pigment with rice paste, brushed onto carved cherry blocks and printed by+hand onto damp kozo washi with a baren, one block per colour, the sheet laid each time against+the kento (an L-notch and a straight guide in the block's margin).++**Marks.** The KEYBLOCK line (sumi) is a ridge left standing between two knife cuts: its width+steps where the carver re-set the knife and wanders a little between (`carved()`), the two edges+wobble independently, and every end is a flat oblique chisel cut. No brush swell, no pen taper.+Solid blacks (crest, primaries, neck streaks) are knife-edged areas (`gouged()`). Colour is FLAT,+shaped only by where the wood was left standing; large flats show the plank's growth rings and+the goma-zuri speckle where the baren rubbed thin (`grain()`). Tone is only BOKASHI: the inked+block wiped with a damp cloth so the colour runs from full to nothing with a wavering edge.++**Edge.** The keyline's hard knife edge. Colour flats land a hair off their keylines (kento+registration is good, never perfect): each block has its own small offset. A colour block is+CUT AWAY where another subject owns the area (the sky block is carved round the herons and the+bridge), so white is bare paper, never a pale ink.++**Order.** Keyblock first (the kento pressed blind into the bottom margin with it). Then the+colour blocks, lightest to darkest: usuzumi sky, kihada yellow, far bank, heron grey, wood,+near bank, water, rain grey. Bokashi blocks last: the sky darkening to the top, the river+deepening toward us, the bridge's shade on the water beneath it.++**Palette.** Sumi #1f1b18, usuzumi #c6c1b0, yellow #d49c3a, heron grey #9fa4a4, far bank #adaf9c,+wood #a77a4a, water #9ab5c4, near bank #7d8a73, rain #8a8983, bero-ai #2c4a78, indigo #3a4557.++**Paper.** Warm kozo washi, a faint cloud, long soft curling bast fibres; a bare margin.++**Not riso, not halftone.** No screen, no dots, no fluorescent overprints mixing into new colours.+Flat knife-shaped colour, one carved key line, bokashi for tone.++**Motion grammar (the pulls).** Each block is a PULL: the baren works over the back of the sheet+in overlapping zig-zag rows and the colour comes through where it has passed, only over the+block's own area (a small block is a quick pull). A breath between pulls while the next block is+inked. The last pull lands, and the print is the still.diff --git a/references/styles/wrenDraw.md b/references/styles/wrenDraw.mdnew file mode 100644index 0000000..6149598--- /dev/null+++ b/references/styles/wrenDraw.md@@ -0,0 +1,30 @@+# Ink & line-wash, drawn (wren draw-on)++Module: `engine/src/canvas-core/wrenDraw.ts`. Plate: `wren.ts` (unchanged). Hero: a Eurasian wren+singing on a hawthorn twig.++**The medium, physically.** Watercolour washes on cold-press paper, then a flexible steel nib in+dark ink over the dried washes.++**The marks, in order.** Every wash goes down first, then all the pen work, then the spatter.+- **A wash is laid as a bead.** The loaded brush touches the top of the shape, and the bead of wet+ paint is pulled down it, with a wavering wet front and a darker line of pigment riding that front.+- **The pigment settles.** Once the shape is covered, the pigment slides down and pools along its+ bottom edge (the gradient band sinks and deepens).+- **The backrun.** Where a second, wetter drop touched the damp body, a pale cauliflower opens+ outward and its crinkled dark rim rides the edge.+- **Wash order.** Background (one big bead across the sheet), twig, leaves, haws, and the haw+ highlights lifted out; then the bird light to dark: tail, body (with its backrun), belly buff,+ rufous back, wing, the eyebrow lifted, the eyestripe.+- **The pen.** The bird first, as the focal subject: contour (left open where the light eats it,+ pressed at the belly), bill and gape, eyestripe, eye, breast flicks, tail and its barring, wing,+ covert spots, flank, legs and toes. Then the twig: bark edges, thorns, ticks, leaves, haws. Each+ line grows along its path through `g.pen({ progress })`, heavy where pressed, hair-thin at the lift.+- **Spatter.** The pen is shaken, and the dots land one after another.++**Exactness.** `wren.ts` is untouched, so its hero md5 is unchanged. The process re-authors the+same geometry as timed marks. In line-wash order, the bird's washes composite before the twig's+ink (the still does the twig whole, then the bird), so the finished process differs from the still+by about 240 overlap pixels (57.7 dB PSNR). The last 30 frames are therefore `drawWren` itself,+byte for byte. That needs GPU raster (the default, as wren has): with `raster: "cpu"`, or with the+still cached on an offscreen surface, the hold was measured NOT identical to the wren still.diff --git a/references/workflows/adapt-a-style.md b/references/workflows/adapt-a-style.mdnew file mode 100644index 0000000..b584ceb--- /dev/null+++ b/references/workflows/adapt-a-style.md@@ -0,0 +1,62 @@+# Adapt a style from a picture someone brings++"Here is an image, draw in that style." The rule: **borrow the hand, never the picture.** A hand+is a way of making marks: what touches the paper, what the edge does, the order things go down,+the paper, the palette. The picture is the subject, the composition and the layout, and none of+that crosses over.++Numbers help you look; they do not decide. Every statistic of an image mixes subject, layout,+lighting and medium, so a mostly empty page reads "light, few edges" whatever hand drew it, and+lettering reads as "line". The verdict is a written recipe and a side-by-side of a DIFFERENT+subject drawn in that hand. (On the two proofs below, the statistical nearest plate was wrong+both times: charcoal and broken-colour for a watercolour, wren for a scrapbook.)++## The workflow++1. **Analyze.** `node tools/analyze-style.mjs <image> --json <dir>/profile.json` (from `engine/`).+ Exclude anything that is not the hand, UI above all: `--exclude x,y,w,h;x,y,w,h`, or+ `--crop x,y,w,h` to a clean region. It prints palette (OKLab k-means, paper and ink, area+ shares), value key and contrast, line presence and width, fill direction and coherence+ (structure tensor on the grain), stroke length, speckle, pooled rims, edge hardness shares,+ spectrum slope, a periodic lattice (halftone or regular ruling), and the nearest plates with+ the numbers that match and differ.+2. **Look.** Open the image at full size AND at a 3x crop of a busy region. Write what you see+ before trusting any number. Read the profile only for what the eye can miss: a stroke+ direction, a halftone pitch, whether edges pool.+3. **Write the MEDIUM RECIPE in words**, as the header comment of a new plate, before any code:+ - **MARK**: what touches the paper, how wet or dry, what one unit mark is.+ - **EDGE**: hard, soft, lost, pooled, torn, deckled; where the edge darkens or disappears.+ - **ORDER**: what goes down first and what last. The order is half the hand.+ - **PAPER**: colour, tooth, age; which tiles at what opacity.+ - **PALETTE**: the colours, and the value range they live in.+ Add what it is NOT: which plate it is nearest, and the one or two things that make it differ.+4. **Pick or grow the nearest plate.** Nearest by eye, with the profile as a tiebreak. Reuse its+ kit and change the MARK; a recolour is a failure (`references/styles.md`, "Your own style").+5. **Draw a DIFFERENT subject in that hand.** New subject, new composition, same recipe. The+ subject must still read: give it its own value step and temperature against the ground.+6. **Compare side by side**: `node tools/compare.mjs <reference> <new.png> --out compare.png+ [--exclude ...]`. Critique in writing: mark, edge, order, paper, palette, one line each,+ "matches" or "differs because". Re-run `analyze-style.mjs` on your still as a diagnostic.+7. **Iterate** on the recipe, not on the numbers. Two or three rounds is normal.+8. **Save it as a house style**: `styles/house/<name>.json` with the plate, the recipe, key+ params, the profile summary, and provenance: the reference's sha256, its filename, the date,+ who brought it, `embedded: false`, and a sentence on what was NOT taken from it. From then on+ every piece for that brand uses that hand.++## The no-copy rule++- Never trace, re-lay-out or re-stage the reference. Its subject, composition, characters,+ signature motifs and text are not material. A living artist's signature motifs are never+ reproduced; ids and labels use technique names.+- No reference pixel is ever drawn. The art core never reads the image; only the tools do.+- The user's own image may be EMBEDDED (as an asset) only when they ask for exactly that.+- SSIM or pHash distance cannot certify "not a copy", and a small style distance cannot+ certify "a convincing adaptation". The rule is kept by construction: new subject, new layout.+- Teach mode is the one sibling allowed to follow a picture closely: see `teach-drawing.md`.++## Proofs (2026-09-25)++| Reference | Hand, in one line | New plate | Proof |+|---|---|---|---|+| a pastel watercolour backdrop (terminal UI excluded) | jagged-coast puddles, pooled rims, bare-paper rests, spatter, gouache sparkles | `adaptAquarelle.ts`, a moon jellyfish | `styles/house/pastel-blotch.json` |+| an explainer frame (Ritwika, f_10) | tidy torn pastel cards with soft shadows, typewriter, thin pen diagrams, one engraving | `adaptScrapbook.ts`, why sourdough rises | `styles/house/quiet-scrapbook.json` |diff --git a/references/workflows/character-consistency.md b/references/workflows/character-consistency.mdnew file mode 100644index 0000000..c48708c--- /dev/null+++ b/references/workflows/character-consistency.md@@ -0,0 +1,75 @@+# Workflow: a character that stays itself++> "I want to make a movie about this specific character." The character is built ONCE, as a+> module, approved ONCE, as a model sheet, and from then on every still, shot, film and style+> POSES it. Nothing ever draws it again. Worked example: Mira (`engine/src/canvas-core/characters/mira/`).++**Why.** `storybook.ts` and `print.ts` both draw Bit, from two separate sets of control points.+Change one and the other is a different robot. A character drawn per shot drifts per shot: the+glasses change size, the coat changes yellow, the hand grows a sixth finger. The fix is structural,+not diligence: one source of truth, and a gate that says when a shot departs from it.++## The module (one file per character, plus its poses and palettes)++| Export | What it is |+|---|---|+| canon + spec | a canon ROW (`human/canon.ts`), height, body and head specs |+| rig | the 3D skeleton the canon implies, with joint limits (`human/skeleton.ts`) |+| drawn views | parts a volume can't describe (a fringe, a cowlick) authored as 2D shapes in 3 views with matching points, blended by view angle (`view25d.ts`, Rivers et al. 2010) |+| palette ROLES | `coat`, `skin`, `hair` ... each with a hue family; every hand MAPS the roles in its own medium (`palettes.ts`) |+| distinguishing features | glasses, fringe, cowlick, freckles, raincoat, satchel, wellies: part ids plus the views they must appear in |+| `pose(p)` | validates a pose; throws if any joint leaves its range |+| `toScene(pose, camera)` | the character as a Scene: parts in paint order, each a union of polygons plus marks, in role colours |++Hands render any Scene with their own marks: `storybook`, `marker`, `riso`, `woodcut`,+`scratch`, `sumi`, `pencil` (in `character/render/`), each built on its plate's kit. The geometry+every hand receives for one pose is identical (the gate asserts it).++**Consistency is style-free.** The module is a spec (features, proportions, palette roles, signature+shapes), not a look. Line hands draw the Scene; GRID hands (`render/grid.ts` → `pixel.ts`, `brick.ts`)+re-express it in their own units: sample the top part per cell, exaggerate small rings (glasses) to a+minimum radius, and drop what a sprite can't hold (lids, brows, temples). Identity is then checked on+the cells, not the scene (`character/identity.ts`), plus silhouette IoU against a finer sampling.++**The drawing layer (illustrator-first, IN PROGRESS).** The skeleton, canon, limits and balance are the+invisible checker and pose source. Visible masses are designed sweeps (`character/design.ts`): a gesture+curve through the joints, an authored section table along it, the silhouette taken perpendicular to the+curve, split at joints with overlap so no seam shows. Mira's coat, sleeves, legs and boots and the baker+(`characters/theo/baker.ts`) use it; the scene carries `gesture` curves for a lay-in pass. Not done yet:+per-view hand-placed contour control points, drape from contact points for all clothing, landmarks as+contour breaks on the drawn layer. The older Theo figure model still renders the volumes literally.++## Steps++1. **From a description**: write the identity in one paragraph (age, canon, the 5-8 features a+ child would draw from memory). Pick the canon row; if the look needs a bigger head, DECLARE a+ stylised row, keep the body real. **From a user's image**: list the features, sample the colours+ into roles, read proportions against a head-unit grid, draw the image's own view first; views the+ image does not show are invented and labelled as invented on the sheet.+2. **Build the module**: spec, roles, features, clothing as inflated body blobs, 2.5D parts for+ hair, a pose library built from placed feet, solved legs, balance and reach targets.+3. **Model sheet** (`miraSheet.ts`): turnaround (front, 3/4, profile, back) on a head grid, six+ expressions, six poses, six hands, a scale line-up. Look at it at full size against+ `references/anatomy.md`'s look-at-it list. ✋ **The one approval.** It pins the version.+4. **Prove the hands**: the same pose and camera in every hand you will use (`miraTriptych.ts`,+ and `miraEveryHand.ts` for nine hands, each tile at full size from `miraTile.ts`). If she reads as+ different girls, fix the hand's role mapping, not the character.+5. **Use it**: shots import the module and pose it. A film computes a pose per frame (the walk is+ footsteps, not keyframes) and hands it to `toScene`.+6. **Change it**: any change to the module bumps its version and re-renders the sheet.++## Invariants the gate checks (`node tools/character-check.mjs`)++- canon ratios and segment lengths; bone lengths constant in every pose; left/right symmetry;+- every library pose inside joint limits; standing poses balanced; feet on, not through, the floor;+- five digits in length order, knuckle arc, thumb meets index in the pinch;+- every distinguishing feature present in every view it should be (ten views, both sides);+- every palette role inside its hue family in every hand (riso measured as the overprint it prints);+- scene geometry deterministic; a film's planted feet do not slide.++- per hand in the every-hand sheet: the feature checklist (scene features for line hands, cell+ features for pixel and brick), palette roles in family, grid IoU > 0.8 for pixel and brick.++Each has a negative twin that must fail. What the gate cannot see: whether she LOOKS like herself.+Silhouette overlap is identical by construction across line hands, so it proves nothing there; the+model sheet and the every-hand sheet, looked at by a person, are the identity test.diff --git a/references/workflows/drawing-process.md b/references/workflows/drawing-process.mdnew file mode 100644index 0000000..4d70060--- /dev/null+++ b/references/workflows/drawing-process.md@@ -0,0 +1,38 @@+# A picture that draws itself++Every hand in the gallery ships two things from one source: the finished still and a film of it+being made, mark by mark, in the order an artist in that medium works. The film's last frames+are the still, pixel for pixel. This is the timelapse people share, the making-of, the teaching+step, and the explainer's diagram assembling.++## Rules++- **Frame 0 is the bare ground**: paper, board, linen, black clay, a blank screen.+- **The medium's own order**: watercolour lays in pencil, then light washes, darker washes, detail,+ line. Woodcut prints the keyblock, then colour blocks light to dark. Pixel art blocks flat+ masses, cleans the line, shades clusters, adds highlights. Oil tones the ground, blocks in dark+ to light, finishes with impasto. Embroidery pulls each stitch through. Each plate's header says+ its order.+- **Marks are made, never faded**: a stroke grows along its path, a wash spreads from where the+ brush touched, a brick drops and seats, a stamp lands.+- **A hand's pace**: long strokes fast, fiddly ones slow, a short rest between passes (up to half a+ second; the gate allows it for `kind: "drawing"`).+- **The last stretch is the still**: declare it with `meta.holds` so the gate knows it is meant.++## How to build one++Declare `meta.kind: "drawing"` and the final hold. Then either:+- **Author the process**: list the marks as timed operations and replay them over a cache that only+ grows (the pattern in `colouredPencilKit.ts` `replay`, `sumiEKit.ts` `runProcess`,+ `brokenColourKit.ts` `staged`); or+- **Add a clock to an existing plate**: an optional parameter that gates each draw call by its+ pass; with no clock the plate draws exactly as before (check the hero's md5 before and after).++Set `meta.raster: "cpu"` for process films built on replay caches; mixed GPU and software+rasterisation breaks determinism.++## The gate for drawing films++`kind: "drawing"` judges dead air over one second at a 0.02% changed-area floor (fine pencil lines+change little per frame) and allows rests up to half a second. A freeze longer than that still+fails, because a viewer sees it.diff --git a/references/workflows/explainer.md b/references/workflows/explainer.mdnew file mode 100644index 0000000..6c9d664--- /dev/null+++ b/references/workflows/explainer.md@@ -0,0 +1,50 @@+# Explainers and infographics++An explainer teaches one idea per chapter; an infographic makes numbers readable at a glance.+Both are judged on whether a viewer understands something true afterwards, so the writing and+the facts come before any drawing.++## The research ledger (before the storyboard)++For every claim the piece makes: the claim in one sentence, the source (URL or exact passage),+your confidence, and what you are simplifying. A claim you cannot source is cut or clearly shown+as a metaphor. Numbers on screen come from the ledger, and each carries its source in a comment+beside the code that draws it. Record the audience (age band, expertise) because it sets the+reading level and the pace.++## The storyboard (`STORYBOARD.md`)++One row per chapter or shot: claim id, the one-sentence takeaway, the on-screen caption, the+visual metaphor and where it stops being literal, what the recurring character or token does,+the frame range on the beat grid, the music and sound cues, the transition out. Show it for+review when the person wants that step; otherwise build from it.++## Picture rules++- **One concept on screen at a time.** Build it up in the order the viewer needs it, marks drawn+ on, never faded in. The drawing process (`drawing-process.md`) is the explainer's best tool:+ the diagram assembling IS the explanation.+- **Captions are drawn lettering** (`lettering.ts`, `drafting.ts`, a style's own hand), sized for+ the smallest shape the piece ships in. Keep them short enough to read twice in their time on+ screen.+- **A recurring guide** (a mascot, a hand, an object) gives continuity across chapters; build it+ once as a character module.+- **Charts are drawn to scale** from the ledger's numbers, labelled with the values they reach,+ with annotations in the style's hand (the scrapbook hand's red pencil marks, a blueprint's+ dimension lines).+- **Styles that suit explaining**: scrapbook (archival, research-y), blueprint (technical),+ chalkboard (a lesson), flat vector and isometric (products and systems), paper-craft+ (playful, for children), marker comic (energetic). Say why you chose one.++## Infographic stills++Same ledger, one page. A clear reading order (top-left in, one path through), one hero figure,+three to seven supporting facts, every number sourced. Ship it as a still at each shape the+person needs; a vertical version is a relayout, not a crop.++## Checks++- Every caption on screen long enough to read in the chosen audience's pace (a human pass).+- Every chapter owns a non-empty frame range; the chapters tile the film with no gaps.+- A phone-width check of the smallest shipped shape: no caption under a readable size.+- Delivery says which facts were independently checked and what was simplified.diff --git a/references/workflows/interactive.md b/references/workflows/interactive.mdnew file mode 100644index 0000000..e9a6ac5--- /dev/null+++ b/references/workflows/interactive.md@@ -0,0 +1,150 @@+# Interactive web animation++Hand-drawn pieces that live on a web page and answer the person using it. They follow the pointer,+react to hovered and focused buttons, draw themselves as you scroll, and read along with a form.+None of this is a video or an embedded player: the piece is part of the page's UI.++Three worked demos. Each is one self-contained HTML file that opens offline:++| Demo (piece) | What it does |+|---|---|+| **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. |+| **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+code (`drawBit`, `limb`, `hand`), unchanged.++## The contract: a frame is a fact, given its input log++```+draw(ctx, tick, env, stateAt(tick, log, piece.input))+```++Nothing else in the contract moves. The art stays pure: a `Piece` never sees a clock, an event or the+DOM. It gets a 60 Hz tick and an `InputState`, and paints the whole frame. The host+(`hosts/interactive.ts`) owns time and the DOM, and turns the person into an append-only `InputLog`.+`stateAt` (`canvas-core/input.ts`) is a pure fold of that log, checkpointed every 60 ticks. The same+log replayed in any page, in any order, cold or warm, draws the same pixels, and `tools/replay.mjs`+proves it for every emitted page.++| Question | Answer |+|---|---|+| Two events in one tick? | They apply in log order. Ticks never decrease; the reducer throws if they do. |+| 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. |+| 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. |+| Typing? | Only the length and caret position are logged, never the text. A log holds no personal data. |+| Reduced motion? | It is in the log. The untouched piece is still, reactions are short expression crossfades, and a scroll piece shows its finished picture. |++## Making one++1. **The piece**, in `engine/src/canvas-core/<name>.ts`:+ ```ts+ export const myPiece: Piece = {+ meta: { title, W: 560, H: 560, loop: 480, alt: "what a screen reader hears" },+ input: { springs: {+ look: { omega: 0.3, target: (d) => lookTarget(d, FACE) }, // eyes, quick+ arm: { omega: 0.16, target: (d) => (attentionOf(d) === "cta" ? 0.5 : 0) },+ } },+ bake: function* (env) { usePaper(env, SHEETS); yield; bg(env); yield* bakeBit(env); },+ draw: (ctx, tick, env, s) => { /* sprites + a few live marks */ },+ };+ ```+ `InputState` gives the art `pointer`, `hover`, `focus`, `attention`, `pressed`, `scroll`, `state`,+ `rects`, `fields`, `since`, `count`, `spring`, `vel` and `reduced`. The helpers are `gaze`, `lean`,+ `parallax`, `lookTarget`, `clip`, `ticksSince`, `reactionSeed`, `scrollSpan` and `ease`.+ Untouched, the piece must loop (`meta.loop`) with no dead second.+2. **The web profile** (`bake.ts`). A plate draws a character in about 130 ms at DPR 2; a page has+ 6 ms. Draw once at mount, then composite each frame.+ - `bake` crops exactly what the drawing touched into a sprite.+ - `bakePart` runs chosen groups of a plate's own drawing function.+ - `usePaper` multiplies the sheet into every sprite once (multiply distributes over source-over), so frames need no sheet pass.+ - `blit` on whole device pixels stays crisp.+ - Rotate at most one composed layer per frame: a rotated blit costs about 8x an axis-aligned one on a software canvas.+ - Never enlarge a bitmap.+ - The scroll hero shows the other pattern: the plate recorded as a mark log, four stage images, and strokes as masks.+3. **The page.** Mark UI with `data-anidoodle="<name>"`, add `<ani-doodle piece="<kebab-name>">`+ (plus `scroll-track="#selector"` for scroll pieces), and put `<!--anidoodle-->` where the module+ goes. UI states: `document.querySelector("ani-doodle").setState("success")`.+4. **Emit, gate, record:**+ ```bash+ node tools/emit-interactive.mjs myPiece --page page.html --out out/my-piece.html # also writes out/my-piece.mjs+ node tools/replay.mjs out/my-piece.html --out out/my-piece.replay.json+ node tools/record-interactive.mjs out/my-piece.html choreo.mjs --out out/my-piece.mp4+ ```+ The `.mjs` is the module a real site loads, via `<script type="module" src>` or `import { mount, piece }`.+ The `.html` inlines it, because browsers refuse module imports from `file://`.++`mount(el, piece, opts)` returns `setState`, `pause`, `play` and `destroy`. There is no framework.+The host provides:+- a visible pause button;+- `role="img"` with the piece's `alt`;+- a fade-in once baked;+- no drawing offscreen or in hidden tabs (the clock keeps time);+- no sound.++## What the replay gate proves++1. A scripted person drives the page in real time at DPR 2: sweeps, hover on every target, rapid+ in/out reversals, press, click, cancel, Tab and Enter, typing, a resize **while hovering**, the+ wheel to the bottom and back, and state changes. Every third drawn frame is hashed live.+2. The same on a touch phone (taps, a swipe).+3. A fresh page gets only the log and redraws every sampled tick in reverse, then forward, then cold+ (brand-new env, every sprite re-baked). All three must hash exactly as live.+4. An empty log equals `restState` (built without the reducer); the live tick-0 configuration changes+ nothing; the loop closes; and the untouched piece moves.+5. Reduced motion: still when idle, and a full session renders.+6. Frame time at DPR 2 (with raster forced, and default), startup, sprite memory, and bundle size.++Hashing needs one renderer: Chromium silently moves a GPU canvas to software after its first+readback, so hashed pages run with `window.__ANI_RASTER__ = "cpu"` from the start.++**Two traps the gate caught, both platform behaviour and not bugs in the art:**++- **A canvas remembers gradients.** In Chromium, a 2D canvas that has *ever* filled with a gradient+ (radial or linear, e.g. `Gfx.glow` or `Gfx.vignette`) rasterises later drawing differently, by up+ to 8/255. This holds even after its pixels are cleared and its `fillStyle` is reset. Solid fills+ and patterns do not do this. Because the Gfx layer pool and the bake scratch are shared, a sprite+ came out differently depending on which sprites were baked before it: cold != warm. `bake()` now+ calls `ctx.reset()` on every shared surface first (and drops the pool where `reset` is missing).+ The film engine shares the same pool across frames, so the same order-dependence may exist there.+ It is a lead for the determinism doctrine's unexplained first-run 0/12, not yet a proven cause.+- **GPU to software on readback**, above. Hash only canvases that were software from the start.++## Measured (headless Chromium 1140, this Mac, 1280x800 at DPR 2, September 2026)++| Demo | Gate | Frame p95 (raster forced / default) | Ready | Sprites | Module |+|---|---|---|---|---|---|+| Landing mascot | 22/22 | 4.1 ms / 0.3 ms (2.8 on an earlier run) | 1.9 s | 152, 35 MB at scale 1.5 | 50 KB (20 KB gzip) |+| Form mascot | 22/22 | 3.5 ms / 0.3 ms (2.2 on an earlier run) | 2.0 s | 152, 31 MB at scale 1.25 | 51 KB (20 KB gzip) |+| Scroll hero | 22/22 | 1.8 ms / 0.4 ms | 2.0 s | 4 stages + one patch per stroke, 34 MB at 1.25, 58 MB at 2 | 48 KB (19 KB gzip) |++The budget was 6 ms p95 at DPR 2. The first build measured 7.8 ms, because the head rotated ten face+sprites a frame and the paper multiplied the full canvas every frame. Composing the head once and+baking the paper into the sprites brought it to 2-4 ms (it varies by run on a shared machine). Single frames reach 10-22 ms when a+reaction first needs a cel, or during a rescale swap.++## Limits++- **Frame time is measured on headless Chromium's software canvas**, which is the honest upper bound+ on this machine. A GPU-composited page draws the same frame for well under 1 ms of JS. Measured on+ no real phone.+- **Sprite memory is the price of speed.** It is tens of MB at scale 2, and the scroll hero is the+ heaviest (one patch per stroke). Budget it on low-memory phones, or cap `maxScale`.+- **Startup.** Baking takes about 2 s before the canvas fades in (software raster, DPR 2); the page is usable meanwhile. It happens again on a resize that changes the scale (debounced and off the visible frame, but it doubles memory while both scales exist).+- **Moving parts carry their paper grain** (`usePaper`): exact at rest, a few percent of tone off in+ motion.+- **Continuous poses are quantised**, as hand-drawn animation is: arm lift in 16 cels and the key in+ 8 phases. Only the head rotates, as one layer.+- **Logs grow** with pointer movement (coalesced to one move per tick). Hours-long sessions are not+ compacted.+- **Chromium only, verified.** Other browsers are expected to be deterministic within themselves, not+ bit-identical to Chromium. `ctx.reset()` is needed for the order-independence fix; without it the+ pool is dropped instead.+- **The plates were not drawn for this.** Bit's expressions (brows, mouths, lids) are new marks in the+ plate's pen, not the plate's. A new character needs its own parts list.diff --git a/references/workflows/launch-video.md b/references/workflows/launch-video.mdnew file mode 100644index 0000000..7bd8dcd--- /dev/null+++ b/references/workflows/launch-video.md@@ -0,0 +1,35 @@+# Launch and product videos++A launch video makes one promise about a product and shows it being kept. It is a short film+with a job: the viewer should know what the thing is, why it matters to them, and where to get+it, in that order.++## Inputs the person brings++Product screenshots, a logo, UI captures, a repo link, a feature list. Images they bring may be+embedded (pinned by sha256, provenance recorded in the film's manifest); everything around them+is drawn in code. Never generate or fetch images.++## Shape of the film++1. **Hook in the first two seconds**: the problem, drawn being made (a tangle, a pile, a clock),+ never a fade from black.+2. **The turn**: the product arrives. A screenshot slides in on a drawn device frame, or the+ UI is redrawn in the chosen hand.+3. **Three proofs at most**: each feature shown doing something, one per beat group, with a short+ drawn caption.+4. **The payoff and the call**: the product name drawn on, the one-line promise, where to get it.+ Hold it long enough to read twice.++Length follows the content: 15 s for a social teaser, 30-60 s for a launch post, longer for a+walkthrough (then use chapters, `long-film.md`). Ship the shapes where it will run: `9x16` for+Reels/Shorts, `16x9` for YouTube and the site, `1x1` for feeds.++## Craft notes++- **Kinetic type is lettering**, stroke-drawn in the chosen hand, timed to the beat grid.+- **Screenshots are content, not decoration**: large enough to read on a phone, framed, with the+ part that matters called out by a drawn circle or arrow in the style's hand.+- **Music**: a style that matches the brand (drive/electronic for energy, minimalist mallets for+ calm confidence, lo-fi for friendly), with the product reveal on a true sync point.+- **Brand colours** map onto the style's palette roles; the style's hand stays intact.diff --git a/references/workflows/long-film.md b/references/workflows/long-film.mdnew file mode 100644index 0000000..6be565d--- /dev/null+++ b/references/workflows/long-film.md@@ -0,0 +1,41 @@+# Films of any length++A film is `meta.durationFrames` long, and that number comes from the story, never from a+template. Three minutes, five, twenty: the engine streams frame by frame, the gate measures+frame by frame, and nothing buffers the whole film. What changes with length is how you+organise the work.++## Up to about 90 seconds: one arc++The Film workflow in `SKILL.md` as written: three sentences (setup, transformation, payoff), one+token that returns, one cue table, one look still, one music sample, build end to end.++## Longer: chapters++A long film is a sequence of chapters, each with its own small arc, joined by one through-line.++1. **Write the spine first**: the through-line in one sentence, then one line per chapter+ (what changes in it). If a chapter changes nothing, cut it.+2. **One cue table per chapter, one master table** that places the chapters. Chapter tables use+ local frames; the master adds offsets. Retiming a chapter moves everything after it, and the+ checker runs at load on both levels.+3. **One style contract** (`STYLE-GUIDE.md` in the project) before parallel work: palette, line+ weight at final size, type size per shape, the characters' modules, the music style and its+ section moods. Chapters import it; nobody changes it privately.+4. **Transitions carry the story**: each chapter hands over with a match cut, a covered switch+ (a shape passing, a page turning, a fog at full density) or a shared token. A hard cut to+ black between every chapter is a slideshow.+5. **Music follows the chapters**: one theme, varied per chapter mood (see+ `references/music/`), with the transitions scored (pre-lap, pivot chord, texture handoff).+6. **Review per chapter, then once whole**: a contact sheet per chapter at one tile per beat,+ then the whole film once, with sound and without.++## Rendering long work++- Render chapters as separate films in parallel (`--workers` per film, one film per machine+ core pair), then join the MP4s with ffmpeg's concat demuxer. Each chapter is still exactly+ reproducible on its own.+- Draw budget matters more at length: cache finished layers under keys that name everything+ their pixels depend on, and keep the median frame well under 150 ms.+- The gate's dead-air check reads one small frame at a time, so a twenty-minute film costs+ time, not memory.diff --git a/references/workflows/start-here.md b/references/workflows/start-here.mdnew file mode 100644index 0000000..26ba806--- /dev/null+++ b/references/workflows/start-here.md@@ -0,0 +1,49 @@+# Start here: agree the piece with the person, then build++anidoodle makes many kinds of thing in many hands. Nothing about a piece is fixed in advance:+not its length, its shape, its style or its sound. So the first job is to find out what this+person wants, quickly, one question at a time, and to fill every gap with a stated default+instead of a guess.++## The intake (ask only what the request leaves open)++Ask one question per turn, with short options and your recommendation first. If they say "you+pick", pick, say what you picked and why in one line, and carry on.++1. **What are you making?** A still, a loop, a picture that draws itself, a story film, an+ explainer, an infographic, a launch or product video, an interactive web piece, a drawing+ lesson, a character, or a style matched from their image. The table in `SKILL.md` routes each+ one to its workflow file.+2. **Which style?** Show the gallery (`assets/gallery/styles.jpg`, one tile per hand; the list with+ each hand's medium is `references/styles/INDEX.md`). Recommend two or three hands that suit the+ subject and the audience, with one reason each. Offer two other routes:+ - **"Match my image"**: they bring a picture and you adapt its hand (`adapt-a-style.md`).+ - **"A house style"**: they already picked one before; load it from `styles/house/`.+3. **What shape and where will it live?** Square `1x1`, vertical `9x16`, wide `16x9`, portrait+ `4x5`, or any W x H they name. One source can ship several shapes (`references/formats.md`).+4. **How long?** Any length. A three-second sticker, a ninety-second story, a five-minute+ explainer, a twenty-minute lesson. Never cap it and never assume it. Long pieces get chapters+ (`long-film.md`).+5. **Sound?** Silent, or a score: name a music style and a mood per section+ (`references/music/`). Their own voice-over or track is theirs to bring; anidoodle composes+ and synthesizes everything else.+6. **Characters?** A new one (build it once, `character-consistency.md`), one they already have+ in a module, or one from their image (reference, embedded only if they ask).++Stop asking the moment you can build. Two questions answered well beat six asked.++## Defaults when they do not say++| Open question | Default | Why |+|---|---|---|+| Style | the hand whose recipe best fits the subject, named with a reason | a style is a decision, not a coin toss |+| Shape | `1x1` for social, `16x9` for web heroes and YouTube, `9x16` for Reels/Shorts/TikTok | where it lives decides it |+| Length | still: one frame; loop: 4-8 s; story film: long enough for its arc; explainer: one idea per chapter | the content sets the length, not a template |+| Sound | a film gets a score in the style that fits its mood; a loop or still is silent | silence is a choice too |+| fps | 30 (24 for a hand-drawn cartoon feel, 12 on twos for paper and stop-motion) | the medium's own rhythm |++## Write it down before you draw++One short brief file in the project: kind, style (and why), shape(s), length, sound (style ++moods), characters, the one-sentence idea. Everything the person said goes in their words.+Everything you decided is marked as yours so they can veto it in one line.diff --git a/references/workflows/teach-drawing.md b/references/workflows/teach-drawing.mdnew file mode 100644index 0000000..f730a2e--- /dev/null+++ b/references/workflows/teach-drawing.md@@ -0,0 +1,82 @@+# Teach drawing: a lesson from a request or from somebody's picture++Two asks, one machine:+- **"How do I draw a cat sitting?"** A basic-drawing lesson: you choose the subject's pose and+ construction, and teach it the way a drawing teacher would.+- **"Here is my drawing, show me how it's drawn."** Recreate the picture and teach one way to+ draw it. This is the one place anidoodle may follow a picture closely (the master copy: the+ user asked for THIS image). Label it **"a way to draw it, not a record of how it was drawn"**:+ nobody knows the real order, and the lesson must not pretend to.++A lesson is a **drawing score** (`engine/src/canvas-core/drawingScore.ts`): parts of the subject,+marks with stable ids, dependencies, teaching phases, layers, erasers and corrections, all+authored as data. One score gives the finished still, the timelapse, the step sheet and a replay+at any frame, from ONE renderer, so the last frame of the timelapse is the finished drawing.++## The workflow++1. **Name the subject and the medium physically** (header comment, like every plate): what the+ tool is, what the paper does, how tone is built, what the construction pencil is.+2. **State the anatomy / structure** that makes it read (realism-and-craft.md), and the+ construction a teacher would use for it (head ball + chest egg + haunch circle for a sitting+ cat; a box and its proportions for a block character).+3. **For a user image:** analyze it (`tools/analyze-style.mjs`), measure the big masses off it+ (bounding boxes, rows of lines, positions: a few lines of python or the profile are enough),+ and redraw them as marks in the matching medium. Pick the medium's plate kit for the marks.+4. **Write the steps first, then the marks.** 6 to 8 steps, in teaching order:+ placement and gesture → big shapes → construction → value masses → local colour → edges and+ details → accents. Not every medium uses every phase; construction can repeat (a "check and+ correct" step is construction). Each step carries:+ - `title` (a few words) and `caption` (24 words or fewer, drawn on the sheet and in the film),+ - `look`: what to look for, with a real proportion or measurement,+ - `how`: the technique (grip, pressure, direction, eraser),+ - `mistake`: the common mistake and why it goes wrong.+ A numbered reveal with captions is not a lesson. Teach something in every step.+5. **Author the score** with `ScoreBuilder`: `layer()`, `part(id, label, dependsOn)`, `step()`,+ then `add()` / `addAll()` / `erase()` under each step. Marks come from `drawingMarks.ts`:+ `stroke`, `hatch` (clipped to a region, density function for tone), `contour` (overlapping+ strokes, weight from a keep function), `sketchEllipse`, `guideLine`, `scribbleDot`.+ - **Construction in blue** on its own layer (`kind: "guide"`); **erase it** with an eraser+ pass (`erase()` with a ghost of 0.05 to 0.3: a kneaded eraser leaves a trace; before+ coloured pencil, lift it to a ghost, because wax seals whatever is under it).+ - **Corrections** are authored events: put the wrong mark on its own layer, erase that layer,+ draw the new mark with `supersedes: oldId`. The validator refuses a correction whose old+ mark was never erased first. Teach the correction: say what was measured and why it was wrong.+6. **Export three films** (see `lessonCat.ts` + `lessonCatSheet.ts` + `lessonCatFinal.ts`, and a+ `page-*.ts` host each): `lessonFilm(score)` (the captioned timelapse; its `.final` is the cold+ render for the identity gate) and `lessonSheet(score, { crop })`. Export+ `LESSON = { score, sheet, final, source? }` from the lesson module.+7. **Run** `node tools/lesson.mjs <lessonFilm> --out <dir> [--ref image --ref-crop x,y,w,h]`. It+ writes `<name>-steps.png`, `<name>-timelapse.mp4`, `<name>-contact.png`, `<name>-final.png`,+ `LESSON.md`, `gates.txt`, and runs:+ - **schema**: unique ids, parts and layers resolve, dependencies acyclic and in order,+ corrections erased first, captions at 24 words or fewer, every guide erased;+ - **identity**: the timelapse's last frame (prefix-cached replay) hashes the same as the+ finished drawing rendered cold;+ - **time travel**: sampled frames hash the same rendered forward, reversed, and each in a+ freshly mounted page;+ - **fidelity** (`--ref`, recreate lessons only): value-mass IoU against the user's image+ (the reference posterised to its own three values) and mean OKLab colour distance.+8. **Look at it.** Read the step sheet at full size, watch the contact sheet, and check that+ every step's caption is true of its panel. No gate can tell you whether the order reads like+ a hand working or whether the teaching is right.++## Grammar of the outputs++- **Step sheet**: one panel per step; everything from earlier steps pale under a paper veil,+ the step's new marks strong; an eraser step shows the erased state pale. Under each panel the+ step number, title, phase and caption, all as pen strokes (`drafting.ts`), never `fillText`.+- **Timelapse**: one mark at a time, each taking time in proportion to its length plus a lift;+ the step's caption is written on as the step starts; a title card first; a closing line and a+ held finished frame last. Steps start on the beat grid.+- **LESSON.md**: every step written out with look / how / mistake, its time in the film, its+ marks and parts, and the layers.++## Proofs (2026-09-25)++| Lesson | From | Steps | Marks |+|---|---|---|---|+| How to draw a cat sitting (graphite, blue col-erase, kneaded eraser) | a plain request | 8, including a measured ear correction | 844 |+| Clawd at the piano (coloured pencil) | the owner's crop of Kevin Ngo's piano film | 8, with the guides lifted to a ghost before colour | 9676 |++Outputs: `anidoodle-research/samples/adapt-teach/lesson-cat/`, `lesson-clawd/`.diff --git a/scripts/sync-codex-marketplace-plugin.sh b/scripts/sync-codex-marketplace-plugin.shnew file mode 100755index 0000000..a5480fb--- /dev/null+++ b/scripts/sync-codex-marketplace-plugin.sh@@ -0,0 +1,38 @@+#!/usr/bin/env bash+# sync-codex-marketplace-plugin.sh+#+# Regenerates plugins/anidoodle/ (the Codex marketplace plugin) from the canonical skill at+# skills/anidoodle/ and .codex-plugin/plugin.json.+#+# WHY: Codex resolves marketplace plugins only from a subdirectory (./plugins/<name>), and its+# install copy does not follow symlinks, so the nested plugin must hold real files.+# WHY git ls-files: the mirror copies ONLY files tracked by git. Private work (gitignored+# recreations, scratch renders, node_modules) can never leak into the published plugin.+#+# Run before every release; scripts are idempotent (an in-sync tree gives no git diff).+set -euo pipefail+[ -n "${BASH_VERSION:-}" ] || { echo "ERROR: run with bash" >&2; exit 2; }++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+for marker in ".agents/plugins/marketplace.json" ".codex-plugin/plugin.json" "skills/anidoodle/SKILL.md"; do+ [ -e "${REPO_ROOT}/${marker}" ] || { echo "ERROR: REPO_ROOT looks wrong (missing ${marker}): ${REPO_ROOT}" >&2; exit 3; }+done++NESTED="${REPO_ROOT}/plugins/anidoodle"+mkdir -p "${REPO_ROOT}/plugins"+STAGE="$(mktemp -d "${REPO_ROOT}/plugins/.stage-XXXXXX")"+trap 'rm -rf "${STAGE}"' EXIT++mkdir -p "${STAGE}/.codex-plugin"+cp "${REPO_ROOT}/.codex-plugin/plugin.json" "${STAGE}/.codex-plugin/plugin.json"+cd "${REPO_ROOT}"+count=0+while IFS= read -r f; do+ mkdir -p "${STAGE}/$(dirname "$f")"; cp -p "$f" "${STAGE}/$f"; count=$((count + 1))+done < <(git ls-files skills/)++[ -f "${STAGE}/skills/anidoodle/SKILL.md" ] || { echo "ERROR: SKILL.md missing after copy (is it committed?)" >&2; exit 4; }+[ "${count}" -ge 50 ] || { echo "ERROR: only ${count} files copied; expected the whole skill" >&2; exit 4; }++rm -rf "${NESTED}"; mv "${STAGE}" "${NESTED}"; trap - EXIT+echo "Synced Codex marketplace plugin -> plugins/anidoodle (${count} tracked files, $(grep -o '"version"[^,]*' "${NESTED}/.codex-plugin/plugin.json" | head -1))"diff --git a/styles/house/pastel-blotch.json b/styles/house/pastel-blotch.jsonnew file mode 100644index 0000000..28cbc22--- /dev/null+++ b/styles/house/pastel-blotch.json@@ -0,0 +1,26 @@+{+ "name": "pastel-blotch",+ "title": "Pastel blotch watercolour",+ "plate": "engine/src/canvas-core/adaptAquarelle.ts",+ "nearest": "ranunculus",+ "recipe": {+ "mark": "a blotch: one loaded round brush set down and pushed about; one flat puddle of dilute pigment with a jagged coastline (big lobes plus a fine torn fringe); never an ellipse, never a directional stroke",+ "edge": "hard-dry: the puddle dries with a crisp, darker rim where pigment migrates to the edge and a paler bloom inside; no soft blending into neighbours; no drawn line",+ "order": "palest big puddles first; smaller, stronger puddles glazed over them (overlaps multiply into secondary colours); bare paper left between islands; a few spatter dots; white gouache sparkles with a halo last",+ "paper": "warm cream cold-press (#f5f1e6), coldpress tile at 0.1, paper tile at 0.05",+ "palette": ["#f7a86a", "#f7d77e", "#f5b5a6", "#eb97ad", "#cf95c6", "#b49ae0", "#a6e0bd", "#8fd3cc", "#9dbdec", "#5fb3b8", "#4f8fc4"],+ "subject rule": "the focal subject is painted in the same puddles but a full value step darker than the ground, in the opposite temperature (warm magentas on a cool ground in the proof), with a bare-paper reserve round it"+ },+ "params": { "puddleAlpha": 0.62, "rim": 0.8, "rimDarken": 0.72, "fringePx": 13, "firstPassBlur": 1.6, "bareRests": "one place in three" },+ "profile": { "file": "samples/adapt-teach/aquarelle/profile.json", "summary": "high key (mean L 0.84), contrast 0.23, 8 colours over 2%, chroma 0.064, no line, no measurable grain, edges 90% soft, no lattice; measured with the terminal window excluded" },+ "provenance": {+ "reference": "lightshot-aquarelle.png (1310x552), a pastel watercolour backdrop behind a terminal window",+ "sha256": "397bc0daeac41e18f6c3001c03582a7a8ab617a2b97377e8b7152538e6a89ae4",+ "broughtBy": "Alex Greenshpun (owner)",+ "date": "2026-09-25",+ "excludedFromAnalysis": "the terminal window, 228,188,854,176 (UI, not the hand)",+ "embedded": false,+ "copied": "nothing: the reference is an abstract backdrop; the proof subject (a moon jellyfish) and its composition are new"+ },+ "proof": ["samples/adapt-teach/aquarelle/adaptAquarelle-still.png", "samples/adapt-teach/aquarelle/compare-aquarelle.png"]+}diff --git a/styles/house/quiet-scrapbook.json b/styles/house/quiet-scrapbook.jsonnew file mode 100644index 0000000..3a8e085--- /dev/null+++ b/styles/house/quiet-scrapbook.json@@ -0,0 +1,26 @@+{+ "name": "quiet-scrapbook",+ "title": "Quiet archival scrapbook",+ "plate": "engine/src/canvas-core/adaptScrapbook.ts",+ "nearest": "scrapbook (v1 wave; the loud sibling: foxed parchment, ransom titles, copperplate everywhere)",+ "recipe": {+ "mark": "flat pieces of coloured stock with a fine torn deckle; typewriter strikes (one weight, each strike its own ink density); thin steady technical-pen diagrams; ONE small vintage engraving as ornament; a red pen and a blue pencil used once or twice each",+ "edge": "torn but tidy: an even fine deckle, never ragged; every piece throws the same soft shadow down-right (lamp upper left); ink lines clean and unhatched outside the engraving",+ "order": "page; cards laid down big first; coloured label chips; the diagram inked on its card; typed labels; the engraving; red and blue annotations last",+ "paper": "a pale warm sheet (#efe7d3), barely aged: soft mottle, slight darkening toward the edges; no foxing, tape or pegs",+ "palette": { "page": "#efe7d3", "ink": "#35302d", "duckEgg": "#bcd3d6", "rose": "#e3a3a6", "sage": "#7fa99e", "cream": "#f4efe3", "card": "#e6e1d2", "redPen": "#c44a36", "bluePencil": "#4f86c6" },+ "layout rule": "mostly empty page; pieces are islands with air round them; one diagram card is the focal piece"+ },+ "params": { "deckle": 3.2, "shadow": { "dx": 4, "dy": 6, "blur": 5, "alpha": 0.55 }, "typeCell": 0.86 },+ "profile": { "file": "samples/adapt-teach/scrapbook/profile.json", "summary": "high key (mean L 0.86), contrast 0.23, 5 colours over 2%, low chroma 0.03 with one vermilion accent, line presence 1.8% (mostly type), pooled rims 0.42 (card shadows), no lattice. The statistical nearest was wren: the empty page dominates the numbers, which is why the plate was picked by eye" },+ "provenance": {+ "reference": "refs/ritwika-explainer/frames/f_10.png (1280x720), frame 10 of Ritwika's explainer film",+ "sha256": "8d9f7315fb91a81b364235f77bd3653a794c97967cbf99a8a24fcfed4d26fb34",+ "broughtBy": "Alex Greenshpun (owner)",+ "date": "2026-09-25",+ "embedded": false,+ "copied": "nothing: its subject (a frozen-LLM encoder), diagram (bars in a box, a vector), quote card, padlock engraving, asterisk and progress dots are not used; the proof subject (why sourdough rises) and its layout are new"+ },+ "knownGaps": ["the typewriter is capitals only (drafting.ts has no lowercase); the reference types lowercase serif", "no brush-script hand yet (lettering.ts spells one authored word)"],+ "proof": ["samples/adapt-teach/scrapbook/adaptScrapbook-still.png", "samples/adapt-teach/scrapbook/compare-scrapbook.png"]+}