An AI skill that turns books into animated, narrated, interactive web experiences
JavaScript ai-agentsai-educationanimationclaudeclaude-codeclaude-skillsedtecheducationinteractive-textbookscormtext-to-video
feat(skill): documentaries, a kit, a reference and their scripts
yzr619319def86f
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.mdindex ca9c5af..a0bed78 100644--- a/.claude/skills/papermorph/SKILL.md+++ b/.claude/skills/papermorph/SKILL.md@@ -1,6 +1,6 @@---name: papermorph-description: Make or edit animated, narrated, interactive web books from reference PDFs, and animated picture books (paper-puppet films) from a story, a joke or a fairy tale. Use for book planning, storyboards, chapter animation and exercises, narration, and cover and contents pages, including "make the next chapter", "turn this story into a picture book" or "fix this animation". Deliver runnable static book files; bookshelf design, bookshelf registration and hosting are separate tasks.+description: Make or edit animated, narrated, interactive web books from reference PDFs, animated picture books (paper-puppet films) from a story, a joke or a fairy tale, and narrated documentaries about a book or an idea, built from public-domain pictures. Use for book planning, storyboards, chapter animation and exercises, narration, and cover and contents pages, including "make the next chapter", "turn this story into a picture book", "make a documentary about this book" or "fix this animation". Deliver runnable static book files; bookshelf design, bookshelf registration and hosting are separate tasks.---# Papermorph@@ -20,9 +20,10 @@ What the picture should be depends on the book and on the user, so the work star|---|---|---|| A textbook PDF | [Lessons](#lessons) | [intake.md](references/intake.md), then [diagrams.md](references/diagrams.md) (tier 1) or [scenes.md](references/scenes.md) (tier 2), [authoring.md](references/authoring.md), [assets.md](references/assets.md), [review.md](references/review.md) || A story, a joke, a fairy tale, or a story book's PDF | [Picture books](#picture-books) | [stories.md](references/stories.md), [puppets.md](references/puppets.md), [sound.md](references/sound.md), [painting.md](references/painting.md) for a painted look |+| A book, an idea or a stretch of history to explain as a narrated film | [Documentaries](#documentaries) | [documentary.md](references/documentary.md), [sound.md](references/sound.md) for music || A course book (cites works, reviewed questions, an LMS) | Lessons plus options | [courses.md](references/courses.md), only when the book calls for them |-Both paths share [site.md](references/site.md) (the book folder, cover or series page, preview, video export), [engine.md](references/engine.md) (the player and drawing API), [team.md](references/team.md) (making chapters with subagents) and the models step of [intake.md](references/intake.md#5-models). Read only the reference the current step needs.+Every path shares [site.md](references/site.md) (the book folder, cover or series page, preview, video export), [engine.md](references/engine.md) (the player and drawing API), [team.md](references/team.md) (making chapters with subagents) and the models step of [intake.md](references/intake.md#5-models). Read only the reference the current step needs.## Project layout@@ -78,6 +79,10 @@ A course book may also want verified citation links, a reviewed question bank orStart with the story intake in [stories.md](references/stories.md#intake-for-a-story) whenever `books/<book>/style.json` does not exist yet; agree the models ([intake.md](references/intake.md#5-models)) and write `style.json`. Then follow [the order of work](references/stories.md#the-order-of-work): the script and storyboard shown to the user before anything is built, the book folder ([site.md](references/site.md#a-picture-book)), sound, sets, scenes, [review rounds](references/stories.md#review-rounds), and the user's viewing of the first cut. Each episode is a chapter (`chNN`); a series shares its cast, sets and series page.+## Documentaries++Start with the intake in [documentary.md](references/documentary.md#intake) whenever `books/<book>/style.json` does not exist yet. Then follow [the order of work](references/documentary.md#the-order-of-work): research, the script and storyboard shown to the user, the folder from `assets/templates/documentary/`, pictures found and treated, voice, music, the beats, [review rounds](references/documentary.md#review-rounds) and the user's viewing. *Madness and Civilization* on the shelf is the approved reference.+## ScriptsAll in `SKILL/scripts/`; each prints its usage with `--help` (run it with the `uv run --with …` its docstring names).@@ -87,6 +92,7 @@ All in `SKILL/scripts/`; each prints its usage with `--help` (run it with the `u| Every book | `serve.py` preview without caching · `engine.py` sync the engine into books · `tts.py` narration and word times · `lint.py` static checks · `shot.py` beat screenshots · `strip.py` storyboard sheets and motion strips · `still.py` stretches where nothing moves · `perf.py` Firefox frame times · `export.py` MP4 and `.srt` || Lessons | `outline.py` and `split_pages.py` page map and chapter text · `check_blank.py` empty openings · `overlap.py` arrows through text · `sprites.py` image processing steps || Picture books | `mouths.py` mouth shapes · `level.py` even loudness · `join.py` one clip per scene · `sfx.py` synthesized effects · `playlog.py` sounds and captions against the picture · `bake_sets.py` set layers · `bake_puppets.py` puppet bitmaps · `paint.py` / `paint_openai.py` image-model pictures · `painted.py` place them in the book |+| Documentaries | `commons.py` public-domain pictures and recordings with their licences · `prep.py` print and line treatments · `trace.py` drawings that draw themselves on · `video.py` a clip from a still · `frames.py` a clip as treated frames · `eleven.py` ElevenLabs narration with word times || Course options | `refs.py` verified citations · `items.py` question bank · `scorm.py` LMS package |`silence.py`, `ledger.py` and `browsers.py` are helpers the others import.diff --git a/.claude/skills/papermorph/assets/templates/documentary/chapter.html b/.claude/skills/papermorph/assets/templates/documentary/chapter.htmlnew file mode 100644index 0000000..ded6ac7--- /dev/null+++ b/.claude/skills/papermorph/assets/templates/documentary/chapter.html@@ -0,0 +1,49 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>FILM TITLE</title>+<link rel="stylesheet" href="../lib/engine.css">+<link rel="expect" href="#bar" blocking="render">+</head>+<body>+<!-- A documentary chapter: one beat per paragraph of the script. Copy lib/ (film.js, book.css with the ground colours,+ fonts.css and fonts/) into site/<book>/lib/ next to the engine, and this file to site/<book>/chNN/index.html. img/art.js (prep.py) lists the+ found pictures; add lib/lines.js (trace.py) and img/frames.js (frames.py) when the film uses traced drawings or clips. -->+<script src="../lib/engine.js"></script>+<script src="../lib/film.js"></script>+<script src="audio/en/timings.js"></script>+<script src="../img/art.js"></script>+<script>+'use strict';+// lead: false — every opening is timed by hand, so the engine never pulls a beat's first reveal earlier+const CHAPTER = { number: 1, title: 'FILM TITLE', minutes: 10, language: 'en', lead: false };++const OPEN_PRE = 5; // seconds of title and music before the first line++/* ---------- beats ----------+ [id, title, run, extra]: id names audio/en/<id>.mp3 and its TIMINGS entry; m('mark') is the time a word is heard.+ `pre` gives the picture (and music) seconds before the narration starts. */+const BEATS = [+ ['open', 'Title', (m, D) => {+ const p = panel(0);+ const ti = key(p, 'FILM TITLE', 800, 420, .5, { size: 96 });+ hide(ti, OPEN_PRE - .9, .6);+ const g = pic(p, 'first-picture', { x: 800, y: 470, h: 640, at: OPEN_PRE - .6 });+ push(g, OPEN_PRE, D); // a slow push-in while it is talked about+ say(p, ['The first line, typed as it is spoken.'], 800, 820, m('first'), m('first') + 2, { size: 48, anchor: 'middle' });+ }, { pre: OPEN_PRE }],+].map(([id, title, run, extra]) => ({ id, title, run, ...extra }));++/* ---------- music ----------+ One music(file, [beat ids], gain, fade) per part of the film; window.MUSIC_UP_IN_PRE lifts it in a music-only opening. */+window.MUSIC_UP_IN_PRE = ['open'];+// music('audio/bgm/part1.mp3', ['open'], .5, 3);++// the fonts must be in before words are measured+Promise.all(['600 40px Oswald', '500 40px Oswald', 'italic 400 40px "EB Garamond"', '400 40px "EB Garamond"']+ .map(f => document.fonts.load(f))).then(boot);+</script>+</body>+</html>diff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/book.css b/.claude/skills/papermorph/assets/templates/documentary/lib/book.cssnew file mode 100644index 0000000..25e4beb--- /dev/null+++ b/.claude/skills/papermorph/assets/templates/documentary/lib/book.css@@ -0,0 +1,11 @@+/* The film's ground and ink (here Madness and Civilization's burgundy and cream): --board is the ground, --chalk the ink.+ Imported by engine.css; engine.py never overwrites it. Keep film.js's colours in step. */+@import url("fonts.css");+:root {+ --page: #2a060a; --board: #5a0e16; --panel: #4a0b12; --edge: #7a2a30;+ --chalk: #f3ede0; --dim: #d9b9b0; --faint: #9a5a58;+ --task: #f0b45a; --quiz: #e8c8a0; --good: #c8e0b0; --bad: #ffb0a0;+ --vignette: rgba(20, 0, 4, .45);+ --rule: #6e2028; --track: #6a1a22; --track-ask: #6a1a22;+ --bar-edge: #6a1a22; --hover: #6e1e26; --veil: #22050a;+}diff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/film.js b/.claude/skills/papermorph/assets/templates/documentary/lib/film.jsnew file mode 100644index 0000000..5be03b5--- /dev/null+++ b/.claude/skills/papermorph/assets/templates/documentary/lib/film.js@@ -0,0 +1,186 @@+/* film.js — the documentary kit: found pictures, line drawings, words and maps on the engine's beat clock.+ This is the book's own copy: set its look here (fonts in lib/fonts.css, colours below) and add the film's recurring+ pieces at the end. Every helper is a pure function of the beat clock, so pause, seek, ?beat=N&t=S and export.py agree.+ Pictures are img/<name>.webp with their sizes in ART (img/art.js, from prep.py); traced drawings are LINES (lib/lines.js,+ from trace.py); clips are FRAMES (img/frames.js, from frames.py). The fonts must be loaded before boot(): words are+ measured on a canvas (chapter.html does this). */+'use strict';+/* ---------- the look ---------- */+const KEY = '"Oswald", "Arial Narrow", sans-serif', SER = '"EB Garamond", Georgia, serif'; // titles and key words; quotes and captions+const CREAM = '#f3ede0', HOT = '#f08a4b', SOFT = '#d9b9b0', INK = '#3a2a24'; // ink on the ground, the accent, captions, ink on paper++// a picture from img/: centred on (x, y), h or w in stage px; `at` makes it enter (from offset dx, dy) at that time+function pic(p, name, { x = 800, y = 450, h = 600, w, r = 0, s = 1, at, from = [0, 40], dur = .9, o = 1, back = false } = {}) {+ const sz = ART[name];+ const g = G(p, at === undefined ? { x, y, r, s, o } : { x: x + from[0], y: y + from[1], r, s, o: 0 });+ const k = w ? w / sz[0] : h / sz[1], W = sz[0] * k, H = sz[1] * k;+ if (back) mk('rect', { x: -W / 2 + 4, y: -H / 2 + 4, width: W - 8, height: H - 8, fill: COL.board }, g); // a solid line drawing (a door)+ mk('image', { href: `../img/${name}.webp`, x: -W / 2, y: -H / 2, width: W, height: H }, g);+ g._w = W; g._h = H; g._x = x; g._y = y;+ if (at !== undefined) tw(g, { x, y, o }, at, dur, out);+ return g;+}+const leave = (g, t0, dx = 0, dy = 0, dur = .7) => tw(g, { x: g._x + dx, y: g._y + dy, o: 0 }, t0, dur, io);+const push = (g, t0, t1, s1 = 1.06, dx = 0, dy = 0) => tw(g, { s: s1, x: g._x + dx, y: g._y + dy }, t0, t1 - t0, lin); // slow Ken Burns+// one picture turning into another in place (a figure changing era)+const dissolve = (a, b, t0, dur = 1.2) => { hide(a, t0, dur, lin); show(b, t0, dur, lin); };++// a line drawing traced into strokes (LINES[name] from trace.py): drawn on stroke by stroke over `draw` s, or shown whole+function traced(p, name, { x = 800, y = 450, h = 600, at = 0, draw: dd = 0, o = 1, flip = false } = {}) {+ const L = LINES[name], [x0, y0, x1, y1] = L.box, k = h / (y1 - y0);+ const g = G(p, { x, y, o: dd ? 1 : 0 });+ const inner = mk('g', { transform: `scale(${flip ? -k : k},${k}) translate(${-(x0 + x1) / 2},${-(y0 + y1) / 2})` }, g);+ const total = L.l.reduce((a, b) => a + b, 0);+ let acc = 0;+ L.p.forEach((d, i) => {+ const e = path(inner, d, { stroke: CREAM, 'stroke-width': 2.4 / k }, dd ? { d: 0 } : {});+ if (dd) { draw(e, at + dd * acc / total, Math.max(.04, dd * L.l[i] / total), lin); acc += L.l[i]; }+ });+ if (!dd) tw(g, { o }, at, .6);+ g._x = x; g._y = y; g._h = h;+ return g;+}+// words in a font measured on a canvas (fonts are loaded before boot)+const CTX = document.createElement('canvas').getContext('2d');+const wid = (str, size, font, style = '', weight = 400) => { CTX.font = `${style} ${weight} ${size}px ${font}`; return CTX.measureText(str).width; };++// big condensed word(s)+function key(p, str, x, y, t0, { size = 96, fill = CREAM, anchor = 'middle', from = 24, o = 1 } = {}) {+ const e = T(p, str.toUpperCase(), { x, y: y + from, size, fill, font: KEY, weight: 600, anchor, o: 0 });+ e.setAttribute('letter-spacing', '.02em');+ e._w = wid(str.toUpperCase(), size, KEY, '', 600) * 1.02;+ tw(e, { y, o }, t0, .55, out);+ return e;+}+// a line struck through a key word (the word's own width)+function strike(p, e, x, y, t0, size, anchor = 'middle') {+ const x0 = anchor === 'middle' ? x - e._w / 2 : anchor === 'end' ? x - e._w : x;+ return line(p, `M${x0 - 16} ${y - size * .32}H${x0 + e._w + 16}`, t0, .4, Math.max(5, size / 12), { stroke: HOT });+}+// serif lines typed word by word between t0 and t1+function say(p, lines, x, y, t0, t1, { size = 44, fill = CREAM, italic = true, anchor = 'start', lh = 1.3, weight = 400 } = {}) {+ const g = G(p, {}), style = italic ? 'italic' : '', words = [];+ const sp = wid(' ', size, SER, style, weight);+ lines.forEach((ln, i) => {+ const ws = ln.split(' '), W = wid(ln, size, SER, style, weight);+ let cx = anchor === 'middle' ? x - W / 2 : anchor === 'end' ? x - W : x;+ ws.forEach(w => {+ const e = T(g, w, { x: cx, y: y + i * size * lh, size, fill, font: SER, weight, o: 0 });+ if (italic) e.setAttribute('font-style', 'italic');+ words.push(e); cx += wid(w, size, SER, style, weight) + sp;+ });+ });+ const chars = words.map(e => e.textContent.length + 1), all = chars.reduce((a, b) => a + b, 0);+ let acc = 0;+ words.forEach((e, i) => { show(e, t1 === t0 ? t0 : t0 + (t1 - t0) * acc / all, .25, lin); acc += chars[i]; });+ return g;+}+// a small caption under a picture (a credit or a name tag)+function tag(p, str, x, y, t0, { size = 24, anchor = 'start', fill = SOFT } = {}) {+ const e = T(p, str, { x, y, size, fill, font: SER, anchor, o: 0 });+ e.setAttribute('font-style', 'italic');+ show(e, t0, .5);+ return e;+}+// the era at the top left, like a chapter opener: the year in italic, a hairline, the place or topic in spaced capitals+function dateChip(p, year, topic, t0 = .2) {+ const g = G(p, { x: 80, y: 112, o: 0 });+ T(g, year, { size: 72, font: SER, weight: 400, fill: HOT }).setAttribute('font-style', 'italic');+ const tw_ = wid(topic.toUpperCase(), 26, SER) * 1.3 + 8; // letter-spacing .28em widens the caps by about 30 %+ const rule = path(g, `M3 22H${Math.max(220, tw_)}`, { stroke: CREAM, 'stroke-width': 1.4, opacity: .7 }, { d: 0 });+ T(g, topic.toUpperCase(), { x: 3, y: 58, size: 26, font: SER, weight: 400, fill: CREAM }).setAttribute('letter-spacing', '.28em');+ tw(g, { o: 1 }, t0, .6); draw(rule, t0 + .2, .6);+ return g;+}+// cream line, drawn on+const line = (p, d, t0, dur = .8, w = 3, extra = {}) => { const e = path(p, d, { stroke: CREAM, 'stroke-width': w, ...extra }, { d: 0 }); draw(e, t0, dur); return e; };+// wavy water lines that flow forever (pure function of the beat clock); amp may be a function of t+function water(p, y0, D, { rows = 3, amp = 8, len = 1700, x0 = -50, gap = 26, o = .75 } = {}) {+ const g = G(p, { o: 0 }); tw(g, { o }, 0, .6);+ const ps = [...Array(rows)].map((_, i) => path(g, '', { stroke: CREAM, 'stroke-width': 2.2, opacity: 1 - i * .25 }));+ clockRun(t => { const a = typeof amp === 'function' ? amp(t) : amp; ps.forEach((e, i) => {+ let d = ''; for (let x = 0; x <= len; x += 20) d += `${x ? 'L' : 'M'}${x0 + x} ${(y0 + i * gap * (a / 8) ** .5 + a * Math.sin(x / 70 + t * 1.6 + i)).toFixed(1)}`;+ e.setAttribute('d', d);+ }); }, D, { tail: true });+ return g;+}+// something that bobs on the water (a boat); x may follow a function of t+const bob = (g, D, a = 6, xf) => clockRun(t => put(g, { y: g._y + a * Math.sin(t * 1.6), r: 1.5 * Math.sin(t * 1.1), ...(xf ? { x: xf(t) } : {}) }), D, { tail: true });+const span01 = (t, a, b) => Math.min(1, Math.max(0, (t - a) / (b - a)));+const smooth01 = q => q * q * (3 - 2 * q);+// a speech balloon, cream outline, its tail to (tx, ty)+function balloon(p, x, y, w, h, tx, ty, t0) {+ const bx = Math.min(Math.max(tx, x + 60), x + w - 100);+ const d = `M${x + 30} ${y}H${x + w - 30}Q${x + w} ${y} ${x + w} ${y + 30}V${y + h - 30}Q${x + w} ${y + h} ${x + w - 30} ${y + h}H${bx + 40}L${tx} ${ty}L${bx} ${y + h}H${x + 30}Q${x} ${y + h} ${x} ${y + h - 30}V${y + 30}Q${x} ${y} ${x + 30} ${y}Z`;+ return line(p, d, t0, .7, 3);+}+// a field of dots: positions from a fixed seed so every replay is the same+function rng(seed) { return () => (seed = (seed * 16807) % 2147483647) / 2147483647; }+function dots(p, n, box, r, seed, fill = CREAM) {+ const R = rng(seed), g = G(p, {});+ return { g, el: [...Array(n)].map(() => mk('circle', { cx: box[0] + R() * box[2], cy: box[1] + R() * box[3], r, fill }, g)).map(e => put(e, { o: 0 })) };+}+// close-ups inside a print as their words are spoken: shots [[mark, fx, fy, label, zoom]], fx/fy the point in the picture+// (0..1 of the picture inside its border); the view never leaves the picture; a band names each one; back to the whole after+function closeups(p, g, name, shots, m, tBack, home) {+ const [W, H] = ART[name], k = g._w / W, iw = (W - 112) * k, ih = (H - 112) * k; // a print's picture sits 56 px in+ const clamp = (v, lim) => Math.max(-lim, Math.min(lim, v));+ shots.forEach(([mark, fx, fy, label, Z = 3], i) => {+ const dx = clamp((fx - .5) * iw, iw / 2 - 800 / Z), dy = clamp((fy - .5) * ih, ih / 2 - 450 / Z), t0 = m(mark) - .15;+ tw(g, { s: Z, x: 800 - Z * dx, y: 450 - Z * dy, r: 0 }, t0, .35, out);+ const l = G(p, { x: 800, y: fy > .7 ? 130 : 820, o: 0 }), lw = wid(label.toUpperCase(), 72, KEY, '', 600) + 70; // clear of a low subject+ mk('rect', { x: -lw / 2, y: -68, width: lw, height: 92, fill: COL.board }, l);+ T(l, label.toUpperCase(), { y: 0, size: 72, font: KEY, weight: 600, fill: CREAM, anchor: 'middle' });+ show(l, t0, .12);+ hide(l, i < shots.length - 1 ? m(shots[i + 1][0]) - .15 : tBack, .15);+ });+ if (home) tw(g, { s: 1, ...home }, tBack, .8, soft); // no home: stay on the last close-up+}+// a generated clip as cream-line frames on one sprite sheet (frames.py), played on the beat clock from t0:+// the frame is a pure function of the time, so pausing, seeking and the export all show the same picture+function anim(p, name, { x = 800, y = 450, size = 600, at = 0, t0 = at, D, o = 1 } = {}) {+ const F = FRAMES[name], rows = Math.ceil(F.n / F.cols);+ const g = G(p, { x, y, o: 0 });+ const v = mk('svg', { x: -size / 2, y: -size / 2, width: size, height: size, viewBox: `0 0 ${F.fw} ${F.fh}` }, g);+ mk('image', { href: `../img/${name}-sheet.webp`, width: F.cols * F.fw, height: rows * F.fh }, v);+ let last = -1;+ clockRun(t => {+ const f = Math.max(0, Math.min(F.n - 1, Math.floor((t - t0) * F.fps)));+ if (f !== last) { last = f; v.setAttribute('viewBox', `${(f % F.cols) * F.fw} ${Math.floor(f / F.cols) * F.fh} ${F.fw} ${F.fh}`); }+ }, D, { tail: true });+ tw(g, { o }, at, .8);+ return g;+}+// an old document: cream paper, lines of ink, a label+function doc(p, label, x, y, r, t0, seed) {+ const R = rng(seed), g = G(p, { x: x - 700, y, r, o: 0 });+ mk('rect', { x: -150, y: -200, width: 300, height: 400, fill: CREAM, stroke: '#cdbfa6' }, g);+ for (let i = 0; i < 13; i++) {+ const yy = -130 + i * 24, ww = 160 + R() * 70;+ path(g, `M-118 ${yy}q${ww / 4} ${-3 + R() * 6} ${ww / 2} 0t${ww / 2} 0`, { stroke: INK, 'stroke-width': 2, opacity: .7 });+ }+ T(g, label.toUpperCase(), { y: -160, size: 22, font: KEY, weight: 600, fill: '#7a1a20', anchor: 'middle' }).setAttribute('letter-spacing', '.06em');+ tw(g, { x, o: 1 }, t0, .8, out);+ g._x = x; g._y = y;+ return g;+}+// a point moving along a polyline [[x, y], …] as q goes 0..1+function along(pts, q) {+ const seg = pts.slice(1).map((b, i) => Math.hypot(b[0] - pts[i][0], b[1] - pts[i][1])), L = seg.reduce((a, b) => a + b, 0);+ let d = q * L, i = 0;+ while (i < seg.length - 1 && d > seg[i]) d -= seg[i++];+ const f = seg[i] ? d / seg[i] : 0, a = pts[i], b = pts[i + 1];+ return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f];+}++// a picture with its credit or name under it, and a quote typed beside it (an epigraph): portrait left, the quote large+function epigraph(p, name, who, lines, tin, tq, tq1, tout) {+ const g = G(p, {});+ pic(g, name, { x: 330, y: 430, h: 440, r: -2, at: tin, from: [-500, 0] });+ tag(g, who, 330, 690, tin + .5, { anchor: 'middle', size: 30, fill: CREAM });+ say(g, lines, 620, 330, tq, tq1, { size: 62 });+ if (tout !== undefined) tw(g, { x: -200, o: 0 }, tout, .7, io);+ return g;+}++/* ---------- this film's own pieces ---------- */diff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts.css b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts.cssnew file mode 100644index 0000000..bc8f044--- /dev/null+++ b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts.css@@ -0,0 +1,81 @@+/* Oswald and EB Garamond (SIL Open Font License 1.1), latin subsets, from Google Fonts */+@font-face {+ font-family: 'EB Garamond';+ font-style: italic;+ font-weight: 400;+ font-display: block;+ src: url(../lib/fonts/EBGaramond-italic-400-latin-ext.woff2) format('woff2');+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;+}+@font-face {+ font-family: 'EB Garamond';+ font-style: italic;+ font-weight: 400;+ font-display: block;+ src: url(../lib/fonts/EBGaramond-italic-400-latin.woff2) format('woff2');+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}+@font-face {+ font-family: 'EB Garamond';+ font-style: normal;+ font-weight: 400;+ font-display: block;+ src: url(../lib/fonts/EBGaramond-normal-400-latin-ext.woff2) format('woff2');+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;+}+@font-face {+ font-family: 'EB Garamond';+ font-style: normal;+ font-weight: 400;+ font-display: block;+ src: url(../lib/fonts/EBGaramond-normal-400-latin.woff2) format('woff2');+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}+@font-face {+ font-family: 'EB Garamond';+ font-style: normal;+ font-weight: 500;+ font-display: block;+ src: url(../lib/fonts/EBGaramond-normal-500-latin-ext.woff2) format('woff2');+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;+}+@font-face {+ font-family: 'EB Garamond';+ font-style: normal;+ font-weight: 500;+ font-display: block;+ src: url(../lib/fonts/EBGaramond-normal-500-latin.woff2) format('woff2');+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}+@font-face {+ font-family: 'Oswald';+ font-style: normal;+ font-weight: 500;+ font-display: block;+ src: url(../lib/fonts/Oswald-normal-500-latin-ext.woff2) format('woff2');+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;+}+@font-face {+ font-family: 'Oswald';+ font-style: normal;+ font-weight: 500;+ font-display: block;+ src: url(../lib/fonts/Oswald-normal-500-latin.woff2) format('woff2');+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}+@font-face {+ font-family: 'Oswald';+ font-style: normal;+ font-weight: 600;+ font-display: block;+ src: url(../lib/fonts/Oswald-normal-600-latin-ext.woff2) format('woff2');+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;+}+@font-face {+ font-family: 'Oswald';+ font-style: normal;+ font-weight: 600;+ font-display: block;+ src: url(../lib/fonts/Oswald-normal-600-latin.woff2) format('woff2');+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;+}diff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-italic-400-latin-ext.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-italic-400-latin-ext.woff2new file mode 100644index 0000000..54a3a75Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-italic-400-latin-ext.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-italic-400-latin.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-italic-400-latin.woff2new file mode 100644index 0000000..dbb5b42Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-italic-400-latin.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-400-latin-ext.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-400-latin-ext.woff2new file mode 100644index 0000000..ac677d1Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-400-latin-ext.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-400-latin.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-400-latin.woff2new file mode 100644index 0000000..4971c6aBinary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-400-latin.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-500-latin-ext.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-500-latin-ext.woff2new file mode 100644index 0000000..0712a53Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-500-latin-ext.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-500-latin.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-500-latin.woff2new file mode 100644index 0000000..eebd0b1Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/EBGaramond-normal-500-latin.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/OFL-EBGaramond.txt b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/OFL-EBGaramond.txtnew file mode 100644index 0000000..c1ec5e1--- /dev/null+++ b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/OFL-EBGaramond.txt@@ -0,0 +1,93 @@+Copyright 2017 The EB Garamond Project Authors (https://github.com/octaviopardo/EBGaramond12)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/OFL-Oswald.txt b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/OFL-Oswald.txtnew file mode 100644index 0000000..4d4e319--- /dev/null+++ b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/OFL-Oswald.txt@@ -0,0 +1,93 @@+Copyright 2016 The Oswald Project Authors (https://github.com/googlefonts/OswaldFont)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-500-latin-ext.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-500-latin-ext.woff2new file mode 100644index 0000000..c05db68Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-500-latin-ext.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-500-latin.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-500-latin.woff2new file mode 100644index 0000000..371bb5eBinary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-500-latin.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-600-latin-ext.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-600-latin-ext.woff2new file mode 100644index 0000000..4e5bfd6Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-600-latin-ext.woff2 differdiff --git a/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-600-latin.woff2 b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-600-latin.woff2new file mode 100644index 0000000..600dec1Binary files /dev/null and b/.claude/skills/papermorph/assets/templates/documentary/lib/fonts/Oswald-normal-600-latin.woff2 differdiff --git a/.claude/skills/papermorph/references/documentary.md b/.claude/skills/papermorph/references/documentary.mdnew file mode 100644index 0000000..26e91e1--- /dev/null+++ b/.claude/skills/papermorph/references/documentary.md@@ -0,0 +1,66 @@+# Documentaries: from a book or an idea to a film++A documentary is a narrated film of five to fifteen minutes about a book, an idea or a stretch of history. Its pictures are mostly found: public-domain engravings, paintings and photographs, a few line drawings that draw themselves on, words set large, a map or two, all on one coloured ground and moved in step with a narrator. There are no questions; the reader watches. The published example is *Madness and Civilization* (after Foucault, ten minutes) on the shelf at https://papermorph.diamonddoge.org/. The user signed it off as the reference for this kind of film: when in doubt, open it and match its level.++It shares the engine, the player, captions, previews, `export.py` and the team with every other book. What is its own: the kit `assets/templates/documentary/` (`chapter.html`, `lib/film.js`, `lib/book.css`, `lib/fonts.css` and the fonts), the picture scripts (`commons.py`, `prep.py`, `trace.py`, `frames.py`, `video.py`), the voice script `eleven.py`, and the order of work below.++## Intake++The same spirit as [intake.md](intake.md): a short conversation, choices to click, the user's words kept. Settle, skipping what the request already settles:++1. **The subject and the angle.** What the film is about, and the one thing a viewer should leave with (Foucault: madness was not always locked up; each age decided what to do with it). Ask what must be in it: a scene, a quote, a person, an ending. What the user stresses is a theme to carry, not a thing to repeat: in the first cut the two epigraphs appeared four times and the user said it was overdone; they belong at the start and the end, with light echoes between.+2. **Length and audience.** Ten minutes holds one argument with five or six turns; a two-minute film holds one turn.+3. **The look.** One ground colour for the whole film (burgundy `#5a0e16` for Foucault, chosen from four tested with the actual pictures on them), two fonts (a condensed sans for key words, a serif for quotes and captions), and how found pictures are treated (below). Offer a ground test: three or four grounds with real pictures on them, side by side, before anything is built.+4. **The voice.** The narrator carries the film. ElevenLabs (`elevenlabs/eleven-v4` through OpenRouter) gave the voice the user accepted; Edge TTS was rejected for this film. Ask for the key, play a few short samples, and let the user pick. Characters can have their own voices (the Fool's giggle, a king's edict); v4 audio tags such as `[cackles]` are acted, not read.+5. **Music.** Classical music suits found pictures: one recording per part of the film, changing at the turns, never abruptly, at a level that never covers the narrator. Open with something short and rhythmic so the start is not slow.+6. **Budget.** Voices cost about $0.65 for ten minutes; a five-second clip from a still about $0.42. Pictures from Wikimedia Commons cost nothing.++Then agree the models ([intake.md](intake.md#5-models)) and write `style.json` with `tier: "documentary"`, the user's words, the look, the voice and the models.++## The order of work++1. **Research and the script.** Read the source, then write the narration (`content/<book>/chNN/narration.en.json`, one beat per paragraph, `[[mark]]` before each word a picture lands on) and a storyboard table (`books/<book>/storyboard.md`: beat, what is said, what we see, which picture). Show both to the user before anything is built. The hard part of a documentary is the argument and the storyboard, not the animation.+2. **The folder.** `site/<book>/lib/` gets the kit's `lib/` (`film.js`, `book.css` with the ground and ink colours, `fonts.css`, `fonts/`) and then the engine (`engine.py`); `chNN/index.html` starts from the kit's `chapter.html`.+3. **Pictures.** Find them, record them, treat them (below).+4. **Voice.** `eleven.py` (or `tts.py`) writes one clip per beat and `timings.js` with the marks. It takes the voice and model from the narration file's `voice` and `model`, keeps paid clips cached (a rerun costs nothing), and `--only beat,beat` redoes some beats without touching the others. Its word alignment (local Whisper) assumes words split by spaces, so a Chinese or Japanese film needs `tts.py` for now.+5. **Music.** Find recordings (`commons.py --audio`), bring them to one loudness (`level.py`), and give each part of the film its track with `music(file, beats, gain, fade)` ([engine.md](engine.md#player)).+6. **The beats**, built from the kit's helpers and timed to the marks.+7. **Review rounds** (below), then the user's viewing, then `export.py` for a video and registering the film on the shelf ([site.md](site.md)).++## Pictures++- **Find, then record.** `commons.py` searches Wikimedia Commons and downloads only public-domain and CC0 files, logging each in `SOURCES.tsv` (title, author, licence, URL). One subagent with it found all twenty storyboard pictures for Foucault in thirteen minutes. Other good sources: the Library of Congress, Old Book Illustrations, the Internet Archive; record those by hand the same way.+- **Two treatments**, made by `prep.py`, which also writes `img/art.js` with each picture's size:+ - *print*: the picture keeps its paper, with a border and a soft shadow, like a photograph laid on the ground. Paintings, photographs, title pages.+ - *line*: an engraving's dark lines turn into the ground's ink colour and the paper drops out, so the figure stands on the ground itself. Woodcuts and engravings with clean lines.+- **Line drawings that draw themselves.** `trace.py` turns a line drawing into ordered strokes; `traced()` draws it on over a few seconds. It is striking once or twice; on every picture it becomes a tic.+- **A still that moves.** For one or two moments, `video.py` makes a five-second clip from a still (Kling kept the engraving style), and `frames.py` gives every frame the same treatment on one sprite sheet, played by `anim()` on the beat clock so pause, seek and the export agree. The user liked this most when it was rare.+- **Maps.** A coastline from Natural Earth (public domain) as one SVG path in the film's box, a route drawn on with `along()`. A map earns its place when the narration talks about where (the Rhine, the leper houses across Europe).++## Building the beats++`film.js` holds the helpers, all pure functions of the beat clock:++- `pic()` places a picture with an entrance; `leave()`, `push()` (a slow Ken Burns move), `dissolve()` (one picture turning into another in place);+- `key()` big words in the condensed font, `strike()` a line through one, `say()` a quote typed word by word as it is spoken, `tag()` a small caption, `dateChip()` the year and place at the top left;+- `closeups()` pushes into a print onto each thing as it is named, with a label, and back out;+- `epigraph()`, `doc()` (an old document), `balloon()`, `dots()`, `water()` and `bob()`, `anim()`, `along()`.++Add the film's own recurring pieces at the end of the book's `film.js` (Foucault's guide peeking up from the bottom edge, the Europe map). Set the chapter's `lead: false`: every opening is timed by hand.++What made the Foucault film work:++- **One idea or element every two to four seconds**, in step with the voice, on a sparse screen: one to three things on the ground.+- **Close-ups on what is named.** When the narration names "the greedy" and "the vain" aboard the ship of fools, the camera goes to each in the woodcut, with the words as a label.+- **A host, used sparingly.** The author as a cut-out guide works at the key points; fifteen appearances was too many, and the user asked for fewer.+- **Characters get voices** for a line or a laugh, short: the jester's laugh at the end of a section, not over it.+- **The ending gathers the film.** Foucault ends with every era's Fool appearing in turn, and the opening epigraph returns.+- **Words on screen are few**: a key word, a quote being read, a year. Everything else is said.++## Review rounds++After the first cut, an independent director pass: a fresh agent on a strong model, given contact sheets of every beat (`strip.py`) and the reference film, with no knowledge of how the beats were built. On Foucault it found ten must-fix defects, about half of them places where the picture contradicted the narration (the wrong figure on screen while another was named). Fix, then show each fix on a contact sheet at once, which is how the user liked to review. Then the user watches the whole film.++## Later++Vertical shorts (a 9:16 stage, faster cuts, a single music track cut to the timeline) are being worked out on their own branch and are not yet part of this path.diff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.mdindex 96609f1..13441e7 100644--- a/.claude/skills/papermorph/references/engine.md+++ b/.claude/skills/papermorph/references/engine.md@@ -59,7 +59,7 @@ A book whose formulas need more than `M()` parts (indices, sums, matrices, accen- `m('name', offset)` is the start time of the word after `[[name]]`; `D` is the clip's length. Use marks for actions tied to speech; scene entrances and transitions can use fixed offsets.- Tweens: `tw(e, to, t0, dur, ease)`, `prog(q => …, t0, dur, ease)` for custom motion (arcs, counters, live redraws), `show(e, t0, dur, ease)`, `hide`, `draw` (same arguments), `pop`, `pulse`, `stream`. Eases: `io`, `out`, `back`, `lin`, `soft`. Continuous motion and cameras: see below.- A lesson beat ends after its narration and its last tween, and holds that picture `HOLD` (0.6 s) before the next starts; an `ask` beat waits for `done()`.-- **Opening lead-in**: if a beat calls `panel()` (before 0.5 s) and no element is revealed (faded, scaled or drawn in from nothing) within 0.8 s, `runBeat` moves the opening group (every tween starting within 1.2 s of the first reveal) to start at 0.4 s, so the narration never runs over an empty board. It looks only at reveals: a beat that lays out part of its picture visible at once (axes, empty boxes, a set) and reveals the rest on later words still has that first group pulled to 0.4 s. When those words matter, give the beat `{ lead: false }` in its fourth slot; a camera that shows a picture from the first frame is the same case. To see where a beat's reveals land, put marks on a contact sheet: `strip.py chNN OUT idea:0.4,label,label+0.3,end --sheet storyboard --url http://localhost:8765/<book>/` (a mark plus an offset is the moment the action is timed to).+- **Opening lead-in**: if a beat calls `panel()` (before 0.5 s) and no element is revealed (faded, scaled or drawn in from nothing) within 0.8 s, `runBeat` moves the opening group (every tween starting within 1.2 s of the first reveal) to start at 0.4 s, so the narration never runs over an empty board. It looks only at reveals: a beat that lays out part of its picture visible at once (axes, empty boxes, a set) and reveals the rest on later words still has that first group pulled to 0.4 s. When those words matter, give the beat `{ lead: false }` in its fourth slot, or the whole chapter `CHAPTER.lead = false` *(v2.2)* when every opening is timed by hand (a documentary); a camera that shows a picture from the first frame is the same case. To see where a beat's reveals land, put marks on a contact sheet: `strip.py chNN OUT idea:0.4,label,label+0.3,end --sheet storyboard --url http://localhost:8765/<book>/` (a mark plus an offset is the moment the action is timed to).- **`pre`** in the fourth slot (`{ pre: 1.2 }`) runs the picture that many seconds before the narration starts: an action, then the line. Picture books use it on every scene.- **The end of a film**: a chapter whose last beat asks nothing (a picture book) is finished when that beat ends: it is marked done and, with `CHAPTER.next`, offers the next chapter (Enter).- **Seeking replays**: jumping to beat N rebuilds the scene and runs earlier beats instantly. Make `run` deterministic: create objects and schedule tweens through the timeline, with inputs from chapter data and replayed `S` state. Create interactions inside `ask`; use `fx`/`fxp` for answer effects.diff --git a/.claude/skills/papermorph/scripts/commons.py b/.claude/skills/papermorph/scripts/commons.pynew file mode 100644index 0000000..9830948--- /dev/null+++ b/.claude/skills/papermorph/scripts/commons.py@@ -0,0 +1,94 @@+#!/usr/bin/env python3+"""Public-domain pictures and music recordings from Wikimedia Commons: search, look, download with a licence check.++ python3 commons.py search "ship of fools engraving" [-n 12] # OK/XX, size, [licence], title+ python3 commons.py search "La Folia" --audio [-n 15] # OK/XX, length, [licence], title | artist+ python3 commons.py preview "File:A.jpg" "File:B.jpg" --out books/<book>/art/preview # 700 px thumbs, 0.jpg, 1.jpg ...+ python3 commons.py get "File:Title.jpg" bosch.jpg --out books/<book>/art/found [--page 3]+ python3 commons.py get "File:Title.ogg" m1-folia --audio --out books/<book>/music # the file's extension is added++Only public domain and CC0 are downloaded: the licence (Commons' LicenseShortName) must start with "public domain",+"cc0" or "pd" (PDM-owner counts), else the script refuses. Each download appends a row to the sources log+(--sources, default OUT/SOURCES.tsv): file, Commons title (and page), licence. Pictures wider than 1800 px, TIFF,+DjVu and PDF come as an 1800 px rendering (--page picks a page of a scan); recordings come as the original file.+Previews skip the licence check: they are for looking, not for the film.++Recordings: a composition can be centuries old while a recording of it is still protected. Commons marks some+1950s-60s recordings (Karajan, Walter) public domain under EU rules; in the US they are protected until 2067, so+avoid them. Safe: recordings their performers released (PDM-owner, CC0), Musopen, and US government band recordings+(US Marine Band, Air Force bands).+"""+import argparse, json, os, re, sys, urllib.parse, urllib.request++API = "https://commons.wikimedia.org/w/api.php"+UA = {"User-Agent": "papermorph/1.0 (https://github.com/DozenTwelve/Papermorph)"} # Commons asks for a contact+++def api(**p):+ p.update(format="json", action="query")+ return json.load(urllib.request.urlopen(urllib.request.Request(API + "?" + urllib.parse.urlencode(p), headers=UA), timeout=60))+++def fetch(url, path, timeout=120):+ with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=timeout) as r, open(path, "wb") as f:+ f.write(r.read())+++ok = lambda lic: bool(re.match(r"(public domain|cc0|pd)", lic.strip(), re.I))+licence = lambda ii: ii.get("extmetadata", {}).get("LicenseShortName", {}).get("value", "?")+strip = lambda s: re.sub(r"<[^>]+>", "", s or "")[:70]+IMG = dict(prop="imageinfo", iiprop="url|size|extmetadata|mime", iiurlwidth=1800)+AUD = dict(prop="imageinfo", iiprop="url|size|extmetadata|mime|mediatype")+++def search(q, n, audio):+ d = api(generator="search", gsrsearch=q + (" filetype:audio" if audio else ""), gsrnamespace=6, gsrlimit=n or (15 if audio else 12), **(AUD if audio else IMG))+ for p in sorted(d.get("query", {}).get("pages", {}).values(), key=lambda p: p.get("index", 0)):+ ii = p["imageinfo"][0]; lic = licence(ii); tag = "OK" if ok(lic) else "XX"+ if audio:+ print(f"{tag} {ii.get('duration', 0):6.0f}s [{lic}] {p['title']} | {strip(ii.get('extmetadata', {}).get('Artist', {}).get('value'))}")+ else:+ print(f"{tag} {ii['width']}x{ii['height']} [{lic}] {p['title']}")+ if audio:+ print("(a PD composition is not a PD recording: check the performer and year, see --help)", file=sys.stderr)+++def get(title, name, out, sources, page, audio):+ params = AUD if audio else dict(IMG, iiurlparam=f"page{page}-1800px") if page else IMG+ p = next(iter(api(titles=title, **params)["query"]["pages"].values()))+ if "imageinfo" not in p:+ sys.exit(f"no such file: {title}")+ ii = p["imageinfo"][0]; lic = licence(ii)+ if not ok(lic):+ sys.exit(f"REJECT licence {lic}")+ if audio:+ url = ii["url"]; name += os.path.splitext(urllib.parse.urlparse(url).path)[1]+ else:+ url = ii.get("thumburl") if ii["width"] > 1800 else ii["url"]+ if page or ii["mime"] in ("image/tiff", "image/vnd.djvu", "application/pdf"):+ url = ii["thumburl"]+ os.makedirs(out, exist_ok=True)+ path = os.path.join(out, name)+ fetch(url, path, 300 if audio else 120)+ with open(sources or os.path.join(out, "SOURCES.tsv"), "a", encoding="utf-8") as f:+ f.write(f"{name}\t{p['title']}{f' (page {page})' if page else ''}\t{lic}\n")+ print("saved", path, *([] if audio else [ii["width"], ii["height"]]), lic, url)+++def preview(titles, out):+ os.makedirs(out, exist_ok=True)+ for i, t in enumerate(titles):+ ii = next(iter(api(titles=t, prop="imageinfo", iiprop="url", iiurlwidth=700)["query"]["pages"].values()))["imageinfo"][0]+ fn = os.path.join(out, f"{i}.jpg"); fetch(ii["thumburl"], fn); print(fn, t)+++ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+sub = ap.add_subparsers(dest="cmd", required=True)+s = sub.add_parser("search"); s.add_argument("query"); s.add_argument("-n", type=int, help="results (12, or 15 with --audio)"); s.add_argument("--audio", action="store_true")+g = sub.add_parser("get"); g.add_argument("title"); g.add_argument("name"); g.add_argument("--out", required=True)+g.add_argument("--sources", help="sources log (default OUT/SOURCES.tsv)"); g.add_argument("--page"); g.add_argument("--audio", action="store_true")+v = sub.add_parser("preview"); v.add_argument("titles", nargs="+"); v.add_argument("--out", required=True)+a = ap.parse_args()+if a.cmd == "search": search(a.query, a.n, a.audio)+elif a.cmd == "get": get(a.title, a.name, a.out, a.sources, a.page, a.audio)+else: preview(a.titles, a.out)diff --git a/.claude/skills/papermorph/scripts/eleven.py b/.claude/skills/papermorph/scripts/eleven.pynew file mode 100644index 0000000..4ebb52b--- /dev/null+++ b/.claude/skills/papermorph/scripts/eleven.py@@ -0,0 +1,107 @@+#!/usr/bin/env python3+"""Narration with OpenRouter's ElevenLabs voices; marks and caption cues from local word alignment (faster-whisper).++ uv run --with faster-whisper --with numpy python eleven.py content/<book>/ch01/narration.en.json site/<book>/ch01/audio/en+ ... [--model elevenlabs/eleven-v4] [--voice george] [--only beat,beat]++Same input and output as tts.py: the narration file's beats with [[mark]] tags in, <beat>.mp3 and timings.js+({dur, marks, cues} per beat) out, so the page cannot tell the two apart. The voice and model come from the+narration file ("voice", "model"), else from the flags (default george, eleven-v4); OpenRouter offers 21 preset+voices. A beat may be {"speaker": name, "text": ...} with the speaker's "voice" under the file's "voices", as in tts.py.++ElevenLabs returns no word timings, so each clip is transcribed locally (faster-whisper base.en, or base for another+language, from the file name narration.<lang>.json; the first run downloads the model) and the script's words are+matched to the heard words in order; each [[mark]] is the start of the word after it, and there is one caption cue per+sentence and per clause after a colon. Audio is decoded with ffmpeg, not PyAV (faster-whisper's PyAV version clashes). Needs ffmpeg.++v4 audio tags such as [cackles] or [whispers] act: they are performed, not read aloud, and left out of captions.+Price: about $0.00008 per character (about $0.65 for a ten-minute film); the run prints its estimate.++Each beat's clip is cached beside the narration as .eleven/<beat>.<hash>.mp3 (hash of model, voice and text), so+moving marks or rerunning never pays twice. --only regenerates the listed beats and leaves the others' mp3 (perhaps+levelled since) and timings as they are. The key is read from ~/.config/openrouter/key or $OPENROUTER_API_KEY.+"""+import argparse, hashlib, json, pathlib, re, subprocess, sys, urllib.error, urllib.request+import numpy as np+from paint import key+from tts import split_marks, mark_times, duration, write_atomic++TAG = re.compile(r"(?<!\[)\[[^\[\]]+\](?!\])") # a v4 audio tag, not a [[mark]]+PRICE = 0.00008 # USD per character++ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ap.add_argument("narration"); ap.add_argument("out")+ap.add_argument("--model"); ap.add_argument("--voice")+ap.add_argument("--only", default="", help="comma-separated beats to regenerate")+a = ap.parse_args()+spec = json.loads(pathlib.Path(a.narration).read_text(encoding="utf-8-sig"))+model = a.model or spec.get("model", "elevenlabs/eleven-v4")+lang = pathlib.Path(a.narration).stem.split(".")[-1]+out = pathlib.Path(a.out); out.mkdir(parents=True, exist_ok=True)+cache = pathlib.Path(a.narration).parent / ".eleven"; cache.mkdir(exist_ok=True)+only = set(filter(None, a.only.split(",")))+++def speak(text, voice, dst):+ body = json.dumps({"model": model, "input": text, "voice": voice, "response_format": "mp3"}).encode()+ req = urllib.request.Request("https://openrouter.ai/api/v1/audio/speech", body,+ {"Authorization": f"Bearer {key()}", "Content-Type": "application/json"})+ try:+ data = urllib.request.urlopen(req, timeout=300).read()+ except urllib.error.HTTPError as e:+ sys.exit(f"{e.code} {e.read().decode(errors='replace')[:500]}")+ if not data.startswith(b"ID3") and not (data[:1] == b"\xff" and len(data) > 1 and data[1] & 0xE0 == 0xE0):+ sys.exit(f"not audio: {data[:300]!r}")+ dst.write_bytes(data)+++norm = lambda w: re.sub(r"\W", "", w.lower())+asr = None+tf = out / "timings.js"+old = {}+if tf.exists():+ t = tf.read_text(encoding="utf-8"); old = json.loads(t[t.index("{"):t.rindex("}") + 1])+timings, spent = {}, 0+for beat, raw in spec["beats"].items():+ voice = spec["voices"][raw["speaker"]]["voice"] if isinstance(raw, dict) else a.voice or spec.get("voice", "george")+ raw = raw["text"] if isinstance(raw, dict) else raw+ clean, marks = split_marks(raw) # clean keeps audio tags: they go to the voice+ if only and beat not in only and beat in old:+ timings[beat] = old[beat]; continue # --only leaves the other beats alone+ cached = cache / f"{beat}.{hashlib.sha1(f'{model}|{voice}|{clean}'.encode()).hexdigest()[:12]}.mp3"+ if not cached.exists():+ if only and beat not in only:+ continue+ speak(clean, voice, cached); spent += len(clean); print(beat, "synthesized")+ mp3 = out / f"{beat}.mp3"; mp3.write_bytes(cached.read_bytes())+ if asr is None:+ from faster_whisper import WhisperModel+ asr = WhisperModel("base.en" if lang == "en" else "base", device="cpu", compute_type="int8")+ pcm = subprocess.run(["ffmpeg", "-v", "error", "-i", str(mp3), "-f", "f32le", "-ac", "1", "-ar", "16000", "-"],+ capture_output=True, check=True).stdout+ segs, _ = asr.transcribe(np.frombuffer(pcm, np.float32), word_timestamps=True, language=lang)+ heard = [(norm(w.word), w.start) for s in segs for w in s.words if norm(w.word)]+ # the script's words (audio tags blanked out, positions kept), matched to heard words in order with a small look-ahead+ spoken = TAG.sub(lambda m: " " * len(m.group()), clean)+ toks = [w for w in re.findall(r"\S+", spoken) if norm(w)]+ times, j = [], 0+ for w in map(norm, toks):+ k = next((k for k in range(j, min(j + 6, len(heard))) if heard[k][0] == w or heard[k][0].startswith(w[:4])), None)+ times.append(None if k is None else heard[k][1]); j = j if k is None else k + 1+ dur = duration(mp3)+ for i, v in enumerate(times): # words Whisper merged or split: halfway between their known neighbours+ if v is None:+ prev = next((times[q] for q in range(i - 1, -1, -1) if times[q] is not None), 0.0)+ nxt = next((times[q] for q in range(i + 1, len(times)) if times[q] is not None), dur)+ times[i] = round(prev + (nxt - prev) * .5, 3)+ words = list(zip(times, toks))+ # caption cues: one per sentence or clause after a colon (long documentary sentences), at its first word+ cues, i = [], 0+ for sent in re.split(r"(?<=[.?!:])\s+", re.sub(r"\s+", " ", TAG.sub("", clean)).strip()):+ n = len([w for w in sent.split() if norm(w)])+ if n: cues.append([round(times[i], 3) if i < len(times) else 0, sent]); i += n+ if cues: cues[0][0] = min(cues[0][0], .1)+ timings[beat] = {"dur": dur, "marks": mark_times(clean, marks, words), "cues": cues}+ print(f"{beat}: {dur} s, {len(marks)} marks")+write_atomic(tf, "window.TIMINGS = " + json.dumps(timings, indent=1, ensure_ascii=False) + ";\n")+print(f"{len(timings)} beats in {tf}; synthesized {spent} characters, about ${spent * PRICE:.2f}")diff --git a/.claude/skills/papermorph/scripts/frames.py b/.claude/skills/papermorph/scripts/frames.pynew file mode 100644index 0000000..1625683--- /dev/null+++ b/.claude/skills/papermorph/scripts/frames.py@@ -0,0 +1,36 @@+#!/usr/bin/env python3+"""A generated clip (video.py) -> ink-line frames on one sprite sheet, the same treatment as prep.py's line mode.++ uv run --with pillow --with numpy python frames.py books/<book>/art/video/chained.mp4 chained --out site/<book>/img+ ... [--fps 12] [--side 560] [--cols 10] [--ink 243,237,224]++Every frame is scaled to side x side, its paper made transparent and its lines drawn in --ink, then laid out in rows+of --cols. Writes OUT/<name>-sheet.webp (quality 80) and adds <name>: {fw, fh, cols, n, fps} to OUT/frames.js+(window.FRAMES), which the documentary kit's anim() plays on the beat clock. Needs ffmpeg. Keep clips short: a 5 s+clip at 12 fps and 560 px is about 4 MB.+"""+import argparse, json, pathlib, subprocess+import numpy as np+from PIL import Image+from prep import CREAM, ink, rgb++ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ap.add_argument("src"); ap.add_argument("name")+ap.add_argument("--out", required=True, help="the book's img folder, e.g. site/<book>/img")+ap.add_argument("--fps", type=int, default=12); ap.add_argument("--side", type=int, default=560); ap.add_argument("--cols", type=int, default=10)+ap.add_argument("--ink", type=rgb, default=CREAM, help="line colour r,g,b")+a = ap.parse_args()+raw = subprocess.run(["ffmpeg", "-v", "error", "-i", a.src, "-vf", f"fps={a.fps},scale={a.side}:{a.side}", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],+ capture_output=True, check=True).stdout+fr = np.frombuffer(raw, np.uint8).reshape(-1, a.side, a.side, 3)+n, cols = len(fr), a.cols; rows = -(-n // cols)+sheet = Image.new("RGBA", (cols * a.side, rows * a.side), tuple(a.ink) + (0,))+for i, f in enumerate(fr):+ sheet.paste(ink(f, a.ink), ((i % cols) * a.side, (i // cols) * a.side))+out = pathlib.Path(a.out); out.mkdir(parents=True, exist_ok=True)+dst = out / f"{a.name}-sheet.webp"; sheet.save(dst, quality=80, method=5)+jf = out / "frames.js"+data = json.loads(jf.read_text().split("=", 1)[1].rstrip().rstrip(";")) if jf.exists() else {}+data[a.name] = {"fw": a.side, "fh": a.side, "cols": cols, "n": n, "fps": a.fps}+jf.write_text("window.FRAMES = " + json.dumps(data) + ";\n")+print(n, "frames ->", dst, round(dst.stat().st_size / 1e6, 2), "MB")diff --git a/.claude/skills/papermorph/scripts/prep.py b/.claude/skills/papermorph/scripts/prep.pynew file mode 100644index 0000000..df04cfc--- /dev/null+++ b/.claude/skills/papermorph/scripts/prep.py@@ -0,0 +1,98 @@+#!/usr/bin/env python3+"""Found or generated pictures -> a documentary's two treatments, plus img/art.js (sizes for the page).++ uv run --with pillow --with numpy python prep.py books/<book>/art/prep.json --src books/<book>/art/found --out site/<book>/img+ ... [--ink 243,237,224] [--paper 243,237,224]++line: dark lines on light paper -> ink-coloured lines on transparent (the paper drops out), cropped to the ink.+ The brightest channel decides, so coloured library stamps drop out with the paper and light plate marks and+ stains stay paper. An inset (0.09 = 9 % a side) shaves a printed plate mark off the edges of the ink box.+print: any picture -> a paper-coloured border and a soft baked shadow, slightly larger than the picture; a near-black+ scanner mat at the edges is trimmed first (never more than 6 % a side).++The list is JSON: [[name, file, mode, max side], ...], a line entry optionally followed by [inset, [r, g, b]] (its own+ink colour, e.g. dark lines for a light map). Files are relative to --src (absolute paths pass through). Writes+OUT/<name>.webp (quality 88) and updates OUT/art.js, window.ART = {name: [w, h]}; entries of other names are kept,+so several lists (one per source folder) can write into one art.js. --ink and --paper default to the cream of the+documentary kit's CREAM.+"""+import argparse, json, pathlib+import numpy as np+from PIL import Image, ImageFilter++CREAM = (243, 237, 224)+++def ink(rgb, colour=CREAM):+ """RGB picture or array -> RGBA: dark lines in `colour`, paper transparent (shared with frames.py)."""+ a = np.asarray(rgb, float).max(axis=2) # brightest channel: coloured stamps drop out with the paper+ # paper -> 0, ink -> 255, with a soft knee so hatching keeps its weight; light plate marks and stains stay paper+ alpha = np.clip((190 - a) / (190 - 60), 0, 1) ** .8 * 255+ im = Image.new("RGBA", (a.shape[1], a.shape[0]), tuple(colour) + (0,))+ im.putalpha(Image.fromarray(alpha.astype("uint8")))+ return im+++def line(src, side, inset=0, colour=CREAM):+ rgba = ink(Image.open(src).convert("RGB"), colour)+ box = rgba.getchannel("A").point(lambda v: 255 if v > 40 else 0).getbbox()+ if inset: # shave a printed plate mark off the edges of the ink box+ dx, dy = int((box[2] - box[0]) * inset), int((box[3] - box[1]) * inset)+ box = (box[0] + dx, box[1] + dy, box[2] - dx, box[3] - dy)+ rgba = rgba.crop(box)+ rgba.thumbnail((side, side), Image.LANCZOS)+ return rgba+++def print_(src, side, paper=CREAM, border=16, pad=40):+ im = Image.open(src).convert("RGB")+ g = np.asarray(im.convert("L"), float) # trim a near-black scanner mat at the edges (never more than 6 % a side)+ def edge(means):+ n, lim = len(means), int(len(means) * .06)+ a = next((i for i in range(lim) if means[i] > 30), 0); b = next((i for i in range(lim) if means[n - 1 - i] > 30), 0)+ return a, n - b+ (y0, y1), (x0, x1) = edge(g.mean(1)), edge(g.mean(0))+ im = im.crop((x0, y0, x1, y1))+ im.thumbnail((side, side), Image.LANCZOS)+ w, h = im.size[0] + 2 * border, im.size[1] + 2 * border+ W, H = w + 2 * pad, h + 2 * pad+ sh = Image.new("L", (W, H), 0); sh.paste(150, (pad + 8, pad + 14, pad + 8 + w, pad + 14 + h))+ sh = sh.filter(ImageFilter.GaussianBlur(14))+ out = Image.new("RGBA", (W, H), (20, 4, 6, 0)); out.putalpha(sh)+ card = Image.new("RGBA", (w, h), tuple(paper) + (255,)); card.paste(im, (border, border))+ out.alpha_composite(card, (pad, pad))+ return out+++def rgb(s):+ return tuple(int(v) for v in s.split(","))+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("list", help="JSON list of [name, file, mode, side, (inset, [r,g,b])]")+ ap.add_argument("--src", default=".", help="folder the list's files are in")+ ap.add_argument("--out", required=True, help="the book's img folder, e.g. site/<book>/img")+ ap.add_argument("--ink", type=rgb, default=CREAM, help="line colour r,g,b")+ ap.add_argument("--paper", type=rgb, default=CREAM, help="print border colour r,g,b")+ a = ap.parse_args()+ src, out = pathlib.Path(a.src), pathlib.Path(a.out)+ out.mkdir(parents=True, exist_ok=True)+ jf = out / "art.js"+ sizes = json.loads(jf.read_text().split("=", 1)[1].strip().rstrip(";")) if jf.exists() else {}+ for name, f, mode, side, *rest in json.loads(pathlib.Path(a.list).read_text()):+ if mode == "line":+ im = line(src / f, side, rest[0] if rest else 0, rest[1] if len(rest) > 1 else a.ink)+ elif mode == "print":+ im = print_(src / f, side, a.paper)+ else:+ raise SystemExit(f"{name}: mode {mode!r} is not line or print")+ im.save(out / f"{name}.webp", quality=88, method=5)+ sizes[name] = [im.width, im.height]+ print(name, mode, im.width, im.height)+ jf.write_text("window.ART = " + json.dumps(sizes, separators=(",", ":")) + ";\n")+ print(len(sizes), "pictures in", jf)+++if __name__ == "__main__":+ main()diff --git a/.claude/skills/papermorph/scripts/trace.py b/.claude/skills/papermorph/scripts/trace.pynew file mode 100644index 0000000..be49db2--- /dev/null+++ b/.claude/skills/papermorph/scripts/trace.py@@ -0,0 +1,87 @@+#!/usr/bin/env python3+"""Line drawing (dark lines on light paper) -> centreline strokes, ordered like a hand draws, for a draw-on animation.++ uv run --with scikit-image --with pillow python trace.py IN.png OUT.svg [--width 900] [--min 12]+ ... --lines site/<book>/lib/lines.js [--name NAME] # also add or replace LINES[NAME] (default: OUT's stem)++The drawing is scaled to --width, thresholded, skeletonised and walked into strokes (endpoints first, stopping at+junctions, loops last); strokes shorter than --min px are dropped. Draw order runs top to bottom, each stroke chaining+to the nearest unfinished one. OUT.svg holds one <path data-len> per stroke, to look at. --lines writes the entry+the documentary kit's traced() reads: LINES[name] = {box: [x0, y0, x1, y1] of the strokes, p: [path d], l: [lengths]}.+"""+import argparse, json, pathlib+import numpy as np+from PIL import Image+from skimage.morphology import skeletonize+from skimage.measure import approximate_polygon++ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ap.add_argument("src"); ap.add_argument("out")+ap.add_argument("--width", type=int, default=900)+ap.add_argument("--min", type=float, default=12, help="drop strokes shorter than this (px)")+ap.add_argument("--lines", help="lines.js to add or replace this drawing's entry in")+ap.add_argument("--name", help="its key in LINES (default: OUT's file name without .svg)")+a = ap.parse_args()++im = Image.open(a.src).convert("L")+im = im.resize((a.width, round(im.height * a.width / im.width)), Image.LANCZOS)+ink = np.asarray(im) < 140+sk = skeletonize(ink)+H, W = sk.shape+pts = set(zip(*np.nonzero(sk)))+N8 = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]+nb = lambda p: [(p[0] + dy, p[1] + dx) for dy, dx in N8 if (p[0] + dy, p[1] + dx) in pts]++# walk the skeleton: start at endpoints, stop at junctions; every edge used once; loops last+used, strokes = set(), []+def walk(p):+ path = [p]+ while True:+ nxt = [q for q in nb(p) if frozenset((p, q)) not in used]+ if not nxt:+ return path+ q = nxt[0]; used.add(frozenset((p, q))); path.append(q); p = q+ if len(nb(p)) > 2:+ return path+ends = [p for p in pts if len(nb(p)) == 1] + [p for p in pts if len(nb(p)) > 2] + list(pts)+for p in ends:+ while any(frozenset((p, q)) not in used for q in nb(p)):+ s = walk(p)+ if len(s) > 1:+ strokes.append(s)++def length(s):+ return float(np.sum(np.hypot(*np.diff(np.array(s, float), axis=0).T)))+strokes = [approximate_polygon(np.array(s, float), 0.8) for s in strokes if length(s) >= a.min]+if not strokes:+ raise SystemExit("no strokes: is it dark lines on light paper?")+# draw order: like a hand, top to bottom, chaining to the nearest unfinished stroke+order, left = [], strokes[:]+cur = min(left, key=lambda s: s[:, 0].min())+while left:+ left = [s for s in left if s is not cur]; order.append(cur)+ if not left:+ break+ end = cur[-1]+ best = min(left, key=lambda s: min(np.hypot(*(s[0] - end)), np.hypot(*(s[-1] - end))))+ if np.hypot(*(best[-1] - end)) < np.hypot(*(best[0] - end)):+ best = best[::-1]+ cur = best+ds = [f'M{" L".join(f"{x:.1f} {y:.1f}" for y, x in s)}' for s in order]+lens = [f"{length(s):.1f}" for s in order]+paths = "\n".join(f'<path d="{d}" data-len="{l}"/>' for d, l in zip(ds, lens))+open(a.out, "w").write(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">\n{paths}\n</svg>\n')+print(f"{len(order)} strokes, {sum(length(s) for s in order):.0f} px of line")++if a.lines:+ all_ = np.concatenate(order)+ entry = {"box": [round(all_[:, 1].min()), round(all_[:, 0].min()), round(all_[:, 1].max()), round(all_[:, 0].max())],+ "p": ds, "l": [round(float(l)) for l in lens]}+ lf = pathlib.Path(a.lines)+ head, data = "// centreline traces of line drawings (trace.py)\n", {}+ if lf.exists():+ t = lf.read_text()+ head, data = t[:t.index("window.LINES")], json.loads(t[t.index("{"):t.rindex("}") + 1])+ data[a.name or pathlib.Path(a.out).stem] = entry+ lf.write_text(head + "window.LINES = " + json.dumps(data, separators=(",", ":")) + ";\n")+ print(len(data), "drawings in", lf)diff --git a/.claude/skills/papermorph/scripts/video.py b/.claude/skills/papermorph/scripts/video.pynew file mode 100644index 0000000..03f9084--- /dev/null+++ b/.claude/skills/papermorph/scripts/video.py@@ -0,0 +1,45 @@+#!/usr/bin/env python3+"""A short clip from a still (image-to-video through OpenRouter: POST /api/v1/videos, poll, download).++ python3 video.py OUT.mp4 FIRST_FRAME.png "prompt" --model kwaivgi/kling-v3.0-std --ledger books/<book>/art/costs.tsv+ ... [--duration 5] [--resolution 720p] [--aspect 1:1]++The still is the first frame; the clip has no sound. Then frames.py turns it into an ink-line sprite sheet, so it+plays on the beat clock like the rest of the film (pause, seek and export match, which a <video> would not).+Kling 3.0 std, 5 s, cost about $0.42 and kept an engraving's style; Veo 3.1 lite refused 1:1. A job takes minutes;+the script polls every 20 s. The key is read from ~/.config/openrouter/key or $OPENROUTER_API_KEY.++Prints the cost OpenRouter reports and appends a row to the ledger (date, file, model, "video<N>s", cost), the same+ledger paint.py writes, so `python3 paint.py --total LEDGER` sums both.+"""+import argparse, base64, datetime, json, mimetypes, pathlib, time, urllib.error, urllib.request+from paint import key++ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ap.add_argument("out"); ap.add_argument("frame"); ap.add_argument("prompt")+ap.add_argument("--model", required=True); ap.add_argument("--duration", type=int, default=5); ap.add_argument("--resolution", default="720p")+ap.add_argument("--aspect", default="1:1")+ap.add_argument("--ledger", required=True, help="tab-separated cost log, e.g. books/<book>/art/costs.tsv")+a = ap.parse_args()+k = key()+H = {"Authorization": f"Bearer {k}", "Content-Type": "application/json"}+def call(url, body=None):+ try:+ return urllib.request.urlopen(urllib.request.Request(url, json.dumps(body).encode() if body else None, H), timeout=300)+ except urllib.error.HTTPError as e:+ raise SystemExit(f"{e.code} {e.read().decode(errors='replace').replace(k, '***')[:500]}")+img = f"data:{mimetypes.guess_type(a.frame)[0] or 'image/png'};base64," + base64.b64encode(pathlib.Path(a.frame).read_bytes()).decode()+body = {"model": a.model, "prompt": a.prompt, "duration": a.duration, "resolution": a.resolution, "aspect_ratio": a.aspect,+ "generate_audio": False, "frame_images": [{"type": "image_url", "image_url": {"url": img}, "frame_type": "first_frame"}]}+jid = json.load(call("https://openrouter.ai/api/v1/videos", body))["id"]; print(a.model, "job", jid, flush=True)+while True:+ time.sleep(20)+ s = json.load(call(f"https://openrouter.ai/api/v1/videos/{jid}"))+ if s["status"] in ("completed", "failed"): break+if s["status"] == "failed": raise SystemExit(f"failed: {s.get('error')}")+out = pathlib.Path(a.out); out.parent.mkdir(parents=True, exist_ok=True)+out.write_bytes(call(f"https://openrouter.ai/api/v1/videos/{jid}/content?index=0").read())+cost = (s.get("usage") or {}).get("cost", 0) or 0+led = pathlib.Path(a.ledger); led.parent.mkdir(parents=True, exist_ok=True)+with led.open("a", encoding="utf-8") as f: f.write(f"{datetime.date.today()}\t{a.out}\t{a.model}\tvideo{a.duration}s\t{cost}\n")+print(a.out, f"cost {cost} USD")diff --git a/engine/engine.js b/engine/engine.jsindex 8fe15c8..f994247 100644--- a/engine/engine.js+++ b/engine/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/elementary-algebra/lib/engine.js b/site/elementary-algebra/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/elementary-algebra/lib/engine.js+++ b/site/elementary-algebra/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/joke-collection/lib/engine.js b/site/joke-collection/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/joke-collection/lib/engine.js+++ b/site/joke-collection/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/little-red-riding-hood/lib/engine.js b/site/little-red-riding-hood/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/little-red-riding-hood/lib/engine.js+++ b/site/little-red-riding-hood/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/madness/ch01/index.html b/site/madness/ch01/index.htmlindex 783209e..62ce3e1 100644--- a/site/madness/ch01/index.html+++ b/site/madness/ch01/index.html@@ -10,6 +10,7 @@<body><script src="../lib/engine.js"></script><script src="../lib/shared.js"></script>+<script src="../lib/film.js"></script><script src="audio/en/timings.js"></script><script src="../img/art.js"></script><script src="../lib/lines.js"></script>@@ -19,204 +20,6 @@'use strict';const CHAPTER = { number: 1, title: 'Madness and Civilization', minutes: 10, language: 'en' };-/* ---------- the look: burgundy ground, cream ink, found pictures ---------- */-const KEY = '"Oswald", "Arial Narrow", sans-serif', SER = '"EB Garamond", Georgia, serif';-const CREAM = '#f3ede0', HOT = '#f08a4b', SOFT = '#d9b9b0', INK = '#3a2a24';--// a picture from img/: centred on (x, y), h or w in stage px; `at` makes it enter (from offset dx, dy) at that time-function pic(p, name, { x = 800, y = 450, h = 600, w, r = 0, s = 1, at, from = [0, 40], dur = .9, o = 1, back = false } = {}) {- const sz = ART[name];- const g = G(p, at === undefined ? { x, y, r, s, o } : { x: x + from[0], y: y + from[1], r, s, o: 0 });- const k = w ? w / sz[0] : h / sz[1], W = sz[0] * k, H = sz[1] * k;- if (back) mk('rect', { x: -W / 2 + 4, y: -H / 2 + 4, width: W - 8, height: H - 8, fill: COL.board }, g); // a solid line drawing (a door)- mk('image', { href: `../img/${name}.webp`, x: -W / 2, y: -H / 2, width: W, height: H }, g);- g._w = W; g._h = H; g._x = x; g._y = y;- if (at !== undefined) tw(g, { x, y, o }, at, dur, out);- return g;-}-const leave = (g, t0, dx = 0, dy = 0, dur = .7) => tw(g, { x: g._x + dx, y: g._y + dy, o: 0 }, t0, dur, io);-const push = (g, t0, t1, s1 = 1.06, dx = 0, dy = 0) => tw(g, { s: s1, x: g._x + dx, y: g._y + dy }, t0, t1 - t0, lin); // slow Ken Burns-// one picture turning into another in place (the Fool changing era)-const dissolve = (a, b, t0, dur = 1.2) => { hide(a, t0, dur, lin); show(b, t0, dur, lin); };--// a Foucault line drawing: drawn on stroke by stroke over `draw` s, or shown whole-function mf(p, name, { x = 800, y = 450, h = 600, at = 0, draw: dd = 0, o = 1, flip = false } = {}) {- const L = LINES[name], [x0, y0, x1, y1] = L.box, k = h / (y1 - y0);- const g = G(p, { x, y, o: dd ? 1 : 0 });- const inner = mk('g', { transform: `scale(${flip ? -k : k},${k}) translate(${-(x0 + x1) / 2},${-(y0 + y1) / 2})` }, g);- const total = L.l.reduce((a, b) => a + b, 0);- let acc = 0;- L.p.forEach((d, i) => {- const e = path(inner, d, { stroke: CREAM, 'stroke-width': 2.4 / k }, dd ? { d: 0 } : {});- if (dd) { draw(e, at + dd * acc / total, Math.max(.04, dd * L.l[i] / total), lin); acc += L.l[i]; }- });- if (!dd) tw(g, { o }, at, .6);- g._x = x; g._y = y; g._h = h;- return g;-}-// Foucault the guide, peeking up from the bottom edge when the narration names him-function peek(p, t0, { x = 1440, y = 870, h = 230, until } = {}) {- const g = mf(p, 'mf-peek', { x, y: y + 90, h, at: t0 });- tw(g, { y }, t0, .8, out);- if (until !== undefined) tw(g, { y: y + 140, o: 0 }, until, .7, io);- return g;-}--// words in a font measured on a canvas (fonts are loaded before boot)-const CTX = document.createElement('canvas').getContext('2d');-const wid = (str, size, font, style = '', weight = 400) => { CTX.font = `${style} ${weight} ${size}px ${font}`; return CTX.measureText(str).width; };--// big condensed word(s)-function key(p, str, x, y, t0, { size = 96, fill = CREAM, anchor = 'middle', from = 24, o = 1 } = {}) {- const e = T(p, str.toUpperCase(), { x, y: y + from, size, fill, font: KEY, weight: 600, anchor, o: 0 });- e.setAttribute('letter-spacing', '.02em');- e._w = wid(str.toUpperCase(), size, KEY, '', 600) * 1.02;- tw(e, { y, o }, t0, .55, out);- return e;-}-// a line struck through a key word (the word's own width)-function strike(p, e, x, y, t0, size, anchor = 'middle') {- const x0 = anchor === 'middle' ? x - e._w / 2 : anchor === 'end' ? x - e._w : x;- return line(p, `M${x0 - 16} ${y - size * .32}H${x0 + e._w + 16}`, t0, .4, Math.max(5, size / 12), { stroke: HOT });-}-// serif lines typed word by word between t0 and t1-function say(p, lines, x, y, t0, t1, { size = 44, fill = CREAM, italic = true, anchor = 'start', lh = 1.3, weight = 400 } = {}) {- const g = G(p, {}), style = italic ? 'italic' : '', words = [];- const sp = wid(' ', size, SER, style, weight);- lines.forEach((ln, i) => {- const ws = ln.split(' '), W = wid(ln, size, SER, style, weight);- let cx = anchor === 'middle' ? x - W / 2 : anchor === 'end' ? x - W : x;- ws.forEach(w => {- const e = T(g, w, { x: cx, y: y + i * size * lh, size, fill, font: SER, weight, o: 0 });- if (italic) e.setAttribute('font-style', 'italic');- words.push(e); cx += wid(w, size, SER, style, weight) + sp;- });- });- const chars = words.map(e => e.textContent.length + 1), all = chars.reduce((a, b) => a + b, 0);- let acc = 0;- words.forEach((e, i) => { show(e, t1 === t0 ? t0 : t0 + (t1 - t0) * acc / all, .25, lin); acc += chars[i]; });- return g;-}-// a small caption under a picture (a credit or a name tag)-function tag(p, str, x, y, t0, { size = 24, anchor = 'start', fill = SOFT } = {}) {- const e = T(p, str, { x, y, size, fill, font: SER, anchor, o: 0 });- e.setAttribute('font-style', 'italic');- show(e, t0, .5);- return e;-}-// the era at the top left, like a chapter opener: the year in italic, a hairline, the place or topic in spaced capitals-function dateChip(p, year, topic, t0 = .2) {- const g = G(p, { x: 80, y: 112, o: 0 });- T(g, year, { size: 72, font: SER, weight: 400, fill: HOT }).setAttribute('font-style', 'italic');- const tw_ = wid(topic.toUpperCase(), 26, SER) * 1.3 + 8; // letter-spacing .28em widens the caps by about 30 %- const rule = path(g, `M3 22H${Math.max(220, tw_)}`, { stroke: CREAM, 'stroke-width': 1.4, opacity: .7 }, { d: 0 });- T(g, topic.toUpperCase(), { x: 3, y: 58, size: 26, font: SER, weight: 400, fill: CREAM }).setAttribute('letter-spacing', '.28em');- tw(g, { o: 1 }, t0, .6); draw(rule, t0 + .2, .6);- return g;-}-// cream line, drawn on-const line = (p, d, t0, dur = .8, w = 3, extra = {}) => { const e = path(p, d, { stroke: CREAM, 'stroke-width': w, ...extra }, { d: 0 }); draw(e, t0, dur); return e; };-// wavy water lines that flow forever (pure function of the beat clock); amp may be a function of t-function water(p, y0, D, { rows = 3, amp = 8, len = 1700, x0 = -50, gap = 26, o = .75 } = {}) {- const g = G(p, { o: 0 }); tw(g, { o }, 0, .6);- const ps = [...Array(rows)].map((_, i) => path(g, '', { stroke: CREAM, 'stroke-width': 2.2, opacity: 1 - i * .25 }));- clockRun(t => { const a = typeof amp === 'function' ? amp(t) : amp; ps.forEach((e, i) => {- let d = ''; for (let x = 0; x <= len; x += 20) d += `${x ? 'L' : 'M'}${x0 + x} ${(y0 + i * gap * (a / 8) ** .5 + a * Math.sin(x / 70 + t * 1.6 + i)).toFixed(1)}`;- e.setAttribute('d', d);- }); }, D, { tail: true });- return g;-}-// something that bobs on the water (a boat); x may follow a function of t-const bob = (g, D, a = 6, xf) => clockRun(t => put(g, { y: g._y + a * Math.sin(t * 1.6), r: 1.5 * Math.sin(t * 1.1), ...(xf ? { x: xf(t) } : {}) }), D, { tail: true });-const span01 = (t, a, b) => Math.min(1, Math.max(0, (t - a) / (b - a)));-const smooth01 = q => q * q * (3 - 2 * q);-// a speech balloon, cream outline, its tail to (tx, ty)-function balloon(p, x, y, w, h, tx, ty, t0) {- const bx = Math.min(Math.max(tx, x + 60), x + w - 100);- const d = `M${x + 30} ${y}H${x + w - 30}Q${x + w} ${y} ${x + w} ${y + 30}V${y + h - 30}Q${x + w} ${y + h} ${x + w - 30} ${y + h}H${bx + 40}L${tx} ${ty}L${bx} ${y + h}H${x + 30}Q${x} ${y + h} ${x} ${y + h - 30}V${y + 30}Q${x} ${y} ${x + 30} ${y}Z`;- return line(p, d, t0, .7, 3);-}-// a field of dots (leper houses): positions from a fixed seed so every replay is the same-function rng(seed) { return () => (seed = (seed * 16807) % 2147483647) / 2147483647; }-function dots(p, n, box, r, seed, fill = CREAM) {- const R = rng(seed), g = G(p, {});- return { g, el: [...Array(n)].map(() => mk('circle', { cx: box[0] + R() * box[2], cy: box[1] + R() * box[3], r, fill }, g)).map(e => put(e, { o: 0 })) };-}-// close-ups inside a print as their words are spoken: shots [[mark, fx, fy, label, zoom]], fx/fy the point in the picture-// (0..1 of the picture inside its border); the view never leaves the picture; a band names each one; back to the whole after-function closeups(p, g, name, shots, m, tBack, home) {- const [W, H] = ART[name], k = g._w / W, iw = (W - 112) * k, ih = (H - 112) * k; // a print's picture sits 56 px in- const clamp = (v, lim) => Math.max(-lim, Math.min(lim, v));- shots.forEach(([mark, fx, fy, label, Z = 3], i) => {- const dx = clamp((fx - .5) * iw, iw / 2 - 800 / Z), dy = clamp((fy - .5) * ih, ih / 2 - 450 / Z), t0 = m(mark) - .15;- tw(g, { s: Z, x: 800 - Z * dx, y: 450 - Z * dy, r: 0 }, t0, .35, out);- const l = G(p, { x: 800, y: fy > .7 ? 130 : 820, o: 0 }), lw = wid(label.toUpperCase(), 72, KEY, '', 600) + 70; // clear of a low subject- mk('rect', { x: -lw / 2, y: -68, width: lw, height: 92, fill: COL.board }, l);- T(l, label.toUpperCase(), { y: 0, size: 72, font: KEY, weight: 600, fill: CREAM, anchor: 'middle' });- show(l, t0, .12);- hide(l, i < shots.length - 1 ? m(shots[i + 1][0]) - .15 : tBack, .15);- });- if (home) tw(g, { s: 1, ...home }, tBack, .8, soft); // no home: stay on the last close-up-}-// a generated clip as cream-line frames on one sprite sheet (tools/madness/frames.py), played on the beat clock from t0:-// the frame is a pure function of the time, so pausing, seeking and the export all show the same picture-function anim(p, name, { x = 800, y = 450, size = 600, at = 0, t0 = at, D, o = 1 } = {}) {- const F = FRAMES[name], rows = Math.ceil(F.n / F.cols);- const g = G(p, { x, y, o: 0 });- const v = mk('svg', { x: -size / 2, y: -size / 2, width: size, height: size, viewBox: `0 0 ${F.fw} ${F.fh}` }, g);- mk('image', { href: `../img/${name}-sheet.webp`, width: F.cols * F.fw, height: rows * F.fh }, v);- let last = -1;- clockRun(t => {- const f = Math.max(0, Math.min(F.n - 1, Math.floor((t - t0) * F.fps)));- if (f !== last) { last = f; v.setAttribute('viewBox', `${(f % F.cols) * F.fw} ${Math.floor(f / F.cols) * F.fh} ${F.fw} ${F.fh}`); }- }, D, { tail: true });- tw(g, { o }, at, .8);- return g;-}-// Europe (Natural Earth coastline) in its box, faint, with the leper-house dots on land.-// Outline only: Eurasia's ring crosses the antimeridian, so a fill would flood the whole box.-function europe(p, t0) {- const [bx, by, bw, bh] = EUROPE.box, g = G(p, { o: 0 });- const cp = mk('clipPath', { id: 'eu' + t0 }, g); mk('rect', { x: bx, y: by, width: bw, height: bh }, cp);- mk('path', { d: EUROPE.d, fill: 'none', stroke: CREAM, 'stroke-width': 1.5, 'stroke-opacity': .6, 'clip-path': `url(#eu${t0})` }, g);- tw(g, { o: 1 }, t0, .8);- const dg = G(p, {});- const el = EUROPE.dots.map(([x, y]) => put(mk('circle', { cx: x, cy: y, r: 4.5, fill: CREAM }, dg), { o: 0 }));- return { g, el };-}-// an old document: cream paper, lines of ink, a label-function doc(p, label, x, y, r, t0, seed) {- const R = rng(seed), g = G(p, { x: x - 700, y, r, o: 0 });- mk('rect', { x: -150, y: -200, width: 300, height: 400, fill: CREAM, stroke: '#cdbfa6' }, g);- for (let i = 0; i < 13; i++) {- const yy = -130 + i * 24, ww = 160 + R() * 70;- path(g, `M-118 ${yy}q${ww / 4} ${-3 + R() * 6} ${ww / 2} 0t${ww / 2} 0`, { stroke: INK, 'stroke-width': 2, opacity: .7 });- }- T(g, label.toUpperCase(), { y: -160, size: 22, font: KEY, weight: 600, fill: '#7a1a20', anchor: 'middle' }).setAttribute('letter-spacing', '.06em');- tw(g, { x, o: 1 }, t0, .8, out);- g._x = x; g._y = y;- return g;-}-// a point moving along a polyline [[x, y], …] as q goes 0..1-function along(pts, q) {- const seg = pts.slice(1).map((b, i) => Math.hypot(b[0] - pts[i][0], b[1] - pts[i][1])), L = seg.reduce((a, b) => a + b, 0);- let d = q * L, i = 0;- while (i < seg.length - 1 && d > seg[i]) d -= seg[i++];- const f = seg[i] ? d / seg[i] : 0, a = pts[i], b = pts[i + 1];- return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f];-}-// the epigraphs, each in its own frame: portrait left, the quote large beside it-const PASCAL = ['“Men are so necessarily mad,', 'that not to be mad would amount', 'to another form of madness.”'];-const DOSTO = ['“It is not by confining', 'one’s neighbor that one', 'is convinced of one’s own sanity.”'];-function epigraph(p, name, who, lines, tin, tq, tq1, tout) {- const g = G(p, {});- pic(g, name, { x: 330, y: 430, h: 440, r: -2, at: tin, from: [-500, 0] });- tag(g, who, 330, 690, tin + .5, { anchor: 'middle', size: 30, fill: CREAM });- say(g, lines, 620, 330, tq, tq1, { size: 62 });- if (tout !== undefined) tw(g, { x: -200, o: 0 }, tout, .7, io);- return g;-}-const OPEN_PRE = 5;// the confined, one figure per word (inmates), then small in the lower half (idle); without m, all shown at once@@ -261,7 +64,7 @@ const BEATS = [['foucault', 'Michel Foucault', (m, D) => {const p = panel(0);dateChip(p, '1950s', 'Paris');- mf(p, 'mf-front', { x: 1130, y: 500, h: 760, at: m('mf') - .6, draw: 4.2 });+ traced(p, 'mf-front', { x: 1130, y: 500, h: 760, at: m('mf') - .6, draw: 4.2 });key(p, 'Michel Foucault', 80, 380, m('mf') + .2, { size: 84, anchor: 'start' });tag(p, '1926 – 1984', 84, 430, m('mf') + .8, { size: 30 });tag(p, 'psychologist at a psychiatric hospital in Paris', 84, 490, m('hosp'), { size: 30, fill: CREAM });@@ -270,7 +73,7 @@ const BEATS = [['uppsala', 'Uppsala', (m, D) => {const p = panel(0);dateChip(p, '1955', 'Uppsala, Sweden', m('upp') - .2);- const g = mf(p, 'mf-glass', { x: 1180, y: 480, h: 560, at: .1 });+ const g = traced(p, 'mf-glass', { x: 1180, y: 480, h: 560, at: .1 });const ds = [['city accounts', -7, 330, 380], ['royal edicts', 5, 560, 470], ['hospital registers', -3, 420, 600]].map(([l, r, x, y], i) => { const t = m('edicts') - 1.6 + i * .9; sfx('uppsala', t + .2, 'page', .5); return doc(p, l, x, y, r, t, 3 + i); });ds.forEach(d => leave(d, m('title') - .9, -200, 0));@@ -379,7 +182,7 @@ const BEATS = [['records', 'The real ships', (m, D) => {const p = panel(0);pic(p, 'rhine', { x: 560, y: 470, w: 1040, r: -1, at: .1, from: [-600, 0] });- mf(p, 'mf-glass', { x: 1240, y: 520, h: 560, at: m('real') - .3, draw: 3.2 });+ traced(p, 'mf-glass', { x: 1240, y: 520, h: 560, at: m('real') - .3, draw: 3.2 });dateChip(p, '1399', 'Frankfurt', m('ffm') - .2);const pin = G(p, { x: 510, y: 500, o: 0, s: 0 }); mk('circle', { r: 13, fill: HOT, stroke: CREAM, 'stroke-width': 3 }, pin);pop(pin, m('ffm'));@@ -659,7 +462,7 @@ const BEATS = [const p = panel(0);key(p, 'A triumph', 520, 400, 0, { size: 110, from: 0 });const h = key(p, 'of humanity', 520, 520, 0, { size: 110, fill: HOT, from: 0 });- mf(p, 'mf-profile', { x: 1220, y: 470, h: 720, at: m('mf') - .1, draw: 2.8, flip: true });+ traced(p, 'mf-profile', { x: 1220, y: 470, h: 720, at: m('mf') - .1, draw: 2.8, flip: true });tw(h, { x: 340, y: 640, r: 9, o: 0 }, m('what') - .2, .9, io);key(p, '?', 520, 660, m('what') + .4, { size: 180, fill: HOT });}],@@ -689,7 +492,7 @@ const BEATS = [}],['moral', 'A gigantic moral imprisonment', (m, D) => {const p = panel(0);- mf(p, 'mf-hands', { x: 1330, y: 560, h: 560, at: .2 });+ traced(p, 'mf-hands', { x: 1330, y: 560, h: 560, at: .2 });say(p, ['“that gigantic moral imprisonment', 'which we are in the habit of calling,', 'doubtless by antiphrasis,'], 90, 220, m('q'), m('lib') - .3, { size: 52 });say(p, ['the liberation of the insane', 'by Pinel and Tuke.”'], 90, 440, m('lib'), D, { size: 52, fill: HOT });tag(p, 'Madness and Civilization, ch. 9', 90, 580, D - 1, { size: 28 });@@ -763,7 +566,7 @@ const BEATS = [['question', 'The world questioned', (m, D) => {const p = panel(0);const C = TIMINGS.question.cues;- mf(p, 'mf-smoke', { x: 430, y: 500, h: 640, at: .2 });+ traced(p, 'mf-smoke', { x: 430, y: 500, h: 640, at: .2 });pic(p, 'fool-vangogh', { x: 1150, y: 410, h: 600, r: 2, at: .6, from: [500, 0] });key(p, '?', 800, 300, m('quest'), { size: 140, fill: HOT });tag(p, 'the work interrupts us', 800, 380, C[1][0] + .2, { anchor: 'middle', size: 36, fill: CREAM });diff --git a/site/madness/lib/engine.js b/site/madness/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/madness/lib/engine.js+++ b/site/madness/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/madness/lib/film.js b/site/madness/lib/film.jsnew file mode 100644index 0000000..5d4c424--- /dev/null+++ b/site/madness/lib/film.js@@ -0,0 +1,208 @@+/* film.js — the documentary kit: found pictures, line drawings, words and maps on the engine's beat clock.+ This is the book's own copy: set its look here (fonts in lib/fonts.css, colours below) and add the film's recurring+ pieces at the end. Every helper is a pure function of the beat clock, so pause, seek, ?beat=N&t=S and export.py agree.+ Pictures are img/<name>.webp with their sizes in ART (img/art.js, from prep.py); traced drawings are LINES (lib/lines.js,+ from trace.py); clips are FRAMES (img/frames.js, from frames.py). The fonts must be loaded before boot(): words are+ measured on a canvas (chapter.html does this). */+'use strict';+/* ---------- the look ---------- */+const KEY = '"Oswald", "Arial Narrow", sans-serif', SER = '"EB Garamond", Georgia, serif'; // titles and key words; quotes and captions+const CREAM = '#f3ede0', HOT = '#f08a4b', SOFT = '#d9b9b0', INK = '#3a2a24'; // ink on the ground, the accent, captions, ink on paper++// a picture from img/: centred on (x, y), h or w in stage px; `at` makes it enter (from offset dx, dy) at that time+function pic(p, name, { x = 800, y = 450, h = 600, w, r = 0, s = 1, at, from = [0, 40], dur = .9, o = 1, back = false } = {}) {+ const sz = ART[name];+ const g = G(p, at === undefined ? { x, y, r, s, o } : { x: x + from[0], y: y + from[1], r, s, o: 0 });+ const k = w ? w / sz[0] : h / sz[1], W = sz[0] * k, H = sz[1] * k;+ if (back) mk('rect', { x: -W / 2 + 4, y: -H / 2 + 4, width: W - 8, height: H - 8, fill: COL.board }, g); // a solid line drawing (a door)+ mk('image', { href: `../img/${name}.webp`, x: -W / 2, y: -H / 2, width: W, height: H }, g);+ g._w = W; g._h = H; g._x = x; g._y = y;+ if (at !== undefined) tw(g, { x, y, o }, at, dur, out);+ return g;+}+const leave = (g, t0, dx = 0, dy = 0, dur = .7) => tw(g, { x: g._x + dx, y: g._y + dy, o: 0 }, t0, dur, io);+const push = (g, t0, t1, s1 = 1.06, dx = 0, dy = 0) => tw(g, { s: s1, x: g._x + dx, y: g._y + dy }, t0, t1 - t0, lin); // slow Ken Burns+// one picture turning into another in place (a figure changing era)+const dissolve = (a, b, t0, dur = 1.2) => { hide(a, t0, dur, lin); show(b, t0, dur, lin); };++// a line drawing traced into strokes (LINES[name] from trace.py): drawn on stroke by stroke over `draw` s, or shown whole+function traced(p, name, { x = 800, y = 450, h = 600, at = 0, draw: dd = 0, o = 1, flip = false } = {}) {+ const L = LINES[name], [x0, y0, x1, y1] = L.box, k = h / (y1 - y0);+ const g = G(p, { x, y, o: dd ? 1 : 0 });+ const inner = mk('g', { transform: `scale(${flip ? -k : k},${k}) translate(${-(x0 + x1) / 2},${-(y0 + y1) / 2})` }, g);+ const total = L.l.reduce((a, b) => a + b, 0);+ let acc = 0;+ L.p.forEach((d, i) => {+ const e = path(inner, d, { stroke: CREAM, 'stroke-width': 2.4 / k }, dd ? { d: 0 } : {});+ if (dd) { draw(e, at + dd * acc / total, Math.max(.04, dd * L.l[i] / total), lin); acc += L.l[i]; }+ });+ if (!dd) tw(g, { o }, at, .6);+ g._x = x; g._y = y; g._h = h;+ return g;+}+// words in a font measured on a canvas (fonts are loaded before boot)+const CTX = document.createElement('canvas').getContext('2d');+const wid = (str, size, font, style = '', weight = 400) => { CTX.font = `${style} ${weight} ${size}px ${font}`; return CTX.measureText(str).width; };++// big condensed word(s)+function key(p, str, x, y, t0, { size = 96, fill = CREAM, anchor = 'middle', from = 24, o = 1 } = {}) {+ const e = T(p, str.toUpperCase(), { x, y: y + from, size, fill, font: KEY, weight: 600, anchor, o: 0 });+ e.setAttribute('letter-spacing', '.02em');+ e._w = wid(str.toUpperCase(), size, KEY, '', 600) * 1.02;+ tw(e, { y, o }, t0, .55, out);+ return e;+}+// a line struck through a key word (the word's own width)+function strike(p, e, x, y, t0, size, anchor = 'middle') {+ const x0 = anchor === 'middle' ? x - e._w / 2 : anchor === 'end' ? x - e._w : x;+ return line(p, `M${x0 - 16} ${y - size * .32}H${x0 + e._w + 16}`, t0, .4, Math.max(5, size / 12), { stroke: HOT });+}+// serif lines typed word by word between t0 and t1+function say(p, lines, x, y, t0, t1, { size = 44, fill = CREAM, italic = true, anchor = 'start', lh = 1.3, weight = 400 } = {}) {+ const g = G(p, {}), style = italic ? 'italic' : '', words = [];+ const sp = wid(' ', size, SER, style, weight);+ lines.forEach((ln, i) => {+ const ws = ln.split(' '), W = wid(ln, size, SER, style, weight);+ let cx = anchor === 'middle' ? x - W / 2 : anchor === 'end' ? x - W : x;+ ws.forEach(w => {+ const e = T(g, w, { x: cx, y: y + i * size * lh, size, fill, font: SER, weight, o: 0 });+ if (italic) e.setAttribute('font-style', 'italic');+ words.push(e); cx += wid(w, size, SER, style, weight) + sp;+ });+ });+ const chars = words.map(e => e.textContent.length + 1), all = chars.reduce((a, b) => a + b, 0);+ let acc = 0;+ words.forEach((e, i) => { show(e, t1 === t0 ? t0 : t0 + (t1 - t0) * acc / all, .25, lin); acc += chars[i]; });+ return g;+}+// a small caption under a picture (a credit or a name tag)+function tag(p, str, x, y, t0, { size = 24, anchor = 'start', fill = SOFT } = {}) {+ const e = T(p, str, { x, y, size, fill, font: SER, anchor, o: 0 });+ e.setAttribute('font-style', 'italic');+ show(e, t0, .5);+ return e;+}+// the era at the top left, like a chapter opener: the year in italic, a hairline, the place or topic in spaced capitals+function dateChip(p, year, topic, t0 = .2) {+ const g = G(p, { x: 80, y: 112, o: 0 });+ T(g, year, { size: 72, font: SER, weight: 400, fill: HOT }).setAttribute('font-style', 'italic');+ const tw_ = wid(topic.toUpperCase(), 26, SER) * 1.3 + 8; // letter-spacing .28em widens the caps by about 30 %+ const rule = path(g, `M3 22H${Math.max(220, tw_)}`, { stroke: CREAM, 'stroke-width': 1.4, opacity: .7 }, { d: 0 });+ T(g, topic.toUpperCase(), { x: 3, y: 58, size: 26, font: SER, weight: 400, fill: CREAM }).setAttribute('letter-spacing', '.28em');+ tw(g, { o: 1 }, t0, .6); draw(rule, t0 + .2, .6);+ return g;+}+// cream line, drawn on+const line = (p, d, t0, dur = .8, w = 3, extra = {}) => { const e = path(p, d, { stroke: CREAM, 'stroke-width': w, ...extra }, { d: 0 }); draw(e, t0, dur); return e; };+// wavy water lines that flow forever (pure function of the beat clock); amp may be a function of t+function water(p, y0, D, { rows = 3, amp = 8, len = 1700, x0 = -50, gap = 26, o = .75 } = {}) {+ const g = G(p, { o: 0 }); tw(g, { o }, 0, .6);+ const ps = [...Array(rows)].map((_, i) => path(g, '', { stroke: CREAM, 'stroke-width': 2.2, opacity: 1 - i * .25 }));+ clockRun(t => { const a = typeof amp === 'function' ? amp(t) : amp; ps.forEach((e, i) => {+ let d = ''; for (let x = 0; x <= len; x += 20) d += `${x ? 'L' : 'M'}${x0 + x} ${(y0 + i * gap * (a / 8) ** .5 + a * Math.sin(x / 70 + t * 1.6 + i)).toFixed(1)}`;+ e.setAttribute('d', d);+ }); }, D, { tail: true });+ return g;+}+// something that bobs on the water (a boat); x may follow a function of t+const bob = (g, D, a = 6, xf) => clockRun(t => put(g, { y: g._y + a * Math.sin(t * 1.6), r: 1.5 * Math.sin(t * 1.1), ...(xf ? { x: xf(t) } : {}) }), D, { tail: true });+const span01 = (t, a, b) => Math.min(1, Math.max(0, (t - a) / (b - a)));+const smooth01 = q => q * q * (3 - 2 * q);+// a speech balloon, cream outline, its tail to (tx, ty)+function balloon(p, x, y, w, h, tx, ty, t0) {+ const bx = Math.min(Math.max(tx, x + 60), x + w - 100);+ const d = `M${x + 30} ${y}H${x + w - 30}Q${x + w} ${y} ${x + w} ${y + 30}V${y + h - 30}Q${x + w} ${y + h} ${x + w - 30} ${y + h}H${bx + 40}L${tx} ${ty}L${bx} ${y + h}H${x + 30}Q${x} ${y + h} ${x} ${y + h - 30}V${y + 30}Q${x} ${y} ${x + 30} ${y}Z`;+ return line(p, d, t0, .7, 3);+}+// a field of dots: positions from a fixed seed so every replay is the same+function rng(seed) { return () => (seed = (seed * 16807) % 2147483647) / 2147483647; }+function dots(p, n, box, r, seed, fill = CREAM) {+ const R = rng(seed), g = G(p, {});+ return { g, el: [...Array(n)].map(() => mk('circle', { cx: box[0] + R() * box[2], cy: box[1] + R() * box[3], r, fill }, g)).map(e => put(e, { o: 0 })) };+}+// close-ups inside a print as their words are spoken: shots [[mark, fx, fy, label, zoom]], fx/fy the point in the picture+// (0..1 of the picture inside its border); the view never leaves the picture; a band names each one; back to the whole after+function closeups(p, g, name, shots, m, tBack, home) {+ const [W, H] = ART[name], k = g._w / W, iw = (W - 112) * k, ih = (H - 112) * k; // a print's picture sits 56 px in+ const clamp = (v, lim) => Math.max(-lim, Math.min(lim, v));+ shots.forEach(([mark, fx, fy, label, Z = 3], i) => {+ const dx = clamp((fx - .5) * iw, iw / 2 - 800 / Z), dy = clamp((fy - .5) * ih, ih / 2 - 450 / Z), t0 = m(mark) - .15;+ tw(g, { s: Z, x: 800 - Z * dx, y: 450 - Z * dy, r: 0 }, t0, .35, out);+ const l = G(p, { x: 800, y: fy > .7 ? 130 : 820, o: 0 }), lw = wid(label.toUpperCase(), 72, KEY, '', 600) + 70; // clear of a low subject+ mk('rect', { x: -lw / 2, y: -68, width: lw, height: 92, fill: COL.board }, l);+ T(l, label.toUpperCase(), { y: 0, size: 72, font: KEY, weight: 600, fill: CREAM, anchor: 'middle' });+ show(l, t0, .12);+ hide(l, i < shots.length - 1 ? m(shots[i + 1][0]) - .15 : tBack, .15);+ });+ if (home) tw(g, { s: 1, ...home }, tBack, .8, soft); // no home: stay on the last close-up+}+// a generated clip as cream-line frames on one sprite sheet (frames.py), played on the beat clock from t0:+// the frame is a pure function of the time, so pausing, seeking and the export all show the same picture+function anim(p, name, { x = 800, y = 450, size = 600, at = 0, t0 = at, D, o = 1 } = {}) {+ const F = FRAMES[name], rows = Math.ceil(F.n / F.cols);+ const g = G(p, { x, y, o: 0 });+ const v = mk('svg', { x: -size / 2, y: -size / 2, width: size, height: size, viewBox: `0 0 ${F.fw} ${F.fh}` }, g);+ mk('image', { href: `../img/${name}-sheet.webp`, width: F.cols * F.fw, height: rows * F.fh }, v);+ let last = -1;+ clockRun(t => {+ const f = Math.max(0, Math.min(F.n - 1, Math.floor((t - t0) * F.fps)));+ if (f !== last) { last = f; v.setAttribute('viewBox', `${(f % F.cols) * F.fw} ${Math.floor(f / F.cols) * F.fh} ${F.fw} ${F.fh}`); }+ }, D, { tail: true });+ tw(g, { o }, at, .8);+ return g;+}+// an old document: cream paper, lines of ink, a label+function doc(p, label, x, y, r, t0, seed) {+ const R = rng(seed), g = G(p, { x: x - 700, y, r, o: 0 });+ mk('rect', { x: -150, y: -200, width: 300, height: 400, fill: CREAM, stroke: '#cdbfa6' }, g);+ for (let i = 0; i < 13; i++) {+ const yy = -130 + i * 24, ww = 160 + R() * 70;+ path(g, `M-118 ${yy}q${ww / 4} ${-3 + R() * 6} ${ww / 2} 0t${ww / 2} 0`, { stroke: INK, 'stroke-width': 2, opacity: .7 });+ }+ T(g, label.toUpperCase(), { y: -160, size: 22, font: KEY, weight: 600, fill: '#7a1a20', anchor: 'middle' }).setAttribute('letter-spacing', '.06em');+ tw(g, { x, o: 1 }, t0, .8, out);+ g._x = x; g._y = y;+ return g;+}+// a point moving along a polyline [[x, y], …] as q goes 0..1+function along(pts, q) {+ const seg = pts.slice(1).map((b, i) => Math.hypot(b[0] - pts[i][0], b[1] - pts[i][1])), L = seg.reduce((a, b) => a + b, 0);+ let d = q * L, i = 0;+ while (i < seg.length - 1 && d > seg[i]) d -= seg[i++];+ const f = seg[i] ? d / seg[i] : 0, a = pts[i], b = pts[i + 1];+ return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f];+}++// a picture with its credit or name under it, and a quote typed beside it (an epigraph): portrait left, the quote large+function epigraph(p, name, who, lines, tin, tq, tq1, tout) {+ const g = G(p, {});+ pic(g, name, { x: 330, y: 430, h: 440, r: -2, at: tin, from: [-500, 0] });+ tag(g, who, 330, 690, tin + .5, { anchor: 'middle', size: 30, fill: CREAM });+ say(g, lines, 620, 330, tq, tq1, { size: 62 });+ if (tout !== undefined) tw(g, { x: -200, o: 0 }, tout, .7, io);+ return g;+}++/* ---------- this film's own pieces ---------- */+// Foucault the guide, peeking up from the bottom edge when the narration names him+function peek(p, t0, { x = 1440, y = 870, h = 230, until } = {}) {+ const g = traced(p, 'mf-peek', { x, y: y + 90, h, at: t0 });+ tw(g, { y }, t0, .8, out);+ if (until !== undefined) tw(g, { y: y + 140, o: 0 }, until, .7, io);+ return g;+}++// Europe (Natural Earth coastline) in its box, faint, with the leper-house dots on land.+// Outline only: Eurasia's ring crosses the antimeridian, so a fill would flood the whole box.+function europe(p, t0) {+ const [bx, by, bw, bh] = EUROPE.box, g = G(p, { o: 0 });+ const cp = mk('clipPath', { id: 'eu' + t0 }, g); mk('rect', { x: bx, y: by, width: bw, height: bh }, cp);+ mk('path', { d: EUROPE.d, fill: 'none', stroke: CREAM, 'stroke-width': 1.5, 'stroke-opacity': .6, 'clip-path': `url(#eu${t0})` }, g);+ tw(g, { o: 1 }, t0, .8);+ const dg = G(p, {});+ const el = EUROPE.dots.map(([x, y]) => put(mk('circle', { cx: x, cy: y, r: 4.5, fill: CREAM }, dg), { o: 0 }));+ return { g, el };+}+// the two epigraphs+const PASCAL = ['“Men are so necessarily mad,', 'that not to be mad would amount', 'to another form of madness.”'];+const DOSTO = ['“It is not by confining', 'one’s neighbor that one', 'is convinced of one’s own sanity.”'];diff --git a/site/math-notebook/lib/engine.js b/site/math-notebook/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/math-notebook/lib/engine.js+++ b/site/math-notebook/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/physics-notebook/lib/engine.js b/site/physics-notebook/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/physics-notebook/lib/engine.js+++ b/site/physics-notebook/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/science/lib/engine.js b/site/science/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/science/lib/engine.js+++ b/site/science/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);diff --git a/site/three-little-pigs/lib/engine.js b/site/three-little-pigs/lib/engine.jsindex 8fe15c8..f994247 100644--- a/site/three-little-pigs/lib/engine.js+++ b/site/three-little-pigs/lib/engine.js@@ -1271,7 +1271,7 @@ function runBeat(i) {};S.cleared = false;b.run(m, pre + tm.dur);- if (S.cleared && b.lead !== false && !pre) leadIn();+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)TW.sort((a, c) => a.t0 - c.t0);const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;const tail = TW.some(w => w.tail === true);