Show it a video you love. Get a new video in the same style. An AI crew (Claude Code or Codex) plans, builds and reviews it with you.
JavaScript 2d-animationai-agentsai-videoanimationclaude-codecodexmulti-agentstyle-transfervideo-generation
Add five new drawing engines
許元豪d622540bfcd1
diff --git a/.claude/skills/anime-cel/GUIDE.md b/.claude/skills/anime-cel/GUIDE.mdnew file mode 100644index 0000000..6a47374--- /dev/null+++ b/.claude/skills/anime-cel/GUIDE.md@@ -0,0 +1,200 @@+# anime-cel — drawing & animation guide++Read this whole file before drawing. It covers the look, the full API with examples, the character system, how to+review, and known pitfalls. `template/src/scenes/demo.js` is a complete worked example (10 s, three shots).++---++## 1. The look++Modern TV anime (a clean slice-of-life / school series), not chibi, not manga screentone.++- **Characters have line art; backgrounds don't.** Character lines are filled tapered polygons: thicker on the outer+ silhouette and on the side away from the light, thin and tapered inside (folds, hair strands, lashes). One line+ colour per character (`D.line`: warm brown for Hina, indigo for Ren) — never pure black.+- **Cel shading = base + one hard shadow + a rim highlight.** The shadow is where the shape, pushed toward the light,+ no longer covers it (`cel()`), so every limb/lock gets a crescent on its far side. Set the light per shot with+ `setTOD()` (which sets `LIGHT`) or `setLight(x, y)` (vector TOWARD the light, screen space).+- **Faces**: big eyes (iris gradient, pupil, two catch-lights toward the light, thick upper lash that flicks out,+ thin lower lash, lid shadow), tiny nose tick, small mouth, blush with hatch lines. Hair casts a hard shadow on the+ forehead. Brows are drawn over the bangs, as anime does.+- **Backgrounds are painted shapes**: vertical-gradient skies, cumulus clouds with a hard lavender underside and a+ bright rim, simplified buildings in one-point perspective, sakura trees, utility poles and wires. No outlines.+- **Compositing**: a soft bloom and light vignette are added in `ENGINE.end` (`GRADE = { bloom, vignette }`, reset+ every frame; a shot may change it).+- **Anime effects** are graphic, not realistic: radial focus lines, parallel speed lines, 2–3 frame inverted impact+ frames, star sparkles, petals, smear lines, a flat pink/colour BG with focus lines for an emotional beat.++## 2. Timing and staging (what makes it read as anime)++- **On twos.** Characters change drawing 12×/s: pass `t: onTwos(lt)` and compute poses from `onTwos(lt)`. Cameras,+ particles and effects stay smooth (use `lt`/`t`).+- **Moving holds.** Anime holds poses; keep a little life (blinks via `autoBlink`, hair `sway`, a slow camera push),+ but don't wobble everything.+- **Snap + hold.** Anticipation (small opposite move, 4–8 frames) → the action in 2–4 frames (with `smearLines`) →+ overshoot/settle with `spring()` → hold so the read lands. See shot B of the demo.+- **Reactions**: expression change on a drawing via `faceAt()` (adds a 1-frame blink and a pop you can add to `sq`),+ plus `take()` for the body. Big reactions: cut to a close-up with `impactFrame` for 2–3 frames + `dramaticZoom`.+- **Emotional beat BG**: at the peak, cut the background to a flat radial gradient + `focusLines` (demo shot B).+- **Reads** (from the painted-animation guide, still true): one read at a time, lead the eye, let the reads set the+ shot length, give every seam a transition.++## 3. Characters (`src/cast.js`)++```js+const info = hina(x, y, u, {+ t: ta, // time for blinks, hair wind, talk (use onTwos)+ turn: .5, // -1 profile left · -.5 3/4 left · 0 front · .5 3/4 right · 1 profile right+ headTurn, bodyTurn, // override either (e.g. body 3/4, head to camera)+ face: 'surprised', // EXPR name or an expression object (see below)+ look: [.3, .2], // eye direction -1..1+ blink: 1, // 0..1 override (default autoBlink)+ mouth: 'a', talk: true, // mouth override, or auto lip-flap+ armL: [25, 95, 'hold'], // [shoulder°, elbow°, hand, wrist°, forearm length ×, flipThumb]+ armR: [8, 10, 'open'],+ legL: [20, 10], legR: [-10, 30], // [hip°, knee°]+ walk: phase, run: phase, // cycles (phase 0..1 per two steps); walkAmt / runAmt blend them out+ lean: 10, bend: 5, tilt: -8, // body lean°, spine bend°, head tilt°+ sq: .1, dy: -.3, // squash (+) / stretch (−), vertical offset in head units+ sway: [.1, 0], // secondary motion of hair/skirt/ribbon/tie (head units), see follow()+ fx: ['sweat'], // extra face marks: sweat vein steam gloom sparkles+ blush: .6,+ prop: { hand: 'L', draw: PROPS.envelope, rot: -60, s: 1, at: [0, 0] },+ armsOver: false, // draw arms over the head (hand to cheek, etc.)+ stance: 'contra', // default when standing: weight on one leg (hip up + out), shoulders counter-tilt, S-curve+ // spine, relaxed free knee, arms hang with 'relax' hands. 'straight' turns it off.+ weight: 'R', contra: 1, // weight leg (default per design: Hina R, Ren L) and strength 0..1+ ground: false, // don't snap the lowest foot to y (sitting, flying, bust)+});+info.head / info.handL / info.handR / info.footL / info.footR // screen points for props, cameras, effects+```++- **Proportions** (head units): Hina upper arm 1.02, forearm .9, hand .54; Ren 1.12 / .97 / .6 — fingertips reach+ mid-thigh when the arm hangs. Hands are ≈ the face's length. Sleeves taper shoulder → pinched elbow (creases on+ the inner side, more as it bends) → looser forearm → a cuff band (Hina ribbed, Ren blazer cuff + shirt cuff).+ A straight arm parallel to the picture plane always reads long: bend the elbow 10–20° and foreshorten the forearm+ (`arm[4]` ≈ .8) when reaching toward someone.+- **Shoulders follow the arms**: raising an arm lifts that shoulder and pushes it out/forward automatically.+- **Units & sizes.** `u` = head height in px. Hina is ≈5.6u tall, Ren ≈5.9u. Full body in frame u≈110–150, knees-up+ u≈180–260, bust/close-up use `bust(DESIGNS.ren, x, y, u, o)` with u≈380–600 where (x, y) is the head centre.+- **Angles.** Measured from straight down. With `|turn| > .3` (3/4 or side) positive = forward in the facing+ direction; in front view positive = outward from the body. Elbow adds to the shoulder angle. Knee positive bends+ the shin back. The near arm when facing right is `armL` (screen-left in the front view).+- **Hands**: `'open' 'relax' 'fist' 'point' 'peace' 'spread' 'hold' 'grip' 'pocket'`. `relax` = a hanging hand seen+ from the side (fingers curled) — use it for arms at rest instead of a flat `open`. `pocket` = the hand is in the+ trouser pocket (no hand drawn; aim the wrist at the hip, e.g. `armL: [14, -40, 'pocket']`, Ren's default stance). `hold` pinches a flat prop that extends past the+ fingertips (thumb in front); `grip` puts a handle inside the curled fingers.+- **Props**: `PROPS.envelope / book / phone / can / flower` (draw fn `(s, line)` in hand-local units, origin = grip).+ Write new ones the same way: build `Path2D`s and draw them with `drawGroup([...], line, lw)` for outline + cel.+- **Expressions** (`EXPR`, 19): neutral smile happy laugh sad cry angry rage surprised shocked scared love sleepy+ deadpan xd embarrassed smug determined dizzy. Each is `{ eye: {type, open, squint, iris, tilt, look, wet, shake},+ brow: {raise, ang}, mouth, blush, fx }`. Eye types: open happy(^^) closed tight xd(≥<) dot line white(shock)+ sparkle half swirl. Mouths: neutral smile grin wide open o cat frown wavy line set grit shout wail + talk a i u e o n.+ Make variants inline: `face: { ...EXPR.smile, blush: 1, fx: ['sweat'] }`.+- **Helpers**: `faceAt(t, keys)` (expression timeline with blink + pop), `autoBlink(t, seed)`, `talk(t, seed)`,+ `follow(t, f, k, w, amt)` (spring follow-through of any function of time — pass the character's x in head units to+ get hair lag), `walkPose/runPose(phase)`, `stroll(t, t0, t1, x0, x1, u)`.+- **Secondary motion**: the scene computes `sway` (e.g. `[-v / u * .05 + follow(t, tt => X(tt) / u, 5, 12), 0]`).+ Hair tips, the skirt hem, ribbon tails and tie follow it.++### How a character is built (for adding new ones)++- `DESIGNS.<name>`: `weight` (default weight leg), `pocketArm`, `kneeIn` (how much the relaxed knee turns in:+ .6 girlish, .2 boyish), colours, eye shape (`eyeU` upper lid / `eyeL` lower lid control points in eye-local coords,+ `eyeW/eyeH/eyeY/eyeR`, `lash`, `spikes`, `crease`, `irisS`), face (`chinY`, `jawW`, `faceW`, `mouthY`), body+ proportions (`hipH`, `thigh`, `shin`, `ua`, `fa`, `hl`, `torso` rows `[height, half-width]`, `armW`, `legW`),+ `clothes` (branch in `drawTorso` / `drawLeg` / sleeves) and `hairStyle`.+- `HAIR.<style>`: `front` locks (drawn over the face) and `back` locks (behind head/body; they move to the front+ layer when the head turns them toward the viewer), each `{ p: [[azimuth°, y, radius], …root→tip], w, flex }` on a+ skull sphere; `hairline` heights (front, 45°, temple, 135°, nape); `specY` for the angel ring. Keep root radii+ inside the skull (≤ .5) or they poke out of the silhouette.+- The head: skull sphere + a face outline morphing through front / 3/4 / profile keys (`FACE_KEYS`), features placed+ by azimuth on the sphere (eyes, brows, nose, mouth, ears), everything clipped to the face so the far eye hides+ naturally. Body: a posed skeleton; limbs are `tubePts` along smoothed centre-lines, grouped with `drawGroup` so+ every group has ONE outer outline (joints never show seams except intended clothing seams).+- Draw order: back hair → far arm → legs → neck (with the jaw's cast shadow) → skirt/torso/collar/bow → near arms →+ face → front hair → eyes/brows → face marks.++## 4. Drawing library (`src/anime.js`)++| function | purpose |+|---|---|+| `crPts(P, closed, n)` | Catmull-Rom through points (`[x,y,w]` keeps widths; `[x,y,w,true]` = sharp corner) |+| `ink(P, w, col, TAPER.x, {raw, closed, caps})` | tapered line as one filled polygon (`TAPER.both soft head tail flat lash`) |+| `tubePts(P)` / `ribbonPts(C, wf)` | outline of a tube/ribbon along a centre-line |+| `cel(path, base, shade, hi, d, r)` | cel fill: hard shadow depth d, rim highlight r |+| `drawGroup(parts, line, lw)` | union-outlined group; part = `{path, b, s, h, d, r, lw, join, noLine, clip, after}` |+| `polyPath, smooth, shifted, union, ellPts, heart` | path helpers |+| `setTOD(name)`, `tone(hex)`, `TOD` | time of day: day morning evening night (sky, clouds, light, character tint) |+| `SET.street / classroom / rooftop (cam, t, o)` | painted sets with parallax; leave the camera open. `cam = {x, y, zoom, rot}` in set coords (centre 960,540; street ground ≈ y 900–1000) |+| `skyLayer(cam, t, {clouds, sun, moon, wind})`, `cloud(x,y,w,h,seed)`, `sakuraTree`, `pole`, `wire`, `windowGrid`, `paintPoly` | build new sets |+| `layer(key, w, h, fn)` / `blit(c, x, y)` | cache a static painting (pure: same every frame) |+| `focusLines(t, cx, cy, {r, n, w, col})` | radial concentration lines (boil on twos) |+| `speedLines(t, ang, {rect, n, len, w, col})` | parallel streaks |+| `impactFrame(k, 'invert'|'mono'|'red', {x, y, t})` | impact flash frame (hold 2–3 frames) |+| `flash(k, col)` | full-frame flash |+| `dramaticZoom(t, t0, amt, shake)` → `{zoom, dx, dy}` | snap zoom with overshoot + decaying shake |+| `smear(fn, from, to, n)`, `smearLines(x0,y0,x1,y1,spread,col)` | multiples and motion lines |+| `blurBand(y, h, {blur, n, t})` | motion-blurred band of the current frame (BG streak) |+| `sparkle(x,y,r,a)`, `sparkles(t,x,y,R,n,seed,minR)`, `petals(t, {n, size, wind, kind:'sakura'|'leaf', rect})` | particles |+| `slashWipe(p, {cols, ang})`, `irisWipe(p, cx, cy, {shape:'circle'|'star', col})` | transitions (cover 0→.5, reveal .5→1) |+| `subtitle(c, txt, {y, size, alpha, fg, line})` | anime subtitle in `overlayHook` |++Kit (shared, `src/kit.js`): `shots`, `seg`, `kf`, `ease/easeIn/easeOut/backOut/elasticOut`, `spring`, `jump`, `take`,+`arcPt`, `onTwos`, `onStep`, `pulse`, `hash`, `rnd`, `camBegin/camEnd/toScreen`, `shakeXY`, `mixCol`, `LOOPS`.++### A shot skeleton++```js+(() => {+ function shot(t, lt, dur) {+ setTOD('evening');+ const ta = onTwos(lt), cam = { x: 960 + 40 * ease(seg(lt, 0, dur)), y: 560, zoom: 1.2 };+ SET.rooftop(cam, t, { sun: [1500, 640] }); // camera is now open (world coords)+ const f = faceAt(ta, [[0, 'neutral'], [1.4, 'surprised'], [2.2, 'smile']]), tk = take(ta, 1.4);+ const r = ren(1100, 990, 130, { t: ta, turn: -.5, face: f.face, blink: f.blink ?? autoBlink(ta, 3), sq: f.sq + tk.sq, talk: ta > 2.2 });+ hina(780, 990, 130, { t: ta, turn: .5, face: 'happy', armL: [40, 60, 'hold'], prop: { hand: 'L', draw: PROPS.can, rot: 90 } });+ camEnd();+ petals(t, { n: 20 });+ if (lt > 1.4 && lt < 1.4 + 3 / 24) impactFrame(1, 'invert', { x: r.head[0], y: r.head[1], t });+ if (lt < .3) flash(1 - lt / .3);+ if (lt > dur - .35) slashWipe(seg(lt, dur - .35, dur) * .5);+ }+ shots([[0, shot]]);+ window.overlayHook = (c, t) => { if (t > 2.2 && t < 3.6) subtitle(c, '夕陽好美喔。'); };+ window.EXTRA_FONTS.push(['800 58px "M PLUS Rounded 1c"', '夕陽好美喔。']);+})();+```++## 5. Review loop++You can't see it from code. For every shot: a key-frame sheet, a strip of each key action/transition, and full-res+stills (`--stills`) of every face that carries a read. The model-sheet loops (`--loop=faces_hina|faces_ren|turns|+bodies|hands|sets|fx|motion|close_hina|close_ren`; `motion` = stances + walk + run) are the fastest way to check a change to the rig. Check:++- **Faces**: eyes the same size/shape on both sides (front), far eye narrower and clipped (3/4), lash line+ confident, catch-lights on the light side in both eyes, mouth small, brows readable, hair shadow on the forehead.+- **Silhouette**: hair reads as clumps with pointed tips, no stray lobes/stubs outside the skull; limbs continuous;+ hands attached; props touching the hand.+- **Motion**: on twos, anticipation → snap → overshoot → hold; nothing constant-speed; no twinning of arms.+- **Staging**: the read is clear at 390 px wide (phone), characters big enough, one read at a time.+- **Seams**: every cut has a transition or is a deliberate cut on action / impact cut.++## 6. Known pitfalls++- A lock whose root radius is > .5 or whose last two control points coincide makes a lobe/stub on the silhouette.+- Catmull-Rom through duplicated points overshoots (lobes). Don't repeat points; mark corners with `[x,y,w,true]`.+- Two-point `ink()` calls are auto-densified; still prefer ≥ 3 points for curves.+- Screen-space effects called inside a scaled `G.save()` (e.g. a split-screen panel) ignore that transform.+- Profile views are the weakest angle (see limits); prefer 3/4 for acting, profile for walking/running.+- `impactFrame` / `blurBand` copy the whole canvas: use them sparingly (a few ms each).+- Fonts load from Google Fonts at render time (needs network); push caption text to `EXTRA_FONTS`.++## 7. Limits (honest)++- It reads as anime, but as a clean "digital TV-anime model sheet" rather than a key-animator's drawing: line+ weight varies by light side and taper, not by hand pressure; no hand-drawn wobble or per-shot redraws.+- Turns are geometric (sphere-projected features + morphing outline), so extreme angles (profile, looking up/down)+ are stiffer than a drawn model; there is no up/down head pitch beyond small `tilt`/look.+- Hands are simplified mitten-with-fingers shapes; the torso has one silhouette per body turn (no twisting).+- No back view; no sitting pose helper (use `ground:false` + leg angles).diff --git a/.claude/skills/anime-cel/SKILL.md b/.claude/skills/anime-cel/SKILL.mdnew file mode 100644index 0000000..5edb3a8--- /dev/null+++ b/.claude/skills/anime-cel/SKILL.md@@ -0,0 +1,76 @@+---+name: anime-cel+description: Make Japanese TV-anime style videos (MP4) with code — cel-shaded characters with tapered line art, big detailed eyes, hair clumps with a specular band, comedic anime reactions (sweat drop, anger vein, sparkle eyes, ≥< eyes, dot eyes, tears), painted skies with cumulus clouds, school/street/classroom/rooftop sets with time-of-day palettes, speed/focus lines, impact frames, dramatic zooms, smears, sakura petals and anime subtitles (CJK). Canvas 2D rendered frame by frame in headless Chrome, encoded with ffmpeg. Use when a reference video or brief calls for anime / 動畫 / 日系動畫 / アニメ / cel-shaded / slice-of-life / school romance / shōnen-style reactions, or when the video-clone router picks the anime-cel style. 2D only; characters are original (Hina, Ren) or new ones built on the same rig.+---++# anime-cel++Modern TV-anime look drawn entirely by code: characters with confident tapered line art (heavier on the shadow side),+flat cel colour + one hard-edged shadow tone + a rim highlight, large layered eyes, hair built from pointed locks with+an "angel ring" highlight; line-free painted backgrounds; anime staging effects. Every frame is a pure function of `t`.++Read **[GUIDE.md](GUIDE.md)** in full before building anything. Model sheets in `docs/`: `faces-hina.jpg`,+`faces-ren.jpg` (19 expressions each), `turns.jpg` (front → 3/4 → profile), `bodies.jpg`, `motion.jpg` (stances, walk, run), `hands.jpg`, `sets.jpg`,+`fx.jpg`, and `demo-sheet.jpg` (the demo film).++## Workflow++1. **Scaffold** `bash .claude/skills/anime-cel/scripts/new_project.sh <project-dir>` (`--keep-demo` keeps the example).+ It copies `template/`, unhooks the demo, runs `npm install`, checks node/ffmpeg/Chrome.+2. **Storyboard** each shot with its reads (what the viewer must understand, in order, with times) and the anime+ staging you will use (establishing pan, cut on action, focus-line BG for the emotional beat, impact frame, reaction+ close-up…). Set `duration` in `src/config.js`.+3. **Build one file per shot** in `src/scenes/` (IIFE ending in `shots([[t0, fn]])`, add its `<script>` to+ `studio.html`). A shot paints the whole frame: `setTOD()` → `SET.<set>(cam, t)` (opens the camera) → characters →+ `camEnd()` → screen effects → transition. Captions go in `window.overlayHook` with `subtitle()`.+4. **Look at it** (from the project dir), open every image with Read:+ ```bash+ node render.mjs --sheet=0.5,1.5,2.5,3.5 --cols=4 --w=480 --out=out/check/a.jpg # key frames+ node render.mjs --strip=3.8:4.5 --cols=6 --w=320 --out=out/check/s.jpg # every frame of an action+ node render.mjs --stills=4.4 --out=out/check/st # full-res PNG to judge faces+ node render.mjs --loop=faces_hina --sheet=0 --cols=1 --w=1920 --out=out/check/f.jpg # model sheets (faces_ren, turns, bodies, motion, hands, sets, fx, close_hina, close_ren)+ ```+5. **Render** `node render.mjs --frames --workers=4 && node render.mjs --encode --out=out/video.mp4 [--audio=...]`.++## API summary++```js+hina(x, y, u, o) / ren(x, y, u, o) → { head, handL, handR, footL, footR, top, u } // (x, y) ground point, u = head height px+bust(DESIGNS.ren, x, y, u, o) // close-up: (x, y) = head centre+o = { t, turn (-1..1: 0 front, ±.5 3/4, ±1 profile), headTurn, bodyTurn, face ('happy' …), look [x,y], blink, mouth, talk,+ armL/armR [shoulder°, elbow°, hand, wrist°, foreshorten], legL/legR [hip°, knee°], walk: phase, run: phase,+ lean°, bend°, tilt°, sq, dy, flip, sway [x,y], fx ['sweat','vein','steam','gloom','sparkles'], blush,+ prop { hand:'L'|'R', draw: PROPS.envelope, rot°, s, at }, armsOver, ground:false,+ stance:'contra'|'straight', weight:'L'|'R', contra } // hands: open relax fist point peace spread hold grip pocket+faceAt(t, [[0,'neutral'],[1.2,'surprised']]) · autoBlink(t, seed) · talk(t) · follow(t, f) · walkPose/runPose · stroll+setTOD('day'|'morning'|'evening'|'night') · setLight(x, y) · SET.street / SET.classroom / SET.rooftop (cam, t, o)+focusLines · speedLines · impactFrame · flash · dramaticZoom · smear · smearLines · blurBand · sparkle(s) · petals+slashWipe · irisWipe · subtitle(c, txt, o) · onTwos(t) · kit: kf, seg, ease*, spring, jump, take, camBegin/camEnd+drawing primitives: ink (tapered line), tubePts, ribbonPts, crPts, cel, drawGroup, layer (cache), paintPoly+```++## Rules that matter most++1. **Pure function of t** — no `Math.random()`, no state between frames (`rnd(key)`/`hash()`; `follow()` for springs).+2. **Scenes never draw body parts.** Characters are one call. New characters = a new entry in `DESIGNS` + `HAIR`+ (+ clothes branch) in `cast.js`, never ad-hoc drawing in a scene.+3. **Animate characters on twos** (`const ta = onTwos(lt)` for poses/faces), keep camera moves smooth (`lt`).+4. **Anime timing**: quick actions with a held pose after; anticipation → snap → overshoot (`spring`, `take`); faces+ change on a drawing via `faceAt` (it adds the blink + pop), never by crossfading.+5. **Staging**: establish → react. Emotional peaks cut the BG to a flat gradient + `focusLines`; hits get an+ `impactFrame` (2–3 frames) + `dramaticZoom`; fast moves get `smearLines`.+6. **Sizes**: full body u≈110–150, knees-up 180–260, bust 380–560. Keep faces ≥ u 150 when they carry a read.+7. **Transitions at every seam** (`slashWipe`, `irisWipe` star, `flash`, impact cut, cut on action).+8. **Captions**: only via `overlayHook` + `subtitle()` (white, dark outline, CJK font). Push new caption text into+ `window.EXTRA_FONTS` so the glyphs load before rendering.++## Engine gotchas++- `SET.*` leaves the camera **open**; draw characters in the same world coords and call `camEnd()` before screen+ effects. Screen-space effects (`blurBand`, `impactFrame`, `slashWipe`) use `setTransform` and ignore the camera.+- Characters face screen-right with positive `turn`. With `|turn| > .3` limb angles are "forward/back" in the facing+ direction; in front view they are "outward/inward". The near arm when facing right is `armL`.+- Props in hands: use hand `'hold'` (pinch, prop extends past the fingertips) or `'grip'` (handle in the fist).+ `rot` rotates the prop about the grip point.+- `layer(key, …)` caches static paintings per page; include the time-of-day name in the key if colours depend on it.+- Speed: ~5–25 ms to draw a frame, ~100 ms/frame effective incl. JPEG with 4 workers (first frame ~0.6 s builds caches).diff --git a/.claude/skills/anime-cel/docs/bodies.jpg b/.claude/skills/anime-cel/docs/bodies.jpgnew file mode 100644index 0000000..041f5b0Binary files /dev/null and b/.claude/skills/anime-cel/docs/bodies.jpg differdiff --git a/.claude/skills/anime-cel/docs/demo-sheet.jpg b/.claude/skills/anime-cel/docs/demo-sheet.jpgnew file mode 100644index 0000000..47354c7Binary files /dev/null and b/.claude/skills/anime-cel/docs/demo-sheet.jpg differdiff --git a/.claude/skills/anime-cel/docs/faces-hina.jpg b/.claude/skills/anime-cel/docs/faces-hina.jpgnew file mode 100644index 0000000..2e71f85Binary files /dev/null and b/.claude/skills/anime-cel/docs/faces-hina.jpg differdiff --git a/.claude/skills/anime-cel/docs/faces-ren.jpg b/.claude/skills/anime-cel/docs/faces-ren.jpgnew file mode 100644index 0000000..3f69ac8Binary files /dev/null and b/.claude/skills/anime-cel/docs/faces-ren.jpg differdiff --git a/.claude/skills/anime-cel/docs/fx.jpg b/.claude/skills/anime-cel/docs/fx.jpgnew file mode 100644index 0000000..e139e9cBinary files /dev/null and b/.claude/skills/anime-cel/docs/fx.jpg differdiff --git a/.claude/skills/anime-cel/docs/hands.jpg b/.claude/skills/anime-cel/docs/hands.jpgnew file mode 100644index 0000000..8df02c6Binary files /dev/null and b/.claude/skills/anime-cel/docs/hands.jpg differdiff --git a/.claude/skills/anime-cel/docs/motion.jpg b/.claude/skills/anime-cel/docs/motion.jpgnew file mode 100644index 0000000..d9f0f43Binary files /dev/null and b/.claude/skills/anime-cel/docs/motion.jpg differdiff --git a/.claude/skills/anime-cel/docs/sets.jpg b/.claude/skills/anime-cel/docs/sets.jpgnew file mode 100644index 0000000..96028b9Binary files /dev/null and b/.claude/skills/anime-cel/docs/sets.jpg differdiff --git a/.claude/skills/anime-cel/docs/turns.jpg b/.claude/skills/anime-cel/docs/turns.jpgnew file mode 100644index 0000000..7fe21c8Binary files /dev/null and b/.claude/skills/anime-cel/docs/turns.jpg differdiff --git a/.claude/skills/anime-cel/scripts/new_project.sh b/.claude/skills/anime-cel/scripts/new_project.shnew file mode 100644index 0000000..740cd15--- /dev/null+++ b/.claude/skills/anime-cel/scripts/new_project.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+# Scaffolds a project from this engine's template, installs deps and checks the toolchain.+# bash .claude/skills/<engine>/scripts/new_project.sh <project-dir> [--keep-demo]+set -e+SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"+TARGET="${1:?usage: new_project.sh <project-dir> [--keep-demo]}"+if [ -e "$TARGET/studio.html" ]; then echo "error: $TARGET already has a studio.html; not overwriting" >&2; exit 1; fi+mkdir -p "$TARGET"+if command -v rsync >/dev/null; then rsync -a --exclude node_modules --exclude out "$SKILL_DIR/template/" "$TARGET/"; else cp -R "$SKILL_DIR/template/." "$TARGET/"; rm -rf "$TARGET/node_modules" "$TARGET/out"; fi # Git Bash on Windows has no rsync+mkdir -p "$TARGET/assets" "$TARGET/out/check"+# The demo is an example, not a template: unless asked, unhook it so the new video starts clean.+if [ "${2:-}" != "--keep-demo" ]; then sed -i.bak 's#<script src="src/scenes/demo.js"></script>##' "$TARGET/studio.html" && rm -f "$TARGET/studio.html.bak"; fi+( cd "$TARGET" && npm install --silent --no-audit --no-fund )+echo "node $(node -v)"+command -v ffmpeg >/dev/null && echo "ffmpeg ok" || echo "MISSING: ffmpeg"+FOUND=+for c in "${CHROME_PATH:-}" "/c/Program Files/Google/Chrome/Application/chrome.exe" "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" /usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do+ [ -n "$c" ] && [ -x "$c" ] && { echo "chrome $c"; FOUND=1; break; }+done+[ "${FOUND:-}" = 1 ] || echo "MISSING: Chrome (install it, or pass --chrome=<path> to render.mjs)"+echo "== ready: $TARGET"diff --git a/.claude/skills/anime-cel/template/.gitignore b/.claude/skills/anime-cel/template/.gitignorenew file mode 100644index 0000000..9209ef5--- /dev/null+++ b/.claude/skills/anime-cel/template/.gitignore@@ -0,0 +1,2 @@+node_modules+outdiff --git a/.claude/skills/anime-cel/template/LICENSE-render.mjs.txt b/.claude/skills/anime-cel/template/LICENSE-render.mjs.txtnew file mode 100644index 0000000..1215a85--- /dev/null+++ b/.claude/skills/anime-cel/template/LICENSE-render.mjs.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 John Heibel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/.claude/skills/anime-cel/template/package-lock.json b/.claude/skills/anime-cel/template/package-lock.jsonnew file mode 100644index 0000000..5036bec--- /dev/null+++ b/.claude/skills/anime-cel/template/package-lock.json@@ -0,0 +1,329 @@+{+ "name": "anime-cel-engine",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "anime-cel-engine",+ "license": "MIT",+ "dependencies": {+ "puppeteer-core": "^25.11.0"+ }+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.3.tgz",+ "integrity": "sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.4",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.4.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",+ "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^3.24.1"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1687809",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",+ "integrity": "sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.5",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.5.tgz",+ "integrity": "sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/puppeteer-core": {+ "version": "25.12.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.12.0.tgz",+ "integrity": "sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.3",+ "chromium-bidi": "17.0.2",+ "devtools-protocol": "0.0.1687809",+ "typed-query-selector": "^2.12.2",+ "webdriver-bidi-protocol": "0.4.3",+ "ws": "^8.21.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.3",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz",+ "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==",+ "license": "MIT"+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",+ "integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",+ "license": "Apache-2.0"+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.22.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.2.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",+ "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/.claude/skills/anime-cel/template/package.json b/.claude/skills/anime-cel/template/package.jsonnew file mode 100644index 0000000..0f4e910--- /dev/null+++ b/.claude/skills/anime-cel/template/package.json@@ -0,0 +1,6 @@+{+ "name": "anime-cel-engine",+ "private": true,+ "license": "MIT",+ "dependencies": { "puppeteer-core": "^25.11.0" }+}diff --git a/.claude/skills/anime-cel/template/render.mjs b/.claude/skills/anime-cel/template/render.mjsnew file mode 100644index 0000000..9f7418a--- /dev/null+++ b/.claude/skills/anime-cel/template/render.mjs@@ -0,0 +1,161 @@+// render.mjs: renders studio.html in headless Chrome. Length and fps come from the page (PROJECT in src/config.js).+//+// Look at it (open the images with your image viewer / Read tool):+// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)+// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point+// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera+// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs+// Make the video:+// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --encode --out=out/video.mp4 out/frames → MP4+// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or+// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)+// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,+// --chrome=<path to Chrome/Chromium>.+import puppeteer from 'puppeteer-core';+import { spawn } from 'node:child_process';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { homedir } from 'node:os';++const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));+const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+ ...playwrightChromes()];+// Chromium builds Playwright downloaded (~/.cache/ms-playwright/chromium-NNNN), newest first+function playwrightChromes() {+ const dir = `${homedir()}/.cache/ms-playwright`;+ if (!existsSync(dir)) return [];+ return readdirSync(dir).filter(n => /^chromium-\d+$/.test(n)).sort((a, b) => b.split('-')[1] - a.split('-')[1])+ .map(n => `${dir}/${n}/chrome-linux64/chrome`);+}+const CHROME = CHROMES.find(p => p && existsSync(p));+if (!CHROME) { console.error('Chrome not found: pass --chrome=<path> or set CHROME_PATH'); process.exit(1); }+const fps = +(args.fps || 24), FRAMES_DIR = 'out/frames';+const run = (cmd, a) => new Promise((ok, bad) => { const p = spawn(cmd, a, { stdio: 'inherit' }); p.on('close', c => c ? bad(new Error(cmd + ' exited ' + c)) : ok()); });+const times = s => String(s).split(',').map(Number);+const span = s => String(s).split(':').map(Number);+// comma-separated fields, keeping commas inside parentheses ('PLK.MX(1.38),PLK.WL,500,300'); numbers stay numbers+const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of String(s)) { if (ch === ',' && !d) { out.push(cur); cur = ''; continue; } d += ch === '(' ? 1 : ch === ')' ? -1 : 0; cur += ch; } out.push(cur); return out.map(v => isNaN(+v) ? v : +v); };++// JPEG frames decode as full-range (yuvj420p); without this the MP4 is flagged full-range and some players/platforms+// show it washed out or with crushed shadows. Convert to standard (tv) range and say so.+const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];++if (args.encode) {+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,+ ...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);+ console.log('wrote ' + out);+ process.exit(0);+}++// --soft-gl: no GPU on this machine; render WebGL in software (SwiftShader), which Chrome only allows when asked.+// --gpu-angle=vulkan|gl-egl: headless Linux on an NVIDIA GPU (e.g. a cloud or cluster node); plain --use-gl=angle gets+// no WebGL context there. Check which GPU Chrome actually lands on with gpu_probe.mjs.+const ANGLE = { vulkan: ['--use-angle=vulkan', '--enable-features=Vulkan'], 'gl-egl': ['--use-angle=gl-egl'] };+if (args['gpu-angle'] && !ANGLE[args['gpu-angle']]) { console.error(`--gpu-angle must be one of ${Object.keys(ANGLE)}`); process.exit(1); }+const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ : args['gpu-angle'] ? ANGLE[args['gpu-angle']]+ : process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];+// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.+const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+const browser = await puppeteer.launch({+ executablePath: CHROME, headless: true, protocolTimeout: 0,+ args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']+});+async function openPage(tag = '') {+ const page = await browser.newPage();+ page.on('console', m => { if (['error', 'warn'].includes(m.type())) console.log(`[page${tag}]`, m.text()); });+ page.on('pageerror', e => console.log(`[page error${tag}]`, e.message));+ await page.goto(pathToFileURL(resolve('studio.html')).href + '?render', { waitUntil: 'networkidle0' });+ await page.waitForFunction('window.ready === true', { timeout: 60000 });+ if (args.loop) {+ const ok = await page.evaluate(name => { if (!LOOPS[name]) return false; window.LOOP = LOOPS[name]; return true; }, args.loop);+ if (!ok) { console.error(`no loop named "${args.loop}"`); process.exit(1); }+ }+ return page;+}+const frameOf = async (page, t, type, q) => {+ const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);+ return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');+};+// the length of whatever is being rendered: a loop's .len, or the video's duration+const lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);++if (args.sheet || args.strip) {+ const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });+ let ts;+ if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ else ts = times(args.sheet);+ const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;+ const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);+ writeFileSync(out, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));+ console.log(`${out} (${ts.length} frames) ms/frame: ${ms.join(' ')}`);+} else if (args.stills) {+ const page = await openPage(), out = args.out || 'out/stills'; mkdirSync(out, { recursive: true });+ console.log('GPU:', await page.evaluate(() => window.gpuInfo()));+ for (const s of times(args.stills)) {+ const t0 = Date.now(), buf = await frameOf(page, s, 'image/png');+ const f = `${out}/t${s.toFixed(2).replace('.', '_')}.png`; writeFileSync(f, buf);+ console.log(`${f} ${Date.now() - t0} ms`);+ }+} else if (args.png) {+ // PNG sequence (for GIFs): a loop's full cycle (frame n equals frame 0, so it isn't rendered), or --range=a:b.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], n = Math.round((b - a) * fps);+ const out = args.out || `out/${args.loop ? 'loop_' + args.loop : 'png'}`, workers = +(args.workers || 3); mkdirSync(out, { recursive: true });+ let next = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < n) { const i = next++; writeFileSync(`${out}/f${String(i).padStart(4, '0')}.png`, await frameOf(page, a + i / fps, 'image/png')); }+ }));+ console.log(`${n} frames → ${out} (${((Date.now() - start) / n).toFixed(0)} ms/frame)`);+} else if (args.frames) {+ // Parallel and resumable: each worker pulls the next missing frame; files are written atomically.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);+ mkdirSync(FRAMES_DIR, { recursive: true });+ const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);+ const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }+ console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ let next = 0, done = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < todo.length) {+ const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;+ const buf = await frameOf(page, i / fps, 'image/jpeg', .94);+ writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ if (++done % 24 === 0 || done === todo.length) {+ const el = (Date.now() - start) / 1000;+ console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);+ }+ }+ }));+} else if (args.clip) {+ const page = await openPage(), len = await lengthOf(page);+ const [a, b] = args.range ? span(args.range) : typeof args.clip === 'string' ? span(args.clip) : [0, len];+ const audio = args.audio || await page.evaluate(() => PROJECT.audio || '');+ const out = args.out || 'out/clip.mp4'; mkdirSync(dirname(out), { recursive: true });+ const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',+ ...(audio ? ['-ss', String(a), '-t', String(b - a), '-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', ...TV_RANGE, '-movflags', '+faststart', out],+ { stdio: ['pipe', 'inherit', 'inherit'] });+ const n = Math.round((b - a) * fps), start = Date.now();+ for (let i = 0; i < n; i++) {+ const buf = await frameOf(page, a + i / fps, 'image/jpeg', .93);+ if (!ff.stdin.write(buf)) await new Promise(r => ff.stdin.once('drain', r));+ if (i % 24 === 0 || i === n - 1) console.log(`frame ${i + 1}/${n} ${((Date.now() - start) / (i + 1)).toFixed(0)} ms/frame`);+ }+ ff.stdin.end(); await new Promise(r => ff.on('close', r));+ console.log(`wrote ${out}`);+} else {+ console.log('nothing to do: see the usage notes at the top of render.mjs');+}+await browser.close();diff --git a/.claude/skills/anime-cel/template/src/anime.js b/.claude/skills/anime-cel/template/src/anime.jsnew file mode 100644index 0000000..3335983--- /dev/null+++ b/.claude/skills/anime-cel/template/src/anime.js@@ -0,0 +1,564 @@+// anime.js — the anime-cel drawing library (Canvas 2D, draws into the kit's G).+// Look: modern TV anime. Tapered line art on characters, flat cel colour + one hard shadow tone + a highlight,+// painted backgrounds with no line art (gradient skies, cumulus with bright rims), and anime effects.+//+// Sections: light · curves & tapered strokes · cel fills & line groups · palettes (time of day) · layer cache ·+// sky & clouds · sets (street, classroom, rooftop) · props · effects · transitions · captions · grade.++// ======================================================================================= light+// LIGHT points TOWARD the key light, in screen space (default: upper left). Shadows fall on the far side of every+// shape; outlines get thicker on the shadow side. Characters convert it into their local frame (_L).+let LIGHT = [-.55, -.83], _L = LIGHT;+function setLight(x, y) { const l = Math.hypot(x, y) || 1; LIGHT = _L = [x / l, y / l]; }++// ======================================================================================= curves+// Catmull-Rom through control points. A point may carry extra numbers (e.g. [x, y, w]): they are interpolated+// linearly. Mark a point sharp with the flag S=true in the 4th slot: [x, y, w, true] (tangents stop at it: a corner).+function crPts(P, closed = false, n = 7) {+ const N = P.length; if (N < 3) return P.map(p => p.slice());+ const get = i => closed ? P[(i % N + N) % N] : P[clamp(i, 0, N - 1)];+ const out = [], segs = closed ? N : N - 1, dims = P[0].length > 2 && typeof P[0][2] === 'number' ? 3 : 2;+ for (let i = 0; i < segs; i++) {+ const p1 = get(i), p2 = get(i + 1);+ const p0 = p1[3] ? p1 : get(i - 1), p3 = p2[3] ? p2 : get(i + 2);+ for (let k = 0; k < n; k++) {+ const t = k / n, t2 = t * t, t3 = t2 * t, q = [];+ for (let d = 0; d < 2; d++) q.push(.5 * (2 * p1[d] + (-p0[d] + p2[d]) * t + (2 * p0[d] - 5 * p1[d] + 4 * p2[d] - p3[d]) * t2 + (-p0[d] + 3 * p1[d] - 3 * p2[d] + p3[d]) * t3));+ if (dims === 3) q.push(lerp(p1[2], p2[2], t));+ out.push(q);+ }+ }+ if (!closed) out.push(P[N - 1].slice(0, dims));+ return out;+}+function polyPath(P, closed = true, into) {+ const p = into || new Path2D(); if (!P.length) return p;+ p.moveTo(P[0][0], P[0][1]); for (let i = 1; i < P.length; i++) p.lineTo(P[i][0], P[i][1]);+ if (closed) p.closePath(); return p;+}+const sArea = P => { let a = 0; for (let i = 0; i < P.length; i++) { const p = P[i], q = P[(i + 1) % P.length]; a += p[0] * q[1] - q[0] * p[1]; } return a / 2; };+const ccw = P => sArea(P) < 0 ? P.slice().reverse() : P; // one winding for every shape, so unions fill cleanly+const smooth = (P, closed = true, n = 7) => polyPath(ccw(crPts(P, closed, n)), closed);+const shifted = (path, dx, dy) => { const p = new Path2D(); p.addPath(path, new DOMMatrix([1, 0, 0, 1, dx, dy])); return p; };+const xform = (P, m) => P.map(([x, y, ...r]) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5], ...r]);+const rot2 = (x, y, a) => [x * Math.cos(a) - y * Math.sin(a), x * Math.sin(a) + y * Math.cos(a)];+function ellPts(cx, cy, rx, ry, n = 24, a0 = 0) { const o = []; for (let i = 0; i < n; i++) { const a = a0 + i / n * TAU; o.push([cx + Math.cos(a) * rx, cy + Math.sin(a) * ry]); } return o; }+function cumLen(P) { const L = [0]; for (let i = 1; i < P.length; i++) L.push(L[i - 1] + Math.hypot(P[i][0] - P[i - 1][0], P[i][1] - P[i - 1][1])); return L; }++// A ribbon along a dense centreline C with full width wf(s, i) (s = 0..1 by arc length) → closed outline points.+// caps: round the ends where the width is > 0.+function ribbonPts(C, wf, caps = true) {+ const N = C.length; if (N < 2) return [];+ const L = cumLen(C), tot = L[N - 1] || 1, left = [], right = [], nrm = [];+ for (let i = 0; i < N; i++) {+ const a = C[Math.max(0, i - 1)], b = C[Math.min(N - 1, i + 1)];+ let tx = b[0] - a[0], ty = b[1] - a[1]; const l = Math.hypot(tx, ty) || 1; tx /= l; ty /= l;+ const w = Math.max(0, wf(L[i] / tot, i)) / 2; nrm.push([tx, ty, w]);+ left.push([C[i][0] - ty * w, C[i][1] + tx * w]); right.push([C[i][0] + ty * w, C[i][1] - tx * w]);+ }+ const out = left.slice(), cap = (c, t, w, from) => { // semicircle from side `from` (+1 left) round the tip+ for (let k = 1; k < 6; k++) { const a = k / 6 * Math.PI, nx = -t[1] * from, ny = t[0] * from, fx = t[0] * from, fy = t[1] * from;+ out.push([c[0] + (nx * Math.cos(a) + fx * Math.sin(a)) * w, c[1] + (ny * Math.cos(a) + fy * Math.sin(a)) * w]); }+ };+ if (caps && nrm[N - 1][2] > 0) cap(C[N - 1], nrm[N - 1], nrm[N - 1][2], 1);+ for (let i = N - 1; i >= 0; i--) out.push(right[i]);+ if (caps && nrm[0][2] > 0) cap(C[0], nrm[0], nrm[0][2], -1);+ return out;+}+// width profiles for tapered lines (s = 0..1 along the line)+const TAPER = {+ both: s => Math.pow(Math.max(0, Math.sin(Math.PI * s)), .55), // pointed at both ends+ soft: s => .35 + .65 * Math.pow(Math.max(0, Math.sin(Math.PI * s)), .7), // thinner ends, never zero+ head: s => Math.pow(1 - s, .7), // thick start → point+ tail: s => Math.pow(s, .7), // point → thick end+ flat: s => 1,+ lash: s => s < .82 ? .45 + .55 * Math.pow(s / .82, 1.4) : Math.pow((1 - s) / .18, .8), // eyeliner: thickens to the outer corner, flicks to a point+};+// tube: control points [x, y, w] (w = full width) → smooth closed outline points (round caps)+function tubePts(P, n = 6, caps = true) { const C = crPts(P, false, n); return ribbonPts(C, (s, i) => C[i][2], caps); }+// ink(P, w, col, prof): a tapered line through control points (px or local units), filled as one polygon+function ink(P, w, col, prof = TAPER.both, o = {}) {+ if (P.length < 2) return;+ let C = o.raw ? P : crPts(P, !!o.closed, o.n || 7);+ if (C.length < 8) { const D = []; for (let i = 0; i < C.length - 1; i++) for (let k = 0; k < 6; k++) D.push([lerp(C[i][0], C[i + 1][0], k / 6), lerp(C[i][1], C[i + 1][1], k / 6)]); D.push(C[C.length - 1]); C = D; }+ if (o.closed) C.push(C[0]);+ const pts = ribbonPts(C, s => w * prof(s), !!o.caps);+ G.fillStyle = col; G.fill(polyPath(pts));+}+// a hard little line cluster (blush hatching, shading strokes)+function hatch(x, y, n, len, ang, gap, w, col) {+ for (let i = 0; i < n; i++) {+ const cx = x + (i - (n - 1) / 2) * gap, dx = Math.sin(ang) * len / 2, dy = Math.cos(ang) * len / 2;+ ink([[cx + dx, y - dy], [cx - dx, y + dy]], w, col, TAPER.both, { raw: true });+ }+}++// ======================================================================================= cel fill & line groups+// cel(path, base, shade, hi, d, r): flat base; a hard-edged shadow where the shape, pushed d toward the light,+// no longer covers it (the far side); a rim highlight r wide on the lit side. Works for any path (unions too).+function cel(path, b, s, h, d = .08, r = 0) {+ G.fillStyle = b; G.fill(path);+ if (!(s && d) && !(h && r)) return;+ G.save(); G.clip(path);+ if (s && d) { G.fillStyle = s; G.fill(path); G.clip(shifted(path, _L[0] * d, _L[1] * d)); }+ if (h && r) { G.fillStyle = h; G.fill(path); G.clip(shifted(path, -_L[0] * r, -_L[1] * r)); }+ G.fillStyle = b; G.fill(path); G.restore();+}+// drawGroup(parts, line, lw): parts that form ONE silhouette. Every part's outline is stroked first (2×lw, and+// once more nudged toward the shadow side, so lines are heavier away from the light), then every part is filled on+// top: joins between parts vanish and only the outer silhouette keeps its line. Part:+// { path, b, s, h, d, r, lw, join, noLine, clip (fn: extra detail drawn clipped to this part), after (fn) }+function drawGroup(parts, line, lw, o = {}) {+ G.save(); G.strokeStyle = line; G.lineCap = 'round'; G.miterLimit = 8;+ const k = o.thick ?? .6;+ for (const p of parts) {+ if (!p || p.noLine) continue;+ G.lineJoin = p.join || 'round'; const w = p.lw ?? lw; G.lineWidth = 2 * w; G.stroke(p.path);+ if (k) { G.save(); G.translate(-_L[0] * w * k, -_L[1] * w * k); G.stroke(p.path); G.restore(); }+ }+ G.restore();+ for (const p of parts) if (p) {+ cel(p.path, p.b, p.s, p.h, p.d ?? .08, p.r ?? 0);+ if (p.clip) { G.save(); G.clip(p.path); p.clip(); G.restore(); }+ }+ for (const p of parts) if (p && p.after) p.after();+}+const union = paths => { const u = new Path2D(); for (const p of paths) u.addPath(p); return u; };++// ======================================================================================= palettes (time of day)+// TOD[name] = sky gradient, cloud tones, sun, ambient tint for characters (tintK), light direction.+const TOD = {+ day: { sky: ['#3f86d8', '#7fb6ec', '#cfe6f6'], haze: '#e9f3f8', cloud: ['#ffffff', '#bdc9e8', '#fffdf6'], sun: '#fff6d8', tint: '#ffffff', tintK: 0, light: [-.55, -.83], bgTint: '#ffffff', grade: '#fff7e8' },+ morning: { sky: ['#5f9fe0', '#a9d0f0', '#f6e6d4'], haze: '#f8efe4', cloud: ['#fffaf2', '#c8c3e0', '#fff6e0'], sun: '#fff0cc', tint: '#fff2dd', tintK: .08, light: [-.8, -.6], bgTint: '#fff4e4', grade: '#fff2dc' },+ evening: { sky: ['#4b4f9a', '#d9829a', '#ffc98e'], haze: '#ffd7a8', cloud: ['#ffd9b8', '#9a6f9e', '#fff0c8'], sun: '#ffe2a8', tint: '#ff9a6a', tintK: .22, light: [.85, -.35], bgTint: '#ffb38a', grade: '#ffcf9e' },+ night: { sky: ['#0f1638', '#263a72', '#4f5f9a'], haze: '#5a6aa6', cloud: ['#56608f', '#2a3160', '#8e9ad0'], sun: '#dfe8ff', tint: '#5d6fb8', tintK: .38, light: [.3, -.9], bgTint: '#5a68a8', grade: '#9fb0ff' },+};+let TODN = 'day', _tone = {};+function setTOD(name) { if (TODN !== name) { TODN = name; _tone = {}; } setLight(...TOD[name].light); }+// tone(hex): a character/prop colour under the current time-of-day light+function tone(c) { if (!c || c[0] !== '#') return c; const k = TOD[TODN].tintK; if (!k) return c; return _tone[c] || (_tone[c] = mixCol(c, TOD[TODN].tint, k)); }++// ======================================================================================= layer cache+// Static paintings (sets, clouds, trees) are painted once into an offscreen canvas and reused: fast and still pure.+const LAYERS = {};+function layer(key, w, h, fn, scale = 1) {+ if (LAYERS[key]) return LAYERS[key];+ const c = makeCanvas(Math.ceil(w * scale), Math.ceil(h * scale)), g = c.getContext('2d'), keep = G, keepL = _L;+ G = g; G.scale(scale, scale); fn(g); G = keep; _L = keepL;+ c.lw = w; c.lh = h; return (LAYERS[key] = c);+}+const blit = (c, x, y, w = c.lw, h = c.lh) => G.drawImage(c, x, y, w, h);++// ======================================================================================= sky & clouds+function skyGrad(x, y, w, h, pal = TOD[TODN]) {+ const g = G.createLinearGradient(0, y, 0, y + h); g.addColorStop(0, pal.sky[0]); g.addColorStop(.55, pal.sky[1]); g.addColorStop(1, pal.sky[2]);+ G.fillStyle = g; G.fillRect(x, y, w, h);+}+// a cumulus cloud as a cached painting: flat-ish base, bumpy top, hard cel shadow under every puff, bright rim+function cloudCanvas(seed, w, h, tod = TODN) {+ return layer(`cloud:${seed}:${w}:${h}:${tod}`, w + 80, h + 60, g => {+ const pal = TOD[tod], r = rnd('cloud' + seed), path = new Path2D(), puffs = [];+ const cx = (w + 80) / 2, base = h + 30, n = 5 + Math.floor(r() * 3);+ for (let i = 0; i < n; i++) {+ const k = (i + .5) / n, peak = h * (.42 + .58 * Math.pow(Math.sin(Math.PI * k), .8)) * (.8 + .3 * r());+ const rad = Math.min(w / n * (.62 + .3 * r()), peak * .55);+ puffs.push([cx + (k - .5) * w * .82, base - peak + rad, rad]);+ }+ for (let i = 0; i < n - 1; i++) { const a = puffs[i], b = puffs[i + 1]; if (r() < .8) puffs.push([(a[0] + b[0]) / 2 + (r() - .5) * 20, Math.min(a[1], b[1]) - Math.min(a[2], b[2]) * .35, Math.min(a[2], b[2]) * (.55 + .2 * r())]); }+ for (const [x, y, rr] of puffs) { path.moveTo(x + rr, y); path.arc(x, y, rr, 0, TAU); }+ const hull = puffs.slice(0, n).map(([x, y]) => [x, y]); hull.push([cx + w * .44, base - h * .1], [cx - w * .44, base - h * .1]); // fill the gaps between puffs+ polyPath(sArea(hull) > 0 ? hull : hull.slice().reverse(), true, path); // same winding as the arcs+ path.moveTo(cx + w * .46, base - h * .16); path.ellipse(cx, base - h * .16, w * .46, h * .16, 0, 0, TAU);+ const L = [pal.light[0] * .6, -.8]; const l = Math.hypot(...L); _L = [L[0] / l, L[1] / l];+ const gr = G.createLinearGradient(0, base - h, 0, base); gr.addColorStop(0, pal.cloud[2]); gr.addColorStop(1, pal.cloud[0]);+ G.fillStyle = gr; G.fill(path);+ G.save(); G.clip(path);+ const sh = G.createLinearGradient(0, base - h, 0, base); sh.addColorStop(0, mixCol(pal.cloud[1], pal.cloud[0], .35)); sh.addColorStop(1, pal.cloud[1]);+ G.fillStyle = sh; G.fill(path);+ G.clip(shifted(path, _L[0] * h * .16, _L[1] * h * .16));+ G.fillStyle = pal.cloud[2]; G.fill(path);+ G.clip(shifted(path, -_L[0] * h * .035, -_L[1] * h * .035));+ G.fillStyle = gr; G.fill(path);+ G.restore();+ G.save(); G.clip(path); G.globalAlpha = .35; G.fillStyle = pal.cloud[1]; G.fillRect(0, base - h * .12, w + 80, h); // flat grey underside+ G.restore();+ });+}+function cloud(x, y, w, h, seed, alpha = 1) { const c = cloudCanvas(seed, w, h); G.save(); G.globalAlpha = alpha; blit(c, x - c.lw / 2, y - c.lh + 30); G.restore(); }++// ======================================================================================= sets+// A set is painted in its own world (SET_W × SET_H px) as parallax layers and leaves the camera OPEN at the end,+// so the scene draws characters in the same world coords and calls camEnd() (drawWorld does it if you forget).+// setView(cam) → { cx, cy, zoom } ; cam = { x, y, zoom, rot } in set coords.+// Layers use depth k: 0 = infinitely far (sky), 1 = the character plane.+function parallax(cam, k, ref = [960, 540]) {+ camBegin(ref[0] + (cam.x - ref[0]) * k, ref[1] + (cam.y - ref[1]) * k, 1 + ((cam.zoom || 1) - 1) * k, (cam.rot || 0));+}+function skyLayer(cam, t, o = {}) {+ const pal = TOD[TODN];+ parallax(cam, .08); skyGrad(-1200, -1200, 4400, 3200, pal);+ if (TODN === 'night') { // stars + moon+ const q = rnd('stars'); G.fillStyle = '#fff8e0';+ for (let i = 0; i < 160; i++) { const x = -1200 + q() * 4400, y = -1200 + q() * 2000, r = .8 + q() * 2.2, tw = .5 + .5 * Math.sin((t || 0) * (1 + q() * 3) + i); G.globalAlpha = .4 + .6 * tw; G.beginPath(); G.arc(x, y, r, 0, TAU); G.fill(); }+ G.globalAlpha = 1; const [mx, my] = o.moon || [1500, 180], g = G.createRadialGradient(mx, my, 0, mx, my, 220); g.addColorStop(0, 'rgba(255,248,220,.5)'); g.addColorStop(1, 'rgba(255,248,220,0)'); G.fillStyle = g; G.fillRect(mx - 220, my - 220, 440, 440);+ G.fillStyle = '#fff6da'; G.beginPath(); G.arc(mx, my, 56, 0, TAU); G.fill(); G.fillStyle = '#efe4c2'; G.beginPath(); G.arc(mx - 14, my + 10, 12, 0, TAU); G.arc(mx + 18, my - 16, 8, 0, TAU); G.fill();+ }+ if (o.sun) { const [sx, sy] = o.sun, g = G.createRadialGradient(sx, sy, 0, sx, sy, 520); g.addColorStop(0, pal.sun); g.addColorStop(.25, mixCol(pal.sun, pal.sky[2], .5) + 'aa'); g.addColorStop(1, pal.sky[2] + '00'); G.fillStyle = g; G.fillRect(sx - 600, sy - 600, 1200, 1200); }+ camEnd();+ parallax(cam, .18);+ const drift = (t || 0) * (o.wind ?? 6);+ for (const [x, y, w, h, s] of (o.clouds || [[300, 360, 520, 230, 1], [1250, 250, 700, 300, 2], [1850, 420, 420, 170, 3], [-300, 300, 420, 180, 4]]))+ cloud(x + drift, y, w, h, s);+ camEnd();+}+// helpers for painted (line-free) set pieces: flat colour + a soft vertical gradient+function paintPoly(P, top, bottom = top) {+ const ys = P.map(p => p[1]), y0 = Math.min(...ys), y1 = Math.max(...ys);+ if (top !== bottom) { const g = G.createLinearGradient(0, y0, 0, y1); g.addColorStop(0, top); g.addColorStop(1, bottom); G.fillStyle = g; } else G.fillStyle = top;+ G.fill(polyPath(P));+}+function blossomClump(x, y, r, seed, pal) { // sakura foliage: puffs with a hard shade under and a light top+ const q = rnd('bl' + seed), p = new Path2D();+ for (let i = 0; i < 9; i++) { const a = q() * TAU, d = Math.sqrt(q()) * r * .7, rr = r * (.35 + .3 * q()); const cx = x + Math.cos(a) * d, cy = y + Math.sin(a) * d * .7; p.moveTo(cx + rr, cy); p.arc(cx, cy, rr, 0, TAU); }+ const keep = _L; _L = [-.5, -.86]; cel(p, pal[0], pal[1], pal[2], r * .22, r * .09); _L = keep;+ G.fillStyle = pal[3]; for (let i = 0; i < 7; i++) { const a = q() * TAU, d = q() * r * .8; G.beginPath(); G.ellipse(x + Math.cos(a) * d, y + Math.sin(a) * d * .7, r * .05, r * .035, a, 0, TAU); G.fill(); }+}+function sakuraTree(x, y, s, seed) { // (x, y) = trunk base, s = scale (~1 = 600 px tall)+ const q = rnd('tree' + seed), bark = mixCol('#5a3a3e', TOD[TODN].bgTint, .15), pal = ['#f7c3cf', '#e592a8', '#fff0f2', '#fbe2e8'].map(c => mixCol(c, TOD[TODN].bgTint, TOD[TODN].tintK));+ const br = (x0, y0, a, len, w, d) => {+ const x1 = x0 + Math.sin(a) * len, y1 = y0 - Math.cos(a) * len;+ ink([[x0, y0], [(x0 + x1) / 2 + (q() - .5) * len * .2, (y0 + y1) / 2], [x1, y1]], w, bark, s2 => 1 - s2 * .45, { caps: true });+ if (d > 0) { br(x1, y1, a - .35 - q() * .3, len * .72, w * .62, d - 1); br(x1, y1, a + .35 + q() * .3, len * .7, w * .6, d - 1); }+ else blossomClump(x1, y1, 95 * s, seed + ':' + x1.toFixed(0), pal);+ };+ br(x, y, (q() - .5) * .2, 190 * s, 34 * s, 3);+}+function pole(x, yb, h, col) { // utility pole with crossbar+ paintPoly([[x - 9, yb], [x - 6, yb - h], [x + 6, yb - h], [x + 9, yb]], col, mixCol(col, '#000000', .25));+ G.fillStyle = col; G.fillRect(x - 60, yb - h + 40, 120, 9); G.fillRect(x - 45, yb - h + 80, 90, 7);+}+function wire(x0, y0, x1, y1, sag, col, w = 2.2) { G.strokeStyle = col; G.lineWidth = w; G.beginPath(); G.moveTo(x0, y0); G.quadraticCurveTo((x0 + x1) / 2, (y0 + y1) / 2 + sag, x1, y1); G.stroke(); }+function windowGrid(x, y, cols, rows, w, h, gx, gy, glass, frame) {+ for (let i = 0; i < cols; i++) for (let j = 0; j < rows; j++) {+ const X = x + i * (w + gx), Y = y + j * (h + gy); G.fillStyle = frame; G.fillRect(X - 3, Y - 3, w + 6, h + 6);+ const g = G.createLinearGradient(X, Y, X + w, Y + h); g.addColorStop(0, glass[0]); g.addColorStop(1, glass[1]); G.fillStyle = g; G.fillRect(X, Y, w, h);+ G.fillStyle = 'rgba(255,255,255,.35)'; G.beginPath(); G.moveTo(X + w * .15, Y + h); G.lineTo(X + w * .45, Y); G.lineTo(X + w * .6, Y); G.lineTo(X + w * .3, Y + h); G.fill();+ }+}+const SET = {};+// ---- street: a school-route street in one-point perspective, sakura on the left, houses right, school at the end.+// World 1920×1080 around (960, 540); ground line of the character plane ≈ y 900. Horizon y 560.+SET.street = (cam, t, o = {}) => {+ skyLayer(cam, t, { clouds: [[260, 330, 560, 240, 11], [1200, 230, 760, 320, 12], [1800, 400, 440, 170, 13], [-420, 380, 480, 200, 14], [2400, 300, 520, 220, 15]], sun: o.sun, wind: o.wind });+ const tn = TODN, tintK = TOD[tn].tintK, bt = c => mixCol(c, TOD[tn].bgTint, tintK * 1.2);+ parallax(cam, .45);+ blit(layer('street-far:' + tn, 3000, 1400, () => {+ G.translate(1040, 0);+ const hz = 560;+ paintPoly([[-1100, hz + 10], [-700, hz - 90], [-300, hz - 40], [100, hz - 120], [600, hz - 60], [1100, hz - 110], [2000, hz - 30], [2000, hz + 20], [-1100, hz + 20]], bt('#9fb7d6'), bt('#c3d3e6'));+ // the school at the end of the road+ paintPoly([[640, hz - 190], [1290, hz - 190], [1290, hz + 20], [640, hz + 20]], bt('#f3eee4'), bt('#d9d2c6'));+ paintPoly([[900, hz - 260], [1030, hz - 260], [1030, hz - 190], [900, hz - 190]], bt('#efe9de'), bt('#dcd4c8'));+ G.fillStyle = bt('#ffffff'); G.beginPath(); G.arc(965, hz - 225, 22, 0, TAU); G.fill(); G.strokeStyle = bt('#6b6f86'); G.lineWidth = 3; G.stroke();+ G.beginPath(); G.moveTo(965, hz - 225); G.lineTo(965, hz - 240); G.moveTo(965, hz - 225); G.lineTo(976, hz - 222); G.stroke();+ windowGrid(660, hz - 176, 12, 3, 36, 30, 14, 26, [bt('#8fb4d8'), bt('#d8e8f4')], bt('#e6e0d4'));+ G.fillStyle = bt('#c6bfb2'); G.fillRect(640, hz - 196, 650, 8);+ for (let i = 0; i < 9; i++) blossomClump(560 + i * 90 + ((i * 37) % 30), hz - 10 + ((i * 53) % 20), 42, 'far' + i, ['#f2c6d2', '#dca0b8', '#fbe4ea', '#fff'].map(bt));+ }), -1040, 0);+ camEnd();+ parallax(cam, 1);+ blit(layer('street-mid:' + tn, 3200, 1500, () => {+ G.translate(1200, 200);+ const hz = 560, vp = [960, hz];+ // road + sidewalks in perspective+ paintPoly([[vp[0] - 30, hz], [vp[0] + 30, hz], [2600, 1400], [-700, 1400]], bt('#8a8fa3'), bt('#6d7288'));+ paintPoly([[vp[0] - 30, hz], [vp[0] - 55, hz], [-900, 1400], [-700, 1400]], bt('#c9c3bc'), bt('#b3aca6'));+ paintPoly([[vp[0] + 30, hz], [vp[0] + 55, hz], [2900, 1400], [2600, 1400]], bt('#c9c3bc'), bt('#b3aca6'));+ for (let i = 0; i < 9; i++) { const k0 = Math.pow(i / 9, 2.2), k1 = Math.pow((i + .45) / 9, 2.2); const y0 = lerp(hz, 1400, k0), y1 = lerp(hz, 1400, k1); const w0 = lerp(1.5, 26, k0), w1 = lerp(1.5, 26, k1);+ G.fillStyle = bt('#f4f1ea'); G.beginPath(); G.moveTo(vp[0] - w0 / 2, y0); G.lineTo(vp[0] + w0 / 2, y0); G.lineTo(vp[0] + w1 / 2, y1); G.lineTo(vp[0] - w1 / 2, y1); G.fill(); }+ // left: long wall with sakura behind it+ for (let i = 0; i < 6; i++) sakuraTree(lerp(-500, 820, Math.pow(i / 6, .8)), lerp(760, 575, Math.pow(i / 6, .6)), lerp(1.25, .28, Math.pow(i / 6, .6)), 'L' + i);+ paintPoly([[-900, 700], [vp[0] - 60, hz - 12], [vp[0] - 60, hz + 4], [-900, 1010]], bt('#e8e0d6'), bt('#cfc5bb'));+ paintPoly([[-900, 690], [vp[0] - 60, hz - 14], [vp[0] - 60, hz - 10], [-900, 715]], bt('#b9aea6'));+ // right: houses with roofs, receding+ for (let i = 0; i < 5; i++) {+ const k = Math.pow(i / 5, .75), x = lerp(2500, 1080, k), s = lerp(1.5, .22, k), y = lerp(1000, hz + 8, Math.pow(k, .8));+ const hw = 330 * s, hh = 300 * s, roof = [bt('#50638f'), bt('#8d5a57'), bt('#5d7a6c'), bt('#7a6a9a'), bt('#9a6a50')][i];+ paintPoly([[x - hw, y], [x - hw, y - hh], [x + hw, y - hh], [x + hw, y]], bt('#f2ece2'), bt('#dcd3c6'));+ paintPoly([[x - hw * 1.12, y - hh], [x - hw * .6, y - hh * 1.55], [x + hw * .6, y - hh * 1.55], [x + hw * 1.12, y - hh]], roof, mixCol(roof, '#000000', .2));+ windowGrid(x - hw * .7, y - hh * .78, 2, 1, hw * .45, hh * .38, hw * .35, 0, [bt('#7fa6cf'), bt('#dbe9f5')], bt('#ebe4d8'));+ paintPoly([[x - hw * 1.05, y + 4], [x - hw * 1.05, y - hh * .38], [x + hw * 1.05, y - hh * .38], [x + hw * 1.05, y + 4]], bt('#d8cfc2'), bt('#c2b8aa'));+ }+ // utility poles + wires (the anime street staple)+ const P = [[1180, 590, 150], [1460, 700, 330], [2000, 900, 700]], Q = [[640, 585, 130], [300, 660, 300], [-420, 860, 690]];+ for (const [x, y, h] of [...P, ...Q]) pole(x, y, h, bt('#6e6a78'));+ const wc = bt('#3d3a4c');+ for (const S of [P, Q]) for (let i = 0; i < S.length - 1; i++) for (const dy of [44, 84]) { const a = S[i], b = S[i + 1]; wire(a[0], a[1] - a[2] + dy * a[2] / 700, b[0], b[1] - b[2] + dy * b[2] / 700, 40 + b[2] * .08, wc, 1 + b[2] / 400); }+ }), -1200, -200);+};+// ---- classroom: one-point perspective, windows on the left with sky, desks, warm light patches on the floor.+SET.classroom = (cam, t, o = {}) => {+ skyLayer(cam, t, { clouds: [[-100, 300, 460, 200, 21], [520, 240, 600, 250, 22], [-500, 420, 380, 150, 23]], wind: 3 });+ const tn = TODN, bt = c => mixCol(c, TOD[tn].bgTint, TOD[tn].tintK * 1.2);+ parallax(cam, 1);+ blit(layer('classroom:' + tn, 3000, 1600, () => {+ G.translate(1000, 250);+ const vp = [1000, 470], wallTop = -250, fl = 780;+ const toVP = (x, y, k) => [lerp(x, vp[0], k), lerp(y, vp[1], k)];+ // back wall+ const bw = [toVP(-1000, wallTop, .62), toVP(3000, wallTop, .62), toVP(3000, 1350, .62), toVP(-1000, 1350, .62)];+ paintPoly(bw, bt('#ece3d2'), bt('#dccfbb'));+ // blackboard on the back wall+ const bb = [toVP(-200, 200, .62), toVP(2200, 200, .62), toVP(2200, 700, .62), toVP(-200, 700, .62)];+ paintPoly(bb.map(([x, y]) => [x - 8, y - 8 * (y < 600 ? 1 : -1)]), bt('#9a7a58')); paintPoly(bb, bt('#3f6456'), bt('#2f4d43'));+ G.strokeStyle = 'rgba(255,255,255,.25)'; G.lineWidth = 3; G.beginPath(); G.moveTo(bb[0][0] + 60, bb[0][1] + 60); G.bezierCurveTo(bb[0][0] + 160, bb[0][1] + 20, bb[0][0] + 200, bb[0][1] + 110, bb[0][0] + 300, bb[0][1] + 70); G.stroke();+ // left wall with windows (sky shows through: cut the glass out of the wall)+ const lw = [[-1000, wallTop - 900], bw[0], bw[3], [-1000, 2400]];+ G.save(); const wallPath = polyPath(lw), holes = new Path2D();+ for (let i = 0; i < 3; i++) { const x0 = -1000 + i * 520, k0 = 0, pts = [[-1000, -60], [-560, 60], [-560, 700], [-1000, 900]].map(([x, y]) => [x, y]);+ const ka = i / 3 * .62, kb = (i + .82) / 3 * .62; const a0 = toVP(-1000, 20, ka), a1 = toVP(-1000, 20, kb), b1 = toVP(-1000, 820, kb), b0 = toVP(-1000, 820, ka);+ polyPath([a0, a1, b1, b0], true, holes); }+ const wp = new Path2D(); wp.addPath(wallPath); wp.addPath(holes);+ G.fillStyle = bt('#e3d8c5'); G.fill(wp, 'evenodd');+ // window frames + curtains+ G.strokeStyle = bt('#f7f2e8'); G.lineWidth = 16; G.stroke(holes);+ for (let i = 0; i < 3; i++) { const ka = i / 3 * .62, kb = (i + .82) / 3 * .62, km = (ka + kb) / 2, a = toVP(-1000, 20, km), b = toVP(-1000, 820, km), c = toVP(-1000, 420, ka), d = toVP(-1000, 420, kb);+ G.lineWidth = 9; G.beginPath(); G.moveTo(...a); G.lineTo(...b); G.moveTo(...c); G.lineTo(...d); G.stroke();+ const cu = [toVP(-1000, 10, ka), toVP(-1000, 10, ka + .05), toVP(-1000, 840, ka + .04), toVP(-1000, 840, ka - .01)]; paintPoly(cu, bt('#f4ead2'), bt('#e0d2b4')); }+ G.restore();+ // floor+ paintPoly([bw[3], bw[2], [3000, 1500], [-1000, 1500]], bt('#b98e62'), bt('#9c7250'));+ G.strokeStyle = bt('#8a6244'); G.lineWidth = 2;+ for (let i = -14; i <= 22; i++) { G.beginPath(); G.moveTo(vp[0] + (i * 60) * .38, bw[3][1]); G.lineTo(vp[0] + i * 170, 1500); G.stroke(); }+ // sunlight patches on the floor from the windows+ G.fillStyle = 'rgba(255,236,190,.35)';+ for (let i = 0; i < 3; i++) { const x = -200 + i * 480; G.beginPath(); G.moveTo(x, 1500); G.lineTo(x + 330, 1500); G.lineTo(x + 690, bw[3][1] + 90); G.lineTo(x + 520, bw[3][1] + 90); G.fill(); }+ // desks in rows+ const desk = (x, y, s) => {+ const top = [[x - 110 * s, y - 120 * s], [x + 110 * s, y - 120 * s], [x + 95 * s, y - 160 * s], [x - 95 * s, y - 160 * s]];+ G.fillStyle = bt('#5f5b66'); G.fillRect(x - 100 * s, y - 120 * s, 8 * s, 120 * s); G.fillRect(x + 92 * s, y - 120 * s, 8 * s, 120 * s);+ paintPoly([[x - 110 * s, y - 120 * s], [x + 110 * s, y - 120 * s], [x + 110 * s, y - 100 * s], [x - 110 * s, y - 100 * s]], bt('#8a6446'));+ paintPoly(top, bt('#e0b784'), bt('#c99d6c')); G.fillStyle = bt('#b0b3c2'); G.fillRect(x - 90 * s, y - 100 * s, 180 * s, 34 * s);+ };+ for (let r = 3; r >= 0; r--) for (let c = -2; c <= 3; c++) { const k = r / 4, s = lerp(1.25, .55, k), y = lerp(1320, 860, k); desk(lerp(vp[0] + c * 480, vp[0] + c * 200, k), y, s); }+ }), -1000, -250);+};+// ---- rooftop: big sky, chain-link fence and railing, tiled floor. Horizon low.+SET.rooftop = (cam, t, o = {}) => {+ skyLayer(cam, t, { clouds: [[200, 420, 700, 300, 31], [1300, 330, 900, 380, 32], [2100, 500, 500, 200, 33], [-500, 500, 560, 220, 34]], sun: o.sun, wind: 8 });+ const tn = TODN, bt = c => mixCol(c, TOD[tn].bgTint, TOD[tn].tintK * 1.2);+ parallax(cam, .6);+ blit(layer('roof-far:' + tn, 3400, 1200, () => {+ G.translate(1100, 0);+ for (let i = 0; i < 26; i++) { const x = -1100 + i * 130 + ((i * 71) % 60), h = 60 + ((i * 97) % 140); paintPoly([[x, 760], [x, 760 - h], [x + 110, 760 - h], [x + 110, 760]], bt('#b6c6dc'), bt('#cad6e6')); }+ }), -1100, 0);+ camEnd();+ parallax(cam, 1);+ blit(layer('roof-near:' + tn, 3400, 1500, () => {+ G.translate(1100, 200);+ paintPoly([[-1100, 760], [2300, 760], [2300, 1300], [-1100, 1300]], bt('#c8c2bc'), bt('#a79f9a'));+ G.strokeStyle = bt('#9d958f'); G.lineWidth = 2; for (let i = -20; i < 40; i++) { G.beginPath(); G.moveTo(960 + i * 40, 760); G.lineTo(960 + i * 150, 1300); G.stroke(); }+ for (let j = 0; j < 7; j++) { const y = 760 + Math.pow(j / 7, 1.6) * 540; G.beginPath(); G.moveTo(-1100, y); G.lineTo(2300, y); G.stroke(); }+ // fence: posts + mesh + rail+ G.strokeStyle = bt('#7d8a93'); G.lineWidth = 1.6; G.globalAlpha = .7;+ for (let i = -80; i < 120; i++) { G.beginPath(); G.moveTo(i * 30, 470); G.lineTo(i * 30 + 290, 760); G.stroke(); G.beginPath(); G.moveTo(i * 30 + 290, 470); G.lineTo(i * 30, 760); G.stroke(); }+ G.globalAlpha = 1; G.fillStyle = bt('#5f6b76');+ for (let i = -8; i < 12; i++) G.fillRect(i * 240, 440, 12, 330);+ G.fillRect(-1100, 440, 3400, 14); G.fillRect(-1100, 600, 3400, 8);+ }), -1100, -200);+};++// ======================================================================================= props+// A prop is drawn in hand-local coords: origin = grip point, +x = along the fingers, s = size (usually u).+// Every prop has an ink outline in the holder's line colour and cel shading.+const PROPS = {+ envelope(s, line) { // held by its short edge: extends along +x from the grip+ const w = .62 * s, h = .42 * s; G.save(); G.translate(w / 2 - .08 * s, 0); G.rotate(Math.PI / 2); G.translate(0, 0);+ const P = polyPath([[-h / 2, -w / 2], [h / 2, -w / 2], [h / 2, w / 2], [-h / 2, w / 2]]);+ drawGroup([{ path: P, b: tone('#fbd7e0'), s: tone('#eeb0c2'), h: tone('#fff4f6'), d: .06 * s, r: .02 * s }], line, .018 * s);+ ink([[-h / 2 + .02 * s, -w / 2 + .02 * s], [0, -w * .12], [h / 2 - .02 * s, -w / 2 + .02 * s]], .016 * s, line, TAPER.soft);+ heart(0, -w * .08, .075 * s, tone('#e0485f'), line); G.restore();+ },+ envelopeFlat(s, line) {+ const w = .62 * s, h = .42 * s, P = polyPath([[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, h / 2], [-w / 2, h / 2]]);+ drawGroup([{ path: P, b: tone('#fbd7e0'), s: tone('#eeb0c2'), h: tone('#fff4f6'), d: .06 * s, r: .02 * s }], line, .018 * s);+ ink([[-w / 2 + .02 * s, -h / 2 + .02 * s], [0, h * .08], [w / 2 - .02 * s, -h / 2 + .02 * s]], .016 * s, line, TAPER.soft);+ heart(0, h * .1, .075 * s, tone('#e0485f'), line);+ },+ phone(s, line) {+ const P = polyPath(ccw(ellPts(0, 0, .001, .001, 4))), r = new Path2D(); r.roundRect(-.14 * s, -.26 * s, .28 * s, .52 * s, .05 * s);+ drawGroup([{ path: r, b: tone('#3a3f5c'), s: tone('#262a40'), d: .04 * s }], line, .016 * s);+ const g = G.createLinearGradient(0, -.22 * s, 0, .22 * s); g.addColorStop(0, '#9fd6ff'); g.addColorStop(1, '#e8c6ff'); G.fillStyle = g; G.fillRect(-.11 * s, -.22 * s, .22 * s, .43 * s);+ },+ book(s, line) {+ const r = new Path2D(); r.roundRect(-.3 * s, -.2 * s, .6 * s, .4 * s, .02 * s);+ drawGroup([{ path: r, b: tone('#4f7fc8'), s: tone('#3a5f9c'), h: tone('#86b0ea'), d: .05 * s, r: .02 * s }], line, .018 * s);+ G.fillStyle = tone('#f5efe0'); G.fillRect(-.28 * s, .15 * s, .56 * s, .04 * s);+ },+ can(s, line) {+ const r = new Path2D(); r.roundRect(-.1 * s, -.19 * s, .2 * s, .38 * s, .04 * s);+ drawGroup([{ path: r, b: tone('#ff7a59'), s: tone('#d8553f'), h: tone('#ffd0b8'), d: .05 * s, r: .025 * s }], line, .016 * s);+ G.fillStyle = tone('#fff3d6'); G.fillRect(-.1 * s, -.05 * s, .2 * s, .08 * s);+ },+ flower(s, line) {+ ink([[0, .3 * s], [.02 * s, 0], [0, -.2 * s]], .03 * s, tone('#4f8a4a'), TAPER.flat, { caps: true });+ for (let i = 0; i < 5; i++) { const a = i / 5 * TAU; const p = polyPath(ccw(ellPts(Math.cos(a) * .07 * s, -.26 * s + Math.sin(a) * .07 * s, .06 * s, .045 * s, 12, a)));+ drawGroup([{ path: p, b: tone('#ffc2d6'), s: tone('#f090b0'), d: .02 * s }], line, .01 * s); }+ G.fillStyle = tone('#ffd65a'); G.beginPath(); G.arc(0, -.26 * s, .035 * s, 0, TAU); G.fill();+ },+};+function heart(x, y, r, col, line) {+ const P = [[x, y + r * .9], [x - r, y - r * .1], [x - r * .55, y - r * .8], [x, y - r * .35, 0, true], [x + r * .55, y - r * .8], [x + r, y - r * .1]];+ P[0][3] = true; P[0][2] = 0;+ const path = polyPath(ccw(crPts(P.map(p => [p[0], p[1], 0, p[3]]), true, 6)));+ if (line) { G.strokeStyle = line; G.lineWidth = r * .25; G.lineJoin = 'round'; G.stroke(path); }+ G.fillStyle = col; G.fill(path);+}++// ======================================================================================= effects (screen or world)+// Drawn with rnd() streams re-seeded per drawing step (on twos), so lines "boil" like hand-drawn effects animation.+const fxStep = (t, fps = 12) => Math.floor(t * fps + 1e-6);+// focusLines: radial concentration lines (集中線) toward (cx, cy); r = clear radius; dense 0..1; col.+function focusLines(t, cx, cy, o = {}) {+ const q = rnd('focus' + fxStep(t, o.fps || 12) + (o.seed || '')), n = o.n || 110, R = 1500, r0 = o.r || 330, col = o.col || 'rgba(30,26,46,.85)';+ G.save(); G.fillStyle = col;+ for (let i = 0; i < n; i++) {+ const a = (i + q() * .8) / n * TAU, ri = r0 * (.75 + q() * .6), w = (o.w || 16) * (.3 + q());+ const ca = Math.cos(a), sa = Math.sin(a), px = -sa, py = ca;+ G.beginPath(); G.moveTo(cx + ca * ri, cy + sa * ri); G.lineTo(cx + ca * R + px * w, cy + sa * R + py * w); G.lineTo(cx + ca * R - px * w, cy + sa * R - py * w); G.fill();+ }+ G.restore();+}+// speedLines: parallel streaks along angle `ang` (radians, 0 = moving right), for chases, dashes, BG streaks.+function speedLines(t, ang, o = {}) {+ const q = rnd('speed' + fxStep(t, o.fps || 12) + (o.seed || '')), n = o.n || 60, col = o.col || 'rgba(255,255,255,.85)';+ const [x0, y0, w, h] = o.rect || [0, 0, W, H], ca = Math.cos(ang), sa = Math.sin(ang), cx = x0 + w / 2, cy = y0 + h / 2, D = Math.hypot(w, h);+ G.save(); G.beginPath(); G.rect(x0, y0, w, h); G.clip(); G.fillStyle = col;+ for (let i = 0; i < n; i++) {+ const off = (q() - .5) * D, along = (q() - .5) * D * 1.2, len = (o.len || 500) * (.4 + q()), th = (o.w || 5) * (.4 + q());+ const bx = cx - sa * off + ca * along, by = cy + ca * off + sa * along;+ ink([[bx - ca * len / 2, by - sa * len / 2], [bx + ca * len / 2, by + sa * len / 2]], th, col, TAPER.both, { raw: true });+ }+ G.restore();+}+// sparkle: a four-point anime star (+ soft glow). sparkles(): a twinkling cluster around a point.+function sparkle(x, y, r, a = 0, col = '#fffbe8', glow = true) {+ if (r <= 0) return;+ if (glow) { const g = G.createRadialGradient(x, y, 0, x, y, r * 1.6); g.addColorStop(0, 'rgba(255,250,220,.55)'); g.addColorStop(1, 'rgba(255,250,220,0)'); G.fillStyle = g; G.fillRect(x - r * 2, y - r * 2, r * 4, r * 4); }+ const P = []; for (let i = 0; i < 8; i++) { const rr = i % 2 ? r * .16 : r, an = a + i / 8 * TAU; P.push([x + Math.cos(an) * rr, y + Math.sin(an) * rr]); }+ G.fillStyle = col; G.beginPath(); P.forEach((p, i) => i ? G.lineTo(...p) : G.moveTo(...p)); G.closePath(); G.fill();+}+function sparkles(t, x, y, R, n = 6, seed = 's', minR = .35) {+ for (let i = 0; i < n; i++) { const q = rnd(seed + i), ph = q(), a = q() * TAU, d = R * (minR + (1 - minR) * q()), life = frac(t * .9 + ph), s = Math.sin(Math.PI * life);+ sparkle(x + Math.cos(a) * d, y + Math.sin(a) * d * .8, R * (.08 + .1 * q()) * s, life * .8); }+}+// petals: sakura (or leaves) drifting across a rect: pure function of t (each petal loops through the rect).+function petals(t, o = {}) {+ const [x0, y0, w, h] = o.rect || [-100, -100, W + 200, H + 200], n = o.n || 40, s = o.size || 16, wind = o.wind ?? 90, kind = o.kind || 'sakura';+ for (let i = 0; i < n; i++) {+ const q = rnd('petal' + i + (o.seed || '')), sp = (60 + q() * 70) * (o.speed || 1), life = h / sp, ph = q() * life;+ const k = frac((t + ph) / life), y = y0 + k * h, x = x0 + frac(q() + (wind * (t + ph)) / w) * w + Math.sin((t + ph) * (1 + q()) * 2) * 30;+ const a = (t + ph) * (1.5 + q() * 2), sc = s * (.6 + q() * .7) * (o.depth ? lerp(.6, 1.4, q()) : 1), flip = Math.cos((t + ph) * (2 + q() * 3));+ G.save(); G.translate(x, y); G.rotate(a); G.scale(sc, sc * Math.max(.15, Math.abs(flip)));+ if (kind === 'leaf') { G.fillStyle = flip > 0 ? '#7fb35a' : '#5d8f44'; G.beginPath(); G.moveTo(-1, 0); G.quadraticCurveTo(0, -.6, 1, 0); G.quadraticCurveTo(0, .6, -1, 0); G.fill(); }+ else { G.fillStyle = flip > 0 ? '#ffd3de' : '#f4a9bf'; G.beginPath(); G.moveTo(-.9, 0); G.quadraticCurveTo(-.3, -.7, .7, -.35); G.lineTo(.45, 0); G.lineTo(.7, .35); G.quadraticCurveTo(-.3, .7, -.9, 0); G.fill(); }+ G.restore();+ }+}+// dramaticZoom: a snap zoom-in at t0 with overshoot and a decaying shake → { zoom, dx, dy } to add to a camera.+function dramaticZoom(t, t0, amt = .35, shake = 14) {+ if (t < t0) return { zoom: 1, dx: 0, dy: 0 };+ const a = t - t0, z = 1 + amt * backOut(clamp(a / .18)), s = shake * Math.exp(-a * 5), [dx, dy] = shakeXY(t, s);+ return { zoom: z, dx, dy };+}+// smear: draw a moving thing as multiples/ghosts along its path (fast motion). fn(x, y, alpha) draws it once.+function smear(fn, from, to, n = 3) { for (let i = n; i >= 1; i--) { const k = i / (n + 1); G.save(); G.globalAlpha = .28 * (1 - k); fn(lerp(from[0], to[0], k), lerp(from[1], to[1], k), .3); G.restore(); } fn(to[0], to[1], 1); }+// smearLines: tapered motion lines trailing a fast object (world or screen coords)+function smearLines(x0, y0, x1, y1, spread, col = 'rgba(255,255,255,.9)', n = 5, seed = 'sm') {+ const dx = x1 - x0, dy = y1 - y0, l = Math.hypot(dx, dy) || 1, px = -dy / l, py = dx / l, q = rnd(seed);+ for (let i = 0; i < n; i++) { const o = (i / (n - 1) - .5) * spread, k = .5 + q() * .5; ink([[x0 + px * o + dx * (1 - k), y0 + py * o + dy * (1 - k)], [x1 + px * o, y1 + py * o]], 3 + q() * 5, col, TAPER.tail, { raw: true }); }+}+// scratch canvas for full-frame effects+let _tmp = null; const tmpCanvas = () => _tmp || (_tmp = makeCanvas());+// blurBand: re-draw a horizontal band of the current frame motion-blurred (the anime "BG streak" behind a dash).+function blurBand(y, h, o = {}) {+ const c = tmpCanvas(), g = c.getContext('2d'), b = o.blur || 14;+ g.setTransform(1, 0, 0, 1, 0, 0); g.clearRect(0, 0, W, H); g.drawImage(G.canvas, 0, 0);+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0); G.beginPath(); G.rect(0, y, W, h); G.clip();+ G.filter = `blur(${b}px)`; G.drawImage(c, 0, y - 20, W, h + 40, -40, y - 20, W + 80, h + 40); G.filter = 'none';+ G.restore();+ speedLines(o.t || 0, o.ang || 0, { rect: [0, y, W, h], n: o.n || 26, len: 700, w: 4, col: o.col || 'rgba(255,255,255,.55)' });+}+// impactFrame: the anime impact flash. mode 'invert' (negative), 'mono' (hard black/white), 'red' (black/red).+// k = 0..1 strength (use a 2–4 frame hold). Optional radial lines from (o.x, o.y).+function impactFrame(k, mode = 'invert', o = {}) {+ if (k <= 0) return;+ const c = tmpCanvas(), g = c.getContext('2d');+ g.setTransform(1, 0, 0, 1, 0, 0); g.globalCompositeOperation = 'source-over'; g.filter = 'none';+ g.filter = mode === 'invert' ? 'grayscale(1) contrast(4) invert(1)' : 'grayscale(1) contrast(9) brightness(1.1)';+ g.drawImage(G.canvas, 0, 0); g.filter = 'none';+ if (mode === 'red') { g.globalCompositeOperation = 'multiply'; g.fillStyle = '#e8283c'; g.fillRect(0, 0, W, H); g.globalCompositeOperation = 'source-over'; }+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = k; G.drawImage(c, 0, 0);+ if (o.x != null) focusLines(o.t || 0, o.x, o.y, { col: mode === 'invert' ? 'rgba(255,255,255,.9)' : 'rgba(0,0,0,.9)', r: o.r || 260, n: 90, w: 22 });+ G.restore();+}+function flash(k, col = '#ffffff') { if (k <= 0) return; G.save(); G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = clamp(k); G.fillStyle = col; G.fillRect(0, 0, W, H); G.restore(); }++// ======================================================================================= transitions (screen space)+// slashWipe(p): diagonal bands slash across (p 0→.5 covers, .5→1 uncovers the other way). Cut to the next shot at .5+// (call it at the end of shot A with p = k/2 and at the start of shot B with p = .5 + k/2).+function slashWipe(p, o = {}) {+ if (p <= 0 || p >= 1) return;+ const cols = o.cols || ['#ff7da0', '#ffd9e2', '#2d2f5a'], a = o.ang ?? -.35, n = cols.length;+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0); G.translate(W / 2, H / 2); G.rotate(a);+ const D = 2600;+ for (let i = 0; i < n; i++) {+ const lag = i * .07, k = p < .5 ? easeIn(clamp((p * 2 - lag) / (1 - lag * 2))) : easeOut(clamp(((p - .5) * 2 - (n - 1 - i) * .07) / (1 - .14)));+ const x0 = p < .5 ? -D / 2 - 300 : lerp(-D / 2, D / 2 + 300, k), x1 = p < .5 ? lerp(-D / 2 - 300, D / 2, k) : D / 2 + 300;+ const skew = 260;+ G.fillStyle = cols[i]; G.beginPath(); G.moveTo(x0, -D / 2); G.lineTo(x1 + skew, -D / 2); G.lineTo(x1 - skew, D / 2); G.lineTo(x0 - 2 * skew, D / 2); G.fill();+ }+ G.restore();+}+// irisWipe(p, cx, cy, shape): closes to black (p 0→.5) and opens (p .5→1) around a point; shape 'circle' | 'star'.+function irisWipe(p, cx, cy, o = {}) {+ if (p <= 0 || p >= 1) return;+ const R = Math.hypot(W, H), r = p < .5 ? lerp(R, 0, easeIn(p * 2)) : lerp(0, R, easeOut((p - .5) * 2));+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0); G.fillStyle = o.col || '#1a1830'; G.beginPath(); G.rect(0, 0, W, H);+ if (o.shape === 'star') { for (let i = 0; i <= 10; i++) { const a = -Math.PI / 2 + i / 10 * TAU, rr = i % 2 ? r * .45 : r; G[i ? 'lineTo' : 'moveTo'](cx + Math.cos(a) * rr, cy + Math.sin(a) * rr); } }+ else { G.moveTo(cx + r, cy); G.arc(cx, cy, r, 0, TAU, true); }+ G.fill('evenodd'); G.restore();+}++// ======================================================================================= captions+// subtitle(c, txt, o): anime TV subtitle — white text, thick dark outline, soft shadow. Use in window.overlayHook.+// o: { y, size, fg, line, alpha, font, speaker (colour of a small leading bar) }+function subtitle(c, txt, o = {}) {+ const size = o.size || 58, y = o.y || H - 92;+ c.save(); c.globalAlpha = o.alpha ?? 1;+ c.font = o.font || `800 ${size}px "M PLUS Rounded 1c", "Noto Sans TC", "Noto Sans JP", system-ui, sans-serif`;+ c.textAlign = 'center'; c.textBaseline = 'middle'; c.lineJoin = 'round';+ c.shadowColor = 'rgba(10,8,30,.45)'; c.shadowBlur = size * .25; c.shadowOffsetY = size * .06;+ c.strokeStyle = o.line || '#1d1a33'; c.lineWidth = size * .2; c.strokeText(txt, W / 2, y);+ c.shadowColor = 'transparent'; c.fillStyle = o.fg || '#ffffff'; c.fillText(txt, W / 2, y);+ c.restore();+}+window.EXTRA_FONTS = [['800 58px "M PLUS Rounded 1c"', 'あア那個給你請收下'], ['900 58px "Noto Sans TC"', '那個給你請收下']];++// ======================================================================================= grade (ENGINE hooks)+// GRADE is reset every frame; a shot may change it: { bloom 0..1, vignette 0..1, tint }.+let GRADE = {};+let _small = null;+window.ENGINE = {+ begin(t) { GRADE = { bloom: .22, vignette: .22 }; setTOD('day'); },+ end(t) {+ const g = OUT;+ g.setTransform(1, 0, 0, 1, 0, 0);+ if (GRADE.bloom) { // soft diffusion glow of the bright parts (the "compositing" look of TV anime)+ _small = _small || makeCanvas(W / 8, H / 8); const s = _small.getContext('2d');+ s.filter = 'blur(3px) brightness(1.15)'; s.clearRect(0, 0, W / 8, H / 8); s.drawImage(OUTC, 0, 0, W / 8, H / 8); s.filter = 'none';+ g.save(); g.globalCompositeOperation = 'screen'; g.globalAlpha = GRADE.bloom * .6; g.drawImage(_small, 0, 0, W, H); g.restore();+ }+ if (GRADE.vignette) { const v = g.createRadialGradient(W / 2, H / 2, H * .45, W / 2, H / 2, H * 1.05); v.addColorStop(0, 'rgba(40,20,60,0)'); v.addColorStop(1, `rgba(40,20,60,${GRADE.vignette})`); g.fillStyle = v; g.fillRect(0, 0, W, H); }+ },+};diff --git a/.claude/skills/anime-cel/template/src/cast.js b/.claude/skills/anime-cel/template/src/cast.jsnew file mode 100644index 0000000..09c5d47--- /dev/null+++ b/.claude/skills/anime-cel/template/src/cast.js@@ -0,0 +1,720 @@+// cast.js — the anime character system: a shared rig + two original characters (Hina, Ren).+//+// hina(x, y, u, o) / ren(x, y, u, o) → info (x, y) = ground point between the feet, u = HEAD HEIGHT in px+// Heights: Hina ≈ 5.6u, Ren ≈ 5.9u. Full body in frame: u ≈ 120–150 · knees-up: 200–260 · bust: 380–480+// · face close-up: 600–900 (then put the camera on the head: info.head gives its screen point).+//+// Every part is built in the character's own units (1 = head height) from a skeleton posed by joint angles, drawn+// as groups that share one outline (see drawGroup in anime.js), so limbs are continuous silhouettes. The head is+// built on a construction (skull sphere + morphing face outline) so it turns front → 3/4 → profile with features+// placed on the skull. See GUIDE.md for the full option list.++const DEG = Math.PI / 180;+const dirA = a => [Math.sin(a), Math.cos(a)]; // angle measured from straight DOWN, positive toward +x+const addV = (p, d, k = 1) => [p[0] + d[0] * k, p[1] + d[1] * k];+const nrm2 = v => { const l = Math.hypot(v[0], v[1]) || 1; return [v[0] / l, v[1] / l]; };++// draw fn() in a local frame: ex, ey = the local x/y axes (in the current units), o = origin. Light follows.+function inFrame(ex, ey, o, fn) {+ G.save(); G.transform(ex[0], ex[1], ey[0], ey[1], o[0], o[1]);+ const keep = _L, lx = ex[0] * _L[0] + ex[1] * _L[1], ly = ey[0] * _L[0] + ey[1] * _L[1];+ const sx = Math.hypot(...ex), sy = Math.hypot(...ey); _L = nrm2([lx / sx / sx, ly / sy / sy]);+ fn(); _L = keep; G.restore();+}++// ======================================================================================= expressions+// eye: type ('open' | 'happy' | 'closed' | 'xd' | 'dot' | 'line' | 'white' | 'sparkle' | 'tight' | 'half' | 'swirl'),+// open (lid 0..1+), squint (lower lid up 0..1), iris (size ×), tilt (+ angry: inner lid corner down, − worried)+// brow: raise (+ up), ang (+ inner end up = worried/sad, − = angry), mouth: see drawMouth, blush 0..1, fx: face marks+const EXPR = {+ neutral: { eye: { open: 1 }, brow: {}, mouth: 'neutral' },+ smile: { eye: { open: .92, squint: .22 }, brow: { raise: .01 }, mouth: 'smile', blush: .25 },+ happy: { eye: { type: 'happy' }, brow: { raise: .03, ang: .02 }, mouth: 'grin', blush: .45 },+ laugh: { eye: { type: 'happy' }, brow: { raise: .04, ang: .03 }, mouth: 'wide', blush: .5 },+ sad: { eye: { open: .78, iris: .95, tilt: -.14, look: [0, .45], wet: 1 }, brow: { ang: .07, raise: .01 }, mouth: 'frown' },+ cry: { eye: { type: 'tight' }, brow: { ang: .08, raise: .01 }, mouth: 'wail', fx: ['tears'], blush: .4 },+ angry: { eye: { open: .9, tilt: .36, iris: .88, squint: .2 }, brow: { ang: -.13, raise: -.055 }, mouth: 'grit', fx: ['vein'] },+ rage: { eye: { type: 'white', open: 1.05, tilt: .35 }, brow: { ang: -.1, raise: -.03 }, mouth: 'shout', fx: ['vein', 'steam'] },+ surprised: { eye: { open: 1.12, iris: .78 }, brow: { raise: .06 }, mouth: 'o' },+ shocked: { eye: { type: 'white', open: 1.15 }, brow: { raise: .07, ang: .03 }, mouth: 'shout', fx: ['gloom', 'sweat'] },+ scared: { eye: { open: 1.05, iris: .6, tilt: -.1, shake: 1 }, brow: { ang: .08, raise: .04 }, mouth: 'wavy', fx: ['sweat', 'gloom'] },+ love: { eye: { type: 'sparkle', open: 1.05, iris: 1.08 }, brow: { raise: .04, ang: .03 }, mouth: 'grin', blush: .9, fx: ['sparkles'] },+ sleepy: { eye: { type: 'half', open: .38 }, brow: { raise: -.01, ang: .03 }, mouth: 'o', fx: [] },+ deadpan: { eye: { type: 'dot' }, brow: { raise: 0 }, mouth: 'line' },+ xd: { eye: { type: 'xd' }, brow: { ang: .05, raise: .02 }, mouth: 'wide', blush: .6 },+ embarrassed:{ eye: { open: .82, look: [-.6, .35], tilt: -.08, wet: .6 }, brow: { ang: .06, raise: .02 }, mouth: 'wavy', blush: 1, fx: ['sweat'] },+ smug: { eye: { type: 'half', open: .62, squint: .3 }, brow: { raise: .015, ang: -.03 }, mouth: 'cat', blush: .15 },+ determined: { eye: { open: .96, tilt: .22, iris: .95, squint: .1 }, brow: { ang: -.08, raise: -.03 }, mouth: 'set', fx: [] },+ dizzy: { eye: { type: 'swirl' }, brow: { ang: .06 }, mouth: 'wavy', fx: ['sweat'] },+};+const EXPR_NAMES = Object.keys(EXPR);++// ======================================================================================= designs+// Two original characters. Hina: small, bright, long chestnut hair, cream cardigan. Ren: tall, cool, messy navy+// hair, open blazer. Colours go through tone() (time-of-day tint) when drawn.+const DESIGNS = {+ hina: {+ name: 'hina', line: '#4c2830', lineSoft: '#8a4a4c',+ skin: { b: '#fde9de', s: '#f1bda9', h: '#fff7f2' }, blush: '#f5788c', mouthIn: '#9a3040', tongue: '#e8808a',+ hair: { b: '#94513f', s: '#643230', h: '#c47a5c', spec: '#f4bf97', line: '#4a2327' },+ iris: { top: '#123046', mid: '#2a8390', bot: '#98ead3', pupil: '#0d1a28' },+ eyeW: .205, eyeH: .25, eyeY: .07, eyeR: .385, lash: .036, spikes: 2, browCol: '#6e3a36',+ eyeU: [[-.5, .08], [-.38, -.28], [-.1, -.5], [.22, -.5], [.46, -.3], [.62, -.14]],+ eyeL: [[-.46, .2], [-.2, .42], [.14, .47], [.4, .34], [.5, .14]],+ mouthY: .315, chinY: .465, jawW: 1, faceW: 1, earShow: .5,+ // body (units = head height)+ hipH: 2.8, hipX: .19, shV: 1.37, shX: .39, neckV: 1.64, neckLen: .16, neckW: .155, chest: 1.25,+ ua: 1.02, fa: .9, hl: .54, thigh: 1.38, weight: 'R', shin: 1.3, ankleH: .1,+ torso: [[1.66, .07], [1.6, .24], [1.53, .42], [1.42, .48], [1.3, .46], [1.12, .41], [.92, .37], [.62, .33], [.34, .4], [.2, .42]],+ armW: [.25, .215, .18, .205, .19, .205], legW: [.38, .32, .2, .255, .2, .13],+ clothes: 'hina', hairStyle: 'hina',+ cardigan: { b: '#f4e7ca', s: '#d9c39c', h: '#fffaf0' }, collar: { b: '#fbfbff', s: '#d9dbee' }, ribbon: { b: '#e2485c', s: '#b02f46' },+ skirt: { b: '#353f70', s: '#252c52', h: '#4a5690' }, sock: { b: '#2d3150', s: '#1e2138' }, shoe: { b: '#70402f', s: '#4a2620', h: '#a0684f' },+ hairLen: 1.45,+ },+ ren: {+ name: 'ren', line: '#221e38', lineSoft: '#5a4e70',+ skin: { b: '#f9e2d4', s: '#e4b19e', h: '#fff4ec' }, blush: '#ee7f8e', mouthIn: '#8a2c3c', tongue: '#e07b86',+ hair: { b: '#303656', s: '#1c1f37', h: '#4f5a86', spec: '#8e9dd0', line: '#1a1830' },+ iris: { top: '#262550', mid: '#5a5ea8', bot: '#b2bdf0', pupil: '#14132b' },+ eyeW: .198, eyeH: .148, eyeY: .095, eyeR: .375, lash: .03, spikes: 0, browCol: '#242845', browW: .028, browDrop: -.01, crease: .5,+ eyeU: [[-.5, .0], [-.34, -.36], [-.04, -.48], [.3, -.46], [.52, -.24], [.62, -.1]],+ eyeL: [[-.46, .26], [-.2, .46], [.14, .5], [.42, .38], [.54, .1]],+ mouthY: .345, chinY: .515, jawW: .98, faceW: .97, earShow: 1, irisS: .9,+ hipH: 3.02, hipX: .21, shV: 1.44, shX: .49, neckV: 1.74, neckLen: .15, neckW: .235, chest: 1.32,+ ua: 1.12, fa: .97, hl: .6, thigh: 1.5, weight: 'L', pocketArm: 'L', kneeIn: .22, shin: 1.42, ankleH: .1,+ torso: [[1.76, .09], [1.7, .3], [1.63, .52], [1.52, .6], [1.36, .56], [1.15, .5], [.9, .46], [.6, .44], [.2, .47], [-.12, .5]],+ armW: [.3, .26, .215, .245, .225, .235], legW: [.43, .38, .31, .3, .29, .29],+ clothes: 'ren', hairStyle: 'ren',+ blazer: { b: '#3d4873', s: '#29315a', h: '#5a67a0' }, shirt: { b: '#f6f7fc', s: '#d3d7ea' }, tie: { b: '#2d8f89', s: '#1d6461' },+ pants: { b: '#5a5f73', s: '#42465a', h: '#737a92' }, shoe: { b: '#f4f3f6', s: '#c7c6d6', h: '#ffffff' }, shoeAcc: '#e05a5a',+ },+};++// ======================================================================================= hair data+// A lock = control points [azimuth°, y, r] from root to tip on the skull (azimuth 0 = facing the viewer at turn 0,+// +90 = screen right), w = width, flex = how much it swings. Layer 'front' draws over the face, 'back' behind the+// head and body. Locks that turn behind the head move to the back layer by themselves.+const HAIR = {+ hina: {+ Rh: .5, hairline: [-.2, -.14, .06, .16, .32], specY: -.29, capBack: 'b',+ front: [+ { p: [[62, -.3, .5], [74, -.02, .545], [77, .3, .53], [72, .6, .5]], w: .15, flex: 1.3 },+ { p: [[-62, -.3, .5], [-74, -.02, .545], [-77, .3, .53], [-72, .6, .5]], w: .15, flex: 1.3 },+ { p: [[40, -.42, .46], [53, -.2, .555], [60, .03, .535], [62, .13, .51]], w: .15 },+ { p: [[-42, -.42, .46], [-55, -.18, .555], [-62, .05, .535], [-65, .15, .51]], w: .15 },+ { p: [[20, -.46, .44], [30, -.26, .545], [37, -.05, .53], [41, .05, .505]], w: .16 },+ { p: [[-24, -.46, .44], [-34, -.25, .545], [-42, -.05, .53], [-46, .06, .505]], w: .17 },+ { p: [[6, -.48, .42], [11, -.27, .54], [15, -.08, .53], [17, -.01, .505]], w: .16 },+ { p: [[-7, -.48, .42], [-11, -.27, .54], [-14, -.07, .53], [-17, .02, .505]], w: .17 },+ { p: [[0, -.47, .43], [1, -.3, .535], [3, -.15, .53]], w: .1 },+ { p: [[-6, -.42, .16], [-2, -.6, .26], [12, -.7, .28], [24, -.63, .3]], w: .065, flex: 2.2, ahoge: 1 },+ ],+ back: [+ ...[100, 122, 144, 166].map((a, i) => ({ p: [[a, -.25, .5], [a + 4, .3, .6], [a + 2, .95, .6 - i * .02], [a - 4, 1.45 - i * .04, .52]], w: .34 })),+ ...[-100, -122, -144, -166].map((a, i) => ({ p: [[a, -.25, .5], [a - 4, .3, .6], [a - 2, .95, .6 - i * .02], [a + 4, 1.42 - i * .04, .52]], w: .34 })),+ { p: [[88, -.2, .5], [96, .2, .56], [96, .75, .56], [92, 1.25, .52]], w: .2 },+ { p: [[-88, -.2, .5], [-96, .2, .56], [-96, .75, .56], [-92, 1.25, .52]], w: .2 },+ ],+ },+ ren: {+ Rh: .545, hairline: [-.24, -.17, .02, .14, .3], specY: -.32, capBack: 'b',+ front: [+ { p: [[-34, -.5, .4], [-18, -.34, .56], [0, -.12, .545], [12, .02, .52]], w: .17 },+ { p: [[38, -.5, .4], [26, -.32, .565], [12, -.1, .545], [4, .12, .52]], w: .15 },+ { p: [[72, -.26, .5], [82, .0, .555], [84, .2, .52]], w: .14 },+ { p: [[-72, -.26, .5], [-82, .0, .555], [-84, .2, .52]], w: .14 },+ { p: [[44, -.42, .46], [58, -.2, .565], [66, .04, .535]], w: .16 },+ { p: [[-46, -.42, .46], [-60, -.18, .565], [-68, .06, .535]], w: .16 },+ { p: [[26, -.46, .44], [38, -.26, .56], [48, -.06, .53], [54, .02, .505]], w: .17 },+ { p: [[-26, -.46, .44], [-38, -.24, .56], [-48, -.04, .53], [-51, .08, .505]], w: .18 },+ { p: [[10, -.48, .42], [16, -.3, .555], [22, -.08, .535], [26, .04, .505]], w: .19 },+ { p: [[-4, -.48, .42], [-8, -.3, .555], [-16, -.06, .535], [-24, .07, .505]], w: .2 },+ { p: [[2, -.47, .43], [4, -.3, .55], [3, -.16, .535]], w: .11 },+ ],+ back: [+ ...[100, 126, 152, 180, 208, 234, 260].map((a, i) => { const k = 1 - Math.abs(i - 3) / 3; return { p: [[a, -.3, .47], [a + 3, -.05, .52], [a + 6, lerp(.08, .24, k), lerp(.5, .44, k)], [a + 9, lerp(.16, .38, k) + (i % 2) * .03, lerp(.48, .34, k)]], w: lerp(.14, .2, k) }; }),+ ],+ },+};++// ======================================================================================= helpers for scenes+// autoBlink(t, seed): eye openness 0..1 with a blink every ~2.5–4 s, drawn on twos (open, half, shut, half, open).+function autoBlink(t, seed = 0) {+ const per = 3.3, k = Math.floor(t / per), at = k * per + .25 + hash(k * 3.7 + seed * 11.3) * (per - .8), d = t - at;+ if (d < 0 || d >= 4 / 12) return 1;+ return [.45, 0, .1, .6][Math.floor(d * 12)];+}+// talk(t, seed): a mouth shape cycling on threes (8 drawings/s), like anime lip flap. Returns a mouth name.+function talk(t, seed = 0) { const k = Math.floor(t * 8), h = hash(k * 1.93 + seed * 7.1); return ['a', 'o', 'a', 'i', 'n', 'a', 'e', 'o'][Math.floor(h * 8)]; }+// faceAt(t, [[t0, 'neutral'], [1.2, 'surprised'], ...]) → { face, blink, sq, since }: expressions change on a drawing,+// with a 1-frame blink (anime does this) and a small squash-pop the scene may add to the character.+function faceAt(t, keys) {+ let i = 0; while (i + 1 < keys.length && t >= keys[i + 1][0]) i++;+ const since = t - keys[i][0], ch = i > 0 && since < 1 / 12;+ return { face: keys[i][1], blink: ch ? .15 : null, sq: i > 0 ? -.05 * Math.exp(-since * 10) * Math.cos(since * 30) : 0, since };+}+// follow(t, f, k, w): spring follow-through. f(t) → number or [x, y] (e.g. a character's x over time); returns how+// far a loose part (hair, skirt, ribbon) lags/overshoots, in the same units. Pure: integrates the past 1.2 s.+function follow(t, f, k = 6, w = 14, amt = 1) {+ const dt = 1 / 60, v = tt => { const a = f(tt - dt), b = f(tt), c = f(tt + dt); return Array.isArray(b) ? b.map((_, j) => (a[j] - 2 * b[j] + c[j]) / (dt * dt)) : [(a - 2 * b + c) / (dt * dt)]; };+ let acc = null;+ for (let tau = 0; tau < 1.2; tau += dt) {+ const a = v(t - tau), h = Math.exp(-k * tau) * Math.sin(w * tau) / w * dt;+ acc = acc ? acc.map((s, j) => s - a[j] * h) : a.map(x => -x * h);+ }+ return acc.length === 1 ? acc[0] * amt : acc.map(x => x * amt);+}+// walkPose(phase, amt): legs/arms for a walk (phase 0..1 per two steps). For bodies turned ≳ 3/4 (turn ≥ .4).+// one leg's cycle as key poses [phase, hip°, knee°] (contact → down → passing → reach), sampled cyclically+const WALK_KEYS = [[0, 24, 4], [.1, 16, 18], [.3, 0, 6], [.45, -16, 10], [.55, -22, 32], [.7, -4, 56], [.85, 20, 26], [1, 24, 4]];+const RUN_KEYS = [[0, 30, 14], [.13, 8, 34], [.3, -28, 18], [.45, -32, 78], [.65, 14, 112], [.85, 46, 52], [1, 30, 14]];+const cyc = (keys, p) => kf(frac(p), keys.map(([ph, a, b]) => [ph, [a, b]]), x => x);+function walkPose(p, amt = 1) {+ const L = cyc(WALK_KEYS, p), R = cyc(WALK_KEYS, p + .5);+ return { legL: [L[0] * amt, L[1] * amt], legR: [R[0] * amt, R[1] * amt], armL: [-R[0] * .8 * amt, (10 + Math.max(0, R[0]) * .6) * amt], armR: [-L[0] * .8 * amt, (10 + Math.max(0, L[0]) * .6) * amt], lean: 3 * amt };+}+// runPose(phase): a run with forward lean, pumping bent arms and a flight phase (dy).+function runPose(p, amt = 1) {+ const L = cyc(RUN_KEYS, p), R = cyc(RUN_KEYS, p + .5), fl = Math.max(0, Math.sin(frac(p) * TAU * 2 - 1.2));+ return { legL: [L[0] * amt, L[1] * amt], legR: [R[0] * amt, R[1] * amt], armL: [-R[0] * 1.1 * amt, (80 + R[0] * .4) * amt], armR: [-L[0] * 1.1 * amt, (80 + L[0] * .4) * amt], lean: 14 * amt, dy: -.16 * fl * amt };+}+// stroll(t, t0, t1, x0, x1, u, stride): eased walk from x0 to x1 → { x, phase, moving }+function stroll(t, t0, t1, x0, x1, u, stride = 2.6) {+ const k = ease(seg(t, t0, t1)), x = lerp(x0, x1, k);+ return { x, phase: Math.abs(x - x0) / (stride * u), moving: t > t0 && t < t1 };+}++// ======================================================================================= head construction+// Face outline keys (18 points, same order) at turn 0, .5 and 1 (facing screen right); morphed between.+const FACE_KEYS = [+ [[0, -.5], [.28, -.43], [.4, -.25], [.42, -.08], [.415, .04], [.4, .12], [.37, .21], [.315, .29], [.23, .37], [.12, .435], [0, .465], [-.12, .435], [-.23, .37], [-.315, .29], [-.37, .21], [-.415, .04], [-.42, -.25], [-.28, -.43]],+ [[-.03, -.51], [.27, -.44], [.385, -.26], [.41, -.08], [.395, .03], [.405, .11], [.375, .2], [.335, .27], [.275, .35], [.215, .42], [.15, .463], [.03, .43], [-.12, .345], [-.25, .23], [-.37, .08], [-.45, -.12], [-.43, -.33], [-.29, -.47]],+ [[-.03, -.52], [.25, -.45], [.36, -.28], [.4, -.08], [.385, .02], [.45, .15], [.405, .195], [.41, .25], [.4, .3], [.37, .36], [.3, .43], [.16, .39], [.03, .3], [-.1, .17], [-.27, .0], [-.44, -.14], [-.44, -.32], [-.28, -.47]],+];+function faceOutline(D, turn) {+ const a = Math.abs(turn), sg = turn < 0 ? -1 : 1, [A, B, k] = a <= .5 ? [FACE_KEYS[0], FACE_KEYS[1], a / .5] : [FACE_KEYS[1], FACE_KEYS[2], (a - .5) / .5];+ return A.map((p, i) => {+ let x = lerp(p[0], B[i][0], k), y = lerp(p[1], B[i][1], k);+ if (y > .15) { x *= D.jawW; y = .15 + (y - .15) * (D.chinY - .15) / (.465 - .15); }+ return [x * D.faceW * sg, y];+ });+}+const wrapDeg = a => ((a + 180) % 360 + 360) % 360 - 180;+function hairlineY(D, az) { // hairline height at an azimuth (deg): front, 45°, temple, 135°, nape+ const h = HAIR[D.hairStyle].hairline, a = Math.abs(wrapDeg(az)) / 45, i = Math.min(3, Math.floor(a));+ return lerp(h[i], h[i + 1], ease(a - i));+}+// lock → { pts (outline), C (centreline), z (depth: + in front), W (width fn) } in head units+function lockGeom(L, psi, sway, t, key) {+ const n = L.p.length, ph = hash(key * 13.7) * TAU;+ const P = L.p.map(([az, y, r], i) => {+ const k = i / (n - 1), b = az * DEG + psi, f = (L.flex ?? 1) * k * k;+ const w = .012 * Math.sin(t * 2.1 + ph + k * 2) * k * (L.flex ?? 1);+ const rr = i === 0 ? r * .88 : r; return [rr * Math.sin(b) + (sway[0] + w) * f, y + sway[1] * f * .6];+ });+ const C = crPts(P, false, 8), W = s => L.w * (s < .22 ? lerp(.35, 1, Math.sqrt(s / .22)) : Math.pow(Math.max(0, (1 - s) / .78), .9));+ const mid = L.p[Math.floor(n / 2)];+ return { pts: ccw(ribbonPts(C, W, false)), C, W, z: Math.cos(mid[0] * DEG + psi), L };+}+// the eye in eye-local coords (x: -.5 inner → +.5 outer, y: -.5 top → .5 bottom) → head units+function eyeShape(D, ex) {+ const o = clamp(ex.open ?? 1, 0, 1.3), sq = ex.squint || 0, tl = ex.tilt || 0;+ const Yc = x => .2 + .12 * (1 - 4 * x * x); // the closed-lid line (a gentle ∪)+ const U = D.eyeU.map(([x, y]) => { const yo = y * (o > 1 ? o : 1) + tl * (.5 - x) * (tl > 0 ? 1.05 : .6); return [x, lerp(Yc(x), yo, Math.min(1, o))]; });+ if (ex.type === 'half') U.forEach(p => p[1] = Math.max(p[1], lerp(-.05, .12, clamp((1 - o) * 1.4)) + p[0] * .02));+ const Lo = D.eyeL.map(([x, y]) => [x, Math.max(lerp(y, y - .42, sq), 0)]);+ // keep the lower lid under the upper+ for (const p of Lo) { const ux = U.reduce((best, q) => Math.abs(q[0] - p[0]) < Math.abs(best[0] - p[0]) ? q : best); p[1] = Math.max(p[1], ux[1] + .06); }+ return { U, Lo };+}++// ======================================================================================= eyes+function drawEye(D, cx, cy, j, persp, ex, look, t, lw) {+ const ew = D.eyeW * lerp(.42, 1, persp), eh = D.eyeH * (ex.type === 'white' || (ex.open || 1) > 1 ? 1.08 : 1);+ const P = ([x, y]) => [cx + j * x * ew, cy + y * eh], line = tone(D.line), type = ex.type || 'open';+ const lashW = D.lash;+ const lashCurve = (pts, w, prof = TAPER.lash) => ink(pts.map(P), w, line, prof);+ if (type === 'happy') { lashCurve([[-.5, .22], [-.22, -.12], [.12, -.18], [.5, .12]], lashW * 1.05, TAPER.both); return; }+ if (type === 'tight') { lashCurve([[-.5, .02], [-.2, .24], [.15, .16], [.52, .3]], lashW * 1.1, TAPER.both); lashCurve([[.3, .02], [.58, -.1]], lashW * .5, TAPER.both); return; }+ if (type === 'xd') { lashCurve([[.42, -.36], [-.3, .04], [.42, .4]], lashW * 1.25, TAPER.soft); return; }+ if (type === 'dot') { G.fillStyle = line; G.beginPath(); G.ellipse(cx + j * .02 * ew, cy + .1 * eh, .12 * ew, .17 * eh, 0, 0, TAU); G.fill(); return; }+ if (type === 'line') { lashCurve([[-.4, .12], [.45, .1]], lashW * .8, TAPER.both); return; }+ if (type === 'swirl') {+ const pts = []; for (let i = 0; i < 40; i++) { const a = i * .45 + t * 10 * j, r = .05 + i / 40 * .42; pts.push([Math.cos(a) * r, .05 + Math.sin(a) * r * 1.1]); }+ ink(pts.map(P), lashW * .5, line, TAPER.soft); return;+ }+ const { U, Lo } = eyeShape(D, ex);+ const open = ex.open ?? 1;+ if (open < .2) { // shut (blink): one confident lash line+ lashCurve(U, lashW * 1.05, TAPER.lash);+ ink([P([.46, U[4][1]]), P([.6, U[4][1] + .05])], lashW * .4, line, TAPER.head); return;+ }+ const white = polyPath(crPts([...U.slice(0, 5), ...Lo.slice().reverse()], true, 6).map(P));+ // sclera (a cool off-white) with the upper lid's cast shadow+ G.fillStyle = '#fdfbff'; G.fill(white);+ G.save(); G.clip(white);+ if (type !== 'white') {+ const s = (ex.iris ?? 1) * (D.irisS || 1), ix = cx + (look[0] * .2) * ew, iy = cy + (.1 + look[1] * .16) * eh, rx = .33 * ew * s, ry = .5 * eh * s * lerp(.92, 1, persp);+ const ir = new Path2D(); ir.ellipse(ix, iy, rx, ry, 0, 0, TAU);+ const g = G.createLinearGradient(0, iy - ry, 0, iy + ry); g.addColorStop(0, tone(D.iris.top)); g.addColorStop(.5, tone(D.iris.mid)); g.addColorStop(1, tone(D.iris.bot));+ G.fillStyle = g; G.fill(ir);+ G.save(); G.clip(ir);+ G.fillStyle = tone(D.iris.pupil); G.beginPath(); G.ellipse(ix, iy - ry * .06, rx * .42, ry * .44, 0, 0, TAU); G.fill();+ G.globalAlpha = .75; G.fillStyle = tone(D.iris.bot); G.beginPath(); G.ellipse(ix, iy + ry * .78, rx * .72, ry * .42, 0, 0, TAU); G.fill(); // lower glow+ G.globalAlpha = .5; for (let k = -2; k <= 2; k++) { if (!k) continue; ink([[ix + rx * .16 * k, iy + ry * .25], [ix + rx * .3 * k, iy + ry * .8]], rx * .09, '#ffffff', TAPER.both, { raw: true }); }+ G.globalAlpha = 1; G.strokeStyle = tone(D.iris.top); G.lineWidth = rx * .1; G.stroke(ir);+ G.restore();+ // catch-lights: a big one toward the light, a small one opposite (sparkle eyes: stars)+ const lx = _L[0] >= 0 ? 1 : -1;+ if (type === 'sparkle') {+ sparkle(ix + lx * rx * .3, iy - ry * .3, rx * .75, t * 2, '#ffffff', false); sparkle(ix - lx * rx * .35, iy + ry * .35, rx * .38, .4, '#ffffff', false);+ sparkle(ix + lx * rx * .45, iy + ry * .45, rx * .18, 0, '#ffffff', false);+ } else {+ G.fillStyle = '#ffffff'; G.beginPath(); G.ellipse(ix + lx * rx * .36, iy - ry * .34, rx * .32, ry * .24, -.4 * lx, 0, TAU); G.fill();+ G.beginPath(); G.ellipse(ix - lx * rx * .34, iy + ry * .36, rx * .14, ry * .1, 0, 0, TAU); G.fill();+ }+ if (ex.wet) { G.globalAlpha = .8 * ex.wet; ink([[ix - rx * .9, iy + ry * .62], [ix, iy + ry * .75], [ix + rx * .9, iy + ry * .6]], ry * .1, '#ffffff', TAPER.both); G.globalAlpha = 1; }+ } else {+ const ix = cx + look[0] * .1 * ew, iy = cy + .06 * eh; G.fillStyle = line; G.beginPath(); G.ellipse(ix, iy, .05 * ew, .07 * eh, 0, 0, TAU); G.fill();+ }+ // the upper lid's shadow band on the eye+ const band = [...U.slice(0, 5), ...U.slice(0, 5).reverse().map(([x, y]) => [x, y + .24])];+ G.fillStyle = 'rgba(70,50,110,.22)'; G.fill(polyPath(crPts(band, true, 5).map(P)));+ G.restore();+ // line work: crease, upper lash (thick, flicks out), lash spikes, lower lash (thin, outer part)+ if ((D.crease ?? 1) > 0) { G.globalAlpha = D.crease ?? 1; ink(U.slice(1, 5).map(([x, y]) => [x + .04, y - .18 - .04 * (1 - Math.abs(x))]).map(P), lashW * .22, tone(D.lineSoft), TAPER.both); G.globalAlpha = 1; }+ lashCurve(U, lashW);+ const tip = U[5], u4 = U[4];+ for (let k = 0; k < D.spikes; k++) { const b = P([u4[0] - .08 - k * .12, u4[1] - .06 + k * .02]), e = P([u4[0] + .1 - k * .1, u4[1] - .24 - k * .04]); ink([b, e], lashW * .45, line, TAPER.head); }+ const lo = crPts(Lo, false, 6), n0 = Math.floor(lo.length * .42);+ ink(lo.slice(n0).map(([x, y]) => P([x, y + .03])), lashW * .38, line, TAPER.both, { raw: true });+ ink(lo.slice(2, Math.floor(lo.length * .24)).map(([x, y]) => P([x, y + .03])), lashW * .18, tone(D.lineSoft), TAPER.both, { raw: true });+}+function drawBrow(D, cx, cy, j, persp, br, lw) {+ const ew = D.eyeW * lerp(.5, 1, persp), y0 = cy - D.eyeH * .5 - .07 - (D.browDrop || 0) - (br.raise || 0), a = br.ang || 0;+ const P = ([x, y]) => [cx + j * x * ew, y0 + y];+ ink([[-.42, -a * .75 + .005], [-.1, -.028 - a * .3], [.3, -.03 + a * .05], [.66, .012 + a * .2]].map(P), D.browW || .02, tone(D.browCol), TAPER.both);+}++// ======================================================================================= mouths+// Mouth names: neutral smile grin wide open o cat frown wavy line set grit shout wail + talk shapes a i u e o n+function drawMouth(D, mx, my, fw, name, lw, t) {+ const line = tone(D.line), inC = tone(D.mouthIn), tg = tone(D.tongue);+ G.save(); G.translate(mx, my); G.scale(fw, 1);+ const lip = (pts, w = .013, prof = TAPER.both) => ink(pts, w, line, prof);+ const hole = (pts, tongue = true, teeth = 0) => {+ const p = polyPath(crPts(pts, true, 6)); G.fillStyle = inC; G.fill(p);+ G.save(); G.clip(p);+ if (tongue) { G.fillStyle = tg; G.beginPath(); G.ellipse(0, Math.max(...pts.map(q => q[1])) + .006, .05, .035, 0, 0, TAU); G.fill(); }+ if (teeth) { G.fillStyle = '#ffffff'; G.fillRect(-.2, Math.min(...pts.map(q => q[1])) - .01, .4, teeth); }+ G.restore();+ G.strokeStyle = line; G.lineWidth = lw * .55; G.lineJoin = 'round'; G.stroke(p);+ };+ switch (name) {+ case 'smile': lip([[-.05, -.012], [-.02, .006], [.02, .006], [.05, -.012]], .012); break;+ case 'neutral': case 'n': lip([[-.03, .002], [0, .004], [.03, 0]], .01); break;+ case 'line': lip([[-.055, 0], [.055, .002]], .011); break;+ case 'frown': lip([[-.04, .01], [0, -.006], [.04, .01]], .011); break;+ case 'set': lip([[-.05, .004], [0, -.004], [.05, .002]], .012); break;+ case 'grin': hole([[-.065, -.012], [0, -.006], [.065, -.012], [.03, .045], [-.03, .045]], true, .012); break;+ case 'wide': case 'shout': hole([[-.075, -.03], [0, -.04], [.075, -.03], [.055, .06], [0, .085], [-.055, .06]], true, name === 'shout' ? .014 : 0); break;+ case 'wail': hole([[-.07, -.01], [-.02, -.035], [.03, -.02], [.07, -.03], [.06, .05], [0, .07], [-.06, .05]], true, 0); break;+ case 'a': case 'open': hole([[-.04, -.012], [0, -.016], [.04, -.012], [.025, .035], [-.025, .035]], true); break;+ case 'i': case 'e': hole([[-.05, -.01], [0, -.012], [.05, -.01], [.035, .018], [-.035, .018]], false, .01); break;+ case 'o': case 'u': hole([[0, -.022], [.022, 0], [0, .03], [-.022, 0]], false); break;+ case 'cat': lip([[-.05, -.012], [-.025, .01], [0, -.004]], .011); lip([[0, -.004], [.025, .01], [.05, -.012]], .011); break;+ case 'wavy': { const P = []; for (let i = 0; i <= 12; i++) { const x = -.05 + i / 12 * .1; P.push([x, Math.sin(i * 1.6 + t * 20) * .007]); } lip(P, .011, TAPER.soft); break; }+ case 'grit': G.scale(1.35, 1.35); G.fillStyle = '#ffffff'; G.beginPath(); G.roundRect(-.06, -.018, .12, .034, .012); G.fill(); G.strokeStyle = line; G.lineWidth = lw * .5; G.stroke();+ G.beginPath(); G.moveTo(-.058, 0); G.lineTo(.058, 0); for (const x of [-.03, 0, .03]) { G.moveTo(x, -.017); G.lineTo(x, .016); } G.lineWidth = lw * .3; G.stroke(); break;+ default: lip([[-.03, .002], [0, .004], [.03, 0]], .01);+ }+ G.restore();+}++// ======================================================================================= face marks (comedy fx)+function sweatDrop(x, y, s, line, t) {+ const dy = (t % 1.2) * .04 * s;+ const P = [[0, -1, 0, true], [.55, .3], [0, .75], [-.55, .3]].map(([a, b, ...r]) => [x + a * s, y + dy + b * s, ...r]);+ const path = polyPath(ccw(crPts(P.map(p => [p[0], p[1], 0, p[3]]), true, 7)));+ drawGroup([{ path, b: '#cfeeff', s: '#8fc8ee', d: s * .22 }], line, s * .1);+ G.fillStyle = '#ffffff'; G.beginPath(); G.ellipse(x - s * .18, y + dy + s * .18, s * .09, s * .18, .3, 0, TAU); G.fill();+}+function angerVein(x, y, s, t) {+ const k = 1 + .12 * Math.sin(t * 18), col = '#e2324c';+ for (let i = 0; i < 4; i++) {+ const a = i * Math.PI / 2 + Math.PI / 4, cx = x + Math.cos(a) * s * .42 * k, cy = y + Math.sin(a) * s * .42 * k, r = s * .36 * k;+ const P = []; for (let j = 0; j <= 8; j++) { const b = a + Math.PI - .95 + j / 8 * 1.9; P.push([cx + Math.cos(b) * r, cy + Math.sin(b) * r]); }+ ink(P, s * .17, col, TAPER.soft, { raw: true });+ }+}+function tearStreams(D, eyes, t) {+ for (const e of eyes) {+ const x0 = e.cx + e.j * D.eyeW * .25, y0 = e.cy + D.eyeH * .4, P = [];+ for (let i = 0; i <= 10; i++) { const k = i / 10; P.push([x0 + e.j * (.02 + k * .05) + Math.sin(k * 7 - t * 18 + e.j) * .012, y0 + k * .62]); }+ ink(P, .07, 'rgba(150,215,255,.92)', s => .55 + .45 * s); ink(P.map(([x, y]) => [x - .012, y]), .018, 'rgba(255,255,255,.95)', TAPER.both);+ G.fillStyle = 'rgba(160,220,255,.9)'; G.beginPath(); G.ellipse(e.cx, e.cy + D.eyeH * .38, D.eyeW * .45, D.eyeH * .12, 0, 0, TAU); G.fill();+ }+}++// ======================================================================================= head+// headGeom: everything about the head at this pose, in head units (origin = centre of the skull, 1 = head height).+function headGeom(D, o, t) {+ const turn = clamp(o.headTurn ?? o.turn ?? 0, -1, 1), psi = turn * Math.PI / 2, H = HAIR[D.hairStyle], sway = o.sway || [0, 0];+ const face = faceOutline(D, turn), facePath = smooth(face, true, 7);+ const locks = { front: [], back: [] };+ H.front.forEach((L, i) => { const g = lockGeom(L, psi, sway, t, i); (g.z < -.28 ? locks.back : locks.front).push(g); });+ H.back.forEach((L, i) => { const g = lockGeom(L, psi, [sway[0] * 1.4, sway[1]], t, 50 + i); (g.z > .15 ? locks.front : locks.back).push(g); });+ // the front hair cap: hairline across the visible hemisphere + the skull silhouette over the top+ const Rh = H.Rh, cap = [], cy = -.06;+ for (let b = -90; b <= 90; b += 5) cap.push([Rh * Math.sin(b * DEG), hairlineY(D, b - turn * 90)]);+ const yR = cap[cap.length - 1][1], yL = cap[0][1];+ if (yR > cy) cap.push([Rh, cy]);+ for (let a = 6; a <= 174; a += 6) cap.push([Rh * Math.cos(a * DEG), cy - Rh * Math.sin(a * DEG) * 1.02]);+ if (yL > cy) cap.push([-Rh, cy]);+ return { turn, psi, face, facePath, locks, cap: polyPath(ccw(cap)), Rh };+}+function drawHeadBack(D, hg, lw) {+ const hc = D.hair, back = [];+ const nape = HAIR[D.hairStyle].hairline[4], cb = [];+ for (let a = 0; a <= 360; a += 10) { const x = hg.Rh * .97 * Math.cos(a * DEG), y = -.06 + hg.Rh * .99 * Math.sin(a * DEG); cb.push([x, Math.min(y, nape)]); }+ const capB = polyPath(ccw(cb));+ back.push({ path: capB, b: tone(hc.s), d: 0 });+ for (const g of hg.locks.back.sort((a, b) => a.z - b.z)) back.push({ path: polyPath(g.pts), b: tone(hc.b), s: tone(hc.s), h: tone(hc.h), d: .07, r: .018, join: 'miter' });+ drawGroup(back, tone(hc.line), lw);+ for (const g of hg.locks.back) strand(g, tone(hc.line), lw * .7);+}+function strand(g, col, w) { // an interior strand line along one side of a lock, from its tip up+ const C = g.C, N = C.length, a = Math.floor(N * .38), side = [];+ for (let i = a; i < N - 1; i++) { const p = C[i], q = C[i + 1], dx = q[0] - p[0], dy = q[1] - p[1], l = Math.hypot(dx, dy) || 1, ww = g.W(i / (N - 1)) * .5 * .55; side.push([p[0] - dy / l * ww, p[1] + dx / l * ww]); }+ if (side.length > 2) ink(side, w * 1.4, col, s => Math.pow(Math.sin(Math.PI * s), .5) * (.3 + .7 * s), { raw: true });+}+function drawHeadFront(D, hg, o, t, lw) {+ const ex = o.expr, turn = hg.turn, psi = hg.psi, sk = D.skin, line = tone(D.line);+ // ears (part of the face silhouette)+ const parts = [], ears = [];+ for (const j of [-1, 1]) {+ const th = psi + j * Math.PI / 2, c = Math.cos(th); if (c < -.25) continue;+ const s = Math.sin(th), ex_ = clamp(s * 1 + (turn ? -Math.sign(turn) : 0) * Math.max(0, c) * .9, -1, 1), x0 = .4 * s * D.faceW;+ const sc = D.earShow * lerp(.45, 1, Math.abs(ex_)), sgn = ex_ >= 0 ? 1 : -1;+ const P = [[0, -.07], [.06, -.075], [.085, .0], [.06, .08], [.02, .12], [0, .09]].map(([x, y]) => [x0 + sgn * x * sc * 1.1, .1 + y]);+ ears.push({ P, sgn, x0, sc });+ parts.push({ path: smooth(P, true, 6), b: tone(sk.b), s: tone(sk.s), d: .02 });+ }+ parts.push({ path: hg.facePath, b: tone(sk.b), s: tone(sk.s), h: tone(sk.h), d: .045 * Math.max(.4, Math.abs(Math.sin(psi)) + .3), r: .012 });+ drawGroup(parts, line, lw);+ for (const e of ears) ink([[e.x0 + e.sgn * .05 * e.sc, .06], [e.x0 + e.sgn * .03 * e.sc, .12], [e.x0 + e.sgn * .01 * e.sc, .15]], lw * .8, tone(D.lineSoft), TAPER.both);+ // front hair geometry (needed for the shadow it casts on the face)+ const hc = D.hair, frontLocks = hg.locks.front.sort((a, b) => a.z - b.z);+ const hairParts = [{ path: hg.cap, b: tone(hc.b), noLine: false }];+ for (const g of frontLocks) hairParts.push({ path: polyPath(g.pts), b: tone(hc.b), s: tone(hc.s), d: .045, join: 'miter' });+ const hairU = union(hairParts.map(p => p.path));+ // face details, clipped to the face+ const eyes = [];+ for (const j of [-1, 1]) { const th = psi + j * .47, c = Math.cos(th); if (c < -.12) continue; eyes.push({ j, cx: D.eyeR * Math.sin(th) * D.faceW * (1 - .2 * clamp((Math.abs(turn) - .6) / .4) * (c > .3 ? 1 : 0)) + (o.eyeShake ? Math.sin(t * 90 + j) * .006 : 0), cy: D.eyeY, persp: clamp(c, 0, 1) }); }+ G.save(); G.clip(hg.facePath);+ G.fillStyle = tone(sk.s); G.fill(shifted(hairU, -_L[0] * .035, .075)); // hair shadow on the forehead+ const fw = lerp(.55, 1, Math.cos(psi)), sn = Math.sin(psi);+ if (ex.fx && ex.fx.includes('gloom')) {+ const g = G.createLinearGradient(0, -.4, 0, .2); g.addColorStop(0, 'rgba(60,70,160,.55)'); g.addColorStop(1, 'rgba(60,70,160,0)'); G.fillStyle = g; G.fillRect(-.6, -.6, 1.2, .9);+ for (let i = 0; i < 7; i++) ink([[-.28 + i * .09 + sn * .15, -.3], [-.28 + i * .09 + sn * .15, -.08 - (i % 2) * .05]], .012, 'rgba(40,40,110,.7)', TAPER.head, { raw: true });+ }+ const bl = o.blush ?? ex.blush ?? 0;+ if (bl > 0) for (const e of eyes) {+ const bx = e.cx + e.j * .03 + sn * .02, by = e.cy + D.eyeH * .78, rx = .085 * lerp(.5, 1, e.persp);+ const g = G.createRadialGradient(bx, by, 0, bx, by, rx * 1.2); g.addColorStop(0, D.blush + Math.round(clamp(bl) * 150).toString(16).padStart(2, '0')); g.addColorStop(1, D.blush + '00');+ G.fillStyle = g; G.save(); G.translate(bx, by); G.scale(1, .5); G.translate(-bx, -by); G.beginPath(); G.arc(bx, by, rx * 1.2, 0, TAU); G.fill(); G.restore();+ if (bl > .35) { G.globalAlpha = clamp(bl * 1.2); for (let k = 0; k < 3 + (bl > .7); k++) { const hx = bx - rx * .55 + k * rx * .38 * lerp(.6, 1, e.persp); ink([[hx + .014, by - .018], [hx - .012, by + .018]], .01, tone('#e0506c'), TAPER.both, { raw: true }); } G.globalAlpha = 1; }+ }+ // nose: a small tick + a shadow plane on the far side+ const nx = .43 * sn * D.faceW, ny = .225;+ if (Math.abs(turn) < .85) {+ const k = Math.abs(sn), sg = Math.sign(sn) || (_L[0] > 0 ? -1 : 1);+ G.fillStyle = tone(sk.s); G.beginPath(); G.moveTo(nx, ny - .06); G.lineTo(nx + sg * (.018 + .02 * k), ny + .005); G.lineTo(nx, ny + .012); G.fill();+ ink([[nx + sg * (.004 + .018 * k), ny - .01], [nx + sg * (.012 + .02 * k), ny + .008], [nx - sg * .006, ny + .012]], lw * .75, tone(D.lineSoft), TAPER.both);+ } else ink([[nx - .03 * Math.sign(sn), ny + .01], [nx - .012 * Math.sign(sn), ny + .016]], lw * .6, tone(D.lineSoft), TAPER.both);+ // mouth+ const mouth = o.mouth || ex.mouth || 'neutral';+ drawMouth(D, .4 * sn * D.faceW * (Math.abs(turn) > .8 ? .93 : .92), D.mouthY, fw, mouth, lw, t);+ G.restore();+ // front hair: cap + locks, one silhouette; per-lock shade; spec band; strand lines+ drawGroup(hairParts, tone(hc.line), lw);+ G.save(); G.clip(hairU);+ G.fillStyle = tone(hc.s); G.globalAlpha = .9; G.fill(shifted(hairU, 0, .0)); G.globalAlpha = 1;+ G.clip(shifted(hairU, _L[0] * .05, _L[1] * .05 - .012));+ G.fillStyle = tone(hc.b); G.fill(hairU);+ for (const g of frontLocks) { const p = polyPath(g.pts); G.save(); G.clip(p); G.fillStyle = tone(hc.s); G.fill(p); G.clip(shifted(p, _L[0] * g.L.w * .24, _L[1] * g.L.w * .12 - .01)); G.fillStyle = tone(hc.b); G.fill(p); G.restore(); }+ // the "angel ring" specular band+ // a zig-zag band on the skull, broken into clumps, biased toward the light; it slides as the head turns+ const H = HAIR[D.hairStyle], q = rnd('spec' + D.name), band = new Path2D(), lb = _L[0] < 0 ? -1 : 1;+ const runs = [[-62, -30], [-24, 8], [14, 44], [50, 70]].map(([a, b]) => [a + lb * 8, b + lb * 8]);+ runs.forEach(([a0, a1], ri) => {+ const top = [], bot = [], n = 8, fade = ri === (lb < 0 ? 3 : 0) ? .55 : 1;+ for (let i = 0; i <= n; i++) {+ const az = lerp(a0, a1, i / n) * DEG + psi * .9, c = Math.cos(az); if (c < .08) continue;+ const x = hg.Rh * .96 * Math.sin(az), y = H.specY + .075 * (1 - c), edge = i === 0 || i === n;+ const up = edge ? 0 : (.025 + q() * .05) * c * fade, dn = edge ? 0 : (.035 + q() * .08) * c * fade, th = .007 * c;+ top.push([x, y - th - (i % 2 ? up : 0)]); bot.push([x + .004, y + th + (i % 2 ? 0 : dn)]);+ }+ if (top.length > 2) polyPath([...top, ...bot.reverse()], true, band);+ });+ G.fillStyle = tone(hc.spec); G.fill(band);++ G.restore();+ for (const g of frontLocks) if (!g.L.ahoge) strand(g, tone(hc.line), lw * .75);+ // eyes and brows (drawn over the hair, as anime does), clipped to the face so turned heads hide the far eye+ G.save(); G.clip(union([hg.facePath, hairU]));+ const look = o.look || ex.eye.look || [0, 0], eyeState = { ...ex.eye };+ if (o.blink != null && eyeState.type !== 'happy' && !['xd', 'dot', 'line', 'tight', 'swirl'].includes(eyeState.type)) eyeState.open = (eyeState.open ?? 1) * o.blink;+ for (const e of eyes) {+ const lk = [clamp(look[0] + sn * .55, -1, 1) * e.j * (e.j), look[1]];+ drawEye(D, e.cx, e.cy, e.j, e.persp, eyeState, [look[0] + sn * .5, look[1]], t, lw);+ if (!['xd', 'happy'].includes(eyeState.type) || true) drawBrow(D, e.cx, e.cy, e.j, e.persp, ex.brow || {}, lw);+ }+ G.restore();+ // face marks+ const fx = [...(ex.fx || []), ...(o.fx || [])], side = _L[0] > 0 ? -1 : 1;+ if (ex.fx && ex.fx.includes('tears')) tearStreams(D, eyes, t);+ if (fx.includes('sweat')) sweatDrop(side * .44 + sn * .1, -.3, .1, line, t);+ if (fx.includes('vein')) angerVein(-side * .26 + sn * .12, -.36, .13, t);+ if (fx.includes('steam')) for (let i = 0; i < 2; i++) { const k = frac(t * 1.4 + i * .5), x = (i ? .5 : -.5) * (1 + k * .3), y = -.35 - k * .3; G.globalAlpha = 1 - k; G.fillStyle = '#ffffff'; G.beginPath(); G.arc(x, y, .06 + k * .06, 0, TAU); G.arc(x + .06, y - .03, .05 + k * .05, 0, TAU); G.fill(); G.globalAlpha = 1; }+ return { eyes };+}++// ======================================================================================= hands+// Hand shapes in hand-local units (1 = hand length): origin = wrist, +x toward the fingertips, +y = thumb side.+// 'open' 'fist' 'point' 'peace' 'spread' 'hold' (pinch: a flat prop sits between thumb and fingers) 'grip' (a+// handle sits inside the curled fingers). Returns the parts per layer: back (behind the prop) and front.+function handShape(shape) {+ const F = (P, w) => tubePts(P.map(([x, y], i) => [x, y, w * (1 - i / P.length * .22)]), 6), palm = [[-.02, -.15], [.2, -.22], [.46, -.22], [.5, .02], [.46, .2], [.2, .2], [-.02, .14]];+ const ys = [-.17, -.055, .06, .16];+ const fingers = (len, curl) => ys.map((y, i) => { const l = len * [.92, 1, .96, .8][i]; return F([[.4, y], [.4 + l * .55, y + curl * .3 - .01 * i], [.4 + l, y + curl]], .125); });+ const thumbOut = F([[.12, .15], [.3, .3], [.5, .34]], .14);+ switch (shape) {+ case 'relax': return { back: [[[-.02, -.13], [.2, -.17], [.44, -.16], [.5, .02], [.44, .15], [.2, .15], [-.02, .12]], ...[-.1, 0, .09].map((y, i) => F([[.4, y], [.62, y + .03], [.78, y + .12 + i * .02], [.8, y + .2]], .12)), F([[.1, .12], [.3, .22], [.46, .26]], .12)], front: [], lines: [[[.62, -.05], [.76, .02]], [[.62, .045], [.76, .12]]] };+ case 'fist': return { back: [palm, ...ys.map((y, i) => F([[.38, y], [.52, y + .01]], .13 + (i === 3 ? -.01 : 0)))], front: [F([[.12, .17], [.32, .2], [.5, .08]], .13)], lines: ys.slice(0, 3).map((y, i) => [[.46, y + .055], [.56, y + .06]]) };+ case 'point': return { back: [palm, ...ys.slice(1).map(y => F([[.38, y], [.52, y + .01]], .13)), F([[.4, -.17], [.7, -.19], [1.02, -.19]], .115)], front: [F([[.12, .17], [.32, .2], [.5, .08]], .13)], lines: [[[.46, 0], [.56, 0]], [[.46, .11], [.56, .11]]] };+ case 'peace': return { back: [palm, ...ys.slice(2).map(y => F([[.38, y], [.52, y + .01]], .13)), F([[.4, -.17], [.72, -.28], [.98, -.36]], .115), F([[.4, -.06], [.74, -.06], [1.02, -.05]], .115)], front: [F([[.12, .17], [.32, .2], [.5, .1]], .13)], lines: [[[.46, .11], [.56, .11]]] };+ case 'spread': return { back: [palm, ...ys.map((y, i) => { const a = (i - 1.5) * .3, l = .55 * [.92, 1, .96, .8][i]; return F([[.42, y], [.42 + Math.cos(a) * l * .55, y + Math.sin(a) * l * .55], [.42 + Math.cos(a) * l, y + Math.sin(a) * l]], .12); }), F([[.14, .16], [.28, .36], [.42, .52]], .14)], front: [], lines: [] };+ case 'hold': return { back: [palm, ...fingers(.52, .05)], front: [F([[.12, .16], [.34, .12], [.58, .02]], .14)], grip: [.6, .06], lines: [[[.72, -.11], [.93, -.1]], [[.72, .005], [.95, .01]], [[.72, .11], [.9, .12]]] };+ case 'grip': return { back: [palm], front: [...ys.map(y => F([[.36, y], [.56, y + .02], [.6, y + .12]], .13)), F([[.12, .17], [.32, .22], [.5, .16]], .13)], grip: [.52, .12], lines: [] };+ default: return { back: [palm, ...fingers(.52, .05), thumbOut], front: [], lines: [[[.72, -.11], [.93, -.1]], [[.72, .005], [.96, .01]], [[.72, .11], [.9, .12]]] };+ }+}+function drawHand(D, wrist, ang, th, shape, prop, lw, u) {+ const hl = D.hl, ex = [Math.sin(ang) * hl, Math.cos(ang) * hl], ey = [-Math.cos(ang) * hl * th, Math.sin(ang) * hl * th];+ const S = handShape(shape), sk = D.skin, line = tone(D.line), L = lw / hl;+ let gripAt = null;+ inFrame(ex, ey, wrist, () => {+ const part = P => ({ path: polyPath(ccw(P.length > 8 ? P : crPts(P, true, 5))), b: tone(sk.b), s: tone(sk.s), d: .07 });+ drawGroup(S.back.map(part), line, L);+ for (const l of S.lines) ink(l, L * 1.1, tone(D.lineSoft), TAPER.both);+ if (S.grip) {+ gripAt = S.grip;+ if (prop) { G.save(); G.translate(...S.grip); G.rotate(((prop.rot || 0)) * DEG); G.scale(1 / hl, 1 / hl); G.translate(...(prop.at || [0, 0])); prop.draw(prop.s || 1, line); G.restore(); }+ }+ if (S.front.length) drawGroup(S.front.map(part), line, L);+ });+ return gripAt ? addV(addV(wrist, ex, gripAt[0]), ey, gripAt[1]) : addV(wrist, ex, .5);+}++// ======================================================================================= body+function drawChar(D, x, y, u, o = {}) {+ const t = o.t ?? T;+ const lwPx = o.lw ?? clamp(1.5 + u * .011, 2, 6.5), lw = lwPx / u;+ const fx = o.flip ? -1 : 1, sq = o.sq || 0, sx = 1 + sq * .6, syy = 1 - sq;+ // pose+ let pose = { ...o };+ if (o.walk != null) pose = { ...walkPose(o.walk, o.walkAmt ?? 1), ...o, legL: o.legL || walkPose(o.walk, o.walkAmt ?? 1).legL, legR: o.legR || walkPose(o.walk, o.walkAmt ?? 1).legR };+ if (o.run != null) { const r = runPose(o.run, o.runAmt ?? 1); pose = { ...r, ...o, legL: o.legL || r.legL, legR: o.legR || r.legR, armL: o.armL || r.armL, armR: o.armR || r.armR, lean: (o.lean ?? 0) + r.lean, dy: (o.dy || 0) + r.dy }; }+ if (o.walk != null) { const w = walkPose(o.walk, o.walkAmt ?? 1); pose.armL = o.armL || w.armL; pose.armR = o.armR || w.armR; pose.lean = (o.lean ?? 0) + w.lean; }+ const bt = clamp(o.bodyTurn ?? o.turn ?? 0, -1, 1), abt = Math.abs(bt), side = abt > .3, f = bt >= 0 ? 1 : -1;+ // contrapposto: a standing pose puts the weight on one leg — that hip rises and pushes out, the shoulders counter-tilt,+ // the spine makes a gentle S, the free knee relaxes. Default for standing; stance:'straight' turns it off.+ const moving = o.walk != null || o.run != null, standing = !moving && o.ground !== false;+ const cp = (o.stance ?? (standing ? 'contra' : 'straight')) === 'contra' ? (o.contra ?? 1) : 0, ws = (o.weight || D.weight || 'R') === 'L' ? -1 : 1;+ if (cp) {+ if (!o.legL && !o.legR) { const wl = side ? [-5, 3] : [-3, 0], fl = side ? [16, 26] : [9, 32]; pose.legL = ws < 0 ? wl : fl; pose.legR = ws < 0 ? fl : wl; pose.legL = pose.legL.map(v => v * cp); pose.legR = pose.legR.map(v => v * cp); }+ const nearIsL = f > 0, nearA = [1 * cp, 12 * cp, 'relax'], farA = [-11 * cp, 10 * cp, 'relax'];+ if (!o.armL) pose.armL = side ? (nearIsL ? nearA : farA) : D.pocketArm === 'L' ? [14 * cp, -40 * cp, 'pocket'] : [5 * cp, (ws < 0 ? 10 : 18) * cp, 'relax'];+ if (!o.armR) pose.armR = side ? (nearIsL ? farA : nearA) : [5 * cp, (ws < 0 ? 18 : 10) * cp, 'relax'];+ if (side) { pose.lean = (pose.lean || 0) - 2.5 * f * cp; pose.headFwd = 5 * f * cp; }+ }+ const pelvisRoll = side ? 0 : -ws * 7.5 * DEG * cp, shoulderRoll = side ? 0 : ws * 4 * DEG * cp, sCurve = side ? 0 : -ws * 3 * DEG * cp;+ const lean = (pose.lean || 0) * DEG, bend = (pose.bend || 0) * DEG, wf = lerp(1, .64, abt);+ const expr = typeof o.face === 'object' ? o.face : (EXPR[o.face || 'neutral'] || EXPR.neutral);+ const blink = o.blink ?? (o.autoBlink === false ? 1 : autoBlink(t, D.name === 'ren' ? 5 : 1));+ const mouth = o.mouth || (o.talk ? talk(t, D.name.length) : null);+ // legs → where the pelvis must be for the feet to touch the ground+ const legA = s => { const L = (s < 0 ? pose.legL : pose.legR) || [0, 0]; if (side) { const a1 = L[0] * DEG * f; return [a1, a1 - (L[1] || 0) * DEG * f, 1]; } const a1 = L[0] * DEG * s; return [a1, a1 - s * (L[1] || 0) * DEG * (D.kneeIn ?? .6), Math.cos((L[1] || 0) * DEG * .5)]; };+ const hipJ = s => [s * D.hipX * lerp(1, .3, abt), Math.sin(pelvisRoll) * s * D.hipX];+ const legPts = s => { const [a1, a2, fsh] = legA(s), h = hipJ(s), k = addV(h, dirA(a1), D.thigh * (side ? 1 : lerp(1, .9, 1 - fsh))), an = addV(k, dirA(a2), D.shin * fsh); return { h, k, an, a1, a2 }; };+ const LL = legPts(-1), LR = legPts(1);+ const low = Math.max(LL.an[1], LR.an[1]) + D.ankleH;+ const py = (o.ground === false ? -D.hipH : -low) + (pose.dy || 0);+ const Pv = [(pose.hipX || 0) + ws * .07 * cp * (side ? 0 : 1), py];+ // spine frame: height v above the hip joints, sideways offset xx; lean + bend + S-curve, pelvis→shoulder roll+ const F = (v, xx) => { const k = ease(clamp(v / 1.5)), roll = lerp(pelvisRoll, shoulderRoll, k);+ const r = rot2(xx * Math.cos(roll), -v + xx * Math.sin(roll), lean + bend * v / 3.2 + sCurve * k); return [Pv[0] + r[0], Pv[1] + r[1]]; };+ // secondary motion+ const sway = o.sway || [0, 0];+ const info = {};+ G.save(); G.translate(x, y); G.scale(u * fx * sx, u * syy);+ const keepL = _L; _L = [LIGHT[0] * fx, LIGHT[1]];+ const hLean = lean + bend * .5 + (o.tilt || 0) * DEG - sCurve * .8 + ws * 2.5 * DEG * cp * (side ? 0 : 1) + (pose.headFwd || 0) * DEG, neckB = F(D.neckV, (o.neckX || 0));+ const headO = addV(addV(neckB, dirA(Math.PI + hLean + (o.tilt || 0) * DEG * .3), D.neckLen + D.chinY + .02), [bt * .07, abt * .05]);+ const hg = headGeom(D, { ...o, sway: [sway[0] - Math.sin(lean) * .15, sway[1]] }, t);+ const drawHead = () => inFrame([Math.cos(hLean), Math.sin(hLean)], [-Math.sin(hLean), Math.cos(hLean)], headO, () => { info.hf = drawHeadFront(D, hg, { ...o, expr, blink, mouth, eyeShake: expr.eye.shake }, t, lw); });+ const drawBack = () => inFrame([Math.cos(hLean), Math.sin(hLean)], [-Math.sin(hLean), Math.cos(hLean)], headO, () => drawHeadBack(D, hg, lw));+ // arms+ const shJ = s => F(D.shV, s * D.shX * lerp(1, .2, abt) * (side ? 1 : 1));+ const armGeo = s => {+ const A = (s < 0 ? pose.armL : pose.armR) || [4, 6, 'open'], lift = clamp((Math.abs(A[0]) - 40) / 100) * .1;+ const sh = addV(shJ(s), [side ? f * lift * .6 * Math.sign(A[0]) : s * lift * .35, -lift]);+ const a1 = (side ? A[0] * f : A[0] * s) * DEG, a2 = a1 + (side ? (A[1] || 0) * f : (A[1] || 0) * s) * DEG;+ const e = addV(sh, dirA(a1 + lean * .4), D.ua), w = addV(e, dirA(a2 + lean * .4), D.fa * (A[4] ?? 1));+ const ha = a2 + lean * .4 + (A[3] || 0) * DEG * (side ? f : s);+ return { sh, e, w, ha, hand: A[2] || 'open', a1, a2, A };+ };+ const drawArm = s => {+ const g = armGeo(s), wd = D.armW, dir = nrm2([g.w[0] - g.e[0], g.w[1] - g.e[1]]);+ // hand first (the cuff overlaps the wrist)+ const hy = [-Math.cos(g.ha), Math.sin(g.ha)];+ let th = s > 0 ? 1 : -1; if (side) th = hy[1] * f > 0 ? -f * (s > 0 ? 1 : 1) : f; if (!side && Math.abs(hy[1]) > .5) th = hy[1] > 0 ? -1 : 1;+ if (g.A[5]) th *= -1;+ const prop = o.prop && (o.prop.hand || 'R') === (s < 0 ? 'L' : 'R') ? o.prop : null;+ const handAt = g.hand === 'pocket' ? (ink([addV(g.w, [-.08, -.06]), addV(g.w, [.02, .1])], lw * .9, tone(D.line), TAPER.both), g.w) : drawHand(D, addV(g.w, dir, -.05), g.ha, th, prop ? (g.hand === 'open' ? 'hold' : g.hand) : g.hand, prop, lw, u);+ const m1 = [(g.sh[0] + g.e[0]) / 2, (g.sh[1] + g.e[1]) / 2], m2 = [(g.e[0] + g.w[0]) / 2, (g.e[1] + g.w[1]) / 2];+ const cl = D.clothes === 'hina' ? D.cardigan : D.blazer;+ // sleeve: tapers shoulder → elbow (pinched) → a looser forearm → gathered at the cuff+ const ud = nrm2([g.e[0] - g.sh[0], g.e[1] - g.sh[1]]), cuffLen = D.clothes === 'hina' ? .15 : .1, ce = addV(g.w, dir, -.02), cs = addV(ce, dir, -cuffLen);+ const f1 = [lerp(g.e[0], cs[0], .45), lerp(g.e[1], cs[1], .45)];+ const sleeve = tubePts([[...g.sh, wd[0]], [...m1, wd[1]], [...addV(g.e, ud, -.06), wd[2] * 1.03], [...g.e, wd[2]], [...addV(g.e, dir, .07), wd[2] * 1.04], [...f1, wd[3]], [...addV(cs, dir, .02), wd[4]]], 5);+ const cuff = tubePts([[...cs, wd[5]], [...ce, wd[5] * (D.clothes === 'hina' ? .97 : 1)]], 3, false);+ const cuffCol = D.clothes === 'hina' ? { b: tone(mixCol(cl.b, cl.s, .45)), s: tone(cl.s) } : { b: tone(cl.b), s: tone(cl.s) };+ const parts = [{ path: polyPath(ccw(sleeve)), b: tone(cl.b), s: tone(cl.s), h: tone(cl.h), d: .07, r: .015 }, { path: polyPath(ccw(cuff)), b: cuffCol.b, s: cuffCol.s, d: .05 }];+ drawGroup(parts, tone(D.line), lw);+ const n = [-dir[1], dir[0]], bendK = Math.abs(Math.sin((g.a2 - g.a1) / 2)), inner = Math.sign(Math.sin(g.a2 - g.a1)) || 1, soft = tone(D.lineSoft);+ // elbow: creases on the inner side (more as it bends), a point line on the outer side+ for (let k = 0; k < 2 + (bendK > .4); k++) { const o1 = addV(addV(g.e, n, -inner * wd[2] * (.5 - k * .12)), dir, -.03 + k * .05);+ ink([o1, addV(addV(o1, n, inner * wd[2] * (.35 + bendK * .2)), dir, .03 + bendK * .04)], lw * (1 - k * .2), soft, TAPER.both); }+ ink([addV(addV(g.e, n, inner * wd[2] * .5), ud, -.07), addV(addV(g.e, n, inner * wd[2] * .38), dir, .05)], lw * .7, soft, TAPER.both);+ // forearm drape folds and the cuff edge / ribbing+ ink([addV(addV(cs, n, wd[4] * .45), dir, -.16), addV(addV(cs, n, wd[4] * .05), dir, -.03)], lw * .7, soft, TAPER.both);+ if (D.clothes === 'hina') for (const k of [-.25, 0, .25]) ink([addV(addV(cs, n, k * wd[5]), dir, .025), addV(addV(ce, n, k * wd[5]), dir, -.02)], lw * .5, soft, TAPER.both);+ else { const sc = tubePts([[...addV(ce, dir, -.03), wd[5] * .72], [...addV(ce, dir, .025), wd[5] * .68]], 3, false); drawGroup([{ path: polyPath(ccw(sc)), b: tone(D.shirt.s), s: tone(mixCol(D.shirt.s, '#7a82a6', .3)), d: .03 }], tone(D.line), lw * .7); }+ info[s < 0 ? 'handL' : 'handR'] = handAt;+ };+ // legs+ const drawLeg = s => {+ const g = s < 0 ? LL : LR, P = F(0, 0), off = [P[0] - Pv[0], P[1] - Pv[1]];+ const h = addV(g.h, [Pv[0], Pv[1]]), k = addV(g.k, [Pv[0], Pv[1]]), an = addV(g.an, [Pv[0], Pv[1]]), wd = D.legW;+ const m1 = [(h[0] * .5 + k[0] * .5), (h[1] * .5 + k[1] * .5)], m2 = [(k[0] * .5 + an[0] * .5), (k[1] * .5 + an[1] * .5)];+ const top = addV(h, [0, -.25]);+ const c1 = [k[0] * .7 + an[0] * .3, k[1] * .7 + an[1] * .3], c2 = [k[0] * .3 + an[0] * .7, k[1] * .3 + an[1] * .7];+ const P5 = [[...top, wd[0]], [...h, wd[0]], [...m1, wd[1]], [...k, wd[2]], [...c1, wd[3]], [...c2, wd[4]], [...an, wd[5]]];+ const parts = [], dirS = nrm2([an[0] - k[0], an[1] - k[1]]);+ // shoe+ const sideShoe = side || Math.abs(Math.sin(g.a2)) > .5, sf = side ? f : (Math.sin(g.a2) >= 0 ? 1 : -1);+ const footA = side ? (g.a2 - (o.ground === false ? 0 : 0)) * .5 : 0;+ const sh = D.shoe, shoeP = sideShoe+ ? [[-.1, -.06], [.03, -.1], [.2, -.06], [.3, .01], [.3, .06], [-.11, .06]].map(([a, b]) => { const r = rot2(a * sf, b, footA); return [an[0] + r[0], an[1] + D.ankleH * .35 + r[1]]; })+ : [[-.11, -.05], [.11, -.05], [.14, .05], [.08, .1], [-.08, .1], [-.14, .05]].map(([a, b]) => [an[0] + a + s * .02, an[1] + D.ankleH * .2 + b]);+ if (D.clothes === 'hina') {+ parts.push({ path: polyPath(ccw(tubePts(P5, 6))), b: tone(D.skin.b), s: tone(D.skin.s), h: tone(D.skin.h), d: .06, r: .012 });+ const sock = tubePts([[...addV(k, dirS, .16), wd[3] * 1.05], [...c1, wd[3] * 1.06], [...c2, wd[4] * 1.06], [...an, wd[5] * 1.12]], 6);+ parts.push({ path: polyPath(ccw(sock)), b: tone(D.sock.b), s: tone(D.sock.s), d: .06 });+ } else {+ parts.push({ path: polyPath(ccw(tubePts(P5.map((p, i) => [p[0], p[1], p[2]]), 6))), b: tone(D.pants.b), s: tone(D.pants.s), h: tone(D.pants.h), d: .08, r: .015 });+ }+ parts.push({ path: smooth(shoeP, true, 5), b: tone(sh.b), s: tone(sh.s), h: tone(sh.h), d: .04, r: .015 });+ drawGroup(parts, tone(D.line), lw);+ if (D.clothes === 'hina') { ink([addV(k, dirS, .2), addV(addV(k, dirS, .2), [-dirS[1], dirS[0]], wd[3] * .5)], lw * .6, tone(D.lineSoft)); }+ else { ink([addV(k, [0, -.1]), addV(k, [s * .05, .08]), addV(k, [s * .02, .2])], lw * .7, tone(D.lineSoft), TAPER.both); G.fillStyle = D.shoeAcc; }+ info[s < 0 ? 'footL' : 'footR'] = an;+ };+ // torso+ const torsoPts = () => {+ const R = D.torso.map(([v, w]) => F(v, w * wf + bt * .03 * (v > 1 ? 1 : 0))), Lf = D.torso.map(([v, w]) => F(v, -w * wf + bt * .03 * (v > 1 ? 1 : 0)));+ return [...R, ...Lf.reverse()];+ };+ const drawNeck = () => {+ const sn = Math.sin(hg.psi), nb = F(D.neckV - .12, -sn * .04), top = addV(addV(headO, dirA(hLean), .16), [-sn * .07 * Math.cos(hLean), 0]);+ const neck = polyPath(ccw(tubePts([[...nb, D.neckW * 1.05], [...top, D.neckW]], 4, false)));+ drawGroup([{ path: neck, b: tone(D.skin.b), s: tone(D.skin.s), d: .05 }], tone(D.line), lw);+ // the jaw's cast shadow on the neck+ G.save(); G.clip(neck); inFrame([Math.cos(hLean), Math.sin(hLean)], [-Math.sin(hLean), Math.cos(hLean)], headO, () => { G.fillStyle = tone(D.skin.s); G.fill(shifted(hg.facePath, _L[0] * -.02, .085)); }); G.restore();+ };+ const drawTorso = () => {+ const tp = torsoPts(), torso = smooth(tp, true, 5), parts = [];+ const cx = v => F(v, bt * .22 * wf);+ if (D.clothes === 'hina') {+ // skirt (under the cardigan hem), pleated+ const sw = sway[0] * .5, legSpread = Math.max(.62, Math.abs(LL.k[0] - LR.k[0]) * .5 + .3);+ const hem = []; const n = 9;+ for (let i = 0; i <= n; i++) { const k2 = i / n, xx = lerp(-legSpread, legSpread, k2) * lerp(1, .8, abt); hem.push(addV(F(-.66, xx), [sw * (1 - Math.abs(k2 - .5)), (i % 2 ? .035 : 0)])); }+ const skirtP = [F(.66, -.33 * wf), F(.66, .33 * wf), ...hem.slice().reverse().map((p, i) => i === 0 ? p : p)];+ const skirt = polyPath(ccw([F(.66, -.34 * wf), F(.66, .34 * wf), ...hem.slice().reverse()]));+ drawGroup([{ path: skirt, b: tone(D.skirt.b), s: tone(D.skirt.s), h: tone(D.skirt.h), d: .09, r: .02,+ clip: () => { for (let i = 1; i < n; i += 2) { G.fillStyle = tone(D.skirt.s); G.globalAlpha = .55; G.beginPath(); const a = F(.66, lerp(-.3, .3, i / n) * wf), b = F(.66, lerp(-.3, .3, (i + 1) / n) * wf); G.moveTo(...a); G.lineTo(...b); G.lineTo(...hem[i + 1]); G.lineTo(...hem[i]); G.fill(); G.globalAlpha = 1; } } }], tone(D.line), lw);+ for (let i = 1; i < n; i++) { const a = F(.3, lerp(-.34, .34, i / n) * wf); ink([a, hem[i]], lw * .8, tone(D.line), TAPER.tail); }+ // cardigan body+ parts.push({ path: torso, b: tone(D.cardigan.b), s: tone(D.cardigan.s), h: tone(D.cardigan.h), d: .1, r: .02 });+ drawGroup(parts, tone(D.line), lw);+ // hem ribbing, button line, collar + ribbon+ const hemL = F(.24, -.41 * wf), hemR = F(.24, .41 * wf); ink([hemL, cx(.22), hemR], lw * .8, tone(D.lineSoft), TAPER.soft);+ ink([cx(1.15), cx(.7), cx(.2)], lw * .9, tone(D.line), TAPER.soft);+ for (const v of [1.0, .75, .5]) { const b = cx(v); G.fillStyle = tone('#c9a870'); G.beginPath(); G.arc(b[0] + .035, b[1], .025, 0, TAU); G.fill(); }+ const c0 = cx(1.66), col = [[...F(1.62, -.2 * wf)], [...F(1.72, -.02)], [...F(1.72, .02)], [...F(1.62, .2 * wf)], [...cx(1.3)]];+ const flap = sg => polyPath(ccw(crPts([[...F(1.74, sg * .02)], [...F(1.7, sg * .15 * wf)], [...F(1.6, sg * .25 * wf)], [...F(1.37, sg * .2 * wf + bt * .06), 0, true], [...F(1.44, sg * .05 * wf + bt * .12)], [...F(1.5, bt * .15 * wf), 0, true]], true, 5)));+ const collarL = flap(-1), collarR = flap(1);+ drawGroup([{ path: collarL, b: tone(D.collar.b), s: tone(D.collar.s), d: .03 }, { path: collarR, b: tone(D.collar.b), s: tone(D.collar.s), d: .03 }], tone(D.line), lw * .9, { thick: .3 });+ // ribbon bow+ const rb = cx(1.43), bow = [];+ const loop = sg => polyPath(ccw(crPts([[rb[0], rb[1]], [rb[0] + sg * .14, rb[1] - .08], [rb[0] + sg * .19, rb[1] + .01], [rb[0] + sg * .1, rb[1] + .05]], true, 6)));+ const tail = sg => polyPath(ccw(crPts([[rb[0] + sg * .01, rb[1]], [rb[0] + sg * .08 + sway[0] * .3, rb[1] + .22], [rb[0] + sg * .05 + sway[0] * .3, rb[1] + .27, 0, true], [rb[0] + sg * .01 + sway[0] * .3, rb[1] + .22]], true, 5)));+ drawGroup([tail(-1), tail(1), loop(-1), loop(1)].map(p => ({ path: p, b: tone(D.ribbon.b), s: tone(D.ribbon.s), d: .025 })), tone(D.line), lw * .85);+ const knot = new Path2D(); knot.ellipse(rb[0], rb[1], .035, .04, 0, 0, TAU); drawGroup([{ path: knot, b: tone(D.ribbon.b), s: tone(D.ribbon.s), d: .01 }], tone(D.line), lw * .8);+ } else {+ parts.push({ path: torso, b: tone(D.blazer.b), s: tone(D.blazer.s), h: tone(D.blazer.h), d: .12, r: .02 });+ drawGroup(parts, tone(D.line), lw);+ // open jacket: shirt panel, tie, lapels+ const sh = polyPath(ccw([F(1.84, -.13 * wf), F(1.86, .0), F(1.84, .13 * wf), cx(1.1), F(.95, .1 * wf + bt * .2), F(-.08, .12 * wf + bt * .2), F(-.08, -.1 * wf + bt * .2), F(.95, -.1 * wf + bt * .2)]));+ drawGroup([{ path: sh, b: tone(D.shirt.b), s: tone(D.shirt.s), d: .04 }], tone(D.line), lw * .9, { thick: .2 });+ const tk = cx(1.6), tie = polyPath(ccw([[tk[0] - .045, tk[1]], [tk[0] + .045, tk[1]], addV(cx(.7), [.06 + sway[0] * .2, 0]), addV(cx(.62), [sway[0] * .2, .05]), addV(cx(.7), [-.06 + sway[0] * .2, 0])]));+ drawGroup([{ path: tie, b: tone(D.tie.b), s: tone(D.tie.s), d: .03 }], tone(D.line), lw * .85);+ for (const sg of [-1, 1]) ink([F(1.72, sg * .15 * wf), F(1.45, sg * .24 * wf + bt * .1), F(1.05, sg * .12 * wf + bt * .2), F(-.1, sg * .13 * wf + bt * .2)], lw * 1.1, tone(D.line), TAPER.soft);+ ink([F(1.45, .24 * wf), F(1.35, .3 * wf)], lw * .8, tone(D.line), TAPER.both); ink([F(1.45, -.24 * wf), F(1.35, -.3 * wf)], lw * .8, tone(D.line), TAPER.both);+ const pk = F(.35, .3 * wf * (bt >= 0 ? 1 : -1)); ink([addV(pk, [-.1, 0]), addV(pk, [.1, 0])], lw * .8, tone(D.lineSoft), TAPER.soft);+ }+ };+ // ---- draw order: back hair, far limbs, legs, neck, torso, near arms, head+ const near = f < 0 ? 1 : -1, far = -near;+ const armsOver = o.armsOver;+ drawBack();+ if (side) drawArm(far);+ if (side) { drawLeg(far); drawLeg(near); } else { drawLeg(-1); drawLeg(1); }+ drawNeck();+ drawTorso();+ if (!armsOver) { if (side) drawArm(near); else { drawArm(-1); drawArm(1); } }+ drawHead();+ if (armsOver) { if (side) drawArm(near); else { drawArm(-1); drawArm(1); } }+ _L = keepL;+ G.restore();+ // screen-space info for the scene (props, cameras, effects)+ const toW = p => [x + p[0] * u * fx * sx, y + p[1] * u * syy];+ info.head = toW(headO); info.u = u; info.top = toW(addV(headO, [0, -.6]))[1];+ if (info.handL) info.handL = toW(info.handL); if (info.handR) info.handR = toW(info.handR);+ if (info.footL) info.footL = toW(info.footL); if (info.footR) info.footR = toW(info.footR);+ // sparkles/hearts around the head for 'love'+ const fxl = [...(expr.fx || []), ...(o.fx || [])];+ if (fxl.includes('sparkles')) sparkles(t, info.head[0], info.head[1] - u * .1, u * 1.1, 7, D.name);+ return info;+}+const hina = (x, y, u, o) => drawChar(DESIGNS.hina, x, y, u, o);+const ren = (x, y, u, o) => drawChar(DESIGNS.ren, x, y, u, o);+// bust(): draw just the head and shoulders large (close-ups). Same options; (x, y) = the head centre on screen.+function bust(D, x, y, u, o = {}) {+ const h = D.hipH + D.neckV + D.neckLen + D.chinY + .02;+ return drawChar(D, x, y + (h - 0) * u, u, { ...o, ground: false, dy: 0 });+}diff --git a/.claude/skills/anime-cel/template/src/config.js b/.claude/skills/anime-cel/template/src/config.jsnew file mode 100644index 0000000..18aed52--- /dev/null+++ b/.claude/skills/anime-cel/template/src/config.js@@ -0,0 +1,4 @@+// config.js: project settings.+// duration: the video's length in seconds. fps: 24 (anime timing: animate characters on twos with onTwos(t)).+// bpm/offset: the pulse that pulse()/beatN() follow (set to the song's tempo and first downbeat if there is music).+const PROJECT = { duration: 10, bpm: 120, offset: 0, fps: 24 };diff --git a/.claude/skills/anime-cel/template/src/kit.js b/.claude/skills/anime-cel/template/src/kit.jsnew file mode 100644index 0000000..8d6f3c2--- /dev/null+++ b/.claude/skills/anime-cel/template/src/kit.js@@ -0,0 +1,154 @@+// kit.js: the shared runtime for ReelMimic's Canvas-2D drawing engines (pixel art, paper cut-out, whiteboard, anime+// cel, crayon storybook). Each engine copies this file into its template unchanged and adds its own drawing library.+//+// The render contract is the same as painted-animation's, so the same render.mjs drives every engine:+// window.ready = true once fonts and assets are loaded+// window.renderAt(t, type, q) → data URL of the frame at time t+// window.renderSheet(times, cols, w, crop, at) → { url, ms[] } contact sheet (crop = [x,y,w,h] in screen px,+// at = [x,y,w,h] around a WORLD point, wherever the camera put it)+// Every frame is a pure function of t: frames render in parallel and out of order, so nothing may carry over from one+// frame to the next. Use hash()/rnd() for stable randomness, never Math.random().+//+// An engine plugs in through window.ENGINE = { setup(), begin(t), end(t) } (all optional):+// setup() → once, async (load images, build textures); begin(t) → before the shot draws (e.g. switch G to a low-res+// buffer); end(t) → after it (e.g. upscale, add grain). Shots draw with the 2D context G.++const W = 1920, H = 1080, TAU = Math.PI * 2;+const DUR = PROJECT.duration, BPM = PROJECT.bpm || 120, BEAT = 60 / BPM, OFF = PROJECT.offset || 0;+const FPS = PROJECT.fps || 24;++// ---------- math & timing (pure functions of t) ----------+const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));+const lerp = (a, b, x) => a + (b - a) * x;+const ease = x => { x = clamp(x); return x * x * (3 - 2 * x); };+const easeIn = x => Math.pow(clamp(x), 3);+const easeOut = x => 1 - Math.pow(1 - clamp(x), 3);+const backOut = x => { x = clamp(x); const s = 1.9; return 1 + (s + 1) * Math.pow(x - 1, 3) + s * Math.pow(x - 1, 2); };+const elasticOut = x => { x = clamp(x); return x === 0 || x === 1 ? x : Math.pow(2, -10 * x) * Math.sin((x * 10 - .75) * (TAU / 3)) + 1; };+const hash = i => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };+// seeded stream for one element: const r = rnd('tree' + i); r() → 0..1, the same every frame+function rnd(key) { let h = 2166136261; for (const c of String(key)) h = Math.imul(h ^ c.charCodeAt(0), 16777619); let s = h >>> 0 || 1; return () => (s = Math.imul(s ^ (s >>> 15), 2246822519) >>> 0, s = (s ^ (s >>> 13)) >>> 0, (s % 1000003) / 1000003); }+const seg = (t, a, b) => clamp((t - a) / (b - a));+const frac = x => x - Math.floor(x);+const bpOf = t => (t - OFF) / BEAT;+const beatN = t => Math.floor(bpOf(t));+const pulse = (t, k = 6) => Math.exp(-frac(bpOf(t)) * k);+const wob = (t, f = 1, ph = 0) => Math.sin((t * f + ph) * TAU);+// hold drawings like hand animation: onTwos(t) = 12 drawings/s, onStep(t, 8) = 8/s (stop-motion feel)+const onTwos = t => Math.floor(t * 12 + 1e-6) / 12;+const onStep = (t, n) => Math.floor(t * n + 1e-6) / n;+function kf(t, keys, e = ease) {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) if (t < keys[i][0]) {+ const [a, va] = keys[i - 1], [b, vb] = keys[i], k = e((t - a) / (b - a));+ return Array.isArray(va) ? va.map((v, j) => lerp(v, vb[j], k)) : lerp(va, vb, k);+ }+ return keys[keys.length - 1][1];+}+function mixCol(a, b, k) {+ const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16), c = i => Math.round(lerp((pa >> i) & 255, (pb >> i) & 255, clamp(k)));+ return '#' + ((1 << 24) + (c(16) << 16) + (c(8) << 8) + c(0)).toString(16).slice(1);+}+const shakeXY = (t, amt) => { const f = Math.floor(t * 24); return [(hash(f * 1.7) - .5) * 2 * amt, (hash(f * 2.3 + 9) - .5) * 2 * amt]; };+// motion principles+const spring = (t, t0, k = 6, w = 18) => t < t0 ? 0 : Math.exp(-k * (t - t0)) * Math.sin(w * (t - t0));+const arcPt = (p0, p1, h, k) => [lerp(p0[0], p1[0], k), lerp(p0[1], p1[1], k) - h * 4 * k * (1 - k)];+function jump(t, t0, t1, h = 3) { // → { dy (units, up is negative), sq (squash +, stretch -) }+ if (t < t0 - .12) return { dy: 0, sq: 0 };+ if (t < t0) return { dy: 0, sq: .18 * ease(seg(t, t0 - .12, t0)) };+ if (t < t1) { const k = (t - t0) / (t1 - t0); return { dy: -h * 4 * k * (1 - k), sq: -.16 * Math.abs(1 - 2 * k) }; }+ const a = t - t1; return { dy: 0, sq: .22 * Math.exp(-8 * a) * Math.cos(20 * a) };+}+function take(t, t0, amt = 1) { // surprise take peaking at t0+ if (t < t0 - .1) return { sq: 0, dy: 0 };+ if (t < t0) return { sq: .12 * amt * ease(seg(t, t0 - .1, t0)), dy: 0 };+ const a = t - t0; return { sq: -.26 * amt * Math.exp(-6 * a) * Math.cos(16 * a), dy: -1.2 * amt * Math.exp(-7 * a) * Math.max(0, Math.cos(9 * a)) };+}++// ---------- shots ----------+// shots([[t0, fn], ...]); fn(t, lt, dur) paints the WHOLE frame (background included) with G.+const SHOTS = [], LOOPS = {};+function shots(list) { SHOTS.push(...list); SHOTS.sort((a, b) => a[0] - b[0]); }+function drawWorld(t) {+ if (window.LOOP) return window.LOOP(t);+ if (!SHOTS.length) { G.fillStyle = '#EDE6D8'; G.fillRect(0, 0, W, H); return; }+ let i = 0; while (i + 1 < SHOTS.length && t >= SHOTS[i + 1][0]) i++;+ const t0 = SHOTS[i][0], end = i + 1 < SHOTS.length ? SHOTS[i + 1][0] : DUR;+ SHOTS[i][1](t, t - t0, end - t0);+ if (CAM) camEnd();+}++// ---------- camera (world → screen) ----------+let CAM = null, LAST_CAM = null;+function camBegin(cx = W / 2, cy = H / 2, zoom = 1, rot = 0) {+ G.save(); G.translate(W / 2, H / 2); G.rotate(rot); G.scale(zoom, zoom); G.translate(-cx, -cy);+ CAM = LAST_CAM = { cx, cy, zoom, rot };+}+function camEnd() { G.restore(); CAM = null; }+function toScreen(x, y, cam = CAM) {+ if (!cam) return [x, y];+ const dx = (x - cam.cx) * cam.zoom, dy = (y - cam.cy) * cam.zoom, c = Math.cos(cam.rot), s = Math.sin(cam.rot);+ return [W / 2 + dx * c - dy * s, H / 2 + dx * s + dy * c];+}++// ---------- canvases & frame ----------+// G: the context shots draw into (an engine may point it at a low-res buffer in begin()). OUT: the visible 1920×1080.+let G = null, OUT = null, OUTC = null, T = 0;+function makeCanvas(w = W, h = H) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }+async function renderFrame(t) {+ T = t; CAM = LAST_CAM = null;+ G = OUT; G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over';+ G.clearRect(0, 0, W, H);+ if (window.ENGINE && ENGINE.begin) ENGINE.begin(t);+ drawWorld(t);+ if (window.ENGINE && ENGINE.end) ENGINE.end(t);+ OUT.setTransform(1, 0, 0, 1, 0, 0); OUT.globalAlpha = 1; OUT.globalCompositeOperation = 'source-over';+ if (window.overlayHook) window.overlayHook(OUT, t); // crisp captions / karaoke above everything+}+window.renderAt = async (t, type = 'image/png', q = .92) => { await renderFrame(t); return OUTC.toDataURL(type, q); };+window.renderSheet = async (times, cols = 3, w = 640, crop = null, at = null) => {+ if (at) at = at.map((v) => typeof v === 'string' ? (0, eval)(v) : v);+ const [, , cw, ch] = at || crop || [0, 0, W, H], h = Math.round(w * ch / cw), rows = Math.ceil(times.length / cols), sc = makeCanvas(cols * w, rows * h);+ const c = sc.getContext('2d'), ms = [];+ for (let i = 0; i < times.length; i++) {+ const t0 = performance.now(); await renderFrame(times[i]); ms.push(Math.round(performance.now() - t0));+ const x = (i % cols) * w, y = Math.floor(i / cols) * h;+ const [cx, cy] = at ? toScreen(at[0], at[1], LAST_CAM).map((v, j) => v - (j ? ch : cw) / 2) : crop || [0, 0];+ c.imageSmoothingEnabled = !(window.ENGINE && ENGINE.crisp);+ c.drawImage(OUTC, cx, cy, cw, ch, x, y, w, h);+ c.fillStyle = 'rgba(0,0,0,.65)'; c.fillRect(x, y, 84, 24); c.fillStyle = '#fff'; c.font = '15px sans-serif'; c.fillText(times[i].toFixed(2) + 's', x + 6, y + 17);+ }+ return { url: sc.toDataURL('image/jpeg', .9), ms };+};+window.gpuInfo = () => 'canvas2d';++// ---------- captions (optional) ----------+// A simple, legible caption bar on the overlay: caption(c, text, { y, size, font, fg, bg }). Engines may style their own.+function caption(c, txt, o = {}) {+ const size = o.size || 54, y = o.y || H - 70, font = o.font || `700 ${size}px "Noto Sans TC", "Noto Sans", system-ui, sans-serif`;+ c.save(); c.font = font; c.textAlign = 'center'; c.textBaseline = 'middle';+ const w = c.measureText(txt).width + size * 1.1;+ c.fillStyle = o.bg || 'rgba(20,18,26,.72)'; const r = size * .5;+ c.beginPath(); c.roundRect(W / 2 - w / 2, y - size * .78, w, size * 1.56, r); c.fill();+ c.lineJoin = 'round'; c.lineWidth = size * .14; c.strokeStyle = 'rgba(0,0,0,.55)'; c.strokeText(txt, W / 2, y + 2);+ c.fillStyle = o.fg || '#FFF8EC'; c.fillText(txt, W / 2, y + 2); c.restore();+}++// ---------- boot ----------+async function boot() {+ OUTC = document.getElementById('out'); OUT = OUTC.getContext('2d', { willReadFrequently: false });+ const fonts = [...(window.EXTRA_FONTS || [])].map(([f, txt]) => document.fonts.load(f, txt));+ await Promise.all(fonts);+ if (window.ENGINE && ENGINE.setup) await ENGINE.setup();+ window.ready = true;+ if (!location.search.includes('render')) devUI();+}+function devUI() {+ const s = document.getElementById('scrub'), lab = document.getElementById('tt'); if (!s) return;+ s.max = window.LOOP ? window.LOOP.len : DUR; s.step = 1 / FPS;+ let busy = false, want = null;+ const go = async () => { if (busy) return; busy = true; while (want != null) { const t = want; want = null; const t0 = performance.now(); await renderFrame(t); lab.textContent = `${t.toFixed(2)}s · ${Math.round(performance.now() - t0)} ms/frame`; } busy = false; };+ s.addEventListener('input', () => { want = +s.value; go(); });+ want = +(new URLSearchParams(location.search).get('t') || 0); s.value = want; go();+}+window.addEventListener('load', () => { const q = new URLSearchParams(location.search).get('loop'); if (q && LOOPS[q]) window.LOOP = LOOPS[q]; boot(); });diff --git a/.claude/skills/anime-cel/template/src/scenes/demo.js b/.claude/skills/anime-cel/template/src/scenes/demo.jsnew file mode 100644index 0000000..3e593c7--- /dev/null+++ b/.claude/skills/anime-cel/template/src/scenes/demo.js@@ -0,0 +1,81 @@+// demo.js — "The Letter" (10 s). Hina dashes down a sakura street to hand Ren a letter; he's caught off guard.+// A 0.0–3.4 establishing: tilt down from the sky to the street, Hina runs in with the letter and skids to a stop+// B 3.4–6.4 [slash wipe] knees-up: she winds up, bows and thrusts the letter (smear, focus-line BG), Ren's take+// C 6.4–10 [impact frame] Ren close-up: dramatic zoom, surprised → flustered → a soft smile. [star iris out]+(() => {+ const U = 125;+ // ---------------------------------------------------------------- A: establishing+ const runX = tt => lerp(-160, 760, easeOut(seg(tt, .35, 2.5)) * .15 + seg(tt, .35, 2.5) * .85);+ function shotA(t, lt, dur) {+ setTOD('day');+ const k = ease(seg(lt, 0, 2.2)), cam = { x: 960 + 40 * k, y: lerp(120, 560, k), zoom: lerp(1, 1.1, ease(seg(lt, .6, 3.4))) };+ SET.street(cam, t, {});+ const ta = onTwos(lt), x = runX(ta), v = (runX(ta + .02) - runX(ta - .02)) / .04;+ const stopped = ta > 2.5, skid = seg(ta, 2.35, 2.75);+ const sway = [-v / U * .05 + follow(ta, tt => runX(tt) / U, 5, 12, 1.4), 0];+ const hinaO = { t: ta, turn: .75, sway, face: stopped ? 'embarrassed' : 'determined',+ prop: { hand: 'L', draw: PROPS.envelope, rot: -60 } };+ if (!stopped) Object.assign(hinaO, { run: x / (3.4 * U), runAmt: 1 - skid * .8, lean: -skid * 18 });+ else Object.assign(hinaO, { armL: [25, 95, 'hold'], armR: [-4, 16, 'relax'], lean: 6 * spring(ta, 2.5, 5, 13), look: [.2, .5], blink: autoBlink(ta, 2) });+ const r = ren(1330, 955, U, { t: ta, turn: -.55, face: ta > 2.7 ? 'surprised' : 'deadpan', look: ta > 2.4 ? [-.8, 0] : [0, 0], sway: [.02 * Math.sin(t), 0] });+ hina(x, 965, U, hinaO);+ camEnd();+ petals(t, { n: 34, size: 15, wind: 110, seed: 'A' });+ if (lt < .45) flash(1 - lt / .45, '#fff8f0');+ if (lt > dur - .35) slashWipe(seg(lt, dur - .35, dur) * .5);+ }+ // ---------------------------------------------------------------- B: the thrust+ function shotB(t, lt, dur) {+ setTOD('day');+ const ta = onTwos(lt), cam = { x: 1060 + 30 * ease(seg(lt, 0, 3)), y: 640, zoom: 1.3 };+ const hit = .92, after = ta >= hit;+ SET.street(cam, t, {});+ if (after) { // cut on action: the BG drops to a pink focus-line "moment"+ camEnd(); G.save(); G.setTransform(1, 0, 0, 1, 0, 0);+ const g = G.createRadialGradient(W * .42, H * .42, 50, W * .42, H * .42, 1200); g.addColorStop(0, '#fff3f6'); g.addColorStop(.5, '#ffc2d2'); g.addColorStop(1, '#e889a8');+ G.fillStyle = g; G.fillRect(0, 0, W, H); focusLines(t, W * .6, H * .4, { col: 'rgba(255,255,255,.95)', r: 380, n: 120, w: 14 }); G.restore();+ parallax(cam, 1);+ }+ // Hina: fidget → anticipation (lean back, arm cocked, squash) → thrust + bow → overshoot and settle+ const pull = ease(seg(ta, .45, .8)), go = easeOut(seg(ta, .8, hit)), set = spring(ta, hit, 6, 16);+ const lean = lerp(0, -12, pull) * (1 - go) + go * 24 + set * 8;+ const armL = [lerp(lerp(22, -18, pull), 76, go) + set * 6, lerp(lerp(100, 140, pull), 16, go), 'hold', 0, lerp(1, .8, go)]; // forearm foreshortens toward Ren/camera+ const armR = [lerp(8, -10, pull) * (1 - go) + go * -30, lerp(12, 30, pull) * (1 - go) + go * 10, after ? 'fist' : 'open'];+ const face = ta < .45 ? 'embarrassed' : 'xd', sq = pull * .06 * (1 - go) - go * .04 * (1 - seg(ta, hit, hit + .2));+ const sway = [-(go - pull) * .12 + set * .2, 0];+ const hi = hina(760, 1500, 180, { t: ta, turn: .55, face, sq, lean, armL, armR, sway, look: [.4, .3], prop: { hand: 'L', draw: PROPS.envelope, rot: -75 } });+ if (ta > .84 && ta < hit + .12 && hi.handL) smearLines(hi.handL[0] - 260, hi.handL[1] + 30, hi.handL[0] - 20, hi.handL[1], 90, 'rgba(255,255,255,.95)', 5, 'thr' + beatN(ta));+ const tk = take(ta, 1.25, 1);+ ren(1480, 1500 + tk.dy * 30, 180, { t: ta, turn: -.5, face: ta < 1.2 ? 'deadpan' : 'surprised', sq: tk.sq * .5, look: [-.6, .2], });+ camEnd();+ if (after) petals(t, { n: 22, size: 20, wind: 60, seed: 'B' });+ if (lt < .35) slashWipe(.5 + seg(lt, 0, .35) * .5);+ }+ // ---------------------------------------------------------------- C: Ren's reaction close-up+ function shotC(t, lt, dur) {+ setTOD('day');+ const ta = onTwos(lt), dz = dramaticZoom(lt, 0, .12, 16);+ const cam = { x: 1100 + dz.dx, y: 380 + dz.dy, zoom: 1.7 * dz.zoom };+ SET.street(cam, t, {});+ camEnd();+ blurBand(0, H, { blur: 5, n: 0 });+ G.save(); G.fillStyle = 'rgba(255,236,242,.25)'; G.fillRect(0, 0, W, H); G.restore();+ G.save(); G.translate(W / 2 + dz.dx, H / 2 + dz.dy); G.scale(dz.zoom, dz.zoom); G.translate(-W / 2, -H / 2);+ const f = faceAt(ta, [[0, 'surprised'], [1.25, 'embarrassed'], [2.05, 'smile']]);+ const tk = take(ta, .05, .8);+ bust(DESIGNS.ren, 1000, 470 + tk.dy * 20, 560, { t: ta, turn: -.22, face: f.face, sq: tk.sq * .4 + f.sq, blink: f.blink ?? autoBlink(ta, 4),+ look: f.face === 'smile' ? [-.35, .05] : f.face === 'embarrassed' ? [.5, .4] : [-.3, 0], sway: [.02 * Math.sin(t * 1.3), 0], blush: f.face === 'smile' ? .55 : undefined });+ if (f.face === 'smile') sparkles(t, 1000, 400, 560, 9, 'renC', .72);+ G.restore();+ petals(t, { n: 16, size: 34, wind: 80, seed: 'C', speed: 1.4 });+ impactFrame(lt < 3 / 24 ? 1 : 0, 'invert', { x: 1000, y: 430, t });+ if (lt > dur - .5) irisWipe(seg(lt, dur - .5, dur) * .5, 1000, 450, { shape: 'star', col: '#2a2440' });+ }+ shots([[0, shotA], [3.4, shotB], [6.4, shotC]]);+ window.overlayHook = (c, t) => {+ const line = (a, b, txt) => { if (t >= a && t < b) subtitle(c, txt, { alpha: clamp(Math.min((t - a) / .12, (b - t) / .12)) }); };+ line(4.35, 6.3, '請、請收下這個!');+ line(8.6, 9.7, '……謝謝。');+ };+ window.EXTRA_FONTS.push(['800 58px "M PLUS Rounded 1c"', '請、請收下這個!……謝謝。'], ['900 58px "Noto Sans TC"', '請、請收下這個!……謝謝。']);+})();diff --git a/.claude/skills/anime-cel/template/src/sheets.js b/.claude/skills/anime-cel/template/src/sheets.jsnew file mode 100644index 0000000..c2699e6--- /dev/null+++ b/.claude/skills/anime-cel/template/src/sheets.js@@ -0,0 +1,76 @@+// sheets.js — model sheets as LOOPS (render with --loop=<name>): faces_hina, faces_ren, turns, bodies, hands, fx.+// node render.mjs --loop=faces_hina --sheet=0 --cols=1 --w=1920 --out=out/check/faces_hina.jpg+(() => {+ const paper = () => { G.fillStyle = '#f4f1f8'; G.fillRect(0, 0, W, H); };+ const cellClip = (x, y, w, h, fn) => { G.save(); G.beginPath(); G.rect(x, y, w, h); G.clip(); G.fillStyle = '#e9e4f2'; G.fillRect(x + 4, y + 4, w - 8, h - 8); fn(); G.restore(); };+ const label = (txt, x, y) => { G.fillStyle = '#4a4560'; G.font = '600 22px system-ui, sans-serif'; G.textAlign = 'center'; G.fillText(txt, x, y); };+ for (const who of ['hina', 'ren']) {+ LOOPS['faces_' + who] = t => {+ paper(); const D = DESIGNS[who], cols = 6, cw = W / cols, ch = H / 4;+ EXPR_NAMES.forEach((name, i) => {+ const x = (i % cols) * cw, y = Math.floor(i / cols) * ch;+ cellClip(x, y, cw, ch, () => { bust(D, x + cw / 2, y + ch * .47, 150, { face: name, t: t + i * .37, blink: 1, turn: (i % 3 === 2) ? .35 : 0 }); label(name, x + 70, y + 30); });+ });+ };+ LOOPS['faces_' + who].len = 2;+ }+ LOOPS.turns = t => {+ paper(); const turns = [-1, -.5, 0, .5, 1];+ turns.forEach((tr, i) => { cellClip(i * W / 5, 0, W / 5, H / 2, () => bust(DESIGNS.hina, i * W / 5 + W / 10, H * .26, 200, { turn: tr, face: 'smile', blink: 1, t })); });+ turns.forEach((tr, i) => { cellClip(i * W / 5, H / 2, W / 5, H / 2, () => bust(DESIGNS.ren, i * W / 5 + W / 10, H * .76, 200, { turn: tr, face: 'neutral', blink: 1, t })); });+ };+ LOOPS.turns.len = 2;+ LOOPS.bodies = t => {+ paper(); const u = 150, gy = 1010;+ hina(170, gy, u, { turn: 0, face: 'happy', t, armL: [20, 10, 'open'], armR: [150, 20, 'spread'] });+ hina(470, gy, u, { turn: .5, face: 'smile', t, armR: [40, 70, 'open'], prop: { hand: 'R', draw: PROPS.envelope, rot: 0 } });+ hina(770, gy, u, { turn: 1, face: 'neutral', t, walk: frac(t) });+ ren(1130, gy, u * .95, { turn: 0, face: 'neutral', t, armL: [6, 4, 'fist'], armR: [30, 120, 'peace'] });+ ren(1450, gy, u * .95, { turn: -.5, face: 'smug', t, armL: [70, 40, 'point'] });+ ren(1760, gy, u * .95, { turn: -1, face: 'determined', t, run: frac(t * 1.5) });+ };+ LOOPS.bodies.len = 2;+ LOOPS.hands = t => {+ paper(); const shapes = ['open', 'relax', 'fist', 'point', 'peace', 'spread', 'hold', 'grip'];+ shapes.forEach((s, i) => { G.save(); const x = 120 + i * 232; G.translate(x, 250); G.scale(420, 420); _L = LIGHT; drawHand(DESIGNS.hina, [0, 0], 0, 1, s, s === 'hold' ? { draw: PROPS.envelope } : s === 'grip' ? { draw: PROPS.can } : null, 4 / 420, 420); G.restore(); label(s, x, 520); });+ shapes.forEach((s, i) => { G.save(); const x = 120 + i * 232; G.translate(x, 640); G.scale(420, 420); _L = LIGHT; drawHand(DESIGNS.ren, [0, 0], -.3, -1, s, null, 4 / 420, 420); G.restore(); });+ };+ LOOPS.hands.len = 1;+})();+(() => {+ for (const who of ['hina', 'ren']) {+ LOOPS['close_' + who] = t => {+ G.fillStyle = '#eef0f6'; G.fillRect(0, 0, W, H);+ const D = DESIGNS[who], f = window.CLOSE_FACE || 'neutral';+ [0, .5, 1].forEach((tr, i) => { G.save(); G.beginPath(); G.rect(i * 640, 0, 640, H); G.clip(); bust(D, i * 640 + 320, 430, 520, { turn: tr, face: f, blink: 1, t }); G.restore(); });+ };+ LOOPS['close_' + who].len = 2;+ }+})();+(() => {+ // sets × time of day, and the effects library+ const panel = (i, fn) => { G.save(); const x = (i % 2) * W / 2, y = Math.floor(i / 2) * H / 2; G.translate(x, y); G.scale(.5, .5); G.beginPath(); G.rect(0, 0, W, H); G.clip(); fn(); if (CAM) camEnd(); G.restore(); };+ LOOPS.sets = t => {+ panel(0, () => { setTOD('morning'); SET.street({ x: 960, y: 540, zoom: 1 }, t); camEnd(); });+ panel(1, () => { setTOD('day'); SET.classroom({ x: 960, y: 540, zoom: 1 }, t); hina(900, 1000, 110, { t, turn: .3, face: 'smile', armR: [30, 110, 'hold'], prop: { hand: 'R', draw: PROPS.book, rot: 90 } }); camEnd(); });+ panel(2, () => { setTOD('evening'); SET.rooftop({ x: 960, y: 540, zoom: 1 }, t, { sun: [1500, 640] }); ren(900, 1000, 110, { t, turn: .5, face: 'smile' }); camEnd(); });+ panel(3, () => { setTOD('night'); SET.street({ x: 960, y: 540, zoom: 1 }, t); hina(700, 980, 110, { t, turn: .6, face: 'surprised' }); camEnd(); });+ setTOD('day');+ };+ LOOPS.sets.len = 2;+ LOOPS.fx = t => {+ panel(0, () => { G.fillStyle = '#20264a'; G.fillRect(0, 0, W, H); speedLines(t, 0, { n: 70 }); hina(960, 1010, 130, { t, turn: 1, run: frac(t * 1.6), face: 'determined' }); });+ panel(1, () => { setTOD('day'); SET.street({ x: 960, y: 540, zoom: 1 }, t); hina(960, 960, 130, { t, turn: 0, face: 'love' }); camEnd(); blurBand(300, 480, { t }); });+ panel(2, () => { G.fillStyle = '#ffe7ef'; G.fillRect(0, 0, W, H); ren(960, 1300, 200, { t, face: 'rage' }); impactFrame(1, 'red', { x: 960, y: 400, t }); });+ panel(3, () => { G.fillStyle = '#fbe9f0'; G.fillRect(0, 0, W, H); petals(t, { n: 60, size: 20 }); sparkles(t, 600, 500, 300, 8, 'a'); smear((x, y) => { heart(x, y, 70, '#ff5a7a', '#4c2830'); }, [300, 800], [1400, 400], 4); smearLines(300, 800, 1300, 440, 80, 'rgba(255,90,122,.8)'); focusLines(t, 1400, 400, { r: 200, n: 60, col: 'rgba(60,40,90,.6)' }); });+ };+ LOOPS.fx.len = 2;+})();++LOOPS.motion = t => {+ G.fillStyle = '#f4f1f8'; G.fillRect(0, 0, W, H); G.fillStyle = '#e2dcea'; G.fillRect(0, 1000, W, 80);+ hina(150, 1000, 130, { t, turn: 0, face: 'smile' }); hina(420, 1000, 130, { t, turn: .55, face: 'smile' });+ ren(700, 1000, 125, { t, turn: 0, face: 'neutral' }); ren(980, 1000, 125, { t, turn: -.55, face: 'neutral' });+ hina(1260, 1000, 130, { t, turn: .8, walk: frac(t), face: 'happy' }); ren(1620, 1000, 125, { t, turn: .8, run: frac(t * 1.4), face: 'determined' });+};+LOOPS.motion.len = 1;diff --git a/.claude/skills/anime-cel/template/studio.html b/.claude/skills/anime-cel/template/studio.htmlnew file mode 100644index 0000000..84ab29b--- /dev/null+++ b/.claude/skills/anime-cel/template/studio.html@@ -0,0 +1,29 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>anime-cel studio</title>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@800&family=Noto+Sans+TC:wght@900&display=block">+<style>+ html, body { margin: 0; background: #1b1820; color: #eee; font: 13px system-ui, sans-serif; }+ main { padding: 12px; display: grid; gap: 8px; }+ #out { width: min(100%, 1280px); aspect-ratio: 16 / 9; height: auto; background: #fff; }+ .bar { display: flex; gap: 10px; align-items: center; max-width: 1280px; }+ #scrub { flex: 1; } #tt { font-variant-numeric: tabular-nums; min-width: 190px; }+</style>+</head>+<body>+<main>+ <canvas id="out" width="1920" height="1080"></canvas>+ <div class="bar"><input id="scrub" type="range" min="0" max="10" step="0.0417" value="0"><span id="tt">loading…</span></div>+</main>+<!-- engine: config, shared kit, this engine's drawing library -->+<script src="src/config.js"></script>+<script src="src/kit.js"></script>+<script src="src/anime.js"></script>+<script src="src/cast.js"></script>+<script src="src/sheets.js"></script>+<!-- your video: one script per scene file, in order -->+<script src="src/scenes/demo.js"></script>+</body>+</html>diff --git a/.claude/skills/crayon-storybook/GUIDE.md b/.claude/skills/crayon-storybook/GUIDE.mdnew file mode 100644index 0000000..ad58477--- /dev/null+++ b/.claude/skills/crayon-storybook/GUIDE.md@@ -0,0 +1,268 @@+# Crayon storybook — the drawing and animation guide++Read all of it before drawing. It covers the look, the full API with examples, the cast, how to review your frames, and+the known pitfalls. Model sheets: `docs/cast.jpg` (views + 18 moods of both characters), `docs/looks.jpg` (brushes,+fills, props, emotes), `docs/demo-sheet.jpg` (the demo). The animation principles, the "reads" timing method and the+review discipline are the same as painted-animation's `template/ANIMATION_GUIDE.md` — read its *Timing* and *Animation+principles* sections too; they apply unchanged.++---++## 1. The look++A warm, cosy children's picture book. Think a skilful illustrator using a child's materials:++- **Paper**: cream drawing paper (`PAL.paper`) with soft uneven warmth and fibres. It is under everything; leaving+ paper showing is part of the look.+- **Crayon fills**: every coloured shape is *coloured in* — a pale flat base of its colour, then crayon strokes in the+ full colour going back and forth in one direction (`scribble`), or parallel hatching (`hatch`), or two directions+ (`cross`), or soft powder (`smudge`). Gaps between strokes show the pale base: that's what makes it crayon.+- **Paper tooth**: after the frame is drawn, the paper's tooth is laid over it — pigment skips in the paper's pits,+ so every stroke breaks up the same way. You don't do anything for it; `tooth(k)` scales it (default 1).+- **Coloured-pencil outlines** (`cpen`), dark and fairly thick so they survive a phone screen. Default outline colour+ is a deep tint of the fill colour; characters use the cocoa `PAL.ink`.+- **Gentle palette**: butter, sky, rose, sage, lilac, peach, coral, cocoa (+ `Dk`/`Lt` variants). No pure black or+ white. Pick 4–6 colours per video and keep them.+- **Boil**: linework and fills are re-drawn 8 times a second (`BOIL`, `PROJECT.boil`), like frames re-drawn by hand;+ the tooth shifts with each drawing. Still things hold perfectly between drawings (see `boilSeed`).+- **Staging**: soft warm vignette (always on, `vignette(k)`), optional picture-book page border (`bookPage(k)`),+ gentle camera moves (slow drifts and pushes — never whip pans in this style), page turns between scenes.+- **Naive but skilful**: simple round shapes, chunky proportions, big heads, dot eyes — but clean staging, clear+ silhouettes and real animation (anticipation, follow-through, acting).++Don't: plain p5 shapes (`rect`, `ellipse`, `fill()`), gradients, drop-shadowed vector UI, 3D, photographic textures,+neon colours, black outlines on everything at full strength, busy tiny details.++## 2. Files++| file | what |+|---|---|+| `src/config.js` | `PROJECT = { duration, bpm, offset, fps: 24, boil?, toothBoil? }` |+| `src/core.js` | runtime (from painted-animation): palette `PAL`, timing/motion helpers, camera, `paint`, `inkLine`, geometry, `glow`, `iris`, `flash`, lettering, render hooks |+| `src/crayon.js` | the look: brushes, fills, paper/tooth/grain, page finish, page turn, scenery, props, emotes, captions |+| `src/cast.js` | Lulu and Kuri, faces, moods (`EMO`, `feel`, `emotions`), `walkCycle`, `pose` |+| `src/timeline.js` | `shots()`, `LOOPS`, page-turn orchestration, `crayonWipe` |+| `src/sheets.js` | model sheets as loops: `?loop=cast`, `?loop=looks` |+| `src/scenes/demo.js` | the 10 s example ("The red apple") — one idea, not a template |+| `src/karaoke.js` | optional KTV lyric bar (from painted-animation); not loaded by default |+| `patch_brush.mjs` | writes the crayon-patched p5.brush build on `npm install` |++## 3. Colouring in: the fills++```js+colorIn(pts, o) // the workhorse+```+| option | meaning |+|---|---|+| `col` | the colour. Strokes use it; the base is a paler version |+| `fill` | `'scribble'` (default) · `'hatch'` · `'cross'` · `'smudge'` · `'flat'` (base only) · `'none'` (outline only) |+| `pale` | how much paler the base is (0 = same, default .6); `base` sets it explicitly; `baseOp` its opacity |+| `tone` | stroke colour if not `col` |+| `ang`, `gap`, `w`, `br` | stroke direction (radians), spacing px (default 13), weight, brush (`crayon`) |+| `over`, `loose`, `run` | scribble: overshoot px at the turns, wobble 0..1, rows per stroke before the crayon lifts |+| `line`, `lw`, `lbr`, `curv` | outline colour (`null` = none), weight (≈ .6–2), brush (`cpen`), smoothing 0..1 |+| `shade` | `{ pts, col, ang, gap }`: an extra scribble pass over a shadow side |++Lower-level: `scribbleFill(pts, col, o)`, `hatchFill(pts, col, { ang, gap, cross, grad })`, `crossHatch`,+`smudge(pts, col, { op, tex })`, `dab(x, y, r, col)` (a little crayon spiral: cheeks, dots, berries).++```js+colorIn(ellPts(600, 500, 160, 120, 30), { col: PAL.rose }); // a scribbled pink blob+colorIn(rrPts(900, 400, 300, 200, 30), { col: PAL.sky, fill: 'cross', gap: 16, ang: .7 }); // cross-hatched box+smudge(ellPts(960, 300, 500, 180, 30), PAL.lilac, { op: 90 }); // a soft pastel cloud of colour+```++Choosing: characters and props → `scribble` (lively); architecture, clothes with pattern → `hatch`; shadows and+night → `cross`; skies, distant hills, glows, cheeks → `smudge`; tiny parts (hands, buttons, eyes) → `flat`.+Big areas cost stroke area: use a bigger `gap` (30–45) and `w` 1.4–1.8 for backgrounds — the pale base carries them.++### Lines and brushes++`crayonLine(pts, sw, col)`, `pencilLine`, `pastelLine`, `sketchLine`, or `inkLine(pts, sw, col, brush, curv)`.++| brush | use |+|---|---|+| `crayon` | wide waxy crayon: fills, rays, grass, big strokes |+| `crayonFine` | smaller crayon: stems, hatching, details (used automatically by `crayonLine` when sw < .7) |+| `cpen` | coloured pencil, thin and grainy: every outline, faces |+| `pastel` | soft powdery stroke: glows, sky streaks, magic trails |+| `chalk` | dry broken stroke |+| `graphite` | light sketch lines, construction lines, rain |++`sw` is a multiplier (≈ .5–2). Built-ins also work: `'2B'`, `'HB'`, `'charcoal'`, `'marker'`, `'spray'`.++### Shapes (core)++`ellPts(cx, cy, rx, ry, n, jitter, rot)`, `rectPts(x, y, w, h, j)`, `rrPts(x, y, w, h, r)`, `starPts(cx, cy, r, inner, n, rot)`,+`heartPts(cx, cy, r)`, `through(P)` (smooth curve), `ribbon(P, w0, w1)` (tapered band as one outline: branches, tails,+scarves, rivers).++## 4. Scenery, props, emotes++- `sky(top, bottom, { y0, y1, x0, x1, strokes })` — soft pastel sky with long crayon streaks. Oversize it if the camera moves.+- `sun(x, y, r, t, { face, rays, glow })`, `cloud(x, y, s, { key, col, line })`+- `hill(cx, cy, rx, ry, col, { gap, ang, line })` + `hillY(x, cx, cy, rx, ry)` (for standing on it),+ `ground(y, col, { x0, x1, depth, gap })`, `tufts(x0, x1, yOfX, n, col, t, key)`+- `tree(x, y, s, { col })`, `flower(x, y, s, col, t)`, `house(x, y, s, { wall, roof })`, `paperWash(t, col)`+- props (centre + size, so a hand hook can call them at (0, 0)): `apple(x, y, r)`, `leafProp(x, y, r, rot, col)`,+ `starProp(x, y, r, col, rot)`, `heartProp(x, y, r, col)`, `balloon(x, y, r, len, col, t)` (x, y = the hand)+- `emote(kind, x, y, s, k, age)`: `'!' '?' heart hearts sweat spark zzz bulb music anger cloud dots swirl` — drawn marks,+ never typed. The cast pops them automatically from moods.+- `glow(x, y, r, col, a)`: additive light (sun halo, lamp, magic). On cream paper it's a gentle bloom.++Every background element: call `boilSeed('unique key')` first (the scenery helpers do it for you, keyed by position).++## 5. Staging and transitions++- **Shots**: `shots([[0, shotA], [4.6, shotB, { turn: 1.0 }], …])`. `fn(t, lt, dur)` draws the whole frame.+- **Page turn**: `{ turn: seconds, turnDir: 1 | -1 }` on the arriving shot. The old page (finished with its own+ vignette/border) curls away from the bottom-right corner, showing its paper back with a faint mirrored ghost of the+ picture and a soft shadow on the new page. The previous shot keeps running with `lt > dur` during the turn.+- **Crayon wipe**: `crayonWipe(p, [c1, c2, c3])` — big crayon bands scribble across (p 0 → .5) and away (.5 → 1); cut+ under full cover. End of A: `if (lt > dur - .35) crayonWipe((lt - (dur - .35)) / .7)`; start of B: `if (lt < .35) crayonWipe(.5 + lt / .7)`.+- **Iris**: `iris(cx, cy, r, PAL.paper)` / `irisShape(heartPts(...), col)` — use paper or cocoa, not black.+- **Fade from / to blank paper**: `flash(k, PAL.paper)` (the storybook way to open and close).+- **Page framing**: `bookPage(k, { m, r, line })` — cream border + hand-drawn frame line; animate `k` in/out.+- `vignette(k)` (default .3), `tooth(k)` (default 1) — set per frame in the shot.+- **Camera**: `camBegin(cx, cy, zoom, rot)` … `camEnd()`. Storybook moves: slow pan down from sky, gentle push-in+ (1.0 → 1.1 over a shot), drift of 20–50 px. Add `shakeXY(t, amt)` only for landings/bumps, small.++## 6. Captions (storybook text)++```js+captions([+ [0.5, 2.5, '露露和小栗出門散步。', { pos: 'top' }],+ [5.9, 7.3, '跳高一點⋯⋯摘到了!'], // bottom by default+]);+```+Options: `pos: 'top' | 'bottom'`, `y`, `size` (default 74 px ≈ 15 px on a 390 px-wide phone; don't go below 60),+`rate` (characters written per second, default 16), `box: false` (no paper label), `col`. The text is hand-lettered+(LXGW WenKai TC → Zen Maru Gothic → Noto Serif TC), written on character by character with a slightly uneven baseline,+sits on a torn cream label, and is nibbled by the paper tooth. `captions()` registers `window.overlayHook` and the+font preload; call it once per video. Keep one short sentence per caption, ≥ 1.4 s on screen. Put captions where the+action isn't (`pos: 'top'` over sky in wide shots).++## 7. The cast++Two original characters, drawn by one call each, from the ground point between the feet:++```js+lulu(x, y, u, o) // small girl: butter raincoat, sky-blue boots, cocoa bob with a star clip. ≈ 11u tall, 5u wide+kuri(x, y, u, o) // round hedgehog: cocoa spikes, cream face, button nose, pink ears. ≈ 5u tall, 6u wide+```+Both return `{ head, top, handL, handR, feet }` in world coordinates (for props flying to/from hands, irises, emotes).++| size | Lulu u | Kuri u |+|---|---|---|+| wide | 16–26 | 14–22 |+| medium | 30–45 | 26–38 |+| close-up | 60–90 | 50–80 |++### Options (both)++| group | options |+|---|---|+| pose | `dx`, `dy` (u, − = up), `sq` (squash, − stretches), `rot`, `flip`, `sx`, `sy` |+| arms | `aL`, `aR`: 0 = straight out sideways, + up, − down (rest ≈ −1.2; side view: 0 = forward). `bL`, `bR` (Lulu): elbow bend, + folds the forearm up/in (2 = hand at chest, 2.3 = at chin), − = back (hands on hips ≈ `a −.6, b −1.8`) |+| legs | `walk` (phase, 1 = a full stride; null = standing) — use `walkCycle(ph, side)` |+| hair | `hair` (Lulu: hair and hem lag in u, + flicks up; Kuri: spikes ruffle). Drive with the jump / `spring()` |+| view | `'front' | 'q' | 'side' | 'back'` (all face right; `flip: true` faces left) |+| face | `eyes`, `mouth`, `brows`, `lookX`, `lookY`, `squint`, `blush`, `seed` (blink timing), `noBlink` |+| extras | `emote`, `emoteK`, `emoteAge`; `holdL/holdR(u, sw)` draw a prop UPRIGHT at the hand; `armL/armR(u, sw)` draw in ARM space (+x along the forearm); `propFront` draws props over the hand; `draw(u, sw)` body-local extra |+| colour | Lulu: `coat`, `boots`, `hairCol`; Kuri: `spikes`, `faceCol` |+| boil | `boilKey` — set it if characters appear/disappear mid-shot |++Eyes: `normal wide happy closed squeeze sad cry teary angry heart sleepy shine look scared x` (or a pair). Mouths:+`smile grin laugh o O frown wobble flat wail cat tongue pout` (or `null`). Brows: `up worried angry flat`. Eyes blink+by themselves every 3–4.5 s (per `seed`; give each character a different seed).++Limbs are always attached: arms are one tapered sleeve (shoulder → elbow → mitten) rooted inside the body outline;+legs root under the coat hem; Kuri's paws and feet root inside his body. In front view Lulu's arms draw over everything+(so raised arms show beside her head); in 3/4 and side views the far arm is behind the body and shaded.++**Proportions matter for reach**: Lulu's arms are short (chibi). A straight-up arm (`a 1.5`) ends at ear height; to+reach something overhead use `a ≈ 1.1, b ≈ .35` (up and out) and place the target at the returned `handR`.++### Moods++```js+lulu(x, y, 36, feel('happy', t)); // one mood, alive (idle motion on the beat)+lulu(x, y, 36, emotions(lt, [[0, 'curious'], [1.4, 'surprised'], [1.9, 'happy']])); // acted changes+lulu(x, y, 36, pose(emotions(lt, keys), jump(lt, 2, 2.6, 4), { view: 'q', aR: 1.1 })); // mood + action + override+```+18 moods: `neutral happy laugh excited love shy proud curious thinking idea surprised scared sad cry angry sleepy+determined relieved`. Each sets eyes/mouth/brows/blush/emote, a take size and an idle body motion locked to `bpm`.+`emotions()` squints and squashes before each change, swaps the face under the squint, fires a take, settles with+overshoot and pops the new emote. Add a mood by adding an `EMO` entry in `cast.js`.++`pose(...ps)` merges pose objects: later ones win, but `dy`, `sq`, `rot`, `dx` ADD (so a mood's bounce and a jump+combine). `walkCycle(ph, side = true, amt)` gives legs, arm swing, bob, sway. `stroll(t, t0, t1, x0, x1, u, stride)`+(core) gives an eased walk `{ x, walk, view, flip }`: `pose(mood, walkCycle(w.walk || 0), { view: 'side' })`.++### Holding and passing props++```js+// holding an apple up in the right hand (upright, the hand grips over it)+lulu(x, y, 40, { ...feel('proud', t), aR: 1.1, bR: .35, holdR: u => apple(0, -u * .6, u) });+// passing it: draw the receiver and the giver, then the prop in flight between their returned hands+const K = kuri(...), L = lulu(...);+const p = arcPt(L.handR, K.handR, 70, ease(seg(lt, tGive, tGot))); apple(p[0], p[1], 40);+```++### New characters++Add a function to `cast.js` (or `src/cast_<name>.js`) following Lulu/Kuri: `boilSeed` per part (`rs(part)`), one+`push/translate/rotate/scale` for pose + squash + flip, parts drawn with `colorIn`, faces through `eyeMark` /+`mouthMark` / `browMarks` / `cheeks`, arms through `arm2()` (attached limbs, hooks, returned hand), return anchors.+Outline weight `sw = clamp(u / 20, .5, 2.6)`; scribble `gap ≈ u * .3`. Keep 3 views minimum (front, q, side).+Characters must be original — never an existing IP. A user's own character (design sheet provided) can be built the+same way.++## 8. Rules for scenes++1. One IIFE per scene file; scenes call library + cast only. No character body parts drawn in scenes.+2. Pure function of `t`: no `Math.random()`, no counters, no state. `hash(i)`, `rnd(key)`.+3. `boilSeed('key')` before every separate element you draw yourself (props, branches, effects).+4. Something happens in every shot; one read at a time; anticipation → action → follow-through; hold after meanings.+5. A transition at every seam, including into the first shot (`flash` from paper) and out of the last.+6. Main subjects big and central; nothing story-critical under the caption label.++## 9. Review loop (do it for real)++```bash+node render.mjs --sheet=0.3,1.2,2.2,3.0,3.6,4.3 --cols=4 --w=480 --out=out/check/a.jpg # key frames+node render.mjs --strip=5.9:6.9 --cols=5 --w=384 --out=out/check/jump.jpg # every frame of an action+node render.mjs --sheet=6.45,8.1 --cols=2 --crop=380,240,1000,760 --w=700 --out=out/check/faces.jpg # faces/hands+node render.mjs --strip=2.0:2.5 --crop-at=L_X,L_Y,500,500 --out=out/check/feet.jpg # follow a world point+node render.mjs --loop=cast --sheet=1 --cols=1 --w=1920 --out=out/check/cast.jpg # model sheet+```+(`--cols=1` when you render a single frame with `--crop`.) Open each with Read and check:++- **Look**: unmistakably crayon on paper? Colours bright and gentle (no mustard/olive muddiness — see pitfalls)? Is+ the scribble direction consistent within an object? Paper visible somewhere?+- **Read**: is each shot's event clear from its sheet? Characters big enough at 480 px wide? Faces readable?+- **Acting**: anticipation before jumps/throws, squash on landing, hair/hem follow-through, moods changing through+ `emotions()` not snapping, both arms not doing the same thing.+- **Contacts**: feet on the ground line (use `hillY` on hills), props touching hands (crop them), apples on stems.+- **Boil**: in a strip, frames inside one boil drawing (3 frames at 24 fps / 8 boil) match except what moves.+- **Captions**: legible, not covering the action, on screen long enough.+- **Transitions**: first and last 0.5 s of every shot; page-turn frames look like paper.++## 10. Pitfalls++- **Muddy yellows** mean the stock p5.brush got loaded: `studio.html` must load `p5.brush.crayon.js` (run+ `node patch_brush.mjs`). Stock p5.brush darkens saturated stroke pigment (≈ pigment × .85 − .075): butter → mustard.+- **Speed**: ≈ 150–250 ms/frame wide shots, ~350 ms busy medium shots, ~0.7–1 s page-turn frames (two pages), single+ worker on an RTX-class GPU. Costs: colour changes (each `colorIn` ≈ 3 passes), stroke area (big shapes at small gaps),+ watercolour `smudge` on huge areas. With 4 workers expect ≈ 0.45 s/frame throughput.+- **Jittering still things**: a moving element before them shifted the random stream → `boilSeed(key)` per element.+- **Hidden raised arms**: only in custom characters that draw arms before the head; draw raised arms last.+- **Spiky elbows**: build bent limbs with `limbPts()` (clamped miter), not `ribbon()` (Catmull-Rom overshoots on+ sharp bends).+- **Giant emotes / props**: sizes are in px, not in u. An emote's `s` ≈ u.+- **Huge strokes under zoom**: shapes much bigger than the canvas can lose their outline under camera zoom ≳ 2; split+ long edges into `inkLine`s, keep zoom ≤ 1.6 for wide scenery.+- **Globals**: never name a function `line`, `text`, `color`, `scale`, `shape`, `fill` … (p5 owns them).+- `x ** 2` after a unary minus (`-x ** 2`) is a syntax error that stops the whole page — write `x * x`.+- **Navigation timeouts** in render.mjs = the Google Fonts request was slow; render.mjs retries 3×; re-run if needed.+- The overlay (captions) is skipped for `LOOPS` (model sheets).diff --git a/.claude/skills/crayon-storybook/SKILL.md b/.claude/skills/crayon-storybook/SKILL.mdnew file mode 100644index 0000000..58b3631--- /dev/null+++ b/.claude/skills/crayon-storybook/SKILL.md@@ -0,0 +1,80 @@+---+name: crayon-storybook+description: Make warm children's picture-book animations (MP4) drawn in crayon, coloured pencil and pastel on cream drawing paper — waxy crayon scribble fills broken by paper tooth, coloured-pencil outlines, slow 8 fps line boil, page-turn transitions, picture-book page framing and hand-lettered CJK storybook captions. p5.js + p5.brush rendered frame by frame in headless Chrome, encoded with ffmpeg. Use when a reference video or brief calls for a crayon / colored-pencil / pastel / kids' drawing / picture-book / bedtime-story / 繪本 / 蠟筆 / 色鉛筆 / 童書 look, or when the video-clone router picks the crayon-storybook style.+---++# Crayon storybook++A drawing engine for ReelMimic. Every frame is a pure function of time `t`: `studio.html` loads p5.js + p5.brush, the+crayon look library, the cast and your scene files; each shot draws the whole 1920×1080 frame; `render.mjs` renders+contact sheets, strips and crops for review, or all frames in parallel, and ffmpeg encodes the MP4.++**Provenance.** The runtime (`template/src/core.js`, `timeline.js`, `render.mjs`, `studio.html`, the render contract and+helpers: `paint`, `inkLine`, camera, `shots`, `glow`, `jump`/`take`/`spring`, `boilSeed`…) derives from the+**painted-animation** skill (ClaudeAnimationBase, MIT © John Heibel / tuzhechen2005 — see `template/LICENSE`). The+look (`crayon.js`), the characters (`cast.js`), the page turn, the page finish and the captions are this engine's own.++## Workflow++1. **Scaffold** — `bash .claude/skills/crayon-storybook/scripts/new_project.sh <project-dir>` (add `--keep-demo` to keep+ the example). It copies the template, runs `npm install` (which also writes the patched p5.brush build, see+ gotchas) and checks node / ffmpeg / Chrome. Then **read [GUIDE.md](GUIDE.md) in full** and look at+ `docs/demo-sheet.jpg` and `docs/cast.jpg` with Read.+2. **Storyboard** in writing: shots, reads (what the viewer must understand, when), transitions, captions.+3. **Build** — `src/config.js` (`duration`, `bpm`, `fps: 24`); one IIFE file per shot/scene in `src/scenes/`, ending with+ `shots([...])`; add its `<script>` to `studio.html`. Captions: `captions([[t0, t1, '文字', { pos }]])` once.+4. **Look, fix, look again** (from the project dir):+ ```bash+ node render.mjs --sheet=0.5,1.5,2.5,3.5 --cols=4 --w=480 --out=out/check/a.jpg+ node render.mjs --strip=2.0:2.6 --cols=6 --w=320 --out=out/check/strip.jpg+ node render.mjs --sheet=2.3 --cols=1 --crop=600,200,900,700 --w=900 --out=out/check/face.jpg+ ```+ Open every image with Read. At least a sheet per shot, a strip per key action and per transition, a crop per face.+5. **Render** — `node render.mjs --frames --workers=4 && node render.mjs --encode --out=out/video.mp4 [--audio=…]`.++## API in one screen++| area | calls |+|---|---|+| fills | `colorIn(pts, { col, fill: 'scribble'|'hatch'|'cross'|'smudge'|'flat', ang, gap, line, lw, shade })`, `scribbleFill`, `hatchFill`, `crossHatch`, `smudge`, `dab` |+| lines | `crayonLine`, `pencilLine`, `pastelLine`, `sketchLine`, `inkLine(pts, sw, col, brush)` — brushes `crayon`, `crayonFine`, `cpen`, `pastel`, `chalk`, `graphite` |+| shapes | `ellPts`, `rectPts`, `rrPts`, `starPts`, `heartPts`, `through`, `ribbon` (core) |+| scenery | `sky`, `sun`, `cloud`, `hill`/`hillY`, `ground`, `tufts`, `tree`, `flower`, `house`, `paperWash` |+| props | `apple`, `leafProp`, `starProp`, `heartProp`, `balloon`; emotes `emote(kind, x, y, s, k, age)` |+| cast | `lulu(x, y, u, o)`, `kuri(x, y, u, o)` → `{ head, top, handL, handR, feet }`; `feel`, `emotions`, `walkCycle`, `pose` |+| motion | `seg`, `kf`, `ease*`, `backOut`, `spring`, `ring`, `jump`, `take`, `stroll`, `arcPt`, `onTwos`, `pulse`, `shakeXY` |+| camera | `camBegin(cx, cy, zoom, rot)` … `camEnd()`, `toScreen` |+| staging | `shots([[t0, fn], [t1, fn, { turn: 1.0 }]])` (page turn), `bookPage(k)`, `vignette(k)`, `tooth(k)`, `crayonWipe(p)`, `iris`, `flash`, `glow` |+| text | `captions(list)` (storybook captions via `window.overlayHook`), `letter()` for words inside the picture |++## Rules that matter most++1. **Crayon medium only.** Colour shapes in with `colorIn` (pale base + crayon scribble/hatch + coloured-pencil outline);+ lines with the crayon/pencil brushes. No plain p5 `rect/ellipse/fill`, no gradients, no 3D. Turns go through the+ drawn key views (`front`, `q`, `side`, `back`).+2. **Pure functions of `t`.** No `Math.random()`, no state between frames. `hash()` / `rnd(key)` for stable randomness;+ `jit()` only for boil. Call `boilSeed(key)` before each separate background element/prop.+3. **Characters come from `cast.js` only.** Scenes pass poses (`aR`, `bR`, `view`, `walk`, `dy`, `sq`, `hair`,+ `holdR`…) — they never draw a character's parts themselves. New characters go in `cast.js` (or one file each).+4. **Big and legible.** Lulu u ≈ 30–45 in medium shots (≈ 11u tall), Kuri u ≈ 26–36. Captions ≥ 64 px. Keep the+ caption band (bottom ~200 px, or `pos: 'top'`) free of story-critical action.+5. **Alive and acted.** Moods change through `emotions()` (anticipation squint → take → settle); actions have+ anticipation → action → follow-through (`jump`, `spring`, `hair`); something happens in every shot.+6. **A transition at every seam**: page turn (`{ turn }`), crayon wipe, iris, fade from/to paper.++## Engine gotchas++- **Patched p5.brush.** `studio.html` loads `node_modules/p5.brush/dist/p5.brush.crayon.js`, written by+ `patch_brush.mjs` on `npm install`. Stock p5.brush darkens pigment where overlapping stamps saturate (right for ink,+ wrong for wax): butter-yellow turned mustard. If that file is missing, run `node patch_brush.mjs`.+- **Cost = number of colour changes + stroke area.** Each `colorIn` is ~3 brush passes; p5.brush composites a mask per+ colour change. Keep big background shapes sparse (`hill`/`ground` already use wide gaps), don't scribble far+ off-screen. Typical: 150–250 ms/frame for a wide shot, ~350 ms for a busy medium shot with two characters and the+ page border, ~0.7–1 s during a page turn (two pages are drawn).+- **Page turn:** the previous shot keeps being called with `lt > dur` for `turn` seconds — let its motion settle.+- **Don't name globals after p5's** (`line`, `text`, `color`, `scale`, `shape`…): the page never gets ready.+- A `NaN` in a point list throws `Failed to construct 'OffscreenCanvas'`. `**` after a unary minus is a syntax error.+- Strokes far from the origin under zoom ≳ 2 collapse (p5.brush); `paint/inkLine/colorIn` draw around each shape's+ centre, which avoids it for normal sizes.+- Google Fonts load over the network at page load; if a render times out on navigation, just re-run it.+- `src/karaoke.js` (from painted-animation) still works for lyric videos; add its `<script>` if needed.diff --git a/.claude/skills/crayon-storybook/docs/cast.jpg b/.claude/skills/crayon-storybook/docs/cast.jpgnew file mode 100644index 0000000..ef2ccc6Binary files /dev/null and b/.claude/skills/crayon-storybook/docs/cast.jpg differdiff --git a/.claude/skills/crayon-storybook/docs/demo-sheet.jpg b/.claude/skills/crayon-storybook/docs/demo-sheet.jpgnew file mode 100644index 0000000..1ea358eBinary files /dev/null and b/.claude/skills/crayon-storybook/docs/demo-sheet.jpg differdiff --git a/.claude/skills/crayon-storybook/docs/looks.jpg b/.claude/skills/crayon-storybook/docs/looks.jpgnew file mode 100644index 0000000..63aa65eBinary files /dev/null and b/.claude/skills/crayon-storybook/docs/looks.jpg differdiff --git a/.claude/skills/crayon-storybook/scripts/new_project.sh b/.claude/skills/crayon-storybook/scripts/new_project.shnew file mode 100644index 0000000..358fa4f--- /dev/null+++ b/.claude/skills/crayon-storybook/scripts/new_project.sh@@ -0,0 +1,33 @@+#!/usr/bin/env bash+# new_project.sh <target-dir> [--keep-demo]+# Scaffolds a crayon-storybook project from the skill's template, installs deps (npm install also writes the patched+# p5.brush build, see template/patch_brush.mjs) and checks the toolchain.+set -euo pipefail+SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"+TARGET="${1:?usage: new_project.sh <target-dir> [--keep-demo]}"+KEEP_DEMO="${2:-}"++if [ -e "$TARGET/studio.html" ]; then echo "error: $TARGET already has a studio.html; not overwriting" >&2; exit 1; fi+mkdir -p "$TARGET"+if command -v rsync >/dev/null; then rsync -a --exclude node_modules --exclude out "$SKILL_DIR/template/" "$TARGET/"+else (cd "$SKILL_DIR/template" && for f in * .gitignore; do case "$f" in node_modules|out) ;; *) cp -R "$f" "$TARGET/";; esac; done); fi # Git Bash on Windows has no rsync+mkdir -p "$TARGET/assets" "$TARGET/out/check"++# The demo is an example, not a template: unless asked, unhook it so the new video starts clean.+if [ "$KEEP_DEMO" != "--keep-demo" ]; then+ sed -i.bak 's|<script src="src/scenes/demo.js"></script>|<!-- <script src="src/scenes/demo.js"></script> (example only) -->|' "$TARGET/studio.html" && rm -f "$TARGET/studio.html.bak"+fi++cd "$TARGET"+echo "== installing p5, p5.brush, puppeteer-core (+ patched p5.brush build)"+npm install --silent+[ -f node_modules/p5.brush/dist/p5.brush.crayon.js ] || node patch_brush.mjs++echo "== toolchain"+command -v node >/dev/null && echo "node $(node -v)" || echo "MISSING: node"+if command -v ffmpeg >/dev/null; then echo "ffmpeg ok"; elif [ -n "${FFMPEG_DIR:-}" ] && [ -x "$FFMPEG_DIR/ffmpeg" -o -x "$FFMPEG_DIR/ffmpeg.exe" ]; then echo "ffmpeg in FFMPEG_DIR (add it to PATH before --encode)"; else echo "MISSING: ffmpeg"; fi+for c in "${CHROME_PATH:-}" "/c/Program Files/Google/Chrome/Application/chrome.exe" "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" /usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do+ [ -n "$c" ] && [ -x "$c" ] && { echo "chrome $c"; FOUND=1; break; }+done+[ "${FOUND:-}" = 1 ] || echo "MISSING: Chrome (install it, or pass --chrome=<path> to render.mjs)"+echo "== ready: $TARGET (read GUIDE.md in the skill folder before drawing)"diff --git a/.claude/skills/crayon-storybook/template/.gitignore b/.claude/skills/crayon-storybook/template/.gitignorenew file mode 100644index 0000000..f4bc71e--- /dev/null+++ b/.claude/skills/crayon-storybook/template/.gitignore@@ -0,0 +1,2 @@+node_modules+out/diff --git a/.claude/skills/crayon-storybook/template/LICENSE b/.claude/skills/crayon-storybook/template/LICENSEnew file mode 100644index 0000000..be8ec42--- /dev/null+++ b/.claude/skills/crayon-storybook/template/LICENSE@@ -0,0 +1,49 @@+crayon-storybook's runtime (src/core.js, src/timeline.js, render.mjs, studio.html) is derived from the+painted-animation skill (ClaudeAnimationBase). Its licence is reproduced below.++MIT License++Copyright (c) 2026 tuzhechen2005+Portions (template/) Copyright (c) 2026 John Heibel, see template/LICENSE++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++-----++MIT License++Copyright (c) 2026 John Heibel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/.claude/skills/crayon-storybook/template/package-lock.json b/.claude/skills/crayon-storybook/template/package-lock.jsonnew file mode 100644index 0000000..bb950ee--- /dev/null+++ b/.claude/skills/crayon-storybook/template/package-lock.json@@ -0,0 +1,550 @@+{+ "name": "claude-animation-base",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "claude-animation-base",+ "version": "1.0.0",+ "license": "MIT",+ "dependencies": {+ "p5": "^2.3.3",+ "p5.brush": "^2.2.3",+ "puppeteer-core": "^25.11.0"+ }+ },+ "node_modules/@babel/runtime": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@davepagurek/bezier-path": {+ "version": "0.0.7",+ "resolved": "https://registry.npmjs.org/@davepagurek/bezier-path/-/bezier-path-0.0.7.tgz",+ "integrity": "sha512-CVlnCOrV1iy4Z12T756i9l4G6kF7r8uhlnb+xqDemAMmWQB+8Q0b+8VEqIiUfywgZDSiDr18Rm7pZlnA69rE8Q==",+ "license": "MIT"+ },+ "node_modules/@japont/unicode-range": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@japont/unicode-range/-/unicode-range-1.0.0.tgz",+ "integrity": "sha512-BckHvA2XdjRBVAWe2uceNuRf78lBeI28kyWEbfr/Q2pE17POkwuZ6WWY/UMv8FL9iBxhW4xfDoNLM9UVZaTeUQ==",+ "license": "MIT"+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.3.tgz",+ "integrity": "sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.4",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/acorn": {+ "version": "8.18.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",+ "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-walk": {+ "version": "8.3.5",+ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz",+ "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==",+ "license": "MIT",+ "dependencies": {+ "acorn": "^8.11.0"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.4.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",+ "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^3.24.1"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/chromium-bidi/node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/colorjs.io": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.6.1.tgz",+ "integrity": "sha512-8lyR2wHzuIykCpqHKgluGsqQi5iDm3/a2IgP2GBZrasn2sBRkE4NOGsglZxWLs/jZQoNkmA/KM/8NV16rLUdBg==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/color"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1687809",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",+ "integrity": "sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/escodegen": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz",+ "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "esprima": "^4.0.1",+ "estraverse": "^5.2.0",+ "esutils": "^2.0.2"+ },+ "bin": {+ "escodegen": "bin/escodegen.js",+ "esgenerate": "bin/esgenerate.js"+ },+ "engines": {+ "node": ">=6.0"+ },+ "optionalDependencies": {+ "source-map": "~0.6.1"+ }+ },+ "node_modules/esprima": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",+ "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",+ "license": "BSD-2-Clause",+ "bin": {+ "esparse": "bin/esparse.js",+ "esvalidate": "bin/esvalidate.js"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/esutils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/gifenc": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/gifenc/-/gifenc-1.0.3.tgz",+ "integrity": "sha512-xdr6AdrfGBcfzncONUOlXMBuc5wJDtOueE3c5rdG0oNgtINLD+f2iFZltrBRZYzACRbKr+mSVU/x98zv2u3jmw==",+ "license": "MIT"+ },+ "node_modules/i18next": {+ "version": "19.9.2",+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-19.9.2.tgz",+ "integrity": "sha512-0i6cuo6ER6usEOtKajUUDj92zlG+KArFia0857xxiEHAQcUwh/RtOQocui1LPJwunSYT574Pk64aNva1kwtxZg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.12.0"+ }+ },+ "node_modules/i18next-browser-languagedetector": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-4.3.1.tgz",+ "integrity": "sha512-KIToAzf8zwWvacgnRwJp63ase26o24AuNUlfNVJ5YZAFmdGhsJpmFClxXPuk9rv1FMI4lnc8zLSqgZPEZMrW4g==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.5.5"+ }+ },+ "node_modules/libtess": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/libtess/-/libtess-1.2.2.tgz",+ "integrity": "sha512-Nps8HPeVVcsmJxUvFLKVJcCgcz+1ajPTXDVAVPs6+giOQP4AHV31uZFFkh+CKow/bkB7GbZWKmwmit7myaqDSw==",+ "license": "SGI-B-2.0"+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.5",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.5.tgz",+ "integrity": "sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/omggif": {+ "version": "1.0.10",+ "resolved": "https://registry.npmjs.org/omggif/-/omggif-1.0.10.tgz",+ "integrity": "sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==",+ "license": "MIT"+ },+ "node_modules/p5": {+ "version": "2.3.4",+ "resolved": "https://registry.npmjs.org/p5/-/p5-2.3.4.tgz",+ "integrity": "sha512-bU5oNunn4L51hFu3+b6+zAQj+sPIlVyY0JmUCjABVytYwjNwf06EKFiLQgU70z5HPW58qTHRf5G8vM8gNtfbng==",+ "license": "LGPL-2.1",+ "dependencies": {+ "@davepagurek/bezier-path": "^0.0.7",+ "@japont/unicode-range": "^1.0.0",+ "acorn": "^8.15.0",+ "acorn-walk": "^8.3.4",+ "colorjs.io": "^0.6.0",+ "escodegen": "^2.1.0",+ "gifenc": "^1.0.3",+ "i18next": "^19.0.2",+ "i18next-browser-languagedetector": "^4.0.1",+ "libtess": "^1.2.2",+ "omggif": "^1.0.10",+ "pako": "^2.1.0",+ "zod": "^4.2.1"+ }+ },+ "node_modules/p5.brush": {+ "version": "2.2.3",+ "resolved": "https://registry.npmjs.org/p5.brush/-/p5.brush-2.2.3.tgz",+ "integrity": "sha512-Jxl7Rl01StakZN7OnaY+HYLXvemeIiCnDzVz6qnvsABF8GunCBcQON7xUKZUjV1E/Ab7VIFSMOspmVzLO/ljTw==",+ "license": "MIT",+ "dependencies": {+ "simplex-noise": "^4.0.3"+ },+ "peerDependencies": {+ "p5": "^2.2"+ }+ },+ "node_modules/pako": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",+ "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/puzrin"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodeca"+ }+ ],+ "license": "(MIT AND Zlib)"+ },+ "node_modules/puppeteer-core": {+ "version": "25.12.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.12.0.tgz",+ "integrity": "sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.3",+ "chromium-bidi": "17.0.2",+ "devtools-protocol": "0.0.1687809",+ "typed-query-selector": "^2.12.2",+ "webdriver-bidi-protocol": "0.4.3",+ "ws": "^8.21.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/simplex-noise": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/simplex-noise/-/simplex-noise-4.0.3.tgz",+ "integrity": "sha512-qSE2I4AngLQG7BXqoZj51jokT4WUXe8mOBrvfOXpci8+6Yu44+/dD5zqDpOx3Ux792eamTd2lLcI8jqFntk/lg==",+ "license": "MIT"+ },+ "node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "license": "BSD-3-Clause",+ "optional": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.3",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz",+ "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==",+ "license": "MIT"+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",+ "integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",+ "license": "Apache-2.0"+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.22.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.2.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",+ "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/zod": {+ "version": "4.6.5",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/.claude/skills/crayon-storybook/template/package.json b/.claude/skills/crayon-storybook/template/package.jsonnew file mode 100644index 0000000..03279f9--- /dev/null+++ b/.claude/skills/crayon-storybook/template/package.json@@ -0,0 +1,17 @@+{+ "name": "crayon-storybook",+ "version": "1.0.0",+ "private": true,+ "license": "MIT",+ "description": "Crayon storybook: a p5 + p5.brush drawing engine for picture-book crayon animation (runtime derived from painted-animation / ClaudeAnimationBase, MIT)",+ "scripts": {+ "sheet": "node render.mjs --sheet=0,1,2,3,4,5 --out=out/sheet.jpg",+ "video": "node render.mjs --clip --out=out/video.mp4",+ "postinstall": "node patch_brush.mjs"+ },+ "dependencies": {+ "p5": "^2.3.3",+ "p5.brush": "^2.2.3",+ "puppeteer-core": "^25.11.0"+ }+}diff --git a/.claude/skills/crayon-storybook/template/patch_brush.mjs b/.claude/skills/crayon-storybook/template/patch_brush.mjsnew file mode 100644index 0000000..ecd80cc--- /dev/null+++ b/.claude/skills/crayon-storybook/template/patch_brush.mjs@@ -0,0 +1,11 @@+// patch_brush.mjs (runs on `npm install`): writes node_modules/p5.brush/dist/p5.brush.crayon.js, a copy of p5.brush+// with its stroke "darkening" turned off. p5.brush darkens a stroke's pigment wherever overlapping stamps push the mask+// past 0.7 — right for ink and graphite, wrong for wax crayon, which stays bright: butter-yellow scribbles came out+// mustard. The patch only raises that threshold; everything else in p5.brush is unchanged.+import { readFileSync, writeFileSync, existsSync } from 'node:fs';+const src = 'node_modules/p5.brush/dist/p5.brush.js', dst = 'node_modules/p5.brush/dist/p5.brush.crayon.js';+if (!existsSync(src)) { console.error('patch_brush: ' + src + ' not found (run npm install)'); process.exit(0); }+const s = readFileSync(src, 'utf8'), out = s.replace(/DARKEN_THRESHOLD\s*=\s*0\.7/g, 'DARKEN_THRESHOLD=9.0');+if (out === s) console.warn('patch_brush: DARKEN_THRESHOLD not found — p5.brush changed; crayon colours may darken');+writeFileSync(dst, out);+console.log('patch_brush: wrote ' + dst);diff --git a/.claude/skills/crayon-storybook/template/render.mjs b/.claude/skills/crayon-storybook/template/render.mjsnew file mode 100644index 0000000..7f91853--- /dev/null+++ b/.claude/skills/crayon-storybook/template/render.mjs@@ -0,0 +1,165 @@+// render.mjs: renders studio.html in headless Chrome. Length and fps come from the page (PROJECT in src/config.js).+//+// Look at it (open the images with your image viewer / Read tool):+// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)+// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point+// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera+// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs+// Make the video:+// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --encode --out=out/video.mp4 out/frames → MP4+// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or+// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)+// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,+// --chrome=<path to Chrome/Chromium>.+import puppeteer from 'puppeteer-core';+import { spawn } from 'node:child_process';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { homedir } from 'node:os';++const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));+const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+ ...playwrightChromes()];+// Chromium builds Playwright downloaded (~/.cache/ms-playwright/chromium-NNNN), newest first+function playwrightChromes() {+ const dir = `${homedir()}/.cache/ms-playwright`;+ if (!existsSync(dir)) return [];+ return readdirSync(dir).filter(n => /^chromium-\d+$/.test(n)).sort((a, b) => b.split('-')[1] - a.split('-')[1])+ .map(n => `${dir}/${n}/chrome-linux64/chrome`);+}+const CHROME = CHROMES.find(p => p && existsSync(p));+if (!CHROME) { console.error('Chrome not found: pass --chrome=<path> or set CHROME_PATH'); process.exit(1); }+const fps = +(args.fps || 24), FRAMES_DIR = 'out/frames';+const run = (cmd, a) => new Promise((ok, bad) => { const p = spawn(cmd, a, { stdio: 'inherit' }); p.on('close', c => c ? bad(new Error(cmd + ' exited ' + c)) : ok()); });+const times = s => String(s).split(',').map(Number);+const span = s => String(s).split(':').map(Number);+// comma-separated fields, keeping commas inside parentheses ('PLK.MX(1.38),PLK.WL,500,300'); numbers stay numbers+const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of String(s)) { if (ch === ',' && !d) { out.push(cur); cur = ''; continue; } d += ch === '(' ? 1 : ch === ')' ? -1 : 0; cur += ch; } out.push(cur); return out.map(v => isNaN(+v) ? v : +v); };++// JPEG frames decode as full-range (yuvj420p); without this the MP4 is flagged full-range and some players/platforms+// show it washed out or with crushed shadows. Convert to standard (tv) range and say so.+const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];++if (args.encode) {+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,+ ...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);+ console.log('wrote ' + out);+ process.exit(0);+}++// --soft-gl: no GPU on this machine; render WebGL in software (SwiftShader), which Chrome only allows when asked.+// --gpu-angle=vulkan|gl-egl: headless Linux on an NVIDIA GPU (e.g. a cloud or cluster node); plain --use-gl=angle gets+// no WebGL context there. Check which GPU Chrome actually lands on with gpu_probe.mjs.+const ANGLE = { vulkan: ['--use-angle=vulkan', '--enable-features=Vulkan'], 'gl-egl': ['--use-angle=gl-egl'] };+if (args['gpu-angle'] && !ANGLE[args['gpu-angle']]) { console.error(`--gpu-angle must be one of ${Object.keys(ANGLE)}`); process.exit(1); }+const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ : args['gpu-angle'] ? ANGLE[args['gpu-angle']]+ : process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];+// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.+const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+const browser = await puppeteer.launch({+ executablePath: CHROME, headless: true, protocolTimeout: 0,+ args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']+});+async function openPage(tag = '') {+ const page = await browser.newPage();+ page.on('console', m => { if (['error', 'warn'].includes(m.type())) console.log(`[page${tag}]`, m.text()); });+ page.on('pageerror', e => console.log(`[page error${tag}]`, e.message));+ // Web fonts come over the network: give the page time, and retry a slow load instead of dying mid-render.+ for (let k = 1; ; k++) {+ try { await page.goto(pathToFileURL(resolve('studio.html')).href + '?render', { waitUntil: 'networkidle0', timeout: 90000 }); break; }+ catch (e) { if (k >= 3) throw e; console.log(`[page${tag}] slow load (${e.message}); retrying`); }+ }+ await page.waitForFunction('window.ready === true', { timeout: 60000 });+ if (args.loop) {+ const ok = await page.evaluate(name => { if (!LOOPS[name]) return false; window.LOOP = LOOPS[name]; return true; }, args.loop);+ if (!ok) { console.error(`no loop named "${args.loop}"`); process.exit(1); }+ }+ return page;+}+const frameOf = async (page, t, type, q) => {+ const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);+ return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');+};+// the length of whatever is being rendered: a loop's .len, or the video's duration+const lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);++if (args.sheet || args.strip) {+ const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });+ let ts;+ if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ else ts = times(args.sheet);+ const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;+ const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);+ writeFileSync(out, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));+ console.log(`${out} (${ts.length} frames) ms/frame: ${ms.join(' ')}`);+} else if (args.stills) {+ const page = await openPage(), out = args.out || 'out/stills'; mkdirSync(out, { recursive: true });+ console.log('GPU:', await page.evaluate(() => window.gpuInfo()));+ for (const s of times(args.stills)) {+ const t0 = Date.now(), buf = await frameOf(page, s, 'image/png');+ const f = `${out}/t${s.toFixed(2).replace('.', '_')}.png`; writeFileSync(f, buf);+ console.log(`${f} ${Date.now() - t0} ms`);+ }+} else if (args.png) {+ // PNG sequence (for GIFs): a loop's full cycle (frame n equals frame 0, so it isn't rendered), or --range=a:b.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], n = Math.round((b - a) * fps);+ const out = args.out || `out/${args.loop ? 'loop_' + args.loop : 'png'}`, workers = +(args.workers || 3); mkdirSync(out, { recursive: true });+ let next = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < n) { const i = next++; writeFileSync(`${out}/f${String(i).padStart(4, '0')}.png`, await frameOf(page, a + i / fps, 'image/png')); }+ }));+ console.log(`${n} frames → ${out} (${((Date.now() - start) / n).toFixed(0)} ms/frame)`);+} else if (args.frames) {+ // Parallel and resumable: each worker pulls the next missing frame; files are written atomically.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);+ mkdirSync(FRAMES_DIR, { recursive: true });+ const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);+ const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }+ console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ let next = 0, done = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < todo.length) {+ const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;+ const buf = await frameOf(page, i / fps, 'image/jpeg', .94);+ writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ if (++done % 24 === 0 || done === todo.length) {+ const el = (Date.now() - start) / 1000;+ console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);+ }+ }+ }));+} else if (args.clip) {+ const page = await openPage(), len = await lengthOf(page);+ const [a, b] = args.range ? span(args.range) : typeof args.clip === 'string' ? span(args.clip) : [0, len];+ const audio = args.audio || await page.evaluate(() => PROJECT.audio || '');+ const out = args.out || 'out/clip.mp4'; mkdirSync(dirname(out), { recursive: true });+ const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',+ ...(audio ? ['-ss', String(a), '-t', String(b - a), '-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', ...TV_RANGE, '-movflags', '+faststart', out],+ { stdio: ['pipe', 'inherit', 'inherit'] });+ const n = Math.round((b - a) * fps), start = Date.now();+ for (let i = 0; i < n; i++) {+ const buf = await frameOf(page, a + i / fps, 'image/jpeg', .93);+ if (!ff.stdin.write(buf)) await new Promise(r => ff.stdin.once('drain', r));+ if (i % 24 === 0 || i === n - 1) console.log(`frame ${i + 1}/${n} ${((Date.now() - start) / (i + 1)).toFixed(0)} ms/frame`);+ }+ ff.stdin.end(); await new Promise(r => ff.on('close', r));+ console.log(`wrote ${out}`);+} else {+ console.log('nothing to do: see the usage notes at the top of render.mjs');+}+await browser.close();diff --git a/.claude/skills/crayon-storybook/template/src/cast.js b/.claude/skills/crayon-storybook/template/src/cast.jsnew file mode 100644index 0000000..8749e44--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/cast.js@@ -0,0 +1,425 @@+// cast.js: the picture-book characters. Coloured-pencil outlines, crayon-scribble fills, boiling linework.+//+// lulu(x, y, u, o) a small girl in a butter-yellow raincoat and sky-blue boots, with a cocoa bob and a star clip.+// About 11u tall and 5u wide. (x, y) = the ground point between her feet.+// kuri(x, y, u, o) Lulu's companion, a round hedgehog: a cocoa spiky ball with a cream face and a button nose.+// About 5u tall and 6u wide. (x, y) = the ground point between his feet.+// Size guide at 1920×1080: wide shot u ≈ 14–20 (Lulu), medium 30–45, close-up 60–90. Kuri reads best at u ≥ 12.+//+// Both take the same options (all optional) and return { head, top, handL, handR, feet } in world coordinates:+// pose: dx, dy (in u, negative = up), sq (squash; negative stretches), rot (pivots at the feet), flip, sx, sy+// aL, aR arm angles: 0 = straight out sideways, + = up, − = down (±1.5 vertical). Rest ≈ −1.2.+// In side view 0 points forward (the way the character faces).+// bL, bR elbow bend (Lulu): + folds the forearm up/in (hand to chest ≈ 2, hand to chin ≈ 2.3), − back (hips)+// walk leg phase (1 = a full stride cycle); null = standing. See walkCycle().+// hair Lulu's hair/hem lag in u (+ = flicks up, e.g. while falling after a jump; use spring())+// view: 'front' | 'q' (3/4, facing right) | 'side' (profile, facing right) | 'back'. flip: true faces left.+// face: eyes, mouth, brows, lookX / lookY (−1..1), squint 0..1, blush 0..1, seed (blink timing), noBlink+// eyes: normal, wide, happy, closed, squeeze, sad, cry, teary, angry, heart, sleepy, shine, look, scared, x,+// wink — or a pair ['normal', 'happy'] for mismatched eyes+// mouth: smile, grin, laugh, o, O, frown, wobble, flat, wail, cat, tongue, pout+// brows: up, worried, angry, flat (or null)+// extras: emote + emoteK (0..1 pop) + emoteAge, draw(u, sw) (body-local, front coordinates, drawn last),+// armL/armR(u, sw) called at the hand in ARM space (+x along the forearm), holdL/holdR(u, sw) called at the+// hand UPRIGHT (props that stay level: an apple, a cup, a balloon string), propFront: draw props over the hand.+// boil: boilKey (a stable id for its boil seeds; default: call order — set it if characters come and go mid-shot)+// col: Lulu: coat, boots, hair colours via coat / boots / hairCol; Kuri: spikes, face via spikes / faceCol+//+// Moods: feel(name, t) and emotions(t, keys) (below) give the face, blush, emote and the idle body motion together:+// lulu(x, y, 36, { ...emotions(t, [[0, 'curious'], [1.4, 'surprised'], [1.9, 'happy']]), view: 'q' })++// ---------- shared helpers ----------+const U = (u, pts) => pts.map(([x, y]) => [x * u, y * u]);+const OPEN_EYES = ['normal', 'wide', 'look', 'sad', 'angry', 'scared', 'shine', 'teary'];+function blinkK(o) { // 1 while the eyes are shut for a blink (0.12 s every ~3–4.5 s, per seed)+ if (o.noBlink) return 0;+ const s = o.seed || 0, per = 3.1 + hash(s + 11) * 1.4, ph = (T + hash(s + 5) * 7) % per;+ return ph < .12 ? 1 : 0;+}+// local → world, for returned anchor points (mirrors the push/translate/rotate/scale the characters do)+function xform(x, y, rot, sx, sy) {+ const c = Math.cos(rot || 0), s = Math.sin(rot || 0);+ return (lx, ly) => [x + c * lx * sx - s * ly * sy, y + s * lx * sx + c * ly * sy];+}++// A two-segment arm (upper + fore), as one tapered sleeve with a mitten hand. Draws in the current body space.+// dirx: −1 left, +1 right (in side view +1 = forward). Returns the hand position (body space) and forearm angle.+function arm2(px, py, a, b, dirx, L1, L2, w0, w1, col, handCol, line, sw, u, hooks, gap) {+ const e = [px + dirx * Math.cos(a) * L1, py - Math.sin(a) * L1], a2 = a + b;+ const h = [e[0] + dirx * Math.cos(a2) * L2, e[1] - Math.sin(a2) * L2];+ const th = Math.atan2(h[1] - e[1], h[0] - e[0]);+ // slightly past the elbow the path gets a middle point so the bend reads as an elbow, not a kink+ colorIn(limbPts([px, py], e, h, w0, (w0 + w1) / 2, w1), { col, gap, ang: th + 1.3, w: clamp(u / 40, .45, 1.1), line, lw: sw * .85, curv: .25 });+ const hand = () => colorIn(ellPts(h[0] + Math.cos(th) * u * .12, h[1] + Math.sin(th) * u * .12, u * .42, u * .4, 14), { col: handCol, fill: 'flat', line, lw: sw * .8 });+ const props = () => {+ if (hooks.hold) { push(); translate(h[0], h[1]); hooks.hold(u, sw); pop(); }+ if (hooks.arm) { push(); translate(h[0], h[1]); rotate(th); if (dirx < 0) scale(1, -1); hooks.arm(u, sw); pop(); }+ };+ if (hooks.front) { hand(); props(); } else { props(); hand(); }+ return { h, th };+}+// One closed outline for a bent limb (root → elbow → tip) with a clamped miter at the elbow, so tight bends never spike.+function limbPts(A, E, Hh, wA, wE, wH) {+ const nrm = (p, q) => { const dx = q[0] - p[0], dy = q[1] - p[1], d = Math.hypot(dx, dy) || 1; return [-dy / d, dx / d]; };+ const n1 = nrm(A, E), n2 = nrm(E, Hh); let m = [n1[0] + n2[0], n1[1] + n2[1]]; const ml = Math.hypot(m[0], m[1]);+ m = ml < .2 ? n1 : [m[0] / ml, m[1] / ml]; const k = Math.min(1.6, 1 / Math.max(.4, m[0] * n1[0] + m[1] * n1[1]));+ const off = (p, n, w, s) => [p[0] + n[0] * w / 2 * s, p[1] + n[1] * w / 2 * s];+ const dir = [Hh[0] - E[0], Hh[1] - E[1]], dl = Math.hypot(dir[0], dir[1]) || 1, cap = [Hh[0] + dir[0] / dl * wH * .45, Hh[1] + dir[1] / dl * wH * .45];+ return [off(A, n1, wA, 1), off(E, m, wE * k, 1), off(Hh, n2, wH, 1), cap, off(Hh, n2, wH, -1), off(E, m, wE * k, -1), off(A, n1, wA, -1)];+}+const shadowUnder = (x, y, w, h, lift) => smudge(ellPts(x, y, w * (1 - Math.min(.5, lift * .06)), h * (1 - Math.min(.5, lift * .06)), 20), PAL.inkSoft, { op: 70, tex: .3 });++// ---------- faces (shared) ----------+// s = size unit; (x, y) = the eye's centre. Pupils follow lookX / lookY.+function eyeMark(kind, x, y, s, o, side, sw) {+ const lx = (o.lookX || 0) * s * .12, ly = (o.lookY || 0) * s * .1, sq = clamp(o.squint || 0), col = PAL.ink;+ if (sq > .6 && OPEN_EYES.includes(kind)) kind = 'closed';+ const dot = (rx, ry, hl = true) => {+ paint(ellPts(x + lx, y + ly, rx, ry * (1 - sq * .7), 14), { wash: col, ink: null });+ if (hl && rx > 3) paint(ellPts(x + lx - rx * .3, y + ly - ry * .35, rx * .32, rx * .32, 8), { wash: PAL.cream, ink: null });+ };+ const arc = (up, w = .3) => pencilLine([[x - s * w, y + (up ? s * .08 : -s * .06)], [x, y + (up ? -s * .14 : s * .1)], [x + s * w, y + (up ? s * .08 : -s * .06)]], sw * .9, col, .5);+ switch (kind) {+ case 'wide': paint(ellPts(x, y, s * .34, s * .4, 16), { wash: PAL.cream, ink: col, sw: sw * .6 }); dot(s * .16, s * .2); break;+ case 'scared': paint(ellPts(x, y, s * .34, s * .42, 16), { wash: PAL.cream, ink: col, sw: sw * .6 }); paint(ellPts(x + lx + jit(s * .02), y + ly, s * .08, s * .09, 8), { wash: col, ink: null }); break;+ case 'happy': arc(true); break;+ case 'closed': arc(false, .27); break;+ case 'squeeze': pencilLine([[x - side * s * .26, y - s * .18], [x + side * s * .18, y], [x - side * s * .26, y + s * .18]], sw * .9, col, 0); break;+ case 'sad': dot(s * .15, s * .2); pencilLine([[x - side * s * .3, y - s * .34], [x + side * s * .2, y - s * .22]], sw * .7, col, 0); break;+ case 'teary': dot(s * .17, s * .23); paint(ellPts(x + side * s * .12, y + s * .3, s * .09, s * .12, 10), { wash: PAL.sky, ink: PAL.skyDk, sw: sw * .4 }); break;+ case 'cry': {+ arc(true, .28);+ const ph = (T * 1.6 + (side > 0 ? .5 : 0)) % 1;+ paint(ribbon([[x + side * s * .1, y + s * .12], [x + side * s * .22, y + s * .6], [x + side * s * .16, y + s * 1.05]], s * .16, s * .26), { wash: PAL.skyLt, ink: PAL.skyDk, sw: sw * .5 });+ paint(ellPts(x + side * s * .2, y + s * (.3 + ph * 1.1), s * .09, s * .12, 10), { wash: PAL.sky, ink: null });+ break;+ }+ case 'angry': dot(s * .16, s * .2); pencilLine([[x - side * s * .32, y - s * .34], [x + side * s * .24, y - s * .12]], sw, col, 0); break;+ case 'heart': heartProp(x, y, s * .3, PAL.roseDk); break;+ case 'sleepy': pencilLine([[x - s * .28, y], [x + s * .28, y]], sw * .9, col, 0); paint(ellPts(x, y + s * .07, s * .12, s * .07, 8), { wash: col, ink: null }); break;+ case 'shine': dot(s * .2, s * .26, false); paint(ellPts(x + lx - s * .07, y + ly - s * .09, s * .08, s * .08, 8), { wash: PAL.cream, ink: null }); paint(ellPts(x + lx + s * .07, y + ly + s * .08, s * .04, s * .04, 6), { wash: PAL.cream, ink: null }); break;+ case 'x': pencilLine([[x - s * .2, y - s * .2], [x + s * .2, y + s * .2]], sw * .9, col, 0); pencilLine([[x + s * .2, y - s * .2], [x - s * .2, y + s * .2]], sw * .9, col, 0); break;+ case 'look': dot(s * .15, s * .21); break;+ default: dot(s * .15, s * .21);+ }+}+function mouthMark(kind, x, y, s, sw) {+ const col = PAL.ink, tong = PAL.rose, dark = '#8E4B4B';+ switch (kind) {+ case 'smile': pencilLine([[x - s * .32, y - s * .06], [x, y + s * .14], [x + s * .32, y - s * .06]], sw, col, .6); break;+ case 'grin': colorIn([[x - s * .38, y - s * .1], [x + s * .38, y - s * .1], [x + s * .22, y + s * .2], [x, y + s * .27], [x - s * .22, y + s * .2]], { col: dark, fill: 'flat', line: col, lw: sw * .8, curv: .5 }); break;+ case 'laugh': colorIn([[x - s * .45, y - s * .15], [x + s * .45, y - s * .15], [x + s * .3, y + s * .28], [x, y + s * .4], [x - s * .3, y + s * .28]], { col: dark, fill: 'flat', line: col, lw: sw * .8, curv: .5 });+ paint(ellPts(x, y + s * .24, s * .2, s * .1, 10), { wash: tong, ink: null }); break;+ case 'o': paint(ellPts(x, y + s * .04, s * .1, s * .12, 10), { wash: dark, ink: col, sw: sw * .7 }); break;+ case 'O': paint(ellPts(x, y + s * .08, s * .2, s * .28, 14), { wash: dark, ink: col, sw: sw * .8 }); paint(ellPts(x, y + s * .22, s * .12, s * .07, 8), { wash: tong, ink: null }); break;+ case 'frown': pencilLine([[x - s * .3, y + s * .12], [x, y - s * .06], [x + s * .3, y + s * .12]], sw, col, .6); break;+ case 'wobble': pencilLine([[x - s * .32, y + s * .04], [x - s * .16, y - s * .04], [x, y + s * .04], [x + s * .16, y - s * .04], [x + s * .32, y + s * .04]], sw * .9, col, .4); break;+ case 'flat': pencilLine([[x - s * .24, y], [x + s * .24, y + s * .01]], sw * .9, col, 0); break;+ case 'wail': colorIn([[x - s * .34, y - s * .12], [x + s * .34, y - s * .12], [x + s * .24, y + s * .42], [x - s * .24, y + s * .42]], { col: dark, fill: 'flat', line: col, lw: sw * .8, curv: .4 });+ paint(ellPts(x, y + s * .34, s * .16, s * .07, 8), { wash: tong, ink: null }); break;+ case 'cat': pencilLine([[x - s * .3, y], [x - s * .15, y + s * .1], [x, y], [x + s * .15, y + s * .1], [x + s * .3, y]], sw * .9, col, .5); break;+ case 'tongue': pencilLine([[x - s * .3, y - s * .04], [x, y + s * .12], [x + s * .3, y - s * .04]], sw, col, .6); paint(ellPts(x + s * .08, y + s * .17, s * .12, s * .11, 10), { wash: tong, ink: col, sw: sw * .5 }); break;+ case 'pout': pencilLine([[x - s * .12, y + s * .02], [x, y - s * .05], [x + s * .12, y + s * .02]], sw * .9, col, .5); break;+ }+}+function browMarks(kind, xs, y, s, sw) {+ if (!kind) return;+ for (const [x, side] of xs) {+ const P = { up: [[-.24, .04], [0, -.08], [.24, .02]], worried: [[-.24, -.12], [.24, .06]], angry: [[-.24, .1], [.24, -.08]], flat: [[-.22, 0], [.22, 0]] }[kind];+ if (!P) continue;+ // P is written for the right eye (inner end = −x); mirror it for the left one+ pencilLine(P.map(([px, py]) => [x + px * s * side, y + py * s]), sw * .8, PAL.ink, .5);+ }+}+function cheeks(xs, y, r, k, sw) {+ if (k <= .02) return;+ for (const x of xs) { smudge(ellPts(x, y, r, r * .75, 14), PAL.rose, { op: 70 + 110 * k, tex: .4 }); if (k > .5) for (let i = 0; i < 3; i++) pencilLine([[x - r * .5 + i * r * .4, y + r * .25], [x - r * .3 + i * r * .4, y - r * .25]], sw * .5, PAL.roseDk, 0); }+}++// ---------- Lulu ----------+const LULU = { coat: PAL.butter, coatDk: PAL.butterDk, boots: PAL.sky, hair: '#8A5A44', skin: '#F8D2B4', clip: PAL.rose };+function lulu(x, y, u, o = {}) {+ const id = o.boilKey ?? 'l' + (++CAST_N), rs = part => boilSeed(`lulu ${id} ${part}`);+ const view = o.view || 'front', side = view === 'side', q = view === 'q', back = view === 'back';+ const coat = o.coat || LULU.coat, boots = o.boots || LULU.boots, hairC = o.hairCol || LULU.hair, skin = LULU.skin;+ const dy = (o.dy || 0) * u, sq = o.sq || 0, sw = clamp(u / 21, .5, 2.6), line = PAL.ink, gap = clamp(u * .3, 5, 18), cw = clamp(u / 38, .45, 1.2);+ x += (o.dx || 0) * u;+ const fx = (o.flip ? -1 : 1) * (o.sx ?? 1) * (1 + sq * .5), fy = (o.sy ?? 1) * (1 - sq);+ rs('shadow'); if (!o.noShadow) shadowUnder(x, y + u * .1, u * (side ? 2 : 2.6), u * .55, Math.abs(o.dy || 0));+ push(); translate(x, y + dy); if (o.rot) rotate(o.rot); scale(fx, fy);+ const hairLag = (o.hair || 0);++ // --- arms (defined here, drawn at the right layer) ---+ const aL = o.aL ?? -1.2, aR = o.aR ?? -1.2, bL = o.bL ?? .2, bR = o.bR ?? .2;+ const hands = {};+ const drawArm = (which, far) => {+ rs('arm' + which);+ const a = which === 'L' ? aL : aR, b = which === 'L' ? bL : bR;+ const hooks = { arm: which === 'L' ? o.armL : o.armR, hold: which === 'L' ? o.holdL : o.holdR, front: o.propFront };+ let px, dirx;+ if (side) { px = far ? -.15 : .15; dirx = 1; }+ else if (q) { px = which === 'L' ? -1.05 : 1.3; dirx = which === 'L' ? -1 : 1; }+ else { px = which === 'L' ? -1.15 : 1.15; dirx = which === 'L' ? -1 : 1; }+ if (back) dirx = -dirx, px = -px;+ const c = far ? mixCol(coat, PAL.inkSoft, .25) : coat, hc = far ? mixCol(skin, PAL.inkSoft, .2) : skin;+ const r = arm2(px * u, -5.25 * u, a, b, dirx, 1.3 * u, 1.2 * u, .95 * u, .72 * u, c, hc, line, sw, u, hooks, gap);+ hands[which] = r.h;+ };++ // --- back hair (behind everything above the shoulders) ---+ rs('hairback');+ const hx = q ? .12 : 0;+ if (!back && !side) {+ const P = [];+ for (let i = 0; i <= 16; i++) { const a = Math.PI + i / 16 * Math.PI; P.push([hx + Math.cos(a) * 2.95, -8.3 + Math.sin(a) * 2.8]); }+ const fl = hairLag * .6;+ P.push([hx + 3.05, -6.9], [hx + 3.3 + fl * .2, -6.15 - fl], [hx + 2.4, -6.35 - fl * .4], [hx + 1.2, -6.5], [hx - 1.2, -6.5], [hx - 2.4, -6.35 - fl * .4], [hx - 3.3 - fl * .2, -6.15 - fl], [hx - 3.05, -6.9]);+ colorIn(U(u, P), { col: hairC, gap, ang: 1.2, w: cw, line, lw: sw, curv: .4 });+ }+ // far arm (side / 3/4): behind the body+ if (side) drawArm('L', true); if (q) drawArm('L', true);++ // --- legs + boots ---+ const legs = side ? [[-.32, 1], [.32, 0]] : q ? [[-.55, 1], [.75, 0]] : [[-.62, 0], [.62, 0]];+ legs.forEach(([lx, far], i) => {+ rs('leg' + i);+ let ang = 0, lift = 0;+ if (o.walk != null) {+ const ph = (o.walk + (i ? .5 : 0)) * TAU;+ if (side || q) { ang = Math.sin(ph) * .5; lift = Math.max(0, Math.cos(ph)) * .35; }+ else lift = Math.max(0, Math.sin(ph)) * .55;+ }+ push(); translate(lx * u, -2.5 * u); rotate(-ang);+ const len = (2.05 - lift) * u, lc = far ? mixCol(skin, PAL.inkSoft, .2) : skin, bc = far ? mixCol(boots, PAL.inkSoft, .25) : boots;+ colorIn(rectPts(-.3 * u, 0, .6 * u, len - .5 * u), { col: lc, fill: 'flat', line, lw: sw * .8 });+ const toe = side || q ? .42 : (lx < 0 ? -.12 : .12);+ colorIn(rrPts((-.5 + toe) * u, len - .9 * u, 1.0 * u, .95 * u, .35 * u), { col: bc, gap: gap * .8, ang: .3, w: cw * .8, line, lw: sw * .85 });+ pop();+ });++ // --- coat ---+ rs('coat');+ const cs = side ? .72 : q ? .95 : 1, hem = hairLag * .15;+ const C = [[-.55, -5.8], [-1.35 * cs, -5.45], [-1.7 * cs, -4.4], [-2.3 * cs, -2.2 - hem]];+ for (let i = 1; i < 6; i++) C.push([lerp(-2.3 * cs, 2.3 * cs, i / 6), -2.2 - hem + (i % 2 ? .22 : -.02)]); // scalloped hem+ C.push([2.3 * cs, -2.2 - hem], [1.7 * cs, -4.4], [1.35 * cs, -5.45], [.55, -5.8]);+ const CP = U(u, C.map(([cx, cy]) => [cx + (q ? .12 : 0), cy]));+ colorIn(CP, { col: coat, gap, ang: -.55, w: cw, line, lw: sw, curv: .25, shade: { pts: U(u, [[.9 * cs, -5.2], [2.1 * cs, -2.4], [.9 * cs, -2.4]]), col: mixCol(coat, LULU.coatDk, .55), gap: gap * 1.3, ang: .4 } });+ if (!back) { // buttons + collar+ const bx = side ? .75 : q ? .55 : 0;+ for (const by of [-4.6, -3.5]) paint(ellPts(bx * u, by * u, .17 * u, .17 * u, 10), { wash: PAL.coral, ink: line, sw: sw * .5 });+ if (!side) colorIn(U(u, [[-.95 + (q ? .2 : 0), -5.85], [(q ? .25 : 0), -5.05], [.95 + (q ? .2 : 0), -5.85], [(q ? .2 : 0), -5.6]]), { col: PAL.cream, fill: 'flat', line, lw: sw * .7 });+ } else pencilLine(U(u, [[0, -5.5], [0, -2.5]]), sw * .6, LULU.coatDk, 0);+ if (back) { drawArm('L', false); drawArm('R', false); }++ // --- head ---+ rs('head');+ const HX = side ? .25 : q ? .2 : 0, HY = -8.1;+ let head;+ if (side) { // profile: one outline with a little button nose+ head = []; for (let i = 0; i < 40; i++) { const a = i / 40 * TAU, d = ((a + Math.PI) % TAU - Math.PI - .28) / .13, bump = .3 * Math.exp(-d * d); head.push([(HX + Math.cos(a) * (2.45 + bump)) * u, (HY + Math.sin(a) * (2.35 + bump * .4)) * u]); }+ } else head = ellPts(HX * u, HY * u, 2.55 * u, 2.35 * u, 26);+ colorIn(head, { col: skin, gap: gap * 1.1, ang: .9, w: cw * .8, line, lw: sw, pale: .35, tone: mixCol(skin, PAL.peachDk, .45), curv: .3 });++ // --- face ---+ if (!back) {+ rs('face');+ const eyes = Array.isArray(o.eyes) ? o.eyes : [o.eyes || 'normal', o.eyes || 'normal'];+ const blink = blinkK(o), E = k => blink && OPEN_EYES.includes(k) ? 'closed' : k;+ const fc = side ? 1.45 : q ? .7 : 0, sp = side ? 0 : q ? .78 : .98;+ const ex = side ? [[fc + .05, 1]] : [[fc - sp, -1], [fc + sp, 1]];+ ex.forEach(([ex1, s1], i) => eyeMark(E(eyes[side ? 1 : i]), ex1 * u, -7.75 * u, u * 1.3, o, s1, sw));+ browMarks(o.brows, ex.map(([e1, s1]) => [e1 * u, s1]), -8.55 * u, u, sw);+ cheeks(side ? [(fc + .15) * u] : [(fc - sp - .6) * u, (fc + sp + .6) * u], -7.0 * u, .45 * u, .35 + .65 * (o.blush || 0), sw);+ mouthMark(o.mouth === undefined ? 'smile' : o.mouth, (fc + (side ? .55 : q ? .15 : 0)) * u, -6.8 * u, u, sw);+ }++ // --- bangs / back of the hair ---+ rs('hairfront');+ if (back) {+ const P = []; for (let i = 0; i <= 20; i++) { const a = Math.PI + i / 20 * TAU * .5; P.push([Math.cos(a) * 2.9, -8.2 + Math.sin(a) * 2.75]); }+ P.push([3.1, -6.6], [3.3, -6.1 - hairLag * .6], [0, -6.25], [-3.3, -6.1 - hairLag * .6], [-3.1, -6.6]);+ colorIn(U(u, P), { col: hairC, gap, ang: 1.3, w: cw, line, lw: sw, curv: .4 });+ } else {+ const bx = side ? .55 : q ? .38 : 0, P = [];+ if (!side) {+ const a0 = side ? 1.05 * Math.PI : Math.PI * 1.02, a1 = side ? 1.97 * Math.PI : Math.PI * 1.98;+ for (let i = 0; i <= 12; i++) { const a = lerp(a0, a1, i / 12); P.push([bx + Math.cos(a) * 2.65, -8.2 + Math.sin(a) * 2.55]); }+ const x0 = P[P.length - 1][0], xs = P[0][0];+ for (let i = 1; i <= 3; i++) { const xx = lerp(x0, xs, i / 3), xm = lerp(x0, xs, (i - .5) / 3); P.push([xm, -8.75], [xx, -9.05]); }+ colorIn(U(u, P), { col: hairC, gap: gap * .9, ang: -1.1, w: cw, line, lw: sw, curv: .35 });+ } else { // profile: one hair shape — fringe at the front, over the crown, down the back to the flick, and back up behind the ear+ const Q = [[2.15, -8.85]];+ for (let i = 0; i <= 14; i++) { const a = lerp(-.35 * Math.PI, -1.05 * Math.PI, i / 14); Q.push([.2 + Math.cos(a) * 2.72, -8.2 + Math.sin(a) * 2.62]); }+ Q.push([-2.75, -6.9], [-3.1 - hairLag * .2, -6.1 - hairLag * .6], [-2.2, -6.3 - hairLag * .4], [-1.0, -6.5], [-.35, -7.2], [-.1, -8.2], [.7, -8.75], [1.4, -8.95]);+ colorIn(U(u, Q), { col: hairC, gap, ang: 1.2, w: cw, line, lw: sw, curv: .35 });+ }+ rs('clip');+ starProp((bx + 1.65) * u, -9.85 * u, .55 * u, PAL.butter, .2);+ }+ // arms in front (3/4: near arm; side: near arm)+ if (side) drawArm('R', false); if (q) drawArm('R', false);+ if (!side && !q && !back) { drawArm('L', false); drawArm('R', false); } // front: arms over everything, so raised arms show+ rs('draw'); if (o.draw) o.draw(u, sw);+ pop();++ rs('emote');+ const dir = o.flip ? -1 : 1;+ if (o.emote) emote(o.emote, x + dir * 3.2 * u, y + dy - 11.2 * u * (1 - sq), u * .9, o.emoteK ?? 1, o.emoteAge ?? T);+ rs('after');+ const W2 = xform(x, y + dy, o.rot, fx, fy);+ return { head: W2(0, -8.1 * u), top: W2(0, -10.9 * u), handL: hands.L ? W2(...hands.L) : null, handR: hands.R ? W2(...hands.R) : null, feet: [x, y] };+}++// ---------- Kuri ----------+const KURI = { spikes: '#9C6B50', spikesDk: '#6E4A39', face: '#F6DFC2', feet: '#E9B996', nose: '#4A3631' };+function kuri(x, y, u, o = {}) {+ const id = o.boilKey ?? 'k' + (++CAST_N), rs = part => boilSeed(`kuri ${id} ${part}`);+ const view = o.view || 'front', side = view === 'side', q = view === 'q', back = view === 'back';+ const spk = o.spikes || KURI.spikes, faceC = o.faceCol || KURI.face, line = PAL.ink;+ const dy = (o.dy || 0) * u, sq = o.sq || 0, sw = clamp(u / 17, .5, 2.6), gap = clamp(u * .55, 5, 16), cw = clamp(u / 30, .45, 1.2);+ x += (o.dx || 0) * u;+ const fx = (o.flip ? -1 : 1) * (o.sx ?? 1) * (1 + sq * .6), fy = (o.sy ?? 1) * (1 - sq);+ rs('shadow'); if (!o.noShadow) shadowUnder(x, y + u * .1, u * 2.9, u * .55, Math.abs(o.dy || 0) * .5);+ push(); translate(x, y + dy); if (o.rot) rotate(o.rot); scale(fx, fy);+ const hands = {};+ const drawArm = (which, far) => {+ rs('arm' + which);+ const a = which === 'L' ? (o.aL ?? -1.1) : (o.aR ?? -1.1), b = which === 'L' ? (o.bL ?? .3) : (o.bR ?? .3);+ const hooks = { arm: which === 'L' ? o.armL : o.armR, hold: which === 'L' ? o.holdL : o.holdR, front: o.propFront };+ let px, py = -1.45, dirx;+ if (side) { px = far ? .2 : .5; py = -1.0; dirx = 1; } else if (q) { px = which === 'L' ? -1.25 : 2.1; py = which === 'L' ? -1.45 : -1.1; dirx = which === 'L' ? -1 : 1; }+ else { px = which === 'L' ? -1.75 : 1.75; dirx = which === 'L' ? -1 : 1; }+ if (back) dirx = -dirx, px = -px;+ const c = far ? mixCol(KURI.feet, PAL.inkSoft, .25) : KURI.feet;+ const r = arm2(px * u, py * u, a, b, dirx, .6 * u, .55 * u, .62 * u, .5 * u, c, c, line, sw * .9, u * .8, hooks, gap);+ hands[which] = r.h;+ };+ // feet+ const feet = side ? [[-.5, 1], [.7, 0]] : q ? [[-.6, 1], [1.1, 0]] : [[-.95, 0], [.95, 0]];+ feet.forEach(([fxp, far], i) => {+ rs('foot' + i);+ let lift = 0, sx = 0;+ if (o.walk != null) { const ph = (o.walk + (i ? .5 : 0)) * TAU; lift = Math.max(0, Math.sin(ph)) * .45; if (side || q) sx = Math.cos(ph) * .45; }+ colorIn(ellPts((fxp + sx) * u, (-.28 - lift) * u, .62 * u, .34 * u, 14), { col: far ? mixCol(KURI.feet, PAL.inkSoft, .25) : KURI.feet, fill: 'flat', line, lw: sw * .8 });+ });+ if (side || q) drawArm('L', true);+ // spikes: a spiky ball, coloured with radiating strokes+ rs('spikes');+ const cx = side ? -.35 : q ? -.3 : 0, cy = -2.35, S = [];+ const N = back ? 26 : 22;+ for (let i = 0; i < N * 2; i++) {+ const a = i / (N * 2) * TAU - Math.PI / 2, down = Math.sin(a);+ let r = (i % 2 ? 2.55 : 3.2 + .12 * Math.sin(i * 1.7));+ if (!back && down > .55) r = 2.35; // no spikes underneath+ if (side && Math.cos(a) > .45 && down > -.2) r = 2.3; // nor in front of the face in profile+ if (q && Math.cos(a) > .7 && down > -.1) r = 2.3;+ S.push([cx + Math.cos(a) * r * 1.05, cy + Math.sin(a) * r * .92 + (i % 2 ? 0 : -.08 * (1 - Math.abs(Math.cos(a))) * (o.hair || 0))]);+ }+ colorIn(U(u, S), { col: spk, gap: gap * .7, ang: 1.2, w: cw, line, lw: sw, pale: .3, tone: KURI.spikesDk });+ for (let i = 0; i < 9; i++) { // a few long spike strokes radiating out, for texture+ const a = -Math.PI + (i + .5) / 9 * Math.PI + (side ? -.4 : 0), r0 = 1.4, r1 = 2.7;+ crayonLine(U(u, [[cx + Math.cos(a) * r0, cy + Math.sin(a) * r0 * .9], [cx + Math.cos(a) * r1, cy + Math.sin(a) * r1 * .9]]), cw * .7, KURI.spikesDk, 0);+ }+ if (!back) {+ // ears+ rs('ears');+ const ears = side ? [[.55, -4.05]] : q ? [[-.55, -4.05], [1.55, -3.95]] : [[-1.4, -4.0], [1.4, -4.0]];+ ears.forEach(([ex, ey]) => { colorIn(ellPts(ex * u, ey * u, .5 * u, .48 * u, 12), { col: KURI.feet, fill: 'flat', line, lw: sw * .8 }); dab(ex * u, ey * u + .05 * u, .2 * u, PAL.rose, cw * .6); });+ // face / belly+ rs('face');+ const F = side ? ellPts(1.05 * u, -2.0 * u, 1.75 * u, 1.65 * u, 22) : q ? ellPts(.55 * u, -1.85 * u, 2.0 * u, 1.75 * u, 22) : ellPts(0, -1.85 * u, 2.15 * u, 1.8 * u, 22);+ colorIn(F, { col: faceC, gap: gap * .9, ang: .5, w: cw * .8, line, lw: sw, pale: .3, tone: mixCol(faceC, PAL.peachDk, .35) });+ // snout + nose+ const nx = side ? 3.1 : q ? 1.35 : 0, ny = side ? -1.85 : -1.7;+ if (side) colorIn(ellPts(2.3 * u, -1.9 * u, .9 * u, .5 * u, 18, 0, .12), { col: faceC, fill: 'flat', line, lw: sw * .85 }); // snout+ paint(ellPts(nx * u, ny * u, .34 * u, .26 * u, 12), { wash: KURI.nose, ink: line, sw: sw * .6 });+ paint(ellPts((nx - .1) * u, (ny - .09) * u, .1 * u, .07 * u, 8), { wash: PAL.cream, ink: null });+ const eyes = Array.isArray(o.eyes) ? o.eyes : [o.eyes || 'normal', o.eyes || 'normal'];+ const blink = blinkK(o), E = k => blink && OPEN_EYES.includes(k) ? 'closed' : k;+ const ex = side ? [[1.7, 1]] : q ? [[-.05, -1], [1.35, 1]] : [[-.78, -1], [.78, 1]];+ ex.forEach(([e1, s1], i) => eyeMark(E(eyes[side ? 1 : i]), e1 * u, -2.5 * u, u * 1.25, o, s1, sw));+ browMarks(o.brows, ex.map(([e1, s1]) => [e1 * u, s1]), -3.2 * u, u, sw);+ cheeks(side ? [1.4 * u] : q ? [-.5 * u, 1.95 * u] : [-1.4 * u, 1.4 * u], -1.75 * u, .38 * u, .35 + .65 * (o.blush || 0), sw);+ mouthMark(o.mouth === undefined ? 'cat' : o.mouth, (side ? 2.5 : nx) * u, (side ? -1.45 : -1.1) * u, u * .8, sw);+ } else {+ rs('ears');+ [[-1.4, -4.0], [1.4, -4.0]].forEach(([ex, ey]) => colorIn(ellPts(ex * u, ey * u, .45 * u, .42 * u, 12), { col: mixCol(KURI.feet, PAL.inkSoft, .2), fill: 'flat', line, lw: sw * .8 }));+ }+ if (side || q) drawArm('R', false); else { drawArm('L', false); drawArm('R', false); }+ rs('draw'); if (o.draw) o.draw(u, sw);+ pop();+ rs('emote');+ if (o.emote) emote(o.emote, x + (o.flip ? -1 : 1) * 2.6 * u, y + dy - 5.4 * u * (1 - sq), u * .85, o.emoteK ?? 1, o.emoteAge ?? T);+ rs('after');+ const W2 = xform(x, y + dy, o.rot, fx, fy);+ return { head: W2(0, -2.3 * u), top: W2(0, -5.2 * u), handL: hands.L ? W2(...hands.L) : null, handR: hands.R ? W2(...hands.R) : null, feet: [x, y] };+}++// ---------- moods ----------+// Each emotion: a face (eyes, mouth, brows, blush), an emote, a take size, and an idle body motion locked to the beat.+const _b = t => { const bp = bpOf(t), s1 = Math.sin(bp * Math.PI); return { bp, s1, ab: Math.abs(s1), hit: pulse(t), s2: Math.sin(bp * TAU), f: frac(bp) }; };+const EMO = {+ neutral: { eyes: 'normal', mouth: 'smile', take: .3, body: t => { const b = _b(t); return { dy: -.12 * b.ab, sq: .02 * b.hit, aL: -1.22 + .04 * b.s1, aR: -1.2 - .04 * b.s1 }; } },+ happy: { eyes: 'happy', mouth: 'grin', blush: .4, take: .6, body: t => { const b = _b(t); return { dy: -.45 * b.ab, sq: .06 * b.hit, aL: -.95 + .2 * b.s1, aR: -.95 - .2 * b.s1, bL: .5, bR: .5 }; } },+ laugh: { eyes: 'squeeze', mouth: 'laugh', blush: .6, take: .8, body: t => { const c = Math.abs(Math.sin(t * TAU * 4.5)); return { dy: -.25 * c, sq: .06 * c - .03, rot: -.05 + .03 * Math.sin(t * TAU * 4.5), aL: -1.3, aR: -1.3, bL: 1.7 + .15 * c, bR: 1.7 + .15 * c }; } },+ excited: { eyes: 'shine', mouth: 'laugh', emote: 'spark', blush: .4, take: 1, body: t => { const b = _b(t), h = Math.abs(b.s2); return { dy: -1.1 * h, sq: .12 * pulse2(t) - .05 * h, aL: .9 + .35 * Math.sin(b.bp * TAU * 2), aR: .9 - .35 * Math.sin(b.bp * TAU * 2), bL: .2, bR: .2 }; } },+ love: { eyes: 'heart', mouth: 'cat', blush: 1, emote: 'hearts', take: .7, body: t => { const b = _b(t), s = Math.sin(b.bp * Math.PI / 2); return { rot: .06 * s, dy: -.2 * b.ab, aL: -1.15, aR: -1.15, bL: 2.3, bR: 2.3 }; } },+ shy: { eyes: 'look', mouth: 'pout', blush: 1, take: .3, body: t => { const b = _b(t), s = Math.sin(b.bp * Math.PI / 2); return { lookX: -.7, lookY: .8, sq: .04, rot: -.05 + .02 * s, aL: -1.35, aR: -1.35, bL: 1.1, bR: 1.1 }; } },+ proud: { eyes: 'closed', mouth: 'grin', brows: 'up', blush: .3, emote: 'spark', take: .5, body: t => { const b = _b(t); return { sq: -.06 - .02 * b.ab, dy: -.1 * b.hit, aL: -.55, aR: -.55, bL: -1.8, bR: -1.8, rot: .02 * b.s1 }; } },+ curious: { eyes: 'look', mouth: 'o', brows: 'up', emote: '?', take: .5, body: t => { const b = _b(t); return { lookX: .7, rot: .07 + .02 * b.s1, dy: -.08 * b.ab, aL: -1.25, aR: -1.05, bR: 2.25 }; } },+ thinking: { eyes: 'look', mouth: 'flat', brows: 'worried', emote: 'dots', take: .4, body: t => { const b = _b(t); return { lookX: .4, lookY: -.8, rot: .04, aR: -1.05, bR: 2.35, aL: -1.25, dy: -.05 * b.ab }; } },+ idea: { eyes: 'shine', mouth: 'grin', brows: 'up', emote: 'bulb', take: 1.1, body: t => { const b = _b(t); return { dy: -.5 * b.ab, sq: -.04 + .06 * b.hit, aR: 1.25 + .08 * b.s2, bR: .15, aL: -1.1 }; } },+ surprised: { eyes: 'wide', mouth: 'O', brows: 'up', emote: '!', fade: true, take: 1.3, body: t => { const b = _b(t); return { sq: -.1, dy: -.2 - .1 * b.ab, aL: .35 + .05 * b.s2, aR: .35 - .05 * b.s2, bL: .6, bR: .6 }; } },+ scared: { eyes: 'scared', mouth: 'wobble', brows: 'worried', emote: 'sweat', take: 1.1, body: t => ({ dx: .06 * Math.sin(t * TAU * 20), sq: .06, aL: -.35 + .06 * Math.sin(t * TAU * 17), aR: -.35 + .06 * Math.sin(t * TAU * 19), bL: 2.1, bR: 2.1, lookX: .6 * Math.sign(Math.sin(t * 2.3)) }) },+ sad: { eyes: 'sad', mouth: 'frown', brows: 'worried', emote: 'cloud', take: .3, body: t => { const b = _b(t), s = Math.sin(b.bp * Math.PI / 4); return { sq: .07 + .02 * s, rot: .025 * s, aL: -1.42, aR: -1.42, bL: .05, bR: .05, lookY: .6 }; } },+ cry: { eyes: 'cry', mouth: 'wail', brows: 'worried', blush: .5, take: .8, body: t => { const b = _b(t), sob = Math.sin(b.f * Math.PI) * Math.exp(-b.f * 2); return { sq: .1 * sob - .02, dy: -.35 * sob, aL: -.95, aR: -.95, bL: 2.45 + .1 * Math.sin(t * TAU * 5), bR: 2.45 - .1 * Math.sin(t * TAU * 5), rot: .03 * b.s1 }; } },+ angry: { eyes: 'angry', mouth: 'frown', brows: 'angry', emote: 'anger', blush: .5, take: .8, body: t => { const b = _b(t); return { dx: .05 * Math.sin(t * TAU * 16), sq: .08 * b.hit, aL: -1.05, aR: -1.05, bL: -.25, bR: -.25 }; } },+ sleepy: { eyes: 'sleepy', mouth: 'o', emote: 'zzz', take: .2, body: t => { const br = Math.sin(t * TAU * .3); return { sq: .04 + .04 * br, rot: .05 * Math.sin(t * .8), aL: -1.4, aR: -1.4, bL: .05, bR: .05 }; } },+ determined: { eyes: 'angry', mouth: 'flat', brows: 'angry', take: .7, body: t => { const b = _b(t), p = Math.sin(b.f * Math.PI); return { rot: .05, sq: -.03 + .05 * b.hit, dy: -.12 * b.ab, aL: -.65 + .3 * p, aR: -.65 + .3 * p, bL: 2.0, bR: 2.0 }; } },+ relieved: { eyes: 'closed', mouth: 'smile', emote: 'sweat', take: .4, body: t => { const br = Math.sin(t * TAU * .35); return { sq: .04 + .04 * br, aL: -1.35, aR: -1.35, bL: .1, bR: .1 }; } },+};+function feel(name, t, over = {}) {+ const E = EMO[name] || EMO.neutral;+ return { eyes: E.eyes, mouth: E.mouth, brows: E.brows || null, blush: E.blush || 0, emote: E.emote, ...(E.body ? E.body(t) : {}), ...over };+}+// An emotion timeline with ACTED changes: keys = [[t0, 'neutral'], [t1, 'surprised'], [t2, 'happy', { emote: null }]].+// Before each change the eyes squeeze and the body squashes (anticipation); the face swaps under the squint; a take the+// size of the new emotion fires; the body settles into the new idle with overshoot; blush cross-fades; the emote pops.+function emotions(t, keys, o = {}) {+ let i = 0; while (i + 1 < keys.length && t >= keys[i + 1][0]) i++;+ const [tc, name, over] = keys[i], age = t - tc, cur = feel(name, t, over);+ const tn = i + 1 < keys.length ? keys[i + 1][0] : Infinity, tkS = o.take ?? 1;+ const E = EMO[name] || EMO.neutral;+ let squint = cur.squint || 0;+ if (tn - t < .1) squint = Math.max(squint, 1 - (tn - t) / .1);+ if (i > 0 && age < .14) squint = Math.max(squint, 1 - age / .14);+ const prev = i > 0 ? feel(keys[i - 1][1], t, keys[i - 1][2]) : null;+ if (prev && age < .5) {+ const base = { dy: 0, sq: 0, aL: -1.2, aR: -1.2, bL: .2, bR: .2, rot: 0, dx: 0, lookX: 0, lookY: 0 };+ const k = backOut(seg(age, 0, .4)), kc = ease(seg(age, 0, .3));+ for (const f in base) cur[f] = lerp(prev[f] ?? base[f], cur[f] ?? base[f], k);+ cur.blush = lerp(prev.blush || 0, cur.blush || 0, kc);+ }+ const t1 = prev ? take(t, tc, (E.take ?? .6) * tkS) : { sq: 0, dy: 0 };+ const En = i + 1 < keys.length ? EMO[keys[i + 1][1]] || EMO.neutral : null, t2 = En ? take(t, tn, (En.take ?? .6) * tkS) : { sq: 0, dy: 0 };+ cur.sq = (cur.sq || 0) + t1.sq * .7 + t2.sq * .7; cur.dy = (cur.dy || 0) + t1.dy * .6 + t2.dy * .6;+ cur.squint = squint;+ const same = prev && prev.emote === cur.emote;+ cur.emoteK = same ? 1 : seg(age, .06, .32) * (E.fade && !(over && over.emote) ? 1 - seg(age, 1.4, 1.8) : 1);+ cur.emoteAge = age;+ return cur;+}+// A walk cycle at phase ph (1 = one full stride): legs, arm swing, bob and a little sway. Spread it into a character.+// For side view pass side = true (arms swing forward/back instead of out/in).+function walkCycle(ph, side = true, amt = 1) {+ const s = Math.sin(ph * TAU), b = Math.abs(Math.sin(ph * TAU));+ return side ? { walk: ph, dy: -.28 * b * amt, aL: -1.35 + .55 * s * amt, aR: -1.35 - .55 * s * amt, bL: .35, bR: .35, rot: .03 * amt }+ : { walk: ph, dy: -.22 * b * amt, aL: -1.2 + .25 * s * amt, aR: -1.2 - .25 * s * amt, rot: .025 * s * amt };+}+// Merge poses: later ones win, except dy / sq / rot / dx, which add (so a mood's bounce and a jump combine).+function pose(...ps) {+ const out = {};+ for (const p of ps) for (const k in p) out[k] = ['dy', 'sq', 'rot', 'dx'].includes(k) ? (out[k] || 0) + (p[k] || 0) : p[k];+ return out;+}diff --git a/.claude/skills/crayon-storybook/template/src/config.js b/.claude/skills/crayon-storybook/template/src/config.jsnew file mode 100644index 0000000..e1c8a3f--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/config.js@@ -0,0 +1,8 @@+// config.js: project settings.+// duration: the video's length in seconds.+// bpm: the rhythm idles, bounces and pulse() follow. With music, set it to the song's tempo and offset to the+// time in seconds of its first downbeat.+// fps: output frame rate (render.mjs reads --fps; 24 is the storybook default).+// boil: linework boil rate in drawings per second (default 8: slow, re-drawn-by-hand).+// toothBoil: false keeps the paper tooth fixed on screen (default: it shifts with each boil drawing).+const PROJECT = { duration: 10, bpm: 96, offset: 0, fps: 24 };diff --git a/.claude/skills/crayon-storybook/template/src/core.js b/.claude/skills/crayon-storybook/template/src/core.jsnew file mode 100644index 0000000..cc42aca--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/core.js@@ -0,0 +1,318 @@+// core.js: the runtime. Constants, timing and motion helpers, camera, paint wrapper, compositing and the render hooks.+// Derived from painted-animation's core.js (ClaudeAnimationBase, MIT © John Heibel; see LICENSE). The render contract+// (window.ready / renderAt / renderSheet) is unchanged, so the same render.mjs drives it. The LOOK (brushes, paper,+// tooth, fills, finishing) lives in crayon.js; the characters in cast.js.+// Length and rhythm come from PROJECT in config.js.+const W = 1920, H = 1080;+const BPM = PROJECT.bpm, BEAT = 60 / BPM, OFF = PROJECT.offset || 0, DUR = PROJECT.duration;+// Linework boils at BOIL drawings a second. 8 reads as "re-drawn by hand": slow, calm, storybook.+const BOIL = PROJECT.boil || 8;+const TAU = Math.PI * 2;+// The storybook palette: soft crayon colours on cream paper. No pure black or white: PAL.ink is a cocoa pencil,+// PAL.cream the lightest light. Dk/Lt variants are for shading scribbles and highlights.+const PAL = {+ paper: '#F7EFDD', cream: '#FFF9EC', ink: '#4A3631', inkSoft: '#7A5C52',+ butter: '#F7D774', butterDk: '#E8B64A', sky: '#9ECBEA', skyDk: '#6FA6D6', skyLt: '#CFE6F5',+ rose: '#F09AAB', roseDk: '#D9687F', sage: '#AECB98', sageDk: '#7FA56E', leaf: '#8DBB78',+ lilac: '#C3AEE0', lilacDk: '#9A82C4', peach: '#F9CFA8', peachDk: '#EBA57E', coral: '#EE8A6E',+ cocoa: '#8C5E48', bark: '#A77657', night: '#5C6BA8', dusk: '#8E86C7',+ // aliases kept so older helpers (karaoke.js, brushWipe) still work+ clay: '#EE8A6E', clayDk: '#C8694F', clayLt: '#F6B59C', ochre: '#EDB84F', sap: '#8DBB78', teal: '#7FB9B1',+ violet: '#9A82C4', indigo: '#5C6BA8'+};++const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));+const lerp = (a, b, x) => a + (b - a) * x;+const ease = x => { x = clamp(x); return x * x * (3 - 2 * x); };+const easeOut = x => 1 - Math.pow(1 - clamp(x), 3);+const backOut = x => { x = clamp(x); const s = 1.9; return 1 + (s + 1) * Math.pow(x - 1, 3) + s * Math.pow(x - 1, 2); };+const hash = i => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };+// seeded stream for one element, the same every frame: const r = rnd('tree' + i); r() → 0..1+function rnd(key) { let h = 2166136261; for (const c of String(key)) h = Math.imul(h ^ c.charCodeAt(0), 16777619); let s = h >>> 0 || 1; return () => (s = Math.imul(s ^ (s >>> 15), 2246822519) >>> 0, s = (s ^ (s >>> 13)) >>> 0, (s % 1000003) / 1000003); }+const bpOf = t => (t - OFF) / BEAT;+// Seeded by the boil frame, so linework "boils" at BOIL fps like hand-drawn animation.+const jit = a => (random() * 2 - 1) * a;+// Each boil drawing holds for several frames, so whatever isn't moving must draw the same until the next one. But a moving+// thing uses a different amount of randomness each frame, which shifts the stream for everything drawn after it and makes+// that re-boil every frame (jitter). boilSeed(key) restarts the stream from the boil frame and a key (any string or+// number) that's the same every frame: call it before each separate element. The cast does this for itself and its parts.+let BOILN = 0, CAST_N = 0;+const boilSeed = key => { let h = 2166136261; for (const c of key + '|' + BOILN) h = Math.imul(h ^ c.charCodeAt(0), 16777619); randomSeed(h >>> 0); };++// ---------- timing helpers (everything is a pure function of t; no state survives between frames) ----------+const seg = (t, a, b) => clamp((t - a) / (b - a)); // 0..1 progress of t through [a, b]+const frac = x => x - Math.floor(x);+const beatN = t => Math.floor(bpOf(t)); // integer beat index+const pulse = (t, k = 6) => Math.exp(-frac(bpOf(t)) * k); // 1 exactly on each beat, decays after+const pulse2 = (t, k = 6) => Math.exp(-frac(bpOf(t) * 2) * k); // same on eighth notes+const wob = (t, f = 1, ph = 0) => Math.sin((t * f + ph) * TAU);+const easeIn = x => Math.pow(clamp(x), 3);+const elasticOut = x => { x = clamp(x); return x === 0 || x === 1 ? x : Math.pow(2, -10 * x) * Math.sin((x * 10 - .75) * (TAU / 3)) + 1; };+// keyframes: kf(t, [[t0, v0], [t1, v1], ...], easeFn). Values may be numbers or arrays of numbers.+function kf(t, keys, e = ease) {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) {+ if (t < keys[i][0]) {+ const [a, va] = keys[i - 1], [b, vb] = keys[i], k = e((t - a) / (b - a));+ return Array.isArray(va) ? va.map((v, j) => lerp(v, vb[j], k)) : lerp(va, vb, k);+ }+ }+ return keys[keys.length - 1][1];+}+// hex color mix+function mixCol(a, b, k) {+ const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16), c = i => Math.round(lerp((pa >> i) & 255, (pb >> i) & 255, clamp(k)));+ return '#' + ((1 << 24) + (c(16) << 16) + (c(8) << 8) + c(0)).toString(16).slice(1);+}+// small deterministic camera shake, changes at 24 fps+const shakeXY = (t, amt) => { const f = Math.floor(t * 24); return [(hash(f * 1.7) - .5) * 2 * amt, (hash(f * 2.3 + 9) - .5) * 2 * amt]; };++// ---------- motion principles, as pure functions of t ----------+// Damped spring kicked at t0: 0 before, then a wobble that dies away (settles, jiggles, hair after a landing).+const spring = (t, t0, k = 6, w = 18) => t < t0 ? 0 : Math.exp(-k * (t - t0)) * Math.sin(w * (t - t0));+const ring = (t, evs, k = 6, w = 18) => evs.reduce((s, e) => s + spring(t, e, k, w), 0); // one kick per event time+// Hold each drawing for two frames (12 drawings a second), like hand-drawn animation "on twos". Wrap a shot's t in it.+const onTwos = t => Math.floor(t * 12 + 1e-6) / 12;+const onStep = (t, n) => Math.floor(t * n + 1e-6) / n;+// Point on a thrown or jumping arc from p0 to p1, peaking h px above the straight line; k = 0..1 along the flight.+const arcPt = (p0, p1, h, k) => [lerp(p0[0], p1[0], k), lerp(p0[1], p1[1], k) - h * 4 * k * (1 - k)];+// A hop that takes off at t0 and lands at t1, h body units high: crouch (anticipation), stretch on takeoff,+// round at the top, squash on landing and spring back. Returns { dy, sq } to add into a character's pose.+function jump(t, t0, t1, h = 3) {+ if (t < t0 - .16) return { dy: 0, sq: 0 };+ if (t < t0) return { dy: 0, sq: .2 * ease(seg(t, t0 - .16, t0)) };+ if (t < t1) { const k = (t - t0) / (t1 - t0); return { dy: -h * 4 * k * (1 - k), sq: -.16 * Math.abs(1 - 2 * k) }; }+ const a = t - t1; return { dy: 0, sq: .24 * Math.exp(-8 * a) * Math.cos(20 * a) };+}+// A surprise "take" peaking at t0: a quick squash, then a big stretch up that springs back. amt scales it.+function take(t, t0, amt = 1) {+ if (t < t0 - .1) return { sq: 0, dy: 0 };+ if (t < t0) return { sq: .12 * amt * ease(seg(t, t0 - .1, t0)), dy: 0 };+ const a = t - t0; return { sq: -.26 * amt * Math.exp(-6 * a) * Math.cos(16 * a), dy: -1.2 * amt * Math.exp(-7 * a) * Math.max(0, Math.cos(9 * a)) };+}+// Walk from x0 to x1 (px) between t0 and t1 for a character of unit u, taking steps of `stride` u: eases in and out,+// faces the way it's going, and faces front when it stops. Returns { x, walk, view, flip, dy } for the cast.+function stroll(t, t0, t1, x0, x1, u, stride = 3, view = 'side') {+ const x = lerp(x0, x1, ease(seg(t, t0, t1))), d = Math.abs(x - x0) / (stride * u), moving = t > t0 && t < t1;+ return { x, walk: moving ? d : null, view: moving ? view : 'front', flip: x1 < x0, dy: moving ? -Math.abs(Math.sin(d * Math.PI)) * .35 : 0 };+}++// ---------- camera ----------+// camBegin(cx, cy, zoom, rot): world point (cx, cy) lands at screen centre. Letters queued while a camera is+// active are placed through it automatically (pass {screen:true} to opt out). One level only: always pair with camEnd().+// LAST_CAM stays set after camEnd(), until the next frame: renderSheet's crops that follow a world point use it.+let CAM = null, LAST_CAM = null;+function camBegin(cx = W / 2, cy = H / 2, zoom = 1, rot = 0) { push(); translate(W / 2, H / 2); rotate(rot); scale(zoom); translate(-cx, -cy); CAM = LAST_CAM = { cx, cy, zoom, rot }; }+function camEnd() { pop(); CAM = null; }+function toScreen(x, y, cam = CAM) {+ if (!cam) return [x, y];+ const c = Math.cos(cam.rot), s = Math.sin(cam.rot), dx = (x - cam.cx) * cam.zoom, dy = (y - cam.cy) * cam.zoom;+ return [W / 2 + dx * c - dy * s, H / 2 + dx * s + dy * c];+}++// ---------- full-frame effects (call outside a camera, in screen space) ----------+function flash(k, col = PAL.cream) { if (k > .01) paint(rectPts(-60, -60, W + 120, H + 120), { wash: col, washOp: 255 * clamp(k), ink: null }); }+// Light: glow(x, y, r, col, a) ADDS a soft halo of light (sun, lamp, fireflies, magic). p5.brush mixes colour like+// pigment, so light can't be painted; this is the one non-crayon mark in the kit. It lands on what's drawn so far,+// under anything drawn after it, and follows the camera. On cream paper it shows only as a gentle warm bloom.+function glow(x, y, r, col = '#FFD98A', a = 1) {+ if (a <= 0 || r < 1) return;+ flushBrush();+ const c = color(col), rr = r * (1 + jit(.03));+ push(); blendMode(ADD); tint(red(c), green(c), blue(c), 150 * clamp(a)); image(glowTex, x - rr, y - rr, 2 * rr, 2 * rr); noTint(); blendMode(BLEND); pop();+}+function makeGlowTex() {+ const g = createGraphics(256, 256); g.pixelDensity(1); const c = g.drawingContext, gr = c.createRadialGradient(128, 128, 0, 128, 128, 128);+ [[0, 1], [.18, .8], [.45, .32], [.75, .08], [1, 0]].forEach(([s, a]) => gr.addColorStop(s, `rgba(255,255,255,${a})`));+ c.fillStyle = gr; c.fillRect(0, 0, 256, 256);+ return g;+}+// Paint everything OUTSIDE a star-shaped hole (irises, keyholes, heart-shaped reveals).+function irisShape(pts, col = PAL.ink, far = 4000) {+ const n = pts.length; let cx = 0, cy = 0; for (const p of pts) { cx += p[0]; cy += p[1]; } cx /= n; cy /= n;+ const out = p => { const dx = p[0] - cx, dy = p[1] - cy, d = Math.hypot(dx, dy) || 1; return [cx + dx / d * far, cy + dy / d * far]; };+ for (let i = 0; i < n; i++) {+ const a = pts[i], b = pts[(i + 1) % n], ex = (b[0] - a[0]) * .06, ey = (b[1] - a[1]) * .06;+ const a2 = [a[0] - ex, a[1] - ey], b2 = [b[0] + ex, b[1] + ey];+ paint([a2, b2, out(b2), out(a2)], { wash: col, washOp: 255, ink: null });+ }+}+function iris(cx, cy, r, col = PAL.ink) { if (r < 4) paint(rectPts(-60, -60, W + 120, H + 120), { wash: col, ink: null }); else irisShape(ellPts(cx, cy, r, r, 40), col); }++let T = 0, paperG = null, glowTex = null, letG = null, outC = null, outX = null;+let LETTERS = [];++// ---------- geometry ----------+function rectPts(x, y, w, h, j = 0) {+ return [[x + jit(j), y + jit(j)], [x + w / 2 + jit(j), y + jit(j) * .5], [x + w + jit(j), y + jit(j)],+ [x + w + jit(j) * .5, y + h / 2], [x + w + jit(j), y + h + jit(j)], [x + w / 2 + jit(j), y + h + jit(j) * .5],+ [x + jit(j), y + h + jit(j)], [x + jit(j) * .5, y + h / 2]];+}+function ellPts(cx, cy, rx, ry, n = 28, j = 0, rot = 0) {+ const p = []; for (let i = 0; i < n; i++) { const a = rot + i / n * TAU; p.push([cx + Math.cos(a) * rx + jit(j), cy + Math.sin(a) * ry + jit(j)]); } return p;+}+function rrPts(x, y, w, h, r, j = 0) {+ const p = [], seg = 5, corner = (cx, cy, a0) => { for (let i = 0; i <= seg; i++) { const a = a0 + i / seg * Math.PI / 2; p.push([cx + Math.cos(a) * r + jit(j), cy + Math.sin(a) * r + jit(j)]); } };+ corner(x + w - r, y + r, -Math.PI / 2); corner(x + w - r, y + h - r, 0); corner(x + r, y + h - r, Math.PI / 2); corner(x + r, y + r, Math.PI);+ return p;+}+function starPts(cx, cy, r, inner = .38, n = 4, rot = -Math.PI / 2) {+ const p = []; for (let i = 0; i < n * 2; i++) { const a = rot + i * Math.PI / n, q = i % 2 ? r * inner : r; p.push([cx + Math.cos(a) * q, cy + Math.sin(a) * q]); } return p;+}+function heartPts(cx, cy, r, n = 22) {+ const p = []; for (let i = 0; i < n; i++) { const a = i / n * TAU, x = 16 * Math.pow(Math.sin(a), 3), y = 13 * Math.cos(a) - 5 * Math.cos(2 * a) - 2 * Math.cos(3 * a) - Math.cos(4 * a); p.push([cx + x * r / 16, cy - y * r / 16]); }+ return p;+}+// Smooth curve through the points (Catmull-Rom), n samples per span.+function through(P, n = 6) {+ if (P.length < 3) return P.slice();+ const out = [];+ for (let i = 0; i < P.length - 1; i++) {+ const p0 = P[Math.max(0, i - 1)], p1 = P[i], p2 = P[i + 1], p3 = P[Math.min(P.length - 1, i + 2)];+ for (let k = 0; k < n; k++) {+ const u = k / n, u2 = u * u, u3 = u2 * u;+ out.push([0, 1].map(d => .5 * (2 * p1[d] + (p2[d] - p0[d]) * u + (2 * p0[d] - 5 * p1[d] + 4 * p2[d] - p3[d]) * u2 + (3 * p1[d] - p0[d] - 3 * p2[d] + p3[d]) * u3)));+ }+ }+ out.push(P[P.length - 1]);+ return out;+}+// Tapered ribbon around a path (w0 wide at the start, w1 at the end), as one closed outline.+// Limbs, tails, scarves, stems: one shape with one outline, so nothing looks glued on.+function ribbon(P, w0, w1 = w0) {+ const C = through(P), n = C.length, L = [], R = [];+ for (let i = 0; i < n; i++) {+ 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], d = Math.hypot(dx, dy) || 1, w = lerp(w0, w1, i / Math.max(1, n - 1)) / 2;+ L.push([C[i][0] - dy / d * w, C[i][1] + dx / d * w]); R.push([C[i][0] + dy / d * w, C[i][1] - dx / d * w]);+ }+ return L.concat(R.reverse());+}++// ---------- paint wrapper ----------+// One call = one shape: optional flat wash, optional watercolour-style fill, optional hatch, optional outline.+// It's the low-level primitive; the crayon look is built on it in crayon.js (colorIn, scribbleFill, hatchFill …).+// p5.brush 2.2.3 loses strokes drawn far from the origin under a zoomed camera, so every shape and line is drawn+// around its own centre.+function centred(pts, draw) {+ if (!pts.length) return;+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;+ for (const [x, y] of pts) { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }+ const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;+ push(); translate(cx, cy); draw(pts.map(([x, y]) => [x - cx, y - cy])); pop();+}+function paint(pts, o = {}) { centred(pts, (P) => paintAt(P, o)); }+function paintAt(pts, o) {+ if (o.wash || o.fill || o.hatch) {+ if (o.wash) brush.wash(o.wash, o.washOp ?? 255); else brush.noWash();+ if (o.fill) { brush.fill(o.fill, o.fillOp ?? 170); brush.fillBleed(o.bleed ?? .1); brush.fillTexture(o.tex ?? .4, o.border ?? .35); } else brush.noFill();+ if (o.hatch) { brush.hatch(o.hatch.d, o.hatch.a, o.hatch.o || { rand: .15 }); brush.hatchStyle(o.hatch.b || 'cpen', o.hatch.c || PAL.ink, o.hatch.w || 1); } else brush.noHatch();+ brush.noStroke();+ if (o.curv) { brush.beginShape(o.curv); for (const p of pts) brush.vertex(p[0], p[1]); brush.endShape(true); }+ else brush.polygon(pts);+ }+ if (o.ink !== null) {+ brush.noWash(); brush.noFill(); brush.noHatch(); brush.set(o.br || 'cpen', o.ink || PAL.ink, o.sw ?? 1);+ brush.beginShape(o.curv || 0); for (const p of pts) brush.vertex(p[0], p[1]); brush.endShape(true);+ }+}+// An open line. The default brush is the coloured pencil ('cpen'); see crayon.js for the others.+function inkLine(pts, sw = 1, col = PAL.ink, br = 'cpen', curv = .5) {+ if (pts.length < 2) return;+ centred(pts, (P) => { brush.noFill(); brush.noWash(); brush.noHatch(); brush.set(br, col, sw); brush.spline(P, curv); });+}++// ---------- lettering in the scene (drawn on the 2D compositor, under the paper finish) ----------+// For a word that belongs IN the picture (a shop sign, a name on a mailbox). Captions go through captions() instead.+const HAND_FONT = '"LXGW WenKai TC", "Zen Maru Gothic", "Noto Serif TC", "Kaiti TC", serif';+function letter(txt, x, y, size, color, o = {}) {+ if (CAM && !o.screen) { [x, y] = toScreen(x, y); size *= CAM.zoom; o = { ...o, rot: (o.rot || 0) + CAM.rot }; }+ LETTERS.push({ txt, x, y, size, color, ...o });+}+// Comic sound effect: pops in at age 0, wobbles, fades by `life` seconds.+function sfx(txt, x, y, size, color, age, o = {}) {+ const life = o.life ?? 1.2; if (age < 0 || age > life) return;+ letter(txt, x, y, size, color, { pop: age * 5, rot: (o.rot ?? -.08) + Math.sin(age * 20) * .03 * (1 - age / life), alpha: 1 - seg(age, life - .25, life), ...o });+}+function drawLetters(c) {+ for (const L of LETTERS) {+ const k = L.pop != null ? backOut(L.pop) : 1; if (k <= .01) continue;+ c.save(); c.translate(L.x, L.y); c.rotate(L.rot || 0); c.scale(k, k); c.globalAlpha = L.alpha ?? 1;+ c.font = L.font || `700 ${L.size}px ${HAND_FONT}`;+ c.textAlign = L.align || 'center'; c.textBaseline = 'middle';+ if (L.stroke) { c.lineJoin = 'round'; c.lineWidth = L.size * .12; c.strokeStyle = L.stroke; c.strokeText(L.txt, 0, 0); }+ c.fillStyle = L.color; c.fillText(L.txt, 0, 0);+ c.restore();+ }+}++// p5.brush defers washes and strokes into a mask layer; a (tiny, off-screen) fill forces it to composite now, so+// everything drawn before this call really lands under whatever p5 draws next (letters, glow, snapshots).+function flushBrush() {+ push(); resetMatrix(); translate(-W / 2, -H / 2);+ brush.noStroke(); brush.noHatch(); brush.noWash(); brush.fill('#000000', 1); brush.fillBleed(0); brush.fillTexture(0, 0);+ brush.polygon([[-50, -50], [-40, -50], [-40, -40]]); brush.noFill(); pop();+}+// Paint the queued lettering into the scene itself, so later layers (wipes) cover it. drawWorld calls this after each shot.+function flushLetters() {+ if (!LETTERS.length) return;+ letG.clear(); drawLetters(letG.drawingContext); LETTERS = [];+ flushBrush();+ push(); resetMatrix(); translate(-W / 2, -H / 2); image(letG, 0, 0); pop();+}+// Wipe the canvas back to blank paper (used between the two pages of a page turn).+function clearToPaper() { flushBrush(); push(); resetMatrix(); translate(-W / 2, -H / 2); image(paperG, 0, 0); pop(); }++// ---------- frame ----------+async function setup() {+ createCanvas(W, H, WEBGL); pixelDensity(1); noLoop();+ brush.scaleBrushes(5); defineBrushes(); // crayon.js+ lookSetup(); // crayon.js: paper, tooth, grain, page textures (cached)+ glowTex = makeGlowTex(); letG = createGraphics(W, H); letG.pixelDensity(1);+ outC = document.getElementById('out'); outX = outC.getContext('2d');+ await Promise.all([document.fonts.load(`700 80px ${HAND_FONT}`, '從前有一隻小刺蝟 Once upon a time'), ...(window.EXTRA_FONTS || []).map(([f, txt]) => document.fonts.load(f, txt))]);+ window.ready = true;+ if (!location.search.includes('render')) devUI();+}+function draw() {+ if (!window.ready) return;+ LETTERS = []; CAM = LAST_CAM = null; stageReset();+ push(); translate(-W / 2, -H / 2);+ BOILN = Math.floor(T * BOIL + 1e-6); CAST_N = 0; boilSeed('frame'); noiseSeed(77);+ image(paperG, 0, 0);+ drawWorld(T);+ pop();+}+function composite(t) {+ const c = outX;+ c.globalCompositeOperation = 'source-over'; c.globalAlpha = 1;+ finishPage(c, drawingContext.canvas, t); // crayon.js: tooth, grain, vignette, page border+ if (STAGE.turn) pageTurnComposite(c, STAGE.turn, t); // crayon.js: the previous page curling away+ drawLetters(c);+ c.globalCompositeOperation = 'source-over'; c.globalAlpha = 1;+ if (window.overlayHook && !window.LOOP) window.overlayHook(c, t); // crisp 2D overlay on top (captions: see captions() in crayon.js)+}+window.renderAt = async (t, type = 'image/png', q = .92) => { T = t; await redraw(); composite(t); return outC.toDataURL(type, q); };+// Contact sheet of several times, for visual checks: returns { url, ms[] }. crop = [x, y, w, h] fills each cell with just+// that region of the frame, at full resolution. at = [x, y, w, h] instead crops w × h around the WORLD point (x, y),+// wherever each frame's camera put it; x and y may be expressions evaluated in the page.+window.renderSheet = async (times, cols = 3, w = 640, crop = null, at = null) => {+ if (at) at = at.map((v) => typeof v === 'string' ? (0, eval)(v) : v);+ const [, , cw, ch] = at || crop || [0, 0, W, H], h = Math.round(w * ch / cw), rows = Math.ceil(times.length / cols), sc = document.createElement('canvas');+ sc.width = cols * w; sc.height = rows * h; const c = sc.getContext('2d'), ms = [];+ for (let i = 0; i < times.length; i++) {+ const t0 = performance.now(); T = times[i]; await redraw(); composite(times[i]); ms.push(Math.round(performance.now() - t0));+ const x = (i % cols) * w, y = Math.floor(i / cols) * h;+ const [cx, cy] = at ? toScreen(at[0], at[1], LAST_CAM).map((v, j) => v - (j ? ch : cw) / 2) : crop || [0, 0];+ c.drawImage(outC, cx, cy, cw, ch, x, y, w, h); c.fillStyle = 'rgba(0,0,0,.65)'; c.fillRect(x, y, 84, 24); c.fillStyle = '#fff'; c.font = '15px sans-serif'; c.fillText(times[i].toFixed(2) + 's', x + 6, y + 17);+ }+ return { url: sc.toDataURL('image/jpeg', .9), ms };+};+window.gpuInfo = () => { const gl = drawingContext, e = gl.getExtension('WEBGL_debug_renderer_info'); return e ? gl.getParameter(e.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER); };++function devUI() {+ const s = document.getElementById('scrub'), lab = document.getElementById('tt'); s.max = window.LOOP ? window.LOOP.len : DUR;+ let busy = false, want = null;+ const go = async () => { if (busy) return; busy = true; while (want != null) { const t = want; want = null; const t0 = performance.now(); await window.renderAt(t); lab.textContent = `${t.toFixed(2)}s · ${Math.round(performance.now() - t0)} ms/frame`; } busy = false; };+ s.addEventListener('input', () => { want = +s.value; go(); });+ want = +(new URLSearchParams(location.search).get('t') || 0); s.value = want; go();+}diff --git a/.claude/skills/crayon-storybook/template/src/crayon.js b/.claude/skills/crayon-storybook/template/src/crayon.jsnew file mode 100644index 0000000..90aead0--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/crayon.js@@ -0,0 +1,466 @@+// crayon.js: the CRAYON-STORYBOOK look. Brushes (crayon, coloured pencil, pastel, graphite), fills (scribble, hatch,+// cross-hatch, smudge), the paper and its tooth, the page finish (grain, vignette, picture-book border), the page turn,+// scenery and props, emotes and storybook captions.+//+// How the crayon look is made:+// 1. Shapes are coloured in: a pale flat base (so a character is opaque), then directional crayon scribble or hatching+// on top in the full colour, then a coloured-pencil outline (colorIn).+// 2. Everything is drawn on cream paper (paperG) and, after the frame is drawn, the paper's TOOTH is laid over it: a+// fixed speckle mask in the paper colour. Where the paper has a pit, pigment skips, exactly like wax crayon on+// drawing paper. Pure paper is unchanged (paper over paper), so only drawn marks break up. The tooth is the same+// pattern everywhere, so every stroke breaks consistently; it shifts a little with each boil drawing (PROJECT.toothBoil,+// default on) so a moving camera doesn't "swim" through a fixed texture.+// 3. Linework boils at 8 drawings/s (BOIL in core.js) through boilSeed(), like frames re-drawn by hand.+// Textures (paper, tooth, grain, vignette) are built once in lookSetup() and only blitted per frame.++// ---------- brushes ----------+// Names: 'crayon' (wide, waxy), 'crayonFine' (crayon for details and small lines), 'cpen' (coloured pencil: thin,+// grainy — the default outline), 'pastel' (soft, powdery), 'graphite' (sketch), 'chalk' (dry, broken, bigger than pastel).+// p5.brush built-ins still work: '2B', 'HB', 'charcoal', 'cpencil', 'marker', 'spray' …+function defineBrushes() {+ brush.add('crayon', { type: 'default', weight: 8, scatter: .7, sharpness: .45, grain: 5, opacity: 150, spacing: .22, pressure: [1.05, .95], rotate: 'natural', noise: .35 });+ brush.add('crayonFine', { type: 'default', weight: 4.2, scatter: .4, sharpness: .55, grain: 7, opacity: 165, spacing: .2, pressure: [1.1, .9], rotate: 'natural', noise: .3 });+ brush.add('cpen', { type: 'default', weight: 3.0, scatter: .35, sharpness: .7, grain: 9, opacity: 205, spacing: .15, pressure: [1.15, .8], rotate: 'natural', noise: .2 });+ brush.add('pastel', { type: 'default', weight: 20, scatter: 3, sharpness: .12, grain: 3, opacity: 60, spacing: .35, pressure: [1, .8], rotate: 'random', noise: .5 });+ brush.add('chalk', { type: 'default', weight: 12, scatter: 1.6, sharpness: .25, grain: 2.5, opacity: 120, spacing: .28, pressure: [1, .85], rotate: 'random', noise: .5 });+ brush.add('graphite', { type: 'default', weight: 1.8, scatter: .3, sharpness: .6, grain: 22, opacity: 150, spacing: .15, pressure: [1.2, .7], rotate: 'natural', noise: .3 });+}++// ---------- lines ----------+const pencilLine = (pts, sw = 1, col = PAL.ink, curv = .5) => inkLine(pts, sw, col, 'cpen', curv);+const crayonLine = (pts, sw = 1, col = PAL.ink, curv = .5) => inkLine(pts, sw, col, sw < .7 ? 'crayonFine' : 'crayon', curv);+const pastelLine = (pts, sw = 1, col = PAL.rose, curv = .5) => inkLine(pts, sw, col, 'pastel', curv);+const sketchLine = (pts, sw = 1, col = PAL.inkSoft, curv = .5) => inkLine(pts, sw, col, 'graphite', curv);++// ---------- fills ----------+// Scanlines through a polygon at angle `ang` (radians), `gap` px apart → rows of [x0, x1] segments in rotated space.+function scanRows(pts, ang, gap, off = .5) {+ const c = Math.cos(-ang), s = Math.sin(-ang), R = pts.map(([x, y]) => [x * c - y * s, x * s + y * c]);+ let y0 = Infinity, y1 = -Infinity; for (const p of R) { if (p[1] < y0) y0 = p[1]; if (p[1] > y1) y1 = p[1]; }+ const rows = [], n = R.length;+ for (let y = y0 + gap * off; y < y1; y += gap) {+ const xs = [];+ for (let i = 0; i < n; i++) {+ const a = R[i], b = R[(i + 1) % n];+ if ((a[1] <= y) !== (b[1] <= y)) xs.push(a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0]));+ }+ xs.sort((p, q) => p - q);+ const segs = []; for (let i = 0; i + 1 < xs.length; i += 2) if (xs[i + 1] - xs[i] > 1) segs.push([xs[i], xs[i + 1]]);+ rows.push({ y, segs });+ }+ return { rows, back: (x, y) => [x * c + y * s, -x * s + y * c] };+}+// Scribble fill: back-and-forth crayon zigzags inside the shape, the way a child (or an illustrator) colours in.+// o.ang direction of the strokes in radians (default ~ -0.5, a comfortable right-handed diagonal)+// o.gap px between passes (smaller = denser; default 11) o.w brush weight (default 1)+// o.br brush (default 'crayon') o.op colour opacity is in the brush; use a paler col+// o.over px the turns overshoot (+) or stop short (-) of the edge (default 1: a tiny, natural overshoot)+// o.loose 0..1 how wobbly the turns are (default .35) o.run rows per stroke before lifting (default 7)+function scribbleFill(pts, col, o = {}) {+ if (pts.length < 3) return;+ centred(pts, P => {+ const gap = o.gap ?? 13, ang = o.ang ?? -.5, over = o.over ?? 1, loose = o.loose ?? .35, run = o.run ?? 7;+ const { rows, back } = scanRows(P, ang + jit(.03), gap, .35 + random() * .3);+ // chain each row's segments to an overlapping segment of the row before, so a zigzag follows the shape+ const chains = [];+ let open = [];+ for (const r of rows) {+ const next = [];+ for (const s of r.segs) {+ const ch = open.find(c => !c.used && c.last[0] < s[1] && c.last[1] > s[0] && c.rows.length < run);+ if (ch) { ch.used = true; ch.rows.push([r.y, s]); ch.last = s; next.push(ch); }+ else { const c = { rows: [[r.y, s]], last: s }; chains.push(c); next.push(c); }+ }+ next.forEach(c => c.used = false); open = next;+ }+ brush.noFill(); brush.noWash(); brush.noHatch(); brush.set(o.br || 'crayon', col, o.w ?? 1);+ for (const c of chains) {+ const Q = [];+ c.rows.forEach(([y, [a, b]], k) => {+ const len = b - a, inA = Math.min(len * .3, -over + jit(gap * loose)), inB = Math.min(len * .3, -over + jit(gap * loose));+ const ya = y + jit(gap * .18), yb = y + jit(gap * .18);+ const mid = back((a + b) / 2 + jit(len * .08), (ya + yb) / 2 + jit(gap * .35));+ if (k % 2 === 0) Q.push(back(a + inA, ya), mid, back(b - inB, yb)); else Q.push(back(b - inB, yb), mid, back(a + inA, ya));+ });+ brush.spline(Q, .4);+ }+ });+}+// Hatch fill: parallel strokes (p5.brush's hatch, clipped to the shape). cross: true adds a second direction.+// o.ang (radians, default .6), o.gap (default 12), o.br ('crayonFine'), o.w (1), o.rand (.25), o.grad (0: even; up to 1 fades)+function hatchFill(pts, col, o = {}) {+ const one = (a) => paint(pts, { hatch: { d: o.gap ?? 12, a, o: { rand: o.rand ?? .25, gradient: o.grad || false }, b: o.br || 'crayonFine', c: col, w: o.w ?? 1 }, ink: null });+ one(o.ang ?? .6);+ if (o.cross) one((o.ang ?? .6) + (o.crossAng ?? 1.25));+}+const crossHatch = (pts, col, o = {}) => hatchFill(pts, col, { ...o, cross: true });+// Smudge: soft, powdery pastel colour with no hard edge (skies, cheeks, shadows, glows on paper, distant hills).+// o.op (default 110), o.tex (default .55), o.bleed (default .12)+function smudge(pts, col, o = {}) {+ paint(pts, { fill: col, fillOp: o.op ?? 110, bleed: o.bleed ?? .12, tex: o.tex ?? .55, border: o.border ?? .08, ink: null });+}+// The workhorse: colour a shape in, picture-book style.+// col the colour (crayon strokes use it; the base under them is a paler version)+// fill 'scribble' (default) | 'hatch' | 'cross' | 'smudge' | 'flat' | 'none'+// pale how much paler the base is (0 = same as col, default .45); base: an explicit base colour; baseOp (255)+// tone stroke colour (default: col, a touch deeper) ang, gap, w, br, over, loose: passed to the fill+// line outline colour (default: a deep tint of col; null = no outline) lw: outline weight (default 1)+// lbr outline brush (default 'cpen') curv: 0..1 smooth the outline through the points+// shade { pts, col, ang, gap }: an extra scribble pass (a shadow side), drawn over the fill+function colorIn(pts, o = {}) {+ if (pts.length < 3) return;+ const col = o.col || PAL.butter, base = o.base || mixCol(col, PAL.paper, o.pale ?? .6);+ const fill = o.fill || 'scribble', tone = o.tone || col;+ if (fill !== 'none') paint(pts, { wash: base, washOp: o.baseOp ?? 255, ink: null, curv: o.curv });+ if (fill === 'scribble') scribbleFill(pts, tone, o);+ else if (fill === 'hatch') hatchFill(pts, tone, o);+ else if (fill === 'cross') hatchFill(pts, tone, { ...o, cross: true });+ else if (fill === 'smudge') smudge(pts, tone, o);+ if (o.shade) scribbleFill(o.shade.pts, o.shade.col || mixCol(col, PAL.ink, .3), { ang: o.shade.ang ?? (o.ang ?? -.5) + .5, gap: o.shade.gap ?? 9, br: 'crayonFine', w: .9 });+ const line = o.line === undefined ? mixCol(col, PAL.ink, .72) : o.line;+ if (line) paint(pts, { ink: line, sw: o.lw ?? 1, br: o.lbr || 'cpen', curv: o.curv });+}+// A round dab of colour (cheeks, dots, berries, polka dots): a little crayon spiral.+function dab(x, y, r, col, w = .8) {+ const P = []; for (let a = 0; a < TAU * 2.3; a += .5) { const q = r * (.2 + .8 * a / (TAU * 2.3)); P.push([x + Math.cos(a) * q + jit(r * .08), y + Math.sin(a) * q * .9 + jit(r * .08)]); }+ inkLine(P, w, col, 'crayonFine', .5);+}++// ---------- paper, tooth, grain ----------+function lcg(seed) { let s = seed; return () => (s = (s * 16807) % 2147483647) / 2147483647; }+let toothC = null, grainC = null, pageA = null, pageAX = null, TOOTH_PAD = 96;+function lookSetup() {+ paperG = makePaper(); toothC = makeTooth(); grainC = makeGrain();+ pageA = document.createElement('canvas'); pageA.width = W; pageA.height = H; pageAX = pageA.getContext('2d');+}+function makePaper() {+ const g = createGraphics(W, H); g.pixelDensity(1); const c = g.drawingContext, r = lcg(11);+ c.fillStyle = PAL.paper; c.fillRect(0, 0, W, H);+ // soft uneven warmth, like real drawing paper under a lamp+ for (let i = 0; i < 60; i++) { const x = r() * W, y = r() * H, rr = 140 + r() * 420, gr = c.createRadialGradient(x, y, 0, x, y, rr), a = .035 * r(); gr.addColorStop(0, `rgba(190,150,100,${a})`); gr.addColorStop(1, 'rgba(190,150,100,0)'); c.fillStyle = gr; c.fillRect(x - rr, y - rr, 2 * rr, 2 * rr); }+ // fibres+ c.lineWidth = 1;+ for (let i = 0; i < 1600; i++) { const x = r() * W, y = r() * H, l = 5 + r() * 20, a = r() * TAU; c.strokeStyle = `rgba(140,110,80,${.03 + r() * .05})`; c.beginPath(); c.moveTo(x, y); c.quadraticCurveTo(x + Math.cos(a + .6) * l * .5, y + Math.sin(a + .6) * l * .5, x + Math.cos(a) * l, y + Math.sin(a) * l); c.stroke(); }+ return g;+}+// value noise on a lattice, bilinear+function noiseField(w, h, cell, r) {+ const gw = Math.ceil(w / cell) + 2, gh = Math.ceil(h / cell) + 2, g = new Float32Array(gw * gh); for (let i = 0; i < g.length; i++) g[i] = r();+ return (x, y) => { const fx = x / cell, fy = y / cell, ix = fx | 0, iy = fy | 0, tx = fx - ix, ty = fy - iy, sx = tx * tx * (3 - 2 * tx), sy = ty * ty * (3 - 2 * ty), i = iy * gw + ix;+ return lerp(lerp(g[i], g[i + 1], sx), lerp(g[i + gw], g[i + gw + 1], sx), sy); };+}+// The tooth: paper-coloured speckles whose alpha is how deep the pit is. Laid over the drawn frame, pigment skips there.+function makeTooth() {+ const TW = W + TOOTH_PAD, TH = H + TOOTH_PAD, cv = document.createElement('canvas'); cv.width = TW; cv.height = TH;+ const c = cv.getContext('2d'), id = c.createImageData(TW, TH), d = id.data, r = lcg(7);+ const n1 = noiseField(TW, TH, 2.3, r), n2 = noiseField(TW, TH, 6.5, r), n3 = noiseField(TW, TH, 38, r);+ const pc = parseInt(PAL.paper.slice(1), 16), pr = (pc >> 16) & 255, pg = (pc >> 8) & 255, pb = pc & 255;+ for (let y = 0, i = 0; y < TH; y++) for (let x = 0; x < TW; x++, i += 4) {+ // fine pits + a medium weave + large patches where the paper is rougher (crayon breaks more there)+ const v = .55 * n1(x, y * 1.35) + .3 * n2(x * 1.2, y) + .15 * r() + .12 * (n3(x, y) - .5);+ const a = clamp((v - .5) / .22);+ d[i] = pr + 4; d[i + 1] = pg + 3; d[i + 2] = pb + 2; d[i + 3] = 255 * a * a * .92;+ }+ c.putImageData(id, 0, 0);+ return cv;+}+// Static grain multiplied over the frame, so pigment sits "in" the paper.+function makeGrain() {+ const cv = document.createElement('canvas'); cv.width = W; cv.height = H; const c = cv.getContext('2d'), r = lcg(5);+ const id = c.createImageData(W, H), d = id.data;+ for (let i = 0; i < d.length; i += 4) { const v = 255 - (r() < .5 ? r() * r() * 26 : 0); d[i] = v; d[i + 1] = v - 1; d[i + 2] = v - 3; d[i + 3] = 255; }+ c.putImageData(id, 0, 0);+ return cv;+}++// ---------- stage: per-frame finishing options (reset every frame; set them from a shot) ----------+// vignette(k): soft warm darkening at the corners (default .3; 0 = off).+// bookPage(k, o): the picture-book framing: a cream page border around the illustration. k 0..1 (animate it in/out),+// o.m margin px (default 64), o.r corner radius (default 26), o.line: draw the pencil frame line (default true).+// tooth(k): how strongly the paper tooth breaks the crayon (default 1).+let STAGE = {};+function stageReset() { STAGE = { vig: .3, page: 0, pageM: 64, pageR: 26, pageLine: true, tooth: 1, turn: null }; }+stageReset();+const vignette = k => { STAGE.vig = k; };+const bookPage = (k = 1, o = {}) => { STAGE.page = clamp(k); STAGE.pageM = o.m ?? 64; STAGE.pageR = o.r ?? 26; STAGE.pageLine = o.line ?? true; };+const tooth = k => { STAGE.tooth = k; };++// Draw a finished page into c: the drawn frame, the tooth, the grain, the vignette and the page border.+function finishPage(c, src, t, st = STAGE) {+ c.save(); c.globalCompositeOperation = 'source-over'; c.globalAlpha = 1;+ c.drawImage(src, 0, 0, W, H);+ if (st.tooth > 0) {+ const bn = PROJECT.toothBoil === false ? 0 : Math.floor(t * BOIL + 1e-6), ox = Math.floor(hash(bn * 3.7 + 1) * TOOTH_PAD), oy = Math.floor(hash(bn * 5.3 + 2) * TOOTH_PAD);+ c.globalAlpha = clamp(st.tooth); c.drawImage(toothC, -ox, -oy); c.globalAlpha = 1;+ }+ c.globalCompositeOperation = 'multiply'; c.drawImage(grainC, 0, 0);+ if (st.vig > 0) {+ const g = c.createRadialGradient(W / 2, H / 2, H * .42, W / 2, H / 2, H * 1.08);+ g.addColorStop(0, 'rgba(255,255,255,0)'); g.addColorStop(1, `rgba(150,112,82,${.55 * st.vig})`);+ c.fillStyle = g; c.fillRect(0, 0, W, H);+ }+ c.globalCompositeOperation = 'source-over';+ if (st.page > 0) pageBorder(c, st);+ c.restore();+}+function pageBorder(c, st) {+ const m = st.pageM * easeOut(st.page), r = st.pageR, x0 = m, y0 = m * .85, x1 = W - m, y1 = H - m * .85;+ c.save();+ c.beginPath(); c.rect(-10, -10, W + 20, H + 20); c.roundRect(x0, y0, x1 - x0, y1 - y0, r);+ c.fillStyle = PAL.paper; c.fill('evenodd');+ c.clip('evenodd'); c.drawImage(paperG.elt || paperG.canvas, 0, 0); c.restore();+ if (st.pageLine && st.page > .3) { // a hand-drawn frame line, drawn twice, slightly off (boils with the linework)+ c.save(); c.globalAlpha = .55 * seg(st.page, .3, 1); c.strokeStyle = PAL.ink; c.lineJoin = 'round';+ for (let k = 0; k < 2; k++) {+ const j = n => (hash(BOILN * 7 + n + k * 31) - .5) * 3.5, e = 5 + k * 2;+ c.lineWidth = k ? 1.4 : 2.4; c.beginPath();+ c.moveTo(x0 - e + j(1), y0 + r + j(2)); c.quadraticCurveTo(x0 - e + j(3), y0 - e + j(4), x0 + r + j(5), y0 - e + j(6));+ c.lineTo(x1 - r + j(7), y0 - e + j(8)); c.quadraticCurveTo(x1 + e + j(9), y0 - e + j(10), x1 + e + j(11), y0 + r + j(12));+ c.lineTo(x1 + e + j(13), y1 - r + j(14)); c.quadraticCurveTo(x1 + e + j(15), y1 + e + j(16), x1 - r + j(17), y1 + e + j(18));+ c.lineTo(x0 + r + j(19), y1 + e + j(20)); c.quadraticCurveTo(x0 - e + j(21), y1 + e + j(22), x0 - e + j(23), y1 - r + j(24));+ c.closePath(); c.stroke();+ }+ c.restore();+ }+}++// ---------- page turn ----------+// Registered per shot in shots(): [t, shotFn, { turn: .9 }]. The previous page is snapshotted (finished with ITS stage+// settings), then composited over the new one, curling away from the bottom-right corner with its back showing.+function snapshotPage() { flushBrush(); finishPage(pageAX, drawingContext.canvas, T, STAGE); }+function clipHalf(poly, F, n, keepPos) { // Sutherland–Hodgman against the line through F with normal n+ const out = [], s = p => ((p[0] - F[0]) * n[0] + (p[1] - F[1]) * n[1]) * (keepPos ? 1 : -1);+ for (let i = 0; i < poly.length; i++) {+ const a = poly[i], b = poly[(i + 1) % poly.length], sa = s(a), sb = s(b);+ if (sa >= 0) out.push(a);+ if ((sa >= 0) !== (sb >= 0)) { const k = sa / (sa - sb); out.push([lerp(a[0], b[0], k), lerp(a[1], b[1], k)]); }+ }+ return out;+}+function pageTurnComposite(c, turn, t) {+ const e = ease(turn.p), dir = turn.dir;+ // fold line: its bottom end leads (the corner is lifted first), its top end follows+ const xb = lerp(W + 30, -90, e), xt = xb + 420 * Math.sin(Math.PI * Math.min(1, e * 1.1)) + 40 * (1 - e);+ const mx = x => dir > 0 ? x : W - x;+ const F0 = [mx(xb), H + 30], F1 = [mx(xt), -30], dx = F1[0] - F0[0], dy = F1[1] - F0[1], L = Math.hypot(dx, dy);+ let n = [dy / L, -dx / L]; if ((mx(W + 999) - F0[0]) * n[0] + (H / 2 - F0[1]) * n[1] < 0) n = [-n[0], -n[1]]; // n points to the revealed side+ const rect = [[0, 0], [W, 0], [W, H], [0, H]], keep = clipHalf(rect, F0, n, false), gone = clipHalf(rect, F0, n, true);+ const sq = .72, refl = p => { const d = (p[0] - F0[0]) * n[0] + (p[1] - F0[1]) * n[1]; return [p[0] - (1 + sq) * d * n[0], p[1] - (1 + sq) * d * n[1]]; };+ const flap = gone.map(refl);+ const path = P => { c.beginPath(); P.forEach((p, i) => i ? c.lineTo(p[0], p[1]) : c.moveTo(p[0], p[1])); c.closePath(); };+ c.save();+ // the new page gets a soft shadow along the fold+ if (gone.length > 2) {+ path(gone); c.save(); c.clip();+ const g = c.createLinearGradient(F0[0], F0[1], F0[0] + n[0] * 140, F0[1] + n[1] * 140);+ g.addColorStop(0, 'rgba(90,60,40,.32)'); g.addColorStop(1, 'rgba(90,60,40,0)'); c.fillStyle = g; c.fillRect(0, 0, W, H); c.restore();+ }+ // the old page, what's left of it+ if (keep.length > 2) { path(keep); c.save(); c.clip(); c.drawImage(pageA, 0, 0); c.restore(); }+ // the flap: the page's back, curling over, with a drop shadow+ if (flap.length > 2) {+ c.save(); path(flap); c.shadowColor = 'rgba(70,45,30,.38)'; c.shadowBlur = 36; c.shadowOffsetX = -n[0] * 10; c.shadowOffsetY = -n[1] * 10 + 6;+ c.fillStyle = PAL.paper; c.fill(); c.restore();+ c.save(); path(flap); c.clip();+ c.drawImage(paperG.elt || paperG.canvas, 0, 0);+ // a ghost of the picture showing through the paper, mirrored+ const k = 1 + sq, M = [1 - k * n[0] * n[0], -k * n[0] * n[1], -k * n[0] * n[1], 1 - k * n[1] * n[1]], dF = F0[0] * n[0] + F0[1] * n[1];+ c.globalAlpha = .09; c.setTransform(M[0], M[1], M[2], M[3], k * dF * n[0], k * dF * n[1]); c.drawImage(pageA, 0, 0); c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1;+ // curl shading: bright along the fold, warmer towards the lifted edge+ const g = c.createLinearGradient(F0[0], F0[1], F0[0] - n[0] * 520, F0[1] - n[1] * 520);+ g.addColorStop(0, 'rgba(255,252,242,.5)'); g.addColorStop(.25, 'rgba(255,252,242,0)'); g.addColorStop(1, 'rgba(150,110,80,.22)');+ c.fillStyle = g; c.fillRect(0, 0, W, H);+ c.restore();+ c.save(); path(flap); c.strokeStyle = 'rgba(74,54,49,.45)'; c.lineWidth = 2; c.lineJoin = 'round'; c.stroke(); c.restore();+ }+ c.restore();+}++// ---------- scenery ----------+// Plain page: nothing but the paper with a whisper of colour. sky(top, bottom): a soft pastel sky, smudged and stroked.+function paperWash(t, col = PAL.skyLt) { boilSeed('paperwash'); smudge(rectPts(-100, -100, W + 200, H + 200), col, { op: 60 }); }+function sky(top = PAL.sky, bottom = PAL.cream, o = {}) {+ boilSeed('sky');+ const x0 = o.x0 ?? -400, x1 = o.x1 ?? W + 400, y0 = o.y0 ?? -300, y1 = o.y1 ?? H * .75;+ paint(rectPts(x0, y0, x1 - x0, y1 - y0), { wash: mixCol(top, bottom, .55), ink: null });+ smudge(rectPts(x0, y0, x1 - x0, (y1 - y0) * .6, 20), top, { op: 120 });+ // long, loose horizontal pastel strokes: the sky is coloured in, not printed+ for (let i = 0; i < (o.strokes ?? 9); i++) {+ const y = lerp(y0 + 60, y1 - 100, (i + .5) / (o.strokes ?? 9)) + jit(10), xa = lerp(x0, x1, hash(i + 3) * .3), xb = lerp(x0, x1, .7 + hash(i + 9) * .3);+ inkLine([[xa, y], [(xa + xb) / 2, y + jit(8)], [xb, y + jit(6)]], 1.6, mixCol(top, PAL.cream, .15 + i / 14), 'crayon', .5);+ }+}+// A crayon sun: a butter disc coloured in circles, with wobbly rays that turn slowly.+function sun(x, y, r, t = T, o = {}) {+ boilSeed('sun' + (o.key || ''));+ if (o.glow !== false) glow(x, y, r * 3.2, '#FFE2A0', .35);+ const rays = o.rays ?? 12, rot = t * .15;+ for (let i = 0; i < rays; i++) {+ const a = rot + i / rays * TAU, l = r * (i % 2 ? 1.55 : 1.8);+ crayonLine([[x + Math.cos(a) * r * 1.2, y + Math.sin(a) * r * 1.2], [x + Math.cos(a + .05) * (r * 1.2 + l * .5), y + Math.sin(a + .05) * (r * 1.2 + l * .5)], [x + Math.cos(a) * (r * .9 + l), y + Math.sin(a) * (r * .9 + l)]], .9, PAL.butterDk);+ }+ colorIn(ellPts(x, y, r, r, 26, r * .02), { col: PAL.butter, gap: 10, ang: .3, line: PAL.butterDk, lw: 1.1 });+ if (o.face) { dab(x - r * .32, y - r * .08, r * .08, PAL.ink, .6); dab(x + r * .32, y - r * .08, r * .08, PAL.ink, .6); pencilLine([[x - r * .25, y + r * .25], [x, y + r * .38], [x + r * .25, y + r * .25]], .9, PAL.ink, .6); dab(x - r * .55, y + r * .2, r * .13, PAL.rose); dab(x + r * .55, y + r * .2, r * .13, PAL.rose); }+}+// A puffy cloud of scallops, lightly coloured.+function cloud(x, y, s = 1, o = {}) {+ boilSeed('cloud' + (o.key ?? Math.round(x)));+ const P = [], n = 40;+ for (let i = 0; i < n; i++) { // an ellipse with round bumps on top and a flatter, softer underside+ const a = i / n * TAU, top = Math.sin(a) < 0, bump = top ? .22 * Math.abs(Math.sin(a * 3.5 + .4)) : .03 * Math.abs(Math.sin(a * 5));+ P.push([x + Math.cos(a) * 190 * s * (1 + bump * .6), y + Math.sin(a) * (top ? 78 : 40) * s * (1 + bump * 1.4)]);+ }+ colorIn(P, { col: o.col || PAL.cream, base: o.base || '#FFFCF3', fill: 'hatch', ang: .1, gap: 22 * s, tone: o.tone || PAL.skyLt, line: o.line || PAL.skyDk, lw: .8, curv: .5 });+}+// A hill: a big soft mound, coloured in long strokes that follow its slope.+function hill(cx, cy, rx, ry, col = PAL.sage, o = {}) {+ boilSeed('hill' + cx + ':' + cy);+ colorIn(ellPts(cx, cy, rx, ry, 44, 2), { col, gap: o.gap ?? 40, ang: o.ang ?? -.12, w: 1.5, run: 12, pale: .35, line: o.line ?? mixCol(col, PAL.ink, .55), lw: 1 });+}+const hillY = (x, cx, cy, rx, ry) => cy - ry * Math.sqrt(Math.max(0, 1 - ((x - cx) / rx) ** 2));+// A ground strip from y down, coloured in, with a pencil horizon.+function ground(y, col = PAL.sage, o = {}) {+ boilSeed('ground' + y);+ const x0 = o.x0 ?? -400, x1 = o.x1 ?? W + 400;+ colorIn(rectPts(x0, y, x1 - x0, (o.depth ?? H + 250 - y)), { col, gap: o.gap ?? 44, ang: -.05, w: 1.6, pale: .3, line: null, run: 12 });+ inkLine([[x0, y + 4], [(x0 + x1) / 2, y - 4], [x1, y + 3]], 1, mixCol(col, PAL.ink, .6), 'cpen', .5);+}+// Grass tufts that sway (key them so they don't re-boil).+function tufts(x0, x1, yf, n, col = PAL.sageDk, t = T, key = 'tufts') {+ boilSeed(key);+ for (let i = 0; i < n; i++) {+ const x = lerp(x0, x1, (i + hash(i + 7) * .6) / n), y = yf(x), sw = wob(t, .45, hash(i) * 3) * 5;+ for (const k of [-1, 0, 1]) inkLine([[x + k * 6, y], [x + k * 10 + sw, y - 20 - 10 * hash(i * 3 + k)]], .8, col, 'crayonFine', .4);+ }+}+// A round storybook tree: a scribbled crown of greens on a crayon trunk. o.fruit: [[dx, dy], …] apples (in crown units).+function tree(x, y, s = 1, o = {}) {+ boilSeed('tree' + Math.round(x));+ colorIn([[x - 26 * s, y], [x - 18 * s, y - 210 * s], [x - 44 * s, y - 260 * s], [x + 40 * s, y - 262 * s], [x + 20 * s, y - 210 * s], [x + 30 * s, y]], { col: PAL.bark, ang: 1.45, gap: 9, line: mixCol(PAL.bark, PAL.ink, .6) });+ const crown = [];+ for (let i = 0; i < 16; i++) { const a = i / 16 * TAU, rr = (1 + .1 * Math.sin(i * 2.7)) * 190 * s; crown.push([x + Math.cos(a) * rr, y - 360 * s + Math.sin(a) * rr * .82]); }+ colorIn(through([...crown, crown[0]], 3), { col: o.col || PAL.leaf, gap: 13, ang: -.7, w: 1.1, pale: .35, line: mixCol(o.col || PAL.leaf, PAL.ink, .55), shade: { pts: ellPts(x + 50 * s, y - 300 * s, 120 * s, 90 * s, 18), col: PAL.sageDk } });+ for (let i = 0; i < 6; i++) { const a = hash(i + x) * TAU, q = hash(i * 3 + x) * 130 * s; dab(x + Math.cos(a) * q, y - 380 * s + Math.sin(a) * q * .7, 10 * s, PAL.sageDk, .7); }+}+// A little flower on a stem, nodding in the breeze.+function flower(x, y, s = 1, col = PAL.rose, t = T, o = {}) {+ boilSeed('flower' + Math.round(x) + ':' + Math.round(y));+ const sw = Math.sin(t * 1.6 + x * .01) * 6 * s, hx = x + sw, hy = y - 60 * s;+ crayonLine([[x, y], [x + sw * .4, y - 30 * s], [hx, hy]], .55, PAL.sageDk, .5);+ for (let i = 0; i < 5; i++) { const a = i / 5 * TAU + .3; paint(ellPts(hx + Math.cos(a) * 12 * s, hy + Math.sin(a) * 12 * s, 10 * s, 10 * s, 10), { wash: mixCol(col, PAL.paper, .15), ink: mixCol(col, PAL.ink, .5), sw: .55 * s, br: 'cpen' }); }+ paint(ellPts(hx, hy, 7 * s, 7 * s, 10), { wash: PAL.butter, ink: PAL.butterDk, sw: .5 * s, br: 'cpen' });+}+// A storybook cottage.+function house(x, y, s = 1, o = {}) {+ boilSeed('house' + Math.round(x));+ const w = 300 * s, h = 220 * s;+ colorIn(rectPts(x - w / 2, y - h, w, h, 2), { col: o.wall || PAL.peach, gap: 11, ang: 1.4, line: PAL.ink });+ colorIn([[x - w / 2 - 30 * s, y - h + 6], [x, y - h - 170 * s], [x + w / 2 + 30 * s, y - h + 6]], { col: o.roof || PAL.coral, gap: 10, ang: -.9, line: PAL.ink });+ colorIn(rrPts(x - 40 * s, y - 120 * s, 80 * s, 120 * s, 30 * s), { col: PAL.sky, gap: 8, ang: 1.5, line: PAL.ink });+ colorIn(rectPts(x + 60 * s, y - 180 * s, 60 * s, 60 * s), { col: PAL.butter, gap: 8, ang: .2, line: PAL.ink });+ pencilLine([[x + 90 * s, y - 180 * s], [x + 90 * s, y - 120 * s]], .7); pencilLine([[x + 60 * s, y - 150 * s], [x + 120 * s, y - 150 * s]], .7);+}++// ---------- props (draw them in a hand hook, or free in the scene) ----------+// Each takes a centre and a size r and draws around it, so a hand hook can call prop(0, 0, u * 1.2) directly.+function apple(x, y, r, o = {}) {+ const P = []; for (let i = 0; i < 24; i++) { const a = i / 24 * TAU, dent = .12 * Math.exp(-((a - 1.5 * Math.PI) ** 2) * 6); P.push([x + Math.cos(a) * r * 1.02, y + Math.sin(a) * r * (.95 - dent)]); }+ colorIn(P, { col: o.col || '#E8655E', gap: Math.max(4, r * .22), ang: .8, w: clamp(r / 40, .45, 1), line: '#8E3B3A', lw: clamp(r / 35, .4, 1), curv: .5 });+ paint(ellPts(x - r * .38, y - r * .3, r * .16, r * .24, 10, 0, -.5), { wash: '#FFE8DA', washOp: 200, ink: null });+ crayonLine([[x, y - r * .8], [x + r * .08, y - r * 1.25]], clamp(r / 50, .4, .9), PAL.cocoa, .4);+ colorIn([[x + r * .08, y - r * 1.05], [x + r * .5, y - r * 1.35], [x + r * .75, y - r * 1.1], [x + r * .35, y - r * .95]], { col: PAL.leaf, fill: 'flat', line: PAL.sageDk, lw: clamp(r / 50, .35, .8), curv: .5 });+}+function leafProp(x, y, r, rot = 0, col = PAL.leaf) {+ push(); translate(x, y); rotate(rot);+ colorIn([[-r, 0], [-r * .3, -r * .45], [r * .5, -r * .38], [r, 0], [r * .5, r * .38], [-r * .3, r * .45]], { col, gap: Math.max(4, r * .25), ang: .6, w: clamp(r / 40, .4, 1), curv: .6, lw: clamp(r / 40, .4, 1) });+ pencilLine([[-r * .95, 0], [r * .9, 0]], clamp(r / 50, .3, .8), mixCol(col, PAL.ink, .6));+ pop();+}+function starProp(x, y, r, col = PAL.butter, rot = 0) { colorIn(starPts(x, y, r, .5, 5, -Math.PI / 2 + rot), { col, gap: Math.max(4, r * .22), ang: .4, w: clamp(r / 40, .4, 1), lw: clamp(r / 40, .4, 1) }); }+function heartProp(x, y, r, col = PAL.rose) { colorIn(heartPts(x, y, r), { col, gap: Math.max(4, r * .22), ang: .7, w: clamp(r / 40, .4, 1), lw: clamp(r / 40, .4, 1) }); }+// A balloon on a string. (x, y) is the string's end (the hand); the balloon floats `len` above, swaying.+function balloon(x, y, r, len, col = PAL.rose, t = T) {+ const sw = Math.sin(t * 1.3) * r * .25, bx = x + sw, by = y - len;+ pencilLine([[x, y], [x + sw * .3, y - len * .4], [bx - sw * .2, y - len * .75], [bx, by + r * 1.05]], .6, PAL.inkSoft, .5);+ colorIn(ellPts(bx, by, r * .9, r, 24), { col, gap: Math.max(5, r * .2), ang: .5, curv: .5 });+ paint(ellPts(bx - r * .35, by - r * .35, r * .14, r * .22, 10, 0, -.5), { wash: PAL.cream, washOp: 220, ink: null });+ paint([[bx - r * .12, by + r * .98], [bx + r * .12, by + r * .98], [bx, by + r * 1.12]], { wash: col, ink: mixCol(col, PAL.ink, .6), sw: .5 });+}++// ---------- emotes: drawn marks that pop in by a head (never typed letters) ----------+// emote(kind, x, y, s, k = pop 0..1, age = seconds since it appeared). kinds: '!', '?', 'heart', 'hearts', 'sweat',+// 'spark', 'zzz', 'bulb', 'music', 'anger', 'cloud', 'tears', 'dots', 'swirl'+function emote(kind, x, y, s, k = 1, age = T) {+ if (k <= .01 || !kind) return;+ const p = backOut(k); push(); translate(x, y); scale(p);+ const lw = clamp(s / 22, .5, 1.3);+ switch (kind) {+ case '!': colorIn([[-s * .22, -s * 1.6], [s * .22, -s * 1.6], [s * .1, -s * .4], [-s * .1, -s * .4]], { col: PAL.coral, fill: 'flat', lw }); dab(0, -s * .05, s * .18, PAL.coral, lw); break;+ case '?': crayonLine([[-s * .4, -s * 1.1], [-s * .2, -s * 1.5], [s * .3, -s * 1.45], [s * .35, -s * 1], [0, -s * .75], [0, -s * .45]], lw * 1.1, PAL.skyDk, .5); dab(0, -s * .05, s * .16, PAL.skyDk, lw); break;+ case 'heart': heartProp(0, -s * .8, s * .7, PAL.rose); break;+ case 'hearts': for (let i = 0; i < 3; i++) { const a = (age * .8 + i / 3) % 1; heartProp(Math.sin(a * 6 + i) * s * .4 + (i - 1) * s * .5, -s * (.4 + a * 1.8), s * .38 * (1 - a * .5), PAL.rose); } break;+ case 'sweat': colorIn([[0, -s * 1.4], [s * .38, -s * .6], [0, -s * .3], [-s * .38, -s * .6]], { col: PAL.sky, fill: 'flat', lw, curv: .7 }); break;+ case 'spark': for (let i = 0; i < 3; i++) { const q = .7 + .3 * Math.sin(age * 8 + i * 2); starProp((i - 1) * s * .7, -s * (.6 + (i % 2) * .6), s * .35 * q, PAL.butter); } break;+ case 'zzz': for (let i = 0; i < 3; i++) { const a = (age * .5 + i / 3) % 1, z = s * (.3 + .25 * a), zx = s * (.2 + a * .9), zy = -s * (.3 + a * 1.6);+ crayonLine([[zx - z, zy - z], [zx + z, zy - z], [zx - z, zy + z], [zx + z, zy + z]], lw * .8, mixCol(PAL.lilacDk, PAL.paper, a * .6), 0); } break;+ case 'bulb': glow(0, -s * 1.2, s * 1.6, '#FFE3A0', .8); colorIn(ellPts(0, -s * 1.3, s * .5, s * .55, 18), { col: PAL.butter, fill: 'flat', lw }); colorIn(rectPts(-s * .22, -s * .82, s * .44, s * .3), { col: PAL.inkSoft, fill: 'flat', lw: lw * .7 });+ for (let i = 0; i < 5; i++) { const a = -Math.PI / 2 + (i - 2) * .55; crayonLine([[Math.cos(a) * s * .75, -s * 1.3 + Math.sin(a) * s * .75], [Math.cos(a) * s * 1.05, -s * 1.3 + Math.sin(a) * s * 1.05]], lw * .7, PAL.butterDk, 0); } break;+ case 'music': for (let i = 0; i < 2; i++) { const a = (age * .6 + i / 2) % 1, nx = (i - .5) * s * .9 + Math.sin(a * 5) * s * .2, ny = -s * (.5 + a * 1.3);+ paint(ellPts(nx, ny, s * .2, s * .15, 10, 0, -.4), { wash: PAL.lilacDk, ink: null }); crayonLine([[nx + s * .18, ny], [nx + s * .18, ny - s * .6], [nx + s * .4, ny - s * .45]], lw * .7, PAL.lilacDk, 0); } break;+ case 'anger': for (let q = 0; q < 4; q++) { const a = q * Math.PI / 2 + .78; crayonLine([[Math.cos(a) * s * .2, -s + Math.sin(a) * s * .2], [Math.cos(a) * s * .55 + Math.cos(a + 1.57) * s * .15, -s + Math.sin(a) * s * .55 + Math.sin(a + 1.57) * s * .15]], lw * .9, PAL.coral, .3); } break;+ case 'cloud': cloud(0, -s * 1.3, s * .0055, { key: 'emo', col: PAL.skyLt, base: '#DDE6EE', line: PAL.inkSoft }); for (let i = 0; i < 4; i++) { const a = (age * 1.4 + i / 4) % 1; crayonLine([[(i - 1.5) * s * .3, -s * (1 - a * .8)], [(i - 1.5) * s * .3 - s * .05, -s * (.8 - a * .8)]], lw * .6, PAL.skyDk, 0); } break;+ case 'dots': for (let i = 0; i < 3; i++) if ((age * 3) % 3 >= i) dab((i - 1) * s * .5, -s * .8, s * .12, PAL.inkSoft, lw); break;+ case 'swirl': { const P = []; for (let a = 0; a < TAU * 2; a += .4) P.push([Math.cos(a + age * 6) * s * .1 * a, -s + Math.sin(a + age * 6) * s * .1 * a]); crayonLine(P, lw * .8, PAL.lilacDk, .5); } break;+ }+ pop();+}++// ---------- captions: storybook text ----------+// captions([[t0, t1, 'text', { pos: 'bottom' | 'top', size, box }], …]) registers the lines and the overlay hook.+// The text is hand-lettered (a warm kai / rounded font with a slightly uneven baseline), writes itself on character by+// character, sits on a soft torn-paper label (box: false to put it straight on the picture), and is broken a little by+// the paper tooth like the rest of the drawing. Sized for phones: default 74 px (≈ 15 px on a 390 px-wide screen).+const CAPTION_FONT = HAND_FONT;+let CAPTIONS = [], capC = null;+function captions(list) {+ CAPTIONS = list;+ window.EXTRA_FONTS = [...(window.EXTRA_FONTS || []), [`700 74px ${CAPTION_FONT}`, list.map(l => l[2]).join('')]];+ window.overlayHook = (c, t) => { for (const L of CAPTIONS) if (t >= L[0] - .01 && t < L[1] + .4) storyCaption(c, L, t); };+}+function storyCaption(c, [a, b, txt, o = {}], t) {+ const size = o.size || 74, chars = [...txt], rate = o.rate || 16, age = t - a;+ const alpha = seg(age, 0, .15) * (1 - seg(t, b, b + .4));+ if (alpha <= 0) return;+ if (!capC) { capC = document.createElement('canvas'); capC.width = W; capC.height = 300; }+ const k = capC.getContext('2d'); k.setTransform(1, 0, 0, 1, 0, 0); k.clearRect(0, 0, W, 300);+ k.font = `700 ${size}px ${CAPTION_FONT}`; k.textBaseline = 'middle';+ const ws = chars.map(ch => k.measureText(ch).width), total = ws.reduce((s, v) => s + v, 0) + (chars.length - 1) * size * .04;+ const cy = 150, bn = Math.floor(t * BOIL + 1e-6);+ // label: a torn cream paper strip with a pencil edge+ if (o.box !== false) {+ const bw = total + size * 1.3, bh = size * 1.55, x0 = W / 2 - bw / 2, y0 = cy - bh / 2, j = n => (hash(n * 13.1 + 5) - .5) * size * .1;+ k.beginPath(); const N = 14;+ for (let i = 0; i <= N; i++) k.lineTo(x0 + bw * i / N, y0 + j(i));+ for (let i = 1; i <= 4; i++) k.lineTo(x0 + bw + j(40 + i), y0 + bh * i / 4);+ for (let i = N - 1; i >= 0; i--) k.lineTo(x0 + bw * i / N, y0 + bh + j(20 + i));+ for (let i = 3; i >= 1; i--) k.lineTo(x0 + j(60 + i), y0 + bh * i / 4);+ k.closePath(); k.fillStyle = 'rgba(255,250,236,.93)'; k.fill();+ k.strokeStyle = 'rgba(74,54,49,.35)'; k.lineWidth = 2.2; k.stroke();+ }+ // the letters, written on one by one, each a little off the line like hand lettering+ let x = W / 2 - total / 2;+ chars.forEach((ch, i) => {+ const ka = seg(age * rate, i, i + 2.2); if (ka <= 0) { x += ws[i] + size * .04; return; }+ const r = (hash(i * 7.3 + txt.length) - .5) * .09, dy = (hash(i * 3.1 + 2) - .5) * size * .07 + (1 - easeOut(ka)) * size * .25;+ k.save(); k.translate(x + ws[i] / 2, cy + dy); k.rotate(r); k.globalAlpha = easeOut(ka);+ k.lineJoin = 'round'; k.lineWidth = size * .16; k.strokeStyle = 'rgba(255,249,234,.95)'; k.textAlign = 'center';+ k.strokeText(ch, 0, 0); k.fillStyle = o.col || PAL.ink; k.fillText(ch, 0, 0); k.restore();+ x += ws[i] + size * .04;+ });+ // crayon-ish: the paper tooth nibbles the letters a little+ k.globalCompositeOperation = 'destination-out'; k.globalAlpha = .45;+ k.drawImage(toothC, -Math.floor(hash(bn * 3.7 + 1) * TOOTH_PAD), -Math.floor(hash(bn * 5.3 + 2) * TOOTH_PAD));+ k.globalCompositeOperation = 'source-over'; k.globalAlpha = 1;+ const y = o.pos === 'top' ? 150 : o.y ?? H - 140;+ c.save(); c.globalAlpha = alpha; c.drawImage(capC, 0, y - 150); c.restore();+}diff --git a/.claude/skills/crayon-storybook/template/src/karaoke.js b/.claude/skills/crayon-storybook/template/src/karaoke.jsnew file mode 100644index 0000000..e0b67c3--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/karaoke.js@@ -0,0 +1,63 @@+// karaoke.js: brush-font karaoke with a character-by-character fill, drawn on the 2D compositor through+// window.overlayHook in core.js (crisp, above the paper grain). The bar covers y ≈ 975–1070 while a line shows.+//+// LY = [[start, end, "line", opts?]]. opts.sing = seconds the line takes to sing (for the fill); opts.pun =+// { from, to, at }: at time `at`, the characters `from` get a painted strike and `to` pops in above them (e.g. the fans'+// 大经理 → 大锦鲤 joke); opts.hold = seconds the line stays up after it ends, lifted above the next line.+// Times are clip times: the song's LRC time minus the clip start (see references/music-video.md). Let lines run into each other.+const LY = [+ // [3.02, 6.02, '第一句歌词'],+ // [6.07, 9.03, 'a line that holds', { sing: 2.2, hold: 1.4, pun: { from: 'old', to: 'new', at: 8.4 } }],+];+const KFONT = '"Ma Shan Zheng", "Kaiti SC", "STKaiti", serif';+window.EXTRA_FONTS = [[`64px ${KFONT}`, LY.map(l => l[2] + ((l[3] && l[3].pun && l[3].pun.to) || '')).join('')]];++window.overlayHook = (c, t) => {+ const i = LY.findIndex(l => t >= l[0] && t < l[1]);+ // a line with opts.hold stays up after its time, lifted and shrunk above the next one (two-row KTV style)+ const P = LY.find(l => l[3] && l[3].hold && t >= l[1] && t < l[1] + l[3].hold);+ if (P) { const a = t - P[1], k = ease(a / .15); kLine(c, P, t, 1024 - 108 * k, 1 - .3 * k, 1 - ease((a - (P[3].hold - .3)) / .3), true); }+ if (i >= 0) kLine(c, LY[i], t, 1024, 1, 1, false);+};+function kLine(c, L, t, y, sc, alpha, held) {+ const [a, b, txt, opt = {}] = L;+ const grow = held ? 1 : easeOut((t - a) / .18) * (opt.hold ? 1 : 1 - ease((t - (b - .1)) / .1));+ if (grow < .02 || alpha <= .01) return;+ c.save(); c.globalAlpha = alpha; c.translate(960, y); c.scale(sc, sc); c.translate(-960, -y);+ c.font = `64px ${KFONT}`; c.textBaseline = 'middle'; c.textAlign = 'left';+ const total = c.measureText(txt).width;+ // the bar: a ragged ink lozenge that grows from the centre and boils with the linework+ const w = (total + 120) * grow, x0 = 960 - w / 2, y0 = y - 48, r = n => hash(BOILN * 13 + n) * 8 - 4;+ c.globalAlpha = .86 * alpha; c.fillStyle = PAL.ink; c.beginPath();+ c.moveTo(x0 + r(1), y0 + r(2)); c.lineTo(x0 + w / 2, y0 - 5 + r(3)); c.lineTo(x0 + w + r(4), y0 + r(5));+ c.lineTo(x0 + w + 16, y0 + 46); c.lineTo(x0 + w + r(6), y0 + 92 + r(7)); c.lineTo(x0 + w / 2, y0 + 96 + r(8));+ c.lineTo(x0 + r(9), y0 + 92 + r(10)); c.lineTo(x0 - 16, y0 + 46); c.closePath(); c.fill();+ c.globalAlpha = alpha;+ if (grow > .85) {+ // characters fill left to right as they're sung (opt.sing = how long the line takes to sing)+ const n = [...txt].length, singDur = opt.sing ?? Math.min((b - a) * .85, n * .3), f = held ? 1 : clamp((t - a) / singDur);+ const x = 960 - total / 2;+ c.fillStyle = PAL.cream; c.fillText(txt, x, y);+ c.save(); c.beginPath(); c.rect(x - 2, y - 50, total * f + 2, 100); c.clip(); c.fillStyle = PAL.ochre; c.fillText(txt, x, y); c.restore();+ if (opt.pun && t > opt.pun.at) pun(c, txt, x, y, opt.pun, t - opt.pun.at);+ }+ c.restore();+}++// Strike through `from` with a red brush stroke, then pop `to` in above it, tilted, in gold with an ink shadow.+function pun(c, txt, x, y, p, age) {+ const i = txt.indexOf(p.from); if (i < 0) return;+ const px = x + c.measureText(txt.slice(0, i)).width, pw = c.measureText(p.from).width;+ const k = easeOut(age / .25);+ c.save(); c.strokeStyle = '#D8394E'; c.lineCap = 'round'; c.lineWidth = 9;+ c.beginPath(); c.moveTo(px - 8, y + 6);+ for (let j = 1; j <= 8; j++) { const q = j / 8 * k; c.lineTo(px - 8 + (pw + 16) * q, y + 6 - 12 * q + Math.sin(j * 1.7) * 2); }+ c.stroke(); c.restore();+ const pop = backOut(clamp((age - .2) / .35)); if (pop <= .01) return;+ c.save(); c.translate(px + pw / 2 + 10, y - 88); c.rotate(-.12 + Math.sin(age * 14) * .04 * Math.exp(-age * 2)); c.scale(pop, pop);+ c.font = `96px ${KFONT}`; c.textAlign = 'center'; c.textBaseline = 'middle';+ c.lineJoin = 'round'; c.lineWidth = 14; c.strokeStyle = PAL.ink; c.strokeText(p.to, 0, 0);+ c.fillStyle = PAL.ink; c.fillText(p.to, 5, 6);+ c.fillStyle = '#F4B63A'; c.fillText(p.to, 0, 0);+ c.restore();+}diff --git a/.claude/skills/crayon-storybook/template/src/scenes/demo.js b/.claude/skills/crayon-storybook/template/src/scenes/demo.jsnew file mode 100644index 0000000..3036e8d--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/scenes/demo.js@@ -0,0 +1,99 @@+// demo.js: "The red apple", a 10-second example that exercises the engine. One idea, not a template: don't reuse its+// story, meadow or shot structure in your own video.+// Shot A (0–4.6 s): establishing. The camera drifts down from the sun to a meadow. Lulu and Kuri walk in and stop+// under an apple tree. Kuri spots the apple, can't reach it, droops. Lulu thinks … idea!+// Page turn (4.6–5.6 s).+// Shot B (4.6–10 s): closer, framed as a picture-book page. Lulu crouches (anticipation), jumps and plucks the apple+// (action), lands with a squash and a hair bounce (follow-through), turns and gives it to Kuri,+// who falls in love with it. The page fades back to paper.+(() => {+ captions([+ [0.5, 2.5, '露露和小栗出門散步。', { pos: 'top' }],+ [2.9, 4.4, '樹上有一顆紅蘋果⋯⋯', { pos: 'top' }],+ [5.95, 7.3, '跳高一點⋯⋯摘到了!'],+ [7.8, 9.4, '這顆送給你!'],+ ]);++ // ---------- shot A: the meadow ----------+ const GA = 880;+ function meadow(t, lt, dur) {+ camBegin(kf(lt, [[0, 820], [2.6, 960], [dur + 1, 1010]]), kf(lt, [[0, 300], [2.4, 555], [dur + 1, 640]], ease), kf(lt, [[0, 1.12], [2.4, 1.0], [dur + 1, 1.32]]));+ sky(PAL.sky, PAL.cream, { y1: GA - 100 });+ sun(1580, 150, 70, t, { face: true });+ cloud(460 + lt * 12, 170, .9, { key: 'c1' }); cloud(1120 + lt * 8, 90, .6, { key: 'c2' });+ hill(350, GA + 140, 760, 300, mixCol(PAL.sage, PAL.skyLt, .35));+ house(360, GA - 150, .55);+ hill(1500, GA + 170, 900, 330, mixCol(PAL.leaf, PAL.skyLt, .25), { ang: .15 });+ ground(GA, PAL.sage);+ tufts(-300, 2200, () => GA + 6, 26, PAL.sageDk, t, 'tA');+ for (let i = 0; i < 7; i++) flower(-200 + i * 330 + hash(i) * 90, GA + 40 + hash(i + 4) * 90, 1.1, [PAL.rose, PAL.lilac, PAL.butter][i % 3], t);+ tree(1420, GA, 1.25);+ boilSeed('appleA'); apple(1330, 610 + Math.sin(t * 1.4) * 3, 26);+ crayonLine([[1330, 584], [1340, 560]], .5, PAL.cocoa);++ // Kuri trots in behind Lulu, stops, looks up at the apple, and droops+ const kw = stroll(lt, .15, 2.7, -420, 800, 26, 2.2);+ const km = emotions(lt, [[0, 'happy'], [2.95, 'curious', { lookX: .8, lookY: -1 }], [3.65, 'sad', { lookX: .6, lookY: -.4 }]]);+ const kpose = lt < 2.7 ? pose(km, walkCycle(kw.walk || 0, true), { view: 'side' }) : pose(km, { view: 'q' });+ kuri(kw.x, GA + 10, 26, { ...kpose, seed: 2 });+ // Lulu leads, stops under the tree, thinks, gets an idea+ const lw = stroll(lt, 0, 2.5, -150, 1060, 30, 3);+ const lm = emotions(lt, [[0, 'happy'], [3.05, 'thinking'], [3.9, 'idea']]);+ const lpose = lt < 2.5 ? pose(lm, walkCycle(lw.walk || 0, true), { view: 'side' }) : pose(lm, { view: lt < 2.62 ? 'q' : 'front' });+ lulu(lw.x, GA + 4, 30, { ...lpose, seed: 1 });+ camEnd();+ if (lt < .6) flash(1 - easeOut(lt / .6), PAL.paper); // open from the blank page+ }++ // ---------- shot B: the jump ----------+ const GB = 900, P = [943, 357]; // P: where the apple hangs = Lulu's raised hand at the top of her jump+ const tJ0 = 1.5, tJ1 = 2.2, tGrab = 1.83, tTurn = 2.85, tGive = 3.45, tGot = 3.8;+ function jumpShot(t, lt, dur) {+ const land = lt > tJ1 ? shakeXY(t, 5 * Math.exp(-(lt - tJ1) * 9)) : [0, 0];+ camBegin(kf(lt, [[0, 930], [dur, 880]]) + land[0], kf(lt, [[0, 560], [tJ0, 540], [tJ1 + .4, 575]]) + land[1], kf(lt, [[0, 1], [dur, 1.07]]));+ sky(PAL.skyLt, PAL.cream, { y1: GB - 60, strokes: 6 });+ hill(1100, GB + 200, 1300, 360, mixCol(PAL.leaf, PAL.skyLt, .3));+ ground(GB, PAL.sage);+ tufts(-300, 2200, () => GB + 6, 22, PAL.sageDk, t, 'tB');+ for (let i = 0; i < 5; i++) flower(-100 + i * 480 + hash(i + 9) * 100, GB + 70 + hash(i + 2) * 60, 1.5, [PAL.lilac, PAL.rose, PAL.butter][i % 3], t);+ tree(1480, GB, 1.8);+ // the branch reaching out over Lulu, with the apple's stem+ boilSeed('branch');+ colorIn(ribbon([[1420, 430], [1200, 330], [1040, 300], [925, 305]], 34, 12), { col: PAL.bark, ang: .2, gap: 8 });+ for (let i = 0; i < 4; i++) leafProp(1300 - i * 115, 330 - 25 * (i % 2) - i * 8, 30, -.5 + i * .4);+ const grabbed = lt >= tGrab;+ if (!grabbed) { boilSeed('stem'); crayonLine([[P[0] + 2, 306], [P[0], P[1] - 28]], .5, PAL.cocoa); boilSeed('appleB'); apple(P[0], P[1] + 8 + Math.sin(t * 1.4) * 2, 40); }+ else { boilSeed('stem'); crayonLine([[P[0] + 2, 306], [P[0] - 4 + 8 * spring(lt, tGrab, 5, 20), 328]], .5, PAL.cocoa); } // the snapped stem twangs++ // Kuri: worried → surprised by the jump → excited → the apple arrives → love, with a little hop+ const km = emotions(lt, [[0, 'sad', { lookX: .6, lookY: -.5 }], [tJ0 - .05, 'surprised', { lookY: -.8 }], [tJ1 + .15, 'excited'], [tGive, 'curious', { lookX: .6 }], [tGot + .05, 'love']]);+ const khop = jump(lt, tGot + .35, tGot + .7, 1.6);+ const giftFlight = lt > tGive && lt < tGot;+ const K = kuri(520, GB + 8, 34, { ...pose(km, khop, { view: 'q' }), seed: 3, aR: lt > tGive - .2 ? kf(lt, [[tGive - .2, -1.1], [tGive + .1, .1], [tGot + .3, -.35]]) : km.aR, bR: lt > tGive ? 1.2 : .3,+ holdR: lt >= tGot ? (u) => apple(0, -u * .75, u * 1.15) : null, propFront: false });++ // Lulu: determined look up → crouch → jump with her arm up → grab → land → turn to Kuri → give+ const lm = emotions(lt, [[0, 'determined', { lookX: .4, lookY: -1 }], [tGrab, 'excited'], [tJ1 + .5, 'happy'], [tGot + .15, 'proud']], { take: .6 });+ const hop = jump(lt, tJ0, tJ1, 4.6);+ const k = seg(lt, tJ0, tJ1), inAir = lt > tJ0 && lt < tJ1;+ const hair = inAir ? 1.3 * (2 * k - 1) : lt >= tJ1 ? -1.2 * spring(lt, tJ1, 5, 16) : 0;+ const reach = kf(lt, [[tJ0 - .3, -1.2], [tJ0 - .05, -.2], [tJ0 + .12, 1.15], [tJ1 + .1, 1.15], [tJ1 + .5, .6], [tTurn, -1]], ease);+ let lp = pose(lm, hop, { hair, aR: reach, bR: lt < tJ1 + .3 ? .35 : .8, aL: inAir ? .3 : lm.aL, view: 'front' });+ if (lt < tJ0) lp.lookY = -1;+ if (lt >= tTurn) lp = pose(lp, { view: 'q', flip: true, aR: kf(lt, [[tTurn, -1], [tGive, -.15], [tGot, -.3], [tGot + .5, -1.2]]), bR: kf(lt, [[tTurn, .8], [tGive, .25], [tGot + .5, .3]]) });+ if (lt >= tTurn && lt < tTurn + .12) lp.sq = (lp.sq || 0) + .08; // a little squash on the turn drawing+ const holding = grabbed && lt < tGive + .05;+ const L = lulu(860, GB + 4, 40, { ...lp, seed: 5, hairCol: undefined, holdR: holding ? (u) => apple(0, -u * .6, u * 1.0) : null, propFront: false });+ // the hand-over: the apple arcs from Lulu's hand to Kuri's paws+ if (lt >= tGive + .05 && lt < tGot && L.handR && K.handR) {+ const q = ease(seg(lt, tGive + .05, tGot)); boilSeed('gift');+ const p = arcPt([L.handR[0], L.handR[1] - 24], [K.handR[0], K.handR[1] - 26], 70, q); apple(p[0], p[1], 40);+ }+ camEnd();+ bookPage(ease(seg(lt, 1.0, 1.7)));+ vignette(.3 + .4 * seg(lt, dur - 1.2, dur));+ if (lt > dur - .55) flash(easeIn(seg(lt, dur - .55, dur - .05)), PAL.paper); // the page fades back to blank paper+ }++ shots([[0, meadow], [4.6, jumpShot, { turn: 1.0 }]]);+})();diff --git a/.claude/skills/crayon-storybook/template/src/sheets.js b/.claude/skills/crayon-storybook/template/src/sheets.jsnew file mode 100644index 0000000..552c84a--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/sheets.js@@ -0,0 +1,35 @@+// sheets.js: model sheets as standalone loops (reference, not part of a video — the one place labels are fine).+// studio.html?loop=cast (or render: node render.mjs --loop=cast --sheet=1 --cols=1 --w=1920 --out=docs/cast.jpg)+// ?loop=looks brushes and fills+(() => {+ const label = (txt, x, y, size = 24) => letter(txt, x, y, size, PAL.inkSoft, { alpha: .9 });++ // Views and moods of both characters.+ LOOPS.cast = t => {+ vignette(0);+ const views = ['front', 'q', 'side', 'back'];+ views.forEach((v, i) => { const x = 150 + i * 250; lulu(x, 400, 26, { ...feel('neutral', t, { seed: i }), view: v }); label(v, x, 440); });+ views.forEach((v, i) => { const x = 1180 + i * 200; kuri(x, 400, 26, { ...feel('happy', t, { seed: i }), view: v }); label(v, x, 440); });+ const moods = Object.keys(EMO);+ moods.forEach((m, i) => {+ const x = 70 + (i % 18) * 105, y = 770;+ lulu(x, y - 0, 17, { ...feel(m, t, { seed: i }), emote: null });+ kuri(x, y + 230, 17, { ...feel(m, t, { seed: i + 3 }), emote: null });+ label(m, x, y + 30, 17);+ });+ };+ LOOPS.cast.len = 4;++ // Brushes and fills.+ LOOPS.looks = t => {+ vignette(0);+ const lines = [['crayon', crayonLine], ['cpen', pencilLine], ['pastel', pastelLine], ['graphite', sketchLine]];+ lines.forEach(([n, f], i) => { boilSeed('ln' + i); f([[80, 120 + i * 90], [400, 90 + i * 90], [700, 140 + i * 90]], 1.2, [PAL.coral, PAL.ink, PAL.lilac, PAL.inkSoft][i]); label(n, 800, 115 + i * 90); });+ const fills = [['scribble', 'scribble', PAL.butter], ['hatch', 'hatch', PAL.sky], ['cross', 'cross', PAL.rose], ['smudge', 'smudge', PAL.lilac], ['flat', 'flat', PAL.sage]];+ fills.forEach(([n, f, c], i) => { boilSeed('f' + i); colorIn(ellPts(170 + i * 360, 620, 150, 130, 30, 3), { col: c, fill: f }); label(n, 170 + i * 360, 800); });+ boilSeed('props'); apple(1100, 250, 60); starProp(1300, 250, 60); heartProp(1480, 250, 55); leafProp(1680, 250, 60, .4); balloon(1300, 480, 55, 150);+ emote('!', 1100, 480, 50); emote('heart', 1500, 480, 50); emote('zzz', 1680, 480, 50, 1, t);+ sun(300, 950, 60, t); cloud(800, 960, .8); flower(1200, 1040, 1.3, PAL.rose, t); flower(1300, 1040, 1.1, PAL.lilac, t);+ };+ LOOPS.looks.len = 4;+})();diff --git a/.claude/skills/crayon-storybook/template/src/timeline.js b/.claude/skills/crayon-storybook/template/src/timeline.jsnew file mode 100644index 0000000..84b90b3--- /dev/null+++ b/.claude/skills/crayon-storybook/template/src/timeline.js@@ -0,0 +1,65 @@+// timeline.js: the shot list, standalone loops and the timeline-level transitions (page turn).+//+// shots([[t0, fn], [t1, fn, opts], ...]) registers shots in time order. Each fn(t, lt, dur) is called with t = video+// time, lt = time since the shot started, dur = the shot's length. It paints the WHOLE frame, background included, and+// must be a pure function of t: frames render in parallel and out of order, so nothing may carry over between frames.+//+// opts.turn = seconds: the shot arrives by a PAGE TURN. For that long after t1 the previous shot keeps playing+// (called with lt > its dur, so let its motion settle rather than end abruptly) on the page that curls away, revealing+// this shot underneath. opts.turnDir = 1 (default: the page turns right → left, like a book) or -1.++const SHOTS = [];+function shots(list) { SHOTS.push(...list); SHOTS.sort((a, b) => a[0] - b[0]); }++// Standalone loops (model sheets, GIFs, tests), outside the main timeline: window.LOOP = LOOPS[name] swaps the whole+// frame for that function, called with loop time. Give each a length: LOOPS.x = t => { ... }; LOOPS.x.len = 4;+const LOOPS = {};++function drawWorld(t) {+ if (window.LOOP) window.LOOP(t);+ else if (!SHOTS.length) placeholder(t);+ else {+ let i = 0; while (i + 1 < SHOTS.length && t >= SHOTS[i + 1][0]) i++;+ const t0 = SHOTS[i][0], end = i + 1 < SHOTS.length ? SHOTS[i + 1][0] : DUR, opt = SHOTS[i][2] || {};+ if (opt.turn && i > 0 && t - t0 < opt.turn) {+ // page turn: paint the previous shot, keep it as the turning page, then paint this one underneath+ const [p0, pfn] = SHOTS[i - 1];+ stageReset(); pfn(t, t - p0, t0 - p0); CAM = null; flushLetters();+ snapshotPage();+ const keep = { ...STAGE };+ clearToPaper(); stageReset(); boilSeed('frame');+ STAGE.turn = { p: (t - t0) / opt.turn, dir: opt.turnDir || 1, prevStage: keep };+ }+ SHOTS[i][1](t, t - t0, end - t0);+ CAM = null;+ }+ flushLetters();+}++function placeholder(t) {+ paperWash(t);+ const k = feel('happy', t);+ lulu(820, 860, 44, k); kuri(1120, 860, 40, { ...feel('happy', t + .3), seed: 2 });+}++// ---------- crayon wipe ----------+// Fat crayon zigzags scribble across to cover the frame (p 0 → .5), then are scribbled away (p .5 → 1).+// Cut to the next shot at p = .5, under full cover. Call it last in both shots, in screen space (outside a camera):+// end of shot A: if (lt > dur - .35) crayonWipe((lt - (dur - .35)) / .7);+// start of shot B: if (lt < .35) crayonWipe(.5 + lt / .7);+function crayonWipe(p, cols = [PAL.butter, PAL.rose, PAL.sky]) {+ if (p <= 0 || p >= 1) return;+ boilSeed('wipe');+ const n = 4, bh = (H + 300) / n;+ for (let i = 0; i < n; i++) {+ const d = [0, .12, .05, .16][i];+ const q = p < .5 ? easeOut(clamp((p * 2 - d) / (1 - d))) : ease(clamp(((p - .5) * 2 - d) / (1 - d)));+ const x0 = p < .5 ? -200 : lerp(-200, W + 300, q), x1 = p < .5 ? lerp(-200, W + 300, q) : W + 300;+ if (x1 - x0 < 30) continue;+ const y0 = -150 + i * bh, col = cols[i % cols.length];+ paint(rectPts(x0, y0 - 10, x1 - x0, bh + 20, 6), { wash: mixCol(col, PAL.paper, .25), ink: null });+ scribbleFill(rectPts(x0, y0 - 10, x1 - x0, bh + 20), mixCol(col, PAL.ink, .12), { ang: 1.35 + i * .15, gap: 26, w: 1.2, over: 0 });+ }+}+// kept for compatibility with painted-animation scene code+const brushWipe = (p, cols) => crayonWipe(p, cols);diff --git a/.claude/skills/crayon-storybook/template/studio.html b/.claude/skills/crayon-storybook/template/studio.htmlnew file mode 100644index 0000000..c5bddb6--- /dev/null+++ b/.claude/skills/crayon-storybook/template/studio.html@@ -0,0 +1,39 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>Crayon storybook studio</title>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=LXGW+WenKai+TC:wght@400;700&family=Zen+Maru+Gothic:wght@700&display=block">+<style>+ html, body { margin: 0; background: #1b1820; color: #eee; font: 13px system-ui, sans-serif; }+ main { padding: 12px; display: grid; gap: 8px; }+ #out { width: min(100%, 1280px); aspect-ratio: 16 / 9; height: auto; background: #F7EFDD; }+ .p5Canvas { display: none !important; }+ .bar { display: flex; gap: 10px; align-items: center; max-width: 1280px; }+ #scrub { flex: 1; }+ #tt { font-variant-numeric: tabular-nums; min-width: 190px; }+</style>+<script src="node_modules/p5/lib/p5.min.js"></script>+<script src="node_modules/p5.brush/dist/p5.brush.crayon.js"></script>+</head>+<body>+<main>+ <canvas id="out" width="1920" height="1080"></canvas>+ <div class="bar"><input id="scrub" type="range" min="0" max="10" step="0.0417" value="0"><span id="tt">loading…</span></div>+</main>+<!-- engine: config, runtime, the crayon look, the cast, the timeline -->+<script src="src/config.js"></script>+<script src="src/core.js"></script>+<script src="src/crayon.js"></script>+<script src="src/cast.js"></script>+<script src="src/timeline.js"></script>+<!-- reference sheets (standalone loops: ?loop=cast, ?loop=looks) -->+<script src="src/sheets.js"></script>+<!-- your video: add a script per scene file, in order -->+<script src="src/scenes/demo.js"></script>+<script>+ // Open studio.html?loop=cast (or looks) to scrub a standalone loop instead of the video.+ const q = new URLSearchParams(location.search).get('loop'); if (q && LOOPS[q]) window.LOOP = LOOPS[q];+</script>+</body>+</html>diff --git a/.claude/skills/paper-cutout/GUIDE.md b/.claude/skills/paper-cutout/GUIDE.mdnew file mode 100644index 0000000..bf8c563--- /dev/null+++ b/.claude/skills/paper-cutout/GUIDE.md@@ -0,0 +1,233 @@+# Paper cut-out engine: the guide++Read this whole file before drawing. It covers the look, the full API with examples, the puppet system, how to review+and the known pitfalls. For storytelling craft (reads, timing, anticipation, one read at a time, transitions at every+seam, "something happens in every shot") follow `.claude/skills/painted-animation/template/ANIMATION_GUIDE.md` — it+applies here unchanged, except that this engine **does** allow captions (via `captionTrack`).++Model sheets: `docs/expressions.jpg` (all 13 expressions, both puppets, both views), `docs/poses.jpg` (holding,+walking, jumping), `docs/demo-sheet.jpg` (the demo). Re-render them any time:+`node render.mjs --loop=faces --sheet=0 --cols=1 --w=1600 --out=out/check/faces.jpg` (and `--loop=poses`).++---++## 1. The look++A tabletop stop-motion film made of paper. Everything on screen is a cut or torn piece of real-looking paper lying on+the layer below, lit by a warm lamp from the top-left and photographed a frame at a time.++- **Materials** (`mat`): `paper` construction paper (default: mottled, fibres), `card` smooth cardstock (whites, eyes,+ labels, clouds), `kraft` brown fibre paper with specks (trunks, sticks, paths, boxes), `felt` fuzzy (rugs, animals,+ cosy things), `tissue` see-through and multiplies over what's under it (glows, water, cheeks, sun cores, glass),+ `corr` corrugated card (boxes, buildings, signs), `wood` (the table itself). Textures are generated once in+ `ENGINE.setup` and cached per colour.+- **Edges.** Scissor cuts are slightly faceted and wobbly (deterministic per `seed`). Torn edges (`torn:`) get a jagged+ line and a lighter fibrous rim — use them for hills, grounds, water, labels and anything "ripped out of a magazine".+- **Depth is shadow.** Each piece drops a soft warm shadow down-right; `depth` sets how far above the layer below it+ floats (offset + blur). Stack layers from back to front: backdrop (0) → far hills .3–.8 → set pieces ~1 → puppets+ 1–1.3 → things lifted off the page 1.5–3. Parallax with `layer(k)`.+- **Palette** `PC.*`: construction-paper colours (`cream sky mint sage leaf grass forest teal orange tangerine mustard+ yellow lemon red tomato rose pink blush peach lilac violet plum navy blue kraft cork brown bark ink …`). Use hex+ colours only (`mixCol(a, b, k)` to blend). Avoid pure black and white — use `PC.ink`, `PC.white` (warm).+- **Photographed finish** (automatic, `ENGINE.end`): warm lamp falloff/vignette, a soft warm spot top-left, per-step+ exposure flicker and a light grain that changes each step. Tune with `PAPER.vignette / flicker / grain / shadow`+ (0 turns off).+- **Stop-motion.** Puppets and props move in steps of `PAPER.fps` (12/s) — use `sm(lt)` for every pose. Each puppet+ piece shifts a hair per step (`PAPER.jit`, set automatically ≈ u/50 px) like hand-placed paper. Set dressing is glued+ (no jitter) but can `sway()` in steps. Camera: smooth (motion-control rig) or `stepped` (hand-nudged).+- **No 3D projection.** Turns use the drawn `front` / `3q` views; depth is overlap, scale, shadow and parallax only.++## 2. Structure of a video++```+studio.html → src/config.js, src/kit.js, fonts, src/cutout.js, src/cast.js, src/scenes/<shot>.js …+```++```js+// src/scenes/meadow.js+(() => {+ function meadow(t, lt, dur) { // t = video time, lt = time in shot, dur = shot length+ const st = sm(lt); // the stop-motion clock: use it for all poses+ paperCam(lt, [[0, [960, 540, 1]], [dur, [930, 560, 1.12]]]); // slow push-in (smooth)+ backdrop(PC.sky, { to: 'rgba(255,240,210,.35)' });+ layer(.3, () => { sun(1560, 190, 85); cloud(420, 210, 300, { hang: 'string', seed: 1 }); });+ layer(.6, () => hills(960, 720, 3800, 110, PC.mint, { seed: 3 }));+ hills(960, 920, 3800, 50, PC.leaf, { seed: 5 });+ const m = moods(lt, [[0, 'neutral'], [1.2, 'surprised']]);+ const J = pom(800, 960, 64, { view: '3q', ...m, look: [.6, -.4], armR: [100, 10], holdR: 'balloon' });+ if (st >= 1.2) emote('!', J.top[0], J.top[1] - 20, 40, st - 1.2);+ layer(1.25, () => grass(400, 1010, 900, 60, PC.grass, 3)); // foreground plane+ camEnd(); // transitions are screen-space: after camEnd+ trTear(t, seg(sm(lt), 0, .7)); // this shot tears in over the previous one+ }+ shots([[4.25, meadow]]);+})();+```++A shot paints the whole frame. Use one file per shot; scenes only call the library and the cast.++## 3. API reference (`src/cutout.js`)++### Time & randomness+- `sm(lt, fps = PAPER.fps)` — stepped time (hold each pose for 1/12 s). `onStep`, `onTwos`, `seg`, `kf`, `ease*`,+ `spring`, `jump`, `take`, `arcPt`, `hash`, `rnd(key)` come from kit.js.+- `sway(key, amp, freq)` — stepped sine for set dressing (trees, flags, dangling things); phase from `key`.+- `fbm1(x, seed)` — smooth 1D noise 0..1.++### Shapes (`SH`) — dense outlines in local px around (0,0)+| call | notes |+|---|---|+| `SH.ellipse(rx, ry)`, `SH.circle(r)` | |+| `SH.rect(w, h)`, `SH.round(w, h, r)` | centred |+| `SH.poly([[x,y],…])` | straight edges, sharp corners |+| `SH.smooth([[x,y,corner?],…])` | closed Catmull-Rom curve through the points — the general organic tool |+| `SH.capsule(len, r0, r1)` | limb from (0,0) down to (0,len) with round ends; rotate with `rot` |+| `SH.blob(r, n, amt, seed)` | lumpy circle (foliage, bushes) |+| `SH.cloud(w, h, seed)` | scalloped top, flat bottom; origin at bottom centre |+| `SH.leaf(len, w)` | from (0,0) up to (0,-len) |+| `SH.heart(s)`, `SH.star(r1, r2, n)`, `SH.drop(r)`, `SH.tri(w, h)` | |+| `SH.band(r, th, a0, a1)` | curved strip (smiles, brows, rainbows, tails); angles in deg, 0 = right, 90 = down |+| `SH.zig(w, h, n, seed)` | zig-zag top strip (grass, fringe); base at y=0 |+| `SH.hills(w, h, n, seed, down)` | rolling top edge around y=0, extends `down` px |+| `clipHalf(shape, nx, ny, c)` | keep the part where nx·x + ny·y ≤ c (eyelids, bibs, half moons) |+| `xform(shape, dx, dy, sx, sy)` | move/scale a shape |++### The piece+`piece(shape, o)` draws one cut-out. Options:+`x, y` position · `rot` degrees · `sx, sy` scale (mirror with -1) · `col` hex · `mat` material · `depth` shadow height+(default 1) · `seed` (cut wobble, texture offset, jitter — give every distinct piece its own) · `torn: true | 'top' |+'bottom' | 'left' | 'right' | 'sides'` · `tornAmp` (px, default 5) · `rim` colour of the torn core · `wob` scissor+wobble px · `alpha` · `jit` per-step jitter px (default `PAPER.jit`) · `edge: false` (no thin edge line).++Other primitives: `brad(x, y, r)` brass split pin · `thread(pts, { col, w })` string with a faint shadow ·+`popUp(k, x, y, fn)` draws `fn` unfolding from a hinge line at y (pop-up book elements; k 0 → 1) ·+`mat(col, kind)` / `matPat(col, kind, seed)` the texture patterns · `setShadow(depth)` / `noShadow()`.++### Camera & depth+- `paperCam(lt, keys, { stepped, fps, ease })` — keys `[[t, [cx, cy, zoom, rotDeg]], …]` in shot time; calls+ kit's `camBegin`. End with `camEnd()`.+- `layer(k, fn)` — parallax plane inside the camera: `k < 1` far (moves and zooms less), `k > 1` foreground.+- `backdrop(col, { to, mat, par })` — screen-filling sheet; `to` = gradient colour toward the bottom; `par` how much+ it slides with the camera (default .15).+- `table({ col })` — the wooden table (seen around flip cards / pop-up pages).++### Set dressing+`hills(x, y, w, h, col, { bumps, seed, depth, torn, tornAmp, mat, down })` ·+`grass(x, y, w, h, col, seed)` · `tree(x, y, s, { cols, trunk, seed, sway, fruit })` → `{ top, fruit: [[x,y]…], sway }`+(`fruit: [[dx, dy]…]` offsets from the crown centre ×s; hang props there) · `bush(x, y, s, { cols, seed })` ·+`flower(x, y, s, col, { center, stem, seed, sway })` · `cloud(x, y, w, { col, hang: 'string' | 'stick', bob, seed,+depth })` · `sun(x, y, r, { col, col2, rays, spin })` · `house(x, y, s, { wall, roof, door, win })` ·+`stripes(x, y, w, h, n, cols)` · `bunting(x0, y0, x1, y1, n, cols, { sag })` ·+`confetti(lt, x, y, { t0, n, cols, spread, power, size, seed })`.++### Props (`PROPS`) — drawn around a grip point+`PROPS.apple | balloon | flower | star | gift | letter (x, y, ang, s, col?)`. `s` ≈ size unit (a character's u × .6–.9).+Add new props in the same style: a function of `(x, y, ang, s)` made of `piece()` calls with fixed seeds.++### Transitions (screen space, after `camEnd()`)+Called by the **incoming** shot over its first frames with `k` going 0 → 1 (use stepped time:+`seg(sm(lt), 0, .7)`). They re-render the previous shot live via `prevFrame(t)`, so **the previous shot must not+draw an out-transition of its own**.++| call | what you see | good for |+|---|---|---|+| `trBook(t, k)` | the new scene stands up off the page from a bottom hinge (table behind for the first shot) | the opening, "once upon a time", new chapter |+| `trTear(t, k, { seed, rot })` | the old frame tears down a ragged line; the halves pull apart | a change of place, a surprise |+| `trFlip(t, k, { tilt })` | the old frame is a card that flips over on the table; its back is the new shot | time skip, "meanwhile", close-ups |+| `trSlide(t, k, { dir })` | the new shot on a sheet slides over the old one | fast continuity, lists |+| `sheetIn(k)` / `sheetOut(k, { col, dir })` | a plain paper sheet with a torn edge slides off / over | the very start / the very end |++### Captions+`captionTrack([[t0, t1, text, opts], …])` (call once per file; tracks accumulate). `opts.style`:+- `'label'` (default): ink text on a torn white card label with a bit of tape — subtitles, speech. `size` 72.+- `'letters'`: every glyph cut out of coloured paper with a white margin, popping in one by one — titles, shouts.+ `size` 96, `cols` palette, `y` 150.+Both pop in and out on the stop-motion step, sit above the grain, and use the CJK font stack+`"Chiron GoRound TC", "Zen Maru Gothic", "Noto Sans TC"`. All caption text is preloaded in `ENGINE.setup`. Keep lines+short (≤ 12 CJK chars) and ≥ 70 px so they read at phone width.++## 4. Puppets (`src/cast.js`)++Jointed paper puppets: every part is its own piece (so it casts a shadow on the part behind), joined by brass brads at+shoulders, elbows, hips and knees. Arms are forward kinematics; legs are 2-bone IK to planted feet, so crouches bend+the knees and feet never slide or detach.++### The two demo characters+- **Pom** — `pom(x, y, u, opts)`: round orange critter with pointy ears, cream muzzle, tuft, curled tail, teal+ overalls, red boots. ~8.5u tall. Medium shot u 55–75; close-up 85–110. Stubby arms: raised hands reach beside the+ head (angle ~135°), never above it.+- **Lulu** — `lulu(x, y, u, opts)`: tall girl puppet, navy bob with bun, mustard coat with brass buttons, rose scarf+ (swings behind), lilac tights, red shoes. ~15u tall. Medium shot u 34–42; close-up 55–70.++### Options (both)+| option | meaning |+|---|---|+| `face` | expression name (below) or an object `{ eye, lid, low, tilt, brow:[lift, ang], mouth, cheek, pupil, pupilY, tears, sweat, vein }`; `faceMix` overrides fields |+| `view` | `'front'` or `'3q'` (three-quarter, facing screen-right). `flip: true` mirrors (face left) |+| `look` | `[lx, ly]` −1..1 pupil direction (or a number) |+| `blink` | extra lid 0..1 (auto-blink always runs, desynced per puppet; `blink: false` disables it) |+| `armL`, `armR` | `[shoulder, elbow]` degrees: 0 hangs down, +90 points to the facing side, ±180 up, −90 back. Elbow adds to the shoulder angle. In 3q, `armL` is the far arm (drawn behind the body, slightly darker) |+| `footL`, `footR` | `[dx, dy]` in u from the rest spot (dy < 0 lifts) — IK bends the knees |+| `sq` | squash (+: hips drop, knees bend, torso widens) / stretch (−) |+| `dy` | whole-puppet vertical offset in u (jumps; up negative) |+| `lean`, `tilt` | torso lean, head tilt (degrees, + toward the facing side) |+| `holdL`, `holdR` | prop in the hand: `'apple'`, `{ prop: 'apple', s: .7, dy: -.3, ang, col }` or `(x, y, ang, u) => …`. Drawn between palm and thumb |+| `jit` | per-step jitter px (default ≈ u/50; 0 locks the pose) |+| `seed` | variant seed (desyncs blinks/jitter of two copies of the same puppet) |+| `dry` | measure only: returns joints, draws nothing |++Returns joints in world px: `{ hand: [L, R], elbow, shoulder, foot, head, top, mouth }` — aim props, emotes, eye-lines+and hand-offs at these. Use `dry: true` to find where a hand WILL be (the demo hangs the apple exactly where Pom's hand+is at the top of his jump).++### Expressions (`EXPR`)+`neutral happy laugh sad cry angry surprised scared love sleepy wink determined shy` — built from layered paper:+white card eye + pupil + highlight, eyelid pieces in skin colour (upper `lid`, lower `low`, slant `tilt`), strip brows,+blush circles, replacement mouths (`flat set small smile grin open frown o wail grit wobble`), `^ ^` / `> <` / heart+eyes, tissue tears and sweat, anger vein. Add a new one by adding an entry to `EXPR`.++### Helpers+- `moods(lt, [[t, face], …])` → `{ face, blink, sq, dy }`. Replacement-animation change: the eyes blink shut on the+ swap step, with a little take for big emotions. Spread it in, and ADD its `sq`/`dy` if you also jump.+- `walkCycle(lt, { rate, stride, lift, swing, lean, phase })` → `{ footL, footR, armL, armR, dy, lean }` (stepped).+ Move the puppet at `walkSpeed(o) * u` px/s to keep planted feet from sliding. Use `view: '3q'` (+ `flip` to go left).+- `jumpPose(lt, t0, t1, h)` → crouch with arms back (anticipation) → stretch, arms up, feet tucked → land squash and+ settle (follow-through). Override `armR` in the air for a reach.+- `emote(kind, x, y, s, age)` — `'!' '?' heart sweat zzz anger sparkle note`, pops in on steps. Put it at `J.top`.++### Making a new character+Copy the `POM` or `LULU` definition: joint layout per view (`front`, `'3q'`: hips, feet, shoulders, neck, head in u+from the hip centre), limb lengths/radii, colours, `footShape`, and three draw functions — `back` (behind everything:+tails, scarf ends), `body` (torso and clothes, drawn in the body frame), `head` (ears/hair behind, head, then+`drawFace(F, u, e, …)`, then noses/fringes on top). Put a `face` spec (eye positions/sizes, lid/cheek colours, mouth+position, 3/4 `turn` shift). Then `const myChar = (x, y, u, o) => puppet(DEF, x, y, u, o)`. Use user-provided designs+the same way: trace their shapes into `SH.smooth` control points.++## 5. Reviewing++Do the painted-animation review loop: sheets per shot, strips of every key motion and transition, crops of every+face and hand. Specific to this look, check:+- **It reads as paper:** fibres visible at full res, edges faceted/torn, every layer has a shadow, nothing flat-vector.+- **Depth order:** far things smaller, paler, less shadow; the puppet clearly separated from its background.+- **Joints:** limbs connect at brads in every frame (strip the action); held props sit in the hand between palm and+ thumb; feet on the ground line (use the same `y` for puppet and ground).+- **Stop-motion feel:** poses change on steps (pairs of identical frames at 24 fps) but set pieces don't jitter;+ nothing drifts smoothly that should be stepped (unless it's a camera move).+- **Faces:** expression changes through `moods()`, eyes aimed at what matters (`look`), expressions readable in a+ 480 px-wide sheet.+- **Captions:** readable at 480 px width, not covering faces.++## 6. Known pitfalls++- Everything must be a pure function of `t` (frames render in parallel). No `Math.random()`, no accumulators.+- Re-using a `seed` for two copies of the same shape gives identical cuts; vary it.+- Animating a shape's *size* re-cuts its edge every frame (shimmer). Scale with `sx/sy`, `popUp`, or the camera.+- A shot that is followed by `trTear/trFlip/trBook/trSlide` keeps running past its end (the next shot renders it at+ the current time) — keep its last pose valid for `lt > dur`, and don't draw an out-transition in it.+- Transitions and `backdrop` work in screen space; call transitions after `camEnd()`.+- Tissue multiplies: a light tissue over a saturated colour goes dark/muddy — use `card`/`paper` for light spots over+ strong colours.+- Pom's arms can't reach above his head; stage reaches to the side or give him a prop that extends his reach.+- Very large pieces (> 1500 px) are fine but keep `depth` modest (< .5) or the shadow halo gets heavy.+- Captions: fonts load from Google Fonts at page load (network needed then); glyphs missing in Chiron GoRound TC fall+ back to Zen Maru Gothic / Noto Sans TC.diff --git a/.claude/skills/paper-cutout/SKILL.md b/.claude/skills/paper-cutout/SKILL.mdnew file mode 100644index 0000000..023c8d2--- /dev/null+++ b/.claude/skills/paper-cutout/SKILL.md@@ -0,0 +1,73 @@+---+name: paper-cutout+description: Make paper cut-out / stop-motion style animated videos (MP4) with code — handmade construction paper, cardstock, kraft, felt and tissue pieces with scissor-cut or torn edges and soft drop shadows, photographed on a table under a warm lamp; jointed paper puppets with brass split-pin joints, moving in 12 fps steps. Canvas 2D rendered frame by frame in headless Chrome, encoded with ffmpeg. Use when a reference video or brief calls for paper craft, cut-paper, papercraft, stop-motion paper, kids' storybook collage, 剪紙 / 紙片 / 紙偶 / 定格動畫 looks, or when the video-clone router picks the paper-cutout style.+---++# Paper cut-out (stop-motion paper) engine++Every frame is a pure function of time `t`. `studio.html` loads `src/kit.js` (shared ReelMimic runtime: timeline,+motion helpers, camera, render hooks), `src/cutout.js` (this look: materials, cut/torn pieces, shadows, set dressing,+props, transitions, captions, the photographed finish), `src/cast.js` (the puppets) and one scene file per shot.+`render.mjs` drives headless Chrome for contact sheets, strips, crops and the final frames.++## Workflow++1. **Scaffold** — `bash .claude/skills/paper-cutout/scripts/new_project.sh <project-dir>` (add `--keep-demo` to keep+ the example). Then read **`GUIDE.md`** (in this skill folder) in full, and look at `docs/demo-sheet.jpg`,+ `docs/expressions.jpg` (13 expressions × both puppets) and `docs/poses.jpg`.+2. **Storyboard** with reads (what the viewer must understand, when) — the same discipline as painted-animation's+ `ANIMATION_GUIDE.md` (timing, one read at a time, anticipation → action → follow-through, transitions at every seam).+3. **Build** one IIFE file per shot in `src/scenes/`, each ending with `shots([[t0, fn]])`; add its `<script>` to+ `studio.html` after `cast.js`. Set `duration` in `src/config.js`. Start shots on multiples of 1/12 s.+4. **Look** — `node render.mjs --sheet=... --cols=4 --w=480 --out=out/check/a.jpg`, `--strip=a:b` for motion,+ `--crop=x,y,w,h` / `--crop-at=` for faces and hands. Open every image with Read. Fix, re-render.+5. **Render** — `node render.mjs --frames --workers=4 && node render.mjs --encode --out=out/video.mp4 [--audio=...]`.++## API in one screen (all angles in DEGREES, sizes in px, time via `sm(lt)`)++```js+paperCam(lt, [[0,[cx,cy,zoom]], [2,[cx,cy,zoom]]], { stepped }) // camBegin with a (smooth | stepped) move+backdrop(PC.sky, { to }) layer(.5, () => ...) // screen-fixed sheet; parallax depth plane+hills(x,y,w,h,col,{seed,torn}) grass(x,y,w,h,col,seed) tree(x,y,s,{fruit,sway}) → {fruit:[[x,y]..]} bush flower+cloud(x,y,w,{hang:'string'|'stick'}) sun(x,y,r) house(x,y,s) bunting(x0,y0,x1,y1,n,cols) stripes confetti(lt,x,y,{t0})+piece(SH.xxx(...), { x,y,rot,sx,sy, col, mat, depth, torn, seed, alpha, jit }) // ONE cut-out; the base of everything+SH.ellipse/circle/rect/round/poly/smooth/capsule/blob/cloud/leaf/heart/star/drop/tri/band/zig/hills ; clipHalf ; xform+mat: 'paper' | 'card' | 'kraft' | 'felt' | 'tissue' | 'corr' | 'wood' brad(x,y,r) thread(pts) popUp(k,x,y,fn)+PROPS.apple|balloon|flower|star|gift|letter(x, y, ang, s)+// transitions — call AFTER camEnd(), in the INCOMING shot, k = 0→1 on stepped time:+trBook(t,k) trTear(t,k) trFlip(t,k) trSlide(t,k,{dir}) sheetIn(k) sheetOut(k)+captionTrack([[t0, t1, '文字', { style: 'label' | 'letters', y, size }]])++// puppets (cast.js) — (x, y) = ground point, u = size unit+pom(x, y, u, opts) lulu(x, y, u, opts) → joints { hand:[L,R], elbow, shoulder, foot, head, top, mouth }+opts: face, view:'front'|'3q', flip, look, blink, armL/armR:[shoulder,elbow], footL/footR:[dx,dy], sq, dy, lean, tilt,+ holdL/holdR:'apple'|{prop,s,dy}|fn, jit, dry (measure only)+moods(lt, [[0,'sad'],[2,'surprised']]) walkCycle(lt,{stride,rate}) + walkSpeed() jumpPose(lt,t0,t1,h) emote(kind,x,y,s,age)+EXPR: neutral happy laugh sad cry angry surprised scared love sleepy wink determined shy+```++## Rules that matter most++1. **Everything is paper.** Draw only through `piece()` / the helpers (never raw `fillRect`/`arc` in scenes). Pick a+ material per object; torn edges for landscapes and labels, scissor edges for characters and props.+2. **Depth = shadow.** Background layers `depth` .3–.8, set pieces ~1, puppets 1–1.3, things floating/held up 1.5–3.+ Parallax with `layer(k)`. Never fake 3D.+3. **Stop-motion timing.** Drive every puppet/prop pose with `sm(lt)` (12 steps/s). Puppets jitter a hair per step by+ themselves; set pieces stay glued (`jit: 0`). Camera moves may be smooth (motion control) or `stepped`.+4. **Replacement faces.** Change expressions with `moods()` (blink hides the swap), not by flipping `face` per frame.+5. **Transitions from the kit of four** (book fold, torn reveal, flip card, sheet slide) at every seam; the previous+ shot must NOT draw its own out-transition when the next shot uses one of them (they re-render it live).+6. **Legible at phone size:** puppets big (pom u ≥ 55, lulu u ≥ 36 in a medium shot), captions ≥ 70 px.+7. Captions only via `captionTrack` (overlay, CJK font "Chiron GoRound TC" → "Zen Maru Gothic" → "Noto Sans TC").++## Engine gotchas++- Pure function of `t`: no `Math.random()`, no state between frames. Use `hash`/`rnd`/`sway(key)`.+- `piece()` caches the cut outline by shape key + `seed`. Give each distinct piece its own `seed`, or two identical+ shapes get identical wobble (fine for confetti, odd for a pair of trees).+- The cut outline depends on the shape's size, so an animated size re-cuts every frame (edges shimmer). Scale with+ `sx/sy` or the camera instead of animating the shape's dimensions.+- `prevFrame()` renders the previous shot at the CURRENT time (it keeps moving under a transition) and swaps `G`;+ scenes must use `G`, not a captured context.+- Props held by a flipped puppet are un-mirrored automatically (text/asymmetric props stay readable).+- Speed: ~5–30 ms draw per frame, ~130 ms/frame effective with 4 workers incl. JPEG encode at 1920×1080.diff --git a/.claude/skills/paper-cutout/docs/demo-sheet.jpg b/.claude/skills/paper-cutout/docs/demo-sheet.jpgnew file mode 100644index 0000000..88d4506Binary files /dev/null and b/.claude/skills/paper-cutout/docs/demo-sheet.jpg differdiff --git a/.claude/skills/paper-cutout/docs/expressions.jpg b/.claude/skills/paper-cutout/docs/expressions.jpgnew file mode 100644index 0000000..f0beafcBinary files /dev/null and b/.claude/skills/paper-cutout/docs/expressions.jpg differdiff --git a/.claude/skills/paper-cutout/docs/poses.jpg b/.claude/skills/paper-cutout/docs/poses.jpgnew file mode 100644index 0000000..f22c708Binary files /dev/null and b/.claude/skills/paper-cutout/docs/poses.jpg differdiff --git a/.claude/skills/paper-cutout/scripts/new_project.sh b/.claude/skills/paper-cutout/scripts/new_project.shnew file mode 100644index 0000000..740cd15--- /dev/null+++ b/.claude/skills/paper-cutout/scripts/new_project.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+# Scaffolds a project from this engine's template, installs deps and checks the toolchain.+# bash .claude/skills/<engine>/scripts/new_project.sh <project-dir> [--keep-demo]+set -e+SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"+TARGET="${1:?usage: new_project.sh <project-dir> [--keep-demo]}"+if [ -e "$TARGET/studio.html" ]; then echo "error: $TARGET already has a studio.html; not overwriting" >&2; exit 1; fi+mkdir -p "$TARGET"+if command -v rsync >/dev/null; then rsync -a --exclude node_modules --exclude out "$SKILL_DIR/template/" "$TARGET/"; else cp -R "$SKILL_DIR/template/." "$TARGET/"; rm -rf "$TARGET/node_modules" "$TARGET/out"; fi # Git Bash on Windows has no rsync+mkdir -p "$TARGET/assets" "$TARGET/out/check"+# The demo is an example, not a template: unless asked, unhook it so the new video starts clean.+if [ "${2:-}" != "--keep-demo" ]; then sed -i.bak 's#<script src="src/scenes/demo.js"></script>##' "$TARGET/studio.html" && rm -f "$TARGET/studio.html.bak"; fi+( cd "$TARGET" && npm install --silent --no-audit --no-fund )+echo "node $(node -v)"+command -v ffmpeg >/dev/null && echo "ffmpeg ok" || echo "MISSING: ffmpeg"+FOUND=+for c in "${CHROME_PATH:-}" "/c/Program Files/Google/Chrome/Application/chrome.exe" "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" /usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do+ [ -n "$c" ] && [ -x "$c" ] && { echo "chrome $c"; FOUND=1; break; }+done+[ "${FOUND:-}" = 1 ] || echo "MISSING: Chrome (install it, or pass --chrome=<path> to render.mjs)"+echo "== ready: $TARGET"diff --git a/.claude/skills/paper-cutout/template/.gitignore b/.claude/skills/paper-cutout/template/.gitignorenew file mode 100644index 0000000..9209ef5--- /dev/null+++ b/.claude/skills/paper-cutout/template/.gitignore@@ -0,0 +1,2 @@+node_modules+outdiff --git a/.claude/skills/paper-cutout/template/LICENSE-render.mjs.txt b/.claude/skills/paper-cutout/template/LICENSE-render.mjs.txtnew file mode 100644index 0000000..1215a85--- /dev/null+++ b/.claude/skills/paper-cutout/template/LICENSE-render.mjs.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 John Heibel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/.claude/skills/paper-cutout/template/package-lock.json b/.claude/skills/paper-cutout/template/package-lock.jsonnew file mode 100644index 0000000..ea79120--- /dev/null+++ b/.claude/skills/paper-cutout/template/package-lock.json@@ -0,0 +1,329 @@+{+ "name": "reelmimic-paper-cutout",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "reelmimic-paper-cutout",+ "license": "MIT",+ "dependencies": {+ "puppeteer-core": "^25.11.0"+ }+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.3.tgz",+ "integrity": "sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.4",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.4.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",+ "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^3.24.1"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1687809",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",+ "integrity": "sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.5",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.5.tgz",+ "integrity": "sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/puppeteer-core": {+ "version": "25.12.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.12.0.tgz",+ "integrity": "sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.3",+ "chromium-bidi": "17.0.2",+ "devtools-protocol": "0.0.1687809",+ "typed-query-selector": "^2.12.2",+ "webdriver-bidi-protocol": "0.4.3",+ "ws": "^8.21.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.3",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz",+ "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==",+ "license": "MIT"+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",+ "integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",+ "license": "Apache-2.0"+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.22.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.2.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",+ "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/.claude/skills/paper-cutout/template/package.json b/.claude/skills/paper-cutout/template/package.jsonnew file mode 100644index 0000000..1ca583e--- /dev/null+++ b/.claude/skills/paper-cutout/template/package.json@@ -0,0 +1,6 @@+{+ "name": "reelmimic-paper-cutout",+ "private": true,+ "license": "MIT",+ "dependencies": { "puppeteer-core": "^25.11.0" }+}diff --git a/.claude/skills/paper-cutout/template/render.mjs b/.claude/skills/paper-cutout/template/render.mjsnew file mode 100644index 0000000..9f7418a--- /dev/null+++ b/.claude/skills/paper-cutout/template/render.mjs@@ -0,0 +1,161 @@+// render.mjs: renders studio.html in headless Chrome. Length and fps come from the page (PROJECT in src/config.js).+//+// Look at it (open the images with your image viewer / Read tool):+// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)+// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point+// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera+// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs+// Make the video:+// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --encode --out=out/video.mp4 out/frames → MP4+// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or+// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)+// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,+// --chrome=<path to Chrome/Chromium>.+import puppeteer from 'puppeteer-core';+import { spawn } from 'node:child_process';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { homedir } from 'node:os';++const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));+const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+ ...playwrightChromes()];+// Chromium builds Playwright downloaded (~/.cache/ms-playwright/chromium-NNNN), newest first+function playwrightChromes() {+ const dir = `${homedir()}/.cache/ms-playwright`;+ if (!existsSync(dir)) return [];+ return readdirSync(dir).filter(n => /^chromium-\d+$/.test(n)).sort((a, b) => b.split('-')[1] - a.split('-')[1])+ .map(n => `${dir}/${n}/chrome-linux64/chrome`);+}+const CHROME = CHROMES.find(p => p && existsSync(p));+if (!CHROME) { console.error('Chrome not found: pass --chrome=<path> or set CHROME_PATH'); process.exit(1); }+const fps = +(args.fps || 24), FRAMES_DIR = 'out/frames';+const run = (cmd, a) => new Promise((ok, bad) => { const p = spawn(cmd, a, { stdio: 'inherit' }); p.on('close', c => c ? bad(new Error(cmd + ' exited ' + c)) : ok()); });+const times = s => String(s).split(',').map(Number);+const span = s => String(s).split(':').map(Number);+// comma-separated fields, keeping commas inside parentheses ('PLK.MX(1.38),PLK.WL,500,300'); numbers stay numbers+const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of String(s)) { if (ch === ',' && !d) { out.push(cur); cur = ''; continue; } d += ch === '(' ? 1 : ch === ')' ? -1 : 0; cur += ch; } out.push(cur); return out.map(v => isNaN(+v) ? v : +v); };++// JPEG frames decode as full-range (yuvj420p); without this the MP4 is flagged full-range and some players/platforms+// show it washed out or with crushed shadows. Convert to standard (tv) range and say so.+const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];++if (args.encode) {+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,+ ...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);+ console.log('wrote ' + out);+ process.exit(0);+}++// --soft-gl: no GPU on this machine; render WebGL in software (SwiftShader), which Chrome only allows when asked.+// --gpu-angle=vulkan|gl-egl: headless Linux on an NVIDIA GPU (e.g. a cloud or cluster node); plain --use-gl=angle gets+// no WebGL context there. Check which GPU Chrome actually lands on with gpu_probe.mjs.+const ANGLE = { vulkan: ['--use-angle=vulkan', '--enable-features=Vulkan'], 'gl-egl': ['--use-angle=gl-egl'] };+if (args['gpu-angle'] && !ANGLE[args['gpu-angle']]) { console.error(`--gpu-angle must be one of ${Object.keys(ANGLE)}`); process.exit(1); }+const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ : args['gpu-angle'] ? ANGLE[args['gpu-angle']]+ : process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];+// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.+const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+const browser = await puppeteer.launch({+ executablePath: CHROME, headless: true, protocolTimeout: 0,+ args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']+});+async function openPage(tag = '') {+ const page = await browser.newPage();+ page.on('console', m => { if (['error', 'warn'].includes(m.type())) console.log(`[page${tag}]`, m.text()); });+ page.on('pageerror', e => console.log(`[page error${tag}]`, e.message));+ await page.goto(pathToFileURL(resolve('studio.html')).href + '?render', { waitUntil: 'networkidle0' });+ await page.waitForFunction('window.ready === true', { timeout: 60000 });+ if (args.loop) {+ const ok = await page.evaluate(name => { if (!LOOPS[name]) return false; window.LOOP = LOOPS[name]; return true; }, args.loop);+ if (!ok) { console.error(`no loop named "${args.loop}"`); process.exit(1); }+ }+ return page;+}+const frameOf = async (page, t, type, q) => {+ const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);+ return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');+};+// the length of whatever is being rendered: a loop's .len, or the video's duration+const lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);++if (args.sheet || args.strip) {+ const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });+ let ts;+ if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ else ts = times(args.sheet);+ const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;+ const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);+ writeFileSync(out, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));+ console.log(`${out} (${ts.length} frames) ms/frame: ${ms.join(' ')}`);+} else if (args.stills) {+ const page = await openPage(), out = args.out || 'out/stills'; mkdirSync(out, { recursive: true });+ console.log('GPU:', await page.evaluate(() => window.gpuInfo()));+ for (const s of times(args.stills)) {+ const t0 = Date.now(), buf = await frameOf(page, s, 'image/png');+ const f = `${out}/t${s.toFixed(2).replace('.', '_')}.png`; writeFileSync(f, buf);+ console.log(`${f} ${Date.now() - t0} ms`);+ }+} else if (args.png) {+ // PNG sequence (for GIFs): a loop's full cycle (frame n equals frame 0, so it isn't rendered), or --range=a:b.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], n = Math.round((b - a) * fps);+ const out = args.out || `out/${args.loop ? 'loop_' + args.loop : 'png'}`, workers = +(args.workers || 3); mkdirSync(out, { recursive: true });+ let next = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < n) { const i = next++; writeFileSync(`${out}/f${String(i).padStart(4, '0')}.png`, await frameOf(page, a + i / fps, 'image/png')); }+ }));+ console.log(`${n} frames → ${out} (${((Date.now() - start) / n).toFixed(0)} ms/frame)`);+} else if (args.frames) {+ // Parallel and resumable: each worker pulls the next missing frame; files are written atomically.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);+ mkdirSync(FRAMES_DIR, { recursive: true });+ const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);+ const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }+ console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ let next = 0, done = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < todo.length) {+ const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;+ const buf = await frameOf(page, i / fps, 'image/jpeg', .94);+ writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ if (++done % 24 === 0 || done === todo.length) {+ const el = (Date.now() - start) / 1000;+ console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);+ }+ }+ }));+} else if (args.clip) {+ const page = await openPage(), len = await lengthOf(page);+ const [a, b] = args.range ? span(args.range) : typeof args.clip === 'string' ? span(args.clip) : [0, len];+ const audio = args.audio || await page.evaluate(() => PROJECT.audio || '');+ const out = args.out || 'out/clip.mp4'; mkdirSync(dirname(out), { recursive: true });+ const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',+ ...(audio ? ['-ss', String(a), '-t', String(b - a), '-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', ...TV_RANGE, '-movflags', '+faststart', out],+ { stdio: ['pipe', 'inherit', 'inherit'] });+ const n = Math.round((b - a) * fps), start = Date.now();+ for (let i = 0; i < n; i++) {+ const buf = await frameOf(page, a + i / fps, 'image/jpeg', .93);+ if (!ff.stdin.write(buf)) await new Promise(r => ff.stdin.once('drain', r));+ if (i % 24 === 0 || i === n - 1) console.log(`frame ${i + 1}/${n} ${((Date.now() - start) / (i + 1)).toFixed(0)} ms/frame`);+ }+ ff.stdin.end(); await new Promise(r => ff.on('close', r));+ console.log(`wrote ${out}`);+} else {+ console.log('nothing to do: see the usage notes at the top of render.mjs');+}+await browser.close();diff --git a/.claude/skills/paper-cutout/template/src/cast.js b/.claude/skills/paper-cutout/template/src/cast.jsnew file mode 100644index 0000000..a37ece9--- /dev/null+++ b/.claude/skills/paper-cutout/template/src/cast.js@@ -0,0 +1,372 @@+// cast.js: jointed paper puppets. Every body part is a separate cut piece; joints are brass split-pin brads, so limbs+// always visibly connect. Faces are layered paper (eye whites, pupils, eyelid pieces, brows, cheeks, replacement mouths).+//+// pom(x, y, u, opts) round orange critter in teal overalls (about 8.5u tall, 5u wide)+// lulu(x, y, u, opts) tall girl puppet in a mustard coat (about 15u tall, 4u wide)+// (x, y) = the ground point between the feet. u = size unit in px (medium shot: pom u≈55–75, lulu u≈32–42).+//+// opts (all optional):+// face expression name (see EXPR) or an object { eye, lid, brow, mouth, ... } — use moods() to change it+// view 'front' | '3q' (three-quarter, facing screen-right; add flip:true to face left)+// flip mirror the puppet+// look [lx, ly] pupils (-1..1), or a number for lx+// blink 0..1 extra eyelid (auto-blink runs anyway; blink:false turns auto-blink off)+// armL/armR [shoulder, elbow] degrees. 0 = hanging down, +90 = pointing toward the facing side (screen-right+// unless flipped), 180 = straight up, -90 = pointing back. Elbow adds to the shoulder angle.+// footL/footR [dx, dy] in u: foot offset from its rest spot (dy < 0 lifts it). Knees bend by IK, so feet stay planted.+// sq squash (+) / stretch (−): the hips drop and the knees bend, torso+head widen slightly+// dy whole-puppet vertical offset in u (jumps; up is negative)+// lean torso lean in degrees (+ = toward the facing side); tilt = head tilt in degrees+// holdL/holdR a prop in that hand: 'apple' | 'balloon' | 'flower' | 'star' | 'gift' | 'letter' |+// { prop, ang, s, col } | (x, y, ang, u) => draw. Drawn between the palm and the thumb (a real grip).+// jit per-step placement jitter in px (default ≈ u/50); 0 for a locked pose+// Returns the joints in world px: { hand: [L, R], elbow, shoulder, foot, head, top, mouth } for aiming props/emotes.++// ---------- expressions ----------+// eye: open | wide | arcUp (^ ^) | shut (> <) | heart ; lid 0..1 (upper eyelid) ; low 0..1 (lower lid, smiling eyes)+// tilt: lid slant (+ angry, − sad) ; brow: [lift, angle] (angle + = inner ends down/angry, − = worried)+// mouth: flat | set | small | smile | grin | open | frown | o | wail | grit | wobble ; cheek 0..2 ; tears, sweat, vein+const EXPR = {+ neutral: { eye: 'open', lid: .12, brow: [0, 0], mouth: 'flat', cheek: .7 },+ happy: { eye: 'open', lid: .06, low: .28, brow: [.25, -4], mouth: 'smile', cheek: 1 },+ laugh: { eye: 'arcUp', brow: [.45, -6], mouth: 'open', cheek: 1.2 },+ sad: { eye: 'open', lid: .4, tilt: -20, brow: [.1, -22], mouth: 'frown', cheek: .5, pupilY: .35 },+ cry: { eye: 'shut', brow: [.1, -24], mouth: 'wail', cheek: .9, tears: 1 },+ angry: { eye: 'open', lid: .42, tilt: 24, brow: [-.2, 26], mouth: 'grit', cheek: 0, vein: 1 },+ surprised: { eye: 'wide', pupil: .62, brow: [.8, -4], mouth: 'o', cheek: .4 },+ scared: { eye: 'wide', pupil: .45, brow: [.55, -20], mouth: 'wobble', cheek: 0, sweat: 1 },+ love: { eye: 'heart', brow: [.4, -8], mouth: 'grin', cheek: 1.6 },+ sleepy: { eye: 'open', lid: .7, brow: [-.05, -4], mouth: 'small', cheek: .6, pupilY: .3 },+ wink: { eye: 'open', eyeR: 'arcUp', lid: .05, low: .25, brow: [.3, -6], mouth: 'grin', cheek: 1.1 },+ determined: { eye: 'open', lid: .3, tilt: 12, brow: [-.1, 16], mouth: 'set', cheek: .4 },+ shy: { eye: 'open', lid: .25, pupilY: .4, look: [-.6, 0], brow: [.2, -12], mouth: 'small', cheek: 1.9 },+};+const MOUTH_IN = '#6E2331', MOUTH_LINE = '#4E2629';++// moods(lt, [[t, 'neutral'], [1.2, 'surprised'], ...]) → { face, blink, sq, dy } — a replacement-animation change:+// the eyes blink shut on the swap step (hiding the pop), with a small take on surprised/scared changes.+// Spread it into the puppet opts (add to sq/dy if you also jump): pom(x, y, u, { ...m, ... }).+function moods(lt, keys) {+ const st = sm(lt); let i = 0; while (i + 1 < keys.length && st >= keys[i + 1][0]) i++;+ const face = keys[i][1]; let blink = 0, sq = 0, dy = 0;+ for (let j = 1; j < keys.length; j++) {+ const tc = keys[j][0], d = Math.round((st - tc) * PAPER.fps);+ if (d === -1) blink = Math.max(blink, .55); else if (d === 0) blink = 1; else if (d === 1) blink = Math.max(blink, .45);+ const big = ['surprised', 'scared', 'angry', 'laugh'].includes(keys[j][1]);+ if (d === -1) sq += big ? .12 : .05;+ if (big && d >= 0 && d < 8) { const tk = take(st, tc, .8); sq += tk.sq; dy += tk.dy * .35; }+ }+ return { face, blink, sq, dy };+}+// auto blink: every few seconds, 3 steps, phase from the seed so two puppets never blink together+function autoBlink(seed) { const n = Math.floor(T * PAPER.fps + 1e-6), L = 38 + (seed % 3) * 11, p = (n + seed * 7) % L; return p === 0 ? .6 : p === 1 ? 1 : p === 2 ? .45 : 0; }++// walkCycle(lt, { rate, stride, lift, swing, phase }) → { footL, footR, armL, armR, dy, lean } (stepped)+// rate = full cycles per second. To keep planted feet from sliding, move the puppet at walkSpeed(o) * u px/s.+function walkCycle(lt, o = {}) {+ const rate = o.rate || 1.5, stride = o.stride ?? .75, lift = o.lift ?? .5, sw = o.swing ?? 34, p = frac(sm(lt) * rate + (o.phase || 0)), a = p * TAU;+ const leg = ph => { const b = ph * TAU; return [-Math.cos(b) * stride, -Math.max(0, Math.sin(b)) * lift]; };+ return { footL: leg(p), footR: leg(p + .5), armL: [-Math.cos(a) * sw + 4, 12], armR: [Math.cos(a) * sw + 4, 12], dy: -.14 * Math.abs(Math.sin(a)), lean: o.lean ?? 5 };+}+const walkSpeed = (o = {}) => 4 * (o.stride ?? .75) * (o.rate || 1.5);+// jumpPose(lt, t0, t1, h) → { dy, sq, armL, armR, footL, footR } : crouch + arms back → stretch + arms up → land squash+function jumpPose(lt, t0, t1, h = 3) {+ const st = sm(lt), j = jump(st, t0, t1, h), pre = seg(st, t0 - .3, t0), air = st >= t0 && st < t1, k = air ? (st - t0) / (t1 - t0) : 0, post = seg(st, t1, t1 + .35);+ let arm = st < t0 ? lerp(8, -40, pre) : air ? lerp(140, 110, k) : lerp(80, 10, post);+ const tuck = air ? Math.sin(k * Math.PI) : 0;+ return { dy: j.dy, sq: j.sq + (st < t0 ? .25 * pre : 0), armL: [-arm, air ? -10 : 10], armR: [arm, air ? 10 : 10], footL: [-.15 * tuck, -.45 * tuck], footR: [.2 * tuck, -.3 * tuck] };+}++// ---------- the generic puppet rig ----------+const dirOf = a => [Math.sin(a * D2R), Math.cos(a * D2R)];+function drawHold(h, x, y, ang, u) {+ if (!h) return;+ if (typeof h === 'function') return h(x, y, ang, u);+ const spec = typeof h === 'string' ? { prop: h } : h, f = PROPS[spec.prop]; if (!f) return;+ f(x + (spec.dx || 0) * u, y + (spec.dy || 0) * u, spec.ang ?? 0, (spec.s || .62) * u, spec.col);+}+function ik2(hx, hy, fx, fy, l1, l2, bend) { // → knee [x, y]; bend +1 = knee toward +x side of the hip→foot line+ let dx = fx - hx, dy = fy - hy, d = Math.hypot(dx, dy); const maxd = (l1 + l2) * .999; if (d > maxd) { dx *= maxd / d; dy *= maxd / d; d = maxd; }+ const a = Math.acos(clamp((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1)), base = Math.atan2(dy, dx), s = bend > 0 ? -1 : 1;+ // atan2 frame: rotating the hip→foot direction by -a swings toward +x when the foot is below the hip+ const ang = base + s * a; return [hx + Math.cos(ang) * l1, hy + Math.sin(ang) * l1];+}+function puppet(D, x, y, u, o = {}) {+ const view = o.view === '3q' ? '3q' : 'front', q3 = view === '3q', flip = o.flip ? -1 : 1, V = D[view];+ const sq = o.sq || 0, lean = o.lean || 0, sx = 1 + .28 * sq, sy = 1 - .28 * sq, crouch = Math.max(0, sq) * D.crouch * u - Math.max(0, -sq) * .6 * u;+ const hipY = -D.hipH * u + crouch, lr = lean * D2R, cs = Math.cos(lr), sn = Math.sin(lr);+ const B = (px, py) => { const X = px * u * sx, Y = py * u * sy; return [X * cs - Y * sn, hipY + X * sn + Y * cs]; };+ const oy = y + (o.dy || 0) * u, W2 = (lx, ly) => [x + flip * lx, oy + ly];+ let e = typeof o.face === 'object' ? o.face : EXPR[o.face || 'neutral'] || EXPR.neutral;+ if (o.faceMix) e = { ...e, ...o.faceMix };+ const blink = o.blink === false ? 0 : Math.max(autoBlink(D.seed + (o.seed || 0)), o.blink || 0);+ const look = o.look == null ? (e.look || [0, 0]) : Array.isArray(o.look) ? o.look : [o.look, 0];+ const S = D.seed + (o.seed || 0) * 1000;+ const savedJ = PAPER.jit, savedD = PAPER.dry; PAPER.jit = o.jit ?? Math.min(2.2, u / 50); if (o.dry) PAPER.dry = true;+ G.save(); G.translate(x, oy); if (flip < 0) G.scale(-1, 1);+ const J = { hand: [], elbow: [], shoulder: [], foot: [] };++ // --- arms (FK) ---+ const arm = (i) => {+ const sp = B(...V.shoulders[i]), pose = (i === 0 ? o.armL : o.armR) || D.restArm[i], a1 = pose[0] + lean, a2 = a1 + (pose[1] || 0);+ const d1 = dirOf(a1), el = [sp[0] + d1[0] * D.upper * u, sp[1] + d1[1] * D.upper * u], d2 = dirOf(a2), hd = [el[0] + d2[0] * D.fore * u, el[1] + d2[1] * D.fore * u];+ const far = q3 && i === 0, tint = far ? D.farTint : 0, col = c => tint ? mixCol(c, '#3A2A30', tint) : c;+ piece(SH.capsule(D.upper * u, D.armR[0] * u, D.armR[1] * u), { x: sp[0], y: sp[1], rot: -a1, col: col(D.sleeve || D.limb), mat: D.sleeveMat, depth: 1, seed: S + 11 + i });+ piece(SH.capsule(D.fore * u, D.armR[1] * u, D.armR[2] * u), { x: el[0], y: el[1], rot: -a2, col: col(D.sleeve2 || D.sleeve || D.limb), mat: D.sleeveMat, depth: 1, seed: S + 13 + i });+ if (D.cuff) piece(SH.round(D.armR[2] * 2.3 * u, D.armR[2] * 1.1 * u, D.armR[2] * .5 * u), { x: el[0] + d2[0] * (D.fore - .08) * u, y: el[1] + d2[1] * (D.fore - .08) * u, rot: -a2, col: col(D.cuff), depth: .5, seed: S + 15 + i });+ brad(el[0], el[1], D.brad * u);+ // hand: palm, prop, thumb over it+ piece(SH.circle(D.handR * u), { x: hd[0], y: hd[1], col: col(D.hand), depth: .9, seed: S + 17 + i });+ const hold = i === 0 ? o.holdL : o.holdR;+ if (hold) {+ G.save(); if (flip < 0) { G.translate(hd[0], hd[1]); G.scale(-1, 1); G.translate(-hd[0], -hd[1]); } // props stay readable (unmirrored)+ drawHold(hold, hd[0], hd[1], a2, u); G.restore();+ const td = dirOf(a2 + (i === 0 ? -70 : 70));+ piece(SH.ellipse(D.handR * .4 * u, D.handR * .58 * u), { x: hd[0] + td[0] * D.handR * .8 * u, y: hd[1] + td[1] * D.handR * .8 * u, rot: -a2, col: col(D.hand), depth: .8, seed: S + 19 + i });+ } else {+ const td = dirOf(a2 + (i === 0 ? -1 : 1) * 60 * (q3 ? 1 : 1));+ piece(SH.ellipse(D.handR * .42 * u, D.handR * .62 * u), { x: hd[0] + td[0] * D.handR * .78 * u, y: hd[1] + td[1] * D.handR * .78 * u, rot: -(a2 + (i === 0 ? -1 : 1) * 60), col: col(D.hand), depth: .6, seed: S + 21 + i });+ }+ brad(sp[0], sp[1], D.brad * u * 1.1);+ J.hand[i] = W2(...hd); J.elbow[i] = W2(...el); J.shoulder[i] = W2(...sp);+ };+ // --- legs (IK) ---+ const leg = (i) => {+ const hp = B(...V.hips[i]), off = (i === 0 ? o.footL : o.footR) || [0, 0], rest = V.feet[i];+ const ax = (rest[0] + off[0]) * u, ay = (-D.ankleH + (off[1] || 0)) * u;+ const bend = q3 ? 1 : (i === 0 ? -1 : 1), kn = ik2(hp[0], hp[1], ax, ay, D.thigh * u, D.shin * u, bend);+ const a1 = Math.atan2(kn[0] - hp[0], kn[1] - hp[1]) / D2R, kd = Math.hypot(ax - kn[0], ay - kn[1]), sd = Math.min(kd, D.shin * u), a2 = Math.atan2(ax - kn[0], ay - kn[1]) / D2R;+ const an = [kn[0] + Math.sin(a2 * D2R) * sd, kn[1] + Math.cos(a2 * D2R) * sd];+ const far = q3 && i === 0, col = c => far ? mixCol(c, '#3A2A30', D.farTint) : c;+ piece(SH.capsule(D.thigh * u, D.legR[0] * u, D.legR[1] * u), { x: hp[0], y: hp[1], rot: -a1, col: col(D.leg), mat: D.legMat, depth: 1, seed: S + 31 + i });+ piece(SH.capsule(sd, D.legR[1] * u, D.legR[2] * u), { x: kn[0], y: kn[1], rot: -a2, col: col(D.leg2 || D.leg), mat: D.legMat, depth: 1, seed: S + 33 + i });+ const fw = q3 ? 1 : (i === 0 ? -.45 : .45), toe = (off[1] || 0) < -.05 ? -8 * fw : 0;+ piece(D.footShape(u), { x: an[0] + fw * D.foot[2] * u, y: an[1] + D.foot[3] * u, rot: toe, sx: q3 || i === 1 ? 1 : -1, col: col(D.shoe), mat: D.shoeMat, depth: 1, seed: S + 35 + i });+ brad(kn[0], kn[1], D.brad * u);+ J.foot[i] = W2(an[0], an[1] + D.ankleH * u);+ };++ // draw order: far arm (3/4) · back pieces · legs · body · hip brads · head · near arms+ if (q3) arm(0);+ G.save(); G.translate(0, hipY); G.rotate(lr); G.scale(sx, sy); D.back(u, view, o, S); G.restore();+ leg(0); leg(1);+ G.save(); G.translate(0, hipY); G.rotate(lr); G.scale(sx, sy); D.body(u, view, o, S); G.restore();+ for (let i = 0; i < 2; i++) { const hp = B(...V.hips[i]); brad(hp[0], hp[1], D.brad * u * 1.1); }+ // head (tilt around the neck)+ const nk = V.neck, hc = V.head, tilt = (o.tilt || 0) + (flip < 0 ? 0 : 0);+ G.save(); G.translate(0, hipY); G.rotate(lr); G.scale(sx, sy); G.translate(nk[0] * u, nk[1] * u); G.rotate(tilt * D2R); G.translate((hc[0] - nk[0]) * u, (hc[1] - nk[1]) * u);+ D.head(u, view, o, S, e, { blink, look });+ G.restore();+ if (q3) arm(1); else { arm(0); arm(1); }+ G.restore(); PAPER.jit = savedJ; PAPER.dry = savedD;+ const hw = B(...V.head), tr = tilt * D2R;+ J.head = W2(hw[0], hw[1]); J.top = W2(hw[0] + Math.sin(tr + lr) * D.topR * u, hw[1] - Math.cos(tr + lr) * D.topR * u); J.mouth = W2(hw[0] + (q3 ? D.face.turn * u : 0), hw[1] + D.face.mouth[1] * u);+ return J;+}++// ---------- faces (layered paper) ----------+function drawFace(F, s, e, o, S) {+ const q3 = o.view === '3q', sh = q3 ? F.turn * s : 0, blink = o.blink || 0, L = o.look || [0, 0];+ const exOf = (x, i) => q3 ? x * .8 + sh + (i === 0 ? .06 * s : 0) : x;+ // cheeks first (under the eyes)+ if ((e.cheek ?? .7) > 0) F.cheeks.forEach(([cx0, cy0], i) => {+ const far = q3 && i === 0, k = e.cheek ?? .7, r = F.cheekR * s * (.75 + .25 * Math.min(k, 2));+ piece(SH.ellipse(r * (far ? .7 : 1), r * .8), { x: exOf(cx0 * s, i) + (far ? .1 * s : 0), y: cy0 * s, col: F.cheekCol || PC.pink, depth: .35, seed: S + 61 + i, alpha: clamp(.45 + .3 * k) });+ });+ F.eyes.forEach(([x0, y0], i) => {+ const side = i === 0 ? -1 : 1, far = q3 && i === 0, cx = exOf(x0 * s, i), cy = y0 * s, kind = (i === 1 && e.eyeR) || e.eye || 'open';+ const wide = kind === 'wide', rx = F.eyeR[0] * s * (far ? .78 : 1) * (wide ? 1.15 : 1), ry = F.eyeR[1] * s * (wide ? 1.15 : 1);+ const lid = clamp(Math.max(kind === 'wide' ? 0 : (e.lid || 0), blink));+ if (kind === 'heart') {+ piece(SH.heart(ry * 2.4), { x: cx, y: cy, rot: side * 8, col: PC.red, depth: .6, seed: S + 71 + i });+ piece(SH.ellipse(ry * .22, ry * .16), { x: cx - ry * .35, y: cy - ry * .25, col: PC.white, depth: .1, seed: S + 73 + i, edge: false });+ } else if (kind === 'arcUp' || (lid >= .97 && kind !== 'shut')) {+ const up = kind === 'arcUp';+ piece(SH.band(rx * .95, ry * .34, up ? 200 : 20, up ? 340 : 160), { x: cx, y: cy + (up ? ry * .45 : -ry * .35), col: F.lineCol || PC.ink, depth: .4, seed: S + 75 + i });+ } else if (kind === 'shut') {+ const d = -side * (q3 ? 1 : 1), w = rx * 1.1, t = ry * .22;+ piece(SH.poly([[-w * .55 * d, -ry * .55], [w * .55 * d, 0], [-w * .55 * d, ry * .55], [-w * .55 * d + t * d * 1.2, ry * .55 + t * .2], [w * .55 * d - t * 1.9 * d, 0], [-w * .55 * d + t * d * 1.2, -ry * .55 - t * .2]]), { x: cx, y: cy, col: F.lineCol || PC.ink, depth: .4, seed: S + 77 + i });+ } else {+ piece(SH.ellipse(rx, ry), { x: cx, y: cy, col: F.white || PC.white, mat: 'card', depth: .45, seed: S + 81 + i });+ const pr = F.pupil * s * (e.pupil ?? 1) * (far ? .9 : 1), mx = Math.max(0, rx - pr * 1.05), my = Math.max(0, ry - pr * 1.05);+ const px = cx + clamp(L[0] + (q3 ? .35 : 0), -1, 1) * mx * .8, py = cy + clamp((L[1] || 0) + (e.pupilY || 0), -1, 1) * my * .8;+ piece(SH.circle(pr), { x: px, y: py, col: F.pupilCol || PC.ink, depth: .3, seed: S + 83 + i });+ piece(SH.circle(pr * .32), { x: px - pr * .32, y: py - pr * .36, col: PC.white, depth: 0, seed: S + 85 + i, edge: false });+ if (lid > .02) {+ const E = SH.ellipse(rx * 1.14, ry * 1.14), phi = (e.tilt || 0) * -side * D2R, c0 = -ry * 1.14 + 2 * ry * 1.14 * lid;+ piece(clipHalf(E, Math.sin(phi), Math.cos(phi), c0), { x: cx, y: cy, col: F.lid, depth: .45, seed: S + 87 + i });+ }+ if ((e.low || 0) > .02) piece(clipHalf(SH.ellipse(rx * 1.14, ry * 1.14), 0, -1, -(ry * 1.14 * (1 - 2 * e.low))), { x: cx, y: cy, col: F.lid, depth: .35, seed: S + 89 + i });+ }+ // brow+ if (F.brow && e.brow) {+ const [lift, ang] = e.brow, bw = F.brow[0] * s * (far ? .8 : 1);+ piece(SH.round(bw, F.brow[1] * s, F.brow[1] * s * .5), { x: cx, y: cy - ry - F.brow[2] * s - lift * ry * .7, rot: -side * ang, col: F.browCol || PC.ink, depth: .35, seed: S + 91 + i });+ }+ // tears: tissue streams + falling drops+ if (e.tears) {+ const tx = cx + side * rx * .55;+ piece(SH.round(ry * .5, ry * 2.4, ry * .25), { x: tx, y: cy + ry * 1.6, col: '#8FD0F0', mat: 'tissue', depth: .2, seed: S + 95 + i });+ for (let k = 0; k < 2; k++) { const p = frac(sm(T) * 1.4 + k * .5 + i * .25); piece(SH.drop(ry * .32), { x: tx + side * p * ry * 1.4, y: cy + ry * (1.2 + p * 3.2), col: '#8FD0F0', mat: 'tissue', depth: .8, seed: S + 97 + k + i * 2, alpha: 1 - p * .6 }); }+ }+ });+ const mx = (F.mouth[0] * s) * (q3 ? .8 : 1) + sh * 1.05, my = F.mouth[1] * s;+ drawMouth(e.mouth || 'flat', mx, my, s * F.mouthS, S, q3);+ if (e.sweat) piece(SH.drop(.26 * s), { x: (F.sweat[0] * s) + sh * .6, y: F.sweat[1] * s + sm(T) * 0, col: '#9AD6F2', mat: 'tissue', depth: 1, seed: S + 99 });+ if (e.vein) { const vx = F.vein[0] * s + sh * .5, vy = F.vein[1] * s; for (let k = 0; k < 4; k++) piece(SH.band(.2 * s, .08 * s, 100, 170), { x: vx + (k % 2 ? .1 : -.1) * s, y: vy + (k < 2 ? .1 : -.1) * s, rot: k * 90, col: PC.red, depth: .5, seed: S + 101 + k }); }+}+function drawMouth(kind, x, y, s, S, q3) {+ const P = (sh, o) => piece(sh, { x, y, depth: .35, seed: S + 111, col: MOUTH_LINE, ...o });+ switch (kind) {+ case 'flat': P(SH.round(.6 * s, .12 * s, .06 * s)); break;+ case 'set': P(SH.round(.5 * s, .12 * s, .06 * s), { rot: -7 }); break;+ case 'small': P(SH.ellipse(.13 * s, .1 * s), { col: MOUTH_IN }); break;+ case 'smile': P(SH.band(.4 * s, .13 * s, 28, 152), { y: y - .3 * s }); break;+ case 'frown': P(SH.band(.36 * s, .12 * s, 212, 328), { y: y + .38 * s }); break;+ case 'grin': P(SH.smooth([[-.5 * s, -.1 * s, 1], [.5 * s, -.1 * s, 1], [.3 * s, .22 * s], [0, .3 * s], [-.3 * s, .22 * s]]), { col: MOUTH_IN }); piece(SH.ellipse(.2 * s, .08 * s), { x, y: y + .14 * s, col: PC.rose, depth: .1, seed: S + 112 }); break;+ case 'open': P(SH.smooth([[-.46 * s, -.16 * s, 1], [.46 * s, -.16 * s, 1], [.38 * s, .2 * s], [0, .5 * s], [-.38 * s, .2 * s]]), { col: MOUTH_IN }); piece(SH.ellipse(.24 * s, .12 * s), { x, y: y + .3 * s, col: PC.rose, depth: .1, seed: S + 113 }); piece(SH.round(.62 * s, .09 * s, .04 * s), { x, y: y - .1 * s, col: PC.white, depth: .1, seed: S + 114 }); break;+ case 'o': P(SH.ellipse(.2 * s, .27 * s), { col: MOUTH_IN }); piece(SH.ellipse(.11 * s, .08 * s), { x, y: y + .12 * s, col: PC.rose, depth: .1, seed: S + 115 }); break;+ case 'wail': P(SH.smooth([[-.5 * s, .08 * s, 1], [0, -.22 * s], [.5 * s, .08 * s, 1], [.36 * s, .42 * s], [0, .5 * s], [-.36 * s, .42 * s]]), { col: MOUTH_IN }); piece(SH.ellipse(.22 * s, .1 * s), { x, y: y + .36 * s, col: PC.rose, depth: .1, seed: S + 116 }); break;+ case 'grit': P(SH.round(.82 * s, .38 * s, .1 * s)); piece(SH.round(.7 * s, .26 * s, .06 * s), { x, y, col: PC.white, depth: .15, seed: S + 117 }); piece(SH.rect(.66 * s, .04 * s), { x, y, col: MOUTH_LINE, depth: 0, seed: S + 118, edge: false }); break;+ case 'wobble': { const a = [], n = 6, w = .7 * s, t = .1 * s; for (let i = 0; i <= n; i++) a.push([-w / 2 + w * i / n, (i % 2 ? -1 : 1) * .07 * s - t / 2]); for (let i = n; i >= 0; i--) a.push([-w / 2 + w * i / n, (i % 2 ? -1 : 1) * .07 * s + t / 2]); P(SH.poly(a)); break; }+ }+}++// ---------- emotes (paper marks that pop in, stepped) ----------+// emote(kind, x, y, s, age) kinds: '!' '?' heart sweat zzz anger sparkle note ; age = seconds since it appeared+function emote(kind, x, y, s = 40, age = 1) {+ const a = sm(age); if (a < 0) return; const pop = a < .25 ? backOut(a / .25) : 1, bob = sway('em' + kind, .08 * s, .9);+ G.save(); G.translate(x, y + bob); G.scale(pop, pop);+ const P = (sh, o) => piece(sh, { depth: 1.4, seed: 1900, jit: 0, ...o });+ switch (kind) {+ case '!': P(SH.poly([[-.3 * s, -1.6 * s], [.3 * s, -1.6 * s], [.15 * s, -.35 * s], [-.15 * s, -.35 * s]]), { col: PC.red }); P(SH.circle(.2 * s), { y: 0, col: PC.red, seed: 1901 }); break;+ case '?': P(SH.band(.45 * s, .26 * s, 180, 400), { y: -1.15 * s, col: PC.blue }); P(SH.round(.26 * s, .45 * s, .1 * s), { y: -.5 * s, col: PC.blue, seed: 1902 }); P(SH.circle(.17 * s), { y: 0, col: PC.blue, seed: 1903 }); break;+ case 'heart': P(SH.heart(1.2 * s), { rot: sway('eh', 8, .8), col: PC.red }); P(SH.heart(.55 * s), { x: .75 * s, y: -.8 * s, rot: 15, col: PC.rose, seed: 1904 }); break;+ case 'sweat': P(SH.drop(.35 * s), { col: '#9AD6F2', mat: 'tissue' }); break;+ case 'zzz': [0, 1, 2].forEach(i => { const z = (.35 + i * .15) * s; P(SH.poly([[-z, -z], [z, -z], [z, -z + z * .35], [-z * .35, z - z * .35], [z, z - z * .35], [z, z], [-z, z], [-z, z - z * .35], [z * .35, -z + z * .35], [-z, -z + z * .35]]), { x: i * .6 * s, y: -i * .8 * s, rot: -10, col: PC.lilac, seed: 1905 + i }); }); break;+ case 'anger': for (let k = 0; k < 4; k++) P(SH.band(.32 * s, .13 * s, 100, 170), { x: (k % 2 ? .16 : -.16) * s, y: (k < 2 ? .16 : -.16) * s, rot: k * 90, col: PC.red, seed: 1910 + k }); break;+ case 'sparkle': [[0, 0, 1], [.9, -.6, .55], [-.7, -.9, .45]].forEach(([dx, dy, k], i) => P(SH.star(.6 * s * k, .18 * s * k, 4), { x: dx * s, y: dy * s, rot: sway('sp' + i, 10, .7), col: i ? PC.lemon : PC.yellow, seed: 1915 + i })); break;+ case 'note': P(SH.ellipse(.32 * s, .24 * s), { rot: -20, col: PC.ink }); P(SH.rect(.1 * s, 1.1 * s), { x: .26 * s, y: -.55 * s, col: PC.ink, seed: 1920 }); P(SH.poly([[.2 * s, -1.1 * s], [.7 * s, -.85 * s], [.7 * s, -.6 * s], [.2 * s, -.8 * s]]), { col: PC.ink, seed: 1921 }); break;+ }+ G.restore();+}++// ---------- POM: round orange critter, teal overalls, red boots ----------+const POM = {+ seed: 1000, hipH: 2.05, crouch: 1.1, ankleH: .3, thigh: .95, shin: .92, legR: [.42, .38, .34], upper: .9, fore: .82, armR: [.36, .33, .3], handR: .44,+ brad: .13, topR: 3.2, farTint: .12,+ limb: PC.orange, sleeve: PC.orange, hand: PC.orange, leg: PC.orange, shoe: PC.red, restArm: [[-14, 8], [14, -8]],+ foot: [0, 0, .22, -.02], footShape: u => SH.smooth([[-.5 * u, .12 * u], [-.45 * u, -.22 * u], [.25 * u, -.3 * u], [.65 * u, -.05 * u], [.6 * u, .22 * u], [0, .3 * u]]),+ front: { hips: [[-.72, 0], [.72, 0]], feet: [[-.95, 0], [.95, 0]], shoulders: [[-1.45, -1.85], [1.45, -1.85]], neck: [0, -2.6], head: [0, -4.35] },+ '3q': { hips: [[-.35, -.05], [.62, 0]], feet: [[-.55, 0], [.75, 0]], shoulders: [[-.95, -1.95], [1.3, -1.8]], neck: [.1, -2.6], head: [.12, -4.35] },+ face: { eyes: [[-.8, -.28], [.8, -.28]], eyeR: [.44, .54], pupil: .27, lid: PC.orange, brow: [.55, .13, .22], browCol: PC.bark, lineCol: PC.ink,+ cheeks: [[-1.52, .4], [1.52, .4]], cheekR: .36, mouth: [0, .92], mouthS: .9, turn: .62, sweat: [2.2, -.9], vein: [1.4, -1.5] },+ back(u, view, o, S) { // curled tail behind the body (a thick paper crescent with a cream tip)+ const q3 = view === '3q', sd = q3 ? -1 : 1, w = sway('pomtail', 5, .7);+ G.save(); G.translate(sd * 1.25 * u, -.1 * u); G.scale(sd, 1); G.rotate(w * D2R);+ piece(SH.band(.95 * u, .5 * u, 95, 300), { x: .75 * u, y: -.95 * u, col: PC.orange, depth: 1, seed: S + 1 });+ const e = [.75 * u + Math.cos(300 * D2R) * .95 * u, -.95 * u + Math.sin(300 * D2R) * .95 * u];+ piece(SH.circle(.3 * u), { x: e[0], y: e[1], col: PC.tangerine, depth: .5, seed: S + 2 });+ G.restore();+ },+ body(u, view, o, S) {+ const q3 = view === '3q', bx = q3 ? .1 : 0, bs = q3 ? .93 : 1;+ const body = SH.smooth([[0, -2.9 * u], [1.3 * u, -2.5 * u], [1.8 * u, -1.25 * u], [1.6 * u, -.1 * u], [.85 * u, .42 * u], [0, .48 * u], [-.85 * u, .42 * u], [-1.6 * u, -.1 * u], [-1.8 * u, -1.25 * u], [-1.3 * u, -2.5 * u]]);+ piece(body, { x: bx * u, sx: bs, col: PC.orange, depth: 1.2, seed: S + 3 });+ piece(clipHalf(body, 0, -1, 1.0 * u), { x: bx * u, sx: bs, col: PC.teal, depth: .5, seed: S + 4 }); // trousers+ const bib = q3 ? .35 : 0;+ piece(SH.round(1.55 * u, 1.2 * u, .22 * u), { x: bib * u, y: -1.35 * u, col: PC.teal, depth: .5, seed: S + 5 }); // bib+ piece(SH.round(.7 * u, .5 * u, .1 * u), { x: (bib + .05) * u, y: -1.25 * u, rot: -3, col: mixCol(PC.teal, PC.navy, .3), depth: .3, seed: S + 6 }); // pocket+ [-1, 1].forEach((sd, i) => { const x0 = (bib + sd * .6) * u; piece(SH.round(.26 * u, 1.05 * u, .1 * u), { x: x0 + sd * .12 * u, y: -2.2 * u, rot: sd * 14, col: PC.teal, depth: .5, seed: S + 7 + i }); brad(x0, -1.85 * u, .14 * u); });+ },+ head(u, view, o, S, e, st) {+ const q3 = view === '3q', F = POM.face;+ // ears (behind the head)+ const ears = q3 ? [[-1.05, -1.55, -24, .85], [1.55, -1.45, 18, 1]] : [[-1.45, -1.5, -20, 1], [1.45, -1.5, 20, 1]];+ ears.forEach(([ex, ey, r, k], i) => {+ const ear = SH.smooth([[-.72 * u * k, .35 * u, 1], [-.12 * u * k, -1.0 * u * k], [.12 * u * k, -1.02 * u * k], [.7 * u * k, .35 * u, 1]]);+ piece(ear, { x: ex * u, y: ey * u, rot: r + sway('pomear' + i, 3, .6), col: q3 && i === 0 ? mixCol(PC.orange, '#3A2A30', .1) : PC.orange, depth: 1, seed: S + 41 + i });+ piece(SH.smooth([[-.4 * u * k, .25 * u, 1], [-.06 * u * k, -.62 * u * k], [.06 * u * k, -.62 * u * k], [.4 * u * k, .25 * u, 1]]), { x: ex * u, y: (ey + .02) * u, rot: r + sway('pomear' + i, 3, .6), col: PC.pink, depth: .3, seed: S + 43 + i });+ });+ const hs = q3 ? .95 : 1;+ piece(SH.ellipse(2.4 * u * hs, 2.08 * u), { x: q3 ? .08 * u : 0, col: PC.orange, depth: 1.3, seed: S + 45 });+ // cream muzzle and a fringe tuft+ piece(SH.ellipse(1.42 * u * (q3 ? .9 : 1), 1.0 * u), { x: (q3 ? F.turn * 1.05 : 0) * u, y: .72 * u, col: PC.cream, depth: .45, seed: S + 46 });+ piece(SH.smooth([[-.6 * u, 0, 1], [-.3 * u, -.55 * u], [0, -.2 * u], [.3 * u, -.62 * u], [.62 * u, 0, 1], [0, .15 * u]]), { x: (q3 ? .35 : 0) * u, y: -1.95 * u, rot: 4, col: PC.tangerine, depth: .6, seed: S + 47 });+ drawFace(F, u, e, { view, blink: st.blink, look: st.look }, S);+ // nose on the muzzle (above the mouth)+ piece(SH.smooth([[-.26 * u, -.08 * u], [.26 * u, -.08 * u], [.05 * u, .2 * u], [-.05 * u, .2 * u]]), { x: (q3 ? F.turn * 1.25 : 0) * u, y: .42 * u, col: PC.bark, depth: .4, seed: S + 49 });+ },+};+function pom(x, y, u, o = {}) { return puppet(POM, x, y, u, o); }++// ---------- LULU: tall girl puppet, mustard coat, navy bob, rose scarf, lilac tights ----------+const LULU = {+ seed: 2000, hipH: 4.45, crouch: 1.6, ankleH: .32, thigh: 2.15, shin: 2.05, legR: [.36, .31, .27], upper: 1.7, fore: 1.55, armR: [.33, .29, .26], handR: .36,+ brad: .12, topR: 3.6, farTint: .12,+ limb: PC.skin, sleeve: PC.mustard, cuff: mixCol(PC.mustard, PC.brown, .25), hand: PC.skin, leg: PC.lilac, shoe: PC.red, restArm: [[-10, 6], [10, -6]],+ foot: [0, 0, .25, -.02], footShape: u => SH.smooth([[-.55 * u, .14 * u], [-.5 * u, -.2 * u], [.3 * u, -.28 * u], [.75 * u, -.02 * u], [.68 * u, .2 * u], [0, .28 * u]]),+ front: { hips: [[-.5, 0], [.5, 0]], feet: [[-.62, 0], [.62, 0]], shoulders: [[-1.12, -4.05], [1.12, -4.05]], neck: [0, -4.6], head: [0, -6.55] },+ '3q': { hips: [[-.2, -.05], [.45, 0]], feet: [[-.35, 0], [.55, 0]], shoulders: [[-.75, -4.1], [.95, -4.0]], neck: [.12, -4.6], head: [.15, -6.55] },+ face: { eyes: [[-.58, .08], [.58, .08]], eyeR: [.3, .38], pupil: .2, lid: PC.skin, brow: [.42, .1, .16], browCol: PC.navy, lineCol: PC.ink,+ cheeks: [[-.98, .62], [.98, .62]], cheekR: .26, mouth: [0, .98], mouthS: .62, turn: .42, sweat: [1.6, -.4], vein: [1.0, -1.1] },+ back(u, view, o, S) { // scarf tail (it swings behind)+ const q3 = view === '3q', sw = sway('lulus', 5, .6);+ G.save(); G.translate((q3 ? -.35 : .55) * u, -4.4 * u); G.rotate(((q3 ? 28 : 12) + sw) * D2R);+ piece(SH.round(.5 * u, 1.9 * u, .2 * u), { y: .9 * u, col: PC.rose, depth: 1, seed: S + 1 });+ stripes(0, 1.75 * u, .5 * u, .2 * u, 3, [PC.rose, PC.white], { seed: S + 2, depth: .2 });+ G.restore();+ },+ body(u, view, o, S) {+ const q3 = view === '3q', cx = q3 ? .08 : 0, k = q3 ? .92 : 1;+ const coat = SH.smooth([[-.95 * u, -4.55 * u], [.95 * u, -4.55 * u], [1.35 * u, -3.7 * u], [1.55 * u, -1.2 * u], [2.0 * u, .85 * u, 1], [0, 1.02 * u], [-2.0 * u, .85 * u, 1], [-1.55 * u, -1.2 * u], [-1.35 * u, -3.7 * u]]);+ piece(coat, { x: cx * u, sx: k, col: PC.mustard, depth: 1.2, seed: S + 11 });+ const fx = (q3 ? .55 : 0) * u;+ piece(SH.rect(.08 * u, 5.1 * u), { x: fx + .05 * u, y: -1.75 * u, col: mixCol(PC.mustard, PC.brown, .35), depth: .15, seed: S + 12 }); // front seam+ [-3.3, -2.3, -1.3].forEach((by, i) => brad(fx + .38 * u, by * u, .15 * u));+ [-1, 1].forEach((sd, i) => { if (q3 && sd < 0) return; piece(SH.round(.8 * u, .62 * u, .12 * u), { x: fx + sd * (q3 ? 1.15 : 1.0) * u, y: -.7 * u, rot: sd * -4, col: mixCol(PC.mustard, PC.orange, .3), depth: .35, seed: S + 13 + i }); });+ // neck + scarf wrap+ piece(SH.capsule(.9 * u, .3 * u), { x: (q3 ? .1 : 0) * u, y: -5.2 * u, col: mixCol(PC.skin, PC.peach, .4), depth: .4, seed: S + 15 });+ piece(SH.round(2.1 * u * k, .62 * u, .3 * u), { x: (cx + (q3 ? .1 : 0)) * u, y: -4.45 * u, rot: q3 ? -4 : 0, col: PC.rose, depth: .9, seed: S + 16 });+ stripes((cx + (q3 ? .1 : 0)) * u, -4.45 * u, .5 * u, .56 * u, 2, [PC.white, PC.rose], { seed: S + 17, depth: .1 });+ },+ head(u, view, o, S, e, st) {+ const q3 = view === '3q', F = LULU.face;+ // hair back piece, bun and hair tie (behind the face)+ piece(SH.smooth([[-1.75 * u, 1.0 * u, 1], [-1.85 * u, -.6 * u], [-1.2 * u, -1.75 * u], [0, -2.1 * u], [1.2 * u, -1.75 * u], [1.85 * u, -.6 * u], [1.75 * u, 1.0 * u, 1], [0, .75 * u]]), { x: (q3 ? -.3 : 0) * u, col: PC.navy, depth: 1.2, seed: S + 3 });+ piece(SH.circle(.78 * u), { x: (q3 ? -.35 : 0) * u, y: -2.35 * u, col: PC.navy, depth: 1, seed: S + 4 });+ piece(SH.round(.9 * u, .28 * u, .1 * u), { x: (q3 ? -.3 : 0) * u, y: -1.72 * u, rot: q3 ? -8 : 0, col: PC.rose, depth: .6, seed: S + 5 });+ if (q3) piece(SH.poly([[0, -.3 * u], [.42 * u, .12 * u], [0, .22 * u]]), { x: 1.43 * u, y: .3 * u, col: PC.skin, depth: .8, seed: S + 20 }); // nose tip at the profile edge+ piece(SH.ellipse(1.48 * u * (q3 ? .96 : 1), 1.72 * u), { x: (q3 ? .05 : 0) * u, col: PC.skin, depth: 1.2, seed: S + 21 });+ if (q3) piece(SH.ellipse(.3 * u, .42 * u), { x: -1.0 * u, y: .1 * u, col: mixCol(PC.skin, PC.peach, .5), depth: .4, seed: S + 22 }); // ear+ // bangs: a scalloped fringe+ const bang = []; const n = 5; bang.push([-1.62 * u, .1 * u, 1]); bang.push([-1.45 * u, -1.25 * u]); bang.push([0, -1.9 * u]); bang.push([1.45 * u, -1.25 * u]); bang.push([1.62 * u, .1 * u, 1]);+ for (let i = n; i >= 0; i--) { const xx = -1.4 * u + 2.8 * u * i / n; bang.push([xx, (i % 2 ? -.72 : -.52) * u - (i === 0 || i === n ? -.35 * u : 0)]); }+ piece(SH.smooth(bang), { x: (q3 ? .32 : 0) * u, y: 0, col: PC.navy, depth: .9, seed: S + 23 });+ drawFace(F, u, e, { view, blink: st.blink, look: st.look }, S);+ if (!q3) piece(SH.ellipse(.13 * u, .1 * u), { x: 0, y: .5 * u, col: mixCol(PC.skin, PC.rose, .35), depth: .25, seed: S + 24 });+ },+};+function lulu(x, y, u, o = {}) { return puppet(LULU, x, y, u, o); }++// ---------- model sheets (render: node render.mjs --loop=faces --sheet=0 --cols=1 --w=1600 --out=out/check/faces.jpg) ----------+LOOPS.faces = t => {+ backdrop(PC.sand);+ const names = Object.keys(EXPR);+ names.forEach((nm, i) => {+ const col = i % 7, row = Math.floor(i / 7), x = 150 + col * 270, y = 470 + row * 520;+ pom(x - 55, y, 38, { face: nm, blink: false, jit: 0, view: i % 2 ? '3q' : 'front' });+ lulu(x + 80, y + 20, 22, { face: nm, blink: false, jit: 0, view: i % 2 ? 'front' : '3q', flip: true });+ G.save(); G.font = '700 26px "Noto Sans TC", sans-serif'; G.fillStyle = PC.ink; G.textAlign = 'center'; G.fillText(nm, x, y + 50); G.restore();+ });+};+LOOPS.faces.len = 1;+LOOPS.poses = t => {+ backdrop(PC.mint);+ pom(260, 900, 70, { face: 'happy', holdR: 'apple', armR: [120, 30], jit: 0 });+ pom(640, 900, 70, { face: 'determined', view: '3q', ...walkCycle(.25), jit: 0 });+ lulu(1000, 950, 40, { face: 'love', holdL: 'flower', armL: [-70, -40], armR: [150, 20], jit: 0 });+ lulu(1350, 950, 40, { view: '3q', face: 'neutral', ...walkCycle(.1, { stride: .9 }), jit: 0 });+ pom(1700, 900, 62, { view: '3q', flip: true, face: 'surprised', ...jumpPose(1.25, 1.2, 1.7, 2), jit: 0 });+};+LOOPS.poses.len = 1;diff --git a/.claude/skills/paper-cutout/template/src/config.js b/.claude/skills/paper-cutout/template/src/config.jsnew file mode 100644index 0000000..42d5fba--- /dev/null+++ b/.claude/skills/paper-cutout/template/src/config.js@@ -0,0 +1,2 @@+// Project settings. duration in seconds; fps 24 (the stop-motion "steps" are PAPER.fps = 12 inside that).+const PROJECT = { duration: 11, bpm: 100, offset: 0, fps: 24 };diff --git a/.claude/skills/paper-cutout/template/src/cutout.js b/.claude/skills/paper-cutout/template/src/cutout.jsnew file mode 100644index 0000000..e43aed4--- /dev/null+++ b/.claude/skills/paper-cutout/template/src/cutout.js@@ -0,0 +1,650 @@+// cutout.js: the paper cut-out / stop-motion drawing library (Canvas 2D, on top of kit.js).+//+// Everything is a piece of paper lying on a table under a warm lamp: construction paper, cardstock, kraft, felt, tissue+// and corrugated card, cut with scissors (slightly faceted, wobbly edges) or torn (a lighter fibrous rim). Each piece+// casts a soft drop shadow onto whatever is under it; the shadow's offset/blur is the piece's depth above the layer below.+// Puppets and props move in steps (PAPER.fps, default 12/s) with a tiny per-step placement jitter and light flicker.+//+// Conventions: sizes in world pixels, ALL ANGLES IN DEGREES, every function is a pure function of time (use sm()).+// See GUIDE.md for the full API with examples.++const D2R = Math.PI / 180;+const PAPER = {+ fps: 12, // stop-motion step rate: puppets/props change pose this many times a second (use sm(lt))+ jit: 0, // current per-step placement jitter in px (cast.js sets it while drawing a puppet)+ light: [0.5, 0.86], // direction shadows fall (light from top-left → shadows to the bottom-right)+ shadow: 1, // global drop-shadow strength+ flicker: 1, // per-step exposure flicker strength (0 = off)+ grain: 1, // photographic grain strength+ vignette: 1, // warm lamp falloff at the frame edges+ step: 0, // the stop-motion step index of the frame being drawn: floor(t * fps)+ dry: false, // true = measure only: piece/brad/thread draw nothing (puppet(..., { dry: true }) uses it)+};+// the stop-motion clock: hold time in steps. Drive every puppet/prop pose with sm(lt), not lt.+const sm = (lt, fps = PAPER.fps) => onStep(lt, fps);+// stepped periodic sway for set dressing: amp * sin(...), phase from a key+const sway = (key, amp = 1, f = .5, fps = PAPER.fps) => amp * Math.sin((onStep(T, fps) * f + hash(String(key).length * 3.1 + keyNum(key))) * TAU);+function keyNum(k) { let h = 0; for (const c of String(k)) h = (h * 31 + c.charCodeAt(0)) % 100003; return h; }++// ---------- palette: construction paper colours ----------+const PC = {+ white: '#FAF6EC', cream: '#F3E7CF', paper: '#EFE3C8', sand: '#E6CFA0', kraft: '#C39767', cork: '#B07E50', brown: '#865437', bark: '#6B4430',+ ink: '#2E2630', charcoal: '#45404A', grey: '#A29C94', silver: '#CFCBC3',+ red: '#D6402F', tomato: '#E8603C', orange: '#EF8733', tangerine: '#F5A043', mustard: '#E7B23A', yellow: '#F4D05A', lemon: '#F6E382',+ lime: '#B3CC4E', leaf: '#76AE48', grass: '#5E9A3E', forest: '#3F7A45', pine: '#2F5E44', mint: '#A6D8BC', sage: '#9DBE93',+ teal: '#2C9A93', aqua: '#7FCFCB', sky: '#9CCFE9', blue: '#3E7EC2', cobalt: '#2E5DA8', navy: '#2A3F6E',+ lilac: '#B7A0D8', violet: '#7E5CB0', plum: '#7A4A84', pink: '#F4A7B6', rose: '#E26D8A', blush: '#F7C2C4', peach: '#F8C49A', skin: '#F6D6BA',+};++// ---------- noise ----------+function vn1(x, s = 0) { const i = Math.floor(x), f = x - i, u = f * f * (3 - 2 * f); return lerp(hash(i * .713 + s * 17.31), hash((i + 1) * .713 + s * 17.31), u); }+const fbm1 = (x, s = 0) => vn1(x, s) * .55 + vn1(x * 2.13, s + 1) * .28 + vn1(x * 4.71, s + 2) * .17;++// ---------- materials: procedural paper textures, generated once and cached ----------+// mat(col, kind) → a CanvasPattern of that colour in that material. kinds:+// paper (construction paper, default) · card (smooth cardstock) · kraft (brown fibres, specks) · felt (fuzzy)+// tissue (see-through, multiplies over what's under it) · corr (corrugated card flutes) · wood (table top)+const GRAIN_SPEC = {+ paper: { mott: 9, mid: 6, fine: 7, fib: 520, fibL: [4, 18], fibA: .09, specks: 70, str: .6 },+ card: { mott: 4, mid: 3, fine: 4, fib: 90, fibL: [3, 10], fibA: .05, specks: 16, str: .5 },+ kraft: { mott: 14, mid: 9, fine: 9, fib: 1100, fibL: [5, 24], fibA: .15, specks: 260, str: .75 },+ felt: { mott: 12, mid: 14, fine: 26, fib: 2400, fibL: [3, 9], fibA: .16, specks: 0, str: .85 },+ tissue: { mott: 6, mid: 4, fine: 3, fib: 50, fibL: [8, 24], fibA: .05, specks: 0, creases: 26, str: .7 },+ corr: { mott: 8, mid: 5, fine: 6, fib: 400, fibL: [4, 14], fibA: .1, specks: 60, flutes: 16, str: .85 },+ wood: { mott: 10, mid: 0, fine: 5, fib: 0, fibL: [4, 8], fibA: 0, specks: 0, wood: 1, str: .9 },+};+const GRAIN = {}, MATC = new Map();+function makeGrain(kind) {+ const S = 512, sp = GRAIN_SPEC[kind] || GRAIN_SPEC.paper, c = makeCanvas(S, S), x = c.getContext('2d'), r = rnd('grain:' + kind);+ const lat = n => { const a = new Float32Array(n * n); for (let i = 0; i < a.length; i++) a[i] = r(); return a; };+ const L1 = lat(6), L2 = lat(24);+ const pn = (L, n, px, py) => {+ const gx = px / S * n, gy = py / S * n, i0 = Math.floor(gx), j0 = Math.floor(gy), fx = gx - i0, fy = gy - j0;+ const ux = fx * fx * (3 - 2 * fx), uy = fy * fy * (3 - 2 * fy), g = (i, j) => L[(j % n) * n + (i % n)];+ return lerp(lerp(g(i0, j0), g(i0 + 1, j0), ux), lerp(g(i0, j0 + 1), g(i0 + 1, j0 + 1), ux), uy);+ };+ const id = x.createImageData(S, S), d = id.data;+ for (let py = 0; py < S; py++) for (let px = 0; px < S; px++) {+ let v = 128 + sp.mott * (pn(L1, 6, px, py) - .5) * 2 + sp.mid * (pn(L2, 24, px, py) - .5) * 2 + sp.fine * (r() - .5) * 2;+ if (sp.flutes) v += 26 * Math.sin((px % sp.flutes) / sp.flutes * TAU);+ if (sp.wood) { const w = py + 22 * Math.sin(px * TAU * 2 / S) + 30 * pn(L1, 6, px, py); v += 10 * Math.sin(w * TAU * 38 / S) + 6 * Math.sin(w * TAU * 97 / S); }+ const k = (py * S + px) * 4; d[k] = d[k + 1] = d[k + 2] = clamp(v, 0, 255); d[k + 3] = 255;+ }+ x.putImageData(id, 0, 0);+ const wrap = (fn, bx, by, m) => { for (const ox of [-S, 0, S]) for (const oy of [-S, 0, S]) { if (bx + ox < -m || bx + ox > S + m || by + oy < -m || by + oy > S + m) continue; fn(ox, oy); } };+ x.lineCap = 'round';+ for (let i = 0; i < sp.fib; i++) { // fibres+ const fx = r() * S, fy = r() * S, L = lerp(sp.fibL[0], sp.fibL[1], r()), a = r() * TAU, b = (r() - .5) * 1.2, light = r() < .55;+ x.strokeStyle = light ? `rgba(255,255,255,${sp.fibA * (1 + r())})` : `rgba(0,0,0,${sp.fibA * (.6 + r())})`; x.lineWidth = .5 + r() * .9;+ wrap((ox, oy) => { x.beginPath(); x.moveTo(fx + ox, fy + oy); x.quadraticCurveTo(fx + ox + Math.cos(a + b) * L * .5, fy + oy + Math.sin(a + b) * L * .5, fx + ox + Math.cos(a) * L, fy + oy + Math.sin(a) * L); x.stroke(); }, fx, fy, 30);+ }+ for (let i = 0; i < sp.specks; i++) {+ const fx = r() * S, fy = r() * S, rr = .5 + r() * 1.4, dark = kind === 'kraft' ? r() < .8 : r() < .5;+ x.fillStyle = dark ? `rgba(40,20,5,${.12 + r() * .25})` : `rgba(255,255,255,${.2 + r() * .3})`;+ wrap((ox, oy) => { x.beginPath(); x.arc(fx + ox, fy + oy, rr, 0, TAU); x.fill(); }, fx, fy, 4);+ }+ for (let i = 0; i < (sp.creases || 0); i++) { // tissue creases: long light/dark line pairs+ const fx = r() * S, fy = r() * S, a = r() * TAU, L = 60 + r() * 180, dx = Math.cos(a) * L, dy = Math.sin(a) * L, bx = (r() - .5) * 30;+ wrap((ox, oy) => {+ x.lineWidth = 1.2; x.strokeStyle = 'rgba(255,255,255,.35)'; x.beginPath(); x.moveTo(fx + ox, fy + oy); x.quadraticCurveTo(fx + ox + dx / 2 + bx, fy + oy + dy / 2 - bx, fx + ox + dx, fy + oy + dy); x.stroke();+ x.strokeStyle = 'rgba(0,0,0,.18)'; x.beginPath(); x.moveTo(fx + ox + 1.5, fy + oy + 1.5); x.quadraticCurveTo(fx + ox + dx / 2 + bx + 1.5, fy + oy + dy / 2 - bx + 1.5, fx + ox + dx + 1.5, fy + oy + dy + 1.5); x.stroke();+ }, fx + dx / 2, fy + dy / 2, L);+ }+ return c;+}+function mat(col, kind = 'paper') {+ const key = kind + col; let p = MATC.get(key); if (p) return p;+ const g = GRAIN[kind] || (GRAIN[kind] = makeGrain(kind)), S = g.width, c = makeCanvas(S, S), x = c.getContext('2d');+ x.fillStyle = col; x.fillRect(0, 0, S, S);+ x.globalAlpha = (GRAIN_SPEC[kind] || GRAIN_SPEC.paper).str; x.globalCompositeOperation = 'overlay'; x.drawImage(g, 0, 0);+ x.globalCompositeOperation = 'destination-in'; x.globalAlpha = 1; x.drawImage(c, 0, 0);+ p = x.createPattern(c, 'repeat'); MATC.set(key, p); return p;+}+// the pattern, shifted by a per-piece offset so neighbouring pieces don't share the same fibres+function matPat(col, kind, seed = 0) { const p = mat(col, kind); p.setTransform(new DOMMatrix([1, 0, 0, 1, hash(seed * 3.7) * 512, hash(seed * 5.3 + 1) * 512])); return p; }+const rimOf = col => mixCol(col, '#FBF6EA', .72); // the lighter fibrous core seen on a torn edge++// ---------- shadows ----------+function curScale(c = G) { const m = c.getTransform(); return Math.hypot(m.a, m.b) || 1; }+// depth = how high the piece floats above what's under it (0 flat … 1 normal piece … 3 lifted card)+function setShadow(depth = 1, k = curScale(), alpha = 1, c = G) {+ const s = PAPER.shadow * depth;+ if (s <= 0) { c.shadowColor = 'transparent'; return; }+ c.shadowColor = `rgba(48,28,14,${Math.min(.6, (.2 + .09 * s) * alpha)})`;+ const off = (1.5 + 4.5 * s) * k; c.shadowOffsetX = PAPER.light[0] * off; c.shadowOffsetY = PAPER.light[1] * off; c.shadowBlur = (2 + 6 * s) * k;+}+function noShadow(c = G) { c.shadowColor = 'transparent'; c.shadowBlur = 0; c.shadowOffsetX = c.shadowOffsetY = 0; }++// ---------- shapes: dense outlines [x, y, corner?] with a .key (for caching the cut) ----------+const f1 = v => Math.round(v * 10) / 10;+const keyed = (a, k) => (a.key = k, a);+const SH = {+ ellipse(rx, ry = rx) {+ const n = clamp(Math.round((rx + ry) * .5), 18, 200), a = [];+ for (let i = 0; i < n; i++) { const t = i / n * TAU; a.push([Math.cos(t) * rx, Math.sin(t) * ry]); }+ return keyed(a, `e${f1(rx)},${f1(ry)}`);+ },+ circle(r) { return SH.ellipse(r, r); },+ poly(pts, key) { // straight-edged polygon; every vertex is a sharp scissor corner+ const a = [];+ for (let i = 0; i < pts.length; i++) {+ const p = pts[i], q = pts[(i + 1) % pts.length], L = Math.hypot(q[0] - p[0], q[1] - p[1]), n = Math.max(1, Math.round(L / 9));+ a.push([p[0], p[1], 1]); for (let j = 1; j < n; j++) a.push([lerp(p[0], q[0], j / n), lerp(p[1], q[1], j / n)]);+ }+ return keyed(a, key || 'p' + pts.map(p => f1(p[0]) + ',' + f1(p[1])).join(';'));+ },+ rect(w, h) { return SH.poly([[-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, h / 2], [-w / 2, h / 2]], `r${f1(w)},${f1(h)}`); },+ round(w, h, r) { // rounded rectangle, centred+ r = Math.min(r, w / 2, h / 2); const a = [], cs = [[w / 2 - r, -h / 2 + r, -90], [w / 2 - r, h / 2 - r, 0], [-w / 2 + r, h / 2 - r, 90], [-w / 2 + r, -h / 2 + r, 180]];+ const na = clamp(Math.round(r * .4), 3, 30);+ cs.forEach(([cx, cy, a0], k) => {+ for (let i = 0; i <= na; i++) { const t = (a0 + 90 * i / na) * D2R; a.push([cx + Math.cos(t) * r, cy + Math.sin(t) * r]); }+ const [nx, ny] = cs[(k + 1) % 4], ex = cx + Math.cos((a0 + 90) * D2R) * r, ey = cy + Math.sin((a0 + 90) * D2R) * r, fx = nx + Math.cos((a0 + 90) * D2R) * r, fy = ny + Math.sin((a0 + 90) * D2R) * r;+ const L = Math.hypot(fx - ex, fy - ey), m = Math.round(L / 10); for (let j = 1; j < m; j++) a.push([lerp(ex, fx, j / m), lerp(ey, fy, j / m)]);+ });+ return keyed(a, `R${f1(w)},${f1(h)},${f1(r)}`);+ },+ // closed Catmull-Rom curve through control points: the general tool for organic pieces (bodies, heads, leaves)+ smooth(ctrl, key) {+ const a = [], n = ctrl.length;+ for (let i = 0; i < n; i++) {+ const p0 = ctrl[(i - 1 + n) % n], p1 = ctrl[i], p2 = ctrl[(i + 1) % n], p3 = ctrl[(i + 2) % n], L = Math.hypot(p2[0] - p1[0], p2[1] - p1[1]), m = clamp(Math.round(L / 5), 2, 60);+ for (let j = 0; j < m; j++) {+ const t = j / m, t2 = t * t, t3 = t2 * t;+ const f = (a0, a1, a2, a3) => .5 * (2 * a1 + (-a0 + a2) * t + (2 * a0 - 5 * a1 + 4 * a2 - a3) * t2 + (-a0 + 3 * a1 - 3 * a2 + a3) * t3);+ a.push([f(p0[0], p1[0], p2[0], p3[0]), f(p0[1], p1[1], p2[1], p3[1]), j === 0 && p1[2] ? 1 : 0]);+ }+ }+ return keyed(a, key || 's' + ctrl.map(p => f1(p[0]) + ',' + f1(p[1])).join(';'));+ },+ // limb piece from (0,0) down to (0,len), round ends of radius r0 / r1 (joints sit at the two centres)+ capsule(len, r0, r1 = r0) {+ const a = [], n0 = clamp(Math.round(r0 * .5), 6, 30), n1 = clamp(Math.round(r1 * .5), 6, 30);+ for (let i = 0; i <= n0; i++) { const t = Math.PI + Math.PI * i / n0; a.push([Math.cos(t) * r0, Math.sin(t) * r0]); }+ const m = Math.max(1, Math.round(len / 10)); for (let j = 1; j < m; j++) a.push([lerp(r0, r1, j / m), len * j / m]);+ for (let i = 0; i <= n1; i++) { const t = Math.PI * i / n1; a.push([Math.cos(t) * r1, len + Math.sin(t) * r1]); }+ for (let j = m - 1; j >= 1; j--) a.push([-lerp(r0, r1, j / m), len * j / m]);+ return keyed(a, `c${f1(len)},${f1(r0)},${f1(r1)}`);+ },+ blob(r, n = 7, amt = .15, seed = 1) { const q = rnd('blob' + seed), c = []; for (let i = 0; i < n; i++) { const t = i / n * TAU; const rr = r * (1 + (q() - .5) * 2 * amt); c.push([Math.cos(t) * rr, Math.sin(t) * rr]); } return SH.smooth(c, `b${f1(r)},${n},${amt},${seed}`); },+ // scalloped cloud: flat-ish bottom, round bumps on top; centred on the bottom edge's middle+ cloud(w, h, seed = 1) {+ const q = rnd('cloud' + seed), a = [], bumps = 3 + Math.floor(q() * 2);+ const ws = []; let tot = 0; for (let i = 0; i < bumps; i++) { const v = .7 + q() * .6 + (i > 0 && i < bumps - 1 ? .5 : 0); ws.push(v); tot += v; }+ let x0 = -w / 2;+ for (let i = 0; i < bumps; i++) {+ const bw = ws[i] / tot * w, cx = x0 + bw / 2, env = Math.sin(Math.PI * (cx + w / 2) / w), top = h * (.35 + .65 * env), r = bw / 2;+ for (let j = 0; j <= 24; j++) { const t = Math.PI + Math.PI * j / 24; a.push([cx + Math.cos(t) * r, -top + r * .15 + Math.sin(t) * Math.min(r, top) * 1.0 - 0]); }+ x0 += bw;+ }+ a.push([w / 2, -h * .12]); a.push([w / 2 - h * .15, 0, 1]); for (let j = 1; j < 8; j++) a.push([w / 2 - h * .15 - (w - h * .3) * j / 8, 0 + Math.sin(j * 1.7) * 1.5]); a.push([-w / 2 + h * .15, 0, 1]); a.push([-w / 2, -h * .12]);+ return keyed(a, `cl${f1(w)},${f1(h)},${seed}`);+ },+ leaf(len, w) { // pointed at both ends, from (0,0) to (0,-len)+ const a = [], n = clamp(Math.round(len / 5), 8, 60);+ for (let i = 0; i <= n; i++) { const t = i / n; a.push([Math.sin(t * Math.PI) * w / 2, -len * t, i === 0 || i === n ? 1 : 0]); }+ for (let i = n - 1; i >= 1; i--) { const t = i / n; a.push([-Math.sin(t * Math.PI) * w / 2 * .92, -len * t]); }+ return keyed(a, `lf${f1(len)},${f1(w)}`);+ },+ heart(s) { const a = []; for (let i = 0; i < 60; i++) { const t = i / 60 * TAU, x = 16 * Math.pow(Math.sin(t), 3), y = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)); a.push([x * s / 32, y * s / 32, i === 0 || i === 30 ? 1 : 0]); } return keyed(a, `h${f1(s)}`); },+ star(r1, r2 = r1 * .45, n = 5) { const p = []; for (let i = 0; i < n * 2; i++) { const t = (i / (n * 2)) * TAU - Math.PI / 2, r = i % 2 ? r2 : r1; p.push([Math.cos(t) * r, Math.sin(t) * r]); } return SH.poly(p, `st${f1(r1)},${f1(r2)},${n}`); },+ drop(r) { const a = []; for (let i = 0; i < 40; i++) { const t = i / 40 * TAU, k = Math.sin(t / 2); a.push([Math.sin(t) * r * k * 1.05, -Math.cos(t) * r * 1.3 + r * .3, i === 0 ? 1 : 0]); } return keyed(a, `d${f1(r)}`); },+ tri(w, h) { return SH.poly([[0, -h / 2], [w / 2, h / 2], [-w / 2, h / 2]], `t${f1(w)},${f1(h)}`); },+ // a curved band (smile, brow, rainbow): centre radius r, thickness th, from angle a0 to a1 (deg, 0 = right, 90 = down)+ band(r, th, a0, a1) {+ const a = [], n = clamp(Math.round(Math.abs(a1 - a0) / 6), 6, 60), ro = r + th / 2, ri = r - th / 2, cap = th / 2, dir = a1 > a0 ? 1 : -1;+ const P = (rad, deg) => [Math.cos(deg * D2R) * rad, Math.sin(deg * D2R) * rad];+ const capAt = (deg, fwd) => { const t = deg * D2R, u = [Math.cos(t), Math.sin(t)], v = [-Math.sin(t) * dir * fwd, Math.cos(t) * dir * fwd], c = P(r, deg);+ for (let i = 1; i < 8; i++) { const f = i / 8 * Math.PI, cu = Math.cos(f) * fwd, sv = Math.sin(f); a.push([c[0] + (u[0] * cu + v[0] * sv) * cap, c[1] + (u[1] * cu + v[1] * sv) * cap]); } };+ for (let i = 0; i <= n; i++) a.push(P(ro, lerp(a0, a1, i / n)));+ capAt(a1, 1);+ for (let i = n; i >= 0; i--) a.push(P(ri, lerp(a0, a1, i / n)));+ capAt(a0, -1);+ return keyed(a, `bd${f1(r)},${f1(th)},${f1(a0)},${f1(a1)}`);+ },+ // a strip with a zig-zag top (grass, fringe): x from -w/2..w/2, base at y=0, teeth up to -h+ zig(w, h, n = 12, seed = 1) {+ const q = rnd('zig' + seed), a = [[w / 2, 0, 1], [-w / 2, 0, 1]];+ for (let i = 0; i <= n * 2; i++) { const x = -w / 2 + w * i / (n * 2), up = i % 2 === 1; a.push([x + (q() - .5) * w / n * .3, up ? -h * (.6 + q() * .4) : -h * (.05 + q() * .12), 1]); }+ return SH.poly(a, `z${f1(w)},${f1(h)},${n},${seed}`);+ },+ // rolling hill band: top edge around y=0 (± h/2), x from -w/2..w/2, reaching down `down` px+ hills(w, h, n = 3, seed = 1, down = 1400) {+ const q = rnd('hill' + seed), ph = [q() * TAU, q() * TAU, q() * TAU], c = [];+ const top = x => -h / 2 * (Math.sin(x / w * TAU * n * .5 + ph[0]) * .65 + Math.sin(x / w * TAU * n * 1.3 + ph[1]) * .25 + Math.sin(x / w * TAU * n * 3.1 + ph[2]) * .1);+ const m = Math.round(w / 12); for (let i = 0; i <= m; i++) { const x = -w / 2 + w * i / m; c.push([x, top(x), i === 0 || i === m ? 1 : 0]); }+ c.push([w / 2, down, 1]); c.push([-w / 2, down, 1]);+ return keyed(c, `hl${f1(w)},${f1(h)},${n},${seed},${down}`);+ },+};+// keep the part of a shape on one side of a line (n·p ≤ c): eyelids, overall bibs, half moons+function clipHalf(shape, nx, ny, c) {+ const out = [], n = shape.length, inside = p => nx * p[0] + ny * p[1] <= c;+ for (let i = 0; i < n; i++) {+ const p = shape[i], q = shape[(i + 1) % n], a = inside(p), b = inside(q);+ if (a) out.push(p);+ if (a !== b) { const dp = nx * p[0] + ny * p[1] - c, dq = nx * q[0] + ny * q[1] - c, k = dp / (dp - dq); out.push([lerp(p[0], q[0], k), lerp(p[1], q[1], k), 1]); }+ }+ return keyed(out, (shape.key || '') + `|${f1(nx * 100)},${f1(ny * 100)},${f1(c)}`);+}+// move / scale a shape's points (returns a new keyed shape)+function xform(shape, dx = 0, dy = 0, sx = 1, sy = sx) { return keyed(shape.map(p => [p[0] * sx + dx, p[1] * sy + dy, p[2]]), (shape.key || '') + `|x${f1(dx)},${f1(dy)},${f1(sx * 100)},${f1(sy * 100)}`); }++// ---------- cutting: scissor facets & wobble, or torn edges ----------+const CUTS = new Map();+function normalsOf(pts) {+ const n = pts.length; let area = 0; for (let i = 0; i < n; i++) { const p = pts[i], q = pts[(i + 1) % n]; area += p[0] * q[1] - q[0] * p[1]; }+ const s = area > 0 ? 1 : -1, N = [];+ for (let i = 0; i < n; i++) { const a = pts[(i - 1 + n) % n], b = pts[(i + 1) % n]; let dx = b[0] - a[0], dy = b[1] - a[1]; const L = Math.hypot(dx, dy) || 1; N.push([s * dy / L, -s * dx / L]); }+ return N;+}+function toPath(pts) { const p = new Path2D(); p.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) p.lineTo(pts[i][0], pts[i][1]); p.closePath(); return p; }+function buildCut(shape, seed, o) {+ const r = rnd('cut' + seed), n = shape.length, N = normalsOf(shape);+ let per = 0; for (let i = 0; i < n; i++) { const p = shape[i], q = shape[(i + 1) % n]; per += Math.hypot(q[0] - p[0], q[1] - p[1]); }+ if (o.torn) return buildTorn(shape, seed, o, N);+ const wob = o.wob ?? Math.min(1.4, .3 + per / 1000), s0 = clamp(per / 46, 2, 16), s1 = clamp(per / 13, 4.5, 30);+ let out = [], acc = 0, next = lerp(s0, s1, r());+ for (let i = 0; i < n; i++) {+ const p = shape[i], q = shape[(i - 1 + n) % n]; acc += Math.hypot(p[0] - q[0], p[1] - q[1]);+ if (p[2] || acc >= next || i === 0) { const d = (r() - .5) * 2 * (p[2] ? wob * .3 : wob); out.push([p[0] + N[i][0] * d, p[1] + N[i][1] * d]); acc = 0; next = lerp(s0, s1, r()); }+ }+ if (out.length < 3) out = shape.map(p => [p[0], p[1]]);+ return { outer: toPath(out) };+}+function buildTorn(shape, seed, o, N) {+ const amp = o.tornAmp ?? 5, rimW = o.rimW ?? amp * .9, sel = o.torn, q = rnd('tear' + seed);+ const on = nv => sel === true || sel === 'all' ? 1 : sel === 'top' ? nv[1] < -.35 : sel === 'bottom' ? nv[1] > .35 : sel === 'left' ? nv[0] < -.35 : sel === 'right' ? nv[0] > .35 : sel === 'sides' ? Math.abs(nv[0]) > .35 : 0;+ // resample densely so the tear has fine detail+ const dense = [], n = shape.length;+ for (let i = 0; i < n; i++) {+ const p = shape[i], nx = shape[(i + 1) % n], L = Math.hypot(nx[0] - p[0], nx[1] - p[1]), m = Math.max(1, Math.round(L / 2.5));+ for (let j = 0; j < m; j++) dense.push([lerp(p[0], nx[0], j / m), lerp(p[1], nx[1], j / m), j === 0 ? p[2] : 0]);+ }+ const DN = normalsOf(dense), outer = [], inner = [], fib = new Path2D(); let s = 0;+ for (let i = 0; i < dense.length; i++) {+ const p = dense[i], pv = dense[(i - 1 + dense.length) % dense.length]; s += Math.hypot(p[0] - pv[0], p[1] - pv[1]);+ const t = on(DN[i]) ? 1 : 0;+ if (!t) { outer.push([p[0], p[1]]); inner.push([p[0], p[1]]); continue; }+ const jag = (fbm1(s / 26, seed) - .5) * 2 * amp + (q() - .5) * amp * .45, rim = rimW * (.35 + .9 * fbm1(s / 11, seed + 7));+ const ox = p[0] + DN[i][0] * jag, oy = p[1] + DN[i][1] * jag;+ outer.push([ox, oy]); inner.push([ox - DN[i][0] * rim, oy - DN[i][1] * rim]);+ if (q() < .22) { const fl = 1.5 + q() * amp * .7, a = (q() - .5) * 1.4, cx = DN[i][0] * Math.cos(a) - DN[i][1] * Math.sin(a), cy = DN[i][0] * Math.sin(a) + DN[i][1] * Math.cos(a); fib.moveTo(ox - DN[i][0], oy - DN[i][1]); fib.lineTo(ox + cx * fl, oy + cy * fl); }+ }+ return { outer: toPath(outer), inner: toPath(inner), fib };+}+function cutOf(shape, seed, o) {+ const ck = shape.key != null ? `${shape.key}|${seed}|${o.torn || ''}|${o.wob ?? ''}|${o.tornAmp ?? ''}` : null;+ let P = ck && CUTS.get(ck);+ if (!P) { P = buildCut(shape, seed, o); if (ck) { if (CUTS.size > 8000) CUTS.clear(); CUTS.set(ck, P); } }+ return P;+}++// ---------- the piece: one cut-out on the table ----------+// piece(shape, { x, y, rot (deg), sx, sy, col, mat, depth, seed, torn, tornAmp, rim, alpha, jit, edge, hi })+// torn: true | 'top' | 'bottom' | 'left' | 'right' | 'sides' → torn edge(s) with a lighter fibrous rim+// depth: shadow height (0 = glued flat, 1 = a normal layer, 2–3 = lifted); jit: per-step jitter px (default PAPER.jit)+function piece(shape, o = {}) {+ if (PAPER.dry || !shape || shape.length < 3) return;+ const seed = o.seed ?? 1, col = o.col || PC.cream, kind = o.mat || 'paper', P = cutOf(shape, seed, o);+ let x = o.x || 0, y = o.y || 0, rot = o.rot || 0;+ const jit = o.jit ?? PAPER.jit;+ if (jit) { const h = seed * 13.17 + PAPER.step * 7.31; x += (hash(h) - .5) * 2 * jit; y += (hash(h + 1.7) - .5) * 2 * jit; rot += (hash(h + 3.1) - .5) * .7 * jit; }+ G.save(); G.translate(x, y); if (rot) G.rotate(rot * D2R); if (o.sx != null || o.sy != null) G.scale(o.sx ?? 1, o.sy ?? o.sx ?? 1);+ const k = curScale(), tissue = kind === 'tissue';+ if (o.alpha != null) G.globalAlpha *= o.alpha;+ if (tissue) { G.globalAlpha *= .8; G.globalCompositeOperation = 'multiply'; }+ setShadow((o.depth ?? 1) * (tissue ? .35 : 1), k);+ const pat = matPat(col, kind, seed);+ if (P.inner) {+ G.fillStyle = o.rim || rimOf(col); G.fill(P.outer); noShadow();+ G.lineWidth = .9 / k * (k > 1 ? k * .7 : 1); G.strokeStyle = o.rim || rimOf(col); G.stroke(P.fib);+ G.fillStyle = pat; G.fill(P.inner);+ } else { G.fillStyle = pat; G.fill(P.outer); noShadow(); }+ if (!tissue && o.edge !== false) { G.lineWidth = Math.max(.8, 1.3 / k); G.strokeStyle = 'rgba(52,30,16,.2)'; G.stroke(P.outer); }+ if (o.hi) { G.globalCompositeOperation = 'source-atop'; } // reserved+ G.restore();+}+// a split-pin paper fastener (brass brad) at a joint+function brad(x, y, r = 6, o = {}) {+ if (PAPER.dry) return;+ G.save(); G.translate(x, y); const k = curScale();+ setShadow(.35, k);+ const g = G.createRadialGradient(-r * .35, -r * .4, r * .1, 0, 0, r);+ g.addColorStop(0, o.hi || '#FFF2B8'); g.addColorStop(.45, o.col || '#D9AE4B'); g.addColorStop(1, o.lo || '#8A6420');+ G.fillStyle = g; G.beginPath(); G.arc(0, 0, r, 0, TAU); G.fill(); noShadow();+ G.strokeStyle = 'rgba(80,50,10,.55)'; G.lineWidth = Math.max(.7, r * .12); G.beginPath(); G.arc(0, 0, r * .92, 0, TAU); G.stroke();+ G.fillStyle = 'rgba(255,255,240,.8)'; G.beginPath(); G.ellipse(-r * .35, -r * .38, r * .28, r * .18, -.6, 0, TAU); G.fill();+ G.restore();+}+// a thread / string (hangs clouds, stars, bunting): a thin line with its own faint shadow+function thread(pts, o = {}) {+ if (PAPER.dry) return;+ G.save(); const k = curScale(); setShadow(o.depth ?? .6, k, .7);+ G.strokeStyle = o.col || 'rgba(110,98,84,.85)'; G.lineWidth = (o.w || 2) * (o.world ? 1 : 1); G.lineCap = 'round'; G.lineJoin = 'round';+ G.beginPath(); G.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) G.lineTo(pts[i][0], pts[i][1]); G.stroke();+ G.restore();+}+// draw fn() scaled up from a hinge line (pop-up book element): k 0 = flat, 1 = standing+function popUp(k, x, y, fn) {+ if (k <= 0) return; if (k >= 1) return fn();+ G.save(); G.translate(x, y); G.scale(1, Math.max(.02, k)); G.translate(-x, -y); fn(); G.restore();+}++// ---------- camera & depth planes ----------+// paperCam(lt, [[t, [cx, cy, zoom, rotDeg]], ...], { stepped, fps, ease }) → camBegin(...). stepped = move in steps+// like a hand-nudged stop-motion camera; default is a smooth motion-control move.+function paperCam(lt, keys, o = {}) {+ const tt = o.stepped ? sm(lt, o.fps || PAPER.fps) : lt, v = kf(tt, keys, o.ease || ease);+ camBegin(v[0], v[1], v[2] ?? 1, (v[3] || 0) * D2R);+}+// layer(k, fn): a depth plane. k = 1 moves with the world, k < 1 is farther away (moves & zooms less), k > 1 is a+// foreground plane that sweeps past faster. Call inside camBegin/paperCam.+function layer(k, fn) {+ if (!CAM || k === 1) return fn();+ const { cx, cy, zoom } = CAM, zk = 1 + (zoom - 1) * k, ckx = W / 2 + (cx - W / 2) * k, cky = H / 2 + (cy - H / 2) * k;+ G.save(); G.translate(cx, cy); G.scale(zk / zoom, zk / zoom); G.translate(-ckx, -cky); fn(); G.restore();+}++// ---------- backdrops ----------+// backdrop(col, { to, mat, par }): a full sheet of paper behind everything (screen-fixed; par>0 slides it a little with the camera)+function backdrop(col = PC.sky, o = {}) {+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0); noShadow(); G.globalAlpha = 1;+ const p = mat(col, o.mat || 'paper'), cam = CAM || { cx: W / 2, cy: H / 2 }, par = o.par ?? .15;+ p.setTransform(new DOMMatrix([1, 0, 0, 1, -(cam.cx - W / 2) * par, -(cam.cy - H / 2) * par]));+ G.fillStyle = p; G.fillRect(0, 0, W, H);+ if (o.to) { const g = G.createLinearGradient(0, 0, 0, H); g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(1, o.to); G.fillStyle = g; G.fillRect(0, 0, W, H); }+ G.restore();+}+// the table the paper lies on (seen around flip cards / pop-up pages)+function table(o = {}) {+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0); noShadow(); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over';+ const p = mat(o.col || '#B48458', 'wood'); p.setTransform(new DOMMatrix([1.6, 0, 0, 1.6, 0, 0])); G.fillStyle = p; G.fillRect(0, 0, W, H);+ G.restore();+}++// ---------- set dressing ----------+// hills(x, y, w, h, col, { bumps, seed, depth, torn, mat }): a torn-top paper hill band (top edge around y)+function hills(x, y, w, h, col, o = {}) { piece(SH.hills(w, h, o.bumps || 3, o.seed || 1, o.down || 1400), { x, y, col, mat: o.mat, torn: o.torn ?? 'top', tornAmp: o.tornAmp ?? 5, depth: o.depth ?? 1.1, seed: o.seed || 1, jit: 0 }); }+// grass(x, y, w, h, col, seed): zig-zag cut grass strip standing on y+function grass(x, y, w, h, col = PC.grass, seed = 1, o = {}) { piece(SH.zig(w, h, Math.max(3, Math.round(w / (h * .9))), seed), { x, y, col, depth: o.depth ?? .8, seed, jit: 0 }); }+// tree(x, y, s, { cols, trunk, seed, sway, fruit }) → returns { top:[x,y], fruit:[[x,y],...] } (fruit anchor points)+function tree(x, y, s = 1, o = {}) {+ const cols = o.cols || [PC.forest, PC.grass, PC.leaf], seed = o.seed || 1, q = rnd('tree' + seed), sw = o.sway ?? sway('tree' + seed, 1.2, .35);+ // trunk with two branches (kraft)+ piece(SH.smooth([[-34 * s, 0, 1], [-22 * s, -150 * s], [-26 * s, -300 * s], [-70 * s, -380 * s], [-50 * s, -395 * s], [-8 * s, -335 * s], [14 * s, -390 * s], [36 * s, -380 * s], [22 * s, -300 * s], [26 * s, -150 * s], [40 * s, 0, 1]]), { x, y, col: o.trunk || PC.cork, mat: 'kraft', depth: 1, seed: seed * 7 });+ G.save(); G.translate(x, y - 300 * s); G.rotate(sw * D2R); G.translate(-x, -(y - 300 * s));+ const cx = x, cy = y - 470 * s, blobs = [[0, 0, 190], [-140, 40, 120], [140, 30, 130], [-80, -110, 120], [90, -110, 120], [0, 70, 130]];+ blobs.forEach(([bx, by, br], i) => piece(SH.blob(br * s, 8, .12, seed * 10 + i), { x: cx + bx * s, y: cy + by * s, col: cols[i % 2], depth: 1.1, seed: seed * 10 + i }));+ const front = [[-60, 20, 95], [70, 10, 100], [0, -60, 105]];+ front.forEach(([bx, by, br], i) => piece(SH.blob(br * s, 7, .14, seed * 20 + i), { x: cx + bx * s, y: cy + by * s, col: cols[2 + (i % Math.max(1, cols.length - 2))] || cols[2], depth: 1.2, seed: seed * 20 + i }));+ for (let i = 0; i < 7; i++) { const a = -150 + i * 50 + (q() - .5) * 20, rr = 215 * s; piece(SH.leaf(60 * s, 30 * s), { x: cx + Math.cos(a * D2R) * rr * .98, y: cy + Math.sin(a * D2R) * rr * .9, rot: a + 90, col: cols[i % cols.length], depth: 1.2, seed: seed * 30 + i }); }+ G.restore();+ const rot = (px, py) => { const a = sw * D2R, dx = px - x, dy = py - (y - 300 * s); return [x + dx * Math.cos(a) - dy * Math.sin(a), y - 300 * s + dx * Math.sin(a) + dy * Math.cos(a)]; };+ return { top: rot(cx, cy - 190 * s), fruit: (o.fruit || [[-120, 60], [110, -40], [30, 120]]).map(([fx, fy]) => rot(cx + fx * s, cy + fy * s)), sway: sw };+}+function bush(x, y, s = 1, o = {}) {+ const cols = o.cols || [PC.forest, PC.leaf], seed = o.seed || 1;+ [[-70, -40, 70], [60, -45, 75], [0, -75, 85]].forEach(([bx, by, br], i) => piece(SH.blob(br * s, 7, .12, seed * 5 + i), { x: x + bx * s, y: y + by * s, col: cols[i % cols.length], depth: 1, seed: seed * 5 + i }));+}+// flower(x, y, s, col, { center, stem, seed, sway }) standing on (x, y)+function flower(x, y, s = 1, col = PC.rose, o = {}) {+ const seed = o.seed || 1, sw = o.sway ?? sway('fl' + seed, 3, .5), top = [x + Math.sin(sw * D2R) * 90 * s, y - 90 * s * Math.cos(sw * D2R)];+ piece(SH.capsule(92 * s, 4 * s), { x: top[0], y: top[1], rot: -sw, col: o.stem || PC.grass, depth: .7, seed: seed * 3 });+ piece(SH.leaf(34 * s, 16 * s), { x: x + (top[0] - x) * .5, y: y - 40 * s, rot: 50, col: o.stem || PC.leaf, depth: .7, seed: seed * 3 + 1 });+ for (let i = 0; i < 5; i++) { const a = (i / 5 * 360 + sw * 2) * D2R; piece(SH.ellipse(15 * s, 10 * s), { x: top[0] + Math.cos(a) * 15 * s, y: top[1] + Math.sin(a) * 15 * s, rot: a / D2R, col, depth: .8, seed: seed * 7 + i }); }+ piece(SH.circle(10 * s), { x: top[0], y: top[1], col: o.center || PC.yellow, depth: .8, seed: seed * 11 });+}+// cloud(x, y, w, { col, hang: 'string'|'stick'|null, bob, seed, depth }) — a cloud cut-out hung on a thread or on a stick+function cloud(x, y, w = 260, o = {}) {+ const seed = o.seed || 1, bob = o.bob ?? 1, dy = sway('cl' + seed, 7 * bob, .3), rot = sway('clr' + seed, 1.6 * bob, .23), h = w * .5;+ if (o.hang === 'string' || o.hang === true) { thread([[x - w * .22, y + dy - 1600], [x - w * .22, y + dy - h * .6]]); thread([[x + w * .24, y + dy - 1600], [x + w * .24, y + dy - h * .55]]); }+ if (o.hang === 'stick') piece(SH.rect(w * .05, 900), { x: x + w * .05, y: y + dy + 440, rot: rot * .3, col: PC.kraft, mat: 'kraft', depth: .9, seed: seed * 3 });+ piece(SH.cloud(w, h, seed), { x, y: y + dy, rot, col: o.col || PC.white, mat: o.mat || 'card', depth: o.depth ?? 1.6, seed: seed * 17 });+}+// sun(x, y, r, { col, rays, spin }) — disc + triangular ray pieces that tick round+function sun(x, y, r = 90, o = {}) {+ const n = o.rays ?? 12, spin = sm(T) * (o.spin ?? 6);+ for (let i = 0; i < n; i++) { const a = (i / n * 360 + spin) * D2R, d = r * 1.32; piece(SH.tri(r * .38, r * .5), { x: x + Math.cos(a) * d, y: y + Math.sin(a) * d, rot: a / D2R + 90, col: i % 2 ? (o.col2 || PC.orange) : (o.col || PC.yellow), depth: .9, seed: 400 + i }); }+ piece(SH.circle(r), { x, y, col: o.col || PC.yellow, depth: 1.2, seed: 399 });+ if (o.inner !== false) piece(SH.circle(r * .72), { x: x - r * .06, y: y - r * .06, col: o.col3 || PC.lemon, mat: 'tissue', depth: .2, seed: 398 });+}+// stripes(x, y, w, h, n, cols, { rot, depth }) — n separate strips side by side (awnings, flags, patterned grounds)+function stripes(x, y, w, h, n, cols, o = {}) { for (let i = 0; i < n; i++) piece(SH.rect(w / n + .5, h), { x: x - w / 2 + (i + .5) * w / n, y, col: cols[i % cols.length], depth: o.depth ?? .5, seed: (o.seed || 50) + i, rot: o.rot || 0 }); }+// bunting(x0, y0, x1, y1, n, cols, { sag }) — flags on a sagging string+function bunting(x0, y0, x1, y1, n = 8, cols = [PC.red, PC.yellow, PC.teal, PC.pink], o = {}) {+ const sag = o.sag ?? 60, pt = k => [lerp(x0, x1, k), lerp(y0, y1, k) + sag * 4 * k * (1 - k)], pts = []; for (let i = 0; i <= 20; i++) pts.push(pt(i / 20));+ thread(pts, { col: o.string || '#EDE6D6' });+ const fw = Math.hypot(x1 - x0, y1 - y0) / n * .8;+ for (let i = 0; i < n; i++) { const k = (i + .5) / n, [px, py] = pt(k), a = sway('bn' + i, 4, .6); piece(SH.poly([[-fw / 2, 0], [fw / 2, 0], [0, fw * 1.1]]), { x: px, y: py - 2, rot: a, col: cols[i % cols.length], depth: 1, seed: 700 + i }); }+}+// house(x, y, s, { wall, roof, door, win }) — a little paper house standing on (x, y)+function house(x, y, s = 1, o = {}) {+ const wall = o.wall || PC.cream, roof = o.roof || PC.red;+ piece(SH.rect(300 * s, 240 * s), { x, y: y - 120 * s, col: wall, mat: 'card', depth: 1, seed: 801 });+ piece(SH.poly([[-190 * s, 0], [0, -150 * s], [190 * s, 0]]), { x, y: y - 236 * s, col: roof, depth: 1.3, seed: 802 });+ stripes(x, y - 246 * s, 250 * s, 14 * s, 5, [PC.white, roof], { seed: 810, depth: .4 });+ piece(SH.round(80 * s, 130 * s, 38 * s), { x: x + 60 * s, y: y - 65 * s, col: o.door || PC.teal, depth: .6, seed: 803 });+ brad(x + 84 * s, y - 62 * s, 6 * s);+ piece(SH.round(80 * s, 70 * s, 8 * s), { x: x - 70 * s, y: y - 150 * s, col: o.win || PC.sky, depth: .5, seed: 804 });+ piece(SH.rect(84 * s, 8 * s), { x: x - 70 * s, y: y - 150 * s, col: wall, depth: .4, seed: 805 });+ piece(SH.rect(8 * s, 74 * s), { x: x - 70 * s, y: y - 150 * s, col: wall, depth: .4, seed: 806 });+}+// confetti(lt, x, y, { t0, n, cols, spread, power, seed }) — a stepped paper-confetti burst from (x, y) at t0+function confetti(lt, x, y, o = {}) {+ const t0 = o.t0 || 0, a = sm(lt) - t0; if (a < 0) return;+ const n = o.n || 40, cols = o.cols || [PC.red, PC.yellow, PC.teal, PC.pink, PC.blue, PC.lime, PC.orange], q = rnd('conf' + (o.seed || 1)), pw = o.power || 1;+ for (let i = 0; i < n; i++) {+ const ang = (-90 + (q() - .5) * (o.spread || 110)) * D2R, v = (700 + q() * 900) * pw, drag = Math.exp(-1.6 * a), sz = (18 + q() * 16) * (o.size || 1), kind = Math.floor(q() * 4), c = cols[i % cols.length], ph = q() * TAU, spin = (q() - .5) * 900;+ const px = x + Math.cos(ang) * v * (1 - drag) / 1.6 + Math.sin(a * 3 + ph) * 25 * Math.min(1, a), py = y + Math.sin(ang) * v * (1 - drag) / 1.6 + 260 * a * a;+ const sh = kind === 0 ? SH.rect(sz, sz * .6) : kind === 1 ? SH.circle(sz * .45) : kind === 2 ? SH.tri(sz, sz * .9) : SH.rect(sz * 1.5, sz * .35);+ piece(sh, { x: px, y: py, rot: spin * a, sx: Math.max(.15, Math.abs(Math.cos(a * 7 + ph))), col: c, depth: 2, seed: 900 + i, edge: false, jit: 0 });+ }+}++// ---------- props (all drawn around a grip point, angle in degrees, size unit s ≈ the character's u) ----------+const PROPS = {+ apple(x, y, ang = 0, s = 30) {+ G.save(); G.translate(x, y); G.rotate(ang * D2R);+ piece(SH.smooth([[0, -.55 * s], [.55 * s, -.75 * s], [.95 * s, -.2 * s], [.8 * s, .55 * s], [.35 * s, .85 * s], [0, .72 * s], [-.35 * s, .85 * s], [-.8 * s, .55 * s], [-.95 * s, -.2 * s], [-.55 * s, -.75 * s]]), { y: -.1 * s, col: PC.red, depth: 1, seed: 1201 });+ piece(SH.ellipse(.2 * s, .32 * s), { x: -.45 * s, y: -.25 * s, rot: 20, col: '#F08A7A', depth: 0, seed: 1204, edge: false });+ piece(SH.capsule(.45 * s, .07 * s), { x: .05 * s, y: -1.05 * s, rot: -15, col: PC.bark, mat: 'kraft', depth: .6, seed: 1202 });+ piece(SH.leaf(.6 * s, .3 * s), { x: .1 * s, y: -.75 * s, rot: 60, col: PC.leaf, depth: .7, seed: 1203 });+ G.restore();+ },+ balloon(x, y, ang = 0, s = 30, col = PC.red) {+ const bx = x + Math.sin(ang * D2R) * 4 * s, by = y - 4 * s;+ thread([[x, y], [lerp(x, bx, .5) + s * .3, lerp(y, by, .5)], [bx, by + 1.3 * s]], { col: '#F4EEE2', w: 2 });+ piece(SH.ellipse(1.1 * s, 1.35 * s), { x: bx, y: by, rot: ang, col, depth: 1.6, seed: 1301 });+ piece(SH.tri(.4 * s, .3 * s), { x: bx, y: by + 1.42 * s, col, depth: .8, seed: 1302 });+ piece(SH.ellipse(.22 * s, .38 * s), { x: bx - .45 * s, y: by - .5 * s, rot: 25, col: '#FFFFFF', mat: 'tissue', depth: 0, seed: 1303 });+ },+ flower(x, y, ang = 0, s = 30, col = PC.pink) { G.save(); G.translate(x, y); G.rotate(ang * D2R); flower(0, 1.6 * s, s / 22, col, { seed: 1400, sway: 0 }); G.restore(); },+ star(x, y, ang = 0, s = 30, col = PC.yellow) { // a star wand+ G.save(); G.translate(x, y); G.rotate(ang * D2R);+ piece(SH.capsule(2.6 * s, .1 * s), { y: -2.2 * s, col: PC.kraft, mat: 'kraft', depth: .7, seed: 1501 });+ piece(SH.star(.9 * s, .42 * s), { y: -2.4 * s, col, depth: 1.4, seed: 1502 }); G.restore();+ },+ gift(x, y, ang = 0, s = 30, col = PC.teal, rib = PC.pink) {+ G.save(); G.translate(x, y); G.rotate(ang * D2R);+ piece(SH.rect(1.6 * s, 1.3 * s), { y: -.3 * s, col, depth: 1, seed: 1601 });+ piece(SH.rect(.3 * s, 1.34 * s), { y: -.3 * s, col: rib, depth: .3, seed: 1602 });+ piece(SH.ellipse(.4 * s, .25 * s), { x: -.3 * s, y: -1.05 * s, rot: 20, col: rib, depth: .6, seed: 1603 });+ piece(SH.ellipse(.4 * s, .25 * s), { x: .3 * s, y: -1.05 * s, rot: -20, col: rib, depth: .6, seed: 1604 });+ G.restore();+ },+ letter(x, y, ang = 0, s = 30, col = PC.white) {+ G.save(); G.translate(x, y); G.rotate(ang * D2R);+ piece(SH.rect(1.8 * s, 1.2 * s), { y: -.3 * s, col, mat: 'card', depth: 1, seed: 1701 });+ piece(SH.poly([[-.9 * s, -.9 * s], [.9 * s, -.9 * s], [0, -.2 * s]]), { col: mixCol(col, '#C8B89A', .25), mat: 'card', depth: .3, seed: 1702 });+ piece(SH.heart(.45 * s), { y: -.35 * s, col: PC.red, depth: .3, seed: 1703 });+ G.restore();+ },+};++// ---------- transitions (screen space: call after camEnd(), with k = 0 → 1) ----------+// The incoming shot calls them over its own first frames; they render the PREVIOUS shot themselves (still moving),+// so the previous shot must not draw an out-transition of its own. Drive k with stepped time for a stop-motion feel:+// trTear(t, seg(sm(lt), 0, .7)).+let IN_PREV = false;+const BUFS = {};+const buf = name => BUFS[name] || (BUFS[name] = makeCanvas());+function shotIndexAt(t) { let i = 0; while (i + 1 < SHOTS.length && t >= SHOTS[i + 1][0]) i++; return i; }+// render the previous shot (at time t, i.e. still running) into a buffer; null if this is the first shot+function prevFrame(t) {+ const i = shotIndexAt(t); if (i === 0) return null;+ const b = buf('prev'), c = b.getContext('2d'), [t0, fn] = SHOTS[i - 1], end = SHOTS[i][0];+ const sG = G, sCAM = CAM, sLAST = LAST_CAM, sJ = PAPER.jit;+ G = c; G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over'; noShadow(); G.clearRect(0, 0, W, H); CAM = null; IN_PREV = true;+ try { fn(t, t - t0, end - t0); if (CAM) camEnd(); } finally { IN_PREV = false; G = sG; CAM = sCAM; LAST_CAM = sLAST; PAPER.jit = sJ; }+ return b;+}+function snapCur() { const b = buf('cur'), c = b.getContext('2d'); c.setTransform(1, 0, 0, 1, 0, 0); c.globalCompositeOperation = 'copy'; c.drawImage(G.canvas, 0, 0); c.globalCompositeOperation = 'source-over'; return b; }+function plainSheet(col = PC.cream) { const b = buf('sheet' + col), c = b.getContext('2d'); if (!b.done) { c.fillStyle = mat(col, 'paper'); c.fillRect(0, 0, W, H); b.done = 1; } return b; }+function screenReset() { G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over'; noShadow(); }+// 1. a paper sheet with the new shot on it slides over the old one (dir: 'left' | 'right' | 'up' | 'down' = where it travels)+function trSlide(t, k, o = {}) {+ if (IN_PREV || k >= 1) return; const prev = prevFrame(t) || plainSheet(o.col), cur = snapCur(), e = easeOut(k);+ screenReset(); G.drawImage(prev, 0, 0);+ const d = o.dir || 'left', dx = d === 'left' ? W * (1 - e) : d === 'right' ? -W * (1 - e) : 0, dy = d === 'up' ? H * (1 - e) : d === 'down' ? -H * (1 - e) : 0;+ G.fillStyle = `rgba(40,25,12,${.25 * e})`; G.fillRect(0, 0, W, H);+ G.save(); G.translate(W / 2 + dx, H / 2 + dy); G.rotate((1 - e) * (o.tilt ?? 3) * D2R);+ setShadow(3.5, 1); G.fillStyle = PC.white; G.fillRect(-W / 2, -H / 2, W, H); noShadow(); G.drawImage(cur, -W / 2, -H / 2);+ G.restore();+}+// 2. flip-card turn: the old frame is a card that flips over; its back is the new shot. Table shows behind.+function trFlip(t, k, o = {}) {+ if (IN_PREV || k >= 1) return; const prev = prevFrame(t) || plainSheet(o.col), cur = snapCur(), e = ease(k);+ const img = e < .5 ? prev : cur, sx = Math.max(.004, Math.abs(Math.cos(e * Math.PI))), lift = 1 - .16 * Math.sin(e * Math.PI);+ screenReset(); table(o);+ G.save(); G.translate(W / 2, H / 2 - 30 * Math.sin(e * Math.PI)); G.rotate((o.tilt ?? -4) * Math.sin(e * Math.PI) * D2R); G.scale(sx * lift, lift);+ setShadow(2 + 5 * Math.sin(e * Math.PI), lift); G.fillStyle = PC.white; G.fillRect(-W / 2, -H / 2, W, H); noShadow(); G.drawImage(img, -W / 2, -H / 2);+ G.fillStyle = `rgba(30,18,8,${(1 - sx) * .45})`; G.fillRect(-W / 2, -H / 2, W, H);+ G.strokeStyle = 'rgba(255,252,240,.9)'; G.lineWidth = 14; G.strokeRect(-W / 2 + 7, -H / 2 + 7, W - 14, H - 14);+ G.restore();+}+// 3. torn-paper reveal: the old frame is torn in two down a ragged line and the halves pull apart+function trTear(t, k, o = {}) {+ if (IN_PREV || k >= 1) return; const prev = prevFrame(t) || plainSheet(o.col), e = easeIn(k), seed = o.seed || 3;+ screenReset();+ const pts = []; for (let y = -40; y <= H + 40; y += 6) pts.push([W / 2 + (fbm1(y / 260, seed) - .5) * 420 + (fbm1(y / 23, seed + 4) - .5) * 30 + (hash(y * .37 + seed) - .5) * 7, y]);+ const halves = [{ side: -1, rot: -(o.rot ?? 9) }, { side: 1, rot: o.rot ?? 7 }];+ for (const hf of halves) {+ const tear = pts.map(([x, y]) => [x, y]), rimPts = pts.map(([x, y], i) => [x - hf.side * (5 + 11 * fbm1(i / 5, seed + 9)), y]);+ const edgeX = hf.side < 0 ? -60 : W + 60, outer = new Path2D(), inner = new Path2D();+ outer.moveTo(edgeX, -40); tear.forEach(p => outer.lineTo(p[0], p[1])); outer.lineTo(edgeX, H + 40); outer.closePath();+ inner.moveTo(edgeX, -40); rimPts.forEach(p => inner.lineTo(p[0], p[1])); inner.lineTo(edgeX, H + 40); inner.closePath();+ const fib = new Path2D(); tear.forEach(([x, y], i) => { if (hash(i * 1.3 + seed) < .5) { fib.moveTo(x, y); fib.lineTo(x + hf.side * -1 * (3 + hash(i) * 7), y + (hash(i * 2.1) - .5) * 8); } });+ G.save();+ const px = hf.side < 0 ? 0 : W, py = H * .9; // pull pivot at the outer bottom corner+ G.translate(px + hf.side * e * W * .62, py + e * 90); G.rotate(hf.rot * e * D2R); G.translate(-px, -py);+ setShadow(1.5 + 3 * e, 1); G.fillStyle = PC.white; G.fill(outer); noShadow();+ G.strokeStyle = '#FBF7EE'; G.lineWidth = 1.2; G.stroke(fib);+ G.save(); G.clip(inner); G.drawImage(prev, 0, 0); G.restore();+ G.restore();+ }+}+// 4. pop-up book fold: the new shot stands up off the page from a hinge at the bottom (old shot / table lies behind).+// Pair it with popUp() on scene elements for pieces that unfold a beat later.+function trBook(t, k, o = {}) {+ if (IN_PREV || k >= 1) return; const prev = prevFrame(t), cur = snapCur(), sy = Math.max(.01, easeOut(k) * (1 + (o.bounce === false ? 0 : .07) * Math.sin(k * Math.PI)));+ screenReset(); if (prev) G.drawImage(prev, 0, 0); else table(o);+ G.fillStyle = `rgba(30,18,8,${.3 * k})`; G.fillRect(0, 0, W, H);+ G.save(); G.translate(0, H); G.scale(1, sy);+ setShadow(3, 1); G.fillStyle = PC.white; G.fillRect(0, -H, W, H); noShadow(); G.drawImage(cur, 0, -H);+ G.fillStyle = `rgba(30,18,8,${(1 - Math.min(1, sy)) * .55})`; G.fillRect(0, -H, W, H);+ G.restore();+ // the page crease+ G.fillStyle = 'rgba(40,24,10,.25)'; G.fillRect(0, H - 6, W, 6);+}+// sheetIn / sheetOut: a plain paper sheet slides off (opening) or over (ending) the frame — no previous shot needed+function sheetOut(k, o = {}) { if (IN_PREV || k <= 0) return; sheetAt(1 - easeOut(clamp(k)), o); }+function sheetIn(k, o = {}) { if (IN_PREV || k >= 1) return; sheetAt(easeIn(clamp(k)), o); }+function sheetAt(off, o) {+ screenReset(); const d = o.dir || 'left', dx = d === 'left' ? W * off : d === 'right' ? -W * off : 0, dy = d === 'up' ? H * off : d === 'down' ? -H * off : 0;+ G.save(); G.translate(W / 2 + dx, H / 2 + dy); G.rotate(off * 3 * D2R);+ piece(SH.rect(W + 40, H + 40), { col: o.col || PC.cream, torn: 'left', tornAmp: 9, depth: 3.2, seed: 4242, jit: 0 });+ G.restore();+}++// ---------- captions (overlay, crisp, CJK-capable) ----------+// captionTrack([[t0, t1, text, { style: 'label' | 'letters', y, size, col, bg, cols, rot }], ...])+// label = ink letters printed on a torn paper label strip (subtitles, speech)+// letters = each glyph cut out of coloured paper with a white margin (titles, shouts)+const CAP_FONT = '"Chiron GoRound TC", "Zen Maru Gothic", "Noto Sans TC", "Noto Sans", system-ui, sans-serif';+window.EXTRA_FONTS = [[`900 64px "Chiron GoRound TC"`, '紙片字幕'], [`900 64px "Zen Maru Gothic"`, 'あ字'], [`900 64px "Noto Sans TC"`, '紙片字幕']];+const CAPS = [], FONT_TEXT = [];+function captionTrack(list) { CAPS.push(...list); list.forEach(c => FONT_TEXT.push(c[2])); window.overlayHook = drawCaptions; }+function drawCaptions(c, t) {+ for (const [t0, t1, txt, o = {}] of CAPS) {+ if (t < t0 || t > t1 + .4) continue;+ const kin = seg(sm(t - t0), 0, .34), kout = seg(sm(t - t1), 0, .34);+ (o.style === 'letters' ? lettersCap : labelCap)(c, txt, { ...o, kin, kout, t0 });+ }+}+function withG(c, fn) { const s = G; G = c; try { fn(); } finally { G = s; } }+function labelCap(c, txt, o = {}) {+ const size = o.size || 72, kin = o.kin ?? 1, kout = o.kout ?? 0; if (kin <= 0 || kout >= 1) return;+ c.save(); c.font = `900 ${size}px ${CAP_FONT}`; const tw = c.measureText(txt).width, w = tw + size * 1.3, h = size * 1.55;+ const x = o.x ?? W / 2, y = (o.y ?? H - 118) + kout * 260, pop = kin < 1 ? backOut(kin) : 1, rot = o.rot ?? (hash(keyNum(txt)) - .5) * 3;+ c.translate(x, y); c.rotate(rot * D2R); c.scale(pop, pop);+ withG(c, () => { piece(SH.rect(w, h), { col: o.bg || PC.white, mat: 'card', torn: 'sides', tornAmp: 6, depth: 2.2, seed: keyNum(txt) % 997, jit: 0 }); piece(SH.rect(w * .16, h * .34), { x: -w * .5 + size * .1, y: -h * .5, rot: -30, col: '#E9E2C9', mat: 'tissue', depth: .2, seed: 5, jit: 0 }); });+ c.textAlign = 'center'; c.textBaseline = 'middle'; c.fillStyle = o.col || PC.ink; c.fillText(txt, 0, size * .05);+ c.restore();+}+function lettersCap(c, txt, o = {}) {+ const size = o.size || 96, kin = o.kin ?? 1, kout = o.kout ?? 0; if (kout >= 1) return;+ const cols = o.cols || [PC.red, PC.orange, PC.teal, PC.blue, PC.rose, PC.grass], chars = [...txt];+ c.save(); c.font = `900 ${size}px ${CAP_FONT}`; c.textAlign = 'center'; c.textBaseline = 'middle'; c.lineJoin = 'round';+ const ws = chars.map(ch => c.measureText(ch).width + size * .12), tot = ws.reduce((a, b) => a + b, 0);+ let x = (o.x ?? W / 2) - tot / 2; const y0 = (o.y ?? 150) - kout * 420, n = chars.length;+ chars.forEach((ch, i) => {+ const cx = x + ws[i] / 2; x += ws[i]; if (ch === ' ') return;+ const kk = clamp(kin * (n + 2) - i), pop = kk <= 0 ? 0 : kk < 1 ? backOut(kk) : 1; if (pop <= 0) return;+ const h = keyNum(txt) + i * 7.7, r = (hash(h) - .5) * 12 + (hash(h + PAPER.step * .31) - .5) * 1.2, dy = (hash(h + 3) - .5) * size * .14;+ c.save(); c.translate(cx, y0 + dy); c.rotate(r * D2R); c.scale(pop, pop);+ setShadow(2.2, 1, 1, c); c.lineWidth = size * .26; c.strokeStyle = mat(PC.white, 'card'); c.strokeText(ch, 0, 0); c.fillStyle = PC.white; c.fillText(ch, 0, 0); noShadow(c);+ c.fillStyle = mat(cols[i % cols.length], 'paper'); c.fillText(ch, 0, 0);+ c.restore();+ });+ c.restore();+}++// ---------- the photographed look: lamp light, vignette, flicker, grain ----------+const LOOK = {};+function buildLook() {+ const c = makeCanvas(W, H), x = c.getContext('2d');+ x.fillStyle = '#fff'; x.fillRect(0, 0, W, H);+ const g = x.createRadialGradient(W * .4, H * .36, H * .28, W * .5, H * .5, W * .75);+ g.addColorStop(0, 'rgba(255,250,240,0)'); g.addColorStop(.6, 'rgba(236,214,190,.35)'); g.addColorStop(1, 'rgba(150,112,80,.8)');+ x.fillStyle = g; x.fillRect(0, 0, W, H); LOOK.mul = c;+ const s = makeCanvas(480, 270), y = s.getContext('2d'), g2 = y.createRadialGradient(150, 80, 0, 150, 80, 300);+ g2.addColorStop(0, 'rgba(255,226,170,.55)'); g2.addColorStop(1, 'rgba(255,226,170,0)'); y.fillStyle = g2; y.fillRect(0, 0, 480, 270); LOOK.spot = s;+ const n = makeCanvas(256, 256), z = n.getContext('2d'), id = z.createImageData(256, 256), r = rnd('filmgrain');+ for (let i = 0; i < id.data.length; i += 4) { const v = 128 + (r() - .5) * 90; id.data[i] = id.data[i + 1] = id.data[i + 2] = v; id.data[i + 3] = 255; }+ z.putImageData(id, 0, 0); LOOK.grain = OUT.createPattern(n, 'repeat');+}+function applyLook(t) {+ const c = OUT; c.setTransform(1, 0, 0, 1, 0, 0); noShadow(c);+ if (PAPER.vignette) { c.globalCompositeOperation = 'multiply'; c.globalAlpha = PAPER.vignette; c.drawImage(LOOK.mul, 0, 0); }+ c.globalCompositeOperation = 'screen'; c.globalAlpha = .55; c.drawImage(LOOK.spot, 0, 0, W, H);+ const f = (hash(PAPER.step * .917 + .3) - .5) * 2 * .03 * PAPER.flicker;+ c.globalAlpha = 1; c.globalCompositeOperation = 'source-over';+ if (f > 0) { c.fillStyle = `rgba(255,240,215,${f})`; c.fillRect(0, 0, W, H); } else if (f < 0) { c.fillStyle = `rgba(35,22,12,${-f})`; c.fillRect(0, 0, W, H); }+ if (PAPER.grain) {+ LOOK.grain.setTransform(new DOMMatrix([1, 0, 0, 1, hash(PAPER.step * 1.3) * 256, hash(PAPER.step * 2.9) * 256]));+ c.globalCompositeOperation = 'overlay'; c.globalAlpha = .07 * PAPER.grain; c.fillStyle = LOOK.grain; c.fillRect(0, 0, W, H);+ }+ c.globalAlpha = 1; c.globalCompositeOperation = 'source-over';+}++window.ENGINE = {+ async setup() {+ for (const k of Object.keys(GRAIN_SPEC)) GRAIN[k] = makeGrain(k);+ for (const col of Object.values(PC)) mat(col, 'paper');+ buildLook();+ if (FONT_TEXT.length) { const all = FONT_TEXT.join(''); await Promise.all([`900 64px "Chiron GoRound TC"`, `900 64px "Zen Maru Gothic"`, `900 64px "Noto Sans TC"`].map(f => document.fonts.load(f, all).catch(() => { }))); }+ },+ begin(t) { PAPER.step = Math.floor(t * PAPER.fps + 1e-6); PAPER.jit = 0; PAPER.dry = false; IN_PREV = false; },+ end(t) { applyLook(t); },+};diff --git a/.claude/skills/paper-cutout/template/src/kit.js b/.claude/skills/paper-cutout/template/src/kit.jsnew file mode 100644index 0000000..8d6f3c2--- /dev/null+++ b/.claude/skills/paper-cutout/template/src/kit.js@@ -0,0 +1,154 @@+// kit.js: the shared runtime for ReelMimic's Canvas-2D drawing engines (pixel art, paper cut-out, whiteboard, anime+// cel, crayon storybook). Each engine copies this file into its template unchanged and adds its own drawing library.+//+// The render contract is the same as painted-animation's, so the same render.mjs drives every engine:+// window.ready = true once fonts and assets are loaded+// window.renderAt(t, type, q) → data URL of the frame at time t+// window.renderSheet(times, cols, w, crop, at) → { url, ms[] } contact sheet (crop = [x,y,w,h] in screen px,+// at = [x,y,w,h] around a WORLD point, wherever the camera put it)+// Every frame is a pure function of t: frames render in parallel and out of order, so nothing may carry over from one+// frame to the next. Use hash()/rnd() for stable randomness, never Math.random().+//+// An engine plugs in through window.ENGINE = { setup(), begin(t), end(t) } (all optional):+// setup() → once, async (load images, build textures); begin(t) → before the shot draws (e.g. switch G to a low-res+// buffer); end(t) → after it (e.g. upscale, add grain). Shots draw with the 2D context G.++const W = 1920, H = 1080, TAU = Math.PI * 2;+const DUR = PROJECT.duration, BPM = PROJECT.bpm || 120, BEAT = 60 / BPM, OFF = PROJECT.offset || 0;+const FPS = PROJECT.fps || 24;++// ---------- math & timing (pure functions of t) ----------+const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));+const lerp = (a, b, x) => a + (b - a) * x;+const ease = x => { x = clamp(x); return x * x * (3 - 2 * x); };+const easeIn = x => Math.pow(clamp(x), 3);+const easeOut = x => 1 - Math.pow(1 - clamp(x), 3);+const backOut = x => { x = clamp(x); const s = 1.9; return 1 + (s + 1) * Math.pow(x - 1, 3) + s * Math.pow(x - 1, 2); };+const elasticOut = x => { x = clamp(x); return x === 0 || x === 1 ? x : Math.pow(2, -10 * x) * Math.sin((x * 10 - .75) * (TAU / 3)) + 1; };+const hash = i => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };+// seeded stream for one element: const r = rnd('tree' + i); r() → 0..1, the same every frame+function rnd(key) { let h = 2166136261; for (const c of String(key)) h = Math.imul(h ^ c.charCodeAt(0), 16777619); let s = h >>> 0 || 1; return () => (s = Math.imul(s ^ (s >>> 15), 2246822519) >>> 0, s = (s ^ (s >>> 13)) >>> 0, (s % 1000003) / 1000003); }+const seg = (t, a, b) => clamp((t - a) / (b - a));+const frac = x => x - Math.floor(x);+const bpOf = t => (t - OFF) / BEAT;+const beatN = t => Math.floor(bpOf(t));+const pulse = (t, k = 6) => Math.exp(-frac(bpOf(t)) * k);+const wob = (t, f = 1, ph = 0) => Math.sin((t * f + ph) * TAU);+// hold drawings like hand animation: onTwos(t) = 12 drawings/s, onStep(t, 8) = 8/s (stop-motion feel)+const onTwos = t => Math.floor(t * 12 + 1e-6) / 12;+const onStep = (t, n) => Math.floor(t * n + 1e-6) / n;+function kf(t, keys, e = ease) {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) if (t < keys[i][0]) {+ const [a, va] = keys[i - 1], [b, vb] = keys[i], k = e((t - a) / (b - a));+ return Array.isArray(va) ? va.map((v, j) => lerp(v, vb[j], k)) : lerp(va, vb, k);+ }+ return keys[keys.length - 1][1];+}+function mixCol(a, b, k) {+ const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16), c = i => Math.round(lerp((pa >> i) & 255, (pb >> i) & 255, clamp(k)));+ return '#' + ((1 << 24) + (c(16) << 16) + (c(8) << 8) + c(0)).toString(16).slice(1);+}+const shakeXY = (t, amt) => { const f = Math.floor(t * 24); return [(hash(f * 1.7) - .5) * 2 * amt, (hash(f * 2.3 + 9) - .5) * 2 * amt]; };+// motion principles+const spring = (t, t0, k = 6, w = 18) => t < t0 ? 0 : Math.exp(-k * (t - t0)) * Math.sin(w * (t - t0));+const arcPt = (p0, p1, h, k) => [lerp(p0[0], p1[0], k), lerp(p0[1], p1[1], k) - h * 4 * k * (1 - k)];+function jump(t, t0, t1, h = 3) { // → { dy (units, up is negative), sq (squash +, stretch -) }+ if (t < t0 - .12) return { dy: 0, sq: 0 };+ if (t < t0) return { dy: 0, sq: .18 * ease(seg(t, t0 - .12, t0)) };+ if (t < t1) { const k = (t - t0) / (t1 - t0); return { dy: -h * 4 * k * (1 - k), sq: -.16 * Math.abs(1 - 2 * k) }; }+ const a = t - t1; return { dy: 0, sq: .22 * Math.exp(-8 * a) * Math.cos(20 * a) };+}+function take(t, t0, amt = 1) { // surprise take peaking at t0+ if (t < t0 - .1) return { sq: 0, dy: 0 };+ if (t < t0) return { sq: .12 * amt * ease(seg(t, t0 - .1, t0)), dy: 0 };+ const a = t - t0; return { sq: -.26 * amt * Math.exp(-6 * a) * Math.cos(16 * a), dy: -1.2 * amt * Math.exp(-7 * a) * Math.max(0, Math.cos(9 * a)) };+}++// ---------- shots ----------+// shots([[t0, fn], ...]); fn(t, lt, dur) paints the WHOLE frame (background included) with G.+const SHOTS = [], LOOPS = {};+function shots(list) { SHOTS.push(...list); SHOTS.sort((a, b) => a[0] - b[0]); }+function drawWorld(t) {+ if (window.LOOP) return window.LOOP(t);+ if (!SHOTS.length) { G.fillStyle = '#EDE6D8'; G.fillRect(0, 0, W, H); return; }+ let i = 0; while (i + 1 < SHOTS.length && t >= SHOTS[i + 1][0]) i++;+ const t0 = SHOTS[i][0], end = i + 1 < SHOTS.length ? SHOTS[i + 1][0] : DUR;+ SHOTS[i][1](t, t - t0, end - t0);+ if (CAM) camEnd();+}++// ---------- camera (world → screen) ----------+let CAM = null, LAST_CAM = null;+function camBegin(cx = W / 2, cy = H / 2, zoom = 1, rot = 0) {+ G.save(); G.translate(W / 2, H / 2); G.rotate(rot); G.scale(zoom, zoom); G.translate(-cx, -cy);+ CAM = LAST_CAM = { cx, cy, zoom, rot };+}+function camEnd() { G.restore(); CAM = null; }+function toScreen(x, y, cam = CAM) {+ if (!cam) return [x, y];+ const dx = (x - cam.cx) * cam.zoom, dy = (y - cam.cy) * cam.zoom, c = Math.cos(cam.rot), s = Math.sin(cam.rot);+ return [W / 2 + dx * c - dy * s, H / 2 + dx * s + dy * c];+}++// ---------- canvases & frame ----------+// G: the context shots draw into (an engine may point it at a low-res buffer in begin()). OUT: the visible 1920×1080.+let G = null, OUT = null, OUTC = null, T = 0;+function makeCanvas(w = W, h = H) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }+async function renderFrame(t) {+ T = t; CAM = LAST_CAM = null;+ G = OUT; G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over';+ G.clearRect(0, 0, W, H);+ if (window.ENGINE && ENGINE.begin) ENGINE.begin(t);+ drawWorld(t);+ if (window.ENGINE && ENGINE.end) ENGINE.end(t);+ OUT.setTransform(1, 0, 0, 1, 0, 0); OUT.globalAlpha = 1; OUT.globalCompositeOperation = 'source-over';+ if (window.overlayHook) window.overlayHook(OUT, t); // crisp captions / karaoke above everything+}+window.renderAt = async (t, type = 'image/png', q = .92) => { await renderFrame(t); return OUTC.toDataURL(type, q); };+window.renderSheet = async (times, cols = 3, w = 640, crop = null, at = null) => {+ if (at) at = at.map((v) => typeof v === 'string' ? (0, eval)(v) : v);+ const [, , cw, ch] = at || crop || [0, 0, W, H], h = Math.round(w * ch / cw), rows = Math.ceil(times.length / cols), sc = makeCanvas(cols * w, rows * h);+ const c = sc.getContext('2d'), ms = [];+ for (let i = 0; i < times.length; i++) {+ const t0 = performance.now(); await renderFrame(times[i]); ms.push(Math.round(performance.now() - t0));+ const x = (i % cols) * w, y = Math.floor(i / cols) * h;+ const [cx, cy] = at ? toScreen(at[0], at[1], LAST_CAM).map((v, j) => v - (j ? ch : cw) / 2) : crop || [0, 0];+ c.imageSmoothingEnabled = !(window.ENGINE && ENGINE.crisp);+ c.drawImage(OUTC, cx, cy, cw, ch, x, y, w, h);+ c.fillStyle = 'rgba(0,0,0,.65)'; c.fillRect(x, y, 84, 24); c.fillStyle = '#fff'; c.font = '15px sans-serif'; c.fillText(times[i].toFixed(2) + 's', x + 6, y + 17);+ }+ return { url: sc.toDataURL('image/jpeg', .9), ms };+};+window.gpuInfo = () => 'canvas2d';++// ---------- captions (optional) ----------+// A simple, legible caption bar on the overlay: caption(c, text, { y, size, font, fg, bg }). Engines may style their own.+function caption(c, txt, o = {}) {+ const size = o.size || 54, y = o.y || H - 70, font = o.font || `700 ${size}px "Noto Sans TC", "Noto Sans", system-ui, sans-serif`;+ c.save(); c.font = font; c.textAlign = 'center'; c.textBaseline = 'middle';+ const w = c.measureText(txt).width + size * 1.1;+ c.fillStyle = o.bg || 'rgba(20,18,26,.72)'; const r = size * .5;+ c.beginPath(); c.roundRect(W / 2 - w / 2, y - size * .78, w, size * 1.56, r); c.fill();+ c.lineJoin = 'round'; c.lineWidth = size * .14; c.strokeStyle = 'rgba(0,0,0,.55)'; c.strokeText(txt, W / 2, y + 2);+ c.fillStyle = o.fg || '#FFF8EC'; c.fillText(txt, W / 2, y + 2); c.restore();+}++// ---------- boot ----------+async function boot() {+ OUTC = document.getElementById('out'); OUT = OUTC.getContext('2d', { willReadFrequently: false });+ const fonts = [...(window.EXTRA_FONTS || [])].map(([f, txt]) => document.fonts.load(f, txt));+ await Promise.all(fonts);+ if (window.ENGINE && ENGINE.setup) await ENGINE.setup();+ window.ready = true;+ if (!location.search.includes('render')) devUI();+}+function devUI() {+ const s = document.getElementById('scrub'), lab = document.getElementById('tt'); if (!s) return;+ s.max = window.LOOP ? window.LOOP.len : DUR; s.step = 1 / FPS;+ let busy = false, want = null;+ const go = async () => { if (busy) return; busy = true; while (want != null) { const t = want; want = null; const t0 = performance.now(); await renderFrame(t); lab.textContent = `${t.toFixed(2)}s · ${Math.round(performance.now() - t0)} ms/frame`; } busy = false; };+ s.addEventListener('input', () => { want = +s.value; go(); });+ want = +(new URLSearchParams(location.search).get('t') || 0); s.value = want; go();+}+window.addEventListener('load', () => { const q = new URLSearchParams(location.search).get('loop'); if (q && LOOPS[q]) window.LOOP = LOOPS[q]; boot(); });diff --git a/.claude/skills/paper-cutout/template/src/scenes/demo.js b/.claude/skills/paper-cutout/template/src/scenes/demo.jsnew file mode 100644index 0000000..90b2894--- /dev/null+++ b/.claude/skills/paper-cutout/template/src/scenes/demo.js@@ -0,0 +1,100 @@+// demo.js — "The Apple" (11 s, 3 shots). Pom jumps for an apple, then gives it to Lulu.+// A 0.00–4.25 pop-up page in · meadow establishing push-in · Pom looks up, decides, crouch → jump → grab → land, laughs+// B 4.25–8.00 torn-paper reveal · Lulu walks in, sad · Pom offers the apple · Lulu: surprised → love+// C 8.00–11.0 flip-card turn · close two-shot, Lulu holds the apple, both laugh, confetti · caption · sheet slides over+(() => {+ // ---------------- A: the apple tree ----------------+ const PX = 780, PY = 965, PU = 64, TX = 1180, TY = 950, TS = 1.4;+ const J0 = 2.2, J1 = 2.75, GRAB = 2.5;+ // where Pom's right hand is at the top of the jump: hang the apple exactly there+ let APPLE = null;+ const reach = st => ({ view: '3q', ...jumpPose(st, J0, J1, 5), armR: [135, 12], armL: [-120, -10] });+ function appleSpot() { if (!APPLE) { const j = pom(PX, PY, PU, { ...reach(GRAB), dry: true, jit: 0 }); APPLE = j.hand[1]; } return APPLE; }++ function shotA(t, lt, dur) {+ const st = sm(lt);+ paperCam(lt, [[0, [960, 540, 1]], [1.7, [930, 540, 1.1]], [dur, [905, 545, 1.15]]]);+ backdrop(PC.sky, { to: 'rgba(255,240,210,.35)' });+ layer(.25, () => { sun(1560, 190, 85); cloud(420, 210, 300, { hang: 'string', seed: 1 }); cloud(1180, 150, 230, { hang: 'string', seed: 2 }); });+ layer(.5, () => hills(960, 700, 3800, 120, PC.mint, { seed: 3, bumps: 3 }));+ layer(.75, () => { hills(960, 790, 3800, 90, PC.sage, { seed: 4, bumps: 4 }); bush(260, 820, .9, { seed: 2, cols: [PC.forest, PC.grass] }); });+ hills(960, 925, 3800, 50, PC.leaf, { seed: 5, bumps: 2 });+ // the tree shakes when the apple is pulled off it+ const shake = st >= GRAB ? spring(st, GRAB, 5, 22) * 5 : 0;+ const tr = tree(TX, TY, TS, { seed: 2, sway: sway('treeA', .8, .35) + shake, fruit: [[140, -40], [30, 110]] });+ tr.fruit.forEach(([fx, fy], i) => PROPS.apple(fx, fy + 20, (i ? -8 : 10) + shake * 2, 40));+ const ap = appleSpot();+ if (st < GRAB) { thread([[ap[0] + 6, ap[1] - 110], [ap[0] + 2, ap[1] - 30]], { col: PC.bark, w: 4 }); PROPS.apple(ap[0], ap[1] - 6, sway('hang', 4, .5), 44); }+ // Pom: look up → decide → crouch, jump, grab → land → laugh with the apple held high+ const m = moods(lt, [[0, 'neutral'], [1.45, 'determined'], [2.85, 'laugh']]);+ const air = st >= J0 - .3 && st < J1 + .35, jp = jumpPose(st, J0, J1, 5);+ let o = { view: '3q', ...m, look: [.5, -.9], tilt: -8 };+ if (st < 1.45) o.tilt = lerp(0, -10, ease(seg(st, .7, 1.1)));+ if (air) { o = { ...o, ...jp, sq: jp.sq + m.sq, look: [.3, -1] }; if (st >= J0) { o.armR = [135, 12]; o.armL = [-120, -10]; } }+ if (st >= J1 + .35) { const k = ease(seg(st, J1 + .35, J1 + .7)); o.armR = [lerp(80, 145, k), lerp(10, -5, k)]; o.armL = [lerp(-80, -25, k), 10]; o.look = [0, -.3]; o.tilt = lerp(0, -6, k); }+ if (st >= GRAB) o.holdR = { prop: 'apple', s: .72, dy: -.3 };+ const J = pom(PX, PY, PU, o);+ if (st >= 3.0) emote('sparkle', J.hand[1][0] + 40, J.hand[1][1] - 60, 34, st - 3.0);+ // foreground: grass and flowers on a nearer plane+ layer(1.25, () => { grass(400, 1010, 900, 60, PC.grass, 3); grass(1500, 1015, 1000, 70, PC.forest, 4); flower(1320, 1000, 1.2, PC.rose, { seed: 1 }); flower(560, 1005, 1, PC.yellow, { seed: 2, center: PC.orange }); flower(1650, 1000, 1.1, PC.lilac, { seed: 3 }); });+ camEnd();+ trBook(t, seg(sm(lt), 0, 1.0));+ }++ // ---------------- B: the gift ----------------+ const LW = { stride: 1.05, rate: 2.25 }, W0 = .1, W1 = 2.0, LX0 = 2020, LX1 = 1330;+ function shotB(t, lt, dur) {+ const st = sm(lt);+ paperCam(lt, [[0, [1000, 600, 1.14]], [dur, [1010, 600, 1.2]]], { stepped: true, fps: 6 });+ backdrop(PC.sky, { to: 'rgba(255,236,205,.45)' });+ layer(.3, () => { cloud(1500, 180, 260, { hang: 'string', seed: 4 }); cloud(700, 240, 200, { hang: 'string', seed: 5 }); });+ layer(.55, () => hills(960, 760, 3800, 110, PC.mint, { seed: 7, bumps: 2 }));+ layer(.8, () => { house(330, 830, 1.05, { roof: PC.tomato, door: PC.teal }); bunting(470, 560, 1250, 470, 8, [PC.red, PC.yellow, PC.teal, PC.pink], { sag: 70 }); tree(1640, 840, .8, { seed: 5, fruit: [] }); });+ hills(960, 915, 3800, 40, PC.leaf, { seed: 8, bumps: 2 });+ piece(SH.hills(3800, 30, 2, 9, 200), { x: 960, y: 985, col: PC.sand, mat: 'kraft', torn: 'top', depth: .6, seed: 9 }); // the path+ // Lulu walks in from the right, sad; stops; surprised → love when she sees the apple+ const k = seg(st, W1 - .15, W1 + .1), walking = st < W1;+ const lx = lerp(LX0, LX1, clamp((st - W0) / (W1 - W0)));+ const wc = walkCycle(st - W0, LW), lm = moods(lt, [[0, 'sad'], [2.45, 'surprised'], [2.95, 'love']]);+ let lo = { view: '3q', flip: true, ...lm, look: [.2, .4], tilt: 6 };+ if (walking) lo = { ...lo, ...wc, lean: 3 };+ else { lo.footL = [0, 0]; lo.footR = [0, 0]; lo.armL = [-8, 6]; lo.armR = [8, -6]; }+ if (st >= 2.45) { lo.look = [.6, .2]; lo.tilt = 0; }+ if (st >= 2.95) { const h = ease(seg(st, 2.95, 3.15)); lo.armL = [lerp(-8, -140, h), lerp(6, -96, h)]; lo.armR = [lerp(8, 140, h), lerp(-6, 96, h)]; lo.tilt = -6; } // hands to her cheeks+ const JL = lulu(lx, 985, 38, lo);+ // Pom offers the apple+ const off = ease(seg(st, 2.05, 2.35)), pm = moods(lt, [[0, 'happy'], [2.05, 'happy'], [2.95, 'laugh']]);+ const JP = pom(640, 990, 56, { view: '3q', ...pm, look: [.8, -.1], lean: lerp(0, 7, off), armR: [lerp(25, 95, off), lerp(15, -5, off)], armL: [-20, 10], holdR: { prop: 'apple', s: .75, dy: -.3 } });+ if (st >= 2.45 && st < 2.95) emote('!', JL.top[0] + 20, JL.top[1] - 30, 42, st - 2.45);+ if (st >= 2.95) emote('heart', JL.top[0] - 10, JL.top[1] - 40, 40, st - 2.95);+ layer(1.3, () => { grass(300, 1080, 900, 70, PC.forest, 6); flower(1780, 1075, 1.3, PC.yellow, { seed: 7 }); });+ camEnd();+ trTear(t, seg(sm(lt), 0, .75));+ }++ // ---------------- C: sharing ----------------+ function shotC(t, lt, dur) {+ const st = sm(lt);+ paperCam(lt, [[0, [960, 540, 1]], [dur, [960, 555, 1.07]]]);+ backdrop(PC.peach);+ // sun-burst rays behind them, ticking round+ const rot = sm(lt) * 4;+ for (let i = 1; i < 18; i += 2) { const a = (i / 18 * 360 + rot) * D2R, a2 = ((i + .5) / 18 * 360 + rot) * D2R; piece(SH.poly([[0, 0], [Math.cos(a) * 1500, Math.sin(a) * 1500], [Math.cos(a2) * 1500, Math.sin(a2) * 1500]]), { x: 960, y: 560, col: PC.tangerine, depth: .3, seed: 3000 + i, edge: false, jit: 0 }); }+ piece(SH.circle(210), { x: 960, y: 560, col: PC.lemon, depth: .6, seed: 3100, jit: 0 }); piece(SH.circle(150), { x: 960, y: 560, col: PC.white, mat: 'card', depth: .4, seed: 3101, jit: 0 });+ const pm = moods(lt, [[0, 'happy'], [.55, 'laugh']]), lm = moods(lt, [[0, 'love'], [.7, 'laugh']]);+ const bounce = Math.abs(Math.sin(st * Math.PI * 2.2)) * -.15;+ pom(640, 1170, 92, { view: '3q', ...pm, dy: pm.dy + (st > .55 ? bounce : 0), armR: [120, 20], armL: [-40, 10], look: [.7, 0], tilt: -4 });+ lulu(1290, 1175, 60, { view: '3q', flip: true, ...lm, dy: lm.dy + (st > .7 ? bounce * .8 : 0), armR: [100, 40], armL: [-30, 10], holdR: { prop: 'apple', s: .85, dy: -.3 }, look: [.6, 0], tilt: 5 });+ confetti(lt, 960, 700, { t0: .6, n: 46, power: 1.1 });+ confetti(lt, 500, 800, { t0: .85, n: 20, seed: 2, spread: 70, power: .8 });+ camEnd();+ trFlip(t, seg(sm(lt), 0, .8));+ sheetOut(seg(sm(lt), dur - .6, dur), { col: PC.cream });+ }++ shots([[0, shotA], [4.25, shotB], [8.0, shotC]]);+ captionTrack([+ [.55, 2.0, '蘋果樹下', { style: 'letters', y: 150, size: 110 }],+ [8.8, 10.3, '一起分享吧!', { style: 'label', size: 76 }],+ ]);+})();diff --git a/.claude/skills/paper-cutout/template/studio.html b/.claude/skills/paper-cutout/template/studio.htmlnew file mode 100644index 0000000..119d91f--- /dev/null+++ b/.claude/skills/paper-cutout/template/studio.html@@ -0,0 +1,29 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>paper-cutout studio</title>+<style>+ html, body { margin: 0; background: #1b1820; color: #eee; font: 13px system-ui, sans-serif; }+ main { padding: 12px; display: grid; gap: 8px; }+ #out { width: min(100%, 1280px); aspect-ratio: 16 / 9; height: auto; background: #fff; }+ .bar { display: flex; gap: 10px; align-items: center; max-width: 1280px; }+ #scrub { flex: 1; } #tt { font-variant-numeric: tabular-nums; min-width: 190px; }+</style>+</head>+<body>+<main>+ <canvas id="out" width="1920" height="1080"></canvas>+ <div class="bar"><input id="scrub" type="range" min="0" max="10" step="0.0417" value="0"><span id="tt">loading…</span></div>+</main>+<!-- engine: config, shared kit, this engine's drawing library -->+<script src="src/config.js"></script>+<script src="src/kit.js"></script>+<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link href="https://fonts.googleapis.com/css2?family=Chiron+GoRound+TC:wght@700;900&family=Zen+Maru+Gothic:wght@700;900&family=Noto+Sans+TC:wght@700;900&display=block" rel="stylesheet">+<script src="src/cutout.js"></script>+<script src="src/cast.js"></script>+<!-- your video: one script per scene file, in order -->+<script src="src/scenes/demo.js"></script>+</body>+</html>diff --git a/.claude/skills/pixel-art/GUIDE.md b/.claude/skills/pixel-art/GUIDE.mdnew file mode 100644index 0000000..df219f9--- /dev/null+++ b/.claude/skills/pixel-art/GUIDE.md@@ -0,0 +1,254 @@+# Pixel-art engine — the full guide++Read this before drawing anything. It covers the look, the complete API with examples, the character system, the+review loop and the pitfalls. The animation principles and "reads" timing method from painted-animation's+`ANIMATION_GUIDE.md` apply unchanged (anticipation → action → follow-through, one read at a time, transitions at every+seam, nothing still); this guide covers what is specific to pixel art.++Model sheets: `docs/model-faces.png` (16 expressions × 2 characters), `docs/model-views.png` (views, walk frames,+jump keys, props in hands), `docs/kit-sheet.png` (palettes, emotes, weather, light), `docs/demo-sheet.jpg`.+Regenerate them with `node render.mjs --loop=faces|views|kit|wipes --stills=0.5 --out=out/sheets`.++---++## 1. The look++Modern indie pixel art, not 1985: a limited but rich palette, hue-shifted ramps, crisp selective outlines, dithered+skies and light, parallax depth, sprites animating on 12s while the camera glides.++- **Resolution:** 480×270 art pixels, ×4 nearest-neighbour to 1920×1080 (`ENGINE.crisp = true`). One art pixel =+ 4 screen px. Why not 384×216 ×5: faces need 2–3 px eyes and 3–5 px mouths, and two characters plus a tree and sky+ need room; at 480×270 a character is 40–65 px tall (160–260 screen px) and still reads as pixel art on a phone.+- **Palettes:** `PALS.day`, `PALS.dusk`, `PALS.night` (~30–36 colours each, organised as ramps, dark → light). Every+ palette has the same keys, so a scene can swap palettes and keep working:+ `ink paper rim sky cloud far mid grass earth stone wood light sun accent cool` (+ `charTint` = how characters are+ tinted to sit in the light: none by day, warm at dusk, blue at night).+- **Shading = walking a ramp.** `shade(c, -1)` is the next darker colour of c's ramp, `shade(c, +1)` the next lighter;+ past the ramp's end it hue-shifts (shadows toward blue-violet, lights toward warm). Outlines, inner lines, lights and+ shadows all use this, so everything stays on-palette. Register your own ramps with `regRamp(['#..', ...])`.+- **Selective outlines:** sprite passes add a 1-px outline in a darker hue of the adjacent fill, never flat black.+- **Dithering:** ordered 4×4 Bayer (`BAY4`) anchored to the layer, so patterns move with their layer and never swim.+ Use it for sky seams, glows, shadows, fades. Quantise densities (`qd(d)`) so dithers come in clean bands.+- **No anti-aliasing, no smooth gradients, no rotation of sprites, no non-integer scaling.** Rotation-like changes are+ new drawings (views, poses). Zoom only by integer punch-in.+- **Motion on steps:** sprite poses, walk frames, blinks, emotes, weather: 12 fps (`st(t)`), or 8/6/4 fps for slower+ things. Camera and positions are smooth but snapped to whole art pixels.++## 2. Frame structure++```js+(() => { // src/scenes/my_shot.js+ useText('你好!Hello!'); // every caption string, so its glyphs are loaded before rendering+ function shot(t, lt, dur) { // t = video time, lt = time in shot+ pal('dusk'); // palette FIRST (ENGINE.begin resets to day)+ const s = st(t); // 12 fps sprite time for poses+ camAt(lerp(240, 300, ease(seg(t, 0, 3))), 135); // world point at screen centre (snapped)+ sky(P.sky, { soft: .5 }); // back → front+ sunDisc(360, 180, 16, { par: .2 });+ clouds(t, { y: 60, par: .2 });+ hills(200, { c: P.far[0], rim: P.far[1], par: .3 });+ city(214, { c: P.mid[1], lit: .3, par: .45 });+ ground(x => 225, { tufts: .5 });+ footShadow(220, 225, 11);+ pip(220, 225, { ...act(s, [[0, 'happy'], [1.5, 'surprised']]), t: s, view: 'q' });+ if (lt > 2) punch(2, 230, 190); // medium shot (call before transitions)+ screenSpace();+ dissolve(1 - seg(lt, 0, .4)); // transitions last+ }+ shots([[0, shot]]);+ window.overlayHook = (c, t) => say(c, t, 1.0, 3.0, '你好!Hello!', { name: 'PIP' });+})();+```++A shot paints the whole frame. Order = back to front. There's no persistent state; everything is computed from `t`.++## 3. Coordinates, camera, layers++- World units are art pixels. `camAt(cx, cy)` puts world (cx, cy) at screen centre, rounded to whole pixels.+- `layer(f, fy = f)`: parallax factor for what follows (0 = glued to screen, 1 = world). Background helpers take a+ `par` option and restore `layer(1)` afterwards. Vertical parallax of hills/forests is `par * .6`.+- `screenSpace()`: screen pixels (HUD, transitions). `scr(x, y)` world → screen of the current layer.+- `shake(t, amt)` → `[dx, dy]` integer offsets on 12s; add to `camAt`.+- `punch(z, x, y)`: integer zoom (2 or 3) around a world point: the art pixels simply get bigger. Use it as a+ **medium shot** for acting; cut to it on an action or a take. `--crop-at` in render.mjs follows it.+- `clip(x, y, w, h)` / `noclip()`: world-rect clip for everything drawn.+- `measure(fn)`: runs a draw call with drawing disabled and returns its result — e.g. where a character's hand will+ be at another time: `const h = measure(() => juno(x, y, poseAt(3.8))).hands[1]`.++## 4. Primitives (world coords; `c` = '#hex' or u32; `d` = dither density 0..1, default solid)++| call | what |+|---|---|+| `fill(c)` | whole buffer |+| `px(x, y, c)` | one pixel |+| `rect(x, y, w, h, c, d)` | rectangle |+| `line(x0, y0, x1, y1, c, w)` | Bresenham line, `w` = round brush width |+| `pline(pts, c, w)` / `curve(pts, c, w)` | polyline / smooth curve through points (strings, tails, ropes) |+| `disc(cx, cy, r, c, d)` / `oval(cx, cy, rx, ry, c, d)` | filled circle (diameter 2r+1) / ellipse, pixel-centred |+| `ring(cx, cy, r, c, w)` | circle outline |+| `poly(pts, c, d)` | scanline polygon (vertices snapped) |+| `ball(cx, cy, rx, ry, c)` | 3-tone shaded ball (dark crescent bottom-right, highlight top-left) |+| `sprite(rows, map, x, y, { ax, ay, flip, z })` | sprite from a string grid; `'.'` transparent; anchor bottom-centre |+| `tile(kind, x, y)` / `tilemap(rows, legend, x0, y0)` | 16-px tiles generated from the palette: grass dirt brick plank water stone |+| `tinyText(s, x, y, c, { z, align, shadow })` | 3×5 in-world pixel font (A–Z 0–9 !?.-:/) for signs, scores, SFX |++```js+const HOUSE = ['..rrrr..', '.rrrrrr.', 'rrrrrrrr', '.wwwwww.', '.wddwgw.', '.wddwww.'];+sprite(HOUSE, { r: P.accent[1], w: P.paper, d: P.wood[1], g: P.light[1] }, 300, 200);+```++**Outlined sprite passes.** Anything that should look like a game object (props, trees, characters) is drawn inside a+sprite pass; the pass composites it with an automatic 1-px outline in a darker hue of each edge's fill:++```js+beginSpr(); // or outlined(() => { ... })+oval(100, 150, 8, 6, '#e24a5e');+part(); // new part: it gets an inner line where it overlaps earlier parts+rect(96, 146, 3, 3, '#fff8e8');+part(false); // new part without inner line (faces, highlights)+endSpr({ tint: null }); // opts: k (outline shade, −2), inner (−2), tint ['#hex', k] (default P.charTint), z, ax, ay, flash+```++## 5. Backgrounds (parallax, back → front)++| call | notes |+|---|---|+| `sky(stops, { soft, par, y0, y1 })` | banded vertical gradient with dithered seams; `stops` default `P.sky` |+| `sunDisc(x, y, r, { par, moon, halo, cols })` | sun/moon with banded dithered halo |+| `stars(t, { n, seed, par, y1 })` | twinkling on 6s, big ones cross-shaped |+| `clouds(t, { y, dy, n, par, speed, size, seed, cols })` | flat-bottomed puff clouds, 3 tones, drifting |+| `hills(base, { c, rim, amp, freq, seed, par, bumps, bumpW })` | rolling silhouette with lit rim; `bumps` = tree-canopy lumps |+| `forest(base, { c, rim, par, gap, hmin, hmax, seed })` | pine silhouettes |+| `city(base, { c, lit, win, par, hmin, hmax, seed })` | skyline; `lit` 0..1 fraction of lit windows (dusk/night) |+| `ground(topY(x), { c, tufts, flowers, deep, par })` | grassy ground following a height function; lit edge, tufts, dithered depth |+| `tree(x, y, { h, r, t, seed })` | big outlined leafy tree swaying on 4s; returns canopy |+| `bush(x, y, w, { berries })` | outlined bush |++Depth rules: farther = paler/bluer (`P.far`), smaller parallax, no outline; nearer = more contrast, outlines. Give+every silhouette a 1-px lit `rim` on the side of the light.++## 6. Light, weather, particles++- `glow(x, y, r, c, k, { bands })` — dithered radial light in banded rings (lamps, sun halos, magic).+- `light(x, y, r, k, { ry })` — brightens what's already drawn 1–2 steps along its own ramp (lamp pools, windows,+ spotlight). Best way to light a scene while staying on palette. `shadowAt(x, y, rx, ry, k)` does the reverse+ (contact shadows; `footShadow(x, y, w)` for characters). `vignette(k)` dithered darker corners.+- `rain(t, { n, slant, ground, par })` (streaks + splashes at `ground` y), `snow(t, { n })`,+ `sparkles(t, x, y, w, h, { n, c, c2 })` (4-point twinkles), `fireflies(t, x, y, w, h)`, `birds(t, { x, y, n })`,+ `petals(t)`, `puff(age, x, y, { n, c, spread })` dust on landings.+- `emote(kind, x, y, { age, bubble })` — RPG emote balloon that pops in over steps (burst → overshoot → settle), kinds:+ `! ? !? heart sweat anger dots note bulb star spiral zzz`. Characters draw their own via `emote`/`emoteAge`.++## 7. Transitions (after the shot is drawn; screen space; punch-aware)++| call | look |+|---|---|+| `dissolve(k, c)` | 8×8 Bayer dither fade to colour (k 0 → 1) |+| `iris(k, x, y, { shape: 'circle'|'diamond'|'square', c, edge })` | closes around a world point (k 0 open → 1 closed) |+| `diamonds(k, { dir: 'right'|'left'|'up'|'down'|'center', size, c })` | classic diamond-tile wipe |+| `blocks(k, { dir, size, stagger })` | chunky stair-stepped slide |+| `crossDither(k, drawA, drawB)` | dither dissolve between two full drawings |++Wipe out with `diamonds(seg(t, a, b), { dir: 'right' })` and in with `diamonds(1 - seg(t, b, c), { dir: 'left' })`, so+the motion continues across the cut.++## 8. Captions and text++Text lives on the overlay (full res) and is rasterised on a pixel grid: glyphs are drawn at native size on a tiny+canvas, alpha-thresholded, outlined by one pixel and scaled up ×2 nearest-neighbour. CJK runs use DotGothic16 at 24 px+(fallback Noto Sans TC, thresholded so it still reads as pixels); Latin runs use Press Start 2P at 16 px.++```js+useText('謝謝你!Thank you!PIP'); // at load time+window.overlayHook = (c, t) => {+ say(c, t, 7.35, 9.3, '謝謝你!Thank you!', { name: 'PIP', cps: 16 }); // RPG box, typewriter, blinking ▼+ // pxText(c, 'GAME OVER', 960, 200, { k: 3 }); // free pixel text+};+```++One line at a time, ≤ ~20 CJK characters. The box covers the bottom ~20 % of the frame while visible.++## 9. Characters (`src/cast.js`)++Two original characters, drawn procedurally in pixels each frame (no bitmaps):++- **Pip** — a round 40-px sprout-spirit: cream body, green two-leaf sprout, red knitted scarf with a fluttering tail,+ stubby feet, little nub arms, big 3×4 eyes, brows.+- **Juno** — a tall 65-px kid: navy bob with fringe and a springy cowlick, yellow A-line raincoat, navy trousers, red+ boots, two-segment arms (elbows), 2×4 eyes.++```js+const info = juno(x, y, { // (x, y) = ground point between the feet+ t: s, // time for blink / idle / tears (default: frame time)+ face: 'happy', // or spread act(...)+ view: 'front' | 'q' | 'side' | 'back', flip: false,+ look: [1, -1], // pupils: +x toward facing, −y up+ sq: 0, dx: 0, dy: 0, // squash (+) / stretch (−), offsets (px)+ arm: [a0, a1], bend: [b0, b1], // radians; 0 = straight out, + up, − down. front: [left, right]; side/q: [back, front]+ hold: [null, (hx, hy, ang) => PROP.kite(hx, hy - 9, { hang: true, t: s })],+ walk: phase, // 6-frame walk cycle (use walkTo)+ air: true, // tuck legs mid-jump+ drag: -1..1, wind: -1..1, // secondary motion: hair / sprout / scarf+ emote: 'heart', emoteAge: 0.4, emoteSide: 1,+ tint: ['#hex', k] | null, z: 1, flash: 0, seed: 0, blink: true,+});+// info = { head: [x,y], top: [x,y], hands: [[x,y], [x,y]], face: [x,y] }+```++- **Sizes:** Pip ≈ 40 px (27 wide), Juno ≈ 65 px. At 1× they suit wide shots; use `punch(2)` for acting.+- **Views:** front, q (3/4), side (profile), back — all face right; `flip` mirrors. Turns are view swaps on a step,+ ideally hidden under an action (landing, take).+- **Expressions (16):** neutral, happy, excited, laugh, love, shy, smug, sad, cry, angry, determined, surprised, scared,+ confused, thinking, sleepy. Each = eyes + mouth (+ brows, blush, tears, tint) + an idle motion + a default emote.+ Eye kinds: open shine sad angry half wide tiny happy closed sleepy squeeze heart dot (pairs allowed, e.g.+ `['open', 'half']`). Mouths: flat smile grin laugh O o frown wavy cat smug wail grit side pout. Add expressions to+ `EXPR`.+- **Acting:** `act(s, [[t0, 'sad'], [2.4, 'surprised', { look: [1, 0] }], [2.8, 'love']], { emoteFrom, take })` →+ squash + blink just before each change, face swap, a take (stretch + hop) settling with overshoot, emote pop. Key+ overrides: `take` (0 = no take), `emote` (null removes), `emoteHold`, any option like `look`.+- **Walking:** `walkTo(t, t0, t1, x0, x1, stride, easing)` → `{ x, walk, moving }`: phase = distance / stride, so feet+ don't slide. Use `view: 'side'`. Pass smooth `t` for x and `st(t)` for pose.+- **Jumping:** kit `jump(s, t0, t1, h)` → `{ dy, sq }` with anticipation squash, stretch and landing squash; add+ `air: true` mid-flight, `drag: clamp(-vel(u => jump(u, t0, t1, h).dy, s) / 120, -1, 1)` for hair follow-through,+ `puff(t - t1, x, y)` + `shake` on landing.+- **Holding props:** `hold: [back/left fn, front/right fn]`; the fn draws at the hand (world coords) inside the same+ sprite pass, so the prop gets the character's outline and the hand is drawn over its handle. Props:+ `PROP.kite(x, y, { s, tilt, tail, hang, t })`, `spool`, `lantern`, `flower(x, y, ang)`, `balloon`, `mug`, `letter`,+ `star`, `umbrella`. Anything not in a hand (a kite in the sky) is drawn separately; attach strings with+ `info.hands[i]` or `measure()`.+- **Arms:** `ARM.down −1.3, low −.7, out 0, up 1.25, high 1.45`. Chibi arms reach about head height: raise both arms in+ front view for "reach up" (hands beside the head). In side view an arm above ~0.6 rad crosses the face.+- **New characters:** copy `pip()` / `juno()` — a rig (`_rig`), a sprite pass, parts in back-to-front order (back arm,+ legs, body, head, face `part(false)`, front arm), a face config (eye / mouth / blush positions per view) handed to+ `_face`. Keep new colours in registered ramps (base at index 2 so the outline = index 0).++## 10. Review loop (do it for real)++```bash+node render.mjs --sheet=0.3,1.3,2.3,3.2,3.55,3.85 --cols=4 --w=480 --out=out/check/a.jpg # key frames+node render.mjs --strip=3.3:4.3 --cols=8 --w=240 --out=out/check/jump.jpg # every frame of an action+node render.mjs --sheet=4.6 --crop=780,380,700,560 --w=700 --out=out/check/face.jpg # full-res detail+node render.mjs --strip=3.3:4.3 --crop-at=610,160,700,700 --out=out/check/follow.jpg # follow a world point+```++Check, like an art director:+- **Pixel purity:** any blur, mixed pixel sizes inside one shot (other than a deliberate punch), stray anti-aliased+ edges, colours off-palette, flat-black outlines?+- **Read:** are the characters big enough (punch in for acting)? Does each read get its time? Emote bubbles not+ covering faces (`emoteSide`)?+- **Motion:** anticipation → action → follow-through visible in the strip? feet planted while walking? no pops when+ views/props swap (grab points computed with `measure`)?+- **Contacts:** props touching hands, strings attached, feet on the ground (`y = ground(x)`), contact shadows.+- **Transitions** at every seam and in/out of the film; caption box not hiding the action.++## 11. Known pitfalls++- Names: pixel.js/cast.js declare many short globals (`P C st px rect line disc poly sky ground tree …`). Wrap scene+ code in an IIFE and don't redeclare them.+- `pal()` must be called at the top of every shot (begin resets to `day`); `P.charTint` tints characters per palette.+- `punch()` and transitions operate on the low-res buffer at the end of the shot: call `punch` before transitions.+- A cached tile or text image depends on the palette/string, not on time: don't try to animate them via cache keys.+- `ball`/`oval`/`disc` centre on a pixel (odd sizes); for even sizes use `rect`/`poly`.+- Very long captions overflow the text canvas (~60 CJK chars); split them.+- Captions need network access for Google Fonts on first load (studio.html `<link>`); without it the fallback is a+ system font (still thresholded to pixels).diff --git a/.claude/skills/pixel-art/SKILL.md b/.claude/skills/pixel-art/SKILL.mdnew file mode 100644index 0000000..642cfbd--- /dev/null+++ b/.claude/skills/pixel-art/SKILL.md@@ -0,0 +1,69 @@+---+name: pixel-art+description: Make modern, polished pixel-art animated videos (MP4) with code — indie-game look (Celeste / Eastward / Stardew-level scenes, original), 480×270 art upscaled ×4 with nearest-neighbour, limited palettes (day / dusk / night) with Bayer dithering, parallax skies, hills, forests and towns, dithered light and weather, auto-outlined procedural pixel characters with 16 expressions, walk cycles, jumps and held props, emote bubbles, dither / diamond / iris / block transitions and crisp RPG dialogue-box captions (Latin + CJK). Canvas 2D in headless Chrome, encoded with ffmpeg. Use when a reference video or brief calls for pixel art, 8-bit / 16-bit, retro game, JRPG, cozy-game or 像素風 / 像素動畫 / 點陣 looks, or when the video-clone router picks the pixel-art style.+---++# Pixel art engine++Every frame is a pure function of `t`. Shots draw into a **480×270 software framebuffer** (world unit = one art+pixel), `ENGINE.end` upscales it ×4 to 1920×1080 with nearest-neighbour, and `window.overlayHook` draws crisp pixel+captions on top at full res. Same render contract and `render.mjs` CLI as painted-animation.++## Workflow++1. **Scaffold:** `bash .claude/skills/pixel-art/scripts/new_project.sh <project-dir> [--keep-demo]`, then **read+ `GUIDE.md` in full** (look rules, full API, character system, review loop). Look at `docs/model-faces.png`,+ `docs/model-views.png`, `docs/kit-sheet.png`, `docs/demo-sheet.jpg`.+2. **Storyboard** with reads per shot (as in painted-animation). Pick a palette per shot (`pal('day'|'dusk'|'night')`)+ and a colour arc.+3. **Build one file per shot** in `src/scenes/`, IIFE-wrapped, ending with `shots([[t0, fn], ...])`; add a `<script>` in+ `studio.html` (replace the demo). Scenes call only the library + cast; never redraw a character's body.+4. **Review every shot** (sheet, strips of every action and transition, crops of faces), fix, repeat:+ ```bash+ node render.mjs --sheet=0.5,1,1.5,2 --cols=4 --w=480 --out=out/check/a.jpg+ node render.mjs --strip=3.3:4.3 --cols=6 --w=320 --out=out/check/jump.jpg+ node render.mjs --sheet=4.5 --crop=780,380,700,560 --w=700 --out=out/check/face.jpg+ node render.mjs --loop=faces --stills=0.5 --out=out/sheets # model sheets: faces | views | kit | wipes+ ```+5. **Render:** `node render.mjs --frames --workers=4 && node render.mjs --encode --out=out/video.mp4 [--audio=...]`.++## API in one screen (details in GUIDE.md)++- Camera/layers: `camAt(cx, cy)` (snapped), `layer(f)` parallax, `screenSpace()`, `punch(2, x, y)` integer punch-in+ (medium shots), `shake(t, amt)`, `clip()/noclip()`, `measure(fn)` (dry-run a draw to get positions).+- Colour: `pal(name)` → `P` (ramps: `sky cloud far mid grass earth stone wood light sun accent cool`, `ink paper rim`),+ `shade(c, ±k)` walks the ramp (hue-shifted beyond it), `regRamp([...])`, `dith(x,y,d)`, `qd(d)`.+- Primitives: `px rect line(w) pline curve disc oval ring poly ball sprite(rows,map,x,y) tile tilemap tinyText`,+ all with optional dither density `d`. Outlines: `beginSpr(); part(); … endSpr({tint,z,flash})` or `outlined(fn)`.+- World: `sky sunDisc stars clouds hills forest city ground tree bush`; light: `glow light shadowAt vignette`;+ weather/fx: `rain snow sparkles fireflies birds petals puff`; `emote(kind, x, y, {age})`.+- Transitions (call last, screen space): `dissolve(k)`, `iris(k, x, y, {shape})`, `diamonds(k, {dir})`,+ `blocks(k, {dir})`, `crossDither(k, drawA, drawB)`.+- Captions (overlay): `say(c, t, t0, t1, text, { name })` RPG box + typewriter; `pxText(c, text, x, y)`;+ declare strings with `useText('…')` at load.+- Cast: `pip(x, y, o)` (round, 40 px), `juno(x, y, o)` (tall, 65 px); `o = { t, face, view, flip, look, sq, dy, arm,+ bend, hold, walk, air, drag, wind, emote, emoteAge, emoteSide, tint, z }` → `{ head, top, hands, face }`.+ `act(t, keys)` acted expression changes, `walkTo()` foot-planted walks, `st(t)` 12 fps sprite time, `vel(f, t)`,+ `PROP.kite/spool/lantern/flower/balloon/mug/letter/star/umbrella`, `ARM.down/low/out/up/high`, `footShadow()`.++## Rules that matter most++1. **Pixel discipline.** Everything goes through the library (it snaps to whole art pixels). Never draw with `G`/Canvas+ paths, never scale by non-integers, no anti-aliasing, no gradients except dithered ones, colours from `P`/`CR` ramps.+2. **Motion on steps:** poses, walk frames, blinks, weather use `st(t)` (12 fps); positions and camera may move every+ frame (snapped). Squash/stretch, jump anticipation, follow-through (`drag` via `vel`) as in any cartoon.+3. **Big enough to read:** wide shots at 1× for establishing; do the acting in **`punch(2)` medium shots** (characters+ ≈ half the frame height). Cut to a punch on an action or a take, never mid-stillness.+4. **Transitions at every seam** — dither dissolve in/out, diamond wipe, iris, blocks; wipe-in direction continues the+ wipe-out direction.+5. **Text only via the overlay caption box** (one line at a time, typewriter), or `tinyText` for in-world signs/SFX.++## Engine gotchas++- Don't declare globals that clash with kit.js or pixel.js names (`W H G P C st px rect line …`): wrap scenes in IIFEs.+- `act(...)` overrides use `'emote' in over`, so `{ emote: null }` removes an expression's default emote.+- Transitions/`punch` are post-effects on the low-res buffer: call `punch()` before transitions in the shot.+- Held props: draw via `hold: [fnBack, fnFront]` so they join the character outline; in side view an arm raised above+ ~0.6 rad crosses the face — do reaches in front view (hands go beside the head).+- The dialogue caption box sits over the bottom ~20 % of frame: keep feet/props above it while it's up.+- Speed: 3–40 ms/frame; a full 10 s demo renders in ~10 s with 4 workers.diff --git a/.claude/skills/pixel-art/docs/demo-sheet.jpg b/.claude/skills/pixel-art/docs/demo-sheet.jpgnew file mode 100644index 0000000..32f4609Binary files /dev/null and b/.claude/skills/pixel-art/docs/demo-sheet.jpg differdiff --git a/.claude/skills/pixel-art/docs/kit-sheet.png b/.claude/skills/pixel-art/docs/kit-sheet.pngnew file mode 100644index 0000000..385627dBinary files /dev/null and b/.claude/skills/pixel-art/docs/kit-sheet.png differdiff --git a/.claude/skills/pixel-art/docs/model-faces.png b/.claude/skills/pixel-art/docs/model-faces.pngnew file mode 100644index 0000000..e7fe878Binary files /dev/null and b/.claude/skills/pixel-art/docs/model-faces.png differdiff --git a/.claude/skills/pixel-art/docs/model-views.png b/.claude/skills/pixel-art/docs/model-views.pngnew file mode 100644index 0000000..1ce6581Binary files /dev/null and b/.claude/skills/pixel-art/docs/model-views.png differdiff --git a/.claude/skills/pixel-art/scripts/new_project.sh b/.claude/skills/pixel-art/scripts/new_project.shnew file mode 100644index 0000000..740cd15--- /dev/null+++ b/.claude/skills/pixel-art/scripts/new_project.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+# Scaffolds a project from this engine's template, installs deps and checks the toolchain.+# bash .claude/skills/<engine>/scripts/new_project.sh <project-dir> [--keep-demo]+set -e+SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"+TARGET="${1:?usage: new_project.sh <project-dir> [--keep-demo]}"+if [ -e "$TARGET/studio.html" ]; then echo "error: $TARGET already has a studio.html; not overwriting" >&2; exit 1; fi+mkdir -p "$TARGET"+if command -v rsync >/dev/null; then rsync -a --exclude node_modules --exclude out "$SKILL_DIR/template/" "$TARGET/"; else cp -R "$SKILL_DIR/template/." "$TARGET/"; rm -rf "$TARGET/node_modules" "$TARGET/out"; fi # Git Bash on Windows has no rsync+mkdir -p "$TARGET/assets" "$TARGET/out/check"+# The demo is an example, not a template: unless asked, unhook it so the new video starts clean.+if [ "${2:-}" != "--keep-demo" ]; then sed -i.bak 's#<script src="src/scenes/demo.js"></script>##' "$TARGET/studio.html" && rm -f "$TARGET/studio.html.bak"; fi+( cd "$TARGET" && npm install --silent --no-audit --no-fund )+echo "node $(node -v)"+command -v ffmpeg >/dev/null && echo "ffmpeg ok" || echo "MISSING: ffmpeg"+FOUND=+for c in "${CHROME_PATH:-}" "/c/Program Files/Google/Chrome/Application/chrome.exe" "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" /usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do+ [ -n "$c" ] && [ -x "$c" ] && { echo "chrome $c"; FOUND=1; break; }+done+[ "${FOUND:-}" = 1 ] || echo "MISSING: Chrome (install it, or pass --chrome=<path> to render.mjs)"+echo "== ready: $TARGET"diff --git a/.claude/skills/pixel-art/template/.gitignore b/.claude/skills/pixel-art/template/.gitignorenew file mode 100644index 0000000..9209ef5--- /dev/null+++ b/.claude/skills/pixel-art/template/.gitignore@@ -0,0 +1,2 @@+node_modules+outdiff --git a/.claude/skills/pixel-art/template/LICENSE-render.mjs.txt b/.claude/skills/pixel-art/template/LICENSE-render.mjs.txtnew file mode 100644index 0000000..1215a85--- /dev/null+++ b/.claude/skills/pixel-art/template/LICENSE-render.mjs.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 John Heibel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/.claude/skills/pixel-art/template/package-lock.json b/.claude/skills/pixel-art/template/package-lock.jsonnew file mode 100644index 0000000..0213263--- /dev/null+++ b/.claude/skills/pixel-art/template/package-lock.json@@ -0,0 +1,329 @@+{+ "name": "reelmimic-pixel-art",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "reelmimic-pixel-art",+ "license": "MIT",+ "dependencies": {+ "puppeteer-core": "^25.11.0"+ }+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.3.tgz",+ "integrity": "sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.4",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.4.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",+ "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^3.24.1"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1687809",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",+ "integrity": "sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.5",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.5.tgz",+ "integrity": "sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/puppeteer-core": {+ "version": "25.12.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.12.0.tgz",+ "integrity": "sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.3",+ "chromium-bidi": "17.0.2",+ "devtools-protocol": "0.0.1687809",+ "typed-query-selector": "^2.12.2",+ "webdriver-bidi-protocol": "0.4.3",+ "ws": "^8.21.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.3",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz",+ "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==",+ "license": "MIT"+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",+ "integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",+ "license": "Apache-2.0"+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.22.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.2.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",+ "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/.claude/skills/pixel-art/template/package.json b/.claude/skills/pixel-art/template/package.jsonnew file mode 100644index 0000000..3875ee2--- /dev/null+++ b/.claude/skills/pixel-art/template/package.json@@ -0,0 +1,6 @@+{+ "name": "reelmimic-pixel-art",+ "private": true,+ "license": "MIT",+ "dependencies": { "puppeteer-core": "^25.11.0" }+}diff --git a/.claude/skills/pixel-art/template/render.mjs b/.claude/skills/pixel-art/template/render.mjsnew file mode 100644index 0000000..9f7418a--- /dev/null+++ b/.claude/skills/pixel-art/template/render.mjs@@ -0,0 +1,161 @@+// render.mjs: renders studio.html in headless Chrome. Length and fps come from the page (PROJECT in src/config.js).+//+// Look at it (open the images with your image viewer / Read tool):+// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)+// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point+// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera+// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs+// Make the video:+// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --encode --out=out/video.mp4 out/frames → MP4+// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or+// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)+// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,+// --chrome=<path to Chrome/Chromium>.+import puppeteer from 'puppeteer-core';+import { spawn } from 'node:child_process';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { homedir } from 'node:os';++const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));+const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+ ...playwrightChromes()];+// Chromium builds Playwright downloaded (~/.cache/ms-playwright/chromium-NNNN), newest first+function playwrightChromes() {+ const dir = `${homedir()}/.cache/ms-playwright`;+ if (!existsSync(dir)) return [];+ return readdirSync(dir).filter(n => /^chromium-\d+$/.test(n)).sort((a, b) => b.split('-')[1] - a.split('-')[1])+ .map(n => `${dir}/${n}/chrome-linux64/chrome`);+}+const CHROME = CHROMES.find(p => p && existsSync(p));+if (!CHROME) { console.error('Chrome not found: pass --chrome=<path> or set CHROME_PATH'); process.exit(1); }+const fps = +(args.fps || 24), FRAMES_DIR = 'out/frames';+const run = (cmd, a) => new Promise((ok, bad) => { const p = spawn(cmd, a, { stdio: 'inherit' }); p.on('close', c => c ? bad(new Error(cmd + ' exited ' + c)) : ok()); });+const times = s => String(s).split(',').map(Number);+const span = s => String(s).split(':').map(Number);+// comma-separated fields, keeping commas inside parentheses ('PLK.MX(1.38),PLK.WL,500,300'); numbers stay numbers+const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of String(s)) { if (ch === ',' && !d) { out.push(cur); cur = ''; continue; } d += ch === '(' ? 1 : ch === ')' ? -1 : 0; cur += ch; } out.push(cur); return out.map(v => isNaN(+v) ? v : +v); };++// JPEG frames decode as full-range (yuvj420p); without this the MP4 is flagged full-range and some players/platforms+// show it washed out or with crushed shadows. Convert to standard (tv) range and say so.+const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];++if (args.encode) {+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,+ ...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);+ console.log('wrote ' + out);+ process.exit(0);+}++// --soft-gl: no GPU on this machine; render WebGL in software (SwiftShader), which Chrome only allows when asked.+// --gpu-angle=vulkan|gl-egl: headless Linux on an NVIDIA GPU (e.g. a cloud or cluster node); plain --use-gl=angle gets+// no WebGL context there. Check which GPU Chrome actually lands on with gpu_probe.mjs.+const ANGLE = { vulkan: ['--use-angle=vulkan', '--enable-features=Vulkan'], 'gl-egl': ['--use-angle=gl-egl'] };+if (args['gpu-angle'] && !ANGLE[args['gpu-angle']]) { console.error(`--gpu-angle must be one of ${Object.keys(ANGLE)}`); process.exit(1); }+const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ : args['gpu-angle'] ? ANGLE[args['gpu-angle']]+ : process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];+// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.+const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+const browser = await puppeteer.launch({+ executablePath: CHROME, headless: true, protocolTimeout: 0,+ args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']+});+async function openPage(tag = '') {+ const page = await browser.newPage();+ page.on('console', m => { if (['error', 'warn'].includes(m.type())) console.log(`[page${tag}]`, m.text()); });+ page.on('pageerror', e => console.log(`[page error${tag}]`, e.message));+ await page.goto(pathToFileURL(resolve('studio.html')).href + '?render', { waitUntil: 'networkidle0' });+ await page.waitForFunction('window.ready === true', { timeout: 60000 });+ if (args.loop) {+ const ok = await page.evaluate(name => { if (!LOOPS[name]) return false; window.LOOP = LOOPS[name]; return true; }, args.loop);+ if (!ok) { console.error(`no loop named "${args.loop}"`); process.exit(1); }+ }+ return page;+}+const frameOf = async (page, t, type, q) => {+ const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);+ return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');+};+// the length of whatever is being rendered: a loop's .len, or the video's duration+const lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);++if (args.sheet || args.strip) {+ const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });+ let ts;+ if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ else ts = times(args.sheet);+ const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;+ const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);+ writeFileSync(out, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));+ console.log(`${out} (${ts.length} frames) ms/frame: ${ms.join(' ')}`);+} else if (args.stills) {+ const page = await openPage(), out = args.out || 'out/stills'; mkdirSync(out, { recursive: true });+ console.log('GPU:', await page.evaluate(() => window.gpuInfo()));+ for (const s of times(args.stills)) {+ const t0 = Date.now(), buf = await frameOf(page, s, 'image/png');+ const f = `${out}/t${s.toFixed(2).replace('.', '_')}.png`; writeFileSync(f, buf);+ console.log(`${f} ${Date.now() - t0} ms`);+ }+} else if (args.png) {+ // PNG sequence (for GIFs): a loop's full cycle (frame n equals frame 0, so it isn't rendered), or --range=a:b.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], n = Math.round((b - a) * fps);+ const out = args.out || `out/${args.loop ? 'loop_' + args.loop : 'png'}`, workers = +(args.workers || 3); mkdirSync(out, { recursive: true });+ let next = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < n) { const i = next++; writeFileSync(`${out}/f${String(i).padStart(4, '0')}.png`, await frameOf(page, a + i / fps, 'image/png')); }+ }));+ console.log(`${n} frames → ${out} (${((Date.now() - start) / n).toFixed(0)} ms/frame)`);+} else if (args.frames) {+ // Parallel and resumable: each worker pulls the next missing frame; files are written atomically.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);+ mkdirSync(FRAMES_DIR, { recursive: true });+ const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);+ const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }+ console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ let next = 0, done = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < todo.length) {+ const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;+ const buf = await frameOf(page, i / fps, 'image/jpeg', .94);+ writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ if (++done % 24 === 0 || done === todo.length) {+ const el = (Date.now() - start) / 1000;+ console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);+ }+ }+ }));+} else if (args.clip) {+ const page = await openPage(), len = await lengthOf(page);+ const [a, b] = args.range ? span(args.range) : typeof args.clip === 'string' ? span(args.clip) : [0, len];+ const audio = args.audio || await page.evaluate(() => PROJECT.audio || '');+ const out = args.out || 'out/clip.mp4'; mkdirSync(dirname(out), { recursive: true });+ const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',+ ...(audio ? ['-ss', String(a), '-t', String(b - a), '-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', ...TV_RANGE, '-movflags', '+faststart', out],+ { stdio: ['pipe', 'inherit', 'inherit'] });+ const n = Math.round((b - a) * fps), start = Date.now();+ for (let i = 0; i < n; i++) {+ const buf = await frameOf(page, a + i / fps, 'image/jpeg', .93);+ if (!ff.stdin.write(buf)) await new Promise(r => ff.stdin.once('drain', r));+ if (i % 24 === 0 || i === n - 1) console.log(`frame ${i + 1}/${n} ${((Date.now() - start) / (i + 1)).toFixed(0)} ms/frame`);+ }+ ff.stdin.end(); await new Promise(r => ff.on('close', r));+ console.log(`wrote ${out}`);+} else {+ console.log('nothing to do: see the usage notes at the top of render.mjs');+}+await browser.close();diff --git a/.claude/skills/pixel-art/template/src/cast.js b/.claude/skills/pixel-art/template/src/cast.jsnew file mode 100644index 0000000..335f26b--- /dev/null+++ b/.claude/skills/pixel-art/template/src/cast.js@@ -0,0 +1,335 @@+// cast.js: the pixel-art character system. Two original demo characters drawn procedurally in pixels (no bitmaps):+// pip(x, y, o) a round, 40-px sprout-spirit in a red scarf (small, bouncy, big eyes)+// juno(x, y, o) a tall, 65-px kid in a yellow raincoat with a navy bob and a springy cowlick+// (x, y) = the ground point between the feet, in world px. One call draws the whole character as one outlined sprite+// (limbs are parts of the same sprite, so they always connect). Options (all optional):+// t time (default: the frame time) — drives blinks, idles, tears+// face expression name (EXPR below) or use act(t, keys) to act changes+// view 'front' | 'q' (3/4) | 'side' | 'back' flip: true → faces left+// look [lx, ly] pupils −1..1 (lx + = toward facing) blink: false to disable auto-blink; seed: blink phase+// sq squash (+) / stretch (−) dx, dy: offsets in px (dy − = up)+// arm [a0, a1] arm angles in radians: 0 = straight out, + up, − down (ARM.down ≈ −1.3). In 'side'/'q' view+// a0 = back arm, a1 = front arm, both measured toward the facing side. bend: [b0, b1] elbow (juno only)+// hold [fn0, fn1] draw a prop in that hand: fn(hx, hy, ang) in world px, ang = forearm direction (radians)+// walk walk phase (cycles per stride; use walkTo()) → 6-frame walk cycle air: true → legs tucked (jumps)+// drag −1..1 secondary motion for hair/sprout/scarf (use vel() of your motion) wind: −1..1 scarf/hair blow+// emote emote kind + emoteAge (s since it popped); emoteSide ±1 (default: facing side)+// tint: ['#hex', k] mood tint z: integer scale (close-up)+// Returns { head, top, hands: [[x,y],[x,y]], face } in world px for attaching strings, emotes and props.++const CR = {+ skin: regRamp(['#5a2a33', '#a4524a', '#e3906e', '#f6c29a', '#ffe4c8']),+ hair: regRamp(['#141329', '#22224a', '#34386c', '#56609c']),+ coat: regRamp(['#6a3420', '#b86420', '#f0a02e', '#ffd05a', '#fff0a0']),+ pants: regRamp(['#141a2c', '#24304e', '#3a4c76']),+ boot: regRamp(['#40121e', '#842634', '#c43e48', '#ea766c']),+ body: regRamp(['#5c3a3c', '#a86e5a', '#e8b48c', '#f8dcb4', '#fff4e2']),+ leaf: regRamp(['#1a4428', '#2c7438', '#4eaa46', '#96d666']),+ scarf: regRamp(['#4e1628', '#9e2638', '#dc4448', '#ff8262']),+ feet: regRamp(['#351f22', '#65382f', '#935641', '#bf7a58']),+ eye: '#231a33', white: '#fffaf0', blush: '#f27c84', tear: '#6cc4f4', mouth: '#5a1f2e', inside: '#9e2a3a', tongue: '#f07a84',+};+regRamp([CR.eye, '#3a2e52']); regRamp([CR.mouth, '#8a3040']);+const ARM = { down: -1.3, low: -.7, out: 0, up: 1.25, high: 1.45 };++// ---------- expressions ----------+const EXPR = {+ neutral: { eyes: 'open', mouth: 'flat' },+ happy: { eyes: 'open', mouth: 'smile', blush: 1, idle: 'bounce' },+ excited: { eyes: 'shine', mouth: 'grin', blush: 1, idle: 'hop', emote: '!' },+ laugh: { eyes: 'squeeze', mouth: 'laugh', blush: 2, idle: 'laugh', emote: 'note' },+ love: { eyes: 'heart', mouth: 'smile', blush: 2, idle: 'sway', emote: 'heart' },+ shy: { eyes: 'happy', mouth: 'pout', blush: 2, idle: 'sway', emote: 'sweat' },+ smug: { eyes: 'half', mouth: 'smug', blush: 1, idle: 'sway' },+ sad: { eyes: 'sad', mouth: 'frown', brows: 'sad', idle: 'droop', emote: 'dots' },+ cry: { eyes: 'squeeze', mouth: 'wail', brows: 'sad', tears: 1, idle: 'sob', emote: 'sweat' },+ angry: { eyes: 'angry', mouth: 'grit', brows: 'angry', tint: ['#ff3a2a', .1], idle: 'shake', emote: 'anger' },+ determined: { eyes: 'half', mouth: 'flat', brows: 'angry', idle: 'still', emote: 'star' },+ surprised: { eyes: 'wide', mouth: 'O', brows: 'up', idle: 'still', emote: '!' },+ scared: { eyes: 'tiny', mouth: 'wavy', brows: 'sad', tint: ['#7088d0', .12], idle: 'shiver', emote: 'sweat' },+ confused: { eyes: ['open', 'half'], mouth: 'wavy', idle: 'still', emote: '?' },+ thinking: { eyes: 'open', look: [1, -1], mouth: 'side', idle: 'still', emote: '?' },+ sleepy: { eyes: 'sleepy', mouth: 'o', idle: 'breathe', emote: 'zzz' },+};+const EXPR_NAMES = Object.keys(EXPR);++function _idle(kind, t, seed = 0) {+ const s = st(t), b = bpOf(s);+ switch (kind) {+ case 'bounce': return { dy: frac(b) < .3 ? -1 : 0 };+ case 'hop': { const k = frac(b); return { dy: -Math.round(Math.max(0, Math.sin(k * Math.PI)) * 3), sq: k < .12 ? .08 : 0 }; }+ case 'laugh': return { dy: Math.floor(s * 8 + seed) % 2 ? -1 : 0, sq: Math.floor(s * 8 + seed) % 2 ? -.03 : .03 };+ case 'sway': return { dx: Math.round(Math.sin(s * 2.4 + seed)), dy: 0 };+ case 'droop': return { dy: Math.sin(s * 1.6 + seed) > .2 ? 1 : 0, sq: .03 };+ case 'sob': return { dy: Math.floor(s * 5) % 2, sq: Math.floor(s * 5) % 2 ? .05 : 0 };+ case 'shake': return { dx: [0, 1, 0, -1][Math.floor(s * 12) % 4] };+ case 'shiver': return { dx: Math.floor(s * 12) % 3 === 0 ? 1 : 0 };+ case 'breathe': return { sq: Math.sin(s * 1.8 + seed) * .03 };+ default: return {};+ }+}+const _blinking = (t, seed = 0) => { const per = 2.6 + hash(seed * 7.1 + 1) * 1.6, a = (st(t) + hash(seed) * per) % per; return a < .12; };++// act(t, keys, o): an acted emotion timeline, keys = [[t0, 'face', { overrides }], ...]. Around each change: a+// squash + blink frame just before (anticipation), the face swaps, a take (stretch + hop) settles with overshoot,+// and the expression's emote pops (emoteHold s, default 1.5). Returns options to spread into pip()/juno().+function act(t, keys, o = {}) {+ let i = 0; while (i + 1 < keys.length && t >= keys[i + 1][0]) i++;+ const [t0, face, over = {}] = keys[i], ex = EXPR[face] || {}, s = st(t), out = { face, sq: 0, dy: 0 };+ const nx = keys[i + 1]; if (nx && s > nx[0] - .1) { out.sq += .1; out.blinkNow = true; }+ const a = s - t0, amt = (over.take ?? o.take ?? 1) * (i > 0 || t0 > 0 ? 1 : 0);+ if (a >= 0 && amt) { out.sq += -.16 * amt * Math.exp(-7 * a) * Math.cos(17 * a); out.dy += -Math.round(3 * amt * Math.exp(-8 * a) * Math.max(0, Math.cos(9 * a))); }+ const em = 'emote' in over ? over.emote : ex.emote, hold = over.emoteHold ?? o.emoteHold ?? 1.5;+ if (em && a < hold && i >= (o.emoteFrom ?? 0)) { out.emote = em; out.emoteAge = a; }+ const { take, emote, emoteHold, ...rest } = over; return { ...out, ...rest };+}+// walkTo(t, t0, t1, x0, x1, stride): position + walk phase that plants the feet (no sliding); e = easing+function walkTo(t, t0, t1, x0, x1, stride = 20, e = x => x) {+ const k = e(seg(t, t0, t1)), x = lerp(x0, x1, k), moving = t > t0 && t < t1;+ return { x, walk: moving ? Math.abs(x - x0) / stride : null, moving, dir: Math.sign(x1 - x0) };+}++// ---------- shared rig & face ----------+function _rig(x, y, o) {+ const fl = o.flip ? -1 : 1, sq = o.sq || 0, sx = 1 + (sq > 0 ? sq * .7 : sq * .45), sy = 1 - sq;+ const X0 = Math.round(x + (o.dx || 0)), Y0 = Math.round(y + (o.dy || 0));+ const L = (lx, ly) => [X0 + fl * lx * sx, Y0 + ly * sy];+ const Lp = pts => pts.map(([a, b]) => L(a, b));+ return { fl, sx, sy, X0, Y0, L, Lp };+}+// mirrored pixel at local offset from a snapped origin (face features keep their exact pixel shape)+function _fp(R, ox, oy, i, j, c) { px(ox + R.fl * i, oy + j, c); }+function _eye(R, kind, lx, ly, ew, eh, side, look, t) {+ const [ox, oy] = R.L(lx, ly).map(Math.round), E = CR.eye, Wc = CR.white;+ const P_ = (i, j, c) => _fp(R, ox, oy, i, j, c), inner = side < 0 ? ew - 1 : 0, outer = side < 0 ? 0 : ew - 1;+ const lkx = Math.round(clamp(look[0], -1, 1)), lky = Math.round(clamp(look[1], -1, 1));+ switch (kind) {+ case 'open': case 'shine': case 'sad': case 'angry': case 'half': {+ for (let j = 0; j < eh; j++) for (let i = 0; i < ew; i++) {+ if (kind === 'sad' && j === 0 && i === outer) continue;+ if (kind === 'angry' && j === 0 && i === inner) continue;+ if (kind === 'half' && j === 0) continue;+ P_(i + lkx, j + lky, E);+ }+ if (kind === 'half') for (let i = -1; i <= ew; i++) P_(i + lkx, 1 + lky, E);+ else { P_(lkx + (ew > 2 ? 0 : 0), lky + (kind === 'sad' || kind === 'angry' ? 1 : 0), Wc); if (kind === 'shine' || ew > 2) P_(lkx + ew - 1, lky + eh - 1, kind === 'shine' ? Wc : '#4a3e66'); }+ break;+ }+ case 'wide': case 'tiny': {+ for (let j = -1; j <= eh; j++) for (let i = -1; i <= ew; i++) { const edge = j === -1 || j === eh || i === -1 || i === ew; if (edge && (i === -1 || i === ew) && (j === -1 || j === eh)) continue; P_(i, j, edge ? E : Wc); }+ const jx = kind === 'tiny' ? (Math.floor(st(t) * 12) % 2) : 0, cx = Math.floor((ew - 1) / 2) + lkx + jx, cy = Math.floor((eh - 1) / 2) + lky;+ P_(clamp(cx, 0, ew - 1), clamp(cy, 0, eh - 1), E); if (kind === 'wide') P_(clamp(cx, 0, ew - 1), clamp(cy + 1, 0, eh - 1), E);+ break;+ }+ case 'happy': { // ∩ arcs+ const a = ew > 2 ? 0 : -1, b = ew > 2 ? ew - 1 : ew;+ for (let i = a + 1; i < b; i++) P_(i, 1, E); P_(a, 2, E); P_(b, 2, E); P_(a, 3, E); P_(b, 3, E); break;+ }+ case 'closed': for (let i = -1; i <= ew; i++) P_(i, 2, E); P_(side < 0 ? -1 : ew, 1, E); break;+ case 'sleepy': for (let i = -1; i <= ew; i++) P_(i, 2, E); for (let i = 0; i < ew; i++) P_(i, 3, E); break;+ case 'squeeze': { const pts = side < 0 ? [[0, 0], [1, 1], [2, 2], [1, 3], [0, 4]] : [[2, 0], [1, 1], [0, 2], [1, 3], [2, 4]]; const o2 = ew > 2 ? 0 : -.5; for (const [i, j] of pts) P_(Math.round(i + o2 - (side < 0 ? 0 : 0)), j - 1, E); break; }+ case 'heart': { const H_ = ['rr.rr', 'rrrrr', '.rrr.', '..r..']; const x0 = Math.floor(ew / 2) - 2; H_.forEach((l, j) => { for (let i = 0; i < 5; i++) if (l[i] === 'r') P_(x0 + i, j, i === 1 && j === 1 ? '#ffb0c0' : '#e8485c'); }); break; }+ case 'dot': P_(Math.floor(ew / 2), 1, E); P_(Math.floor(ew / 2), 2, E); break;+ }+}+const MOUTHS = {+ flat: ['kkk'], smile: ['k...k', '.kkk.'], grin: ['kkkkk', 'krrrk', '.kkk.'], laugh: ['kkkkk', 'krrrk', 'krttk', '.kkk.'],+ O: ['.kk.', 'krrk', 'krrk', '.kk.'], o: ['.k.', 'k.k', '.k.'], frown: ['.kkk.', 'k...k'], wavy: ['.k.k.', 'k.k.k'],+ cat: ['k.k.k', '.k.k.'], smug: ['....k', 'kkkk.'], wail: ['.kkk.', 'krrrk', 'krttk', 'kkkkk'], grit: ['kkkkk', 'kwkwk', 'kkkkk'],+ side: ['..kk', '.k..'], pout: ['.k.', 'k.k'],+};+function _mouth(R, kind, lx, ly) {+ const g = MOUTHS[kind]; if (!g) return; const [ox, oy] = R.L(lx, ly).map(Math.round), w = g[0].length, x0 = -Math.floor(w / 2);+ const cm = { k: CR.mouth, r: CR.inside, t: CR.tongue, w: CR.white };+ g.forEach((l, j) => { for (let i = 0; i < w; i++) if (cm[l[i]]) _fp(R, ox, oy, x0 + i, j, cm[l[i]]); });+}+function _brows(R, kind, lx, ly, ew, side, col) {+ if (!kind) return; const [ox, oy] = R.L(lx, ly).map(Math.round), inner = side < 0 ? ew - 1 : 0, outer = side < 0 ? 0 : ew - 1, di = side < 0 ? 1 : -1;+ if (kind === 'sad') { _fp(R, ox, oy, inner, -3, col); _fp(R, ox, oy, inner - di, -2, col); _fp(R, ox, oy, outer - di * 0, -2, col); }+ if (kind === 'angry') { _fp(R, ox, oy, inner + di, -1, col); _fp(R, ox, oy, inner, -2, col); _fp(R, ox, oy, outer, -3, col); }+ if (kind === 'up') { for (let i = 0; i < ew; i++) _fp(R, ox, oy, i, -4, col); }+}+// face(R, f, spec): f = { eyes: [[lx,ly],[lx,ly]|null], ew, eh, mouth: [lx,ly], blush: [[lx,ly],[lx,ly]], brow col }+function _face(R, f, ex, o, t) {+ const blink = o.blinkNow || (o.blink !== false && _blinking(t, o.seed || 0)), look = o.look || ex.look || [0, 0];+ const kinds = Array.isArray(ex.eyes) ? ex.eyes : [ex.eyes, ex.eyes];+ if ((ex.blush || o.blush) && f.blush) { const n = o.blush ?? ex.blush; for (const [bx, by] of f.blush) { if (!bx && bx !== 0) continue; const [ox, oy] = R.L(bx, by).map(Math.round); _fp(R, ox, oy, 0, 0, CR.blush); _fp(R, ox, oy, 1, 0, CR.blush); if (n > 1) { _fp(R, ox, oy, -1, 0, CR.blush); _fp(R, ox, oy, 2, 0, CR.blush); _fp(R, ox, oy, 0, 1, CR.blush); _fp(R, ox, oy, 1, 1, CR.blush); } } }+ f.eyes.forEach((e, i) => {+ if (!e) return; const side = i === 0 ? -1 : 1; let k = kinds[i] || 'open';+ if (blink && ['open', 'shine', 'sad', 'angry', 'half', 'wide', 'tiny'].includes(k)) k = 'closed';+ _eye(R, k, e[0], e[1], f.ew - (e[2] || 0), f.eh, side, look, t);+ if (f.browCol) _brows(R, ex.brows, e[0], e[1] + (ex.brows === 'up' ? 0 : 0), f.ew - (e[2] || 0), side, f.browCol);+ if (ex.tears) { const [ox, oy] = R.L(e[0], e[1]).map(Math.round), s = st(t), n = 2 + (Math.floor(s * 12) % 4); const tx = side < 0 ? 0 : f.ew - 1; for (let j = 0; j < n; j++) _fp(R, ox, oy, tx, 3 + j, CR.tear); if (Math.floor(s * 12) % 4 === 3) _fp(R, ox, oy, tx + side, 5 + n, CR.tear); }+ });+ if (f.mouth) _mouth(R, o.mouth || ex.mouth, f.mouth[0], f.mouth[1]);+}+// arm: shoulder (local) → elbow → hand; w px thick. Returns [hx, hy] world.+function _arm(R, sh, a, len1, len2, bend, w, col, hand, holdFn, outward) {+ const [sx, sy] = R.L(sh[0], sh[1]), d = outward * R.fl;+ const ex = sx + Math.cos(a) * len1 * d * R.sx, ey = sy - Math.sin(a) * len1 * R.sy, a2 = a + bend;+ const hx = ex + Math.cos(a2) * len2 * d * R.sx, hy = ey - Math.sin(a2) * len2 * R.sy;+ line(sx, sy, ex, ey, col, w); if (len2) line(ex, ey, hx, hy, col, w);+ const ang = Math.atan2(hy - ey, hx - ex || (len2 ? 1e-6 : Math.cos(a) * d));+ if (holdFn) { part(); holdFn(hx, hy, len2 ? ang : Math.atan2(-Math.sin(a), Math.cos(a) * d)); part(); }+ disc(hx, hy, 1, hand);+ return [Math.round(hx), Math.round(hy)];+}+function _legGait(o, view) {+ if (o.walk == null) return null; const f = Math.floor(frac(o.walk) * 6) / 6, a = f * TAU;+ return { a, fA: Math.sin(a), fB: -Math.sin(a), lA: Math.max(0, Math.cos(a)), lB: Math.max(0, -Math.cos(a)), bob: -Math.round(Math.abs(Math.cos(a))), swing: Math.sin(a) };+}+function _mood(o, t) { const ex = EXPR[o.face || 'neutral'] || EXPR.neutral, id = _idle(ex.idle, t, o.seed || 0); return { ex, id }; }++// ---------- JUNO: tall raincoat kid (≈65 px incl. cowlick) ----------+function juno(x, y, o = {}) {+ const t = o.t ?? T, { ex, id } = _mood(o, t), view = o.view || 'front', g = _legGait(o, view);+ const R = _rig(x, y, { ...o, dx: (o.dx || 0) + (id.dx || 0), dy: (o.dy || 0) + (id.dy || 0) + (g ? g.bob : 0), sq: (o.sq || 0) + (id.sq || 0) });+ const side = view === 'side', q = view === 'q', back = view === 'back', front = view === 'front';+ const fsh = side ? 3 : q ? 1 : 0, arm = o.arm || [ARM.down, ARM.down], bend = o.bend || [.25, .25], drag = clamp(o.drag || 0, -1, 1), wind = o.wind || 0;+ const hands = [];+ const sw = g ? g.swing * .32 : 0;+ beginSpr();+ // back arm (side / q views): darker, behind the body+ if (side || q) { hands[0] = _arm(R, [side ? -1 : -5, -37], arm[0] - sw, 8, 7, bend[0], 3, CR.coat[1], CR.skin[2], o.hold && o.hold[0], 1); part(); }+ // legs + boots+ const air = o.air ? 1 : 0;+ const legs = side || q ? [[-1 + (q ? -2 : 0), g ? g.fB * 5 : -2, g ? g.lB * 3 : 0, true], [1 + (q ? 2 : 0), g ? g.fA * 5 : 3, g ? g.lA * 3 : 0, false]]+ : [[-3, -4, g ? Math.max(0, g.fA) * 2 : 0, false], [3, 4, g ? Math.max(0, g.fB) * 2 : 0, false]];+ for (const [hx, fx0, lift, far] of legs) {+ const fx = fx0 + (air ? (side ? 2 : 0) : 0), fy = -lift - air * 4;+ const pc = far ? CR.pants[0] : CR.pants[1], bc = far ? CR.boot[1] : CR.boot[2];+ const [kx, ky] = R.L((hx + fx) / 2 + (air ? 3 : 0) * (side || q ? 1 : 0), -12 - air * 3);+ line(...R.L(hx, -20), kx, ky, pc, 3); line(kx, ky, ...R.L(fx, fy - 4), pc, 3);+ if (side || q) poly(R.Lp([[fx - 2, fy - 5], [fx + 2, fy - 5], [fx + 2, fy - 3], [fx + 4, fy - 2], [fx + 4, fy], [fx - 2, fy]]), bc);+ else poly(R.Lp([[fx - 2, fy - 5], [fx + 2, fy - 5], [fx + 3, fy - 1], [fx + 2, fy + 0], [fx - 3, fy], [fx - 3, fy - 1]]), bc);+ part();+ }+ // raincoat+ const cw = side ? .78 : q ? .9 : 1;+ poly(R.Lp([[-5 * cw, -39], [5 * cw, -39], [7 * cw, -33], [9 * cw, -22], [10 * cw, -18], [-10 * cw, -18], [-9 * cw, -22], [-7 * cw, -33]]), CR.coat[2]);+ poly(R.Lp([[(side ? -1 : 3) * cw, -39], [5 * cw, -39], [7 * cw, -33], [9 * cw, -22], [10 * cw, -18], [(side ? 0 : 5) * cw, -18]]), CR.coat[1]);+ line(...R.L(-9 * cw, -19), ...R.L(9 * cw, -19), CR.coat[1]);+ line(...R.L(-6 * cw, -36), ...R.L(-8 * cw, -24), CR.coat[3]);+ if (front || q) { const zx = q ? 2 : 0; line(...R.L(zx, -38), ...R.L(zx, -20), CR.coat[1]); px(...R.L(zx - 2, -34), CR.coat[0]); px(...R.L(zx - 2, -29), CR.coat[0]); rect(...R.L(-7 + zx, -26), 3, 1, CR.coat[1]); }+ else { line(...R.L(4, -38), ...R.L(6, -20), CR.coat[1]); oval(...R.L(-4, -39), 3, 2, CR.coat[2]); }+ part();+ // head: neck, hair mass, face, bangs, cowlick+ const hx = side ? 1 : q ? .5 : 0;+ rect(...R.L(-1, -42), 3, 3, CR.skin[1]);+ oval(...R.L(hx - (side ? 2 : q ? 1 : 0), -51), 11 * R.sx, 10 * R.sy, CR.hair[1]);+ poly(R.Lp([[hx - 11 - (side ? 1 : 0), -51], [hx + (side ? 6 : 11), -51], [hx + (side ? 6 : 11), -44], [hx + (side ? 5 : 9), -41], [hx - (side ? 10 : 9), -41], [hx - 11 - (side ? 1 : 0), -44]]), CR.hair[1]);+ if (!back) {+ const fcx = side ? 3 : q ? 1.5 : 0;+ part(); oval(...R.L(fcx, -48), (side ? 7 : 8) * R.sx, 7.5 * R.sy, CR.skin[2]);+ if (side) px(...R.L(11, -47), CR.skin[2]);+ oval(...R.L(fcx - (side ? 2 : 3), -45), 2, 1, CR.skin[2]);+ part();+ const B = side ? [[-6, -56], [-1, -60], [6, -59], [10, -55], [10, -52], [8, -53], [6, -51], [4, -53], [1, -51], [-2, -52], [-6, -48]]+ : [[-9, -54], [-6, -58], [0, -60], [6, -58], [9, -54], [9, -50], [7, -52], [6, -50], [4, -52], [2, -51], [0, -53], [-2, -51], [-4, -52], [-6, -50], [-7, -52], [-9, -50]];+ poly(R.Lp(B.map(([a, b]) => [a + (q ? 1 : 0), b])), CR.hair[1]);+ } else part();+ // hair shine + cowlick (springs with drag)+ line(...R.L(hx - 7, -56), ...R.L(hx - 3, -59), CR.hair[2]); px(...R.L(hx - 1, -59), CR.hair[3]);+ const dg = Math.round(drag * 3), wd = Math.round(wind * 2);+ pline(R.Lp([[hx + 1, -60], [hx + 2 + wd, -63 + dg], [hx + 5 + wd, -65 + dg * 1.5], [hx + 7 + wd, -63 + dg * 1.5]]), CR.hair[1], 2);+ part(false);+ if (!back) {+ const f = side ? { eyes: [null, [6, -49]], mouth: [9, -44], blush: [[5, -45]] }+ : q ? { eyes: [[-3, -49, 0], [5, -49]], mouth: [3, -44], blush: [[-5, -45], [7, -45]] }+ : { eyes: [[-5, -49], [4, -49]], mouth: [0, -44], blush: [[-8, -45], [6, -45]] };+ _face(R, { ...f, ew: 2, eh: 4, browCol: null }, ex, o, t);+ }+ // front arm(s)+ part();+ if (front || back) {+ hands[0] = _arm(R, [-6, -37], arm[0], 8, 7, bend[0], 3, CR.coat[2], CR.skin[3], o.hold && o.hold[0], -1); part();+ hands[1] = _arm(R, [6, -37], arm[1], 8, 7, bend[1], 3, CR.coat[2], CR.skin[3], o.hold && o.hold[1], 1);+ } else hands[1] = _arm(R, [side ? 1 : 4, -37], arm[1] + sw, 8, 7, bend[1], 3, CR.coat[2], CR.skin[3], o.hold && o.hold[1], 1);+ const tint = ex.tint || o.tint;+ endSpr({ tint: tint === undefined ? P.charTint : tint, z: o.z, ax: R.X0, ay: R.Y0, flash: o.flash });+ const top = R.L(hx, -64), info = { head: R.L(0, -50), top, hands, face: R.L(side ? 5 : 0, -47) };+ if (o.emote) emote(o.emote, (o.emoteSide ?? R.fl) > 0 ? top[0] + 4 : top[0] - 18, top[1] - 1, { age: o.emoteAge ?? 1 });+ return info;+}++// ---------- PIP: round sprout-spirit (≈40 px incl. sprout) ----------+function pip(x, y, o = {}) {+ const t = o.t ?? T, { ex, id } = _mood(o, t), view = o.view || 'front', g = _legGait(o, view);+ const R = _rig(x, y, { ...o, dx: (o.dx || 0) + (id.dx || 0), dy: (o.dy || 0) + (id.dy || 0) + (g ? g.bob : 0), sq: (o.sq || 0) + (id.sq || 0) });+ const side = view === 'side', q = view === 'q', back = view === 'back', front = view === 'front';+ const arm = o.arm || [ARM.low, ARM.low], drag = clamp(o.drag || 0, -1, 1), wind = o.wind || 0, sw = g ? g.swing * .6 : 0, hands = [];+ const ts = st(t), flut = Math.round(Math.sin(ts * 9) * (Math.abs(wind) + (g ? 1 : 0)) * .8);+ beginSpr();+ if (side || q) { hands[0] = _arm(R, [side ? -2 : -8, -13], arm[0] - sw, 6, 0, 0, 3, CR.body[1], CR.body[2], o.hold && o.hold[0], 1); part(); }+ // feet+ const air = o.air ? 1 : 0;+ const feet = side || q ? [[g ? g.fB * 4 - 1 : -4, g ? g.lB * 2 : 0, true], [g ? g.fA * 4 + 1 : 4, g ? g.lA * 2 : 0, false]] : [[-5, g ? Math.max(0, g.fA) * 2 : 0, false], [5, g ? Math.max(0, g.fB) * 2 : 0, false]];+ for (const [fx, lift, far] of feet) { oval(...R.L(fx + (side ? 1 : 0), -2 - lift - air * 2), 3.5 * R.sx, 2.2, far ? CR.feet[1] : CR.feet[2]); }+ part();+ // scarf tail behind (side/q) + body+ if (side || q) { const tx = side ? -8 : -6; poly(R.Lp([[tx + 2, -11], [tx, -7], [tx - 6 - Math.abs(wind) * 3, -5 + flut - drag * 2], [tx - 7 - Math.abs(wind) * 3, -9 + flut - drag * 2]]), CR.scarf[1]); part(); }+ const bcx = 0, bcy = -17;+ oval(...R.L(bcx, bcy), 13 * R.sx, 12.5 * R.sy, CR.body[1]);+ oval(...R.L(bcx - 1, bcy - 1), 12 * R.sx, 11.3 * R.sy, CR.body[2]);+ oval(...R.L(bcx - (side ? 2 : 5), bcy - 7), 3.2 * R.sx, 2 * R.sy, CR.body[3]); px(...R.L(bcx - (side ? 3 : 6), bcy - 8), CR.body[4]);+ // scarf band + knot + front tail+ part();+ oval(...R.L(0, -9), 10.6 * R.sx, 2 * R.sy, CR.scarf[2]);+ line(...R.L(-9, -8), ...R.L(9, -8), CR.scarf[1]); px(...R.L(-5, -10), CR.scarf[3]); px(...R.L(-1, -10), CR.scarf[3]); px(...R.L(3, -10), CR.scarf[3]);+ if (front) { part(); const kx = 6; oval(...R.L(kx, -9), 2.2, 2, CR.scarf[3]); poly(R.Lp([[kx - 1, -8], [kx + 2, -8], [kx + 3 + flut, -1], [kx + flut, -1]]), CR.scarf[2]); px(...R.L(kx + 1 + flut, -4), CR.scarf[3]); px(...R.L(kx + 1 + flut, -2), CR.scarf[1]); }+ // sprout+ part();+ const dg = drag * 2.5, wd = wind * 2, top = [(side ? -1 : 0) + wd * .5, -34 + dg];+ pline(R.Lp([[side ? -1 : 0, -29], [(side ? -1 : 0) + wd * .3, -32 + dg * .5], top]), CR.leaf[1], 1);+ poly(R.Lp([[top[0], top[1]], [top[0] - 3, top[1] - 3 + dg * .4], [top[0] - 6, top[1] - 2 + dg * .6], [top[0] - 3, top[1] + 1]]), CR.leaf[2]);+ poly(R.Lp([[top[0], top[1]], [top[0] + 2, top[1] - 4 + dg * .4], [top[0] + 6, top[1] - 4 + dg * .6], [top[0] + 4, top[1]]]), CR.leaf[2]);+ px(...R.L(top[0] + 3, top[1] - 3 + dg * .5), CR.leaf[3]); px(...R.L(top[0] - 3, top[1] - 2 + dg * .4), CR.leaf[3]);+ part(false);+ if (!back) {+ const f = side ? { eyes: [null, [7, -20]], mouth: [10, -14], blush: [[5, -15]] }+ : q ? { eyes: [[-3, -20, 1], [5, -20]], mouth: [3, -14], blush: [[-6, -15], [8, -15]] }+ : { eyes: [[-6, -20], [4, -20]], mouth: [0, -14], blush: [[-10, -15], [7, -15]] };+ _face(R, { ...f, ew: 3, eh: 4, browCol: CR.body[1] }, ex, o, t);+ }+ part();+ if (front || back) {+ hands[0] = _arm(R, [-11, -13], arm[0], 6, 0, 0, 3, CR.body[2], CR.body[3], o.hold && o.hold[0], -1); part();+ hands[1] = _arm(R, [11, -13], arm[1], 6, 0, 0, 3, CR.body[2], CR.body[3], o.hold && o.hold[1], 1);+ } else hands[1] = _arm(R, [side ? 2 : 5, -12], arm[1] + sw, 6, 0, 0, 3, CR.body[2], CR.body[3], o.hold && o.hold[1], 1);+ const tint = ex.tint || o.tint;+ endSpr({ tint: tint === undefined ? P.charTint : tint, z: o.z, ax: R.X0, ay: R.Y0, flash: o.flash });+ const tp = R.L(top[0], top[1] - 4), info = { head: R.L(0, -17), top: tp, hands, face: R.L(side ? 6 : 0, -17) };+ if (o.emote) emote(o.emote, (o.emoteSide ?? R.fl) > 0 ? tp[0] + 5 : tp[0] - 19, tp[1] + 2, { age: o.emoteAge ?? 1 });+ return info;+}+const CAST = { pip, juno };+// contact shadow under a character (call BEFORE drawing it)+function footShadow(x, y, w = 12, lift = 0) { shadowAt(x, y, Math.max(3, w - lift * .3), 2, 1); }++// ---------- props (drawn procedurally; inside a hold callback they join the character's outline) ----------+const PROP = {+ // diamond kite centred at (x,y); o: { s: half-height, tilt (rad), t, tail: [dx,dy] trailing direction, hang: tail hangs }+ kite(x, y, o = {}) {+ const own = !SPRM; if (own) beginSpr();+ const s = o.s ?? 9, a = o.tilt ?? 0, ca = Math.cos(a), sa = Math.sin(a), cs = o.cols || ['#e24a5e', '#ffd35e'], t = st(o.t ?? T);+ const Rt = (u, v) => [x + u * ca - v * sa, y + u * sa + v * ca];+ const top = Rt(0, -s), rt = Rt(s * .8, -s * .2), bot = Rt(0, s * 1.15), lt = Rt(-s * .8, -s * .2), mid = Rt(0, -s * .2);+ poly([top, rt, bot, lt], cs[0]); poly([top, rt, mid], cs[1]); poly([lt, mid, bot], cs[1]);+ part(false); line(...top, ...bot, '#7a4432'); line(...lt, ...rt, '#7a4432');+ part();+ const td = o.tail || [0, 1], n = 6, pts = [bot];+ for (let i = 1; i <= n; i++) { const k = i / n, wv = Math.sin(t * 10 - i * 1.3) * (o.hang ? 1 : 3) * k; pts.push([bot[0] + td[0] * i * 4.5 - td[1] * wv, bot[1] + td[1] * i * 4.5 + td[0] * wv]); }+ curve(pts, '#fff0d0', 1);+ for (let i = 2; i <= n; i += 2) { const [bx, by] = pts[i]; px(bx - 1, by, cs[i % 4 ? 0 : 1]); px(bx + 1, by, cs[i % 4 ? 0 : 1]); px(bx, by, cs[i % 4 ? 1 : 0]); }+ if (own) endSpr({ tint: o.tint === undefined ? P.charTint : o.tint });+ return { bridle: mid, tailEnd: pts[n] };+ },+ spool(x, y) { rect(x - 3, y - 4, 7, 2, '#a36844'); rect(x - 3, y + 3, 7, 2, '#a36844'); rect(x - 2, y - 2, 5, 5, '#fff0d0'); line(x - 2, y - 1, x + 2, y + 1, '#d8c8a8'); line(x - 2, y + 1, x + 2, y + 3, '#d8c8a8'); },+ lantern(x, y, o = {}) { line(x, y, x, y + 3, '#3a2e52'); rect(x - 3, y + 3, 7, 2, '#3a2e52'); rect(x - 3, y + 5, 7, 7, o.lit === false ? '#6a5a4a' : '#ffd35e'); rect(x - 2, y + 6, 5, 5, o.lit === false ? '#8a7a6a' : '#fff3b0'); rect(x - 3, y + 12, 7, 2, '#3a2e52'); },+ flower(x, y, ang = -Math.PI / 2, o = {}) { const L_ = 9, fx = x + Math.cos(ang) * L_, fy = y + Math.sin(ang) * L_; line(x, y, fx, fy, '#2f7545'); const c = o.c || '#ff8f8a'; for (let i = 0; i < 5; i++) { const a = i / 5 * TAU; disc(fx + Math.cos(a) * 2, fy + Math.sin(a) * 2, 1, c); } px(fx, fy, '#ffd35e'); },+ balloon(x, y, o = {}) { const bx = x + (o.dx ?? 2), by = y - (o.len ?? 26); curve([[x, y], [x + 2, y - 8], [bx - 1, by + 14], [bx, by + 9]], '#fff0d0'); oval(bx, by, 7, 8, o.c || '#e24a5e'); oval(bx - 2, by - 3, 2, 2, shade(o.c || '#e24a5e', 1)); px(bx, by + 9, o.c || '#e24a5e'); },+ mug(x, y) { rect(x - 3, y - 6, 6, 7, '#fff0d0'); rect(x + 3, y - 4, 2, 3, '#fff0d0'); rect(x - 2, y - 5, 4, 1, '#7a4432'); },+ letter(x, y, ang = 0) { rect(x - 5, y - 4, 10, 7, '#fff8e8'); line(x - 5, y - 4, x, y, '#c9b8a0'); line(x + 4, y - 4, x, y, '#c9b8a0'); px(x, y + 1, '#e24a5e'); },+ star(x, y, o = {}) { const r = o.r ?? 5; poly([...Array(10)].map((_, i) => { const a = -Math.PI / 2 + i * Math.PI / 5, rr = i % 2 ? r * .45 : r; return [x + Math.cos(a) * rr, y + Math.sin(a) * rr]; }), o.c || '#ffd35e'); },+ umbrella(x, y, o = {}) { const h = o.h ?? 18, c = o.c || '#4f86c6'; line(x, y, x, y - h, '#3a2e52'); const cx = x, cy = y - h; poly([[cx - 13, cy + 2], [cx - 10, cy - 5], [cx, cy - 8], [cx + 10, cy - 5], [cx + 13, cy + 2]], c); for (const k of [-8, 0, 8]) line(cx + k, cy - 6, cx + k * 1.5, cy + 2, shade(c, -1)); line(x, y, x - 2, y + 2, '#3a2e52'); },+};diff --git a/.claude/skills/pixel-art/template/src/config.js b/.claude/skills/pixel-art/template/src/config.jsnew file mode 100644index 0000000..7eb6330--- /dev/null+++ b/.claude/skills/pixel-art/template/src/config.js@@ -0,0 +1,4 @@+// config.js: project settings.+// duration: the video's length in seconds. fps: output frame rate (sprites still animate on 12s via st(t)).+// bpm/offset: the beat idles, hops and pulse() follow; with music set bpm to the song's tempo and offset to its first downbeat.+const PROJECT = { duration: 10, bpm: 120, offset: 0, fps: 24 };diff --git a/.claude/skills/pixel-art/template/src/kit.js b/.claude/skills/pixel-art/template/src/kit.jsnew file mode 100644index 0000000..8d6f3c2--- /dev/null+++ b/.claude/skills/pixel-art/template/src/kit.js@@ -0,0 +1,154 @@+// kit.js: the shared runtime for ReelMimic's Canvas-2D drawing engines (pixel art, paper cut-out, whiteboard, anime+// cel, crayon storybook). Each engine copies this file into its template unchanged and adds its own drawing library.+//+// The render contract is the same as painted-animation's, so the same render.mjs drives every engine:+// window.ready = true once fonts and assets are loaded+// window.renderAt(t, type, q) → data URL of the frame at time t+// window.renderSheet(times, cols, w, crop, at) → { url, ms[] } contact sheet (crop = [x,y,w,h] in screen px,+// at = [x,y,w,h] around a WORLD point, wherever the camera put it)+// Every frame is a pure function of t: frames render in parallel and out of order, so nothing may carry over from one+// frame to the next. Use hash()/rnd() for stable randomness, never Math.random().+//+// An engine plugs in through window.ENGINE = { setup(), begin(t), end(t) } (all optional):+// setup() → once, async (load images, build textures); begin(t) → before the shot draws (e.g. switch G to a low-res+// buffer); end(t) → after it (e.g. upscale, add grain). Shots draw with the 2D context G.++const W = 1920, H = 1080, TAU = Math.PI * 2;+const DUR = PROJECT.duration, BPM = PROJECT.bpm || 120, BEAT = 60 / BPM, OFF = PROJECT.offset || 0;+const FPS = PROJECT.fps || 24;++// ---------- math & timing (pure functions of t) ----------+const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));+const lerp = (a, b, x) => a + (b - a) * x;+const ease = x => { x = clamp(x); return x * x * (3 - 2 * x); };+const easeIn = x => Math.pow(clamp(x), 3);+const easeOut = x => 1 - Math.pow(1 - clamp(x), 3);+const backOut = x => { x = clamp(x); const s = 1.9; return 1 + (s + 1) * Math.pow(x - 1, 3) + s * Math.pow(x - 1, 2); };+const elasticOut = x => { x = clamp(x); return x === 0 || x === 1 ? x : Math.pow(2, -10 * x) * Math.sin((x * 10 - .75) * (TAU / 3)) + 1; };+const hash = i => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };+// seeded stream for one element: const r = rnd('tree' + i); r() → 0..1, the same every frame+function rnd(key) { let h = 2166136261; for (const c of String(key)) h = Math.imul(h ^ c.charCodeAt(0), 16777619); let s = h >>> 0 || 1; return () => (s = Math.imul(s ^ (s >>> 15), 2246822519) >>> 0, s = (s ^ (s >>> 13)) >>> 0, (s % 1000003) / 1000003); }+const seg = (t, a, b) => clamp((t - a) / (b - a));+const frac = x => x - Math.floor(x);+const bpOf = t => (t - OFF) / BEAT;+const beatN = t => Math.floor(bpOf(t));+const pulse = (t, k = 6) => Math.exp(-frac(bpOf(t)) * k);+const wob = (t, f = 1, ph = 0) => Math.sin((t * f + ph) * TAU);+// hold drawings like hand animation: onTwos(t) = 12 drawings/s, onStep(t, 8) = 8/s (stop-motion feel)+const onTwos = t => Math.floor(t * 12 + 1e-6) / 12;+const onStep = (t, n) => Math.floor(t * n + 1e-6) / n;+function kf(t, keys, e = ease) {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) if (t < keys[i][0]) {+ const [a, va] = keys[i - 1], [b, vb] = keys[i], k = e((t - a) / (b - a));+ return Array.isArray(va) ? va.map((v, j) => lerp(v, vb[j], k)) : lerp(va, vb, k);+ }+ return keys[keys.length - 1][1];+}+function mixCol(a, b, k) {+ const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16), c = i => Math.round(lerp((pa >> i) & 255, (pb >> i) & 255, clamp(k)));+ return '#' + ((1 << 24) + (c(16) << 16) + (c(8) << 8) + c(0)).toString(16).slice(1);+}+const shakeXY = (t, amt) => { const f = Math.floor(t * 24); return [(hash(f * 1.7) - .5) * 2 * amt, (hash(f * 2.3 + 9) - .5) * 2 * amt]; };+// motion principles+const spring = (t, t0, k = 6, w = 18) => t < t0 ? 0 : Math.exp(-k * (t - t0)) * Math.sin(w * (t - t0));+const arcPt = (p0, p1, h, k) => [lerp(p0[0], p1[0], k), lerp(p0[1], p1[1], k) - h * 4 * k * (1 - k)];+function jump(t, t0, t1, h = 3) { // → { dy (units, up is negative), sq (squash +, stretch -) }+ if (t < t0 - .12) return { dy: 0, sq: 0 };+ if (t < t0) return { dy: 0, sq: .18 * ease(seg(t, t0 - .12, t0)) };+ if (t < t1) { const k = (t - t0) / (t1 - t0); return { dy: -h * 4 * k * (1 - k), sq: -.16 * Math.abs(1 - 2 * k) }; }+ const a = t - t1; return { dy: 0, sq: .22 * Math.exp(-8 * a) * Math.cos(20 * a) };+}+function take(t, t0, amt = 1) { // surprise take peaking at t0+ if (t < t0 - .1) return { sq: 0, dy: 0 };+ if (t < t0) return { sq: .12 * amt * ease(seg(t, t0 - .1, t0)), dy: 0 };+ const a = t - t0; return { sq: -.26 * amt * Math.exp(-6 * a) * Math.cos(16 * a), dy: -1.2 * amt * Math.exp(-7 * a) * Math.max(0, Math.cos(9 * a)) };+}++// ---------- shots ----------+// shots([[t0, fn], ...]); fn(t, lt, dur) paints the WHOLE frame (background included) with G.+const SHOTS = [], LOOPS = {};+function shots(list) { SHOTS.push(...list); SHOTS.sort((a, b) => a[0] - b[0]); }+function drawWorld(t) {+ if (window.LOOP) return window.LOOP(t);+ if (!SHOTS.length) { G.fillStyle = '#EDE6D8'; G.fillRect(0, 0, W, H); return; }+ let i = 0; while (i + 1 < SHOTS.length && t >= SHOTS[i + 1][0]) i++;+ const t0 = SHOTS[i][0], end = i + 1 < SHOTS.length ? SHOTS[i + 1][0] : DUR;+ SHOTS[i][1](t, t - t0, end - t0);+ if (CAM) camEnd();+}++// ---------- camera (world → screen) ----------+let CAM = null, LAST_CAM = null;+function camBegin(cx = W / 2, cy = H / 2, zoom = 1, rot = 0) {+ G.save(); G.translate(W / 2, H / 2); G.rotate(rot); G.scale(zoom, zoom); G.translate(-cx, -cy);+ CAM = LAST_CAM = { cx, cy, zoom, rot };+}+function camEnd() { G.restore(); CAM = null; }+function toScreen(x, y, cam = CAM) {+ if (!cam) return [x, y];+ const dx = (x - cam.cx) * cam.zoom, dy = (y - cam.cy) * cam.zoom, c = Math.cos(cam.rot), s = Math.sin(cam.rot);+ return [W / 2 + dx * c - dy * s, H / 2 + dx * s + dy * c];+}++// ---------- canvases & frame ----------+// G: the context shots draw into (an engine may point it at a low-res buffer in begin()). OUT: the visible 1920×1080.+let G = null, OUT = null, OUTC = null, T = 0;+function makeCanvas(w = W, h = H) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }+async function renderFrame(t) {+ T = t; CAM = LAST_CAM = null;+ G = OUT; G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over';+ G.clearRect(0, 0, W, H);+ if (window.ENGINE && ENGINE.begin) ENGINE.begin(t);+ drawWorld(t);+ if (window.ENGINE && ENGINE.end) ENGINE.end(t);+ OUT.setTransform(1, 0, 0, 1, 0, 0); OUT.globalAlpha = 1; OUT.globalCompositeOperation = 'source-over';+ if (window.overlayHook) window.overlayHook(OUT, t); // crisp captions / karaoke above everything+}+window.renderAt = async (t, type = 'image/png', q = .92) => { await renderFrame(t); return OUTC.toDataURL(type, q); };+window.renderSheet = async (times, cols = 3, w = 640, crop = null, at = null) => {+ if (at) at = at.map((v) => typeof v === 'string' ? (0, eval)(v) : v);+ const [, , cw, ch] = at || crop || [0, 0, W, H], h = Math.round(w * ch / cw), rows = Math.ceil(times.length / cols), sc = makeCanvas(cols * w, rows * h);+ const c = sc.getContext('2d'), ms = [];+ for (let i = 0; i < times.length; i++) {+ const t0 = performance.now(); await renderFrame(times[i]); ms.push(Math.round(performance.now() - t0));+ const x = (i % cols) * w, y = Math.floor(i / cols) * h;+ const [cx, cy] = at ? toScreen(at[0], at[1], LAST_CAM).map((v, j) => v - (j ? ch : cw) / 2) : crop || [0, 0];+ c.imageSmoothingEnabled = !(window.ENGINE && ENGINE.crisp);+ c.drawImage(OUTC, cx, cy, cw, ch, x, y, w, h);+ c.fillStyle = 'rgba(0,0,0,.65)'; c.fillRect(x, y, 84, 24); c.fillStyle = '#fff'; c.font = '15px sans-serif'; c.fillText(times[i].toFixed(2) + 's', x + 6, y + 17);+ }+ return { url: sc.toDataURL('image/jpeg', .9), ms };+};+window.gpuInfo = () => 'canvas2d';++// ---------- captions (optional) ----------+// A simple, legible caption bar on the overlay: caption(c, text, { y, size, font, fg, bg }). Engines may style their own.+function caption(c, txt, o = {}) {+ const size = o.size || 54, y = o.y || H - 70, font = o.font || `700 ${size}px "Noto Sans TC", "Noto Sans", system-ui, sans-serif`;+ c.save(); c.font = font; c.textAlign = 'center'; c.textBaseline = 'middle';+ const w = c.measureText(txt).width + size * 1.1;+ c.fillStyle = o.bg || 'rgba(20,18,26,.72)'; const r = size * .5;+ c.beginPath(); c.roundRect(W / 2 - w / 2, y - size * .78, w, size * 1.56, r); c.fill();+ c.lineJoin = 'round'; c.lineWidth = size * .14; c.strokeStyle = 'rgba(0,0,0,.55)'; c.strokeText(txt, W / 2, y + 2);+ c.fillStyle = o.fg || '#FFF8EC'; c.fillText(txt, W / 2, y + 2); c.restore();+}++// ---------- boot ----------+async function boot() {+ OUTC = document.getElementById('out'); OUT = OUTC.getContext('2d', { willReadFrequently: false });+ const fonts = [...(window.EXTRA_FONTS || [])].map(([f, txt]) => document.fonts.load(f, txt));+ await Promise.all(fonts);+ if (window.ENGINE && ENGINE.setup) await ENGINE.setup();+ window.ready = true;+ if (!location.search.includes('render')) devUI();+}+function devUI() {+ const s = document.getElementById('scrub'), lab = document.getElementById('tt'); if (!s) return;+ s.max = window.LOOP ? window.LOOP.len : DUR; s.step = 1 / FPS;+ let busy = false, want = null;+ const go = async () => { if (busy) return; busy = true; while (want != null) { const t = want; want = null; const t0 = performance.now(); await renderFrame(t); lab.textContent = `${t.toFixed(2)}s · ${Math.round(performance.now() - t0)} ms/frame`; } busy = false; };+ s.addEventListener('input', () => { want = +s.value; go(); });+ want = +(new URLSearchParams(location.search).get('t') || 0); s.value = want; go();+}+window.addEventListener('load', () => { const q = new URLSearchParams(location.search).get('loop'); if (q && LOOPS[q]) window.LOOP = LOOPS[q]; boot(); });diff --git a/.claude/skills/pixel-art/template/src/pixel.js b/.claude/skills/pixel-art/template/src/pixel.jsnew file mode 100644index 0000000..c6bfdd7--- /dev/null+++ b/.claude/skills/pixel-art/template/src/pixel.js@@ -0,0 +1,693 @@+// pixel.js: ReelMimic's PIXEL-ART drawing library.+//+// Everything is drawn into a 480×270 software framebuffer (FB, one Uint32 per pixel) and upscaled ×4 to 1920×1080+// with nearest-neighbour in ENGINE.end. World units = low-res pixels. The camera and every shape snap to whole pixels,+// so nothing shimmers. Colours come from limited palettes (P = PALS.day / dusk / night) organised as ramps+// (dark → light); shade(c, k) walks a ramp, which is how outlines, shadows and lights stay on-palette.+//+// Why 480×270 ×4: a 40–70 px character is big enough for readable faces (eyes 2–3 px, mouths 3–5 px) and the pixel+// grid still reads as pixel art at phone size (1 art pixel = 4 screen px; ≈0.8 px on a 390-px phone, and characters+// are 160–280 screen px tall). 384×216 ×5 is chunkier but leaves too few pixels for faces and two-character staging.+//+// Pure functions of t: no Math.random, no state between frames. Everything below takes world coordinates unless noted.++const LW = 480, LH = 270, PXS = W / LW;+const LOC = makeCanvas(LW, LH), LOX = LOC.getContext('2d');+const IMG = LOX.createImageData(LW, LH), FB = new Uint32Array(IMG.data.buffer), FB2 = new Uint32Array(LW * LH);+const SB = new Uint32Array(LW * LH), SID = new Uint8Array(LW * LH), PLINE = new Uint8Array(256);+let OX = 0, OY = 0, CAMX = 0, CAMY = 0, SPRM = false, PART = 1, PUNCH = null;+let KX0 = 0, KY0 = 0, KX1 = LW - 1, KY1 = LH - 1; // clip rect (screen px, inclusive)+let BX0 = LW, BY0 = LH, BX1 = -1, BY1 = -1; // sprite bbox++// ---------- colour ----------+const _C = new Map();+function C(c) { // '#rrggbb' | u32 → u32 (ABGR, as stored in FB)+ if (typeof c === 'number') return c;+ let v = _C.get(c); if (v !== undefined) return v;+ const n = parseInt(c.slice(1, 7), 16);+ v = (0xff000000 | ((n & 255) << 16) | (n & 0xff00) | ((n >> 16) & 255)) >>> 0; _C.set(c, v); return v;+}+const _b8 = v => v < 0 ? 0 : v > 255 ? 255 : v | 0;+const U = (r, g, b) => (0xff000000 | (_b8(b) << 16) | (_b8(g) << 8) | _b8(r)) >>> 0;+const rgbOf = u => [u & 255, (u >>> 8) & 255, (u >>> 16) & 255];+const hexOf = u => { const [r, g, b] = rgbOf(C(u)); return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); };+function mixU(a, b, k) { const A = rgbOf(C(a)), B = rgbOf(C(b)); return U(lerp(A[0], B[0], k), lerp(A[1], B[1], k), lerp(A[2], B[2], k)); }++// ramps: every registered ramp lets shade() step along it. Off the end, a hue-shifted darken/lighten takes over+// (shadows drift toward blue-violet, lights toward warm), the classic pixel-art ramp rule.+const RAMP = new Map();+function regRamp(arr) { const us = arr.map(C); us.forEach((u, i) => RAMP.set(u, { r: us, i })); return arr; }+function _shift(u, k) {+ let [r, g, b] = rgbOf(u);+ for (let s = 0; s < Math.abs(k); s++) {+ if (k < 0) { r = r * .72; g = g * .7; b = b * .8 + 10; }+ else { r += (255 - r) * .32 + 6; g += (255 - g) * .28 + 3; b += (255 - b) * .2; }+ }+ return U(r, g, b);+}+const _SH = new Map();+function shade(c, k = -1) { // k steps along c's ramp (− darker, + lighter) → u32+ const u = C(c); if (!k) return u;+ const key = u * 32 + k + 16; let v = _SH.get(key); if (v !== undefined) return v;+ const e = RAMP.get(u);+ if (e) { const j = e.i + k, n = e.r.length; v = j >= 0 && j < n ? e.r[j] : _shift(e.r[j < 0 ? 0 : n - 1], j < 0 ? j : j - n + 1); }+ else v = _shift(u, k);+ _SH.set(key, v); return v;+}+const _TN = new Map();+function tintU(u, tc, k) { const key = u + '|' + tc + '|' + k; let v = _TN.get(key); if (v === undefined) { v = mixU(u, tc, k); _TN.set(key, v); } return v; }++// ---------- palettes (~30 colours each, as ramps dark → light; same keys in every palette) ----------+const PALS = {+ day: {+ name: 'day', ink: '#1d1b2e', paper: '#fff8e8',+ sky: ['#3f73c6', '#5a95e0', '#7fb6ee', '#abd6f5', '#dcf1fa'],+ cloud: ['#98b2da', '#cfe0f3', '#f8fbff'],+ far: ['#6d93c8', '#8cb0da'], mid: ['#3f8a78', '#5aa880', '#86c98c'],+ grass: ['#1f4d3c', '#2f7545', '#489c48', '#78c455', '#b9e26c'],+ earth: ['#3e2a30', '#6a4034', '#946140', '#c08b56', '#e4bb86'],+ stone: ['#434563', '#6b6e8e', '#9da2bd'], wood: ['#472a2b', '#744332', '#a36844'],+ light: ['#e89a3c', '#ffd35e', '#fff3b0'], sun: ['#ffd35e', '#fff3b0', '#fffdf0'],+ accent: ['#9c2a48', '#e24a5e', '#ff8f8a'], cool: ['#2c4f8a', '#4f86c6'], rim: '#fff3b0',+ charTint: null,+ },+ dusk: {+ name: 'dusk', ink: '#1a1228', paper: '#fff0dc',+ sky: ['#2c2254', '#512d66', '#8a3d6e', '#cf5b6a', '#f38f5e', '#ffc67a'],+ cloud: ['#6a3566', '#b8546e', '#f39a7e'],+ far: ['#4e3474', '#6c4284'], mid: ['#35285a', '#452f66', '#5a3a72'],+ grass: ['#1c1834', '#2a2246', '#3d2d58', '#5e3f68', '#8a5670'],+ earth: ['#221628', '#35203a', '#4c2c4a'],+ stone: ['#2e2a48', '#48406a'], wood: ['#2c1a2c', '#4a2a3a', '#6c3c46'],+ light: ['#ff8a45', '#ffc862', '#fff0b0'], sun: ['#ffb45a', '#ffe08a', '#fff6d2'],+ accent: ['#a02a4a', '#ff5a6a', '#ff9d8a'], cool: ['#3a3a7a', '#5a5aa0'], rim: '#ffb07a',+ charTint: ['#ff7a5a', .1],+ },+ night: {+ name: 'night', ink: '#08091a', paper: '#e8ecff',+ sky: ['#090b22', '#10173a', '#192655', '#263a72', '#3a5594'],+ cloud: ['#1e2a55', '#2f4278', '#4a64a0'],+ far: ['#172246', '#1f2d58'], mid: ['#111a36', '#172444', '#1f3050'],+ grass: ['#0c1624', '#132536', '#1c3846', '#2a525c', '#3f7474'],+ earth: ['#100c1c', '#1c162e', '#2a2242'],+ stone: ['#1e2240', '#2e3458'], wood: ['#160f1e', '#261a2e', '#3a2a40'],+ light: ['#e0783a', '#ffb44a', '#ffe08a', '#fff6cc'], sun: ['#cfc7a0', '#efe9c8', '#fffbe8'],+ accent: ['#6a2a5a', '#c84a78', '#ff8aa8'], cool: ['#8fa6e0', '#dfe8ff'], rim: '#8fb0ff',+ charTint: ['#3a4a9a', .32],+ },+};+for (const p of Object.values(PALS)) for (const v of Object.values(p)) if (Array.isArray(v) && typeof v[0] === 'string' && v[0][0] === '#') regRamp(v);+let P = PALS.day;+function pal(name) { P = PALS[name] || name; return P; }+function palColours(p = P) { const s = new Set(); for (const [k, v] of Object.entries(p)) if (k !== 'charTint') [].concat(v).forEach(c => typeof c === 'string' && c[0] === '#' && s.add(c)); return [...s]; }++// ---------- ordered (Bayer) dithering ----------+const BAY4 = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5].map(v => (v + .5) / 16);+const BAY8 = (() => { const m = [0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30, 54, 22, 3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21]; return m.map(v => (v + .5) / 64); })();+// dither test at a WORLD pixel of the current layer (pattern moves with the layer, so it never swims)+const dith = (x, y, d) => BAY4[((Math.round(y) & 3) << 2) | (Math.round(x) & 3)] < d;+const qd = (d, n = 4) => Math.round(clamp(d) * n) / n; // quantise a level so dithers come in clean bands++// ---------- camera & layers ----------+// camAt(cx, cy): world point at screen centre, snapped to whole pixels. layer(f) = parallax factor for what follows+// (0 = fixed to screen, 1 = world). screenSpace() = draw in screen pixels (HUD, transitions).+function camAt(cx = LW / 2, cy = LH / 2) {+ CAMX = Math.round(cx - LW / 2); CAMY = Math.round(cy - LH / 2); layer(1);+ LAST_CAM = { cx: CAMX + LW / 2, cy: CAMY + LH / 2, zoom: PXS, rot: 0 };+}+function layer(f = 1, fy = f) { OX = Math.round(CAMX * f); OY = Math.round(CAMY * fy); }+function screenSpace() { OX = 0; OY = 0; }+const shake = (t, amt) => shakeXY(onStep(t, 12), amt).map(Math.round);+// integer punch-in: z = 2 or 3 magnifies around a world point (pixels just get bigger, still crisp)+function punch(z, x, y) {+ z = Math.max(1, Math.round(z)); if (z === 1) { PUNCH = null; return; }+ const sx = clamp(Math.round(x - CAMX - LW / z / 2), 0, LW - LW / z), sy = clamp(Math.round(y - CAMY - LH / z / 2), 0, LH - LH / z);+ PUNCH = { z, sx, sy }; LAST_CAM = { cx: CAMX + sx + LW / z / 2, cy: CAMY + sy + LH / z / 2, zoom: PXS * z, rot: 0 };+}+// world → screen px of the current layer, and back+const scr = (x, y) => [Math.round(x) - OX, Math.round(y) - OY];+function clip(x, y, w, h) { KX0 = Math.max(0, Math.round(x) - OX); KY0 = Math.max(0, Math.round(y) - OY); KX1 = Math.min(LW - 1, Math.round(x + w) - OX - 1); KY1 = Math.min(LH - 1, Math.round(y + h) - OY - 1); }+function noclip() { KX0 = 0; KY0 = 0; KX1 = LW - 1; KY1 = LH - 1; }++// ---------- raster core (screen px) ----------+function _p(x, y, u) {+ if (x < KX0 || x > KX1 || y < KY0 || y > KY1) return;+ const i = y * LW + x;+ if (SPRM) { SB[i] = u; SID[i] = PART; if (x < BX0) BX0 = x; if (x > BX1) BX1 = x; if (y < BY0) BY0 = y; if (y > BY1) BY1 = y; }+ else FB[i] = u;+}+function _span(y, x0, x1, u, d = 1) {+ if (y < KY0 || y > KY1) return; if (x0 < KX0) x0 = KX0; if (x1 > KX1) x1 = KX1; if (x0 > x1) return;+ const row = y * LW, by = ((y + OY) & 3) << 2;+ if (SPRM) {+ if (x0 < BX0) BX0 = x0; if (x1 > BX1) BX1 = x1; if (y < BY0) BY0 = y; if (y > BY1) BY1 = y;+ for (let x = x0; x <= x1; x++) if (d >= 1 || BAY4[by | ((x + OX) & 3)] < d) { SB[row + x] = u; SID[row + x] = PART; }+ } else if (d >= 1) FB.fill(u, row + x0, row + x1 + 1);+ else for (let x = x0; x <= x1; x++) if (BAY4[by | ((x + OX) & 3)] < d) FB[row + x] = u;+}++// ---------- primitives (world coords; c = '#hex' or u32; d = dither density 0..1, 1 = solid) ----------+function fill(c) { FB.fill(C(c)); }+function px(x, y, c) { _p(Math.round(x) - OX, Math.round(y) - OY, C(c)); }+function rect(x, y, w, h, c, d = 1) {+ const u = C(c), sx = Math.round(x) - OX, sy = Math.round(y) - OY, ww = Math.round(w), hh = Math.round(h);+ for (let j = 0; j < hh; j++) _span(sy + j, sx, sx + ww - 1, u, d);+}+const _ST = {};+function _stamp(w) {+ if (_ST[w]) return _ST[w];+ const o = [], a = -Math.floor((w - 1) / 2), c = (w - 1) / 2 + a, th = (w / 2) ** 2 - (w === 3 ? 1 : 0);+ for (let j = a; j < a + w; j++) for (let i = a; i < a + w; i++) if (w <= 2 || (i - c) ** 2 + (j - c) ** 2 <= th) o.push(i, j);+ return (_ST[w] = o);+}+function line(x0, y0, x1, y1, c, w = 1) { // Bresenham, w = brush width in px (round brush)+ const u = C(c), st = _stamp(Math.max(1, Math.round(w)));+ let ax = Math.round(x0) - OX, ay = Math.round(y0) - OY; const bx = Math.round(x1) - OX, by = Math.round(y1) - OY;+ const dx = Math.abs(bx - ax), dy = -Math.abs(by - ay), sx = ax < bx ? 1 : -1, sy = ay < by ? 1 : -1; let e = dx + dy;+ for (let n = 0; n < 2000; n++) {+ for (let k = 0; k < st.length; k += 2) _p(ax + st[k], ay + st[k + 1], u);+ if (ax === bx && ay === by) break;+ const e2 = 2 * e; if (e2 >= dy) { e += dy; ax += sx; } if (e2 <= dx) { e += dx; ay += sy; }+ }+}+function pline(pts, c, w = 1) { for (let i = 1; i < pts.length; i++) line(pts[i - 1][0], pts[i - 1][1], pts[i][0], pts[i][1], c, w); }+// smooth curve through control points (quadratic B-spline sampled per pixel) — ropes, strings, tails+function curve(pts, c, w = 1, n = 0) {+ const out = []; n = n || Math.max(4, Math.round(pts.reduce((s, p, i) => i ? s + Math.hypot(p[0] - pts[i - 1][0], p[1] - pts[i - 1][1]) : 0, 0) / 3));+ for (let i = 0; i <= n; i++) { const k = i / n, q = k * (pts.length - 1), a = Math.min(pts.length - 2, Math.floor(q)), f = q - a; out.push([lerp(pts[a][0], pts[a + 1][0], f), lerp(pts[a][1], pts[a + 1][1], f)]); }+ pline(out, c, w);+}+function disc(cx, cy, r, c, d = 1) { // filled circle, diameter 2r+1, centred on pixel (cx, cy)+ const u = C(c), sx = Math.round(cx) - OX, sy = Math.round(cy) - OY, R = r + .4, R2 = R * R;+ for (let j = -Math.floor(R); j <= Math.floor(R); j++) { const h = Math.floor(Math.sqrt(R2 - j * j)); _span(sy + j, sx - h, sx + h, u, d); }+}+function oval(cx, cy, rx, ry, c, d = 1) { // filled ellipse centred on pixel (cx, cy)+ if (rx < .5 && ry < .5) return px(cx, cy, c);+ const u = C(c), sx = Math.round(cx) - OX, sy = Math.round(cy) - OY, Ry = ry + .4, Rx = rx + .4;+ for (let j = -Math.floor(Ry); j <= Math.floor(Ry); j++) { const t = 1 - (j / Ry) ** 2; if (t < 0) continue; const h = Math.floor(Rx * Math.sqrt(t)); _span(sy + j, sx - h, sx + h, u, d); }+}+function ring(cx, cy, r, c, w = 1) { // circle outline+ const u = C(c), sx = Math.round(cx) - OX, sy = Math.round(cy) - OY, R = r + .4, Ri = Math.max(0, r - w + .4);+ for (let j = -Math.floor(R); j <= Math.floor(R); j++) for (let i = -Math.floor(R); i <= Math.floor(R); i++) { const d2 = i * i + j * j; if (d2 <= R * R && d2 > Ri * Ri) _p(sx + i, sy + j, u); }+}+function poly(pts, c, d = 1) { // scanline polygon fill (even-odd), vertices snapped to pixels+ const u = C(c), n = pts.length; if (n < 3) return;+ const xs = new Array(n), ys = new Array(n); let y0 = 1e9, y1 = -1e9;+ for (let i = 0; i < n; i++) { xs[i] = Math.round(pts[i][0]) - OX; ys[i] = Math.round(pts[i][1]) - OY; if (ys[i] < y0) y0 = ys[i]; if (ys[i] > y1) y1 = ys[i]; }+ y0 = Math.max(y0, KY0); y1 = Math.min(y1, KY1 + 1);+ const hit = [];+ for (let y = y0; y < y1; y++) {+ const yc = y + .5; hit.length = 0;+ for (let i = 0, j = n - 1; i < n; j = i++) { const ya = ys[j], yb = ys[i]; if ((ya <= yc && yc < yb) || (yb <= yc && yc < ya)) hit.push(xs[j] + (yc - ya) * (xs[i] - xs[j]) / (yb - ya)); }+ hit.sort((a, b) => a - b);+ for (let k = 0; k + 1 < hit.length; k += 2) _span(y, Math.ceil(hit[k] - .5), Math.floor(hit[k + 1] - .5), u, d);+ }+}+// shaded ball: dark crescent bottom-right, base, highlight top-left (volume in three tones of one ramp)+function ball(cx, cy, rx, ry, c, o = {}) {+ const b = C(c); oval(cx, cy, rx, ry, o.dark ?? shade(b, -1));+ oval(cx - 1, cy - 1, Math.max(0, rx - 1.2), Math.max(0, ry - 1.2), b);+ if (o.hi !== false && rx > 2) oval(cx - rx * .38, cy - ry * .42, Math.max(.4, rx * .28), Math.max(.4, ry * .2), o.light ?? shade(b, 1));+}++// ---------- sprite passes: auto selective outlines ----------+// beginSpr(); ...draw parts...; endSpr(opts). Everything drawn in between is composited as one sprite with a 1-px+// outline in a darker hue of the neighbouring fill (never flat black). part(line) starts a new part: a part drawn over+// an earlier one gets an inner line on the pixels it covers the edge of (arms over bodies). part(false) = no inner line+// (faces, highlights). opts: { outline: true, k: -2 (outline shade), inner: -1, tint: ['#hex', k], z (integer scale),+// ax, ay (world anchor for z), flash (0..1 white), alpha: false }+function beginSpr() { SPRM = true; PART = 1; PLINE.fill(0); BX0 = LW; BY0 = LH; BX1 = -1; BY1 = -1; }+function part(ln = true) { PART = Math.min(255, PART + 1); PLINE[PART] = ln ? 1 : 0; }+function endSpr(o = {}) {+ SPRM = false; if (BX1 < BX0) return null;+ const x0 = Math.max(0, BX0 - 1), y0 = Math.max(0, BY0 - 1), x1 = Math.min(LW - 1, BX1 + 1), y1 = Math.min(LH - 1, BY1 + 1);+ const w = x1 - x0 + 1, h = y1 - y0 + 1, R = new Uint32Array(w * h), ok = o.outline !== false, ko = o.k ?? -2, ki = o.inner ?? -2;+ const tint = o.tint === undefined ? P.charTint : o.tint, tc = tint ? C(tint[0]) : 0, tk = tint ? tint[1] : 0;+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {+ const i = y * LW + x, c = SB[i]; let out = 0;+ if (c) {+ out = c; const id = SID[i];+ // inner line: this pixel lies under the edge of a later part that wants a line+ if (ki) for (let q = 0; q < 4; q++) {+ const nx = x + (q === 0 ? -1 : q === 1 ? 1 : 0), ny = y + (q === 2 ? -1 : q === 3 ? 1 : 0);+ if (nx < 0 || ny < 0 || nx >= LW || ny >= LH) continue;+ const j = ny * LW + nx, nid = SID[j]; if (SB[j] && nid > id && PLINE[nid]) { out = shade(SB[j], ki); break; }+ }+ } else if (ok) {+ // outer outline: darker hue of a filled 4-neighbour (prefer the one below: shapes read as lit from above)+ let nb = 0;+ if (y + 1 < LH && SB[i + LW]) nb = SB[i + LW]; else if (x > 0 && SB[i - 1]) nb = SB[i - 1];+ else if (x + 1 < LW && SB[i + 1]) nb = SB[i + 1]; else if (y > 0 && SB[i - LW]) nb = SB[i - LW];+ if (nb) out = shade(nb, ko);+ }+ if (out && tk) out = tintU(out, tc, tk);+ if (out && o.flash) out = tintU(out, 0xffffffff, o.flash);+ R[(y - y0) * w + (x - x0)] = out;+ }+ for (let y = y0; y <= y1; y++) { SB.fill(0, y * LW + x0, y * LW + x1 + 1); }+ const z = Math.max(1, Math.round(o.z || 1));+ if (z === 1) { for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const c = R[y * w + x]; if (c && x0 + x >= KX0 && x0 + x <= KX1 && y0 + y >= KY0 && y0 + y <= KY1) FB[(y0 + y) * LW + x0 + x] = c; } }+ else {+ const ax = Math.round(o.ax ?? 0) - OX, ay = Math.round(o.ay ?? 0) - OY;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {+ const c = R[y * w + x]; if (!c) continue; const X = ax + (x0 + x - ax) * z, Y = ay + (y0 + y - ay) * z;+ for (let b = 0; b < z; b++) for (let a = 0; a < z; a++) { const xx = X + a, yy = Y + b; if (xx >= KX0 && xx <= KX1 && yy >= KY0 && yy <= KY1) FB[yy * LW + xx] = c; }+ }+ }+ return [x0 + OX, y0 + OY, w, h];+}+function outlined(fn, o) { beginSpr(); fn(); return endSpr({ tint: null, ...o }); }++// ---------- sprites from string grids ----------+// sprite(rows, map, x, y, { ax=.5, ay=1, flip, z }): rows = array of strings (or one multi-line string); map maps+// each char to a colour; '.' and ' ' are transparent. Anchor (ax, ay) is where (x, y) sits inside the sprite.+const _SP = new Map();+function _parse(rows) {+ let s = _SP.get(rows); if (s) return s;+ const r = typeof rows === 'string' ? rows.split('\n').map(l => l.trim()).filter(Boolean) : rows;+ s = { w: Math.max(...r.map(l => l.length)), h: r.length, r }; _SP.set(rows, s); return s;+}+function sprite(rows, map, x, y, o = {}) {+ const s = _parse(rows), z = o.z || 1, fl = o.flip, bx = Math.round(x - (o.ax ?? .5) * s.w * z), by = Math.round(y - (o.ay ?? 1) * s.h * z);+ const cm = {}; for (const k in map) cm[k] = map[k] == null ? 0 : C(map[k]);+ for (let j = 0; j < s.h; j++) { const l = s.r[j]; for (let i = 0; i < l.length; i++) { const ch = l[i]; if (ch === '.' || ch === ' ' || !cm[ch]) continue; const ii = fl ? s.w - 1 - i : i; if (z === 1) px(bx + ii, by + j, cm[ch]); else rect(bx + ii * z, by + j * z, z, z, cm[ch]); } }+}++// ---------- tiles (16×16, generated from the palette, cached per palette) ----------+const TS = 16, _TL = new Map();+const TILE_GEN = {+ grass(p, x, y, r) { const g = p.grass, e = p.earth; const edge = 4 + Math.round(r(x) * 2); if (y === 0) return g[4]; if (y < edge - 1) return g[3]; if (y < edge) return g[2]; if (y === edge) return e[1]; return (hash(x * 7 + y * 31) > .9) ? e[1] : (hash(x * 13 + y * 5) > .93 ? e[3] : e[2]); },+ dirt(p, x, y) { const e = p.earth; return hash(x * 7 + y * 31 + 3) > .9 ? e[1] : hash(x * 17 + y * 3) > .94 ? e[3] : e[2]; },+ brick(p, x, y) { const s = p.stone, row = y >> 2, off = (row & 1) * 4; if ((y & 3) === 3 || ((x + off) & 7) === 7) return s[0]; return (y & 3) === 0 ? s[2] : s[1]; },+ plank(p, x, y) { const w = p.wood; if ((y & 7) === 7) return w[0]; if ((y & 7) === 0) return w[2]; if ((x === 3 || x === 12) && (y & 7) === 3) return w[0]; return hash(x * 3 + (y >> 3) * 17) > .85 ? w[0] : w[1]; },+ water(p, x, y) { const c = p.cool; return ((x + (y >> 2) * 5) % 16 < 3 && (y & 3) === 1) ? (p.sky[p.sky.length - 1]) : (y < 2 ? c[1] : c[0]); },+ stone(p, x, y) { const s = p.stone, d = Math.min(x, y, 15 - x, 15 - y); return d === 0 ? s[0] : (x === 1 || y === 1) ? s[2] : s[1]; },+};+function _tile(kind) {+ const key = P.name + kind; let t = _TL.get(key); if (t) return t;+ t = new Uint32Array(TS * TS); const g = TILE_GEN[kind], r = i => hash(i * 3.7 + kind.length);+ for (let y = 0; y < TS; y++) for (let x = 0; x < TS; x++) { const c = g(P, x, y, r); t[y * TS + x] = c ? C(c) : 0; }+ _TL.set(key, t); return t;+}+function tile(kind, x, y) { const t = _tile(kind), sx = Math.round(x) - OX, sy = Math.round(y) - OY; if (sx > LW || sy > LH || sx < -TS || sy < -TS) return; for (let j = 0; j < TS; j++) for (let i = 0; i < TS; i++) { const c = t[j * TS + i]; if (c) _p(sx + i, sy + j, c); } }+// tilemap(['..gggg', 'ggdddd'], { g: 'grass', d: 'dirt' }, x0, y0): one char per 16-px tile+function tilemap(rows, legend, x0, y0) { rows.forEach((l, j) => { for (let i = 0; i < l.length; i++) { const k = legend[l[i]]; if (k) tile(k, x0 + i * TS, y0 + j * TS); } }); }++// ---------- backgrounds & parallax ----------+// sky(stops, { y0, y1, soft, par }): vertical bands of palette colours with ordered-dither seams (screen space)+function sky(stops = P.sky, o = {}) {+ const y0 = o.y0 ?? 0, y1 = o.y1 ?? LH, soft = o.soft ?? .55, us = stops.map(C), n = us.length - 1, oy = Math.round(CAMY * (o.par ?? 0));+ for (let y = 0; y < LH; y++) {+ const p = clamp((y + oy - y0) / (y1 - y0)) * n, i = Math.min(n - 1, Math.floor(p)), f = p - i, g = clamp((f - .5) / soft + .5), row = y * LW, by = ((y + oy) & 3) << 2;+ const a = us[i], b = us[i + 1];+ if (g <= 0) FB.fill(a, row, row + LW); else if (g >= 1) FB.fill(b, row, row + LW);+ else for (let x = 0; x < LW; x++) FB[row + x] = BAY4[by | (x & 3)] < g ? b : a;+ }+}+// dithered radial light blob in banded rings (glows, halos, lamp pools)+function glow(x, y, r, c, k = 1, o = {}) {+ const u = C(c), sx = Math.round(x) - OX, sy = Math.round(y) - OY, bands = o.bands ?? 4, pw = o.pow ?? 1.3;+ for (let j = -r; j <= r; j++) { const yy = sy + j; if (yy < KY0 || yy > KY1) continue; const by = ((yy + OY) & 3) << 2;+ for (let i = -r; i <= r; i++) { const xx = sx + i; if (xx < KX0 || xx > KX1) continue; const d = Math.sqrt(i * i + j * j) / r; if (d >= 1) continue;+ const lv = Math.ceil(k * Math.pow(1 - d, pw) * bands) / bands; if (BAY4[by | ((xx + OX) & 3)] < lv) _p(xx, yy, u); } }+}+// light(x, y, r, k): brighten whatever is already there one or two steps along its own ramp (on-palette lighting)+function light(x, y, r, k = 1, o = {}) {+ const sx = Math.round(x) - OX, sy = Math.round(y) - OY, ry = o.ry ?? r;+ for (let j = -ry; j <= ry; j++) { const yy = sy + j; if (yy < 0 || yy >= LH) continue; const by = ((yy + OY) & 3) << 2;+ for (let i = -r; i <= r; i++) { const xx = sx + i; if (xx < 0 || xx >= LW) continue; const d = Math.sqrt((i / r) ** 2 + (j / ry) ** 2); if (d >= 1) continue;+ const lv = Math.ceil(k * (1 - d) * 4) / 4, n = Math.floor(lv) + (BAY4[by | ((xx + OX) & 3)] < lv - Math.floor(lv) ? 1 : 0);+ if (n > 0) { const ii = yy * LW + xx; FB[ii] = shade(FB[ii], Math.min(n, 2)); } } }+}+// shadowAt(x, y, rx, ry, k): darken what's there (contact shadows, vignettes); dithered edge+function shadowAt(x, y, rx, ry = rx * .3, k = 1) {+ const sx = Math.round(x) - OX, sy = Math.round(y) - OY;+ for (let j = -Math.ceil(ry); j <= Math.ceil(ry); j++) { const yy = sy + j; if (yy < 0 || yy >= LH) continue; const by = ((yy + OY) & 3) << 2;+ for (let i = -Math.ceil(rx); i <= Math.ceil(rx); i++) { const xx = sx + i; if (xx < 0 || xx >= LW) continue; const d = (i / (rx + .4)) ** 2 + (j / (ry + .4)) ** 2; if (d > 1) continue;+ if (BAY4[by | ((xx + OX) & 3)] < k * (d < .55 ? 1 : .5)) { const ii = yy * LW + xx; FB[ii] = shade(FB[ii], -1); } } }+}+// vignette(k): darkened, dithered corners (screen space) — use lightly for mood+function vignette(k = .5) { for (let y = 0; y < LH; y++) for (let x = 0; x < LW; x++) { const dx = (x - LW / 2) / (LW / 2), dy = (y - LH / 2) / (LH / 2), d = (dx * dx * .8 + dy * dy) - (1 - k * .6); if (d > 0 && BAY4[((y & 3) << 2) | (x & 3)] < d * 2.2) { const i = y * LW + x; FB[i] = shade(FB[i], -1); } } }++function sunDisc(x, y, r, o = {}) { // sun or moon with banded halo; o.par, o.moon+ layer(o.par ?? 0); const s = o.cols || P.sun;+ if (o.halo !== false) { glow(x, y, Math.round(r * 3.2), s[0], .55); glow(x, y, Math.round(r * 1.9), s[1], .8); }+ disc(x, y, r, s[1]); disc(x - 1, y - 1, r - 1, s[2]);+ if (o.moon) { disc(x + r * .35, y - r * .1, r * .28, s[0]); disc(x - r * .3, y + r * .35, r * .18, s[0]); }+ layer(1);+}+function stars(t, o = {}) {+ layer(o.par ?? .05, 0); const n = o.n ?? 90, sd = o.seed ?? 1, y1 = o.y1 ?? LH * .62, cols = o.cols || P.cool, ts = onStep(t, 6), span = LW + 40;+ for (let i = 0; i < n; i++) {+ const wx = hash(i * 3.13 + sd) * span * 3, sx = ((Math.round(wx - OX) % span) + span) % span - 20, sy = Math.round(hash(i * 7.77 + sd) * y1);+ const big = hash(i * 1.91 + sd) > .86, tw = Math.sin(ts * (2 + hash(i) * 3) + i) > .55;+ const c = C(tw || big ? cols[1] : cols[0]); _p(sx, sy, c);+ if (big && tw) { _p(sx - 1, sy, C(cols[0])); _p(sx + 1, sy, C(cols[0])); _p(sx, sy - 1, C(cols[0])); _p(sx, sy + 1, C(cols[0])); }+ }+ layer(1);+}+// clouds(t, { y, n, seed, par, speed, cols:[shadow, base, light], size }): puffy flat-bottomed pixel clouds that drift+function clouds(t, o = {}) {+ const par = o.par ?? .3; layer(par, par * .5);+ const n = o.n ?? 5, sd = o.seed ?? 3, cols = o.cols || P.cloud, span = o.span ?? LW * 2.4, sp = o.speed ?? 3, sz = o.size ?? 1;+ for (let i = 0; i < n; i++) {+ const r = rnd('cl' + sd + '_' + i), w = (26 + r() * 40) * sz, cy = (o.y ?? 50) + (r() - .5) * (o.dy ?? 40);+ let cx = r() * span + t * sp * (.6 + r() * .6); cx = ((cx - OX + 80) % span + span) % span - 80 + OX;+ const bot = Math.round(cy + 5 * sz), pf = [];+ const k = 3 + Math.floor(r() * 3); for (let j = 0; j < k; j++) { const f = j / (k - 1); pf.push([cx - w / 2 + f * w, cy - Math.sin(f * Math.PI) * 7 * sz - r() * 4 * sz, (6 + Math.sin(f * Math.PI) * 9 + r() * 4) * sz]); }+ clip(-1e5, -1e5, 2e5, bot + 1e5 + 1);+ for (const [x, y, rr] of pf) disc(x + 1, y + 2, rr, cols[0]);+ for (const [x, y, rr] of pf) disc(x, y, rr, cols[1]);+ clip(-1e5, -1e5, 2e5, bot - 2 + 1e5 + 1);+ for (const [x, y, rr] of pf) disc(x - 2, y - 2, rr * .72, cols[2]);+ noclip();+ rect(cx - w / 2 - 6 * sz, bot - 1, w + 12 * sz, 1, cols[0], .5);+ }+ layer(1);+}+// rolling hills silhouette; o: { amp, freq, seed, c, rim (lit top edge colour), rimW, bumps (tree-canopy lumps), par }+function hills(base, o = {}) {+ layer(o.par ?? .4, (o.par ?? .4) * .6);+ const amp = o.amp ?? 16, f = o.freq ?? .012, sd = o.seed ?? 1, u = C(o.c || P.mid[0]), rim = C(o.rim || shade(u, 1)), rw = o.rimW ?? 1, bump = o.bumps || 0, bw = o.bumpW ?? 9;+ for (let sx = 0; sx < LW; sx++) {+ const wx = sx + OX;+ let h = amp * (.6 * Math.sin(wx * f + sd) + .3 * Math.sin(wx * f * 2.3 + sd * 3) + .1 * Math.sin(wx * f * 5.1 + sd * 7));+ if (bump) { const cell = Math.floor(wx / bw), cr = (bw * .5 + hash(cell * 1.3 + sd) * bw * .5) * bump, dx = wx - (cell + .5) * bw; h += Math.sqrt(Math.max(0, cr * cr - dx * dx)) * .9; const c2 = cell + (dx > 0 ? 1 : -1), cr2 = (bw * .5 + hash(c2 * 1.3 + sd) * bw * .5) * bump, dx2 = wx - (c2 + .5) * bw; h = Math.max(h, amp * (.6 * Math.sin(wx * f + sd) + .3 * Math.sin(wx * f * 2.3 + sd * 3)) + Math.sqrt(Math.max(0, cr2 * cr2 - dx2 * dx2)) * .9); }+ const top = Math.round(base - h) - OY;+ for (let y = Math.max(0, top); y < LH; y++) FB[y * LW + sx] = y < top + rw ? rim : u;+ }+ layer(1);+}+// pine forest silhouette; o: { c, rim, par, gap, hmin, hmax, seed }+function forest(base, o = {}) {+ const par = o.par ?? .6; layer(par, par * .6);+ const gap = o.gap ?? 8, sd = o.seed ?? 5, c = o.c || P.mid[0], rim = o.rim, x0 = Math.floor((OX - 20) / gap), x1 = Math.ceil((OX + LW + 20) / gap);+ for (let i = x0; i <= x1; i++) {+ const r = rnd('pine' + sd + '_' + i), h = (o.hmin ?? 16) + r() * ((o.hmax ?? 34) - (o.hmin ?? 16)), x = i * gap + r() * gap * .8, w = h * .42, b = base + r() * 4;+ rect(x - 1, b - 3, 2, 4, c);+ for (let k = 0; k < 3; k++) { const ty = b - h * (.3 + k * .28) - 2, tw = w * (1 - k * .25); poly([[x, ty - h * .34], [x + tw, ty + h * .14], [x - tw, ty + h * .14]], c); if (rim) line(x, ty - h * .34, x - tw + 1, ty + h * .12, rim); }+ }+ rect(OX - 2, base + 2, LW + 4, LH, c);+ layer(1);+}+// city skyline; o: { c, win (lit colour), lit 0..1, par, seed, hmin, hmax }+function city(base, o = {}) {+ const par = o.par ?? .5; layer(par, par * .6);+ const cw = 20, sd = o.seed ?? 7, c = C(o.c || P.far[0]), dk = shade(c, -1), win = C(o.win || P.light[1]), lit = o.lit ?? 0;+ const x0 = Math.floor((OX - 40) / cw), x1 = Math.ceil((OX + LW + 40) / cw);+ for (let i = x0; i <= x1; i++) {+ const r = rnd('bld' + sd + '_' + i), w = 12 + Math.floor(r() * 12), h = (o.hmin ?? 18) + Math.floor(r() * r() * ((o.hmax ?? 70) - (o.hmin ?? 18))), x = i * cw + Math.floor(r() * 6) - 3, y = base - h;+ rect(x, y, w, h + 40, c);+ const roof = r(); if (roof > .7) line(x + 3, y - 1, x + 3, y - 6 - r() * 6, c); else if (roof > .45) rect(x + 2, y - 3, w - 4, 3, c); else if (roof > .3) poly([[x, y], [x + w / 2, y - 6], [x + w, y]], c);+ for (let wy = y + 3; wy < base - 2; wy += 4) for (let wx = x + 2; wx < x + w - 2; wx += 3) {+ const on = hash(i * 91 + wx * 7.1 + wy * 3.3 + sd) < lit; px(wx, wy, on ? win : dk); if (on) px(wx, wy + 1, win);+ }+ }+ layer(1);+}+// ground(topY(x), o): grassy ground following a height function (world coords); lit top edge, tufts, dithered depth.+// o: { c: ramp (default P.grass), deep: colour at depth, tufts 0..1, flowers: [colours], par }+function ground(topY, o = {}) {+ layer(o.par ?? 1); const g = (o.c || P.grass).map(C), n = g.length, deep = C(o.deep || g[0]), tf = o.tufts ?? .35, fl = o.flowers;+ for (let sx = 0; sx < LW; sx++) {+ const wx = sx + OX, top = Math.round(topY(wx)) - OY;+ for (let y = Math.max(0, top); y < LH; y++) {+ const d = y - top, wy = y + OY; let c;+ if (d === 0) c = g[n - 1]; else if (d < 3) c = g[n - 2]; else if (d < 7) c = g[n - 3];+ else { const k = clamp((d - 7) / 26); c = BAY4[((wy & 3) << 2) | (wx & 3)] < k ? (k > .7 && n > 3 ? deep : g[Math.max(0, n - 4)]) : g[n - 3]; }+ if (d > 3 && hash(wx * 12.9 + wy * 78.2) > .96) c = shade(c, 1);+ FB[y * LW + sx] = c;+ }+ const hh = hash(wx * 3.7 + 11);+ if (hh < tf && top - 1 >= 0 && top - 1 < LH) { FB[(top - 1) * LW + sx] = g[n - 2]; if (hh < tf * .35 && top - 2 >= 0) FB[(top - 2) * LW + sx] = g[n - 1]; }+ if (fl && hash(wx * 5.3 + 2) > .965 && top - 2 >= 0 && top < LH) { const fc = C(fl[Math.floor(hash(wx) * fl.length)]); FB[(top - 2) * LW + sx] = fc; if (sx > 0) FB[(top - 2) * LW + sx - 1] = shade(fc, 1); FB[(top - 1) * LW + sx] = g[n - 3]; }+ }+ layer(1);+}+// a big leafy tree (drawn as an outlined sprite); returns { canopy: [cx, cy, r] }. o: { h, r, sway, t, leaf, wood, seed }+function tree(x, y, o = {}) {+ const h = o.h ?? 70, R = o.r ?? 42, lf = o.leaf || P.grass, wd = o.wood || P.wood, sd = o.seed ?? 2, sw = Math.round((o.sway ?? 1) * Math.sin(onStep(o.t || 0, 4) * 1.7));+ const cx = x, cy = y - h - R * .35;+ beginSpr();+ poly([[x - 5, y], [x - 9, y + 1], [x - 4, y - h * .5], [x - 3, y - h], [x + 4, y - h], [x + 4, y - h * .5], [x + 8, y + 1], [x + 4, y]], wd[1]);+ line(x + 2, y - 2, x + 3, y - h * .8, wd[0], 2);+ line(x - 2, y - h * .55, x - R * .55, y - h - 4, wd[1], 3); line(x + 2, y - h * .7, x + R * .5, y - h - 8, wd[1], 3);+ part();+ const r = rnd('tree' + sd), blobs = [];+ for (let i = 0; i < 9; i++) { const a = i / 9 * TAU + r(), d = R * (.35 + r() * .45); blobs.push([cx + Math.cos(a) * d * 1.15, cy + Math.sin(a) * d * .75, R * (.32 + r() * .2)]); }+ blobs.push([cx, cy, R * .55]);+ blobs.sort((a, b) => a[1] - b[1]);+ for (const [bx, by, br] of blobs) oval(bx + sw * (by < cy ? 1 : 0), by + 2, br, br * .85, lf[1]);+ for (const [bx, by, br] of blobs) oval(bx + sw * (by < cy ? 1 : 0) - 1, by - 1, br * .9, br * .75, lf[2]);+ for (const [bx, by, br] of blobs) if (by < cy + R * .2) oval(bx + sw * (by < cy ? 1 : 0) - br * .3, by - br * .35, br * .45, br * .3, lf[3]);+ for (let i = 0; i < 30; i++) { const a = r() * TAU, d = r() * R * .9; px(cx + Math.cos(a) * d * 1.1, cy + Math.sin(a) * d * .7 - 2, lf[4] || lf[3]); }+ endSpr({ tint: null });+ return { canopy: [cx, cy, R] };+}+function bush(x, y, w = 24, o = {}) {+ const lf = o.leaf || P.grass; beginSpr();+ const r = rnd('bush' + x); for (let i = 0; i < 4; i++) { const f = i / 3; oval(x - w / 2 + f * w, y - 5 - Math.sin(f * Math.PI) * 5, w * .28, w * .24, lf[2]); }+ for (let i = 0; i < 4; i++) { const f = i / 3; oval(x - w / 2 + f * w - 1, y - 7 - Math.sin(f * Math.PI) * 5, w * .15, w * .1, lf[3]); }+ rect(x - w / 2 - 2, y - 2, w + 4, 2, lf[1]);+ if (o.berries) for (let i = 0; i < 5; i++) px(x - w / 2 + r() * w, y - 4 - r() * 8, o.berries);+ endSpr({ tint: null });+}++// ---------- weather & particles (all pure functions of t) ----------+function rain(t, o = {}) {+ layer(o.par ?? 0); const n = o.n ?? 140, c = C(o.c || P.cool[1]), c2 = shade(c, 1), ts = onStep(t, o.fps ?? 24), sl = o.slant ?? 2, gy = o.ground;+ for (let i = 0; i < n; i++) {+ const sp = 260 + hash(i * 1.7) * 120, span = LH + 30, y = ((hash(i * 3.3) * span + ts * sp) % span) - 15, x = ((hash(i * 5.1) * (LW + 40) - y * sl / 4 - OX) % (LW + 40) + LW + 40) % (LW + 40) - 20;+ if (gy != null && y > gy - OY) { const a = (hash(i * 9.1) * 3 + ts * 12) % 3 | 0; if (a < 2) { _p(Math.round(x) - 1 - a, gy - OY - 1 - a, c2); _p(Math.round(x) + 1 + a, gy - OY - 1 - a, c2); } continue; }+ line(x + OX, y + OY, x + OX - sl, y + OY + 4, hash(i) > .7 ? c2 : c);+ }+ layer(1);+}+function snow(t, o = {}) {+ layer(o.par ?? .2); const n = o.n ?? 90, c = C(o.c || P.cloud[2]), ts = onStep(t, o.fps ?? 12);+ for (let i = 0; i < n; i++) {+ const sp = 14 + hash(i * 1.7) * 18, span = LH + 10, y = ((hash(i * 3.3) * span + ts * sp) % span) - 5, x = ((hash(i * 5.1) * (LW + 20) + Math.sin(ts * 1.3 + i) * 4 - OX) % (LW + 20) + LW + 20) % (LW + 20) - 10;+ const big = hash(i * 7.3) > .75; _p(Math.round(x), Math.round(y), c); if (big) { _p(Math.round(x) + 1, Math.round(y), c); _p(Math.round(x), Math.round(y) + 1, c); _p(Math.round(x) + 1, Math.round(y) + 1, shade(c, -1)); }+ }+ layer(1);+}+// 4-point twinkles popping inside a box (world): sparkles(t, x, y, w, h, { n, c, seed, rate })+function sparkles(t, x, y, w, h, o = {}) {+ const n = o.n ?? 8, c = o.c || P.light[2], c2 = o.c2 || P.light[1], ts = onStep(t, 12), sd = o.seed ?? 1, per = o.period ?? .7;+ for (let i = 0; i < n; i++) {+ const ph = hash(i * 1.37 + sd) * per, cyc = Math.floor((ts + ph) / per), a = ((ts + ph) % per) / per, r = rnd('sp' + sd + i + '_' + cyc);+ const sx = x + r() * w, sy = y + r() * h, f = Math.floor(a * 7); if (f > 5) continue;+ const s = [0, 1, 2, 3, 2, 1][f];+ px(sx, sy, s >= 2 ? c : c2);+ for (let k = 1; k <= s; k++) { const cc = k === s ? c2 : c; px(sx - k, sy, cc); px(sx + k, sy, cc); px(sx, sy - k, cc); px(sx, sy + k, cc); }+ }+}+function fireflies(t, x, y, w, h, o = {}) {+ const n = o.n ?? 10, c = o.c || '#d8ff7a', ts = onStep(t, 12);+ for (let i = 0; i < n; i++) {+ const r = rnd('ff' + i + (o.seed ?? 0)), fx = x + r() * w + Math.sin(ts * (.6 + r()) + i) * 8, fy = y + r() * h + Math.sin(ts * (.9 + r()) + i * 2) * 5;+ const on = Math.sin(ts * (1.5 + r() * 2) + i * 3) > -.2; if (!on) continue;+ glow(fx, fy, 4, shade(c, -1), .7, { bands: 2 }); px(fx, fy, c);+ }+}+// small birds flapping across: birds(t, { y, n, speed, c, par, seed })+function birds(t, o = {}) {+ layer(o.par ?? .5); const n = o.n ?? 4, c = o.c || P.ink, ts = onStep(t, 8), sp = o.speed ?? 22, sd = o.seed ?? 1;+ for (let i = 0; i < n; i++) {+ const x = (o.x ?? 0) + ts * sp + i * 11 - (i % 2) * 4 + OX * 0, y = (o.y ?? 60) + (i % 3) * 5 + Math.sin(ts * 2 + i) * 2, up = (Math.floor(ts * 8) + i) % 2;+ if (up) { px(x - 2, y - 1, c); px(x - 1, y, c); px(x, y, c); px(x + 1, y, c); px(x + 2, y - 1, c); }+ else { px(x - 2, y + 1, c); px(x - 1, y, c); px(x, y, c); px(x + 1, y, c); px(x + 2, y + 1, c); }+ }+ layer(1);+}+function petals(t, o = {}) {+ layer(o.par ?? .8); const n = o.n ?? 20, cs = o.cols || [P.accent[2], P.accent[1]], ts = onStep(t, 12);+ for (let i = 0; i < n; i++) {+ const sp = 12 + hash(i) * 14, span = LH + 20, y = ((hash(i * 3.3) * span + ts * sp) % span) - 10, x = ((hash(i * 5.1) * (LW + 40) + ts * 18 + Math.sin(ts * 2 + i) * 6) % (LW + 40)) - 20 + OX;+ const c = cs[i % cs.length]; px(x, y + OY, c); if ((Math.floor(ts * 6) + i) % 3) px(x + 1, y + OY, shade(c, -1));+ }+ layer(1);+}++// dust puff (landings, skids, poofs): age in s since the impact; o: { n, c, spread, dir }+function puff(age, x, y, o = {}) {+ if (age < 0 || age > .5) return; const n = o.n ?? 6, c = o.c || P.paper, s = onStep(age, 12), k = s / .5, sp = o.spread ?? 14;+ for (let i = 0; i < n; i++) {+ const side = (i % 2 ? 1 : -1) * (o.dir ? Math.sign(o.dir) * (i % 3 ? 1 : -1) : 1), f = .4 + hash(i * 3.7) * .6;+ const px_ = x + side * sp * f * easeOut(k * 1.4), py_ = y - 1 - 5 * f * easeOut(k) + 3 * k * k;+ disc(px_, py_, Math.max(0, Math.round(1 + 2 * f * Math.sin(Math.min(1, k * 1.6) * Math.PI))), c, qd(1 - k * k, 4));+ }+}+// measure(fn): run a draw call without drawing (e.g. to get a character's hand position at another time)+function measure(fn) { const k = [KX0, KY0, KX1, KY1]; KX0 = 1; KX1 = 0; KY0 = 1; KY1 = 0; const s = SPRM; let r; try { r = fn(); } finally { [KX0, KY0, KX1, KY1] = k; SPRM = s; } return r; }++// ---------- emotes & speech bubbles ----------+const EMO_ART = {+ '!': ['.kk.', '.kk.', '.kk.', '.kk.', '....', '.kk.'],+ '?': ['.kkk.', 'kk.kk', '...kk', '..kk.', '..k..', '.....', '..k..'],+ '!?': ['kk.kkk.', 'kkkk.kk', 'kk...kk', 'kk..kk.', 'kk..k..', '.......', 'kk..k..'],+ heart: ['.rr.rr.', 'rwrrrrr', 'rrrrrrr', '.rrrrr.', '..rrr..', '...r...'],+ sweat: ['..b..', '..b..', '.bbb.', 'bbbbb', 'bwbbb', '.bbb.'],+ anger: ['..r.r..', '.rr.rr.', 'rr...rr', '.......', 'rr...rr', '.rr.rr.', '..r.r..'],+ dots: ['.......', '.......', '.......', 'k..k..k'],+ note: ['..kkk', '..k.k', '..k..', '..k..', 'kkk..', 'kkk..'],+ bulb: ['.yyy.', 'yywyy', 'yyyyy', 'yyyyy', '.yyy.', '.kkk.', '.kkk.'],+ star: ['...y...', '..yyy..', 'yyywyyy', '.yyyyy.', '..yyy..', '.yy.yy.', 'y.....y'],+ spiral: ['.kkkk.', 'k....k', 'k.kk.k', 'k.k..k', 'k...k.', '.kkk..'],+};+const EMO_COL = { k: '#2a1f3a', r: '#e8485c', w: '#ffffff', b: '#5fb8f0', y: '#ffd35e' };+// emote(kind, x, y, { age, bubble, out }): pops in over steps (burst → overshoot → settle); x,y = bubble bottom-left+// point (where it attaches to the head). Kinds: ! ? !? heart sweat anger dots note bulb star spiral zzz+function emote(kind, x, y, o = {}) {+ const age = o.age ?? 1, f = Math.floor(onStep(age, 12) * 12); if (age < 0) return;+ if (o.out != null && o.out >= 1) return;+ x = Math.round(x); y = Math.round(y);+ if (f < 1) { beginSpr(); const c = '#fff8e8'; px(x + 4, y - 6, c); px(x + 2, y - 8, c); px(x + 6, y - 8, c); px(x + 4, y - 10, c); endSpr({ tint: null }); return; }+ const bob = f < 2 ? -3 : f < 3 ? -1 : 0, loop = onStep(age, 4);+ if (kind === 'zzz') { beginSpr(); const Z = ['kkkk', '..k.', '.k..', 'kkkk']; for (let i = 0; i < 3; i++) { const a = (loop * .5 + i / 3) % 1; sprite(Z, { k: '#dfe8ff' }, x + 3 + i * 4 + Math.sin(a * 6) * 1, y - 4 - a * 16, { z: 1 }); } endSpr({ tint: null, k: -6 }); return; }+ const art = EMO_ART[kind] || EMO_ART['!'], s = _parse(art), bw = Math.max(11, s.w + 6), bh = s.h + 6;+ const bx = x, by = y - bh - 3 + bob;+ const pump = kind === 'heart' && Math.floor(loop * 2) % 2 ? 1 : 0;+ const dy = kind === 'sweat' ? (Math.floor(loop * 2) % 3) : 0;+ beginSpr();+ if (o.bubble !== false) {+ const wc = o.bg || '#fff8e8'; rect(bx + 1, by, bw - 2, bh, wc); rect(bx, by + 1, bw, bh - 2, wc);+ poly([[bx + 2, by + bh - 1], [bx + 7, by + bh - 1], [bx + 1, by + bh + 3]], wc);+ part(false);+ rect(bx + 1, by + bh - 1, bw - 2, 1, shade(wc, -1));+ }+ part(false);+ sprite(art, EMO_COL, bx + Math.floor(bw / 2), by + 3 + s.h + (o.bubble === false ? 0 : 0) + dy - pump, { ax: .5, ay: 1, z: 1 });+ endSpr({ tint: null, k: o.bubble === false ? -1 : -3 });+}++// ---------- tiny in-world pixel font (3×5, A–Z 0–9 !?.-:/) for signs, scores, SFX ----------+const FONT35 = {+ A: '010101111101101', B: '110101110101110', C: '011100100100011', D: '110101101101110', E: '111100110100111', F: '111100110100100',+ G: '011100101101011', H: '101101111101101', I: '111010010010111', J: '001001001101010', K: '101101110101101', L: '100100100100111',+ M: '101111111101101', N: '110101101101101', O: '010101101101010', P: '110101110100100', Q: '010101101110011', R: '110101110101101',+ S: '011100010001110', T: '111010010010010', U: '101101101101111', V: '101101101101010', W: '101101111111101', X: '101101010101101',+ Y: '101101010010010', Z: '111001010100111', 0: '111101101101111', 1: '010110010010111', 2: '110001010100111', 3: '110001010001110',+ 4: '101101111001001', 5: '111100110001110', 6: '011100111101111', 7: '111001010010010', 8: '111101111101111', 9: '111101111001110',+ '!': '010010010000010', '?': '110001010000010', '.': '000000000000010', '-': '000000111000000', ':': '000010000010000', '/': '001001010100100', ' ': '000000000000000',+};+// tinyText(s, x, y, c, { z, align, shadow }): (x, y) = top-left (align 'center' centres on x). Returns width in px.+function tinyText(s, x, y, c, o = {}) {+ const z = o.z || 1, str = String(s).toUpperCase(), w = (str.length * 4 - 1) * z, x0 = Math.round(o.align === 'center' ? x - w / 2 : x);+ for (const [dd, cc] of o.shadow ? [[z, o.shadow], [0, c]] : [[0, c]])+ for (let n = 0; n < str.length; n++) { const g = FONT35[str[n]] || FONT35['?']; for (let k = 0; k < 15; k++) if (g[k] === '1') rect(x0 + (n * 4 + k % 3) * z + dd, y + Math.floor(k / 3) * z + dd, z, z, cc); }+ return w;+}++// ---------- transitions (screen space; call after drawing the shot) ----------+// dissolve(k, c): ordered-dither fade to colour c (k: 0 = none, 1 = solid), 64 levels+function dissolve(k, c = P.ink) { if (k <= 0) return; const u = C(c); if (k >= 1) return FB.fill(u); for (let y = 0; y < LH; y++) { const r = (y & 7) << 3, row = y * LW; for (let x = 0; x < LW; x++) if (BAY8[r | (x & 7)] < k) FB[row + x] = u; } }+// iris(k, x, y, { c, shape: 'circle'|'diamond'|'square', edge }): k = 0 open, 1 closed around WORLD point (x,y)+function iris(k, x, y, o = {}) {+ if (k <= 0) return; const u = C(o.c || P.ink), sx = Math.round(x) - OX, sy = Math.round(y) - OY, sh = o.shape || 'circle';+ const [vx, vy, vw, vh] = viewRect(), far = Math.max(Math.hypot(Math.max(sx - vx, vx + vw - sx), Math.max(sy - vy, vy + vh - sy)), 1) * (sh === 'diamond' ? 1.45 : 1), R = far * (1 - ease(k)), e = o.edge ?? 4;+ for (let y = 0; y < LH; y++) for (let x = 0; x < LW; x++) {+ const dx = x - sx, dy = y - sy, d = sh === 'diamond' ? Math.abs(dx) + Math.abs(dy) : sh === 'square' ? Math.max(Math.abs(dx), Math.abs(dy) * 1.78) : Math.sqrt(dx * dx + dy * dy);+ const v = (d - R) / e; if (v > 1 || (v > 0 && BAY4[((y & 3) << 2) | (x & 3)] < v)) FB[y * LW + x] = u;+ }+}+// diamonds(k, { c, size, dir }): grid of diamonds that grow to cover the screen, staggered along dir ('right'|'left'|'down'|'up'|'center')+// visible part of the low-res buffer (the whole buffer, or the punched-in window)+const viewRect = () => PUNCH ? [PUNCH.sx, PUNCH.sy, LW / PUNCH.z, LH / PUNCH.z, PUNCH.z] : [0, 0, LW, LH, 1];+function diamonds(k, o = {}) {+ if (k <= 0) return; const [vx, vy, vw, vh, z] = viewRect(), u = C(o.c || P.ink), s = (o.size ?? 20) / z, dir = o.dir || 'right', sp = .9;+ for (let y = vy; y < vy + vh; y++) for (let x = vx; x < vx + vw; x++) {+ const lx = x - vx, ly = y - vy, cx = Math.floor(lx / s), cy = Math.floor(ly / s), gx = (cx + .5) * s, gy = (cy + .5) * s;+ const f = dir === 'right' ? gx / vw : dir === 'left' ? 1 - gx / vw : dir === 'down' ? gy / vh : dir === 'up' ? 1 - gy / vh : Math.hypot(gx - vw / 2, gy - vh / 2) / Math.hypot(vw / 2, vh / 2);+ const loc = clamp(k * (1 + sp) - f * sp), d = (Math.abs(lx + .5 - gx) + Math.abs(ly + .5 - gy)) / s;+ if (loc > 0 && d <= loc + .001) FB[y * LW + x] = u;+ }+}+// blocks(k, { c, size, dir, stagger }): chunky stair-stepped slide, rows staggered (dir 'right'|'left')+function blocks(k, o = {}) {+ if (k <= 0) return; const [vx, vy, vw, vh, z] = viewRect(), u = C(o.c || P.ink), b = Math.max(2, Math.round((o.size ?? 18) / z)), sp = .5, rows = Math.ceil(vh / b), cols = Math.ceil(vw / b);+ for (let r = 0; r < rows; r++) {+ const sg = o.stagger === 'random' ? hash(r * 3.1) : r / rows, e = Math.min(vw, Math.floor(clamp(k * (1 + sp) - sg * sp) * (cols + 1)) * b);+ for (let y = vy + r * b; y < Math.min(vy + vh, vy + (r + 1) * b); y++) { if (o.dir === 'left') FB.fill(u, y * LW + vx + vw - e, y * LW + vx + vw); else FB.fill(u, y * LW + vx, y * LW + vx + e); }+ }+}+// crossDither(k, drawA, drawB): dither-dissolve from one full drawing to another (both drawn this frame)+function crossDither(k, drawA, drawB) {+ drawA(); FB2.set(FB); drawB();+ for (let y = 0; y < LH; y++) { const r = (y & 7) << 3, row = y * LW; for (let x = 0; x < LW; x++) if (BAY8[r | (x & 7)] >= k) FB[row + x] = FB2[row + x]; }+}++// ---------- pixel captions (drawn at full res on the overlay, but rasterised on a pixel grid) ----------+// Text is rendered at its native pixel size on a tiny canvas, alpha-thresholded (no anti-aliasing), outlined by one+// font pixel and blown up ×k with nearest-neighbour → crisp pixel lettering. Latin runs use "Press Start 2P", CJK runs+// "DotGothic16" (fallback "Noto Sans TC", thresholded so it still reads as pixels). Declare every string you'll show+// with useText('...') at load time so its glyphs are fetched before rendering.+let PXTEXT = 'Aa0!?';+function useText(s) { PXTEXT += s; }+window.EXTRA_FONTS = [['16px "DotGothic16"', '字あA'], ['16px "Press Start 2P"', 'A'], ['16px "Noto Sans TC"', '字']];+const _TXC = makeCanvas(1600, 48), _TXX = _TXC.getContext('2d', { willReadFrequently: true }), _TXCACHE = new Map();+const _isCJK = ch => /[⺀-鿿豈-- -〿-ヿ가-]/.test(ch);+function _runs(s) { const out = []; for (const ch of s) { const cj = _isCJK(ch); if (out.length && out[out.length - 1].cj === cj) out[out.length - 1].s += ch; else out.push({ cj, s: ch }); } return out; }+// → { canvas, w, h } native-size pixel text with outline & drop shadow baked in+function pxTextImg(s, o = {}) {+ const key = s + '|' + (o.fg || '') + (o.ol || '') + (o.sh || ''); let r = _TXCACHE.get(key); if (r) return r;+ const X = _TXX, fs = 24, pad = 3; X.clearRect(0, 0, _TXC.width, _TXC.height); X.textBaseline = 'alphabetic'; X.fillStyle = '#fff';+ let x = pad; for (const run of _runs(s)) { X.font = run.cj ? `${fs}px "DotGothic16", "Noto Sans TC", sans-serif` : `16px "Press Start 2P", "DotGothic16", monospace`; X.fillText(run.s, x, pad + 21); x += X.measureText(run.s).width; }+ const w = Math.ceil(x + pad), h = fs + pad * 2 + 1, id = X.getImageData(0, 0, w, h), d = id.data, m = new Uint8Array(w * h);+ for (let i = 0; i < w * h; i++) m[i] = d[i * 4 + 3] > 140 ? 1 : 0;+ const cv = makeCanvas(w, h), cx = cv.getContext('2d'), oi = cx.createImageData(w, h), od = new Uint32Array(oi.data.buffer);+ const fg = C(o.fg || '#fff8e8'), ol = C(o.ol || '#1d1b2e'), sh = C(o.sh || '#1d1b2e');+ for (let y = 0; y < h; y++) for (let xx = 0; xx < w; xx++) {+ const i = y * w + xx; if (m[i]) { od[i] = fg; continue; }+ let n = 0; for (let b = -1; b <= 1; b++) for (let a = -1; a <= 1; a++) { const X2 = xx + a, Y2 = y + b; if (X2 >= 0 && Y2 >= 0 && X2 < w && Y2 < h && m[Y2 * w + X2]) n = 1; }+ if (n) od[i] = ol; else if (y > 1 && xx > 0 && m[(y - 2) * w + xx - 1]) od[i] = sh;+ }+ cx.putImageData(oi, 0, 0); r = { canvas: cv, w, h }; _TXCACHE.set(key, r); return r;+}+// pxText(c, s, x, y, { k: 3, align: 'center', fg, ol }) on the full-res overlay canvas c; (x, y) = top anchor in screen px+function pxText(c, s, x, y, o = {}) {+ const k = o.k ?? 2, im = pxTextImg(s, o), w = im.w * k, xx = o.align === 'left' ? x : o.align === 'right' ? x - w : x - w / 2;+ c.save(); c.imageSmoothingEnabled = false; c.drawImage(im.canvas, Math.round(xx / k) * k, Math.round(y / k) * k, w, im.h * k); c.restore(); return w;+}+// say(c, t, t0, t1, text, { name, y, k, cps, box }): RPG dialogue window with typewriter reveal on the overlay.+// k (default 3) keeps text ≈ 5.5% of frame height, readable on a phone; that fits ≈ 20 CJK / 34 Latin chars per line.+// Opens in 3 steps, types at cps chars/s, blinks a ▼ when done, closes in 3 steps at t1.+function say(c, t, t0, t1, s, o = {}) {+ if (t < t0 || t > t1) return; const U4 = PXS, k = o.k ?? 3, cps = o.cps ?? 16, chars = [...s];+ const open = Math.min(1, Math.floor((t - t0) * 24) / 3), close = Math.min(1, Math.floor((t1 - t) * 24) / 3), g = Math.min(open, close);+ const full = pxTextImg(s, o), bw = Math.max(W * .42, full.w * k + 26 * U4), bh = full.h * k + 16 * U4 * .75, cx = W / 2, y = o.y ?? (H - bh - 14 * U4);+ const hh = Math.max(U4 * 3, Math.round(bh * g / U4) * U4), by = Math.round((y + (bh - hh) / 2) / U4) * U4, bx = Math.round((cx - bw / 2) / U4) * U4, bW = Math.round(bw / U4) * U4;+ const box = o.box || ['#1d1b2e', '#3a3560', '#fff8e8'];+ c.save(); c.fillStyle = box[2]; c.fillRect(bx + U4, by, bW - 2 * U4, hh); c.fillRect(bx, by + U4, bW, hh - 2 * U4);+ c.fillStyle = box[0]; c.fillRect(bx + 2 * U4, by + U4, bW - 4 * U4, hh - 2 * U4); c.fillRect(bx + U4, by + 2 * U4, bW - 2 * U4, hh - 4 * U4);+ c.fillStyle = box[1]; c.fillRect(bx + 2 * U4, by + hh - 3 * U4, bW - 4 * U4, U4);+ if (g >= 1) {+ const n = Math.min(chars.length, Math.floor((t - t0 - .12) * cps)), shown = chars.slice(0, Math.max(0, n)).join('');+ if (shown) pxText(c, shown, bx + 7 * U4, by + (hh - full.h * k) / 2, { ...o, k, align: 'left' });+ if (n >= chars.length && Math.floor(t * 3) % 2 === 0) { c.fillStyle = box[2]; const ax = bx + bW - 7 * U4, ay = by + hh - 7 * U4; c.fillRect(ax - U4, ay - U4, 5 * U4, U4); c.fillRect(ax, ay, 3 * U4, U4); c.fillRect(ax + U4, ay + U4, U4, U4); }+ if (o.name) { const nm = pxTextImg(o.name, { fg: o.nameFg || '#ffd35e' }); const nw = Math.round(nm.w * 2 / U4 + 5) * U4, nx = bx + 4 * U4, ny = by - Math.round(nm.h * 2 / U4) * U4 + U4; c.fillStyle = box[2]; c.fillRect(nx, ny, nw, nm.h * 2 + U4); c.fillStyle = box[0]; c.fillRect(nx + U4, ny + U4, nw - 2 * U4, nm.h * 2 - U4); pxText(c, o.name, nx + 3 * U4, ny + U4 * .5, { k: 2, fg: o.nameFg || '#ffd35e', align: 'left' }); }+ }+ c.restore();+}++// ---------- time helpers ----------+const st = t => onStep(t, 12); // sprite time: poses, walk frames, blinks change 12×/s+const vel = (f, t, dt = 1 / 12) => (f(t + dt) - f(t - dt)) / (2 * dt); // velocity of any pure position function++// ---------- engine hooks ----------+window.ENGINE = {+ crisp: true,+ async setup() {+ const fams = ['16px "DotGothic16"', '16px "Noto Sans TC"', '16px "Press Start 2P"'];+ await Promise.all(fams.map(f => document.fonts.load(f, PXTEXT).catch(() => null)));+ },+ begin(t) { P = PALS.day; SPRM = false; PUNCH = null; noclip(); camAt(LW / 2, LH / 2); FB.fill(C(P.ink)); G = LOX; },+ end(t) {+ if (SPRM) endSpr();+ LOX.putImageData(IMG, 0, 0);+ OUT.setTransform(1, 0, 0, 1, 0, 0); OUT.imageSmoothingEnabled = false;+ if (PUNCH) OUT.drawImage(LOC, PUNCH.sx, PUNCH.sy, LW / PUNCH.z, LH / PUNCH.z, 0, 0, W, H);+ else OUT.drawImage(LOC, 0, 0, W, H);+ G = OUT;+ },+};diff --git a/.claude/skills/pixel-art/template/src/scenes/demo.js b/.claude/skills/pixel-art/template/src/scenes/demo.jsnew file mode 100644index 0000000..f62654a--- /dev/null+++ b/.claude/skills/pixel-art/template/src/scenes/demo.js@@ -0,0 +1,122 @@+// demo.js — "The Kite" (10 s, 2 shots). An example, not a template: write your own story, world and shots.+// A 0.0–5.6 day dither fade in · camera pans across the valley to a tree where Pip's kite is stuck · Pip hops,+// fails, goes sad · Juno trots in, spots it (!), crouches, JUMPS, grabs it, lands (squash, dust),+// offers it · Pip: surprised → love · diamond wipe out+// B 5.6–10.0 dusk diamond wipe in on the kite flying free in the sunset · camera tilts down the string to the pair ·+// Pip turns to Juno: caption "謝謝你!Thank you!" · Juno goes shy · iris closes on the two+(() => {+ useText('謝謝你!Thank you!PIP');+ const A_END = 5.6;++ // ---------------- shot A: the stuck kite ----------------+ const gA = x => 212 + 5 * Math.sin(x * .013) + 3 * Math.sin(x * .031 + 1);+ const DECEL = x => Math.sin(x * Math.PI / 2);+ const JX0 = 305, JX1 = 596, JUMP0 = 3.55, JUMP1 = 4.05, JLAND = 602, PIPX = 630, TREEX = 660;+ const junoX = t => t < 3.1 ? walkTo(t, 1.85, 3.1, JX0, JX1, 22, DECEL).x+ : lerp(JX1, JLAND, ease(seg(t, JUMP0, JUMP1)));+ const junoDy = t => jump(t, JUMP0, JUMP1, 22).dy;+ const junoPose = t => {+ const s = st(t), w = walkTo(t, 1.85, 3.1, JX0, JX1, 22, DECEL), x = junoX(t), j = jump(s, JUMP0, JUMP1, 22);+ const air = s > JUMP0 && s < JUMP1;+ const face = act(s, [[0, 'neutral'], [3.12, 'surprised', { look: [1, -1] }], [3.4, 'determined', { look: [1, -1], emote: null, take: 0 }], [4.15, 'happy', { look: [1, 0], take: .6 }]]);+ // arms: swing while walking, ready at crouch, reach forward-up in the air, hold the kite up, then offer it to Pip+ let arm = [ARM.down, ARM.down], bend = [.25, .25];+ if (s > 3.4 && s < JUMP0) arm = [-1.0, -1.0]; // crouch: arms back+ if (s >= JUMP0 && s < 4.2) { arm = [kf(s, [[JUMP0, -.2], [JUMP0 + .15, .5], [4.1, -.6]]), kf(s, [[JUMP0, .4], [JUMP0 + .12, 1.05]], easeOut)]; bend = [.4, .55]; }+ if (s >= 4.2) { arm = [ARM.down, kf(s, [[4.2, .9], [4.5, -.35]], easeOut)]; bend = [.25, kf(s, [[4.2, .3], [4.5, .5]])]; }+ return { x, y: gA(x), view: s < 3.12 ? 'side' : s < 3.4 ? 'q' : s < 4.2 ? 'front' : 'side', walk: w.walk, dy: Math.round(j.dy), sq: j.sq + (face.sq || 0) * (air ? 0 : 1), air: air && s > JUMP0 + .05 && s < JUMP1 - .06, arm, bend, face, drag: clamp(-vel(junoDy, s) / 120, -1, 1) };+ };+ const GRAB = 3.8, CLOSE_A = 2.95, CLOSE_B = 7.2;+ // where the kite hangs in the tree = Juno's hand at the jump apex (measured, so the grab always connects)+ let K = null;+ const kiteHome = () => K || (K = measure(() => { const p = junoPose(GRAB); return juno(p.x, p.y, { ...p.face, ...p, face: p.face.face, t: GRAB }).hands[1]; }));++ function shotA(t, lt) {+ pal('day');+ const s = st(t), cx = lerp(250, 572, ease(seg(t, 0, 1.7)));+ const [shx, shy] = t > JUMP1 && t < JUMP1 + .2 ? shake(t, 1.2) : [0, 0];+ camAt(cx + shx, 135 + shy);+ const close = t >= CLOSE_A; // cut on action (Juno arriving) to a 2× medium shot+ sky(P.sky, { soft: .45 });+ sunDisc(70, 42, 11, { par: 0 });+ clouds(t, { y: 46, n: 6, par: .12, speed: 4, dy: 36 });+ hills(176, { c: P.far[0], rim: P.far[1], amp: 16, freq: .009, par: .18, seed: 2 });+ hills(196, { c: P.mid[0], rim: P.mid[1], amp: 10, freq: .015, par: .4, seed: 5, bumps: .9, bumpW: 11 });+ forest(206, { c: P.mid[0], rim: P.mid[1], par: .62, gap: 11, hmin: 14, hmax: 26, seed: 3 });+ birds(t, { x: 150, y: 70, n: 3, par: .3, speed: 14, c: '#3a4a7a' });+ ground(gA, { flowers: [P.accent[2], P.light[1], '#fff8e8'], tufts: .4 });+ bush(TREEX + 46, gA(TREEX + 46) + 1, 26);+ tree(TREEX, gA(TREEX) + 1, { h: 62, r: 46, t, seed: 4 });+ bush(470, gA(470) + 1, 20, { berries: P.accent[1] });++ // Pip: two failed hops reaching up → sad → surprised → love (hearts) + a happy hop+ const pj = t < 1.62 ? jump(s, 1.25, 1.5, 7) : t < 3 ? jump(s, 1.68, 1.93, 8) : jump(s, 4.95, 5.25, 9);+ const pf = act(s, [[0, 'determined', { look: [1, -1], emote: null }], [2.05, 'sad', { look: [1, -1] }], [4.38, 'surprised', { look: [1, 0] }], [4.72, 'love', { look: [1, 0] }]]);+ const reach = (t > 1.1 && t < 2.05) ? [1.1, 1.3] : t > 4.72 ? [.5 + .3 * Math.sin(s * 9), .9] : t > 4.38 ? [ARM.low, .2] : [ARM.low, ARM.low];+ footShadow(PIPX, gA(PIPX), 11 + Math.round(pj.dy * .2));+ pip(PIPX, gA(PIPX), { ...pf, t: s, flip: true, view: 'q', emoteSide: 1, dy: Math.round(pj.dy), sq: pj.sq + pf.sq, air: pj.dy < -2, arm: reach, drag: clamp(-vel(u => (u < 1.62 ? jump(u, 1.25, 1.5, 7) : jump(u, 1.68, 1.93, 8)).dy, s) / 60, -1, 1), seed: 3 });++ // Juno+ const p = junoPose(t), held = s >= GRAB;+ const home = kiteHome();+ if (!held) PROP.kite(home[0] + Math.round(Math.sin(s * 3) * .6), home[1] - 9, { hang: true, t: s, tilt: -.25 + .05 * Math.sin(s * 5), tail: [.3, 1] });+ if (t >= 1.85) {+ footShadow(p.x, gA(p.x), 12 + Math.round(p.dy * .25));+ juno(p.x, p.y, { ...p.face, ...p, face: p.face.face, t: s, seed: 1, hold: [null, held ? (hx, hy) => PROP.kite(hx + Math.round(8 * seg(s, 4.2, 4.5)), hy - 9 + Math.round(1 * seg(s, 4.2, 4.5)), { hang: true, t: s, tilt: s < 4.3 ? -.25 : lerp(-.25, .2, seg(s, 4.25, 4.55)), tail: [-.4, 1] }) : null] });+ }+ if (!held) sparkles(t, home[0] - 10, home[1] - 20, 20, 18, { n: 3, seed: 2 });+ puff(t - JUMP1, p.x, gA(p.x));+ if (t > 4.72) sparkles(t, PIPX - 12, gA(PIPX) - 58, 30, 26, { n: 5, seed: 7 });++ if (close) punch(2, 604 + shx, 170 + shy);+ // transitions: pixel dissolve in, diamond wipe out+ screenSpace();+ dissolve(1 - seg(t, 0, .45));+ diamonds(seg(t, 5.2, A_END), { dir: 'right', size: 22 });+ }++ // ---------------- shot B: flying it together at sunset ----------------+ const gB = x => 232 - 20 * Math.exp(-(((x - 210) / 150) ** 2));+ const PX_ = 222, JXB = 190;+ function shotB(t, lt) {+ pal('dusk');+ const s = st(t), tilt = ease(seg(t, 6.1, 7.35)), cx = lerp(292, 236, tilt), cy = lerp(62, 150, tilt);+ camAt(cx, cy);+ sky(P.sky, { soft: .5, par: .25, y0: -60, y1: 250 });+ sunDisc(340, 176, 17, { par: .2 });+ clouds(t, { y: 70, n: 7, par: .22, speed: 3, dy: 70, seed: 9, size: 1.1 });+ birds(t - 5.6, { x: 120, y: 60, n: 4, par: .5, speed: 16, c: P.ink });+ hills(196, { c: P.far[0], rim: P.far[1], amp: 14, freq: .01, par: .3, seed: 8 });+ city(214, { c: P.mid[1], lit: .3, par: .45, hmin: 12, hmax: 46, seed: 4, win: P.light[1] });+ hills(222, { c: P.mid[0], rim: P.rim, amp: 8, freq: .018, par: .65, seed: 3, bumps: .8, bumpW: 10 });+ ground(gB, { tufts: .5, flowers: [P.accent[2], P.light[1]] });+ fireflies(t, 80, 190, 280, 30, { n: 7 });++ // the kite, bobbing in the wind high above; the string runs down to Pip's spool+ const kx = 330 + Math.round(6 * Math.sin(s * 1.3)), ky = 34 + Math.round(4 * Math.sin(s * 2.1 + 1));+ const pf = act(s, [[5.6, 'laugh', { look: [1, -1] }], [7.25, 'happy', { look: [-1, 0], emote: null }]], { emoteFrom: 1 });+ const turned = s >= 7.25;+ const hand = measure(() => pip(PX_, gB(PX_), { ...pf, t: s, view: 'q', flip: turned, arm: [ARM.low, turned ? .5 : .8], hold: [null, null] })).hands[1];+ const kbr = PROP.kite ? [kx, ky] : null;+ curve([hand, [lerp(hand[0], kx, .5) + 4, lerp(hand[1], ky, .5) + 14], [kx, ky + 1]], '#ffe8cc');+ PROP.kite(kx, ky, { s: 9, t: s, tilt: .18 + .1 * Math.sin(s * 2.3), tail: [-.55, .85] });+ sparkles(t, kx - 22, ky - 14, 44, 34, { n: 6, seed: 4, c: P.sun[2], c2: P.light[1] });++ // Juno cheers, then goes shy when thanked+ const jf = act(s, [[5.6, 'laugh', { look: [1, -1] }], [7.9, 'shy', { look: [1, 0], emote: 'heart' }]], { emoteFrom: 1 });+ const jj = jump(s, 6.5, 6.8, 6);+ footShadow(JXB, gB(JXB), 12);+ juno(JXB, gB(JXB), { ...jf, t: s, view: s < 7.9 ? 'front' : 'q', dy: Math.round(jj.dy), sq: jj.sq + jf.sq, arm: s < 7.9 ? [1.0 + .15 * Math.sin(s * 8), 1.05 + .15 * Math.sin(s * 8 + 2)] : [ARM.low, ARM.low + .4], bend: s < 7.9 ? [.5, .5] : [.2, 1.2], seed: 5, wind: .6 });+ footShadow(PX_, gB(PX_), 11);+ pip(PX_, gB(PX_), { ...pf, t: s, view: 'q', flip: turned, arm: [ARM.low, turned ? .5 : .8], hold: [null, (x, y) => PROP.spool(x, y)], wind: .8, seed: 2 });++ screenSpace();+ if (t >= CLOSE_B) punch(2, (PX_ + JXB) / 2 + 2, gB(PX_) - 34);+ diamonds(1 - seg(t, A_END, 6.0), { dir: 'left', size: 22 });+ layer(1);+ iris(seg(t, 9.3, 9.95), (PX_ + JXB) / 2 + 2, gB(PX_) - 30, { c: P.ink });+ }++ shots([[0, shotA], [A_END, shotB]]);+ window.overlayHook = (c, t) => { say(c, t, 7.35, 9.3, '謝謝你!Thank you!', { name: 'PIP' }); };+})();diff --git a/.claude/skills/pixel-art/template/src/sheets.js b/.claude/skills/pixel-art/template/src/sheets.jsnew file mode 100644index 0000000..977ae4d--- /dev/null+++ b/.claude/skills/pixel-art/template/src/sheets.js@@ -0,0 +1,80 @@+// sheets.js: model sheets as standalone loops (studio.html?loop=faces | views | kit). Render one with+// node render.mjs --loop=faces --stills=0.5 --out=out/sheets+(() => {+ const bg = () => { sky(['#2a2a48', '#34345a'], { soft: .3 }); };+ const floor = (y) => { rect(0, y, LW, 1, '#4a4a78'); };++ // every expression, front view, for both characters+ LOOPS.faces = t => {+ pal('day'); camAt(); bg();+ [58, 118, 180, 262].forEach(floor);+ EXPR_NAMES.forEach((f, i) => {+ const cx = 30 + (i % 8) * 60;+ const r = Math.floor(i / 8);+ const yp = 58 + r * 60, yj = 180 + r * 82;+ pip(cx, yp, { t, face: f, seed: i, blink: false, emote: EXPR[f].emote, emoteAge: 1 });+ juno(cx, yj, { t, face: f, seed: i, blink: false });+ tinyText(f, cx, yj + 3, '#b0b0d8', { align: 'center' });+ });+ };+ LOOPS.faces.len = 2;++ // views, walk cycle frames, jump keys, arms holding props+ LOOPS.views = t => {+ pal('day'); camAt(); bg();+ const views = ['front', 'q', 'side', 'back'];+ views.forEach((v, i) => { floor(70); pip(30 + i * 34, 70, { t, view: v, face: 'happy', blink: false }); floor(160); juno(34 + i * 34, 160, { t, view: v, face: 'happy', blink: false }); });+ views.forEach((v, i) => { pip(170 + i * 34, 70, { t, view: v, face: 'happy', flip: true, blink: false }); });+ // walk frames+ for (let k = 0; k < 6; k++) { pip(300 + k * 30, 70, { t, view: 'side', face: 'happy', walk: k / 6, blink: false }); }+ for (let k = 0; k < 6; k++) { juno(185 + k * 24, 160, { t, view: 'side', face: 'neutral', walk: k / 6, blink: false }); }+ tinyText('walk x6', 390, 76, '#b0b0d8', { align: 'center' });+ // jump keys: crouch, stretch, apex, land+ const J = [[.18, 0, false], [-.18, -14, true], [-.05, -22, true], [.22, 0, false]];+ J.forEach(([sq, dy, air], i) => juno(350 + i * 32, 160, { t, face: i === 0 ? 'determined' : i === 3 ? 'happy' : 'excited', sq, dy, air, view: 'q', arm: i === 0 ? [ARM.low, -.2] : [ARM.low, ARM.high], blink: false }));+ floor(250);+ // props in hands+ pip(40, 250, { t, face: 'happy', arm: [ARM.low, .9], hold: [null, (x, y) => PROP.balloon(x, y)] });+ pip(90, 250, { t, face: 'love', arm: [.4, .4], hold: [null, (x, y, a) => PROP.flower(x, y, a)] });+ juno(150, 250, { t, face: 'happy', view: 'q', arm: [ARM.down, .6], bend: [.2, .8], hold: [null, (x, y) => PROP.lantern(x, y)] });+ juno(210, 250, { t, face: 'smug', view: 'side', arm: [ARM.down, 1.0], bend: [.2, .3], hold: [null, (x, y, a) => PROP.umbrella(x, y + 2, { h: 22 })] });+ juno(270, 250, { t, face: 'excited', view: 'front', arm: [1.1, 1.1], bend: [.3, .3], hold: [null, (x, y) => PROP.kite(x, y - 9, { hang: true, t })] });+ pip(330, 250, { t, face: 'surprised', view: 'q', arm: [ARM.low, .3], hold: [null, (x, y) => PROP.mug(x + 1, y + 1)] });+ juno(390, 250, { t, face: 'shy', view: 'q', arm: [ARM.low, .2], bend: [.2, .6], hold: [null, (x, y) => PROP.letter(x + 3, y)] });+ pip(445, 250, { t, face: 'determined', view: 'side', arm: [ARM.low, .6], hold: [null, (x, y) => PROP.star(x + 2, y - 5)] });+ };+ LOOPS.views.len = 2;++ // palettes, emotes, weather, light, transitions+ LOOPS.kit = t => {+ camAt();+ ['day', 'dusk', 'night'].forEach((p, i) => {+ pal(p); const x0 = i * 160;+ clip(x0, 0, 160, 120);+ const s = P.sky; for (let y = 0; y < 120; y++) { const k = y / 120 * (s.length - 1), a = Math.floor(k); for (let x = x0; x < x0 + 160; x++) px(x, y, dith(x, y, k - a) ? s[Math.min(s.length - 1, a + 1)] : s[a]); }+ glow(x0 + 120, 40, 18, P.sun[0], .7); disc(x0 + 120, 40, 7, P.sun[1]);+ noclip();+ palColours(P).forEach((c, j) => rect(x0 + 4 + (j % 16) * 9, 92 + Math.floor(j / 16) * 9, 8, 8, c));+ tinyText(p, x0 + 6, 4, P.ink);+ });+ pal('day');+ rect(0, 120, LW, 150, '#2a2a48');+ const em = ['!', '?', '!?', 'heart', 'sweat', 'anger', 'dots', 'note', 'bulb', 'star', 'spiral', 'zzz'];+ em.forEach((k, i) => emote(k, 8 + i * 39, 150, { age: t + 1 }));+ // weather boxes+ const box = (x, fn) => { rect(x, 160, 110, 100, '#1c2a4a'); clip(x, 160, 110, 100); fn(x); noclip(); };+ box(4, x => { pal('night'); rain(t, { n: 60 }); pal('day'); });+ box(122, x => { snow(t, { n: 60 }); });+ box(240, x => { sparkles(t, x + 10, 170, 90, 80, { n: 12 }); });+ box(358, x => { glow(x + 55, 210, 40, '#ffb44a', 1); disc(x + 55, 210, 4, '#fff3b0'); fireflies(t, x + 5, 170, 100, 80); });+ };+ LOOPS.kit.len = 2;++ // transitions (loop time 0..4: dissolve, iris, diamonds, blocks at k = frac)+ LOOPS.wipes = t => {+ pal('day'); camAt(); sky(); hills(200, { c: P.mid[1] }); ground(x => 230);+ const k = frac(t), i = Math.floor(t) % 4;+ [() => dissolve(k), () => iris(k, 240, 150, { shape: 'diamond' }), () => diamonds(k), () => blocks(k)][i]();+ };+ LOOPS.wipes.len = 4;+})();diff --git a/.claude/skills/pixel-art/template/studio.html b/.claude/skills/pixel-art/template/studio.htmlnew file mode 100644index 0000000..650ae90--- /dev/null+++ b/.claude/skills/pixel-art/template/studio.html@@ -0,0 +1,29 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>studio</title>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=DotGothic16&family=Press+Start+2P&family=Noto+Sans+TC:wght@400&display=block">+<style>+ html, body { margin: 0; background: #1b1820; color: #eee; font: 13px system-ui, sans-serif; }+ main { padding: 12px; display: grid; gap: 8px; }+ #out { width: min(100%, 1280px); aspect-ratio: 16 / 9; height: auto; background: #fff; image-rendering: pixelated; }+ .bar { display: flex; gap: 10px; align-items: center; max-width: 1280px; }+ #scrub { flex: 1; } #tt { font-variant-numeric: tabular-nums; min-width: 190px; }+</style>+</head>+<body>+<main>+ <canvas id="out" width="1920" height="1080"></canvas>+ <div class="bar"><input id="scrub" type="range" min="0" max="10" step="0.0417" value="0"><span id="tt">loading…</span></div>+</main>+<!-- engine: config, shared kit, this engine's drawing library -->+<script src="src/config.js"></script>+<script src="src/kit.js"></script>+<script src="src/pixel.js"></script>+<script src="src/cast.js"></script>+<script src="src/sheets.js"></script>+<!-- your video: one script per scene file, in order -->+<script src="src/scenes/demo.js"></script>+</body>+</html>diff --git a/.claude/skills/video-clone/SKILL.md b/.claude/skills/video-clone/SKILL.mdindex 5a2d6af..9526734 100644--- a/.claude/skills/video-clone/SKILL.md+++ b/.claude/skills/video-clone/SKILL.md@@ -31,7 +31,8 @@ python .claude/skills/video-clone/scripts/analyze.py "<檔案或網址>" --out p以及**每個鏡頭的運鏡(shot_details:推近/拉遠/平移/環繞/靜止 + 快慢)與畫面數據(亮度、對比、暗部比例、飽和度、主色)**,`look_summary` 是整支的摘要。然後**用 Read 打開 `sheet_1fps.jpg` 和 `sheet_scenes.jpg` 實際看**,搭配 `report.json` 寫 `analysis/STYLE.md`:-- **媒材**(必填、放第一行):2d-painted · 2d-vector · 3d-stylized · 3d-photoreal · live-action。這是選 skill 的硬條件+- **媒材**(必填、放第一行):2d-painted(水彩/墨線)· 2d-crayon(蠟筆/色鉛筆繪本)· 2d-vector(扁平向量、動態圖像)· 2d-pixel(像素)·+ 2d-paper(剪紙/定格)· 2d-lineart(白板/手繪線稿解說)· 2d-cel(日式動畫賽璐璐)· 3d-stylized · 3d-photoreal · live-action。這是選 skill 的硬條件- 鏡頭清單:把 `shot_details` 整理成表(編號、秒數、內容、運鏡與快慢、亮暗),企劃會逐鏡對照這張表- 配色與色彩弧線、角色造型語言- 剪接:鏡頭數、平均鏡頭長度(秒與拍)、切點是否對拍、轉場種類@@ -45,7 +46,7 @@ python .claude/skills/video-clone/scripts/analyze.py "<檔案或網址>" --out p讀 `styles/` 底下所有 `*.md`(`_TEMPLATE.md` 除外)。每個檔案的 frontmatter 有 `engine`(交給哪個 skill)、`medium` 與 `priority`,內文有「辨識特徵」。**engine 對應的 `.claude/skills/<engine>/` 資料夾不存在的風格直接跳過**(使用者沒有安裝那個引擎,例如開源版不附的 Remotion skills)。-- **先過濾媒材**:只考慮 `medium` 與參考片媒材相同的風格(live-action 參考片 → 用 3d-photoreal 或最接近的 CG 媒材重現,並告訴使用者)。+- **先過濾媒材**:只考慮 `medium` 與參考片媒材相同的風格;沒有同媒材的風格時,選畫面最接近的媒材並在 why 說明(live-action 參考片 → 用最接近的 2D 媒材重現,並告訴使用者)。**目前只做 2D**(3D 賽道暫停,`styles/_disabled/` 裡的風格不參與選擇)。參考片是 3D/擬真時,選最接近的 2D 風格,重現它的節奏、運鏡、構圖、光影氣氛與字卡手法(例如黑底+光暈、慢推、灰白兩階標語),並在 route.json 的 why 與回報裡明說「參考片是 3D,這支用 2D 重現」——不要默默降級。diff --git a/.claude/skills/video-clone/assets/engine-kit/ENGINE_BRIEF.md b/.claude/skills/video-clone/assets/engine-kit/ENGINE_BRIEF.mdnew file mode 100644index 0000000..436a257--- /dev/null+++ b/.claude/skills/video-clone/assets/engine-kit/ENGINE_BRIEF.md@@ -0,0 +1,80 @@+# Building a ReelMimic drawing engine++ReelMimic (repo root: `C:/Users/Eden/Desktop/yt克隆`) turns a reference video + a one-line brief into a new 2D animation.+An AI director plans it, then several builder agents write one scene file per shot in parallel, fresh reviewer agents+check every shot on rendered frames, and a final critic checks the whole film. A **drawing engine** is the skill those+agents use to actually draw the frames. Today there are two (HyperFrames vector, painted-animation watercolor). You are+building one more.++## What you get++- `.claude/skills/video-clone/assets/engine-kit/` — shared runtime, copy these into your template **unchanged**:+ - `kit.js` → `template/src/kit.js`: timeline (`shots`), timing/motion helpers (`seg`, `kf`, `ease*`, `spring`,+ `jump`, `take`, `onTwos`, `onStep`, `pulse`, `hash`, `rnd`), camera (`camBegin/camEnd/toScreen`), render hooks,+ `caption()`, and the `window.ENGINE = { setup, begin, end, crisp }` plug-in point. Read it fully first.+ - `render.mjs` → `template/render.mjs`: headless-Chrome renderer (`--sheet`, `--strip`, `--crop`, `--stills`,+ `--frames` parallel+resumable, `--encode`, `--clip`). Same CLI as painted-animation.+ - `studio.html` → `template/studio.html`: replace `<!-- ENGINE-LIBS -->` with your library scripts and+ `<!-- SCENES -->` with `<script src="src/scenes/demo.js"></script>`.+ - `package.json` → `template/package.json` (rename `name`; add deps only if truly needed).+ - `new_project.sh` → `scripts/new_project.sh`.+- `.claude/skills/painted-animation/` — the reference engine. Read its `SKILL.md` and `template/ANIMATION_GUIDE.md`+ for the standard of craft expected (animation principles, reads, review loop). Don't copy its Clawd character.++## What you build — only inside `.claude/skills/<your-engine>/`++```+SKILL.md frontmatter (name, description: when to use) + workflow, API summary, rules, engine gotchas+GUIDE.md the full drawing/animation guide for agents: look rules, full API with examples, character+ system, how to review, known pitfalls+scripts/new_project.sh (from the kit)+template/+ studio.html render.mjs package.json .gitignore (node_modules, out)+ src/config.js const PROJECT = { duration, bpm, offset, fps: 24 };+ src/kit.js (from the kit, unchanged)+ src/<look>.js YOUR drawing library: primitives, materials, palettes, backgrounds, effects, transitions+ src/cast.js the character system (see below)+ src/scenes/demo.js an 8–10 s demo that exercises everything (see below)+docs/demo-sheet.jpg contact sheet of the demo (render it with render.mjs)+```++### Hard requirements (the production line depends on them)++1. **Pure function of t.** No `Math.random()`, no state carried between frames, no timers. Use `hash()` / `rnd(key)`.+2. **One file per shot works.** Scenes are separate files that only call your library and the cast; they never+ redraw a character's body parts themselves.+3. **Characters in one shared file** (`cast.js`, or one file per character in real projects): a character is drawn by+ one call with pose parameters, e.g. `bean(x, y, u, { face: 'happy', look: .3, arm: [...], sq, flip, view })`.+ Provide: ≥ 8 expressions (neutral, happy, laugh, sad, cry, angry, surprised, scared, love, sleepy…), a front view and+ a 3/4 or side view, walk cycle helper, arm/hand poses that can hold props, squash & stretch, blink. Limbs must always+ stay attached to the body (one continuous silhouette, or joints that visibly connect). Build two original demo+ characters that show the range (e.g. one round, one tall). Never copy an existing IP character.+4. **Everything drawn by code** — no image files you didn't generate, no network at render time. Google Fonts via a+ `<link>` in studio.html is OK (painted-animation does it); prefer a font with CJK coverage for any caption text.+5. **Speed:** aim for ≤ 250 ms/frame at 1920×1080 (the log prints ms/frame). Cache static textures in `ENGINE.setup`.+6. **Legible at phone size:** main subjects big, outlines thick enough to survive being shown at 390 px wide.+7. Don't touch anything outside your folder. Don't install global packages.++### The demo (8–10 s, 2+ shots)++Tells a tiny original story with the two characters and shows: an establishing shot with a camera move; a+character action with anticipation → action → follow-through (e.g. jump, throw, trip); an expression change; a prop+held in a hand; a designed transition between the shots that fits your look; one caption via `window.overlayHook`+(`caption(c, text)` or your own styled one). It must look **good** — this is what users judge the engine by.++## Quality loop (do it for real)++Render with `node render.mjs --sheet=... --cols=4 --w=480 --out=out/check/x.jpg` and crops of faces/hands+(`--crop=x,y,w,h`), then open the images with the Read tool and critique them like an art director: is the look+unmistakably <your style> and appealing? are characters on-model and cute/expressive? limbs attached? motion readable?+anything muddy, tiny, clipped, or broken? Fix and re-render. Do at least 3 full rounds; keep going until you'd put it on+the project's front page. Then render `docs/demo-sheet.jpg` (8–12 frames, 4 cols, w 480) and the full demo once:+`node render.mjs --frames --workers=4 && node render.mjs --encode --out=out/demo.mp4` to confirm it encodes.++Work in a scratch copy for testing (e.g. `%TEMP%/<engine>_dev`, scaffolded with your own new_project.sh --keep-demo)+or inside `template/` directly (run `npm install` there; node_modules/out are gitignored).++## Report back++What you built (files), the look in two sentences, API summary (character call signature + key library functions),+ms/frame, the path to `docs/demo-sheet.jpg`, and honest known limits.diff --git a/.claude/skills/video-clone/assets/engine-kit/LICENSE-render.mjs.txt b/.claude/skills/video-clone/assets/engine-kit/LICENSE-render.mjs.txtnew file mode 100644index 0000000..1215a85--- /dev/null+++ b/.claude/skills/video-clone/assets/engine-kit/LICENSE-render.mjs.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 John Heibel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/.claude/skills/video-clone/assets/engine-kit/kit.js b/.claude/skills/video-clone/assets/engine-kit/kit.jsnew file mode 100644index 0000000..8d6f3c2--- /dev/null+++ b/.claude/skills/video-clone/assets/engine-kit/kit.js@@ -0,0 +1,154 @@+// kit.js: the shared runtime for ReelMimic's Canvas-2D drawing engines (pixel art, paper cut-out, whiteboard, anime+// cel, crayon storybook). Each engine copies this file into its template unchanged and adds its own drawing library.+//+// The render contract is the same as painted-animation's, so the same render.mjs drives every engine:+// window.ready = true once fonts and assets are loaded+// window.renderAt(t, type, q) → data URL of the frame at time t+// window.renderSheet(times, cols, w, crop, at) → { url, ms[] } contact sheet (crop = [x,y,w,h] in screen px,+// at = [x,y,w,h] around a WORLD point, wherever the camera put it)+// Every frame is a pure function of t: frames render in parallel and out of order, so nothing may carry over from one+// frame to the next. Use hash()/rnd() for stable randomness, never Math.random().+//+// An engine plugs in through window.ENGINE = { setup(), begin(t), end(t) } (all optional):+// setup() → once, async (load images, build textures); begin(t) → before the shot draws (e.g. switch G to a low-res+// buffer); end(t) → after it (e.g. upscale, add grain). Shots draw with the 2D context G.++const W = 1920, H = 1080, TAU = Math.PI * 2;+const DUR = PROJECT.duration, BPM = PROJECT.bpm || 120, BEAT = 60 / BPM, OFF = PROJECT.offset || 0;+const FPS = PROJECT.fps || 24;++// ---------- math & timing (pure functions of t) ----------+const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));+const lerp = (a, b, x) => a + (b - a) * x;+const ease = x => { x = clamp(x); return x * x * (3 - 2 * x); };+const easeIn = x => Math.pow(clamp(x), 3);+const easeOut = x => 1 - Math.pow(1 - clamp(x), 3);+const backOut = x => { x = clamp(x); const s = 1.9; return 1 + (s + 1) * Math.pow(x - 1, 3) + s * Math.pow(x - 1, 2); };+const elasticOut = x => { x = clamp(x); return x === 0 || x === 1 ? x : Math.pow(2, -10 * x) * Math.sin((x * 10 - .75) * (TAU / 3)) + 1; };+const hash = i => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };+// seeded stream for one element: const r = rnd('tree' + i); r() → 0..1, the same every frame+function rnd(key) { let h = 2166136261; for (const c of String(key)) h = Math.imul(h ^ c.charCodeAt(0), 16777619); let s = h >>> 0 || 1; return () => (s = Math.imul(s ^ (s >>> 15), 2246822519) >>> 0, s = (s ^ (s >>> 13)) >>> 0, (s % 1000003) / 1000003); }+const seg = (t, a, b) => clamp((t - a) / (b - a));+const frac = x => x - Math.floor(x);+const bpOf = t => (t - OFF) / BEAT;+const beatN = t => Math.floor(bpOf(t));+const pulse = (t, k = 6) => Math.exp(-frac(bpOf(t)) * k);+const wob = (t, f = 1, ph = 0) => Math.sin((t * f + ph) * TAU);+// hold drawings like hand animation: onTwos(t) = 12 drawings/s, onStep(t, 8) = 8/s (stop-motion feel)+const onTwos = t => Math.floor(t * 12 + 1e-6) / 12;+const onStep = (t, n) => Math.floor(t * n + 1e-6) / n;+function kf(t, keys, e = ease) {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) if (t < keys[i][0]) {+ const [a, va] = keys[i - 1], [b, vb] = keys[i], k = e((t - a) / (b - a));+ return Array.isArray(va) ? va.map((v, j) => lerp(v, vb[j], k)) : lerp(va, vb, k);+ }+ return keys[keys.length - 1][1];+}+function mixCol(a, b, k) {+ const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16), c = i => Math.round(lerp((pa >> i) & 255, (pb >> i) & 255, clamp(k)));+ return '#' + ((1 << 24) + (c(16) << 16) + (c(8) << 8) + c(0)).toString(16).slice(1);+}+const shakeXY = (t, amt) => { const f = Math.floor(t * 24); return [(hash(f * 1.7) - .5) * 2 * amt, (hash(f * 2.3 + 9) - .5) * 2 * amt]; };+// motion principles+const spring = (t, t0, k = 6, w = 18) => t < t0 ? 0 : Math.exp(-k * (t - t0)) * Math.sin(w * (t - t0));+const arcPt = (p0, p1, h, k) => [lerp(p0[0], p1[0], k), lerp(p0[1], p1[1], k) - h * 4 * k * (1 - k)];+function jump(t, t0, t1, h = 3) { // → { dy (units, up is negative), sq (squash +, stretch -) }+ if (t < t0 - .12) return { dy: 0, sq: 0 };+ if (t < t0) return { dy: 0, sq: .18 * ease(seg(t, t0 - .12, t0)) };+ if (t < t1) { const k = (t - t0) / (t1 - t0); return { dy: -h * 4 * k * (1 - k), sq: -.16 * Math.abs(1 - 2 * k) }; }+ const a = t - t1; return { dy: 0, sq: .22 * Math.exp(-8 * a) * Math.cos(20 * a) };+}+function take(t, t0, amt = 1) { // surprise take peaking at t0+ if (t < t0 - .1) return { sq: 0, dy: 0 };+ if (t < t0) return { sq: .12 * amt * ease(seg(t, t0 - .1, t0)), dy: 0 };+ const a = t - t0; return { sq: -.26 * amt * Math.exp(-6 * a) * Math.cos(16 * a), dy: -1.2 * amt * Math.exp(-7 * a) * Math.max(0, Math.cos(9 * a)) };+}++// ---------- shots ----------+// shots([[t0, fn], ...]); fn(t, lt, dur) paints the WHOLE frame (background included) with G.+const SHOTS = [], LOOPS = {};+function shots(list) { SHOTS.push(...list); SHOTS.sort((a, b) => a[0] - b[0]); }+function drawWorld(t) {+ if (window.LOOP) return window.LOOP(t);+ if (!SHOTS.length) { G.fillStyle = '#EDE6D8'; G.fillRect(0, 0, W, H); return; }+ let i = 0; while (i + 1 < SHOTS.length && t >= SHOTS[i + 1][0]) i++;+ const t0 = SHOTS[i][0], end = i + 1 < SHOTS.length ? SHOTS[i + 1][0] : DUR;+ SHOTS[i][1](t, t - t0, end - t0);+ if (CAM) camEnd();+}++// ---------- camera (world → screen) ----------+let CAM = null, LAST_CAM = null;+function camBegin(cx = W / 2, cy = H / 2, zoom = 1, rot = 0) {+ G.save(); G.translate(W / 2, H / 2); G.rotate(rot); G.scale(zoom, zoom); G.translate(-cx, -cy);+ CAM = LAST_CAM = { cx, cy, zoom, rot };+}+function camEnd() { G.restore(); CAM = null; }+function toScreen(x, y, cam = CAM) {+ if (!cam) return [x, y];+ const dx = (x - cam.cx) * cam.zoom, dy = (y - cam.cy) * cam.zoom, c = Math.cos(cam.rot), s = Math.sin(cam.rot);+ return [W / 2 + dx * c - dy * s, H / 2 + dx * s + dy * c];+}++// ---------- canvases & frame ----------+// G: the context shots draw into (an engine may point it at a low-res buffer in begin()). OUT: the visible 1920×1080.+let G = null, OUT = null, OUTC = null, T = 0;+function makeCanvas(w = W, h = H) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }+async function renderFrame(t) {+ T = t; CAM = LAST_CAM = null;+ G = OUT; G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over';+ G.clearRect(0, 0, W, H);+ if (window.ENGINE && ENGINE.begin) ENGINE.begin(t);+ drawWorld(t);+ if (window.ENGINE && ENGINE.end) ENGINE.end(t);+ OUT.setTransform(1, 0, 0, 1, 0, 0); OUT.globalAlpha = 1; OUT.globalCompositeOperation = 'source-over';+ if (window.overlayHook) window.overlayHook(OUT, t); // crisp captions / karaoke above everything+}+window.renderAt = async (t, type = 'image/png', q = .92) => { await renderFrame(t); return OUTC.toDataURL(type, q); };+window.renderSheet = async (times, cols = 3, w = 640, crop = null, at = null) => {+ if (at) at = at.map((v) => typeof v === 'string' ? (0, eval)(v) : v);+ const [, , cw, ch] = at || crop || [0, 0, W, H], h = Math.round(w * ch / cw), rows = Math.ceil(times.length / cols), sc = makeCanvas(cols * w, rows * h);+ const c = sc.getContext('2d'), ms = [];+ for (let i = 0; i < times.length; i++) {+ const t0 = performance.now(); await renderFrame(times[i]); ms.push(Math.round(performance.now() - t0));+ const x = (i % cols) * w, y = Math.floor(i / cols) * h;+ const [cx, cy] = at ? toScreen(at[0], at[1], LAST_CAM).map((v, j) => v - (j ? ch : cw) / 2) : crop || [0, 0];+ c.imageSmoothingEnabled = !(window.ENGINE && ENGINE.crisp);+ c.drawImage(OUTC, cx, cy, cw, ch, x, y, w, h);+ c.fillStyle = 'rgba(0,0,0,.65)'; c.fillRect(x, y, 84, 24); c.fillStyle = '#fff'; c.font = '15px sans-serif'; c.fillText(times[i].toFixed(2) + 's', x + 6, y + 17);+ }+ return { url: sc.toDataURL('image/jpeg', .9), ms };+};+window.gpuInfo = () => 'canvas2d';++// ---------- captions (optional) ----------+// A simple, legible caption bar on the overlay: caption(c, text, { y, size, font, fg, bg }). Engines may style their own.+function caption(c, txt, o = {}) {+ const size = o.size || 54, y = o.y || H - 70, font = o.font || `700 ${size}px "Noto Sans TC", "Noto Sans", system-ui, sans-serif`;+ c.save(); c.font = font; c.textAlign = 'center'; c.textBaseline = 'middle';+ const w = c.measureText(txt).width + size * 1.1;+ c.fillStyle = o.bg || 'rgba(20,18,26,.72)'; const r = size * .5;+ c.beginPath(); c.roundRect(W / 2 - w / 2, y - size * .78, w, size * 1.56, r); c.fill();+ c.lineJoin = 'round'; c.lineWidth = size * .14; c.strokeStyle = 'rgba(0,0,0,.55)'; c.strokeText(txt, W / 2, y + 2);+ c.fillStyle = o.fg || '#FFF8EC'; c.fillText(txt, W / 2, y + 2); c.restore();+}++// ---------- boot ----------+async function boot() {+ OUTC = document.getElementById('out'); OUT = OUTC.getContext('2d', { willReadFrequently: false });+ const fonts = [...(window.EXTRA_FONTS || [])].map(([f, txt]) => document.fonts.load(f, txt));+ await Promise.all(fonts);+ if (window.ENGINE && ENGINE.setup) await ENGINE.setup();+ window.ready = true;+ if (!location.search.includes('render')) devUI();+}+function devUI() {+ const s = document.getElementById('scrub'), lab = document.getElementById('tt'); if (!s) return;+ s.max = window.LOOP ? window.LOOP.len : DUR; s.step = 1 / FPS;+ let busy = false, want = null;+ const go = async () => { if (busy) return; busy = true; while (want != null) { const t = want; want = null; const t0 = performance.now(); await renderFrame(t); lab.textContent = `${t.toFixed(2)}s · ${Math.round(performance.now() - t0)} ms/frame`; } busy = false; };+ s.addEventListener('input', () => { want = +s.value; go(); });+ want = +(new URLSearchParams(location.search).get('t') || 0); s.value = want; go();+}+window.addEventListener('load', () => { const q = new URLSearchParams(location.search).get('loop'); if (q && LOOPS[q]) window.LOOP = LOOPS[q]; boot(); });diff --git a/.claude/skills/video-clone/assets/engine-kit/new_project.sh b/.claude/skills/video-clone/assets/engine-kit/new_project.shnew file mode 100644index 0000000..740cd15--- /dev/null+++ b/.claude/skills/video-clone/assets/engine-kit/new_project.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+# Scaffolds a project from this engine's template, installs deps and checks the toolchain.+# bash .claude/skills/<engine>/scripts/new_project.sh <project-dir> [--keep-demo]+set -e+SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"+TARGET="${1:?usage: new_project.sh <project-dir> [--keep-demo]}"+if [ -e "$TARGET/studio.html" ]; then echo "error: $TARGET already has a studio.html; not overwriting" >&2; exit 1; fi+mkdir -p "$TARGET"+if command -v rsync >/dev/null; then rsync -a --exclude node_modules --exclude out "$SKILL_DIR/template/" "$TARGET/"; else cp -R "$SKILL_DIR/template/." "$TARGET/"; rm -rf "$TARGET/node_modules" "$TARGET/out"; fi # Git Bash on Windows has no rsync+mkdir -p "$TARGET/assets" "$TARGET/out/check"+# The demo is an example, not a template: unless asked, unhook it so the new video starts clean.+if [ "${2:-}" != "--keep-demo" ]; then sed -i.bak 's#<script src="src/scenes/demo.js"></script>##' "$TARGET/studio.html" && rm -f "$TARGET/studio.html.bak"; fi+( cd "$TARGET" && npm install --silent --no-audit --no-fund )+echo "node $(node -v)"+command -v ffmpeg >/dev/null && echo "ffmpeg ok" || echo "MISSING: ffmpeg"+FOUND=+for c in "${CHROME_PATH:-}" "/c/Program Files/Google/Chrome/Application/chrome.exe" "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" /usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do+ [ -n "$c" ] && [ -x "$c" ] && { echo "chrome $c"; FOUND=1; break; }+done+[ "${FOUND:-}" = 1 ] || echo "MISSING: Chrome (install it, or pass --chrome=<path> to render.mjs)"+echo "== ready: $TARGET"diff --git a/.claude/skills/video-clone/assets/engine-kit/package.json b/.claude/skills/video-clone/assets/engine-kit/package.jsonnew file mode 100644index 0000000..9750f97--- /dev/null+++ b/.claude/skills/video-clone/assets/engine-kit/package.json@@ -0,0 +1,6 @@+{+ "name": "reelmimic-engine",+ "private": true,+ "license": "MIT",+ "dependencies": { "puppeteer-core": "^25.11.0" }+}diff --git a/.claude/skills/video-clone/assets/engine-kit/render.mjs b/.claude/skills/video-clone/assets/engine-kit/render.mjsnew file mode 100644index 0000000..9f7418a--- /dev/null+++ b/.claude/skills/video-clone/assets/engine-kit/render.mjs@@ -0,0 +1,161 @@+// render.mjs: renders studio.html in headless Chrome. Length and fps come from the page (PROJECT in src/config.js).+//+// Look at it (open the images with your image viewer / Read tool):+// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)+// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point+// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera+// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs+// Make the video:+// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --encode --out=out/video.mp4 out/frames → MP4+// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or+// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)+// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,+// --chrome=<path to Chrome/Chromium>.+import puppeteer from 'puppeteer-core';+import { spawn } from 'node:child_process';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { homedir } from 'node:os';++const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));+const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+ ...playwrightChromes()];+// Chromium builds Playwright downloaded (~/.cache/ms-playwright/chromium-NNNN), newest first+function playwrightChromes() {+ const dir = `${homedir()}/.cache/ms-playwright`;+ if (!existsSync(dir)) return [];+ return readdirSync(dir).filter(n => /^chromium-\d+$/.test(n)).sort((a, b) => b.split('-')[1] - a.split('-')[1])+ .map(n => `${dir}/${n}/chrome-linux64/chrome`);+}+const CHROME = CHROMES.find(p => p && existsSync(p));+if (!CHROME) { console.error('Chrome not found: pass --chrome=<path> or set CHROME_PATH'); process.exit(1); }+const fps = +(args.fps || 24), FRAMES_DIR = 'out/frames';+const run = (cmd, a) => new Promise((ok, bad) => { const p = spawn(cmd, a, { stdio: 'inherit' }); p.on('close', c => c ? bad(new Error(cmd + ' exited ' + c)) : ok()); });+const times = s => String(s).split(',').map(Number);+const span = s => String(s).split(':').map(Number);+// comma-separated fields, keeping commas inside parentheses ('PLK.MX(1.38),PLK.WL,500,300'); numbers stay numbers+const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of String(s)) { if (ch === ',' && !d) { out.push(cur); cur = ''; continue; } d += ch === '(' ? 1 : ch === ')' ? -1 : 0; cur += ch; } out.push(cur); return out.map(v => isNaN(+v) ? v : +v); };++// JPEG frames decode as full-range (yuvj420p); without this the MP4 is flagged full-range and some players/platforms+// show it washed out or with crushed shadows. Convert to standard (tv) range and say so.+const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];++if (args.encode) {+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,+ ...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);+ console.log('wrote ' + out);+ process.exit(0);+}++// --soft-gl: no GPU on this machine; render WebGL in software (SwiftShader), which Chrome only allows when asked.+// --gpu-angle=vulkan|gl-egl: headless Linux on an NVIDIA GPU (e.g. a cloud or cluster node); plain --use-gl=angle gets+// no WebGL context there. Check which GPU Chrome actually lands on with gpu_probe.mjs.+const ANGLE = { vulkan: ['--use-angle=vulkan', '--enable-features=Vulkan'], 'gl-egl': ['--use-angle=gl-egl'] };+if (args['gpu-angle'] && !ANGLE[args['gpu-angle']]) { console.error(`--gpu-angle must be one of ${Object.keys(ANGLE)}`); process.exit(1); }+const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ : args['gpu-angle'] ? ANGLE[args['gpu-angle']]+ : process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];+// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.+const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+const browser = await puppeteer.launch({+ executablePath: CHROME, headless: true, protocolTimeout: 0,+ args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']+});+async function openPage(tag = '') {+ const page = await browser.newPage();+ page.on('console', m => { if (['error', 'warn'].includes(m.type())) console.log(`[page${tag}]`, m.text()); });+ page.on('pageerror', e => console.log(`[page error${tag}]`, e.message));+ await page.goto(pathToFileURL(resolve('studio.html')).href + '?render', { waitUntil: 'networkidle0' });+ await page.waitForFunction('window.ready === true', { timeout: 60000 });+ if (args.loop) {+ const ok = await page.evaluate(name => { if (!LOOPS[name]) return false; window.LOOP = LOOPS[name]; return true; }, args.loop);+ if (!ok) { console.error(`no loop named "${args.loop}"`); process.exit(1); }+ }+ return page;+}+const frameOf = async (page, t, type, q) => {+ const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);+ return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');+};+// the length of whatever is being rendered: a loop's .len, or the video's duration+const lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);++if (args.sheet || args.strip) {+ const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });+ let ts;+ if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ else ts = times(args.sheet);+ const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;+ const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);+ writeFileSync(out, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));+ console.log(`${out} (${ts.length} frames) ms/frame: ${ms.join(' ')}`);+} else if (args.stills) {+ const page = await openPage(), out = args.out || 'out/stills'; mkdirSync(out, { recursive: true });+ console.log('GPU:', await page.evaluate(() => window.gpuInfo()));+ for (const s of times(args.stills)) {+ const t0 = Date.now(), buf = await frameOf(page, s, 'image/png');+ const f = `${out}/t${s.toFixed(2).replace('.', '_')}.png`; writeFileSync(f, buf);+ console.log(`${f} ${Date.now() - t0} ms`);+ }+} else if (args.png) {+ // PNG sequence (for GIFs): a loop's full cycle (frame n equals frame 0, so it isn't rendered), or --range=a:b.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], n = Math.round((b - a) * fps);+ const out = args.out || `out/${args.loop ? 'loop_' + args.loop : 'png'}`, workers = +(args.workers || 3); mkdirSync(out, { recursive: true });+ let next = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < n) { const i = next++; writeFileSync(`${out}/f${String(i).padStart(4, '0')}.png`, await frameOf(page, a + i / fps, 'image/png')); }+ }));+ console.log(`${n} frames → ${out} (${((Date.now() - start) / n).toFixed(0)} ms/frame)`);+} else if (args.frames) {+ // Parallel and resumable: each worker pulls the next missing frame; files are written atomically.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);+ mkdirSync(FRAMES_DIR, { recursive: true });+ const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);+ const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }+ console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ let next = 0, done = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < todo.length) {+ const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;+ const buf = await frameOf(page, i / fps, 'image/jpeg', .94);+ writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ if (++done % 24 === 0 || done === todo.length) {+ const el = (Date.now() - start) / 1000;+ console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);+ }+ }+ }));+} else if (args.clip) {+ const page = await openPage(), len = await lengthOf(page);+ const [a, b] = args.range ? span(args.range) : typeof args.clip === 'string' ? span(args.clip) : [0, len];+ const audio = args.audio || await page.evaluate(() => PROJECT.audio || '');+ const out = args.out || 'out/clip.mp4'; mkdirSync(dirname(out), { recursive: true });+ const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',+ ...(audio ? ['-ss', String(a), '-t', String(b - a), '-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', ...TV_RANGE, '-movflags', '+faststart', out],+ { stdio: ['pipe', 'inherit', 'inherit'] });+ const n = Math.round((b - a) * fps), start = Date.now();+ for (let i = 0; i < n; i++) {+ const buf = await frameOf(page, a + i / fps, 'image/jpeg', .93);+ if (!ff.stdin.write(buf)) await new Promise(r => ff.stdin.once('drain', r));+ if (i % 24 === 0 || i === n - 1) console.log(`frame ${i + 1}/${n} ${((Date.now() - start) / (i + 1)).toFixed(0)} ms/frame`);+ }+ ff.stdin.end(); await new Promise(r => ff.on('close', r));+ console.log(`wrote ${out}`);+} else {+ console.log('nothing to do: see the usage notes at the top of render.mjs');+}+await browser.close();diff --git a/.claude/skills/video-clone/assets/engine-kit/studio.html b/.claude/skills/video-clone/assets/engine-kit/studio.htmlnew file mode 100644index 0000000..e2acfcb--- /dev/null+++ b/.claude/skills/video-clone/assets/engine-kit/studio.html@@ -0,0 +1,26 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>studio</title>+<style>+ html, body { margin: 0; background: #1b1820; color: #eee; font: 13px system-ui, sans-serif; }+ main { padding: 12px; display: grid; gap: 8px; }+ #out { width: min(100%, 1280px); aspect-ratio: 16 / 9; height: auto; background: #fff; }+ .bar { display: flex; gap: 10px; align-items: center; max-width: 1280px; }+ #scrub { flex: 1; } #tt { font-variant-numeric: tabular-nums; min-width: 190px; }+</style>+</head>+<body>+<main>+ <canvas id="out" width="1920" height="1080"></canvas>+ <div class="bar"><input id="scrub" type="range" min="0" max="10" step="0.0417" value="0"><span id="tt">loading…</span></div>+</main>+<!-- engine: config, shared kit, this engine's drawing library -->+<script src="src/config.js"></script>+<script src="src/kit.js"></script>+<!-- ENGINE-LIBS -->+<!-- your video: one script per scene file, in order -->+<!-- SCENES -->+</body>+</html>diff --git a/.claude/skills/video-clone/styles/_TEMPLATE.md b/.claude/skills/video-clone/styles/_TEMPLATE.mdindex 4edea84..42f24a7 100644--- a/.claude/skills/video-clone/styles/_TEMPLATE.md+++ b/.claude/skills/video-clone/styles/_TEMPLATE.md@@ -1,7 +1,7 @@---name: my-style # 唯一代號(檔名同名)engine: painted-animation # 交給哪個 skill 製作(.claude/skills/ 底下的資料夾名)-medium: 2d-painted # 媒材:2d-painted · 2d-vector · 3d-stylized · 3d-photoreal(選 skill 的硬條件)+medium: 2d-painted # 媒材:2d-painted · 2d-crayon · 2d-vector · 2d-pixel · 2d-paper · 2d-lineart · 2d-cel · 3d-stylized · 3d-photoreal(選 skill 的硬條件)priority: 50 # 兩種風格都符合時,數字大的優先---# 風格名稱(一句話描述)diff --git a/.claude/skills/video-clone/styles/anime-cel.md b/.claude/skills/video-clone/styles/anime-cel.mdnew file mode 100644index 0000000..c32db7c--- /dev/null+++ b/.claude/skills/video-clone/styles/anime-cel.md@@ -0,0 +1,26 @@+---+name: anime-cel+engine: anime-cel+medium: 2d-cel+priority: 75+---+# 日式動畫賽璐璐風(動漫感角色與演出)++## 辨識特徵+- 畫面:乾淨有粗細變化的線稿、平塗上色+一階硬陰影+高光、大眼睛、頭髮成束、漂亮的漸層天空與雲+- 演出:速度線、集中線、衝擊畫面、閃光、誇張表情(汗滴、青筋、星星眼、豆豆眼)、一拍二/一拍三的動作+- 剪接:日劇動畫式的鏡頭語言(特寫表情、反應鏡頭、定格+鏡頭搖)+- 常見題材:校園、日常搞笑、青春、MV++## 製作預設+- 1920×1080、24 fps;角色動作 onTwos,鏡頭平移可平滑+- 角色一律原創(不可模仿既有動漫角色),用引擎的 cast.js 起手改造型+- 字幕用動畫字幕樣式(白字深色描邊),確保手機看得清楚+- 所有 API 與畫法規則以 `.claude/skills/anime-cel/SKILL.md` 和 `GUIDE.md` 為準++## 已知的坑+- 側面角度最弱(後腦頭髮像平台),重要演技用正面或 3/4 側+- 沒有背面、低頭/抬頭、坐姿的現成姿勢;需要時用鏡頭與構圖避開+- 手是簡化版,特寫手部的鏡頭要少+- 動作用 onTwos;表情變化用 `faceAt()`(眨眼+小彈跳),不要瞬間切換+- (之後每次製作學到的新坑補在這裡)diff --git a/.claude/skills/video-clone/styles/crayon-storybook.md b/.claude/skills/video-clone/styles/crayon-storybook.mdnew file mode 100644index 0000000..9028bc6--- /dev/null+++ b/.claude/skills/video-clone/styles/crayon-storybook.md@@ -0,0 +1,27 @@+---+name: crayon-storybook+engine: crayon-storybook+medium: 2d-crayon+priority: 70+---+# 蠟筆/色鉛筆繪本風(溫暖童書感)++## 辨識特徵+- 畫面:蠟筆或色鉛筆筆觸、看得到紙張紋理(蠟筆在紙紋上斷斷續續)、柔和粉彩色、線條略帶童趣+- 構圖:像繪本內頁,留白多、常有頁面邊框或暈邊+- 轉場:翻頁、淡入淡出+- 常見題材:童話、親子、溫馨故事、睡前故事;常配旁白++## 製作預設+- 1920×1080、24 fps;線稿慢慢地 boil(像重畫的手繪動畫)+- 角色一律原創,用引擎的 cast.js 起手改造型+- 字幕用繪本字體,確保手機看得清楚+- 所有 API 與畫法規則以 `.claude/skills/crayon-storybook/SKILL.md` 和 `GUIDE.md` 為準++## 已知的坑+- 遠景角色太小會看不清表情 → 情緒重點用中景以上,u 至少 30+- 渲染較慢(約 150–400 ms/格,翻頁那幾格更久),30 秒片光整片渲染就要 15–30 分鐘;長渲染照規則分段前景跑+- Lulu 手臂短,舉手只到耳朵高度 → 拿高處的東西先量手的位置再擺道具+- 刺蝟 Kuri 的 3/4 和側面比正面僵,演技鏡頭優先用正面+- 用的是修補過的 p5.brush(避免疊色變髒);npm install 時自動產生,若出現警告代表 p5.brush 版本改了+- (之後每次製作學到的新坑補在這裡)diff --git a/.claude/skills/video-clone/styles/paper-cutout.md b/.claude/skills/video-clone/styles/paper-cutout.mdnew file mode 100644index 0000000..60fe58e--- /dev/null+++ b/.claude/skills/video-clone/styles/paper-cutout.md@@ -0,0 +1,28 @@+---+name: paper-cutout+engine: paper-cutout+medium: 2d-paper+priority: 70+---+# 剪紙/定格動畫(紙材、手作感)++## 辨識特徵+- 畫面:看得出紙張纖維、剪裁邊緣不規則、每一層有投影、角色是關節紙偶(看得到釘扣)+- 動作:有定格動畫的頓挫感(每秒 8–12 張)、位置每格微微抖動+- 轉場:紙張滑入、翻卡、撕紙、立體書展開+- 常見題材:童趣故事、手作風廣告、溫馨短片++## 製作預設+- 1920×1080、24 fps;角色動作用 onStep 保持定格頓挫,鏡頭可平滑+- 角色一律原創,用引擎的 cast.js(紙偶關節)起手改造型+- 字幕做成剪紙字或紙標籤,確保手機看得清楚+- 所有 API 與畫法規則以 `.claude/skills/paper-cutout/SKILL.md` 和 `GUIDE.md` 為準++## 已知的坑+- 女孩角色 lulu 臉比較小,情緒重點用中景以上或特寫,遠景只做動作+- pom 手臂短,舉手只到頭旁邊 → 拿高處的東西改成從側面或跳起來+- 沒有側面/背面,轉身是換圖;表情是瞬間切換(用眨眼遮住),沒有嘴型對嘴+- 淺色薄紙疊在深色上會變髒,重要的色塊不要用 tissue 蓋+- 形狀大小做動畫會讓剪裁邊閃爍 → 改用 sx/sy、popUp 或鏡頭縮放+- 後面接快照式轉場(trBook/trTear/trFlip)的鏡頭,自己不要畫出場轉場,而且要能畫到結束時間之後+- (之後每次製作學到的新坑補在這裡)diff --git a/.claude/skills/video-clone/styles/pixel-story.md b/.claude/skills/video-clone/styles/pixel-story.mdnew file mode 100644index 0000000..bf5c6bf--- /dev/null+++ b/.claude/skills/video-clone/styles/pixel-story.md@@ -0,0 +1,27 @@+---+name: pixel-story+engine: pixel-art+medium: 2d-pixel+priority: 70+---+# 像素風故事短片(復古遊戲感)++## 辨識特徵+- 畫面:看得到方塊像素、有限色盤、抖色(dither)漸層、1 像素描邊;角色像遊戲精靈圖+- 動作:角色動作是一格一格的(8–12 fps),鏡頭平移很順;常有遊戲 UI 元素(對話框、血條、!)+- 剪接:節奏偏快,常用像素溶解、菱形/方塊轉場+- 聲音:8-bit/chiptune 或 lo-fi 配樂常見++## 製作預設+- 1920×1080、24 fps;引擎內部低解析度畫、最近鄰放大,鏡頭與位置都對齊像素+- 角色一律原創,用引擎的 cast.js 起手改造型+- 字幕用引擎的像素風字幕(全解析度繪製,確保手機看得清楚)+- 所有 API 與畫法規則以 `.claude/skills/pixel-art/SKILL.md` 和 `GUIDE.md` 為準++## 已知的坑+- 角色在 1× 很小(40–65 像素高),演表情的鏡頭用 `punch(2)` 放大;同一段內盡量不要混用不同像素大小+- 手臂最高只到頭部高度;側面舉手會擋到臉 → 伸手拿高處的東西用正面+- 轉身是直接換視角(沒有中間格),用快速動作或鏡頭切換遮掩+- 字幕用 `say()`(預設 3 倍大,手機看得清楚),一行最多約 20 個中文字;太長就拆成兩句+- DotGothic16 缺少部分繁體字(例:你),會自動改用 Noto Sans TC 顯示,字形略有不同+- (之後每次製作學到的新坑補在這裡)diff --git a/.claude/skills/video-clone/styles/whiteboard-explainer.md b/.claude/skills/video-clone/styles/whiteboard-explainer.mdnew file mode 100644index 0000000..53f10f7--- /dev/null+++ b/.claude/skills/video-clone/styles/whiteboard-explainer.md@@ -0,0 +1,26 @@+---+name: whiteboard-explainer+engine: whiteboard+medium: 2d-lineart+priority: 70+---+# 白板手繪解說(邊畫邊講)++## 辨識特徵+- 畫面:白板或白紙底、麥克筆線條一筆一筆畫出來、常有一隻手拿筆跟著畫+- 內容:解說、教學、觀念說明;大量箭頭、圈選、圖示、手寫字+- 鏡頭:在一大片白板上平移/縮放到下一段內容,或用板擦擦掉換頁+- 聲音:通常有旁白,配輕快背景音樂++## 製作預設+- 1920×1080、24 fps;旁白節奏決定每段畫多快(一句旁白畫完一個重點)+- 手寫字與重點詞要大、要在手機上看得清楚;每個畫面只講一件事+- 角色(若有)一律原創,用引擎的 cast.js 起手+- 所有 API 與畫法規則以 `.claude/skills/whiteboard/SKILL.md` 和 `GUIDE.md` 為準++## 已知的坑+- 手固定從右下角進出,排版時把重點放在左上到中間,避免被手擋住+- 手寫字是斜向揭露,不是真正的筆順;中文字幕一行不要太長+- 角色是簡單塗鴉,只有 3 個視角;動作以「畫出來+簡單姿勢」為主,不要排複雜走位+- 場景裡沒出現、但字幕會用到的文字,要加進 `window.WB_TEXT` 讓字型預先載入+- (之後每次製作學到的新坑補在這裡)diff --git a/.claude/skills/whiteboard/GUIDE.md b/.claude/skills/whiteboard/GUIDE.mdnew file mode 100644index 0000000..f827854--- /dev/null+++ b/.claude/skills/whiteboard/GUIDE.md@@ -0,0 +1,262 @@+# Whiteboard engine — drawing & animation guide++Read this whole file before drawing anything. It covers the look, the rules that make a whiteboard explainer read+well, the complete API, the characters, and the review loop. Open the model sheets first:+`docs/kit.jpg` (icons, strokes, fills, handwriting), `docs/faces.jpg` (all 16 expressions, Bo + Mochi),+`docs/poses.jpg` (views, walk cycle, jump, props) and `docs/demo-sheet.jpg` (the 10 s demo, `template/src/scenes/demo.js`).++---++## 1. The look++A clean, warm whiteboard / sketch-note explainer. An off-white board with a faint speckle, soft eraser swirls and+the ghosts of old writing; black marker outlines that draw themselves on at a steady hand pace; a cartoon right hand+with a marker (the marker's colour = the ink being drawn) following the pen tip; a few accent colours; handwritten+titles; colouring-in with a broad marker or highlighter that is slightly off-register with the line.++- **Palette.** `INK.black` for every outline and most text. Accents `INK.blue`, `INK.red`, `INK.orange`, `INK.green`+ (plus `purple`, `grey`, `yellow`, `pink`). Highlighters `HL.yellow/pink/green/blue/orange` (translucent, multiply).+ One board area = black + 1–2 accents. Colour means something (red = problem, green = good, blue = the product…).+- **One marker.** Lines are `WB.w` = 9 px at zoom 1 (details 0.6–0.8×, emphasis 1.4×). Icons and characters scale,+ line weight doesn't — that's what makes it look like one person drew the whole board.+- **Surfaces.** `bg: {kind: 'white'}` (default whiteboard), `'paper'` (ruled cream notebook, optional red `margin`+ x), `'grid'` (squared paper). `frame: [x,y,w,h]` draws the physical board (aluminium frame, marker tray, wall+ around) — great for a first establishing shot that then pushes in.+- **Drawn, not placed.** Everything appears through the hand: `drawOn` for strokes, `writeOn` for text. The only+ things that move after being drawn are the characters (and props they carry), the camera, and small effects+ (emotes, rays, hearts).+- **Flat 2D.** No 3D, no perspective tricks. Depth by overlap and size only.++## 2. Timing: reads and the hand++A whiteboard video is a sequence of drawings, and each drawing is a *read*. The viewer watches the pen, so the pen+leads the eye — use that.++- **Pace.** Drawing speed is about 1,500–2,500 px of line per second for simple icons, text ≈ 7–10 characters/s+ (`writeOn('Got an idea?', …, .15, 1.0)` = 12 chars in 0.85 s). A character (Bo) takes 1.0–1.3 s. Faster reads as+ "sped up" (fine for filler), slower drags.+- **One read at a time.** Don't draw two things at once unless they're one idea (`{ all: true }` draws all strokes+ of a list in parallel — for rays, sparkles, motion lines).+- **Hold after drawing.** Give each finished drawing 0.3–0.8 s before the next starts, longer for the key point.+- **The hand covers the lower right** of the pen tip, and its forearm runs to the bottom-right corner. Never let it+ sit over a reaction. Order: draw → the hand leaves (automatically, ~0.6 s after the last `drawOn` if nothing follows+ within ~1.1 s) → the character acts. In the demo, Mochi reacts only after "Share it!" is written and the hand is gone.+- **Hand travel.** Between drawings less than 1.1 s apart the hand glides (lifted, on an arc) from the end of one to+ the start of the next; otherwise it exits bottom-right and re-enters 0.6 s before the next drawing. Plan drawing+ starts so this looks deliberate (left → right, top → bottom, like a person writing).+- **Let the last read land.** End with ≥ 0.4 s with no hand in frame.++## 3. Shots, the board and the camera++```js+// src/scenes/my_video.js+(() => {+ function intro(t, lt, dur) { // t = video time, lt = time in this shot, dur = shot length+ wbBegin(lt, { cam: [[0, [700, 480, 1.12]], [1.1, [700, 480, 1.08]], [2.1, [1170, 560, 1]]] });+ …draw in WORLD coordinates…+ camEnd(); // then SCREEN-space transitions+ eraseWipe(seg(lt, dur - .75, dur), { rows: 3 });+ }+ shots([[0, intro] /*, [5.5, next] */]);+ wbCaptions([[.4, 5, '每個*好點子*,都從一筆開始']]);+})();+```++- `wbBegin(lt, o)` sets the drawing clock (`WB.clock = lt`, so all `a,b` times in `drawOn`/`writeOn` are shot-local),+ starts the camera and paints the board. `o.cam` is `[cx, cy, zoom]` or keyframes `[[t, [cx, cy, zoom]], …]`+ (eased; `o.ease` to change); `o.drift` (px, default 6) adds a barely-there float so the frame is never dead.+- **The big board.** World coordinates are free: lay ideas out across a board several screens wide, and move the+ camera between them ("slide to the next part of the board") inside ONE shot. That is the signature whiteboard+ transition. Zoom 1.0–1.15 for working shots, 0.8–0.9 to reveal a finished diagram, `frame` board at ~0.5 for an+ establishing view.+- **New board = new shot**, joined by `eraseWipe` (end of the old shot), `pageFlip` (start of the new shot) or a+ camera pan that ends on empty board.+- `camEnd()` is called automatically after the shot function if you didn't; call it yourself before screen-space+ effects (`eraseWipe`, `pageFlip`, anything in screen pixels).++## 4. Strokes++A drawing is an array of strokes (nested arrays and `null`/`false` are fine; they're flattened). Builders return a+stroke or an array; spread arrays with `...`.++| builder | notes |+|---|---|+| `S.line(x1,y1,x2,y2,o)` | slight bow + wobble |+| `S.path(pts,o)` | smooth curve through points; `o.closed`, `o.sharp:[i…]` corners, `o.straight` polyline |+| `S.circle(cx,cy,rx,ry,o)` | hand circle: starts upper-left, overshoots (`turns` 1.06), `o.cw` |+| `S.ring(cx,cy,rx,ry)` | loose loop around a word (1.14 turns, spirals) |+| `S.arc(cx,cy,r,a0,a1)`, `S.dot(x,y,r)` | |+| `S.rect(x,y,w,h,o)` | one continuous stroke, `o.r` rounded |+| `S.arrow(x1,y1,x2,y2,o)` | curved shaft (`o.bend`, fraction of length; negative bends the other way) + head (`o.head` px) |+| `S.underline(x,y,w,o)` | `o.double` adds a shorter second line |+| `S.wave/zigzag/spiral` | |+| `S.bubble(cx,cy,rx,ry,[tx,ty])` | speech bubble with tail |+| `S.box(x,y,w,h,{tail:[tx,ty], r})` | callout box, tail from the bottom edge |+| `S.cloud(cx,cy,rx,ry,{bumps})` | thought cloud |+| `S.heart(cx,cy,w)`, `S.star(cx,cy,r)`, `S.check(x,y,s)`, `S.cross(x,y,s)` | |+| `S.rays(cx,cy,r1,r2,n,{a0,a1})` | emphasis lines around a point (fan with a0..a1) |+| `S.sparkle(x,y,s)`, `S.speed(x,y,len,ang,n,gap)` | twinkle, motion lines |+| `S.fill(poly, {col, alpha, mode, shift, z, cost})` | coloured-in shape (see below) |+| `hatch(poly, {angle, gap, col, w, zig})` | quick parallel hatching (or one zigzag scribble with `zig`) |+| `scribble(poly, {col, w, gap})` | highlighter scribble fill |+| `hilite(x,y,w,h,{col})` | highlighter bar behind text (use `writeOn`'s box) |+| `polyCircle(cx,cy,rx,ry)`, `polyRect(x,y,w,h,r)` | polygons for fills/hatching |+| `place(strokes, x, y, ang, scale)`, `tint(strokes, col)`, `layer(strokes, z)` | transform / recolour / reorder |++Common options: `col`, `w` (width), `z` (paint order, default 0), `alpha`, `key` (wobble seed), `wob` (wobble px, 0 =+none), `hl: true` (highlighter stroke).++**Fills.** `S.fill` is the "coloured in with a broad marker" look: the marker texture, a little off-register+(`shift:[dx,dy]`). `mode:'ink'` (default) multiplies, so black lines under it still show and colours darken where they+overlap; `mode:'cover'` is opaque (use it to hide lines behind a shape, e.g. a head over a body). Default `z` is −1 so+fills sit under outlines while being revealed LAST (colour-in after the outline). When drawn on, a fill is revealed by+a slanted sweep and the hand zigzags across it.++**Wobble seeds.** Each builder seeds its wobble from its coordinates, so a static drawing is stable. A stroke that+MOVES (a prop in a hand, anything whose coordinates change per frame) must get a fixed `key`, or its wobble changes+every frame (shimmer). `ICON.*` take `{key}`; characters and props handle it.++### drawOn / ink++```js+drawOn(strokes, a, b, o) → { p, done, tip }+```+Reveals `strokes` in array order between `a` and `b` (shot-local seconds) by arc length, with a short pen-lift between+strokes (`o.gap`, px of travel), eased slightly. Paints in `z` order. Options: `hand:false` (no hand for this one),+`all:true` (all strokes at once), `x,y` offset, `alpha` (fade a finished drawing), `t` (clock override).+**Call it every frame of the shot** — before `a` it paints nothing but still tells the hand what's coming.+`ink(strokes, {alpha})` paints fully, no hand.++To remove a drawing mid-shot: `eraseRect(x, y, w, h, a, b)` (world) scrubs that area with the eraser and restores+the board surface (paper lines included), or fade it with `{alpha}` (less whiteboard-like).++## 5. Handwriting++```js+const box = writeOn('Save time\n省時間', x, y, a, b, { size: 110, col: INK.blue, align: 'left'|'center'|'right', lh: 1.22, weight: 700 })+// box = { x, y, w, h, cx, cy, x2, y2, base, p, done, tip }+```+`x,y` = baseline start of the first line (or its centre / right end with `align`). Each character is revealed by a+slanted clip sweeping left → right while the hand bobs like it's forming letters; characters sit on a slightly uneven+baseline with a small tilt (`jitter: 0` for neat). Time per character follows its width (spaces are quick).++Fonts: **Kalam 700** for Latin, **LXGW WenKai TC 700** for CJK (both Google Fonts, loaded in `studio.html`; Klee One /+cursive as fallback). Emphasis patterns: `hilite(box.x, box.y, box.w, box.h)` behind a word, `S.underline(box.x,+box.y2 + 4, box.w)`, `S.ring(box.cx, box.cy, box.w/2 + 30, box.h/2 + 20)` around it, an arrow into it.+`textBox(text, x, y, o)` measures without drawing (for layout).++## 6. Icons++`ICON.<name>(cx, cy, size = 140, { col, key, rot, rays })` → strokes, centred, `size` ≈ height. `col` = accent fill.+bulb (`rays:true`), clock, coin, money, heart, check, cross, checkbox, phone, house, star, chart, gear, mail, search,+target, cloud, trophy, person. Make new ones the same way (see the `B(...)` definitions in `whiteboard.js`): build at+the origin in 0..100 units, outline strokes + one `S.fill`, return via `place`.++## 7. The hand++Scenes never draw the hand. Each `drawOn`/`writeOn` records where its pen is; after the shot, `ENGINE.end` draws one+hand at the active pen tip (or gliding / entering / leaving as described in §2). The marker cap and nib take the+colour of the ink being drawn; a highlighter stroke shows a highlighter colour.+- `WB.hand = false` hides it for the rest of the frame (set per shot), `{hand:false}` per call.+- `handAt(x, y, {tool:'marker'|'eraser', col})` forces the hand to a world point this frame (pointing, hovering).+- `WB.sleeve` = shirt colour, `WB.handScale` (0.85) = size. It scales mildly with camera zoom.+- The eraser (`eraseWipe`, `eraseRect`) uses the same hand holding a board eraser.++## 8. Characters (`src/cast.js`)++Two originals, both drawn with the same marker lines, so they can be drawn on like any drawing and then act.++- **Bo** — `bo(x, y, u, o)`: a round-headed kid, black mop of hair with one curl on top, orange shirt (`o.shirt`),+ noodle arms and legs with round mitten hands and black shoes. ~10.5u tall (head r 2.35u). Front, 3/4 and side views.+- **Mochi** — `mochi(x, y, u, o)`: a round white cat with one orange ear and an orange-tipped tail, whiskers, pink+ nose. ~7.8u tall sitting (front), a loaf on four legs in side view (`view ≥ .5`), which can walk. Its front legs are+ its "arms" (raise them to wave or hold); in side view it carries `hold.R` in its mouth.++`x, y` = ground point between the feet. Sizes: wide shot u 15–25, medium u 30–45, close-up u 60–90.++Options (both): `face` (EXPR name) · `look: [lx, ly]` (−1..1) · `view` 0 front … 1 side (continuous for Bo: 0.5 = 3/4)+· `flip` (face left) · `sq` squash (+) / stretch (−) · `dy` lift in u (up is negative) · `tilt` · `arm: [[ang, bend],+[ang, bend]]` (degrees; index 0 = screen-left arm in front view, far arm in side view; 0 = hanging, + = outward /+forward and up, 170 = straight up; bend + lifts the forearm) · `leg` (Bo) · `walk` (phase in cycles) · `hold: {L, R}`+(a `PROPS` name or `fn(x, y, u, key) → strokes`, grip at the hand) · `emote` ('!', '?', 'zzz', 'hearts', 'sweat',+'anger', 'sparkle', 'lines', 'swirl'; '-' suppresses the expression's own) · `draw: [a, b]` (drawn on with the hand,+outline first, colour last) · `hand:false` · `blink` (force) / `noBlink` · `t` (time for blinks/idles) · `id` (wobble+seed; give copies different ids) · `strokesOnly` (build without drawing, to measure: `bo(…, {strokesOnly:true}).hand.R`).++Returns `{ hand: { L, R }, head, top, strokes }` in world coordinates — attach effects, place the next drawing, or+make a prop wait exactly where a hand will be (the demo pre-draws the bulb at Bo's hand position at the top of his+jump, so the grab is seamless).++**Expressions** (`EXPR_NAMES`): neutral, happy, laugh, sad, cry, angry, surprised, scared, love, sleepy, thinking,+wink, proud, confused, excited, dizzy. Each has eyes/brows/mouth + an optional effect (tears, anger mark, sweat drop,+floating hearts, zzz, ?, !, sparkles). Add new ones to `EXPR`.++**Acting helpers**+- `mood(lt, [[0,'thinking'], [3.0,'surprised', .55], [3.35,'excited']])` → `{face, sq, dy, blink}`: each change gets+ a blink on the swap and a take (anticipation squash → stretch → settle). Spread `sq`/`dy` into the pose (add them to+ a jump's).+- `jump(lt, t0, t1, h)` (kit) → `{dy, sq}`: crouch 0.12 s before `t0`, arc, landing squash with wobble.+- `take(lt, t0, amt)` (kit), `spring`, `backOut`, `kf(lt, keys, easing)` to animate `arm` angles.+- `stroll(lt, t0, t1, x0, x1, u)` → `{x, walk, flip, moving}`: pass `x` and `walk` (null when standing) with `view: 1`.+- Blinks are automatic (~every 3.4 s, per `id`).++**Props** (`PROPS`): bulb, bulbOn (with rays), phone, coin, heart, star, flag, balloon, book, cup, fish, marker, sign+(blank board on a stick — `writeOn` onto it). They're upright, gripped at the hand.++Rules for characters: never draw their parts in a scene (use options or extend `cast.js`); limbs are single noodle+strokes from inside the torso, so they always stay attached; change faces through `mood()`, not by swapping between+frames; push poses (arms really up, real crouches) — subtle reads as nothing at this line weight.++## 9. Transitions++- **Camera pan across the board** (in-shot): keyframe `cam` from one area to the next; start drawing in the new area+ as the camera settles. Best for continuing an argument.+- **Eraser wipe** `eraseWipe(p, {rows: 3, ghost: .06})` — screen space, at the end of a shot, `p = seg(lt, dur - .75,+ dur)`. The hand scrubs the whole board in zigzag passes; a faint ghost of the old drawing stays (real whiteboards do+ that). The next shot starts on a clean board.+- **Page flip** `pageFlip(p)` — screen space, at the START of the next shot after `camEnd()`, `p = seg(lt, 0, .9)`.+ The previous shot's last frame curls away from the bottom-right corner, with a shadow and paper back. Suits the+ `paper`/`grid` notebook boards. Start drawing on the new page as the flap clears (≈ p 0.7).+- **Erase one area** `eraseRect(x, y, w, h, a, b)` (world) to swap a piece of the diagram.+- Every seam gets one; the first shot can open on the empty board with the hand entering, the last ends on a held+ finished board.++## 10. Captions++`wbCaptions([[a, b, 'text with *accent* words'], …], {accent, size, y})` installs `window.overlayHook`: a white card+with a dark outline, handwritten font (CJK ok), pops in with a small overshoot. `*word*` is coloured (`INK.orange`+default). Or call `wbCaption(c, text, o)` from your own overlay hook. Keep captions short (≤ 16 CJK chars / 40 Latin)+and keep drawings out of the bottom ~130 px while a caption is on screen.++## 11. Review loop++You can't see motion by reading code. Render and open every image with Read:+```bash+node render.mjs --sheet=0.5,1.5,2.5,3.5,4.5 --cols=5 --w=384 --out=out/check/shot.jpg+node render.mjs --strip=3.5:4.4 --cols=8 --w=240 --out=out/check/jump.jpg+node render.mjs --sheet=3.2,4.6 --crop-at=1340,640,560,560 --w=560 --out=out/check/face.jpg+```+Check:+- **Look**: unmistakably whiteboard? one line weight? accents meaningful and few? anything tiny, clipped, muddy?+- **Reads**: every drawing has time to be drawn AND held; the hand never covers an action or reaction; the pen+ order is natural (left→right, top→bottom); the final frame is hand-free.+- **Characters**: on-model, big enough, limbs attached, props touching the hand, faces changed via `mood()`,+ anticipation before jumps, landing squash.+- **Stability**: in a strip, static drawings must not shimmer (missing `key` on moving strokes), the hand must not+ jump between frames (always call future `drawOn`s every frame).+- **Seams**: transitions at every cut; captions readable at phone size (a 480 px sheet is roughly a phone).+Fix, re-render, look again.++## 12. Known pitfalls++- A `drawOn` wrapped in `if (lt > a)` makes the hand pop in instead of entering; call it unconditionally.+- Two overlapping `drawOn` intervals: the hand follows the most recently started one; the other keeps drawing+ "by itself". Chain them instead.+- Fill `cost` (drawing time) is from its bounding box; set `{cost}` to speed up / slow down colouring-in.+- `writeOn` text needs its characters in the loaded font: text coming from outside the scene files → put it in+ `window.WB_TEXT` (before boot) so the CJK slices get fetched.+- Very large zoom (> 2) makes lines fat: build close-ups with a larger `u`/size at zoom ≈ 1 instead.+- `pageFlip` renders the previous shot inside the current one; keep that previous shot free of screen-space effects+ in its last frame, and don't flip from a shot that itself ends in `eraseWipe`.+- Performance: 20–60 ms/frame; the first frame of a render builds textures/sprites (~150 ms). Thousands of strokes+ per frame (dense hatching over big areas) slow it down — prefer `S.fill` / `scribble`.diff --git a/.claude/skills/whiteboard/SKILL.md b/.claude/skills/whiteboard/SKILL.mdnew file mode 100644index 0000000..5aaeb3f--- /dev/null+++ b/.claude/skills/whiteboard/SKILL.md@@ -0,0 +1,92 @@+---+name: whiteboard+description: Make hand-drawn whiteboard / doodle-explainer / sketch-note animation videos (MP4) with code — marker lines that draw themselves on, a cartoon hand holding a marker that follows the pen tip, handwritten text (Latin + CJK) written left to right, hatching and highlighter fills, arrows/circles/callouts/icons, two doodle characters (Bo the kid, Mochi the cat), camera pans across a big board, eraser wipes and page flips. Canvas 2D rendered frame by frame in headless Chrome, encoded with ffmpeg. Use when a reference video or brief calls for a whiteboard animation, VideoScribe-style explainer, doodle / sketch-note / marker-drawing / notebook-doodle look, 白板動畫 / 手繪解說 / 塗鴉解說 / 手寫字, or when the video-clone router picks the whiteboard style.+---++# Whiteboard engine++Every frame is a pure function of time `t`. `studio.html` loads `src/kit.js` (shared ReelMimic runtime: timeline,+timing/motion helpers, camera, render hooks), `src/whiteboard.js` (the look: board, marker strokes, drawOn,+handwriting, icons, hand, transitions, captions), `src/cast.js` (characters) and your scene files. `render.mjs` drives+headless Chrome for contact sheets / crops / frames and ffmpeg encodes the MP4.++**Read [GUIDE.md](GUIDE.md) in full before designing anything** — it has the look rules, the complete API with+examples, the character system and the review checklist. Look at the model sheets: `docs/faces.jpg` (16 expressions+× 2 characters), `docs/poses.jpg` (views, walk, jump, props), `docs/kit.jpg` (icons, strokes, fills, text) and+`docs/demo-sheet.jpg` (the demo).++## Workflow++1. **Scaffold**: `bash .claude/skills/whiteboard/scripts/new_project.sh <project-dir>` (`--keep-demo` keeps the demo+ hooked up). Copies the template, runs `npm install`, checks node / ffmpeg / Chrome.+2. **Plan the board.** Whiteboard films are planned as a BIG BOARD: decide where each idea is drawn in world+ coordinates, and let the camera travel between areas (one shot) or clear the board (eraser wipe / page flip = new+ shot). Write the reads per shot (see GUIDE §Timing): each drawing is a read, and the hand must not cover a read.+3. **Build** one IIFE file per shot/chapter in `src/scenes/`, ending with `shots([[t0, fn], ...])`; add its+ `<script>` to `studio.html`. Set `duration` in `src/config.js`.+4. **Look** (from the project dir), open every image with Read:+ ```bash+ node render.mjs --sheet=0.5,1.5,2.5,3.5 --cols=4 --w=480 --out=out/check/a.jpg # key frames+ node render.mjs --strip=3.6:4.4 --cols=6 --w=320 --out=out/check/jump.jpg # every frame of a move+ node render.mjs --sheet=3.2 --crop-at=1340,640,560,560 --w=560 --out=out/check/face.jpg # detail at a world point+ node render.mjs --loop=faces --sheet=0 --cols=1 --w=1920 --out=out/check/faces.jpg # model sheets (poses, kit)+ ```+5. **Render**: `node render.mjs --frames --workers=4 && node render.mjs --encode --out=out/video.mp4 [--audio=...]`+ (or `--clip` for short ones). ~20–60 ms/frame single-threaded at 1920×1080.++## API in one screen++```js+function shot(t, lt, dur) { // lt = time in this shot+ wbBegin(lt, { cam: [[0, [900, 540, 1.1]], [2, [1400, 560, 1]]], bg: { kind: 'white' } }); // clock + camera + board+ const box = writeOn('Save time 省時間', 300, 300, .2, 1.2, { size: 110, col: INK.blue }); // handwriting+ drawOn(S.underline(box.x, box.y2 + 4, box.w, { col: INK.orange }), 1.25, 1.5); // strokes, drawn on+ drawOn([...ICON.clock(600, 620, 220), ...S.arrow(760, 620, 1000, 600)], 1.6, 2.6); // icons + arrow+ bo(1300, 940, 40, { face: 'happy', draw: [2.7, 3.8], hold: { R: 'coin' } }); // character, drawn on+ camEnd(); eraseWipe(seg(lt, dur - .8, dur)); // transition (screen space)+}+wbCaptions([[.3, 4, '每天*省下*一小時']]); // overlay captions+```++- Strokes: `S.line/path/circle/ring/arc/dot/rect/arrow/underline/wave/zigzag/spiral/bubble/box/cloud/heart/star/check/+ cross/rays/sparkle/speed/fill`, `hatch(poly)`, `scribble(poly)` (highlighter), `hilite(x,y,w,h)`, `place(strokes, x, y,+ ang, scale)`, `polyCircle`, `polyRect`. `drawOn(strokes, a, b, {hand, all, x, y, alpha})`, `ink(strokes)`.+- Text: `writeOn(text, x, y, a, b, {size, col, align, lh, weight})` → box; `textBox()` measures only.+- Icons: `ICON.bulb/clock/coin/money/heart/check/cross/checkbox/phone/house/star/chart/gear/mail/search/target/cloud/+ trophy/person(cx, cy, size, {col, key, rays})`.+- Characters: `bo(x, y, u, o)`, `mochi(x, y, u, o)` → `{hand:{L,R}, head, top, strokes}`; `o = {face, look, view, flip,+ sq, dy, tilt, arm:[[ang,bend],[ang,bend]], leg, walk, hold:{L,R}, emote, draw:[a,b], hand, shirt, id, blink}`.+ `mood(lt, [[t,'face'],...])`, `stroll(lt, t0, t1, x0, x1, u)`, kit `jump()`, `take()`. `EXPR_NAMES` (16), `PROPS`.+- Board & camera: `wbBegin(lt, {cam, bg:{kind:'white'|'paper'|'grid', margin, frame:[x,y,w,h]}, drift})`, `board()`.+- Transitions: `eraseWipe(p)` (screen, end of shot), `pageFlip(p)` (screen, start of next shot), `eraseRect(x,y,w,h,a,b)`+ (world, erase one area), camera pans across the board (one shot with camera keys).+- Hand: automatic (follows every drawOn/writeOn; glides between close drawings, exits bottom-right on pauses).+ `WB.hand = false` hides it, `{hand:false}` per call, `handAt(x, y, {tool})` forces it. `WB.sleeve` colour.+- Colours: `INK.black/blue/red/orange/green/purple/grey/yellow/pink/skin`, highlighters `HL.yellow/pink/green/blue/orange`.++## Rules that matter most++1. **Everything is drawn ON.** New things appear by `drawOn` / `writeOn` with the hand, never pop in. Only characters+ that were already drawn may move/animate; props arrive in hands or get drawn.+2. **One marker, one width.** Line weight stays ~`WB.w` (9 px) everywhere; icons scale, lines don't. Black for+ outlines, 1–2 accent colours per board area, highlighter for emphasis.+3. **The hand must not hide a read.** It covers the lower-right of whatever it draws. Draw first, then act (characters+ react after the hand has left), or place the drawing so the arm doesn't cross the action.+4. **Big and legible**: characters u ≥ 30 in a medium shot (Bo ≈ 10.5u tall), text ≥ 90 px at zoom 1, captions via+ `wbCaptions` (64 px card).+5. **Pure function of t**: no `Math.random`, no state across frames; always call every `drawOn` of the shot every frame+ (it draws nothing before `a`) so the hand knows what comes next. Give moving strokes a fixed `key`.+6. **Transitions at every seam**: eraser wipe, camera pan to the next area, page flip, or a hand-drawn frame.++## Engine gotchas++- `drawOn` reveals in array order but paints in `z` order; fills (`S.fill`) default to z −1 (under lines), `mode:'ink'`+ multiplies (lines show through), `mode:'cover'` hides what's under.+- Builders seed their wobble from their coordinates: a stroke that MOVES must get `{key:'name'}` or it will shimmer.+ Characters and `PROPS` already do this.+- `eraseWipe` / `pageFlip` are SCREEN-space: call `camEnd()` first. `pageFlip` re-renders the previous shot's last+ frame (costs one extra shot render per frame for ~0.9 s).+- Fonts: Kalam (Latin) + LXGW WenKai TC (CJK) from Google Fonts. `ENGINE.setup` scans every loaded script for the+ characters it needs; text built at runtime from other sources → add it to `window.WB_TEXT` before boot.+- Don't name globals `S`, `INK`, `HL`, `WB`, `PEN`, `ICON`, `PROPS`, `EXPR`, `board`, `ink`, `bo`, `mochi`, `hatch`,+ `mood`, `stroll` in scenes (they're the library's). Keep helpers inside the scene IIFE.diff --git a/.claude/skills/whiteboard/docs/demo-sheet.jpg b/.claude/skills/whiteboard/docs/demo-sheet.jpgnew file mode 100644index 0000000..c522df1Binary files /dev/null and b/.claude/skills/whiteboard/docs/demo-sheet.jpg differdiff --git a/.claude/skills/whiteboard/docs/faces.jpg b/.claude/skills/whiteboard/docs/faces.jpgnew file mode 100644index 0000000..a1a2c8aBinary files /dev/null and b/.claude/skills/whiteboard/docs/faces.jpg differdiff --git a/.claude/skills/whiteboard/docs/kit.jpg b/.claude/skills/whiteboard/docs/kit.jpgnew file mode 100644index 0000000..5156225Binary files /dev/null and b/.claude/skills/whiteboard/docs/kit.jpg differdiff --git a/.claude/skills/whiteboard/docs/poses.jpg b/.claude/skills/whiteboard/docs/poses.jpgnew file mode 100644index 0000000..978e520Binary files /dev/null and b/.claude/skills/whiteboard/docs/poses.jpg differdiff --git a/.claude/skills/whiteboard/scripts/new_project.sh b/.claude/skills/whiteboard/scripts/new_project.shnew file mode 100644index 0000000..740cd15--- /dev/null+++ b/.claude/skills/whiteboard/scripts/new_project.sh@@ -0,0 +1,21 @@+#!/usr/bin/env bash+# Scaffolds a project from this engine's template, installs deps and checks the toolchain.+# bash .claude/skills/<engine>/scripts/new_project.sh <project-dir> [--keep-demo]+set -e+SKILL_DIR="$(cd "$(dirname "$0")/.." && pwd)"+TARGET="${1:?usage: new_project.sh <project-dir> [--keep-demo]}"+if [ -e "$TARGET/studio.html" ]; then echo "error: $TARGET already has a studio.html; not overwriting" >&2; exit 1; fi+mkdir -p "$TARGET"+if command -v rsync >/dev/null; then rsync -a --exclude node_modules --exclude out "$SKILL_DIR/template/" "$TARGET/"; else cp -R "$SKILL_DIR/template/." "$TARGET/"; rm -rf "$TARGET/node_modules" "$TARGET/out"; fi # Git Bash on Windows has no rsync+mkdir -p "$TARGET/assets" "$TARGET/out/check"+# The demo is an example, not a template: unless asked, unhook it so the new video starts clean.+if [ "${2:-}" != "--keep-demo" ]; then sed -i.bak 's#<script src="src/scenes/demo.js"></script>##' "$TARGET/studio.html" && rm -f "$TARGET/studio.html.bak"; fi+( cd "$TARGET" && npm install --silent --no-audit --no-fund )+echo "node $(node -v)"+command -v ffmpeg >/dev/null && echo "ffmpeg ok" || echo "MISSING: ffmpeg"+FOUND=+for c in "${CHROME_PATH:-}" "/c/Program Files/Google/Chrome/Application/chrome.exe" "/c/Program Files (x86)/Google/Chrome/Application/chrome.exe" "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" /usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do+ [ -n "$c" ] && [ -x "$c" ] && { echo "chrome $c"; FOUND=1; break; }+done+[ "${FOUND:-}" = 1 ] || echo "MISSING: Chrome (install it, or pass --chrome=<path> to render.mjs)"+echo "== ready: $TARGET"diff --git a/.claude/skills/whiteboard/template/.gitignore b/.claude/skills/whiteboard/template/.gitignorenew file mode 100644index 0000000..9209ef5--- /dev/null+++ b/.claude/skills/whiteboard/template/.gitignore@@ -0,0 +1,2 @@+node_modules+outdiff --git a/.claude/skills/whiteboard/template/LICENSE-render.mjs.txt b/.claude/skills/whiteboard/template/LICENSE-render.mjs.txtnew file mode 100644index 0000000..1215a85--- /dev/null+++ b/.claude/skills/whiteboard/template/LICENSE-render.mjs.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 John Heibel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/.claude/skills/whiteboard/template/package-lock.json b/.claude/skills/whiteboard/template/package-lock.jsonnew file mode 100644index 0000000..b040817--- /dev/null+++ b/.claude/skills/whiteboard/template/package-lock.json@@ -0,0 +1,329 @@+{+ "name": "reelmimic-whiteboard",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "reelmimic-whiteboard",+ "license": "MIT",+ "dependencies": {+ "puppeteer-core": "^25.11.0"+ }+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.3.tgz",+ "integrity": "sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.4",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.4.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",+ "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^3.24.1"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1687809",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",+ "integrity": "sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.5",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.5.tgz",+ "integrity": "sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/puppeteer-core": {+ "version": "25.12.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.12.0.tgz",+ "integrity": "sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.3",+ "chromium-bidi": "17.0.2",+ "devtools-protocol": "0.0.1687809",+ "typed-query-selector": "^2.12.2",+ "webdriver-bidi-protocol": "0.4.3",+ "ws": "^8.21.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.3",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz",+ "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==",+ "license": "MIT"+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",+ "integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",+ "license": "Apache-2.0"+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.22.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.2.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",+ "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/.claude/skills/whiteboard/template/package.json b/.claude/skills/whiteboard/template/package.jsonnew file mode 100644index 0000000..a9ce24d--- /dev/null+++ b/.claude/skills/whiteboard/template/package.json@@ -0,0 +1,6 @@+{+ "name": "reelmimic-whiteboard",+ "private": true,+ "license": "MIT",+ "dependencies": { "puppeteer-core": "^25.11.0" }+}diff --git a/.claude/skills/whiteboard/template/render.mjs b/.claude/skills/whiteboard/template/render.mjsnew file mode 100644index 0000000..9f7418a--- /dev/null+++ b/.claude/skills/whiteboard/template/render.mjs@@ -0,0 +1,161 @@+// render.mjs: renders studio.html in headless Chrome. Length and fps come from the page (PROJECT in src/config.js).+//+// Look at it (open the images with your image viewer / Read tool):+// node render.mjs --sheet=0.5,1,1.5,2 [--cols=4] [--w=480] --out=out/check/a.jpg contact sheet of chosen times+// node render.mjs --strip=2.0:2.5 [--cols=6] [--w=320] --out=out/check/strip.jpg EVERY frame in a stretch (motion)+// node render.mjs --sheet=2.1,2.2 --crop=760,300,400,400 --w=600 --out=out/check/face.jpg full-res crops (details)+// node render.mjs --strip=2.0:2.5 --crop-at=960,780,500,400 --out=out/check/feet.jpg crops that follow a WORLD point+// (x,y in world px, may be page expressions like PLK.MX(1.38); w,h in screen px) through each frame's camera+// node render.mjs --stills=1.2,3.4 --out=out/stills full-res PNGs+// Make the video:+// node render.mjs --clip [--range=0:4] --out=out/video.mp4 straight to MP4 (one worker)+// node render.mjs --frames [--range=0:8] --workers=4 JPEG frames → out/frames (parallel, resumable)+// node render.mjs --encode --out=out/video.mp4 out/frames → MP4+// Standalone loops (LOOPS in the page): add --loop=<name> to any of the above (times are then loop times), or+// node render.mjs --loop=emotions --png --out=out/loop_emotions one cycle as PNGs (for GIFs)+// Music: --audio=assets/song.mp3 (or PROJECT.audio) is muxed into --clip and --encode. Other flags: --fps=24,+// --chrome=<path to Chrome/Chromium>.+import puppeteer from 'puppeteer-core';+import { spawn } from 'node:child_process';+import { mkdirSync, writeFileSync, existsSync, statSync, renameSync, readdirSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { pathToFileURL } from 'node:url';+import { homedir } from 'node:os';++const args = Object.fromEntries(process.argv.slice(2).map(a => { const [k, v] = a.replace(/^--/, '').split('='); return [k, v ?? true]; }));+const CHROMES = [args.chrome, process.env.CHROME_PATH, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',+ ...playwrightChromes()];+// Chromium builds Playwright downloaded (~/.cache/ms-playwright/chromium-NNNN), newest first+function playwrightChromes() {+ const dir = `${homedir()}/.cache/ms-playwright`;+ if (!existsSync(dir)) return [];+ return readdirSync(dir).filter(n => /^chromium-\d+$/.test(n)).sort((a, b) => b.split('-')[1] - a.split('-')[1])+ .map(n => `${dir}/${n}/chrome-linux64/chrome`);+}+const CHROME = CHROMES.find(p => p && existsSync(p));+if (!CHROME) { console.error('Chrome not found: pass --chrome=<path> or set CHROME_PATH'); process.exit(1); }+const fps = +(args.fps || 24), FRAMES_DIR = 'out/frames';+const run = (cmd, a) => new Promise((ok, bad) => { const p = spawn(cmd, a, { stdio: 'inherit' }); p.on('close', c => c ? bad(new Error(cmd + ' exited ' + c)) : ok()); });+const times = s => String(s).split(',').map(Number);+const span = s => String(s).split(':').map(Number);+// comma-separated fields, keeping commas inside parentheses ('PLK.MX(1.38),PLK.WL,500,300'); numbers stay numbers+const fields = s => { const out = []; let d = 0, cur = ''; for (const ch of String(s)) { if (ch === ',' && !d) { out.push(cur); cur = ''; continue; } d += ch === '(' ? 1 : ch === ')' ? -1 : 0; cur += ch; } out.push(cur); return out.map(v => isNaN(+v) ? v : +v); };++// JPEG frames decode as full-range (yuvj420p); without this the MP4 is flagged full-range and some players/platforms+// show it washed out or with crushed shadows. Convert to standard (tv) range and say so.+const TV_RANGE = ['-vf', 'scale=out_range=tv', '-pix_fmt', 'yuv420p', '-color_range', 'tv'];++if (args.encode) {+ const out = args.out || 'out/video.mp4', n = readdirSync(FRAMES_DIR).filter(f => f.endsWith('.jpg')).length, audio = args.audio;+ console.log(`encoding ${n} frames → ${out}${audio ? ' with ' + audio : ''}`);+ await run('ffmpeg', ['-y', '-loglevel', 'error', '-stats', '-framerate', String(fps), '-i', `${FRAMES_DIR}/f%05d.jpg`,+ ...(audio ? ['-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'slow', '-crf', '17', ...TV_RANGE, '-movflags', '+faststart', out]);+ console.log('wrote ' + out);+ process.exit(0);+}++// --soft-gl: no GPU on this machine; render WebGL in software (SwiftShader), which Chrome only allows when asked.+// --gpu-angle=vulkan|gl-egl: headless Linux on an NVIDIA GPU (e.g. a cloud or cluster node); plain --use-gl=angle gets+// no WebGL context there. Check which GPU Chrome actually lands on with gpu_probe.mjs.+const ANGLE = { vulkan: ['--use-angle=vulkan', '--enable-features=Vulkan'], 'gl-egl': ['--use-angle=gl-egl'] };+if (args['gpu-angle'] && !ANGLE[args['gpu-angle']]) { console.error(`--gpu-angle must be one of ${Object.keys(ANGLE)}`); process.exit(1); }+const gpu = args['soft-gl'] ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ : args['gpu-angle'] ? ANGLE[args['gpu-angle']]+ : process.platform === 'win32' ? ['--use-angle=d3d11'] : process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=angle'];+// Ubuntu 23.10+ blocks Chrome's user-namespace sandbox; headless rendering of local files doesn't need it.+const sandbox = process.platform === 'linux' ? ['--no-sandbox'] : [];+const browser = await puppeteer.launch({+ executablePath: CHROME, headless: true, protocolTimeout: 0,+ args: [...sandbox, '--allow-file-access-from-files', '--ignore-gpu-blocklist', ...gpu, '--enable-gpu-rasterization', '--window-size=1920,1080', '--disable-renderer-backgrounding', '--disable-background-timer-throttling']+});+async function openPage(tag = '') {+ const page = await browser.newPage();+ page.on('console', m => { if (['error', 'warn'].includes(m.type())) console.log(`[page${tag}]`, m.text()); });+ page.on('pageerror', e => console.log(`[page error${tag}]`, e.message));+ await page.goto(pathToFileURL(resolve('studio.html')).href + '?render', { waitUntil: 'networkidle0' });+ await page.waitForFunction('window.ready === true', { timeout: 60000 });+ if (args.loop) {+ const ok = await page.evaluate(name => { if (!LOOPS[name]) return false; window.LOOP = LOOPS[name]; return true; }, args.loop);+ if (!ok) { console.error(`no loop named "${args.loop}"`); process.exit(1); }+ }+ return page;+}+const frameOf = async (page, t, type, q) => {+ const url = await page.evaluate((t, type, q) => window.renderAt(t, type, q), t, type, q);+ return Buffer.from(url.slice(url.indexOf(',') + 1), 'base64');+};+// the length of whatever is being rendered: a loop's .len, or the video's duration+const lengthOf = page => page.evaluate(() => window.LOOP ? window.LOOP.len : DUR);++if (args.sheet || args.strip) {+ const page = await openPage(), out = args.out || 'out/sheet.jpg'; mkdirSync(dirname(out), { recursive: true });+ let ts;+ if (args.strip) { const [a, b] = span(args.strip); ts = []; for (let i = Math.round(a * fps); i <= Math.round(b * fps); i++) ts.push(i / fps); }+ else ts = times(args.sheet);+ const crop = args.crop ? times(args.crop) : null, at = args['crop-at'] ? fields(args['crop-at']) : null;+ const { url, ms } = await page.evaluate((ts, c, w, crop, at) => window.renderSheet(ts, c, w, crop, at), ts, +(args.cols || (args.strip ? 6 : 3)), +(args.w || (args.strip ? 320 : 640)), crop, at);+ writeFileSync(out, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));+ console.log(`${out} (${ts.length} frames) ms/frame: ${ms.join(' ')}`);+} else if (args.stills) {+ const page = await openPage(), out = args.out || 'out/stills'; mkdirSync(out, { recursive: true });+ console.log('GPU:', await page.evaluate(() => window.gpuInfo()));+ for (const s of times(args.stills)) {+ const t0 = Date.now(), buf = await frameOf(page, s, 'image/png');+ const f = `${out}/t${s.toFixed(2).replace('.', '_')}.png`; writeFileSync(f, buf);+ console.log(`${f} ${Date.now() - t0} ms`);+ }+} else if (args.png) {+ // PNG sequence (for GIFs): a loop's full cycle (frame n equals frame 0, so it isn't rendered), or --range=a:b.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], n = Math.round((b - a) * fps);+ const out = args.out || `out/${args.loop ? 'loop_' + args.loop : 'png'}`, workers = +(args.workers || 3); mkdirSync(out, { recursive: true });+ let next = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < n) { const i = next++; writeFileSync(`${out}/f${String(i).padStart(4, '0')}.png`, await frameOf(page, a + i / fps, 'image/png')); }+ }));+ console.log(`${n} frames → ${out} (${((Date.now() - start) / n).toFixed(0)} ms/frame)`);+} else if (args.frames) {+ // Parallel and resumable: each worker pulls the next missing frame; files are written atomically.+ const probe = await openPage(), len = await lengthOf(probe); await probe.close();+ const [a, b] = args.range ? span(args.range) : [0, len], workers = +(args.workers || 4);+ mkdirSync(FRAMES_DIR, { recursive: true });+ const first = Math.round(a * fps), last = Math.min(Math.ceil(len * fps) - 1, Math.round(b * fps) - 1);+ const todo = []; for (let i = first; i <= last; i++) { const f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`; if (!existsSync(f) || statSync(f).size < 1000) todo.push(i); }+ console.log(`${todo.length} frames to render (${last - first + 1 - todo.length} already done), ${workers} workers`);+ let next = 0, done = 0; const start = Date.now();+ await Promise.all(Array.from({ length: workers }, async (_, w) => {+ const page = await openPage('#' + w);+ while (next < todo.length) {+ const i = todo[next++], f = `${FRAMES_DIR}/f${String(i).padStart(5, '0')}.jpg`;+ const buf = await frameOf(page, i / fps, 'image/jpeg', .94);+ writeFileSync(f + '.tmp', buf); renameSync(f + '.tmp', f);+ if (++done % 24 === 0 || done === todo.length) {+ const el = (Date.now() - start) / 1000;+ console.log(`frame ${done}/${todo.length} ${(el / done * 1000).toFixed(0)} ms/frame effective eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);+ }+ }+ }));+} else if (args.clip) {+ const page = await openPage(), len = await lengthOf(page);+ const [a, b] = args.range ? span(args.range) : typeof args.clip === 'string' ? span(args.clip) : [0, len];+ const audio = args.audio || await page.evaluate(() => PROJECT.audio || '');+ const out = args.out || 'out/clip.mp4'; mkdirSync(dirname(out), { recursive: true });+ const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',+ ...(audio ? ['-ss', String(a), '-t', String(b - a), '-i', audio, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-b:a', '192k', '-shortest'] : []),+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', ...TV_RANGE, '-movflags', '+faststart', out],+ { stdio: ['pipe', 'inherit', 'inherit'] });+ const n = Math.round((b - a) * fps), start = Date.now();+ for (let i = 0; i < n; i++) {+ const buf = await frameOf(page, a + i / fps, 'image/jpeg', .93);+ if (!ff.stdin.write(buf)) await new Promise(r => ff.stdin.once('drain', r));+ if (i % 24 === 0 || i === n - 1) console.log(`frame ${i + 1}/${n} ${((Date.now() - start) / (i + 1)).toFixed(0)} ms/frame`);+ }+ ff.stdin.end(); await new Promise(r => ff.on('close', r));+ console.log(`wrote ${out}`);+} else {+ console.log('nothing to do: see the usage notes at the top of render.mjs');+}+await browser.close();diff --git a/.claude/skills/whiteboard/template/src/cast.js b/.claude/skills/whiteboard/template/src/cast.jsnew file mode 100644index 0000000..b6fced1--- /dev/null+++ b/.claude/skills/whiteboard/template/src/cast.js@@ -0,0 +1,273 @@+// cast.js: the whiteboard engine's doodle characters. Two originals:+// bo(x, y, u, o) a round-headed kid in a shirt (noodle limbs, a black mop of hair with one curl)+// mochi(x, y, u, o) a small round cat with one orange ear and an orange-tipped tail+// x,y = the point between the feet on the ground (world px); u = size unit (Bo is ~10.5u tall, Mochi ~7.8u).+// Common options:+// face: an EXPR name ('neutral','happy','laugh','sad','cry','angry','surprised','scared','love','sleepy','thinking',+// 'wink','proud','confused','excited','dizzy') look: [lx, ly] eye direction (-1..1)+// view: 0 front … 1 side (facing right; flip: true faces left) sq: squash (+) / stretch (-) dy: lift in u+// arm: [[angle, bend], [angle, bend]] (degrees; 0 = hanging down, + = outward/forward and up; bend + = elbow up)+// leg: [[angle, bend], ...] (Bo only) walk: phase in cycles (use stroll()) tilt: head tilt (radians)+// hold: { R: 'bulb' | 'phone' | … | fn(x,y,u,key) → strokes, L: … } emote: '!', '?', 'zzz', 'hearts', 'sweat', …+// draw: [a, b] → the character is drawn on between a and b (the hand follows), then stays; hand: false hides the hand+// shirt: colour w: line width t: time for blinks/idles (defaults to the video time) blink: true forces a blink+// id: wobble seed (give two copies of the same character different ids)+// Returns { hand: { L: [x,y], R: [x,y] }, head: [x,y], top: [x,y], strokes }.+// mood(lt, [[t,'face'], ...]) → { face, sq, dy, blink }: acted expression changes (blink + take on each change).+// stroll(lt, t0, t1, x0, x1, u) → { x, walk, flip, moving }: walk from x0 to x1 between t0 and t1.++const EXPR = {+ neutral: { eyes: 'dot', mouth: 'small' },+ happy: { eyes: 'happy', mouth: 'smile', blush: 1 },+ laugh: { eyes: 'happy', mouth: 'open', blush: 1, fx: 'lines' },+ sad: { eyes: 'dot', brows: 'sad', mouth: 'frown', look: [0, .5] },+ cry: { eyes: 'closed', brows: 'sad', mouth: 'wail', fx: 'tears' },+ angry: { eyes: 'dot', brows: 'angry', mouth: 'grit', fx: 'anger' },+ surprised: { eyes: 'big', brows: 'up', mouth: 'o' },+ scared: { eyes: 'tiny', brows: 'sad', mouth: 'wavy', fx: 'sweat' },+ love: { eyes: 'heart', mouth: 'smile', blush: 1, fx: 'hearts' },+ sleepy: { eyes: 'line', mouth: 'osmall', fx: 'zzz' },+ thinking: { eyes: 'dot', brows: 'think', mouth: 'side', look: [.5, -.6], fx: '?' },+ wink: { eyes: 'wink', mouth: 'smile', blush: 1 },+ proud: { eyes: 'happy', brows: 'up', mouth: 'smirk', fx: 'sparkle' },+ confused: { eyes: 'uneven', brows: 'think', mouth: 'wavy', fx: '?' },+ excited: { eyes: 'big', brows: 'up', mouth: 'open', blush: 1, fx: '!' },+ dizzy: { eyes: 'x', mouth: 'wavy', fx: 'swirl' },+};+const EXPR_NAMES = Object.keys(EXPR);++// automatic blinks: ~every 3.4 s, 0.1 s long, desynchronised by seed+function blinkAt(t, seed = 0) { const p = 3.4, s = t + seed * 1.37, k = Math.floor(s / p), ph = s - k * p - hash(k * 3.1 + seed) * 2; return ph >= 0 && ph < .1; }+function mood(lt, keys, amt = .6) {+ let i = 0; while (i + 1 < keys.length && lt >= keys[i + 1][0]) i++;+ let sq = 0, dy = 0, blink = false;+ for (let j = 1; j < keys.length; j++) { const tk = keys[j][0]; if (lt > tk - .08 && lt < tk + .04) blink = true; const k = take(lt, tk, keys[j][2] ?? amt); sq += k.sq; dy += k.dy; }+ return { face: keys[i][1], sq, dy, blink };+}+function stroll(lt, t0, t1, x0, x1, u, cycle = 4.4) {+ const k = seg(lt, t0, t1), e = lerp(k, ease(k), .5), x = lerp(x0, x1, e), moving = lt > t0 && lt < t1;+ return { x, walk: moving ? Math.abs(x - x0) / (u * cycle) : null, flip: x1 < x0, moving };+}++// ---------- shared building blocks ----------+function _rig(x, y, u, o, id) {+ const f = o.flip ? -1 : 1, sq = o.sq || 0, sx = u * (1 + sq), sy = u * (1 - sq), dyy = (o.dy || 0) * u;+ const P = (lx, ly) => [x + f * lx * sx, y + ly * sy + dyy];+ const lw = o.w || clamp(u * .46, 3.5, 20), out = [];+ const add = (st, z) => { for (const s of flatStrokes(st)) { s.z = z; out.push(s); } };+ const line = (k, pts, z = 0, q = {}) => add(S.path(pts.map(p => P(...p)), { key: id + k, wob: u * .035, bow: 0, w: lw, ...q }), z);+ const loop = (k, pts, z = 0, q = {}) => add(S.path(pts.map(p => P(...p)), { key: id + k, wob: u * .03, bow: 0, w: lw, closed: true, ...q }), z);+ const fill = (pts, col, z, q = {}) => add(S.fill(catmull(pts.map(p => P(...p)), true, 8), { col, mode: 'cover', alpha: 1, shift: [u * .1, u * .07], ...q }), z);+ const ell = (cx, cy, rx, ry, n = 22) => { const p = []; for (let i = 0; i < n; i++) { const a = i / n * TAU; p.push([cx + rx * Math.cos(a), cy + ry * Math.sin(a)]); } return p; };+ return { f, P, lw, out, add, line, loop, fill, ell, u, id };+}+// limb: start S (local), upper length l1 at angle a (deg from down, + toward dir), forearm l2 at a+b+function _limb(Sx, Sy, dir, a, b, l1, l2) {+ const r1 = a * Math.PI / 180, r2 = (a + b) * Math.PI / 180, E = [Sx + dir * l1 * Math.sin(r1), Sy + l1 * Math.cos(r1)];+ return { E, H: [E[0] + dir * l2 * Math.sin(r2), E[1] + l2 * Math.cos(r2)], ang: r2 };+}+// the face: eyes, brows, mouth, blush and effects around the head. (fx,fy) face centre, sep eye spacing, head = [hx,hy,hr]+function _face(R, fx, fy, sep, e, o, head, cat) {+ const { line, add, P, lw, u, id } = R, lk = o.look || e.look || [0, 0], eyes = e.eyes;+ const ew = lw * .95, dotR = u * .3, faceZ = 4;+ [-1, 1].forEach(s => {+ const ex = fx + s * sep + lk[0] * .16, ey = fy + lk[1] * .14, k = 'e' + s;+ let ty = eyes; if (ty === 'wink') ty = s < 0 ? 'dot' : 'happy'; if (ty === 'uneven') ty = s < 0 ? 'dot' : 'big';+ if (o.blink && ['dot', 'big', 'tiny', 'uneven', 'wink'].includes(e.eyes)) ty = 'line';+ if (ty === 'dot') add(S.dot(...P(ex, ey), dotR * 1.02, {}), faceZ);+ else if (ty === 'big' || ty === 'tiny') {+ add(S.fill(catmull(R.ell(ex, ey - .05, .52, .6).map(p => P(...p)), true, 8), { col: '#FFFFFF', mode: 'cover', alpha: 1, z: faceZ - .2 }), faceZ - .2);+ line(k + 'o', R.ell(ex, ey - .05, .52, .6, 16).concat([R.ell(ex, ey - .05, .52, .6, 16)[0]]), faceZ, { w: ew * .8 });+ add(S.dot(...P(ex + lk[0] * .18, ey + lk[1] * .18), ty === 'big' ? u * .24 : u * .12), faceZ + .1);+ }+ else if (ty === 'happy') line(k, [[ex - .38, ey + .14], [ex, ey - .22], [ex + .38, ey + .14]], faceZ, { w: ew });+ else if (ty === 'closed') line(k, [[ex - .38, ey - .06], [ex, ey + .18], [ex + .38, ey - .06]], faceZ, { w: ew });+ else if (ty === 'line') line(k, [[ex - .36, ey + .02], [ex + .36, ey + .02]], faceZ, { w: ew });+ else if (ty === 'x') { line(k + 'a', [[ex - .3, ey - .3], [ex + .3, ey + .3]], faceZ, { w: ew * .9 }); line(k + 'b', [[ex + .3, ey - .3], [ex - .3, ey + .3]], faceZ, { w: ew * .9 }); }+ else if (ty === 'heart') { const [hx, hy] = P(ex, ey); add([S.heart(hx, hy, u * 1.05, { key: id + k, col: INK.red, w: ew * .8 }), S.fill(polyCircle(hx, hy - u * .05, u * .36, u * .3), { col: INK.red, alpha: .9 })], faceZ); }+ // brows+ const b = e.brows, inner = -s;+ if (b === 'up') line(k + 'b', [[ex - .34, ey - .86], [ex, ey - 1.06], [ex + .34, ey - .86]], faceZ, { w: ew * .85 });+ else if (b === 'angry') line(k + 'b', [[ex - inner * .46, ey - 1.0], [ex + inner * .34, ey - .62]], faceZ, { w: ew });+ else if (b === 'sad') line(k + 'b', [[ex - inner * .44, ey - .66], [ex + inner * .34, ey - .98]], faceZ, { w: ew * .9 });+ else if (b === 'think') line(k + 'b', s < 0 ? [[ex - .34, ey - .78], [ex + .3, ey - .8]] : [[ex - .34, ey - .9], [ex, ey - 1.14], [ex + .34, ey - .98]], faceZ, { w: ew * .85 });+ if (e.blush) add(S.line(...P(ex - .3 + s * .12, fy + .72), ...P(ex + .3 + s * .12, fy + .6), { key: id + k + 'bl', hl: true, col: HL.pink, w: u * .4, alpha: .75, wob: 0 }), faceZ - .5);+ if (e.fx === 'tears') { const tt = frac((o.t ?? T) * 1.6 + (s > 0 ? .5 : 0)); line(k + 'tr', [[ex + s * .1, ey + .25], [ex + s * .28, ey + .9], [ex + s * .22, ey + 1.6]], faceZ, { col: INK.blue, w: ew * .9 });+ add(S.dot(...P(ex + s * .25, ey + 1.7 + tt * 1.6), u * .16, { col: INK.blue, alpha: 1 - tt }), faceZ); }+ });+ // mouth+ const m = e.mouth, mx = fx + lk[0] * .1, my = fy + 1.05, q = { w: ew };+ const dark = (pts, k) => { add(S.fill(catmull(pts.map(p => P(...p)), true, 6), { col: INK.black, mode: 'cover', alpha: 1 }), faceZ); line(k, [...pts, pts[0]], faceZ + .1, { w: ew * .8, closed: true }); };+ if (cat && (m === 'small' || m === 'smile')) { line('mw', [[mx - .5, my - .12], [mx - .25, my + (m === 'smile' ? .2 : .1)], [mx, my - .06], [mx + .25, my + (m === 'smile' ? .2 : .1)], [mx + .5, my - .12]], faceZ, q); }+ else if (m === 'small') line('m', [[mx - .3, my], [mx, my + .12], [mx + .3, my]], faceZ, q);+ else if (m === 'smile') line('m', [[mx - .62, my - .12], [mx, my + .36], [mx + .62, my - .12]], faceZ, q);+ else if (m === 'frown') line('m', [[mx - .5, my + .24], [mx, my - .1], [mx + .5, my + .24]], faceZ, q);+ else if (m === 'side') line('m', [[mx - .1, my + .04], [mx + .45, my - .1]], faceZ, q);+ else if (m === 'smirk') line('m', [[mx - .5, my], [mx + .05, my + .2], [mx + .5, my - .18]], faceZ, q);+ else if (m === 'wavy') line('m', [[mx - .55, my + .05], [mx - .28, my - .1], [mx, my + .05], [mx + .28, my - .1], [mx + .55, my + .05]], faceZ, { w: ew * .85 });+ else if (m === 'o') dark(R.ell(mx, my + .1, .3, .38, 12), 'm');+ else if (m === 'osmall') dark(R.ell(mx, my + .05, .16, .2, 10), 'm');+ else if (m === 'open') { const pts = [[mx - .7, my - .15], [mx - .35, my + .5], [mx, my + .72], [mx + .35, my + .5], [mx + .7, my - .15], [mx, my - .1]]; dark(pts, 'm'); add(S.fill(catmull(R.ell(mx, my + .45, .3, .16, 10).map(p => P(...p)), true, 6), { col: INK.red, mode: 'cover', alpha: 1 }), faceZ + .05); }+ else if (m === 'wail') dark([[mx - .5, my + .45], [mx - .3, my + .02], [mx, my - .1], [mx + .3, my + .02], [mx + .5, my + .45], [mx, my + .6]], 'm');+ else if (m === 'grit') { line('m', [[mx - .55, my - .16], [mx + .55, my - .16], [mx + .55, my + .2], [mx - .55, my + .2], [mx - .55, my - .16]], faceZ, { w: ew * .8, straight: true }); line('m2', [[mx - .5, my + .02], [mx + .5, my + .02]], faceZ, { w: ew * .6 }); }+ // effects around the head+ const [hx, hy, hr] = head, tt = o.t ?? T, fx2 = e.fx || o.emote, side = 1, em = o.emote || fx2;+ const ex = hx + side * hr * .95, ey = hy - hr * 1.0;+ const eq = { w: lw * .9 };+ if (em === 'anger') { const c = [hx + hr * .78, hy - hr * .78]; [0, 1, 2, 3].forEach(i => { const a = i * Math.PI / 2 + Math.PI / 4; line('an' + i, [[c[0] + Math.cos(a) * .5 - Math.sin(a) * .2, c[1] + Math.sin(a) * .5 + Math.cos(a) * .2], [c[0] + Math.cos(a) * .2, c[1] + Math.sin(a) * .2], [c[0] + Math.cos(a) * .5 + Math.sin(a) * .2, c[1] + Math.sin(a) * .5 - Math.cos(a) * .2]], 7, { col: INK.red, w: lw * .8 }); }); }+ if (em === 'sweat') { const d = [hx + hr * .92, hy - hr * .35 + frac(tt * .8) * .6]; line('sw', [[d[0], d[1] - .6], [d[0] + .3, d[1] + .05], [d[0], d[1] + .3], [d[0] - .3, d[1] + .05], [d[0], d[1] - .6]], 7, { col: INK.blue, w: lw * .75 }); }+ if (em === 'hearts') [0, 1].forEach(i => { const k = frac(tt * .6 + i * .5), [px, py] = P(hx + (i ? 1.4 : -1.2) + Math.sin(k * 6 + i) * .25, hy - hr - .4 - k * 2.2); if (k < .9) add([S.heart(px, py, u * (.8 + .3 * i), { key: id + 'hh' + i, col: INK.red, w: lw * .7 }), S.fill(polyCircle(px, py - u * .05, u * .28 * (1 + .3 * i), u * .22 * (1 + .3 * i)), { col: INK.red, alpha: .85 })], 7); });+ if (em === 'zzz') [0, 1, 2].forEach(i => { const k = frac(tt * .45 + i / 3), s = .35 + k * .4, zx = hx + hr * .7 + k * 1.6, zy = hy - hr - .2 - k * 2.4; if (k < .92) line('z' + i, [[zx - s, zy - s], [zx + s, zy - s], [zx - s, zy + s], [zx + s, zy + s]], 7, { col: INK.blue, w: lw * .75, straight: true, key: id + 'z' + i }); });+ if (em === 'sparkle') [[hx + hr * 1.1, hy - hr * .9, .45], [hx + hr * 1.45, hy - hr * .3, .3]].forEach(([a, b, s], i) => { const k = .7 + .3 * Math.sin(tt * 8 + i * 2); line('sp' + i, [[a, b - s * k], [a, b + s * k]], 7, { col: INK.orange, w: lw * .8 }); line('sq' + i, [[a - s * k, b], [a + s * k, b]], 7, { col: INK.orange, w: lw * .8 }); });+ if (em === 'lines') [0, 1, 2].forEach(i => { const a = -1.9 + i * .38; line('ln' + i, [[hx + Math.cos(a) * (hr + .5), hy + Math.sin(a) * (hr + .5)], [hx + Math.cos(a) * (hr + 1.2), hy + Math.sin(a) * (hr + 1.2)]], 7, { col: INK.orange, w: lw * .8 }); });+ if (em === '?') { const qx = hx + hr * .9, qy = hy - hr - 1.3, b = Math.sin(tt * 5) * .12; line('q', [[qx - .5, qy - .6 + b], [qx, qy - 1.05 + b], [qx + .5, qy - .55 + b], [qx, qy + .05 + b], [qx, qy + .45 + b]], 7, { col: INK.orange, w: lw }); add(S.dot(...P(qx, qy + .95 + b), lw * .65, { col: INK.orange }), 7); }+ if (em === '!') { const qx = hx + hr * .9, qy = hy - hr - 1.2, b = Math.abs(Math.sin(tt * 7)) * -.15; line('x', [[qx, qy - 1 + b], [qx + .05, qy + .35 + b]], 7, { col: INK.red, w: lw * 1.2 }); add(S.dot(...P(qx + .05, qy + .9 + b), lw * .75, { col: INK.red }), 7); }+ if (em === 'swirl') line('sr', Array.from({ length: 20 }, (_, i) => { const a = i / 19 * TAU * 1.5 + tt * 6; return [hx + Math.cos(a) * 1.3, hy - hr - .5 + Math.sin(a) * .35]; }), 7, { col: INK.purple, w: lw * .7 });+}+function _hold(R, prop, hp, key) {+ if (!prop) return;+ const st = typeof prop === 'function' ? prop(hp[0], hp[1], R.u, key) : PROPS[prop] ? PROPS[prop](hp[0], hp[1], R.u, key) : null;+ if (st) R.add(st, 5.2);+}+function _finish(R, o, ret) {+ ret.strokes = R.out;+ if (o.strokesOnly) return ret;+ if (o.draw) drawOn(R.out, o.draw[0], o.draw[1], { hand: o.hand, t: o.clock });+ else ink(R.out, { alpha: o.alpha });+ return ret;+}++// ---------- props (grip point = hand position; upright) ----------+const PROPS = {+ bulb: (x, y, u, k) => ICON.bulb(x, y - 1.8 * u, 3.8 * u, { key: k + 'bulb' }),+ bulbOn: (x, y, u, k) => ICON.bulb(x, y - 1.8 * u, 3.8 * u, { key: k + 'bulb', rays: true }),+ phone: (x, y, u, k) => ICON.phone(x, y - 1 * u, 2.6 * u, { key: k + 'ph' }),+ coin: (x, y, u, k) => ICON.coin(x, y - 1.2 * u, 2.4 * u, { key: k + 'co' }),+ heart: (x, y, u, k) => ICON.heart(x, y - 1.5 * u, 2.8 * u, { key: k + 'he' }),+ star: (x, y, u, k) => ICON.star(x, y - 1.5 * u, 2.8 * u, { key: k + 'sr' }),+ flag: (x, y, u, k) => [S.line(x, y + .9 * u, x, y - 3.4 * u, { key: k + 'fp', wob: .5 }), S.path([[x, y - 3.3 * u], [x + 2 * u, y - 2.8 * u], [x, y - 2.1 * u]], { key: k + 'ff', straight: true }), S.fill([[x, y - 3.3 * u], [x + 2 * u, y - 2.8 * u], [x, y - 2.1 * u]], { col: INK.red })],+ balloon: (x, y, u, k) => [S.path([[x, y], [x + .3 * u, y - 1.5 * u], [x - .1 * u, y - 3 * u]], { key: k + 'bs', w: WB.w * .5 }), S.circle(x - .1 * u, y - 4.3 * u, 1.1 * u, 1.3 * u, { key: k + 'bb', turns: 1 }), S.fill(polyCircle(x - .1 * u, y - 4.3 * u, 1.05 * u, 1.25 * u), { col: INK.red, alpha: .85 })],+ book: (x, y, u, k) => [S.rect(x - 1.1 * u, y - 1.6 * u, 2.2 * u, 1.6 * u, { key: k + 'bk', r: 4 }), S.line(x, y - 1.6 * u, x, y, { key: k + 'bl' }), S.fill(polyRect(x - 1.1 * u, y - 1.6 * u, 2.2 * u, 1.6 * u), { col: INK.blue, alpha: .8 })],+ cup: (x, y, u, k) => [S.path([[x - .8 * u, y - 1.6 * u], [x - .7 * u, y + .3 * u], [x + .7 * u, y + .3 * u], [x + .8 * u, y - 1.6 * u]], { key: k + 'cu', straight: true }), S.path([[x + .8 * u, y - 1.2 * u], [x + 1.3 * u, y - .9 * u], [x + .75 * u, y - .3 * u]], { key: k + 'ch' }), S.fill(polyRect(x - .75 * u, y - 1.55 * u, 1.5 * u, 1.8 * u), { col: INK.orange, alpha: .8 }), S.wave(x - .2 * u, y - 2 * u, x - .1 * u, y - 3.1 * u, 4, 1.5, { key: k + 'st', col: INK.grey, w: WB.w * .6 })],+ fish: (x, y, u, k) => { const p = [[x - 1.3 * u, y - .7 * u], [x - .2 * u, y - 1.3 * u], [x + .9 * u, y - .7 * u], [x - .2 * u, y - .1 * u]]; return [S.path(p, { key: k + 'fs', closed: true }), S.path([[x + .8 * u, y - .7 * u], [x + 1.5 * u, y - 1.2 * u], [x + 1.5 * u, y - .2 * u], [x + .8 * u, y - .7 * u]], { key: k + 'ft', straight: true }), S.dot(x - .75 * u, y - .8 * u, WB.w * .45), S.fill(catmull(p, true), { col: HL.blue, alpha: .9 })]; },+ marker: (x, y, u, k) => [S.rect(x - .25 * u, y - 2 * u, .5 * u, 2.6 * u, { key: k + 'mk', r: 4 }), S.fill(polyRect(x - .25 * u, y - 2 * u, .5 * u, .7 * u), { col: INK.blue })],+ sign: (x, y, u, k) => [S.line(x, y + .8 * u, x, y - 2 * u, { key: k + 'sp' }), S.rect(x - 2.2 * u, y - 4.6 * u, 4.4 * u, 2.6 * u, { key: k + 'sr', r: 6 }), S.fill(polyRect(x - 2.2 * u, y - 4.6 * u, 4.4 * u, 2.6 * u), { col: '#FFFFFF', mode: 'cover', alpha: 1 })],+};++// ---------- Bo: the round-headed kid ----------+function bo(x, y, u, o = {}) {+ const id = o.id || 'bo', R = _rig(x, y, u, o, id), { line, loop, fill, add, P, lw } = R;+ const e = EXPR[o.face || 'neutral'] || EXPR.neutral, v = clamp(o.view || 0), t = o.t ?? T;+ const blink = o.blink || (!o.noBlink && blinkAt(t, id.length));+ const oo = { ...o, blink, t };+ let arms = o.arm || [[24, 14], [24, 14]], legs = o.leg || [[5, 0], [5, 0]], dyWalk = 0;+ if (o.walk != null) {+ const q = o.walk * TAU; dyWalk = -.2 * Math.abs(Math.cos(q));+ const lg = ph => [30 * Math.sin(ph), -45 * Math.max(0, Math.cos(ph))];+ if (v >= .5) { legs = [lg(q), lg(q + Math.PI)]; if (!o.arm) arms = [[-26 * Math.sin(q), 25], [26 * Math.sin(q), 25]]; }+ else { legs = [[5, -30 * Math.max(0, Math.sin(q))], [5, -30 * Math.max(0, -Math.sin(q))]]; }+ }+ const dy0 = dyWalk, Y = yy => yy + dy0;+ const hx = 0, hy = Y(-7.75), hr = 2.35, side = v >= .5;+ const headTilt = o.tilt || 0, fx = hx + v * 1.1 + (o.look ? o.look[0] * .2 : 0), fy = hy + .15;+ const shx = 1.05 * (1 - .7 * v), hipx = .68 * (1 - .75 * v);+ // head (skin fill + wobbly circle outline), hair, ears+ add(S.circle(...P(hx, hy), hr * u * (1 + (o.sq || 0)), hr * u * (1 - (o.sq || 0)), { key: id + 'head', w: lw, turns: 1.04, a0: -2.4, spiral: .02, wob: u * .03 }), 3);+ if (!side) [-1, 1].forEach(s => line('ear' + s, [[s * (hr - .1), hy - .45], [s * (hr + .38), hy - .3], [s * (hr + .38), hy + .3], [s * (hr - .1), hy + .45]], 2.9, { w: lw * .9 }));+ else { const ear = R.ell(-1.05, hy + .3, .36, .48, 14); add(S.fill(catmull(ear.map(p => P(...p)), true, 6), { col: INK.skin, mode: 'cover', alpha: 1, cost: u * .4 }), 3.6); loop('ear', ear, 3.7, { w: lw * .85 }); line('earin', [[-1.02, hy + .12], [-1.15, hy + .32], [-1.0, hy + .5]], 3.8, { w: lw * .55 }); }+ const a0 = (196 - 34 * v) * Math.PI / 180, a1 = (344 - 26 * v) * Math.PI / 180, hair = [];+ for (let i = 0; i <= 12; i++) { const a = lerp(a0, a1, i / 12); hair.push([hx + Math.cos(a) * hr * 1.03, hy + Math.sin(a) * hr * 1.03]); }+ for (let i = 0; i <= 8; i++) { const a = lerp(a1, a0, i / 8), r = i % 2 ? .58 : .76; hair.push([hx + Math.cos(a) * hr * r, hy + Math.sin(a) * hr * r + .25]); }+ add(S.fill(hair.map(p => P(...p)), { col: INK.black, mode: 'cover', alpha: 1, cost: u * 3 }), 3.4);+ line('curl', [[hx + .2 - v * .4, hy - hr * 1.0], [hx + .5 - v * .4, hy - hr - .9], [hx + 1.25 - v * .4, hy - hr - .95], [hx + 1.2 - v * .4, hy - hr - .35], [hx + .65 - v * .4, hy - hr - .5]], 3.5, { w: lw * .95 });+ // face+ _face(R, fx, fy, .85 * (1 - .28 * v), e, oo, [hx, hy, hr], false);+ // torso (shirt)+ const tw = 1 - .25 * v, torso = [[-1.05 * tw, Y(-5.5)], [1.05 * tw, Y(-5.5)], [1.55 * tw, Y(-2.8)], [1.35 * tw, Y(-2.35)], [-1.35 * tw, Y(-2.35)], [-1.55 * tw, Y(-2.8)]];+ loop('torso', torso, 1);+ if (!side) line('collar', [[-.45, Y(-5.45)], [0, Y(-5.0)], [.45, Y(-5.45)]], 1.1, { w: lw * .75 });+ // limbs: in front view index 0 = screen-left arm/leg (outward = -x); in side view both point forward (+x)+ const hands = {};+ [0, 1].forEach(i => {+ const s = i ? 1 : -1, dir = side ? 1 : s, far = side && i === 0, z = far ? -3 : 5;+ const [la, lb] = legs[i] || [5, 0], L = _limb(s * hipx, Y(-2.5), dir, la, lb, 1.28, 1.22);+ line('leg' + i, [[s * hipx, Y(-2.6)], L.E, L.H], far ? -3 : -2, { w: lw * 1.05 });+ const fxo = side ? .32 : s * .22, shoe = R.ell(L.H[0] + fxo, L.H[1] - .05, .6, .3, 14);+ add(S.fill(catmull(shoe.map(p => P(...p)), true, 6), { col: INK.black, mode: 'cover', alpha: 1, shift: [0, 0], cost: u }), far ? -2.9 : -1.9);+ const [aa, ab] = arms[i] || [14, 12], A = _limb(s * shx, Y(-5.05), dir, aa, ab, 1.45, 1.35);+ line('arm' + i, [[s * shx * .92, Y(-5.15)], A.E, A.H], z, { w: lw * 1.02 });+ const hp = P(...A.H); hands[i ? 'R' : 'L'] = hp;+ _hold(R, o.hold && o.hold[i ? 'R' : 'L'], hp, id + i);+ add(S.fill(polyCircle(hp[0], hp[1], u * .44), { col: INK.skin, mode: 'cover', alpha: 1, shift: [0, 0], cost: u * .5 }), z + .5);+ add(S.circle(hp[0], hp[1], u * .44, u * .44, { key: id + 'hand' + i, w: lw * .9, wob: 0, turns: 1.02 }), z + 1);+ });+ // colour last: head skin + shirt+ fill(R.ell(hx, hy, hr * .99, hr * .99, 26), INK.skin, 2.5, { shift: [0, 0] });+ fill(torso, o.shirt || INK.orange, .5, { mode: 'cover' });+ return _finish(R, o, { hand: hands, head: P(hx, hy), top: P(hx, hy - hr - 1), strokes: null });+}++// ---------- Mochi: the round cat ----------+function mochi(x, y, u, o = {}) {+ const id = o.id || 'mochi', R = _rig(x, y, u, o, id), { line, loop, fill, add, P, lw } = R;+ const e = EXPR[o.face || 'neutral'] || EXPR.neutral, v = clamp(o.view || 0), t = o.t ?? T;+ const blink = o.blink || (!o.noBlink && blinkAt(t, id.length + 3)), oo = { ...o, blink, t };+ const sway = Math.sin(t * 2.4 + 1) * .25, hands = {};+ if (v < .5) { // ---- front, sitting+ const half = [[0, 0], [1.7, .02], [2.35, -.7], [2.45, -1.9], [2.1, -3.15], [2.3, -4.3], [2.1, -5.45], [1.9, -6.15], [2.05, -7.65], [1.0, -6.75], [0, -6.85]];+ const out = [...half, ...half.slice(1, -1).reverse().map(([a, b]) => [-a, b])];+ const tip = [8, 12]; // indices of the two ear tips (right ear at 8, left ear mirrored at 12)+ add(S.path(out.map(p => P(...p)), { key: id + 'body', closed: true, sharp: tip, wob: u * .03, bow: 0, w: lw }), 1);+ // tail behind the body (right side)+ const tl = [[2.0, -.6], [3.2, -.8], [3.9 + sway * .3, -2.0], [3.5 + sway, -3.1], [2.9 + sway, -3.3]];+ line('tail', tl, -1, { w: lw });+ const tp = catmull(tl.map(p => P(...p))), n = tp.length;+ add(mk(tp.slice(Math.floor(n * .72)), { col: INK.orange, w: lw * 2.1 }), -.9);+ // face, whiskers, nose+ const fx = (o.look ? o.look[0] * .15 : 0), fy = -4.7;+ _face(R, fx, fy, .95, e, oo, [0, -4.5, 2.4], true);+ add(S.fill([P(fx - .22, fy + .5), P(fx + .22, fy + .5), P(fx, fy + .78)], { col: INK.pink, mode: 'cover', alpha: 1, shift: [0, 0], cost: u * .3 }), 4.2);+ [-1, 1].forEach(s => { line('wh' + s + 'a', [[s * 1.55, -4.05], [s * 2.95, -4.35]], 4, { w: lw * .6 }); line('wh' + s + 'b', [[s * 1.55, -3.7], [s * 2.9, -3.55]], 4, { w: lw * .6 }); });+ // front paws (arms) + feet+ // front legs (they double as arms: raise them to hold things) + the back feet peeking out at the sides+ const arms = o.arm || [[3, 0], [3, 0]];+ [0, 1].forEach(i => {+ const s = i ? 1 : -1, [aa, ab] = arms[i], A = _limb(s * .78, -2.75, s, aa, ab, 1.2, 1.15), up = aa > 40;+ line('arm' + i, [[s * .78, -2.9], A.E, A.H], 5, { w: lw });+ const hp = P(...A.H); hands[i ? 'R' : 'L'] = hp; _hold(R, o.hold && o.hold[i ? 'R' : 'L'], hp, id + i);+ const pr = up ? [u * .42, u * .42] : [u * .5, u * .34], pc = up ? hp : P(A.H[0] + s * .05, A.H[1] - .04);+ add(S.fill(polyCircle(pc[0], pc[1], pr[0], pr[1]), { col: '#FFFFFF', mode: 'cover', alpha: 1, cost: u * .4 }), 5.5);+ add(S.circle(pc[0], pc[1], pr[0], pr[1], { key: id + 'paw' + i, w: lw * .85, wob: 0, turns: 1.02 }), 6);+ line('ft' + i, [[s * 1.55, -.02], [s * 1.95, -.42], [s * 2.3, -.3]], 1.2, { w: lw * .9 });+ });+ fill(out, '#FFFFFF', .2, { shift: [0, 0], sharp: tip });+ add(S.fill([P(-1.9, -6.15), P(-2.05, -7.65), P(-1.0, -6.75), P(-1.2, -5.9)], { col: INK.orange, alpha: .9, cost: u }), .6);+ return _finish(R, o, { hand: hands, head: P(0, -4.6), top: P(0, -7.8), strokes: null });+ }+ // ---- side, standing / walking (facing right)+ const q = (o.walk ?? 0) * TAU, walking = o.walk != null, bob = walking ? -.12 * Math.abs(Math.cos(q)) : 0, Y = yy => yy + bob;+ const body = [[-2.7, Y(-2.6)], [-2.2, Y(-3.8)], [0, Y(-4.1)], [1.9, Y(-3.6)], [2.4, Y(-2.4)], [1.7, Y(-1.45)], [0, Y(-1.3)], [-2.1, Y(-1.45)]];+ const legs = [[1.3, 1], [-1.8, 0], [.9, 0], [-1.4, 1]]; // [hip x, phase offset]: far legs first+ legs.forEach(([lx, ph], i) => {+ const far = i < 2, a = walking ? 26 * Math.sin(q + ph * Math.PI) : 0, L = _limb(lx, Y(-1.6), 1, a, walking ? -20 * Math.max(0, Math.cos(q + ph * Math.PI)) : 0, .8, .8);+ line('lg' + i, [[lx, Y(-1.8)], L.E, L.H], far ? -3 : 1.5, { w: lw, col: far ? mixCol(INK.black, '#FFFFFF', .3) : INK.black });+ add(S.fill(polyCircle(...P(L.H[0] + .1, L.H[1] - .05), u * .32, u * .24), { col: '#FFFFFF', mode: 'cover', alpha: 1, cost: u * .3 }), far ? -2.8 : 1.6);+ add(S.circle(...P(L.H[0] + .1, L.H[1] - .05), u * .32, u * .24, { key: id + 'pw' + i, w: lw * .8, wob: 0 }), far ? -2.7 : 1.7);+ if (!far) hands[i === 2 ? 'R' : 'L'] = P(L.H[0], L.H[1]);+ });+ loop('body', body, 1);+ const tl = [[-2.6, Y(-3.0)], [-3.6, Y(-3.6)], [-3.9 + sway * .5, Y(-4.9)], [-3.4 + sway, Y(-5.7)], [-2.9 + sway, Y(-5.5)]];+ line('tail', tl, -1, { w: lw });+ const tp = catmull(tl.map(p => P(...p))); add(mk(tp.slice(Math.floor(tp.length * .72)), { col: INK.orange, w: lw * 2.1 }), -.9);+ const hx = 2.2, hy = Y(-4.7), hr = 1.95;+ const head = [[hx - 1.9, hy + .2], [hx - 1.55, hy - 1.3], [hx - 1.4, hy - 2.7], [hx - .45, hy - 1.95], [hx + .5, hy - 2.0], [hx + 1.3, hy - 2.75], [hx + 1.45, hy - 1.3], [hx + 1.95, hy + .1], [hx + 1.3, hy + 1.55], [hx, hy + 1.8], [hx - 1.4, hy + 1.45]];+ add(S.path(head.map(p => P(...p)), { key: id + 'head', closed: true, sharp: [2, 5], wob: u * .03, bow: 0, w: lw }), 3);+ fill(head, '#FFFFFF', 2.5, { shift: [0, 0] });+ add(S.fill([P(hx - 1.55, hy - 1.3), P(hx - 1.4, hy - 2.7), P(hx - .45, hy - 1.95), P(hx - .9, hy - 1.3)], { col: INK.orange, alpha: .9, cost: u }), 3.1);+ _face(R, hx + .45 + (o.look ? o.look[0] * .12 : 0), hy + .1, .72, e, oo, [hx, hy + .3, 2.0], true);+ add(S.fill([P(hx + .25, hy + .6), P(hx + .65, hy + .6), P(hx + .45, hy + .85)], { col: INK.pink, mode: 'cover', alpha: 1, cost: u * .3 }), 4.2);+ line('wha', [[hx + 1.5, hy + .7], [hx + 2.7, hy + .45]], 4, { w: lw * .6 }); line('whb', [[hx + 1.5, hy + 1.0], [hx + 2.6, hy + 1.15]], 4, { w: lw * .6 });+ fill(body, '#FFFFFF', .2, { shift: [0, 0] });+ if (o.hold && o.hold.R) _hold(R, o.hold.R, P(hx + 1.7, hy + 1.3), id + 'm'); // carried in the mouth+ return _finish(R, o, { hand: hands, head: P(hx, hy), top: P(hx, hy - 2.9), strokes: null });+}diff --git a/.claude/skills/whiteboard/template/src/config.js b/.claude/skills/whiteboard/template/src/config.jsnew file mode 100644index 0000000..4bbf18e--- /dev/null+++ b/.claude/skills/whiteboard/template/src/config.js@@ -0,0 +1,2 @@+// length (s), tempo (idles and hits ride the beat), beat offset, frame rate+const PROJECT = { duration: 10, bpm: 100, offset: 0, fps: 24 };diff --git a/.claude/skills/whiteboard/template/src/kit.js b/.claude/skills/whiteboard/template/src/kit.jsnew file mode 100644index 0000000..8d6f3c2--- /dev/null+++ b/.claude/skills/whiteboard/template/src/kit.js@@ -0,0 +1,154 @@+// kit.js: the shared runtime for ReelMimic's Canvas-2D drawing engines (pixel art, paper cut-out, whiteboard, anime+// cel, crayon storybook). Each engine copies this file into its template unchanged and adds its own drawing library.+//+// The render contract is the same as painted-animation's, so the same render.mjs drives every engine:+// window.ready = true once fonts and assets are loaded+// window.renderAt(t, type, q) → data URL of the frame at time t+// window.renderSheet(times, cols, w, crop, at) → { url, ms[] } contact sheet (crop = [x,y,w,h] in screen px,+// at = [x,y,w,h] around a WORLD point, wherever the camera put it)+// Every frame is a pure function of t: frames render in parallel and out of order, so nothing may carry over from one+// frame to the next. Use hash()/rnd() for stable randomness, never Math.random().+//+// An engine plugs in through window.ENGINE = { setup(), begin(t), end(t) } (all optional):+// setup() → once, async (load images, build textures); begin(t) → before the shot draws (e.g. switch G to a low-res+// buffer); end(t) → after it (e.g. upscale, add grain). Shots draw with the 2D context G.++const W = 1920, H = 1080, TAU = Math.PI * 2;+const DUR = PROJECT.duration, BPM = PROJECT.bpm || 120, BEAT = 60 / BPM, OFF = PROJECT.offset || 0;+const FPS = PROJECT.fps || 24;++// ---------- math & timing (pure functions of t) ----------+const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));+const lerp = (a, b, x) => a + (b - a) * x;+const ease = x => { x = clamp(x); return x * x * (3 - 2 * x); };+const easeIn = x => Math.pow(clamp(x), 3);+const easeOut = x => 1 - Math.pow(1 - clamp(x), 3);+const backOut = x => { x = clamp(x); const s = 1.9; return 1 + (s + 1) * Math.pow(x - 1, 3) + s * Math.pow(x - 1, 2); };+const elasticOut = x => { x = clamp(x); return x === 0 || x === 1 ? x : Math.pow(2, -10 * x) * Math.sin((x * 10 - .75) * (TAU / 3)) + 1; };+const hash = i => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };+// seeded stream for one element: const r = rnd('tree' + i); r() → 0..1, the same every frame+function rnd(key) { let h = 2166136261; for (const c of String(key)) h = Math.imul(h ^ c.charCodeAt(0), 16777619); let s = h >>> 0 || 1; return () => (s = Math.imul(s ^ (s >>> 15), 2246822519) >>> 0, s = (s ^ (s >>> 13)) >>> 0, (s % 1000003) / 1000003); }+const seg = (t, a, b) => clamp((t - a) / (b - a));+const frac = x => x - Math.floor(x);+const bpOf = t => (t - OFF) / BEAT;+const beatN = t => Math.floor(bpOf(t));+const pulse = (t, k = 6) => Math.exp(-frac(bpOf(t)) * k);+const wob = (t, f = 1, ph = 0) => Math.sin((t * f + ph) * TAU);+// hold drawings like hand animation: onTwos(t) = 12 drawings/s, onStep(t, 8) = 8/s (stop-motion feel)+const onTwos = t => Math.floor(t * 12 + 1e-6) / 12;+const onStep = (t, n) => Math.floor(t * n + 1e-6) / n;+function kf(t, keys, e = ease) {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) if (t < keys[i][0]) {+ const [a, va] = keys[i - 1], [b, vb] = keys[i], k = e((t - a) / (b - a));+ return Array.isArray(va) ? va.map((v, j) => lerp(v, vb[j], k)) : lerp(va, vb, k);+ }+ return keys[keys.length - 1][1];+}+function mixCol(a, b, k) {+ const pa = parseInt(a.slice(1), 16), pb = parseInt(b.slice(1), 16), c = i => Math.round(lerp((pa >> i) & 255, (pb >> i) & 255, clamp(k)));+ return '#' + ((1 << 24) + (c(16) << 16) + (c(8) << 8) + c(0)).toString(16).slice(1);+}+const shakeXY = (t, amt) => { const f = Math.floor(t * 24); return [(hash(f * 1.7) - .5) * 2 * amt, (hash(f * 2.3 + 9) - .5) * 2 * amt]; };+// motion principles+const spring = (t, t0, k = 6, w = 18) => t < t0 ? 0 : Math.exp(-k * (t - t0)) * Math.sin(w * (t - t0));+const arcPt = (p0, p1, h, k) => [lerp(p0[0], p1[0], k), lerp(p0[1], p1[1], k) - h * 4 * k * (1 - k)];+function jump(t, t0, t1, h = 3) { // → { dy (units, up is negative), sq (squash +, stretch -) }+ if (t < t0 - .12) return { dy: 0, sq: 0 };+ if (t < t0) return { dy: 0, sq: .18 * ease(seg(t, t0 - .12, t0)) };+ if (t < t1) { const k = (t - t0) / (t1 - t0); return { dy: -h * 4 * k * (1 - k), sq: -.16 * Math.abs(1 - 2 * k) }; }+ const a = t - t1; return { dy: 0, sq: .22 * Math.exp(-8 * a) * Math.cos(20 * a) };+}+function take(t, t0, amt = 1) { // surprise take peaking at t0+ if (t < t0 - .1) return { sq: 0, dy: 0 };+ if (t < t0) return { sq: .12 * amt * ease(seg(t, t0 - .1, t0)), dy: 0 };+ const a = t - t0; return { sq: -.26 * amt * Math.exp(-6 * a) * Math.cos(16 * a), dy: -1.2 * amt * Math.exp(-7 * a) * Math.max(0, Math.cos(9 * a)) };+}++// ---------- shots ----------+// shots([[t0, fn], ...]); fn(t, lt, dur) paints the WHOLE frame (background included) with G.+const SHOTS = [], LOOPS = {};+function shots(list) { SHOTS.push(...list); SHOTS.sort((a, b) => a[0] - b[0]); }+function drawWorld(t) {+ if (window.LOOP) return window.LOOP(t);+ if (!SHOTS.length) { G.fillStyle = '#EDE6D8'; G.fillRect(0, 0, W, H); return; }+ let i = 0; while (i + 1 < SHOTS.length && t >= SHOTS[i + 1][0]) i++;+ const t0 = SHOTS[i][0], end = i + 1 < SHOTS.length ? SHOTS[i + 1][0] : DUR;+ SHOTS[i][1](t, t - t0, end - t0);+ if (CAM) camEnd();+}++// ---------- camera (world → screen) ----------+let CAM = null, LAST_CAM = null;+function camBegin(cx = W / 2, cy = H / 2, zoom = 1, rot = 0) {+ G.save(); G.translate(W / 2, H / 2); G.rotate(rot); G.scale(zoom, zoom); G.translate(-cx, -cy);+ CAM = LAST_CAM = { cx, cy, zoom, rot };+}+function camEnd() { G.restore(); CAM = null; }+function toScreen(x, y, cam = CAM) {+ if (!cam) return [x, y];+ const dx = (x - cam.cx) * cam.zoom, dy = (y - cam.cy) * cam.zoom, c = Math.cos(cam.rot), s = Math.sin(cam.rot);+ return [W / 2 + dx * c - dy * s, H / 2 + dx * s + dy * c];+}++// ---------- canvases & frame ----------+// G: the context shots draw into (an engine may point it at a low-res buffer in begin()). OUT: the visible 1920×1080.+let G = null, OUT = null, OUTC = null, T = 0;+function makeCanvas(w = W, h = H) { const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }+async function renderFrame(t) {+ T = t; CAM = LAST_CAM = null;+ G = OUT; G.setTransform(1, 0, 0, 1, 0, 0); G.globalAlpha = 1; G.globalCompositeOperation = 'source-over';+ G.clearRect(0, 0, W, H);+ if (window.ENGINE && ENGINE.begin) ENGINE.begin(t);+ drawWorld(t);+ if (window.ENGINE && ENGINE.end) ENGINE.end(t);+ OUT.setTransform(1, 0, 0, 1, 0, 0); OUT.globalAlpha = 1; OUT.globalCompositeOperation = 'source-over';+ if (window.overlayHook) window.overlayHook(OUT, t); // crisp captions / karaoke above everything+}+window.renderAt = async (t, type = 'image/png', q = .92) => { await renderFrame(t); return OUTC.toDataURL(type, q); };+window.renderSheet = async (times, cols = 3, w = 640, crop = null, at = null) => {+ if (at) at = at.map((v) => typeof v === 'string' ? (0, eval)(v) : v);+ const [, , cw, ch] = at || crop || [0, 0, W, H], h = Math.round(w * ch / cw), rows = Math.ceil(times.length / cols), sc = makeCanvas(cols * w, rows * h);+ const c = sc.getContext('2d'), ms = [];+ for (let i = 0; i < times.length; i++) {+ const t0 = performance.now(); await renderFrame(times[i]); ms.push(Math.round(performance.now() - t0));+ const x = (i % cols) * w, y = Math.floor(i / cols) * h;+ const [cx, cy] = at ? toScreen(at[0], at[1], LAST_CAM).map((v, j) => v - (j ? ch : cw) / 2) : crop || [0, 0];+ c.imageSmoothingEnabled = !(window.ENGINE && ENGINE.crisp);+ c.drawImage(OUTC, cx, cy, cw, ch, x, y, w, h);+ c.fillStyle = 'rgba(0,0,0,.65)'; c.fillRect(x, y, 84, 24); c.fillStyle = '#fff'; c.font = '15px sans-serif'; c.fillText(times[i].toFixed(2) + 's', x + 6, y + 17);+ }+ return { url: sc.toDataURL('image/jpeg', .9), ms };+};+window.gpuInfo = () => 'canvas2d';++// ---------- captions (optional) ----------+// A simple, legible caption bar on the overlay: caption(c, text, { y, size, font, fg, bg }). Engines may style their own.+function caption(c, txt, o = {}) {+ const size = o.size || 54, y = o.y || H - 70, font = o.font || `700 ${size}px "Noto Sans TC", "Noto Sans", system-ui, sans-serif`;+ c.save(); c.font = font; c.textAlign = 'center'; c.textBaseline = 'middle';+ const w = c.measureText(txt).width + size * 1.1;+ c.fillStyle = o.bg || 'rgba(20,18,26,.72)'; const r = size * .5;+ c.beginPath(); c.roundRect(W / 2 - w / 2, y - size * .78, w, size * 1.56, r); c.fill();+ c.lineJoin = 'round'; c.lineWidth = size * .14; c.strokeStyle = 'rgba(0,0,0,.55)'; c.strokeText(txt, W / 2, y + 2);+ c.fillStyle = o.fg || '#FFF8EC'; c.fillText(txt, W / 2, y + 2); c.restore();+}++// ---------- boot ----------+async function boot() {+ OUTC = document.getElementById('out'); OUT = OUTC.getContext('2d', { willReadFrequently: false });+ const fonts = [...(window.EXTRA_FONTS || [])].map(([f, txt]) => document.fonts.load(f, txt));+ await Promise.all(fonts);+ if (window.ENGINE && ENGINE.setup) await ENGINE.setup();+ window.ready = true;+ if (!location.search.includes('render')) devUI();+}+function devUI() {+ const s = document.getElementById('scrub'), lab = document.getElementById('tt'); if (!s) return;+ s.max = window.LOOP ? window.LOOP.len : DUR; s.step = 1 / FPS;+ let busy = false, want = null;+ const go = async () => { if (busy) return; busy = true; while (want != null) { const t = want; want = null; const t0 = performance.now(); await renderFrame(t); lab.textContent = `${t.toFixed(2)}s · ${Math.round(performance.now() - t0)} ms/frame`; } busy = false; };+ s.addEventListener('input', () => { want = +s.value; go(); });+ want = +(new URLSearchParams(location.search).get('t') || 0); s.value = want; go();+}+window.addEventListener('load', () => { const q = new URLSearchParams(location.search).get('loop'); if (q && LOOPS[q]) window.LOOP = LOOPS[q]; boot(); });diff --git a/.claude/skills/whiteboard/template/src/scenes/demo.js b/.claude/skills/whiteboard/template/src/scenes/demo.jsnew file mode 100644index 0000000..5380a32--- /dev/null+++ b/.claude/skills/whiteboard/template/src/scenes/demo.js@@ -0,0 +1,57 @@+// demo.js: "Got an idea?" (10 s). Bo is drawn on, thinks, a light bulb appears above him; he jumps and grabs it.+// The eraser wipes the board; Bo walks in with the glowing bulb and shares it with sleepy Mochi, who falls in love.+// Shows: establishing camera move, handwriting + underline, drawn-on character, expression takes, anticipation →+// jump → landing squash, a prop picked up and held, eraser transition, walk cycle, captions.+(() => {+ const U = 42; // Bo's size in shot A+ const BX = 1340, BY = 940; // Bo's feet (world)++ // ---- A: the idea -------------------------------------------------------------------------------------------+ function idea(t, lt, dur) {+ wbBegin(lt, { cam: [[0, [640, 470, 1.12]], [1.1, [690, 478, 1.08]], [2.1, [1170, 560, 1.0]], [dur, [1190, 570, 1.03]]] });++ const title = writeOn('Got an idea?', 300, 470, .15, 1.0, { size: 140, col: INK.blue });+ drawOn(S.underline(title.x, title.y2 + 4, title.w, { col: INK.orange }), 1.05, 1.25);++ // Bo's acting: think → notice the bulb (take) → excited → crouch, jump, grab it at the top → land, laugh+ const m = mood(lt, [[0, 'thinking'], [3.0, 'surprised', .55], [3.35, 'excited'], [4.2, 'laugh', .3]]);+ const J = jump(lt, 3.65, 4.15, 3.8), grab = 3.9;+ const arm = kf(lt, [[3.3, [24, 14, 24, 14]], [3.5, [-12, 30, -12, 30]], [3.65, [-20, 20, -20, 20]], [3.78, [140, 30, 170, 0]], [4.2, [40, 50, 150, 8]], [4.4, [55, 60, 145, 10]]], easeOut);+ const leg = lt > 3.65 && lt < 4.15 ? [[22, -45], [14, -30]] : null;+ const pose = { face: m.face, blink: m.blink, look: lt > 2.8 && lt < grab ? [0, -1] : null, sq: m.sq + J.sq, dy: m.dy + J.dy, arm: [arm.slice(0, 2), arm.slice(2)], leg, emote: lt > 3.3 ? '-' : null };+ // where Bo's right hand will be at the top of the jump: the bulb waits exactly there+ const J2 = jump(grab, 3.65, 4.15, 3.8), apex = bo(BX, BY, U, { strokesOnly: true, dy: J2.dy, sq: J2.sq, arm: [[140, 30], [170, 0]] }).hand.R;+ if (lt < grab) drawOn(PROPS.bulb(apex[0], apex[1], U, 'bo1'), 2.5, 2.9);+ const me = bo(BX, BY, U, { ...pose, draw: [1.3, 2.45], hold: lt >= grab ? { R: 'bulbOn' } : null });+ // hand-drawn "pop" marks around the bulb as he grabs it (they follow his hand)+ const hr = me.hand.R;+ if (lt > grab && lt < grab + .45) ink(S.rays(hr[0], hr[1] - 1.8 * U, 2.6 * U, 3.2 * U, 8, { col: INK.red, key: 'pop' }), { alpha: 1 - seg(lt, grab + .25, grab + .45) });++ camEnd();+ eraseWipe(seg(lt, dur - .75, dur), { rows: 3 });+ }++ // ---- B: share it -------------------------------------------------------------------------------------------+ function share(t, lt, dur) {+ wbBegin(lt, { cam: [[0, [960, 560, 1]], [dur, [1010, 580, 1.07]]] });+ const u = 40, MX = 1330, MY = 930;++ const walk = stroll(lt, .8, 2.1, -300, 720, u);+ const turn = kf(lt, [[2.15, 1], [2.4, .45]]);+ const offer = kf(lt, [[2.15, [70, 25]], [2.55, [100, 5]]], backOut);+ const swing = walk.walk != null ? -26 * Math.sin(walk.walk * TAU) : 10;+ const bm = mood(lt, [[0, 'happy'], [2.45, 'proud', .3]]);+ bo(walk.x, 930, u, { face: bm.face, blink: bm.blink, sq: bm.sq, view: turn, walk: walk.walk, arm: [[swing, 20], offer], hold: { R: (x, y, u, k) => ICON.bulb(x + .5 * u, y - 1.5 * u, 3.3 * u, { key: k + 'bulb', rays: true }) } });++ const mm = mood(lt, [[0, 'sleepy'], [3.15, 'surprised', 1], [3.5, 'love']]);+ const hop = jump(lt, 3.6, 3.9, 1.1);+ mochi(MX, MY, u * .95, { face: mm.face, blink: mm.blink, sq: mm.sq + hop.sq, dy: mm.dy + hop.dy, look: lt > 3.1 ? [-1, 0] : null,+ arm: lt > 3.5 ? [[3, 0], [kf(lt, [[3.5, 3], [3.75, 150]], backOut), 25 + 20 * Math.sin(lt * 14)]] : null, draw: [.1, 1.2] });++ const txt = writeOn('Share it!', 1000, 250, 2.2, 2.8, { size: 140, col: INK.red, align: 'center' });+ drawOn(S.underline(txt.x, txt.y2 + 2, txt.w, { col: INK.blue, double: true }), 2.83, 3.02);+ }++ shots([[0, idea], [5.5, share]]);+ wbCaptions([[.45, 5.1, '每個*好點子*,都從一筆開始'], [5.85, 9.9, '分享出去,*點子會發光*']]);+})();diff --git a/.claude/skills/whiteboard/template/src/sheets.js b/.claude/skills/whiteboard/template/src/sheets.jsnew file mode 100644index 0000000..894dad8--- /dev/null+++ b/.claude/skills/whiteboard/template/src/sheets.js@@ -0,0 +1,51 @@+// sheets.js: model sheets as standalone loops (they only run with --loop=<name>):+// node render.mjs --loop=faces --sheet=0 --cols=1 --w=1920 --out=out/check/faces.jpg every expression, both characters+// node render.mjs --loop=poses --sheet=0 --cols=1 --w=1920 --out=out/check/poses.jpg views, walk, jump, props+// node render.mjs --loop=kit --sheet=0 --cols=1 --w=1920 --out=out/check/kit.jpg icons, strokes, fills, text+(() => {+ const label = (s, x, y, size = 30, col = INK.grey) => { G.save(); G.font = `700 ${size}px ${FONT_HAND}`; G.textAlign = 'center'; G.fillStyle = col; G.fillText(s, x, y); G.restore(); };+ const plain = t => { WB.clock = t; board({ kind: 'white' }); };++ LOOPS.faces = t => {+ plain(t);+ EXPR_NAMES.forEach((name, i) => {+ const cx = 120 + (i % 8) * 240, row = Math.floor(i / 8);+ bo(cx - 30, 330 + row * 520, 17, { face: name, id: 'bo', noBlink: true, t, arm: [[20, 20], [20, 20]] });+ mochi(cx + 62, 330 + row * 520 + 150, 11, { face: name, noBlink: true, t });+ label(name, cx, 395 + row * 520 + 110 - 30);+ });+ };+ LOOPS.faces.len = 2;++ LOOPS.poses = t => {+ plain(t);+ const u = 20;+ bo(170, 470, u, { face: 'happy', view: 0, noBlink: true }); label('front', 170, 530);+ bo(420, 470, u, { face: 'neutral', view: .5, noBlink: true }); label('3/4', 420, 530);+ bo(660, 470, u, { face: 'neutral', view: 1, noBlink: true }); label('side', 660, 530);+ bo(900, 470, u, { face: 'neutral', view: 1, flip: true, noBlink: true }); label('flip', 900, 530);+ [0, .25, .5, .75].forEach((ph, i) => bo(1150 + i * 150, 470, u * .8, { face: 'happy', view: 1, walk: ph, noBlink: true }));+ label('walk cycle', 1370, 530);+ bo(1760, 470, u * .8, { face: 'excited', sq: -.14, dy: -1.8, arm: [[150, 10], [150, 10]], leg: [[20, -40], [20, -40]], noBlink: true }); label('jump', 1760, 530);+ // props in hands+ const props = ['bulb', 'phone', 'coin', 'heart', 'flag', 'balloon', 'book', 'cup', 'star', 'sign'];+ props.forEach((p, i) => { const x = 110 + i * 185; bo(x, 980, 15, { face: 'happy', arm: [[16, 12], [120, 40]], hold: { R: p }, noBlink: true }); label(p, x, 1040); });+ mochi(1780, 740, 16, { face: 'happy', noBlink: true }); mochi(1640, 740, 16, { face: 'love', view: 1, noBlink: true, walk: .3 });+ mochi(1520, 740, 14, { face: 'excited', arm: [[140, 20], [30, -10]], hold: { R: 'fish' }, noBlink: true });+ };+ LOOPS.poses.len = 2;++ LOOPS.kit = t => {+ plain(t);+ const names = Object.keys(ICON);+ names.forEach((n, i) => { const x = 110 + (i % 10) * 180, y = 120 + Math.floor(i / 10) * 210; ink(ICON[n](x, y, 120)); label(n, x, y + 100, 26); });+ const y0 = 560;+ ink([S.arrow(80, y0, 360, y0 - 60), S.circle(520, y0, 90, 60), S.rect(680, y0 - 70, 220, 140), S.box(960, y0 - 80, 260, 130, { tail: [1010, y0 + 110] }), S.bubble(1400, y0 - 20, 150, 90, [1300, y0 + 110]), S.cloud(1700, y0, 150, 90)]);+ ink([hatch(polyCircle(170, 800, 90), { col: INK.blue }), S.circle(170, 800, 90, 90, { col: INK.blue }), scribble(polyRect(330, 720, 200, 160)), S.rect(330, 720, 200, 160), hatch(polyRect(600, 720, 200, 160), { col: INK.red, angle: -40, gap: 14 }), S.rect(600, 720, 200, 160, { col: INK.red })]);+ const b = writeOn('Handwriting 手寫字 ✓', 880, 820, -1, 0, { size: 84, hand: false });+ ink([hilite(b.x, b.y, b.w * .45, b.h), S.underline(b.x, b.y2 + 6, b.w, { col: INK.red, double: true })]);+ writeOn('Kalam + LXGW WenKai TC', 880, 960, -1, 0, { size: 58, col: INK.blue, hand: false });+ ink([S.heart(1800, 800, 90, { col: INK.red }), S.star(1800, 960, 60, { col: INK.orange })]);+ };+ LOOPS.kit.len = 2;+})();diff --git a/.claude/skills/whiteboard/template/src/whiteboard.js b/.claude/skills/whiteboard/template/src/whiteboard.jsnew file mode 100644index 0000000..e68f3d7--- /dev/null+++ b/.claude/skills/whiteboard/template/src/whiteboard.js@@ -0,0 +1,724 @@+// whiteboard.js: the drawing library of the ReelMimic "whiteboard" engine (hand-drawn whiteboard / doodle explainer).+//+// Everything on the board is a list of STROKES. A stroke is a hand-wobbled polyline (marker or highlighter) or a+// coloured-in shape (fill). Builders in `S` / `ICON` / `hatch()` make strokes; `drawOn(strokes, a, b)` reveals them by+// arc length between times a→b (the marker hand follows the pen tip); `ink(strokes)` draws them fully;+// `writeOn(text, x, y, a, b)` writes handwriting left to right. Every frame is a pure function of time.+//+// Shot skeleton:+// function shot(t, lt, dur) {+// wbBegin(lt, { cam: [[0, [960, 540, .9]], [3, [1300, 560, 1.1]]] }); // clock + camera + board+// drawOn([S.circle(900, 500, 120), ...ICON.bulb(900, 500, 160)], .5, 1.8);+// writeOn('Big idea!', 700, 260, 2, 3, { size: 96, col: INK.blue });+// camEnd(); eraseWipe(seg(lt, dur - .8, dur)); // screen-space transition out+// }++// ---------- palette & settings ----------+const INK = {+ black: '#23262B', blue: '#1F5CC4', red: '#D9392B', orange: '#F28A16', green: '#2A9A4B', purple: '#7A4FC4',+ grey: '#8B9098', yellow: '#FFD62E', pink: '#FF9DB0', skin: '#F7D5B8', white: '#FFFFFF',+ board: '#F7F6F1', paper: '#FBF6E8', wall: '#E3DDD2',+};+const HL = { yellow: '#FFE45C', pink: '#FF9EC4', green: '#9BEA8A', blue: '#8FD3FF', orange: '#FFC06B' }; // highlighters+const FONT_HAND = '"Kalam", "LXGW WenKai TC", "Klee One", cursive';+const WB = {+ w: 9, // default marker width in world px (at zoom 1 on a 1920×1080 frame)+ clock: 0, // the time drawOn/writeOn read (wbBegin sets it to the shot's local time)+ hand: true, // draw the marker hand at the pen tip (false hides it everywhere)+ handScale: .85,+ sleeve: '#3E6FCB', // the drawing hand's shirt sleeve+ bg: { kind: 'white' },+ gap: 30, // pen-lift cost between strokes, in px of travel+ ghost: true, // faint ghosting of old erased writing on the white board+};+const PEN = []; // this frame's drawOn/writeOn intervals (for the hand); reset every frame++// ---------- geometry ----------+const _d = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);+function cumOf(pts) { const c = [0]; for (let i = 1; i < pts.length; i++) c.push(c[i - 1] + _d(pts[i - 1], pts[i])); return c; }+function resample(pts, step = 6) { // polyline → evenly spaced points+ const out = [pts[0]];+ for (let i = 1; i < pts.length; i++) {+ const a = pts[i - 1], b = pts[i], d = _d(a, b), n = Math.max(1, Math.ceil(d / step));+ for (let k = 1; k <= n; k++) out.push([lerp(a[0], b[0], k / n), lerp(a[1], b[1], k / n)]);+ }+ return out;+}+function catmull(ctrl, closed = false, step = 6) { // smooth curve through control points+ const P = closed ? [ctrl[ctrl.length - 1], ...ctrl, ctrl[0], ctrl[1]] : [ctrl[0], ...ctrl, ctrl[ctrl.length - 1]];+ const out = [];+ for (let i = 1; i < P.length - 2; i++) {+ const p0 = P[i - 1], p1 = P[i], p2 = P[i + 1], p3 = P[i + 2], n = Math.max(2, Math.ceil(_d(p1, p2) / step));+ for (let k = i === 1 ? 0 : 1; k <= n; k++) {+ const t = k / n, t2 = t * t, t3 = t2 * t;+ out.push([0, 1].map(j => .5 * (2 * p1[j] + (-p0[j] + p2[j]) * t + (2 * p0[j] - 5 * p1[j] + 4 * p2[j] - p3[j]) * t2 + (-p0[j] + 3 * p1[j] - 3 * p2[j] + p3[j]) * t3)));+ }+ }+ return out;+}+// smooth path with sharp corners at the indices in `sharp` (e.g. ear tips); closed paths start at a sharp point+function spline(ctrl, sharp = [], closed = false, step = 6) {+ if (!sharp.length) return catmull(ctrl, closed, step);+ const n = ctrl.length, idx = [...sharp].sort((a, b) => a - b), out = [];+ const cuts = closed ? [...idx, idx[0] + n] : [0, ...idx.filter(i => i > 0 && i < n - 1), n - 1];+ for (let k = 0; k < cuts.length - 1; k++) {+ const piece = []; for (let i = cuts[k]; i <= cuts[k + 1]; i++) piece.push(ctrl[i % n]);+ const c = piece.length > 2 ? catmull(piece, false, step) : resample(piece, step);+ out.push(...(k ? c.slice(1) : c));+ }+ return out;+}+function keyOf(...v) { return v.map(x => typeof x === 'number' ? Math.round(x) : x).join(':'); }+// hand wobble: low-frequency sideways drift + a gentle bow, seeded by `key` so it's the same every frame+function wobble(pts, amp, key, bow = .012) {+ if (pts.length < 3 || !amp && !bow) return pts;+ const r = rnd('wob' + key), f1 = TAU / (150 + 140 * r()), f2 = TAU / (45 + 40 * r()), p1 = r() * TAU, p2 = r() * TAU, b = (r() - .5) * 2 * bow;+ const cum = cumOf(pts), L = cum[cum.length - 1] || 1;+ return pts.map((p, i) => {+ const a = pts[Math.max(0, i - 1)], c = pts[Math.min(pts.length - 1, i + 1)], dx = c[0] - a[0], dy = c[1] - a[1], m = Math.hypot(dx, dy) || 1;+ const s = cum[i], off = amp * (.72 * Math.sin(s * f1 + p1) + .28 * Math.sin(s * f2 + p2)) * Math.min(1, s / 30, (L - s) / 30 + .35) + b * L * Math.sin(Math.PI * s / L);+ return [p[0] - dy / m * off, p[1] + dx / m * off];+ });+}+const autoAmp = len => Math.min(2.8, .7 + len * .004);++// ---------- strokes ----------+// mk(points, { col, w, z, alpha, kind: 'line'|'hl' }) → stroke. z orders drawing (low first); array order is reveal order.+function mk(pts, o = {}) {+ const cum = cumOf(pts);+ return { kind: o.kind || (o.hl ? 'hl' : 'line'), p: pts, cum, len: cum[cum.length - 1], col: o.col || INK.black, w: o.w || WB.w, z: o.z || 0, a: o.alpha ?? (o.hl ? .55 : 1), seed: hash(pts.length + (pts[0][0] | 0) * .37) * 9 };+}+function _line(pts, o, key) { const L = cumOf(pts).pop(); return mk(o.wob === 0 ? pts : wobble(pts, o.wob ?? autoAmp(L), o.key || key, o.bow ?? .012), o); }+// flatten nested arrays of strokes (null/false entries are skipped, so `cond && S.line(...)` works)+function flatStrokes(d, out = []) { if (!d) return out; if (Array.isArray(d)) { for (const x of d) flatStrokes(x, out); } else out.push(d); return out; }+// move/rotate/scale strokes built at the origin (line widths are NOT scaled: one marker, one width)+function place(d, x, y, ang = 0, sc = 1) {+ const c = Math.cos(ang), s = Math.sin(ang);+ return flatStrokes(d).map(st => {+ const q = { ...st, p: st.p.map(([px, py]) => [x + (px * c - py * s) * sc, y + (px * s + py * c) * sc]), cum: st.cum.map(v => v * sc), len: st.len * sc };+ if (st.kind === 'fill') { q.cost = st.cost * sc; q.bb = _bbox(q.p); q.shift = [(st.shift[0] * c - st.shift[1] * s) * sc, (st.shift[0] * s + st.shift[1] * c) * sc]; }+ return q;+ });+}+function _bbox(poly) { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of poly) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); } return [x0, y0, x1 - x0, y1 - y0]; }+function tint(d, col) { return flatStrokes(d).map(s => ({ ...s, col })); }+function layer(d, z) { return flatStrokes(d).map(s => ({ ...s, z })); }+function polyCircle(cx, cy, rx, ry = rx, n = 48, a0 = 0) { const p = []; for (let i = 0; i < n; i++) { const a = a0 + i / n * TAU; p.push([cx + rx * Math.cos(a), cy + ry * Math.sin(a)]); } return p; }+function polyRect(x, y, w, h, r = 0) {+ if (!r) return [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];+ const p = [], arc = (cx, cy, a0) => { for (let i = 0; i <= 6; i++) { const a = a0 + i / 6 * Math.PI / 2; p.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]); } };+ arc(x + w - r, y + r, -Math.PI / 2); arc(x + w - r, y + h - r, 0); arc(x + r, y + h - r, Math.PI / 2); arc(x + r, y + r, Math.PI); return p;+}++// ---------- stroke builders ----------+const S = {+ line(x1, y1, x2, y2, o = {}) { return _line(resample([[x1, y1], [x2, y2]], 6), o, keyOf('l', x1, y1, x2, y2)); },+ // through points; o.closed, o.sharp = [indices of corners]; o.straight = polyline with corners everywhere+ path(pts, o = {}) {+ const q = o.straight ? resample(o.closed ? [...pts, pts[0]] : pts, 6) : spline(pts, o.sharp || [], !!o.closed);+ if (o.closed && !o.straight && q.length) q.push(q[0]);+ return _line(q, o, keyOf('p', pts[0][0], pts[0][1], pts.length));+ },+ // hand-drawn circle/ellipse: starts upper-left, overshoots past the start (turns 1.06), radius breathes a little+ circle(cx, cy, rx, ry = rx, o = {}) {+ const r = rnd(o.key || keyOf('c', cx, cy, rx)), a0 = o.a0 ?? (-2.3 + r() * .5), turns = o.turns ?? 1.06, dir = o.cw ? 1 : -1;+ const n = Math.max(20, Math.ceil(TAU * Math.max(rx, ry) * turns / 6)), ph = r() * TAU, gr = o.spiral ?? .035, pts = [];+ for (let i = 0; i <= n; i++) {+ const k = i / n, a = a0 + dir * k * TAU * turns, f = 1 + (o.round ? 0 : .03 * Math.sin(2 * a + ph)) + gr * (k - .5);+ pts.push([cx + rx * f * Math.cos(a), cy + ry * f * Math.sin(a)]);+ }+ return _line(pts, { ...o, bow: 0 }, o.key || keyOf('c', cx, cy, rx));+ },+ ring(cx, cy, rx, ry = rx, o = {}) { return S.circle(cx, cy, rx, ry, { turns: 1.14, spiral: .08, ...o }); }, // circle around a word+ arc(cx, cy, r, a0, a1, o = {}) {+ const n = Math.max(6, Math.ceil(Math.abs(a1 - a0) * r / 6)), pts = [];+ for (let i = 0; i <= n; i++) { const a = lerp(a0, a1, i / n); pts.push([cx + r * Math.cos(a), cy + (o.ry || r) * Math.sin(a)]); }+ return _line(pts, o, keyOf('a', cx, cy, r, a0));+ },+ dot(x, y, r = 6, o = {}) { return mk([[x, y], [x + .3, y + .2]], { ...o, w: 2 * r }); },+ // hand-drawn box: one continuous stroke, the last side overshoots the start; o.r rounds corners+ rect(x, y, w, h, o = {}) {+ const q = o.r ? [...polyRect(x, y, w, h, o.r), [x + w - o.r + 4, y - 1]] : [[x - 4, y + 2], [x + w, y], [x + w + 1, y + h], [x, y + h + 1], [x + 1, y - Math.min(10, h * .12)]];+ return _line(resample(q, 6), { ...o, bow: .004 }, o.key || keyOf('r', x, y, w, h));+ },+ // arrow: curved shaft (o.bend, fraction of length, + bends left of travel) + a separate head stroke+ arrow(x1, y1, x2, y2, o = {}) {+ const L = Math.hypot(x2 - x1, y2 - y1), nx = -(y2 - y1) / L, ny = (x2 - x1) / L, b = (o.bend ?? .12) * L;+ const cx = (x1 + x2) / 2 + nx * b, cy = (y1 + y2) / 2 + ny * b, pts = [];+ const n = Math.max(8, Math.ceil(L / 6));+ for (let i = 0; i <= n; i++) { const t = i / n; pts.push([(1 - t) ** 2 * x1 + 2 * (1 - t) * t * cx + t * t * x2, (1 - t) ** 2 * y1 + 2 * (1 - t) * t * cy + t * t * y2]); }+ const shaft = _line(pts, { ...o, bow: 0 }, o.key || keyOf('ar', x1, y1, x2, y2));+ const e = shaft.p[shaft.p.length - 1], q = shaft.p[Math.max(0, shaft.p.length - 5)], ang = Math.atan2(e[1] - q[1], e[0] - q[0]);+ const hs = o.head ?? Math.min(46, 20 + L * .08), sp = .5;+ const head = mk([[e[0] - hs * Math.cos(ang - sp), e[1] - hs * Math.sin(ang - sp)], e, [e[0] - hs * Math.cos(ang + sp), e[1] - hs * Math.sin(ang + sp)]].map(p => p), o);+ return [shaft, mk(resample(head.p, 5), o)];+ },+ underline(x, y, w, o = {}) {+ const a = _line(resample([[x - 6, y + 2], [x + w + 8, y - 3]], 6), { bow: .01, ...o }, o.key || keyOf('u', x, y, w));+ return o.double ? [a, _line(resample([[x + w * .12, y + 16], [x + w * .92, y + 13]], 6), o, keyOf('u2', x, y, w))] : a;+ },+ // wavy / zigzag lines+ wave(x1, y1, x2, y2, amp = 10, waves = 4, o = {}) {+ const L = Math.hypot(x2 - x1, y2 - y1), nx = -(y2 - y1) / L, ny = (x2 - x1) / L, n = Math.ceil(L / 5), pts = [];+ for (let i = 0; i <= n; i++) { const t = i / n, s = amp * Math.sin(t * waves * TAU); pts.push([lerp(x1, x2, t) + nx * s, lerp(y1, y2, t) + ny * s]); }+ return _line(pts, { wob: 0, ...o }, keyOf('w', x1, y1));+ },+ zigzag(x1, y1, x2, y2, amp = 12, n = 6, o = {}) {+ const L = Math.hypot(x2 - x1, y2 - y1), nx = -(y2 - y1) / L, ny = (x2 - x1) / L, pts = [];+ for (let i = 0; i <= n; i++) { const t = i / n, s = i % 2 ? amp : -amp; pts.push([lerp(x1, x2, t) + nx * s * (i && i < n ? 1 : 0), lerp(y1, y2, t) + ny * s * (i && i < n ? 1 : 0)]); }+ return _line(resample(pts, 5), { wob: .5, ...o }, keyOf('z', x1, y1));+ },+ spiral(cx, cy, r, turns = 2.5, o = {}) { const n = Math.ceil(turns * 40), p = []; for (let i = 0; i <= n; i++) { const k = i / n, a = k * turns * TAU; p.push([cx + r * k * Math.cos(a), cy + r * k * Math.sin(a)]); } return _line(p, { wob: .6, ...o }, keyOf('sp', cx, cy)); },+ // speech bubble (ellipse with a tail pointing at [tx,ty]) / callout box with a tail+ bubble(cx, cy, rx, ry, tail, o = {}) {+ const ta = Math.atan2((tail[1] - cy) / ry, (tail[0] - cx) / rx), gap = .22, pts = [];+ const n = 60; for (let i = 0; i <= n; i++) { const a = ta + gap + i / n * (TAU - 2 * gap); pts.push([cx + rx * Math.cos(a), cy + ry * Math.sin(a)]); }+ pts.push(tail, [cx + rx * Math.cos(ta + gap), cy + ry * Math.sin(ta + gap)]);+ return _line(resample(pts, 6), { ...o, bow: 0 }, o.key || keyOf('b', cx, cy));+ },+ box(x, y, w, h, o = {}) { // o.tail = [tx, ty] below the box; o.r corner radius+ const r = o.r ?? 18, P = polyRect(x, y, w, h, r);+ if (o.tail) {+ const bx = clamp(o.tail[0], x + r + 30, x + w - r - 30), i = P.findIndex(p => p[1] >= y + h - .5 && p[0] <= x + w - r + .5); // start of the bottom edge+ P.splice(i + 1, 0, [bx + 26, y + h], o.tail, [bx - 16, y + h]);+ }+ P.push([P[0][0] + 6, P[0][1] - 1]);+ return _line(resample(P, 6), { ...o, bow: .003 }, o.key || keyOf('bx', x, y, w, h));+ },+ cloud(cx, cy, rx, ry, o = {}) {+ const n = o.bumps || 9, r = rnd(keyOf('cl', cx, cy)), pts = [];+ for (let i = 0; i < n; i++) {+ const a0 = -Math.PI / 2 + i / n * TAU, a1 = -Math.PI / 2 + (i + 1) / n * TAU, p0 = [cx + rx * Math.cos(a0), cy + ry * Math.sin(a0)], p1 = [cx + rx * Math.cos(a1), cy + ry * Math.sin(a1)];+ const m = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2], br = _d(p0, p1) / 2 * (1.05 + r() * .2), out = [m[0] - cx, m[1] - cy], s0 = Math.atan2(p0[1] - m[1], p0[0] - m[0]);+ const sw = (Math.cos(s0 - Math.PI / 2) * out[0] + Math.sin(s0 - Math.PI / 2) * out[1]) > 0 ? -Math.PI : Math.PI;+ for (let k = 0; k <= 10; k++) { const a = s0 + sw * k / 10; pts.push([m[0] + br * Math.cos(a), m[1] + br * Math.sin(a)]); }+ }+ pts.push(pts[0]);+ return _line(pts, { wob: .8, ...o, bow: 0 }, keyOf('cl', cx, cy));+ },+ heart(cx, cy, s, o = {}) { // s ≈ width+ const pts = [], k = s / 34;+ for (let i = 0; i <= 64; i++) { const t = Math.PI + i / 64 * TAU * 1.02; pts.push([cx + 16 * Math.pow(Math.sin(t), 3) * k, cy - (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)) * k - 2 * k]); }+ return _line(pts, { wob: .6, ...o, bow: 0 }, o.key || keyOf('h', cx, cy));+ },+ star(cx, cy, r, o = {}) { const p = []; for (let i = 0; i <= 10; i++) { const a = -Math.PI / 2 + i / 10 * TAU, rr = i % 2 ? r * .45 : r; p.push([cx + rr * Math.cos(a), cy + rr * Math.sin(a)]); } p.push([cx + r * .2 * Math.cos(-1.2), cy - r * .8]); return _line(resample(p, 5), { wob: .6, ...o, bow: 0 }, o.key || keyOf('st', cx, cy)); },+ check(x, y, s, o = {}) { return _line(resample([[x - s * .45, y - s * .02], [x - s * .12, y + s * .32], [x + s * .5, y - s * .42]], 5), { col: INK.green, w: WB.w * 1.4, ...o, bow: 0 }, keyOf('ck', x, y)); },+ cross(x, y, s, o = {}) { const h = s * .42, q = { col: INK.red, w: WB.w * 1.4, ...o }; return [S.line(x - h, y - h, x + h, y + h, q), S.line(x + h, y - h, x - h, y + h, q)]; },+ // emphasis rays around a point (o.a0/o.a1 limit the fan), sparkle, speed lines+ rays(cx, cy, r1, r2, n = 8, o = {}) { const a0 = o.a0 ?? 0, a1 = o.a1 ?? TAU, full = Math.abs(a1 - a0 - TAU) < .01, out = []; for (let i = 0; i < n; i++) { const a = lerp(a0, a1, full ? i / n : n > 1 ? i / (n - 1) : .5); out.push(S.line(cx + r1 * Math.cos(a), cy + r1 * Math.sin(a), cx + r2 * Math.cos(a), cy + r2 * Math.sin(a), { ...o, key: (o.key || keyOf('ry', cx, cy)) + ':' + i })); } return out; },+ sparkle(x, y, s, o = {}) { const k = o.key || keyOf('sk', x, y); return [S.line(x, y - s, x, y + s, { ...o, key: k + '1' }), S.line(x - s, y, x + s, y, { ...o, key: k + '2' })]; },+ speed(x, y, len, ang = 0, n = 3, gap = 22, o = {}) { const c = Math.cos(ang), s = Math.sin(ang), out = []; for (let i = 0; i < n; i++) { const off = (i - (n - 1) / 2) * gap, l = len * (i % 2 ? .7 : 1), ox = -s * off, oy = c * off; out.push(S.line(x + ox, y + oy, x + ox - c * l, y + oy - s * l, { w: WB.w * .7, ...o, key: keyOf('sd', x, y, i) })); } return out; },+ // coloured-in shape: o.mode 'ink' (multiply, lines show through; default) or 'cover' (opaque, hides what's under)+ fill(poly, o = {}) {+ const bb = _bbox(poly);+ return { kind: 'fill', p: poly, cum: [0], len: 0, col: o.col || INK.yellow, w: 0, z: o.z ?? -1, a: o.alpha ?? .92, mode: o.mode || 'ink', shift: o.shift || [0, 0], cost: o.cost ?? (bb[2] + bb[3]) * .9, bb, pat: o.pat !== false };+ },+};+// quick hatching inside a polygon: parallel marker lines (o.angle deg, o.gap px); o.zig = one continuous scribble+function hatch(poly, o = {}) {+ const ang = (o.angle ?? 38) * Math.PI / 180, gap = o.gap ?? 16, c = Math.cos(-ang), s = Math.sin(-ang);+ const rp = poly.map(([x, y]) => [x * c - y * s, x * s + y * c]), ys = rp.map(p => p[1]), segs = [];+ const inset = o.inset ?? 4;+ for (let y = Math.min(...ys) + gap * .5; y < Math.max(...ys); y += gap) {+ const xs = [];+ for (let i = 0; i < rp.length; i++) { const a = rp[i], b = rp[(i + 1) % rp.length]; if ((a[1] <= y) !== (b[1] <= y)) xs.push(a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0])); }+ xs.sort((p, q) => p - q);+ for (let i = 0; i + 1 < xs.length; i += 2) if (xs[i + 1] - xs[i] > inset * 2 + 2) segs.push([[xs[i] + inset, y], [xs[i + 1] - inset, y]]);+ }+ const back = ([x, y]) => [x * c + y * s, -x * s + y * c], r = rnd('h' + (poly[0][0] | 0) + (poly[0][1] | 0));+ const q = { w: o.w || WB.w * .55, col: o.col || INK.black, z: o.z ?? -1, alpha: o.alpha, hl: o.hl };+ if (o.zig) { // one back-and-forth scribble+ const pts = []; segs.forEach((sg, i) => { const [a, b] = i % 2 ? [sg[1], sg[0]] : sg; pts.push(back([a[0] + (r() - .5) * 6, a[1]]), back([b[0] + (r() - .5) * 6, b[1]])); });+ return pts.length > 1 ? [mk(resample(pts, 6), q)] : [];+ }+ return segs.map(([a, b], i) => mk(resample([back([a[0] + (r() - .5) * 8, a[1] + (r() - .5) * 3]), back([b[0] + (r() - .5) * 8, b[1] + (r() - .5) * 3])], 6), q));+}+// highlighter scribble fill (translucent, multiply)+function scribble(poly, o = {}) { return hatch(poly, { zig: true, hl: true, gap: o.gap ?? 25, w: o.w ?? 28, col: o.col || HL.yellow, angle: o.angle ?? 28, inset: 10, alpha: o.alpha ?? .6, z: o.z ?? -1 }); }+// highlighter bar behind a word (x,y = top-left of the text box)+function hilite(x, y, w, h, o = {}) { return mk(resample([[x - 8, y + h * .55], [x + w + 8, y + h * .5]], 6), { hl: true, w: h * .75, col: o.col || HL.yellow, z: -1, alpha: o.alpha ?? .6 }); }++// ---------- icons: ICON.name(cx, cy, size, o) → strokes (o.col = accent colour, o.key = wobble seed) ----------+const ICON = {};+{+ const B = (name, fn) => { ICON[name] = (cx, cy, s = 140, o = {}) => place(fn(s / 100, o, o.key || keyOf(name, cx, cy)), cx, cy, o.rot || 0); };+ const L = (pts, k, o = {}) => _line(resample(pts, 5), { wob: .6, bow: 0, ...o }, k);+ const C = (pts, k, o = {}) => _line(catmull(pts), { wob: .6, bow: 0, ...o }, k);+ const circ = (x, y, r, k, o = {}) => S.circle(x, y, r, r, { key: k, ...o });+ B('bulb', (u, o, k) => {+ const g = [[-18, 22], [-24, 8], [-38, -12], [-40, -34], [-26, -56], [0, -64], [26, -56], [40, -34], [38, -12], [24, 8], [18, 22]].map(([x, y]) => [x * u, y * u]);+ const glass = C(g, k + 'g'), fil = L([[-10 * u, 20 * u], [-10 * u, -4 * u], [-4 * u, -14 * u], [2 * u, -4 * u], [8 * u, -14 * u], [10 * u, -4 * u], [10 * u, 20 * u]], k + 'f', { col: INK.orange, w: WB.w * .7 });+ const base = [0, 1, 2].map(i => L([[-19 * u, (28 + i * 9) * u], [19 * u, (28 + i * 9) * u]], k + 'b' + i));+ const tip = L([[-9 * u, 56 * u], [9 * u, 56 * u]], k + 't');+ const out = [glass, fil, ...base, tip, S.fill(catmull([...g]).concat([[0, 24 * u]]), { col: o.col || INK.yellow, alpha: .95 })];+ if (o.rays) out.push(...S.rays(0, -26 * u, 58 * u, 80 * u, 7, { a0: -Math.PI * 1.05, a1: Math.PI * .05, col: INK.orange, key: k + 'r' }));+ return out;+ });+ B('clock', (u, o, k) => [circ(0, 0, 48 * u, k + 'c'), ...[0, 1, 2, 3].map(i => { const a = i * Math.PI / 2; return L([[40 * u * Math.cos(a), 40 * u * Math.sin(a)], [33 * u * Math.cos(a), 33 * u * Math.sin(a)]], k + 't' + i); }),+ L([[0, 0], [0, -30 * u]], k + 'h'), L([[0, 0], [22 * u, 10 * u]], k + 'm'), S.dot(0, 0, WB.w * .7), S.fill(polyCircle(0, 0, 46 * u, 46 * u, 36), { col: o.col || HL.blue, alpha: .7 })]);+ B('coin', (u, o, k) => [circ(0, 0, 46 * u, k + 'c'), circ(0, 0, 34 * u, k + 'i', { w: WB.w * .6, turns: 1 }), C([[14 * u, -14 * u], [4 * u, -20 * u], [-12 * u, -16 * u], [-12 * u, -4 * u], [0, 0], [12 * u, 4 * u], [12 * u, 16 * u], [-2 * u, 20 * u], [-14 * u, 14 * u]], k + 's'),+ L([[0, -28 * u], [0, 28 * u]], k + 'v'), S.fill(polyCircle(0, 0, 45 * u), { col: o.col || INK.yellow, alpha: .9 })]);+ B('money', (u, o, k) => [S.rect(-60 * u, -32 * u, 120 * u, 64 * u, { key: k + 'r', r: 6 }), circ(0, 0, 18 * u, k + 'c', { w: WB.w * .7 }), L([[-46 * u, -18 * u], [-38 * u, -18 * u]], k + 'a'), L([[38 * u, 18 * u], [46 * u, 18 * u]], k + 'b'),+ S.fill(polyRect(-58 * u, -30 * u, 116 * u, 60 * u), { col: o.col || '#8CD49B', alpha: .9 })]);+ B('heart', (u, o, k) => [S.heart(0, 0, 100 * u, { key: k }), S.fill(catmull(S.heart(0, 0, 96 * u, { key: k, wob: 0 }).p.filter((_, i) => i % 3 === 0)), { col: o.col || INK.red, alpha: .9 })]);+ B('check', (u, o, k) => [S.check(0, 0, 100 * u, { key: k, col: o.col || INK.green })]);+ B('cross', (u, o, k) => S.cross(0, 0, 100 * u, { key: k, col: o.col || INK.red }));+ B('checkbox', (u, o, k) => [S.rect(-40 * u, -40 * u, 80 * u, 80 * u, { key: k + 'b' }), S.check(8 * u, -8 * u, 100 * u, { key: k, col: o.col || INK.green })]);+ B('phone', (u, o, k) => [S.rect(-32 * u, -58 * u, 64 * u, 116 * u, { key: k + 'r', r: 12 * u }), L([[-10 * u, -46 * u], [10 * u, -46 * u]], k + 's', { w: WB.w * .6 }), S.dot(0, 46 * u, WB.w * .55),+ S.fill(polyRect(-22 * u, -36 * u, 44 * u, 70 * u, 4), { col: o.col || HL.blue, alpha: .9 })]);+ B('house', (u, o, k) => { const roof = [[-58 * u, -6 * u], [0, -56 * u], [58 * u, -6 * u]]; return [L(roof, k + 'r'), L([[-44 * u, -14 * u], [-44 * u, 48 * u], [44 * u, 48 * u], [44 * u, -14 * u]], k + 'w'),+ L([[-12 * u, 48 * u], [-12 * u, 14 * u], [12 * u, 14 * u], [12 * u, 48 * u]], k + 'd'), S.rect(18 * u, 0, 18 * u, 16 * u, { key: k + 'wi', w: WB.w * .6 }), S.fill([[-52 * u, -8 * u], [0, -52 * u], [52 * u, -8 * u]], { col: o.col || INK.red, alpha: .85 })]; });+ B('star', (u, o, k) => [S.star(0, 0, 52 * u, { key: k }), S.fill(S.star(0, 0, 50 * u, { key: k, wob: 0 }).p, { col: o.col || INK.yellow })]);+ B('chart', (u, o, k) => { const bars = [[-40, 26], [-12, 48], [16, 76]]; return [L([[-56 * u, -56 * u], [-56 * u, 44 * u], [60 * u, 44 * u]], k + 'ax'),+ ...bars.map(([x, h], i) => S.rect(x * u, (44 - h) * u, 20 * u, h * u, { key: k + i, w: WB.w * .7 })), ...bars.map(([x, h], i) => S.fill(polyRect(x * u, (44 - h) * u, 20 * u, h * u), { col: [INK.blue, INK.orange, INK.green][i], alpha: .85 })),+ ...S.arrow(-48 * u, 0, 44 * u, -62 * u, { bend: -.1, col: INK.red, key: k + 'a', head: 22 * u })]; });+ B('gear', (u, o, k) => { const p = []; for (let i = 0; i < 8; i++) { const a = i / 8 * TAU; for (const [da, r] of [[-.2, 36], [-.13, 48], [.13, 48], [.2, 36]]) p.push([r * u * Math.cos(a + da), r * u * Math.sin(a + da)]); } p.push(p[0]);+ return [L(p, k + 'g'), circ(0, 0, 14 * u, k + 'c'), S.fill(p, { col: o.col || '#B9C3D0', alpha: .9 })]; });+ B('mail', (u, o, k) => [S.rect(-56 * u, -36 * u, 112 * u, 72 * u, { key: k + 'r' }), L([[-54 * u, -32 * u], [0, 6 * u], [54 * u, -32 * u]], k + 'v'), S.fill(polyRect(-54 * u, -34 * u, 108 * u, 68 * u), { col: o.col || '#FFF3C4' })]);+ B('search', (u, o, k) => [circ(-10 * u, -10 * u, 34 * u, k + 'c'), L([[14 * u, 14 * u], [48 * u, 48 * u]], k + 'h', { w: WB.w * 1.6 }), S.fill(polyCircle(-10 * u, -10 * u, 32 * u), { col: o.col || HL.blue, alpha: .6 })]);+ B('target', (u, o, k) => [circ(0, 0, 48 * u, k + 'a'), circ(0, 0, 30 * u, k + 'b'), S.dot(0, 0, 11 * u, { col: INK.red }), S.fill(polyCircle(0, 0, 47 * u), { col: o.col || '#FFB3A8', alpha: .8 }), ...S.arrow(52 * u, -52 * u, 6 * u, -6 * u, { bend: 0, key: k + 'ar', head: 18 * u })]);+ B('cloud', (u, o, k) => [S.cloud(0, 0, 60 * u, 36 * u, { key: k }), S.fill(polyCircle(0, 0, 58 * u, 34 * u), { col: o.col || HL.blue, alpha: .5 })]);+ B('trophy', (u, o, k) => { const cup = [[-34 * u, -46 * u], [-30 * u, -8 * u], [-12 * u, 10 * u], [12 * u, 10 * u], [30 * u, -8 * u], [34 * u, -46 * u]]; return [L([...cup, [-34 * u, -46 * u]], k + 'c'),+ C([[-32 * u, -38 * u], [-52 * u, -36 * u], [-46 * u, -16 * u], [-28 * u, -12 * u]], k + 'l'), C([[32 * u, -38 * u], [52 * u, -36 * u], [46 * u, -16 * u], [28 * u, -12 * u]], k + 'r'),+ L([[0, 10 * u], [0, 30 * u]], k + 's'), S.rect(-24 * u, 30 * u, 48 * u, 16 * u, { key: k + 'b' }), S.fill(cup, { col: o.col || INK.yellow })]; });+ B('person', (u, o, k) => [circ(0, -34 * u, 18 * u, k + 'h'), C([[-30 * u, 46 * u], [-28 * u, 4 * u], [0, -10 * u], [28 * u, 4 * u], [30 * u, 46 * u]], k + 'b'), S.fill(polyCircle(0, 20 * u, 26 * u, 30 * u), { col: o.col || HL.blue, alpha: .7 })]);+}++// ---------- textures (built once in ENGINE.setup) ----------+const TEX = {}, _pats = new Map();+function _noiseTile(size, base, amp, key, extra) {+ const c = makeCanvas(size, size), x = c.getContext('2d'), r = rnd(key);+ x.fillStyle = base; x.fillRect(0, 0, size, size);+ const id = x.getImageData(0, 0, size, size), d = id.data;+ for (let i = 0; i < d.length; i += 4) { const n = (r() - .5) * amp; d[i] += n; d[i + 1] += n; d[i + 2] += n * .9; }+ x.putImageData(id, 0, 0);+ // extras are drawn 9 times (wrapped) with the same seed so the tile repeats without seams+ if (extra) for (const dx of [-size, 0, size]) for (const dy of [-size, 0, size]) { x.save(); x.translate(dx, dy); extra(x, rnd(key + 'x'), size); x.restore(); }+ return c;+}+function _buildTextures() {+ // white board: faint speckle, large soft blotches, eraser swirls and ghosts of old writing+ TEX.white = _noiseTile(1024, INK.board, 5, 'wb', (x, r, s) => {+ for (let i = 0; i < 14; i++) { const cx = r() * s, cy = r() * s, rr = 120 + r() * 260, g = x.createRadialGradient(cx, cy, 0, cx, cy, rr); g.addColorStop(0, `rgba(${r() < .5 ? '150,150,160' : '255,255,255'},${.012 + r() * .014})`); g.addColorStop(1, 'rgba(0,0,0,0)'); x.fillStyle = g; x.fillRect(0, 0, s, s); }+ x.lineCap = 'round';+ for (let i = 0; i < 9; i++) { // eraser swirl streaks+ x.strokeStyle = `rgba(140,145,155,${.007 + r() * .009})`; x.lineWidth = 40 + r() * 70; x.beginPath();+ const cx = r() * s, cy = r() * s, R = 60 + r() * 140; for (let a = 0; a < 4.2; a += .2) x.lineTo(cx + Math.cos(a) * R * (1 + a * .12), cy + Math.sin(a) * R * .55); x.stroke();+ }+ if (!WB.ghost) return;+ for (let i = 0; i < 26; i++) { // ghost writing: short scribbly "words"+ x.filter = 'blur(2.5px)'; x.strokeStyle = `rgba(${r() < .25 ? '60,90,170' : '70,72,80'},${.014 + r() * .016})`; x.lineWidth = 5 + r() * 5; x.beginPath();+ let px = r() * s, py = r() * s; const n = 10 + (r() * 30 | 0);+ for (let k = 0; k < n; k++) { px += 5 + r() * 9; py += (r() - .5) * 18; x.lineTo(px, py + Math.sin(k * 1.9) * 10); }+ x.stroke();+ }+ });+ // notebook paper: cream fibres (lines are drawn in world space so they stay put)+ TEX.paper = _noiseTile(512, INK.paper, 9, 'pp', (x, r, s) => { for (let i = 0; i < 400; i++) { x.strokeStyle = `rgba(150,130,90,${.03 + r() * .04})`; x.lineWidth = 1; x.beginPath(); const px = r() * s, py = r() * s, a = r() * TAU, l = 4 + r() * 10; x.moveTo(px, py); x.lineTo(px + Math.cos(a) * l, py + Math.sin(a) * l); x.stroke(); } });+ TEX.wall = _noiseTile(512, INK.wall, 10, 'wl');+ TEX.felt = _noiseTile(128, '#8C9097', 30, 'ft');+ // soft screen-space light falloff+ const v = makeCanvas(W, H), vx = v.getContext('2d'), g = vx.createRadialGradient(W * .5, H * .45, H * .35, W * .5, H * .5, H * 1.05);+ g.addColorStop(0, 'rgba(90,80,60,0)'); g.addColorStop(1, 'rgba(90,80,60,.10)'); vx.fillStyle = g; vx.fillRect(0, 0, W, H); TEX.vignette = v;+}+// marker ink: the colour with a little fibrous unevenness (used as stroke/fill style, so it costs nothing per stroke)+function markerPat(ctx, col) {+ let p = _pats.get(col);+ if (!p) {+ const c = _noiseTile(96, col, 16, 'mk' + col, (x, r, s) => { x.globalAlpha = .07; for (let i = 0; i < 30; i++) { x.fillStyle = r() < .5 ? '#fff' : '#000'; x.fillRect(r() * s, r() * s, 1 + r() * 18, 1 + r() * 3); } });+ p = OUT.createPattern(c, 'repeat'); _pats.set(col, p);+ }+ return p;+}+function _lighter(col, k = .45) { return mixCol(col, '#FFFFFF', k); }++// ---------- board ----------+// board(o) → fills the visible world with the surface. kinds: 'white' (whiteboard), 'paper' (ruled notebook),+// 'grid' (squared paper). o.frame = [x,y,w,h] draws the physical whiteboard's aluminium frame with wall around it.+function board(o = WB.bg, ctx = G, cam = CAM) {+ const z = cam ? cam.zoom : 1, cx = cam ? cam.cx : W / 2, cy = cam ? cam.cy : H / 2, hw = W / 2 / z * 1.5 + 60, hh = H / 2 / z * 1.5 + 60;+ const x0 = cx - hw, y0 = cy - hh, ww = hw * 2, hh2 = hh * 2, kind = o.kind || 'white';+ ctx.save();+ ctx.fillStyle = ctx.createPattern(kind === 'white' ? TEX.white : TEX.paper, 'repeat'); ctx.fillRect(x0, y0, ww, hh2);+ if (kind === 'paper' || kind === 'grid') {+ const sp = o.spacing || (kind === 'grid' ? 48 : 64), top = o.top ?? -1e9;+ ctx.strokeStyle = kind === 'grid' ? 'rgba(90,150,210,.28)' : 'rgba(80,140,210,.42)'; ctx.lineWidth = kind === 'grid' ? 1.6 : 2.4; ctx.beginPath();+ for (let y = Math.ceil(Math.max(y0, top) / sp) * sp; y < y0 + hh2; y += sp) { ctx.moveTo(x0, y); ctx.lineTo(x0 + ww, y); }+ if (kind === 'grid') for (let x = Math.ceil(x0 / sp) * sp; x < x0 + ww; x += sp) { ctx.moveTo(x, y0); ctx.lineTo(x, y0 + hh2); }+ ctx.stroke();+ if (o.margin != null) { ctx.strokeStyle = 'rgba(220,70,70,.5)'; ctx.lineWidth = 2.6; ctx.beginPath(); ctx.moveTo(o.margin, y0); ctx.lineTo(o.margin, y0 + hh2); ctx.stroke(); }+ }+ if (o.frame) {+ const [fx, fy, fw, fh] = o.frame, b = 34;+ ctx.fillStyle = ctx.createPattern(TEX.wall, 'repeat'); ctx.beginPath(); ctx.rect(x0, y0, ww, hh2); ctx.rect(fx - b, fy - b, fw + 2 * b, fh + 2 * b); ctx.fill('evenodd');+ ctx.fillStyle = 'rgba(0,0,0,.10)'; ctx.fillRect(fx - b + 10, fy + fh + b, fw + 2 * b - 4, 16); // cast shadow+ const g = ctx.createLinearGradient(0, fy - b, 0, fy + fh + b); g.addColorStop(0, '#E9ECEF'); g.addColorStop(.5, '#C4C9CF'); g.addColorStop(1, '#AEB4BB');+ ctx.fillStyle = g; ctx.beginPath(); ctx.rect(fx - b, fy - b, fw + 2 * b, fh + 2 * b); ctx.rect(fx, fy, fw, fh); ctx.fill('evenodd');+ ctx.strokeStyle = 'rgba(60,65,72,.45)'; ctx.lineWidth = 2; ctx.strokeRect(fx - b, fy - b, fw + 2 * b, fh + 2 * b); ctx.strokeRect(fx, fy, fw, fh);+ ctx.fillStyle = '#B7BDC4'; ctx.fillRect(fx + fw * .1, fy + fh + b - 4, fw * .8, 22); ctx.fillStyle = 'rgba(40,40,50,.25)'; ctx.fillRect(fx + fw * .1, fy + fh + b + 16, fw * .8, 6); // pen tray+ const trayY = fy + fh + b + 2; [[.2, INK.blue], [.26, INK.red], [.72, INK.black]].forEach(([k, c]) => { ctx.fillStyle = '#F2F2EE'; ctx.fillRect(fx + fw * k, trayY - 6, 120, 16); ctx.fillStyle = c; ctx.fillRect(fx + fw * k + 96, trayY - 7, 30, 18); });+ ctx.fillStyle = 'rgba(90,95,100,.12)'; ctx.fillRect(fx, fy, fw, 6); ctx.fillRect(fx, fy, 6, fh); // inner lip shadow+ }+ ctx.restore();+}++// ---------- the clock + camera + board in one call ----------+// wbBegin(lt, { cam: [cx,cy,zoom] | [[t,[cx,cy,zoom]], ...], bg: {kind, frame, margin}, drift: px, ease })+function wbBegin(lt, o = {}) {+ WB.clock = lt; if (o.bg) WB.bg = o.bg; else WB.bg = { kind: 'white' };+ let c = o.cam || [W / 2, H / 2, 1];+ if (Array.isArray(c[0])) c = kf(lt, c, o.ease || ease);+ const d = o.drift ?? 6;+ camBegin(c[0] + d * Math.sin(lt * .5), c[1] + d * .6 * Math.sin(lt * .37 + 1), c[2], c[3] || 0);+ board(WB.bg);+ return CAM;+}++// ---------- rendering strokes ----------+function _part(s, L) { // the first L px of a stroke+ if (L >= s.len) return s.p;+ let i = 1; while (i < s.cum.length && s.cum[i] < L) i++;+ if (i >= s.p.length) return s.p;+ const a = s.p[i - 1], b = s.p[i], k = (L - s.cum[i - 1]) / ((s.cum[i] - s.cum[i - 1]) || 1);+ return [...s.p.slice(0, i), [lerp(a[0], b[0], k), lerp(a[1], b[1], k)]];+}+function _ptAt(s, r) {+ if (s.kind === 'fill') { const [x, y, w, h] = s.bb, f = clamp(r); return [x + s.shift[0] + f * w, y + s.shift[1] + h * (.5 + .42 * Math.sin(f * TAU * Math.max(2, w / 70)))]; }+ const L = clamp(r) * s.len; let i = 1; while (i < s.cum.length - 1 && s.cum[i] < L) i++;+ const a = s.p[i - 1] || s.p[0], b = s.p[i] || a, k = clamp((L - s.cum[i - 1]) / ((s.cum[i] - s.cum[i - 1]) || 1));+ return [lerp(a[0], b[0], k), lerp(a[1], b[1], k)];+}+function renderStroke(ctx, s, r = 1) {+ if (r <= 0) return;+ ctx.save(); ctx.lineCap = 'round'; ctx.lineJoin = 'round';+ if (s.kind === 'fill') {+ ctx.globalAlpha = s.a; if (s.mode !== 'cover') ctx.globalCompositeOperation = 'multiply';+ const [x, y, w, h] = s.bb;+ if (r < 1) { const f = x + s.shift[0] - 30 + (w + 60) * r; ctx.beginPath(); ctx.moveTo(x - 60, y - 40); ctx.lineTo(f + 20, y - 40); ctx.lineTo(f - 20, y + h + 40); ctx.lineTo(x - 60, y + h + 40); ctx.clip(); }+ ctx.translate(s.shift[0], s.shift[1]); ctx.beginPath(); s.p.forEach((p, i) => i ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1])); ctx.closePath();+ ctx.fillStyle = s.pat ? markerPat(ctx, s.col) : s.col; ctx.fill();+ } else {+ const pts = s.len < 1 ? s.p : _part(s, r * s.len);+ if (pts.length >= 2) {+ if (s.kind === 'hl') {+ ctx.globalCompositeOperation = 'multiply'; ctx.globalAlpha = s.a; ctx.strokeStyle = s.col; ctx.lineWidth = s.w;+ ctx.beginPath(); pts.forEach((p, i) => i ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1])); ctx.stroke();+ } else {+ ctx.globalAlpha = s.a; ctx.strokeStyle = markerPat(ctx, s.col);+ // width breathes along the stroke in ~40 px chunks (opaque ink, so the overlaps don't show)+ let st = 0, ci = 0, acc = 0;+ for (let i = 1; i < pts.length; i++) {+ acc += _d(pts[i - 1], pts[i]);+ if (acc >= 40 || i === pts.length - 1) {+ ctx.beginPath(); ctx.moveTo(pts[st][0], pts[st][1]); for (let j = st + 1; j <= i; j++) ctx.lineTo(pts[j][0], pts[j][1]);+ ctx.lineWidth = s.w * (1 + .1 * Math.sin(ci * 1.9 + s.seed) - (ci === 0 ? .04 : 0)); ctx.stroke(); st = i; ci++; acc = 0;+ }+ }+ if (s.w >= 5 && s.len > 30) { // felt-tip streak+ ctx.globalAlpha = .16 * s.a; ctx.strokeStyle = _lighter(s.col, .6); ctx.lineWidth = s.w * .28; ctx.translate(s.w * .16, -s.w * .12);+ ctx.beginPath(); pts.forEach((p, i) => i ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1])); ctx.stroke(); ctx.translate(-s.w * .16, s.w * .12);+ }+ if (s.len > 12) { // ink pools a little where the pen lands+ ctx.globalAlpha = .28 * s.a; ctx.fillStyle = mixCol(s.col, '#000000', .35); ctx.beginPath(); ctx.arc(pts[0][0], pts[0][1], s.w * .5, 0, TAU); ctx.fill();+ }+ }+ }+ }+ ctx.restore();+}+// ink(strokes) → draw everything fully (no hand)+function ink(d, o = {}) { return drawOn(d, -2, -1, { ...o, hand: false }); }++// drawOn(strokes, a, b, o) → reveals the strokes in array order between times a and b (WB.clock), drawn in z order.+// o: { hand: false (no hand), all: true (every stroke at once), t: clock override, x, y (offset), alpha, gap }+// → { p, done, tip: [x,y] }+function drawOn(d, a, b, o = {}) {+ const list = flatStrokes(d); if (!list.length) return { p: 0, done: false };+ const c = o.t ?? WB.clock, p0 = b > a ? seg(c, a, b) : c >= a ? 1 : 0, pe = lerp(p0, ease(p0), .35);+ const gap = o.gap ?? WB.gap, cost = list.map((s, i) => Math.max(s.kind === 'fill' ? s.cost : s.len, 4) + (i ? gap : 0));+ const total = cost.reduce((x, y) => x + y, 0), rev = new Array(list.length);+ let Lr = pe * total, cur = -1, inGap = false;+ for (let i = 0; i < list.length; i++) {+ if (o.all) { rev[i] = pe; continue; }+ const g = i ? gap : 0, r = p0 >= 1 ? 1 : clamp((Lr - g) / (cost[i] - g));+ rev[i] = r; if (cur < 0 && Lr < cost[i]) { cur = i; inGap = Lr < g; }+ Lr -= cost[i];+ }+ if (cur < 0) cur = list.length - 1;+ const alpha = o.alpha ?? 1;+ if (p0 > 0 && alpha > 0) {+ G.save(); if (o.x || o.y) G.translate(o.x || 0, o.y || 0); if (alpha < 1) G.globalAlpha = alpha;+ const order = list.map((s, i) => i).sort((i, j) => (list[i].z - list[j].z) || i - j);+ for (const i of order) if (rev[i] > 0) renderStroke(G, list[i], rev[i]);+ G.restore();+ }+ // pen tip (local), and the interval for the hand+ let tip;+ if (o.all) tip = _ptAt(list[list.length - 1], pe);+ else if (inGap && cur > 0) { const k = clamp(((pe * total) - cost.slice(0, cur).reduce((x, y) => x + y, 0)) / gap); tip = arcPt(_ptAt(list[cur - 1], 1), _ptAt(list[cur], 0), 14, k); }+ else tip = _ptAt(list[cur], rev[cur]);+ if (o.x || o.y) tip = [tip[0] + (o.x || 0), tip[1] + (o.y || 0)];+ if (o.hand !== false && b > a) {+ const off = [o.x || 0, o.y || 0], s0 = _ptAt(list[0], 0), s1 = _ptAt(list[list.length - 1], 1);+ penRecord(a, b, [s0[0] + off[0], s0[1] + off[1]], [s1[0] + off[0], s1[1] + off[1]], tip, list[cur].kind === 'hl' ? list[cur].col : list[cur].col, list[cur].kind === 'hl' ? 'highlighter' : 'marker', o.handScale);+ }+ return { p: p0, done: p0 >= 1, tip };+}++// ---------- handwriting ----------+function _font(o) { return `${o.weight || 700} ${o.size || 72}px ${o.font || FONT_HAND}`; }+// layout of a (multi-line) string: x,y = first line's baseline start (align 'left'), centre ('center') or end ('right')+function textLayout(str, x, y, o = {}) {+ const size = o.size || 72, lh = size * (o.lh || 1.22), lines = String(str).split('\n'), out = [];+ G.save(); G.font = _font(o);+ let x0 = 1e9, x1 = -1e9;+ lines.forEach((ln, li) => {+ const ch = Array.from(ln), xs = [0]; let acc = '';+ for (const c of ch) { acc += c; xs.push(G.measureText(acc).width); }+ const w = xs[xs.length - 1], lx = o.align === 'center' ? x - w / 2 : o.align === 'right' ? x - w : x;+ out.push({ ch, xs, w, x: lx, y: y + li * lh }); x0 = Math.min(x0, lx); x1 = Math.max(x1, lx + w);+ });+ G.restore();+ const top = y - size * .78, h = (lines.length - 1) * lh + size * 1.02;+ return { lines, rows: out, size, box: { x: x0, y: top, w: x1 - x0, h, cx: (x0 + x1) / 2, cy: top + h / 2, x2: x1, y2: top + h, base: y + (lines.length - 1) * lh } };+}+function textBox(str, x, y, o = {}) { return textLayout(str, x, y, o).box; }+// writeOn(text, x, y, a, b, o) → writes the text left to right as the hand moves, returns its box+// o: { size, col, weight, font, align, lh, hand, slant (deg of the reveal edge), jitter }+function writeOn(str, x, y, a, b, o = {}) {+ const L = textLayout(str, x, y, o), size = L.size, c = o.t ?? WB.clock;+ const wt = ch => /\s/.test(ch) ? .35 : 1;+ const items = []; let total = 0;+ L.rows.forEach((r, li) => { if (li) total += 1.2; r.ch.forEach((ch, i) => { const cw = (r.xs[i + 1] - r.xs[i]); const k = wt(ch) * Math.max(.6, cw / size * 1.7); items.push({ r, i, ch, cw, t0: total, k }); total += k; }); });+ const p = b > a ? seg(c, a, b) : c >= a ? 1 : 0, at = lerp(p, ease(p), .25) * total;+ const jit = o.jitter ?? 1, slant = Math.tan((o.slant ?? 14) * Math.PI / 180) * size;+ let tip = null, tcol = o.col || INK.black;+ if (p > 0) {+ G.save(); G.font = _font(o); G.textBaseline = 'alphabetic'; G.fillStyle = markerPat(G, tcol); if (o.alpha != null) G.globalAlpha = o.alpha;+ for (const it of items) {+ if (at <= it.t0) break;+ const f = clamp((at - it.t0) / it.k), h = hash(it.i * 7.1 + it.r.y * .13 + it.r.x * .07), gx = it.r.x + it.r.xs[it.i], gy = it.r.y + (h - .5) * size * .045 * jit;+ if (/\s/.test(it.ch)) continue;+ G.save();+ if (f < 1) { G.beginPath(); const fx = gx + f * (it.cw + slant * .6) - slant * .3; G.moveTo(gx - size * .3, gy - size * 1.1); G.lineTo(fx + slant * .5, gy - size * 1.1); G.lineTo(fx - slant * .5, gy + size * .45); G.lineTo(gx - size * .3, gy + size * .45); G.clip(); }+ G.translate(gx + it.cw / 2, gy); G.rotate((h - .5) * .06 * jit); G.fillText(it.ch, -it.cw / 2, 0);+ G.restore();+ if (f < 1) tip = [gx + f * it.cw, gy - size * (.18 + .32 * (.5 + .5 * Math.sin(f * TAU * 1.5 + it.i)))];+ }+ G.restore();+ }+ if (!tip) { const last = items[items.length - 1]; tip = at <= 0 || !last ? [L.rows[0].x, L.rows[0].y - size * .3] : [last.r.x + last.r.w, last.r.y - size * .2]; }+ if (o.hand !== false && b > a && items.length) {+ const r0 = L.rows[0], rl = L.rows[L.rows.length - 1];+ penRecord(a, b, [r0.x, r0.y - size * .3], [rl.x + rl.w, rl.y - size * .2], tip, tcol, 'marker', o.handScale);+ }+ return { ...L.box, p, done: p >= 1, tip };+}++// ---------- the hand ----------+// Scenes don't draw the hand: drawOn/writeOn record where the pen is, and ENGINE.end draws one hand that follows the+// active pen tip, glides between nearby drawings and leaves/enters the frame (bottom-right) across longer pauses.+// handAt(x, y, o) forces it somewhere (world coords) this frame, e.g. to point or hover; WB.hand = false hides it.+function penRecord(a, b, s0, s1, now, col, tool, sc) {+ const m = G.getTransform(), T2 = ([x, y]) => [m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f];+ PEN.push({ a, b, s0: T2(s0), s1: T2(s1), now: T2(now), col, tool, sc: (sc || 1) * Math.pow(clamp(Math.hypot(m.a, m.b), .6, 1.8), .55) });+}+let _handForce = null;+function handAt(x, y, o = {}) { const m = G.getTransform(); _handForce = { p: [m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f], tool: o.tool || 'marker', col: o.col || INK.black, lift: o.lift ?? 1, sc: o.scale || 1 }; }+function _handPos() {+ if (_handForce) return _handForce;+ if (!WB.hand || !PEN.length) return null;+ const c = WB.clock, ev = [...PEN].sort((x, y) => x.a - y.a);+ const act = ev.filter(e => c >= e.a && c <= e.b); if (act.length) { const e = act[act.length - 1]; return { p: e.now, tool: e.tool, col: e.col, lift: 0, sc: e.sc }; }+ const prev = ev.filter(e => e.b < c).sort((x, y) => x.b - y.b).pop(), next = ev.find(e => e.a > c);+ const offOf = p => [Math.max(p[0] + 420, W + 260), H + 380];+ if (prev && next && next.a - prev.b < 1.1) { const k = ease(seg(c, prev.b, next.a)); return { p: arcPt(prev.s1, next.s0, 50, k), tool: k < .5 ? prev.tool : next.tool, col: k < .5 ? prev.col : next.col, lift: Math.sin(k * Math.PI), sc: lerp(prev.sc, next.sc, k) }; }+ if (prev && c < prev.b + .6) { const k = easeIn(seg(c, prev.b, prev.b + .6)); return { p: [lerp(prev.s1[0], offOf(prev.s1)[0], k), lerp(prev.s1[1], offOf(prev.s1)[1], k)], tool: prev.tool, col: prev.col, lift: k, sc: prev.sc }; }+ if (next && c > next.a - .6) { const k = easeOut(seg(c, next.a - .6, next.a)); return { p: [lerp(offOf(next.s0)[0], next.s0[0], k), lerp(offOf(next.s0)[1], next.s0[1], k)], tool: next.tool, col: next.col, lift: 1 - k, sc: next.sc }; }+ return null;+}+const _handSprites = new Map();+// the hand + marker, drawn once per ink colour into a sprite; local frame: pen tip at (0,0), marker along +x+function _paintHand(x, tool, col) {+ const OL = '#5A3B2E', SK = '#F4CBA6', SH = '#E3A987', NL = '#FBE3D2';+ const blob = (pts, fill, stroke = OL, lw = 4) => { x.beginPath(); const q = catmull(pts, true, 4); q.forEach((p, i) => i ? x.lineTo(p[0], p[1]) : x.moveTo(p[0], p[1])); x.closePath(); x.fillStyle = fill; x.fill(); if (stroke) { x.strokeStyle = stroke; x.lineWidth = lw; x.lineJoin = 'round'; x.stroke(); } };+ const capsule = (a, b, r, fill) => { x.save(); x.lineCap = 'round'; x.strokeStyle = OL; x.lineWidth = 2 * r + 8; x.beginPath(); x.moveTo(...a); x.lineTo(...b); x.stroke(); x.strokeStyle = fill; x.lineWidth = 2 * r; x.stroke(); x.restore(); };+ x.lineJoin = 'round'; x.lineCap = 'round';+ if (tool === 'eraser') {+ // eraser block (seen from the handle side), anchor at its centre; hand grips it from the right+ x.save(); x.fillStyle = '#6E737B'; x.beginPath(); x.roundRect(-82, -168, 164, 336, 22); x.fill();+ x.fillStyle = '#2F63C7'; x.beginPath(); x.roundRect(-70, -156, 140, 312, 30); x.fill();+ x.fillStyle = 'rgba(255,255,255,.22)'; x.beginPath(); x.roundRect(-58, -144, 36, 288, 18); x.fill();+ x.strokeStyle = '#1F2B45'; x.lineWidth = 4; x.beginPath(); x.roundRect(-82, -168, 164, 336, 22); x.stroke();+ x.restore();+ blob([[30, -90], [80, -118], [140, -104], [176, -40], [172, 40], [140, 96], [70, 104], [36, 60], [26, -20]], SK);+ for (let i = 0; i < 4; i++) capsule([60, -84 + i * 42], [-36, -80 + i * 44], 18, SK);+ blob([[26, -110], [70, -128], [96, -100], [60, -80], [26, -84]], SK);+ x.strokeStyle = SH; x.lineWidth = 5; x.beginPath(); x.moveTo(120, -60); x.quadraticCurveTo(150, 0, 128, 70); x.stroke();+ return;+ }+ // marker body+ const HW = 19;+ x.fillStyle = col; x.beginPath(); x.moveTo(-2, -5); x.quadraticCurveTo(-6, 0, -2, 5); x.lineTo(20, 10); x.lineTo(20, -10); x.closePath(); x.fill();+ x.strokeStyle = '#2B2E33'; x.lineWidth = 3; x.stroke();+ const bar = (a, b, hw, fill) => { x.beginPath(); x.roundRect(a, -hw, b - a, 2 * hw, 7); x.fillStyle = fill; x.fill(); x.strokeStyle = '#2B2E33'; x.lineWidth = 3.5; x.stroke(); };+ bar(18, 360, HW, '#F3F3EF'); bar(18, 40, HW - 3, '#DADBD6');+ x.fillStyle = 'rgba(255,255,255,.7)'; x.fillRect(44, -HW + 5, 300, 6);+ x.fillStyle = 'rgba(0,0,0,.08)'; x.fillRect(44, HW - 9, 300, 7);+ bar(305, 372, HW + 3, col); x.fillStyle = col; x.fillRect(180, -HW + 2, 70, 2 * HW - 4);+ x.fillStyle = 'rgba(255,255,255,.25)'; x.fillRect(308, -HW + 1, 60, 6);+ // curled fingers under the index (middle + ring), then palm, thumb, index finger on top+ capsule([236, 58], [176, 52], 21, SK); // curled middle finger peeking under the thumb+ blob([[150, -36], [196, -66], [262, -74], [318, -56], [342, -6], [330, 50], [290, 84], [232, 88], [176, 70], [150, 30]], SK);+ x.fillStyle = SH; x.globalAlpha = .55; x.beginPath(); x.ellipse(268, 50, 58, 22, -.3, 0, TAU); x.fill(); x.globalAlpha = 1;+ // knuckle bumps on the back of the hand+ x.strokeStyle = SH; x.lineWidth = 4;[[214, -52], [248, -56], [282, -50]].forEach(([a, b]) => { x.beginPath(); x.arc(a, b + 14, 12, Math.PI * 1.15, Math.PI * 1.85); x.stroke(); });+ capsule([204, 64], [104, 30], 21, SK); // thumb+ x.fillStyle = NL; x.beginPath(); x.ellipse(112, 30, 11, 8, .33, 0, TAU); x.fill();+ capsule([200, -42], [70, -38], 18, SK); // index finger along the marker+ x.fillStyle = NL; x.beginPath(); x.ellipse(78, -40, 11, 8, 0, 0, TAU); x.fill();+ x.strokeStyle = SH; x.lineWidth = 4; x.beginPath(); x.arc(132, -34, 10, Math.PI * 1.2, Math.PI * 1.8); x.stroke();+}+function _handSprite(tool, col) {+ const key = tool + col; let c = _handSprites.get(key); if (c) return c;+ const S2 = 760, A = 140; c = makeCanvas(S2, S2); const x = c.getContext('2d');+ // soft shadow on the board first (the hand is a few cm in front of it)+ const sh = makeCanvas(S2, S2), sx = sh.getContext('2d'); sx.translate(A + (tool === 'eraser' ? 240 : 0), A + (tool === 'eraser' ? 240 : 0)); _paintHand(sx, tool, '#000');+ x.save(); x.filter = 'blur(14px)'; x.globalAlpha = .2; x.globalCompositeOperation = 'source-over';+ x.drawImage(sh, 22, 30); x.restore();+ x.save(); x.globalCompositeOperation = 'source-in'; x.fillStyle = '#28231E'; x.fillRect(0, 0, S2, S2); x.restore();+ x.save(); x.translate(A + (tool === 'eraser' ? 240 : 0), A + (tool === 'eraser' ? 240 : 0)); _paintHand(x, tool, col); x.restore();+ c.anchor = tool === 'eraser' ? [A + 240, A + 240] : [A, A]; _handSprites.set(key, c); return c;+}+// draws the hand in SCREEN space: tip at p, `ang` = marker direction (radians; ~0.7 = pointing up-left from lower right)+function drawHand(ctx, p, o = {}) {+ const tool = o.tool || 'marker', col = o.col || INK.black, sc = (o.sc || 1) * WB.handScale * (1 + .05 * (o.lift || 0));+ const ang = o.ang ?? (tool === 'eraser' ? .08 : .64 + .12 * (p[1] / H) - .1 * (p[0] / W) + .025 * Math.sin(WB.clock * 7));+ const lift = (o.lift || 0) * 10, spr = _handSprite(tool, col);+ ctx.save(); ctx.translate(p[0], p[1] - lift); ctx.rotate(ang); ctx.scale(sc, sc);+ // sleeve/forearm running off-frame (drawn per frame: too long for the sprite)+ const [wx, wy, da] = tool === 'eraser' ? [150, 110, .7] : [318, 30, .3], dx = Math.cos(da), dy = Math.sin(da), nx = -dy, ny = dx, L = 3000;+ const arm = (off, fill, hw0 = 64, hw1 = 96) => { ctx.beginPath(); ctx.moveTo(wx + nx * hw0 + off, wy + ny * hw0 + off); ctx.lineTo(wx + dx * L + nx * hw1 + off, wy + dy * L + ny * hw1 + off); ctx.lineTo(wx + dx * L - nx * hw1 + off, wy + dy * L - ny * hw1 + off); ctx.lineTo(wx - nx * hw0 + off, wy - ny * hw0 + off); ctx.closePath(); ctx.fillStyle = fill; ctx.fill(); };+ arm(26, 'rgba(40,35,30,.10)', 74, 110); arm(16, 'rgba(40,35,30,.08)');+ ctx.drawImage(spr, -spr.anchor[0], -spr.anchor[1]);+ arm(0, WB.sleeve); ctx.strokeStyle = '#243E73'; ctx.lineWidth = 4; ctx.stroke();+ // cuff+ const cx0 = wx + dx * 8, cy0 = wy + dy * 8; ctx.beginPath(); ctx.moveTo(cx0 + nx * 70, cy0 + ny * 70); ctx.lineTo(cx0 + dx * 40 + nx * 74, cy0 + dy * 40 + ny * 74); ctx.lineTo(cx0 + dx * 40 - nx * 74, cy0 + dy * 40 - ny * 74); ctx.lineTo(cx0 - nx * 70, cy0 - ny * 70); ctx.closePath();+ ctx.fillStyle = _lighter(WB.sleeve, .25); ctx.fill(); ctx.stroke();+ ctx.restore();+}++// ---------- transitions ----------+let _mask = null, _tmp = null, _tmpCtx = null, _maskCtx = null, _prev = null, _prevCtx = null;+function _scratch() { if (!_mask) { _mask = makeCanvas(); _maskCtx = _mask.getContext('2d'); _tmp = makeCanvas(); _tmpCtx = _tmp.getContext('2d'); _prev = makeCanvas(); _prevCtx = _prev.getContext('2d'); } }+function _zigPath(rows, pad = 260) { const pts = []; for (let r = 0; r < rows; r++) { const y = H * (r + .5) / rows, L = r % 2 ? [W + pad, y] : [-pad, y], R = r % 2 ? [-pad, y] : [W + pad, y]; if (!r) pts.push([W + pad, y - 40], [-pad, y + 10]); else pts.push(L, R); } return resample(pts.slice(0), 12); }+// eraseWipe(p): an eraser (held by the hand) scrubs the whole screen clean in zigzag passes. Call in SCREEN space+// (after camEnd()) at the end of a shot: p = seg(lt, dur - .9, dur). A faint ghost of the old drawing stays behind.+function eraseWipe(p, o = {}) {+ if (p <= 0) return;+ _scratch(); const rows = o.rows || 4, path = _zigPath(rows), cum = cumOf(path), tot = cum[cum.length - 1], L = lerp(p, ease(p), .5) * tot;+ const part = _part({ p: path, cum, len: tot }, L);+ _maskCtx.setTransform(1, 0, 0, 1, 0, 0); _maskCtx.clearRect(0, 0, W, H);+ _maskCtx.lineCap = 'round'; _maskCtx.lineJoin = 'round'; _maskCtx.lineWidth = H / rows * 1.32; _maskCtx.strokeStyle = '#000';+ if (p >= 1) _maskCtx.fillRect(0, 0, W, H); else { _maskCtx.beginPath(); part.forEach((q, i) => i ? _maskCtx.lineTo(q[0], q[1]) : _maskCtx.moveTo(q[0], q[1])); _maskCtx.stroke(); }+ const t = _tmpCtx; t.setTransform(1, 0, 0, 1, 0, 0); t.globalCompositeOperation = 'source-over'; t.globalAlpha = 1; t.clearRect(0, 0, W, H);+ const cam = LAST_CAM || { cx: W / 2, cy: H / 2, zoom: 1, rot: 0 };+ t.save(); t.translate(W / 2, H / 2); t.rotate(cam.rot || 0); t.scale(cam.zoom, cam.zoom); t.translate(-cam.cx, -cam.cy); board(o.bg || WB.bg, t, cam); t.restore();+ t.globalAlpha = o.ghost ?? .06; t.drawImage(OUTC, 0, 0); t.globalAlpha = 1;+ t.globalCompositeOperation = 'destination-in'; t.drawImage(_mask, 0, 0); t.globalCompositeOperation = 'source-over';+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0); G.drawImage(_tmp, 0, 0); G.restore();+ if (p < 1 && o.hand !== false) { const e = part[part.length - 1], q = part[Math.max(0, part.length - 4)]; _handForce = { p: e, tool: 'eraser', col: INK.black, lift: 0, sc: H / rows * 1.32 / 336 / WB.handScale, ang: .08 + clamp((e[0] - q[0]) / 60, -1, 1) * .06 }; }+}+// eraseRect(x, y, w, h, a, b): erase one area of the board (world coords) with the eraser between times a→b.+// The eraser scrubs it in horizontal passes; whatever surface the shot uses (lines, grid) is restored underneath.+function eraseRect(x, y, w, h, a, b, o = {}) {+ const p = seg(o.t ?? WB.clock, a, b); if (p <= 0) return;+ const rows = Math.max(1, Math.round(h / 150)), bh = h / rows, pad = 30, k = ease(p) * rows;+ G.save(); G.beginPath();+ let tip = null;+ for (let r = 0; r < rows; r++) {+ const f = clamp(k - r); if (f <= 0) break;+ const ry = y + bh * r - (r ? 0 : pad * .5), rh = bh + (r === rows - 1 ? pad : 0) + (r ? 0 : pad * .5), ww = (w + 2 * pad) * f;+ if (r % 2) G.rect(x + w + pad - ww, ry, ww, rh); else G.rect(x - pad, ry, ww, rh);+ if (f < 1) tip = [r % 2 ? x + w + pad - ww : x - pad + ww, y + bh * (r + .5)];+ }+ G.clip(); board(WB.bg); G.restore();+ if (p < 1 && tip && o.hand !== false) { const m = G.getTransform(); _handForce = { p: [m.a * tip[0] + m.c * tip[1] + m.e, m.b * tip[0] + m.d * tip[1] + m.f], tool: 'eraser', col: INK.black, lift: 0, sc: bh * 1.2 / 336 / WB.handScale * Math.hypot(m.a, m.b), ang: .08 }; }+}+// render the previous shot's last frame into a canvas (for page flips / cross-shot effects)+function prevShotFrame() {+ let i = 0; while (i + 1 < SHOTS.length && T >= SHOTS[i + 1][0]) i++;+ if (i === 0) return null;+ _scratch(); const t0 = SHOTS[i - 1][0], t1 = SHOTS[i][0] - 1 / FPS, saveG = G, saveCam = CAM, saveLast = LAST_CAM, clk = WB.clock, bg = WB.bg, pen = PEN.splice(0), hf = _handForce;+ const c = _prevCtx; c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = 'source-over'; c.clearRect(0, 0, W, H);+ G = c; CAM = null; WB._nested = true;+ try { SHOTS[i - 1][1](t1, t1 - t0, SHOTS[i][0] - t0); if (CAM) camEnd(); } finally { WB._nested = false; }+ G = saveG; CAM = saveCam; LAST_CAM = saveLast; WB.clock = clk; WB.bg = bg; PEN.length = 0; PEN.push(...pen); _handForce = hf;+ return _prev;+}+// pageFlip(p): the previous shot's page curls away from the bottom-right corner, revealing this shot underneath.+// Call in SCREEN space at the START of the new shot (after camEnd()): p = seg(lt, 0, .9).+function pageFlip(p, o = {}) {+ if (p >= 1 || WB._nested) return;+ const old = prevShotFrame(); if (!old) return;+ const k = easeIn(p) * .55 + ease(p) * .45, C = [W, H], P = [W - 2.4 * W * k - 20 * k, H - 1.15 * H * k - 60 * Math.sin(k * Math.PI)];+ const M = [(C[0] + P[0]) / 2, (C[1] + P[1]) / 2], d = [C[0] - P[0], C[1] - P[1]], dl = Math.hypot(...d) || 1, n = [d[0] / dl, d[1] / dl];+ const side = q => (q[0] - M[0]) * n[0] + (q[1] - M[1]) * n[1]; // > 0: the part that has flipped over+ const rect = [[0, 0], [W, 0], [W, H], [0, H]];+ const clipPoly = (poly, keep) => { const out = []; for (let i = 0; i < poly.length; i++) { const a = poly[i], b = poly[(i + 1) % poly.length], sa = side(a), sb = side(b); if (keep(sa)) out.push(a); if ((sa > 0) !== (sb > 0)) { const t = sa / (sa - sb); out.push([lerp(a[0], b[0], t), lerp(a[1], b[1], t)]); } } return out; };+ const stay = clipPoly(rect, s => s <= 0), flap = clipPoly(rect, s => s > 0).map(q => { const s = side(q); return [q[0] - 2 * s * n[0], q[1] - 2 * s * n[1]]; });+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0);+ const path = poly => { G.beginPath(); poly.forEach((q, i) => i ? G.lineTo(q[0], q[1]) : G.moveTo(q[0], q[1])); G.closePath(); };+ if (stay.length > 2) { G.save(); path(stay); G.clip(); G.drawImage(old, 0, 0); G.restore(); }+ if (flap.length > 2) {+ // shadow of the lifted flap on the new page, the flap's back, and a crease highlight+ G.save(); G.translate(-n[0] * 18, -n[1] * 18); path(flap); G.fillStyle = 'rgba(40,35,25,.16)'; G.filter = 'blur(12px)'; G.fill(); G.restore();+ path(flap); const g = G.createLinearGradient(M[0], M[1], M[0] - n[0] * 500, M[1] - n[1] * 500);+ g.addColorStop(0, '#D9D4C6'); g.addColorStop(.25, '#F4F1E8'); g.addColorStop(1, '#FBF9F2'); G.fillStyle = g; G.fill();+ G.strokeStyle = 'rgba(60,55,45,.35)'; G.lineWidth = 2; G.stroke();+ }+ G.restore();+}+// panCarry: the classic "slide to the next part of the board" is ONE shot whose camera keys travel across a big world;+// use wbBegin(lt, { cam: [[0,[960,540,1]], [3.2,[960,540,1]], [4,[2900,540,1]]] }) and draw both areas in world coords.++// ---------- captions (overlay) ----------+// wbCaption(c, text, o): a clean white card with handwritten text at the bottom; *word* = accent colour.+// wbCaptions([[a, b, 'text'], ...], o) installs window.overlayHook to show them at video times a..b.+function wbCaption(c, txt, o = {}) {+ const size = o.size || 64, y = o.y || H - 88, k = o.k ?? 1, font = `700 ${size}px ${FONT_HAND}`, acc = o.accent || INK.orange;+ const parts = String(txt).split('*');+ c.save(); c.font = font; c.textBaseline = 'middle';+ const widths = parts.map(s => c.measureText(s).width), w = widths.reduce((a, b) => a + b, 0), pw = w + size * 1.3, ph = size * 1.55;+ c.globalAlpha = clamp(k * 1.6); c.translate(W / 2, y); c.scale(lerp(.85, 1, backOut(k)), lerp(.85, 1, backOut(k))); c.rotate(-.006);+ c.fillStyle = 'rgba(30,30,40,.18)'; c.beginPath(); c.roundRect(-pw / 2 + 4, -ph / 2 + 7, pw, ph, 18); c.fill();+ c.fillStyle = '#FFFFFF'; c.beginPath(); c.roundRect(-pw / 2, -ph / 2, pw, ph, 18); c.fill();+ c.strokeStyle = 'rgba(35,38,43,.9)'; c.lineWidth = 4; c.stroke();+ let x = -w / 2; parts.forEach((s, i) => { c.fillStyle = i % 2 ? acc : INK.black; c.fillText(s, x, size * .06); x += widths[i]; });+ c.restore();+}+function wbCaptions(list, o = {}) {+ window.overlayHook = (c, t) => { for (const [a, b, txt] of list) if (t >= a && t < b) wbCaption(c, txt, { ...o, k: Math.min(seg(t, a, a + .3), 1 - seg(t, b - .2, b)) }); };+}++// ---------- engine hooks ----------+function _loadText() { // every character used in the page's scripts, so the CJK font slices get fetched up front+ let s = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~,。!?、:;「」…—';+ for (const el of document.scripts) if (el.src) { try { const x = new XMLHttpRequest(); x.open('GET', el.src, false); x.send(); s += x.responseText; } catch (e) { } }+ s += (window.WB_TEXT || '');+ return [...new Set(s)].filter(ch => ch.codePointAt(0) > 32).join('');+}+window.ENGINE = {+ async setup() {+ const txt = _loadText();+ await Promise.all(['400', '700'].flatMap(w => ['Kalam', 'LXGW WenKai TC'].map(f => document.fonts.load(`${w} 60px "${f}"`, txt).catch(() => null))));+ _buildTextures();+ },+ begin(t) { PEN.length = 0; _handForce = null; WB.clock = t; WB.bg = { kind: 'white' }; },+ end(t) {+ G.save(); G.setTransform(1, 0, 0, 1, 0, 0);+ const h = _handPos(); if (h) drawHand(G, h.p, h);+ G.globalCompositeOperation = 'multiply'; G.drawImage(TEX.vignette, 0, 0);+ G.restore();+ },+};diff --git a/.claude/skills/whiteboard/template/studio.html b/.claude/skills/whiteboard/template/studio.htmlnew file mode 100644index 0000000..7e9f29c--- /dev/null+++ b/.claude/skills/whiteboard/template/studio.html@@ -0,0 +1,30 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>whiteboard studio</title>+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Kalam:wght@400;700&family=LXGW+WenKai+TC:wght@400;700&display=block">+<style>+ html, body { margin: 0; background: #1b1820; color: #eee; font: 13px system-ui, sans-serif; }+ main { padding: 12px; display: grid; gap: 8px; }+ #out { width: min(100%, 1280px); aspect-ratio: 16 / 9; height: auto; background: #fff; }+ .bar { display: flex; gap: 10px; align-items: center; max-width: 1280px; }+ #scrub { flex: 1; } #tt { font-variant-numeric: tabular-nums; min-width: 190px; }+</style>+</head>+<body>+<main>+ <canvas id="out" width="1920" height="1080"></canvas>+ <div class="bar"><input id="scrub" type="range" min="0" max="10" step="0.0417" value="0"><span id="tt">loading…</span></div>+</main>+<!-- engine: config, shared kit, this engine's drawing library -->+<script src="src/config.js"></script>+<script src="src/kit.js"></script>+<script src="src/whiteboard.js"></script>+<script src="src/cast.js"></script>+<!-- model sheets (standalone loops: node render.mjs --loop=cast ...) -->+<script src="src/sheets.js"></script>+<!-- your video: one script per scene file, in order -->+<script src="src/scenes/demo.js"></script>+</body>+</html>diff --git a/README.md b/README.mdindex 234c1bb..becfa0a 100644--- a/README.md+++ b/README.md@@ -76,12 +76,14 @@ The whole thing runs on your own computer, with your own Claude Code or Codex.## Good to know-- **2D only, two drawing engines so far:** clean vector / motion graphics (built on- [HyperFrames](https://github.com/heygen-com/hyperframes)) and hand-painted watercolor (built on- [painted-animation](https://github.com/tuzhechen2005/painted-animation)). When a reference doesn't match a known- style, it uses the closest engine and writes up a proposal for a new style.+- **2D only, seven drawing engines:** vector / motion graphics (built on+ [HyperFrames](https://github.com/heygen-com/hyperframes)), hand-painted watercolor (built on+ [painted-animation](https://github.com/tuzhechen2005/painted-animation)), crayon picture book, pixel art, paper+ cut-out stop-motion, whiteboard doodle, and anime cel. The newer five are young and have had less real-world use than+ the first two. When a reference doesn't match a known style, it uses the closest engine and writes up a proposal+ for a new style.- **It takes a while.** A 30–60 second video usually takes 1–3.5 hours after you approve the plan, depending on the- length and the look. Watercolor is the slowest, because every frame is painted.+ length and the look. Watercolor and crayon are the slowest, because every frame is painted with brushes.- **It uses your AI plan.** All the work runs through your Claude Code or Codex account, so it counts toward thataccount's usage. If you hit a limit, the job pauses and can pick up where it stopped.- **Tested mostly on Windows.** macOS and Linux should work, but they've had less testing. Issues are welcome.@@ -89,7 +91,7 @@ The whole thing runs on your own computer, with your own Claude Code or Codex.## Roadmap-- More drawing engines (pixel art, anime-style hand-drawn characters)+- More built-in characters and styles for each engine- Save a newly discovered style from the web app, so the next similar reference matches it directly- Faster watercolor renderingdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex a59a39d..8dd76c7 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -17,8 +17,8 @@<table><tr><td align="center" width="33%"><img src="docs/assets/demo-sugar.gif" alt="Sugar Rush"></td>- <td align="center" width="33%"><img src="docs/assets/demo-sunshine-boy.gif" alt="阳光宅男"></td>- <td align="center" width="33%"><img src="docs/assets/demo-cat-bath.gif" alt="橘宝洗澡记"></td>+ <td align="center" width="33%"><img src="docs/assets/demo-sunshine-boy.gif" alt="陽光宅男"></td>+ <td align="center" width="33%"><img src="docs/assets/demo-cat-bath.gif" alt="橘寶洗澡記"></td></tr><tr><td align="center"><b>Sugar Rush</b><br><sub>MV · 手绘水彩 · 58 秒</sub></td>@@ -72,15 +72,15 @@ ReelMimic 学的是参考片的做法,不是把原本的画面、角色或素## 先说清楚-- **目前只做 2D,有两种画法:** 干净的矢量/动态图像(以 [HyperFrames](https://github.com/heygen-com/hyperframes) 为基础),以及手绘水彩(以 [painted-animation](https://github.com/tuzhechen2005/painted-animation) 为基础)。参考片对不到已知风格时,会用最接近的画法做,并写一份新风格的建议。-- **需要一点时间。** 30–60 秒的视频,企划核准后通常要 1–3.5 小时,看长度和画风。手绘水彩最慢,因为每一格都是画出来的。+- **目前只做 2D,有七种画法:** 矢量/动态图像(以 [HyperFrames](https://github.com/heygen-com/hyperframes) 为基础)、手绘水彩(以 [painted-animation](https://github.com/tuzhechen2005/painted-animation) 为基础)、蜡笔绘本、像素风、剪纸定格、白板手绘、动漫赛璐璐。后面五种比较新,实际做片的次数比前两种少。参考片对不到已知风格时,会用最接近的画法做,并写一份新风格的建议。+- **需要一点时间。** 30–60 秒的视频,企划核准后通常要 1–3.5 小时,看长度和画风。手绘水彩和蜡笔最慢,因为每一格都是用笔刷画出来的。- **用的是你的 AI 额度。** 所有工作都通过你的 Claude Code 或 Codex 账号跑,会算进那个账号的用量。额度用完时会暂停,之后可以从停下来的地方继续。- **主要在 Windows 上测过。** macOS 和 Linux 应该可以用,但测得比较少,有问题欢迎开 issue。- **不做真人。** 它做的是动画,不会生成真实人物的实拍画面。## 接下来-- 更多画法(像素风、动漫风手绘角色)+- 每种画法更多内置角色与风格- 在网站上一键把新发现的风格存起来,下次遇到同类参考片就直接对到- 让手绘水彩渲染更快diff --git a/README.zh-TW.md b/README.zh-TW.mdindex f9bfd3f..42e875a 100644--- a/README.zh-TW.md+++ b/README.zh-TW.md@@ -72,15 +72,15 @@ ReelMimic 學的是參考片的做法,不是把原本的畫面、角色或素## 先說清楚-- **目前只做 2D,有兩種畫法:** 乾淨的向量/動態圖像(以 [HyperFrames](https://github.com/heygen-com/hyperframes) 為基礎),以及手繪水彩(以 [painted-animation](https://github.com/tuzhechen2005/painted-animation) 為基礎)。參考片對不到已知風格時,會用最接近的畫法做,並寫一份新風格的建議。-- **需要一點時間。** 30–60 秒的影片,企劃核准後通常要 1–3.5 小時,看長度和畫風。手繪水彩最慢,因為每一格都是畫出來的。+- **目前只做 2D,有七種畫法:** 向量/動態圖像(以 [HyperFrames](https://github.com/heygen-com/hyperframes) 為基礎)、手繪水彩(以 [painted-animation](https://github.com/tuzhechen2005/painted-animation) 為基礎)、蠟筆繪本、像素風、剪紙定格、白板手繪、動漫賽璐璐。後面五種比較新,實際做片的次數比前兩種少。參考片對不到已知風格時,會用最接近的畫法做,並寫一份新風格的建議。+- **需要一點時間。** 30–60 秒的影片,企劃核准後通常要 1–3.5 小時,看長度和畫風。手繪水彩和蠟筆最慢,因為每一格都是用筆刷畫出來的。- **用的是你的 AI 額度。** 所有工作都透過你的 Claude Code 或 Codex 帳號跑,會算進那個帳號的用量。額度用完時會暫停,之後可以從停下來的地方繼續。- **主要在 Windows 上測過。** macOS 和 Linux 應該可以用,但測得比較少,有問題歡迎開 issue。- **不做真人。** 它做的是動畫,不會生成真實人物的實拍畫面。## 接下來-- 更多畫法(像素風、動漫風手繪角色)+- 每種畫法更多內建角色與風格- 在網站上一鍵把新發現的風格存起來,下次遇到同類參考片就直接對到- 讓手繪水彩渲染更快diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 93f960e..0e307ca 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -1,6 +1,6 @@# Third-party notices-ReelMimic's own code (`app/`, `.claude/skills/video-clone/`, `.claude/skills/blender-product-film/`) is MIT-licensed (see `LICENSE`).+ReelMimic's own code (`app/`, `.claude/skills/video-clone/`, `.claude/skills/blender-product-film/`, and the `pixel-art`, `paper-cutout`, `whiteboard`, `anime-cel` engines apart from their `render.mjs`) is MIT-licensed (see `LICENSE`).The following bundled skills and assets keep their original licenses.| Path | Upstream | License | Copyright |@@ -11,6 +11,7 @@ The following bundled skills and assets keep their original licenses.| `.claude/skills/frontend-design` | [anthropics/skills](https://github.com/anthropics/skills) | Apache-2.0 (`LICENSE.txt` included) | © Anthropic || `.claude/skills/ffmpeg` | [digitalsamba/claude-code-video-toolkit](https://github.com/digitalsamba/claude-code-video-toolkit) | MIT | © 2024 Digital Samba || `.claude/skills/painted-animation` | [tuzhechen2005/painted-animation](https://github.com/tuzhechen2005/painted-animation); `template/` from [JohnHeibel/ClaudeAnimationBase](https://github.com/JohnHeibel/ClaudeAnimationBase) | MIT (both `LICENSE` files included) | © 2026 tuzhechen2005; © 2026 John Heibel |+| `.claude/skills/crayon-storybook` (runtime derived from painted-animation); `render.mjs` in `video-clone/assets/engine-kit/` and in the `pixel-art`, `paper-cutout`, `whiteboard`, `anime-cel` templates | painted-animation / ClaudeAnimationBase (above) | MIT (`LICENSE` / `LICENSE-render.mjs.txt` included next to them) | © 2026 tuzhechen2005; © 2026 John Heibel || Fonts in `embedded-captions`, `talking-head-recut`, `hyperframes-creative` | Google Fonts / Excalidraw (Virgil) | SIL Open Font License 1.1 | respective authors |Apache-2.0 full text: [LICENSES/Apache-2.0.txt](LICENSES/Apache-2.0.txt) (also <https://www.apache.org/licenses/LICENSE-2.0>) · MIT: see each upstream repository.diff --git a/docs/EXTENDING.md b/docs/EXTENDING.mdindex 4c9b5c7..47510a3 100644--- a/docs/EXTENDING.md+++ b/docs/EXTENDING.md@@ -70,6 +70,15 @@ to build `build/production.json`):Then write a style file pointing to it (previous section). Before adding a third-party skill, read its scripts and addits license to `THIRD_PARTY_NOTICES.md`.+### Starting from the engine kit++`.claude/skills/video-clone/assets/engine-kit/` is the fastest way to build a new look. It has the shared runtime the+pixel-art, paper-cutout, whiteboard and anime-cel engines are built on (timeline, motion helpers, camera, captions and+the render contract), the headless-Chrome `render.mjs`, a page template, `new_project.sh`, and `ENGINE_BRIEF.md`, the+checklist those engines were built from. Copy it into `.claude/skills/<your-engine>/template/`, write your drawing+library and characters, and you get parallel rendering, contact sheets and crops for review, and resumable export for+free.+### Character systems- `assets/vector_rig/`: 2D vector characters — a skeleton (neck, shoulders, elbows, wrists, hips, knees) with onediff --git a/docs/zh-CN/ARCHITECTURE.md b/docs/zh-CN/ARCHITECTURE.mdindex e148910..12b79e5 100644--- a/docs/zh-CN/ARCHITECTURE.md+++ b/docs/zh-CN/ARCHITECTURE.md@@ -138,6 +138,6 @@ projects/<id>/| `compare.py` | 成片与参考片逐镜并排比较 || `hf_frames.py` | HyperFrames 项目截屏:一次调用多个时间点、PIL 裁切、依内容缓存、全机并行上限 || `fetch_assets.py` | 授权安全素材搜索与下载(Openverse、Pixabay、Freesound),自动写 ASSETS.md |-| `align_lyrics.py` | 用户提供的歌词文本 × 音频文件 → 每句时间(faster-whisper 只当量尺) |+| `align_lyrics.py` | 用户提供的歌词文本 × 音档 → 每句时间(faster-whisper 只当量尺) || `yating_tts.py` | 雅婷台湾华语语音 || `timeline.py` | 分析一支片的生产时间:每个阶段、每个 agent、时间花在哪 |diff --git a/docs/zh-CN/EXTENDING.md b/docs/zh-CN/EXTENDING.mdindex 5bad2d1..8aff7ce 100644--- a/docs/zh-CN/EXTENDING.md+++ b/docs/zh-CN/EXTENDING.md@@ -60,6 +60,10 @@ ReelMimic 的扩充点由浅到深:然后写一个指向它的风格档(上一节)。第三方 skill 放进来前,请先看过它的脚本,并把授权补进 `THIRD_PARTY_NOTICES.md`。+### 从引擎骨架开始++`.claude/skills/video-clone/assets/engine-kit/` 是做新画法最快的起点:像素风、剪纸、白板、动漫四个引擎都建在它上面。里面有共用的运行环境(时间轴、动作函数、镜头、字幕与渲染界面)、无头 Chrome 的 `render.mjs`、页面范本、`new_project.sh`,以及当初做这些引擎用的检查清单 `ENGINE_BRIEF.md`。拷贝到 `.claude/skills/<你的引擎>/template/`,写好画法函数库和角色,就直接有平行渲染、审查用的总览图与裁切、可续跑的输出。+### 角色系统- `assets/vector_rig/`:2D 矢量角色,骨架(脖子、肩、肘、腕、髋、膝)+每个深度层只描一次外框,四肢永远接在身上。用法见其 README。@@ -120,7 +124,7 @@ agent 需要能:读写 repo 内文件、运行 shell(python、node、ffmpeg```bashcd appnpm run server # 只跑后端(改 server/ 后重启:bash app/restart.sh)-npm run web # 前端开发服务器 http://localhost:5173(热更新,/api 转到 4318)+npm run web # 前端开发服务器 http://localhost:5173(熱更新,/api 转到 4318)npm run build # 输出 app/dist,给 npm start / start.sh 用npm run doctor # 环境检查```diff --git a/docs/zh-TW/EXTENDING.md b/docs/zh-TW/EXTENDING.mdindex 664f947..f38b859 100644--- a/docs/zh-TW/EXTENDING.md+++ b/docs/zh-TW/EXTENDING.md@@ -60,6 +60,10 @@ ReelMimic 的擴充點由淺到深:然後寫一個指向它的風格檔(上一節)。第三方 skill 放進來前,請先看過它的腳本,並把授權補進 `THIRD_PARTY_NOTICES.md`。+### 從引擎骨架開始++`.claude/skills/video-clone/assets/engine-kit/` 是做新畫法最快的起點:像素風、剪紙、白板、動漫四個引擎都建在它上面。裡面有共用的執行環境(時間軸、動作函式、鏡頭、字幕與渲染介面)、無頭 Chrome 的 `render.mjs`、頁面範本、`new_project.sh`,以及當初做這些引擎用的檢查清單 `ENGINE_BRIEF.md`。複製到 `.claude/skills/<你的引擎>/template/`,寫好畫法函式庫和角色,就直接有平行渲染、審查用的總覽圖與裁切、可續跑的輸出。+### 角色系統- `assets/vector_rig/`:2D 向量角色,骨架(脖子、肩、肘、腕、髖、膝)+每個深度層只描一次外框,四肢永遠接在身上。用法見其 README。